Programs & Examples On #Addeventlistener

a DOM event method that adds an event listener to a given DOM node

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

Solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

ready docs

addEventListener vs onclick

It should also be possible to either extend the listener by prototyping it (if we have a reference to it and its not an anonymous function) -or make the onclick call a call to a function library (a function calling other functions).

Like:

elm.onclick = myFunctionList;
function myFunctionList(){
    myFunc1();
    myFunc2();
}

This means we never have to change the onclick call just alter the function myFunctionList() to do whatever we want, but this leaves us without control of bubbling/catching phases so should be avoided for newer browsers.

addEventListener in Internet Explorer

addEventListener is the proper DOM method to use for attaching event handlers.

Internet Explorer (up to version 8) used an alternate attachEvent method.

Internet Explorer 9 supports the proper addEventListener method.

The following should be an attempt to write a cross-browser addEvent function.

function addEvent(evnt, elem, func) {
   if (elem.addEventListener)  // W3C DOM
      elem.addEventListener(evnt,func,false);
   else if (elem.attachEvent) { // IE DOM
      elem.attachEvent("on"+evnt, func);
   }
   else { // No much to do
      elem["on"+evnt] = func;
   }
}

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

this happened again around last quarter of 2017 . greasemonkey firing too late . after domcontentloaded event already been fired.

what to do:

  • i used @run-at document-start instead of document-end
  • updated firefox to 57.

from : https://github.com/greasemonkey/greasemonkey/issues/2769

Even as a (private) script writer I'm confused why my script isn't working.

The most likely problem is that the 'DOMContentLoaded' event is fired before the script is run. Now before you come back and say @run-at document-start is set, that directive isn't fully supported at the moment. Due to the very asynchronous nature of WebExtensions there's little guarantee on when something will be executed. When FF59 rolls around we'll have #2663 which will help. It'll actually help a lot of things, debugging too.

How to remove all listeners in an element?

I think that the fastest way to do this is to just clone the node, which will remove all event listeners:

var old_element = document.getElementById("btn");
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);

Just be careful, as this will also clear event listeners on all child elements of the node in question, so if you want to preserve that you'll have to resort to explicitly removing listeners one at a time.

Adding click event handler to iframe

You can use closures to pass parameters:

iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);

However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):

document.getElementById("myFrame").contentDocument.addEventListener(...);

Dynamically add event listener

Here's my workaround:

I created a library with Angular 6. I added a common component commonlib-header which is used like this in an external application.

Note the serviceReference which is the class (injected in the component constructor(public serviceReference: MyService) that uses the commonlib-header) that holds the stringFunctionName method:

<commonlib-header
    [logo]="{ src: 'assets/img/logo.svg', alt: 'Logo', href: '#' }"
    [buttons]="[{ index: 0, innerHtml: 'Button', class: 'btn btn-primary', onClick: [serviceReference, 'stringFunctionName', ['arg1','arg2','arg3']] }]">
    </common-header>

The library component is programmed like this. The dynamic event is added in the onClick(fn: any) method:

export class HeaderComponent implements OnInit {

 _buttons: Array<NavItem> = []

 @Input()
  set buttons(buttons: Array<any>) {
    buttons.forEach(navItem => {
      let _navItem = new NavItem(navItem.href, navItem.innerHtml)

      _navItem.class = navItem.class

      _navItem.onClick = navItem.onClick // this is the array from the component @Input properties above

      this._buttons[navItem.index] = _navItem
    })
  }

  constructor() {}

  ngOnInit() {}

  onClick(fn: any){
    let ref = fn[0]
    let fnName = fn[1]
    let args = fn[2]

    ref[fnName].apply(ref, args)
  }

The reusable header.component.html:

<div class="topbar-right">
  <button *ngFor="let btn of _buttons"
    class="{{ btn.class }}"
    (click)="onClick(btn.onClick)"
    [innerHTML]="btn.innerHtml | keepHtml"></button>
</div>

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

Mozila Firefox says that onreadystatechange is an alternative to DOMContentLoaded.

// alternative to DOMContentLoaded
document.onreadystatechange = function () {
    if (document.readyState == "complete") {
        initApplication();
    }
}

In DOMContentLoaded the Mozila's doc says:

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

I think load event should be used for a full document+resources loading.

How to check whether dynamically attached event listener exists or not?

You could always check manually if your EventListener exist using Chrome inspector for example. In Element tab you have the traditional "Styles" subtab and close to it another one : "Event Listeners". Which will give you the list of all EventListeners with their linked elements.

Binding multiple events to a listener (without JQuery)?

For me; this code works fine and is the shortest code to handle multiple events with same (inline) functions.

var eventList = ["change", "keyup", "paste", "input", "propertychange", "..."];
for(event of eventList) {
    element.addEventListener(event, function() {
        // your function body...
        console.log("you inserted things by paste or typing etc.");
    });
}

How to trigger event in JavaScript?

A working example:

// Add an event listener
document.addEventListener("name-of-event", function(e) {
  console.log(e.detail); // Prints "Example of an event"
});

// Create the event
var event = new CustomEvent("name-of-event", { "detail": "Example of an event" });

// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);

For older browsers polyfill and more complex examples, see MDN docs.

See support tables for EventTarget.dispatchEvent and CustomEvent.

How to bind event listener for rendered elements in Angular 2?

If you want to bind an event like 'click' for all the elements having same class in the rendered DOM element then you can set up an event listener by using following parts of the code in components.ts file.

import { Component, OnInit, Renderer, ElementRef} from '@angular/core';

constructor( elementRef: ElementRef, renderer: Renderer) {
    dragulaService.drop.subscribe((value) => {
      this.onDrop(value.slice(1));
    });
}

public onDrop(args) {

  let [e, el] = args;

  this.toggleClassComTitle(e,'checked');

}


public toggleClassComTitle(el: any, name: string) {

    el.querySelectorAll('.com-item-title-anchor').forEach( function ( item ) {

      item.addEventListener('click', function(event) {
              console.log("item-clicked");

       });
    });

}

JavaScript listener, "keypress" doesn't detect backspace?

My numeric control:

function CheckNumeric(event) {
    var _key = (window.Event) ? event.which : event.keyCode;
    if (_key > 95 && _key < 106) {
        return true;
    }
    else if (_key > 47 && _key < 58) {
        return true;
    }
    else {
        return false;
    }
}

<input type="text" onkeydown="return CheckNumerick(event);" />

try it

BackSpace key code is 8

How to pass arguments to addEventListener listener function?

The following approach worked well for me. Modified from here.

_x000D_
_x000D_
function callback(theVar) {_x000D_
  return function() {_x000D_
    theVar();_x000D_
  }_x000D_
}_x000D_
_x000D_
function some_other_function() {_x000D_
  document.body.innerHTML += "made it.";_x000D_
}_x000D_
_x000D_
var someVar = some_other_function;_x000D_
document.getElementById('button').addEventListener('click', callback(someVar));
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <body>_x000D_
    <button type="button" id="button">Click Me!</button>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Cannot read property 'addEventListener' of null

Thanks from all, Load the Scripts in specific pages that you use, not for all pages, sometimes using swiper.js or other library it may cause this error message, the only way to solve this issue it to load the JS library on specific pages that ID is exist and prevent loading of the same library in all pages.

Hope this help you.

MSIE and addEventListener Problem in Javascript?

In case you are using JQuery 2.x then please add the following in the

<html>
   <head>
      <meta http-equiv="X-UA-Compatible" content="IE=edge;" />
   </head>
   <body>
    ...
   </body>
</html>

This worked for me.

addEventListener not working in IE8

Mayb it's easier (and has more performance) if you delegate the event handling to another element, for example your table

$('idOfYourTable').on("click", "input:checkbox", function(){

});

in this way you will have only one event handler, and this will work also for newly added elements. This requires jQuery >= 1.7

Otherwise use delegate()

$('idOfYourTable').delegate("input:checkbox", "click", function(){

});

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

If nearly everything seems right, another thing to look out for is to ensure that the validation summary is not being explicitly hidden via some CSS override like this:

.validation-summary-valid {
    display: none;
}

This may also cause the @Html.ValidationSummary to appear hidden, as the summary is dynamically rendered with the validation-summary-valid class.

How to use a PHP class from another file?

You can use include/include_once or require/require_once

require_once('class.php');

Alternatively, use autoloading by adding to page.php

<?php 
function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

$vars = new IUarts(); 
print($vars->data);    
?>

It also works adding that __autoload function in a lib that you include on every file like utils.php.

There is also this post that has a nice and different approach.

Efficient PHP auto-loading and naming strategies

How to find out what the date was 5 days ago?

find out what the date was 5 days ago from today in php

$date = strtotime(date("Y-m-d", strtotime("-5 day")));

find out what the date was n days ago from today in php

$date = strtotime(date("Y-m-d", strtotime("-n day")));

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

Try passing control to the next matching route. If Express is matching app.get route first, then it won't continue onto the options route unless you do this (note use of next):

app.get('somethingelse', function(req, res, next) {
    //..set headers etc.

    next();
});

In terms of organising the CORS stuff, I put it in a middleware which is working well for me:

//CORS middleware
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'example.com');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    next();
}

//...
app.configure(function() {
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.session({ secret: 'cool beans' }));
    app.use(express.methodOverride());
    app.use(allowCrossDomain);
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
});

latex large division sign in a math formula

Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.

And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.

How to use a variable from a cursor in the select statement of another cursor in pl/sql

You can certainly do something like

SQL> ed
Wrote file afiedt.buf

  1  begin
  2    for d in (select * from dept)
  3    loop
  4      for e in (select * from emp where deptno=d.deptno)
  5      loop
  6        dbms_output.put_line( 'Employee ' || e.ename ||
  7                              ' in department ' || d.dname );
  8      end loop;
  9    end loop;
 10* end;
SQL> /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES

PL/SQL procedure successfully completed.

Or something equivalent using explicit cursors.

SQL> ed
Wrote file afiedt.buf

  1  declare
  2    cursor dept_cur
  3        is select *
  4             from dept;
  5    d dept_cur%rowtype;
  6    cursor emp_cur( p_deptno IN dept.deptno%type )
  7        is select *
  8             from emp
  9            where deptno = p_deptno;
 10    e emp_cur%rowtype;
 11  begin
 12    open dept_cur;
 13    loop
 14      fetch dept_cur into d;
 15      exit when dept_cur%notfound;
 16      open emp_cur( d.deptno );
 17      loop
 18        fetch emp_cur into e;
 19        exit when emp_cur%notfound;
 20        dbms_output.put_line( 'Employee ' || e.ename ||
 21                              ' in department ' || d.dname );
 22      end loop;
 23      close emp_cur;
 24    end loop;
 25    close dept_cur;
 26* end;
 27  /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES

PL/SQL procedure successfully completed.

However, if you find yourself using nested cursor FOR loops, it is almost always more efficient to let the database join the two results for you. After all, relational databases are really, really good at joining. I'm guessing here at what your tables look like and how they relate based on the code you posted but something along the lines of

FOR x IN (SELECT *
            FROM all_users,
                 org
           WHERE length(all_users.username) = 3
             AND all_users.username = org.username )
LOOP
  <<do something>>
END LOOP;

Create pandas Dataframe by appending one row at a time

You can concatenate two DataFrames for this. I basically came across this problem to add a new row to an existing DataFrame with a character index(not numeric). So, I input the data for a new row in a duct() and index in a list.

new_dict = {put input for new row here}
new_list = [put your index here]

new_df = pd.DataFrame(data=new_dict, index=new_list)

df = pd.concat([existing_df, new_df])

Is there a difference between /\s/g and /\s+/g?

\s means "one space", and \s+ means "one or more spaces".

But, because you're using the /g flag (replace all occurrences) and replacing with the empty string, your two expressions have the same effect.

How do I express "if value is not empty" in the VBA language?

Use Not IsEmpty().

For example:

Sub DoStuffIfNotEmpty()
    If Not IsEmpty(ActiveCell.Value) Then
        MsgBox "I'm not empty!"
    End If
End Sub

What are CN, OU, DC in an LDAP search?

At least with Active Directory, I have been able to search by DistinguishedName by doing an LDAP query in this format (assuming that such a record exists with this distinguishedName):

"(distinguishedName=CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com)"

C++ style cast from unsigned char * to const char *

Try reinterpret_cast

unsigned char *foo();
std::string str;
str.append(reinterpret_cast<const char*>(foo()));

Remove new lines from string and replace with one empty space

Use this:

replace series of newlines with an empty string:

$string = preg_replace("/[\\n\\r]+/", "", $string);

or you probably want to replace newlines with a single space:

$string = preg_replace("/[\\n\\r]+/", " ", $string);

Check/Uncheck checkbox with JavaScript

<script type="text/javascript">
    $(document).ready(function () {
        $('.selecctall').click(function (event) {
            if (this.checked) {
                $('.checkbox1').each(function () {
                    this.checked = true;
                });
            } else {
                $('.checkbox1').each(function () {
                    this.checked = false;
                });
            }
        });

    });

</script>

How to convert JSONObjects to JSONArray?

Even shorter and with json-functions:

JSONObject songsObject = json.getJSONObject("songs");
JSONArray songsArray = songsObject.toJSONArray(songsObject.names());

Can I load a UIImage from a URL?

Make sure enable this settings from iOS 9:

App Transport Security Settings in Info.plist to ensure loading image from URL so that it will allow download image and set it.

enter image description here

And write this code:

NSURL *url = [[NSURL alloc]initWithString:@"http://feelgrafix.com/data/images/images-1.jpg"];
NSData *data =[NSData dataWithContentsOfURL:url];
quickViewImage.image = [UIImage imageWithData:data];

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

You likely don't have a CA signed certificate installed in your SQL VM's trusted root store.

If you have Encrypt=True in the connection string, either set that to off (not recommended), or add the following in the connection string:

TrustServerCertificate=True

SQL Server will create a self-signed certificate if you don't install one for it to use, but it won't be trusted by the caller since it's not CA-signed, unless you tell the connection string to trust any server cert by default.

Long term, I'd recommend leveraging Let's Encrypt to get a CA signed certificate from a known trusted CA for free, and install it on the VM. Don't forget to set it up to automatically refresh. You can read more on this topic in SQL Server books online under the topic of "Encryption Hierarchy", and "Using Encryption Without Validation".

Android: How to change CheckBox size?

I use

android:scaleX="0.70" android:scaleY="0.70"

to ajust the size of checkbox

then I set margins like this

android:layout_marginLeft="-10dp"

to adjust ths location of the checkbox.

How do I get java logging output to appear on a single line?

if you're using java.util.logging, then there is a configuration file that is doing this to log contents (unless you're using programmatic configuration). So, your options are
1) run post -processor that removes the line breaks
2) change the log configuration AND remove the line breaks from it. Restart your application (server) and you should be good.

Pull new updates from original GitHub repository into forked GitHub repository

This video shows how to update a fork directly from GitHub

Steps:

  1. Open your fork on GitHub.
  2. Click on Pull Requests.
  3. Click on New Pull Request. By default, GitHub will compare the original with your fork, and there shouldn’t be anything to compare if you didn’t make any changes.
  4. Click on switching the base. Now GitHub will compare your fork with the original, and you should see all the latest changes.
  5. Click on Create a pull request for this comparison and assign a predictable name to your pull request (e.g., Update from original).
  6. Click on Create pull request.
  7. Scroll down and click Merge pull request and finally Confirm merge. If your fork didn’t have any changes, you will be able to merge it automatically.

Creating multiple objects with different names in a loop to store in an array list

ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
    //get a customerName
    //get an amount
    custArr.add(new Customer(customerName, amount);
}

For this to work... you'll have to fix your constructor...


Assuming your Customer class has variables called name and sale, your constructor should look like this:

public Customer(String customerName, double amount) {
    name = customerName;
    sale = amount;
}

Change your Store class to something more like this:

public class Store {

    private ArrayList<Customer> custArr;

    public new Store() {
        custArr = new ArrayList<Customer>();
    }

    public void addSale(String customerName, double amount) {
        custArr.add(new Customer(customerName, amount));
    }

    public Customer getSaleAtIndex(int index) {
        return custArr.get(index);
    }

    //or if you want the entire ArrayList:
    public ArrayList getCustArr() {
        return custArr;
    }
}

Binding Button click to a method

Here is the VB.Net rendition of Rachel's answer above.

Obviously the XAML binding is the same...

<Button Command="{Binding Path=SaveCommand}" />

Your Custom Class would look like this...

''' <summary>
''' Retrieves an new or existing RelayCommand.
''' </summary>
''' <returns>[RelayCommand]</returns>
Public ReadOnly Property SaveCommand() As ICommand
    Get
        If _saveCommand Is Nothing Then
            _saveCommand = New RelayCommand(Function(param) SaveObject(), Function(param) CanSave())
        End If
        Return _saveCommand
    End Get
End Property
Private _saveCommand As ICommand

''' <summary>
''' Returns Boolean flag indicating if command can be executed.
''' </summary>
''' <returns>[Boolean]</returns>
Private Function CanSave() As Boolean
    ' Verify command can be executed here.
    Return True
End Function

''' <summary>
''' Code to be run when the command is executed.
''' </summary>
''' <remarks>Converted to a Function in VB.net to avoid the "Expression does not produce a value" error.</remarks>
''' <returns>[Nothing]</returns>
Private Function SaveObject()
    ' Save command execution logic.
   Return Nothing
End Function

And finally the RelayCommand class is as follows...

Public Class RelayCommand : Implements ICommand

ReadOnly _execute As Action(Of Object)
ReadOnly _canExecute As Predicate(Of Object)
Private Event ICommand_CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged

''' <summary>
''' Creates a new command that can always execute.
''' </summary>
''' <param name="execute">The execution logic.</param>
Public Sub New(execute As Action(Of Object))
    Me.New(execute, Nothing)
End Sub

''' <summary>
''' Creates a new command.
''' </summary>
''' <param name="execute">The execution logic.</param>
''' <param name="canExecute">The execution status logic.</param>
Public Sub New(execute As Action(Of Object), canExecute As Predicate(Of Object))
    If execute Is Nothing Then
        Throw New ArgumentNullException("execute")
    End If
    _execute = execute
    _canExecute = canExecute
End Sub

<DebuggerStepThrough>
Public Function CanExecute(parameters As Object) As Boolean Implements ICommand.CanExecute
    Return If(_canExecute Is Nothing, True, _canExecute(parameters))
End Function

Public Custom Event CanExecuteChanged As EventHandler
    AddHandler(ByVal value As EventHandler)
        AddHandler CommandManager.RequerySuggested, value
    End AddHandler
    RemoveHandler(ByVal value As EventHandler)
        RemoveHandler CommandManager.RequerySuggested, value
    End RemoveHandler
    RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
        If (_canExecute IsNot Nothing) Then
            _canExecute.Invoke(sender)
        End If
    End RaiseEvent
End Event

Public Sub Execute(parameters As Object) Implements ICommand.Execute
    _execute(parameters)
End Sub

End Class

Hope that helps any VB.Net developers!

Parse error: Syntax error, unexpected end of file in my PHP code

Also, another case where it is hard to spot is when you have a file with just a function, I know it is not a common use case but it is annoying and had to spot the error.

<?php
function () {

}

The file above returns the erro Parse error: syntax error, unexpected end of file in while the below does not.

<?php
function () {

};

Stop mouse event propagation

I just checked in an Angular 6 application, the event.stopPropagation() works on an event handler without even passing $event

(click)="doSomething()"  // does not require to pass $event


doSomething(){
   // write any code here

   event.stopPropagation();
}

How to link to apps on the app store

This worked for me perfectly using only APP ID:

 NSString *urlString = [NSString stringWithFormat:@"http://itunes.apple.com/app/id%@",YOUR_APP_ID];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];

The number of redirects is ZERO.

-bash: export: `=': not a valid identifier

Try to surround the path with quotes, and remove the spaces

export PYTHONPATH="/home/user/my_project":$PYTHONPATH

And don't forget to preserve previous content suffixing by :$PYTHONPATH (which is the value of the variable)

Execute the following command to check everything is configured correctly:

echo $PYTHONPATH

selectOneMenu ajax events

I'd rather use more convenient itemSelect event. With this event you can use org.primefaces.event.SelectEvent objects in your listener.

<p:selectOneMenu ...>
    <p:ajax event="itemSelect" 
        update="messages"
        listener="#{beanMB.onItemSelectedListener}"/>
</p:selectOneMenu>

With such listener:

public void onItemSelectedListener(SelectEvent event){
    MyItem selectedItem = (MyItem) event.getObject();
    //do something with selected value
}

why I can't get value of label with jquery and javascript?

You need text() or html() for label not val() The function should not be called for label instead it is used to get values of input like text or checkbox etc.

Change

value = $("#telefon").val(); 

To

value = $("#telefon").text(); 

Python | change text color in shell

Use Curses or ANSI escape sequences. Before you start spouting escape sequences, you should check that stdout is a tty. You can do this with sys.stdout.isatty(). Here's a function pulled from a project of mine that prints output in red or green, depending on the status, using ANSI escape sequences:

def hilite(string, status, bold):
    attr = []
    if status:
        # green
        attr.append('32')
    else:
        # red
        attr.append('31')
    if bold:
        attr.append('1')
    return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)

C# : changing listbox row color?

You will need to draw the item yourself. Change the DrawMode to OwnerDrawFixed and handle the DrawItem event.

/// <summary>
/// Handles the DrawItem event of the listBox1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.DrawItemEventArgs"/> instance containing the event data.</param>
private void listBox1_DrawItem( object sender, DrawItemEventArgs e )
{
   e.DrawBackground();
   Graphics g = e.Graphics;

    // draw the background color you want
    // mine is set to olive, change it to whatever you want
    g.FillRectangle( new SolidBrush( Color.Olive), e.Bounds );

    // draw the text of the list item, not doing this will only show
    // the background color
    // you will need to get the text of item to display
    g.DrawString( THE_LIST_ITEM_TEXT , e.Font, new SolidBrush( e.ForeColor ), new PointF( e.Bounds.X, e.Bounds.Y) );

    e.DrawFocusRectangle();
}

Counting the number of True Booleans in a Python List

I prefer len([b for b in boollist if b is True]) (or the generator-expression equivalent), as it's quite self-explanatory. Less 'magical' than the answer proposed by Ignacio Vazquez-Abrams.

Alternatively, you can do this, which still assumes that bool is convertable to int, but makes no assumptions about the value of True: ntrue = sum(boollist) / int(True)

How to list all dates between two dates

You can create a stored procedure passing 2 dates

CREATE PROCEDURE SELECTALLDATES
(
@StartDate as date,
@EndDate as date
)
AS
Declare @Current as date = DATEADD(DD, 1, @BeginDate);

Create table #tmpDates
(displayDate date)

WHILE @Current < @EndDate
BEGIN
insert into #tmpDates
VALUES(@Current);
set @Current = DATEADD(DD, 1, @Current) -- add 1 to current day
END

Select * 
from #tmpDates

drop table #tmpDates

How can I check if a view is visible or not in Android?

You'd use the corresponding method getVisibility(). Method names prefixed with 'get' and 'set' are Java's convention for representing properties. Some language have actual language constructs for properties but Java isn't one of them. So when you see something labeled 'setX', you can be 99% certain there's a corresponding 'getX' that will tell you the value.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

For python 3, the default encoding would be "utf-8". Following steps are suggested in the base documentation:https://docs.python.org/2/library/csv.html#csv-examples in case of any problem

  1. Create a function

    def utf_8_encoder(unicode_csv_data):
        for line in unicode_csv_data:
            yield line.encode('utf-8')
    
  2. Then use the function inside the reader, for e.g.

    csv_reader = csv.reader(utf_8_encoder(unicode_csv_data))
    

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

There is some issue with some language display time ago for example in Arabic there 3 needed formats to display date. I use this functions in my projects hopefully they can help someone (any suggestion or improvement I'll be apperciate :) )

/**
 *
 * @param   string $date1 
 * @param   string $date2 the date that you want to compare with $date1
 * @param   int $level  
 * @param   bool $absolute  
 */

function app_date_diff( $date1, $date2, $level = 3, $absolute = false ) {

    $date1 = date_create($date1);   
    $date2 = date_create($date2);
    $diff = date_diff( $date1, $date2, $absolute );

    $d = [
        'invert' => $diff->invert
    ];  

    $diffs = [
        'y' => $diff->y, 
        'm' => $diff->m, 
        'd' => $diff->d
    ];

    $level_reached = 0;

    foreach($diffs as $k=>$v) {

        if($level_reached >= $level) {
            break;
        }

        if($v > 0) {
            $d[$k] = $v;
            $level_reached++;
        }

    }

    return  $d;

}

/**
 * 
 */

function date_timestring( $periods, $format = 'latin', $separator = ',' ) {

    $formats = [
        'latin' => [
            'y' => ['year','years'],
            'm' => ['month','months'],
            'd' => ['day','days']
        ],
        'arabic' => [
            'y' => ['???','?????','?????'],
            'm' => ['???','?????','????'],
            'd' => ['???','?????','????']
        ]
    ];

    $formats = $formats[$format];

    $string = [];

    foreach($periods as $period=>$value) {

        if(!isset($formats[$period])) {
            continue;
        }

        $string[$period] = $value.' ';
        if($format == 'arabic') {
            if($value == 2) {
                $string[$period] = $formats[$period][1];
            }elseif($value > 2 && $value <= 10) {
                $string[$period] .= $formats[$period][2];
            }else{
                $string[$period] .= $formats[$period][0];
            }

        }elseif($format == 'latin') {
            $string[$period] .= ($value > 1) ? $formats[$period][1] : $formats[$period][0];
        }

    }

    return implode($separator, $string);


}

function timeago( $date ) {

    $today = date('Y-m-d h:i:s');

    $diff = app_date_diff($date,$today,2);

    if($diff['invert'] == 1) {
        return '';
    }

    unset($diff[0]);

    $date_timestring = date_timestring($diff,'latin');

    return 'About '.$date_timestring;

}

$date1 = date('Y-m-d');
$date2 = '2018-05-14';

$diff = timeago($date2);
echo $diff;

How would you do a "not in" query with LINQ?

items in the first list where the Email does not exist in the second list.

from item1 in List1
where !(list2.Any(item2 => item2.Email == item1.Email))
select item1;

FileNotFoundException..Classpath resource not found in spring?

This is due to spring-config.xml is not in classpath.

Add complete path of spring-config.xml to your classpath.

Also write command you execute to run your project. You can check classpath in command.

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

To declare different layouts and bitmaps you'd like to use for the different screens, you must place these alternative resources in separate directories/folders.

This means that if you generate a 200x200 image for xhdpi devices, you should generate the same resource in 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices.

Then, place the files in the appropriate drawable resource directory:

MyProject/
    res/
        drawable-xhdpi/
            awesomeimage.png
        drawable-hdpi/
            awesomeimage.png
        drawable-mdpi/
            awesomeimage.png
        drawable-ldpi/
            awesomeimage.png

Any time you reference @drawable/awesomeimage, the system selects the appropriate bitmap based on the screen's density.

How to add screenshot to READMEs in github repository?

Method 1->Markdown way

![Alt Text](https://raw.github.com/{USERNAME}/{REPOSITORY}/{BRANCH}/{PATH})

Method 2->HTML way

<img src="https://link(format same as above)" width="100" height="100"/>

or

<img src="https://link" style=" width:100px ; height:100px " />

Note-> If you don't want to style your image i.e resize remove the style part

Database cluster and load balancing

Database Clustering is actually a mode of synchronous replication between two or possibly more nodes with an added functionality of fault tolerance added to your system, and that too in a shared nothing architecture. By shared nothing it means that the individual nodes actually don't share any physical resources like disk or memory.

As far as keeping the data synchronized is concerned, there is a management server to which all the data nodes are connected along with the SQL node to achieve this(talking specifically about MySQL).

Now about the differences: load balancing is just one result that could be achieved through clustering, the others include high availability, scalability and fault tolerance.

XPath - Selecting elements that equal a value

Try

//*[text()='qwerty'] because . is your current element

How to use "svn export" command to get a single file from the repository?

For the substition impaired here is a real example from GitHub.com to a local directory:

svn ls https://github.com/rdcarp/playing-cards/trunk/PumpkinSoup.PlayingCards.Interfaces
svn export https://github.com/rdcarp/playing-cards/trunk/PumpkinSoup.PlayingCards.Interfaces /temp/SvnExport/Washburn

See: Download a single folder or directory from a GitHub repo for more details.

How can one see content of stack with GDB?

You need to use gdb's memory-display commands. The basic one is x, for examine. There's an example on the linked-to page that uses

gdb> x/4xw $sp

to print "four words (w ) of memory above the stack pointer (here, $sp) in hexadecimal (x)". The quotation is slightly paraphrased.

Strip HTML from strings in Python

If you need to preserve HTML entities (i.e. &amp;), I added "handle_entityref" method to Eloff's answer.

from HTMLParser import HTMLParser

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def handle_entityref(self, name):
        self.fed.append('&%s;' % name)
    def get_data(self):
        return ''.join(self.fed)

def html_to_text(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

Specifying row names when reading in a file

If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

read.table(file = "foo.txt", row.names = 1, ....)

where .... are the other arguments you needed/used. The row.names argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

rownames(obj) <- obj[, 1]  ## set rownames
obj <- obj[, -1]           ## remove the first variable

How do I pass command line arguments to a Node.js program?

I extended the getArgs function just to get also commands, as well as flags (-f, --anotherflag) and named args (--data=blablabla):

  1. The module
/**
 * @module getArgs.js
 * get command line arguments (commands, named arguments, flags)
 *
 * @see https://stackoverflow.com/a/54098693/1786393
 *
 * @return {Object}
 *
 */
function getArgs () {
  const commands = []
  const args = {}
  process.argv
    .slice(2, process.argv.length)
    .forEach( arg => {
      // long arg
      if (arg.slice(0,2) === '--') {
        const longArg = arg.split('=')
        const longArgFlag = longArg[0].slice(2,longArg[0].length)
        const longArgValue = longArg.length > 1 ? longArg[1] : true
        args[longArgFlag] = longArgValue
     }
     // flags
      else if (arg[0] === '-') {
        const flags = arg.slice(1,arg.length).split('')
        flags.forEach(flag => {
          args[flag] = true
        })
      }
     else {
      // commands
      commands.push(arg)
     } 
    })
  return { args, commands }
}


// test
if (require.main === module) {
  // node getArgs test --dir=examples/getUserName --start=getUserName.askName
  console.log( getArgs() )
}

module.exports = { getArgs }

  1. Usage example:
$ node lib/getArgs test --dir=examples/getUserName --start=getUserName.askName
{
  args: { dir: 'examples/getUserName', start: 'getUserName.askName' },
  commands: [ 'test' ]
}

$ node lib/getArgs --dir=examples/getUserName --start=getUserName.askName test tutorial
{
  args: { dir: 'examples/getUserName', start: 'getUserName.askName' },
  commands: [ 'test', 'tutorial' ]
}

compilation error: identifier expected

You have not defined a method around your code.

import java.io.*;

public class details
{
    public static void main( String[] args )
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

In this case, I have assumed that you want your code to be executed in the main method of the class. It is, of course, possible that this code goes in any other method.

How to clear out session on log out

The way of clearing the session is a little different for .NET core. There is no Abandon() function.

ASP.NET Core 1.0 or later

//Removes all entries from the current session, if any. The session cookie is not removed.
HttpContext.Session.Clear()

See api Reference here

.NET Framework 4.5 or later

//Removes all keys and values from the session-state collection.
HttpContext.Current.Session.Clear(); 

//Cancels the current session.
HttpContext.Current.Session.Abandon();

See api Reference here

How to maintain page scroll position after a jquery event is carried out?

I had a similar problem getting scrollTop to work after reload of div content. The content scrolled to top each time the procedure below was run. I found that a little delay before setting the new scrolltop solved the issue.

This is cut from wdCalendar where I modified this procedure:

 function BuildDaysAndWeekView(startday, l, events, config)
   ....
        var scrollpos = $("#dvtec").scrollTop();
        gridcontainer.html(html.join(""));
        setTimeout(function() {
            $("#dvtec").scrollTop(scrollpos);
        }, 25);
   ....

Without the delay, it simply did not work.

MySQL, Check if a column exists in a table with SQL

I threw this stored procedure together with a start from @lain's comments above, kind of nice if you need to call it more than a few times (and not needing php):

delimiter //
-- ------------------------------------------------------------
-- Use the inforamtion_schema to tell if a field exists.
-- Optional param dbName, defaults to current database
-- ------------------------------------------------------------
CREATE PROCEDURE fieldExists (
OUT _exists BOOLEAN,      -- return value
IN tableName CHAR(255),   -- name of table to look for
IN columnName CHAR(255),  -- name of column to look for
IN dbName CHAR(255)       -- optional specific db
) BEGIN
-- try to lookup db if none provided
SET @_dbName := IF(dbName IS NULL, database(), dbName);

IF CHAR_LENGTH(@_dbName) = 0
THEN -- no specific or current db to check against
  SELECT FALSE INTO _exists;
ELSE -- we have a db to work with
  SELECT IF(count(*) > 0, TRUE, FALSE) INTO _exists
  FROM information_schema.COLUMNS c
  WHERE 
  c.TABLE_SCHEMA    = @_dbName
  AND c.TABLE_NAME  = tableName
  AND c.COLUMN_NAME = columnName;
END IF;
END //
delimiter ;

Working with fieldExists

mysql> call fieldExists(@_exists, 'jos_vm_product', 'child_option', NULL) //
Query OK, 0 rows affected (0.01 sec)

mysql> select @_exists //
+----------+
| @_exists |
+----------+
|        0 |
+----------+
1 row in set (0.00 sec)

mysql> call fieldExists(@_exists, 'jos_vm_product', 'child_options', 'etrophies') //
Query OK, 0 rows affected (0.01 sec)

mysql> select @_exists //
+----------+
| @_exists |
+----------+
|        1 |
+----------+

How do I make a file:// hyperlink that works in both IE and Firefox?

just use

file:///

works in IE, Firefox and Chrome as far as I can tell.

see http://msdn.microsoft.com/en-us/library/aa767731(VS.85).aspx for more info

How to set environment variables in PyCharm?

This functionality has been added to the IDE now (working Pycharm 2018.3)

Just click the EnvFile tab in the run configuration, click Enable EnvFile and click the + icon to add an env file

Example with the glorious material theme

Update: Essentially the same as the answer by @imguelvargasf but the the plugin was enabled by default for me.

Can I limit the length of an array in JavaScript?

var  arrLength = arr.length;
if(arrLength > maxNumber){
    arr.splice( 0, arrLength - maxNumber);
}

This soultion works better in an dynamic environment like p5js. I put this inside the draw call and it clamps the length of the array dynamically.

The problem with:

arr.slice(0,5)

...is that it only takes a fixed number of items off the array per draw frame, which won't be able to keep the array size constant if your user can add multiple items.

The problem with:

if (arr.length > 4) arr.length = 4;

...is that it takes items off the end of the array, so which won't cycle through the array if you are also adding to the end with push().

How can I symlink a file in Linux?

To the original question:


'ln -s '+basebuild+'/IpDome-kernel/kernel /home/build/sandbox/gen2/basebuild/IpDome-kernel/kernal'

This will indeed create a symbolic link (-s) from the file/directory:

<basebuild>/IpDome-kernel/kernel

to your new link

/home/build/sandbox/gen2/basebuild/IpDome-kernel/kernal

Here's a few ways to help you remember:

First, there's the man page for ln. You can access this via searching "man ln" in google, or just open a terminal window and type man ln and you'll get the same information. The man page clearly states:

ln [OPTION]... [-T] TARGET LINK_NAME (1st form)


If having to search or read through a man page every time isn't for you, maybe you'll have an easier time remembering that all nix commands work the same way:

cp /file/that/exists /location/for/new/file
mv /file/that/exists /location/its/moving/to
ln /file/that/exists /the/new/link

cp copies a file that currently exists (the first argument) to a new file (the second argument).
mv moves a file that currently exists (the first argument) to a new place (the second argument)

Likewise ln links a file that currently exists (the first argument) to a new link (the second argument)*


The final option I would like to suggest is you can create your own man pages that are easy to read and easy (for you) to find/remember. Just make a simple shell script that gives you the hint you need. For example?:

In your .bash_aliases file you can place something like:

commandsfx() {
    echo "Symlink:  ln -s /path/to/file /path/to/symlink"
    echo "Copy:     cp /file/to/copy /destination/to/send/copy"
}

alias 'cmds'=commandsfx

Then when you need it, from the command line just type cmds and you'll get back the proper syntax in a way you can quickly read and understand it. You can make these functions as advanced as you'd like to get what what information you need, it's up to you. You could even make them interactive so you just have to follow the prompts.. something like:

makesymlink() {
    echo "Symlink name:"
    read sym
    echo "File to link to:"
    read fil
    ln -s $fil $sym
}

alias 'symlink'=makesymlink

* - well obviously they can all take different parameters and do different things and can work on files as well as directories... but the premise is the same
? - examples using the bash shell

Can I prevent text in a div block from overflowing?

You can just set the min-width in the css, for example:

.someClass{min-width: 980px;}

It will not break, nevertheless you will still have the scroll-bar to deal with.

GROUP_CONCAT comma separator - MySQL

Looks like you're missing the SEPARATOR keyword in the GROUP_CONCAT function.

GROUP_CONCAT(artists.artistname SEPARATOR '----')

The way you've written it, you're concatenating artists.artistname with the '----' string using the default comma separator.

How to JSON decode array elements in JavaScript?

JSON decoding in JavaScript is simply an eval() if you trust the string or the more safe code you can find on http://json.org if you don't.

You will then have a JavaScript datastructure that you can traverse for the data you need.

Populate one dropdown based on selection in another

Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.

Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.

var data = [ // The data
    ['ten', [
        'eleven','twelve'
    ]],
    ['twenty', [
        'twentyone', 'twentytwo'
    ]]
];

$a = $('#a'); // The dropdowns
$b = $('#b');

for(var i = 0; i < data.length; i++) {
    var first = data[i][0];
    $a.append($("<option>"). // Add options
       attr("value",first).
       data("sel", i).
       text(first));
}

$a.change(function() {
    var index = $(this).children('option:selected').data('sel');
    var second = data[index][1]; // The second-choice data

    $b.html(''); // Clear existing options in second dropdown

    for(var j = 0; j < second.length; j++) {
        $b.append($("<option>"). // Add options
           attr("value",second[j]).
           data("sel", j).
           text(second[j]));
    }
}).change(); // Trigger once to add options at load of first choice

How to find a min/max with Ruby

You can use

[5,10].min 

or

[4,7].max

It's a method for Arrays.

How to create custom spinner like border around the spinner with down triangle on the right side?

This is a simple one.

your_layout.xml

<android.support.v7.widget.AppCompatSpinner
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:background="@drawable/spinner_background"
/>

In the drawable folder, spinner_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item><layer-list>
    <item>
        <shape>
            <solid
                android:color="@color/colorWhite">
            </solid>

            <corners android:radius="3dp" />

            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />
            <stroke
                android:width="2dp"
                android:color="@color/colorDarkGrey"/>
        </shape>
    </item>
    <item >
        <bitmap android:gravity="bottom|right"
        android:src="@drawable/ic_arrow_drop_down_black_24dp" />
    </item>
  </layer-list></item>
</selector>

Preview:

Spinner example

Check if selected dropdown value is empty using jQuery

You can try this also-

if( !$('#EventStartTimeMin').val() ) {
// do something
}

Extract only right most n letters from a string

Guessing at your requirements but the following regular expression will yield only on 6 alphanumerics before the end of the string and no match otherwise.

string result = Regex.Match("PER 343573", @"[a-zA-Z\d]{6}$").Value;

Return current date plus 7 days

you didn't use time() function that returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). use like this:

$date = strtotime(time());
$date = strtotime("+7 day", $date);
echo date('M d, Y', $date);

Assign result of dynamic sql to variable

You should try this while getting SEQUENCE value in a variable from the dynamic table.

DECLARE @temp table (#temp varchar (MAX));
DECLARE @SeqID nvarchar(150);
DECLARE @Name varchar(150); 

SET @Name = (Select Name from table)
SET @SeqID = 'SELECT NEXT VALUE FOR '+ @Name + '_Sequence'
insert @temp exec (@SeqID)

SET @SeqID = (select * from @temp )
PRINT @SeqID

Result:

(1 row(s) affected)
 1

Convert JsonNode into POJO

In Jackson 2.4, you can convert as follows:

MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);

where jsonObjectMapper is a Jackson ObjectMapper.


In older versions of Jackson, it would be

MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);

HTML5 video - show/hide controls programmatically

<video id="myvideo">
  <source src="path/to/movie.mp4" />
</video>

<p onclick="toggleControls();">Toggle</p>

<script>
var video = document.getElementById("myvideo");

function toggleControls() {
  if (video.hasAttribute("controls")) {
     video.removeAttribute("controls")   
  } else {
     video.setAttribute("controls","controls")   
  }
}
</script>

See it working on jsFiddle: http://jsfiddle.net/dgLds/

How can one print a size_t variable portably using the printf family?

As AraK said, the c++ streams interface will always work portably.

std::size_t s = 1024; std::cout << s; // or any other kind of stream like stringstream!

If you want C stdio, there is no portable answer to this for certain cases of "portable." And it gets ugly since as you've seen, picking the wrong format flags may yield a compiler warning or give incorrect output.

C99 tried to solve this problem with inttypes.h formats like "%"PRIdMAX"\n". But just as with "%zu", not everyone supports c99 (like MSVS prior to 2013). There are "msinttypes.h" files floating around to deal with this.

If you cast to a different type, depending on flags you may get a compiler warning for truncation or a change of sign. If you go this route pick a larger relevant fixed size type. One of unsigned long long and "%llu" or unsigned long "%lu" should work, but llu may also slow things down in a 32bit world as excessively large. (Edit - my mac issues a warning in 64 bit for %llu not matching size_t, even though %lu, %llu, and size_t are all the same size. And %lu and %llu are not the same size on my MSVS2012. So you may need to cast + use a format that matches.)

For that matter, you can go with fixed size types, such as int64_t. But wait! Now we're back to c99/c++11, and older MSVS fails again. Plus you also have casts (e.g. map.size() is not a fixed size type)!

You can use a 3rd party header or library such as boost. If you're not already using one, you may not want to inflate your project that way. If you're willing to add one just for this issue, why not use c++ streams, or conditional compilation?

So you're down to c++ streams, conditional compilation, 3rd party frameworks, or something sort of portable that happens to work for you.

How to reset or change the passphrase for a GitHub SSH key?

In short there's no way to recover the passphrase for a pair of SSH keys. Why? Because it was intended this way in the first place for security reasons. The answers the other people gave you are all correct ways to CHANGE the password of your keys, not to recover them. So if you've forgotten your passphrase, the best you can do is create a new pair of SSH keys. Here's how to generate SSH keys and add it to your GitHub account.

Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.

You asked if it is possible to change the circular dependency checking in those slf4j classes.

The simple answer is no.

  • It is unconditional ... as implemented.
  • It is implemented in a static initializer block ... so you can't override the implementation, and you can't stop it happening.

So the only way to change this would be to download the source code, modify the core classes to "fix" them, build and use them. That is probably a bad idea (in general) and probably not solution in this case; i.e. you risk triggering the stack overflow problem that the message warns about.

Reference:


The real solution (as you identified in your Answer) is to use the right JARs. My understanding is that the circularity that was detected is real and potentially problematic ... and unnecessary.

C#: How would I get the current time into a string?

I'd just like to point out something in these answers. In a date/time format string, '/' will be replaced with whatever the user's date separator is, and ':' will be replaced with whatever the user's time separator is. That is, if I've defined my date separator to be '.' (in the Regional and Language Options control panel applet, "intl.cpl"), and my time separator to be '?' (just pretend I'm crazy like that), then

DateTime.Now.ToString("MM/dd/yyyy h:mm tt")

would return

01.05.2009 6?01 PM

In most cases, this is what you want, because you want to respect the user's settings. If, however, you require the format be something specific (say, if it's going to parsed back out by somebody else down the wire), then you need to escape these special characters:

DateTime.Now.ToString("MM\\/dd\\/yyyy h\\:mm tt")

or

DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt")

which would now return

01/05/2009 6:01 PM

EDIT:

Then again, if you really want to respect the user's settings, you should use one of the standard date/time format strings, so that you respect not only the user's choices of separators, but also the general format of the date and/or time.

DateTime.Now.ToShortDateString()
DateTime.Now.ToString("d")

Both would return "1/5/2009" using standard US options, or "05/01/2009" using standard UK options, for instance.

DateTime.Now.ToLongDateString()
DateTime.Now.ToString("D")

Both would return "Monday, January 05, 2009" in US locale, or "05 January 2009" in UK.

DateTime.Now.ToShortTimeString()
DateTime.Now.ToString("t");

"6:01 PM" in US, "18:01" in UK.

DateTime.Now.ToLongTimeString()
DateTime.Now.ToString("T");

"6:01:04 PM" in US, "18:01:04" in UK.

DateTime.Now.ToString()
DateTime.Now.ToString("G");

"1/5/2009 6:01:04 PM" in US, "05/01/2009 18:01:04" in UK.

Many other options are available. See docs for standard date and time format strings and custom date and time format strings.

How to loop through a dataset in powershell?

Here's a practical example (build a dataset from your current location):

$ds = new-object System.Data.DataSet
$ds.Tables.Add("tblTest")
[void]$ds.Tables["tblTest"].Columns.Add("Name",[string])
[void]$ds.Tables["tblTest"].Columns.Add("Path",[string])

dir | foreach {
    $dr = $ds.Tables["tblTest"].NewRow()
    $dr["Name"] = $_.name
    $dr["Path"] = $_.fullname
    $ds.Tables["tblTest"].Rows.Add($dr)
}


$ds.Tables["tblTest"]

$ds.Tables["tblTest"] is an object that you can manipulate just like any other Powershell object:

$ds.Tables["tblTest"] | foreach {
    write-host 'Name value is : $_.name
    write-host 'Path value is : $_.path
}

How to programmatically click a button in WPF?

One way to programmatically "click" the button, if you have access to the source, is to simply call the button's OnClick event handler (or Execute the ICommand associated with the button, if you're doing things in the more WPF-y manner).

Why are you doing this? Are you doing some sort of automated testing, for example, or trying to perform the same action that the button performs from a different section of code?

Get Time from Getdate()

You can use the datapart to maintain time date type and you can compare it to another time.
Check below example:

declare @fromtime time = '09:30'
declare @totime time
SET @totime=CONVERT(TIME, CONCAT(DATEPART(HOUR, GETDATE()),':', DATEPART(MINUTE, GETDATE())))
if @fromtime <= @totime 
begin print 'true' end
else begin print 'no' end

How to fill a datatable with List<T>

I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable and the underlying data was a IEnumerable and the properties couldn't be enumerated. This did the trick:

// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
    List<IDataRecord> list = data.Cast<IDataRecord>().ToList();

    PropertyDescriptorCollection props = null;
    DataTable table = new DataTable();
    if (list != null && list.Count > 0)
    {
        props = TypeDescriptor.GetProperties(list[0]);
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }
    }
    if (props != null)
    {
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item) ?? DBNull.Value;
            }
            table.Rows.Add(values);
        }
    }
    return table;
}

how to calculate binary search complexity

For Binary Search, T(N) = T(N/2) + O(1) // the recurrence relation

Apply Masters Theorem for computing Run time complexity of recurrence relations : T(N) = aT(N/b) + f(N)

Here, a = 1, b = 2 => log (a base b) = 1

also, here f(N) = n^c log^k(n) //k = 0 & c = log (a base b)

So, T(N) = O(N^c log^(k+1)N) = O(log(N))

Source : http://en.wikipedia.org/wiki/Master_theorem

Convert nested Python dict to object?

Convert dict to object

from types import SimpleNamespace

def dict2obj(data):
    """????????????????"""
    if not isinstance(data, dict):
        raise ValueError('data must be dict object.')

    def _d2o(d):
        _d = {}
        for key, item in d.items():
            if isinstance(item, dict):
                _d[key] = _d2o(item)
            else:
                _d[key] = item
        return SimpleNamespace(**_d)

    return _d2o(data)

Reference Answer

Formatting Phone Numbers in PHP

Here's a simple function for formatting phone numbers with 7 to 10 digits in a more European (or Swedish?) manner:

function formatPhone($num) {
    $num = preg_replace('/[^0-9]/', '', $num);
    $len = strlen($num);

    if($len == 7) $num = preg_replace('/([0-9]{2})([0-9]{2})([0-9]{3})/', '$1 $2 $3', $num);
    elseif($len == 8) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{3})/', '$1 - $2 $3', $num);
    elseif($len == 9) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{2})([0-9]{2})/', '$1 - $2 $3 $4', $num);
    elseif($len == 10) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{2})([0-9]{3})/', '$1 - $2 $3 $4', $num);

    return $num;
}

C++ - How to append a char to char*?

The specific problem is that you're declaring a new variable instead of assigning to an existing one:

char * ret = new char[strlen(array) + 1 + 1];
^^^^^^ Remove this

and trying to compare string values by comparing pointers:

if (array!="")     // Wrong - compares pointer with address of string literal
if (array[0] == 0) // Better - checks for empty string

although there's no need to make that comparison at all; the first branch will do the right thing whether or not the string is empty.

The more general problem is that you're messing around with nasty, error-prone C-style string manipulation in C++. Use std::string and it will manage all the memory allocation for you:

std::string appendCharToString(std::string const & s, char a) {
    return s + a;
}

How to convert datetime to integer in python

This in an example that can be used for example to feed a database key, I sometimes use instead of using AUTOINCREMENT options.

import datetime 

dt = datetime.datetime.now()
seq = int(dt.strftime("%Y%m%d%H%M%S"))

How to properly use the "choices" field option in Django

$ pip install django-better-choices

For those who are interested, I have created django-better-choices library, that provides a nice interface to work with Django choices for Python 3.7+. It supports custom parameters, lots of useful features and is very IDE friendly.

You can define your choices as a class:

from django_better_choices import Choices


class PAGE_STATUS(Choices):
    CREATED = 'Created'
    PENDING = Choices.Value('Pending', help_text='This set status to pending')
    ON_HOLD = Choices.Value('On Hold', value='custom_on_hold')

    VALID = Choices.Subset('CREATED', 'ON_HOLD')

    class INTERNAL_STATUS(Choices):
        REVIEW = 'On Review'

    @classmethod
    def get_help_text(cls):
        return tuple(
            value.help_text
            for value in cls.values()
            if hasattr(value, 'help_text')
        )

Then do the following operations and much much more:

print( PAGE_STATUS.CREATED )                # 'created'
print( PAGE_STATUS.ON_HOLD )                # 'custom_on_hold'
print( PAGE_STATUS.PENDING.display )        # 'Pending'
print( PAGE_STATUS.PENDING.help_text )      # 'This set status to pending'

'custom_on_hold' in PAGE_STATUS.VALID       # True
PAGE_STATUS.CREATED in PAGE_STATUS.VALID    # True

PAGE_STATUS.extract('CREATED', 'ON_HOLD')   # ~= PAGE_STATUS.VALID

for value, display in PAGE_STATUS:
    print( value, display )

PAGE_STATUS.get_help_text()
PAGE_STATUS.VALID.get_help_text()

And of course, it is fully supported by Django and Django Migrations:

class Page(models.Model):
    status = models.CharField(choices=PAGE_STATUS, default=PAGE_STATUS.CREATED)

Full documentation here: https://pypi.org/project/django-better-choices/

Python: Append item to list N times

For immutable data types:

l = [0] * 100
# [0, 0, 0, 0, 0, ...]

l = ['foo'] * 100
# ['foo', 'foo', 'foo', 'foo', ...]

For values that are stored by reference and you may wish to modify later (like sub-lists, or dicts):

l = [{} for x in range(100)]

(The reason why the first method is only a good idea for constant values, like ints or strings, is because only a shallow copy is does when using the <list>*<number> syntax, and thus if you did something like [{}]*100, you'd end up with 100 references to the same dictionary - so changing one of them would change them all. Since ints and strings are immutable, this isn't a problem for them.)

If you want to add to an existing list, you can use the extend() method of that list (in conjunction with the generation of a list of things to add via the above techniques):

a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]

I want to truncate a text or line with ellipsis using JavaScript

HTML with JavaScript:

<p id="myid">My long long looooong text cut cut cut cut cut</p>

<script type="text/javascript">
var myid=document.getElementById('myid');
myid.innerHTML=myid.innerHTML.substring(0,10)+'...';
</script>

The result will be:

My long lo...

Cheers

G.

Default instance name of SQL Server Express

You're right, it's localhost\SQLEXPRESS (just no $) and yes, it's the same for both 2005 and 2008 express versions.

How to update (append to) an href in jquery?

Here is what i tried to do to add parameter in the url which contain the specific character in the url.

jQuery('a[href*="google.com"]').attr('href', function(i,href) {
        //jquery date addition
        var requiredDate = new Date();
        var numberOfDaysToAdd = 60;
        requiredDate.setDate(requiredDate.getDate() + numberOfDaysToAdd); 
        //var convertedDate  = requiredDate.format('d-M-Y');
        //var newDate = datepicker.formatDate('yy/mm/dd', requiredDate );
        //console.log(requiredDate);

        var month   = requiredDate.getMonth()+1;
        var day     = requiredDate.getDate();

        var output = requiredDate.getFullYear() + '/' + ((''+month).length<2 ? '0' : '') + month + '/' + ((''+day).length<2 ? '0' : '') + day;
        //

Working Example Click

HTML favicon won't show on google chrome

A common issue where the favicon will not show up when expected is cache, if your .htaccess for example reads: ExpiresByType image/x-icon "access plus 1 month"

Then simply add a random value to your favicon reference: <link rel="shortcut icon" href="https://example.com/favicon.ico?r=31241" type="image/x-icon" />

Works every time for me even with heavy caching.

How can I calculate the difference between two dates?

Checkout this out. It takes care of daylight saving , leap year as it used iOS calendar to calculate.You can change the string and conditions to includes minutes with hours and days.

+(NSString*)remaningTime:(NSDate*)startDate endDate:(NSDate*)endDate
{
    NSDateComponents *components;
    NSInteger days;
    NSInteger hour;
    NSInteger minutes;
    NSString *durationString;

    components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute fromDate: startDate toDate: endDate options: 0];

    days = [components day];
    hour = [components hour];
    minutes = [components minute];

    if(days>0)
    {
        if(days>1)
            durationString=[NSString stringWithFormat:@"%d days",days];
        else
            durationString=[NSString stringWithFormat:@"%d day",days];
        return durationString;
    }
    if(hour>0)
    {        
        if(hour>1)
            durationString=[NSString stringWithFormat:@"%d hours",hour];
        else
            durationString=[NSString stringWithFormat:@"%d hour",hour];
        return durationString;
    }
    if(minutes>0)
    {
        if(minutes>1)
            durationString = [NSString stringWithFormat:@"%d minutes",minutes];
        else
            durationString = [NSString stringWithFormat:@"%d minute",minutes];

        return durationString;
    }
    return @""; 
}

How do I force Kubernetes to re-pull an image?

The Image pull policy will always actually help to pull the image every single time a new pod is created (this can be in any case like scaling the replicas, or pod dies and new pod is created)

But if you want to update the image of the current running pod, deployment is the best way. It leaves you flawless update without any problem (mainly when you have a persistent volume attached to the pod) :)

How to convert a string variable containing time to time_t type in c++?

With C++11 you can now do

struct std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = mktime(&tm);

see std::get_time and strftime for reference

Pass table as parameter into sql server UDF

Unfortunately, there is no simple way in SQL Server 2005. Lukasz' answer is correct for SQL Server 2008 though and the feature is long overdue

Any solution would involve temp tables, or passing in xml/CSV and parsing in the UDF. Example: change to xml, parse in udf

DECLARE @psuedotable xml

SELECT
    @psuedotable = ...
FROM
    ...
FOR XML ...

SELECT ... dbo.MyUDF (@psuedotable)

What do you want to do in the bigger picture though? There may be another way to do this...

Edit: Why not pass in the query as a string and use a stored proc with output parameter

Note: this is an untested bit of code, and you'd need to think about SQL injection etc. However, it also satisfies your "one column" requirement and should help you along

CREATE PROC dbo.ToCSV (
    @MyQuery varchar(2000),
    @CSVOut varchar(max)
)
AS
SET NOCOUNT ON

CREATE TABLE #foo (bar varchar(max))

INSERT #foo
EXEC (@MyQuery)

SELECT
    @CSVOut = SUBSTRING(buzz, 2, 2000000000)
FROM
    (
    SELECT 
        bar -- maybe CAST(bar AS varchar(max))??
    FROM 
        #foo
    FOR XML PATH (',')
    ) fizz(buzz)
GO

Sql Server : How to use an aggregate function like MAX in a WHERE clause

SELECT rest.field1
FROM mastertable as m
INNER JOIN table1 at t1 on t1.field1 = m.field
INNER JOIN table2 at t2 on t2.field = t1.field
WHERE t1.field3 = (SELECT MAX(field3) FROM table1)

Reading string by char till end of line C/C++

A text file does not have \0 at the end of lines. It has \n. \n is a character, not a string, so it must be enclosed in single quotes

if (c == '\n')

How to change a nullable column to not nullable in a Rails migration?

Per the Strong Migrations gem, using change_column_null in production is a bad idea because it blocks reads and writes while all records are checked.

The recommended way to handle these migrations (Postgres specific) is to separate this process into two migrations.

One to alter the table with the constraint:

class SetSomeColumnNotNull < ActiveRecord::Migration[6.0]
  def change
    safety_assured do
      execute 'ALTER TABLE "users" ADD CONSTRAINT "users_some_column_null" CHECK ("some_column" IS NOT NULL) NOT VALID'
    end
  end
end

And a separate migration to validate it:

class ValidateSomeColumnNotNull < ActiveRecord::Migration[6.0]
  def change
    safety_assured do
      execute 'ALTER TABLE "users" VALIDATE CONSTRAINT "users_some_column_null"'
    end
  end
end

The above examples are pulled (and slightly altered) from the linked documentation. Apparently for Postgres 12+ you can also add NOT NULL to the schema and then drop the constraint after the validation has been run:

class ValidateSomeColumnNotNull < ActiveRecord::Migration[6.0]
  def change
    safety_assured do
      execute 'ALTER TABLE "users" VALIDATE CONSTRAINT "users_some_column_null"'
    end

    # in Postgres 12+, you can then safely set NOT NULL on the column
    change_column_null :users, :some_column, false
    safety_assured do
      execute 'ALTER TABLE "users" DROP CONSTRAINT "users_some_column_null"'
    end
  end
end

Naturally, this means your schema will not show that the column is NOT NULL for earlier versions of Postgres, so I'd also advise setting a model level validation to require the value to be present (though I'd suggest the same even for versions of PG that do allow this step).

Further, before running these migrations you'll want to update all existing records with a value other than null, and make sure any production code that writes to the table is not writing null for the value(s).

Fetch: POST json data

It might be useful to somebody:

I was having the issue that formdata was not being sent for my request

In my case it was a combination of following headers that were also causing the issue and the wrong Content-Type.

So I was sending these two headers with the request and it wasn't sending the formdata when I removed the headers that worked.

"X-Prototype-Version" : "1.6.1",
"X-Requested-With" : "XMLHttpRequest"

Also as other answers suggest that the Content-Type header needs to be correct.

For my request the correct Content-Type header was:

"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"

So bottom line if your formdata is not being attached to the Request then it could potentially be your headers. Try bringing your headers to a minimum and then try adding them one by one to see if your problem is rsolved.

JQuery .on() method with multiple event handlers to one selector

That's the other way around. You should write:

$("table.planning_grid").on({
    mouseenter: function() {
        // Handle mouseenter...
    },
    mouseleave: function() {
        // Handle mouseleave...
    },
    click: function() {
        // Handle click...
    }
}, "td");

Force "git push" to overwrite remote files

Another option (to avoid any forced push which can be problematic for other contributors) is to:

  • put your new commits in a dedicated branch
  • reset your master on origin/master
  • merge your dedicated branch to master, always keeping commits from the dedicated branch (meaning creating new revisions on top of master which will mirror your dedicated branch).
    See "git command for making one branch like another" for strategies to simulate a git merge --strategy=theirs.

That way, you can push master to remote without having to force anything.

LINQ to SQL using GROUP BY and COUNT(DISTINCT)

Linq to sql has no support for Count(Distinct ...). You therefore have to map a .NET method in code onto a Sql server function (thus Count(distinct.. )) and use that.

btw, it doesn't help if you post pseudo code copied from a toolkit in a format that's neither VB.NET nor C#.

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

HTTP Request in Kotlin

Send HTTP POST/GET request with parameters using HttpURLConnection :

POST with Parameters:

fun sendPostRequest(userName:String, password:String) {

    var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8")
    reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8")
    val mURL = URL("<Your API Link>")

    with(mURL.openConnection() as HttpURLConnection) {
        // optional default is GET
        requestMethod = "POST"

        val wr = OutputStreamWriter(getOutputStream());
        wr.write(reqParam);
        wr.flush();

        println("URL : $url")
        println("Response Code : $responseCode")

        BufferedReader(InputStreamReader(inputStream)).use {
            val response = StringBuffer()

            var inputLine = it.readLine()
            while (inputLine != null) {
                response.append(inputLine)
                inputLine = it.readLine()
            }
            println("Response : $response")
        }
    }
}

GET with Parameters:

fun sendGetRequest(userName:String, password:String) {

        var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8")
        reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8")

        val mURL = URL("<Yout API Link>?"+reqParam)

        with(mURL.openConnection() as HttpURLConnection) {
            // optional default is GET
            requestMethod = "GET"

            println("URL : $url")
            println("Response Code : $responseCode")

            BufferedReader(InputStreamReader(inputStream)).use {
                val response = StringBuffer()

                var inputLine = it.readLine()
                while (inputLine != null) {
                    response.append(inputLine)
                    inputLine = it.readLine()
                }
                it.close()
                println("Response : $response")
            }
        }
    }

Bootstrap: adding gaps between divs

An alternative way to accomplish what you are asking, without having problems on the mobile version of your website, (Remember that the margin attribute will brake your responsive layout on mobile version thus you have to add on your element a supplementary attribute like @media (min-width:768px){ 'your-class'{margin:0}} to override the previous margin)

is to nest your class in your preferred div and then add on your class the margin option you want

like the following example: HTML

<div class="container">
  <div class="col-md-3 col-xs-12">
   <div class="events">
     <img src="..."  class="img-responsive" alt="...."/>
     <div class="figcaption">
       <h2>Event Title</h2>
       <p>Event Description.</p>
     </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
</div>

And on your CSS you just add the margin option on your class which in this example is "events" like:

.events{
margin: 20px 10px;
}

By this method you will have all the wanted space between your divs making sure you do not brake anything on your website's mobile and tablet versions.

How to find a value in an array of objects in JavaScript?

If you're going to be doing this search frequently, consider changing the format of your object so dinner actually is a key. This is kind of like assigning a primary clustered key in a database table. So, for example:

Obj = { 'pizza' : { 'name' : 'bob' }, 'sushi' : { 'name' : 'john' } }

You can now easily access it like this: Object['sushi']['name']

Or if the object really is this simple (just 'name' in the object), you could just change it to:

Obj = { 'pizza' : 'bob', 'sushi' : 'john' }

And then access it like: Object['sushi'].

It's obviously not always possible or to your advantage to restructure your data object like this, but the point is, sometimes the best answer is to consider whether your data object is structured the best way. Creating a key like this can be faster and create cleaner code.

Versioning SQL Server database

+1 for everyone who's recommended the RedGate tools, with an additional recommendation and a caveat.

SqlCompare also has a decently documented API: so you can, for instance, write a console app which syncs your source controlled scripts folder with a CI integration testing database on checkin, so that when someone checks in a change to the schema from their scripts folder it's automatically deployed along with the matching application code change. This helps close the gap with developers who are forgetful about propagating changes in their local db up to a shared development DB (about half of us, I think :) ).

A caveat is that with a scripted solution or otherwise, the RedGate tools are sufficiently smooth that it's easy to forget about SQL realities underlying the abstraction. If you rename all the columns in a table, SqlCompare has no way to map the old columns to the new columns and will drop all the data in the table. It will generate warnings but I've seen people click past that. There's a general point here worth making, I think, that you can only automate DB versioning and upgrade so far - the abstractions are very leaky.

ActiveModel::ForbiddenAttributesError when creating new user

If using ActiveAdmin don't forget that there is also a permit_params in the model register block:

ActiveAdmin.register Api::V1::Person do
  permit_params :name, :address, :etc
end

These need to be set along with those in the controller:

def api_v1_person_params
  params.require(:api_v1_person).permit(:name, :address, :etc)
end

Otherwise you will get the error:

ActiveModel::ForbiddenAttributesError

MySQL delete multiple rows in one query conditions unique to each row

Took a lot of googling but here is what I do in Python for MySql when I want to delete multiple items from a single table using a list of values.

#create some empty list
values = []
#continue to append the values you want to delete to it
#BUT you must ensure instead of a string it's a single value tuple
values.append(([Your Variable],))
#Then once your array is loaded perform an execute many
cursor.executemany("DELETE FROM YourTable WHERE ID = %s", values)

How to "properly" print a list?

Here's an interactive session showing some of the steps in @TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)

Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.

>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'

Is there an alternative to string.Replace that is case-insensitive?

Regex.Replace(strInput, strToken.Replace("$", "[$]"), strReplaceWith, RegexOptions.IgnoreCase);

Ellipsis for overflow text in dropdown boxes

NOTE: As of July 2020, text-overflow: ellipsis works for <select> on Chrome

HTML is limited in what it specifies for form controls. That leaves room for operating system and browser makers to do what they think is appropriate on that platform (like the iPhone’s modal select which, when open, looks totally different from the traditional pop-up menu).

If it bugs you, you can use a customizable replacement, like Chosen, which looks distinct from the native select.

Or, file a bug against a major operating system or browser. For all we know, the way text is cut off in selects might be the result of a years-old oversight that everyone copied, and it might be time for a change.

AngularJS - ng-if check string empty value

You don't need to explicitly use qualifiers like item.photo == '' or item.photo != ''. Like in JavaScript, an empty string will be evaluated as false.

Your views will be much cleaner and readable as well.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>_x000D_
<div ng-app init="item = {photo: ''}">_x000D_
   <div ng-if="item.photo"> show if photo is not empty</div>_x000D_
   <div ng-if="!item.photo"> show if photo is empty</div>_x000D_
  _x000D_
   <input type=text ng-model="item.photo" placeholder="photo" />_x000D_
</div
_x000D_
_x000D_
_x000D_

Updated to remove bug in Angular

Extracting specific selected columns to new DataFrame as a copy

As far as I can tell, you don't necessarily need to specify the axis when using the filter function.

new = old.filter(['A','B','D'])

returns the same dataframe as

new = old.filter(['A','B','D'], axis=1)

Return datetime object of previous month

Simplest Way that i have tried Just now

from datetime import datetime
from django.utils import timezone





current = timezone.now()
if current.month == 1:
     month = 12
else:
     month = current.month - 1
current = datetime(current.year, month, current.day)

Python - Using regex to find multiple matches and print them out

Instead of using re.search use re.findall it will return you all matches in a List. Or you could also use re.finditer (which i like most to use) it will return an Iterator Object and you can just use it to iterate over all found matches.

line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
for match in re.finditer('<form>(.*?)</form>', line, re.S):
    print match.group(1)

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

Use X-Requested-With: XMLHttpRequest with your request header. So the response header will not contain WWW-Authenticate:Basic.

beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', ("Basic "
                        .concat(btoa(key))));
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                },

PowerShell script to return versions of .NET Framework on a machine?

Nice solution

Try using the downloadable DotNetVersionLister module (based on registry infos and some version-to-marketing-version lookup table).

Which would be used like this:

PS> Get-DotNetVersion -LocalHost -nosummary


ComputerName : localhost
>=4.x        : 4.5.2
v4\Client    : Installed
v4\Full      : Installed
v3.5         : Installed
v3.0         : Installed
v2.0.50727   : Installed
v1.1.4322    : Not installed (no key)
Ping         : True
Error        :

Or like this if you just want to test it for some .NET framework >= 4.*:

PS> (Get-DotNetVersion -LocalHost -nosummary).">=4.x"
4.5.2

But it will not work (install/import) e.g. with PS v2.0 (Win 7, Win Server 2010 standard) due to incompatibility...

Motivation for "legacy" functions below

(You could skip reading this and use code below)

We had to work with PS 2.0 on some machines and could not install/import the above DotNetVersionLister.
On other machines we wanted to update (from PS 2.0) to PS 5.1 (which in turn needs .NET Framework >= 4.5) with the help of two company-custom Install-DotnetLatestCompany and Install-PSLatestCompany.
To guide admins nicely through the install/update process we would have to determine the .NET version in these functions on all machines and PS versions existing.
Thus we used also the below functions to determine them more safely in all environments...

Functions for legacy PS environments (e.g. PS v2.0)

So the following code and below (extracted) usage examples are useful here (based on other answers here):

function Get-DotNetVersionByFs {
  <#
    .SYNOPSIS
      NOT RECOMMENDED - try using instead:
        Get-DotNetVersion 
          from DotNetVersionLister module (https://github.com/EliteLoser/DotNetVersionLister), 
          but it is not usable/importable in PowerShell 2.0 
        Get-DotNetVersionByReg
          reg(istry) based: (available herin as well) but it may return some wrong version or may not work reliably for versions > 4.5 
          (works in PSv2.0)
      Get-DotNetVersionByFs (this):  
        f(ile) s(ystem) based: determines the latest installed .NET version based on $Env:windir\Microsoft.NET\Framework content
        this is unreliable, e.g. if 4.0* is already installed some 4.5 update will overwrite content there without
        renaming the folder
        (works in PSv2.0)
    .EXAMPLE
      PS> Get-DotnetVersionByFs
      4.0.30319
    .EXAMPLE
      PS> Get-DotnetVersionByFs -All
      1.0.3705
      1.1.4322
      2.0.50727
      3.0
      3.5
      4.0.30319
    .NOTES
      from https://stackoverflow.com/a/52078523/1915920
  #>
    [cmdletbinding()]
  param(
    [Switch]$All  ## do not return only latest, but all installed
  )
  $list = ls $Env:windir\Microsoft.NET\Framework |
    ?{ $_.PSIsContainer -and $_.Name -match '^v\d.[\d\.]+' } |
    %{ $_.Name.TrimStart('v') }
  if ($All) { $list } else { $list | select -last 1 }
}


function Get-DotNetVersionByReg {
  <#
    .SYNOPSIS
      NOT RECOMMENDED - try using instead:
        Get-DotNetVersion
          From DotNetVersionLister module (https://github.com/EliteLoser/DotNetVersionLister), 
          but it is not usable/importable in PowerShell 2.0. 
          Determines the latest installed .NET version based on registry infos under 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP'
    .EXAMPLE
        PS> Get-DotnetVersionByReg
        4.5.51209
    .EXAMPLE
        PS> Get-DotnetVersionByReg -AllDetailed
        PSChildName                                          Version                                             Release
        -----------                                          -------                                             -------
        v2.0.50727                                           2.0.50727.5420
        v3.0                                                 3.0.30729.5420
        Windows Communication Foundation                     3.0.4506.5420
        Windows Presentation Foundation                      3.0.6920.5011
        v3.5                                                 3.5.30729.5420
        Client                                               4.0.0.0
        Client                                               4.5.51209                                           379893
        Full                                                 4.5.51209                                           379893
    .NOTES
      from https://stackoverflow.com/a/52078523/1915920
  #>
    [cmdletbinding()]
    param(
        [Switch]$AllDetailed  ## do not return only latest, but all installed with more details
    )
    $Lookup = @{
        378389 = [version]'4.5'
        378675 = [version]'4.5.1'
        378758 = [version]'4.5.1'
        379893 = [version]'4.5.2'
        393295 = [version]'4.6'
        393297 = [version]'4.6'
        394254 = [version]'4.6.1'
        394271 = [version]'4.6.1'
        394802 = [version]'4.6.2'
        394806 = [version]'4.6.2'
        460798 = [version]'4.7'
        460805 = [version]'4.7'
        461308 = [version]'4.7.1'
        461310 = [version]'4.7.1'
        461808 = [version]'4.7.2'
        461814 = [version]'4.7.2'
    }
    $list = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
        Get-ItemProperty -name Version, Release -EA 0 |
        # For One True framework (latest .NET 4x), change match to PSChildName -eq "Full":
        Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} |
        Select-Object `
           @{
               name = ".NET Framework" ; 
               expression = {$_.PSChildName}}, 
           @{  name = "Product" ; 
               expression = {$Lookup[$_.Release]}}, 
           Version, Release
    if ($AllDetailed) { $list | sort version } else { $list | sort version | select -last 1 | %{ $_.version } }
}

Example usage:

PS> Get-DotNetVersionByFs
4.0.30319

PS> Get-DotNetVersionByFs -All
1.0.3705
1.1.4322
2.0.50727
3.0
3.5
4.0.30319

PS> Get-DotNetVersionByReg
4.5.51209

PS> Get-DotNetVersionByReg -AllDetailed

.NET Framework                   Product Version        Release
--------------                   ------- -------        -------
v2.0.50727                               2.0.50727.5420
v3.0                                     3.0.30729.5420
Windows Communication Foundation         3.0.4506.5420
Windows Presentation Foundation          3.0.6920.5011
v3.5                                     3.5.30729.5420
Client                                   4.0.0.0
Client                           4.5.2   4.5.51209      379893
Full                             4.5.2   4.5.51209      379893

Fail to create Android virtual Device, "No system image installed for this Target"

As a workaround, go to sdk installation directory and perform the following steps:

  • Navigate to system-images/android-19/default
  • Move everything in there to system-images/android-19/

The directory structure should look like this: enter image description here

And it should work!

How do I make a <div> move up and down when I'm scrolling the page?

Here is the Jquery Code

$(document).ready(function () {
     var el = $('#Container');
        var originalelpos = el.offset().top; // take it where it originally is on the page

        //run on scroll
        $(window).scroll(function () {
            var el = $('#Container'); // important! (local)
            var elpos = el.offset().top; // take current situation
            var windowpos = $(window).scrollTop();
            var finaldestination = windowpos + originalelpos;
            el.stop().animate({ 'top': finaldestination }, 1000);
        });
    });

Change the borderColor of the TextBox

WinForms was never good at this and it's a bit of a pain.

One way you can try is by embedding a TextBox in a Panel and then manage the drawing based on focus from there:

public class BorderTextBox : Panel {
  private Color _NormalBorderColor = Color.Gray;
  private Color _FocusBorderColor = Color.Blue;

  public TextBox EditBox;

  public BorderTextBox() {
    this.DoubleBuffered = true;
    this.Padding = new Padding(2);

    EditBox = new TextBox();
    EditBox.AutoSize = false;
    EditBox.BorderStyle = BorderStyle.None;
    EditBox.Dock = DockStyle.Fill;
    EditBox.Enter += new EventHandler(EditBox_Refresh);
    EditBox.Leave += new EventHandler(EditBox_Refresh);
    EditBox.Resize += new EventHandler(EditBox_Refresh);
    this.Controls.Add(EditBox);
  }

  private void EditBox_Refresh(object sender, EventArgs e) {
    this.Invalidate();
  }

  protected override void OnPaint(PaintEventArgs e) {
    e.Graphics.Clear(SystemColors.Window);
    using (Pen borderPen = new Pen(this.EditBox.Focused ? _FocusBorderColor : _NormalBorderColor)) {
      e.Graphics.DrawRectangle(borderPen, new Rectangle(0, 0, this.ClientSize.Width - 1, this.ClientSize.Height - 1));
    }
    base.OnPaint(e);
  }
}

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

Maven: How to include jars, which are not available in reps into a J2EE project?

For people wanting a quick solution to this problem:

<dependency>
  <groupId>LIB_NAME</groupId>
  <artifactId>LIB_NAME</artifactId>
  <version>1.0.0</version>
  <scope>system</scope>
  <systemPath>${basedir}/WebContent/WEB-INF/lib/YOUR_LIB.jar</systemPath>
</dependency>

just give your library a unique groupID and artifact name and point to where it is in the file system. You are good to go.

Of course this is a dirty quick fix that will ONLY work on your machine and if you don't change the path to the libs. But some times, that's all you want, to run and do a few tests.

EDIT: just re-red the question and realised the user was already using my solution as a temporary fix. I'll leave my answer as a quick help for others that come to this question. If anyone disagrees with this please leave me a comment. :)

How to check if a file exists in Documents folder?

Swift 3:

let documentsURL = try! FileManager().url(for: .documentDirectory,
                                          in: .userDomainMask,
                                          appropriateFor: nil,
                                          create: true)

... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:

let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)

Objective-C:

NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];

What is NODE_ENV and how to use it in Express?

Typically, you'd use the NODE_ENV variable to take special actions when you develop, test and debug your code. For example to produce detailed logging and debug output which you don't want in production. Express itself behaves differently depending on whether NODE_ENV is set to production or not. You can see this if you put these lines in an Express app, and then make a HTTP GET request to /error:

app.get('/error', function(req, res) {
  if ('production' !== app.get('env')) {
    console.log("Forcing an error!");
  }
  throw new Error('TestError');
});

app.use(function (req, res, next) {
  res.status(501).send("Error!")
})

Note that the latter app.use() must be last, after all other method handlers!

If you set NODE_ENV to production before you start your server, and then send a GET /error request to it, you should not see the text Forcing an error! in the console, and the response should not contain a stack trace in the HTML body (which origins from Express). If, instead, you set NODE_ENV to something else before starting your server, the opposite should happen.

In Linux, set the environment variable NODE_ENV like this:

export NODE_ENV='value'

Good examples of python-memcache (memcached) being used in Python?

It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.

Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.

If you really want to dig into it, I'd look at the source. Here's the header comment:

"""
client module for memcached (memory cache daemon)

Overview
========

See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

Usage summary
=============

This should give you a feel for how this module operates::

    import memcache
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)

    mc.set("some_key", "Some value")
    value = mc.get("some_key")

    mc.set("another_key", 3)
    mc.delete("another_key")

    mc.set("key", "1")   # note that the key used for incr/decr must be a string.
    mc.incr("key")
    mc.decr("key")

The standard way to use memcache with a database is like this::

    key = derive_key(obj)
    obj = mc.get(key)
    if not obj:
        obj = backend_api.get(...)
        mc.set(key, obj)

    # we now have obj, and future passes through this code
    # will use the object from the cache.

Detailed Documentation
======================

More detailed documentation is available in the L{Client} class.
"""

How to colorize diff on the command line?

I use grc (Generic Colouriser), which allows you to colour the output of a number of commands including diff.

It is a python script which can be wrapped around any command. So instead of invoking diff file1 file2, you would invoke grc diff file1 file2 to see colourised output. I have aliased diff to grc diff to make it easier.

How do I modify a MySQL column to allow NULL?

My solution:

ALTER TABLE table_name CHANGE column_name column_name type DEFAULT NULL

For example:

ALTER TABLE SCHEDULE CHANGE date date DATETIME DEFAULT NULL;

How do I export an Android Studio project?

Source control is best way to handle this problem, if you don't want to pay then try bitbucket

It's free, allows private repo for upto 5 members team.

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I had the same error today, after deploying our service calling an external service to the staging environment in azure. Local the service called the external service without errors, but after deployment it didn't.

In the end it turned out to be that the external service has a IP validation. The new environment in Azure has another IP and it was rejected.

So if you ever get this error calling external services

It might be an IP restriction.

$.ajax( type: "POST" POST method to php

Id advice you to use a bit simplier method -

$.post('edit.php', {title: $('input[name="title"]').val() }, function(resp){
    alert(resp);
});

try this one, I just feels its syntax is simplier than the $.ajax's one...

Celery Received unregistered task of type (run example)

If you are running into this kind of error, there are a number of possible causes but the solution I found was that my celeryd config file in /etc/defaults/celeryd was configured for standard use, not for my specific django project. As soon as I converted it to the format specified in the celery docs, all was well.

Store an array in HashMap

Not sure of the exact question but is this what you are looking for?

public class TestRun
{
     public static void main(String [] args)
     {
        Map<String, Integer[]> prices = new HashMap<String, Integer[]>();

        prices.put("milk", new Integer[] {1, 3, 2});
        prices.put("eggs", new Integer[] {1, 1, 2});
     }
}

How do I launch a program from command line without opening a new cmd window?

20190907

OS: Win 10

I'm making an exe in c++, for some reason usting START make my program fail.

So, just use quotes:

"c:\folder\program.exe"

Pandas count(distinct) equivalent

I am also using nunique but it will be very helpful if you have to use an aggregate function like 'min', 'max', 'count' or 'mean' etc.

df.groupby('YEARMONTH')['CLIENTCODE'].transform('nunique') #count(distinct)
df.groupby('YEARMONTH')['CLIENTCODE'].transform('min')     #min
df.groupby('YEARMONTH')['CLIENTCODE'].transform('max')     #max
df.groupby('YEARMONTH')['CLIENTCODE'].transform('mean')    #average
df.groupby('YEARMONTH')['CLIENTCODE'].transform('count')   #count

Class constants in python

Expanding on betabandido's answer, you could write a function to inject the attributes as constants into the module:

def module_register_class_constants(klass, attr_prefix):
    globals().update(
        (name, getattr(klass, name)) for name in dir(klass) if name.startswith(attr_prefix)
    )

class Animal(object):
    SIZE_HUGE = "Huge"
    SIZE_BIG = "Big"

module_register_class_constants(Animal, "SIZE_")

class Horse(Animal):
    def printSize(self):
        print SIZE_BIG

How to pass model attributes from one Spring MVC controller to another controller?

You can resolve it by using org.springframework.web.servlet.mvc.support.RedirectAttributes.

Here is my controller sample.

@RequestMapping(method = RequestMethod.POST)
    public String eligibilityPost(
            @ModelAttribute("form") @Valid EligibiltyForm form,
            Model model,
            RedirectAttributes redirectAttributes) {
        if(eligibilityService.validateEligibility(form)){
            redirectAttributes.addFlashAttribute("form", form);
            return "redirect:<redirect to your page>";
        }
       return "eligibility";
    }

read more on my blog at http://mayurshah.in/596/how-do-i-redirect-to-page-keeping-model-value

How can I implement custom Action Bar with custom buttons in Android?

enter image description here

This is pretty much as close as you'll get if you want to use the ActionBar APIs. I'm not sure you can place a colorstrip above the ActionBar without doing some weird Window hacking, it's not worth the trouble. As far as changing the MenuItems goes, you can make those tighter via a style. It would be something like this, but I haven't tested it.

<style name="MyTheme" parent="android:Theme.Holo.Light">
    <item name="actionButtonStyle">@style/MyActionButtonStyle</item>
</style>

<style name="MyActionButtonStyle" parent="Widget.ActionButton">
    <item name="android:minWidth">28dip</item>
</style>

Here's how to inflate and add the custom layout to your ActionBar.

    // Inflate your custom layout
    final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(
            R.layout.action_bar,
            null);

    // Set up your ActionBar
    final ActionBar actionBar = getActionBar();
    actionBar.setDisplayShowHomeEnabled(false);
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setCustomView(actionBarLayout);

    // You customization
    final int actionBarColor = getResources().getColor(R.color.action_bar);
    actionBar.setBackgroundDrawable(new ColorDrawable(actionBarColor));

    final Button actionBarTitle = (Button) findViewById(R.id.action_bar_title);
    actionBarTitle.setText("Index(2)");

    final Button actionBarSent = (Button) findViewById(R.id.action_bar_sent);
    actionBarSent.setText("Sent");

    final Button actionBarStaff = (Button) findViewById(R.id.action_bar_staff);
    actionBarStaff.setText("Staff");

    final Button actionBarLocations = (Button) findViewById(R.id.action_bar_locations);
    actionBarLocations.setText("HIPPA Locations");

Here's the custom layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:orientation="horizontal"
    android:paddingEnd="8dip" >

    <Button
        android:id="@+id/action_bar_title"
        style="@style/ActionBarButtonWhite" />

    <Button
        android:id="@+id/action_bar_sent"
        style="@style/ActionBarButtonOffWhite" />

    <Button
        android:id="@+id/action_bar_staff"
        style="@style/ActionBarButtonOffWhite" />

    <Button
        android:id="@+id/action_bar_locations"
        style="@style/ActionBarButtonOffWhite" />

</LinearLayout>

Here's the color strip layout: To use it, just use merge in whatever layout you inflate in setContentView.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/colorstrip"
    android:background="@android:color/holo_blue_dark" />

Here are the Button styles:

<style name="ActionBarButton">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:background">@null</item>
    <item name="android:ellipsize">end</item>
    <item name="android:singleLine">true</item>
    <item name="android:textSize">@dimen/text_size_small</item>
</style>

<style name="ActionBarButtonWhite" parent="@style/ActionBarButton">
    <item name="android:textColor">@color/white</item>
</style>

<style name="ActionBarButtonOffWhite" parent="@style/ActionBarButton">
    <item name="android:textColor">@color/off_white</item>
</style>

Here are the colors and dimensions I used:

<color name="action_bar">#ff0d0d0d</color>
<color name="white">#ffffffff</color>
<color name="off_white">#99ffffff</color>

<!-- Text sizes -->
<dimen name="text_size_small">14.0sp</dimen>
<dimen name="text_size_medium">16.0sp</dimen>

<!-- ActionBar color strip -->
<dimen name="colorstrip">5dp</dimen>

If you want to customize it more than this, you may consider not using the ActionBar at all, but I wouldn't recommend that. You may also consider reading through the Android Design Guidelines to get a better idea on how to design your ActionBar.

If you choose to forgo the ActionBar and use your own layout instead, you should be sure to add action-able Toasts when users long press your "MenuItems". This can be easily achieved using this Gist.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

Your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary POST.

That is: Modern browsers will only allow Ajax calls to services in the same domain as the HTML page.

Example: A page in http://www.example.com/myPage.html can only directly request services that are in http://www.example.com, like http://www.example.com/testservice/etc. If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a CORS request, your browser:

  • Will first send an OPTION request to the target URL
  • And then only if the server response to that OPTION contains the adequate headers (Access-Control-Allow-Origin is one of them) to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).

How to solve it? The simplest way is to enable CORS (enable the necessary headers) on the server.

If you don't have server-side access to it, you can mirror the web service from somewhere else, and then enable CORS there.

Can I change the fill color of an svg path with CSS?

Put in all your svg:

fill="var(--svgcolor)"

In Css:

:root {
  --svgcolor: tomato;
}

To use pseudo-classes:

span.github:hover {
  --svgcolor:aquamarine;
}

Explanation

root = html page.
--svgcolor = a variable.
span.github = selecting a span element with a class github, a svg icon inside and assigning pseudo-class hover.

How to set a maximum execution time for a mysql query?

pt_kill has an option for such. But it is on-demand, not continually monitoring. It does what @Rafa suggested. However see --sentinel for a hint of how to come close with cron.

How to change the URI (URL) for a remote Git repository?

Navigate to the project root of the local repository and check for existing remotes:

git remote -v

If your repository is using SSH you will see something like:

> origin  [email protected]:USERNAME/REPOSITORY.git (fetch)
> origin  [email protected]:USERNAME/REPOSITORY.git (push)

And if your repository is using HTTPS you will see something like:

> origin  https://github.com/USERNAME/REPOSITORY.git (fetch)
> origin  https://github.com/USERNAME/REPOSITORY.git (push)

Changing the URL is done with git remote set-url. Depending on the output of git remote -v, you can change the URL in the following manner:

In case of SSH, you can change the URL from REPOSITORY.git to NEW_REPOSITORY.git like:

$ git remote set-url origin [email protected]:USERNAME/NEW_REPOSITORY.git

And in case of HTTPS, you can change the URL from REPOSITORY.git to NEW_REPOSITORY.git like:

$ git remote set-url origin https://github.com/USERNAME/NEW_REPOSITORY.git

NOTE: If you've changed your GitHub username, you can follow the same process as above to update the change in the username associated with your repository. You would only have to update the USERNAME in the git remote set-url command.

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

Event though it's a bit too late to try to answer this I'll leave what worked for me.

Peceps's solution didn't work because the SuperUser app didn't allow "shell" to have root access. So my solution is to directly use another app like RootExplorer and browse the folders from it.

Inline SVG in CSS

I found one solution for SVG. But it is work only for Webkit, I just want share my workaround with you. In my example is shown how to use SVG element from DOM as background through a filter (background-image: url('#glyph') is not working).

Features needed for this SVG icon render:

  1. Applying SVG filter effects to HTML elements using CSS (IE and Edge not supports)
  2. feImage fragment load supporting (firefox not supports)

_x000D_
_x000D_
.test {_x000D_
  /*  background-image: url('#glyph');_x000D_
    background-size:100% 100%;*/_x000D_
    filter: url(#image); _x000D_
    height:100px;_x000D_
    width:100px;_x000D_
}_x000D_
.test:before {_x000D_
   display:block;_x000D_
   content:'';_x000D_
   color:transparent;_x000D_
}_x000D_
.test2{_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
}_x000D_
.test2:before {_x000D_
   display:block;_x000D_
   content:'';_x000D_
   color:transparent;_x000D_
   filter: url(#image); _x000D_
   height:100px;_x000D_
   width:100px;_x000D_
}
_x000D_
<svg style="height:0;width:0;" version="1.1" viewbox="0 0 100 100"_x000D_
     xmlns="http://www.w3.org/2000/svg"_x000D_
     xmlns:xlink="http://www.w3.org/1999/xlink">_x000D_
 <defs>_x000D_
     <g id="glyph">_x000D_
          <path id="heart" d="M100 34.976c0 8.434-3.635 16.019-9.423 21.274h0.048l-31.25 31.25c-3.125 3.125-6.25 6.25-9.375 6.25s-6.25-3.125-9.375-6.25l-31.202-31.25c-5.788-5.255-9.423-12.84-9.423-21.274 0-15.865 12.861-28.726 28.726-28.726 8.434 0 16.019 3.635 21.274 9.423 5.255-5.788 12.84-9.423 21.274-9.423 15.865 0 28.726 12.861 28.726 28.726z" fill="crimson"/>_x000D_
     </g>_x000D_
    <svg id="resized-glyph"  x="0%" y="0%" width="24" height="24" viewBox="0 0 100 100" class="icon shape-codepen">_x000D_
      <use xlink:href="#glyph"></use>_x000D_
    </svg>_x000D_
     <filter id="image">_x000D_
       <feImage xlink:href="#resized-glyph" x="0%" y="0%" width="100%" height="100%" result="res"/>_x000D_
       <feComposite operator="over" in="res" in2="SourceGraphic"/>_x000D_
    </filter>_x000D_
 </defs>_x000D_
</svg>_x000D_
<div class="test">_x000D_
</div>_x000D_
<div class="test2">_x000D_
</div>
_x000D_
_x000D_
_x000D_

One more solution, is use url encode

_x000D_
_x000D_
var container = document.querySelector(".container");_x000D_
var svg = document.querySelector("svg");_x000D_
var svgText = (new XMLSerializer()).serializeToString(svg);_x000D_
container.style.backgroundImage = `url(data:image/svg+xml;utf8,${encodeURIComponent(svgText)})`;
_x000D_
.container{_x000D_
  height:50px;_x000D_
  width:250px;_x000D_
  display:block;_x000D_
  background-position: center center;_x000D_
  background-repeat: no-repeat;_x000D_
  background-size: contain;_x000D_
}
_x000D_
<svg  height="100" width="500" xmlns="http://www.w3.org/2000/svg">_x000D_
    <ellipse cx="240" cy="50" rx="220" ry="30" style="fill:yellow" />_x000D_
</svg>_x000D_
<div class="container"></div>
_x000D_
_x000D_
_x000D_

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

Try this:

package my_default;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Test {

    public static void main(String[] args) {
        try {
        // Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook();

        // Get first/desired sheet from the workbook
        XSSFSheet sheet = createSheet(workbook, "Sheet 1", false);

        // XSSFSheet sheet = workbook.getSheetAt(1);//Don't use this line
        // because you get Sheet index (1) is out of range (no sheets)

        //Write some information in the cells or do what you want
        XSSFRow row1 = sheet.createRow(0);
        XSSFCell r1c2 = row1.createCell(0);
        r1c2.setCellValue("NAME");
        XSSFCell r1c3 = row1.createCell(1);
        r1c3.setCellValue("AGE");


        //Save excel to HDD Drive
        File pathToFile = new File("D:\\test.xlsx");
        if (!pathToFile.exists()) {
            pathToFile.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(pathToFile);
        workbook.write(fos);
        fos.close();
        System.out.println("Done");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static XSSFSheet createSheet(XSSFWorkbook wb, String prefix, boolean isHidden) {
    XSSFSheet sheet = null;
    int count = 0;

    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        String sName = wb.getSheetName(i);
        if (sName.startsWith(prefix))
            count++;
    }

    if (count > 0) {
        sheet = wb.createSheet(prefix + count);
    } else
        sheet = wb.createSheet(prefix);

    if (isHidden)
        wb.setSheetHidden(wb.getNumberOfSheets() - 1, XSSFWorkbook.SHEET_STATE_VERY_HIDDEN);

        return sheet;
    }

}

Loading inline content using FancyBox

The way I figured this out was going through the example index.html/style.css that comes packaged with the Fancybox installation.

If you view the code that is used for the demo website and basically copy/paste, you'll be fine.

To get an inline Fancybox working, you will need to have this code present in your index.html file:

  <head>
    <link href="./fancybox/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" media="screen" />
    <script>!window.jQuery && document.write('<script src="jquery-1.4.3.min.js"><\/script>');</script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript" src="./fancybox/jquery.fancybox-1.3.4.pack.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {

    $("#various1").fancybox({
            'titlePosition'     : 'inside',
            'transitionIn'      : 'none',
            'transitionOut'     : 'none'
        });
    });
    </script>
  </head>

 <body>

    <a id="various1" href="#inline1" title="Put a title here">Name of Link Here</a>
    <div style="display: none;">
        <div id="inline1" style="width:400px;height:100px;overflow:auto;">
                   Write whatever text you want right here!!
        </div>
    </div> 

</body>

Remember to be precise about what folders your script files are placed in and where you are pointing to in the Head tag; they must correspond.

Loop Through Each HTML Table Column and Get the Data using jQuery

You can try with textContent.

var productId = val[key].textContent;

How to find if directory exists in Python

Two things

  1. check if the directory exist?
  2. if not, create a directory (optional).
import os
dirpath = "<dirpath>" # Replace the "<dirpath>" with actual directory path.

if os.path.exists(dirpath):
   print("Directory exist")
else: #this is optional if you want to create a directory if doesn't exist.
   os.mkdir(dirpath):
   print("Directory created")

Excel - extracting data based on another list

New Excel versions

=IF(ISNA(VLOOKUP(A1,B,B,1,FALSE)),"",A1)

Older Excel versions

=IF(ISNA(VLOOKUP(A1;B:B;1;FALSE));"";A1)

That is: "If the value of A1 exists in the B column, display it here. If it doesn't exist, leave it empty."

Create folder with batch but only if it doesn't already exist

You just use this: if not exist "C:\VTS\" mkdir C:\VTS it wll create a directory only if the folder does not exist.

Note that this existence test will return true only if VTS exists and is a directory. If it is not there, or is there as a file, the mkdir command will run, and should cause an error. You might want to check for whether VTS exists as a file as well.

Remove element of a regular array

The nature of arrays is that their length is immutable. You can't add or delete any of the array items.

You will have to create a new array that is one element shorter and copy the old items to the new array, excluding the element you want to delete.

So it is probably better to use a List instead of an array.

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

"Insufficient Storage Available" even there is lot of free space in device memory

I had the same issue on Galaxy S4 (i9505) on stock ROM (4.2.2 ME2). I had free space like this: 473 MB on /data, 344 MB on /system, 2 GB on /cache. I was getting the free spate error on any download from Play Store (small app, 2.5 MB), I checked LogCat, it said "Cancel download of ABC because insufficient free space".

Then I freed up some space on /data, 600 MB free, and now it's working fine, apps download and install ;). So it seems like this ROM needs a little more free space to work OK...

css - position div to bottom of containing div

Assign position:relative to .outside, and then position:absolute; bottom:0; to your .inside.

Like so:

.outside {
    position:relative;
}
.inside {
    position: absolute;
    bottom: 0;
}

How can I reload .emacs after changing it?

I suggest that you don't do this, initially. Instead, start a new emacs session and test whatever changes you made to see if they work correctly. The reason to do it this way is to avoid leaving you in a state where you have an inoperable .emacs file, which fails to load or fails to load cleanly. If you do all of your editing in the original session, and all of your testing in a new session, you'll always have something reliable to comment out offending code.

When you are finally happy with your changes, then go ahead and use one of the other answers to re-load. My personal preference is to eval just the section you've added/changed, and to do that just highlight the region of added/changed code and call M-x eval-region. Doing that minimizes the code that's evaluated, minimizing any unintentional side-effects, as luapyad points out.

How to remove an HTML element using Javascript?

What's happening is that the form is getting submitted, and so the page is being refreshed (with its original content). You're handling the click event on a submit button.

If you want to remove the element and not submit the form, handle the submit event on the form instead, and return false from your handler:

HTML:

<form  onsubmit="return removeDummy(); ">
    <input type="submit" value="Remove DUMMY"/>
</form>

JavaScript:

function removeDummy() {
    var elem = document.getElementById('dummy');
    elem.parentNode.removeChild(elem);
    return false;
}

But you don't need (or want) a form for that at all, not if its sole purpose is to remove the dummy div. Instead:

HTML:

<input type="button" value="Remove DUMMY" onclick="removeDummy()" />

JavaScript:

function removeDummy() {
    var elem = document.getElementById('dummy');
    elem.parentNode.removeChild(elem);
    return false;
}

However, that style of setting up event handlers is old-fashioned. You seem to have good instincts in that your JavaScript code is in its own file and such. The next step is to take it further and avoid using onXYZ attributes for hooking up event handlers. Instead, in your JavaScript, you can hook them up with the newer (circa year 2000) way instead:

HTML:

<input id='btnRemoveDummy' type="button" value="Remove DUMMY"/>

JavaScript:

function removeDummy() {
    var elem = document.getElementById('dummy');
    elem.parentNode.removeChild(elem);
    return false;
}
function pageInit() {
    // Hook up the "remove dummy" button
    var btn = document.getElementById('btnRemoveDummy');
    if (btn.addEventListener) {
        // DOM2 standard
        btn.addEventListener('click', removeDummy, false);
    }
    else if (btn.attachEvent) {
        // IE (IE9 finally supports the above, though)
        btn.attachEvent('onclick', removeDummy);
    }
    else {
        // Really old or non-standard browser, try DOM0
        btn.onclick = removeDummy;
    }
}

...then call pageInit(); from a script tag at the very end of your page body (just before the closing </body> tag), or from within the window load event, though that happens very late in the page load cycle and so usually isn't good for hooking up event handlers (it happens after all images have finally loaded, for instance).

Note that I've had to put in some handling to deal with browser differences. You'll probably want a function for hooking up events so you don't have to repeat that logic every time. Or consider using a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over those browser differences for you. It's very important to understand the underlying stuff going on, both in terms of JavaScript fundamentals and DOM fundamentals, but libraries deal with a lot of inconsistencies, and also provide a lot of handy utilities — like a means of hooking up event handlers that deals with browser differences. Most of them also provide a way to set up a function (like pageInit) to run as soon as the DOM is ready to be manipulated, long before window load fires.

Merge unequal dataframes and replace missing rows with 0

"all" option does not work anymore, The new parameter is;

x = pd.merge(df1, df2, how="outer")

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

How to make a smooth image rotation in Android?

Try using toDegrees="359" since 360° and 0° are the same.

SSL certificate is not trusted - on mobile only

The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.

If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)

You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

It's because you're calling doGet() without actually implementing doGet(). It's the default implementation of doGet() that throws the error saying the method is not supported.

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

Beside the quite obvious reason (IIS), there is another reason that is common enough for this problem. It is worth to quote this question and its answer here:

http://stackoverflow.com/questions/22994888/why-skype-using-http-or-https-ports-80-and-443 

So, if you have Skype installed in the computer, be sure to check this as well. The solution is quoted here:

To turn off and disable Skype usage of and listening on port 80 and port 443, open the Skype window, then click on Tools menu and select Options. Click on Advanced tab, and go to Connection sub-tab. Untick or uncheck the check box for Use port 80 and 443 as an alternatives for incoming connections option. Click on Save button and then restart Skype to make the change effective.

Using getline() in C++

i think you are not pausing the program before it ended so the output you are putting after getting the inpus is not seeing on the screen right?

do:

getchar();

before the end of the program

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

If you put constrains on a generic class or method, every other generic class or method that is using it need to have "at least" those constrains.

How to show a GUI message box from a bash script in linux?

Here's a little Tcl script that will do what you want. The Wish interpreter should be installed by default on Ubuntu.

#!/usr/bin/wish
pack [label .msg -text [lindex $argv 0]]
pack [entry .ent]
bind .ent <KeyPress-Return> { puts [.ent get]; destroy . }
focus .ent

Call it like this:

myanswer=`gui-prompt "type your answer and press enter"`

How to set a default value in react-select

If your options are like this

var options = [
  { value: 'one', label: 'One' },
  { value: 'two', label: 'Two' }
];

Your {props.input.value} should match one of the 'value' in your {props.options}

Meaning, props.input.value should be either 'one' or 'two'

Don't change link color when a link is clicked

just give

a{
color:blue
}

even if its is visited it will always be blue

Redirect HTTP to HTTPS on default virtual host without ServerName

This is the complete way to omit unneeded redirects, too ;)

These rules are intended to be used in .htaccess files, as a RewriteRule in a *:80 VirtualHost entry needs no Conditions.

RewriteEngine on
RewriteCond %{HTTPS} off [OR] 
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]

Eplanations:

RewriteEngine on

==> enable the engine at all

RewriteCond %{HTTPS} off [OR]

==> match on non-https connections, or (not setting [OR] would cause an implicit AND !)

RewriteCond %{HTTP:X-Forwarded-Proto} !https

==> match on forwarded connections (proxy, loadbalancer, etc.) without https

RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]

==> if one of both Conditions match, do the rewrite of the whole URL, sending a 301 to have this 'learned' by the client (some do, some don't) and the L for the last rule.

How to markdown nested list items in Bitbucket?

This worked for me in Bitbucket Cloud.

Entering this:

* item a
* item b
** item b1
** item b2
* item3

I've got this:

enter image description here

How to set a value of a variable inside a template code?

Use the with statement.

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

I can't imply the code in first paragraph in this answer. Maybe the template language had deprecated the old format.

Good way to encapsulate Integer.parseInt()

After reading the answers to the question I think encapsulating or wrapping the parseInt method is not necessary, maybe even not a good idea.

You could return 'null' as Jon suggested, but that's more or less replacing a try/catch construct by a null-check. There's just a slight difference on the behaviour if you 'forget' error handling: if you don't catch the exception, there's no assignment and the left hand side variable keeps it old value. If you don't test for null, you'll probably get hit by the JVM (NPE).

yawn's suggestion looks more elegant to me, because I do not like returning null to signal some errors or exceptional states. Now you have to check referential equality with a predefined object, that indicates a problem. But, as others argue, if again you 'forget' to check and a String is unparsable, the program continous with the wrapped int inside your 'ERROR' or 'NULL' object.

Nikolay's solution is even more object orientated and will work with parseXXX methods from other wrapper classes aswell. But in the end, he just replaced the NumberFormatException by an OperationNotSupported exception - again you need a try/catch to handle unparsable inputs.

So, its my conclusion to not encapsulate the plain parseInt method. I'd only encapsulate if I could add some (application depended) error handling as well.

How can I listen for a click-and-hold in jQuery?

I made a simple JQuery plugin for this if anyone is interested.

http://plugins.jquery.com/pressAndHold/

Push method in React Hooks (useState)?

setTheArray([...theArray, newElement]); is the simplest answer but be careful for the mutation of items in theArray. Use deep cloning of array items.

Stop Chrome Caching My JS Files

When doing updates to my web applications I will either use a handler to return a single JS file to avoid the massive hits on my server, or add a small query string to them:

<script type="text/javascript" src="/mine/myscript?20111205"></script>

Qt. get part of QString

If you do not need to modify the substring, then you can use QStringRef. The QStringRef class is a read only wrapper around an existing QString that references a substring within the existing string. This gives much better performance than creating a new QString object to contain the sub-string. E.g.

QString myString("This is a string");
QStringRef subString(&myString, 5, 2); // subString contains "is"

If you do need to modify the substring, then left(), mid() and right() will do what you need...

QString myString("This is a string");
QString subString = myString.mid(5,2); // subString contains "is"
subString.append("n't"); // subString contains "isn't"

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

I hate answering my own question, but @Matt Bodily put me on the right track.

The @Html.Action method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The @Url.Action(action, controller, { area = "abc" }) does indeed return the URL, but I finally discovered an overload of Html.ActionLink that provided a better solution for my case:

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)

Note: , null is significant in this case, to match the right signature.

Documentation: @Html.ActionLink (LinkExtensions.ActionLink)

Documentation for this particular overload:

LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)

It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.

Still marking Matt's response as the answer.

Edit: Found yet another HTML helper to solve this:

@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })

How to extract img src, title and alt from html using php?

You may use simplehtmldom. Most of the jQuery selectors are supported in simplehtmldom. An example is given below

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
       echo $element->src . '<br>';

// Find all links
foreach($html->find('a') as $element)
       echo $element->href . '<br>'; 

How to add custom html attributes in JSX

You can do it in componentDidMount() lifecycle method in following way

componentDidMount(){
    const buttonElement = document.querySelector(".rsc-submit-button");
    const inputElement = document.querySelector(".rsc-input");
    buttonElement.setAttribute('aria-hidden', 'true');
    inputElement.setAttribute('aria-label', 'input');
  }

Shortcut key for commenting out lines of Python code in Spyder

On macOS:

Cmd + 1

On Windows, probably

Ctrl + (/) near right shift key

An unhandled exception occurred during the execution of the current web request. ASP.NET

Here is the code with line 156, it has try and catch above it

    /// <summary>
    /// Execute a SQL Query statement, using the default SQL connection for the application
    /// </summary>
    /// <param name="query">SQL query to execute</param>
    /// <returns>DataTable of results</returns>
    public static DataTable Query(string query)
    {
        DataTable results = new DataTable();
        string configConnectionString = "ApplicationServices";

        System.Configuration.Configuration WebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/Web.config");
        System.Configuration.ConnectionStringSettings connString;

        if (WebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
        {
            connString = WebConfig.ConnectionStrings.ConnectionStrings[configConnectionString];

            if (connString != null)
            {
                try
                {
                    using (SqlConnection conn = new SqlConnection(connString.ToString()))
                    using (SqlCommand cmd = new SqlCommand(query, conn))
                    using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
                        dataAdapter.Fill(results);

                    return results;
                }
                catch (Exception ex)
                {
                    throw new SqlException(string.Format("SqlException occurred during query execution: ", ex));
                }
            }
            else
            {
                throw new SqlException(string.Format("Connection string for " + configConnectionString + "is null."));
            }
        }
        else
        {
            throw new SqlException(string.Format("No connection strings found in Web.config file."));
        }
    }

How to return a table from a Stored Procedure?

It's VERY important to include:

 SET NOCOUNT ON;

into SP, In First line, if you do INSERT in SP, the END SELECT can't return values.

THEN, in vb60 you can:

SET RS = CN.EXECUTE(SQL)

OR:

RS.OPEN CN, RS, SQL

How should I validate an e-mail address?

email is your email-is.

public boolean validateEmail(String email) {

    Pattern pattern;
    Matcher matcher;
    String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    pattern = Pattern.compile(EMAIL_PATTERN);
    matcher = pattern.matcher(email);
    return matcher.matches();

    }

How to represent the double quotes character (") in regex?

Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex.

However, because java uses double quotes to delimit String constants, if you want to create a string in java with a double quote in it, you must escape them.

This code will test if your String matches:

if (str.matches("\".*\"")) {
    // this string starts and end with a double quote
}

Note that you don't need to add start and end of input markers (^ and $) in the regex, because matches() requires that the whole input be matched to return true - ^ and $ are implied.

How to get an object's methods?

You can use console.dir(object) to write that objects properties to the console.

Iterate over array of objects in Typescript

You can use the built-in forEach function for arrays.

Like this:

//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
    element.product_desc = element.product_desc.substring(0,10);
});

Your version wasn't wrong though. It should look more like this:

for(let i=0; i<data.products.length; i++){
    console.log(data.products[i].product_desc); //use i instead of 0
}

Python NoneType object is not callable (beginner)

You want to pass the function object hi to your loop() function, not the result of a call to hi() (which is None since hi() doesn't return anything).

So try this:

>>> loop(hi, 5)
hi
hi
hi
hi
hi

Perhaps this will help you understand better:

>>> print hi()
hi
None
>>> print hi
<function hi at 0x0000000002422648>

C# how to create a Guid value?

If you want to create a "desired" Guid you can do

var tempGuid = Guid.Parse("<guidValue>");

where <guidValue> would be something like 1A3B944E-3632-467B-A53A-206305310BAE.

how to set windows service username and password through commandline

This works:

sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"

Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)

Just keep in mind that:

  • The spacing in the above example matters. obj= "foo" is correct; obj="foo" is not.
  • '.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
  • Passwords aren't validated until the service is started
  • Quote your parameters, as above. You can sometimes get by without quotes, but good luck.

CSS - display: none; not working

Remove display: block; in the div #tfl style property

<div id="tfl" style="display: block; width: 187px; height: 260px;

Inline style take priority then css file

Thread pooling in C++11

Follwoing [PhD EcE](https://stackoverflow.com/users/3818417/phd-ece) suggestion, I implemented the thread pool:

function_pool.h

#pragma once
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <cassert>

class Function_pool
{

private:
    std::queue<std::function<void()>> m_function_queue;
    std::mutex m_lock;
    std::condition_variable m_data_condition;
    std::atomic<bool> m_accept_functions;

public:

    Function_pool();
    ~Function_pool();
    void push(std::function<void()> func);
    void done();
    void infinite_loop_func();
};

function_pool.cpp

#include "function_pool.h"

Function_pool::Function_pool() : m_function_queue(), m_lock(), m_data_condition(), m_accept_functions(true)
{
}

Function_pool::~Function_pool()
{
}

void Function_pool::push(std::function<void()> func)
{
    std::unique_lock<std::mutex> lock(m_lock);
    m_function_queue.push(func);
    // when we send the notification immediately, the consumer will try to get the lock , so unlock asap
    lock.unlock();
    m_data_condition.notify_one();
}

void Function_pool::done()
{
    std::unique_lock<std::mutex> lock(m_lock);
    m_accept_functions = false;
    lock.unlock();
    // when we send the notification immediately, the consumer will try to get the lock , so unlock asap
    m_data_condition.notify_all();
    //notify all waiting threads.
}

void Function_pool::infinite_loop_func()
{
    std::function<void()> func;
    while (true)
    {
        {
            std::unique_lock<std::mutex> lock(m_lock);
            m_data_condition.wait(lock, [this]() {return !m_function_queue.empty() || !m_accept_functions; });
            if (!m_accept_functions && m_function_queue.empty())
            {
                //lock will be release automatically.
                //finish the thread loop and let it join in the main thread.
                return;
            }
            func = m_function_queue.front();
            m_function_queue.pop();
            //release the lock
        }
        func();
    }
}

main.cpp

#include "function_pool.h"
#include <string>
#include <iostream>
#include <mutex>
#include <functional>
#include <thread>
#include <vector>

Function_pool func_pool;

class quit_worker_exception : public std::exception {};

void example_function()
{
    std::cout << "bla" << std::endl;
}

int main()
{
    std::cout << "stating operation" << std::endl;
    int num_threads = std::thread::hardware_concurrency();
    std::cout << "number of threads = " << num_threads << std::endl;
    std::vector<std::thread> thread_pool;
    for (int i = 0; i < num_threads; i++)
    {
        thread_pool.push_back(std::thread(&Function_pool::infinite_loop_func, &func_pool));
    }

    //here we should send our functions
    for (int i = 0; i < 50; i++)
    {
        func_pool.push(example_function);
    }
    func_pool.done();
    for (unsigned int i = 0; i < thread_pool.size(); i++)
    {
        thread_pool.at(i).join();
    }
}

Get Absolute Position of element within the window in wpf

I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.

For that, there is the TransformToAncestor method:

Point relativePoint = myVisual.TransformToAncestor(rootVisual)
                              .Transform(new Point(0, 0));

Where myVisual is the element that was just double-clicked, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

How to Execute SQL Server Stored Procedure in SQL Developer?

Select * from Table name ..i.e(are you save table name in sql(TEST) k.

Select * from TEST then you will execute your project.

Android - Center TextView Horizontally in LinearLayout

If you set <TextView> in center in <Linearlayout> then first put android:layout_width="fill_parent" compulsory
No need of using any other gravity

    <LinearLayout
            android:layout_toRightOf="@+id/linear_profile" 
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:orientation="vertical"
            android:gravity="center_horizontal">
            <TextView 
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="It's.hhhhhhhh...."
                android:textColor="@color/Black"

                />
    </LinearLayout>

How to run a JAR file

You have to add a manifest to the jar, which tells the java runtime what the main class is. Create a file 'Manifest.mf' with the following content:

Manifest-Version: 1.0
Main-Class: your.programs.MainClass

Change 'your.programs.MainClass' to your actual main class. Now put the file into the Jar-file, in a subfolder named 'META-INF'. You can use any ZIP-utility for that.

How do I use spaces in the Command Prompt?

Try to provide complex pathnames in double-quotes (and include file extensions at the end for files.)

For files:

call "C:\example file.exe"

For Directory:

cd "C:\Users\User Name\New Folder"

CMD interprets text with double quotes ("xyz") as one string and text within single quotes ('xyz') as a command. For example:

FOR %%A in ('dir /b /s *.txt') do ('command')

FOR %%A in ('dir /b /s *.txt') do (echo "%%A")

And one good thing, cmd is not* case sensitive like bash. So "New fiLE.txt" and "new file.TXT" is alike to it.

*Note: The %%A variables in above case is case-sensitive (%%A not equal to %%a).

WhatsApp API (java/python)

From my blog

courtesy

There is a secret pilot program which WhatsApp is working on with selected businesses

News coverage:

For some of my technical experiments, I was trying to figure out how beneficial and feasible it is to implement bots for different chat platforms in terms of market share and so possibilities of adaptation. Especially when you have bankruptly failed twice, it's important to validate ideas and fail more faster.

Popular chat platforms like Messenger, Slack, Skype etc. have happily (in the sense officially) provided APIs for bots to interact with, but WhatsApp has not yet provided any API.

However, since many years, a lot of activities has happened around this - struggle towards automated interaction with WhatsApp platform:

  1. Bots App Bots App is interesting because it shows that something is really tried and tested.

  2. Yowsup A project still actively developed to interact with WhatsApp platform.

  3. Yallagenie Yallagenie claim that there is a demo bot which can be interacted with at +971 56 112 6652

  4. Hubtype Hubtype is working towards having a bot platform for WhatsApp for business.

  5. Fred Fred's task was to automate WhatsApp conversations, however since it was not officially supported by WhatsApp - it was shut down.

  6. Oye Gennie A bot blocked by WhatsApp.

  7. App/Website to WhatsApp We can use custom URL schemes and Android intent system to interact with WhatsApp but still NOT WhatsApp API.

  8. Chat API daemon Probably created by inspecting the API calls in WhatsApp web version. NOT affiliated with WhatsApp.

  9. WhatsBot Deactivated WhatsApp bot. Created during a hackathon.

  10. No API claim WhatsApp co-founder clearly stated this in a conference that they did not had any plans for APIs for WhatsApp.

  11. Bot Ware They probably are expecting WhatsApp to release their APIs for chat bot platforms.

  12. Vixi They seems to be talking about how some platform which probably would work for WhatsApp. There is no clarity as such.

  13. Unofficial API This API can shut off any time.

    And the number goes on...

"Unable to acquire application service" error while launching Eclipse

Download new eclipse or spring suite and open old workspace into new eclipse or STS

How to get the caller's method name in the called method?

This seems to work just fine:

import sys
print sys._getframe().f_back.f_code.co_name

Null check in an enhanced for loop

You could potentially write a helper method which returned an empty sequence if you passed in null:

public static <T> Iterable<T> emptyIfNull(Iterable<T> iterable) {
    return iterable == null ? Collections.<T>emptyList() : iterable;
}

Then use:

for (Object object : emptyIfNull(someList)) {
}

I don't think I'd actually do that though - I'd usually use your second form. In particular, the "or throw ex" is important - if it really shouldn't be null, you should definitely throw an exception. You know that something has gone wrong, but you don't know the extent of the damage. Abort early.

C# Pass Lambda Expression as Method Parameter

Lambda expressions have a type of Action<parameters> (in case they don't return a value) or Func<parameters,return> (in case they have a return value). In your case you have two input parameters, and you need to return a value, so you should use:

Func<FullTimeJob, Student, FullTimeJob>

Sending Email in Android using JavaMail API without using the default/built-in app

here is an alt version that also works for me and has attachments (posted already above but complete version unlike the source link, which people posted they cant get it to work since its missing data)

import java.util.Date; 
import java.util.Properties; 
import javax.activation.CommandMap; 
import javax.activation.DataHandler; 
import javax.activation.DataSource; 
import javax.activation.FileDataSource; 
import javax.activation.MailcapCommandMap; 
import javax.mail.BodyPart; 
import javax.mail.Multipart; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeBodyPart; 
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart; 


public class Mail extends javax.mail.Authenticator { 
  private String _user; 
  private String _pass; 

  private String[] _to; 
  private String _from; 

  private String _port; 
  private String _sport; 

  private String _host; 

  private String _subject; 
  private String _body; 

  private boolean _auth; 

  private boolean _debuggable; 

  private Multipart _multipart; 


  public Mail() { 
    _host = "smtp.gmail.com"; // default smtp server 
    _port = "465"; // default smtp port 
    _sport = "465"; // default socketfactory port 

    _user = ""; // username 
    _pass = ""; // password 
    _from = ""; // email sent from 
    _subject = ""; // email subject 
    _body = ""; // email body 

    _debuggable = false; // debug mode on or off - default off 
    _auth = true; // smtp authentication - default on 

    _multipart = new MimeMultipart(); 

    // There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added. 
    MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); 
    mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); 
    mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); 
    mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); 
    mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
    mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); 
    CommandMap.setDefaultCommandMap(mc); 
  } 

  public Mail(String user, String pass) { 
    this(); 

    _user = user; 
    _pass = pass; 
  } 

  public boolean send() throws Exception { 
    Properties props = _setProperties(); 

    if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) { 
      Session session = Session.getInstance(props, this); 

      MimeMessage msg = new MimeMessage(session); 

      msg.setFrom(new InternetAddress(_from)); 

      InternetAddress[] addressTo = new InternetAddress[_to.length]; 
      for (int i = 0; i < _to.length; i++) { 
        addressTo[i] = new InternetAddress(_to[i]); 
      } 
        msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); 

      msg.setSubject(_subject); 
      msg.setSentDate(new Date()); 

      // setup message body 
      BodyPart messageBodyPart = new MimeBodyPart(); 
      messageBodyPart.setText(_body); 
      _multipart.addBodyPart(messageBodyPart); 

      // Put parts in message 
      msg.setContent(_multipart); 

      // send email 
      Transport.send(msg); 

      return true; 
    } else { 
      return false; 
    } 
  } 

  public void addAttachment(String filename) throws Exception { 
    BodyPart messageBodyPart = new MimeBodyPart(); 
    DataSource source = new FileDataSource(filename); 
    messageBodyPart.setDataHandler(new DataHandler(source)); 
    messageBodyPart.setFileName(filename); 

    _multipart.addBodyPart(messageBodyPart); 
  } 

  @Override 
  public PasswordAuthentication getPasswordAuthentication() { 
    return new PasswordAuthentication(_user, _pass); 
  } 

  private Properties _setProperties() { 
    Properties props = new Properties(); 

    props.put("mail.smtp.host", _host); 

    if(_debuggable) { 
      props.put("mail.debug", "true"); 
    } 

    if(_auth) { 
      props.put("mail.smtp.auth", "true"); 
    } 

    props.put("mail.smtp.port", _port); 
    props.put("mail.smtp.socketFactory.port", _sport); 
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
    props.put("mail.smtp.socketFactory.fallback", "false"); 

    return props; 
  } 

  // the getters and setters 
  public String getBody() { 
    return _body; 
  } 

  public void setBody(String _body) { 
    this._body = _body; 
  }

  public void setTo(String[] toArr) {
      // TODO Auto-generated method stub
      this._to=toArr;
  }

  public void setFrom(String string) {
      // TODO Auto-generated method stub
      this._from=string;
  }

  public void setSubject(String string) {
      // TODO Auto-generated method stub
      this._subject=string;
  }  

  // more of the getters and setters ….. 
}

and to call it in an activity...

@Override 
public void onCreate(Bundle icicle) { 
  super.onCreate(icicle); 
  setContentView(R.layout.main); 

  Button addImage = (Button) findViewById(R.id.send_email); 
  addImage.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View view) { 
      Mail m = new Mail("[email protected]", "password"); 

      String[] toArr = {"[email protected]", "[email protected]"}; 
      m.setTo(toArr); 
      m.setFrom("[email protected]"); 
      m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device."); 
      m.setBody("Email body."); 

      try { 
        m.addAttachment("/sdcard/filelocation"); 

        if(m.send()) { 
          Toast.makeText(MailApp.this, "Email was sent successfully.", Toast.LENGTH_LONG).show(); 
        } else { 
          Toast.makeText(MailApp.this, "Email was not sent.", Toast.LENGTH_LONG).show(); 
        } 
      } catch(Exception e) { 
        //Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show(); 
        Log.e("MailApp", "Could not send email", e); 
      } 
    } 
  }); 
} 

How can I copy columns from one sheet to another with VBA in Excel?

Selecting is often unnecessary. Try this

Sub OneCell()
    Sheets("Sheet2").range("B1:B3").value = Sheets("Sheet1").range("A1:A3").value
End Sub

Youtube iframe wmode issue

If you are using the new asynchronous API, you will need to add the parameter like so:

<!-- YOUTUBE -->
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;
var initialVideo = 'ApkM4t9L5jE'; // YOUR YOUTUBE VIDEO ID
function onYouTubePlayerAPIReady() {
    console.log("onYouTubePlayerAPIReady" + initialVideo);
    player = new YT.Player('player', {
      height: '381',
      width: '681',
      wmode: 'transparent', // SECRET SAUCE HERE
      videoId: initialVideo,      
       playerVars: { 'autoplay': 1, 'rel': 0, 'wmode':'transparent' },
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
}

This is based on the google documentation and example here: http://code.google.com/apis/youtube/iframe_api_reference.html