Programs & Examples On #Using

using is a keyword in some programming languages (C++, C#, VB.NET, Haxe)

What is the best workaround for the WCF client `using` block issue?

Given a choice between the solution advocated by IServiceOriented.com and the solution advocated by David Barret's blog, I prefer the simplicity offered by overriding the client's Dispose() method. This allows me to continue to use the using() statement as one would expect with a disposable object. However, as @Brian pointed out, this solution contains a race condition in that the State might not be faulted when it is checked but could be by the time Close() is called, in which case the CommunicationException still occurs.

So, to get around this, I've employed a solution that mixes the best of both worlds.

void IDisposable.Dispose()
{
    bool success = false;
    try 
    {
        if (State != CommunicationState.Faulted) 
        {
            Close();
            success = true;
        }
    } 
    finally 
    {
        if (!success) 
            Abort();
    }
}

Do HttpClient and HttpClientHandler have to be disposed between requests?

In typical usage (responses<2GB) it is not necessary to Dispose the HttpResponseMessages.

The return types of the HttpClient methods should be Disposed if their Stream Content is not fully Read. Otherwise there is no way for the CLR to know those Streams can be closed until they are garbage collected.

  • If you are reading the data into a byte[] (e.g. GetByteArrayAsync) or string, all data is read, so there is no need to dispose.
  • The other overloads will default to reading the Stream up to 2GB (HttpCompletionOption is ResponseContentRead, HttpClient.MaxResponseContentBufferSize default is 2GB)

If you set the HttpCompletionOption to ResponseHeadersRead or the response is larger than 2GB, you should clean up. This can be done by calling Dispose on the HttpResponseMessage or by calling Dispose/Close on the Stream obtained from the HttpResonseMessage Content or by reading the content completely.

Whether you call Dispose on the HttpClient depends on whether you want to cancel pending requests or not.

What is the C# Using block and why should I use it?

using (B a = new B())
{
   DoSomethingWith(a);
}

is equivalent to

B a = new B();
try
{
  DoSomethingWith(a);
}
finally
{
   ((IDisposable)a).Dispose();
}

MySQL JOIN ON vs USING?

Thought I would chip in here with when I have found ON to be more useful than USING. It is when OUTER joins are introduced into queries.

ON benefits from allowing the results set of the table that a query is OUTER joining onto to be restricted while maintaining the OUTER join. Attempting to restrict the results set through specifying a WHERE clause will, effectively, change the OUTER join into an INNER join.

Granted this may be a relative corner case. Worth putting out there though.....

For example:

CREATE TABLE country (
   countryId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
   country varchar(50) not null,
  UNIQUE KEY countryUIdx1 (country)
) ENGINE=InnoDB;

insert into country(country) values ("France");
insert into country(country) values ("China");
insert into country(country) values ("USA");
insert into country(country) values ("Italy");
insert into country(country) values ("UK");
insert into country(country) values ("Monaco");


CREATE TABLE city (
  cityId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
  countryId int(10) unsigned not null,
  city varchar(50) not null,
  hasAirport boolean not null default true,
  UNIQUE KEY cityUIdx1 (countryId,city),
  CONSTRAINT city_country_fk1 FOREIGN KEY (countryId) REFERENCES country (countryId)
) ENGINE=InnoDB;


insert into city (countryId,city,hasAirport) values (1,"Paris",true);
insert into city (countryId,city,hasAirport) values (2,"Bejing",true);
insert into city (countryId,city,hasAirport) values (3,"New York",true);
insert into city (countryId,city,hasAirport) values (4,"Napoli",true);
insert into city (countryId,city,hasAirport) values (5,"Manchester",true);
insert into city (countryId,city,hasAirport) values (5,"Birmingham",false);
insert into city (countryId,city,hasAirport) values (3,"Cincinatti",false);
insert into city (countryId,city,hasAirport) values (6,"Monaco",false);

-- Gah. Left outer join is now effectively an inner join 
-- because of the where predicate
select *
from country left join city using (countryId)
where hasAirport
; 

-- Hooray! I can see Monaco again thanks to 
-- moving my predicate into the ON
select *
from country co left join city ci on (co.countryId=ci.countryId and ci.hasAirport)
; 

Should I Dispose() DataSet and DataTable?

You should assume it does something useful and call Dispose even if it does nothing in current .NET Framework incarnations. There's no guarantee it will stay that way in future versions leading to inefficient resource usage.

in a "using" block is a SqlConnection closed on return or exception?

I wrote two using statements inside a try/catch block and I could see the exception was being caught the same way if it's placed within the inner using statement just as ShaneLS example.

     try
     {
       using (var con = new SqlConnection(@"Data Source=..."))
       {
         var cad = "INSERT INTO table VALUES (@r1,@r2,@r3)";

         using (var insertCommand = new SqlCommand(cad, con))
         {
           insertCommand.Parameters.AddWithValue("@r1", atxt);
           insertCommand.Parameters.AddWithValue("@r2", btxt);
           insertCommand.Parameters.AddWithValue("@r3", ctxt);
           con.Open();
           insertCommand.ExecuteNonQuery();
         }
       }
     }
     catch (Exception ex)
     {
       MessageBox.Show("Error: " + ex.Message, "UsingTest", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }

No matter where's the try/catch placed, the exception will be caught without issues.

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

Dynamically updating plot in matplotlib

Is there a way in which I can update the plot just by adding more point[s] to it...

There are a number of ways of animating data in matplotlib, depending on the version you have. Have you seen the matplotlib cookbook examples? Also, check out the more modern animation examples in the matplotlib documentation. Finally, the animation API defines a function FuncAnimation which animates a function in time. This function could just be the function you use to acquire your data.

Each method basically sets the data property of the object being drawn, so doesn't require clearing the screen or figure. The data property can simply be extended, so you can keep the previous points and just keep adding to your line (or image or whatever you are drawing).

Given that you say that your data arrival time is uncertain your best bet is probably just to do something like:

import matplotlib.pyplot as plt
import numpy

hl, = plt.plot([], [])

def update_line(hl, new_data):
    hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
    hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
    plt.draw()

Then when you receive data from the serial port just call update_line.

How do I copy to the clipboard in JavaScript?

My bad. This only works in Internet Explorer.

Here's yet another way to copy text:

<p>
    <a onclick="window.clipboardData.setData('text', document.getElementById('Test').innerText);">Copy</a>
</p>

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

The general answer to this question is:

Don't geocode known locations every time you load your page. Geocode them off-line and use the resulting coordinates to display the markers on your page.

The limits exist for a reason.

If you can't geocode the locations off-line, see this page (Part 17 Geocoding multiple addresses) from Mike Williams' v2 tutorial which describes an approach, port that to the v3 API.

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

For Swift 2.3

This seems to be a bug with Xcode 8 and Swift 2.3, if you're connecting the button action to your code via storyboard be sure that Xcode didn't rename the action, for me it's adding a withSender: at the end of the methods, so what I do is going to my code and renaming the method to match the one Xcode wrote.

For any other version check the correct answer.

jquery : focus to div is not working

Focus doesn't work on divs by default. But, according to this, you can make it work:

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

http://api.jquery.com/focus/

Using LINQ to group by multiple properties and sum

Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
                   });

Capitalize first letter. MySQL

http://forge.mysql.com/tools/tool.php?id=201

If there are more than 1 word in the column, then this will not work as shown below. The UDF mentioned above may help in such case.

mysql> select * from names;
+--------------+
| name         |
+--------------+
| john abraham | 
+--------------+
1 row in set (0.00 sec)

mysql> SELECT CONCAT(UCASE(MID(name,1,1)),MID(name,2)) AS name FROM names;
+--------------+
| name         |
+--------------+
| John abraham | 
+--------------+
1 row in set (0.00 sec)

Or maybe this one will help...

https://github.com/mysqludf/lib_mysqludf_str#str_ucwords

What’s the best way to get an HTTP response code from a URL?

Addressing @Niklas R's comment to @nickanor's answer:

from urllib.error import HTTPError
import urllib.request

def getResponseCode(url):
    try:
        conn = urllib.request.urlopen(url)
        return conn.getcode()
    except HTTPError as e:
        return e.code

MySQL: View with Subquery in the FROM Clause Limitation

I had the same problem. I wanted to create a view to show information of the most recent year, from a table with records from 2009 to 2011. Here's the original query:

SELECT a.* 
FROM a 
JOIN ( 
  SELECT a.alias, MAX(a.year) as max_year 
  FROM a 
  GROUP BY a.alias
) b 
ON a.alias=b.alias and a.year=b.max_year

Outline of solution:

  1. create a view for each subquery
  2. replace subqueries with those views

Here's the solution query:

CREATE VIEW v_max_year AS 
  SELECT alias, MAX(year) as max_year 
  FROM a 
  GROUP BY a.alias;

CREATE VIEW v_latest_info AS 
  SELECT a.* 
  FROM a 
  JOIN v_max_year b 
  ON a.alias=b.alias and a.year=b.max_year;

It works fine on mysql 5.0.45, without much of a speed penalty (compared to executing the original sub-query select without any views).

AngularJS : Initialize service with asynchronous data

What you can do is in your .config for the app is create the resolve object for the route and in the function pass in $q (promise object) and the name of the service you're depending on, and resolve the promise in the callback function for the $http in the service like so:

ROUTE CONFIG

app.config(function($routeProvider){
    $routeProvider
     .when('/',{
          templateUrl: 'home.html',
          controller: 'homeCtrl',
          resolve:function($q,MyService) {
                //create the defer variable and pass it to our service
                var defer = $q.defer();
                MyService.fetchData(defer);
                //this will only return when the promise
                //has been resolved. MyService is going to
                //do that for us
                return defer.promise;
          }
      })
}

Angular won't render the template or make the controller available until defer.resolve() has been called. We can do that in our service:

SERVICE

app.service('MyService',function($http){
       var MyService = {};
       //our service accepts a promise object which 
       //it will resolve on behalf of the calling function
       MyService.fetchData = function(q) {
             $http({method:'GET',url:'data.php'}).success(function(data){
                 MyService.data = data;
                 //when the following is called it will
                 //release the calling function. in this
                 //case it's the resolve function in our
                 //route config
                 q.resolve();
             }
       }

       return MyService;
});

Now that MyService has the data assigned to it's data property, and the promise in the route resolve object has been resolved, our controller for the route kicks into life, and we can assign the data from the service to our controller object.

CONTROLLER

  app.controller('homeCtrl',function($scope,MyService){
       $scope.servicedata = MyService.data;
  });

Now all our binding in the scope of the controller will be able to use the data which originated from MyService.

Error: Cannot find module html

Use

res.sendFile()

instead of

res.render().

What your trying to do is send a whole file.

This worked for me.

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

You can try openSSL to generate certificates. Take a look at this.

You are going to need a .key and .crt file to add HTTPS to node JS express server. Once you generate this, use this code to add HTTPS to server.

var https = require('https');
var fs = require('fs');
var express = require('express');

var options = {
    key: fs.readFileSync('/etc/apache2/ssl/server.key'),
    cert: fs.readFileSync('/etc/apache2/ssl/server.crt'),
    requestCert: false,
    rejectUnauthorized: false
};


var app = express();

var server = https.createServer(options, app).listen(3000, function(){
    console.log("server started at port 3000");
});

This is working fine in my local machine as well as the server where I have deployed this. The one I have in server was bought from goDaddy but localhost had a self signed certificate.

However, every browser threw an error saying connection is not trusted, do you want to continue. After I click continue, it worked fine.

If anyone has ever bypassed this error with self signed certificate, please enlighten.

Permission denied when launch python script via bash

Do “chmod +x script”

Now try executing

Postgres manually alter sequence

setval('sequence_name', sequence_value)

How can I check if an element exists in the visible DOM?

The easiest solution is to check the baseURI property, which is set only when the element is inserted in the DOM, and it reverts to an empty string when it is removed.

_x000D_
_x000D_
var div = document.querySelector('div');_x000D_
_x000D_
// "div" is in the DOM, so should print a string_x000D_
console.log(div.baseURI);_x000D_
_x000D_
// Remove "div" from the DOM_x000D_
document.body.removeChild(div);_x000D_
_x000D_
// Should print an empty string_x000D_
console.log(div.baseURI);
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

How to make the overflow CSS property work with hidden as value

I did not get it. I had a similar problem but in my nav bar.

What I was doing is I kept my navBar code in this way: nav>div.navlinks>ul>li*3>a

In order to put hover effects on a I positioned a to relative and designed a::before and a::after then i put a gray background on before and after elements and kept hover effects in such way that as one hovers on <a> they will pop from outside a to fill <a>.

The problem is that the overflow hidden is not working on <a>.

What i discovered is if i removed <li> and simply put <a> without <ul> and <li> then it worked.

What may be the problem?

how do I insert a column at a specific column index in pandas?

You could try to extract columns as list, massage this as you want, and reindex your dataframe:

>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...

>>> df.reindex(columns=['n']+df.columns[:-1].tolist())

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

How to round down to nearest integer in MySQL?

Try this,

SELECT SUBSTR(12345.7344,1,LOCATE('.', 12345.7344) - 1)

or

SELECT FLOOR(12345.7344)

SQLFiddle Demo

TypeError: tuple indices must be integers, not str

The Problem is how you access row

Specifically row["waocs"] and row["pool_number"] of ocs[row["pool_number"]]=int(row["waocs"])

If you look up the official-documentation of fetchall() you find.

The method fetches all (or all remaining) rows of a query result set and returns a list of tuples.

Therefore you have to access the values of rows with row[__integer__] like row[0]

Disable Button in Angular 2

Change ng-disabled="!contractTypeValid" to [disabled]="!contractTypeValid"

Why I get 411 Length required error?

Hey i'm using Volley and was getting Server error 411, I added to the getHeaders method the following line :

params.put("Content-Length","0");

And it solved my issue

How to increase memory limit for PHP over 2GB?

You can also try this:

ini_set("max_execution_time", "-1");
ini_set("memory_limit", "-1");
ignore_user_abort(true);
set_time_limit(0);

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Encoding targetEncoding = Encoding.GetEncoding(1252);
// Encode a string into an array of bytes.
Byte[] encodedBytes = targetEncoding.GetBytes(utfString);
// Show the encoded byte values.
Console.WriteLine("Encoded bytes: " + BitConverter.ToString(encodedBytes));
// Decode the byte array back to a string.
String decodedString = Encoding.Default.GetString(encodedBytes);

Numbering rows within groups in a data frame

Use ave, ddply, dplyr or data.table:

df$num <- ave(df$val, df$cat, FUN = seq_along)

or:

library(plyr)
ddply(df, .(cat), mutate, id = seq_along(val))

or:

library(dplyr)
df %>% group_by(cat) %>% mutate(id = row_number())

or (the most memory efficient, as it assigns by reference within DT):

library(data.table)
DT <- data.table(df)

DT[, id := seq_len(.N), by = cat]
DT[, id := rowid(cat)]

Convert tabs to spaces in Notepad++

The easy way:

  1. Highlight a single tab area
  2. Copy
  3. Bring up find/replace
  4. Paste into the find field
  5. Click into the replace field and hit the space bar
  6. Then replace all.

SVG drop shadow using css3

Here's an example of applying dropshadow to some svg using the 'filter' property. If you want to control the opacity of the dropshadow have a look at this example. The slope attribute controls how much opacity to give to the dropshadow.

Relevant bits from the example:

<filter id="dropshadow" height="130%">
  <feGaussianBlur in="SourceAlpha" stdDeviation="3"/> <!-- stdDeviation is how much to blur -->
  <feOffset dx="2" dy="2" result="offsetblur"/> <!-- how much to offset -->
  <feComponentTransfer>
    <feFuncA type="linear" slope="0.5"/> <!-- slope is the opacity of the shadow -->
  </feComponentTransfer>
  <feMerge> 
    <feMergeNode/> <!-- this contains the offset blurred image -->
    <feMergeNode in="SourceGraphic"/> <!-- this contains the element that the filter is applied to -->
  </feMerge>
</filter>
<circle r="10" style="filter:url(#dropshadow)"/>

Box-shadow is defined to work on CSS boxes (read: rectangles), while svg is a bit more expressive than just rectangles. Read the SVG Primer to learn a bit more about what you can do with SVG filters.

Do I cast the result of malloc?

You do cast, because:

  • It makes your code more portable between C and C++, and as SO experience shows, a great many programmers claim they are writing in C when they are really writing in C++ (or C plus local compiler extensions).
  • Failing to do so can hide an error: note all the SO examples of confusing when to write type * versus type **.
  • The idea that it keeps you from noticing you failed to #include an appropriate header file misses the forest for the trees. It's the same as saying "don't worry about the fact you failed to ask the compiler to complain about not seeing prototypes -- that pesky stdlib.h is the REAL important thing to remember!"
  • It forces an extra cognitive cross-check. It puts the (alleged) desired type right next to the arithmetic you're doing for the raw size of that variable. I bet you could do an SO study that shows that malloc() bugs are caught much faster when there's a cast. As with assertions, annotations that reveal intent decrease bugs.
  • Repeating yourself in a way that the machine can check is often a great idea. In fact, that's what an assertion is, and this use of cast is an assertion. Assertions are still the most general technique we have for getting code correct, since Turing came up with the idea so many years ago.

Python creating a dictionary of lists

Your question has already been answered, but IIRC you can replace lines like:

if d.has_key(scope_item):

with:

if scope_item in d:

That is, d references d.keys() in that construction. Sometimes defaultdict isn't the best option (for example, if you want to execute multiple lines of code after the else associated with the above if), and I find the in syntax easier to read.

how to delete the content of text file without deleting itself

I don't believe you even have to write an empty string to the file.

PrintWriter pw = new PrintWriter("filepath.txt");
pw.close();

How can I get the error message for the mail() function?

As the others have said, there is no error tracking for send mail it return the boolean result of adding the mail to the outgoing queue. If you want to track true success failure try using SMTP with a mail library like Swift Mailer, Zend_Mail, or phpmailer.

Resize jqGrid when browser is resized?

If you:

  • have shrinkToFit: false (mean fixed width columns)
  • have autowidth: true
  • don't care about fluid height
  • have horizontal scrollbar

You can make grid with fluid width with following styles:

.ui-jqgrid {
  max-width: 100% !important;
  width: auto !important;
}

.ui-jqgrid-view,
.ui-jqgrid-hdiv,
.ui-jqgrid-bdiv {
   width: auto !important;
}

Here is a demo

Change background color on mouseover and remove it after mouseout

After lot of struggle finally got it working. ( Perfectly tested)

The below example will also support the fact that color of already clicked button should not be changes

JQuery Code

var flag = 0; // Flag is to check if you are hovering on already clicked item

$("a").click(function() {
    $('a').removeClass("YourColorClass");
    $(this).addClass("YourColorClass");
    flag=1;
}); 

$("a").mouseover(function() {
    if ($(this).hasClass("YourColorClass")) {
        flag=1;
    }
    else{
        $(this).addClass("YourColorClass");
    };
});

$("a").mouseout(function() {
    if (flag == 0) {
        $(this).removeClass("YourColorClass");
    }
    else{
        flag = 0;
    }
});

How to align absolutely positioned element to center?

Have you tried using?:

left:50%;
top:50%;
margin-left:-[half the width] /* As pointed out on the comments by Chetan Sastry */

Not sure if it'll work, but it's worth a try...

Minor edit: Added the margin-left part, as pointed out on the comments by Chetan...

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Alternatively to Martin's answer, you could also add the INTO part at the end of the query to make the query more readable:

SELECT Id, dateCreated FROM products INTO iId, dCreate

How to check if a character in a string is a digit or letter

You need to convert your string into character..

String character = in.next();
char myChar = character.charAt(0);

if (Character.isDigit(myChar)) {
   // print true
}

Check Character for other methods..

Casting a variable using a Type variable

I will never understand why you need up to 50 reputation to leave a comment but I just had to say that @Curt answer is exactly what I was looking and hopefully someone else.

In my example, I have an ActionFilterAttribute that I was using to update the values of a json patch document. I didn't what the T model was for the patch document to I had to serialize & deserialize it to a plain JsonPatchDocument, modify it, then because I had the type, serialize & deserialize it back to the type again.

Type originalType = //someType that gets passed in to my constructor.

var objectAsString = JsonConvert.SerializeObject(myObjectWithAGenericType);
var plainPatchDocument = JsonConvert.DeserializeObject<JsonPatchDocument>(objectAsString);

var plainPatchDocumentAsString= JsonConvert.SerializeObject(plainPatchDocument);
var modifiedObjectWithGenericType = JsonConvert.DeserializeObject(plainPatchDocumentAsString, originalType );

How do you setLayoutParams() for an ImageView?

Old thread but I had the same problem now. If anyone encounters this he'll probably find this answer:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

This will work only if you add the ImageView as a subView to a LinearLayout. If you add it to a RelativeLayout you will need to call:

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

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

Commit: Snapshot | Changeset | Version | History-record | 'Save-as' of a repository. Git repository = series (tree) of commits.

Local repository: repository on your computer.

Remote repository: repository on a server (Github).

git commit: Append a new commit (last commit + staged modifications) to the local repository. (Commits are stored in /.git)

git push, git pull: Sync the local repository with its associated remote repository. push - apply changes from local into remote, pull - apply changes from remote into local.

How do I get the path to the current script with Node.js?

Use the basename method of the path module:

var path = require('path');
var filename = path.basename(__filename);
console.log(filename);

Here is the documentation the above example is taken from.

As Dan pointed out, Node is working on ECMAScript modules with the "--experimental-modules" flag. Node 12 still supports __dirname and __filename as above.


If you are using the --experimental-modules flag, there is an alternative approach.

The alternative is to get the path to the current ES module:

const __filename = new URL(import.meta.url).pathname;

And for the directory containing the current module:

import path from 'path';

const __dirname = path.dirname(new URL(import.meta.url).pathname);

SQL to Query text in access with an apostrophe in it

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

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

This is not really a shortcut but just a quick access to the control menu: Alt-space E P

If you can use your mouse, right click on the cmd window works as paste when I tried it.

Copy all files with a certain extension from all subdirectories

--parents is copying the directory structure, so you should get rid of that.

The way you've written this, the find executes, and the output is put onto the command line such that cp can't distinguish between the spaces separating the filenames, and the spaces within the filename. It's better to do something like

$ find . -name \*.xls -exec cp {} newDir \;

in which cp is executed for each filename that find finds, and passed the filename correctly. Here's more info on this technique.

Instead of all the above, you could use zsh and simply type

$ cp **/*.xls target_directory

zsh can expand wildcards to include subdirectories and makes this sort of thing very easy.

Find Item in ObservableCollection without using a loop

ObservableCollection is a list so if you don't know the element position you have to look at each element until you find the expected one.

Possible optimization If your elements are sorted use a binary search to improve performances otherwise use a Dictionary as index.

Is there a destructor for Java?

If you're writing a Java Applet, you can override the Applet "destroy()" method. It is...

 * Called by the browser or applet viewer to inform
 * this applet that it is being reclaimed and that it should destroy
 * any resources that it has allocated. The stop() method
 * will always be called before destroy().

Obviously not what you want, but might be what other people are looking for.

Bash: infinite sleep (infinite blocking)

What about sending a SIGSTOP to itself?

This should pause the process until SIGCONT is received. Which is in your case: never.

kill -STOP "$$";
# grace time for signal delivery
sleep 60;

AngularJs event to call after content is loaded

According to documentation of $viewContentLoaded, it supposed to work

Emitted every time the ngView content is reloaded.

$viewContentLoaded event is emitted that means to receive this event you need a parent controller like

<div ng-controller="MainCtrl">
  <div ng-view></div>
</div>

From MainCtrl you can listen the event

  $scope.$on('$viewContentLoaded', function(){
    //Here your view content is fully loaded !!
  });

Check the Demo

Any way to generate ant build.xml file automatically from Eclipse?

I'm the one who donated the Ant export filter to Eclipse. I added the auto export feature, but only to my personal plug-in eclipse2ant, which I still maintain to coordinate bug fixes.

Unfortunately I have no time to merge it to the official Eclipse builds.

Choose File Dialog

I have implemented the Samsung File Selector Dialog, it provides the ability to open, save file, file extension filter, and create new directory in the same dialog I think it worth trying Here is the Link you have to log in to Samsung developer site to view the solution

What causes a SIGSEGV

Here is an example of SIGSEGV.

root@pierr-desktop:/opt/playGround# cat test.c
int main()
{
     int * p ;
     * p = 0x1234;
     return 0 ;
}
root@pierr-desktop:/opt/playGround# g++ -o test test.c  
root@pierr-desktop:/opt/playGround# ./test 
Segmentation fault

And here is the detail.

How to handle it?

  1. Avoid it as much as possible in the first place.

    Program defensively: use assert(), check for NULL pointer , check for buffer overflow.

    Use static analysis tools to examine your code.

    compile your code with -Werror -Wall.

    Has somebody review your code.

  2. When that actually happened.

    Examine you code carefully.

    Check what you have changed since the last time you code run successfully without crash.

    Hopefully, gdb will give you a call stack so that you know where the crash happened.


EDIT : sorry for a rush. It should be *p = 0x1234; instead of p = 0x1234;

How do I correctly use "Not Equal" in MS Access?

Like this

SELECT DISTINCT Table1.Column1
FROM Table1
WHERE NOT EXISTS( SELECT * FROM Table2
    WHERE Table1.Column1 = Table2.Column1  )

You want NOT EXISTS, not "Not Equal"


By the way, you rarely want to write a FROM clause like this:

FROM Table1, Table2

as this means "FROM all combinations of every row in Table1 with every row in Table2..." Usually that's a lot more result rows than you ever want to see. And in the rare case that you really do want to do that, the more accepted syntax is:

FROM Table1 CROSS JOIN Table2

Using an attribute of the current class instance as a default value for method's parameter

There is much more to it than you think. Consider the defaults to be static (=constant reference pointing to one object) and stored somewhere in the definition; evaluated at method definition time; as part of the class, not the instance. As they are constant, they cannot depend on self.

Here is an example. It is counterintuitive, but actually makes perfect sense:

def add(item, s=[]):
    s.append(item)
    print len(s)

add(1)     # 1
add(1)     # 2
add(1, []) # 1
add(1, []) # 1
add(1)     # 3

This will print 1 2 1 1 3.

Because it works the same way as

default_s=[]
def add(item, s=default_s):
    s.append(item)

Obviously, if you modify default_s, it retains these modifications.

There are various workarounds, including

def add(item, s=None):
    if not s: s = []
    s.append(item)

or you could do this:

def add(self, item, s=None):
    if not s: s = self.makeDefaultS()
    s.append(item)

Then the method makeDefaultS will have access to self.

Another variation:

import types
def add(item, s=lambda self:[]):
    if isinstance(s, types.FunctionType): s = s("example")
    s.append(item)

here the default value of s is a factory function.

You can combine all these techniques:

class Foo:
    import types
    def add(self, item, s=Foo.defaultFactory):
        if isinstance(s, types.FunctionType): s = s(self)
        s.append(item)

    def defaultFactory(self):
        """ Can be overridden in a subclass, too!"""
        return []

what is Ljava.lang.String;@

[ stands for single dimension array
Ljava.lang.String stands for the string class (L followed by class/interface name)

Few Examples:

  1. Class.forName("[D") -> Array of primitive double
  2. Class.forName("[[Ljava.lang.String") -> Two dimensional array of strings.

List of notations:
Element Type : Notation
boolean : Z
byte : B
char : C
class or interface : Lclassname
double : D
float : F
int : I
long : J
short : S

Defined Edges With CSS3 Filter Blur

Just some hint to that accepted answer, if you are using position absolute, negative margins will not work, but you can still set the top, bottom, left and right to a negative value, and make the parent element overflow hidden.

The answer about adding clip to position absolute image has a problem if you don't know the image size.

How to remove all leading zeroes in a string

Similar to another suggestion, except will not obliterate actual zero:

if (ltrim($str, '0') != '') {
    $str = ltrim($str, '0');
} else {
    $str = '0';
}

Or as was suggested (as of PHP 5.3), shorthand ternary operator can be used:

$str = ltrim($str, '0') ?: '0'; 

Get the difference between two dates both In Months and days in sql

is this what you've ment ?

select trunc(months_between(To_date('20120325', 'YYYYMMDD'),to_date('20120101','YYYYMMDD'))) months,
             round(To_date('20120325', 'YYYYMMDD')-add_months(to_date('20120101','YYYYMMDD'),
                           trunc(months_between(To_date('20120325', 'YYYYMMDD'),to_date('20120101','YYYYMMDD'))))) days
        from dual;

BigDecimal setScale and round

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

Collection was modified; enumeration operation may not execute

I had the same issue, and it was solved when I used a for loop instead of foreach.

// foreach (var item in itemsToBeLast)
for (int i = 0; i < itemsToBeLast.Count; i++)
{
    var matchingItem = itemsToBeLast.FirstOrDefault(item => item.Detach);

   if (matchingItem != null)
   {
      itemsToBeLast.Remove(matchingItem);
      continue;
   }
   allItems.Add(itemsToBeLast[i]);// (attachDetachItem);
}

Repeating a function every few seconds

There are lot of different Timers in the .NET BCL:

When to use which?

  • System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Windows.Forms.Timer (.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.
  • System.Web.UI.Timer (.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
  • System.Windows.Threading.DispatcherTimer, a timer that's integrated into the Dispatcher queue. This timer is processed with a specified priority at a specified time interval.

Source


Some of them needs explicit Start call to begin ticking (for example System.Timers, System.Windows.Forms). And an explicit Stop to finish ticking.

using TimersTimer = System.Timers.Timer;

static void Main(string[] args)
{
    var timer = new TimersTimer(1000);
    timer.Elapsed += (s, e) => Console.WriteLine("Beep");
    Thread.Sleep(1000); //1 second delay
    timer.Start();
    Console.ReadLine();
    timer.Stop();

}

While on the other hand there are some Timers (like: System.Threading) where you don't need explicit Start and Stop calls. (The provided delegate will run a background thread.) Your timer will tick until you or the runtime dispose it.

So, the following two versions will work in the same way:

using ThreadingTimer = System.Threading.Timer;

static void Main(string[] args)
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
    Console.ReadLine();
}
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
    StartTimer();
    Console.ReadLine();
}

static void StartTimer()
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}

But if your timer disposed then it will stop ticking obviously.

using ThreadingTimer = System.Threading.Timer; 

static void Main(string[] args)
{
    StartTimer();
    GC.Collect(0);
    Console.ReadLine();
}

static void StartTimer()
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}

Default interface methods are only supported starting with Android N

Update your build.gradle(Module:app) add compileOptions block and add JavaVersion.VERSION_1_8

apply plugin: 'com.android.application'

android {
    .................
    .........................
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

How to write a comment in a Razor view?

Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.

Server side Comments:

Razor .cshtml

Like so:

@* Comment goes here *@

.aspx
For those looking for the older .aspx view (and Asp.Net WebForms) server side comment syntax:

<%-- Comment goes here --%>

Client Side Comments

HTML Comment

<!-- Comment goes here -->

Javascript Comment

// One line Comment goes Here
/* Multiline comment
   goes here */

As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).

How do I read a text file of about 2 GB?

Instead of loading / reading the complete file, you could use a tool to split the text file in smaller chunks. If you're using Linux, you could just use the split command (see this stackoverflow thread). For Windows, there are several tools available like HJSplit (see this superuser thread).

Difference between WebStorm and PHPStorm

I use IntelliJ Idea, PHPStorm, and WebStorm. I thought WebStorm would be sufficient for PHP coding, but in reality it's great for editing but doesn't feel like it real-time-error-checks PHP as well as PHPStorm. This is just an observation, coming from a regular user of a JetBrains products.

If you're a student try taking advantage of the free license while attending school; it gives you a chance to explore different JetBrains IDE... Did I mention CLion? =]

XML serialization in Java?

JAXB is part of JDK standard edition version 1.6+. So it is FREE and no extra libraries to download and manage. A simple example can be found here

XStream seems to be dead. Last update was on Dec 6 2008. Simple seems as easy and simpler as JAXB but I could not find any licensing information to evaluate it for enterprise use.

Unable to merge dex

For me the issue was that 2 of the jars that I included in the project had the same classes in them.

For 1 of these jars I needed to exclude the classes:

jar {
    exclude('com/files/to/exclude/**')
}

Android: Expand/collapse animation

I see that this question became popular so I post my actual solution. The main advantage is that you don't have to know the expanded height to apply the animation and once the view is expanded, it adapts height if content changes. It works great for me.

public static void expand(final View v) {
    int matchParentMeasureSpec = View.MeasureSpec.makeMeasureSpec(((View) v.getParent()).getWidth(), View.MeasureSpec.EXACTLY);
    int wrapContentMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    v.measure(matchParentMeasureSpec, wrapContentMeasureSpec);
    final int targetHeight = v.getMeasuredHeight();

    // Older versions of android (pre API 21) cancel animations for views with a height of 0.
    v.getLayoutParams().height = 1;
    v.setVisibility(View.VISIBLE);
    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            v.getLayoutParams().height = interpolatedTime == 1
                    ? LayoutParams.WRAP_CONTENT
                    : (int)(targetHeight * interpolatedTime);
            v.requestLayout();
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // Expansion speed of 1dp/ms
    a.setDuration((int)(targetHeight / v.getContext().getResources().getDisplayMetrics().density));
    v.startAnimation(a);
}

public static void collapse(final View v) {
    final int initialHeight = v.getMeasuredHeight();

    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            if(interpolatedTime == 1){
                v.setVisibility(View.GONE);
            }else{
                v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
                v.requestLayout();
            }
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // Collapse speed of 1dp/ms
    a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density));
    v.startAnimation(a);
}

As mentioned by @Jefferson in the comments, you can obtain a smoother animation by changing the duration (and hence the speed) of the animation. Currently, it has been set at a speed of 1dp/ms

Auto Generate Database Diagram MySQL

Here is a tool that generates relational diagrams from MySQL (on Windows at the moment). I have used it on a database with 400 tables. If the diagram is too big for a single diagram, it gets broken down into smaller ones. So you will probably end up with multiple diagrams and you can navigate between them by right clicking. It is all explained in the link below. The tool is free (as in free beer), the author uses it himself on consulting assignments, and lets other people use it. http://www.scmlite.com/Quick%20overview

Get Value of a Edit Text field

I guess you will have to use this code when calling the "mEdit" your EditText object :

myActivity.this.mEdit.getText().toString()

Just make sure that the compiler know which EditText to call and use.

How to get current memory usage in android?

final long usedMemInMB=(runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long maxHeapSizeInMB=runtime.maxMemory() / 1048576L;
final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;

It is a strange code. It return MaxMemory - (totalMemory - freeMemory). If freeMemory equals 0, then the code will return MaxMemory - totalMemory, so it can more or equals 0. Why freeMemory not used?

Including a groovy script in another groovy

I think that the best choice is to organize utility things in form of groovy classes, add them to classpath and let main script refer to them via import keyword.

Example:

scripts/DbUtils.groovy

class DbUtils{
    def save(something){...}
}

scripts/script1.groovy:

import DbUtils
def dbUtils = new DbUtils()
def something = 'foobar'
dbUtils.save(something)

running script:

cd scripts
groovy -cp . script1.groovy

Why is there no Constant feature in Java?

const in C++ does not mean that a value is a constant.

const in C++ implies that the client of a contract undertakes not to alter its value.

Whether the value of a const expression changes becomes more evident if you are in an environment which supports thread based concurrency.

As Java was designed from the start to support thread and lock concurrency, it didn't add to confusion by overloading the term to have the semantics that final has.

eg:

#include <iostream>

int main ()
{
    volatile const int x = 42;

    std::cout << x << std::endl;

    *const_cast<int*>(&x) = 7;

    std::cout << x << std::endl;

    return 0;
}

outputs 42 then 7.

Although x marked as const, as a non-const alias is created, x is not a constant. Not every compiler requires volatile for this behaviour (though every compiler is permitted to inline the constant)

With more complicated systems you get const/non-const aliases without use of const_cast, so getting into the habit of thinking that const means something won't change becomes more and more dangerous. const merely means that your code can't change it without a cast, not that the value is constant.

Execute a terminal command from a Cocoa app

There is also good old POSIX system("echo -en '\007'");

Calculating a directory's size using Python?

It is handy:

import os
import stat

size = 0
path_ = ""
def calculate(path=os.environ["SYSTEMROOT"]):
    global size, path_
    size = 0
    path_ = path

    for x, y, z in os.walk(path):
        for i in z:
            size += os.path.getsize(x + os.sep + i)

def cevir(x):
    global path_
    print(path_, x, "Byte")
    print(path_, x/1024, "Kilobyte")
    print(path_, x/1048576, "Megabyte")
    print(path_, x/1073741824, "Gigabyte")

calculate("C:\Users\Jundullah\Desktop")
cevir(size)

Output:
C:\Users\Jundullah\Desktop 87874712211 Byte
C:\Users\Jundullah\Desktop 85815148.64355469 Kilobyte
C:\Users\Jundullah\Desktop 83803.85609722137 Megabyte
C:\Users\Jundullah\Desktop 81.83970321994275 Gigabyte

Combine two tables for one output

You'll need to use UNION to combine the results of two queries. In your case:

SELECT ChargeNum, CategoryID, SUM(Hours)
FROM KnownHours
GROUP BY ChargeNum, CategoryID
UNION ALL
SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
FROM UnknownHours
GROUP BY ChargeNum

Note - If you use UNION ALL as in above, it's no slower than running the two queries separately as it does no duplicate-checking.

removing html element styles via javascript

Use

particular_node.classList.remove("<name-of-class>")

For native javascript

Editor does not contain a main type in Eclipse

Problem is that your folder is not identified as a Source folder.

  1. Right click on the project folder -> Properties
  2. Choose 'Java Build Path'
  3. Click on 'Sources' tab on top
  4. Click on 'Add Folder' on the right panel
  5. Select your folders and apply

jQuery find parent form

see also jquery/js -- How do I select the parent form based on which submit button is clicked?

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

In my case issue was that space character was in the name of the source folder (Windows 10).

What is the difference between <html lang="en"> and <html lang="en-US">?

RFC 3066 gives the details of the allowed values (emphasis and links added):

All 2-letter subtags are interpreted as ISO 3166 alpha-2 country codes from [ISO 3166], or subsequently assigned by the ISO 3166 maintenance agency or governing standardization bodies, denoting the area to which this language variant relates.

I interpret that as meaning any valid (according to ISO 3166) 2-letter code is valid as a subtag. The RFC goes on to state:

Tags with second subtags of 3 to 8 letters may be registered with IANA, according to the rules in chapter 5 of this document.

By the way, that looks like a typo, since chapter 3 seems to relate to the the registration process, not chapter 5.

A quick search for the IANA registry reveals a very long list, of all the available language subtags. Here's one example from the list (which would be used as en-scouse):

Type: variant

Subtag: scouse

Description: Scouse

Added: 2006-09-18

Prefix: en

Comments: English Liverpudlian dialect known as 'Scouse'

There are all sorts of subtags available; a quick scroll has already revealed fr-1694acad (17th century French).


The usefulness of some of these (I would say the vast majority of these) tags, when it comes to documents designed for display in the browser, is limited. The W3C Internationalization specification simply states:

Browsers and other applications can use information about the language of content to deliver to users the most appropriate information, or to present information to users in the most appropriate way. The more content is tagged and tagged correctly, the more useful and pervasive such applications will become.

I'm struggling to find detailed information on how browsers behave when encountering different language tags, but they are most likely going to offer some benefit to those users who use a screen reader, which can use the tag to determine the language/dialect/accent in which to present the content.

Redirect all to index.php using htaccess

After doing that don't forget to change your href in, <a href="{the chosen redirected name}"> home</a>

Example:

.htaccess file

RewriteEngine On

RewriteRule ^about/$ /about.php

PHP file:

<a href="about/"> about</a>

Why can't I use Docker CMD multiple times to run multiple services?

While I respect the answer from qkrijger explaining how you can work around this issue I think there is a lot more we can learn about what's going on here ...

To actually answer your question of "why" ... I think it would for helpful for you to understand how the docker stop command works and that all processes should be shutdown cleanly to prevent problems when you try to restart them (file corruption etc).

Problem: What if docker did start SSH from it's command and started RabbitMQ from your Docker file? "The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container." Which process is docker tracking as PID 1 that will get the SIGTERM? Will it be SSH or Rabbit?? "According to the Unix process model, the init process -- PID 1 -- inherits all orphaned child processes and must reap them. Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with zombie processes over time."

Answer: Docker simply takes that last CMD as the one that will get launched as the root process with PID 1 and get the SIGTERM from docker stop.

Suggested solution: You should use (or create) a base image specifically made for running more than one service, such as phusion/baseimage

It should be important to note that tini exists exactly for this reason, and as of Docker 1.13 and up, tini is officially part of Docker, which tells us that running more than one process in Docker IS VALID .. so even if someone claims to be more skilled regarding Docker, and insists that you absurd for thinking of doing this, know that you are not. There are perfectly valid situations for doing so.

Good to know:

How do I space out the child elements of a StackPanel?

sometimes you need to set Padding, not Margin to make space between items smaller than default

How to compile Tensorflow with SSE4.2 and AVX instructions?

To compile TensorFlow with SSE4.2 and AVX, you can use directly

bazel build --config=mkl --config="opt" --copt="-march=broadwell" --copt="-O3" //tensorflow/tools/pip_package:build_pip_package

Source: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/docker/Dockerfile.devel-cpu-mkl

Java multiline string

In the IntelliJ IDE you just need to type:

""

Then position your cursor inside the quotation marks and paste your string. The IDE will expand it into multiple concatenated lines.

Get cookie by name

One approach, which avoids iterating over an array, would be:

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}

Walkthrough

Splitting a string by token will produce either, an array with one string (same value), in case token does not exist in a string, or an array with two strings , in case token is found in a string .

The first (left) element is string of what was before the token, and the second one (right) is what is string of what was after the token.

(NOTE: in case string starts with a token, first element is an empty string)

Considering that cookies are stored as follows:

"{name}={value}; {name}={value}; ..."

in order to retrieve specific cookie value, we just need to get string that is after "; {name}=" and before next ";". Before we do any processing, we prepend the cookies string with "; ", so that every cookie name, including the first one, is enclosed with "; " and "=":

"; {name}={value}; {name}={value}; ..."

Now, we can first split by "; {name}=", and if token is found in a cookie string (i.e. we have two elements), we will end up with second element being a string that begins with our cookie value. Then we pull that out from an array (i.e. pop), and repeat the same process, but now with ";" as a token, but this time pulling out the left string (i.e. shift) to get the actual token value.

How do I execute a program using Maven?

With the global configuration that you have defined for the exec-maven-plugin:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4.0</version>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

invoking mvn exec:java on the command line will invoke the plugin which is configured to execute the class org.dhappy.test.NeoTraverse.

So, to trigger the plugin from the command line, just run:

mvn exec:java

Now, if you want to execute the exec:java goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase to which you want to bind the goal in the execution element:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <id>my-execution</id>
      <phase>package</phase>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

With this example, your class would be executed during the package phase. This is just an example, adapt it to suit your needs. Works also with plugin version 1.1.

How to find if a native DLL file is compiled as x64 or x86?

Open the dll with a hex editor, like HxD

If the there is a "dt" on the 9th line it is 64bit.

If there is an "L." on the 9th line it is 32bit.

Bash checking if string does not contain other string

Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.

fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf 
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"

format a number with commas and decimals in C# (asp.net MVC3)

Maybe you simply want the standard format string "N", as in

number.ToString("N")

It will use thousand separators, and a fixed number of fractional decimals. The symbol for thousands separators and the symbol for the decimal point depend on the format provider (typically CultureInfo) you use, as does the number of decimals (which will normally by 2, as you require).

If the format provider specifies a different number of decimals, and if you don't want to change the format provider, you can give the number of decimals after the N, as in .ToString("N2").

Edit: The sizes of the groups between the commas are governed by the

CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes

array, given that you don't specify a special format provider.

LINQ extension methods - Any() vs. Where() vs. Exists()

Any() returns true if any of the elements in a collection meet your predicate's criteria.

Where() returns an enumerable of all elements in a collection that meet your predicate's criteria.

Exists() does the same thing as any except it's just an older implementation that was there on the IList back before Linq.

How to kill a running SELECT statement

This is what I use. I do this first query to find the sessions and the users:

select s.sid, s.serial#, p.spid, s.username, s.schemaname
     , s.program, s.terminal, s.osuser
  from v$session s
  join v$process p
    on s.paddr = p.addr
 where s.type != 'BACKGROUND';

This will let me know if there are multiple sessions for the same user. Then I usually check to verify if a session is blocking the database.

SELECT SID, SQL_ID, USERNAME, BLOCKING_SESSION, COMMAND, MODULE, STATUS FROM v$session WHERE BLOCKING_SESSION IS NOT NULL;  

Then I run an ALTER statement to kill a specific session in this format:

ALTER SYSTEM KILL SESSION 'sid,serial#'; 

For example:

ALTER SYSTEM KILL SESSION '314, 2643';

Python "SyntaxError: Non-ASCII character '\xe2' in file"

\xe2 is the '-' character, it appears in some copy and paste it uses a different equal looking '-' that causes encoding errors. Replace the '-'(from copy paste) with the correct '-' (from you keyboard button).

How to use SQL LIKE condition with multiple values in PostgreSQL?

You can use regular expression operator (~), separated by (|) as described in Pattern Matching

select column_a from table where column_a ~* 'aaa|bbb|ccc'

C#: Looping through lines of multiline string

I know this has been answered, but I'd like to add my own answer:

using (var reader = new StringReader(multiLineString))
{
    for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
    {
        // Do something with the line
    }
}

How to get a variable name as a string in PHP?

I really fail to see the use case... If you will type print_var_name($foobar) what's so hard (and different) about typing print("foobar") instead?

Because even if you were to use this in a function, you'd get the local name of the variable...

In any case, here's the reflection manual in case there's something you need in there.

How can you customize the numbers in an ordered list?

Quick and dirt alternative solution. You can use a tabulation character along with preformatted text. Here's a possibility:

<style type="text/css">
ol {
    list-style-position: inside;
}
li:first-letter {
    white-space: pre;
}
</style>

and your html:

<ol>
<li>    an item</li>
<li>    another item</li>
...
</ol>

Note that the space between the li tag and the beggining of the text is a tabulation character (what you get when you press the tab key inside notepad).

If you need to support older browsers, you can do this instead:

<style type="text/css">
ol {
    list-style-position: inside;
}
</style>

<ol>
    <li><pre>   </pre>an item</li>
    <li><pre>   </pre>another item</li>
    ...
</ol>

Add new column in Pandas DataFrame Python

You just do an opposite comparison. if Col2 <= 1. This will return a boolean Series with False values for those greater than 1 and True values for the other. If you convert it to an int64 dtype, True becomes 1 and False become 0,

df['Col3'] = (df['Col2'] <= 1).astype(int)

If you want a more general solution, where you can assign any number to Col3 depending on the value of Col2 you should do something like:

df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)

Or:

df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55

Excel VBA If cell.Value =... then

You can determine if as certain word is found in a cell by using

If InStr(cell.Value, "Word1") > 0 Then

If Word1 is found in the string the InStr() function will return the location of the first character of Word1 in the string.

How to export DataTable to Excel

Try simple code, to convert DataTable to excel file as csv:

var lines = new List<string>();

string[] columnNames = dataTable.Columns
    .Cast<DataColumn>()
    .Select(column => column.ColumnName)
    .ToArray();

var header = string.Join(",", columnNames.Select(name => $"\"{name}\""));
lines.Add(header);

var valueLines = dataTable.AsEnumerable()
    .Select(row => string.Join(",", row.ItemArray.Select(val => $"\"{val}\"")));

lines.AddRange(valueLines);

File.WriteAllLines("excel.csv", lines);

This will write a new file excel.csv into the current working directory which is generally either where the .exe is or where you launch it from.

Changing the JFrame title

I strongly recommend you learn how to use layout managers to get the layout you want to see. null layouts are fragile, and cause no end of trouble.

Try this source & check the comments.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class VolumeCalculator extends JFrame implements ActionListener {
    private JTabbedPane jtabbedPane;
    private JPanel options;
    JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
            hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
            myTitle;
    JTextArea labelTubStatus;

    public VolumeCalculator(){
        setSize(400, 250);
        setVisible(true);
        setSize(400, 250);
        setVisible(true);
        setTitle("Volume Calculator");
        setSize(300, 200);
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BorderLayout());
        getContentPane().add(topPanel);

        createOptions();

        jtabbedPane = new JTabbedPane();

        jtabbedPane.addTab("Options", options);

        topPanel.add(jtabbedPane, BorderLayout.CENTER);
    }
    /* CREATE OPTIONS */

    public void createOptions(){
        options = new JPanel();
        //options.setLayout(null);
        JLabel labelOptions = new JLabel("Change Company Name:");
        labelOptions.setBounds(120, 10, 150, 20);
        options.add(labelOptions);
        JTextField newTitle = new JTextField("Some Title");
        //newTitle.setBounds(80, 40, 225, 20);    
        options.add(newTitle);
        myTitle = new JTextField(20);
        // myTitle WAS NEVER ADDED to the GUI!
        options.add(myTitle);
        //myTitle.setBounds(80, 40, 225, 20);
        //myTitle.add(labelOptions);
        JButton newName = new JButton("Set New Name");
        //newName.setBounds(60, 80, 150, 20);
        newName.addActionListener(this);
        options.add(newName);
        JButton Exit = new JButton("Exit");
        //Exit.setBounds(250, 80, 80, 20);
        Exit.addActionListener(this);
        options.add(Exit);
    }

    public void actionPerformed(ActionEvent event){
        JButton button = (JButton) event.getSource();
        String buttonLabel = button.getText();
        if ("Exit".equalsIgnoreCase(buttonLabel)){
            Exit_pressed();
            return;
        }
        if ("Set New Name".equalsIgnoreCase(buttonLabel)){
            New_Name();
            return;
        }
    }

    private void Exit_pressed(){
        System.exit(0);
    }

    private void New_Name(){
        System.out.println("'" + myTitle.getText() + "'");
        this.setTitle(myTitle.getText());
    }

    private void Options(){
    }

    public static void main(String[] args){
        JFrame frame = new VolumeCalculator();
        frame.pack();
        frame.setSize(380, 350);
        frame.setVisible(true);
    }
}

How to set Java environment path in Ubuntu

Java is typically installed in /usr/java locate the version you have and then do the following:

Assuming you are using bash (if you are just starting off, i recommend bash over other shells) you can simply type in bash to start it.

Edit your ~/.bashrc file and add the paths as follows:

for eg. vi ~/.bashrc

insert following lines:

export JAVA_HOME=/usr/java/<your version of java>
export PATH=${PATH}:${JAVA_HOME}/bin

after you save the changes, exit and restart your bash or just type in bash to start a new shell

Type in export to ensure paths are right.

Type in java -version to ensure Java is accessible.

Calculate Age in MySQL (InnoDb)

select floor(datediff (now(), birthday)/365) as age

Python Pandas counting and summing specific conditions

You can first make a conditional selection, and sum up the results of the selection using the sum function.

>> df = pd.DataFrame({'a': [1, 2, 3]})
>> df[df.a > 1].sum()   
a    5
dtype: int64

Having more than one condition:

>> df[(df.a > 1) & (df.a < 3)].sum()
a    2
dtype: int64

Overlaying a DIV On Top Of HTML 5 Video

Here is a stripped down example, using as little HTML markup as possible.

The Basics

  • The overlay is provided by the :before pseudo element on the .content container.

  • No z-index is required, :before is naturally layered over the video element.

  • The .content container is position: relative so that the position: absolute overlay is positioned in relation to it.

  • The overlay is stretched to cover the entire .content div width with left / right / bottom and left set to 0.

  • The width of the video is controlled by the width of its container with width: 100%

The Demo

_x000D_
_x000D_
.content {
  position: relative;
  width: 500px;
  margin: 0 auto;
  padding: 20px;
}
.content video {
  width: 100%;
  display: block;
}
.content:before {
  content: '';
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 5px;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
_x000D_
<div class="content">
  <video id="player" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/1/18/Big_Buck_Bunny_Trailer_1080p.ogv/Big_Buck_Bunny_Trailer_1080p.ogv.360p.vp9.webm" autoplay loop muted></video>
</div>
_x000D_
_x000D_
_x000D_

Convert string to decimal number with 2 decimal places in Java

I just want to be sure that the float number will also have 2 decimal places after converting that string.

You can't, because floating point numbers don't have decimal places. They have binary places, which aren't commensurate with decimal places.

If you want decimal places, use a decimal radix.

Enter key press in C#

Try this:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
        switch (e.Key.ToString())
        {
                case "Return":
                        MessageBox.Show(" Enter pressed ");
                        break;
         }
}

What is the volatile keyword useful for?

You'll need to use 'volatile' keyword, or 'synchronized' and any other concurrency control tools and techniques you might have at your disposal if you are developing a multithreaded application. Example of such application is desktop apps.

If you are developing an application that would be deployed to application server (Tomcat, JBoss AS, Glassfish, etc) you don't have to handle concurrency control yourself as it already addressed by the application server. In fact, if I remembered correctly the Java EE standard prohibit any concurrency control in servlets and EJBs, since it is part of the 'infrastructure' layer which you supposed to be freed from handling it. You only do concurrency control in such app if you're implementing singleton objects. This even already addressed if you knit your components using frameworkd like Spring.

So, in most cases of Java development where the application is a web application and using IoC framework like Spring or EJB, you wouldn't need to use 'volatile'.

What does -Xmn jvm option stands for

From GC Performance Tuning training documents of Oracle:

-Xmn[size]: Size of young generation heap space.

Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.

In short, it sets the NewSize and MaxNewSize values of New generation to the same value.

PHP $_FILES['file']['tmp_name']: How to preserve filename and extension?

If you wanna get the uploaded file name, use $_FILES["file"]["name"]

But If you wanna read the uploaded file you should use $_FILES["file"]["tmp_name"], because tmp_name is a temporary copy of your uploaded file and it's easier than using

$_FILES["file"]["name"] // This name includes a file path, which makes file read process more complex

Oracle Convert Seconds to Hours:Minutes:Seconds

If you have a variable containing f.e. 1 minute(in seconds), you can add it to the systimestamp then use to_char to select the different time parts from it.

select to_char(systimestamp+60/(24*60*60), 'yyyy.mm.dd HH24:mi:ss') from dual

Exception: "URI formats are not supported"

string uriPath =
    "file:\\C:\\Users\\john\\documents\\visual studio 2010\\Projects\\proj";
string localPath = new Uri(uriPath).LocalPath;

PHP Fatal error: Cannot redeclare class

This error might also occur if you define the __construct method more than once.

SQLAlchemy equivalent to SQL "LIKE" statement

If you use native sql, you can refer to my code, otherwise just ignore my answer.

SELECT * FROM table WHERE tags LIKE "%banana%";
from sqlalchemy import text

bar_tags = "banana"

# '%' attention to spaces
query_sql = """SELECT * FROM table WHERE tags LIKE '%' :bar_tags '%'"""

# db is sqlalchemy session object
tags_res_list = db.execute(text(query_sql), {"bar_tags": bar_tags}).fetchall()

How do you get the logical xor of two variables in Python?

Rewarding thread:

Anoder idea... Just you try the (may be) pythonic expression «is not» in order to get behavior of logical «xor»

The truth table would be:

>>> True is not True
False
>>> True is not False
True
>>> False is not True
True
>>> False is not False
False
>>>

And for your example string:

>>> "abc" is not  ""
True
>>> 'abc' is not 'abc' 
False
>>> 'abc' is not '' 
True
>>> '' is not 'abc' 
True
>>> '' is not '' 
False
>>> 

However; as they indicated above, it depends of the actual behavior you want to pull out about any couple strings, because strings aren't boleans... and even more: if you «Dive Into Python» you will find «The Peculiar Nature of "and" and "or"» http://www.diveintopython.net/power_of_introspection/and_or.html

Sorry my writed English, it's not my born language.

Regards.

CardView Corner Radius

You can use this drawable xml and set as background to cardview :

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#ffffffff"/>

    <stroke android:width="1dp"
        android:color="#ff000000"
        />

    <padding android:left="1dp"
        android:top="1dp"
        android:right="1dp"
        android:bottom="1dp"
        />

    <corners 
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/>
</shape>

How to add "active" class to wp_nav_menu() current menu item (simple way)

In addition to previous answers, if your menu items are Categories and you want to highlight them when navigating through posts, check also for current-post-ancestor:

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

function special_nav_class ($classes, $item) {
    if (in_array('current-post-ancestor', $classes) || in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
        $classes[] = 'active ';
    }
    return $classes;
}

Delete certain lines in a txt file via a batch file

Use the following:

type file.txt | findstr /v ERROR | findstr /v REFERENCE

This has the advantage of using standard tools in the Windows OS, rather than having to find and install sed/awk/perl and such.

See the following transcript for it in operation:

C:\>type file.txt
Good Line of data
bad line of C:\Directory\ERROR\myFile.dll
Another good line of data
bad line: REFERENCE
Good line

C:\>type file.txt | findstr /v ERROR | findstr /v REFERENCE
Good Line of data
Another good line of data
Good line

Bootstrap DatePicker, how to set the start date for tomorrow?

1) use for tommorow's date startDate: '+1d'

2) use for yesterday's date startDate: '-1d'

3) use for today's date startDate: new Date()

Create a new TextView programmatically then display it below another TextView

You're not assigning any id to the text view, but you're using tv.getId() to pass it to the addRule method as a parameter. Try to set a unique id via tv.setId(int).

You could also use the LinearLayout with vertical orientation, that might be easier actually. I prefer LinearLayout over RelativeLayouts if not necessary otherwise.

How to get HTTP response code for a URL in Java?

HttpURLConnection:

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();

This is by no means a robust example; you'll need to handle IOExceptions and whatnot. But it should get you started.

If you need something with more capability, check out HttpClient.

MySQL Update Column +1?

update TABLENAME
set COLUMNNAME = COLUMNNAME + 1
where id = 'YOURID'

Solving sslv3 alert handshake failure when trying to use a client certificate

What SSL private key should be sent along with the client certificate?

None of them :)

One of the appealing things about client certificates is it does not do dumb things, like transmit a secret (like a password), in the plain text to a server (HTTP basic_auth). The password is still used to unlock the key for the client certificate, its just not used directly to during exchange or tp authenticate the client.

Instead, the client chooses a temporary, random key for that session. The client then signs the temporary, random key with his cert and sends it to the server (some hand waiving). If a bad guy intercepts anything, its random so it can't be used in the future. It can't even be used for a second run of the protocol with the server because the server will select a new, random value, too.


Fails with: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure

Use TLS 1.0 and above; and use Server Name Indication.

You have not provided any code, so its not clear to me how to tell you what to do. Instead, here's the OpenSSL command line to test it:

openssl s_client -connect www.example.com:443 -tls1 -servername www.example.com \
    -cert mycert.pem -key mykey.pem -CAfile <certificate-authority-for-service>.pem

You can also use -CAfile to avoid the “verify error:num=20”. See, for example, “verify error:num=20” when connecting to gateway.sandbox.push.apple.com.

Merge Cell values with PHPExcel - PHP

$this->excel->setActiveSheetIndex(0)->mergeCells("A".($p).":B".($p)); for dynamic merging of cells

Best tool for inspecting PDF files?

PDFXplorer from O2 Solutions does an outstanding job of displaying the internals.

http://www.o2sol.com/pdfxplorer/overview.htm

(Free, distracting banner at the bottom).

Count elements with jQuery

try this:

var count_element = $('.element').length

Launch Failed. Binary not found. CDT on Eclipse Helios

I faced the same problem while installing Eclipse for c/c++ applications .I downloaded Mingw GCC ,put its bin folder in your path ,used it in toolchains while making new C++ project in Eclipse and build which solved my problem. Referred to this video

Why shouldn't I use "Hungarian Notation"?

For years I used Hungarian notation in my programming. Other than some visual clutter and the task of changing the prefix when I changed the data type, no one could convince me otherwise. Until recently--when I had to combine existing C# and VB.NET assemblies in the same solution.

The result: I had to pass a "fltSomeVariable" to a "sngSomeVariable" method parameter. Even as someone who programs in both C# and VB.NET, it caught me off guard and made me pause for a moment. (C# and VB.NET sometimes use different names to represent the same data type--float and single, for example.)

Now consider this: what if you create a COM component that's callable from many languages? The VB.NET and C# "conversion" was easy for a .NET programmer. But what about someone that develops in C++ or Java? Does "dwSomeVariable" mean anything to a .NET developer not familiar with C++?

Multiple aggregations of the same column using pandas GroupBy.agg()

You can simply pass the functions as a list:

In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:         
           mean       sum
dummy                    
1      0.036901  0.369012

or as a dictionary:

In [21]: df.groupby('dummy').agg({'returns':
                                  {'Mean': np.mean, 'Sum': np.sum}})
Out[21]: 
        returns          
           Mean       Sum
dummy                    
1      0.036901  0.369012

tmux set -g mouse-mode on doesn't work

As @Graham42 noted, mouse option has changed in version 2.1. Scrolling now requires for you to enter copy mode first. To enable scrolling almost identical to how it was before 2.1 add following to your .tmux.conf.

set-option -g mouse on

# make scrolling with wheels work
bind -n WheelUpPane if-shell -F -t = "#{mouse_any_flag}" "send-keys -M" "if -Ft= '#{pane_in_mode}' 'send-keys -M' 'select-pane -t=; copy-mode -e; send-keys -M'"
bind -n WheelDownPane select-pane -t= \; send-keys -M

This will enable scrolling on hover over a pane and you will be able to scroll that pane line by line.

Source: https://groups.google.com/d/msg/tmux-users/TRwPgEOVqho/Ck_oth_SDgAJ

Can't load IA 32-bit .dll on a AMD 64-bit platform

I had the same issue with a Java application using tibco dll originally intended to run on Win XP. To get it to work on Windows 7, I made the application point to 32-bit JRE. Waiting to see if there is another solution.

How to access my localhost from another PC in LAN?

You have to edit httpd.conf and find this line: Listen 127.0.0.1:80

Then write down your desired IP you set for LAN. Don't use automatic IP.
e.g.: Listen 192.168.137.1:80

I used 192.167.137.1 as my LAN IP of Windows 7. Restart Apache and enjoy sharing.

Get $_POST from multiple checkboxes

you have to name your checkboxes accordingly:

<input type="checkbox" name="check_list[]" value="…" />

you can then access all checked checkboxes with

// loop over checked checkboxes
foreach($_POST['check_list'] as $checkbox) {
   // do something
}

ps. make sure to properly escape your output (htmlspecialchars())

Is there a "not equal" operator in Python?

You can use "is not" for "not equal" or "!=". Please see the example below:

a = 2
if a == 2:
   print("true")
else:
   print("false")

The above code will print "true" as a = 2 assigned before the "if" condition. Now please see the code below for "not equal"

a = 2
if a is not 3:
   print("not equal")
else:
   print("equal")

The above code will print "not equal" as a = 2 as assigned earlier.

How do I use Comparator to define a custom sort order?

I will do something like this:

List<String> order = List.of("Red", "Green", "Magenta", "Silver");

Comparator.comparing(Car::getColor(), Comparator.comparingInt(c -> order.indexOf(c)))

All credits go to @Sean Patrick Floyd :)

How would one write object-oriented code in C?

Of course, it just won't be as pretty as using a language with built-in support. I've even written "object-oriented assembler".

Having links relative to root?

If you are creating the URL from the server side of an ASP.NET application, and deploying your website to a virtual directory (e.g. app2) in your website i.e. http://www.yourwebsite.com/app2/

then just insert

<base href="~/" />

just after the title tag.

so whenever you use root relative e.g.

<a href="/Accounts/Login"/> 

would resolve to "http://www.yourwebsite.com/app2/Accounts/Login"

This way you can always point to your files relatively-absolutely ;)

To me this is the most flexible solution.

malloc for struct and pointer in C

No, you're not allocating memory for y->x twice.

Instead, you're allocating memory for the structure (which includes a pointer) plus something for that pointer to point to.

Think of it this way:

         1          2
        +-----+    +------+
y------>|  x------>|  *x  |
        |  n  |    +------+
        +-----+

So you actually need the two allocations (1 and 2) to store everything.

Additionally, your type should be struct Vector *y since it's a pointer, and you should never cast the return value from malloc in C since it can hide certain problems you don't want hidden - C is perfectly capable of implicitly converting the void* return value to any other pointer.

And, of course, you probably want to encapsulate the creation of these vectors to make management of them easier, such as with:

struct Vector {
    double *data;    // no place for x and n in readable code :-)
    size_t size;
};

struct Vector *newVector (size_t sz) {
    // Try to allocate vector structure.

    struct Vector *retVal = malloc (sizeof (struct Vector));
    if (retVal == NULL)
        return NULL;

    // Try to allocate vector data, free structure if fail.

    retVal->data = malloc (sz * sizeof (double));
    if (retVal->data == NULL) {
        free (retVal);
        return NULL;
    }

    // Set size and return.

    retVal->size = sz;
    return retVal;
}

void delVector (struct Vector *vector) {
    // Can safely assume vector is NULL or fully built.

    if (vector != NULL) {
        free (vector->data);
        free (vector);
    }
}

By encapsulating the creation like that, you ensure that vectors are either fully built or not built at all - there's no chance of them being half-built. It also allows you to totally change the underlying data structures in future without affecting clients (for example, if you wanted to make them sparse arrays to trade off space for speed).

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

How to convert a string to character array in c (or) how to extract a single char form string?

In C, there's no (real, distinct type of) strings. Every C "string" is an array of chars, zero terminated.

Therefore, to extract a character c at index i from string your_string, just use

char c = your_string[i];

Index is base 0 (first character is your_string[0], second is your_string[1]...).

How to convert Double to int directly?

All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.

You can use Math.round(double) function or simply do :

(int)(yourDoubleValue + 0.5d)

Add missing dates to pandas dataframe

A quicker workaround is to use .asfreq(). This doesn't require creation of a new index to call within .reindex().

# "broken" (staggered) dates
dates = pd.Index([pd.Timestamp('2012-05-01'), 
                  pd.Timestamp('2012-05-04'), 
                  pd.Timestamp('2012-05-06')])
s = pd.Series([1, 2, 3], dates)

print(s.asfreq('D'))
2012-05-01    1.0
2012-05-02    NaN
2012-05-03    NaN
2012-05-04    2.0
2012-05-05    NaN
2012-05-06    3.0
Freq: D, dtype: float64

Disable browser cache for entire ASP.NET website

I implemented all the previous answers and still had one view that did not work correctly.

It turned out the name of the view I was having the problem with was named 'Recent'. Apparently this confused the Internet Explorer browser.

After I changed the view name (in the controller) to a different name (I chose to 'Recent5'), the solutions above started to work.

What GRANT USAGE ON SCHEMA exactly do?

GRANTs on different objects are separate. GRANTing on a database doesn't GRANT rights to the schema within. Similiarly, GRANTing on a schema doesn't grant rights on the tables within.

If you have rights to SELECT from a table, but not the right to see it in the schema that contains it then you can't access the table.

The rights tests are done in order:

Do you have `USAGE` on the schema? 
    No:  Reject access. 
    Yes: Do you also have the appropriate rights on the table? 
        No:  Reject access. 
        Yes: Check column privileges.

Your confusion may arise from the fact that the public schema has a default GRANT of all rights to the role public, which every user/group is a member of. So everyone already has usage on that schema.

The phrase:

(assuming that the objects' own privilege requirements are also met)

Is saying that you must have USAGE on a schema to use objects within it, but having USAGE on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.

It's like a directory tree. If you create a directory somedir with file somefile within it then set it so that only your own user can access the directory or the file (mode rwx------ on the dir, mode rw------- on the file) then nobody else can list the directory to see that the file exists.

If you were to grant world-read rights on the file (mode rw-r--r--) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.

If you instead set rwx-r-xr-x on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.

You need to set both permissions for people to actually be able to view the file.

Same thing in Pg. You need both schema USAGE rights and object rights to perform an action on an object, like SELECT from a table.

(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECTing from pg_class directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)

Boolean vs tinyint(1) for boolean values in MySQL

use enum its the easy and fastest

i will not recommend enum or tinyint(1) as bit(1) needs only 1 bit for storing boolean value while tinyint(1) needs 8 bits.

ref

TINYINT vs ENUM(0, 1) for boolean values in MySQL

How to specify a port to run a create-react-app based project?

Create a file with name .env in the main directory besidespackage.json and set PORT variable to desired port number.

For example:

.env

PORT=4200

You can find the documentation for this action here: https://create-react-app.dev/docs/advanced-configuration

Twitter bootstrap collapse: change display of toggle button

I liked the CSS-only solution from PSL, but in my case I needed to include some HTML in the button, and the content CSS property is showing the raw HTML with tags in this case.

In case that could help someone else, I've forked his fiddle to cover my use case: http://jsfiddle.net/brunoalla/99j11h40/2/

HTML:

<div class="row-fluid summary">
    <div class="span11">
        <h2>MyHeading</h2>  
    </div>
    <div class="span1">
        <button class="btn btn-success collapsed" data-toggle="collapse" data-target="#intro">
            <span class="show-ctrl">
                <i class="fa fa-chevron-down"></i> Expand
            </span>
            <span class="hide-ctrl">
                <i class="fa fa-chevron-up"></i> Collapse
            </span>            
        </button>
    </div>
</div>
<div class="row-fluid summary">
    <div id="intro" class="collapse"> 
        Here comes the text...
    </div>
</div>

CSS:

button.btn .show-ctrl{
    display: none;
}
button.btn .hide-ctrl{
    display: block;
}
button.btn.collapsed .show-ctrl{
    display: block;
}
button.btn.collapsed .hide-ctrl{
    display: none;
}

Better naming in Tuple classes than "Item1", "Item2"

You Can write a class that contains the Tuple.

You need to override the Equals and GetHashCode functions

and the == and != operators.

class Program
{
    public class MyTuple
    {
        private Tuple<int, int> t;

        public MyTuple(int a, int b)
        {
            t = new Tuple<int, int>(a, b);
        }

        public int A
        {
            get
            {
                return t.Item1;
            }
        }

        public int B
        {
            get
            {
                return t.Item2;
            }
        }

        public override bool Equals(object obj)
        {
            return t.Equals(((MyTuple)obj).t);
        }

        public override int GetHashCode()
        {
            return t.GetHashCode();
        }

        public static bool operator ==(MyTuple m1, MyTuple m2)
        {
            return m1.Equals(m2);
        }

        public static bool operator !=(MyTuple m1, MyTuple m2)
        {
            return !m1.Equals(m2);
        }
    }

    static void Main(string[] args)
    {
        var v1 = new MyTuple(1, 2);
        var v2 = new MyTuple(1, 2);

        Console.WriteLine(v1 == v2);

        Dictionary<MyTuple, int> d = new Dictionary<MyTuple, int>();
        d.Add(v1, 1);

        Console.WriteLine(d.ContainsKey(v2));
    }
}

will return:

True

True

Can I add extension methods to an existing static class?

I tried to do this with System.Environment back when I was learning extension methods and was not successful. The reason is, as others mention, because extension methods require an instance of the class.

Get the second highest value in a MySQL table

SELECT MAX(salary) salary
FROM tbl
WHERE salary <
  (SELECT MAX(salary)
   FROM tbl);

Find integer index of rows with NaN in pandas dataframe

And just in case, if you want to find the coordinates of 'nan' for all the columns instead (supposing they are all numericals), here you go:

df = pd.DataFrame([[0,1,3,4,np.nan,2],[3,5,6,np.nan,3,3]])

df
   0  1  2    3    4  5
0  0  1  3  4.0  NaN  2
1  3  5  6  NaN  3.0  3

np.where(np.asanyarray(np.isnan(df)))
(array([0, 1]), array([4, 3]))

Dynamic Height Issue for UITableView Cells (Swift)

Use this:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 300

and don't use: heightForRowAtIndexPath delegate function

Also, in the storyboard don't set the height of the label that contains a large amount of data. Give it top, bottom, leading, trailing constraints.

Android: Background Image Size (in Pixel) which Support All Devices

I looked around the internet for correct dimensions for these densities for square images, but couldn't find anything reliable.

If it's any consolation, referring to Veerababu Medisetti's answer I used these dimensions for SQUARES :)

xxxhdpi: 1280x1280 px
xxhdpi: 960x960 px
xhdpi: 640x640 px
hdpi: 480x480 px
mdpi: 320x320 px
ldpi: 240x240 px

Why Choose Struct Over Class?

According to the very popular WWDC 2015 talk Protocol Oriented Programming in Swift (video, transcript), Swift provides a number of features that make structs better than classes in many circumstances.

Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple references to the same instance as happens with classes. This is especially important when passing around a variable to many classes and/or in a multithreaded environment. If you can always send a copy of your variable to other places, you never have to worry about that other place changing the value of your variable underneath you.

With Structs, there is much less need to worry about memory leaks or multiple threads racing to access/modify a single instance of a variable. (For the more technically minded, the exception to that is when capturing a struct inside a closure because then it is actually capturing a reference to the instance unless you explicitly mark it to be copied).

Classes can also become bloated because a class can only inherit from a single superclass. That encourages us to create huge superclasses that encompass many different abilities that are only loosely related. Using protocols, especially with protocol extensions where you can provide implementations to protocols, allows you to eliminate the need for classes to achieve this sort of behavior.

The talk lays out these scenarios where classes are preferred:

  • Copying or comparing instances doesn't make sense (e.g., Window)
  • Instance lifetime is tied to external effects (e.g., TemporaryFile)
  • Instances are just "sinks"--write-only conduits to external state (e.g.CGContext)

It implies that structs should be the default and classes should be a fallback.

On the other hand, The Swift Programming Language documentation is somewhat contradictory:

Structure instances are always passed by value, and class instances are always passed by reference. This means that they are suited to different kinds of tasks. As you consider the data constructs and functionality that you need for a project, decide whether each data construct should be defined as a class or as a structure.

As a general guideline, consider creating a structure when one or more of these conditions apply:

  • The structure’s primary purpose is to encapsulate a few relatively simple data values.
  • It is reasonable to expect that the encapsulated values will be copied rather than referenced when you assign or pass around an instance of that structure.
  • Any properties stored by the structure are themselves value types, which would also be expected to be copied rather than referenced.
  • The structure does not need to inherit properties or behavior from another existing type.

Examples of good candidates for structures include:

  • The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.
  • A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int.
  • A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.

In all other cases, define a class, and create instances of that class to be managed and passed by reference. In practice, this means that most custom data constructs should be classes, not structures.

Here it is claiming that we should default to using classes and use structures only in specific circumstances. Ultimately, you need to understand the real world implication of value types vs. reference types and then you can make an informed decision about when to use structs or classes. Also, keep in mind that these concepts are always evolving and The Swift Programming Language documentation was written before the Protocol Oriented Programming talk was given.

Multiple values in single-value context

Yes, there is.

Surprising, huh? You can get a specific value from a multiple return using a simple mute function:

package main

import "fmt"
import "strings"

func µ(a ...interface{}) []interface{} {
    return a
}

type A struct {
    B string
    C func()(string)
}

func main() {
    a := A {
        B:strings.TrimSpace(µ(E())[1].(string)),
        C:µ(G())[0].(func()(string)),
    }

    fmt.Printf ("%s says %s\n", a.B, a.C())
}

func E() (bool, string) {
    return false, "F"
}

func G() (func()(string), bool) {
    return func() string { return "Hello" }, true
}

https://play.golang.org/p/IwqmoKwVm-

Notice how you select the value number just like you would from a slice/array and then the type to get the actual value.

You can read more about the science behind that from this article. Credits to the author.

Simple way to find if two different lists contain exactly the same elements?

I posted a bunch of stuff in comments I think it warrants its own answer.

As everyone says here, using equals() depends on the order. If you don't care about order, you have 3 options.

Option 1

Use containsAll(). This option is not ideal, in my opinion, because it offers worst case performance, O(n^2).

Option 2

There are two variations to this:

2a) If you don't care about maintaining the order ofyour lists... use Collections.sort() on both list. Then use the equals(). This is O(nlogn), because you do two sorts, and then an O(n) comparison.

2b) If you need to maintain the lists' order, you can copy both lists first. THEN you can use solution 2a on both the copied lists. However this might be unattractive if copying is very expensive.

This leads to:

Option 3

If your requirements are the same as part 2b, but copying is too expensive. You can use a TreeSet to do the sorting for you. Dump each list into its own TreeSet. It will be sorted in the set, and the original lists will remain intact. Then perform an equals() comparison on both TreeSets. The TreeSetss can be built in O(nlogn) time, and the equals() is O(n).

Take your pick :-).

EDIT: I almost forgot the same caveat that Laurence Gonsalves points out. The TreeSet implementation will eliminate duplicates. If you care about duplicates, you will need some sort of sorted multiset.

How do you perform a left outer join using linq extension methods

Group Join method is unnecessary to achieve joining of two data sets.

Inner Join:

var qry = Foos.SelectMany
            (
                foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id),
                (foo, bar) => new
                    {
                    Foo = foo,
                    Bar = bar
                    }
            );

For Left Join just add DefaultIfEmpty()

var qry = Foos.SelectMany
            (
                foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id).DefaultIfEmpty(),
                (foo, bar) => new
                    {
                    Foo = foo,
                    Bar = bar
                    }
            );

EF and LINQ to SQL correctly transform to SQL. For LINQ to Objects it is beter to join using GroupJoin as it internally uses Lookup. But if you are querying DB then skipping of GroupJoin is AFAIK as performant.

Personlay for me this way is more readable compared to GroupJoin().SelectMany()

Undefined index error PHP

TRY

<?php

  $rowID=$productid=$name=$price=$description="";  

   if (isset($_POST['submit'])) {
      $rowID = $_POST['rowID'];
      $productid = $_POST['productid']; //this is line 32 and so on...
      $name = $_POST['name'];
      $price = $_POST['price'];
      $description = $_POST['description'];

}

How do I improve ASP.NET MVC application performance?

Just wanted to add my 2 cents. The MOST effective way to optimize the URL route generation in an MVC application is... not generate them at all.

Most of us more or less know how URLs are generated in our apps anyway, so simply using static Url.Content("~/Blahblah") instead of Url.Action() or Url.RouteUrl() where possible, beats all other methods by almost 20 times and even more.

PS. I've ran a benchmark of couple of thousand iterations and posted results on my blog if interested.

JQuery $.ajax() post - data in a java servlet

To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

How to check if a column exists in Pandas

This will work:

if 'A' in df:

But for clarity, I'd probably write it as:

if 'A' in df.columns:

can't start MySql in Mac OS 10.6 Snow Leopard

  1. Change the following to the file /usr/local/mysql/support-files/mysql.server the follow lines:

    basedir="/usr/local/mysql"
    
    datadir="/usr/local/mysql/data"
    

    and save it.

  2. In the file /etc/rc.common add the follow line at end: /usr/local/mysql/bin/mysqld_safe --user=mysql &

Difference between return and exit in Bash functions

From man bash on return [n];

Causes a function to stop executing and return the value specified by n to its caller. If n is omitted, the return status is that of the last command executed in the function body.

... on exit [n]:

Cause the shell to exit with a status of n. If n is omitted, the exit status is that of the last command executed. A trap on EXIT is executed before the shell terminates.

EDIT:

As per your edit of the question, regarding exit codes, return has nothing to do with exit codes. Exit codes are intended for applications/scripts, not functions. So in this regard, the only keyword that sets the exit code of the script (the one that can be caught by the calling program using the $? shell variable) is exit.

EDIT 2:

My last statement referring exit is causing some comments. It was made to differentiate return and exit for the understanding of the OP, and in fact, at any given point of a program/shell script, exit is the only way of ending the script with an exit code to the calling process.

Every command executed in the shell produces a local "exit code": it sets the $? variable to that code, and can be used with if, && and other operators to conditionally execute other commands.

These exit codes (and the value of the $? variable) are reset by each command execution.

Incidentally, the exit code of the last command executed by the script is used as the exit code of the script itself as seen by the calling process.

Finally, functions, when called, act as shell commands with respect to exit codes. The exit code of the function (within the function) is set by using return. So when in a function return 0 is run, the function execution terminates, giving an exit code of 0.

Corrupt jar file

Could be because of issue with MANIFEST.MF. Try starting main class with following command if you know the package where main class is located.

java -cp launcher/target/usergrid-launcher-1.0-SNAPSHOT.jar co.pseudononymous.Server

How to query all the GraphQL type fields without writing a long query?

I guess the only way to do this is by utilizing reusable fragments:

fragment UserFragment on Users {
    id
    username
    count
} 

FetchUsers {
    users(id: "2") {
        ...UserFragment
    }
}

Running AMP (apache mysql php) on Android

Finally - someone has released the full package!

Bit Web Server (AMP; also see their homepage) stack running on Android. No hacking required. $2 to pay though!

If you are looking for a stack for iOS then the cydia-ios-lighttpd-php-mysql-web-stack does the trick: Should run lighttpd + php 5.4 + mysql - unfortunately only on jailbroken devices.

Edit: In case anyone is interested I have switched to Windows 8 tablet which happily runs all of the opensource AMP stacks. Runs very nicely and with a bit of Bootstrap styling I have a full feature sales order "app" for nothing. Little bit of code to sync back to the online version - no need to spend $50 per month per user on HandShake or similar.

Initializing entire 2D array with one value

int array[ROW][COLUMN]={1};

This initialises only the first element to 1. Everything else gets a 0.

In the first instance, you're doing the same - initialising the first element to 0, and the rest defaults to 0.

The reason is straightforward: for an array, the compiler will initialise every value you don't specify with 0.

With a char array you could use memset to set every byte, but this will not generally work with an int array (though it's fine for 0).

A general for loop will do this quickly:

for (int i = 0; i < ROW; i++)
  for (int j = 0; j < COLUMN; j++)
    array[i][j] = 1;

Or possibly quicker (depending on the compiler)

for (int i = 0; i < ROW*COLUMN; i++)
  *((int*)a + i) = 1;

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

Nobody used the STL algorithm/mismatch function yet. If this returns true, prefix is a prefix of 'toCheck':

std::mismatch(prefix.begin(), prefix.end(), toCheck.begin()).first == prefix.end()

Full example prog:

#include <algorithm>
#include <string>
#include <iostream>

int main(int argc, char** argv) {
    if (argc != 3) {
        std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
                  << "Will print true if 'prefix' is a prefix of string" << std::endl;
        return -1;
    }
    std::string prefix(argv[1]);
    std::string toCheck(argv[2]);
    if (prefix.length() > toCheck.length()) {
        std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
                  << "'prefix' is longer than 'string'" <<  std::endl;
        return 2;
    }
    if (std::mismatch(prefix.begin(), prefix.end(), toCheck.begin()).first == prefix.end()) {
        std::cout << '"' << prefix << '"' << " is a prefix of " << '"' << toCheck << '"' << std::endl;
        return 0;
    } else {
        std::cout << '"' << prefix << '"' << " is NOT a prefix of " << '"' << toCheck << '"' << std::endl;
        return 1;
    }
}

Edit:

As @James T. Huggett suggests, std::equal is a better fit for the question: Is A a prefix of B? and is slight shorter code:

std::equal(prefix.begin(), prefix.end(), toCheck.begin())

Full example prog:

#include <algorithm>
#include <string>
#include <iostream>

int main(int argc, char **argv) {
  if (argc != 3) {
    std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
              << "Will print true if 'prefix' is a prefix of string"
              << std::endl;
    return -1;
  }
  std::string prefix(argv[1]);
  std::string toCheck(argv[2]);
  if (prefix.length() > toCheck.length()) {
    std::cerr << "Usage: " << argv[0] << " prefix string" << std::endl
              << "'prefix' is longer than 'string'" << std::endl;
    return 2;
  }
  if (std::equal(prefix.begin(), prefix.end(), toCheck.begin())) {
    std::cout << '"' << prefix << '"' << " is a prefix of " << '"' << toCheck
              << '"' << std::endl;
    return 0;
  } else {
    std::cout << '"' << prefix << '"' << " is NOT a prefix of " << '"'
              << toCheck << '"' << std::endl;
    return 1;
  }
}

How to open the terminal in Atom?

I didn't want to install a package just for that purpose so I ended up using this in my init.coffee:

spawn = require('child_process').spawn
atom.commands.add 'atom-text-editor', 'open-terminal', ->
  file = atom.workspace.getActiveTextEditor().getPath()
  dir = atom.project.getDirectoryForProjectPath(file).path
  spawn 'mate-terminal', ["--working-directory=#{dir}"], {
    detached: true
  }

With that, I could map ctrl-shift-t to the open-terminal command and it opens a mate-terminal.

Javascript string/integer comparisons

The alert() wants to display a string, so it will interpret "2">"10" as a string.

Use the following:

var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);

var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);

Creating and Naming Worksheet in Excel VBA

Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.

A better way to do this is to pop up a dialog box and get the name you wish to use.

How to use Bootstrap modal using the anchor tag for Register?

You will have to modify the below line:

<li><a href="#" data-toggle="modal" data-target="modalRegister">Register</a></li>

modalRegister is the ID and hence requires a preceding # for ID reference in html.

So, the modified html code snippet would be as follows:

<li><a href="#" data-toggle="modal" data-target="#modalRegister">Register</a></li>

JOptionPane YES/No Options Confirm Dialog Box Issue

You need to look at the return value of the call to showConfirmDialog. I.E.:

int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){
  // Saving code here
}

You were testing against dialogButton, which you were using to set the buttons that should be displayed by the dialog, and this variable was never updated - so dialogButton would never have been anything other than JOptionPane.YES_NO_OPTION.

Per the Javadoc for showConfirmDialog:

Returns: an integer indicating the option selected by the user

How to remove the arrow from a select element in Firefox

Important Update:

As of Firefox V35 the appearance property now works !!

From firefox's official release notes on V35:

Using -moz-appearance with the none value on a combobox now remove the dropdown button (bug 649849).

So now in order to hide the default arrow - it's as easy as adding the following rules on our select element:

select {
   -webkit-appearance: none;
   -moz-appearance: none;
   appearance: none;
}

DEMO

_x000D_
_x000D_
select {_x000D_
  margin: 50px;_x000D_
  border: 1px solid #111;_x000D_
  background: transparent;_x000D_
  width: 150px;_x000D_
  padding: 5px;_x000D_
  font-size: 16px;_x000D_
  border: 1px solid #ccc;_x000D_
  height: 34px;_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
}
_x000D_
<select>_x000D_
  <option>Apples</option>_x000D_
  <option selected>Pineapples</option>_x000D_
  <option>Chocklate</option>_x000D_
  <option>Pancakes</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to check if Receiver is registered in Android?

You can do it easy....

1) create a boolean variable ...

private boolean bolBroacastRegistred;

2) When you register your Broadcast Receiver, set it to TRUE

...
bolBroacastRegistred = true;
this.registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
....

3) In the onPause() do it...

if (bolBroacastRegistred) {
    this.unregisterReceiver(mReceiver);
    bolBroacastRegistred = false
}

Just it, and now, you will not receive more exception error message on onPause().

Tip1: Always use the unregisterReceiver() in onPause() not in onDestroy() Tip2: Dont forget to set the bolBroadcastRegistred variable to FALSE when run the unregisterReceive()

Success!

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

public List<Control> GetAllChildControls(Control Root, Type FilterType = null)
{
    List<Control> AllChilds = new List<Control>();
    foreach (Control ctl in Root.Controls) {
        if (FilterType != null) {
            if (ctl.GetType == FilterType) {
                AllChilds.Add(ctl);
            }
        } else {
            AllChilds.Add(ctl);
        }
        if (ctl.HasChildren) {
            GetAllChildControls(ctl, FilterType);
        }
    }
    return AllChilds;
}

Is there a need for range(len(a))?

I have an use case I don't believe any of your examples cover.

boxes = [b1, b2, b3]
items = [i1, i2, i3, i4, i5]
for j in range(len(boxes)):
    boxes[j].putitemin(items[j])

I'm relatively new to python though so happy to learn a more elegant approach.

Where/How to getIntent().getExtras() in an Android Fragment?

What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments.

There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity and Fragment from the support library.

You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:

public static class DetailsActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // (omitted some other stuff)

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction().add(
                    android.R.id.content, details).commit();
        }
    }
}

In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance in the examples given by Google. There actually is a newInstance method in DetailsFragment, so I'm unsure why it isn't used in the snippet above...

Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments(). Since this returns a Bundle, its usage is similar to that of the extras in an Activity.

public static class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    // (other stuff omitted)

}

Setting timezone to UTC (0) in PHP

In PHP DateTime (PHP >= 5.3)

$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->getTimestamp();

Replace last occurrence of a string in a string

Another 1-liner but without preg:

$subject = 'bourbon, scotch, beer';
$search = ',';
$replace = ', and';

echo strrev(implode(strrev($replace), explode(strrev($search), strrev($subject), 2))); //output: bourbon, scotch, and beer

How to break long string to multiple lines

You cannot use the VB line-continuation character inside of a string.

SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & _
"','" & txtContractStartDate.Value &  _
"','" & txtSeatNo.Value & _
"','" & txtFloor.Value & "','" & txtLeaves.Value & "')"

Call function with setInterval in jQuery?

I have written a custom code for setInterval function which can also help

_x000D_
_x000D_
let interval;
      
function startInterval(){
  interval = setInterval(appendDateToBody, 1000);
  console.log(interval);
}

function appendDateToBody() {
    document.body.appendChild(
        document.createTextNode(new Date() + " "));
}

function stopInterval() {
    clearInterval(interval);
  console.log(interval);
}
_x000D_
<!DOCTYPE html>
<html>
<head>
    <title>setInterval</title>
</head>
<body>
    <input type="button" value="Stop" onclick="stopInterval();" />
    <input type="button" value="Start" onclick="startInterval();" />
</body>
</html>
_x000D_
_x000D_
_x000D_

Finding the average of a list

In order to use reduce for taking a running average, you'll need to track the total but also the total number of elements seen so far. since that's not a trivial element in the list, you'll also have to pass reduce an extra argument to fold into.

>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> running_average = reduce(lambda aggr, elem: (aggr[0] + elem, aggr[1]+1), l, (0.0,0))
>>> running_average[0]
(181.0, 9)
>>> running_average[0]/running_average[1]
20.111111111111111

PHP multidimensional array search by value

you can use this function ; https://github.com/serhatozles/ArrayAdvancedSearch

<?php 
include('ArraySearch.php');

$query = "a='Example World' and b>='2'";

$Array = array(
'a' => array('d' => '2'),
array('a' => 'Example World','b' => '2'),
array('c' => '3'), array('d' => '4'),
);

$Result = ArraySearch($Array,$query,1);

echo '<pre>';
print_r($Result);
echo '</pre>'; 

// Output:
// Array
// (
//    [0] => Array
//        (
//            [a] => Example World
//            [b] => 2
//        )
//
// )

Cannot connect to repo with TortoiseSVN

I was struggling with exactly the same issue. I got my work laptop replaced and suddenly I stopped being able to connect to server. Strangely, initially I was getting errors only blocking me from committing, like: Command : Commit Error : Commit failed (details follow): Error : MKACTIVITY of '/svn//!svn/act/c511b853-23b4-db4a-8991-0bc689a63353': Error : Could not parse response status line (http://*.**.com) Completed! :

When I moved to work in another branch (the SVN server was accessible with no issues for everyone on both branches, who has proper security), I started getting error like:

Command : Checkout from http://.com/svn/fineos//trunk, revision HEAD, Fully recursive, Externals included Error : Unable to connect to a repository at URL Error : 'http://**.com/svn/fineos*/*/trunk' Error : OPTIONS of Error : 'http://*.com/svn/fineos*/*/trunk': could Error : not connect to server (http://*.com) Completed! :

Note: In each case, I could access repository through browser and it was working for everyone else, so obviously it wasn't network or repository issue.

This what worked for me was to uninstall Tortoise client, then remove Tortoise cache folder from Local and Roaming folders under C:\Users\user\AppData. Additionally I renamed TortoiseSVN node in Windows registry so the old configuration cannot be found. Then after reinstallation, client connected to repo beautifully. I am not sure if both steps are required, maybe just changing registry will be enough, I will leave that to you to confirm.

Apologies for long response, but as I haven't seen response to this problem after googling for longer while, I thought that may be helpful for different cases.

How to browse localhost on Android device?

I use my local ip for that i.e. 192.168.0.1 and it works.

Auto submit form on page load

Add the following to Body tag,

<body onload="document.forms['member_signup'].submit()">

and give name attribute to your Form.

<form method="POST" action="" name="member_signup">

How to ignore parent css style

you can create another definition lower in your CSS stylesheet that basically reverses the initial rule. you could also append "!important" to said rule to make sure it sticks.

Check whether a string is not null and not empty

Almost every library I know defines a utility class called StringUtils, StringUtil or StringHelper, and they usually include the method you are looking for.

My personal favorite is Apache Commons / Lang, where in the StringUtils class, you get both the

  1. StringUtils.isEmpty(String) and the
  2. StringUtils.isBlank(String) method

(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)

There are similar utility classes in Spring, Wicket and lots of other libs. If you don't use external libraries, you might want to introduce a StringUtils class in your own project.


Update: many years have passed, and these days I'd recommend using Guava's Strings.isNullOrEmpty(string) method.

PHP Warning: PHP Startup: Unable to load dynamic library

It means there is an extension=... or zend_extension=... line in one of your php configuration files (php.ini, or another close to it) that is trying to load that extension : ixed.5.2.lin

Unfortunately that file or path doesn't exist or the permissions are incorrect.

  1. Try to search in the .ini files that are loaded by PHP (phpinfo() can indicate which ones are) - one of them should try to load that extension.
  2. Either correct the path to the file or comment out the corresponding line.

Installing python module within code

You can also use something like:

import pip

def install(package):
    if hasattr(pip, 'main'):
        pip.main(['install', package])
    else:
        pip._internal.main(['install', package])

# Example
if __name__ == '__main__':
    install('argh')

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

I think what you want is not to override the back button (that just doesn't seem like a good idea - Android OS defines that behavior, why change it?), but to use the Activity Lifecycle and persist your settings/data in the onSaveInstanceState(Bundle) event.

@Override
onSaveInstanceState(Bundle frozenState) {
    frozenState.putSerializable("object_key",
        someSerializableClassYouWantToPersist);
    // etc. until you have everything important stored in the bundle
}

Then you use onCreate(Bundle) to get everything out of that persisted bundle and recreate your state.

@Override
onCreate(Bundle savedInstanceState) {
    if(savedInstanceState!=null){ //It could be null if starting the app.
        mCustomObject = savedInstanceState.getSerializable("object_key");
    }
    // etc. until you have reloaded everything you stored
}

Consider the above psuedo-code to point you in the right direction. Reading up on the Activity Lifecycle should help you determine the best way to accomplish what you're looking for.

How to find all links / pages on a website

If you have the developer console (JavaScript) in your browser, you can type this code in:

urls = document.querySelectorAll('a'); for (url in urls) console.log(urls[url].href);

Shortened:

n=$$('a');for(u in n)console.log(n[u].href)

Javascript swap array elements

Well, you don't need to buffer both values - only one:

var tmp = list[x];
list[x] = list[y];
list[y] = tmp;

In Python, how do I iterate over a dictionary in sorted key order?

Haven't tested this very extensively, but works in Python 2.5.2.

>>> d = {"x":2, "h":15, "a":2222}
>>> it = iter(sorted(d.iteritems()))
>>> it.next()
('a', 2222)
>>> it.next()
('h', 15)
>>> it.next()
('x', 2)
>>>

If you are used to doing for key, value in d.iteritems(): ... instead of iterators, this will still work with the solution above

>>> d = {"x":2, "h":15, "a":2222}
>>> for key, value in sorted(d.iteritems()):
>>>     print(key, value)
('a', 2222)
('h', 15)
('x', 2)
>>>

With Python 3.x, use d.items() instead of d.iteritems() to return an iterator.

SQL Combine Two Columns in Select Statement

If your address1 = '123 Center St' and address2 = 'Apt 3B' then even if you combine and do a LIKE, you cannot search on searchstring as 'Center St 3B'. However, if your searchstring was 'Center St Apt', then you can do it using -

WHERE (address1 + ' ' + address2) LIKE '%searchstring%'