Programs & Examples On #Reorderlist

How to rollback everything to previous commit

I searched for multiple options to get my git reset to specific commit, but most of them aren't so satisfactory.

I generally use this to reset the git to the specific commit in source tree.

  1. select commit to reset on sourcetree.

  2. In dropdowns select the active branch , first Parent Only

  3. And right click on "Reset branch to this commit" and select hard reset option (soft, mixed and hard)

  4. and then go to terminal git push -f

You should be all set!

How do I count cells that are between two numbers in Excel?

If you have Excel 2007 or later use COUNTIFS with an "S" on the end, i.e.

=COUNTIFS(B2:B292,">10",B2:B292,"<10000")

You may need to change commas , to semi-colons ;

In earlier versions of excel use SUMPRODUCT like this

=SUMPRODUCT((B2:B292>10)*(B2:B292<10000))

Note: if you want to include exactly 10 change > to >= - similarly with 10000, change < to <=

How to remove margin space around body or clear default css styles

Go with this

body {
    padding:0px;
    margin:0px;
}

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

This looks like a Bootstrap issue...

Currently, here's a workaround : add .col-xs-12 to your responsive image.

Bootply

Angular 2 filter/search list

This code nearly worked for me...but I wanted a multiple element filter so my mods to the filter pipe are below:

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]): any[] {
    const searchText = args[0];
    const jsonKey = args[1];
    let jsonKeyArray = [];

    if (searchText == null || searchText === 'undefined') { return json; }

    if (jsonKey.indexOf(',') > 0) {
        jsonKey.split(',').forEach( function(key) {
            jsonKeyArray.push(key.trim());
        });
    } else {
        jsonKeyArray.push(jsonKey.trim());
    }

    if (jsonKeyArray.length === 0) { return json; }

    // Start with new Array and push found objects onto it.
    let returnObjects = [];
    json.forEach( function ( filterObjectEntry ) {

        jsonKeyArray.forEach( function (jsonKeyValue) {
            if ( typeof filterObjectEntry[jsonKeyValue] !== 'undefined' &&
            filterObjectEntry[jsonKeyValue].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
                // object value contains the user provided text.
                returnObjects.push(filterObjectEntry);
                }
            });

    });
    return returnObjects;
  }
} 

Now, instead of

jsonFilterBy:[ searchText, 'name']

you can do

jsonFilterBy:[ searchText, 'name, other, other2...']

Objective-C: Extract filename from path string

At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:

let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Simply :

$(".leaderMultiSelctdropdown").val()

Can an AJAX response set a cookie?

Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.

Has anyone ever got a remote JMX JConsole to work?

These are the steps that worked for me (debian behind firewall on the server side, reached over VPN from my local Mac):

check server ip

hostname -i

use JVM params:

-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=[jmx port]
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Djava.rmi.server.hostname=[server ip from step 1]

run application

find pid of the running java process

check all ports used by JMX/RMI

netstat -lp | grep [pid from step 4]

open all ports from step 5 on the firewall

Voila.

Form onSubmit determine which submit button was pressed

Not in the submit event handler itself, no.

But what you can do is add click handlers to each submit which will inform the submit handler as to which was clicked.

Here's a full example (using jQuery for brevity)

<html>
<head>
  <title>Test Page</title>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript">

  jQuery(function($) {
      var submitActor = null;
      var $form = $('#test');
      var $submitActors = $form.find('input[type=submit]');

      $form.submit(function(event) {
          if (null === submitActor) {
              // If no actor is explicitly clicked, the browser will
              // automatically choose the first in source-order
              // so we do the same here
              submitActor = $submitActors[0];
          }

          console.log(submitActor.name);
          // alert(submitActor.name);

          return false;
      });

      $submitActors.click(function(event) {
          submitActor = this;
      });
  });

  </script>
</head>

<body>

  <form id="test">

    <input type="text" />

    <input type="submit" name="save" value="Save" />
    <input type="submit" name="saveAndAdd" value="Save and add another" />

  </form>

</body>
</html>

What is the easiest way to push an element to the beginning of the array?

You can use insert:

a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]

Where the first argument is the index to insert at and the second is the value.

Upload file to FTP using C#

This works for me,this method will SFTP a file to a location within your network. It uses SSH.NET.2013.4.7 library.One can just download it for free.

    //Secure FTP
    public void SecureFTPUploadFile(string destinationHost,int port,string username,string password,string source,string destination)

    {
        ConnectionInfo ConnNfo = new ConnectionInfo(destinationHost, port, username, new PasswordAuthenticationMethod(username, password));

        var temp = destination.Split('/');
        string destinationFileName = temp[temp.Count() - 1];
        string parentDirectory = destination.Remove(destination.Length - (destinationFileName.Length + 1), destinationFileName.Length + 1);


        using (var sshclient = new SshClient(ConnNfo))
        {
            sshclient.Connect();
            using (var cmd = sshclient.CreateCommand("mkdir -p " + parentDirectory + " && chmod +rw " + parentDirectory))
            {
                cmd.Execute();
            }
            sshclient.Disconnect();
        }


        using (var sftp = new SftpClient(ConnNfo))
        {
            sftp.Connect();
            sftp.ChangeDirectory(parentDirectory);
            using (var uplfileStream = System.IO.File.OpenRead(source))
            {
                sftp.UploadFile(uplfileStream, destinationFileName, true);
            }
            sftp.Disconnect();
        }
    }

Making LaTeX tables smaller?

if it's too long for one page, use the longtable package. and if it's too wide for the page, use p{width} in place of l,r, or c for the column specifier. you can also go smaller than \small, i.e. \footnotesize and \tiny. I would consult the setspace package for options on how to remove the double space, though it's probably \singlespace or something like that.

Get the last inserted row ID (with SQL statement)

If your SQL Server table has a column of type INT IDENTITY (or BIGINT IDENTITY), then you can get the latest inserted value using:

INSERT INTO dbo.YourTable(columns....)
   VALUES(..........)

SELECT SCOPE_IDENTITY()

This works as long as you haven't inserted another row - it just returns the last IDENTITY value handed out in this scope here.

There are at least two more options - @@IDENTITY and IDENT_CURRENT - read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.

MySQL parameterized queries

Actually, even if your variable (SongLength) is numeric, you will still have to format it with %s in order to bind the parameter correctly. If you try to use %d, you will get an error. Here's a small excerpt from this link http://mysql-python.sourceforge.net/MySQLdb.html:

To perform a query, you first need a cursor, and then you can execute queries on it:

c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
          WHERE price < %s""", (max_price,))

In this example, max_price=5 Why, then, use %s in the string? Because MySQLdb will convert it to a SQL literal value, which is the string '5'. When it's finished, the query will actually say, "...WHERE price < 5".

What is the most appropriate way to store user settings in Android application

I'll throw my hat into the ring just to talk about securing passwords in general on Android. On Android, the device binary should be considered compromised - this is the same for any end application which is in direct user control. Conceptually, a hacker could use the necessary access to the binary to decompile it and root out your encrypted passwords and etc.

As such there's two suggestions I'd like to throw out there if security is a major concern for you:

1) Don't store the actual password. Store a granted access token and use the access token and the signature of the phone to authenticate the session server-side. The benefit to this is that you can make the token have a limited duration, you're not compromising the original password and you have a good signature that you can use to correlate to traffic later (to for instance check for intrusion attempts and invalidate the token rendering it useless).

2) Utilize 2 factor authentication. This may be more annoying and intrusive but for some compliance situations unavoidable.

How do I find duplicate values in a table in Oracle?

1. solution

select * from emp
    where rowid not in
    (select max(rowid) from emp group by empno);

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

Can I style an image's ALT text with CSS?

In Firefox and Chrome (and possibly more) we can insert the string ‘( .... )’ into the alt text of an image that hasn’t loaded.

_x000D_
_x000D_
img {_x000D_
  font-style: italic;_x000D_
  color: #c00;_x000D_
}_x000D_
_x000D_
img:after {_x000D_
  content: " (Image - Right click to reload if not loaded)";_x000D_
}_x000D_
_x000D_
img::after {_x000D_
  content: " (Image - Right click to reload if not loaded)";_x000D_
}
_x000D_
<img alt="Alt text - " />
_x000D_
_x000D_
_x000D_

Check whether user has a Chrome extension installed

Here is how you can detect a specific Extension installed and show a warning message.

First you need to open the manifest file of the extension by going to chrome-extension://extension_id_here_hkdppipefbchgpohn/manifest.json and look for any file name within "web_accessible_resources" section.

<div class="chromewarning" style="display:none">
    <script type="text/javascript">
                            $.get("chrome-extension://extension_id_here_hkdppipefbchgpohn/filename_found_in_ web_accessible_resources.png").done(function () {
                              $(".chromewarning").show();
                            }).fail(function () {
                             //  alert("failed.");
                            });
                        </script>
                        <p>We have detected a browser extension that conflicts with learning modules in this course.</p>
            </div>

Generating a drop down list of timezones with PHP

Here's one that creates a multidimensional array sorted by offset and niceified name:

function timezones() {
    $timezones = [];

    foreach (timezone_identifiers_list() as $timezone) {
        $datetime = new \DateTime('now', new DateTimeZone($timezone));
        $timezones[] = [
            'sort' => str_replace(':', '', $datetime->format('P')),
            'offset' => $datetime->format('P'),
            'name' => str_replace('_', ' ', implode(', ', explode('/', $timezone))),
            'timezone' => $timezone,
        ];
    }

    usort($timezones, function($a, $b) {
        return $a['sort'] - $b['sort'] ?: strcmp($a['name'], $b['name']);
    });

    return $timezones;
}

foreach (timezones() as $timezone) {
    echo '(UTC '.$timezone['offset'].') '.$timezone['name'].'<br>';
}

Echos:

(UTC -11:00) Pacific, Midway
(UTC -11:00) Pacific, Niue
(UTC -11:00) Pacific, Pago Pago
(UTC -10:00) Pacific, Honolulu
(UTC -10:00) Pacific, Johnston
(UTC -10:00) Pacific, Rarotonga
(UTC -10:00) Pacific, Tahiti
(UTC -09:30) Pacific, Marquesas
(UTC -09:00) America, Adak
(UTC -09:00) Pacific, Gambier
(UTC -08:00) America, Anchorage
(UTC -08:00) America, Juneau
...

How to import a SQL Server .bak file into MySQL?

MySql have an application to import db from microsoft sql. Steps:

  1. Open MySql Workbench
  2. Click on "Database Migration" (if it do not appear you have to install it from MySql update)
  3. Follow the Migration Task List using the simple Wizard.

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

For Vb.Net Framework 4.0, U can use:

Alert("your message here", Boolean)

The Boolean here can be True or False. True If you want to close the window right after, False If you want to keep the window open.

Remove item from list based on condition

If your collection type is a List<stuff>, then the best approach is probably the following:

prods.RemoveAll(s => s.ID == 1)

This only does one pass (iteration) over the list, so should be more efficient than other methods.

If your type is more generically an ICollection<T>, it might help to write a short extension method if you care about performance. If not, then you'd probably get away with using LINQ (calling Where or Single).

How do I use WPF bindings with RelativeSource?

Don't forget TemplatedParent:

<Binding RelativeSource="{RelativeSource TemplatedParent}"/>

or

{Binding RelativeSource={RelativeSource TemplatedParent}}

Mongodb service won't start

I verified permissions but all was good (mongod:mongod). As I'm working on a large project and from a similar issue in our dev environment where we had a script consuming all available disk space, I could see in the error messages that mongod needs at least 3.7Gb free disk space to run..

I checked my own disk space only to see that less than 2Gb was remaining. After moving / erasing some data I can successfully start mongod again.

Hope this helps ;-)

print memory address of Python variable

There is no way to get the memory address of a value in Python 2.7 in general. In Jython or PyPy, the implementation doesn't even know your value's address (and there's not even a guarantee that it will stay in the same place—e.g., the garbage collector is allowed to move it around if it wants).

However, if you only care about CPython, id is already returning the address. If the only issue is how to format that integer in a certain way… it's the same as formatting any integer:

>>> hex(33)
0x21
>>> '{:#010x}'.format(33) # 32-bit
0x00000021
>>> '{:#018x}'.format(33) # 64-bit
0x0000000000000021

… and so on.

However, there's almost never a good reason for this. If you actually need the address of an object, it's presumably to pass it to ctypes or similar, in which case you should use ctypes.addressof or similar.

Git push rejected after feature branch rebase

Instead of using -f or --force developers should use

--force-with-lease

Why? Because it checks the remote branch for changes which is absolutely a good idea. Let's imagine that James and Lisa are working on the same feature branch and Lisa has pushed a commit. James now rebases his local branch and is rejected when trying to push. Of course James thinks this is due to rebase and uses --force and would rewrite all Lisa's changes. If James had used --force-with-lease he would have received a warning that there are commits done by someone else. I don't see why anyone would use --force instead of --force-with-lease when pushing after a rebase.

Today's Date in Perl in MM/DD/YYYY format

use DateTime qw();
DateTime->now->strftime('%m/%d/%Y')   

expression returns 06/13/2012

Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes

This was driving me bonkers as the .astype() solution above didn't work for me. But I found another way. Haven't timed it or anything, but might work for others out there:

t1 = pd.to_datetime('1/1/2015 01:00')
t2 = pd.to_datetime('1/1/2015 03:30')

print pd.Timedelta(t2 - t1).seconds / 3600.0

...if you want hours. Or:

print pd.Timedelta(t2 - t1).seconds / 60.0

...if you want minutes.

XPath to get all child nodes (elements, comments, and text) without parent

Use this XPath expression:

/*/*/X/node()

This selects any node (element, text node, comment or processing instruction) that is a child of any X element that is a grand-child of the top element of the XML document.

To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>
 <xsl:template match="/">
  <xsl:copy-of select="/*/*/X/node()"/>
 </xsl:template>
</xsl:stylesheet>

and it produces exactly the wanted, correct result:

   First Text Node #1            
    <y> Y can Have Child Nodes #                
        <child> deep to it </child>
    </y>            Second Text Node #2 
    <z />

Explanation:

  1. As defined in the W3 XPath 1.0 Spec, "child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.

  2. node() is an abbreviation of child::node() (because child:: is the primary axis and is used when no axis is explicitly specified).

package javax.mail and javax.mail.internet do not exist

You need the javax.mail.jar library. Download it from the Java EE JavaMail GitHub page and add it to your IntelliJ project:

  1. Download javax.mail.jar
  2. Navigate to File > Project Structure...
  3. Go to the Libraries tab
  4. Click on the + button (Add New Project Library)
  5. Browse to the javax.mail.jar file
  6. Click OK to apply the changes

SOAP PHP fault parsing WSDL: failed to load external entity?

Got a similar response with https WSDL URL using php soapClient

SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from ...

After server has been updated from PHP 5.5.9-1ubuntu4.21 >> PHP 5.5.9-1ubuntu4.23 something went wrong for my client machine osx 10.12.6 / PHP 5.6.30, but MS Web Services Clients connections could be made without issues.

Apache2's server_access.log showed no entry when i tried to load WSDL so i added 'cache_wsdl' => WSDL_CACHE_NONE to prevent client-side wsdl caching, but still got no entries. Finally i tried to load wsdl per CURL -i checked HEADERS but all seemed to be ok..

Only libxml_get_last_error() provided some insight > SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

So I added some ssl options to my call:

$contextOptions = array(
    'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
    ));

$sslContext = stream_context_create($contextOptions);

$params =  array(
    'trace' => 1,
    'exceptions' => true,
    'cache_wsdl' => WSDL_CACHE_NONE,
    'stream_context' => $sslContext
    );

try {
    $proxy = new SoapClient( $wsdl_url, $params );
} catch (SoapFault $proxy) {
    var_dump(libxml_get_last_error());
    var_dump($proxy);
}

In my case 'allow_self_signed' => true did the trick!

How to turn a string formula into a "real" formula

Just for fun, I found an interesting article here, to use a somehow hidden evaluate function that does exist in Excel. The trick is to assign it to a name, and use the name in your cells, because EVALUATE() would give you an error msg if used directly in a cell. I tried and it works! You can use it with a relative name, if you want to copy accross rows if a sheet.

Centering a canvas

As to the CSS suggestion:

#myCanvas { 
 width: 100%;
 height: 100%;
}

By the standard, CSS does not size the canvas coordinate system, it scales the content. In Chrome, the CSS mentioned will scale the canvas up or down to fit the browser's layout. In the typical case where the coordinate system is smaller than the browser's dimensions in pixels, this effectively lowers the resolution of your drawing. It most likely results in non-proportional drawing as well.

Change the project theme in Android Studio?

In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click on android:theme = "@style/AppTheme" in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

At parent= in styles.xml you can browse all available styles by using auto-complete inside the "". E.g. try parent="Theme." with your cursor right after the . and then pressing Ctrl + Space.

You can also preview themes in the preview window in Android Studio.

enter image description here

How to convert an Array to a Set in Java

With Guava you can do:

T[] array = ...
Set<T> set = Sets.newHashSet(array);

AWS Lambda import module error in python

@nithin, AWS released layers concept inside Lambda functions. You can create your layer and there you can upload as much as libraries and then you can connect the layer with the lambda functions. For more details: https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

Another to answer this question available here answered by @nilesh https://stackoverflow.com/a/19934852/2079692

public void setAttributeValue(WebElement elem, String value){
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])",
        elem, "value", value
    );
}

this takes advantage of selenium findElementBy function where xpath can be used also.

How do you easily create empty matrices javascript?

Here's one, no looping:

(Math.pow(10, 20)+'').replace((/0/g),'1').split('').map(parseFloat);

Fill the '20' for length, use the (optional) regexp for handy transforms and map to ensure datatype. I added a function to the Array prototype to easily pull the parameters of 'map' into your functions.. bit risky, some people strongly oppose touching native prototypes, but it does come in handy..

    Array.prototype.$args = function(idx) {
        idx || (idx = 0);
        return function() {
            return arguments.length > idx ? arguments[idx] : null;
        };
    };

// Keys
(Math.pow(10, 20)+'').replace((/0/g),'1').split('').map(this.$args(1));
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

// Matrix
(Math.pow(10, 9)+'').replace((/0/g),'1').split('').map(this.$args(1)).map(this.$args(2))

Mocking Extension Methods with Moq

You can easily mock an extension method with JustMock. The API is the same as mocking normal method. Consider the following

public static string Echo(this Foo foo, string strValue) 
{ 
    return strValue; 
}

To arrange and verify this method use the following:

string expected = "World";

var foo = new Foo();
Mock.Arrange(() => foo.Echo(Arg.IsAny<string>())).Returns(expected);

string result = foo.Echo("Hello");

Assert.AreEqual(expected, result);

Here is also a link to the documentation: Extension Methods Mocking

Disclaimer. I am one of the developers responsible for JustMock.

Duplicate symbols for architecture x86_64 under Xcode

For me, changing 'No Common Blocks' from Yes to No ( under Targets->Build Settings->Apple LLVM - Code Generation ) fixed the problem.

Why does Node.js' fs.readFile() return a buffer instead of string?

Try:

    fs.readFile("test.txt", "utf8", function(err, data) {...});

Basically, you need to specify the encoding.

@Html.DropDownListFor how to set default value

try this

 @Html.DropDownListFor(model => model.UserName, new List<SelectListItem> 
   { new SelectListItem{Text="Active", Value="True",Selected =true },
     new SelectListItem{Text="Deactive", Value="False"}})

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

For me, it was the StackOverFlow Exception because of recursive code.

How to install APK from PC?

3 Ways to Install Applications On Android Without The Market

And don't forget to enable Unknown sources in your Android device Settings, before installing apk, else Android platform will not allow you to install apk directly

enter image description here

Send push to Android by C# using FCM (Firebase Cloud Messaging)

I write this code and It's worked for me .

public static string ExcutePushNotification(string title, string msg, string fcmToken, object data) 
{

        var serverKey = "AAAA*******************";
        var senderId = "3333333333333";


        var result = "-1";

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://fcm.googleapis.com/fcm/send");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
        httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
        httpWebRequest.Method = "POST";


        var payload = new
        {
            notification = new
            {
                title = title,
                body = msg,
                sound = "default"
            },

            data = new
            {
                info = data
            },
            to = fcmToken,
            priority = "high",
            content_available = true,

        };


        var serializer = new JavaScriptSerializer();

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = serializer.Serialize(payload);
            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
        }
        return result;
}

SUM OVER PARTITION BY

You could have used DISTINCT or just remove the PARTITION BY portions and use GROUP BY:

SELECT BrandId
       ,SUM(ICount)
       ,TotalICount = SUM(ICount) OVER ()    
       ,Percentage = SUM(ICount) OVER ()*1.0 / SUM(ICount) 
FROM Table 
WHERE DateId  = 20130618
GROUP BY BrandID

Not sure why you are dividing the total by the count per BrandID, if that's a mistake and you want percent of total then reverse those bits above to:

SELECT BrandId
           ,SUM(ICount)
           ,TotalICount = SUM(ICount) OVER ()    
           ,Percentage = SUM(ICount)*1.0 / SUM(ICount) OVER () 
    FROM Table 
    WHERE DateId  = 20130618
    GROUP BY BrandID

Excel VBA - select a dynamic cell range

I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.

Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")

'Find Last Row and Column
  LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
  LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column

'Select Range
  sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select

End Sub

Failed to find 'ANDROID_HOME' environment variable

In Linux

First of all set ANDROID_HOME in .bashrc file

Run command

sudo gedit ~/.bashrc

set andoid sdk path where you have installed

export ANDROID_HOME=/opt/android-sdk-linux 
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

to reload file run command

source ~/.bashrc

Now check installed platform, run command

ionic platform

Output

Installed platforms:
  android 6.0.0
Available platforms: 
  amazon-fireos ~3.6.3 (deprecated)
  blackberry10 ~3.8.0
  browser ~4.1.0
  firefoxos ~3.6.3
  ubuntu ~4.3.4
  webos ~3.7.0

if android already installed then need to remove and install again

ionic platform rm android
ionic platform add android

If not installed already please add android platform

ionic platform add android

Please make sure you have added android platform without sudo command

if you still getting error in adding android platfrom like following

Error: EACCES: permission denied, open '/home/ubuntu/.cordova/lib/npm_cache/cordova-android/6.0.0/package/package.json'

Please go to /home/ubuntu/ and remove .cordova folder from there

cd /home/ubuntu/
sudo rm -r .cordova

Now run following command again

ionic platform add android

after adding platform successfully you will be able to build andoid in ionic.

Thanks

Testing Private method using mockito

You can't do that with Mockito but you can use Powermock to extend Mockito and mock private methods. Powermock supports Mockito. Here's an example.

Resize UIImage by keeping Aspect ratio and width

This method is a category on UIImage. Does scale to fit in few lines of code using AVFoundation. Don't forget to import #import <AVFoundation/AVFoundation.h>.

@implementation UIImage (Helper)

- (UIImage *)imageScaledToFitToSize:(CGSize)size
{
    CGRect scaledRect = AVMakeRectWithAspectRatioInsideRect(self.size, CGRectMake(0, 0, size.width, size.height));
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    [self drawInRect:scaledRect];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

@end

How to get the excel file name / path in VBA

   strScriptFullname = WScript.ScriptFullName 
   strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\")) 

C#: Converting byte array to string and printing out to console

 byte[] bytes = { 1,2,3,4 };

 string stringByte= BitConverter.ToString(bytes);

 Console.WriteLine(stringByte);

How to use new PasswordEncoder from Spring Security

Here is the implementation of BCrypt which is working for me.

in spring-security.xml

<authentication-manager >
    <authentication-provider ref="authProvider"></authentication-provider>  
    </authentication-manager>
<beans:bean id="authProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
  <beans:property name="userDetailsService" ref="userDetailsServiceImpl" />
  <beans:property name="passwordEncoder" ref="encoder" />
</beans:bean>
<!-- For hashing and salting user passwords -->
    <beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

In java class

PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(yourpassword);

For more detailed example of spring security Click Here

Hope this will help.

Thanks

Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

You can use this css:

.inactiveLink {
   pointer-events: none;
   cursor: default;
}

And then assign the class to your html code:

<a style="" href="page.html" class="inactiveLink">page link</a>

It makes the link not clickeable and the cursor style an arrow, not a hand as the links have.

or use this style in the html:

<a style="pointer-events: none; cursor: default;" href="page.html">page link</a>

but I suggest the first approach.

Bootstrap 3 Flush footer to bottom. not fixed

For Bootstrap:

<div class="navbar-fixed-bottom row-fluid">
  <div class="navbar-inner">
    <div class="container">
      Text
    </div>
  </div>
</div>

Add a custom attribute to a Laravel / Eloquent model on load?

The problem is caused by the fact that the Model's toArray() method ignores any accessors which do not directly relate to a column in the underlying table.

As Taylor Otwell mentioned here, "This is intentional and for performance reasons." However there is an easy way to achieve this:

class EventSession extends Eloquent {

    protected $table = 'sessions';
    protected $appends = array('availability');

    public function getAvailabilityAttribute()
    {
        return $this->calculateAvailability();  
    }
}

Any attributes listed in the $appends property will automatically be included in the array or JSON form of the model, provided that you've added the appropriate accessor.

Old answer (for Laravel versions < 4.08):

The best solution that I've found is to override the toArray() method and either explicity set the attribute:

class Book extends Eloquent {

    protected $table = 'books';

    public function toArray()
    {
        $array = parent::toArray();
        $array['upper'] = $this->upper;
        return $array;
    }

    public function getUpperAttribute()
    {
        return strtoupper($this->title);    
    }

}

or, if you have lots of custom accessors, loop through them all and apply them:

class Book extends Eloquent {

    protected $table = 'books';

    public function toArray()
    {
        $array = parent::toArray();
        foreach ($this->getMutatedAttributes() as $key)
        {
            if ( ! array_key_exists($key, $array)) {
                $array[$key] = $this->{$key};   
            }
        }
        return $array;
    }

    public function getUpperAttribute()
    {
        return strtoupper($this->title);    
    }

}

javascript regex : only english letters allowed

Another option is to use the case-insensitive flag i, then there's no need for the extra character range A-Z.

var reg = /^[a-z]+$/i;
console.log( reg.test("somethingELSE") ); //true
console.log( "somethingELSE".match(reg)[0] ); //"somethingELSE"

Here's a DEMO on how this regex works with test() and match().

Xcode 'CodeSign error: code signing is required'

Most common cause, considering that all certificates are installed properly is not specifying the Code Signing Identity in the Active Target settings along with the Project settings. Change these from to iPhone Developer (Xcode will select the right profile depending on App ID match).

  • In Xcode , change from Simulator to Device (in the dropdown at the top of the Xcode window), so that your target for application deployment will be the Device.

  • The default ID which is a wild card ID is like a catch all iD, when associated in Code Signing (if you are using sample files to build, they will most obviously not have com.coolapps.appfile imports, in which case without the 'Team Provisioning profile', your build would fail. So you would want to set this in your

  • Xcode->Project ->Edit Project Settings->Build (tab)->Code Signing Identity (header) ->Any iOS (change from Any iOS Simulator)->(select 'iPhone Developer' as value and it will default to the wildcard development provisioning profile (Team Provisioning Profile: * )

and also (VERY IMPORTANT)

  • Xcode->Project ->Edit Active Target ->Build (tab)->Code Signing Identity (header) ->Any iOS (change from Any iOS Simulator)->(select 'iPhone Developer' as value and it will default to the wildcard development provisioning profile (Team Provisioning Profile: * )

Complete steps for a beginner at: http://codevelle.wordpress.com/2010/12/21/moving-from-ios-simulator-to-the-ios-device-smoothly-without-code-sign-error/

How to pass boolean values to a PowerShell script from a command prompt

A more clear usage might be to use switch parameters instead. Then, just the existence of the Unify parameter would mean it was set.

Like so:

param (
  [int] $Turn,
  [switch] $Unify
)

Change background color for selected ListBox item

You need to use ListBox.ItemContainerStyle.

ListBox.ItemTemplate specifies how the content of an item should be displayed. But WPF still wraps each item in a ListBoxItem control, which by default gets its Background set to the system highlight colour if it is selected. You can't stop WPF creating the ListBoxItem controls, but you can style them -- in your case, to set the Background to always be Transparent or Black or whatever -- and to do so, you use ItemContainerStyle.

juFo's answer shows one possible implementation, by "hijacking" the system background brush resource within the context of the item style; another, perhaps more idiomatic technique is to use a Setter for the Background property.

For loop in Oracle SQL

You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:

-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
  k NUMBER:= 0;
BEGIN
  FOR i IN 1..10 LOOP
    k:= k+1;
    dbms_output.put_line(i||' '||k);
 END LOOP;
END;
/

-- Cursor FOR loop --
set serveroutput on
DECLARE
   CURSOR c1 IS SELECT * FROM scott.emp;
   i NUMBER:= 0;
BEGIN
  FOR e_rec IN c1 LOOP
  i:= i+1;
    dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
  END LOOP;
END;
/

-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
  FROM dual
CONNECT BY LEVEL <= 10
/

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

For data import scripts, to replace "IF NOT EXISTS", in a way, there's a slightly awkward formulation that nevertheless works:

DO
$do$
BEGIN
PERFORM id
FROM whatever_table;

IF NOT FOUND THEN
-- INSERT stuff
END IF;
END
$do$;

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

I had this problem and its because I wasnt using the latest version of C# (C# 7.3 as of writing this) and I had to change the below internal access modifier to public.

internal class Program
 {
    public static void Main(string[] args)
    {
        //My Code
    }
  }

or ammend the .csproj to use the latest version of C# (this way meant I could still keep the above class as internal):

<PropertyGroup>
    <LangVersion>latest</LangVersion>
    <NoWin32Manifest>true</NoWin32Manifest>
</PropertyGroup>

SQL how to check that two tables has exactly the same data?

I had this same issue in SQL Server and wrote this T-SQL script to automate the process (actually this is the watered-down version, mine wrote all the diff to a single table for easy reporting).

Update 'MyTable' and 'MyOtherTable' to the names of the tables you wish to compare.

DECLARE @ColName varchar(100)
DECLARE @Table1 varchar(100) = 'MyTable'
DECLARE @Table2 varchar(100) = 'MyOtherTable'


IF (OBJECT_ID('tempdb..#col') IS NOT NULL) DROP TABLE #col
SELECT  IDENTITY(INT, 1, 1) RowNum , c.name
INTO    #col
FROM    SYS.Objects o 
        JOIN SYS.columns c on o.object_id = c.object_id
WHERE   o.name = @Table1 AND NOT c.Name IN ('List','Columns','YouWantToIgnore')

DECLARE @Counter INT = (SELECT MAX(RowNum) FROM #col)

    WHILE @Counter > 0

        BEGIN
            SET @ColName = (SELECT name FROM #Col WHERE RowNum= @Counter)
                EXEC ('SELECT  t1.Identifier
                        ,t1.'+@ColName+' AS '+@Table1+@ColName+'
                        ,t2.'+@ColName+' AS '+@Table2+@ColName+'
                FROM    '+@Table1+' t1
                        LEFT JOIN '+@Table2+' t2 ON t1.Identifier = t2.Identifier 
                WHERE   t1.'+@ColName+' <> t2.'+@ColName)
            SET @Counter = @Counter - 1 
        END

stringstream, string, and char* conversion confusion

In this line:

const char* cstr2 = ss.str().c_str();

ss.str() will make a copy of the contents of the stringstream. When you call c_str() on the same line, you'll be referencing legitimate data, but after that line the string will be destroyed, leaving your char* to point to unowned memory.

How do I make a comment in a Dockerfile?

Docker treats lines that begin with # as a comment, unless the line is a valid parser directive. A # marker anywhere else in a line is treated as an argument.

example code:

# this line is a comment

RUN echo 'we are running some # of cool things'

Output:

we are running some # of cool things

Difference between "process.stdout.write" and "console.log" in node.js?

I've just noticed something while researching this after getting help with https.request for post method. Thought I share some input to help understand.

process.stdout.write doesn't add a new line while console.log does, like others had mentioned. But there's also this which is easier to explain with examples.

var req = https.request(options, (res) => {
    res.on('data', (d) => {
        process.stdout.write(d);
        console.log(d)
    });
});

process.stdout.write(d); will print the data properly without a new line. However console.log(d) will print a new line but the data won't show correctly, giving this <Buffer 12 34 56... for example.

To make console.log(d) show the information correctly, I would have to do this.

var req = https.request(options, (res) => {
    var dataQueue = "";    
    res.on("data", function (d) {
        dataQueue += d;
    });
    res.on("end", function () {
        console.log(dataQueue);
    });
});

So basically:

  • process.stdout.write continuously prints the information as the data being retrieved and doesn't add a new line.

  • console.log prints the information what was obtained at the point of retrieval and adds a new line.

That's the best way I can explain it.

How to return a custom object from a Spring Data JPA GROUP BY query

    //in Service      
      `
                public List<DevicesPerCustomer> findDevicesPerCustomer() {
                    LOGGER.info(TAG_NAME + " :: inside findDevicesPerCustomer : ");
                    List<Object[]> list = iDeviceRegistrationRepo.findDevicesPerCustomer();
                    List<DevicesPerCustomer> out = new ArrayList<>();
                    if (list != null && !list.isEmpty()) {
                        DevicesPerCustomer mDevicesPerCustomer = null;
                        for (Object[] object : list) {
                            mDevicesPerCustomer = new DevicesPerCustomer();
mDevicesPerCustomer.setCustomerId(object[0].toString());
                            mDevicesPerCustomer.setCount(Integer.parseInt(object[1].toString()));
                            
                            out.add(mDevicesPerCustomer);
                        }
                    }
            
                    return out;
                }`
        
    //In Repo
        `   @Query(value = "SELECT d.customerId,count(*) FROM senseer.DEVICE_REGISTRATION d  where d.customerId is not null group by d.customerId", nativeQuery=true)
            List<Object[]> findDevicesPerCustomer();`

Setting onClickListener for the Drawable right of an EditText

Please use below trick:

  • Create an image button with your icon and set its background color to be transparent.
  • Put the image button on the EditText
  • Implement the 'onclic'k listener of the button to execute your function

Avoiding NullPointerException in Java

There has a good way to check the null value from JDK. It is Optional.java that has a sea of methods to resolve these problems. Such as follow: `

  • Returns an {@code Optional} describing the specified value, if non-null,
    • otherwise returns an empty {@code Optional}.
    • @param the class of the value
    • @param value the possibly-null value to describe
    • @return an {@code Optional} with a present value if the specified value
    • is non-null, otherwise an empty {@code Optional}
public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}  `

`/

  • Return {@code true} if there is a value present, otherwise {@code false}. *

    • @return {@code true} if there is a value present, otherwise {@code false} */ public boolean isPresent() { return value != null; }

    /**

    • If a value is present, invoke the specified consumer with the value,
    • otherwise do nothing.
    • @param consumer block to be executed if a value is present
    • @throws NullPointerException if value is present and {@code consumer} is
    • null */ public void ifPresent(Consumer<? super T> consumer) { if (value != null) consumer.accept(value); }`

It is really, really useful to help javer.

How to add form validation pattern in Angular 2?

custom validation step by step

Html template

  <form [ngFormModel]="demoForm">
  <input  
  name="NotAllowSpecialCharacters"    
  type="text"                      
  #demo="ngForm"
  [ngFormControl] ="demoForm.controls['spec']"
  >

 <div class='error' *ngIf="demo.control.touched">
   <div *ngIf="demo.control.hasError('required')"> field  is required.</div>
   <div *ngIf="demo.control.hasError('invalidChar')">Special Characters are not Allowed</div>
 </div>
  </form>

Component App.ts

import {Control, ControlGroup, FormBuilder, Validators, NgForm, NgClass} from 'angular2/common';
import {CustomValidator} from '../../yourServices/validatorService';

under class define

 demoForm: ControlGroup;
constructor( @Inject(FormBuilder) private Fb: FormBuilder ) {
    this.demoForm = Fb.group({
       spec: new Control('', Validators.compose([Validators.required,   CustomValidator.specialCharValidator])),
      })
}

under {../../yourServices/validatorService.ts}

export class CustomValidator {
    static specialCharValidator(control: Control): { [key: string]: any } {
   if (control.value) {
       if (!control.value.match(/[-!$%^&*()_+|~=`{}\[\]:";#@'<>?,.\/]/)) {            
           return null;
       }
       else {            
           return { 'invalidChar': true };
       }
   }

 }

 }

Simple (I think) Horizontal Line in WPF?

How about add this to your xaml:

<Separator/>

Insert node at a certain position in a linked list C++

For inserting at a particular position k, you need to traverse the list till the position k-1 and then do the insert.

[You need not create a new node to traverse to that position as you did in your code] You should traverse from the head node.

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I think that error from Nginx is indicating that the connection was closed by your nodejs server (i.e., "upstream"). How is nodejs configured?

How to print something when running Puppet client?

Just as alternative you may consider using execs... (I wouldn't recommend it though)

exec { 'this will output stuff':
  path      => '/bin',
  command   => 'echo Hello World!',
  logoutput => true,
}

So when you run puppet you should find some output like so:

notice: /Stage[main]//Exec[this will output stuff]/returns: Hello World!
notice: /Stage[main]//Exec[this will output stuff]/returns: executed successfully
notice: Finished catalog run in 0.08 seconds

The first line being logged output.

HTML: how to force links to open in a new tab, not new window

In Internet Explorer, click the Tools -> Internet Options. Click General tab -> Tabs -> Settings. Choose "When a pop-up is encountered"-> Always open pop up in new tab option. Click OK.

Getting the names of all files in a directory with PHP

Recursive code to explore all the file contained in a directory ('$path' contains the path of the directory):

function explore_directory($path)
{
    $scans = scandir($path);

    foreach($scans as $scan)
    {
        $new_path = $path.$scan;

        if(is_dir($new_path))
        {
            $new_path = $new_path."/";
            explore_directory($new_path);
        }
        else // A file
        {
            /*
                  Body of code
            */
        }
    }
}

C++ Pass A String

Not very technical answer but just letting you know.

For easy stuff like printing you can define a sort of function in your preprocessors like

#define print(x) cout << x << endl

Why can't variables be declared in a switch statement?

Try this:

switch (val)
{
    case VAL:
    {
        int newVal = 42;
    }
    break;
}

How to use Utilities.sleep() function

Some Google services do not like to be used to much. Quite recently my account was locked because of script, which was sending two e-mails per second to the same user. Google considered it as a spam. So using sleep here is also justified to prevent such situations.

Changing ViewPager to enable infinite page scrolling

I built a library that can make any ViewPager, pagerAdapter (or FragmentStatePagerAdapter), and optional TabLayout infinitely Scrolling.

https://github.com/memorex386/infinite-scroll-viewpager-w-tabs

How to break line in JavaScript?

I was facing the same problem. For my solution, I added br enclosed between 2 brackets < > enclosed in double quotation marks, and preceded and followed by the + sign:

+"<br>"+

Try this in your browser and see, it certainly works in my Internet Explorer.

Building and running app via Gradle and Android Studio is slower than via Eclipse

This setup goes really fast for me (about 2 seconds the build)

build.gradle

android {

    dexOptions {
        incremental true
        preDexLibraries = false
        jumboMode = false
        maxProcessCount 4
        javaMaxHeapSize "6g"
    }
}

gradle.properties

org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.jvmargs=-Xmx8192M

my PC:

  • CPU Intel(R) Pentium(R) CPU G2030 @ 3.00GHz, 3000 Mhz, 2 procesadores principales, 2 procesadores lógicos
  • x64
  • Microsoft Windows 7 Professional
  • (RAM) 16,0 GB

project files
- All located in local HD

Check if string matches pattern

Please try the following:

import re

name = ["A1B1", "djdd", "B2C4", "C2H2", "jdoi","1A4V"]

# Match names.
for element in name:
     m = re.match("(^[A-Z]\d[A-Z]\d)", element)
     if m:
        print(m.groups())

php: catch exception and continue execution, is it possible?

Another angle on this is returning an Exception, NOT throwing one, from the processing code.

I needed to do this with a templating framework I'm writing. If the user attempts to access a property that doesn't exist on the data, I return the error from deep within the processing function, rather than throwing it.

Then, in the calling code, I can decide whether to throw this returned error, causing the try() to catch(), or just continue:

// process the template
    try
    {
        // this function will pass back a value, or a TemplateExecption if invalid
            $result = $this->process($value);

        // if the result is an error, choose what to do with it
            if($result instanceof TemplateExecption)
            {
                if(DEBUGGING == TRUE)
                {
                    throw($result); // throw the original error
                }
                else
                {
                    $result = NULL; // ignore the error
                }
            }
    }

// catch TemplateExceptions
    catch(TemplateException $e)
    {
        // handle template exceptions
    }

// catch normal PHP Exceptions
    catch(Exception $e)
    {
        // handle normal exceptions
    }

// if we get here, $result was valid, or ignored
    return $result;

The result of this is I still get the context of the original error, even though it was thrown at the top.

Another option might be to return a custom NullObject or a UnknownProperty object and compare against that before deciding to trip the catch(), but as you can re-throw errors anyway, and if you're fully in control of the overall structure, I think this is a neat way round the issue of not being able to continue try/catches.

Can someone explain the dollar sign in Javascript?

The $ sign is an identifier for variables and functions.

https://web.archive.org/web/20160529121559/http://www.authenticsociety.com/blog/javascript_dollarsign

That has a clear explanation of what the dollar sign is for.

Here's an alternative explanation: http://www.vcarrer.com/2010/10/about-dollar-sign-in-javascript.html

Matching a space in regex

I am using a regex to make sure that I only allow letters, number and a space

Then it is as simple as adding a space to what you've already got:

$newtag = preg_replace("/[^a-zA-Z0-9 ]/", "", $tag);

(note, I removed the s| which seemed unintentional? Certainly the s was redundant; you can restore the | if you need it)

If you specifically want *a* space, as in only a single one, you will need a more complex expression than this, and might want to consider a separate non-regex piece of logic.

How to use filter, map, and reduce in Python 3

As an addendum to the other answers, this sounds like a fine use-case for a context manager that will re-map the names of these functions to ones which return a list and introduce reduce in the global namespace.

A quick implementation might look like this:

from contextlib import contextmanager    

@contextmanager
def noiters(*funcs):
    if not funcs: 
        funcs = [map, filter, zip] # etc
    from functools import reduce
    globals()[reduce.__name__] = reduce
    for func in funcs:
        globals()[func.__name__] = lambda *ar, func = func, **kwar: list(func(*ar, **kwar))
    try:
        yield
    finally:
        del globals()[reduce.__name__]
        for func in funcs: globals()[func.__name__] = func

With a usage that looks like this:

with noiters(map):
    from operator import add
    print(reduce(add, range(1, 20)))
    print(map(int, ['1', '2']))

Which prints:

190
[1, 2]

Just my 2 cents :-)

How to make Twitter Bootstrap tooltips have multiple lines?

You can use the html property: http://jsfiddle.net/UBr6c/

My <a href="#" title="This is a<br />test...<br />or not" class="my_tooltip">Tooltip</a> test.

$('.my_tooltip').tooltip({html: true})

Do standard windows .ini files allow comments?

Windows INI API support for:

  • Line comments: yes, using semi-colon ;
  • Trailing comments: No

The authoritative source is the Windows API function that reads values out of INI files

GetPrivateProfileString

Retrieves a string from the specified section in an initialization file.

The reason "full line comments" work is because the requested value does not exist. For example, when parsing the following ini file contents:

[Application]
UseLiveData=1
;coke=zero
pepsi=diet   ;gag
#stackoverflow=splotchy

Reading the values:

  • UseLiveData: 1
  • coke: not present
  • ;coke: not present
  • pepsi: diet ;gag
  • stackoverflow: not present
  • #stackoverflow: splotchy

Update: I used to think that the number sign (#) was a pseudo line-comment character. The reason using leading # works to hide stackoverflow is because the name stackoverflow no longer exists. And it turns out that semi-colon (;) is a line-comment.

But there is no support for trailing comments.

Java current machine name and logged in user?

To get the currently logged in user:

System.getProperty("user.name"); //platform independent 

and the hostname of the machine:

java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());

How to output to the console and file?

Create an output file and custom function:

outputFile = open('outputfile.log', 'w')

def printing(text):
    print(text)
    if outputFile:
        outputFile.write(str(text))

Then instead of print(text) in your code, call printing function.

printing("START")
printing(datetime.datetime.now())
printing("COMPLETE")
printing(datetime.datetime.now())

HashMaps and Null values?

It seems that you are trying to call a method with a Map parameter. So, to call with an empty person name the right approach should be

HashMap<String, String> options = new HashMap<String, String>();
options.put("name", null);  
Person person = sample.searchPerson(options);

Or you can do it like this

HashMap<String, String> options = new HashMap<String, String>();
Person person = sample.searchPerson(options);

Using

Person person = sample.searchPerson(null);

Could get you a null pointer exception. It all depends on the implementation of searchPerson() method.

Detecting TCP Client Disconnect

TCP has "open" and a "close" procedures in the protocol. Once "opened", a connection is held until "closed". But there are lots of things that can stop the data flow abnormally. That being said, the techniques to determine if it is possible to use a link are highly dependent on the layers of software between the protocol and the application program. The ones mentioned above focus on a programmer attempting to use a socket in a non-invasive way (read or write 0 bytes) are perhaps the most common. Some layers in libraries will supply the "polling" for a programmer. For example Win32 asych (delayed) calls can Start a read that will return with no errors and 0 bytes to signal a socket that cannot be read any more (presumably a TCP FIN procedure). Other environments might use "events" as defined in their wrapping layers. There is no single answer to this question. The mechanism to detect when a socket cannot be used and should be closed depends on the wrappers supplied in the libraries. It is also worthy to note that sockets themselves can be reused by layers below an application library so it is wise to figure out how your environment deals with the Berkley Sockets interface.

Disable form autofill in Chrome without disabling autocomplete

Fix: prevent browser autofill in

 <input type="password" readonly onfocus="this.removeAttribute('readonly');"/>

Update: Mobile Safari sets cursor in the field, but does not show virtual keyboard. New Fix works like before but handles virtual keyboard:

<input id="email" readonly type="email" onfocus="if (this.hasAttribute('readonly')) {
    this.removeAttribute('readonly');
    // fix for mobile safari to show virtual keyboard
    this.blur();    this.focus();  }" />

Live Demo https://jsfiddle.net/danielsuess/n0scguv6/

// UpdateEnd

Explanation Instead of filling in whitespaces or window-on-load functions this snippet works by setting readonly-mode and changing to writable if user focuses this input field (focus contains mouse click and tabbing through fields).

No jQuery needed, pure JavaScript.

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

I had the exact same problem and figured out that by default the Mail Shield from Avast antivirus had the "Scan SSL connection" activated. Make sure to turn that off.

From my knowledge, Avast will "open" the mail, scan it for any viruses and then sign it using it's own certificate so the mail won't be signed by the gmail's certificate anymore which produces that error.

Solution 1:

  • Turn off the SSL scans from your antivirus (or the entire mail shield).

Solution 2 (Should be the best security speaking):

  • Get somehow the certificate used by the antivirus (Avast has an option to export it)
  • Import it in your imap/pop/smtp client before connecting to gmail server.

How to set $_GET variable

I know this is an old thread, but I wanted to post my 2 cents...

Using Javascript you can achieve this without using $_POST, and thus avoid reloading the page..

<script>
function ButtonPressed()
{
window.location='index.php?view=next'; //this will set $_GET['view']='next'
}
</script>

<button type='button' onClick='ButtonPressed()'>Click me!</button>

<?PHP
 if(isset($_GET['next']))
    {
          echo "This will display after pressing the 'Click Me' button!";
    }
 ?>

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

It is important to define an id in the model

.DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Model(model => model.Id(p => p.id))
    )

How to change the style of a DatePicker in android?

Calendar calendar = Calendar.getInstance();

DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), R.style.DatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
  public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    Calendar newDate = Calendar.getInstance();
    newDate.set(year, monthOfYear, dayOfMonth);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String date = simpleDateFormat.format(newDate.getTime());
  }
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));

datePickerDialog.show();

And use this style:

<style name="DatePickerDialogTheme" parent="Theme.AppCompat.Light.Dialog">
  <item name="colorAccent">@color/colorPrimary</item>
</style>

Drop all tables command

I'd like to add to other answers involving dropping tables and not deleting the file, that you can also execute delete from sqlite_sequence to reset auto-increment sequences.

difference between System.out.println() and System.err.println()

It's worth noting that an OS has one queue for both System.err and System.out. Consider the following code:

public class PrintQueue {
    public static void main(String[] args) {
        for(int i = 0; i < 100; i++) {
            System.out.println("out");
            System.err.println("err");
        }
    }
}

If you compile and run the program, you will see that the order of outputs in console is mixed up.

An OS will remain right order if you work either with System.out or System.err only. But it can randomly choose what to print next to console, if you use both of these.

Even in this code snippet you can see that the order is mixed up sometimes:

public class PrintQueue {
    public static void main(String[] args) {
        System.out.println("out");
        System.err.println("err");
    }
}

RegEx to exclude a specific string constant

You have to use a negative lookahead assertion.

(?!^ABC$)

You could for example use the following.

(?!^ABC$)(^.*$)

If this does not work in your editor, try this. It is tested to work in ruby and javascript:

^((?!ABC).)*$

How do I send a file as an email attachment using Linux command line?

From looking at man mailx, the mailx program does not have an option for attaching a file. You could use another program such as mutt.

echo "This is the message body" | mutt -a file.to.attach -s "subject of message" [email protected]

Command line options for mutt can be shown with mutt -h.

Sass calculate percent minus px

There is a calc function in both SCSS [compile-time] and CSS [run-time]. You're likely invoking the former instead of the latter.

For obvious reasons mixing units won't work compile-time, but will at run-time.

You can force the latter by using unquote, a SCSS function.

.selector { height: unquote("-webkit-calc(100% - 40px)"); }

How to install cron

On CentOS/RHEL:

yum install cronie

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

postgresql: INSERT INTO ... (SELECT * ...)

If you want insert into specify column:

INSERT INTO table (time)
(SELECT time FROM 
    dblink('dbname=dbtest', 'SELECT time FROM tblB') AS t(time integer) 
    WHERE time > 1000
);

How to pass List<String> in post method using Spring MVC?

I had the same use case, You can change your method defination in the following way :

@RequestMapping(value = "/saveFruits", method = RequestMethod.POST, 
    consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody Map<String,List<String>> fruits) {
    ..
}

The only problem is it accepts any key in place of "fruits" but You can easily get rid of a wrapper if it is not big functionality.

What do $? $0 $1 $2 mean in shell script?

They are called the Positional Parameters.

3.4.1 Positional Parameters

A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).

When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.

Sprintf equivalent in Java

Since Java 13 you have formatted 1 method on String, which was added along with text blocks as a preview feature 2. You can use it instead of String.format()

Assertions.assertEquals(
   "%s %d %.3f".formatted("foo", 123, 7.89),
   "foo 123 7.890"
);

How to get detailed list of connections to database in sql server 2005?

There is also who is active?:

Who is Active? is a comprehensive server activity stored procedure based on the SQL Server 2005 and 2008 dynamic management views (DMVs). Think of it as sp_who2 on a hefty dose of anabolic steroids

Importing larger sql files into MySQL

You can import large files this command line way:

mysql -h yourhostname -u username -p databasename < yoursqlfile.sql

Why am I getting string does not name a type Error?

You can overcome this error in two simple ways

First way

using namespace std;
include <string>
// then you can use string class the normal way

Second way

// after including the class string in your cpp file as follows
include <string>
/*Now when you are using a string class you have to put **std::** before you write 
string as follows*/
std::string name; // a string declaration

How to check if a file contains a specific string using Bash

if grep -q [string] [filename]
then
    [whatever action]
fi

Example

if grep -q 'my cat is in a tree' /tmp/cat.txt
then
    mkdir cat
fi

Set Matplotlib colorbar size to match graph

@bogatron already gave the answer suggested by the matplotlib docs, which produces the right height, but it introduces a different problem. Now the width of the colorbar (as well as the space between colorbar and plot) changes with the width of the plot. In other words, the aspect ratio of the colorbar is not fixed anymore.

To get both the right height and a given aspect ratio, you have to dig a bit deeper into the mysterious axes_grid1 module.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size
import numpy as np

aspect = 20
pad_fraction = 0.5

ax = plt.gca()
im = ax.imshow(np.arange(200).reshape((20, 10)))
divider = make_axes_locatable(ax)
width = axes_size.AxesY(ax, aspect=1./aspect)
pad = axes_size.Fraction(pad_fraction, width)
cax = divider.append_axes("right", size=width, pad=pad)
plt.colorbar(im, cax=cax)

Note that this specifies the width of the colorbar w.r.t. the height of the plot (in contrast to the width of the figure, as it was before).

The spacing between colorbar and plot can now be specified as a fraction of the width of the colorbar, which is IMHO a much more meaningful number than a fraction of the figure width.

image plot with colorbar

UPDATE:

I created an IPython notebook on the topic, where I packed the above code into an easily re-usable function:

import matplotlib.pyplot as plt
from mpl_toolkits import axes_grid1

def add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs):
    """Add a vertical color bar to an image plot."""
    divider = axes_grid1.make_axes_locatable(im.axes)
    width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect)
    pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
    current_ax = plt.gca()
    cax = divider.append_axes("right", size=width, pad=pad)
    plt.sca(current_ax)
    return im.axes.figure.colorbar(im, cax=cax, **kwargs)

It can be used like this:

im = plt.imshow(np.arange(200).reshape((20, 10)))
add_colorbar(im)

How do I change db schema to dbo

You can batch change schemas of multiple database objects as described in this post:

How to change schema of all tables, views and stored procedures in MSSQL

How do I execute a bash script in Terminal?

If you are in a directory or folder where the script file is available then simply change the file permission in executable mode by doing

chmod +x your_filename.sh

After that you will run the script by using the following command.

$ sudo ./your_filename.sh

Above the "." represent the current directory. Note! If you are not in the directory where the bash script file is present then you change the directory where the file is located by using

cd Directory_name/write the complete path

command. Otherwise your script can not run.

How can I subset rows in a data frame in R based on a vector of values?

Per the comments to the original post, merges / joins are well-suited for this problem. In particular, an inner join will return only values that are present in both dataframes, making thesetdiff statement unnecessary.

Using the data from Dinre's example:

In base R:

cleanedA <- merge(data_A, data_B[, "index"], by = 1, sort = FALSE)
cleanedB <- merge(data_B, data_A[, "index"], by = 1, sort = FALSE)

Using the dplyr package:

library(dplyr)
cleanedA <- inner_join(data_A, data_B %>% select(index))
cleanedB <- inner_join(data_B, data_A %>% select(index))

To keep the data as two separate tables, each containing only its own variables, this subsets the unwanted table to only its index variable before joining. Then no new variables are added to the resulting table.

What is the difference between require_relative and require in Ruby?

Summary

Use require for installed gems

Use require_relative for local files

require uses your $LOAD_PATH to find the files.
require_relative uses the current location of the file using the statement


require

Require relies on you having installed (e.g. gem install [package]) a package somewhere on your system for that functionality.

When using require you can use the "./" format for a file in the current directory, e.g. require "./my_file" but that is not a common or recommended practice and you should use require_relative instead.

require_relative

This simply means include the file 'relative to the location of the file with the require_relative statement'. I generally recommend that files should be "within" the current directory tree as opposed to "up", e.g. don't use

require_relative '../../../filename'

(up 3 directory levels) within the file system because that tends to create unnecessary and brittle dependencies. However in some cases if you are already 'deep' within a directory tree then "up and down" another directory tree branch may be necessary. More simply perhaps, don't use require_relative for files outside of this repository (assuming you are using git which is largely a de-facto standard at this point, late 2018).

Note that require_relative uses the current directory of the file with the require_relative statement (so not necessarily your current directory that you are using the command from). This keeps the require_relative path "stable" as it always be relative to the file requiring it in the same way.

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

You have to set classpath for mysql-connector.jar

In eclipse, use the build path

If you are developing any web app, you have to put mysql-connector to the lib folder of WEB-INF Directory of your web-app

char initial value in Java

i would just do:

char x = 0; //Which will give you an empty value of character

String's Maximum length in Java - calling length() method

Considering the String class' length method returns an int, the maximum length that would be returned by the method would be Integer.MAX_VALUE, which is 2^31 - 1 (or approximately 2 billion.)

In terms of lengths and indexing of arrays, (such as char[], which is probably the way the internal data representation is implemented for Strings), Chapter 10: Arrays of The Java Language Specification, Java SE 7 Edition says the following:

The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

Furthermore, the indexing must be by int values, as mentioned in Section 10.4:

Arrays must be indexed by int values;

Therefore, it appears that the limit is indeed 2^31 - 1, as that is the maximum value for a nonnegative int value.

However, there probably are going to be other limitations, such as the maximum allocatable size for an array.

.do extension in web pages?

.do comes from the Struts framework. See this question: Why do Java webapps use .do extension? Where did it come from? Also you can change what your urls look like using mod_rewrite (on Apache).

Explain the different tiers of 2 tier & 3 tier architecture?

The general explanation is provided in the link from Dan.


For specific questions your ask :

They can reside on the same machine, even in the same process (JVM for Java). It is a logical distinction (what they do?), not a physical one (where they are?).

How to call external JavaScript function in HTML

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

How to preserve request url with nginx proxy_pass

In case something modifies the location that you're trying to serve, e.g. try_files, this preserves the request for the back-end:

location / {
  proxy_pass http://127.0.0.1:8080$request_uri;
}

CSS-Only Scrollable Table with fixed headers

I was trying to figure this out myself recently, and I came up with a good solution that works perfectly in my browser (Chrome 51) and supports dynamic column widths. I should mention that after I independently derived my answer I also found a similar technique described elsewhere on the web...

The trick is to use two identical tables positioned on top of one another. The lower table is visible and the upper table is invisible expect for the header. The upper table also has pointer-events: none set on the tbody so mouse interactions hit the underneath table. This way the lower table scrolls under the upper table's header.

For everything to layout and resize properly (when the user adjusts screen width for instance), both tables need to have the same scrollbar behavior. However, the upper table's scroll bar is ignored thanks to the pointer-events: none and can be made invisible with:

<style>
    .hiddenScrollbar::-webkit-scrollbar {
        background-color: transparent;
    }
</style>

Here is the complete code:

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <style>_x000D_
    td {_x000D_
      border: 1px solid black; _x000D_
      white-space: nowrap;_x000D_
    }_x000D_
    th {_x000D_
      background-color: gray;_x000D_
      border: 1px solid black;_x000D_
      white-space: nowrap;_x000D_
    }_x000D_
    .hiddenScrollbar::-webkit-scrollbar {_x000D_
      background-color: transparent;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  Table test. Use mouse wheel to scroll or scroll to the right to see vertical scroll bar. You can also remove the outermost div if you don't want a horizontal scroll bar._x000D_
  <br/>_x000D_
  <div style="display: inline-block; height: 10em; width: 15em; overflow-x: scroll; overflow-y: hidden">_x000D_
    <div style="position: relative;">_x000D_
      <div style="display: inline-block; position: absolute; left: 0px; top: 0px; height: 10em; overflow-y: scroll">_x000D_
        <table style="border-collapse: collapse;">_x000D_
          <thead>_x000D_
            <tr>_x000D_
              <th>Column 1</th>_x000D_
              <th>Another Column</th>_x000D_
            </tr>_x000D_
          </thead>_x000D_
          <tbody>_x000D_
            <tr>_x000D_
              <td>Data 1</td>_x000D_
              <td>123409213750213</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Data 2</td>_x000D_
              <td>123409213750213</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Data 3</td>_x000D_
              <td>123409213750213</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Data 4</td>_x000D_
              <td>123409213750213</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Data 5</td>_x000D_
              <td>123409213750213</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Data 6</td>_x000D_
              <td>12340921375021342354235 very long...</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Data 7</td>_x000D_
              <td>123409213750213</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Data 8</td>_x000D_
              <td>123409213750213</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Data 9</td>_x000D_
              <td>123409213750213</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Data 10</td>_x000D_
              <td>123409213750213</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Data 11</td>_x000D_
              <td>123409213750213</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Data 12</td>_x000D_
              <td>123409213750213</td>_x000D_
            </tr>_x000D_
          </tbody>_x000D_
        </table>_x000D_
      </div>_x000D_
      <div class="hiddenScrollbar" style="display: inline-block; pointer-events: none; position: relative; left: 0px; top: 0px; height: 10em; overflow-y: scroll">_x000D_
        <table style="border-collapse: collapse;">_x000D_
          <thead style="pointer-events: auto">_x000D_
            <tr>_x000D_
              <th>Column 1</th>_x000D_
              <th>Another Column</th>_x000D_
            </tr>_x000D_
          </thead>_x000D_
          <tbody style="visibility: hidden">_x000D_
            <tr>_x000D_
              <tr>_x000D_
                <td>Data 1</td>_x000D_
                <td>123409213750213</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Data 2</td>_x000D_
                <td>123409213750213</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Data 3</td>_x000D_
                <td>123409213750213</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Data 4</td>_x000D_
                <td>123409213750213</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Data 5</td>_x000D_
                <td>123409213750213</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Data 6</td>_x000D_
                <td>12340921375021342354235 very long...</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Data 7</td>_x000D_
                <td>123409213750213</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Data 8</td>_x000D_
                <td>123409213750213</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Data 9</td>_x000D_
                <td>123409213750213</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Data 10</td>_x000D_
                <td>123409213750213</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Data 11</td>_x000D_
                <td>123409213750213</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Data 12</td>_x000D_
                <td>123409213750213</td>_x000D_
              </tr>_x000D_
            </tr>_x000D_
          </tbody>_x000D_
        </table>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div><br/>_x000D_
Stuff after table._x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Caveats: More work is required to prove this works in other browsers. Also I was rather liberal in mixing inline and stylesheet styles. However I believe the general concept is the best way of doing this since if the target browser supports it. The only functionality/display issues are that if you want a horizontal scroll bar, the vertical scroll bar can get scrolled out of view (as shown in the snippet). You can still scroll with the mouse wheel though. Additionally you can't have a transparent background on the header (otherwise the underneath table would show through). Finally you need a way to generate two identical tables. Personally I am using react.js and it is easy to do it with react, but php or other server-side generation or javascript will also work.

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

How do I add the Java API documentation to Eclipse?

For OpenJDK 8 on Linux see: https://askubuntu.com/questions/755853/how-to-install-jdk-sources

The way that worked for me is:

  • The default src.zip is a symbolic link pointing to a non-existing folder ...
  • sudo apt-get install openjdk-8-source this adds this folder
  • locate "src.zip"
  • Eclipse: Window --> Preferences --> Java --> "Installed JREs", edit and point to src.zip (or open any JRE class like for example HashMap and attach source)

You should now see the JavaDoc when opening JRE classes via Ctrl+Shift+t, previously this was not possible, Eclipse may have got a docs from the default URL on mouse over methods but this requires a stable internet connection.

Iterate keys in a C++ map

Lots of good answers here, below is an approach using a couple of them which lets you write this:

void main()
{
    std::map<std::string, int> m { {"jim", 1000}, {"sally", 2000} };
    for (auto key : MapKeys(m))
        std::cout << key << std::endl;
}

If that's what you always wanted, then here is the code for MapKeys():

template <class MapType>
class MapKeyIterator {
public:
    class iterator {
    public:
        iterator(typename MapType::iterator it) : it(it) {}
        iterator operator++() { return ++it; }
        bool operator!=(const iterator & other) { return it != other.it; }
        typename MapType::key_type operator*() const { return it->first; }  // Return key part of map
    private:
        typename MapType::iterator it;
    };
private:
    MapType& map;
public:
    MapKeyIterator(MapType& m) : map(m) {}
    iterator begin() { return iterator(map.begin()); }
    iterator end() { return iterator(map.end()); }
};
template <class MapType>
MapKeyIterator<MapType> MapKeys(MapType& m)
{
    return MapKeyIterator<MapType>(m);
}

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()

Here is the result. enter image description here

CSS/HTML: What is the correct way to make text italic?

DO

  1. Give the class attribute a value indicating the nature of the data (i.e. class="footnote" is good)

  2. Create a CSS style sheet for the page

  3. Define a CSS style that is attached to the class that you assign to the element

    .footnote { font-style:italic; }

DO NOT

  1. Don't use <i> or <em> elements - they're unsupported and ties the data and presentation too close.
  2. Don't give the class a value that indicates the presentation rules (i.e. don't use class="italic").

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

What is the best way to conditionally apply a class?

If you having a common class that is applied to many elements you can create a custom directive that will add that class like ng-show/ng-hide.

This directive will add the class 'active' to the button if it's clicked

module.directive('ngActive',  ['$animate', function($animate) {
  return function(scope, element, attr) {
    scope.$watch(attr.ngActive, function ngActiveWatchAction(value){
      $animate[value ? 'addClass' : 'removeClass'](element, 'active');
    });
  };
}]);

More info

How do I add an image to a JButton

buttonB.setIcon(new ImageIcon(this.getClass().getResource("imagename")));

Transmitting newline character "\n"

Use %0A (URL encoding) instead of \n (C encoding).

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

You can do this with a list comprehension and index()

tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
[x[0] for x in tuple_list].index("kumquat")
2
[x[1] for x in tuple_list].index(7)
1

Using a batch to copy from network drive to C: or D: drive

Just do the following change

echo off
cls

echo Would you like to do a backup?

pause

copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER

pause

HTTP Error 404 when running Tomcat from Eclipse

Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.34\webapps, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like your-eclipse-workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or .../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

Exporting results of a Mysql query to excel?

The typical way to achieve this is to export to CSV and then load the CSV into Excel.
You can using any MySQL command line tool to do this by including the INTO OUTFILE clause on your SELECT statement:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'file.csv'
FIELDS TERMINATED BY ','

See this link for detailed options.

Alternatively, you can use mysqldump to store dump into a separated value format using the --tab option, see this link.

mysqldump -u<user> -p<password> -h<host> --where=jtaskResult=2429 --tab=<file.csv> <database> TaskResult

Hint: If you don't specify an absoulte path but use something like INTO OUTFILE 'output.csv' or INTO OUTFILE './output.csv', it will store the output file to the directory specified by show variables like 'datadir';.

MongoDB query multiple collections at once

As mentioned before in MongoDB you can't JOIN between collections.

For your example a solution could be:

var myCursor = db.users.find({admin:1});
var user_id = myCursor.hasNext() ? myCursor.next() : null;
db.posts.find({owner_id : user_id._id});

See the reference manual - cursors section: http://es.docs.mongodb.org/manual/core/cursors/

Other solution would be to embed users in posts collection, but I think for most web applications users collection need to be independent for security reasons. Users collection might have Roles, permissons, etc.

posts
{
 "content":"Some content",
 "user":{"_id":"12345", "admin":1},
 "via":"facebook"
},
{
 "content":"Some other content",
 "user":{"_id":"123456789", "admin":0},
 "via":"facebook"
}

and then:

db.posts.find({user.admin: 1 });

How to access a preexisting collection with Mongoose?

Here's an abstraction of Will Nathan's answer if anyone just wants an easy copy-paste add-in function:

function find (name, query, cb) {
    mongoose.connection.db.collection(name, function (err, collection) {
       collection.find(query).toArray(cb);
   });
}

simply do find(collection_name, query, callback); to be given the result.

for example, if I have a document { a : 1 } in a collection 'foo' and I want to list its properties, I do this:

find('foo', {a : 1}, function (err, docs) {
            console.dir(docs);
        });
//output: [ { _id: 4e22118fb83406f66a159da5, a: 1 } ]

Attach a body onload event with JS

This takes advantage of DOMContentLoaded - which fires before onload - but allows you to stick in all your unobtrusiveness...

window.onload - Dean Edwards - The blog post talks more about it - and here is the complete code copied from the comments of that same blog.

// Dean Edwards/Matthias Miller/John Resig

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);

  // do stuff
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
window.onload = init;

How to manually install a pypi module without pip/easy_install?

To further explain Sheena's answer, I needed to have setup-tools installed as a dependency of another tool e.g. more-itertools.

Download

Click the Clone or download button and choose your method. I placed these into a dev/py/libs directory in my user home directory. It does not matter where they are saved, because they will not be installed there.

Installing setup-tools

You will need to run the following inside the setup-tools directory.

python bootstrap.py
python setup.py install

General dependencies installation

Now you can navigate to the more-itertools direcotry and install it as normal.

  1. Download the package
  2. Unpackage it if it's an archive
  3. Navigate (cd ...) into the directory containing setup.py
  4. If there are any installation instructions contained in the documentation contained herein, read and follow the instructions OTHERWISE
  5. Type in: python setup.py install

How do I install Python libraries in wheel format?

If you want to be relax for installing libraries for python.

You should using pip, that is python installer package.

To install pip:

  1. Download ez_setup.py and then run:

    python ez_setup.py
    
  2. Then download get-pip.py and run:

    python get-pip.py
    
  3. upgrade installed setuptools by pip:

    pip install setuptools --upgrade
    

    If you got this error:

    Wheel installs require setuptools >= 0.8 for dist-info support.
    pip's wheel support requires setuptools >= 0.8 for dist-info support.
    

    Add --no-use-wheel to above cmd:

    pip install setuptools --no-use-wheel --upgrade
    

Now, you can install libraries for python, just by:

pip install library_name

For example:

pip install requests

Note that to install some library may they need to compile, so you need to have compiler.

On windows there is a site for Unofficial Windows Binaries for Python Extension Packages that have huge python packages and complied python packages for windows.

For example to install pip using this site, just download and install setuptools and pip installer from that.

Server configuration by allow_url_fopen=0 in

Use this code in your php script (first lines)

ini_set('allow_url_fopen',1);

Backup/Restore a dockerized PostgreSQL database

dksnap (https://github.com/kelda/dksnap) automates the process of running pg_dumpall and loading the dump via /docker-entrypoint-initdb.d.

It shows you a list of running containers, and you pick which one you want to backup. The resulting artifact is a regular Docker image, so you can then docker run it, or share it by pushing it to a Docker registry.

(disclaimer: I'm a maintainer on the project)

Value Change Listener to JTextField

You can use even "MouseExited" to control. example:

 private void jtSoMauMouseExited(java.awt.event.MouseEvent evt) {                                    
        // TODO add your handling code here:
        try {
            if (Integer.parseInt(jtSoMau.getText()) > 1) {
                //auto update field
                SoMau = Integer.parseInt(jtSoMau.getText());
                int result = SoMau / 5;

                jtSoBlockQuan.setText(String.valueOf(result));
            }
        } catch (Exception e) {

        }

    }   

What is "stdafx.h" used for in Visual Studio?

All C++ compilers have one serious performance problem to deal with. Compiling C++ code is a long, slow process.

Compiling headers included on top of C++ files is a very long, slow process. Compiling the huge header structures that form part of Windows API and other large API libraries is a very, very long, slow process. To have to do it over, and over, and over for every single Cpp source file is a death knell.

This is not unique to Windows but an old problem faced by all compilers that have to compile against a large API like Windows.

The Microsoft compiler can ameliorate this problem with a simple trick called precompiled headers. The trick is pretty slick: although every CPP file can potentially and legally give a sligthly different meaning to the chain of header files included on top of each Cpp file (by things like having different macros #define'd in advance of the includes, or by including the headers in different order), that is most often not the case. Most of the time, we have dozens or hundreds of included files, but they all are intended to have the same meaning for all the Cpp files being compiled in your application.

The compiler can make huge time savings if it doesn't have to start to compile every Cpp file plus its dozens of includes literally from scratch every time.

The trick consists of designating a special header file as the starting point of all compilation chains, the so called 'precompiled header' file, which is commonly a file named stdafx.h simply for historical reasons.

Simply list all your big huge headers for your APIs in your stdafx.h file, in the appropriate order, and then start each of your CPP files at the very top with an #include "stdafx.h", before any meaningful content (just about the only thing allowed before is comments).

Under those conditions, instead of starting from scratch, the compiler starts compiling from the already saved results of compiling everything in stdafx.h.

I don't believe that this trick is unique to Microsoft compilers, nor do I think it was an original development.

For Microsoft compilers, the setting that controls the use of precompiled headers is controlled by a command line argument to the compiler: /Yu "stdafx.h". As you can imagine, the use of the stdafx.h file name is simply a convention; you can change the name if you so wish.

In Visual Studio 2010, this setting is controlled from the GUI via Right-clicking on a CPP Project, selecting 'Properties' and navigating to "Configuration Properties\C/C++\Precompiled Headers". For other versions of Visual Studio, the location in the GUI will be different.

Note that if you disable precompiled headers (or run your project through a tool that doesn't support them), it doesn't make your program illegal; it simply means that your tool will compile everything from scratch every time.

If you are creating a library with no Windows dependencies, you can easily comment out or remove #includes from the stdafx.h file. There is no need to remove the file per se, but clearly you may do so as well, by disabling the precompile header setting above.

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

Completing the answer from @xanblax

private static string getUserName()
    {
        SelectQuery query = new SelectQuery(@"Select * from Win32_Process");
        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
        {
            foreach (System.Management.ManagementObject Process in searcher.Get())
            {
                if (Process["ExecutablePath"] != null &&
                    string.Equals(Path.GetFileName(Process["ExecutablePath"].ToString()), "explorer.exe", StringComparison.OrdinalIgnoreCase))
                {
                    string[] OwnerInfo = new string[2];
                    Process.InvokeMethod("GetOwner", (object[])OwnerInfo);

                    return OwnerInfo[0];
                }
            }
        }
        return "";
    }

Excel Formula: Count cells where value is date

Here's my solution. If your cells will contain only dates or blanks, just compare it to another date. If the cell can be converted to date, it will be counted.

=COUNTIF(C:C,">1/1/1900")
## Counts all the dates in column C

Caution, cells with numbers will be counted.

Can an Android NFC phone act as an NFC tag?

Its possible to make Android device behave as an NFC Tag. Such a behaviour is called Card Emulation.

  • Card emulation can be host-based(HCE) or secure-element based(CE).
  • In HCE, an application running on the Android main processor responds to the reader. So, the phone needs to be ON.
  • In CE, an applet residing in the Secure element responds to the reader. Here, its sufficient to have the NFC controller powered, with rest of the device suspended.
  • One of these or both approaches can be active simultaneously.
    A routing table instructs the NFC controller where route the Reader's commands to.

npm ERR cb() never called

For anyone who has upgraded recently from 6.x to 6.7.0.

Deleting the /Users/{YOUR USERNAME}/.npm folder solved my issues with npm install.

I also, ran some of these commands suggested by https://npm.community/t/crash-npm-err-cb-never-called/858/93?u=jasonfoglia

sudo npm cache clean -f
sudo npm install -g n

But I'm not sure which actually worked until I deleted the folder. So if you experience this issue and just delete the .npm folder fixing your issue please note that in the comments.

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

This worked fine for me:

else if(requestCode == GALLERY_ACTIVITY_NEW && resultCode == Activity.RESULT_OK)
{
    Uri uri = data.getData();
    Log.i(TAG, "old uri =  " + uri);
    dumpImageMetaData(uri);

    try {
        ParcelFileDescriptor parcelFileDescriptor =
                getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Log.i(TAG, "File descriptor " + fileDescriptor.toString());

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);

        options.inSampleSize =
           BitmapHelper.calculateInSampleSize(options,
                                              User.PICTURE_MAX_WIDTH_IN_PIXELS,
                                              User.PICTURE_MAX_HEIGHT_IN_PIXELS);
        options.inJustDecodeBounds = false;

        Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
        imageViewPic.setImageBitmap(bitmap);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        // get byte array here
        byte[] picData = stream.toByteArray();
        ParseFile picFile = new ParseFile(picData);
        user.setProfilePicture(picFile);
    }
    catch(FileNotFoundException exc)
    {
        Log.i(TAG, "File not found: " + exc.toString());
    }
}

How do you divide each element in a list by an int?

The idiomatic way would be to use list comprehension:

myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [x / myInt for x in myList]

or, if you need to maintain the reference to the original list:

myList[:] = [x / myInt for x in myList]

Send POST request with JSON data using Volley

final String URL = "/volley/resource/12";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   VolleyLog.v("Response:%n %s", response.toString(4));
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());
           }
       });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

refer

How do you Sort a DataTable given column and direction?

In case you want to sort in more than one direction

  public static void sortOutputTable(ref DataTable output)
        {
            DataView dv = output.DefaultView;
            dv.Sort = "specialCode ASC, otherCode DESC";
            DataTable sortedDT = dv.ToTable();
            output = sortedDT;
        }

How to add image background to btn-default twitter-bootstrap button?

Have you tried using a icon font like http://fortawesome.github.io/Font-Awesome/

Bootstrap comes with their own library, but it doesn't have as many icons as Font Awesome.

http://getbootstrap.com/components/#glyphicons

Hard reset of a single file

Reference to HEAD is not necessary.

git checkout -- file.js is sufficient

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

ImmutableMap does not accept null values whereas Collections.unmodifiableMap() does. In addition it will never change after construction, while UnmodifiableMap may. From the JavaDoc:

An immutable, hash-based Map with reliable user-specified iteration order. Does not permit null keys or values.

Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.

How to select and change value of table cell with jQuery?

You can use CSS selectors.

Depending on how you get that td, you can either give it an id:

<td id='cell'>c</td>

and then use:

$("#cell").text("text");

Or traverse to the third cell of the first row of table_header, etc.

Convert unix time to readable date in pandas dataframe

These appear to be seconds since epoch.

In [20]: df = DataFrame(data['values'])

In [21]: df.columns = ["date","price"]

In [22]: df
Out[22]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 358 entries, 0 to 357
Data columns (total 2 columns):
date     358  non-null values
price    358  non-null values
dtypes: float64(1), int64(1)

In [23]: df.head()
Out[23]: 
         date  price
0  1349720105  12.08
1  1349806505  12.35
2  1349892905  12.15
3  1349979305  12.19
4  1350065705  12.15
In [25]: df['date'] = pd.to_datetime(df['date'],unit='s')

In [26]: df.head()
Out[26]: 
                 date  price
0 2012-10-08 18:15:05  12.08
1 2012-10-09 18:15:05  12.35
2 2012-10-10 18:15:05  12.15
3 2012-10-11 18:15:05  12.19
4 2012-10-12 18:15:05  12.15

In [27]: df.dtypes
Out[27]: 
date     datetime64[ns]
price           float64
dtype: object

Why do Sublime Text 3 Themes not affect the sidebar?

Here's the short version:

  1. .sublime-theme files change the look of the UI including the Sidebar and File Tabs.
  2. Defining these are a tremendous pain, so save yourself a lot of time and install the Theme Menu Switcher package.

Update: Sublime Text 3 has fundamentally changed the way Color Schemes and Themes work, and has broken many of the packages that were built to handle them. I can no longer confirm the accuracy of this post, nor the functionality of the packages mentioned herein because the Sublime developers have not fully explained the changes to the customization system nor addressed how to fix them. And, at the very best, they are far more difficult to change.

At this point, this post should only be used as a reference to the differences between "themes" and "color schemes" in Sublime Text 2, as I myself have yet to successfully change a theme nor color scheme in Sublime Text 3.

I will update this post as I can dedicate more time to unraveling this Sublime Customization Quagmire.


Here's the long version:

tmTheme vs sublime-theme file type affection areas Figure 1: The difference between "Color Schemes" and "Themes" - In the Sublime Community these terms are often confused and used interchangeably.

Changing the look of Sublime is a relatively difficult endeavor, for three main reasons:

  • Poorly chosen terminology
  • Misinformation in the Sublime Community
  • Installation Nightmare

Terminology

There are 2 different sections of Sublime that can be customized:

  • the editable region (the purple regions)
  • the User Interface (the green regions)

These use two different file types, and they do not accurately reflect the terminology.

The "Why?" of this decision is compatibility, and for brevity's sake I won't get into it here, but the fallout of this effort is:

The file type called tmTheme does not affect the theme, it affects the Color Scheme.

Color Schemes (highlighted in purple)

  • affect the look of the editable region (more specifically, the editable characters, ie what color they are when highlighted or not highlighted, etc).
  • relatively easy to produce
  • Color Schemes are Mistakenly called "Themes" all over the Sublime Community.

Themes (highlighted in green)

  • .sublime-theme files change the Theme, or the UI aspects of Sublime.
  • difficult to produce
  • It is difficult to find true Sublime Themes, compared to "Color Schemes"

Misinformation

Many packages claim to change the Theme, but actually change the Color Scheme. This is usually because the people producing them don't know that "Theme" specifically refers to the UI.

So another level of difficulty is finding a true "Theme" package, rather than Color Scheme.

Even some legit websites do not correctly make a distinction between the two, which adds to the challenges. For instance, colorsublime.com has a tutorial on changing the sublime "theme", but actually references the "Color Scheme" file type (.tmTheme).

Installation Pains

Themes and Color Schemes are hard to install and define. In fact, it's shocking how difficult the process is. The difficulty is further exacerbated with a fundamental change in installation and definition requirements in Sublime Text 3 that are not fully explained, which breaks many of the packages we once were reliant upon to change the Themes and Color Schemes.

It requires installing an actual Theme package (good luck finding one by browsing Packages in Package Control), defining it in settings, and then restarting Sublime. And, if you did something wrong, Sublime will simply replace your user-defined theme setting with the default. Yes, you heard me right, without notice or error message, Sublime will overwrite your theme definition.

But with Themes Menu Switcher All you need to do is go to Preferences > Theme and you'll see a list of all themes you have installed. You can also easily switch between themes without restarting Sublime.

Here's a sample from the website:Theme Switcher gif

I have no affiliation with Theme Menu Switcher at all, I'm just a fan.

Again, Theme Menu Switcher does not work the same in Sublime Text 3. If you need to have a customized look, I recommend not to update to Sublime Text 3.

Remove specific characters from a string in Javascript

if it is not the first two chars and you wanna remove F0 from the whole string then you gotta use this regex

_x000D_
_x000D_
   let string = 'F0123F0456F0';_x000D_
   let result = string.replace(/F0/ig, '');_x000D_
   console.log(result);
_x000D_
_x000D_
_x000D_

Receive JSON POST with PHP

If you already have your parameters set like $_POST['eg'] for example and you don't wish to change it, simply do it like this:

$_POST = json_decode(file_get_contents('php://input'), true);

This will save you the hassle of changing all $_POST to something else and allow you to still make normal post requests if you wish to take this line out.

How to style SVG <g> element?

The style that you give the "g" element will apply the child elements, not the "g" element itself.

Add a rectangle element and position around the group you wish to style.

See: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g

EDIT: updated wording and added fiddle in comments.

Garbage collector in Android

For versions prior to 3.0 honeycomb: Yes, do call System.gc().

I tried to create Bitmaps, but was always getting "VM out of memory error". But, when I called System.gc() first, it was OK.

When creating bitmaps, Android often fails with out of memory errors, and does not try to garbage collect first. Hence, call System.gc(), and you have enough memory to create Bitmaps.

If creating Objects, I think System.gc will be called automatically if needed, but not for creating bitmaps. It just fails.

So I recommend manually calling System.gc() before creating bitmaps.

Mongoose delete array element in document and save

The checked answer does work but officially in MongooseJS latest, you should use pull.

doc.subdocs.push({ _id: 4815162342 }) // added
doc.subdocs.pull({ _id: 4815162342 }) // removed

https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-pull

I was just looking that up too.

See Daniel's answer for the correct answer. Much better.

How do I remove a property from a JavaScript object?

If you don't want to modify the original object.

Remove a property without mutating the object

If mutability is a concern, you can create a completely new object by copying all the properties from the old, except the one you want to remove.

_x000D_
_x000D_
let myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI",
  "regex": "^http://.*"
};

let prop = 'regex';
const updatedObject = Object.keys(myObject).reduce((object, key) => {
  if (key !== prop) {
    object[key] = myObject[key]
  }
  return object
}, {})

console.log(updatedObject);
_x000D_
_x000D_
_x000D_

adding .css file to ejs

app.use(express.static(__dirname + '/public'));
<link href="/css/style.css" rel="stylesheet" type="text/css">

So folder structure should be:

.
./app.js
./public
 /css
 /style.css

How to run a hello.js file in Node.js on windows?

I installed node for windows. There is a node.js command prompt when I search for node.js in windows 7 start menu If you run this special command prompt, you can node anything in any location without setting up the path or copy node.exe everywhere.

git: diff between file in local repo and origin

To check with current branch:

git diff -- projects/components/some.component.ts ... origin
git diff -- projects/components/some.component.html ... origin

To check with some other branch say staging:

git diff -- projects/components/some.component.ts ... origin/staging
git diff -- projects/components/some.component.html ... origin/staging

disable past dates on datepicker

$("#datetimepicker2").datepicker({ 
  dateFormat: "mm/dd/yy", 
  minDate: new Date()
});

How to write specific CSS for mozilla, chrome and IE

Check out this link : http://webdesignerwall.com/tutorials/css-specific-for-internet-explorer

2 CSS Rules Specific to Explorer (IE CSS hacks)

Another option is to declare CSS rules that can only be read by Explorer. For example, add an asterisk (*) before the CSS property will target IE7 or add an underscore before the property will target IE6. However, this method is not recommended because they are not valid CSS syntax.

IE8 or below: to write CSS rules specificially to IE8 or below, add a backslash and 9 (\9) at the end before the semicolon. IE7 or below: add an asterisk (*) before the CSS property. IE6: add an underscore (_) before the property. .box {

background: gray; /* standard */

background: pink\9; /* IE 8 and below */

*background: green; /* IE 7 and below */

_background: blue; /* IE 6 */

}

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

Use the Post/Redirect/Get pattern. http://en.wikipedia.org/wiki/Post/Redirect/Get

With my website, I will store a message in a cookie or session, redirect after the post, read the cookie/session, and then clear the value of that session or cookie variable.

How do I empty an input value with jQuery?

Another way is:

$('#element').attr('value', '');

How to find array / dictionary value using key?

It's as simple as this :

$array[$key];

Oracle: SQL query that returns rows with only numeric values

You can use following command -

LENGTH(TRIM(TRANSLATE(string1, '+-.0123456789', '')))

This will return NULL if your string1 is Numeric

your query would be -

select * from tablename 
where LENGTH(TRIM(TRANSLATE(X, '+-.0123456789', ''))) is null

I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

What are the differences between "git commit" and "git push"?

It is easier to understand the use of the git commands add and commit if you imagine a log file being maintained in your repository on Github. A typical project's log file for me may look like:

---------------- Day 1 --------------------
Message: Completed Task A
Index of files changed: File1, File2

Message: Completed Task B
Index of files changed: File2, File3
-------------------------------------------

---------------- Day 2 --------------------
Message: Corrected typos
Index of files changed: File3, File1
-------------------------------------------
...
...
...and so on

I usually start my day with a git pull request and end it with a git push request. So everything inside a day's record corresponds to what occurs between them. During each day, there are one or more logical tasks that I complete which require changing a few files. The files edited during that task are listed in an index.

Each of these sub tasks(Task A and Task B here) are individual commits. The git add command adds files to the 'Index of Files Changed' list. This process is also called staging and in reality records changed files and the changes performed. The git commit command records/finalizes the changes and the corresponding index list along with a custom message which may be used for later reference.

Remember that you're still only changing the local copy of your repository and not the one on Github. After this, only when you do a git push do all these recorded changes, along with your index files for each commit, get logged on the main repository(on Github).

As an example, to obtain the second entry in that imaginary log file, I would have done:

git pull
# Make changes to File3 and File4
git add File3 File4
# Verify changes, run tests etc..
git commit -m 'Corrected typos'
git push

In a nutshell, git add and git commit lets you break down a change to the main repository into systematic logical sub-changes. As other answers and comments have pointed out, there are ofcourse many more uses to them. However, this is one of the most common usages and a driving principle behind Git being a multi-stage revision control system unlike other popular ones like Svn.

Curl error: Operation timed out

In curl request add time out 0 so its infinite time set like CURLOPT_TIMEOUT set 0

Pointer to incomplete class type is not allowed

You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:

namespace X
{
  namespace Y
  {
    class A;

    void func(A* a) { ... } // incomplete type here!
  }
}

...but, in class A was defined like this:

namespace X
{
  class A { ... };
}

Thus, A was defined as X::A, but I was using it as X::Y::A.

The fix obviously is to move the forward reference to its proper place like so:

namespace X
{
  class A;
  namespace Y
  {
    void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
  }
}

Alternative for PHP_excel

For Writing Excel

  • PEAR's PHP_Excel_Writer (xls only)
  • php_writeexcel from Bettina Attack (xls only)
  • XLS File Generator commercial and xls only
  • Excel Writer for PHP from Sourceforge (spreadsheetML only)
  • Ilia Alshanetsky's Excel extension now on github (xls and xlsx, and requires commercial libXL component)
  • PHP's COM extension (requires a COM enabled spreadsheet program such as MS Excel or OpenOffice Calc running on the server)
  • The Open Office alternative to COM (PUNO) (requires Open Office installed on the server with Java support enabled)
  • PHP-Export-Data by Eli Dickinson (Writes SpreadsheetML - the Excel 2003 XML format, and CSV)
  • Oliver Schwarz's php-excel (SpreadsheetML)
  • Oliver Schwarz's original version of php-excel (SpreadsheetML)
  • excel_xml (SpreadsheetML, despite its name)... link reported as broken
  • The tiny-but-strong (tbs) project includes the OpenTBS tool for creating OfficeOpenXML documents (OpenDocument and OfficeOpenXML formats)
  • SimpleExcel Claims to read and write Microsoft Excel XML / CSV / TSV / HTML / JSON / etc formats
  • KoolGrid xls spreadsheets only, but also doc and pdf
  • PHP_XLSXWriter OfficeOpenXML
  • PHP_XLSXWriter_plus OfficeOpenXML, fork of PHP_XLSXWriter
  • php_writeexcel xls only (looks like it's based on PEAR SEW)
  • spout OfficeOpenXML (xlsx) and CSV
  • Slamdunk/php-excel (xls only) looks like an updated version of the old PEAR Spreadsheet Writer

For Reading Excel

A new C++ Excel extension for PHP, though you'll need to build it yourself, and the docs are pretty sparse when it comes to trying to find out what functionality (I can't even find out from the site what formats it supports, or whether it reads or writes or both.... I'm guessing both) it offers is phpexcellib from SIMITGROUP.

All claim to be faster than PHPExcel from codeplex or from github, but (with the exception of COM, PUNO Ilia's wrapper around libXl and spout) they don't offer both reading and writing, or both xls and xlsx; may no longer be supported; and (while I haven't tested Ilia's extension) only COM and PUNO offers the same degree of control over the created workbook.

Trim Whitespaces (New Line and Tab space) in a String in Oracle

How about the quick and dirty translate function?

This will remove all occurrences of each character in string1:

SELECT translate(
           translate(
               translate(string1, CHR(10), '')
           , CHR(13), '')
       , CHR(09), '') as massaged
FROM BLAH;

Regexp_replace is an option, but you may see a performance hit depending on how complex your expression is.

Getting Python error "from: can't read /var/mail/Bio"

Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.

./manage.py shell

and only then

>>> from django.contrib.sites.models import Site

What is PEP8's E128: continuation line under-indented for visual indent?

PEP-8 recommends you indent lines to the opening parentheses if you put anything on the first line, so it should either be indenting to the opening bracket:

urlpatterns = patterns('',
                       url(r'^$', listing, name='investment-listing'))

or not putting any arguments on the starting line, then indenting to a uniform level:

urlpatterns = patterns(
    '',
    url(r'^$', listing, name='investment-listing'),
)

urlpatterns = patterns(
    '', url(r'^$', listing, name='investment-listing'))

I suggest taking a read through PEP-8 - you can skim through a lot of it, and it's pretty easy to understand, unlike some of the more technical PEPs.

Simple file write function in C++

Your main doesn't know about writeFile() and can't call it.

Move writefile to be before main, or declare a function prototype int writeFile(); before main.

What is the maximum possible length of a .NET string?

For anyone coming to this topic late, I could see that hitscan's "you probably shouldn't do that" might cause someone to ask what they should do…

The StringBuilder class is often an easy replacement. Consider one of the stream-based classes especially, if your data is coming from a file.

The problem with s += "stuff" is that it has to allocate a completely new area to hold the data and then copy all of the old data to it plus the new stuff - EACH AND EVERY LOOP ITERATION. So, adding five bytes to 1,000,000 with s += "stuff" is extremely costly. If what you want is to just write five bytes to the end and proceed with your program, you have to pick a class that leaves some room for growth:

StringBuilder sb = new StringBuilder(5000);
for (; ; )
    {
        sb.Append("stuff");
    }

StringBuilder will auto-grow by doubling when it's limit is hit. So, you will see the growth pain once at start, once at 5,000 bytes, again at 10,000, again at 20,000. Appending strings will incur the pain every loop iteration.

HTML select dropdown list

This is an old post, but this worked for me

_x000D_
_x000D_
<select>_x000D_
  <option value="" disabled selected>Please select a name...</option> _x000D_
  <option>this</option>_x000D_
  <option>that</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Python Variable Declaration

For scoping purpose, I use:

custom_object = None

Get TimeZone offset value from TimeZone without TimeZone name

I need to save the phone's timezone in the format [+/-]hh:mm

No, you don't. Offset on its own is not enough, you need to store the whole time zone name/id. For example I live in Oslo where my current offset is +02:00 but in winter (due to ) it is +01:00. The exact switch between standard and summer time depends on factors you don't want to explore.

So instead of storing + 02:00 (or should it be + 01:00?) I store "Europe/Oslo" in my database. Now I can restore full configuration using:

TimeZone tz = TimeZone.getTimeZone("Europe/Oslo")

Want to know what is my time zone offset today?

tz.getOffset(new Date().getTime()) / 1000 / 60   //yields +120 minutes

However the same in December:

Calendar christmas = new GregorianCalendar(2012, DECEMBER, 25);
tz.getOffset(christmas.getTimeInMillis()) / 1000 / 60   //yields +60 minutes

Enough to say: store time zone name or id and every time you want to display a date, check what is the current offset (today) rather than storing fixed value. You can use TimeZone.getAvailableIDs() to enumerate all supported timezone IDs.

Very Simple, Very Smooth, JavaScript Marquee

Responsive resist jQuery marquee simple plugin. Tutorial:

// start plugin
    (function($){
        $.fn.marque = function(options, callback){

            // check callback

            if(typeof callback == 'function'){
                callback.call(this);
            } else{
                console.log("second argument (callback) is not a function");
                // throw "callback must be a function"; //only if callback for some reason is required
                // return this; //only if callback for some reason is required
            }

            //set and overwrite default functions
            var defOptions = $.extend({
                speedPixelsInOneSecound: 150, //speed will behave same for different screen where duration will be different for each size of the screen
                select: $('.message div'),
                clickSelect: '', // selector that on click will redirect user ... (optional)
                clickUrl: '' //... to this url. (optional)
            }, options);

            //Run marque plugin
            var windowWidth = $(window).width();
            var textWidth = defOptions.select.outerWidth();
            var duration = (windowWidth + textWidth) * 1000 / defOptions.speedPixelsInOneSecound;
            var startingPosition = (windowWidth + textWidth);
            var curentPosition = (windowWidth + textWidth);
            var speedProportionToLocation = curentPosition / startingPosition;
            defOptions.select.css({'right': -(textWidth)});
            defOptions.select.show();
            var animation;


            function marquee(animation){
                curentPosition = (windowWidth + defOptions.select.outerWidth());
                speedProportionToLocation = curentPosition / startingPosition;
                animation = defOptions.select.animate({'right': windowWidth+'px'}, duration * speedProportionToLocation, "linear", function(){
                     defOptions.select.css({'right': -(textWidth)});
                });
            }
            var play = setInterval(marquee, 200);

            //add onclick behaviour
            if(defOptions.clickSelect != '' && defOptions.clickUrl != ''){
                defOptions.clickSelect.click(function(){
                    window.location.href = defOptions.clickUrl;
                });
            }
            return this;
        };

    }(jQuery)); 
// end plugin 

Use this custom jQuery plugin as bellow:

//use example
$(window).marque({
    speedPixelsInOneSecound: 150, // spped pixels/secound
    select: $('.message div'), // select an object on which you want to apply marquee effects.
    clickSelect: $('.message'), // select clicable object (optional)
    clickUrl: 'services.php' // define redirection url (optional)
});