Programs & Examples On #Xnanimation

How to get the full url in Express?

I use the node package 'url' (npm install url)

What it does is when you call

url.parse(req.url, true, true)

it will give you the possibility to retrieve all or parts of the url. More info here: https://github.com/defunctzombie/node-url

I used it in the following way to get whatever comes after the / in http://www.example.com/ to use as a variable and pull up a particular profile (kind of like facebook: http://www.facebook.com/username)

    var url = require('url');
    var urlParts = url.parse(req.url, true, true);
    var pathname = urlParts.pathname;
    var username = pathname.slice(1);

Though for this to work, you have to create your route this way in your server.js file:

self.routes['/:username'] = require('./routes/users');

And set your route file this way:

router.get('/:username', function(req, res) {
 //here comes the url parsing code
}

Position Relative vs Absolute?

Marco Pellicciotta: The position of the element inside another element can be relative or absolute, about the element it's inside.

If you need to position the element in the browser window point of view it's best to use position:fixed

How do you list volumes in docker containers?

Show names and mount point destinations of volumes used by a container:

docker container inspect \
 -f '{{ range .Mounts }}{{ .Name }}:{{ .Destination }} {{ end }}' \
 CONTAINER_ID_OR_NAME

This is compatible with Docker 1.13.

file_get_contents behind a proxy?

There's a similar post here: http://techpad.co.uk/content.php?sid=137 which explains how to do it.

function file_get_contents_proxy($url,$proxy){

    // Create context stream
    $context_array = array('http'=>array('proxy'=>$proxy,'request_fulluri'=>true));
    $context = stream_context_create($context_array);

    // Use context stream with file_get_contents
    $data = file_get_contents($url,false,$context);

    // Return data via proxy
    return $data;

}

Swift: How to get substring from start to last index of character

Swift 4:

extension String {

    /// the length of the string
    var length: Int {
        return self.characters.count
    }

    /// Get substring, e.g. "ABCDE".substring(index: 2, length: 3) -> "CDE"
    ///
    /// - parameter index:  the start index
    /// - parameter length: the length of the substring
    ///
    /// - returns: the substring
    public func substring(index: Int, length: Int) -> String {
        if self.length <= index {
            return ""
        }
        let leftIndex = self.index(self.startIndex, offsetBy: index)
        if self.length <= index + length {
            return self.substring(from: leftIndex)
        }
        let rightIndex = self.index(self.endIndex, offsetBy: -(self.length - index - length))
        return self.substring(with: leftIndex..<rightIndex)
    }

    /// Get substring, e.g. -> "ABCDE".substring(left: 0, right: 2) -> "ABC"
    ///
    /// - parameter left:  the start index
    /// - parameter right: the end index
    ///
    /// - returns: the substring
    public func substring(left: Int, right: Int) -> String {
        if length <= left {
            return ""
        }
        let leftIndex = self.index(self.startIndex, offsetBy: left)
        if length <= right {
            return self.substring(from: leftIndex)
        }
        else {
            let rightIndex = self.index(self.endIndex, offsetBy: -self.length + right + 1)
            return self.substring(with: leftIndex..<rightIndex)
        }
    }
}

you can test it as follows:

    print("test: " + String("ABCDE".substring(index: 2, length: 3) == "CDE"))
    print("test: " + String("ABCDE".substring(index: 0, length: 3) == "ABC"))
    print("test: " + String("ABCDE".substring(index: 2, length: 1000) == "CDE"))
    print("test: " + String("ABCDE".substring(left: 0, right: 2) == "ABC"))
    print("test: " + String("ABCDE".substring(left: 1, right: 3) == "BCD"))
    print("test: " + String("ABCDE".substring(left: 3, right: 1000) == "DE"))

Check https://gitlab.com/seriyvolk83/SwiftEx library. It contains these and other helpful methods.

fatal: The current branch master has no upstream branch

Apparently you also get this error message when you forget the --all parameter when pushing for the first time. I wrote

git push -u origin

which gave this error, it should have been

git push -u origin --all

Oh how I love these copy-paste errors ...

undefined reference to WinMain@16 (codeblocks)

I was interested in setting up graphics for Code Blocks when I ran into a this error: (took me 2 hrs to solve it)

I guess you need to have a bit of luck with this. In my case i just changed the order of contents in Settings menu->Compiler and Debugger->Global compiler settings->Linker settings->Other Linker Options: The working sequence is: -lmingw32 -lSDL -lSDLmain

How to compare binary files to check if they are the same?

I found Visual Binary Diff was what I was looking for, available on:

  • Ubuntu:

    sudo apt install vbindiff
    
  • Arch Linux:

    sudo pacman -S vbindiff
    
  • Mac OS X via MacPorts:

    port install vbindiff
    
  • Mac OS X via Homebrew:

    brew install vbindiff
    

return error message with actionResult

Inside Controller Action you can access HttpContext.Response. There you can set the response status as in the following listing.

[HttpPost]
public ActionResult PostViaAjax()
{
    var body = Request.BinaryRead(Request.TotalBytes);

    var result = Content(JsonError(new Dictionary<string, string>()
    {
        {"err", "Some error!"}
    }), "application/json; charset=utf-8");
    HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    return result;
}

Soft hyphen in HTML (<wbr> vs. &shy;)

Sometimes web browsers seems to be more forgiving if you use the Unicode string &#173; rather than the &shy; entity.

How can I create directory tree in C++/Linux?

Easy with Boost.Filesystem: create_directories

#include <boost/filesystem.hpp>
//...
boost::filesystem::create_directories("/tmp/a/b/c");

Returns: true if a new directory was created, otherwise false.

React native ERROR Packager can't listen on port 8081

This might be because of McAfee using that port. Doing simple lsof -i 8081 may not show the application and you may have to sudo it.

Do sudo lsof -i 8081 and if this command gives an output you can kill it by using sudo launchctl remove com.mcafee.agent.macmn. After this start packager again.

How do you round UP a number in Python?

I'm basically a beginner at Python, but if you're just trying to round up instead of down why not do:

round(integer) + 1

What MySQL data type should be used for Latitude/Longitude with 8 decimal places?

Do not use float... It will round your coordinates, resulting in some strange occurrences.

Use decimal

Laravel Eloquent update just if changes have been made

I like to add this method, if you are using an edit form, you can use this code to save the changes in your update(Request $request, $id) function:

$post = Post::find($id);    
$post->fill($request->input())->save();

keep in mind that you have to name your inputs with the same column name. The fill() function will do all the work for you :)

What is an idiomatic way of representing enums in Go?

As of Go 1.4, the go generate tool has been introduced together with the stringer command that makes your enum easily debuggable and printable.

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>

Is there a naming convention for MySQL?

Simple Answer: NO

Well, at least a naming convention as such encouraged by Oracle or community, no, however, basically you have to be aware of following the rules and limits for identifiers, such as indicated in MySQL documentation: https://dev.mysql.com/doc/refman/8.0/en/identifiers.html

About the naming convention you follow, I think it is ok, just the number 5 is a little bit unnecesary, I think most visual tools for managing databases offer a option for sorting column names (I use DBeaver, and it have it), so if the purpouse is having a nice visual presentation of your table you can use this option I mention.

By personal experience, I would recommed this:

  • Use lower case. This almost ensures interoperability when you migrate your databases from one server to another. Sometimes the lower_case_table_names is not correctly configured and your server start throwing errors just by simply unrecognizing your camelCase or PascalCase standard (case sensitivity problem).
  • Short names. Simple and clear. The most easy and fast is identify your table or columns, the better. Trust me, when you make a lot of different queries in a short amount of time is better having all simple to write (and read).
  • Avoid prefixes. Unless you are using the same database for tables of different applications, don't use prefixes. This only add more verbosity to your queries. There are situations when this could be useful, for example, when you want to indentify primary keys and foreign keys, that usually table names are used as prefix for id columns.
  • Use underscores for separating words. If you still want to use more than one word for naming a table, column, etc., so use underscores for separating_the_words, this helps for legibility (your eyes and your stressed brain are going to thank you).
  • Be consistent. Once you have your own standard, follow it. Don´t be the person that create the rules and is the first who breaking them, that is shameful.

And what about the "Plural vs Singular" naming? Well, this is most a situation of personal preferences. In my case I try to use plural names for tables because I think a table as a collection of elements or a package containig elements, so a plural name make sense for me; and singular names for columns because I see columns as attributes that describe singularly to those table elements.

Download TS files from video stream

You can use Xtreme Download Manager(XDM) software for this. This software can download from any site in this format. Even this software can change the ts file format. You only need to change the format when downloading.

like:https://www.videohelp.com/software/Xtreme-Download-Manager-

How do I tell what type of value is in a Perl variable?

A scalar always holds a single element. Whatever is in a scalar variable is always a scalar. A reference is a scalar value.

If you want to know if it is a reference, you can use ref. If you want to know the reference type, you can use the reftype routine from Scalar::Util.

If you want to know if it is an object, you can use the blessed routine from Scalar::Util. You should never care what the blessed package is, though. UNIVERSAL has some methods to tell you about an object: if you want to check that it has the method you want to call, use can; if you want to see that it inherits from something, use isa; and if you want to see it the object handles a role, use DOES.

If you want to know if that scalar is actually just acting like a scalar but tied to a class, try tied. If you get an object, continue your checks.

If you want to know if it looks like a number, you can use looks_like_number from Scalar::Util. If it doesn't look like a number and it's not a reference, it's a string. However, all simple values can be strings.

If you need to do something more fancy, you can use a module such as Params::Validate.

Getting the number of filled cells in a column (VBA)

You can also use

Cells.CurrentRegion

to give you a range representing the bounds of your data on the current active sheet

Msdn says on the topic

Returns a Range object that represents the current region. The current region is a range bounded by any combination of blank rows and blank columns. Read-only.

Then you can determine the column count via

Cells.CurrentRegion.Columns.Count

and the row count via

Cells.CurrentRegion.Rows.Count

Find nginx version?

If you don't know where it is, locate nginx first.

ps -ef | grep nginx

Then you will see something like this:

root      4801     1  0 May23 ?        00:00:00 nginx: master process /opt/nginx/sbin/nginx -c /opt/nginx/conf/nginx.conf
root     12427 11747  0 03:53 pts/1    00:00:00 grep --color=auto nginx
nginx    24012  4801  0 02:30 ?        00:00:00 nginx: worker process                              
nginx    24013  4801  0 02:30 ?        00:00:00 nginx: worker process

So now you already know where nginx is. You can use the -v or -V. Something like:

/opt/nginx/sbin/nginx -v

how to count the spaces in a java string?

\t will match tabs, rather than spaces and should also be referred to with a double slash: \\t. You could call s.split( " " ) but that wouldn't count consecutive spaces. By that I mean...

String bar = " ba jfjf jjj j   ";
String[] split = bar.split( " " );
System.out.println( split.length ); // Returns 5

So, despite the fact there are seven space characters, there are only five blocks of space. It depends which you're trying to count, I guess.

Commons Lang is your friend for this one.

int count = StringUtils.countMatches( inputString, " " );

Laravel Unknown Column 'updated_at'

Nice answer by Alex and Sameer, but maybe just additional info on why is necessary to put

public $timestamps = false;

Timestamps are nicely explained on official Laravel page:

By default, Eloquent expects created_at and updated_at columns to exist on your >tables. If you do not wish to have these columns automatically managed by >Eloquent, set the $timestamps property on your model to false.

Randomize a List<T>

    List<T> OriginalList = new List<T>();
    List<T> TempList = new List<T>();
    Random random = new Random();
    int length = OriginalList.Count;
    int TempIndex = 0;

    while (length > 0) {
        TempIndex = random.Next(0, length);  // get random value between 0 and original length
        TempList.Add(OriginalList[TempIndex]); // add to temp list
        OriginalList.RemoveAt(TempIndex); // remove from original list
        length = OriginalList.Count;  // get new list <T> length.
    }

    OriginalList = new List<T>();
    OriginalList = TempList; // copy all items from temp list to original list.

Call php function from JavaScript

PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.

I would like to see a hash_map example in C++

The current C++ standard does not have hash maps, but the coming C++0x standard does, and these are already supported by g++ in the shape of "unordered maps":

#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;

int main() {
    unordered_map <string, int> m;
    m["foo"] = 42;
    cout << m["foo"] << endl;
}

In order to get this compile, you need to tell g++ that you are using C++0x:

g++ -std=c++0x main.cpp

These maps work pretty much as std::map does, except that instead of providing a custom operator<() for your own types, you need to provide a custom hash function - suitable functions are provided for types like integers and strings.

get the data of uploaded file in javascript

FileReaderJS can read the files for you. You get the file content inside onLoad(e) event handler as e.target.result.

Extract the last substring from a cell

If you want to get the second to last word in a text, you can use this macro as a function in your spreadsheet:

Public Function Get2ndText(S As String) As String

Dim sArr() As String
Dim i As Integer
sArr = Split(S, " ")

'get the next to the last string
i = UBound(sArr) - 1
Get2ndText = sArr(i)

End Function

Then in your spreadsheet B1 as the text:

CURRENT OWNER 915 BROADWAY ST HOUSTON TX 77012-2126

in B2 your formula would be:

=Get2ndText(B1)

The result would be

TX

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

You need to have DocumentFormat.OpenXML.dll in the same folder as your application - or in the 'bin' path if you are developing an ASP.NET application. However, I'm not certain that the OpenXML SDK is supported on non-Windows operating systems - you may need to look into a third-party solution.

Yes, this answer is right, the only difference is that you copy your .dll into bin folder of the project.

Simple DatePicker-like Calendar

this datepicker is an excellent solution. datepickers are a must if you want to avoid code injection.

How to use Java property files?

If you put the properties file in the same package as class Foo, you can easily load it with

new Properties().load(Foo.class.getResourceAsStream("file.properties"))

Given that Properties extends Hashtable you can iterate over the values in the same manner as you would in a Hashtable.

If you use the *.properties extension you can get editor support, e.g. Eclipse has a properties file editor.

SQL: How to to SUM two values from different tables

select region,sum(number) total
from
(
    select region,number
    from cash_table
    union all
    select region,number
    from cheque_table
) t
group by region

When to use cla(), clf() or close() for clearing a plot in matplotlib?

They all do different things, since matplotlib uses a hierarchical order in which a figure window contains a figure which may consist of many axes. Additionally, there are functions from the pyplot interface and there are methods on the Figure class. I will discuss both cases below.

pyplot interface

pyplot is a module that collects a couple of functions that allow matplotlib to be used in a functional manner. I here assume that pyplot has been imported as import matplotlib.pyplot as plt. In this case, there are three different commands that remove stuff:

plt.cla() clears an axes, i.e. the currently active axes in the current figure. It leaves the other axes untouched.

plt.clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.

plt.close() closes a window, which will be the current window, if not specified otherwise.

Which functions suits you best depends thus on your use-case.

The close() function furthermore allows one to specify which window should be closed. The argument can either be a number or name given to a window when it was created using figure(number_or_name) or it can be a figure instance fig obtained, i.e., usingfig = figure(). If no argument is given to close(), the currently active window will be closed. Furthermore, there is the syntax close('all'), which closes all figures.

methods of the Figure class

Additionally, the Figure class provides methods for clearing figures. I'll assume in the following that fig is an instance of a Figure:

fig.clf() clears the entire figure. This call is equivalent to plt.clf() only if fig is the current figure.

fig.clear() is a synonym for fig.clf()

Note that even del fig will not close the associated figure window. As far as I know the only way to close a figure window is using plt.close(fig) as described above.

Python read-only property

Just my two cents, Silas Ray is on the right track, however I felt like adding an example. ;-)

Python is a type-unsafe language and thus you'll always have to trust the users of your code to use the code like a reasonable (sensible) person.

Per PEP 8:

Use one leading underscore only for non-public methods and instance variables.

To have a 'read-only' property in a class you can make use of the @property decoration, you'll need to inherit from object when you do so to make use of the new-style classes.

Example:

>>> class A(object):
...     def __init__(self, a):
...         self._a = a
...
...     @property
...     def a(self):
...         return self._a
... 
>>> a = A('test')
>>> a.a
'test'
>>> a.a = 'pleh'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

How to pad a string to a fixed length with spaces in Python?

Just whipped this up for my problem, it just adds a space until the length of string is more than the min_length you give it.

def format_string(str, min_length):
    while len(str) < min_length:
        str += " "
    return str

case statement in SQL, how to return multiple variables?

The basic way, unfortunately, is to repeat yourself.

SELECT
  CASE WHEN <condition 1> THEN <a1> WHEN <condition 2> THEN <a2> ELSE <a3> END,
  CASE WHEN <condition 1> THEN <b1> WHEN <condition 2> THEN <b2> ELSE <b3> END
FROM 
  <table> 

Fortunately, most RDBMS are clever enough to NOT have to evaluate the conditions multiple times. It's just redundant typing.


In MS SQL Server (2005+) you could possible use CROSS APPLY as an alternative to this. Though I have no idea how performant it is...

SELECT
  *
FROM
  <table>
CROSS APPLY
  (
   SELECT a1, b1 WHERE <condition 1>
   UNION ALL
   SELECT a2, b2 WHERE <condition 2>
   UNION ALL
   SELECT a3, b3 WHERE <condition 3>
  )
  AS case_proxy

The noticable downside here is that there is no ELSE equivalent and as all the conditions could all return values, they need to be framed such that only one can ever be true at a time.


EDIT

If Yuck's answer is changed to a UNION rather than JOIN approach, it becomes very similar to this. The main difference, however, being that this only scans the input data set once, rather than once per condition (100 times in your case).


EDIT

I've also noticed that you may mean that the values returned by the CASE statements are fixed. All records that match the same condition get the exact sames values in value1 and value2. This could be formed like this...

WITH
  checked_data AS
(
  SELECT
    CASE WHEN <condition1> THEN 1
         WHEN <condition2> THEN 2
         WHEN <condition3> THEN 3
         ...
         ELSE                   100
    END AS condition_id,
    *
  FROM
    <table>
)
,
  results (condition_id, value1, value2) AS
(
   SELECT 1, a1, b1
   UNION ALL
   SELECT 2, a2, b2
   UNION ALL
   SELECT 3, a3, b3
   UNION ALL
   ...
   SELECT 100, a100, b100
)
SELECT
  *
FROM
  checked_data
INNER JOIN
  results
    ON results.condition_id = checked_data.condition_id

Check if an HTML input element is empty or has no value entered by user

Your first one was basically right. This, FYI, is bad. It does an equality check between a DOM node and a string:

if (document.getElementById('customx') == ""){

DOM nodes are actually their own type of JavaScript object. Thus this comparison would never work at all since it's doing an equality comparison on two distinctly different data types.

Javascript Get Values from Multiple Select Option Box

Here i am posting the answer just for reference which may become useful.

<!DOCTYPE html>
<html>
<head>
<script>
function show()
{
     var InvForm = document.forms.form;
     var SelBranchVal = "";
     var x = 0;
     for (x=0;x<InvForm.kb.length;x++)
         {
            if(InvForm.kb[x].selected)
            {
             //alert(InvForm.kb[x].value);
             SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
            }
         }
         alert(SelBranchVal);
}
</script>
</head>
<body>
<form name="form">
<select name="kb" id="kb" onclick="show();" multiple>
<option value="India">India</option>
<option selected="selected" value="US">US</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
</select>
<!--input type="submit" name="cmdShow" value="Customize Fields"
 onclick="show();" id="cmdShow" /-->
</form>
</body>
</html>

Returning null in a method whose signature says return int?

int is a primitive, null is not a value that it can take on. You could change the method return type to return java.lang.Integer and then you can return null, and existing code that returns int will get autoboxed.

Nulls are assigned only to reference types, it means the reference doesn't point to anything. Primitives are not reference types, they are values, so they are never set to null.

Using the object wrapper java.lang.Integer as the return value means you are passing back an Object and the object reference can be null.

Which is better, return value or out parameter?

As others have said: return value, not out param.

May I recommend to you the book "Framework Design Guidelines" (2nd ed)? Pages 184-185 cover the reasons for avoiding out params. The whole book will steer you in the right direction on all sorts of .NET coding issues.

Allied with Framework Design Guidelines is the use of the static analysis tool, FxCop. You'll find this on Microsoft's sites as a free download. Run this on your compiled code and see what it says. If it complains about hundreds and hundreds of things... don't panic! Look calmly and carefully at what it says about each and every case. Don't rush to fix things ASAP. Learn from what it is telling you. You will be put on the road to mastery.

No converter found capable of converting from type to type

You may already have this working, but the I created a test project with the classes below allowing you to retrieve the data into an entity, projection or dto.

Projection - this will return the code column twice, once named code and also named text (for example only). As you say above, you don't need the @Projection annotation

import org.springframework.beans.factory.annotation.Value;

public interface DeadlineTypeProjection {
    String getId();

    // can get code and or change name of getter below
    String getCode();

    // Points to the code attribute of entity class
    @Value(value = "#{target.code}")
    String getText();
}

DTO class - not sure why this was inheriting from your base class and then redefining the attributes. JsonProperty just an example of how you'd change the name of the field passed back to a REST end point

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class DeadlineType {
    String id;

    // Use this annotation if you need to change the name of the property that is passed back from controller
    // Needs to be called code to be used in Repository
    @JsonProperty(value = "text")
    String code;

}

Entity class

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@Entity
@Table(name = "deadline_type")
public class ABDeadlineType {

    @Id
    private String id;
    private String code;
}

Repository - your repository extends JpaRepository<ABDeadlineType, Long> but the Id is a String, so updated below to JpaRepository<ABDeadlineType, String>

import com.example.demo.entity.ABDeadlineType;
import com.example.demo.projection.DeadlineTypeProjection;
import com.example.demo.transfer.DeadlineType;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, String> {

    List<ABDeadlineType> findAll();

    List<DeadlineType> findAllDtoBy();

    List<DeadlineTypeProjection> findAllProjectionBy();

}

Example Controller - accesses the repository directly to simplify code

@RequestMapping(value = "deadlinetype")
@RestController
public class DeadlineTypeController {

    private final ABDeadlineTypeRepository abDeadlineTypeRepository;

    @Autowired
    public DeadlineTypeController(ABDeadlineTypeRepository abDeadlineTypeRepository) {
        this.abDeadlineTypeRepository = abDeadlineTypeRepository;
    }

    @GetMapping(value = "/list")
    public ResponseEntity<List<ABDeadlineType>> list() {

        List<ABDeadlineType> types = abDeadlineTypeRepository.findAll();
        return ResponseEntity.ok(types);
    }

    @GetMapping(value = "/listdto")
    public ResponseEntity<List<DeadlineType>> listDto() {

        List<DeadlineType> types = abDeadlineTypeRepository.findAllDtoBy();
        return ResponseEntity.ok(types);
    }

    @GetMapping(value = "/listprojection")
    public ResponseEntity<List<DeadlineTypeProjection>> listProjection() {

        List<DeadlineTypeProjection> types = abDeadlineTypeRepository.findAllProjectionBy();
        return ResponseEntity.ok(types);
    }
}

Hope that helps

Les

IIS7 URL Redirection from root to sub directory

I think, this could be done without IIS URL Rewrite module. <httpRedirect> supports wildcards, so you can configure it this way:

  <system.webServer>
    <httpRedirect enabled="true">
      <add wildcard="/" destination="/menu_1/MainScreen.aspx" />
    </httpRedirect>
  </system.webServer>

Note that you need to have the "HTTP Redirection" feature enabled on IIS - see HTTP Redirects

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

The most common culprit for me has been Visual Studio trying to run the tests using a different architecture than the library it's testing. Unfortunately there are multiple places where it seems this can go wrong.

In VS 2017, try creating a Run Settings file, e.g. Default.runsettings in your test project. If your main lib is x64, the contents should be:

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <RunConfiguration>
    <TargetPlatform>x64</TargetPlatform>
  </RunConfiguration>
</RunSettings>

Then choose this file from Test -> Test Settings -> Select Test Settings File.

Then, under Test -> Test Settings, Default Processor Architecture, choose the correct architecture again.

Be sure to Clean and Build the entire solution. You may need to close and reopen the Test Explorer window. Look for any additional errors in the Output -> Test window, for more clues about incorrect architecture types.

FYI additional Test Settings entries can be found here.

Bootstrap modal link

A Simple Approach will be to use a normal link and add Bootstrap modal effect to it. Just make use of my Code, hopefully you will get it run.

 <div class="container">
        <div class="row">
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="addContact" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><b style="color:#fb3600; font-weight:700;">X</b></button><!--&times;-->
                            <h4 class="modal-title text-center" id="addContact">Add Contact</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <ul class="nav nav-tabs">
                                    <li class="active">
                                        <a data-toggle="tab" style="background-color:#f5dfbe" href="#contactTab">Contact</a>
                                    </li>
                                    <li>
                                        <a data-toggle="tab" style="background-color:#a6d2f6" href="#speechTab">Speech</a>
                                    </li>
                                </ul>
                                <div class="tab-content">
                                    <div id="contactTab" class="tab-pane in active"><partial name="CreateContactTag"></div>
                                    <div id="speechTab" class="tab-pane fade in"><partial name="CreateSpeechTag"></div>
                                </div>

                            </div>
                        </div>
                        <div class="modal-footer">
                            <a class="btn btn-info" data-dismiss="modal">Close</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Reset select value to default

For those who are working with Bootstrap-select, you might want to use this:

$('#mySelect').selectpicker('render');

HTML Button : Navigate to Other Page - Different Approaches

I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.

I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.

Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.

Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.

Convert between UIImage and Base64 string

//convert Image to Base64 (Encoding)

let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)

print(strBase64)

// convert Base64 to Image (Decoding)

let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!

let decodedimage:UIImage = UIImage(data: dataDecoded)!

print(decodedimage)

yourImageView.image = decodedimage

How to get a specific output iterating a hash in Ruby?

hash.each do |key, array|
  puts "#{key}-----"
  puts array
end

Regarding order I should add, that in 1.8 the items will be iterated in random order (well, actually in an order defined by Fixnum's hashing function), while in 1.9 it will be iterated in the order of the literal.

C - casting int to char and append char to char

Casting int to char involves losing data and the compiler will probably warn you.

Extracting a particular byte from an int sounds more reasonable and can be done like this:

number & 0x000000ff; /* first byte */
(number & 0x0000ff00) >> 8; /* second byte */
(number & 0x00ff0000) >> 16; /* third byte */
(number & 0xff000000) >> 24; /* fourth byte */

How can I reuse a navigation bar on multiple pages?

A very old but simple enough technique is to use "Server-Side Includes", to include HTML pages into a top-level page that has the .shtml extension. For instance this would be your index.shtml file:

<html>
<head>...</head>
<body>
<!-- repeated header: note that the #include is in a HTML comment -->
<!--#include file="header.html" -->
<!-- unique content here... -->
</body>
</html>

Yes, it is lame, but it works. Remember to enable SSI support in your HTTP server configuration (this is how to do it for Apache).

Call ASP.NET function from JavaScript?

I try this and so I could run an Asp.Net method while using jQuery.

  1. Do a page redirect in your jQuery code

    window.location = "Page.aspx?key=1";
    
  2. Then use a Query String in Page Load

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["key"] != null)
        {
            string key= Request.QueryString["key"];
            if (key=="1")
            {
                // Some code
            }
        }
    }
    

So no need to run an extra code

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

The get method of the HashMap is returning an Object, but the variable current is expected to take a ArrayList:

ArrayList current = new ArrayList();
// ...
current = dictMap.get(dictCode);

For the above code to work, the Object must be cast to an ArrayList:

ArrayList current = new ArrayList();
// ...
current = (ArrayList)dictMap.get(dictCode);

However, probably the better way would be to use generic collection objects in the first place:

HashMap<String, ArrayList<Object>> dictMap =
    new HashMap<String, ArrayList<Object>>();

// Populate the HashMap.

ArrayList<Object> current = new ArrayList<Object>();      
if(dictMap.containsKey(dictCode)) {
    current = dictMap.get(dictCode);   
}

The above code is assuming that the ArrayList has a list of Objects, and that should be changed as necessary.

For more information on generics, The Java Tutorials has a lesson on generics.

How to convert a DataTable to a string in C#?

    /// <summary>
    /// Dumps the passed DataSet obj for debugging as list of html tables
    /// </summary>
    /// <param name="msg"> the msg attached </param>
    /// <param name="ds"> the DataSet object passed for Dumping </param>
    /// <returns> the nice looking dump of the DataSet obj in html format</returns>
    public static string DumpHtmlDs(string msg, ref System.Data.DataSet ds)
    {
        StringBuilder objStringBuilder = new StringBuilder();
        objStringBuilder.AppendLine("<html><body>");

        if (ds == null)
        {
            objStringBuilder.AppendLine("Null dataset passed ");
            objStringBuilder.AppendLine("</html></body>");
            WriteIf(objStringBuilder.ToString());
            return objStringBuilder.ToString();
        }

        objStringBuilder.AppendLine("<p>" + msg + " START </p>");
        if (ds != null)
        {
            if (ds.Tables == null)
            {
                objStringBuilder.AppendLine("ds.Tables == null ");
                return objStringBuilder.ToString();
            }


            foreach (System.Data.DataTable dt in ds.Tables)
            {

                if (dt == null)
                {
                    objStringBuilder.AppendLine("ds.Tables == null ");
                    continue;
                }
                objStringBuilder.AppendLine("<table>");

                //objStringBuilder.AppendLine("================= My TableName is  " +
                //dt.TableName + " ========================= START");
                int colNumberInRow = 0;
                objStringBuilder.Append("<tr><th>row number</th>");
                foreach (System.Data.DataColumn dc in dt.Columns)
                {
                    if (dc == null)
                    {
                        objStringBuilder.AppendLine("DataColumn is null ");
                        continue;
                    }


                    objStringBuilder.Append(" <th> |" + colNumberInRow.ToString() + " | ");
                    objStringBuilder.Append(  dc.ColumnName.ToString() + " </th> ");
                    colNumberInRow++;
                } //eof foreach (DataColumn dc in dt.Columns)
                objStringBuilder.Append("</tr>");

                int rowNum = 0;
                foreach (System.Data.DataRow dr in dt.Rows)
                {
                    objStringBuilder.Append("<tr><td> row - | " + rowNum.ToString() + " | </td>");
                    int colNumber = 0;
                    foreach (System.Data.DataColumn dc in dt.Columns)
                    {
                        objStringBuilder.Append(" <td> |" + colNumber + "|" );
                        objStringBuilder.Append(dr[dc].ToString() + "  </td>");
                        colNumber++;
                    } //eof foreach (DataColumn dc in dt.Columns)
                    rowNum++;
                    objStringBuilder.AppendLine(" </tr>");
                }   //eof foreach (DataRow dr in dt.Rows)

                objStringBuilder.AppendLine("</table>");
                objStringBuilder.AppendLine("<p>" + msg + " END </p>");
            }   //eof foreach (DataTable dt in ds.Tables)

        } //eof if ds !=null 
        else
        {

            objStringBuilder.AppendLine("NULL DataSet object passed for debugging !!!");
        }
        return objStringBuilder.ToString();

    } 

Beginner Python Practice?

I always find it easier to learn a language in a specific problem domain. You might try looking at Django and doing the tutorial. This will give you a very light-weight intro to both Python and to a web framework (a very well-documented one) that is 100% Python.

Then do something in your field(s) of expertise -- graph generation, or whatever -- and tie that into a working framework to see if you got it right. My universe tends to be computational linguistics and there are a number of Python-based toolkits to help get you started. E.g. Natural Language Toolkit.

Just a thought.

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

how to properly display an iFrame in mobile safari

Don't scroll the IFrame page or its content, scroll the parent page. If you control the IFrame content, you can use the iframe-resizer library to turn the iframe element itself into a proper block level element, with a natural/correct/native height. Also, don't attempt to position (fixed, absolute) your iframe in the parent page, or present an iframe in a modal window, especially if it has form elements.

I also suspect that iOS Safari has a non-standards behavior that expands your iframe's height to its natural height, much like the iframe-resizer library will do for desktop browsers, which seem to render responsive iframe content at height 0px or 150px or some other not useful default. If you need to contrain width, try a max-width style inside the iframe.

How to debug .htaccess RewriteRule not working

The 'Enter some junk value' answer didn't do the trick for me, my site was continuing to load despite the entered junk.

Instead I added the following line to the top of the .htaccess file:

deny from all

This will quickly let you know if .htaccess is being picked up or not. If the .htaccess is being used, the files in that folder won't load at all.

SQL Server insert if not exists best practice

The answers above which talk about normalizing are great! But what if you find yourself in a position like me where you're not allowed to touch the database schema or structure as it stands? Eg, the DBA's are 'gods' and all suggested revisions go to /dev/null?

In that respect, I feel like this has been answered with this Stack Overflow posting too in regards to all the users above giving code samples.

I'm reposting the code from INSERT VALUES WHERE NOT EXISTS which helped me the most since I can't alter any underlying database tables:

INSERT INTO #table1 (Id, guidd, TimeAdded, ExtraData)
SELECT Id, guidd, TimeAdded, ExtraData
FROM #table2
WHERE NOT EXISTS (Select Id, guidd From #table1 WHERE #table1.id = #table2.id)
-----------------------------------
MERGE #table1 as [Target]
USING  (select Id, guidd, TimeAdded, ExtraData from #table2) as [Source]
(id, guidd, TimeAdded, ExtraData)
    on [Target].id =[Source].id
WHEN NOT MATCHED THEN
    INSERT (id, guidd, TimeAdded, ExtraData)
    VALUES ([Source].id, [Source].guidd, [Source].TimeAdded, [Source].ExtraData);
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT id, guidd, TimeAdded, ExtraData from #table2
EXCEPT
SELECT id, guidd, TimeAdded, ExtraData from #table1
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT #table2.id, #table2.guidd, #table2.TimeAdded, #table2.ExtraData
FROM #table2
LEFT JOIN #table1 on #table1.id = #table2.id
WHERE #table1.id is null

The above code uses different fields than what you have, but you get the general gist with the various techniques.

Note that as per the original answer on Stack Overflow, this code was copied from here.

Anyway my point is "best practice" often comes down to what you can and can't do as well as theory.

  • If you're able to normalize and generate indexes/keys -- great!
  • If not and you have the resort to code hacks like me, hopefully the above helps.

Good luck!

Minimum rights required to run a windows service as a domain account

Two ways:

  1. Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.

  2. Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.

jQuery-UI datepicker default date

$("#birthdate" ).datepicker("setDate", new Date(1985,01,01))

How do I do redo (i.e. "undo undo") in Vim?

Vim documentation

<Undo>      or                  *undo* *<Undo>* *u*
u           Undo [count] changes.  {Vi: only one level}

                            *:u* *:un* *:undo*
:u[ndo]         Undo one change.  {Vi: only one level}

                            *CTRL-R*
CTRL-R          Redo [count] changes which were undone.  {Vi: redraw screen}

                            *:red* *:redo* *redo*
:red[o]         Redo one change which was undone.  {Vi: no redo}

                            *U*
U           Undo all latest changes on one line.  {Vi: while not
            moved off of it}

HTML image not showing in Gmail

You might have them turned off in your gmail settings, heres the link to change them https://support.google.com/mail/answer/145919?hl=en

Also gmail may be blocking the images thinking they are suspicious.

from the link above.

How Gmail makes images safe

Some senders try to use externally linked images in harmful ways, but Gmail takes action to ensure that images are loaded safely. Gmail serves all images through Google’s image proxy servers and transcodes them before delivery to protect you in the following ways:

Senders can’t use image loading to get information like your IP address or location. Senders can’t set or read cookies in your browser. Gmail checks your images for known viruses or malware. In some cases, senders may be able to know whether an individual has opened a message with unique image links. As always, Gmail scans every message for suspicious content and if Gmail considers a sender or message potentially suspicious, images won’t be displayed and you’ll be asked whether you want to see the images.

Border Radius of Table is not working

A note to this old question:

My reset.css had set border-spacing: 0, causing the corners to get cut off. I had to set it to 3px for my radius to work properly (value will depend on the radius in question).

How to check if an element exists in the xml using xpath?

Use:

boolean(/*/*[@subjectIdentifier="Primary"]/*/*/*/*
                           [name()='AttachedXml' 
                          and 
                            namespace-uri()='http://xml.mycompany.com/XMLSchema'
                           ]
       )

Find size of object instance in bytes in c#

For unmanaged types aka value types, structs:

        Marshal.SizeOf(object);

For managed objects the closer i got is an approximation.

        long start_mem = GC.GetTotalMemory(true);

        aclass[] array = new aclass[1000000];
        for (int n = 0; n < 1000000; n++)
            array[n] = new aclass();

        double used_mem_median = (GC.GetTotalMemory(false) - start_mem)/1000000D;

Do not use serialization.A binary formatter adds headers, so you can change your class and load an old serialized file into the modified class.

Also it won't tell you the real size in memory nor will take into account memory alignment.

[Edit] By using BiteConverter.GetBytes(prop-value) recursivelly on every property of your class you would get the contents in bytes, that doesn't count the weight of the class or references but is much closer to reality. I would recommend to use a byte array for data and an unmanaged proxy class to access values using pointer casting if size matters, note that would be non-aligned memory so on old computers is gonna be slow but HUGE datasets on MODERN RAM is gonna be considerably faster, as minimizing the size to read from RAM is gonna be a bigger impact than unaligned.

How do I check if I'm running on Windows in Python?

import platform
is_windows = any(platform.win32_ver())

or

import sys
is_windows = hasattr(sys, 'getwindowsversion')

Android webview & localStorage

setDatabasePath() method was deprecated in API level 19. I advise you to use storage locale like this:

webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");
}

Correct way to try/except using Python requests module?

Have a look at the Requests exception docs. In short:

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception.

In the event of the rare invalid HTTP response, Requests will raise an HTTPError exception.

If a request times out, a Timeout exception is raised.

If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.

All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.

To answer your question, what you show will not cover all of your bases. You'll only catch connection-related errors, not ones that time out.

What to do when you catch the exception is really up to the design of your script/program. Is it acceptable to exit? Can you go on and try again? If the error is catastrophic and you can't go on, then yes, you may abort your program by raising SystemExit (a nice way to both print an error and call sys.exit).

You can either catch the base-class exception, which will handle all cases:

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.RequestException as e:  # This is the correct syntax
    raise SystemExit(e)

Or you can catch them separately and do different things.

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.Timeout:
    # Maybe set up for a retry, or continue in a retry loop
except requests.exceptions.TooManyRedirects:
    # Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
    # catastrophic error. bail.
    raise SystemExit(e)

As Christian pointed out:

If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call Response.raise_for_status. That will raise an HTTPError, if the response was an http error.

An example:

try:
    r = requests.get('http://www.google.com/nothere')
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    raise SystemExit(err)

Will print:

404 Client Error: Not Found for url: http://www.google.com/nothere

Make div scrollable

Use overflow-y:auto for displaying scroll automatically when the content exceeds the divs set height.

See this demo

How to send PUT, DELETE HTTP request in HttpURLConnection?

public  HttpURLConnection getHttpConnection(String url, String type){
        URL uri = null;
        HttpURLConnection con = null;
        try{
            uri = new URL(url);
            con = (HttpURLConnection) uri.openConnection();
            con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setConnectTimeout(60000); //60 secs
            con.setReadTimeout(60000); //60 secs
            con.setRequestProperty("Accept-Encoding", "Your Encoding");
            con.setRequestProperty("Content-Type", "Your Encoding");
        }catch(Exception e){
            logger.info( "connection i/o failed" );
        }
        return con;
}

Then in your code :

public void yourmethod(String url, String type, String reqbody){
    HttpURLConnection con = null;
    String result = null;
    try {
        con = conUtil.getHttpConnection( url , type);
    //you can add any request body here if you want to post
         if( reqbody != null){  
                con.setDoInput(true);
                con.setDoOutput(true);
                DataOutputStream out = new  DataOutputStream(con.getOutputStream());
                out.writeBytes(reqbody);
                out.flush();
                out.close();
            }
        con.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String temp = null;
        StringBuilder sb = new StringBuilder();
        while((temp = in.readLine()) != null){
            sb.append(temp).append(" ");
        }
        result = sb.toString();
        in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.error(e.getMessage());
    }
//result is the response you get from the remote side
}

How to display a pdf in a modal window?

You can have a look at this library: https://github.com/mozilla/pdf.js it renders PDF document in a Web/HTML page

Also you can use Flash to embed the document into any HTML page like that:

<object data="your_file.pdf#view=Fit" type="application/pdf" width="100%" height="850">
    <p>
        It appears your Web browser is not configured to display PDF files. No worries, just <a href="your_file.pdf">click here to download the PDF file.</a>
    </p>
</object>

How can I properly handle 404 in ASP.NET MVC?

1) Make abstract Controller class.

public abstract class MyController:Controller
{
    public ActionResult NotFound()
    {
        Response.StatusCode = 404;
        return View("NotFound");
    }

    protected override void HandleUnknownAction(string actionName)
    {
        this.ActionInvoker.InvokeAction(this.ControllerContext, "NotFound");
    }
    protected override void OnAuthorization(AuthorizationContext filterContext) { }
}  

2) Make inheritence from this abstract class in your all controllers

public class HomeController : MyController
{}  

3) And add a view named "NotFound" in you View-Shared folder.

Loading local JSON file

Found this thread when trying (unsuccessfully) to load a local json file. This solution worked for me...

function load_json(src) {
  var head = document.getElementsByTagName('head')[0];

  //use class, as we can't reference by id
  var element = head.getElementsByClassName("json")[0];

  try {
    element.parentNode.removeChild(element);
  } catch (e) {
    //
  }

  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = src;
  script.className = "json";
  script.async = false;
  head.appendChild(script);

  //call the postload function after a slight delay to allow the json to load
  window.setTimeout(postloadfunction, 100)
}

... and is used like this...

load_json("test2.html.js")

...and this is the <head>...

<head>
  <script type="text/javascript" src="test.html.js" class="json"></script>
</head>

Differences between socket.io and websockets

Im going to provide an argument against using socket.io.

I think using socket.io solely because it has fallbacks isnt a good idea. Let IE8 RIP.

In the past there have been many cases where new versions of NodeJS has broken socket.io. You can check these lists for examples... https://github.com/socketio/socket.io/issues?q=install+error

If you go to develop an Android app or something that needs to work with your existing app, you would probably be okay working with WS right away, socket.io might give you some trouble there...

Plus the WS module for Node.JS is amazingly simple to use.

How to clear APC cache entries?

Another possibility for command-line usage, not yet mentioned, is to use curl.

This doesn't solve your problem for all cache entries if you're using the stock apc.php script, but it could call an adapted script or another one you've put in place.

This clears the opcode cache:

curl --user apc:$PASSWORD "http://www.example.com/apc.php?CC=1&OB=1&`date +%s`"

Change the OB parameter to 3 to clear the user cache:

curl --user apc:$PASSWORD "http://www.example.com/apc.php?CC=1&OB=3&`date +%s`"

Put both lines in a script and call it with $PASSWORD in your env.

Drop shadow for PNG image in CSS

Add border with radius in you class if its a block. because by default shadow will apply on block border, even if your image have rounded corner.

border-radius: 4px;

change its border radius according to your you image corner. Hope this help.

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Both times when you write the package name : 1. When you create a new project in Android Studio and 2. When you create a Configuration File

YOU should write it with lowercase letters - after changing to lowercase it works. If you don't want to waste time just go to you .json file and replace com.myname.MyAPPlicationnamE with com.myname.myapplicationname (for every match in the json file).

Your password does not satisfy the current policy requirements

The problem is that your password wont match the password validation rules. You can simple follow below steps to solve your problem.

You can simply see password validation configuration matrix by typing below code.

mysql-> SHOW VARIABLES LIKE 'validate_password%';

Then in your matrix you can find below variables with corresponding values and in there you have to check validate_password_length , validate_password_number_count and validate_password_policy.

Check the values used for those variables. Make sure your validate_password_length should not be greater than 6. You can set that to 6 by using below code.

SET GLOBAL validate_password_length = 6;

And after that you need to set validate_password_number_count to 0. Do it by using below code.

SET GLOBAL validate_password_number_count = 0;

Finally you have to set you validate_password_policy to low. Having that as Medium or High wont allow your less secure passwords. Set that to low by below code.

SET GLOBAL validate_password_policy=LOW;

How to break nested loops in JavaScript?

Unfortunately you'll have to set a flag or use labels (think old school goto statements)

var breakout = false;

for(i=0;i<5;i++)
{
    for(j=i+1;j<5;j++)
    {
        breakout = true;
        break;
    }
    if (breakout) break;
    alert(1)
};

The label approach looks like:

end_loops:
for(i=0;i<5;i++)
{
    for(j=i+1;j<5;j++)
    {
        break end_loops;
    }
    alert(1)
};

edit: label incorrectly placed.

also see:

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

How can I make a UITextField move up when the keyboard is present - on starting to edit?

here is a UITextfield (and other similar fields) category that i made that will make the textfield avoid the keyboard, you should be able to drop this in your view controller as is and it should work. It moves the entire screen up so the current textfield is above the keyboard with animations

#import "UIView+avoidKeyboard.h"
#import "AppDelegate.h"

@implementation UIView (avoidKeyboard)

- (void) becomeFirstResponder {

if(self.isFirstResponder)
    return;

[super becomeFirstResponder];

if ([self isKindOfClass:[UISearchBar class]] ||
    [self isKindOfClass:[UITextField class]] ||
    [self isKindOfClass:[UITextView class]])
{
    AppDelegate *appDelegate    = [UIApplication sharedApplication].delegate;

    CGRect screenBounds         = appDelegate.window.frame;

    CGFloat keyboardHeight;
    CGFloat keyboardY;
    CGFloat viewsLowestY;
    CGPoint origin              = [self.superview convertPoint:self.frame.origin toView:appDelegate.window]; //get this views origin in terms of the main screens bounds

    if(UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])){ //the window.frame doesnt take its orientation into account so if its sideways we must use the x value of the origin instead of the y
        keyboardHeight          = 216;
        keyboardY               = screenBounds.size.height  - keyboardHeight; //find the keyboards y coord relative to how much the main window has moved up
        viewsLowestY            = origin.y + self.frame.size.height; //find the lowest point of this view
    }
    else {
        keyboardHeight          = 162;
        keyboardY               = screenBounds.size.width  - keyboardHeight;
        viewsLowestY            = origin.x + self.frame.size.height;
    }

    CGFloat difference          = viewsLowestY - keyboardY + 20; //find if this view overlaps with the keyboard with some padding

    if (difference > 0){ //move screen up if there is an overlap

        [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{

            CGRect frame = appDelegate.window.frame;

            if(UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])){
                frame.origin.y -= difference;
            }
            else {
                frame.origin.x -= difference;
            }
            appDelegate.window.frame = frame;
        }
        completion:nil];
    }
}
}

//look at appDelegate to see when the keyboard is hidden

@end

In your appDelegate add this function

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHides:) name:UIKeyboardWillHideNotification object:nil]; //add in didFinishLaunchingWithOptions

...

- (void)keyboardHides:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3 animations:^{
        [window setFrame: CGRectMake(0, 0, window.frame.size.width, window.frame.size.height)];
    } completion:nil];
}

JavaScript/jQuery: replace part of string?

You need to set the text after the replace call:

_x000D_
_x000D_
$('.element span').each(function() {_x000D_
  console.log($(this).text());_x000D_
  var text = $(this).text().replace('N/A, ', '');_x000D_
  $(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
  <span>N/A, Category</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Here's another cool way you can do it (hat tip @Felix King):

$(".element span").text(function(index, text) {
    return text.replace("N/A, ", "");
});

Rotating and spacing axis labels in ggplot2

Use coord_flip()

data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))

qplot(cut, carat, data = diamonds, geom = "boxplot") +
  coord_flip()

enter image description here


Add str_wrap()

# wrap text to no more than 15 spaces
library(stringr)
diamonds$cut2 <- str_wrap(diamonds$cut, width = 15)
qplot(cut2, carat, data = diamonds, geom = "boxplot") +
  coord_flip()

enter image description here


In Ch 3.9 of R for Data Science, Wickham and Grolemund speak to this exact question:

coord_flip() switches the x and y axes. This is useful (for example), if you want horizontal boxplots. It’s also useful for long labels: it’s hard to get them to fit without overlapping on the x-axis.

How to clear text area with a button in html using javascript?

You need to attach a click event handler and clear the contents of the textarea from that handler.

HTML

<input type="button" value="Clear" id="clear"> 
<textarea id='output' rows=20 cols=90></textarea>

JS

var input = document.querySelector('#clear');
var textarea = document.querySelector('#output');

input.addEventListener('click', function () {
    textarea.value = '';
}, false);

and here's the working demo.

Slide right to left?

$("#slide").animate({width:'toggle'},350);

Reference: https://api.jquery.com/animate/

"Full screen" <iframe>

You can also use viewport-percentage lengths to achieve this:

5.1.2. Viewport-percentage lengths: the ‘vw’, ‘vh’, ‘vmin’, ‘vmax’ units

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

Where 100vh represents the height of the viewport, and likewise 100vw represents the width.

Example Here

_x000D_
_x000D_
body {_x000D_
    margin: 0;            /* Reset default margin */_x000D_
}_x000D_
iframe {_x000D_
    display: block;       /* iframes are inline by default */_x000D_
    background: #000;_x000D_
    border: none;         /* Reset default border */_x000D_
    height: 100vh;        /* Viewport-relative units */_x000D_
    width: 100vw;_x000D_
}
_x000D_
<iframe></iframe>
_x000D_
_x000D_
_x000D_

This is supported in most modern browsers - support can be found here.

Is there a method to generate a UUID with go language

"crypto/rand" is cross platform pkg for random bytes generattion

package main

import (
    "crypto/rand"
    "fmt"
)

// Note - NOT RFC4122 compliant
func pseudo_uuid() (uuid string) {

    b := make([]byte, 16)
    _, err := rand.Read(b)
    if err != nil {
        fmt.Println("Error: ", err)
        return
    }

    uuid = fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])

    return
}

JavaScript private methods

The apotheosis of the Module Pattern: The Revealing Module Pattern

A neat little extension to a very robust pattern.

Using HTML5 file uploads with AJAX and jQuery

With jQuery (and without FormData API) you can use something like this:

function readFile(file){
   var loader = new FileReader();
   var def = $.Deferred(), promise = def.promise();

   //--- provide classic deferred interface
   loader.onload = function (e) { def.resolve(e.target.result); };
   loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
   loader.onerror = loader.onabort = function (e) { def.reject(e); };
   promise.abort = function () { return loader.abort.apply(loader, arguments); };

   loader.readAsBinaryString(file);

   return promise;
}

function upload(url, data){
    var def = $.Deferred(), promise = def.promise();
    var mul = buildMultipart(data);
    var req = $.ajax({
        url: url,
        data: mul.data,
        processData: false,
        type: "post",
        async: true,
        contentType: "multipart/form-data; boundary="+mul.bound,
        xhr: function() {
            var xhr = jQuery.ajaxSettings.xhr();
            if (xhr.upload) {

                xhr.upload.addEventListener('progress', function(event) {
                    var percent = 0;
                    var position = event.loaded || event.position; /*event.position is deprecated*/
                    var total = event.total;
                    if (event.lengthComputable) {
                        percent = Math.ceil(position / total * 100);
                        def.notify(percent);
                    }                    
                }, false);
            }
            return xhr;
        }
    });
    req.done(function(){ def.resolve.apply(def, arguments); })
       .fail(function(){ def.reject.apply(def, arguments); });

    promise.abort = function(){ return req.abort.apply(req, arguments); }

    return promise;
}

var buildMultipart = function(data){
    var key, crunks = [], bound = false;
    while (!bound) {
        bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
        for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
    }

    for (var key = 0, l = data.length; key < l; key++){
        if (typeof(data[key].value) !== "string") {
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
                "Content-Type: application/octet-stream\r\n"+
                "Content-Transfer-Encoding: binary\r\n\r\n"+
                data[key].value[0]);
        }else{
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
                data[key].value);
        }
    }

    return {
        bound: bound,
        data: crunks.join("\r\n")+"\r\n--"+bound+"--"
    };
};

//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
   var formData = form.find(":input:not('#file')").serializeArray();
   formData.file = [fileData, $file[0].files[0].name];
   upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});

With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})

How do I plot in real-time in a while loop using matplotlib?

I know this question is old, but there's now a package available called drawnow on GitHub as "python-drawnow". This provides an interface similar to MATLAB's drawnow -- you can easily update a figure.

An example for your use case:

import matplotlib.pyplot as plt
from drawnow import drawnow

def make_fig():
    plt.scatter(x, y)  # I think you meant this

plt.ion()  # enable interactivity
fig = plt.figure()  # make a figure

x = list()
y = list()

for i in range(1000):
    temp_y = np.random.random()
    x.append(i)
    y.append(temp_y)  # or any arbitrary update to your figure's data
    i += 1
    drawnow(make_fig)

python-drawnow is a thin wrapper around plt.draw but provides the ability to confirm (or debug) after figure display.

Use of "this" keyword in C++

Either way works, but many places have coding standards in place that will guide the developer one way or the other. If such a policy is not in place, just follow your heart. One thing, though, it REALLY helps the readability of the code if you do use it. especially if you are not following a naming convention on class-level variable names.

how to convert a string date into datetime format in python?

The particular format for strptime:

datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)

Regex for 1 or 2 digits, optional non-alphanumeric, 2 known alphas

^\d{1,2}[\W_]?po$

\d defines a number and {1,2} means 1 or two of the expression before, \W defines a non word character.

What are .NumberFormat Options In Excel VBA?

The .NET Library EPPlus implements a conversation from the string definition to the built in number. See class ExcelNumberFormat:

internal static int GetFromBuildIdFromFormat(string format)
{
    switch (format)
    {
        case "General":
            return 0;
        case "0":
            return 1;
        case "0.00":
            return 2;
        case "#,##0":
            return 3;
        case "#,##0.00":
            return 4;
        case "0%":
            return 9;
        case "0.00%":
            return 10;
        case "0.00E+00":
            return 11;
        case "# ?/?":
            return 12;
        case "# ??/??":
            return 13;
        case "mm-dd-yy":
            return 14;
        case "d-mmm-yy":
            return 15;
        case "d-mmm":
            return 16;
        case "mmm-yy":
            return 17;
        case "h:mm AM/PM":
            return 18;
        case "h:mm:ss AM/PM":
            return 19;
        case "h:mm":
            return 20;
        case "h:mm:ss":
            return 21;
        case "m/d/yy h:mm":
            return 22;
        case "#,##0 ;(#,##0)":
            return 37;
        case "#,##0 ;[Red](#,##0)":
            return 38;
        case "#,##0.00;(#,##0.00)":
            return 39;
        case "#,##0.00;[Red](#,#)":
            return 40;
        case "mm:ss":
            return 45;
        case "[h]:mm:ss":
            return 46;
        case "mmss.0":
            return 47;
        case "##0.0":
            return 48;
        case "@":
            return 49;
        default:
            return int.MinValue;
    }
}

When you use one of these formats, Excel will automatically identify them as a standard format.

Is it possible to make input fields read-only through CSS?

No behaviors can be set by CSS. The only way to disable something in CSS is to make it invisible by either setting display:none or simply putting div with transparent img all over it and changing their z-orders to disable user focusing on it with mouse. Even though, user will still be able to focus with tab from another field.

Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

The range of floating point numbers usually exceeds the range of integers. By returning a floating point value, the functions can return a sensible value for input values that lie outside the representable range of integers.

Consider: If floor() returned an integer, what should floor(1.0e30) return?

Now, while Python's integers are now arbitrary precision, it wasn't always this way. The standard library functions are thin wrappers around the equivalent C library functions.

How to specify more spaces for the delimiter using cut?

Actually awk is exactly the tool you should be looking into:

ps axu | grep '[j]boss' | awk '{print $5}'

or you can ditch the grep altogether since awk knows about regular expressions:

ps axu | awk '/[j]boss/ {print $5}'

But if, for some bizarre reason, you really can't use awk, there are other simpler things you can do, like collapse all whitespace to a single space first:

ps axu | grep '[j]boss' | sed 's/\s\s*/ /g' | cut -d' ' -f5

That grep trick, by the way, is a neat way to only get the jboss processes and not the grep jboss one (ditto for the awk variant as well).

The grep process will have a literal grep [j]boss in its process command so will not be caught by the grep itself, which is looking for the character class [j] followed by boss.

This is a nifty way to avoid the | grep xyz | grep -v grep paradigm that some people use.

Why does the arrow (->) operator in C exist?

Structure in C

First you need to declare your structure:

struct mystruct{
 char element_1,
 char element_2
};

Instantiate C structure

Once you declared your structure , you can instantiate a variable that has as type your structure using either:

mystruct struct_example;

or :

mystruct* struct_example;

For the first use case you can access the varaiable eleemnet using the following syntax: struct_example.element_1 = 5;

For the second use case which is having a pointer to variable of type your structure, to be able to access the variable structure you need an arrow:

struct_example->element_1 = 5;

What are NR and FNR and what does "NR==FNR" imply?

There are awk built-in variables.

NR - It gives the total number of records processed.

FNR - It gives the total number of records for each input file.

How do I animate constraint changes?

Swift solution:

yourConstraint.constant = 50
UIView.animate(withDuration: 1.0, animations: {
    yourView.layoutIfNeeded
})

Should import statements always be at the top of a module?

This is a fascinating discussion. Like many others I had never even considered this topic. I got cornered into having to have the imports in the functions because of wanting to use the Django ORM in one of my libraries. I was having to call django.setup() before importing my model classes and because this was at the top of the file it was being dragged into completely non-Django library code because of the IoC injector construction.

I kind of hacked around a bit and ended up putting the django.setup() in the singleton constructor and the relevant import at the top of each class method. Now this worked fine but made me uneasy because the imports weren't at the top and also I started worrying about the extra time hit of the imports. Then I came here and read with great interest everybody's take on this.

I have a long C++ background and now use Python/Cython. My take on this is that why not put the imports in the function unless it causes you a profiled bottleneck. It's only like declaring space for variables just before you need them. The trouble is I have thousands of lines of code with all the imports at the top! So I think I will do it from now on and change the odd file here and there when I'm passing through and have the time.

Getting HTTP headers with Node.js

Try to look at http.get and response headers.

var http = require("http");

var options = {
  host: 'stackoverflow.com',
  port: 80,
  path: '/'
};

http.get(options, function(res) {
  console.log("Got response: " + res.statusCode);

  for(var item in res.headers) {
    console.log(item + ": " + res.headers[item]);
  }
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

Python: split a list based on a condition?

def partition(pred, iterable):
    'Use a predicate to partition entries into false entries and true entries'
    # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2)

Check this

CentOS 64 bit bad ELF interpreter

sudo yum install fontconfig freetype libfreetype.so.6 libfontconfig.so.1 libstdc++.so.6

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

All you need is a check on the post side of things.

if(empty($_REQUEST['type_id']) && $_REQUEST['type_id'] != 0)
    $_REQUEST['type_id'] = null;

Windows error 2 occured while loading the Java VM

We could not uninstall a program, stuck with the "Windows error 2 cannot load Java VM". Added the Java path to the PATH variable, uninstalled and re-installed Java 8, the problem would not go away.

Then I found this solution online and it worked for us on the first shot: - Uninstall Java 8 - Install Java 6

Whatever the reason, with Java 6, the error went away, we uninstalled the program, and re-installed Java 8.

Clear Cache in Android Application programmatically

Put this code in onStop() method of MainActivity

@Override
protected void onStop() {
    super.onStop();
    AppUtils.deleteCache(getApplicationContext());
}
public class AppUtils {
    public static void deleteCache(Context context) {
        try {
            File dir = context.getCacheDir();
            deleteDir(dir);
        } catch (Exception e) {}
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
            return dir.delete();
        } else if(dir!= null && dir.isFile()) {
            return dir.delete();
        } else {
            return false;
        }
    }
}

Call a REST API in PHP

CURL is the simplest way to go. Here is a simple call

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "THE URL TO THE SERVICE");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, POST DATA);
$result = curl_exec($ch);


print_r($result);
curl_close($ch);

package R does not exist

Another case of R. breakage is Annotations Processing.

Some processing could refer to classes located in certain folders or folder levels. If you move required classes to other location, you can get R. as an unknown class.

Unfortunately the error-pointer to this problem is not evident in Android Studio.

Python Remove last 3 characters of a string

Removing any and all whitespace:

foo = ''.join(foo.split())

Removing last three characters:

foo = foo[:-3]

Converting to capital letters:

foo = foo.upper()

All of that code in one line:

foo = ''.join(foo.split())[:-3].upper()

Define: What is a HashSet?

A HashSet has an internal structure (hash), where items can be searched and identified quickly. The downside is that iterating through a HashSet (or getting an item by index) is rather slow.

So why would someone want be able to know if an entry already exists in a set?

One situation where a HashSet is useful is in getting distinct values from a list where duplicates may exist. Once an item is added to the HashSet it is quick to determine if the item exists (Contains operator).

Other advantages of the HashSet are the Set operations: IntersectWith, IsSubsetOf, IsSupersetOf, Overlaps, SymmetricExceptWith, UnionWith.

If you are familiar with the object constraint language then you will identify these set operations. You will also see that it is one step closer to an implementation of executable UML.

How to call a web service from jQuery

You can make an AJAX request like any other requests:

$.ajax( {
type:'Get',
url:'http://mysite.com/mywebservice',
success:function(data) {
 alert(data);
}

})

Entity Framework Query for inner join

from s in db.Services
join sa in db.ServiceAssignments on s.Id equals sa.ServiceId
where sa.LocationId == 1
select s

Where db is your DbContext. Generated query will look like (sample for EF6):

SELECT [Extent1].[Id] AS [Id]
       -- other fields from Services table
FROM [dbo].[Services] AS [Extent1]
INNER JOIN [dbo].[ServiceAssignments] AS [Extent2]
    ON [Extent1].[Id] = [Extent2].[ServiceId]
WHERE [Extent2].[LocationId] = 1

How can I position my jQuery dialog to center?

Jquery UI 1.9.2, jquery and the later versions don' support IE8

I found two solutions for that.

  1. Rollback to jquery UI 1.7.2 to support IE8,

  2. Try this code with Jquery UI 1.9.2

position: {my: "center",  at: "center", of: $("body"),within: $("body") }

How do I configure git to ignore some files locally?

Both --assume-unchanged and --skip-worktree are NOT A CORRECT WAY to ignore files locally... Kindly check this answer and the notes in the documentation of git update-index. Files that for any reason keep changing frequently (and/or change from a clone to another) and their changes should not be committed, then these files SHOULD NOT be tracked in the first place.

However, the are two proper ways to ignore files locally (both work with untracked files). Either to put files names in .git/info/exclude file which is the local alternative of .gitignore but specific to the current clone. Or to use a global .gitignore (which should be properly used only for common auxiliary files e.g. pyz, pycache, etc) and the file will be ignored in any git repo in your machine.

To make the above as kind of automated (adding to exclude or global .gitignore), you can use the following commands (add to your bash-profile):

  • Per clone local exclude (Note that you should be in the root of the repository when calling the command because of using the relative path), change ##FILE-NAME## to .git/info/exclude
  • Global .gitignore, first make global .gitignore here then change ##FILE-NAME## to ~/.gitignore

Linux

alias git-ignore='echo $1 >> ##FILE-NAME##'
alias git-show-ignored='cat ##FILE-NAME##'
git-unignore(){
  GITFILETOUNIGNORE=${1//\//\\\/}
  sed -i "/$GITFILETOUNIGNORE/d" ##FILE-NAME##
  unset GITFILETOUNIGNORE
}

MacOS (you need the .bak for sed inplace modifications (i.e. you are forced to add a file extension to inplace sed. i.e. make a backup before replacing something), therefore to delete the .bak file I added rm filename.bak)

alias git-ignore='echo $1 >> ##FILE-NAME##'
alias git-show-ignored='cat ##FILE-NAME##'
git-unignore(){
  GITFILETOUNIGNORE=${1//\//\\\/}
  sed -i.bak "/$GITFILETOUNIGNORE/d" ##FILE-NAME##
  rm ##FILE-NAME##.bak
  unset GITFILETOUNIGNORE
}

Then you can do:

git-ignore example_file.txt
git-unignore example_file.txt

Resetting a setTimeout

var myTimer = setTimeout(..., 115000);
something.click(function () {
    clearTimeout(myTimer);
    myTimer = setTimeout(..., 115000);
}); 

Something along those lines!

Mysql - delete from multiple tables with one query

A join statement is unnecessarily complicated in this situation. The original question only deals with deleting records for a given user from multiple tables at the same time. Intuitively, you might expect something like this to work:

DELETE FROM table1,table2,table3,table4 WHERE user_id='$user_id'

Of course, it doesn't. But rather than writing multiple statements (redundant and inefficient), using joins (difficult for novices), or foreign keys (even more difficult for novices and not available in all engines or existing datasets) you could simplify your code with a LOOP!

As a basic example using PHP (where $db is your connection handle):

$tables = array("table1","table2","table3","table4");
foreach($tables as $table) {
  $query = "DELETE FROM $table WHERE user_id='$user_id'";
  mysqli_query($db,$query);
}

Hope this helps someone!

if, elif, else statement issues in Bash

I would recommend you having a look at the basics of conditioning in bash.

The symbol "[" is a command and must have a whitespace prior to it. If you don't give whitespace after your elif, the system interprets elif[ as a a particular command which is definitely not what you'd want at this time.

Usage:

elif(A COMPULSORY WHITESPACE WITHOUT PARENTHESIS)[(A WHITE SPACE WITHOUT PARENTHESIS)conditions(A WHITESPACE WITHOUT PARENTHESIS)]

In short, edit your code segment to:

elif [ "$seconds" -gt 0 ]

You'd be fine with no compilation errors. Your final code segment should look like this:

#!/bin/sh    
if [ "$seconds" -eq 0 ];then
       $timezone_string="Z"
    elif [ "$seconds" -gt 0 ]
    then
       $timezone_string=`printf "%02d:%02d" $seconds/3600 ($seconds/60)%60`
    else
       echo "Unknown parameter"
    fi

Error handling in getJSON calls

I know it's been a while since someone answerd here and the poster probably already got his answer either from here or from somewhere else. I do however think that this post will help anyone looking for a way to keep track of errors and timeouts while doing getJSON requests. Therefore below my answer to the question

The getJSON structure is as follows (found on http://api.jqueri.com):

$(selector).getJSON(url,data,success(data,status,xhr))

most people implement that using

$.getJSON(url, datatosend, function(data){
    //do something with the data
});

where they use the url var to provide a link to the JSON data, the datatosend as a place to add the "?callback=?" and other variables that have to be send to get the correct JSON data returned, and the success funcion as a function for processing the data.

You can however add the status and xhr variables in your success function. The status variable contains one of the following strings : "success", "notmodified", "error", "timeout", or "parsererror", and the xhr variable contains the returned XMLHttpRequest object (found on w3schools)

$.getJSON(url, datatosend, function(data, status, xhr){
    if (status == "success"){
        //do something with the data
    }else if (status == "timeout"){
        alert("Something is wrong with the connection");
    }else if (status == "error" || status == "parsererror" ){
        alert("An error occured");
    }else{
        alert("datatosend did not change");
    }         
});

This way it is easy to keep track of timeouts and errors without having to implement a custom timeout tracker that is started once a request is done.

Hope this helps someone still looking for an answer to this question.

Using numpy to build an array of all combinations of two arrays

Here's yet another way, using pure NumPy, no recursion, no list comprehension, and no explicit for loops. It's about 20% slower than the original answer, and it's based on np.meshgrid.

def cartesian(*arrays):
    mesh = np.meshgrid(*arrays)  # standard numpy meshgrid
    dim = len(mesh)  # number of dimensions
    elements = mesh[0].size  # number of elements, any index will do
    flat = np.concatenate(mesh).ravel()  # flatten the whole meshgrid
    reshape = np.reshape(flat, (dim, elements)).T  # reshape and transpose
    return reshape

For example,

x = np.arange(3)
a = cartesian(x, x, x, x, x)
print(a)

gives

[[0 0 0 0 0]
 [0 0 0 0 1]
 [0 0 0 0 2]
 ..., 
 [2 2 2 2 0]
 [2 2 2 2 1]
 [2 2 2 2 2]]

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

This totally worked:

gem install --http-proxy http://COMPANY.PROXY.ADDRESS $gem_name

SELECT DISTINCT on one column

Assuming that you're on SQL Server 2005 or greater, you can use a CTE with ROW_NUMBER():

SELECT  *
FROM    (SELECT ID, SKU, Product,
                ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowNumber
         FROM   MyTable
         WHERE  SKU LIKE 'FOO%') AS a
WHERE   a.RowNumber = 1

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

How to enable curl in Wamp server

Left Click on the WAMP icon the system try -> PHP -> PHP Extensions -> Enable php_curl

npm - how to show the latest version of a package

You can use:

npm show {pkg} version

(so npm show express version will return now 3.0.0rc3).

How to generate List<String> from SQL query?

If you would like to query all columns

List<Users> list_users = new List<Users>();
MySqlConnection cn = new MySqlConnection("connection");
MySqlCommand cm = new MySqlCommand("select * from users",cn);
try
{
    cn.Open();
    MySqlDataReader dr = cm.ExecuteReader();
    while (dr.Read())
    {
        list_users.Add(new Users(dr));
    }
}
catch { /* error */ }
finally { cn.Close(); }

The User's constructor would do all the "dr.GetString(i)"

Python print statement “Syntax Error: invalid syntax”

In Python 3, print is a function, you need to call it like print("hello world").

Is there any way to debug chrome in any IOS device

Old Answer (July 2016):

You can't directly debug Chrome for iOS due to restrictions on the published WKWebView apps, but there are a few options already discussed in other SO threads:

  1. If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.

  2. WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.

  3. You could try and create a simple WKWebView browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.

There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView, Chrome for iOS would be debuggable.

Update January 2018:

Since my answer back in 2016, some work has been done to improve things.

There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.

Check out the getting started guide in the repo, which is quite detailed.

If you are interesting, you can read up on the background and architecture here.

Python - Locating the position of a regex match in a string?

re.Match objects have a number of methods to help you with this:

>>> m = re.search("is", String)
>>> m.span()
(2, 4)
>>> m.start()
2
>>> m.end()
4

How can I pass a Bitmap object from one activity to another

Actually, passing a bitmap as a Parcelable will result in a "JAVA BINDER FAILURE" error. Try passing the bitmap as a byte array and building it for display in the next activity.

I shared my solution here:
how do you pass images (bitmaps) between android activities using bundles?

Removing whitespace between HTML elements when using line breaks

Inspired by Quentin's answer, you can also place the closing > next to the start of the next tag.

 <img src="..." alt="..."
 /><img src="..." alt="..."
 /><img src="..." alt="..."
 /><img src="..." alt="..."/>

How to change button text in Swift Xcode 6?

swift 4 work as well as 3

libero.setTitle("---", for: .normal)

where libero is a uibutton

Smooth scroll to div id jQuery

This code will be useful for any internal link on the web

    $("[href^='#']").click(function() {
        id=$(this).attr("href")
        $('html, body').animate({
            scrollTop: $(id).offset().top
        }, 2000);
    });

Plotting a 3d cube, a sphere and a vector in Matplotlib

My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)


# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)

# tails of the arrows
tails= np.zeros(len(bvecs))

# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
          length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

ax.set_title('b-vectors on unit sphere')

plt.show()

How to use this boolean in an if statement?

Actually, the entire approach would be cleaner if you only had to use one instance of StringBuffer, instead of creating one in every recursive call... I would go for:

private String getWhoozitYs(){
     StringBuffer sb = new StringBuffer();
     while (generator.nextBoolean()) {
         sb.append("y");
     }

     return sb.toString();
}

How to clear File Input

I have done something like this and it's working for me

$('#fileInput').val(null); 

How to use split?

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));

Setting up and using environment variables in IntelliJ Idea

In addition to the above answer and restarting the IDE didn't do, try restarting "Jetbrains Toolbox" if you use it, this did it for me

How to copy std::string into std::vector<char>?

std::vector has a constructor that takes two iterators. You can use that:

std::string str = "hello";
std::vector<char> data(str.begin(), str.end());

If you already have a vector and want to add the characters at the end, you need a back inserter:

std::string str = "hello";
std::vector<char> data = /* ... */;
std::copy(str.begin(), str.end(), std::back_inserter(data));

Query to search all packages for table and/or column

you can use the views *_DEPENDENCIES, for example:

SELECT owner, NAME
  FROM dba_dependencies
 WHERE referenced_owner = :table_owner
   AND referenced_name = :table_name
   AND TYPE IN ('PACKAGE', 'PACKAGE BODY')

CASE in WHERE, SQL Server

You can simplify to:

WHERE a.Country = COALESCE(NULLIF(@Country,0), a.Country);

How do you get the length of a list in the JSF expression language?

Note: This solution is better for older versions of JSTL. For versions greater then 1.1 I recommend using fn:length(MyBean.somelist) as suggested by Bill James.


This article has some more detailed information, including another possible solution;

The problem is that we are trying to invoke the list's size method (which is a valid LinkedList method), but it's not a JavaBeans-compliant getter method, so the expression list.size-1 cannot be evaluated.

There are two ways to address this dilemma. First, you can use the RT Core library, like this:

<c_rt:out value='<%= list[list.size()-1] %>'/>

Second, if you want to avoid Java code in your JSP pages, you can implement a simple wrapper class that contains a list and provides access to the list's size property with a JavaBeans-compliant getter method. That bean is listed in Listing 2.25.

The problem with c_rt method is that you need to get the variable from request manually, because it doesn't recognize it otherwise. At this point you are putting in a lot of code for what should be built in functionality. This is a GIANT flaw in the EL.

I ended up using the "wrapper" method, here is the class for it;

public class CollectionWrapper {

    Collection collection;

    public CollectionWrapper(Collection collection) {
        this.collection = collection;
    }

    public Collection getCollection() {
        return collection;
    }

    public int getSize() {
        return collection.size();
    }
}

A third option that no one has mentioned yet is to put your list size into the model (assuming you are using MVC) as a separate attribute. So in your model you would have "someList" and then "someListSize". That may be simplest way to solve this issue.

NHibernate.MappingException: No persister for: XYZ

I have a similar problem but all mentioned requirements are met. In my case I try to save some entity class (Type of OBJEKTE) back to the DB. Other places do work but only in this case it fails and raises this exception.

My solution (HACK) was to re-map the objet of type OBJEKTE again and store it then. Suddenly it works. But don't ask why.

            OBJEKTE t = _mapper.Map<OBJEKTE>(inparam);
            OBJEKTE res = await _objRepo.UpdateAsync(t);

If inparam would go straight to UpdateAsync() it cannot find a matching persistor.

It could be explained by the way NH does this. It derives a proxy from your mapping class and implements the properties with dirty handling included. See this:

t.GetType()
{Name = "OBJEKTE" FullName = "MyComp.Persistence.OBJEKTE"}

inparam.GetType()
{Name = "OBJEKTEProxyForFieldInterceptor" FullName = "OBJEKTEProxyForFieldInterceptor"}

The fun thing though is that the source of inparam is in fact the NH repository itself. Anyways. I stay with this reassign hack for the next time being.

Finding Variable Type in JavaScript

typeof is only good for returning the "primitive" types such as number, boolean, object, string and symbols. You can also use instanceof to test if an object is of a specific type.

function MyObj(prop) {
  this.prop = prop;
}

var obj = new MyObj(10);

console.log(obj instanceof MyObj && obj instanceof Object); // outputs true

Get bitcoin historical data

Coinbase has a REST API that gives you access to historical prices from their website. The data seems to show the Coinbase spot price (in USD) about every ten minutes.

Results are returned in CSV format. You must query the page number you want through the API. There are 1000 results (or price points) per page. That's about 7 days' worth of data per page.

how to show progress bar(circle) in an activity having a listview before loading the listview with data

You can add the ProgressBar to listview footer:

private ListView listview;
private ProgressBar progressBar;

...

progressBar = (ProgressBar) LayoutInflater.from(this).inflate(R.layout.progress_bar, null);

listview.addFooterView(progressBar);

layout/progress_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/load_progress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:indeterminate="true"
     />

when the data is loaded to the adapter view call:

        listview.removeFooterView(progressBar);

Assert a function/method was not called using Mock

With python >= 3.5 you can use mock_object.assert_not_called().

What is the use of rt.jar file in java?

rt.jar contains all of the compiled class files for the base Java Runtime environment. You should not be messing with this jar file.

For MacOS it is called classes.jar and located under /System/Library/Frameworks/<java_version>/Classes . Same not messing with it rule applies there as well :).

http://javahowto.blogspot.com/2006/05/what-does-rtjar-stand-for-in.html

ImportError: DLL load failed: %1 is not a valid Win32 application

You could try installing the 32 bit version of opencv

How to sort dates from Oldest to Newest in Excel?

In my case the format changing did not help, nothing changed in the date representation whatever cell format I was selecting. However, I found that the correct date entry for 18.11.1999 when F2 pressed was 18 11 1999 - whith spaces, no dots! When I performed "search-replace" and changed dots with space, the problem was solved.

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

Customize Bootstrap checkboxes

You have to use Bootstrap version 4 with the custom-* classes to get this style:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- example code of the bootstrap website -->_x000D_
<label class="custom-control custom-checkbox">_x000D_
  <input type="checkbox" class="custom-control-input">_x000D_
  <span class="custom-control-indicator"></span>_x000D_
  <span class="custom-control-description">Check this custom checkbox</span>_x000D_
</label>_x000D_
_x000D_
<!-- your code with the custom classes of version 4 -->_x000D_
<div class="checkbox">_x000D_
  <label class="custom-control custom-checkbox">_x000D_
    <input type="checkbox" [(ngModel)]="rememberMe" name="rememberme" class="custom-control-input">_x000D_
    <span class="custom-control-indicator"></span>_x000D_
    <span class="custom-control-description">Remember me</span>_x000D_
  </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Documentation: https://getbootstrap.com/docs/4.0/components/forms/#checkboxes-and-radios-1


Custom checkbox style on Bootstrap version 3?
Bootstrap version 3 doesn't have custom checkbox styles, but you can use your own. In this case: How to style a checkbox using CSS?

These custom styles are only available since version 4.

Why not inherit from List<T>?

Just because I think the other answers pretty much go off on a tangent of whether a football team "is-a" List<FootballPlayer> or "has-a" List<FootballPlayer>, which really doesn't answer this question as written.

The OP chiefly asks for clarification on guidelines for inheriting from List<T>:

A guideline says that you shouldn't inherit from List<T>. Why not?

Because List<T> has no virtual methods. This is less of a problem in your own code, since you can usually switch out the implementation with relatively little pain - but can be a much bigger deal in a public API.

What is a public API and why should I care?

A public API is an interface you expose to 3rd party programmers. Think framework code. And recall that the guidelines being referenced are the ".NET Framework Design Guidelines" and not the ".NET Application Design Guidelines". There is a difference, and - generally speaking - public API design is a lot more strict.

If my current project does not and is not likely to ever have this public API, can I safely ignore this guideline? If I do inherit from List and it turns out I need a public API, what difficulties will I have?

Pretty much, yeah. You may want to consider the rationale behind it to see if it applies to your situation anyway, but if you're not building a public API then you don't particularly need to worry about API concerns like versioning (of which, this is a subset).

If you add a public API in the future, you will either need to abstract out your API from your implementation (by not exposing your List<T> directly) or violate the guidelines with the possible future pain that entails.

Why does it even matter? A list is a list. What could possibly change? What could I possibly want to change?

Depends on the context, but since we're using FootballTeam as an example - imagine that you can't add a FootballPlayer if it would cause the team to go over the salary cap. A possible way of adding that would be something like:

 class FootballTeam : List<FootballPlayer> {
     override void Add(FootballPlayer player) {
        if (this.Sum(p => p.Salary) + player.Salary > SALARY_CAP)) {
          throw new InvalidOperationException("Would exceed salary cap!");
        }
     }
 }

Ah...but you can't override Add because it's not virtual (for performance reasons).

If you're in an application (which, basically, means that you and all of your callers are compiled together) then you can now change to using IList<T> and fix up any compile errors:

 class FootballTeam : IList<FootballPlayer> {
     private List<FootballPlayer> Players { get; set; }

     override void Add(FootballPlayer player) {
        if (this.Players.Sum(p => p.Salary) + player.Salary > SALARY_CAP)) {
          throw new InvalidOperationException("Would exceed salary cap!");
        }
     }
     /* boiler plate for rest of IList */
 }

but, if you've publically exposed to a 3rd party you just made a breaking change that will cause compile and/or runtime errors.

TL;DR - the guidelines are for public APIs. For private APIs, do what you want.

What exactly is Apache Camel?

One of the things you need to understand, before you try to understand Apache Camel, are Enterprise Integration Patterns. Not everyone in the field is actually aware of them. While you can certainly read the Enterprise Integration Patterns book, a quicker way to get up to speed on them would be to read something like the Wikipedia article on Enterprise Application Integration.

One you have read and understood the subject area, you would be much more likely to understand the purpose of Apache Camel

HTH

Find Nth occurrence of a character in a string

Since the built-in IndexOf function is already optimized for searching a character within a string, an even faster version would be (as extension method):

public static int NthIndexOf(this string input, char value, int n)
{
    if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

    int i = -1;
    do
    {
        i = input.IndexOf(value, i + 1);
        n--;
    }
    while (i != -1 && n > 0);

    return i;
}

Or to search from the end of the string using LastIndexOf:

public static int NthLastIndexOf(this string input, char value, int n)
{
    if (n <= 0) throw new ArgumentOutOfRangeException("n", n, "n is less than zero.");

    int i = input.Length;
    do
    {
        i = input.LastIndexOf(value, i - 1);
        n--;
    }
    while (i != -1 && n > 0);

    return i;
}

Searching for a string instead of a character is as simple as changing the parameter type from char to string and optionally add an overload to specify the StringComparison.

How to pass prepareForSegue: an object

I've implemented a library with a category on UIViewController that simplifies this operation. Basically, you set the parameters you want to pass over in a NSDictionary associated to the UI item that is performing the segue. It works with manual segues too.

For example, you can do

[self performSegueWithIdentifier:@"yourIdentifier" parameters:@{@"customParam1":customValue1, @"customValue2":customValue2}];

for a manual segue or create a button with a segue and use

[button setSegueParameters:@{@"customParam1":customValue1, @"customValue2":customValue2}];

If destination view controller is not key-value coding compliant for a key, nothing happens. It works with key-values too (useful for unwind segues). Check it out here https://github.com/stefanomondino/SMQuickSegue

How do I rename both a Git local and remote branch name?

This can be done even without renaming the local branch in three simple steps:

  1. Go to your repository in GitHub
  2. Create a new branch from the old branch which you want to rename
  3. Delete the old branch

SSIS Text was truncated with status value 4

One possible reason for this error is that your delimiter character (comma, semi-colon, pipe, whatever) actually appears in the data in one column. This can give very misleading error messages, often with the name of a totally different column.

One way to check this is to redirect the 'bad' rows to a separate file and then inspect them manually. Here's a brief explanation of how to do that:

http://redmondmag.com/articles/2010/04/12/log-error-rows-ssis.aspx

If that is indeed your problem, then the best solution is to fix the files at the source to quote the data values and/or use a different delimeter that isn't in the data.

How to get "their" changes in the middle of conflicting Git rebase?

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

Background color of text in SVG

For those wondering how to apply padding to a text element when it has a background like in the Robert's answer, do the following:

  <svg>
    <defs>
      <filter x="-0.1" y="-0.1" width="1.2" height="1.2" id="solid">
        <feFlood flood-color="#171717"/>
        <feComposite in="SourceGraphic" operator="xor" />
      </filter>
    </defs>
    <text filter="url(#solid)" x="20" y="50" font-size="50">Hello</text>
  </svg>

In the example above, filter's x and y positions can be used as transform: translate(-10%, -10%) would, and width and height values can be read as 120% and 120%. So we made background 20% bigger, and offsetted it -10%, so background is now 10% bigger on each side of the text.

Design Android EditText to show error message as described by google

private EditText edt_firstName;
private String firstName;

edt_firstName = findViewById(R.id.edt_firstName);

private void validateData() {
 firstName = edt_firstName.getText().toString().trim();
 if (!firstName.isEmpty(){
//here api call for ....
}else{
if (firstName.isEmpty()) {
                edt_firstName.setError("Please Enter First Name");
                edt_firstName.requestFocus();
            } 
}
}

What is the difference between Normalize.css and Reset CSS?

Normalize.css is mainly a set of styles, based on what its author thought would look good, and make it look consistent across browsers. Reset basically strips styling from elements so you have more control over the styling of everything.

I use both.

Some styles from Reset, some from Normalize.css. For example, from Normalize.css, there's a style to make sure all input elements have the same font, which doesn't occur (between text inputs and textareas). Reset has no such style, so inputs have different fonts, which is not normally wanted.

So bascially, using the two CSS files does a better job 'Equalizing' everything ;)

regards!

How to use OKHTTP to make a post request?

This is one of the possible solutions to implementing an OKHTTP post request without a request body.

RequestBody reqbody = RequestBody.create(null, new byte[0]);  
Request.Builder formBody = new Request.Builder().url(url).method("POST",reqbody).header("Content-Length", "0");
clientOk.newCall(formBody.build()).enqueue(OkHttpCallBack());

How do I delete all the duplicate records in a MySQL table without temp tables

This doesn't use TEMP Tables, but real tables instead. If the problem is just about temp tables and not about table creation or dropping tables, this will work:

SELECT DISTINCT * INTO TableA_Verify FROM TableA;

DROP TABLE TableA;

RENAME TABLE TableA_Verify TO TableA;

How to find whether or not a variable is empty in Bash?

I have also seen

if [ "x$variable" = "x" ]; then ...

which is obviously very robust and shell independent.

Also, there is a difference between "empty" and "unset". See How to tell if a string is not defined in a Bash shell script.

What is the difference between Integer and int in Java?

Integer refers to wrapper type in Java whereas int is a primitive type. Everything except primitive data types in Java is implemented just as objects that implies Java is a highly qualified pure object-oriented programming language. If you need, all primitives types are also available as wrapper types in Java. You can have some performance benefit with primitive types, and hence wrapper types should be used only when it is necessary.

In your example as below.

Integer n = 9;

the constant 9 is being auto-boxed (auto-boxing and unboxing occurs automatically from java 5 onwards) to Integer and therefore you can use the statement like that and also Integer n = new Integer(9). This is actually achieved through the statement Integer.valueOf(9).intValue();

Change NULL values in Datetime format to empty string

select case when IsNull(CONVERT(DATE, StartDate),'')='' then 'NA' else Convert(varchar(10),StartDate,121) end from table1

Spring application context external properties?

You can try something like this:

<context:property-placeholder 
        location="${ext.properties.dir:classpath:}/servlet.properties" />

And define ext.properties.dir property in your application server / jvm, otherwise the default properties location "classpath:/" (i.e., classes dir of .jar or .war) would be used:

-Dext.properties.dir=file:/usr/local/etc/

BTW, very useful blog post.

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});
     }
}

Select records from today, this week, this month php mysql

I think using NOW() function is incorrect for getting time difference. Because by NOW() function every time your are calculating the past 24 hours. You must use CURDATE() instead.

    function your_function($time, $your_date) {
    if ($time == 'today') {
        $timeSQL = ' Date($your_date)= CURDATE()';
    }
    if ($time == 'week') {
        $timeSQL = ' YEARWEEK($your_date)= YEARWEEK(CURDATE())';
    }
    if ($time == 'month') {
        $timeSQL = ' Year($your_date)=Year(CURDATE()) AND Month(`your_date`)= Month(CURDATE())';
    }

    $Sql = "SELECT * FROM jokes WHERE ".$timeSQL
    return $Result = $this->db->query($Sql)->result_array();
}

Upload failed You need to use a different version code for your APK because you already have one with version code 2

if you are using phonegap / cordova applications, just edit your config.xml and add the android-versionCode and version in the widget.

<widget id="com.xxx.yyy" version="1.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" android-versionCode="100001" version="1.0.1">

MySQL combine two columns into one column

table:

---------------------
| column1 | column2 |
---------------------
|   abc   |   xyz   |
---------------------

In Oracle:

SELECT column1 || column2 AS column3
FROM table_name;

Output:

table:

---------------------
| column3           |
---------------------
| abcxyz            |
---------------------

If you want to put ',' or '.' or any string within two column data then you may use:

SELECT column1 || '.' || column2 AS column3
FROM table_name;

Output:

table:

---------------------
| column3           |
---------------------
| abc.xyz           |
---------------------

UnicodeDecodeError when reading CSV file in Pandas with Python

Please try to add

encoding='unicode_escape'

This will help. Worked for me. Also, make sure you're using the correct delimiter and column names.

You can start with loading just 1000 rows to load the file quickly.

Prevent direct access to a php include file

The easiest way is to set some variable in the file that calls include, such as

$including = true;

Then in the file that's being included, check for the variable

if (!$including) exit("direct access not permitted");

Easy way to make a confirmation dialog in Angular?

You could use sweetalert: https://sweetalert.js.org/guides/

npm install sweetalert --save

Then, simply import it into your application:

import swal from 'sweetalert';

If you pass two arguments, the first one will be the modal's title, and the second one its text.

swal("Here's the title!", "...and here's the text!");

RestSharp simple complete example

Changing

RestResponse response = client.Execute(request);

to

IRestResponse response = client.Execute(request);

worked for me.

C# SQL Server - Passing a list to a stored procedure

The typical pattern in this situation is to pass the elements in a comma delimited list, and then in SQL split that out into a table you can use. Most people usually create a specified function for doing this like:

 INSERT INTO <SomeTempTable>
 SELECT item FROM dbo.SplitCommaString(@myParameter)

And then you can use it in other queries.

How do I upgrade PHP in Mac OS X?

Upgrading to Snow Leopard won't solve the your primary problem of keeping PHP up to date. Apple doesn't always keep the third party software that it bundles up to date with OS updates. And relying on Apple to get you the bug fix / security update you need is asking for trouble.

Additionally, I would recommend installing through MacPorts (and doing the config necessary to use it instead of Apple's PHP) rather than try to upgrade the Apple supplied PHP in place. Anything you do to /usr/bin risks being overwritten by some future Apple update.

How to make a floated div 100% height of its parent?

This is a code sample for grid system with equal height.

#outer{
width: 100%;
margin-top: 1rem;
display: flex;
height:auto;
}

Above is the CSS for outer div

#inner{
width: 20%;
float: left;
border: 1px solid;
}

Above is the inner div

Hope this help you

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use the below code on your string and you will get the complete string without html part.

string title = "<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)".Replace("&nbsp;",string.Empty);            
        string s = Regex.Replace(title, "<.*?>", String.Empty);

How to get complete month name from DateTime

If you receive "MMMM" as a response, probably you are getting the month and then converting it to a string of defined format.

DateTime.Now.Month.ToString("MMMM") 

will output "MMMM"

DateTime.Now.ToString("MMMM") 

will output the month name

Run a shell script with an html button

PHP is likely the easiest.

Just make a file script.php that contains <?php shell_exec("yourscript.sh"); ?> and send anybody who clicks the button to that destination. You can return the user to the original page with header:

<?php
shell_exec("yourscript.sh");
header('Location: http://www.website.com/page?success=true');
?>

Reference: http://php.net/manual/en/function.shell-exec.php

Where should I put the log4j.properties file?

Your standard project setup will have a project structure something like:

src/main/java
src/main/resources

You place log4j.properties inside the resources folder, you can create the resources folder if one does not exist

Propagation Delay vs Transmission delay

Transmission Delay:

This is the amount of time required to transmit all of the packet's bits into the link. Transmission delays are typically on the order of microseconds or less in practice. 

L: packet length (bits)
R: link bandwidth (bps)
so transmission delay is = L/R

Propagation Delay:

Is the time it takes a bit to propagate over the transmission medium from the source router to the destination router; it is a function of the distance between the two routers, but has nothing to do with the packet's length or the transmission rate of the link. 

d: length of physical link
S: propagation speed in medium (~2x108m/sec, for copper wires & ~3x108m/sec, for wireless media)
so propagation delay is = d/s

Add numpy array as column to Pandas data frame

Here is other example:

import numpy as np
import pandas as pd

""" This just creates a list of touples, and each element of the touple is an array"""
a = [ (np.random.randint(1,10,10), np.array([0,1,2,3,4,5,6,7,8,9]))  for i in 
range(0,10) ]

""" Panda DataFrame will allocate each of the arrays , contained as a touple 
element , as column"""
df = pd.DataFrame(data =a,columns=['random_num','sequential_num'])

The secret in general is to allocate the data in the form a = [ (array_11, array_12,...,array_1n),...,(array_m1,array_m2,...,array_mn) ] and panda DataFrame will order the data in n columns of arrays. Of course , arrays of arrays could be used instead of touples, in that case the form would be : a = [ [array_11, array_12,...,array_1n],...,[array_m1,array_m2,...,array_mn] ]

This is the output if you print(df) from the code above:

                       random_num                  sequential_num
0  [7, 9, 2, 2, 5, 3, 5, 3, 1, 4]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1  [8, 7, 9, 8, 1, 2, 2, 6, 6, 3]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2  [3, 4, 1, 2, 2, 1, 4, 2, 6, 1]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3  [3, 1, 1, 1, 6, 2, 8, 6, 7, 9]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4  [4, 2, 8, 5, 4, 1, 2, 2, 3, 3]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5  [3, 2, 7, 4, 1, 5, 1, 4, 6, 3]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6  [5, 7, 3, 9, 7, 8, 4, 1, 3, 1]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
7  [7, 4, 7, 6, 2, 6, 3, 2, 5, 6]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8  [3, 1, 6, 3, 2, 1, 5, 2, 2, 9]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9  [7, 2, 3, 9, 5, 5, 8, 6, 9, 8]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Other variation of the example above:

b = [ (i,"text",[14, 5,], np.array([0,1,2,3,4,5,6,7,8,9]))  for i in 
range(0,10) ]
df = pd.DataFrame(data=b,columns=['Number','Text','2Elemnt_array','10Element_array'])

Output of df:

   Number  Text 2Elemnt_array                 10Element_array
0       0  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1       1  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2       2  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3       3  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4       4  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5       5  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6       6  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
7       7  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8       8  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9       9  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If you want to add other columns of arrays, then:

df['3Element_array']=[([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3])]

The final output of df will be:

   Number  Text 2Elemnt_array                 10Element_array 3Element_array
0       0  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
1       1  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
2       2  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
3       3  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
4       4  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
5       5  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
6       6  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
7       7  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
8       8  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
9       9  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]

How to convert from []byte to int in Go Programming

now := []byte{0xFF,0xFF,0xFF,0xFF}
nowBuffer := bytes.NewReader(now)
var  nowVar uint32
binary.Read(nowBuffer,binary.BigEndian,&nowVar)
fmt.Println(nowVar)
4294967295

What is output buffering?

Output buffering is used by PHP to improve performance and to perform a few tricks.

  • You can have PHP store all output into a buffer and output all of it at once improving network performance.

  • You can access the buffer content without sending it back to browser in certain situations.

Consider this example:

<?php
    ob_start( );
    phpinfo( );
    $output = ob_get_clean( );
?>

The above example captures the output into a variable instead of sending it to the browser. output_buffering is turned off by default.

  • You can use output buffering in situations when you want to modify headers after sending content.

Consider this example:

<?php
    ob_start( );
    echo "Hello World";
    if ( $some_error )
    {
        header( "Location: error.php" );
        exit( 0 );
    }
?>

Create a custom View by inflating a layout?

Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.

What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.

http://developer.android.com/guide/topics/ui/custom-components.html

How to make Unicode charset in cmd.exe by default?

Open an elevated Command Prompt (run cmd as administrator). query your registry for available TT fonts to the console by:

    REG query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont"

You'll see an output like :

    0    REG_SZ    Lucida Console
    00    REG_SZ    Consolas
    936    REG_SZ    *???
    932    REG_SZ    *MS ????

Now we need to add a TT font that supports the characters you need like Courier New, we do this by adding zeros to the string name, so in this case the next one would be "000" :

    REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 000 /t REG_SZ /d "Courier New"

Now we implement UTF-8 support:

    REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 65001 /f

Set default font to "Courier New":

    REG ADD HKCU\Console /v FaceName /t REG_SZ /d "Courier New" /f

Set font size to 20 :

    REG ADD HKCU\Console /v FontSize /t REG_DWORD /d 20 /f

Enable quick edit if you like :

    REG ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f

github changes not staged for commit

I kept receiving the same message no matter what i did.

To fix this, i removed .gitignore and i am not getting the Github changes not staged for commit message anymore. Before it would allow me to commit once when i ran git add . and then after it would bring up the same message.

Im not sure why the .gitignore file was causing a problem but i added on my local machine and most likely didn't sync it up properly.

CSS Float: Floating an image to the left of the text

Just need to float both elements left:

.post-container{
    margin: 20px 20px 0 0;  
    border:5px solid #333;
}

.post-thumb img {
    float: left;
}

.post-content {
    float: left;
}

Edit: actually, you do not need the width, just float both left

What does "exited with code 9009" mean during this build?

Most probably you have space in your resultant path.

You can work around this by quoting the paths, thus allowing spaces. For example:

xcopy "$(SolutionDir)\Folder Name\File To Copy.ext" "$(TargetDir)" /R /Y /I

Create a .csv file with values from a Python list

import csv

with open(..., 'wb') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(mylist)

Edit: this only works with python 2.x.

To make it work with python 3.x replace wb with w (see this SO answer)

with open(..., 'w', newline='') as myfile:
     wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
     wr.writerow(mylist)

How to insert a SQLite record with a datetime set to 'now' in Android application?

You cannot use the datetime function using the Java wrapper "ContentValues". Either you can use :

  • SQLiteDatabase.execSQL so you can enter a raw SQL query.

    mDb.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES (null, datetime()) ");
    
  • Or the java date time capabilities :

    // set the format to sql date time
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    Date date = new Date();
    ContentValues initialValues = new ContentValues(); 
    initialValues.put("date_created", dateFormat.format(date));
    long rowId = mDb.insert(DATABASE_TABLE, null, initialValues);
    

How to completely uninstall Visual Studio 2010?

Best way I have used is to mount the VS 2010 Image or insert the Installation disc and run the uninstall option, really works well