Programs & Examples On #Xming

Forward X11 failed: Network error: Connection refused

Do not log in as a root user, try another one with sudo permissions.

Converting Go struct to JSON

Related issue:

I was having trouble converting struct to JSON, sending it as response from Golang, then, later catch the same in JavaScript via Ajax.

Wasted a lot of time, so posting solution here.

In Go:

// web server

type Foo struct {
    Number int    `json:"number"`
    Title  string `json:"title"`
}

foo_marshalled, err := json.Marshal(Foo{Number: 1, Title: "test"})
fmt.Fprint(w, string(foo_marshalled)) // write response to ResponseWriter (w)

In JavaScript:

// web call & receive in "data", thru Ajax/ other

var Foo = JSON.parse(data);
console.log("number: " + Foo.number);
console.log("title: " + Foo.title);

Windows 7 environment variable not working in path

I had the same problem, I fixed it by removing PATHEXT from user variable. It must only exist in System variable with .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

Also remove the variable from user to system and only include that path on user variable

jQuery ajax success callback function definition

I do not know why you are defining the parameter outside the script. That is unnecessary. Your callback function will be called with the return data as a parameter automatically. It is very possible to define your callback outside the sucess: i.e.

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

function handleData(data) {
    alert(data);
    //do some stuff
}

the handleData function will be called and the parameter passed to it by the ajax function.

HTML - Alert Box when loading page

<script> 
    $(document).ready(function(){
        alert('Hi');
    });
</script>

Importing a long list of constants to a Python file

Python doesn't have a preprocessor, nor does it have constants in the sense that they can't be changed - you can always change (nearly, you can emulate constant object properties, but doing this for the sake of constant-ness is rarely done and not considered useful) everything. When defining a constant, we define a name that's upper-case-with-underscores and call it a day - "We're all consenting adults here", no sane man would change a constant. Unless of course he has very good reasons and knows exactly what he's doing, in which case you can't (and propably shouldn't) stop him either way.

But of course you can define a module-level name with a value and use it in another module. This isn't specific to constants or anything, read up on the module system.

# a.py
MY_CONSTANT = ...

# b.py
import a
print a.MY_CONSTANT

package javax.servlet.http does not exist

The solution that work for is were add the next dependency to my pom.xml file.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
</dependency>

I can not find my.cnf on my windows computer

You can find the basedir (and within maybe your my.cnf) if you do the following query in your mysql-Client (e.g. phpmyadmin)

SHOW VARIABLES

Getting list of tables, and fields in each, in a database

Is this what you are looking for:

Using OBJECT CATALOG VIEWS

 SELECT T.name AS Table_Name ,
       C.name AS Column_Name ,
       P.name AS Data_Type ,
       P.max_length AS Size ,
       CAST(P.precision AS VARCHAR) + '/' + CAST(P.scale AS VARCHAR) AS Precision_Scale
FROM   sys.objects AS T
       JOIN sys.columns AS C ON T.object_id = C.object_id
       JOIN sys.types AS P ON C.system_type_id = P.system_type_id
WHERE  T.type_desc = 'USER_TABLE';

Using INFORMATION SCHEMA VIEWS

  SELECT TABLE_SCHEMA ,
       TABLE_NAME ,
       COLUMN_NAME ,
       ORDINAL_POSITION ,
       COLUMN_DEFAULT ,
       DATA_TYPE ,
       CHARACTER_MAXIMUM_LENGTH ,
       NUMERIC_PRECISION ,
       NUMERIC_PRECISION_RADIX ,
       NUMERIC_SCALE ,
       DATETIME_PRECISION
FROM   INFORMATION_SCHEMA.COLUMNS;

Reference : My Blog - http://dbalink.wordpress.com/2008/10/24/querying-the-object-catalog-and-information-schema-views/

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

I tried the solution below, it works on my machine.

<context:property-placeholder location="classpath*:connection.properties" ignore-unresolvable="true" order="1" />

<context:property-placeholder location="classpath*:general.properties" order="2"/>

In case multiple elements are present in the Spring context, there are a few best practices that should be followed:

the order attribute needs to be specified to fix the order in which these are processed by Spring all property placeholders minus the last one (highest order) should have ignore-unresolvable=”true” to allow the resolution mechanism to pass to others in the context without throwing an exception

source: http://www.baeldung.com/2012/02/06/properties-with-spring/

What ports does RabbitMQ use?

What ports is RabbitMQ using?

Default: 5672, the manual has the answer. It's defined in the RABBITMQ_NODE_PORT variable.

https://www.rabbitmq.com/configure.html#define-environment-variables

The number might be differently if changed by someone in the rabbitmq configuration file:

vi /etc/rabbitmq/rabbitmq-env.conf

Ask the computer to tell you:

sudo nmap -p 1-65535 localhost

Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:50 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00041s latency).
PORT      STATE         SERVICE
443/tcp   open          https
5672/tcp  open          amqp
15672/tcp open  unknown
35102/tcp open  unknown
59440/tcp open  unknown

Oh look, 5672, and 15672

Use netstat:

netstat -lntu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 0.0.0.0:15672               0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:55672               0.0.0.0:*                   LISTEN
tcp        0      0 :::5672                     :::*                        LISTEN

Oh look 5672.

use lsof:

eric@dev ~$ sudo lsof -i | grep beam
beam.smp  21216    rabbitmq   17u  IPv4 33148214      0t0  TCP *:55672 (LISTEN)
beam.smp  21216    rabbitmq   18u  IPv4 33148219      0t0  TCP *:15672 (LISTEN)

use nmap from a different machine, find out if 5672 is open:

sudo nmap -p 5672 10.0.1.71
Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:19 EDT
Nmap scan report for 10.0.1.71
Host is up (0.00011s latency).
PORT     STATE SERVICE
5672/tcp open  amqp
MAC Address: 0A:40:0E:8C:75:6C (Unknown)    
Nmap done: 1 IP address (1 host up) scanned in 0.13 seconds

Try to connect to a port manually with telnet, 5671 is CLOSED:

telnet localhost 5671
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

Try to connect to a port manually with telnet, 5672 is OPEN:

telnet localhost 5672
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Check your firewall:

sudo cat /etc/sysconfig/iptables  

It should tell you what ports are made open:

-A INPUT -p tcp -m tcp --dport 5672 -j ACCEPT

Reapply your firewall:

sudo service iptables restart
iptables: Setting chains to policy ACCEPT: filter          [  OK  ]
iptables: Flushing firewall rules:                         [  OK  ]
iptables: Unloading modules:                               [  OK  ]
iptables: Applying firewall rules:                         [  OK  ]

How to make modal dialog in WPF?

Given a Window object myWindow, myWindow.Show() will open it modelessly and myWindow.ShowDialog() will open it modally. However, even the latter doesn't block, from what I remember.

Getting Image from API in Angular 4/5+?

You should set responseType: ResponseContentType.Blob in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.

Here is an working example:

Create image.service.ts and put following code:

Angular 4:

getImage(imageUrl: string): Observable<File> {
    return this.http
        .get(imageUrl, { responseType: ResponseContentType.Blob })
        .map((res: Response) => res.blob());
}

Angular 5+:

getImage(imageUrl: string): Observable<Blob> {
  return this.httpClient.get(imageUrl, { responseType: 'blob' });
}

Important: Since Angular 5+ you should use the new HttpClient.

The new HttpClient returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'. Read more about that here.

Now you need to create some function in your image.component.ts to get image and show it in html.

For creating an image from Blob you need to use JavaScript's FileReader. Here is function which creates new FileReader and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:

imageToShow: any;

createImageFromBlob(image: Blob) {
   let reader = new FileReader();
   reader.addEventListener("load", () => {
      this.imageToShow = reader.result;
   }, false);

   if (image) {
      reader.readAsDataURL(image);
   }
}

Now you should use your created ImageService to get image from api. You should to subscribe to data and give this data to createImageFromBlob-function. Here is an example function:

getImageFromService() {
      this.isImageLoading = true;
      this.imageService.getImage(yourImageUrl).subscribe(data => {
        this.createImageFromBlob(data);
        this.isImageLoading = false;
      }, error => {
        this.isImageLoading = false;
        console.log(error);
      });
}

Now you can use your imageToShow-variable in HTML template like this:

<img [src]="imageToShow"
     alt="Place image title"
     *ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
     <img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>

I hope this description is clear to understand and you can use it in your project.

See the working example for Angular 5+ here.

npm notice created a lockfile as package-lock.json. You should commit this file

Yes you should, As it locks the version of each and every package which you are using in your app and when you run npm install it install the exact same version in your node_modules folder. This is important becasue let say you are using bootstrap 3 in your application and if there is no package-lock.json file in your project then npm install will install bootstrap 4 which is the latest and you whole app ui will break due to version mismatch.

How to add jQuery in JS file

var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

CSS table-cell equal width

This can be done by setting table-cell style to width: auto, and content empty. The columns are now equal-wide, but holding no content.

To insert content to the cell, add an div with css:

position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;

You also need to add position: relative to the cells.

Now you can put the actual content into the div talked above.

https://jsfiddle.net/vensdvvb/

SQL Server SELECT into existing table

It would work as given below :

insert into Gengl_Del Select Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration 
from Gengl where BOOK='" & lblBook.Caption & "' AND DocNO=" & txtVno.Text & ""

Flushing footer to bottom of the page, twitter bootstrap

Use the flex utilities built into Bootstrap 4! Here's what I've come up with using mostly Bootstrap 4 utilities.

<div class="d-flex flex-column" style="min-height: 100vh;">
  <header></header>
  <div class="container flex-grow-1">
    <div>Some Content</div>
  </div>
  <footer></footer>
</div>
  • .d-flex to make the main div a flex container
  • .flex-column on the main div to arrange your flex items in a column
  • min-height: 100vh to the main div, either with a style attribute or in your CSS, to fill the viewport vertically
  • .flex-grow-1 on the container, element to have the main content container take up all the space that remains in the viewport height.

MVC Redirect to View from jQuery with parameters

i used to do like this

inside view

<script type="text/javascript">

//will replace the '_transactionIds_' and '_payeeId_' 
var _addInvoiceUrl = '@(Html.Raw( Url.Action("PayableInvoiceMainEditor", "Payables", new { warehouseTransactionIds ="_transactionIds_",payeeId = "_payeeId_", payeeType="Vendor" })))';

on javascript file

var url = _addInvoiceUrl.replace('_transactionIds_', warehouseTransactionIds).replace('_payeeId_', payeeId);
        window.location.href = url;

in this way i can able to pass the parameter values on demand..

by using @Html.Raw, url will not get amp; for parameters

How do I retrieve an HTML element's actual width and height?

Take a look at Element.getBoundingClientRect().

This method will return an object containing the width, height, and some other useful values:

{
    width: 960,
    height: 71,
    top: 603,
    bottom: 674,
    left: 360,
    right: 1320
}

For Example:

var element = document.getElementById('foo');
var positionInfo = element.getBoundingClientRect();
var height = positionInfo.height;
var width = positionInfo.width;

I believe this does not have the issues that .offsetWidth and .offsetHeight do where they sometimes return 0 (as discussed in the comments here)

Another difference is getBoundingClientRect() may return fractional pixels, where .offsetWidth and .offsetHeight will round to the nearest integer.

IE8 Note: getBoundingClientRect does not return height and width on IE8 and below.*

If you must support IE8, use .offsetWidth and .offsetHeight:

var height = element.offsetHeight;
var width = element.offsetWidth;

Its worth noting that the Object returned by this method is not really a normal object. Its properties are not enumerable (so, for example, Object.keys doesn't work out-of-the-box.)

More info on this here: How best to convert a ClientRect / DomRect into a plain Object

Reference:

Convert seconds value to hours minutes seconds?

I know this is pretty old but in java 8:

LocalTime.MIN.plusSeconds(120).format(DateTimeFormatter.ISO_LOCAL_TIME)

Print very long string completely in pandas dataframe

In the newer version of pandas, use:

pd.set_option('display.max_colwidth', None)

403 Forbidden vs 401 Unauthorized HTTP responses

This is an older question, but one option that was never really brought up was to return a 404. From a security perspective, the highest voted answer suffers from a potential information leakage vulnerability. Say, for instance, that the secure web page in question is a system admin page, or perhaps more commonly, is a record in a system that the user doesn't have access to. Ideally you wouldn't want a malicious user to even know that there's a page / record there, let alone that they don't have access. When I'm building something like this, I'll try to record unauthenticate / unauthorized requests in an internal log, but return a 404.

OWASP has some more information about how an attacker could use this type of information as part of an attack.

How can I select multiple columns from a subquery (in SQL Server) that should have one record (select top 1) for each record in the main query?

You'll have to make a join:

SELECT A.SalesOrderID, B.Foo
FROM A
JOIN B bo ON bo.id = (
     SELECT TOP 1 id
     FROM B bi
     WHERE bi.SalesOrderID = a.SalesOrderID
     ORDER BY bi.whatever
     )
WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'

, assuming that b.id is a PRIMARY KEY on B

In MS SQL 2005 and higher you may use this syntax:

SELECT SalesOrderID, Foo
FROM (
  SELECT A.SalesOrderId, B.Foo,
         ROW_NUMBER() OVER (PARTITION BY B.SalesOrderId ORDER BY B.whatever) AS rn
  FROM A
  JOIN B ON B.SalesOrderID = A.SalesOrderID
  WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
) i
WHERE rn

This will select exactly one record from B for each SalesOrderId.

javascript regex : only english letters allowed

_x000D_
_x000D_
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
_x000D_
_x000D_

Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w covers a-zA-Z and some other word characters. It all depends on what you need specifically.

Counting the Number of keywords in a dictionary in python

Calling len() directly on your dictionary works, and is faster than building an iterator, d.keys(), and calling len() on it, but the speed of either will negligible in comparison to whatever else your program is doing.

d = {x: x**2 for x in range(1000)}

len(d)
# 1000

len(d.keys())
# 1000

%timeit len(d)
# 41.9 ns ± 0.244 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit len(d.keys())
# 83.3 ns ± 0.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

printf() formatting for hex

You could always use "%p" in order to display 8 bit hex numbers.

int main (void)
{
    uint8_t a;
    uint32_t b;
    a=15;
    b=a<<28;
    printf("%p", b);
    return 0;
}

Output:

0xf0000000

How can I query for null values in entity framework?

var result = from entry in table
             where entry.something.Equals(null)
             select entry;

MSDN Reference: LINQ to SQL: .NET Language-Integrated Query for Relational Data

How to get Django and ReactJS to work together?

I know this is a couple of years late, but I'm putting it out there for the next person on this journey.

GraphQL has been helpful and way easier compared to DjangoRESTFramework. It is also more flexible in terms of the responses you get. You get what you ask for and don't have to filter through the response to get what you want.

You can use Graphene Django on the server side and React+Apollo/Relay... You can look into it as that is not your question.

UICollectionView - dynamic cell height?

We can maintain dynamic height for collection view cell without xib(only using storyboard).

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout*)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

        NSAttributedString* labelString = [[NSAttributedString alloc] initWithString:@"Your long string goes here" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0]}];
        CGRect cellRect = [labelString boundingRectWithSize:CGSizeMake(cellWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil];

        return CGSizeMake(cellWidth, cellRect.size.height);
}

Make sure that numberOfLines in IB should be 0.

How can I get Docker Linux container information from within the container itself?

To make it simple,

  1. Container ID is your host name inside docker
  2. Container information is available inside /proc/self/cgroup

To get host name,

hostname

or

uname -n

or

cat /etc/host

Output can be redirected to any file & read back from application E.g.: # hostname > /usr/src//hostname.txt

Insert Data Into Tables Linked by Foreign Key

You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:

insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

If the customer does not exist, you'll get an sql exception which text will be something like:

null value in column "customer_id" violates not-null constraint

(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:

insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.

Recommended way to embed PDF in HTML?

I found that the best way to embed a pdf for my case was by using bootstrap because not only does it show the pdf but it also fill available space and you can specify the ratio as you wish. Here's an example of what i made with it:

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

<div class="embed-responsive embed-responsive-1by1">
  <iframe class="embed-responsive-item" src="http://example.com/the.pdf" type="application/pdf" allowfullscreen></iframe>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
_x000D_
_x000D_
_x000D_

Adding Permissions in AndroidManifest.xml in Android Studio?

You can add manually in the manifest file within manifest tag by:

<uses-permission android:name="android.permission.CAMERA"/>

This permission is required to be able to access the camera device.

What's the difference between equal?, eql?, ===, and ==?

Ruby exposes several different methods for handling equality:

a.equal?(b) # object identity - a and b refer to the same object

a.eql?(b) # object equivalence - a and b have the same value

a == b # object equivalence - a and b have the same value with type conversion.

Continue reading by clicking the link below, it gave me a clear summarized understanding.

https://www.relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/equality-matchers

Hope it helps others.

AngularJS: How to run additional code after AngularJS has rendered a template?

You can also create a directive that runs your code in the link function.

See that stackoverflow reply.

How to make an autocomplete TextBox in ASP.NET?

1-Install AjaxControl Toolkit easily by Nugget

PM> Install-Package AjaxControlToolkit

2-then in markup

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">  
</asp:ToolkitScriptManager>  

<asp:TextBox ID="txtMovie" runat="server"></asp:TextBox>  

<asp:AutoCompleteExtender  ID="AutoCompleteExtender1"  TargetControlID="txtMovie"   
    runat="server" />  

3- in code-behind : to get the suggestions

[System.Web.Services.WebMethodAttribute(),System.Web.Script.Services.ScriptMethodAttribute()]  
    public static string[] GetCompletionList(string prefixText, int count, string contextKey) {  
        // Create array of movies  
        string[] movies = {"Star Wars", "Star Trek", "Superman", "Memento", "Shrek", "Shrek II"};  

        // Return matching movies  
        return (from m in movies where m.StartsWith(prefixText,StringComparison.CurrentCultureIgnoreCase) select m).Take(count).ToArray();  
    }

source: http://www.asp.net/ajaxlibrary/act_autocomplete_simple.ashx

Free Rest API to retrieve current datetime as string (timezone irrelevant)

TimezoneDb provides a free API: http://timezonedb.com/api

GenoNames also has a RESTful API available to get the current time for a given location: http://www.geonames.org/export/ws-overview.html.

You can use Greenwich, UK if you'd like GMT.

Import Excel spreadsheet columns into SQL Server database

go
sp_configure 'show advanced options',1  
reconfigure with override  
go  
sp_configure 'Ad Hoc Distributed Queries',1  
reconfigure with override  
go
SELECT * into temptable
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
                'Excel 8.0;Database=C:\Documents and Settings\abhisharma\Desktop\exl\ImportExcel2SQLServer\ImportExcel2SQLServer\example.xls;IMEX=1',
                'SELECT * FROM [Sheet1$]')

select * from temptable

CSS Transition doesn't work with top, bottom, left, right

In my case div position was fixed , adding left position was not enough it started working only after adding display block

left:0; display:block;

ES6 class variable alternatives

Just define a getter.

_x000D_
_x000D_
class MyClass
{
  get MY_CONST () { return 'string'; }

  constructor ()
  {
    console.log ("MyClass MY_CONST:", this.MY_CONST);
  }
}

var obj = new MyClass();
_x000D_
_x000D_
_x000D_

Showing all session data at once?

print_r($this->session->userdata); 

or

print_r($this->session->all_userdata());

Read lines from a file into a Bash array

Your first attempt was close. Here is the simplistic approach using your idea.

file="somefileondisk"
lines=`cat $file`
for line in $lines; do
        echo "$line"
done

Can you do a partial checkout with Subversion?

If you already have the full local copy, you can remove unwanted sub folders by using --set-depth command.

svn update --set-depth=exclude www

See: http://blogs.collab.net/subversion/sparse-directories-now-with-exclusion

The set-depth command support multipile paths.

Updating the root local copy will not change the depth of the modified folder.

To restore the folder to being recusively checkingout, you could use --set-depth again with infinity param.

svn update --set-depth=infinity www

Python multiprocessing PicklingError: Can't pickle <type 'function'>

Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

This error will also come if you have any inbuilt function inside the model object that was passed to the async job.

So make sure to check the model objects that are passed doesn't have inbuilt functions. (In our case we were using FieldTracker() function of django-model-utils inside the model to track a certain field). Here is the link to relevant GitHub issue.

Magento How to debug blank white screen

This could be as simple as a template conflict. Revert to default template in System/Configuration/Design/Themes.

Difference between onStart() and onResume()

onResume() is called:

  1. after onStart()
  2. when the Activity comes to the foreground.

From http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle: alt text

jQuery - Detect value change on hidden input field

This example returns the draft field value every time the hidden draft field changes its value (chrome browser):

var h = document.querySelectorAll('input[type="hidden"][name="draft"]')[0];
//or jquery.....
//var h = $('input[type="hidden"][name="draft"]')[0];

observeDOM(h, 'n', function(draftValue){ 
  console.log('dom changed draftValue:'+draftValue);
});


var observeDOM = (function(){
var MutationObserver = window.MutationObserver || 
window.WebKitMutationObserver;

  return function(obj, thistime, callback){
    if(typeof obj === 'undefined'){
      console.log('obj is undefined');
      return;
    }

    if( MutationObserver ){

        // define a new observer
        var obs = new MutationObserver(function(mutations, observer){

            if( mutations[0].addedNodes.length || mutations[0].removedNodes.length ){

               callback('pass other observations back...');

            }else if(mutations[0].attributeName == "value" ){

               // use callback to pass back value of hidden form field                            
               callback( obj.value );

            }

        });

        // have the observer observe obj for changes in children
        // note 'attributes:true' else we can't read the input attribute value
        obs.observe( obj, { childList:true, subtree:true, attributes:true  });

       }
  };
})();

Difference between UTF-8 and UTF-16?

This is unrelated to UTF-8/16 (in general, although it does convert to UTF16 and the BE/LE part can be set w/ a single line), yet below is the fastest way to convert String to byte[]. For instance: good exactly for the case provided (hash code). String.getBytes(enc) is relatively slow.

static byte[] toBytes(String s){
        byte[] b=new byte[s.length()*2];
        ByteBuffer.wrap(b).asCharBuffer().put(s);
        return b;
    }

Test if object implements interface

In addition to testing using the "is" operator, you can decorate your methods to make sure that variables passed to it implement a particular interface, like so:

public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
{
     //Some bubbly sorting
}

I'm not sure which version of .Net this was implemented in so it may not work in your version.

Find the item with maximum occurrences in a list

My (simply) code (three months studying Python):

def more_frequent_item(lst):
    new_lst = []
    times = 0
    for item in lst:
        count_num = lst.count(item)
        new_lst.append(count_num)
        times = max(new_lst)
    key = max(lst, key=lst.count)
    print("In the list: ")
    print(lst)
    print("The most frequent item is " + str(key) + ". Appears " + str(times) + " times in this list.")


more_frequent_item([1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67])

The output will be:

In the list: 
[1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
The most frequent item is 4. Appears 6 times in this list.

Python: Find a substring in a string and returning the index of the substring

Adding onto @demented hedgehog answer on using find()

In terms of efficiency

It may be worth first checking to see if s1 is in s2 before calling find().
This can be more efficient if you know that most of the times s1 won't be a substring of s2

Since the in operator is very efficient

 s1 in s2

It can be more efficient to convert:

index = s2.find(s1)

to

index = -1
if s1 in s2:
   index = s2.find(s1)

This is useful for when find() is going to be returning -1 a lot.

I found it substantially faster since find() was being called many times in my algorithm, so I thought it was worth mentioning

JSHint and jQuery: '$' is not defined

You probably want to do the following,

const $ = window.$

to avoid it throwing linting error.

Regular Expression for matching parentheses

The solution consists in a regex pattern matching open and closing parenthesis

String str = "Your(String)";
// parameter inside split method is the pattern that matches opened and closed parenthesis, 
// that means all characters inside "[ ]" escaping parenthesis with "\\" -> "[\\(\\)]"
String[] parts = str.split("[\\(\\)]");
for (String part : parts) {
   // I print first "Your", in the second round trip "String"
   System.out.println(part);
}

Writing in Java 8's style, this can be solved in this way:

Arrays.asList("Your(String)".split("[\\(\\)]"))
    .forEach(System.out::println);

I hope it is clear.

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

For rep reasons, I can't add this as a comment (where it would better go with bennedich's answer), but for Windows command line, here is the correct syntax:

curl -u YOUR_USERNAME https://api.github.com/user/repos -d "{\"name\":\"YOUR_REPO_NAME\"}"

It's the same basic form, but you have to use double quotes (") instead of single, and escape the double quotes sent in the POST parameters (after the -d flag) with backslashes. I also removed the single quotes around my username, but if your username had a space (possible?) it would probably need double quotes.

Stick button to right side of div

Another solution: change margins. Depending on the siblings of the button, display should be modified.

button {
    display:      block;
    margin-left:  auto;
    margin-right: 0;
}

Validating a Textbox field for only numeric input.

I know this is an old question but I figured out I should pitch my answer anyways.

The following snippet iterates through each character of the text and uses the IsNumber() method, which returns true if the character is a number and false the other way, to check if all the characters are numbers. If all are numbers, the method returns true. If not it returns false.

using System;

private bool ValidateText(string text){
    char[] characters = text.ToCharArray();

    foreach(char c in characters){
        if(!char.IsNumber(c))
            return false;
    }
    return true;
}

Python readlines() usage and efficient practice for reading

The short version is: The efficient way to use readlines() is to not use it. Ever.


I read some doc notes on readlines(), where people has claimed that this readlines() reads whole file content into memory and hence generally consumes more memory compared to readline() or read().

The documentation for readlines() explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list full of strings out of those lines.

But the documentation for read() likewise guarantees that it reads the whole file into memory, and builds a string, so that doesn't help.


On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.


You can work around this in three ways:

  1. Write a loop around readlines(sizehint), read(size), or readline().
  2. Just use the file as a lazy iterator without calling any of these.
  3. mmap the file, which allows you to treat it as a giant string without first reading it in.

For example, this has to read all of foo at once:

with open('foo') as f:
    lines = f.readlines()
    for line in lines:
        pass

But this only reads about 8K at a time:

with open('foo') as f:
    while True:
        lines = f.readlines(8192)
        if not lines:
            break
        for line in lines:
            pass

And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.

with open('foo') as f:
    while True:
        line = f.readline()
        if not line:
            break
        pass

And this will do the exact same thing as the previous:

with open('foo') as f:
    for line in f:
        pass

Meanwhile:

but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?

Python doesn't make any such guarantees about garbage collection.

The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.

However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.

On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.

Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of mallocs to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).


Putting it all together, here's how I'd write your program:

for filename in os.listdir(input_dir):
    with open(filename, 'rb') as f:
        if filename.endswith(".gz"):
            f = gzip.open(fileobj=f)
        words = (line.split(delimiter) for line in f)
        ... my logic ...  

Or, maybe:

for filename in os.listdir(input_dir):
    if filename.endswith(".gz"):
        f = gzip.open(filename, 'rb')
    else:
        f = open(filename, 'rb')
    with contextlib.closing(f):
        words = (line.split(delimiter) for line in f)
        ... my logic ...

How to find length of a string array?

This won't work. You first have to initialize the array. So far, you only have a String[] reference, pointing to null.

When you try to read the length member, what you actually do is null.length, which results in a NullPointerException.

What are the best practices for using a GUID as a primary key, specifically regarding performance?

Most of the times it should not be used as the primary key for a table because it really hit the performance of the database. useful links regarding GUID impact on performance and as a primary key.

  1. https://www.sqlskills.com/blogs/kimberly/disk-space-is-cheap/
  2. https://www.sqlskills.com/blogs/kimberly/guids-as-primary-keys-andor-the-clustering-key/

Using :before CSS pseudo element to add image to modal

You should use the background attribute to give an image to that element, and I would use ::after instead of before, this way it should be already drawn on top of your element.

.Modal:before{
  content: '';
  background:url('blackCarrot.png');
  width: /* width of the image */;
  height: /* height of the image */;
  display: block;
}

Stretch Image to Fit 100% of Div Height and Width

will the height attribute stretch the image beyond its native resolution? If I have a image with a height of say 420 pixels, I can't get css to stretch the image beyond the native resolution to fill the height of the viewport.

I am getting pretty close results with:

 .rightdiv img {
        max-width: 25vw;
        min-height: 100vh;
    }

the 100vh is getting pretty close, with just a few pixels left over at the bottom for some reason.

How to rename a pane in tmux?

For those who want to easily rename their panes, this is what I have in my .tmux.conf

set -g default-command '                      \
function renamePane () {                      \
  read -p "Enter Pane Name: " pane_name;      \
  printf "\033]2;%s\033\\r:r" "${pane_name}"; \
};                                            \
export -f renamePane;                         \
bash -i'
set -g pane-border-status top
set -g pane-border-format "#{pane_index} #T #{pane_current_command}"
bind-key -T prefix R send-keys "renamePane" C-m

Panes are automatically named with their index, machine name and current command. To change the machine name you can run <C-b>R which will prompt you to enter a new name.

*Pane renaming only works when you are in a shell.

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

To include column names to your csv file you can do the following:

sqlite> .headers on
sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout

To verify the changes that you have made you can run this command:

sqlite> .show

Output:

echo: off   
explain: off   
headers: on   
mode: csv   
nullvalue: ""  
output: stdout  
separator: "|"   
stats: off   
width: 22 18 

How do I delete multiple rows with different IDs?

  • You can make this.

    CREATE PROC [dbo].[sp_DELETE_MULTI_ROW]
    @CODE XML ,@ERRFLAG CHAR(1) = '0' OUTPUT

AS

SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

DELETE tb_SampleTest WHERE CODE IN( SELECT Item.value('.', 'VARCHAR(20)') FROM @CODE.nodes('RecordList/ID') AS x(Item) )

IF @@ROWCOUNT = 0 SET @ERRFLAG = 200

SET NOCOUNT OFF

  • <'RecordList'><'ID'>1<'/ID'><'ID'>2<'/ID'><'/RecordList'>

Best way to convert an ArrayList to a string

For this simple use case, you can simply join the strings with comma. If you use Java 8:

String csv = String.join("\t", yourArray);

otherwise commons-lang has a join() method:

String csv = org.apache.commons.lang3.StringUtils.join(yourArray, "\t");

How do I test which class an object is in Objective-C?

if you want to get the name of the class simply call:-

id yourObject= [AnotherClass returningObject];

NSString *className=[yourObject className];

NSLog(@"Class name is : %@",className);

How do I get a list of all the duplicate items using pandas in python?

sort("ID") does not seem to be working now, seems deprecated as per sort doc, so use sort_values("ID") instead to sort after duplicate filter, as following:

df[df.ID.duplicated(keep=False)].sort_values("ID")

Java count occurrence of each item in an array

You can use Hash Map as given in the example below:

import java.util.HashMap;
import java.util.Set;

/**
 * 
 * @author Abdul Rab Khan
 * 
 */
public class CounterExample {
    public static void main(String[] args) {
        String[] array = { "name1", "name1", "name2", "name2", "name2" };
        countStringOccurences(array);
    }

    /**
     * This method process the string array to find the number of occurrences of
     * each string element
     * 
     * @param strArray
     *            array containing string elements
     */
    private static void countStringOccurences(String[] strArray) {
        HashMap<String, Integer> countMap = new HashMap<String, Integer>();
        for (String string : strArray) {
            if (!countMap.containsKey(string)) {
                countMap.put(string, 1);
            } else {
                Integer count = countMap.get(string);
                count = count + 1;
                countMap.put(string, count);
            }
        }
        printCount(countMap);
    }

    /**
     * This method will print the occurrence of each element
     * 
     * @param countMap
     *            map containg string as a key, and its count as the value
     */
    private static void printCount(HashMap<String, Integer> countMap) {
        Set<String> keySet = countMap.keySet();
        for (String string : keySet) {
            System.out.println(string + " : " + countMap.get(string));
        }
    }
}

what does this mean ? image/png;base64?

That data:image/png;base64 URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.

Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.

How to count TRUE values in a logical vector

Another way is

> length(z[z==TRUE])
[1] 498

While sum(z) is nice and short, for me length(z[z==TRUE]) is more self explaining. Though, I think with a simple task like this it does not really make a difference...

If it is a large vector, you probably should go with the fastest solution, which is sum(z). length(z[z==TRUE]) is about 10x slower and table(z)[TRUE] is about 200x slower than sum(z).

Summing up, sum(z) is the fastest to type and to execute.

CodeIgniter Active Record not equal

According to the manual this should work:

Custom key/value method:

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

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

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

Using FileUtils in eclipse

Open the project's properties---> Java Build Path ---> Libraries tab ---> Add External Jars

will allow you to add jars.

You need to download commonsIO from here.

Setting the MySQL root user password on OS X

Let us add this workaround that works on my laptop!

Mac with Osx Mojave 10.14.5

Mysql 8.0.17 was installed with homebrew

  • I run the following command to locate the path of mysql

    brew info mysql

  • Once the path is known, I run this :

    /usr/local/Cellar/mysql/8.0.17/bin/mysqld_safe --skip-grant-table

  • In another terminal I run :

    mysql -u root

  • Inside that terminal, I changed the root password using :

    update mysql.user set authentication_string='NewPassword' where user='root';

  • and to finish I run :

    FLUSH PRIVILEGES;

And voila the password was reset.

References :

not-null property references a null or transient value

Every InvoiceItem must have an Invoice attached to it because of the not-null="true" in the many-to-one mapping.

So the basic idea is you need to set up that explicit relationship in code. There are many ways to do that. On your class I see a setItems method. I do NOT see an addInvoiceItem method. When you set items, you need to loop through the set and call item.setInvoice(this) on all of the items. If you implement an addItem method, you need to do the same thing. Or you need to otherwise set the Invoice of every InvoiceItem in the collection.

Storyboard doesn't contain a view controller with identifier

Use your identifier(@"drivingDetails") as Storyboard ID.

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

jQuery each loop in table row

Use immediate children selector >:

$('#tblOne > tbody  > tr')

Description: Selects all direct child elements specified by "child" of elements specified by "parent".

How do I call a SQL Server stored procedure from PowerShell?

Here is a function that I use (slightly redacted). It allows input and output parameters. I only have uniqueidentifier and varchar types implemented, but any other types are easy to add. If you use parameterized stored procedures (or just parameterized sql...this code is easily adapted to that), this will make your life a lot easier.

To call the function, you need a connection to the SQL server (say $conn),

$res=exec-storedprocedure -storedProcName 'stp_myProc' -parameters @{Param1="Hello";Param2=50} -outparams @{ID="uniqueidentifier"} $conn

retrieve proc output from returned object

$res.data #dataset containing the datatables returned by selects

$res.outputparams.ID #output parameter ID (uniqueidentifier)

The function:

function exec-storedprocedure($storedProcName,  
        [hashtable] $parameters=@{},
        [hashtable] $outparams=@{},
        $conn,[switch]$help){ 

        function put-outputparameters($cmd, $outparams){
            foreach($outp in $outparams.Keys){
                $cmd.Parameters.Add("@$outp", (get-paramtype $outparams[$outp])).Direction=[System.Data.ParameterDirection]::Output
            }
        }
        function get-outputparameters($cmd,$outparams){
            foreach($p in $cmd.Parameters){
                if ($p.Direction -eq [System.Data.ParameterDirection]::Output){
                $outparams[$p.ParameterName.Replace("@","")]=$p.Value
                }
            }
        }

        function get-paramtype($typename,[switch]$help){
            switch ($typename){
                'uniqueidentifier' {[System.Data.SqlDbType]::UniqueIdentifier}
                'int' {[System.Data.SqlDbType]::Int}
                'xml' {[System.Data.SqlDbType]::Xml}
                'nvarchar' {[System.Data.SqlDbType]::NVarchar}
                default {[System.Data.SqlDbType]::Varchar}
            }
        }
        if ($help){
            $msg = @"
    Execute a sql statement.  Parameters are allowed.  
    Input parameters should be a dictionary of parameter names and values.
    Output parameters should be a dictionary of parameter names and types.
    Return value will usually be a list of datarows. 

    Usage: exec-query sql [inputparameters] [outputparameters] [conn] [-help]
    "@
            Write-Host $msg
            return
        }
        $close=($conn.State -eq [System.Data.ConnectionState]'Closed')
        if ($close) {
           $conn.Open()
        }

        $cmd=new-object system.Data.SqlClient.SqlCommand($sql,$conn)
        $cmd.CommandType=[System.Data.CommandType]'StoredProcedure'
        $cmd.CommandText=$storedProcName
        foreach($p in $parameters.Keys){
            $cmd.Parameters.AddWithValue("@$p",[string]$parameters[$p]).Direction=
                  [System.Data.ParameterDirection]::Input
        }

        put-outputparameters $cmd $outparams
        $ds=New-Object system.Data.DataSet
        $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
        [Void]$da.fill($ds)
        if ($close) {
           $conn.Close()
        }
        get-outputparameters $cmd $outparams

        return @{data=$ds;outputparams=$outparams}
    }

How can I scan barcodes on iOS?

You can find another native iOS solution using Swift 4 and Xcode 9 at below. Native AVFoundation framework used with in this solution.

First part is the a subclass of UIViewController which have related setup and handler functions for AVCaptureSession.

import UIKit
import AVFoundation

class BarCodeScannerViewController: UIViewController {

    let captureSession = AVCaptureSession()
    var videoPreviewLayer: AVCaptureVideoPreviewLayer!
    var initialized = false

    let barCodeTypes = [AVMetadataObject.ObjectType.upce,
                        AVMetadataObject.ObjectType.code39,
                        AVMetadataObject.ObjectType.code39Mod43,
                        AVMetadataObject.ObjectType.code93,
                        AVMetadataObject.ObjectType.code128,
                        AVMetadataObject.ObjectType.ean8,
                        AVMetadataObject.ObjectType.ean13,
                        AVMetadataObject.ObjectType.aztec,
                        AVMetadataObject.ObjectType.pdf417,
                        AVMetadataObject.ObjectType.itf14,
                        AVMetadataObject.ObjectType.dataMatrix,
                        AVMetadataObject.ObjectType.interleaved2of5,
                        AVMetadataObject.ObjectType.qr]

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setupCapture()
        // set observer for UIApplicationWillEnterForeground, so we know when to start the capture session again
        NotificationCenter.default.addObserver(self,
                                           selector: #selector(willEnterForeground),
                                           name: .UIApplicationWillEnterForeground,
                                           object: nil)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // this view is no longer topmost in the app, so we don't need a callback if we return to the app.
        NotificationCenter.default.removeObserver(self,
                                              name: .UIApplicationWillEnterForeground,
                                              object: nil)
    }

    // This is called when we return from another app to the scanner view
    @objc func willEnterForeground() {
        setupCapture()
    }

    func setupCapture() {
        var success = false
        var accessDenied = false
        var accessRequested = false

        let authorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)
        if authorizationStatus == .notDetermined {
            // permission dialog not yet presented, request authorization
            accessRequested = true
            AVCaptureDevice.requestAccess(for: .video,
                                      completionHandler: { (granted:Bool) -> Void in
                                          self.setupCapture();
            })
            return
        }
        if authorizationStatus == .restricted || authorizationStatus == .denied {
            accessDenied = true
        }
        if initialized {
            success = true
        } else {
            let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera,
                                                                                        .builtInTelephotoCamera,
                                                                                        .builtInDualCamera],
                                                                          mediaType: .video,
                                                                          position: .unspecified)

            if let captureDevice = deviceDiscoverySession.devices.first {
                do {
                    let videoInput = try AVCaptureDeviceInput(device: captureDevice)
                    captureSession.addInput(videoInput)
                    success = true
                } catch {
                    NSLog("Cannot construct capture device input")
                }
            } else {
                NSLog("Cannot get capture device")
            }
        }
        if success {
            DispatchQueue.global().async {
                self.captureSession.startRunning()
                DispatchQueue.main.async {
                    let captureMetadataOutput = AVCaptureMetadataOutput()
                    self.captureSession.addOutput(captureMetadataOutput)
                    let newSerialQueue = DispatchQueue(label: "barCodeScannerQueue") // in iOS 11 you can use main queue
                    captureMetadataOutput.setMetadataObjectsDelegate(self, queue: newSerialQueue)
                    captureMetadataOutput.metadataObjectTypes = self.barCodeTypes
                    self.videoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
                    self.videoPreviewLayer.videoGravity = .resizeAspectFill
                    self.videoPreviewLayer.frame = self.view.layer.bounds
                    self.view.layer.addSublayer(self.videoPreviewLayer)
                } 
            }
            initialized = true
        } else {
            // Only show a dialog if we have not just asked the user for permission to use the camera.  Asking permission
            // sends its own dialog to th user
            if !accessRequested {
                // Generic message if we cannot figure out why we cannot establish a camera session
                var message = "Cannot access camera to scan bar codes"
                #if (arch(i386) || arch(x86_64)) && (!os(macOS))
                    message = "You are running on the simulator, which does not hae a camera device.  Try this on a real iOS device."
                #endif
                if accessDenied {
                    message = "You have denied this app permission to access to the camera.  Please go to settings and enable camera access permission to be able to scan bar codes"
                }
                let alertPrompt = UIAlertController(title: "Cannot access camera", message: message, preferredStyle: .alert)
                let confirmAction = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                    self.navigationController?.popViewController(animated: true)
                })
                alertPrompt.addAction(confirmAction)
                self.present(alertPrompt, animated: true, completion: nil)
            }
        }
    }

    func handleCapturedOutput(metadataObjects: [AVMetadataObject]) {
        if metadataObjects.count == 0 {
            return
        }

        guard let metadataObject = metadataObjects.first as? AVMetadataMachineReadableCodeObject else {
            return
        }

        if barCodeTypes.contains(metadataObject.type) {
            if let metaDataString = metadataObject.stringValue {
                captureSession.stopRunning()
                displayResult(code: metaDataString)
                return
            }
        }
    }

    func displayResult(code: String) {
        let alertPrompt = UIAlertController(title: "Bar code detected", message: code, preferredStyle: .alert)
        if let url = URL(string: code) {
            let confirmAction = UIAlertAction(title: "Launch URL", style: .default, handler: { (action) -> Void in
                UIApplication.shared.open(url, options: [:], completionHandler: { (result) in
                    if result {
                        NSLog("opened url")
                    } else {
                        let alertPrompt = UIAlertController(title: "Cannot open url", message: nil, preferredStyle: .alert)
                        let confirmAction = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                        })
                        alertPrompt.addAction(confirmAction)
                        self.present(alertPrompt, animated: true, completion: {
                            self.setupCapture()
                        })
                    }
                })        
            })
            alertPrompt.addAction(confirmAction)
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
            self.setupCapture()
        })
        alertPrompt.addAction(cancelAction)
        present(alertPrompt, animated: true, completion: nil)
    }

}

Second part is the extension of our UIViewController subclass for AVCaptureMetadataOutputObjectsDelegate where we catch the captured outputs.

extension BarCodeScannerViewController: AVCaptureMetadataOutputObjectsDelegate {

    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        handleCapturedOutput(metadataObjects: metadataObjects)
    }

}

Update for Swift 4.2

.UIApplicationWillEnterForegroundchanges as UIApplication.willEnterForegroundNotification.

VC++ fatal error LNK1168: cannot open filename.exe for writing

well, I actually just saved and closed the project and restarted VS Express 2013 in windows 8 and that sorted my problem.

Configure Nginx with proxy_pass

Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.

The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks

How to make a Div appear on top of everything else on the screen?

One form to do this is insert the panel that you want to expand inside a DIV setted as relative: let me show you:

<div style="position:relative">
  <div style="position:absolute; z-index: 1000;">
    your code
  </div>
</div>

You use the first div to position the inner content in a specific area inside your page and the second absolute should be referred to the container (because is relative) The z-index in this case is referred also to container and if it higher that the container should be at top. You can put the style in a CSS class and change the size of the absolute div to expand it on hover or another action that you want to control.

I hope that this help

jquery datatables default sort

Here is the actual code that does it...

$(document).ready(function()
{
  var oTable = $('#myTable').dataTable();

  // Sort immediately with column 2 (at position 1 in the array (base 0). More could be sorted with additional array elements
  oTable.fnSort( [ [1,'asc'] ] );

  // And to sort another column descending (at position 2 in the array (base 0).
  oTable.fnSort( [ [2,'desc'] ] );
} );

To not have the column highlighted, modify the CSS like so:

table.dataTable tr.odd td.sorting_1 { background-color: transparent; }
table.dataTable tr.even td.sorting_1 { background-color: transparent; }

simple custom event

You haven't created an event. To do that write:

public event EventHandler<Progress> Progress;

Then, you can call Progress from within the class where it was declared like normal function or delegate:

Progress(this, new Progress("some status"));

So, if you want to report progress in TestClass, the event should be in there too and it should be also static. You can the subscribe to it from your form like this:

TestClass.Progress += SetStatus;

Also, you should probably rename Progress to ProgressEventArgs, so that it's clear what it is.

document.createElement("script") synchronously

This is way late but for future reference to anyone who'd like to do this, you can use the following:

function require(file,callback){
    var head=document.getElementsByTagName("head")[0];
    var script=document.createElement('script');
    script.src=file;
    script.type='text/javascript';
    //real browsers
    script.onload=callback;
    //Internet explorer
    script.onreadystatechange = function() {
        if (this.readyState == 'complete') {
            callback();
        }
    }
    head.appendChild(script);
}

I did a short blog post on it some time ago http://crlog.info/2011/10/06/dynamically-requireinclude-a-javascript-file-into-a-page-and-be-notified-when-its-loaded/

Convert string to number and add one

Have you tried flip-flopping it a bit?

var newcurrentpageTemp = parseInt($(this).attr("id"));
newcurrentpageTemp++;
alert(newcurrentpageTemp));

Different ways of clearing lists

Doing alist = [] does not clear the list, just creates an empty list and binds it to the variable alist. The old list will still exist if it had other variable bindings.

To actually clear a list in-place, you can use any of these ways:

  1. alist.clear() # Python 3.3+, most obvious
  2. del alist[:]
  3. alist[:] = []
  4. alist *= 0 # fastest

See the Mutable Sequence Types documentation page for more details.

libxml/tree.h no such file or directory

You also need to add /usr/include/libxml2 to your include path.

ImportError: No module named xlsxwriter

Even if it looks like the module is installed, as far as Python is concerned it isn't since it throws that exception.

Try installing the module again using one of the installation methods shown in the XlsxWriter docs and look out for any installation errors.

If there are none then run a sample program like the following:

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write('A1', 'Hello world')

workbook.close()

git ignore vim temporary files

This is something that should only be done on a per-user basis, not per-repository. If Joe uses emacs, he will want to have emacs backup files ignored, but Betty (who uses vi) will want vi backup files ignored (in many cases, they are similar, but there are about 24,893 common editors in existence and it is pretty ridiculous to try to ignore all of the various backup extensions.)

In other words, do not put anything in .gitignore or in core.excludes in $GIT_DIR/config. Put the info in $HOME/.gitconfig instead (as nunopolonia suggests with --global.) Note that "global" means per-user, not per-system.

If you want configuration across the system for all users (which you don't), you'll need a different mechanism. (Possibly with templates setup prior to initialization of the repository.)

Maven Install on Mac OS X

for the ones that just migrated to mavericks - I used the *-ux solution;

  1. download maven from apache maven site
  2. put in /opt
  3. modified .bash_profile and added:

    alias mvn='/opt/apache-maven-3.1.1/bin/mvn'
    export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home
    

How to export a Hive table into a CSV file?

INSERT OVERWRITE LOCAL DIRECTORY '/home/lvermeer/temp' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' select * from table; 

is the correct answer.

If the number of records is really big, based on the number of files generated

the following command would give only partial result.

hive -e 'select * from some_table' > /home/yourfile.csv

How to config Tomcat to serve images from an external folder outside webapps?

Instead of configuring Tomcat to redirect requests, use Apache as a frontend with the Apache Tomcat connector so that Apache is only serving static content, while asking tomcat for dynamic content.

Using the JKmount directive (or others) you could specify exactly which requests are sent to Tomcat.

Requests for static content, such as images, would be served directly by Apache, using a standard virtual host configuration, while other requests, defined in the JKMount directive will be sent to Tomcat workers.

I think this implementation would give you the most flexibility and control on the overall application.

How to specify multiple conditions in an if statement in javascript

Here is an alternative way to do that.

const conditionsArray = [
    condition1, 
    condition2,
    condition3,
]

if (conditionsArray.indexOf(false) === -1) {
    "do somthing"
}

Or ES6

if (!conditionsArray.includes(false)) {
   "do somthing"
}

Get Date Object In UTC format in Java

In java 8 , It's really easy to get timestamp in UTC by using java 8 java.time.Instant library :

Instant.now();

That few word of code will return the UTC Timestamp.

How to set Sqlite3 to be case insensitive when string comparing?

Another option that may or may not make sense in your case, is to actually have a separate column with pre-lowerscored values of your existing column. This can be populated using the SQLite function LOWER(), and you can then perform matching on this column instead.

Obviously, it adds redundancy and a potential for inconsistency, but if your data is static it might be a suitable option.

How to rollback a specific migration?

If you want to rollback and migrate you can run:

rake db:migrate:redo

That's the same as:

rake db:rollback
rake db:migrate

What is the difference between exit and return?

I wrote two programs:

int main(){return 0;}

and

#include <stdlib.h>
int main(){exit(0)}

After executing gcc -S -O1. Here what I found watching at assembly (only important parts):

main:
    movl    $0, %eax    /* setting return value */
    ret                 /* return from main */

and

main:
    subq    $8, %rsp    /* reserving some space */
    movl    $0, %edi    /* setting return value */
    call    exit        /* calling exit function */
                        /* magic and machine specific wizardry after this call */

So my conclusion is: use return when you can, and exit() when you need.

How to convert date into this 'yyyy-MM-dd' format in angular 2

You can also use formatDate

let formattedDt = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ssZZZZZ', 'en_US')

It says that TypeError: document.getElementById(...) is null

Make sure the script is placed in the bottom of the BODY element of the document you're trying to manipulate, not in the HEAD element or placed before any of the elements you want to "get".

It does not matter if you import the script or if it's inline, the important thing is the placing. You don't have to put the command inside a function either; while it's good practice you can just call it directly, it works just fine.

How can I get the concatenation of two lists in Python without modifying either one?

Yes: list1 + list2. This gives a new list that is the concatenation of list1 and list2.

Difference between $.ajax() and $.get() and $.load()

The methods provide different layers of abstraction.

  • $.ajax() gives you full control over the Ajax request. You should use it if the other methods don't fullfil your needs.

  • $.get() executes an Ajax GET request. The returned data (which can be any data) will be passed to your callback handler.

  • $(selector).load() will execute an Ajax GET request and will set the content of the selected returned data (which should be either text or HTML).

It depends on the situation which method you should use. If you want to do simple stuff, there is no need to bother with $.ajax().

E.g. you won't use $.load(), if the returned data will be JSON which needs to be processed further. Here you would either use $.ajax() or $.get().

link_to image tag. how to add class to a tag

I tried this too, and works very well:

      <%= link_to home_index_path do %>
      <div class='logo-container'>
        <div class='logo'>
          <%= image_tag('bar.ico') %>
        </div>
        <div class='brand' style='font-size: large;'>
          .BAR
        </div>
      </div>
      <% end %>

Android - Handle "Enter" in an EditText

InputType on the textfield must be text in order for what CommonsWare said to work. Just tried all of this, no inputType before the trial and nothing worked, Enter kept registering as soft enter. After inputType = text, everything including the setImeLabel worked.

Example : android:inputType="text"

Conversion of a datetime2 data type to a datetime data type results out-of-range value

Sometimes EF does not know that is dealing with a computed column or a trigger. By design, those operations will set a value outside of EF after an insert.

The fix is to specify Computed in EF's edmx for that column in the StoreGeneratedPattern property.

For me it was when the column had a trigger which inserted the current date and time, see below in the third section.


Steps To Resolve

In Visual Studio open the Model Browser page then Model then Entity Types -> then

  1. Select the entity and the date time property
  2. Select StoreGeneratedPattern
  3. Set to Computed

EF Model Browser Model Entity Type dialog


For this situation other answers are workarounds, for the purpose of the column is to have a time/date specified when the record was created, and that is SQL's job to execute a trigger to add the correct time. Such as this SQL trigger:

DEFAULT (GETDATE()) FOR [DateCreated].

Fixed positioning in Mobile Safari

This is how i did it. I have a nav block that is below the header once you scroll the page down it 'sticks' to the top of the window. If you scroll back to top, nav goes back in it's place I use position:fixed in CSS for non mobile platforms and iOS5. Other Mobile versions do have that 'lag' until screen stops scrolling before it's set.

// css
#sticky.stick {
    width:100%;
    height:50px;
    position: fixed;
    top: 0;
    z-index: 1;
}

// jquery 
//sticky nav
    function sticky_relocate() {
      var window_top = $(window).scrollTop();
      var div_top = $('#sticky-anchor').offset().top;

      if (window_top > div_top)
        $('#sticky').addClass('stick');
      else
        $('#sticky').removeClass('stick');
     }

$(window).scroll(function(event){

    // sticky nav css NON mobile way
       sticky_relocate();

       var st = $(this).scrollTop();

    // sticky nav iPhone android mobile way iOS<5

       if (navigator.userAgent.match(/OS 5(_\d)+ like Mac OS X/i)) {
            //do nothing uses sticky_relocate() css
       } else if ( navigator.userAgent.match(/(iPod|iPhone|iPad)/i) || navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) ) {

            var window_top = $(window).scrollTop();
            var div_top = $('#sticky-anchor').offset().top;

            if (window_top > div_top) {
                $('#sticky').css({'top' : st  , 'position' : 'absolute' });
            } else {
                $('#sticky').css({'top' : 'auto' });
            }
        };

Maven: add a dependency to a jar by relative path

Basically, add this to the pom.xml:

...

<repositories>
   <repository>
       <id>lib_id</id>
       <url>file://${project.basedir}/lib</url>
   </repository>
</repositories>

...

<dependencies>
  ...
  <dependency>
      <groupId>com.mylibrary</groupId>
      <artifactId>mylibraryname</artifactId>
      <version>1.0.0</version>
  </dependency>
  ...
</dependencies>

DIV table colspan: how?

You can do this ( where data-x has the appropriate display:xxxx set ):

<!-- TH -->
<div data-tr>
    <div data-th style="width:25%">TH</div>
    <div data-th style="width:50%">

         <div data-table style="width:100%">
             <div data-tr>
                 <div data-th style="width:25%">TH</div>
                 <div data-th style="width:25%">TH</div>
                 <div data-th style="width:25%">TH</div>
                 <div data-th style="width:25%">TH</div>
             </div>
         </div>

    </div>
    <div data-th style="width:25%">TH</div>
</div>


<!-- TD -->
<div data-tr>
    <div data-td style="width:25%">TD</div>
    <div data-th style="width:50%">

         <div data-table style="width:100%">
             <div data-tr>
                 <div data-td style="width:25%">TD</div>
                 <div data-td style="width:25%">TD</div>
                 <div data-td style="width:25%">TD</div>
                 <div data-td style="width:25%">TD</div>
             </div>
             <div data-tr>
                 ...
             </div>
         </div>

    </div>
    <div data-td style="width:25%">TD</div>
</div>

CSS: fixed to bottom and centered

The problem lies in position: static. Static means don't do anyting at all with the position. position: absolute is what you want. Centering the element is still tricky though. The following should work:

#whatever {
  position: absolute;
  bottom: 0px;
  margin-right: auto;
  margin-left: auto;
  left: 0px;
  right: 0px;
}

or

#whatever {
  position: absolute;
  bottom: 0px;
  margin-right: auto;
  margin-left: auto;
  left: 50%;
  transform: translate(-50%, 0);
}

But I recommend the first method. I used centering techniques from this answer: How to center absolutely positioned element in div?

If (Array.Length == 0)

As other have already suggested it is likely you are getting a NullReferenceException which can be avoided by first checking to see if the reference is null. However, you need to ask yourself whether that check is actually warranted. Would you be doing it because the reference really might be null and it being null has a special meaning in your code? Or would you be doing it to cover up a bug? The nature of the question leads me to believe it would be the latter. In which case you really need to examine the code in depth and figure out why that reference did not get initialized properly in the first place.

How can I get the count of milliseconds since midnight for the current?

Do you mean?

long millis = System.currentTimeMillis() % 1000;

BTW Windows doesn't allow timetravel to 1969

C:\> date
Enter the new date: (dd-mm-yy) 2/8/1969
The system cannot accept the date entered.

Use Toast inside Fragment

As stated by alfo888_ibg:

@Override
public void onClick(View arg0) {
   Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show();
}

Just do:

    Toast.makeText(getActivity(),"Text!",Toast.LENGTH_SHORT).show();

this worked for me.

How do I use variables in Oracle SQL Developer?

Try this it will work, it's better create a procedure, if procedure is not possible you can use this script.

with param AS(
SELECT 1234 empid
FROM dual)
 SELECT *
  FROM Employees, param
  WHERE EmployeeID = param.empid;
END;

Custom Card Shape Flutter SDK

You can also customize the card theme globally with ThemeData.cardTheme:

MaterialApp(
  title: 'savvy',
  theme: ThemeData(
    cardTheme: CardTheme(
      shape: RoundedRectangleBorder(
        borderRadius: const BorderRadius.all(
          Radius.circular(8.0),
        ),
      ),
    ),
    // ...

How can I stop redis-server?

if you did make install (e.g ubuntu) while installing redis then you can do:

redis-cli shutdown

as pointed by @yojimbo87 :)

Setting max-height for table cell contents

Just put the labels in a div inside the TD and put the height and overflow.. like below.

<table>
<tr>
  <td><div style="height:40px; overflow:hidden">Sample</div></td>
  <td><div style="height:40px; overflow:hidden">Text</div></td>
  <td><div style="height:40px; overflow:hidden">Here</div></td>
</tr>
</table>

How to check db2 version

Another one in v11:

select CURRENT APPLICATION COMPATIBILITY from sysibm.sysdummy1

Result:

V11R1

It's not the current version, but the current configured level for the application.

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

If you want to show/hide an element based on the status of one {{expression}} you can use ng-switch:

<p ng-switch="foo.bar">I could be shown, or I could be hidden</p>

The paragraph will be displayed when foo.bar is true, hidden when false.

Update built-in vim on Mac OS X

A note to romainl's answer: aliases don't work together with sudo because only the first word is checked on aliases. To change this add another alias to your .profile / .bashrc:

alias sudo='sudo '

With this change sudo vim will behave as expected!

MongoDB running but can't connect using shell

I think there is some default config what is missing in this version of mongoDb client. Try to run:

mongo 127.0.0.1:27017

It's strange, but then I've experienced the issue went away :) (so the simple command 'mongo' w/o any params started to work again for me)

[Ubuntu Linux 11.10 x64 / MongoDB 2.0.1]

SQL GROUP BY CASE statement with aggregate function

While Shannon's answer is technically correct, it looks like overkill.

The simple solution is that you need to put your summation outside of the case statement. This should do the trick:

sum(CASE WHEN col1 > col2 THEN col3*col4 ELSE 0 END) AS some_product

Basically, your old code tells SQL to execute the sum(X*Y) for each line individually (leaving each line with its own answer that can't be grouped).

The code line I have written takes the sum product, which is what you want.

Are there any free Xml Diff/Merge tools available?

Pretty Diff tool was created with XML in mind. Just ensure you click the option for "markup".

http://prettydiff.com/

Select last N rows from MySQL

You can do it with a sub-query:

SELECT * FROM (
    SELECT * FROM table ORDER BY id DESC LIMIT 50
) sub
ORDER BY id ASC

This will select the last 50 rows from table, and then order them in ascending order.

Angular 4.3 - HttpClient set params

Since @MaciejTreder confirmed that we have to loop, here's a wrapper that will optionally let you add to a set of default params:

function genParams(params: object, httpParams = new HttpParams()): object {
    Object.keys(params)
        .filter(key => {
            let v = params[key];
            return (Array.isArray(v) || typeof v === 'string') ? 
                (v.length > 0) : 
                (v !== null && v !== undefined);
        })
        .forEach(key => {
            httpParams = httpParams.set(key, params[key]);
        });
    return { params: httpParams };
}

You can use it like so:

const OPTIONS = {
    headers: new HttpHeaders({
        'Content-Type': 'application/json'
    }),
    params: new HttpParams().set('verbose', 'true')
};
let opts = Object.assign({}, OPTIONS, genParams({ id: 1 }, OPTIONS.params));
this.http.get(BASE_URL, opts); // --> ...?verbose=true&id=1

C# DLL config file

As Marc says, this is not possible (although Visual Studio allows you to add an application configuration file in a class library project).

You might want to check out the AssemblySettings class which seems to make assembly config files possible.

NSCameraUsageDescription in iOS 10.0 runtime crash?

Use these raw values and copy in info.plist

    <key>NSCalendarsUsageDescription</key>
      <string>$(PRODUCT_NAME) calendar events</string>
    <key>NSRemindersUsageDescription</key>
      <string>$(PRODUCT_NAME) reminder use</string>
    <key>NSCameraUsageDescription</key>
      <string>This app requires to access your photo library to show image on profile and send via chat</string>
    <key>NSMicrophoneUsageDescription</key>
      <string>This app requires to access your microphone to record video with your voice send via chat</string>
    <key>NSPhotoLibraryUsageDescription</key>
      <string>This app requires to access your photo library to show image on profile and send via chat</string>
    <key>NSContactsUsageDescription</key>
       <string>$(PRODUCT_NAME) contact use</string>
    <key>NSLocationAlwaysUsageDescription</key>
      <string>$(PRODUCT_NAME) location use</string>
    <key>NSLocationWhenInUseUsageDescription</key>
      <string>$(PRODUCT_NAME) location use</string>

Fastest way to zero out a 2d array in C?

If you initialize the array with malloc, use calloc instead; it will zero your array for free. (Same perf obviously as memset, just less code for you.)

Is it possible to make Font Awesome icons larger than 'fa-5x'?

  1. Just add the font awesome class like this:

    class="fa fa-plus-circle fa-3x"
    

    (You can increase the size as per 5x, 7x, 9x..)

  2. You can also add custom CSS.

increase font size of hyperlink text html

You can do like this:

a {font-size: 100px}

Try avoid using font tag because it's deprecated. Use CSS like above instead. You can give your anchors specific class and apply any style for them.

git cherry-pick says "...38c74d is a merge but no -m option was given"

@Borealid's answer is correct, but suppose that you don't care about preserving the exact merging history of a branch and just want to cherry-pick a linearized version of it. Here's an easy and safe way to do that:

Starting state: you are on branch X, and you want to cherry-pick the commits Y..Z.

  1. git checkout -b tempZ Z
  2. git rebase Y
  3. git checkout -b newX X
  4. git cherry-pick Y..tempZ
  5. (optional) git branch -D tempZ

What this does is to create a branch tempZ based on Z, but with the history from Y onward linearized, and then cherry-pick that onto a copy of X called newX. (It's safer to do this on a new branch rather than to mutate X.) Of course there might be conflicts in step 4, which you'll have to resolve in the usual way (cherry-pick works very much like rebase in that respect). Finally it deletes the temporary tempZ branch.

If step 2 gives the message "Current branch tempZ is up to date", then Y..Z was already linear, so just ignore that message and proceed with steps 3 onward.

Then review newX and see whether that did what you wanted.

(Note: this is not the same as a simple git rebase X when on branch Z, because it doesn't depend in any way on the relationship between X and Y; there may be commits between the common ancestor and Y that you didn't want.)

How can I assign the output of a function to a variable using bash?

VAR=$(scan)

Exactly the same way as for programs.

How to change the interval time on bootstrap carousel?

       <div class="carousel-inner text-right">
                  <div class="carousel-item active text-center" id="first"  data-interval="1000" >
                    <img src="images/slide-1.gif" alt="slide-1">
                  </div>
                  <div class="carousel-item  text-center" id="second"  data-interval="2000" >
                    <img src="images/slide-2.gif" alt="slide-2">
                  </div>
                  <div class="carousel-item  text-center" id="third"  data-interval="3000" >
                    <img src="images/slide-3.gif" alt="slide-3">
                  </div>
                  <div class="carousel-item text-center" id="four"  data-interval="5000" >
                    <img src="images/slide-4.gif" alt="slide-4">
                  </div>
                </div>

You can also change different slides.

Appending the same string to a list of strings in Python

my_list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
my_new_list = [x + string for x in my_list]
print my_new_list

This will print:

['foobar', 'fobbar', 'fazbar', 'funkbar']

Why is textarea filled with mysterious white spaces?

Also, when you say that the cursor is in the "middle" of the textarea, it makes me think you could also either have extra padding or text-align: center defined somewhere in your CSS.

How to write one new line in Bitbucket markdown?

On Github, <p> and <br/>solves the problem.

<p>I want to this to appear in a new line. Introduces extra line above

or

<br/> another way

upgade python version using pip

Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.

Python Timezone conversion

To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():

time_in_new_timezone = time_in_old_timezone.astimezone(new_timezone)

Given aware_dt (a datetime object in some timezone), to convert it to other timezones and to print the times in a given time format:

#!/usr/bin/env python3
import pytz  # $ pip install pytz

time_format = "%Y-%m-%d %H:%M:%S%z"
tzids = ['Asia/Shanghai', 'Europe/London', 'America/New_York']
for tz in map(pytz.timezone, tzids):
    time_in_tz = aware_dt.astimezone(tz)
    print(f"{time_in_tz:{time_format}}")

If f"" syntax is unavailable, you could replace it with "".format(**vars())

where you could set aware_dt from the current time in the local timezone:

from datetime import datetime
import tzlocal  # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
aware_dt = datetime.now(local_timezone) # the current time

Or from the input time string in the local timezone:

naive_dt = datetime.strptime(time_string, time_format)
aware_dt = local_timezone.localize(naive_dt, is_dst=None)

where time_string could look like: '2016-11-19 02:21:42'. It corresponds to time_format = '%Y-%m-%d %H:%M:%S'.

is_dst=None forces an exception if the input time string corresponds to a non-existing or ambiguous local time such as during a DST transition. You could also pass is_dst=False, is_dst=True. See links with more details at Python: How do you convert datetime/timestamp from one timezone to another timezone?

How to hide image broken Icon using only CSS/HTML?

Missing images will either just display nothing, or display a [ ? ] style box when their source cannot be found. Instead you may want to replace that with a "missing image" graphic that you are sure exists so there is better visual feedback that something is wrong. Or, you might want to hide it entirely. This is possible, because images that a browser can't find fire off an "error" JavaScript event we can watch for.

    //Replace source
    $('img').error(function(){
            $(this).attr('src', 'missing.png');
    });

   //Or, hide them
   $("img").error(function(){
           $(this).hide();
   });

Additionally, you may wish to trigger some kind of Ajax action to send an email to a site admin when this occurs.

iTunes Connect: How to choose a good SKU?

The SKU example used in the documentation was to provide the allowed characters in a new user-specified SKU.

How to wrap text in textview in Android

Use app:breakStrategy="simple" in AppCompatTextView, it will control over paragraph layout.

It has three constant values

  • balanced
  • high_quality
  • simple

Designing in your TextView xml

<android.support.v7.widget.AppCompatTextView
        android:id="@+id/textquestion"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:scrollHorizontally="false"
        android:text="Your Question Display Hear....Your Question Display Hear....Your Question Display Hear....Your Question Display Hear...."
        android:textColor="@android:color/black"
        android:textSize="20sp"
        android:textStyle="bold"
        app:breakStrategy="simple" />

If your current minimum api level is 23 or more then in Coding

yourtextview.setBreakStrategy(Layout.BREAK_STRATEGY_SIMPLE);

For more refrence refer this BreakStrategy

Textview breakStrategy image

Loop in Jade (currently known as "Pug") template engine

Pug (renamed from 'Jade') is a templating engine for full stack web app development. It provides a neat and clean syntax for writing HTML and maintains strict whitespace indentation (like Python). It has been implemented with JavaScript APIs. The language mainly supports two iteration constructs: each and while. 'for' can be used instead 'each'. Kindly consult the language reference here:

https://pugjs.org/language/iteration.html

Here is one of my snippets: each/for iteration in pug_screenshot

How do I check if an HTML element is empty using jQuery?

!elt.hasChildNodes()

Yes, I know, this is not jQuery, so you could use this:

!$(elt)[0].hasChildNodes()

Happy now?

Using {% url ??? %} in django templates

Judging from your example, shouldn't it be {% url myproject.login.views.login_view %} and end of story? (replace myproject with your actual project name)

How to get the command line args passed to a running process on unix/linux systems?

try ps -n in a linux terminal. This will show:

1.All processes RUNNING, their command line and their PIDs

  1. The program intiate the processes.

Afterwards you will know which process to kill

How to compile makefile using MinGW?

I found a very good example here: https://bigcode.wordpress.com/2016/12/20/compiling-a-very-basic-mingw-windows-hello-world-executable-in-c-with-a-makefile/

It is a simple Hello.c (you can use c++ with g++ instead of gcc) using the MinGW on windows.

The Makefile looking like:

EXECUTABLE = src/Main.cpp

CC = "C:\MinGW\bin\g++.exe"
LDFLAGS = -lgdi32

src = $(wildcard *.cpp)
obj = $(src:.cpp=.o)

all: myprog

myprog: $(obj)
    $(CC) -o $(EXECUTABLE) $^ $(LDFLAGS)

.PHONY: clean
clean:
    del $(obj) $(EXECUTABLE)

Numpy, multiply array with scalar

You can multiply numpy arrays by scalars and it just works.

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

This is also a very fast and efficient operation. With your example:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])

Android layout replacing a view with another view on run time

private void replaceView(View oldV,View newV){
        ViewGroup par = (ViewGroup)oldV.getParent();
        if(par == null){return;}
        int i1 = par.indexOfChild(oldV);
        par.removeViewAt(i1);
        par.addView(newV,i1);
    }

php: loop through json array

Set the second function parameter to true if you require an associative array

Some versions of php require a 2nd paramter of true if you require an associative array

$json  = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );

SQL Server, division returns zero

Because it's an integer. You need to declare them as floating point numbers or decimals, or cast to such in the calculation.

Bootstrap 3: How to get two form inputs on one line and other inputs on individual lines?

You can wrap the inputs in col-* classes

<form name="registration_form" id="registration_form" class="form-horizontal">
     <div class="form-group">
           <div class="col-sm-6">
             <label for="firstname" class="sr-only"></label>
             <input id="firstname" class="form-control input-group-lg reg_name" type="text" name="firstname" title="Enter first name" placeholder="First name">
           </div>       
           <div class="col-sm-6">
             <label for="lastname" class="sr-only"></label>
             <input id="lastname" class="form-control input-group-lg reg_name" type="text" name="lastname" title="Enter last name" placeholder="Last name">
           </div>
    </div><!--/form-group-->

    <div class="form-group">
        <div class="col-sm-12">
          <label for="username" class="sr-only"></label>
          <input id="username" class="form-control input-group-lg" type="text" autocapitalize="off" name="username" title="Enter username" placeholder="Username">
        </div>
    </div><!--/form-group-->

    <div class="form-group">
        <div class="col-sm-12">
        <label for="password" class="sr-only"></label>
        <input id="password" class="form-control input-group-lg" type="password" name="password" title="Enter password" placeholder="Password">
        </div>
    </div><!--/form-group-->
 </form>

http://bootply.com/127825

Determining if Swift dictionary contains key and obtaining any of its values

Why not simply check for dict.keys.contains(key)? Checking for dict[key] != nil will not work in cases where the value is nil. As with a dictionary [String: String?] for example.

How to upload files on server folder using jsp

I found the similar problem and found the solution and i have blogged about how to upload the file using JSP , In that example i have used the absolute path. Note that if you want to route to some other URL based location you can put a ESB like WSO2 ESB

iOS: present view controller programmatically

If you're using a storyboard, you probably shouldn't be using alloc and init to create a new view controller. Instead, look at your storyboard and find the segue that you want to perform; it should have a unique identifier (and if not, you can set one in the right sidebar).

Once you've found the identifier for that segue, send your current view controller a -performSegueWithIdentifier:sender message:

[self performSegueWithIdentifier:@"mySegueIdentifier" sender:self];

This will cause the storyboard to instantiate an AddTaskViewController and present it in the way that you've defined for that segue.


If, on the other hand, you're not using a storyboard at all, then you need to give your AddTaskViewController some kind of user interface. The most common way of doing so is to initialize the controller with a nib: instead of just calling init, you'll call -initWithNibName:bundle: and provide the name of a .xib file that contains your add-task UI:

AddTaskViewController *add = [[AddTaskViewController alloc]
                              initWithNibName:@"AddTaskView" bundle:nil];
[self presentViewController:add animated:YES completion:nil];

(There are other (less common) ways of getting a view associated with your new view controller, but this will probably present you the least trouble to get working.)

How can I convert an Integer to localized month name in Java?

Kotlin Extension

fun Int.toMonthName(): String {
    return DateFormatSymbols().months[this]
}

Usage

calendar.get(Calendar.MONTH).toMonthName()

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

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

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

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

How to vertically center an image inside of a div element in HTML using CSS?

Have you tried setting margin on the div? e.g.

div {
    padding: 25px, 0
}

for top and bottom. You may also be able to use a percentage:

div {
    padding: 25%, 0
}

How can I send and receive WebSocket messages on the server side?

In addition to the PHP frame encoding function, here follows a decode function:

function Decode($M){
    $M = array_map("ord", str_split($M));
    $L = $M[1] AND 127;

    if ($L == 126)
        $iFM = 4;
    else if ($L == 127)
        $iFM = 10;
    else
        $iFM = 2;

    $Masks = array_slice($M, $iFM, 4);

    $Out = "";
    for ($i = $iFM + 4, $j = 0; $i < count($M); $i++, $j++ ) {
        $Out .= chr($M[$i] ^ $Masks[$j % 4]);
    }
    return $Out;
}

I've implemented this and also other functions in an easy-to-use WebSocket PHP class here.

Make xargs execute the command once for each line of input

If you want to run the command for every line (i.e. result) coming from find, then what do you need the xargs for?

Try:

find path -type f -exec your-command {} \;

where the literal {} gets substituted by the filename and the literal \; is needed for find to know that the custom command ends there.

EDIT:

(after the edit of your question clarifying that you know about -exec)

From man xargs:

-L max-lines
Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x.

Note that filenames ending in blanks would cause you trouble if you use xargs:

$ mkdir /tmp/bax; cd /tmp/bax
$ touch a\  b c\  c
$ find . -type f -print | xargs -L1 wc -l
0 ./c
0 ./c
0 total
0 ./b
wc: ./a: No such file or directory

So if you don't care about the -exec option, you better use -print0 and -0:

$ find . -type f -print0 | xargs -0L1 wc -l
0 ./c
0 ./c
0 ./b
0 ./a

SQL changing a value to upper or lower case

LCASE or UCASE respectively.

Example:

SELECT UCASE(MyColumn) AS Upper, LCASE(MyColumn) AS Lower
FROM MyTable

Excel VBA date formats

It's important to distinguish between the content of cells, their display format, the data type read from cells by VBA, and the data type written to cells from VBA and how Excel automatically interprets this. (See e.g. this previous answer.) The relationship between these can be a bit complicated, because Excel will do things like interpret values of one type (e.g. string) as being a certain other data type (e.g. date) and then automatically change the display format based on this. Your safest bet it do everything explicitly and not to rely on this automatic stuff.

I ran your experiment and I don't get the same results as you do. My cell A1 stays a Date the whole time, and B1 stays 41575. So I can't answer your question #1. Results probably depend on how your Excel version/settings choose to automatically detect/change a cell's number format based on its content.

Question #2, "How can I ensure that a cell will return a date value": well, not sure what you mean by "return" a date value, but if you want it to contain a numerical value that is displayed as a date, based on what you write to it from VBA, then you can either:

  • Write to the cell a string value that you hope Excel will automatically interpret as a date and format as such. Cross fingers. Obviously this is not very robust. Or,

  • Write a numerical value to the cell from VBA (obviously a Date type is the intended type, but an Integer, Long, Single, or Double could do as well) and explicitly set the cells' number format to your desired date format using the .NumberFormat property (or manually in Excel). This is much more robust.

If you want to check that existing cell contents can be displayed as a date, then here's a function that will help:

Function CellContentCanBeInterpretedAsADate(cell As Range) As Boolean
    Dim d As Date
    On Error Resume Next
    d = CDate(cell.Value)
    If Err.Number <> 0 Then
        CellContentCanBeInterpretedAsADate = False
    Else
        CellContentCanBeInterpretedAsADate = True
    End If
    On Error GoTo 0
End Function

Example usage:

Dim cell As Range
Set cell = Range("A1")

If CellContentCanBeInterpretedAsADate(cell) Then
    cell.NumberFormat = "mm/dd/yyyy hh:mm"
Else
    cell.NumberFormat = "General"
End If

How do I post button value to PHP?

    $restore = $this->createElement('submit', 'restore', array(
        'label' => 'FILE_RESTORE',
        'class' => 'restore btn btn-small btn-primary',
        'attribs' => array(
            'onClick' => 'restoreCheck();return false;'
        )
    ));

Properties private set;

This is one possible solution although not very clean:

  1. Make the property you need to expose to BAL & DAL internal
  2. Mark BAL.dll & DAL.dll Internal Visible in assemblyinfo.cs

public class Person
{
    public Person(int id)
    {
         this.Id=id;
    }

    public string Name { get;  set; }
    public int Id { get; internal set; }
    public int Age { get; set; }
}

AssemblyInfo.cs for Entities.dll

[assembly: InternalsVisibleTo("DAL"), InternalsVisibleTo("BAL")]

That way all your internals will be visible to DAL & BAL. This may not be desirable but I'm just suggesting one possible solution.

Change input text border color without changing its height

Try this

<input type="text"/>

It will display same in all cross browser like mozilla , chrome and internet explorer.

<style>
    input{
       border:2px solid #FF0000;
    }
</style>

Dont add style inline because its not good practise, use class to add style for your input box.

Creating a list of objects in Python

I think this simply demonstrates what you are trying to achieve:

# coding: utf-8

class Class():
    count = 0
    names = []

    def __init__(self,name):
        self.number = Class.count
        self.name = name
        Class.count += 1
        Class.names.append(name)

l=[]
l.append(Class("uno"))
l.append(Class("duo"))
print l
print l[0].number, l[0].name
print l[1].number, l[1].name
print Class.count, Class.names

Run the code above and you get:-

[<__main__.Class instance at 0x6311b2c>, 
<__main__.Class instance at 0x63117ec>]
0 uno
1 duo
2 ['uno', 'duo']

How do I find the version of Apache running without access to the command line?

Simply use something like the following - the string should be there already:

<?php
   if(isset($_SERVER['SERVER_SOFTWARE'])){
      echo $_SERVER['SERVER_SOFTWARE'];
   }
?>

Import error: No module name urllib2

As stated in the urllib2 documentation:

The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

So you should instead be saying

from urllib.request import urlopen
html = urlopen("http://www.google.com/").read()
print(html)

Your current, now-edited code sample is incorrect because you are saying urllib.urlopen("http://www.google.com/") instead of just urlopen("http://www.google.com/").

Kill python interpeter in linux from the terminal

There's a rather crude way of doing this, but be careful because first, this relies on python interpreter process identifying themselves as python, and second, it has the concomitant effect of also killing any other processes identified by that name.

In short, you can kill all python interpreters by typing this into your shell (make sure you read the caveats above!):

ps aux | grep python | grep -v "grep python" | awk '{print $2}' | xargs kill -9

To break this down, this is how it works. The first bit, ps aux | grep python | grep -v "grep python", gets the list of all processes calling themselves python, with the grep -v making sure that the grep command you just ran isn't also included in the output. Next, we use awk to get the second column of the output, which has the process ID's. Finally, these processes are all (rather unceremoniously) killed by supplying each of them with kill -9.

"for loop" with two variables?

for (i,j) in [(i,j) for i in range(x) for j in range(y)]

should do it.

How to get docker-compose to always re-create containers from fresh images?

docker-compose up --build

OR

docker-compose build --no-cache

Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

A rather separable way of doing this is to use

import tensorflow as tf
from keras import backend as K

num_cores = 4

if GPU:
    num_GPU = 1
    num_CPU = 1
if CPU:
    num_CPU = 1
    num_GPU = 0

config = tf.ConfigProto(intra_op_parallelism_threads=num_cores,
                        inter_op_parallelism_threads=num_cores, 
                        allow_soft_placement=True,
                        device_count = {'CPU' : num_CPU,
                                        'GPU' : num_GPU}
                       )

session = tf.Session(config=config)
K.set_session(session)

Here, with booleans GPU and CPU, we indicate whether we would like to run our code with the GPU or CPU by rigidly defining the number of GPUs and CPUs the Tensorflow session is allowed to access. The variables num_GPU and num_CPU define this value. num_cores then sets the number of CPU cores available for usage via intra_op_parallelism_threads and inter_op_parallelism_threads.

The intra_op_parallelism_threads variable dictates the number of threads a parallel operation in a single node in the computation graph is allowed to use (intra). While the inter_ops_parallelism_threads variable defines the number of threads accessible for parallel operations across the nodes of the computation graph (inter).

allow_soft_placement allows for operations to be run on the CPU if any of the following criterion are met:

  1. there is no GPU implementation for the operation

  2. there are no GPU devices known or registered

  3. there is a need to co-locate with other inputs from the CPU

All of this is executed in the constructor of my class before any other operations, and is completely separable from any model or other code I use.

Note: This requires tensorflow-gpu and cuda/cudnn to be installed because the option is given to use a GPU.

Refs:

Fatal Error :1:1: Content is not allowed in prolog

The real solution that I found for this issue was by disabling any XML Format post processors. I have added a post processor called "jp@gc - XML Format Post Processor" and started noticing the error "Fatal Error :1:1: Content is not allowed in prolog"

By disabling the post processor had stopped throwing those errors.

How can I hash a password in Java?

As of 2020, the most reliable password hashing algorithm in use, most likely to optimise its strength given any hardware, is Argon2id or Argon2i but not its Spring implementation.

The PBKDF2 standard includes the the CPU-greedy/computationally-expensive feature of the block cipher BCRYPT algo, and add its stream cipher capability. PBKDF2 was overwhelmed by the memory exponentially-greedy SCRYPT then by the side-channel-attack-resistant Argon2

Argon2 provides the necessary calibration tool to find optimized strength parameters given a target hashing time and the hardware used.

  • Argon2i is specialized in memory greedy hashing
  • Argon2d is specialized in CPU greedy hashing
  • Argon2id use both methods.

Memory greedy hashing would help against GPU use for cracking.

Spring security/Bouncy Castle implementation is not optimized and relatively week given what attacker could use. cf: Spring doc Argon2 and Scrypt

The currently implementation uses Bouncy castle which does not exploit parallelism/optimizations that password crackers will, so there is an unnecessary asymmetry between attacker and defender.

The most credible implementation in use for java is mkammerer's one,

a wrapper jar/library of the official native implementation written in C.

It is well written and simple to use.

The embedded version provides native builds for Linux, windows and OSX.

As an example, it is used by jpmorganchase in its tessera security project used to secure Quorum, its Ethereum cryptocurency implementation.

Here is an example:

    final char[] password = "a4e9y2tr0ngAnd7on6P১M°RD".toCharArray();
    byte[] salt = new byte[128];
    new SecureRandom().nextBytes(salt);
    final Argon2Advanced argon2 = Argon2Factory.createAdvanced(Argon2Factory.Argon2Types.ARGON2id);
    byte[] hash = argon2.rawHash(10, 1048576, 4, password, salt);

(see tessera)

Declare the lib in your POM:

<dependency>
    <groupId>de.mkammerer</groupId>
    <artifactId>argon2-jvm</artifactId>
    <version>2.7</version>
</dependency>

or with gradle:

compile 'de.mkammerer:argon2-jvm:2.7'

Calibration may be performed using de.mkammerer.argon2.Argon2Helper#findIterations

SCRYPT and Pbkdf2 algorithm might also be calibrated by writing some simple benchmark, but current minimal safe iterations values, will require higher hashing times.

getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

Override service method like this:

protected void service(HttpServletRequest request, HttpServletResponse   response) throws ServletException, IOException {
        doPost(request, response);
}

And Voila!

CSS background image alt attribute

It''s not clear to me what you want.

If you want a CSS property to render the alt attribute value, then perhaps you're looking for the CSS attribute function for example:

IMG:before { content: attr(alt) }

If you want to put the alt attribute on a background image, then ... that's odd because the alt attribute is an HTML attribute whereas the background image is a CSS property. If you want to use the HTML alt attribute then I think you'd need a corresponding HTML element to put it in.

Why do you "need to use alt tags on background images": is this for a semantic reason or for some visual-effect reason (and if so, then what effect or what reason)?

How to prevent Screen Capture in Android

Just add this line:

getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);

Before your setContentView() method.

Is there a way to take the first 1000 rows of a Spark Dataframe?

The method you are looking for is .limit.

Returns a new Dataset by taking the first n rows. The difference between this function and head is that head returns an array while limit returns a new Dataset.

Example usage:

df.limit(1000)

What is secret key for JWT based authentication and how to generate it?

You can write your own generator. The secret key is essentially a byte array. Make sure that the string that you convert to a byte array is base64 encoded.

In Java, you could do something like this.

String key = "random_secret_key";
String base64Key = DatatypeConverter.printBase64Binary(key.getBytes());
byte[] secretBytes = DatatypeConverter.parseBase64Binary(base64Key);

How do you scroll up/down on the console of a Linux VM

Fn + Up/Down can scroll Terminal in Mac OS X 10.11

How to set the default value of an attribute on a Laravel model

You can set Default attribute in Model also>

protected $attributes = [
        'status' => self::STATUS_UNCONFIRMED,
        'role_id' => self::ROLE_PUBLISHER,
    ];

You can find the details in these links

1.) How to set a default attribute value for a Laravel / Eloquent model?

2.) https://laracasts.com/index.php/discuss/channels/eloquent/eloquent-help-generating-attribute-values-before-creating-record


You can also Use Accessors & Mutators for this You can find the details in the Laravel documentation 1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators

2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators

3.) Universal accessors and mutators in Laravel 4

Editing hosts file to redirect url?

hosts file:

1.2.3.4 google.com

1.2.3.4 - ip of your server.

Run script on the server for redirecting users to url that you want.

How do I create a right click context menu in Java Swing?

The following code implements a default context menu known from Windows with copy, cut, paste, select all, undo and redo functions. It also works on Linux and Mac OS X:

import javax.swing.*;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class DefaultContextMenu extends JPopupMenu
{
    private Clipboard clipboard;

    private UndoManager undoManager;

    private JMenuItem undo;
    private JMenuItem redo;
    private JMenuItem cut;
    private JMenuItem copy;
    private JMenuItem paste;
    private JMenuItem delete;
    private JMenuItem selectAll;

    private JTextComponent textComponent;

    public DefaultContextMenu()
    {
        undoManager = new UndoManager();
        clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

        addPopupMenuItems();
    }

    private void addPopupMenuItems()
    {
        undo = new JMenuItem("Undo");
        undo.setEnabled(false);
        undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        undo.addActionListener(event -> undoManager.undo());
        add(undo);

        redo = new JMenuItem("Redo");
        redo.setEnabled(false);
        redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        redo.addActionListener(event -> undoManager.redo());
        add(redo);

        add(new JSeparator());

        cut = new JMenuItem("Cut");
        cut.setEnabled(false);
        cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        cut.addActionListener(event -> textComponent.cut());
        add(cut);

        copy = new JMenuItem("Copy");
        copy.setEnabled(false);
        copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        copy.addActionListener(event -> textComponent.copy());
        add(copy);

        paste = new JMenuItem("Paste");
        paste.setEnabled(false);
        paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        paste.addActionListener(event -> textComponent.paste());
        add(paste);

        delete = new JMenuItem("Delete");
        delete.setEnabled(false);
        delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        delete.addActionListener(event -> textComponent.replaceSelection(""));
        add(delete);

        add(new JSeparator());

        selectAll = new JMenuItem("Select All");
        selectAll.setEnabled(false);
        selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        selectAll.addActionListener(event -> textComponent.selectAll());
        add(selectAll);
    }

    private void addTo(JTextComponent textComponent)
    {
        textComponent.addKeyListener(new KeyAdapter()
        {
            @Override
            public void keyPressed(KeyEvent pressedEvent)
            {
                if ((pressedEvent.getKeyCode() == KeyEvent.VK_Z)
                        && ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
                {
                    if (undoManager.canUndo())
                    {
                        undoManager.undo();
                    }
                }

                if ((pressedEvent.getKeyCode() == KeyEvent.VK_Y)
                        && ((pressedEvent.getModifiersEx() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0))
                {
                    if (undoManager.canRedo())
                    {
                        undoManager.redo();
                    }
                }
            }
        });

        textComponent.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mousePressed(MouseEvent releasedEvent)
            {
                handleContextMenu(releasedEvent);
            }

            @Override
            public void mouseReleased(MouseEvent releasedEvent)
            {
                handleContextMenu(releasedEvent);
            }
        });

        textComponent.getDocument().addUndoableEditListener(event -> undoManager.addEdit(event.getEdit()));
    }

    private void handleContextMenu(MouseEvent releasedEvent)
    {
        if (releasedEvent.getButton() == MouseEvent.BUTTON3)
        {
            processClick(releasedEvent);
        }
    }

    private void processClick(MouseEvent event)
    {
        textComponent = (JTextComponent) event.getSource();
        textComponent.requestFocus();

        boolean enableUndo = undoManager.canUndo();
        boolean enableRedo = undoManager.canRedo();
        boolean enableCut = false;
        boolean enableCopy = false;
        boolean enablePaste = false;
        boolean enableDelete = false;
        boolean enableSelectAll = false;

        String selectedText = textComponent.getSelectedText();
        String text = textComponent.getText();

        if (text != null)
        {
            if (text.length() > 0)
            {
                enableSelectAll = true;
            }
        }

        if (selectedText != null)
        {
            if (selectedText.length() > 0)
            {
                enableCut = true;
                enableCopy = true;
                enableDelete = true;
            }
        }

        if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor) && textComponent.isEnabled())
        {
            enablePaste = true;
        }

        undo.setEnabled(enableUndo);
        redo.setEnabled(enableRedo);
        cut.setEnabled(enableCut);
        copy.setEnabled(enableCopy);
        paste.setEnabled(enablePaste);
        delete.setEnabled(enableDelete);
        selectAll.setEnabled(enableSelectAll);

        // Shows the popup menu
        show(textComponent, event.getX(), event.getY());
    }

    public static void addDefaultContextMenu(JTextComponent component)
    {
        DefaultContextMenu defaultContextMenu = new DefaultContextMenu();
        defaultContextMenu.addTo(component);
    }
}

Usage:

JTextArea textArea = new JTextArea();
DefaultContextMenu.addDefaultContextMenu(textArea);

Now the textArea will have a context menu when it is right-clicked on.

Show data on mouseover of circle

There is an awesome library for doing that that I recently discovered. It's simple to use and the result is quite neat: d3-tip.

You can see an example here:

enter image description here

Basically, all you have to do is to download(index.js), include the script:

<script src="index.js"></script>

and then follow the instructions from here (same link as example)

But for your code, it would be something like:

define the method:

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<strong>Frequency:</strong> <span style='color:red'>" + d.frequency + "</span>";
  })

create your svg (as you already do)

var svg = ...

call the method:

svg.call(tip);

add tip to your object:

vis.selectAll("circle")
   .data(datafiltered).enter().append("svg:circle")
...
   .on('mouseover', tip.show)
   .on('mouseout', tip.hide)

Don't forget to add the CSS:

<style>
.d3-tip {
  line-height: 1;
  font-weight: bold;
  padding: 12px;
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  border-radius: 2px;
}

/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
  box-sizing: border-box;
  display: inline;
  font-size: 10px;
  width: 100%;
  line-height: 1;
  color: rgba(0, 0, 0, 0.8);
  content: "\25BC";
  position: absolute;
  text-align: center;
}

/* Style northward tooltips differently */
.d3-tip.n:after {
  margin: -1px 0 0 0;
  top: 100%;
  left: 0;
}
</style>

How to use multiprocessing queue in Python?

in "from queue import Queue" there is no module called queue, instead multiprocessing should be used. Therefore, it should look like "from multiprocessing import Queue"

How to filter input type="file" dialog by specific file type?

See http://www.w3schools.com/tags/att_input_accept.asp:

The accept attribute is supported in all major browsers, except Internet Explorer and Safari. Definition and Usage

The accept attribute specifies the types of files that the server accepts (that can be submitted through a file upload).

Note: The accept attribute can only be used with <input type="file">.

Tip: Do not use this attribute as a validation tool. File uploads should be validated on the server.

Syntax <input accept="audio/*|video/*|image/*|MIME_type" />

Tip: To specify more than one value, separate the values with a comma (e.g. <input accept="audio/*,video/*,image/*" />.

How to change JDK version for an Eclipse project

Click on the Window tab in Eclipse, go to Preferences and when that window comes up, go to Java ? Installed JREs ? Execution Environment and choose JavaSE-1.5. You then have to go to Compiler and set the Compiler compliance level.

Changing JRE

Enter image description here

@import vs #import - iOS 7

It seems that since XCode 7.x a lot of warnings are coming out when enabling clang module with CLANG_ENABLE_MODULES

Take a look at Lots of warnings when building with Xcode 7 with 3rd party libraries

When to use HashMap over LinkedList or ArrayList and vice-versa

Lists and Maps are different data structures. Maps are used for when you want to associate a key with a value and Lists are an ordered collection.

Map is an interface in the Java Collection Framework and a HashMap is one implementation of the Map interface. HashMap are efficient for locating a value based on a key and inserting and deleting values based on a key. The entries of a HashMap are not ordered.

ArrayList and LinkedList are an implementation of the List interface. LinkedList provides sequential access and is generally more efficient at inserting and deleting elements in the list, however, it is it less efficient at accessing elements in a list. ArrayList provides random access and is more efficient at accessing elements but is generally slower at inserting and deleting elements.

How do I send a JSON string in a POST request in Go

you can just use post to post your json.

values := map[string]string{"username": username, "password": password}

jsonValue, _ := json.Marshal(values)

resp, err := http.Post(authAuthenticatorUrl, "application/json", bytes.NewBuffer(jsonValue))

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

To add to the valuable content, I would like to create this reminder on why sometimes RegEx within VBA is not ideal. Not all expressions are supported, but instead may throw an Error 5017 and may leave the author guessing (which I am a victim of myself).

Whilst we can find some sources on what is supported, it would be helpfull to know which metacharacters etc. are not supported. A more in-depth explaination can be found here. Mentioned in this source:

"Although "VBScript’s regular expression ... version 5.5 implements quite a few essential regex features that were missing in previous versions of VBScript. ... JavaScript and VBScript implement Perl-style regular expressions. However, they lack quite a number of advanced features available in Perl and other modern regular expression flavors:"


So, not supported are:

  • Start of String ancor \A, alternatively use the ^ caret to match postion before 1st char in string
  • End of String ancor \Z, alternatively use the $ dollar sign to match postion after last char in string
  • Positive LookBehind, e.g.: (?<=a)b (whilst postive LookAhead is supported)
  • Negative LookBehind, e.g.: (?<!a)b (whilst negative LookAhead is supported)
  • Atomic Grouping
  • Possessive Quantifiers
  • Unicode e.g.: \{uFFFF}
  • Named Capturing Groups. Alternatively use Numbered Capturing Groups
  • Inline modifiers, e.g.: /i (case sensitivity) or /g (global) etc. Set these through the RegExp object properties > RegExp.Global = True and RegExp.IgnoreCase = True if available.
  • Conditionals
  • Regular Expression Comments. Add these with regular ' comments in script

I already hit a wall more than once using regular expressions within VBA. Usually with LookBehind but sometimes I even forget the modifiers. I have not experienced all these above mentioned backdrops myself but thought I would try to be extensive referring to some more in-depth information. Feel free to comment/correct/add. Big shout out to regular-expressions.info for a wealth of information.

P.S. You have mentioned regular VBA methods and functions, and I can confirm they (at least to myself) have been helpful in their own ways where RegEx would fail.

Oracle Differences between NVL and Coalesce

There is also difference is in plan handling.

Oracle is able form an optimized plan with concatenation of branch filters when search contains comparison of nvl result with an indexed column.

create table tt(a, b) as
select level, mod(level,10)
from dual
connect by level<=1e4;

alter table tt add constraint ix_tt_a primary key(a);
create index ix_tt_b on tt(b);

explain plan for
select * from tt
where a=nvl(:1,a)
  and b=:2;

explain plan for
select * from tt
where a=coalesce(:1,a)
  and b=:2;

nvl:

-----------------------------------------------------------------------------------------
| Id  | Operation                     | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT              |         |     2 |    52 |     2   (0)| 00:00:01 |
|   1 |  CONCATENATION                |         |       |       |            |          |
|*  2 |   FILTER                      |         |       |       |            |          |
|*  3 |    TABLE ACCESS BY INDEX ROWID| TT      |     1 |    26 |     1   (0)| 00:00:01 |
|*  4 |     INDEX RANGE SCAN          | IX_TT_B |     7 |       |     1   (0)| 00:00:01 |
|*  5 |   FILTER                      |         |       |       |            |          |
|*  6 |    TABLE ACCESS BY INDEX ROWID| TT      |     1 |    26 |     1   (0)| 00:00:01 |
|*  7 |     INDEX UNIQUE SCAN         | IX_TT_A |     1 |       |     1   (0)| 00:00:01 |
-----------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------
   2 - filter(:1 IS NULL)
   3 - filter("A" IS NOT NULL)
   4 - access("B"=TO_NUMBER(:2))
   5 - filter(:1 IS NOT NULL)
   6 - filter("B"=TO_NUMBER(:2))
   7 - access("A"=:1)

coalesce:

---------------------------------------------------------------------------------------
| Id  | Operation                   | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT            |         |     1 |    26 |     1   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS BY INDEX ROWID| TT      |     1 |    26 |     1   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN          | IX_TT_B |    40 |       |     1   (0)| 00:00:01 |
---------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("A"=COALESCE(:1,"A"))
   2 - access("B"=TO_NUMBER(:2))

Credits go to http://www.xt-r.com/2012/03/nvl-coalesce-concatenation.html.

Is there a way to catch the back button event in javascript?

I have created a solution which may be of use to some people. Simply include the code on your page, and you can write your own function that will be called when the back button is clicked.

I have tested in IE, FF, Chrome, and Safari, and are all working. The solution I have works based on iframes without the need for constant polling, in IE and FF, however, due to limitations in other browsers, the location hash is used in Safari.

Change color of bootstrap navbar on hover link?

Use Come thing link this , This is Based on Bootstrap 3.0

.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:hover, .navbar-default .navbar-nav > .active > a:focus {
    background-color: #977EBD;
    color: #FFFFFF;
}

.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
    background-color: #977EBD;
    color: #FFFFFF;
}

What is the simplest way to SSH using Python?

This worked for me

import subprocess
import sys
HOST="IP"
COMMAND="ifconfig"

def passwordless_ssh(HOST):
        ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
                       shell=False,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
        result = ssh.stdout.readlines()
        if result == []:
                error = ssh.stderr.readlines()
                print >>sys.stderr, "ERROR: %s" % error
                return "error"
        else:
                return result

Detecting when the 'back' button is pressed on a navbar

(SWIFT)

finaly found solution.. method we were looking for is "willShowViewController" which is delegate method of UINavigationController

//IMPORT UINavigationControllerDelegate !!
class PushedController: UIViewController, UINavigationControllerDelegate {

    override func viewDidLoad() {
        //set delegate to current class (self)
        navigationController?.delegate = self
    }

    func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
        //MyViewController shoud be the name of your parent Class
        if var myViewController = viewController as? MyViewController {
            //YOUR STUFF
        }
    }
}

Changing SVG image color with javascript

If it is just about the color and there is no specific need for JavaScript, you could also convert them to a font. This link gives you an opportunity to create a font based on the SVG. However, it is not possible to use img attributes afterwards - like "alt". This also limits the accessibility of your website for blind people and so on.

Replace multiple characters in one replace call

_x000D_
_x000D_
String.prototype.replaceAll=function(obj,keydata='key'){
 const keys=keydata.split('key');
return Object.entries(obj).reduce((a,[key,val])=> a.replace(new RegExp(`${keys[0]}${key}${keys[1]}`,'g'),val),this)
}

const data='hids dv sdc sd {yathin} {ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'{key}'))
_x000D_
_x000D_
_x000D_

String.prototype.replaceAll=function(keydata,obj){ const keys=keydata.split('key'); return Object.entries(obj).reduce((a,[key,val])=> a.replace(${keys[0]}${key}${keys[1]},val),this) }

const data='hids dv sdc sd ${yathin} ${ok}' console.log(data.replaceAll('${key}',{yathin:12,ok:'hi'}))

Android Studio gradle takes too long to build

The second thing i did was Uninstall my Anti-Virus software (AVG Antivirus) {sounds crazy but, i had to}. it reduced gradle build time upto 40%

The first thing i did was enable offline mode (1. click on Gradle usually on the right side of the editor 2. click on the connection button to toggle) it reduced the gradle build time for upto 20%

so my Gradle build time was reduced for upto 60% by doing these two things