Programs & Examples On #Faultexception

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

If you want to do this by code, you can add the behavior like this:

serviceHost.Description.Behaviors.Remove(
    typeof(ServiceDebugBehavior));
serviceHost.Description.Behaviors.Add(
    new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });

WCF gives an unsecured or incorrectly secured fault error

Although your problem was solved with one of the above solutions, for the benefit of others, here's another option.

You also can get this exception when incorrect credentials are passed to a basic endpoint (SOAP 1.1) that uses username message credentials as you are. For example, if you are calling the service from code and do something like this:

var service = new TestService();

service.ClientCredentials.UserName.UserName = "InvalidUser";
service.ClientCredentials.UserName.Password = "InvalidPass";

This is different from a WSHTTP endpoint (SOAP 1.2) that throws an AccessDeniedException when invalid credentials are passed through. I personally find the message contained herein a little misleading (it certainly cost me a few minutes the first time I encountered it for this reason) but the underlying cause was clear once I consulted the WCF Diagnostic Trace Logs.

How do I solve this error, "error while trying to deserialize parameter"

Are you sure your web service is deployed correctly to the enviornment that is NOT working. Looks like the type is out of date.

SQL Error: ORA-00936: missing expression

You did two mistakes . I think you misplace FROM and WHERE keywords.

SELECT DISTINCT Description, Date as treatmentDate
     FROM doothey.Patient P, doothey.Account A, doothey.AccountLine AL,  doothey.Item.I --Here you use "." operator to "I" alias 
  WHERE  -- WHERE should be located here. 
   P.PatientID = A.PatientID
    AND A.AccountNo = AL.AccountNo
    AND AL.ItemNo = I.ItemNo
    AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');

Finding smallest value in an array most efficiently

If finding the minimum is a one time thing, just iterate through the list and find the minimum.

If finding the minimum is a very common thing and you only need to operate on the minimum, use a Heap data structure.

A heap will be faster than doing a sort on the list but the tradeoff is you can only find the minimum.

What is the purpose of backbone.js?

This is a pretty good introductory video: http://vimeo.com/22685608

If you are looking for more on Rails and Backbone, Thoughtbot has this pretty good book (not free): https://workshops.thoughtbot.com/backbone-js-on-rails

Compiling simple Hello World program on OS X via command line

The new version of this should read like so:

xcrun g++ hw.cpp
./a.out

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

You can use the following methods to specify C:\Program Files without a space in it for programs that can't handle spaces in file paths:

'Path to Continuum Reports Subdirectory - Note use DOS equivalent (no spaces)
RepPath = "c:\progra~1\continuum_reports\" or
RepPath = C:\Program Files\Continuum_Reports  'si es para 64 bits.

' Path to Continuum Reports Subdirectory - Note use DOS equivalent (no spaces)
RepPath = "c:\progra~2\continuum_reports\" 'or
RepPath = C:\Program Files (x86)\Continuum_Reports  'si es para 32 bits.

Ordering by specific field value first

This works for me using Postgres 9+:

SELECT *
FROM your_table
ORDER BY name = 'core' DESC, priority DESC

When to use dynamic vs. static libraries

I'd give a general rule of thumb that if you have a large codebase, all built on top of lower level libraries (eg a Utils or Gui framework), which you want to partition into more manageable libraries then make them static libraries. Dynamic libraries don't really buy you anything and there are fewer surprises -- there will only be one instance of singletons for instance.

If you have a library that is entirely separate to the rest of the codebase (eg a third party library) then consider making it a dll. If the library is LGPL you may need to use a dll anyway due to the licensing conditions.

How do I check the difference, in seconds, between two dates?

import time  
current = time.time()

...job...
end = time.time()
diff = end - current

would that work for you?

Checking images for similarity with OpenCV

Sam's solution should be sufficient. I've used combination of both histogram difference and template matching because not one method was working for me 100% of the times. I've given less importance to histogram method though. Here's how I've implemented in simple python script.

import cv2

class CompareImage(object):

    def __init__(self, image_1_path, image_2_path):
        self.minimum_commutative_image_diff = 1
        self.image_1_path = image_1_path
        self.image_2_path = image_2_path

    def compare_image(self):
        image_1 = cv2.imread(self.image_1_path, 0)
        image_2 = cv2.imread(self.image_2_path, 0)
        commutative_image_diff = self.get_image_difference(image_1, image_2)

        if commutative_image_diff < self.minimum_commutative_image_diff:
            print "Matched"
            return commutative_image_diff
        return 10000 //random failure value

    @staticmethod
    def get_image_difference(image_1, image_2):
        first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256])
        second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256])

        img_hist_diff = cv2.compareHist(first_image_hist, second_image_hist, cv2.HISTCMP_BHATTACHARYYA)
        img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0]
        img_template_diff = 1 - img_template_probability_match

        # taking only 10% of histogram diff, since it's less accurate than template method
        commutative_image_diff = (img_hist_diff / 10) + img_template_diff
        return commutative_image_diff


    if __name__ == '__main__':
        compare_image = CompareImage('image1/path', 'image2/path')
        image_difference = compare_image.compare_image()
        print image_difference

Python Regex - How to Get Positions and Values of Matches

Taken from

Regular Expression HOWTO

span() returns both start and end indexes in a single tuple. Since the match method only checks if the RE matches at the start of a string, start() will always be zero. However, the search method of RegexObject instances scans through the string, so the match may not start at zero in that case.

>>> p = re.compile('[a-z]+')
>>> print p.match('::: message')
None
>>> m = p.search('::: message') ; print m
<re.MatchObject instance at 80c9650>
>>> m.group()
'message'
>>> m.span()
(4, 11)

Combine that with:

In Python 2.2, the finditer() method is also available, returning a sequence of MatchObject instances as an iterator.

>>> p = re.compile( ... )
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator
<callable-iterator object at 0x401833ac>
>>> for match in iterator:
...     print match.span()
...
(0, 2)
(22, 24)
(29, 31)

you should be able to do something on the order of

for match in re.finditer(r'[a-z]', 'a1b2c3d4'):
   print match.span()

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

Change grid interval and specify tick labels in Matplotlib

A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.

import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)

fig, ax = plt.subplots(figsize=(10, 8))

# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)

# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))

# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')

Matplotlib Custom Grid

git: How to ignore all present untracked files?

I came here trying to solve a slightly different problem. Maybe this will be useful to someone else:

I create a new branch feature-a. as part of this branch I create new directories and need to modify .gitignore to suppress some of them. This happens a lot when adding new tools to a project that create various cache folders. .serverless, .terraform, etc.

Before I'm ready to merge that back to master I have something else come up, so I checkout master again, but now git status picks up those suppressed folders again, since the .gitignore hasn't been merged yet.

The answer here is actually simple, though I had to find this blog to figure it out:

Just checkout the .gitignore file from feature-a branch

git checkout feature-a -- feature-a/.gitignore
git add .
git commit -m "update .gitignore from feature-a branch"

Can't connect Nexus 4 to adb: unauthorized

It happened for me after my backup software changed the permission to my user directory. I opened it in File Explorer, it prompted me to set permissions and it fixed the issue.

FYI: Android has a special directory under "\User\.android" If you can't access it, it won't prompt you.

How to set a CMake option() at command line

Delete the CMakeCache.txt file and try this:

cmake -G %1 -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DBUILD_TESTS=ON ..

You have to enter all your command-line definitions before including the path.

Plot correlation matrix using pandas

For completeness, the simplest solution i know with seaborn as of late 2019, if one is using Jupyter:

import seaborn as sns
sns.heatmap(dataframe.corr())

A JOIN With Additional Conditions Using Query Builder or Eloquent

$results = DB::table('rooms')
                     ->distinct()
                     ->leftJoin('bookings', function($join)
                         {
                             $join->on('rooms.id', '=', 'bookings.room_type_id');
                             $join->on('arrival','>=',DB::raw("'2012-05-01'"));
                             $join->on('arrival','<=',DB::raw("'2012-05-10'"));
                             $join->on('departure','>=',DB::raw("'2012-05-01'"));
                             $join->on('departure','<=',DB::raw("'2012-05-10'"));
                         })
                     ->where('bookings.room_type_id', '=', NULL)
                     ->get();

Not quite sure if the between clause can be added to the join in laravel.

Notes:

  • DB::raw() instructs Laravel not to put back quotes.
  • By passing a closure to join methods you can add more join conditions to it, on() will add AND condition and orOn() will add OR condition.

How to use sbt from behind proxy?

Add both http and https configuration:

export JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyHost=yourserver -Dhttp.proxyPort=8080 -Dhttp.proxyUser=username -Dhttp.proxyPassword=password"

export JAVA_OPTS="$JAVA_OPTS -Dhttps.proxyHost=yourserver -Dhttps.proxyPort=8080 -Dhttps.proxyUser=username -Dhttps.proxyPassword=password"

(https config is must, since many urls referred by the sbt libraries are https)

In fact, I even had an extra setting 'http.proxySet' to 'true' in both configuration entries.

Convert String to Calendar Object in Java

Parse a time with timezone, Z in pattern is for time zone

String aTime = "2017-10-25T11:39:00+09:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
try {
    Calendar cal = Calendar.getInstance();
    cal.setTime(sdf.parse(aTime));
    Log.i(TAG, "time = " + cal.getTimeInMillis()); 
} catch (ParseException e) {
    e.printStackTrace();
}

Output: it will return the UTC time

1508899140000

enter image description here

If we don't set the time zone in pattern like yyyy-MM-dd'T'HH:mm:ss. SimpleDateFormat will use the time zone which have set in Setting

where does MySQL store database files?

In any case you can know it:

mysql> select @@datadir;
+----------------------------------------------------------------+
| @@datadir                                                      |
+----------------------------------------------------------------+
| D:\Documents and Settings\b394382\My Documents\MySQL_5_1\data\ |
+----------------------------------------------------------------+
1 row in set (0.00 sec)

Thanks Barry Galbraith from the MySql Forum http://forums.mysql.com/read.php?10,379153,379167#msg-379167

Run a controller function whenever a view is opened/shown

This is probably what you were looking for:

Ionic caches your views and thus your controllers by default (max of 10) http://ionicframework.com/docs/api/directive/ionView/

There are events you can hook onto to let your controller do certain things based on those ionic events. see here for an example: http://ionicframework.com/blog/navigating-the-changes/

Function overloading in Javascript - Best practices

While Default parameters is not overloading, it might solve some of the issues that developers face in this area. The input is strictly decided by the order, you can not re-order as you wish as in classical overloading:

function transformer(
    firstNumber = 1,
    secondNumber = new Date().getFullYear(),
    transform = function multiply(firstNumber, secondNumber) {
        return firstNumber * secondNumber;
    }
) {
    return transform(firstNumber, secondNumber);
}

console.info(transformer());
console.info(transformer(8));
console.info(transformer(2, 6));
console.info(transformer(undefined, 65));

function add(firstNumber, secondNumber) {
    return firstNumber + secondNumber;
}
console.info(transformer(undefined, undefined, add));
console.info(transformer(3, undefined, add));

Results in (for year 2020):

2020
16160
12
65
2021
2023

More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters

How to ignore ansible SSH authenticity checking?

If you don't want to modify ansible.cfg or the playbook.yml then you can just set an environment variable:

export ANSIBLE_HOST_KEY_CHECKING=False

How can I inspect element in chrome when right click is disabled?

CTRL+SHIFT+I brings up the developers tools.

Why Java Calendar set(int year, int month, int date) not returning correct date?

Months in Calendar object start from 0

0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY

Basic authentication for REST API using spring restTemplate

Use setBasicAuth to define credentials

HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("myUsername", myPassword);

Then create the request like you prefer.

Example:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, 
request, String.class);
String body = response.getBody();

How many bytes is unsigned long long?

It must be at least 64 bits. Other than that it's implementation defined.

Strictly speaking, unsigned long long isn't standard in C++ until the C++0x standard. unsigned long long is a 'simple-type-specifier' for the type unsigned long long int (so they're synonyms).

The long long set of types is also in C99 and was a common extension to C++ compilers even before being standardized.

Java: Get last element after split

Or you could use lastIndexOf() method on String

String last = string.substring(string.lastIndexOf('-') + 1);

"id cannot be resolved or is not a field" error?

select Project tab and click Build automatically so Build all option will be activated and then click on build all.and always start xml file name with lowercase.

CSV API for Java

I've used OpenCSV in the past.

import au.com.bytecode.opencsv.CSVReader;

String fileName = "data.csv";
CSVReader reader = new CSVReader(new FileReader(fileName ));

// if the first line is the header String[] header = reader.readNext();
// iterate over reader.readNext until it returns null String[] line = reader.readNext();

There were some other choices in the answers to another question.

Find duplicates and delete all in notepad++

You need the textFX plugin. Then, just follow these instructions:

Paste the text into Notepad++ (CTRL+V). ...
Mark all the text (CTRL+A). ...
Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column)
Duplicates and blank lines have been removed and the data has been sorted alphabetically.

Personally, I would use sort -i -u source >dest instead of notepad++

How to create a library project in Android Studio and an application project that uses the library project

For Intellij IDEA (and Android Studio) each library is a Module. Think of a Module in Android Studio as an equivalent to project in Eclipse. Project in Android Studio is a collection of modules. Modules can be runnable applications or library modules.

So, in order to add a new android library project to you need to create a module of type "Android library". Then add this library module to the dependency list of your main module (Application module).

What are the recommendations for html <base> tag?

Also, you should remember that if you run your web server at non-standard port you need to include port number at base href too:

<base href="//localhost:1234" />  // from base url
<base href="../" />  // for one step above

What is the difference between .py and .pyc files?

.pyc contain the compiled bytecode of Python source files. The Python interpreter loads .pyc files before .py files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.

Clear an input field with Reactjs?

You can use input type="reset"

<form action="/action_page.php">
  text: <input type="text" name="email" /><br />  
  <input type="reset" defaultValue="Reset" />  
</form>

Bitwise and in place of modulus operator

Using bitwise_and, bitwise_or, and bitwise_not you can modify any bit configurations to another bit configurations (i.e. these set of operators are "functionally complete"). However, for operations like modulus, the general formula would be necessarily be quite complicated, I wouldn't even bother trying to recreate it.

java.util.NoSuchElementException: No line found

For whatever reason, the Scanner class also issues this same exception if it encounters special characters it cannot read. Beyond using the hasNextLine() method before each call to nextLine(), make sure the correct encoding is passed to the Scanner constructor, e.g.:

Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

How to use Python's "easy_install" on Windows ... it's not so easy

Copy the below script "ez_setup.py" from the below URL

https://bootstrap.pypa.io/ez_setup.py

And copy it into your Python location

C:\Python27>

Run the command

C:\Python27? python ez_setup.py

This will install the easy_install under Scripts directory

C:\Python27\Scripts

Run easy install from the Scripts directory >

C:\Python27\Scripts> easy_install

Does not contain a definition for and no extension method accepting a first argument of type could be found

There are two cases in which this error is raised.

  1. You didn't declare the variable which is used
  2. You didn't create the instances of the class

How to serialize an object to XML without getting xmlns="..."?

I Suggest this helper class:

public static class Xml
{
    #region Fields

    private static readonly XmlWriterSettings WriterSettings = new XmlWriterSettings {OmitXmlDeclaration = true, Indent = true};
    private static readonly XmlSerializerNamespaces Namespaces = new XmlSerializerNamespaces(new[] {new XmlQualifiedName("", "")});

    #endregion

    #region Methods

    public static string Serialize(object obj)
    {
        if (obj == null)
        {
            return null;
        }

        return DoSerialize(obj);
    }

    private static string DoSerialize(object obj)
    {
        using (var ms = new MemoryStream())
        using (var writer = XmlWriter.Create(ms, WriterSettings))
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(writer, obj, Namespaces);
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }

    public static T Deserialize<T>(string data)
        where T : class
    {
        if (string.IsNullOrEmpty(data))
        {
            return null;
        }

        return DoDeserialize<T>(data);
    }

    private static T DoDeserialize<T>(string data) where T : class
    {
        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))
        {
            var serializer = new XmlSerializer(typeof (T));
            return (T) serializer.Deserialize(ms);
        }
    }

    #endregion
}

:)

jQuery Dialog Box

Looks like there is an issue with the code you posted. Your function to display the T&C is referencing the wrong div id. You should consider assigning the showTOC function to the onclick attribute once the document is loaded as well:

$(document).ready({
    $('a.TOClink').click(function(){
        showTOC();
    });
});

function showTOC() {
    $('#example').dialog({modal:true});
}

A more concise example which accomplishes the desired effect using the jQuery UI dialog is:

   <div id="terms" style="display:none;">
       Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
   </div>
   <a id="showTerms" href="#">Show Terms &amp; Conditions</a>      
   <script type="text/javascript">
       $(document).ready(function(){
           $('#showTerms').click(function(){
               $('#terms').dialog({modal:true});   
           });
       });
   </script>

How to create a toggle button in Bootstrap

Bootstrap 3 has options to create toggle buttons based on checkboxes or radio buttons: http://getbootstrap.com/javascript/#buttons

Checkboxes

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="checkbox" checked> Option 1 (pre-checked)
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> Option 2
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> Option 3
  </label>
</div>

Radio buttons

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" checked> Option 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2"> Option 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3"> Option 3
  </label>
</div>

For these to work you must initialize .btns with Bootstrap's Javascript:

$('.btn').button();

How to output in CLI during execution of PHP Unit tests?

This was taken from PHPUnit Docs about Fixtures.

This should allow you to dump information at any point durring the phpunit test life cycle.

Just replace __METHOD__ in the code below with whatever you want to output

Example 4.2: Example showing all template methods available

<?php
class TemplateMethodsTest extends PHPUnit_Framework_TestCase
{
    public static function setUpBeforeClass()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
    }

    protected function setUp()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
    }

    protected function assertPreConditions()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
    }

    public function testOne()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
        $this->assertTrue(TRUE);
    }

    public function testTwo()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
        $this->assertTrue(FALSE);
    }

    protected function assertPostConditions()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
    }

    protected function tearDown()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
    }

    public static function tearDownAfterClass()
    {
        fwrite(STDOUT, __METHOD__ . "\n");
    }

    protected function onNotSuccessfulTest(Exception $e)
    {
        fwrite(STDOUT, __METHOD__ . "\n");
        throw $e;
    }
}
?>

Pass a javascript variable value into input type hidden value

You could do that like this:

<script type="text/javascript">
     function product(a,b)
     {
     return a*b;
     }
    document.getElementById('myvalue').value = product(a,b);
 </script>

 <input type="hidden" value="THE OUTPUT OF PRODUCT FUNCTION" id="myvalue">

jQuery append() vs appendChild()

appendChild is a pure javascript method where as append is a jQuery method.

How to get ip address of a server on Centos 7 in bash

You can use hostname command :

ipaddr=$(hostname -I)

-i, --ip-address: Display the IP address(es) of the host. Note that this works only if the host name can be resolved.

-I, --all-ip-addresses: Display all network addresses of the host. This option enumerates all configured addresses on all network interfaces. The loopback interface and IPv6 link-local addresses are omitted. Contrary to option -i, this option does not depend on name resolution. Do not make any assumptions about the order of the output.

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

You can use native JS so you don't have to rely on external libraries.

(I will use some ES2015 syntax, a.k.a ES6, modern javascript) What is ES2015?

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    });

You can also capture errors if any:

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    })
    .catch(err => {
        console.error('An error ocurred', err);
    });

By default it uses GET and you don't have to specify headers, but you can do all that if you want. For further reference: Fetch API reference

How can I extract a predetermined range of lines from a text file on Unix?

I was about to post the head/tail trick, but actually I'd probably just fire up emacs. ;-)

  1. esc-x goto-line ret 16224
  2. mark (ctrl-space)
  3. esc-x goto-line ret 16482
  4. esc-w

open the new output file, ctl-y save

Let's me see what's happening.

Adding asterisk to required fields in Bootstrap 3

Assuming this is what the HTML looks like

<div class="form-group required">
   <label class="col-md-2 control-label">E-mail</label>
   <div class="col-md-4"><input class="form-control" id="id_email" name="email" placeholder="E-mail" required="required" title="" type="email" /></div>
</div>

To display an asterisk on the right of the label:

.form-group.required .control-label:after { 
    color: #d00;
    content: "*";
    position: absolute;
    margin-left: 8px;
    top:7px;
}

Or to the left of the label:

.form-group.required .control-label:before{
   color: red;
   content: "*";
   position: absolute;
   margin-left: -15px;
}

To make a nice big red asterisks you can add these lines:

font-family: 'Glyphicons Halflings';
font-weight: normal;
font-size: 14px;

Or if you are using Font Awesome add these lines (and change the content line):

font-family: 'FontAwesome';
font-weight: normal;
font-size: 14px;
content: "\f069";

Reversing a string in C

My two cents:

/* Reverses n characters of a string and adds a '\0' at the end */
void strnrev (char *txt, size_t len) {
    size_t idx;
    for (idx = len >> 1; idx > 0; idx--) {
        txt[len] = txt[idx - 1];
        txt[idx - 1] = txt[len - idx];
        txt[len - idx] = txt[len];
    }
    txt[len] = '\0';
}

/* Reverses a null-terminated string */
void strrev (char *txt) {
    size_t len = 0;
    while (txt[len++]);
    strnrev(txt, --len);
}

Test #1strrev():

char string[] = "Hello world!";
strrev(string);
printf("%s\n", string); // Displays "!dlrow olleH"

Test #2strnrev():

char string[] = "Hello world!";
strnrev(string, 5);
printf("%s\n", string); // Displays "olleH"

How to run .APK file on emulator

You need to install the APK on the emulator. You can do this with the adb command line tool that is included in the Android SDK.

adb -e install -r yourapp.apk

Once you've done that you should be able to run the app.

The -e and -r flags might not be necessary. They just specify that you are using an emulator (if you also have a device connected) and that you want to replace the app if it already exists.

Resize external website content to fit iFrame width

What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.

E.g.

<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>

Loop timer in JavaScript

It should be:

function moveItem() {
  jQuery(".stripTransmitter ul li a").trigger('click');
}
setInterval(moveItem,2000);

setInterval(f, t) calls the the argument function, f, once every t milliseconds.

jQuery check/uncheck radio button onclick

-- EDIT --

It sure looks like your code is forcing a radio input to behave like a checkbox input. You might think about just using a checkbox input without the need for jQuery. However, if you want to force, like @manji said, you need to store the value outside the click handler and then set it on each click to the opposite of what it is at that time. @manji's answer is correct, I would just add that you should cache jQuery objects instead of re-querying the DOM:

var $radio = $("#radioinstant"),
    isChecked = $radio.attr("checked");

$radio.click(function() {

    isChecked = !isChecked;
    $(this).attr("checked", isChecked);

});

Best Way to read rss feed in .net Using C#

Update: This supports only with UWP - Windows Community Toolkit

There is a much easier way now. You can use the RssParser class. The sample code is given below.

public async void ParseRSS()
{
    string feed = null;

    using (var client = new HttpClient())
    {
        try
        {
            feed = await client.GetStringAsync("https://visualstudiomagazine.com/rss-feeds/news.aspx");
        }
        catch { }
    }

    if (feed != null)
    {
        var parser = new RssParser();
        var rss = parser.Parse(feed);

        foreach (var element in rss)
        {
            Console.WriteLine($"Title: {element.Title}");
            Console.WriteLine($"Summary: {element.Summary}");
        }
    }
}

For non-UWP use the Syndication from the namespace System.ServiceModel.Syndication as others suggested.

public static IEnumerable <FeedItem> GetLatestFivePosts() {
    var reader = XmlReader.Create("https://sibeeshpassion.com/feed/");
    var feed = SyndicationFeed.Load(reader);
    reader.Close();
    return (from itm in feed.Items select new FeedItem {
        Title = itm.Title.Text, Link = itm.Id
    }).ToList().Take(5);
}

public class FeedItem {
    public string Title {
        get;
        set;
    }
    public string Link {
        get;
        set;
    }
}

How to test abstract class in Java with JUnit?

You can instantiate an anonymous class and then test that class.

public class ClassUnderTest_Test {

    private ClassUnderTest classUnderTest;

    private MyDependencyService myDependencyService;

    @Before
    public void setUp() throws Exception {
        this.myDependencyService = new MyDependencyService();
        this.classUnderTest = getInstance();
    }

    private ClassUnderTest getInstance() {
        return new ClassUnderTest() {    
            private ClassUnderTest init(
                    MyDependencyService myDependencyService
            ) {
                this.myDependencyService = myDependencyService;
                return this;
            }

            @Override
            protected void myMethodToTest() {
                return super.myMethodToTest();
            }
        }.init(myDependencyService);
    }
}

Keep in mind that the visibility must be protected for the property myDependencyService of the abstract class ClassUnderTest.

You can also combine this approach neatly with Mockito. See here.

How to change the data type of a column without dropping the column with query?

ALTER TABLE YourTableNameHere ALTER COLUMN YourColumnNameHere VARCHAR(20)

iOS - Ensure execution on main thread

This will do it:

[[NSOperationQueue mainQueue] addOperationWithBlock:^ {

   //Your code goes in here
   NSLog(@"Main Thread Code");

}];

Hope this helps!

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

Simplified:

DateTime time = System.DateTime.Now;
ModelName m = context.TableName.Where(x=> DbFunctions.TruncateTime(x.Date) == time.Date)).FirstOrDefault();

C# find highest array value and index

Here is a LINQ solution which is O(n) with decent constant factors:

int[] anArray = { 1, 5, 2, 7, 1 };

int index = 0;
int maxIndex = 0;

var max = anArray.Aggregate(
    (oldMax, element) => {
        ++index;
        if (element <= oldMax)
            return oldMax;
        maxIndex = index;
        return element;
    }
);

Console.WriteLine("max = {0}, maxIndex = {1}", max, maxIndex);

But you should really write an explicit for lop if you care about performance.

Convert from enum ordinal to enum type

To convert an ordinal into its enum represantation you might want to do this:

ReportTypeEnum value = ReportTypeEnum.values()[ordinal];

Please notice the array bounds.

Note that every call to values() returns a newly cloned array which might impact performance in a negative way. You may want to cache the array if it's going to be called often.

Code example on how to cache values().


This answer was edited to include the feedback given inside the comments

How to set app icon for Electron / Atom Shell App

If you want to update the app icon in the taskbar, then Update following in main.js (if using typescript then main.ts)

win.setIcon(path.join(__dirname, '/src/assets/logo-small.png'));

__dirname points to the root directory (same directory as package.json) of your application.

Grouping into interval of 5 minutes within a time range

You're probably going to have to break up your timestamp into ymd:HM and use DIV 5 to split the minutes up into 5-minute bins -- something like

select year(a.timestamp), 
       month(a.timestamp), 
       hour(a.timestamp), 
       minute(a.timestamp) DIV 5,
       name, 
       count(b.name)
FROM time a, id b
WHERE a.user = b.user AND a.id = b.id AND b.name = 'John' 
      AND a.timestamp BETWEEN '2010-11-16 10:30:00' AND '2010-11-16 11:00:00'
GROUP BY year(a.timestamp), 
       month(a.timestamp), 
       hour(a.timestamp), 
       minute(a.timestamp) DIV 12

...and then futz the output in client code to appear the way you like it. Or, you can build up the whole date string using the sql concat operatorinstead of getting separate columns, if you like.

select concat(year(a.timestamp), "-", month(a.timestamp), "-" ,day(a.timestamp), 
       " " , lpad(hour(a.timestamp),2,'0'), ":", 
       lpad((minute(a.timestamp) DIV 5) * 5, 2, '0'))

...and then group on that

T-SQL substring - separating first and last name

The code below works with Last, First M name strings. Substitute "Name" with your name string column name. Since you have a period as a final character when there is a middle initial, you would replace the 2's with 3's in each of the lines (2, 6, and 8)- and change "RIGHT(Name, 1)" to "RIGHT(Name, 2)" in line 8.

SELECT  SUBSTRING(Name, 1, CHARINDEX(',', Name) - 1) LastName ,
CASE WHEN LEFT(RIGHT(Name, 2), 1) <> ' '
     THEN LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99))
     ELSE LEFT(LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99)),
               LEN(LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99)))
               - 2)
END FirstName ,
CASE WHEN LEFT(RIGHT(Name, 2), 1) = ' ' THEN RIGHT(Name, 1)
     ELSE NULL
END MiddleName

SQLite Reset Primary Key Field

If you want to reset every RowId via content provider try this

rowCounter=1;
do {            
            rowId = cursor.getInt(0);
            ContentValues values;
            values = new ContentValues();
            values.put(Table_Health.COLUMN_ID,
                       rowCounter);
            updateData2DB(context, values, rowId);
            rowCounter++;

        while (cursor.moveToNext());

public static void updateData2DB(Context context, ContentValues values, int rowId) {
    Uri uri;
    uri = Uri.parseContentProvider.CONTENT_URI_HEALTH + "/" + rowId);
    context.getContentResolver().update(uri, values, null, null);
}

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

Adding to @Kirill Fuchs excellent solution and answering @StackUser's doubt - while starting the http-server, set the path till the app folder only, NOT till the html page! http-server C:\location\to\app and access index.html under app folder

How to retrieve form values from HTTPPOST, dictionary or?

If you want to get the form data directly from Http request, without any model bindings or FormCollection you can use this:

[HttpPost] 
public ActionResult SubmitAction() {

    // This will return an string array of all keys in the form.
    // NOTE: you specify the keys in form by the name attributes e.g:
    // <input name="this is the key" value="some value" type="test" />
    var keys = Request.Form.AllKeys;

    // This will return the value for the keys.
    var value1 = Request.Form.Get(keys[0]);
    var value2 = Request.Form.Get(keys[1]);
}

@selector() in Swift?

Using #selector will check your code at compile time to make sure the method you want to call actually exists. Even better, if the method doesn’t exist, you’ll get a compile error: Xcode will refuse to build your app, thus banishing to oblivion another possible source of bugs.

override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem =
            UIBarButtonItem(barButtonSystemItem: .Add, target: self,
                            action: #selector(addNewFireflyRefernce))
    }

    func addNewFireflyReference() {
        gratuitousReferences.append("Curse your sudden but inevitable betrayal!")
    }

Can you change a path without reloading the controller in AngularJS?

There is simple way to change path without reloading

URL is - http://localhost:9000/#/edit_draft_inbox/1457

Use this code to change URL, Page will not be redirect

Second parameter "false" is very important.

$location.path('/edit_draft_inbox/'+id, false);

How to "z-index" to make a menu always on top of the content

You most probably don't need z-index to do that. You can use relative and absolute positioning.

I advise you to take a better look at css positioning and the difference between relative and absolute positioning... I saw you're setting position: absolute; to an element and trying to float that element. It won't work friend! When you understand positioning in CSS it will make your work a lot easier! ;)

Edit: Just to be clear, positioning is not a replacement for them and I do use z-index. I just try to avoid using them. Using z-indexes everywhere seems easy and fun at first... until you have bugs related to them and find yourself having to revisit and manage z-indexes.

PHP, getting variable from another php-file

You could also use file_get_contents

 $url_a="http://127.0.0.1/get_value.php?line=a&shift=1&tgl=2017-01-01";
 $data_a=file_get_contents($url_a);

 echo $data_a;

How to make input type= file Should accept only pdf and xls

Unfortunately, there is no guaranteed way to do it at time of selection.

Some browsers support the accept attribute for input tags. This is a good start, but cannot be relied upon completely.

<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />

You can use a cfinput and run a validation to check the file extension at submission, but not the mime-type. This is better, but still not fool-proof. Files on OSX often have no file extensions or users could maliciously mislabel the file types.

ColdFusion's cffile can check the mime-type using the contentType property of the result (cffile.contentType), but that can only be done after the upload. This is your best bet, but is still not 100% safe as mime-types could still be wrong.

How to do a JUnit assert on a message in a logger

if you are using java.util.logging.Logger this article might be very helpful, it creates a new handler and make assertions on the log Output: http://octodecillion.com/blog/jmockit-test-logging/

Vue.js getting an element within a component

you can access the children of a vuejs component with this.$children. if you want to use the query selector on the current component instance then this.$el.querySelector(...)

just doing a simple console.log(this) will show you all the properties of a vue component instance.

additionally if you know the element you want to access in your component, you can add the v-el:uniquename directive to it and access it via this.$els.uniquename

How to install Guest addition in Mac OS as guest and Windows machine as host

Have you tried https://www.virtualbox.org/manual/ch04.html which has step-by-step instructions to help you?

  1. Make your VM bi-directional for Clipboard and Drag & Drop
  2. Share folders from your host to the guest VM too.

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Entity framework left join

It might be a bit of an overkill, but I wrote an extension method, so you can do a LeftJoin using the Join syntax (at least in method call notation):

persons.LeftJoin(
    phoneNumbers,
    person => person.Id,
    phoneNumber => phoneNumber.PersonId,
    (person, phoneNumber) => new
        {
            Person = person,
            PhoneNumber = phoneNumber?.Number
        }
);

My code does nothing more than adding a GroupJoin and a SelectMany call to the current expression tree. Nevertheless, it looks pretty complicated because I have to build the expressions myself and modify the expression tree specified by the user in the resultSelector parameter to keep the whole tree translatable by LINQ-to-Entities.

public static class LeftJoinExtension
{
    public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
        this IQueryable<TOuter> outer,
        IQueryable<TInner> inner,
        Expression<Func<TOuter, TKey>> outerKeySelector,
        Expression<Func<TInner, TKey>> innerKeySelector,
        Expression<Func<TOuter, TInner, TResult>> resultSelector)
    {
        MethodInfo groupJoin = typeof (Queryable).GetMethods()
                                                 .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] GroupJoin[TOuter,TInner,TKey,TResult](System.Linq.IQueryable`1[TOuter], System.Collections.Generic.IEnumerable`1[TInner], System.Linq.Expressions.Expression`1[System.Func`2[TOuter,TKey]], System.Linq.Expressions.Expression`1[System.Func`2[TInner,TKey]], System.Linq.Expressions.Expression`1[System.Func`3[TOuter,System.Collections.Generic.IEnumerable`1[TInner],TResult]])")
                                                 .MakeGenericMethod(typeof (TOuter), typeof (TInner), typeof (TKey), typeof (LeftJoinIntermediate<TOuter, TInner>));
        MethodInfo selectMany = typeof (Queryable).GetMethods()
                                                  .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] SelectMany[TSource,TCollection,TResult](System.Linq.IQueryable`1[TSource], System.Linq.Expressions.Expression`1[System.Func`2[TSource,System.Collections.Generic.IEnumerable`1[TCollection]]], System.Linq.Expressions.Expression`1[System.Func`3[TSource,TCollection,TResult]])")
                                                  .MakeGenericMethod(typeof (LeftJoinIntermediate<TOuter, TInner>), typeof (TInner), typeof (TResult));

        var groupJoinResultSelector = (Expression<Func<TOuter, IEnumerable<TInner>, LeftJoinIntermediate<TOuter, TInner>>>)
                                      ((oneOuter, manyInners) => new LeftJoinIntermediate<TOuter, TInner> {OneOuter = oneOuter, ManyInners = manyInners});

        MethodCallExpression exprGroupJoin = Expression.Call(groupJoin, outer.Expression, inner.Expression, outerKeySelector, innerKeySelector, groupJoinResultSelector);

        var selectManyCollectionSelector = (Expression<Func<LeftJoinIntermediate<TOuter, TInner>, IEnumerable<TInner>>>)
                                           (t => t.ManyInners.DefaultIfEmpty());

        ParameterExpression paramUser = resultSelector.Parameters.First();

        ParameterExpression paramNew = Expression.Parameter(typeof (LeftJoinIntermediate<TOuter, TInner>), "t");
        MemberExpression propExpr = Expression.Property(paramNew, "OneOuter");

        LambdaExpression selectManyResultSelector = Expression.Lambda(new Replacer(paramUser, propExpr).Visit(resultSelector.Body), paramNew, resultSelector.Parameters.Skip(1).First());

        MethodCallExpression exprSelectMany = Expression.Call(selectMany, exprGroupJoin, selectManyCollectionSelector, selectManyResultSelector);

        return outer.Provider.CreateQuery<TResult>(exprSelectMany);
    }

    private class LeftJoinIntermediate<TOuter, TInner>
    {
        public TOuter OneOuter { get; set; }
        public IEnumerable<TInner> ManyInners { get; set; }
    }

    private class Replacer : ExpressionVisitor
    {
        private readonly ParameterExpression _oldParam;
        private readonly Expression _replacement;

        public Replacer(ParameterExpression oldParam, Expression replacement)
        {
            _oldParam = oldParam;
            _replacement = replacement;
        }

        public override Expression Visit(Expression exp)
        {
            if (exp == _oldParam)
            {
                return _replacement;
            }

            return base.Visit(exp);
        }
    }
}

Method List in Visual Studio Code

There is a plugin called show functions which lists all the function definitions in a file. It also allows you to sort the function so can search them easily.

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

It seems necessary to state ones degree here: B.A. in Political Science and B.ed in Computer Science.

To the point:

Is this going to put people off coming to Scala?

Scala is difficult, because its underlying programming paradigm is difficult. Functional programming scares a lot of people. It is possible to build closures in PHP but people rarely do. So no, not this signature but all the rest will put people off, if they do not have the specific education to make them value the power of the underlying paradigm.

If this education is available, everyone can do it. Last year I build a chess computer with a bunch of school kids in SCALA! They had their problems but they did fine in the end.

If you're using Scala commercially, are you worried about this? Are you planning to adopt 2.8 immediately or wait to see what happens?

I would not be worried.

Ideal way to cancel an executing AsyncTask

Our global AsyncTask class variable

LongOperation LongOperationOdeme = new LongOperation();

And KEYCODE_BACK action which interrupt AsyncTask

   @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LongOperationOdeme.cancel(true);
        }
        return super.onKeyDown(keyCode, event);
    }

It works for me.

PHP regular expression - filter number only

This is the right answer

preg_match("/^[0-9]+$/", $yourstr);

This function return TRUE(1) if it matches or FALSE(0) if it doesn't

Quick Explanation :

'^' : means that it should begin with the following ( in our case is a range of digital numbers [0-9] ) ( to avoid cases like ("abdjdf125") )

'+' : means there should be at least one digit

'$' : means after our pattern the string should end ( to avoid cases like ("125abdjdf") )

Is it possible to ping a server from Javascript?

Ping is ICMP, but if there is any open TCP port on the remote server it could be achieved like this:

function ping(host, port, pong) {

  var started = new Date().getTime();

  var http = new XMLHttpRequest();

  http.open("GET", "http://" + host + ":" + port, /*async*/true);
  http.onreadystatechange = function() {
    if (http.readyState == 4) {
      var ended = new Date().getTime();

      var milliseconds = ended - started;

      if (pong != null) {
        pong(milliseconds);
      }
    }
  };
  try {
    http.send(null);
  } catch(exception) {
    // this is expected
  }

}

Activating Anaconda Environment in VsCode

I found out that if we do not specify which python version we want the environment which is created is completely empty. Thus, to resolve this issue what I did is that I gave the python version as well. i.e

conda create --name env_name python=3.6

so what it does now is that it installs python 3.6 and now we can select the interpreter. For that follow the below-mentioned steps:

  1. Firstly, open the command palette using Ctrl + Shift + P

  2. Secondly, Select Python: select Interpreter

  3. Now, Select Enter interpreter path

  4. We have to add the path where the env is, the default location will be C:\Users\YourUserName\Anaconda3\envs\env_name

Finally, you have successfully activated your environment. It might now be the best way but it worked for me. Let me know if there is any issue.

PHP check whether property exists in object or class

To check if something exits, you can use the PHP function isset() see php.net. This function will check if the variable is set and is not NULL.

Example:

if(isset($obj->a))
{ 
  //do something
}

If you need to check if a property exists in a class, then you can use the build in function property_exists()

Example:

if (property_exists('class', $property)) {
    //do something
}

EPPlus - Read Excel Table

Not sure why but none of the above solution work for me. So sharing what worked:

public void readXLS(string FilePath)
{
    FileInfo existingFile = new FileInfo(FilePath);
    using (ExcelPackage package = new ExcelPackage(existingFile))
    {
        //get the first worksheet in the workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int colCount = worksheet.Dimension.End.Column;  //get Column Count
        int rowCount = worksheet.Dimension.End.Row;     //get row count
        for (int row = 1; row <= rowCount; row++)
        {
            for (int col = 1; col <= colCount; col++)
            {
                Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value?.ToString().Trim());
            }
        }
    }
}

How can I debug javascript on Android?

FYI, the reason why RaphaelJS doesn't work on android is that android webkit (unlike iPhone webkit) doesn't support SVG at this time. Google has only recently come to the conclusion that SVG support an android is a good idea, so it won't be available yet for some time.

ASP.NET Core configuration for .NET Core console application

If you use .netcore 3.1 the simplest way use new configuration system to call CreateDefaultBuilder method of static class Host and configure application

public class Program
{
    public static void Main(string[] args)
    {
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, config) =>
            {
                IHostEnvironment env = context.HostingEnvironment;
                config.AddEnvironmentVariables()
                    // copy configuration files to output directory
                    .AddJsonFile("appsettings.json")
                    // default prefix for environment variables is DOTNET_
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                    .AddCommandLine(args);
            })
            .ConfigureServices(services =>
            {
                services.AddSingleton<IHostedService, MySimpleService>();
            })
            .Build()
            .Run();
    }
}

class MySimpleService : IHostedService
{
    public Task StartAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine("StartAsync");
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine("StopAsync");
        return Task.CompletedTask;
    }
}

You need set Copy to Output Directory = 'Copy if newer' for the files appsettings.json and appsettings.{environment}.json Also you can set environment variable {prefix}ENVIRONMENT (default prefix is DOTNET) to allow choose specific configuration parameters.

.csproj file:

<PropertyGroup>
  <OutputType>Exe</OutputType>
  <TargetFramework>netcoreapp3.1</TargetFramework>
  <RootNamespace>ConsoleApplication3</RootNamespace>
  <AssemblyName>ConsoleApplication3</AssemblyName>
</PropertyGroup>

<ItemGroup>
  <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.7" />
  <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.7" />
</ItemGroup>

<ItemGroup>
  <None Update="appsettings.Development.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
  <None Update="appsettings.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>

more details .NET Generic Host

Android ImageView Zoom-in and Zoom-Out

Method to call the About&support dialog

 public void setupAboutSupport() {

    try {

        // The About&Support AlertDialog is active
        activeAboutSupport=true;

        View messageView;
        int orientation=this.getResources().getConfiguration().orientation;

        // Inflate the about message contents
        messageView = getLayoutInflater().inflate(R.layout.about_support, null, false);

        ContextThemeWrapper ctw = new ContextThemeWrapper(this, R.style.MyCustomTheme_AlertDialog1);
        AlertDialog.Builder builder = new AlertDialog.Builder(ctw);
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setTitle(R.string.action_aboutSupport);
        builder.setView(messageView);

        TouchImageView imgDisplay = (TouchImageView) messageView.findViewById(R.id.action_infolinks_about_support);
        imgDisplay.setMaxZoom(3f);

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.myinfolinks_about_support);

        int imageWidth = bitmap.getWidth();
        int imageHeight = bitmap.getHeight();
        int newWidth;

        // Calculate the new About_Support image width
        if(orientation==Configuration.ORIENTATION_PORTRAIT ) {
            // For 7" up to 10" tablets
            //if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
            if (SingletonMyInfoLinks.isTablet) {
                    // newWidth = widthScreen - (two borders of about_support layout and 20% of width Screen)
                newWidth = widthScreen - ((2 * toPixels(8)) + (int)(widthScreen*0.2));
            } else newWidth = widthScreen - ((2 * toPixels(8)) + (int)(widthScreen*0.1));

        } else {
            // For 7" up to 10" tablets
            //if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
            if (SingletonMyInfoLinks.isTablet) {
                newWidth = widthScreen - ((2 * toPixels(8)) + (int)(widthScreen*0.5));

            } else newWidth = widthScreen - ((2 * toPixels(8)) + (int)(widthScreen*0.3));
        }

        // Get the scale factor
        float scaleFactor = (float)newWidth/(float)imageWidth;
        // Calculate the new About_Support image height
        int newHeight = (int)(imageHeight * scaleFactor);
        // Set the new bitmap corresponding the adjusted About_Support image
        bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);

        // Rescale the image
        imgDisplay.setImageBitmap(bitmap);

        dialogAboutSupport = builder.show();

        TextView textViewVersion = (TextView) dialogAboutSupport.findViewById(R.id.action_strVersion);
        textViewVersion.setText(Html.fromHtml(getString(R.string.aboutSupport_text1)+" <b>"+versionName+"</b>"));

        TextView textViewDeveloperName = (TextView) dialogAboutSupport.findViewById(R.id.action_strDeveloperName);
        textViewDeveloperName.setText(Html.fromHtml(getString(R.string.aboutSupport_text2)+" <b>"+SingletonMyInfoLinks.developerName+"</b>"));

        TextView textViewSupportEmail = (TextView) dialogAboutSupport.findViewById(R.id.action_strSupportEmail);
        textViewSupportEmail.setText(Html.fromHtml(getString(R.string.aboutSupport_text3)+" "+SingletonMyInfoLinks.developerEmail));

        TextView textViewCompanyName = (TextView) dialogAboutSupport.findViewById(R.id.action_strCompanyName);
        textViewCompanyName.setText(Html.fromHtml(getString(R.string.aboutSupport_text4)+" "+SingletonMyInfoLinks.companyName));

        Button btnOk = (Button) dialogAboutSupport.findViewById(R.id.btnOK);

        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogAboutSupport.dismiss();
            }
        });

        dialogAboutSupport.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(final DialogInterface dialog) {
                // the About & Support AlertDialog is closed
                activeAboutSupport=false;
            }
        });

        dialogAboutSupport.getWindow().setBackgroundDrawable(new ColorDrawable(SingletonMyInfoLinks.atualBackgroundColor));

        /* Effect that image appear slower */
        // Only the fade_in matters
        AlphaAnimation fade_out = new AlphaAnimation(1.0f, 0.0f);
        AlphaAnimation fade_in = new AlphaAnimation(0.0f, 1.0f);
        AlphaAnimation a = false ? fade_out : fade_in;

        a.setDuration(2000); // 2 sec
        a.setFillAfter(true); // Maintain the visibility at the end of animation
        // Animation start
        ImageView img = (ImageView) messageView.findViewById(R.id.action_infolinks_about_support);
        img.startAnimation(a);

    } catch (Exception e) {
        //Log.e(SingletonMyInfoLinks.appNameText +"-" +  getLocalClassName() + ": ", e.getMessage());
    }
}

setTimeout in React Native

There looks to be an issue when the time of the phone/emulator is different to the one of the server (where react-native packager is running). In my case there was a 1 minute difference between the time of the phone and the computer. After synchronizing them (didn't do anything fancy, the phone was set on manual time, and I just set it to use the network(sim) provided time), everything worked fine. This github issue helped me find the problem.

Locate the nginx.conf file my nginx is actually using

% ps -o args -C nginx
COMMAND
build/sbin/nginx -c ../test.conf

If nginx was run without the -c option, then you can use the -V option to find out the configure arguments that were set to non-standard values. Among them the most interesting for you are:

--prefix=PATH                      set installation prefix
--sbin-path=PATH                   set nginx binary pathname
--conf-path=PATH                   set nginx.conf pathname

Apply a theme to an activity in Android?

You can apply a theme to any activity by including android:theme inside <activity> inside manifest file.

For example:

  1. <activity android:theme="@android:style/Theme.Dialog">
  2. <activity android:theme="@style/CustomTheme">

And if you want to set theme programatically then use setTheme() before calling setContentView() and super.onCreate() method inside onCreate() method.

Difference between System.DateTime.Now and System.DateTime.Today

I thought of Adding these links -

Coming back to original question , Using Reflector i have explained the difference in code

 public static DateTime Today
    {
      get
      {
        return DateTime.Now.Date;   // It returns the date part of Now

        //Date Property
       // returns same date as this instance, and the time value set to 12:00:00 midnight (00:00:00) 
      }
    }


    private const long TicksPerMillisecond = 10000L;
    private const long TicksPerDay = 864000000000L;
    private const int MillisPerDay = 86400000;

    public DateTime Date
    {
       get
      {
        long internalTicks = this.InternalTicks; // Date this instance is converted to Ticks 
        return new DateTime((ulong) (internalTicks - internalTicks % 864000000000L) | this.InternalKind);  
// Modulo of TicksPerDay is subtracted - which brings the time to Midnight time 
      }
    }


     public static DateTime Now
        {
          get
          {
           /* this is why I guess Jon Skeet is recommending to use  UtcNow as you can see in one of the above comment*/
            DateTime utcNow = DateTime.UtcNow;


            /* After this i guess it is Timezone conversion */
            bool isAmbiguousLocalDst = false;
            long ticks1 = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utcNow, out isAmbiguousLocalDst).Ticks;
            long ticks2 = utcNow.Ticks + ticks1;
            if (ticks2 > 3155378975999999999L)
              return new DateTime(3155378975999999999L, DateTimeKind.Local);
            if (ticks2 < 0L)
              return new DateTime(0L, DateTimeKind.Local);
            else
              return new DateTime(ticks2, DateTimeKind.Local, isAmbiguousLocalDst);
          }
        }

Aborting a stash pop in Git

I could reproduce clean git stash pop on "dirty" directory, with uncommitted changes, but not yet pop that generates a merge conflict.

If on merge conflict the stash you tried to apply didn't disappear, you can try to examine git show stash@{0} (optionally with --ours or --theirs) and compare with git statis and git diff HEAD. You should be able to see which changes came from applying a stash.

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

sometimes when data grow bigger mysql WHERE IN's could be pretty slow because of query optimization. Try using STRAIGHT_JOIN to tell mysql to execute query as is, e.g.

SELECT STRAIGHT_JOIN table.field FROM table WHERE table.id IN (...)

but beware: in most cases mysql optimizer works pretty well, so I would recommend to use it only when you have this kind of problem

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

Module 'tensorflow' has no attribute 'contrib'

If you want to use tf.contrib, you need to now copy and paste the source code from github into your script/notebook. It's annoying and doesn't always work. But that's the only workaround I've found. For example, if you wanted to use tf.contrib.opt.AdamWOptimizer, you have to copy and paste from here. https://github.com/tensorflow/tensorflow/blob/590d6eef7e91a6a7392c8ffffb7b58f2e0c8bc6b/tensorflow/contrib/opt/python/training/weight_decay_optimizers.py#L32

Newline in JLabel

You can try and do this:

myLabel.setText("<html>" + myString.replaceAll("<","&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<br/>") + "</html>")

The advantages of doing this are:

  • It replaces all newlines with <br/>, without fail.
  • It automatically replaces eventual < and > with &lt; and &gt; respectively, preventing some render havoc.

What it does is:

  • "<html>" + adds an opening html tag at the beginning
  • .replaceAll("<", "&lt;").replaceAll(">", "&gt;") escapes < and > for convenience
  • .replaceAll("\n", "<br/>") replaces all newlines by br (HTML line break) tags for what you wanted
  • ... and + "</html>" closes our html tag at the end.

P.S.: I'm very sorry to wake up such an old post, but whatever, you have a reliable snippet for your Java!

Using CRON jobs to visit url?

You don't need the redirection, use only

* * * * * wget -qO /dev/null http://yoursite.com/tasks.php

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

I'm not sure if this would work, but you could try creating a UINavigationController with the default settings to create the button, find the button in the navigation controller's subview hierarchy, call removeFromSuperview on it, destroy the navigation controller, and then add the button as a subview of your toolbar. You may also need to retain and the button before calling removeFromSuperview (and then release it after adding it as subview of your toolbar) to avoid it being deallocated during the process.

How can I clear previous output in Terminal in Mac OS X?

On Mac OS X Terminal, this functionality is already built in to the Terminal Application as menu View ? Clear Scrollback (the default is CMD + K).

So you can re-assign this as you like with Apple's Keyboard shortcuts. Just add a new shortcut for Terminal with the command "Clear Scrollback". (I use CMD + L, because it's similar to Ctrl + L to clear the current screen contents, without clearing the buffer.)

I am not sure how you would use this in a script (maybe AppleScript as others have pointed out).

How to get current time with jQuery

You need to fetch all "numbers" manually

like this:

_x000D_
_x000D_
var currentdate = new Date(); _x000D_
    var datetime = "Now: " + currentdate.getDate() + "/"_x000D_
                + (currentdate.getMonth()+1)  + "/" _x000D_
                + currentdate.getFullYear() + " @ "  _x000D_
                + currentdate.getHours() + ":"  _x000D_
                + currentdate.getMinutes() + ":" _x000D_
                + currentdate.getSeconds();_x000D_
_x000D_
document.write(datetime);
_x000D_
_x000D_
_x000D_

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

Actually, you can achieve this pretty easy. Simply specify the line height as a number:

<p style="line-height:1.5">
    <span style="font-size:12pt">The quick brown fox jumps over the lazy dog.</span><br />
    <span style="font-size:24pt">The quick brown fox jumps over the lazy dog.</span>
</p>

The difference between number and percentage in the context of the line-height CSS property is that the number value is inherited by the descendant elements, but the percentage value is first computed for the current element using its font size and then this computed value is inherited by the descendant elements.

For more information about the line-height property, which indeed is far more complex than it looks like at first glance, I recommend you take a look at this online presentation.

Maven dependency update on commandline

mvn clean install -U

-U means force update of dependencies.

Also, if you want to import the project into eclipse, I first run:

mvn eclipse:eclipse

then run

mvn eclipse:clean

Seems to work for me, but that's just my pennies worth.

Create a directory if it does not exist and then create the files in that directory as well

Using java.nio.Path it would be quite simple -

public static Path createFileWithDir(String directory, String filename) {
        File dir = new File(directory);
        if (!dir.exists()) dir.mkdirs();
        return Paths.get(directory + File.separatorChar + filename);
    }

Why are static variables considered evil?

No. Global states are not evil per se. But we have to see your code to see if you used it properly. It is quite possible that a newbie abuses global states; just like he would abuses every language feature.

Global states are absolute necessity. We cannot avoid global states. We cannot avoid reasoning about global states. - If we care to understand our application semantics.

People who try to get rid of global states for the sake of it, inevitably end up with a much more complex system - and the global states are still there, cleverly/idiotically disguised under many layers of indirections; and we still have to reason about global states, after unwrapping all the indirections.

Like the Spring people who lavishly declare global states in xml and think somehow it's superior.

@Jon Skeet if I create a new instance of an object now you have two things to reason about - the state within the object, and the state of the environment hosting the object.

Angular HTML binding

If you have templates in your angular (or whatever framework) application, and you return HTML templates from your backend through a HTTP request/response, you are mixing up templates between the frontend and the backend.

Why not just leave the templating stuff either in the frontend (i would suggest that), or in the backend (pretty intransparent imo)?

And if you keep templates in the frontend, why not just respond with JSON for requests to the backend. You do not even have to implement a RESTful structure, but keeping templates on one side makes your code more transparent.

This will pay back when someone else has to cope with your code (or even you yourself are re-entering your own code after a while)!

If you do it right, you will have small components with small templates, and best of all, if your code is imba, someone who doesn't know coding languages will be able to understand your templates and your logic! So additionally, keep your functions/methods as small you can. You will eventually find out that maintaining, refactoring, reviewing, and adding features will be much easier compared to large functions/methods/classes and mixing up templating and logic between the frontend and the backend - and keep as much of the logic in the backend if your frontend needs to be more flexible (e.g. writing an android frontend or switching to a different frontend framework).

Philosophy, man :)

p.s.: you do not have to implement 100% clean code, because it is very expensive - especially if you have to motivate team members ;) but: you should find a good balance between an approach to cleaner code and what you have (maybe it is already pretty clean)

check the book if you can and let it enter your soul: https://de.wikipedia.org/wiki/Clean_Code

How to make div fixed after you scroll to that div?

I know this is tagged html/css only, but you can't do that with css only. Easiest way will be using some jQuery.

var fixmeTop = $('.fixme').offset().top;       // get initial position of the element

$(window).scroll(function() {                  // assign scroll event listener

    var currentScroll = $(window).scrollTop(); // get current position

    if (currentScroll >= fixmeTop) {           // apply position: fixed if you
        $('.fixme').css({                      // scroll to that element or below it
            position: 'fixed',
            top: '0',
            left: '0'
        });
    } else {                                   // apply position: static
        $('.fixme').css({                      // if you scroll above it
            position: 'static'
        });
    }

});

http://jsfiddle.net/5n5MA/2/

how to end ng serve or firebase serve

With Windows 10 / Powershell ctrl + c did not work; Powershell tried to gracefully stop the app.

Used normal cmd and had no issues stopping the ng serve with ctrl + c.

Converting a double to an int in Javascript without rounding

A trick to truncate that avoids a function call entirely is

var number = 2.9
var truncated = number - number % 1;
console.log(truncated); // 2 

To round a floating-point number to the nearest integer, use the addition/subtraction trick. This works for numbers with absolute value < 2 ^ 51.

var number = 2.9
var rounded = number + 6755399441055744.0 - 6755399441055744.0;  // (2^52 + 2^51)
console.log(rounded); // 3 

Note:

Halfway values are rounded to the nearest even using "round half to even" as the tie-breaking rule. Thus, for example, +23.5 becomes +24, as does +24.5. This variant of the round-to-nearest mode is also called bankers' rounding.

The magic number 6755399441055744.0 is explained in the stackoverflow post "A fast method to round a double to a 32-bit int explained".

_x000D_
_x000D_
// Round to whole integers using arithmetic operators
let trunc = (v) => v - v % 1;
let ceil  = (v) => trunc(v % 1 > 0 ? v + 1 : v);
let floor = (v) => trunc(v % 1 < 0 ? v - 1 : v);
let round = (v) => trunc(v < 0 ? v - 0.5 : v + 0.5);

let roundHalfEven = (v) => v + 6755399441055744.0 - 6755399441055744.0; // (2^52 + 2^51)

console.log("number  floor   ceil  round  trunc");
var array = [1.5, 1.4, 1.0, -1.0, -1.4, -1.5];
array.forEach(x => {
    let f = x => (x).toString().padStart(6," ");
    console.log(`${f(x)} ${f(floor(x))} ${f(ceil(x))} ${f(round(x))} ${f(trunc(x))}`);  
});
_x000D_
_x000D_
_x000D_

How do I include a path to libraries in g++

In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")

Remove warning messages in PHP

If you want to suppress the warnings and some other error types (for example, notices) while displaying all other errors, you can do:

error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);

Adding files to java classpath at runtime

You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first.

Here is a rather ugly hack that adds to the SystemClassLoader at runtime:

import java.io.IOException;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;

public class ClassPathHacker {

  private static final Class[] parameters = new Class[]{URL.class};

  public static void addFile(String s) throws IOException {
    File f = new File(s);
    addFile(f);
  }//end method

  public static void addFile(File f) throws IOException {
    addURL(f.toURL());
  }//end method


  public static void addURL(URL u) throws IOException {

    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class sysclass = URLClassLoader.class;

    try {
      Method method = sysclass.getDeclaredMethod("addURL", parameters);
      method.setAccessible(true);
      method.invoke(sysloader, new Object[]{u});
    } catch (Throwable t) {
      t.printStackTrace();
      throw new IOException("Error, could not add URL to system classloader");
    }//end try catch

   }//end method

}//end class

The reflection is necessary to access the protected method addURL. This could fail if there is a SecurityManager.

Sort objects in an array alphabetically on one property of the array

DEMO

var DepartmentFactory = function(data) {
    this.id = data.Id;
    this.name = data.DepartmentName;
    this.active = data.Active;
}

var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));

console.log(objArray.sort(function(a, b) { return a.name > b.name}));

what does -zxvf mean in tar -zxvf <filename>?

Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference under the info tar command.

x means --extract. v means --verbose. f means --file. z means --gzip. You can combine one-letter arguments together, and f takes an argument, the filename. There is something you have to watch out for:

Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).


This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:

 tar cfz archive.tar.gz file
 tar -cfz archive.tar.gz file

are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.

How to find most common elements of a list?

Is't it just this ....

word_list=['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 
 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 
 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 
 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 
 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 
 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 
 'Moon', 'to', 'rise.', ''] 

from collections import Counter
c = Counter(word_list)
c.most_common(3)

Which should output

[('Jellicle', 6), ('Cats', 5), ('are', 3)]

How Should I Set Default Python Version In Windows?

This work for me.

If you want to use the python 3.6 you must move the python3.6 on the top of the list.

The same applies to the python2.7 If you want to have the 2.7 as default then make sure you move the python2.7 on the very top on the list.

step 1

enter image description here

step 2

enter image description here

step 3

enter image description here

then close any cmd command prompt and opened again, it should work as expected.

python --version

>>> Python 3.6

How to remove item from array by value?

In a global function we can't pass a custom value directly but there are many way as below

 var ary = ['three', 'seven', 'eleven'];
 var index = ary.indexOf(item);//item: the value which you want to remove

 //Method 1
 ary.splice(index,1);

 //Method 2
 delete ary[index]; //in this method the deleted element will be undefined

Setting log level of message at runtime in slf4j

no, it has a number of methods, info(), debug(), warn(), etc (this replaces the priority field)

have a look at http://www.slf4j.org/api/org/slf4j/Logger.html for the full Logger api.

How do I determine k when using k-means clustering?

You can maximize the Bayesian Information Criterion (BIC):

BIC(C | X) = L(X | C) - (p / 2) * log n

where L(X | C) is the log-likelihood of the dataset X according to model C, p is the number of parameters in the model C, and n is the number of points in the dataset. See "X-means: extending K-means with efficient estimation of the number of clusters" by Dan Pelleg and Andrew Moore in ICML 2000.

Another approach is to start with a large value for k and keep removing centroids (reducing k) until it no longer reduces the description length. See "MDL principle for robust vector quantisation" by Horst Bischof, Ales Leonardis, and Alexander Selb in Pattern Analysis and Applications vol. 2, p. 59-72, 1999.

Finally, you can start with one cluster, then keep splitting clusters until the points assigned to each cluster have a Gaussian distribution. In "Learning the k in k-means" (NIPS 2003), Greg Hamerly and Charles Elkan show some evidence that this works better than BIC, and that BIC does not penalize the model's complexity strongly enough.

The apk must be signed with the same certificates as the previous version

I just had this occur out of the clear blue. I really do not think I changed anything.

However, Build => Clean Project fixed it.

Format numbers in django templates

Based on muhuk answer I did this simple tag encapsulating python string.format method.

  • Create a templatetags at your's application folder.
  • Create a format.py file on it.
  • Add this to it:

    from django import template
    
    register = template.Library()
    
    @register.filter(name='format')
    def format(value, fmt):
        return fmt.format(value)
    
  • Load it in your template {% load format %}
  • Use it. {{ some_value|format:"{:0.2f}" }}

css to make bootstrap navbar transparent

There is no need for all this mess.

You can make the navbar transparent by not writing navbar-defaultor navbar-inverse

<nav class="navbar">  //Don't add navbar-default to the class

  //

</nav>

Lock, mutex, semaphore... what's the difference?

A lock allows only one thread to enter the part that's locked and the lock is not shared with any other processes.

A mutex is the same as a lock but it can be system wide (shared by multiple processes).

A semaphore does the same as a mutex but allows x number of threads to enter, this can be used for example to limit the number of cpu, io or ram intensive tasks running at the same time.

For a more detailed post about the differences between mutex and semaphore read here.

You also have read/write locks that allows either unlimited number of readers or 1 writer at any given time.

How to change the background color of Action Bar's Option Menu in Android 4.2?

Within your app theme you can set the android:itemBackground property to change the color of the action menu.

For example:

_x000D_
_x000D_
<style name="AppThemeDark" parent="Theme.AppCompat.Light.DarkActionBar">_x000D_
        <item name="colorPrimary">@color/drk_colorPrimary</item>_x000D_
        <item name="colorPrimaryDark">@color/drk_colorPrimaryDark</item>_x000D_
        <item name="colorAccent">@color/drk_colorAccent</item>_x000D_
        <item name="actionBarStyle">@style/NoTitle</item>_x000D_
        <item name="windowNoTitle">true</item>_x000D_
        <item name="android:textColor">@color/white</item>_x000D_
_x000D_
        <!-- THIS IS WHERE YOU CHANGE THE COLOR -->_x000D_
        <item name="android:itemBackground">@color/drk_colorPrimary</item>_x000D_
</style>
_x000D_
_x000D_
_x000D_

Multiline TextView in Android?

TextView is used to display text on Android application. By default, TextView displays text on one line and if long, TextView will automatically display with more lines to display its text in the most logical way.

Android developers can create a new line on TextView both in programming and syntax. Android developers can create multi-line TextView without dividing text into multiple lines according to android: minLines properties. Create layout.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical">

    <TextView

        android:id="@+id/text_view1"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:textSize="30sp"

        android:background="#DA70D6"

        android:text="This is line 1 \nThis is line 2 \nLine number 3"

        />



    <TextView

        android:id="@+id/text_view2"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:textSize="30sp"

        android:background="#DEB887"

        android:text="This is line 1 \nThis is line 2 \nLine number 3"

        android:maxLines="2"

        />



    <TextView

        android:id="@+id/text_view3"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:textSize="30sp"

        android:background="#8FBC8F"

        android:text="This is line 1 \nThis is line 2"

        android:minLines="3"

        />



    <TextView

        android:id="@+id/text_view4"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:textSize="30sp"

        android:background="#5F9EA0"

        android:text="@string/Multiline_Text_By_N"

        />

</LinearLayout>

Add string in file string.xml

<string name="Multiline_Text_By_N">

        Line number 1 \nLine number 2

    </string>

Source: https://code-android-example.blogspot.com/2020/11/android-textview-multiline-example.html

Call to undefined function mysql_connect

After looking at your phpinfo() output, it appears the mysql extensions are not being loaded. I suspect you might be editing the wrong php.ini file (there might be multiple copies). Make sure you are editing the php file at C:\php\php.ini (also check to make sure there is no second copy in C:\Windows).

Also, you should check your Apache logs for errors (should be in the \logs\ directory in your Apache install.

If you haven't read the below, I would take a look at the comments section, because it seems like a lot of people experience quirks with setting this up. A few commenters offer solutions they used to get it working.

http://php.net/manual/en/install.windows.extensions.php

Another common solution seems to be to copy libmysql.dll and php_mysql.dll from c:\PHP to C:\Windows\System32.

How can I create a link to a local file on a locally-run web page?

If you are running IIS on your PC you can add the directory that you are trying to reach as a Virtual Directory. To do this you right-click on your Site in ISS and press "Add Virtual Directory". Name the virtual folder. Point the virtual folder to your folder location on your local PC. You also have to supply credentials that has privileges to access the specific folder eg. HOSTNAME\username and password. After that you can access the file in the virtual folder as any other file on your site.

http://sitename.com/virtual_folder_name/filename.fileextension

By the way, this also works with Chrome that otherwise does not accept the file-protocol file://

Hope this helps someone :)

What's the easiest way to escape HTML in Python?

No libraries, pure python, safely escapes text into html text:

text.replace('&', '&amp;').replace('>', '&gt;').replace('<', '&lt;'
        ).replace('\'','&#39;').replace('"','&#34;').encode('ascii', 'xmlcharrefreplace')

How to implement a ConfigurationSection with a ConfigurationElementCollection

An easier alternative for those who would prefer not to write all that configuration boilerplate manually...

1) Install Nerdle.AutoConfig from NuGet

2) Define your ServiceConfig type (either a concrete class or just an interface, either will do)

public interface IServiceConfiguration
{
    int Port { get; }
    ReportType ReportType { get; }
}

3) You'll need a type to hold the collection, e.g.

public interface IServiceCollectionConfiguration
{
    IEnumerable<IServiceConfiguration> Services { get; } 
}

4) Add the config section like so (note camelCase naming)

<configSections>
  <section name="serviceCollection" type="Nerdle.AutoConfig.Section, Nerdle.AutoConfig"/>
</configSections>

<serviceCollection>
  <services>
    <service port="6996" reportType="File" />
    <service port="7001" reportType="Other" />
  </services>
</serviceCollection>

5) Map with AutoConfig

var services = AutoConfig.Map<IServiceCollectionConfiguration>();

Difference of keywords 'typename' and 'class' in templates?

  1. No difference
  2. Template type parameter Container is itself a template with two type parameters.

c++ boost split string

My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:

-----------test2-------test3

What happened is the machine actually printed this:

test-------test2-------test3\r-------

That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).

Why does modern Perl avoid UTF-8 by default?

We're all in agreement that it is a difficult problem for many reasons, but that's precisely the reason to try to make it easier on everybody.

There is a recent module on CPAN, utf8::all, that attempts to "turn on Unicode. All of it".

As has been pointed out, you can't magically make the entire system (outside programs, external web requests, etc.) use Unicode as well, but we can work together to make sensible tools that make doing common problems easier. That's the reason that we're programmers.

If utf8::all doesn't do something you think it should, let's improve it to make it better. Or let's make additional tools that together can suit people's varying needs as well as possible.

`

Android AudioRecord example

Here I am posting you the some code example which record good quality of sound using AudioRecord API.

Note: If you use in emulator the sound quality will not much good because we are using sample rate 8k which only supports in emulator. In device use sample rate to 44.1k for better quality.

public class Audio_Record extends Activity {
    private static final int RECORDER_SAMPLERATE = 8000;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
    private AudioRecord recorder = null;
    private Thread recordingThread = null;
    private boolean isRecording = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setButtonHandlers();
        enableButtons(false);

        int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
                RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING); 
    }

    private void setButtonHandlers() {
        ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
        ((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
    }

    private void enableButton(int id, boolean isEnable) {
        ((Button) findViewById(id)).setEnabled(isEnable);
    }

    private void enableButtons(boolean isRecording) {
        enableButton(R.id.btnStart, !isRecording);
        enableButton(R.id.btnStop, isRecording);
    }

    int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
    int BytesPerElement = 2; // 2 bytes in 16bit format

    private void startRecording() {

        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);

        recorder.startRecording();
        isRecording = true;
        recordingThread = new Thread(new Runnable() {
            public void run() {
                writeAudioDataToFile();
            }
        }, "AudioRecorder Thread");
        recordingThread.start();
    }

        //convert short to byte
    private byte[] short2byte(short[] sData) {
        int shortArrsize = sData.length;
        byte[] bytes = new byte[shortArrsize * 2];
        for (int i = 0; i < shortArrsize; i++) {
            bytes[i * 2] = (byte) (sData[i] & 0x00FF);
            bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
            sData[i] = 0;
        }
        return bytes;

    }

    private void writeAudioDataToFile() {
        // Write the output audio in byte

        String filePath = "/sdcard/voice8K16bitmono.pcm";
        short sData[] = new short[BufferElements2Rec];

        FileOutputStream os = null;
        try {
            os = new FileOutputStream(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        while (isRecording) {
            // gets the voice output from microphone to byte format

            recorder.read(sData, 0, BufferElements2Rec);
            System.out.println("Short writing to file" + sData.toString());
            try {
                // // writes the data to file from buffer
                // // stores the voice buffer
                byte bData[] = short2byte(sData);
                os.write(bData, 0, BufferElements2Rec * BytesPerElement);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopRecording() {
        // stops the recording activity
        if (null != recorder) {
            isRecording = false;
            recorder.stop();
            recorder.release();
            recorder = null;
            recordingThread = null;
        }
    }

    private View.OnClickListener btnClick = new View.OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.btnStart: {
                enableButtons(true);
                startRecording();
                break;
            }
            case R.id.btnStop: {
                enableButtons(false);
                stopRecording();
                break;
            }
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}

For more detail try this AUDIORECORD BLOG.

Happy Coding !!

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

Python 3.6 Timings

Here are the timing results using Python 3.6.8. Keep in mind these times are relative to one another, not absolute.

I stuck to only doing shallow copies, and also added some new methods that weren't possible in Python2, such as list.copy() (the Python3 slice equivalent) and two forms of list unpacking (*new_list, = list and new_list = [*list]):

METHOD                  TIME TAKEN
b = [*a]                2.75180600000021
b = a * 1               3.50215399999990
b = a[:]                3.78278899999986  # Python2 winner (see above)
b = a.copy()            4.20556500000020  # Python3 "slice equivalent" (see above)
b = []; b.extend(a)     4.68069800000012
b = a[0:len(a)]         6.84498999999959
*b, = a                 7.54031799999984
b = list(a)             7.75815899999997
b = [i for i in a]      18.4886440000000
b = copy.copy(a)        18.8254879999999
b = []
for item in a:
  b.append(item)        35.4729199999997

We can see the Python2 winner still does well, but doesn't edge out Python3 list.copy() by much, especially considering the superior readability of the latter.

The dark horse is the unpacking and repacking method (b = [*a]), which is ~25% faster than raw slicing, and more than twice as fast as the other unpacking method (*b, = a).

b = a * 1 also does surprisingly well.

Note that these methods do not output equivalent results for any input other than lists. They all work for sliceable objects, a few work for any iterable, but only copy.copy() works for more general Python objects.


Here is the testing code for interested parties (Template from here):

import timeit

COUNT = 50000000
print("Array duplicating. Tests run", COUNT, "times")
setup = 'a = [0,1,2,3,4,5,6,7,8,9]; import copy'

print("b = list(a)\t\t", timeit.timeit(stmt='b = list(a)', setup=setup, number=COUNT))
print("b = copy.copy(a)\t", timeit.timeit(stmt='b = copy.copy(a)', setup=setup, number=COUNT))
print("b = a.copy()\t\t", timeit.timeit(stmt='b = a.copy()', setup=setup, number=COUNT))
print("b = a[:]\t\t", timeit.timeit(stmt='b = a[:]', setup=setup, number=COUNT))
print("b = a[0:len(a)]\t\t", timeit.timeit(stmt='b = a[0:len(a)]', setup=setup, number=COUNT))
print("*b, = a\t\t\t", timeit.timeit(stmt='*b, = a', setup=setup, number=COUNT))
print("b = []; b.extend(a)\t", timeit.timeit(stmt='b = []; b.extend(a)', setup=setup, number=COUNT))
print("b = []; for item in a: b.append(item)\t", timeit.timeit(stmt='b = []\nfor item in a:  b.append(item)', setup=setup, number=COUNT))
print("b = [i for i in a]\t", timeit.timeit(stmt='b = [i for i in a]', setup=setup, number=COUNT))
print("b = [*a]\t\t", timeit.timeit(stmt='b = [*a]', setup=setup, number=COUNT))
print("b = a * 1\t\t", timeit.timeit(stmt='b = a * 1', setup=setup, number=COUNT))

Can I apply multiple background colors with CSS3?

In case someone needs a CSS background with different color repeating horizontal stripes, here is how I managed to achieve this:

_x000D_
_x000D_
body {_x000D_
  font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif;_x000D_
  font-size: 13px;_x000D_
}_x000D_
_x000D_
.css-stripes {_x000D_
  margin: 0 auto;_x000D_
  width: 200px;_x000D_
  padding: 100px;_x000D_
  text-align: center;_x000D_
  /* For browsers that do not support gradients */_x000D_
  background-color: #F691FF;_x000D_
  /* Safari 5.1 to 6.0 */_x000D_
  background: -webkit-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
  /* Opera 11.1 to 12.0 */_x000D_
  background: -o-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
  /* Firefox 3.6 to 15 */_x000D_
  background: -moz-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
  /* Standard syntax */_x000D_
  background-image: repeating-linear-gradient(to top, #F691FF, #EC72A8);_x000D_
  background-size: 1px 2px;_x000D_
}
_x000D_
<div class="css-stripes">Hello World!</div>
_x000D_
_x000D_
_x000D_

JSfiddle

Is it possible to install another version of Python to Virtualenv?

I have not found suitable answer, so here goes my take, which builds upon @toszter answer, but does not use system Python (and you may know, it is not always good idea to install setuptools and virtualenv at system level when dealing with many Python configurations):

#!/bin/sh

mkdir python_ve
cd python_ve

MYROOT=`pwd`
mkdir env pyenv dep

cd ${MYROOT}/dep
wget https://pypi.python.org/packages/source/s/setuptools/setuptools-15.2.tar.gz#md5=a9028a9794fc7ae02320d32e2d7e12ee
wget https://raw.github.com/pypa/virtualenv/master/virtualenv.py
wget https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tar.xz
xz -d Python-2.7.9.tar.xz

cd ${MYROOT}/pyenv
tar xf ../dep/Python-2.7.9.tar
cd Python-2.7.9
./configure --prefix=${MYROOT}/pyenv && make -j 4 && make install

cd ${MYROOT}/pyenv

tar xzf ../dep/setuptools-15.2.tar.gz

cd ${MYROOT}

pyenv/bin/python dep/virtualenv.py --no-setuptools --python=${MYROOT}/pyenv/bin/python --verbose env
env/bin/python pyenv/setuptools-15.2/setup.py install
env/bin/easy_install pip

echo "virtualenv in ${MYROOT}/env"

The trick of breaking chicken-egg problem here is to make virtualenv without setuptools first, because it otherwise fails (pip can not be found). It may be possible to install pip / wheel directly, but somehow easy_install was the first thing which came to my mind. Also, the script can be improved by factoring out concrete versions.

NB. Using xz in the script.

How To Check If A Key in **kwargs Exists?

DSM's and Tadeck's answers answer your question directly.

In my scripts I often use the convenient dict.pop() to deal with optional, and additional arguments. Here's an example of a simple print() wrapper:

def my_print(*args, **kwargs):
    prefix = kwargs.pop('prefix', '')
    print(prefix, *args, **kwargs)

Then:

>>> my_print('eggs')
 eggs
>>> my_print('eggs', prefix='spam')
spam eggs

As you can see, if prefix is not contained in kwargs, then the default '' (empty string) is being stored in the local prefix variable. If it is given, then its value is being used.

This is generally a compact and readable recipe for writing wrappers for any kind of function: Always just pass-through arguments you don't understand, and don't even know if they exist. If you always pass through *args and **kwargs you make your code slower, and requires a bit more typing, but if interfaces of the called function (in this case print) changes, you don't need to change your code. This approach reduces development time while supporting all interface changes.

Parsing huge logfiles in Node.js - read in line-by-line

I have made a node module to read large file asynchronously text or JSON. Tested on large files.

var fs = require('fs')
, util = require('util')
, stream = require('stream')
, es = require('event-stream');

module.exports = FileReader;

function FileReader(){

}

FileReader.prototype.read = function(pathToFile, callback){
    var returnTxt = '';
    var s = fs.createReadStream(pathToFile)
    .pipe(es.split())
    .pipe(es.mapSync(function(line){

        // pause the readstream
        s.pause();

        //console.log('reading line: '+line);
        returnTxt += line;        

        // resume the readstream, possibly from a callback
        s.resume();
    })
    .on('error', function(){
        console.log('Error while reading file.');
    })
    .on('end', function(){
        console.log('Read entire file.');
        callback(returnTxt);
    })
);
};

FileReader.prototype.readJSON = function(pathToFile, callback){
    try{
        this.read(pathToFile, function(txt){callback(JSON.parse(txt));});
    }
    catch(err){
        throw new Error('json file is not valid! '+err.stack);
    }
};

Just save the file as file-reader.js, and use it like this:

var FileReader = require('./file-reader');
var fileReader = new FileReader();
fileReader.readJSON(__dirname + '/largeFile.json', function(jsonObj){/*callback logic here*/});

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

Everything you write in your own stylesheet is overwriting the user agent styles - that's the point of writing your own stylesheet.

Using a scanner to accept String input and storing in a String Array

One of the problem with this code is here :

name += contactName[];

This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.

Instead use this:

contactName[index] = name;

this instruction will store the variable name in the contactName array at the index index.

The second problem you have is that you don't have the variable index.

What you can do is a loop with 12 iterations to fill all your arrays. (and index will be your iteration variable)

SQL Server table creation date query

In case you also want Schema:

SELECT CONCAT(ic.TABLE_SCHEMA, '.', st.name) as TableName
   ,st.create_date
   ,st.modify_date

FROM sys.tables st

JOIN INFORMATION_SCHEMA.COLUMNS ic ON ic.TABLE_NAME = st.name

GROUP BY ic.TABLE_SCHEMA, st.name, st.create_date, st.modify_date

ORDER BY st.create_date

Shell Script: How to write a string to file and to stdout on console?

Use the tee command:

echo "hello" | tee logfile.txt

How to get Current Directory?

#include <windows.h>
using namespace std;

// The directory path returned by native GetCurrentDirectory() no end backslash
string getCurrentDirectoryOnWindows()
{
    const unsigned long maxDir = 260;
    char currentDir[maxDir];
    GetCurrentDirectory(maxDir, currentDir);
    return string(currentDir);
}

How to gettext() of an element in Selenium Webdriver

You need to print the result of the getText(). You're currently printing the object TxtBoxContent.

getText() will only get the inner text of an element. To get the value, you need to use getAttribute().

WebElement TxtBoxContent = driver.findElement(By.id(WebelementID));
System.out.println("Printing " + TxtBoxContent.getAttribute("value"));

Facebook development in localhost

In your app's basic settings (https://developers.facebook.com/apps) under Settings->Basic->Select how your app integrates with Facebook...

Use "Site URL:" and "Mobile Site URL:" to hold your production and development URLs respectively. Both sites will be allowed to authenticate. I'm just using Facebook for authentication so I don't need any of the mobile site redirection features. I usually change the "Mobile Site URL:" to my "localhost:12345" site while I'm testing the authentication, and then set it back to normal when I'm done.

Auto number column in SharePoint list

it's in there by default. It's the id field.

How can I create a memory leak in Java?

If Max heap size is X. Y1....Yn no of instances So,total memory= number of instances X Bytes per instance.If X1......Xn is bytes per instances.Then total memory(M)=Y1 * X1+.....+Yn *Xn. So,if M>X it exceeds heap space . following can be the problems in code 1.Use of more instances variable then local one. 2.Creating instances every time instead of pooling object. 3.Not Creating the object on demand. 4.Making the object reference null after the completion of operation.Again ,recreating when it is demanded in program.

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

Here are the three web pages on which we found the answer. The most difficult part was setting up static ports for SQLEXPRESS.

Provisioning a SQL Server Virtual Machine on Windows Azure. These initial instructions provided 25% of the answer.

How to Troubleshoot Connecting to the SQL Server Database Engine. Reading this carefully provided another 50% of the answer.

How to configure SQL server to listen on different ports on different IP addresses?. This enabled setting up static ports for named instances (eg SQLEXPRESS.) It took us the final 25% of the way to the answer.

What's the main difference between Java SE and Java EE?

Java SE refers to the standard version of Java and its libraries. Java EE refers to the Enterprise edition of Java which is used to deploy web applications.

Currency formatting in Python

A lambda for calculating it inside a function, with help from @Nate's answer

converter = lambda amount, currency: "%s%s%s" %(
    "-" if amount < 0 else "", 
    currency, 
    ('{:%d,.2f}'%(len(str(amount))+3)).format(abs(amount)).lstrip())

and then,

>>> converter(123132132.13, "$")
'$123,132,132.13'

>>> converter(-123132132.13, "$")
'-$123,132,132.13'

How to programmatically add controls to a form in VB.NET

Yes.

Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim MyTextbox as New Textbox
    With MyTextbox
       .Size = New Size(100,20)
       .Location = New Point(20,20)
    End With
    AddHandler MyTextbox.TextChanged, AddressOf MyTextbox_Changed
    Me.Controls.Add(MyTextbox)

'Without a help environment for an intelli sense substitution
'the address name and the methods name
'cannot be wrote in exchange for each other.
'Until an equality operation is prior for an exchange i have to work
'on an as is base substituted.

End Sub

Friend Sub MyTextbox_Changed(sender as Object, e as EventArgs)
   'Write code here.
End Sub

How to show the text on a ImageButton?

Here is the solution

<LinearLayout
    android:id="@+id/buttons_line1"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageButton
        android:id="@+id/btn_mute"
        android:src="@drawable/btn_mute"
        android:background="@drawable/circle_gray"
        android:layout_width="60dp"
        android:layout_height="60dp"/>
    <ImageButton
        android:id="@+id/btn_keypad"
        android:layout_marginLeft="50dp"
        android:src="@drawable/btn_dialpad"
        android:background="@drawable/circle_gray"
        android:layout_width="60dp"
        android:layout_height="60dp"/>
    <ImageButton
        android:id="@+id/btn_speaker"
        android:layout_marginLeft="50dp"
        android:src="@drawable/btn_speaker"
        android:background="@drawable/circle_gray"
        android:layout_width="60dp"
        android:layout_height="60dp"/>
</LinearLayout>
<LinearLayout
    android:layout_below="@+id/buttons_line1"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_marginTop="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:text="mute"
        android:clickable="false"
        android:textAlignment="center"
        android:textColor="@color/Grey"
        android:layout_width="60dp"
        android:layout_height="wrap_content"/>
    <TextView
        android:text="keypad"
        android:clickable="false"
        android:layout_marginLeft="50dp"
        android:textAlignment="center"
        android:textColor="@color/Grey"
        android:layout_width="60dp"
        android:layout_height="wrap_content"/>
    <TextView
        android:text="speaker"
        android:clickable="false"
        android:layout_marginLeft="50dp"
        android:textAlignment="center"
        android:textColor="@color/Grey"
        android:layout_width="60dp"
        android:layout_height="wrap_content"/>
</LinearLayout>

Assign static IP to Docker container

You can set the IP while running it.

docker run --cap-add=NET_ADMIN -dit imagename /bin/sh -c "/sbin/ip addr add 172.17.0.12 dev eth0; bash"

See my example at https://github.com/RvdGijp/mariadb-10.1-galera

What is a "web service" in plain English?

For most sites you have HTML pages that you visit when you use your browser. These are human-readable pages (once rendered in your browser) where a lot of data might be crammed together, because it makes sense for humans.

Now imagine that someone else want to use some of that data. They could download your page and start filtering out all the "noise" to get the data they wanted, but most websites are not built in a way where data is 100% certain to be placed in the same spot for all elements, so in addition to being cumbersome it also becomes unreliable.

Enter web services.

A web service is something that a website chooses to offer to those who wish to read, update and/or delete data from your website. You might call it a "backdoor" to your data. Instead of presenting the data as part of a webpage it is provided in a pre-determined way where some of the more popular are XML and JSON. There are several ways to communicate with a webservice, some use SOAP, others have REST'ful web services, etc.

What is common for all web services is that they are the machine-readable equivelant to the webpages the site otherwise offers. This means that others who wish to use the data can send a request to get certain data back that is easy to parse and use. Some sites may require you to provide a username/password in the request, for sensitive data, while other sites allow anyone to extract whatever data they might need.

Base table or view not found: 1146 Table Laravel 5

This problem occur due to wrong spell or undefined database name. Make sure your database name, table name and all column name is same as from phpmyadmin.

Thank You

Strip / trim all strings of a dataframe

Money Shot

Here's a compact version of using applymap with a straightforward lambda expression to call strip only when the value is of a string type:

df.applymap(lambda x: x.strip() if isinstance(x, str) else x)

Full Example

A more complete example:

import pandas as pd


def trim_all_columns(df):
    """
    Trim whitespace from ends of each value across all series in dataframe
    """
    trim_strings = lambda x: x.strip() if isinstance(x, str) else x
    return df.applymap(trim_strings)


# simple example of trimming whitespace from data elements
df = pd.DataFrame([['  a  ', 10], ['  c  ', 5]])
df = trim_all_columns(df)
print(df)


>>>
   0   1
0  a  10
1  c   5

Working Example

Here's a working example hosted by trinket: https://trinket.io/python3/e6ab7fb4ab

Reloading/refreshing Kendo Grid

I want to go back to page 1 when I refresh the grid. Just calling the read() function will keep you on the current page, even if the new results don't have that many pages. Calling .page(1) on the datasource will refresh the datasource AND return to page 1 but fails on grids that aren't pageable. This function handles both:

function refreshGrid(selector) {
     var grid = $(selector);
     if (grid.length === 0)
         return;

     grid = grid.data('kendoGrid');
     if (grid.getOptions().pageable) {
         grid.dataSource.page(1);
     }
     else {
         grid.dataSource.read();
     }
}

Regex date format validation on Java

Use the following regular expression:

^\d{4}-\d{2}-\d{2}$

as in

if (str.matches("\\d{4}-\\d{2}-\\d{2}")) {
    ...
}

With the matches method, the anchors ^ and $ (beginning and end of string, respectively) are present implicitly.

Pipenv: Command Not Found

I have same problem with pipenv on Mac OS X 10.13 High Seirra, another Mac works just fine. I use Heroku to deploy my Django servers, some in 2.7 and some in 3.6. So, I need both 2.7 and 3.6. When HomeBrew install Python, it keeps python points to original 2.7, and python3 points to 3.6.

The problem might due to $ pip install pipenv. I checked /usr/local/bin and pipenv isn't there. So, I tried a full uninstall:

$ pip uninstall pipenv

Cannot uninstall requirement pipenv, not installed
You are using pip version 9.0.1, however version 10.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

$ pip3 uninstall pipenv
Skipping pipenv as it is not installed.

Then reinstall and works now:

$ pip3 install pipenv
Collecting pipenv

How can I see the size of files and directories in linux?

You can use:

ls -lh

Using this command you'll see the apparent space of the directory and true space of the files and in details the names of the files displayed, besides the size and creation date of each.

How can I sort a std::map first by value, then by key?

You can use std::set instead of std::map.

You can store both key and value in std::pair and the type of container will look like this:

std::set< std::pair<int, std::string> > items;

std::set will sort it's values both by original keys and values that were stored in std::map.

How to delete last character in a string in C#?

Try this:

paramstr.Remove((paramstr.Length-1),1);

Pattern matching using a wildcard

If you really do want to use wildcards to identify specific variables, then you can use a combination of ls() and grep() as follows:

l = ls()
vars.with.result <- l[grep("result", l)]

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :

</body>
<script>require('../script/viewLog.js')</script>

after :

<script>require('../script/viewLog.js')</script>
</body>

Using Java to pull data from a webpage?

Here's my solution using URL and try with resources phrase to catch the exceptions.

/**
 * Created by mona on 5/27/16.
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class ReadFromWeb {
    public static void readFromWeb(String webURL) throws IOException {
        URL url = new URL(webURL);
        InputStream is =  url.openStream();
        try( BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
            throw new MalformedURLException("URL is malformed!!");
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new IOException();
        }

    }
    public static void main(String[] args) throws IOException {
        String url = "https://madison.craigslist.org/search/sub";
        readFromWeb(url);
    }

}

You could additionally save it to file based on your needs or parse it using XML or HTML libraries.

Split a string into array in Perl

Having $line as it is now, you can simply split the string based on at least one whitespace separator

my @answer = split(' ', $line); # creates an @answer array

then

print("@answer\n");               # print array on one line

or

print("$_\n") for (@answer);      # print each element on one line

I prefer using () for split, print and for.

How to change current Theme at runtime in Android

This had no effect for me:

public void changeTheme(int newTheme) {
    setTheme(newTheme);
    recreate();
}

But this worked:

int theme = R.style.default;

protected void onCreate(Bundle savedInstanceState) {
    setTheme(this.theme);
    super.onCreate(savedInstanceState);
}

public void changeTheme(int newTheme) {
    this.theme = newTheme;
    recreate();
}

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

I got this error in Ubuntu. I saw that /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts was a broken link to /etc/ssl/certs/java/cacerts. That lead me to this bug: https://bugs.launchpad.net/ubuntu/+source/ca-certificates-java/+bug/983302 The README for ca-certificates-java eventually showed the actual fix:

run

update-ca-certificates -f

apt-get install ca-certificates-java didn't work for me. It just marked it as manually installed.

Could not open input file: artisan

I also had the problem i just installed but forgot to jump the created project folder. So you need to jump your project folder.

cd project_name

and then serve php artisan command

Reloading the page gives wrong GET request with AngularJS HTML5 mode

I believe your issue is with regards to the server. The angular documentation with regards to HTML5 mode (at the link in your question) states:

Server side Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)

I believe you'll need to setup a url rewrite from /about to /.

iPhone UIView Animation Best Practice

Anyway the "Block" method is preffered now-a-days. I will explain the simple block below.

Consider the snipped below. bug2 and bug 3 are imageViews. The below animation describes an animation with 1 second duration after a delay of 1 second. The bug3 is moved from its center to bug2's center. Once the animation is completed it will be logged "Center Animation Done!".

-(void)centerAnimation:(id)sender
{
NSLog(@"Center animation triggered!");
CGPoint bug2Center = bug2.center;

[UIView animateWithDuration:1
                      delay:1.0
                    options: UIViewAnimationCurveEaseOut
                 animations:^{
                     bug3.center = bug2Center;
                 } 
                 completion:^(BOOL finished){
                     NSLog(@"Center Animation Done!");
                 }];
}

Hope that's clean!!!

Server certificate verification failed: issuer is not trusted

string cmdArguments = $@"/k svn log --trust-server-cert --non-interactive ""{servidor}"" --username alex --password alex -r {numeroRevisao}";
ProcessStartInfo cmd = new ProcessStartInfo("cmd.exe", cmdArguments);

cmd.CreateNoWindow = true;
cmd.RedirectStandardOutput = true;
cmd.RedirectStandardError = true;
cmd.WindowStyle = ProcessWindowStyle.Hidden;
cmd.UseShellExecute = false;

Process reg = Process.Start(cmd);
string output = "";

using (System.IO.StreamReader myOutput = reg.StandardOutput)
{
    output += myOutput.ReadToEnd();
}
using (System.IO.StreamReader myError = reg.StandardError)
{
    output += myError.ReadToEnd();
}

return output;

Convert int to char in java

Nobody has answered the real "question" here: you ARE converting int to char correctly; in the ASCII table a decimal value of 01 is "start of heading", a non-printing character. Try looking up an ASCII table and converting an int value between 33 and 7E; that will give you characters to look at.

Most useful NLog configurations

Easier Way To Log each log level with a different layout using Conditional Layouts

<variable name="VerboseLayout" value="${level:uppercase=true}: ${longdate} | ${logger}    : 
${when:when=level == LogLevel.Trace:inner=MONITOR_TRACE ${message}} 
${when:when=level == LogLevel.Debug:inner=MONITOR_DEBUG ${message}} 
${when:when=level == LogLevel.Info:inner=MONITOR_INFO ${message}} 
${when:when=level == LogLevel.Warn:inner=MONITOR_WARN ${message}} 
${when:when=level == LogLevel.Error:inner=MONITOR_ERROR ${message}} 
${when:when=level == LogLevel.Fatal:inner=MONITOR_CRITICAL ${message}} |     
${exception:format=tostring} | ${newline} ${newline}" />

See https://github.com/NLog/NLog/wiki/When-Filter for syntax

add title attribute from css

On the one hand, the title is helpful as a tooltip when moving the mouse over the element. This could be solved with CSS-> element::after. But it is much more important as an aid for visually impaired people (topic handicap-free website). And for this it MUST be included as an attribute in the HTML element. Everything else is junk, botch, idiot stuff ...!

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

I ran into a similar issue today - a co-worker could not build his software but I could build it. When he ran gcc it could not find cc1.

His executable path looked reasonable but the fact that I could not easily replicate the failure suggested something in his environment as the cause.

Eventually we found GCC_EXEC_PREFIX defined in his environment which was the culprit and was misleading gcc in the search for cc1. This was part of his shell startup scripts and was meant to work around a limitation on a SPARC/Solaris system that is no longer in use. The problem was resolved by not setting this environment variable.

http://gcc.gnu.org/onlinedocs/gcc/Environment-Variables.html

HRESULT: 0x800A03EC on Worksheet.range

This type of error can also occur when the excel file is corrupted for some reason

Convert JsonObject to String

There is an inbuilt method to convert a JSONObject to a String. Why don't you use that:

JSONObject json = new JSONObject();

json.toString();

How can I fill a column with random numbers in SQL? I get the same value in every row

Instead of rand(), use newid(), which is recalculated for each row in the result. The usual way is to use the modulo of the checksum. Note that checksum(newid()) can produce -2,147,483,648 and cause integer overflow on abs(), so we need to use modulo on the checksum return value before converting it to absolute value.

UPDATE CattleProds
SET    SheepTherapy = abs(checksum(NewId()) % 10000)
WHERE  SheepTherapy IS NULL

This generates a random number between 0 and 9999.

How to get child element by ID in JavaScript?

If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.

$('#note').find('#textid');

You can also use jQuery selectors to basically achieve the same thing:

$('#note #textid');

Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.

On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.

Update 2020.03.10

It's a breeze to use native JS for this:

document.querySelector('#note #textid');

If you want to first find #note then #textid you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(

var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;

Printing everything except the first field with awk

awk '{ tmp = $1; sub(/^[^ ]+ +/, ""); print $0, tmp }'

Call static methods from regular ES6 class methods

Both ways are viable, but they do different things when it comes to inheritance with an overridden static method. Choose the one whose behavior you expect:

class Super {
  static whoami() {
    return "Super";
  }
  lognameA() {
    console.log(Super.whoami());
  }
  lognameB() {
    console.log(this.constructor.whoami());
  }
}
class Sub extends Super {
  static whoami() {
    return "Sub";
  }
}
new Sub().lognameA(); // Super
new Sub().lognameB(); // Sub

Referring to the static property via the class will be actually static and constantly give the same value. Using this.constructor instead will use dynamic dispatch and refer to the class of the current instance, where the static property might have the inherited value but could also be overridden.

This matches the behavior of Python, where you can choose to refer to static properties either via the class name or the instance self.

If you expect static properties not to be overridden (and always refer to the one of the current class), like in Java, use the explicit reference.

How to distinguish between left and right mouse click with jQuery

If you are looking for "Better Javascript Mouse Events" which allow for

  • left mousedown
  • middle mousedown
  • right mousedown
  • left mouseup
  • middle mouseup
  • right mouseup
  • left click
  • middle click
  • right click
  • mousewheel up
  • mousewheel down

Have a look at this cross browser normal javascript which triggers the above events, and removes the headache work. Just copy and paste it into the head of your script, or include it in a file in the <head> of your document. Then bind your events, refer to the next code block below which shows a jquery example of capturing the events and firing the functions assigned to them, though this works with normal javascript binding as well.

If your interested in seeing it work, have a look at the jsFiddle: https://jsfiddle.net/BNefn/

/**
   Better Javascript Mouse Events
   Author: Casey Childers
**/
(function(){
    // use addEvent cross-browser shim: https://gist.github.com/dciccale/5394590/
    var addEvent = function(a,b,c){try{a.addEventListener(b,c,!1)}catch(d){a.attachEvent('on'+b,c)}};

    /* This function detects what mouse button was used, left, right, middle, or middle scroll either direction */
    function GetMouseButton(e) {
        e = window.event || e; // Normalize event variable

        var button = '';
        if (e.type == 'mousedown' || e.type == 'click' || e.type == 'contextmenu' || e.type == 'mouseup') {
            if (e.which == null) {
                button = (e.button < 2) ? "left" : ((e.button == 4) ? "middle" : "right");
            } else {
                button = (e.which < 2) ? "left" : ((e.which == 2) ? "middle" : "right");
            }
        } else {
            var direction = e.detail ? e.detail * (-120) : e.wheelDelta;
            switch (direction) {
                case 120:
                case 240:
                case 360:
                    button = "up";
                break;
                case -120:
                case -240:
                case -360:
                    button = "down";
                break;
            }
        }

        var type = e.type
        if(e.type == 'contextmenu') {type = "click";}
        if(e.type == 'DOMMouseScroll') {type = "mousewheel";}

        switch(button) {
            case 'contextmenu':
            case 'left':
            case 'middle':
            case 'up':
            case 'down':
            case 'right':
                if (document.createEvent) {
                  event = new Event(type+':'+button);
                  e.target.dispatchEvent(event);
                } else {
                  event = document.createEventObject();
                  e.target.fireEvent('on'+type+':'+button, event);
                }
            break;
        }
    }

    addEvent(window, 'mousedown', GetMouseButton);
    addEvent(window, 'mouseup', GetMouseButton);
    addEvent(window, 'click', GetMouseButton);
    addEvent(window, 'contextmenu', GetMouseButton);

    /* One of FireFox's browser versions doesn't recognize mousewheel, we account for that in this line */
    var MouseWheelEvent = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel";
    addEvent(window, MouseWheelEvent, GetMouseButton);
})();

Better Mouse Click Events Example (uses jquery for simplicity, but the above will work cross browser and fire the same event names, IE uses on before the names)

<div id="Test"></div>
<script type="text/javascript">
    $('#Test').on('mouseup',function(e){$(this).append(e.type+'<br />');})
              .on('mouseup:left',function(e){$(this).append(e.type+'<br />');})
              .on('mouseup:middle',function(e){$(this).append(e.type+'<br />');})
              .on('mouseup:right',function(e){$(this).append(e.type+'<br />');})

              .on('click',function(e){$(this).append(e.type+'<br />');})
              .on('click:left',function(e){$(this).append(e.type+'<br />');})
              .on('click:middle',function(e){$(this).append(e.type+'<br />');})
              .on('click:right',function(e){$(this).append(e.type+'<br />');})

              .on('mousedown',function(e){$(this).html('').append(e.type+'<br />');})
              .on('mousedown:left',function(e){$(this).append(e.type+'<br />');})
              .on('mousedown:middle',function(e){$(this).append(e.type+'<br />');})
              .on('mousedown:right',function(e){$(this).append(e.type+'<br />');})

              .on('mousewheel',function(e){$(this).append(e.type+'<br />');})
              .on('mousewheel:up',function(e){$(this).append(e.type+'<br />');})
              .on('mousewheel:down',function(e){$(this).append(e.type+'<br />');})
              ;
</script>

And for those who are in need of the minified version...

!function(){function e(e){e=window.event||e;var t="";if("mousedown"==e.type||"click"==e.type||"contextmenu"==e.type||"mouseup"==e.type)t=null==e.which?e.button<2?"left":4==e.button?"middle":"right":e.which<2?"left":2==e.which?"middle":"right";else{var n=e.detail?-120*e.detail:e.wheelDelta;switch(n){case 120:case 240:case 360:t="up";break;case-120:case-240:case-360:t="down"}}var c=e.type;switch("contextmenu"==e.type&&(c="click"),"DOMMouseScroll"==e.type&&(c="mousewheel"),t){case"contextmenu":case"left":case"middle":case"up":case"down":case"right":document.createEvent?(event=new Event(c+":"+t),e.target.dispatchEvent(event)):(event=document.createEventObject(),e.target.fireEvent("on"+c+":"+t,event))}}var t=function(e,t,n){try{e.addEventListener(t,n,!1)}catch(c){e.attachEvent("on"+t,n)}};t(window,"mousedown",e),t(window,"mouseup",e),t(window,"click",e),t(window,"contextmenu",e);var n=/Firefox/i.test(navigator.userAgent)?"DOMMouseScroll":"mousewheel";t(window,n,e)}();

Pass a PHP variable value through an HTML form

Try that

First place

global $var;
$var = 'value';

Second place

global $var;
if (isset($_POST['save_exit']))
{
    echo $var; 
}

Or if you want to be more explicit you can use the globals array:

$GLOBALS['var'] = 'test';

// after that
echo $GLOBALS['var'];

And here is third options which has nothing to do with PHP global that is due to the lack of clarity and information in the question. So if you have form in HTML and you want to pass "variable"/value to another PHP script you have to do the following:

HTML form

<form action="script.php" method="post">
    <input type="text" value="<?php echo $var?>" name="var" />
    <input type="submit" value="Send" />
</form>

PHP script ("script.php")

<?php

$var = $_POST['var'];
echo $var;

?>

Why can't I have "public static const string S = "stuff"; in my Class?

A const member is considered static by the compiler, as well as implying constant value semantics, which means references to the constant might be compiled into the using code as the value of the constant member, instead of a reference to the member.

In other words, a const member containing the value 10, might get compiled into code that uses it as the number 10, instead of a reference to the const member.

This is different from a static readonly field, which will always be compiled as a reference to the field.

Note, this is pre-JIT. When the JIT'ter comes into play, it might compile both these into the target code as values.

How do I make an HTTP request in Swift?

Details

  • Xcode 9.2, Swift 4
  • Xcode 10.2.1 (10E1001), Swift 5

Info.plist

NSAppTransportSecurity

Add to the info plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

Alamofire Sample

Alamofire

import Alamofire

class AlamofireDataManager {
    fileprivate let queue: DispatchQueue
    init(queue: DispatchQueue) { self.queue = queue }

    private func createError(message: String, code: Int) -> Error {
        return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
    }

    private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((Result<[String: Any]>) -> Void)?) {
        Alamofire.request(request).responseJSON { response in
            let complete: (Result<[String: Any]>) ->() = { result in DispatchQueue.main.async { closure?(result) } }
            switch response.result {
                case .success(let value): complete(.success(value as! [String: Any]))
                case .failure(let error): complete(.failure(error))
            }
        }
    }

    func searchRequest(term: String, closure: ((Result<[String: Any]>) -> Void)?) {
        guard let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))") else { return }
        let request = URLRequest(url: url)
        make(request: request) { response in closure?(response) }
    }
}

Usage of Alamofire sample

private lazy var alamofireDataManager = AlamofireDataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
//.........

alamofireDataManager.searchRequest(term: "jack johnson") { result in
      print(result.value ?? "no data")
      print(result.error ?? "no error")
}

URLSession Sample

import Foundation

class DataManager {

    fileprivate let queue: DispatchQueue
        init(queue: DispatchQueue) { self.queue = queue }

    private func createError(message: String, code: Int) -> Error {
        return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
    }

    private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
        let task = session.dataTask(with: request) { [weak self] data, response, error in
            self?.queue.async {
                let complete: (_ json: [String: Any]?, _ error: Error?) ->() = { json, error in DispatchQueue.main.async { closure?(json, error) } }

                guard let self = self, error == nil else { complete(nil, error); return }
                guard let data = data else { complete(nil, self.createError(message: "No data", code: 999)); return }

                do {
                    if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                        complete(json, nil)
                    }
                } catch let error { complete(nil, error); return }
            }
        }

        task.resume()
    }

    func searchRequest(term: String, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
        let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))")
        let request = URLRequest(url: url!)
        make(request: request) { json, error in closure?(json, error) }
    }
}

Usage of URLSession sample

private lazy var dataManager = DataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
// .......
dataManager.searchRequest(term: "jack johnson") { json, error  in
      print(error ?? "nil")
      print(json ?? "nil")
      print("Update views")
}

Results

enter image description here

Counting duplicates in Excel

I don't know if it's entirely possible to do your ideal pattern. But I found a way to do your first way: CountIF

+-------+-------------------+
|   A   |         B         |
+-------+-------------------+
| GL15  | =COUNTIF(A:A, A1) |
+-------+-------------------+
| GL15  | =COUNTIF(A:A, A2) |
+-------+-------------------+
| GL15  | =COUNTIF(A:A, A3) |
+-------+-------------------+
| GL16  | =COUNTIF(A:A, A4) |
+-------+-------------------+
| GL17  | =COUNTIF(A:A, A5) |
+-------+-------------------+
| GL17  | =COUNTIF(A:A, A6) |
+-------+-------------------+

Get the data received in a Flask request

@app.route('/addData', methods=['POST'])
def add_data():
     data_in = mongo.db.Data
     id = request.values.get("id")
     name = request.values.get("name")
     newuser = {'id' : id, 'name' : name}
     if voter.find({'id' : id, 'name' : name}).count() > 0:
            return "Data Exists"
     else:
            data_in.insert(newuser)
            return "Data Added"

How do I close an Android alertdialog

try using

dialog.dismiss()

instead of using

dialog.cancel()

How to vertically align an image inside a div

Use this one:

position: absolute;
top: calc(50% - 0.5em);
left: calc(50% - 0.5em);
line-height: 1em;

And you can vary font-size.

Is it possible to put CSS @media rules inline?

if you add the rule to the print.css file you don't have to use @media.

I uncluded it in the smarty foreach i use to give some elements a background color.

_x000D_
_x000D_
<script type='text/javascript'>_x000D_
  document.styleSheets[3].insertRule(" #caldiv_<?smarty $item.calendar_id ?> { border-color:<?smarty $item.color ?> }", 1);_x000D_
</script>
_x000D_
_x000D_
_x000D_

What is the difference between varchar and nvarchar?

The main difference between Varchar(n) and nvarchar(n) is: enter image description here

Varchar( Variable-length, non-Unicode character data) size is upto 8000. 1.It is a variable length data type

  1. Used to store non-Unicode characters

  2. Occupies 1 byte of space for each character

enter image description here

Nvarchar:Variable-length Unicode character data.

1.It is a variable-length data type

2.Used to store Unicode characters.

  1. Data is stored in a Unicode encoding. Every language is supported. (for example the languages Arabic, German,Hindi,etc and so on)

Opening Chrome From Command Line

open command prompt and type

cd\ (enter)

then type

start chrome "www.google.com"(any website you require)

Suppress output of a function

In case anyone's arriving here looking for a solution applicable to RMarkdown, this will suppress all output:

```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({

# Your code goes here
2 * 2
# etc
# etc


})})
```

The code will run, but the output will not be printed to the HTML document