Programs & Examples On #Google website optimizer

Google Website Optimizer was a free website optimization tool that provides a framework for A/B and multivariate testing. It is currently retired as a project, but it's functionality has been integrated into Google Analytics

How to perform OR condition in django queryset?

Because QuerySets implement the Python __or__ operator (|), or union, it just works. As you'd expect, the | binary operator returns a QuerySet so order_by(), .distinct(), and other queryset filters can be tacked on to the end.

combined_queryset = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)
ordered_queryset = combined_queryset.order_by('-income')

Update 2019-06-20: This is now fully documented in the Django 2.1 QuerySet API reference. More historic discussion can be found in DjangoProject ticket #21333.

PHPExcel - creating multiple sheets by iteration

When you first instantiate the $objPHPExcel, it already has a single sheet (sheet 0); you're then adding a new sheet (which will become sheet 1), but setting active sheet to sheet $i (when $i is 0)... so you're renaming and populating the original worksheet created when you instantiated $objPHPExcel rather than the one you've just added... this is your title "0".

You're also using the createSheet() method, which both creates a new worksheet and adds it to the workbook... but you're also adding it again yourself which is effectively adding the sheet in two position.

So first iteration, you already have sheet0, add a new sheet at both indexes 1 and 2, and edit/title sheet 0. Second iteration, you add a new sheet at both indexes 3 and 4, and edit/title sheet 1, but because you have the same sheet at indexes 1 and 2 this effectively writes to the sheet at index 2. Third iteration, you add a new sheet at indexes 5 and 6, and edit/title sheet 2, overwriting your earlier editing/titleing of sheet 1 which acted against sheet 2 instead.... and so on

Using Linq to get the last N elements of a collection?

Honestly I'm not super proud of the answer, but for small collections you could use the following:

var lastN = collection.Reverse().Take(n).Reverse();

A bit hacky but it does the job ;)

How to format an inline code in Confluence?

To format code in-line within your text, use the '`' character to surround your code. Usually located to the left of the '1' key on your keyboard.

Example:

`printf("Hello World");`

Same delimiter as Stack Exchange!

How to write header row with csv.DictWriter?

A few options:

(1) Laboriously make an identity-mapping (i.e. do-nothing) dict out of your fieldnames so that csv.DictWriter can convert it back to a list and pass it to a csv.writer instance.

(2) The documentation mentions "the underlying writer instance" ... so just use it (example at the end).

dw.writer.writerow(dw.fieldnames)

(3) Avoid the csv.Dictwriter overhead and do it yourself with csv.writer

Writing data:

w.writerow([d[k] for k in fieldnames])

or

w.writerow([d.get(k, restval) for k in fieldnames])

Instead of the extrasaction "functionality", I'd prefer to code it myself; that way you can report ALL "extras" with the keys and values, not just the first extra key. What is a real nuisance with DictWriter is that if you've verified the keys yourself as each dict was being built, you need to remember to use extrasaction='ignore' otherwise it's going to SLOWLY (fieldnames is a list) repeat the check:

wrong_fields = [k for k in rowdict if k not in self.fieldnames]

============

>>> f = open('csvtest.csv', 'wb')
>>> import csv
>>> fns = 'foo bar zot'.split()
>>> dw = csv.DictWriter(f, fns, restval='Huh?')
# dw.writefieldnames(fns) -- no such animal
>>> dw.writerow(fns) # no such luck, it can't imagine what to do with a list
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\python26\lib\csv.py", line 144, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\python26\lib\csv.py", line 141, in _dict_to_list
    return [rowdict.get(key, self.restval) for key in self.fieldnames]
AttributeError: 'list' object has no attribute 'get'
>>> dir(dw)
['__doc__', '__init__', '__module__', '_dict_to_list', 'extrasaction', 'fieldnam
es', 'restval', 'writer', 'writerow', 'writerows']
# eureka
>>> dw.writer.writerow(dw.fieldnames)
>>> dw.writerow({'foo':'oof'})
>>> f.close()
>>> open('csvtest.csv', 'rb').read()
'foo,bar,zot\r\noof,Huh?,Huh?\r\n'
>>>

Achieving white opacity effect in html/css

Try RGBA, e.g.

div { background-color: rgba(255, 255, 255, 0.5); }

As always, this won't work in every single browser ever written.

Uploading files to file server using webclient class

Just use

File.Copy(filepath, "\\\\192.168.1.28\\Files");

A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.

The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.

You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!

If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"

If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.

How to write a multiline command?

After trying almost every key on my keyboard:

C:\Users\Tim>cd ^
Mehr? Desktop

C:\Users\Tim\Desktop>

So it seems to be the ^ key.

Inserting data into a temporary table

INSERT INTO #TempTable (ID, Date, Name) 
SELECT id, date, name 
FROM physical_table

jQuery ajax success callback function definition

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

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

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

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

How to customize Bootstrap 3 tab color

On the selector .nav-tabs > li > a:hover add !important to the background-color.

_x000D_
_x000D_
.nav-tabs{_x000D_
  background-color:#161616;_x000D_
}_x000D_
.tab-content{_x000D_
    background-color:#303136;_x000D_
    color:#fff;_x000D_
    padding:5px_x000D_
}_x000D_
.nav-tabs > li > a{_x000D_
  border: medium none;_x000D_
}_x000D_
.nav-tabs > li > a:hover{_x000D_
  background-color: #303136 !important;_x000D_
    border: medium none;_x000D_
    border-radius: 0;_x000D_
    color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul class="nav nav-tabs" id="myTab">_x000D_
    <li class="active"><a data-toggle="tab" href="#search">SEARCH</a></li>_x000D_
    <li><a data-toggle="tab" href="#advanced">ADVANCED</a></li>_x000D_
</ul>_x000D_
<div class="tab-content">_x000D_
    <div id="search" class="tab-pane fade in active">_x000D_
        Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel,_x000D_
        butcher voluptate nisi qui._x000D_
    </div>_x000D_
    <div id="advanced" class="tab-pane fade">_x000D_
        Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna._x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the best way to know if all the variables in a Class are null?

How about streams?

public boolean checkFieldsIsNull(Object instance, List<String> fieldNames) {

    return fieldNames.stream().allMatch(field -> {
        try {
            return Objects.isNull(instance.getClass().getDeclaredField(field).get(instance));
        } catch (IllegalAccessException | NoSuchFieldException e) {
            return true;//You can throw RuntimeException if need.
        }
    });
}

Add tooltip to font awesome icon

Simply with native html & css :

<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>
</div>

/* Tooltip container */
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}

/* Tooltip text */
.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: #555;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;

  /* Position the tooltip text */
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -60px;

  /* Fade in tooltip */
  opacity: 0;
  transition: opacity 0.3s;
}

/* Tooltip arrow */
.tooltip .tooltiptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
  visibility: visible;
  opacity: 1;
}

Here is the source of the example from w3schools

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

Try this

<?php
// 1. Enter Database details
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'database name';

// 2. Create a database connection
$connection = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$connection) {
    die("Database connection failed: " . mysql_error());
}

// 3. Select a database to use 
$db_select = mysql_select_db($dbname,$connection);
if (!$db_select) {
    die("Database selection failed: " . mysql_error());
}

$query = mysql_query("SELECT * FROM users WHERE name = 'Admin' ");

while ($rows = mysql_fetch_array($query)) { 
   $name = $rows['Name'];
   $address = $rows['Address'];
   $email = $rows['Email'];
   $subject = $rows['Subject'];
   $comment = $rows['Comment']

   echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";      
} 

?>

Not tested!! *UPDATED!!

How to get xdebug var_dump to show full object/array

Checkout Xdebbug's var_dump settings, particularly the values of these settings:

xdebug.var_display_max_children
xdebug.var_display_max_data
xdebug.var_display_max_depth

Spring Resttemplate exception handling

I fixed it by overriding the hasError method from DefaultResponseErrorHandler class:

public class BadRequestSafeRestTemplateErrorHandler extends DefaultResponseErrorHandler
{
    @Override
    protected boolean hasError(HttpStatus statusCode)
    {
        if(statusCode == HttpStatus.BAD_REQUEST)
        {
            return false;
        }
        return statusCode.isError();
    }
}

And you need to set this handler for restemplate bean:

@Bean
    protected RestTemplate restTemplate(RestTemplateBuilder builder)
    {
        return builder.errorHandler(new BadRequestSafeRestTemplateErrorHandler()).build();
    }

Find html label associated with a given input

The best answer works perfectly fine but in most cases, it is overkill and inefficient to loop through all the label elements.

Here is an efficent function to get the label that goes with the input element:

function getLabelForInput(id)
{
    var el = document.getElementById(id);
    if (!el)
        return null;
    var elPrev = el.previousElementSibling;
    var elNext = el.nextElementSibling;
    while (elPrev || elNext)
    {
        if (elPrev)
        {
            if (elPrev.htmlFor === id)
                return elPrev;
            elPrev = elPrev.previousElementSibling;
        }
        if (elNext)
        {
            if (elNext.htmlFor === id)
                return elNext;
            elNext = elNext.nextElementSibling;
        }
    }
    return null;
}

For me, this one line of code was sufficient:

el = document.getElementById(id).previousElementSibling;

In most cases, the label will be very close or next to the input, which means the loop in the above function only needs to iterate a very small number of times.

Create GUI using Eclipse (Java)

try http://code.google.com/p/swinghtmltemplate/

this will allow you to create gui with html-like syntax

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

This error is caused by failer of the ng serve serve to automatically pick up a newly added file. To fix this, simply restart your server.

Though closing the reopening the text editor or IDE solves this problem, many people do not want to go through all of the stress of reopening the project. To Fix this without closing the text editor...

In terminal where the server is running,

  • Press ctrl+C to stop the server then,
  • Start the server again: ng serve

That should work.

Spring Boot Remove Whitelabel Error Page

Here's an alternative method which is very similar to the "old way" of specifying error mappings in web.xml.

Just add this to your Spring Boot configuration:

@SpringBootApplication
public class Application implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        factory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/errors/403.html"));
        factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/errors/404.html"));
        factory.addErrorPages(new ErrorPage("/errors/500.html"));
    }

}

Then you can define the error pages in the static content normally.

The customizer can also be a separate @Component, if desired.

Python strptime() and timezones?

Since strptime returns a datetime object which has tzinfo attribute, We can simply replace it with desired timezone.

>>> import datetime

>>> date_time_str = '2018-06-29 08:15:27.243860'
>>> date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc)
>>> date_time_obj.tzname()
'UTC'

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

For nodejs use the below code

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

How do I restart a service on a remote machine in Windows?

You can use the services console, clicking on the left hand side and then selecting the "Connect to another computer" option in the Action menu.

If you wish to use the command line only, you can use

sc \\machine stop <service>

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

I think I figured out the questions after reading the log. Thanks to Will's reminder, I checked the log and found out the some program else is listening to that port. Before I can start to figure out which program, my computer was restarted and localhost:8080 works and showing tomcat page. Whooh

Is it possible to decrypt MD5 hashes?

There's no easy way to do it. This is kind of the point of hashing the password in the first place. :)

One thing you should be able to do is set a temporary password for them manually and send them that.

I hesitate to mention this because it's a bad idea (and it's not guaranteed to work anyway), but you could try looking up the hash in a rainbow table like milw0rm to see if you can recover the old password that way.

How to get access token from FB.login method in javascript SDK

response.session doesn't work anymore because response.authResponse is the new way to access the response content after the oauth migration.
Check this for details: SDKs & Tools › JavaScript SDK › FB.login

Failed to execute removeChild on Node

As others have mentioned, myCoolDiv is a child of markerDiv not playerContainer. If you want to remove myCoolDiv but keep markerDiv for some reason you can do the following

myCoolDiv.parentNode.removeChild(myCoolDiv);

JSFiddle

AngularJS dynamic routing

Ok solved it.

Added the solution to GitHub - http://gregorypratt.github.com/AngularDynamicRouting

In my app.js routing config:

$routeProvider.when('/pages/:name', {
    templateUrl: '/pages/home.html', 
    controller: CMSController 
});

Then in my CMS controller:

function CMSController($scope, $route, $routeParams) {

    $route.current.templateUrl = '/pages/' + $routeParams.name + ".html";

    $.get($route.current.templateUrl, function (data) {
        $scope.$apply(function () {
            $('#views').html($compile(data)($scope));
        });
    });
    ...
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];

With #views being my <div id="views" ng-view></div>

So now it works with standard routing and dynamic routing.

To test it I copied about.html called it portfolio.html, changed some of it's contents and entered /#/pages/portfolio into my browser and hey presto portfolio.html was displayed....

Updated Added $apply and $compile to the html so that dynamic content can be injected.

Convert Uri to String and String to Uri

You can use Drawable instead of Uri.

   ImageView iv=(ImageView)findViewById(R.id.imageView1);
   String pathName = "/external/images/media/470939"; 
   Drawable image = Drawable.createFromPath(pathName);
   iv.setImageDrawable(image);

This would work.

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

You could try the following:

class ResponseCodeCheck 
{

    public static void main (String args[]) throws Exception
    {

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

        int code = connection.getResponseCode();
        System.out.println("Response code of the object is "+code);
        if (code==200)
        {
            System.out.println("OK");
        }
    }
}

Pass arguments into C program from command line

Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

You can make use of ::marker pseudo element. This is useful in situations when you need to have different character entities for each list item.

ul li::marker {
  content: " "; /* Your symbol here */
}

_x000D_
_x000D_
ul li:nth-child(1)::marker {
  content: "\26BD   ";
}

ul li:nth-child(2)::marker {
  content: "\26C5   ";
}

ul li:nth-child(3)::marker {
  content: "\26F3   ";
}

ul li::marker {
  font-size: 20px;
}

ul li {
  margin: 15px 0;
  font-family: sans-serif;
  background: #BADA55;
  color: black;
  padding-bottom: 10px;
  padding-left: 10px;
  padding-top: 5px;
}
_x000D_
<ul>
  <li>France Vs Croatia</li>
  <li>Cloudy with sunshine</li>
  <li>Golf session ahead</li>
</ul>
_x000D_
_x000D_
_x000D_

SQL Server equivalent to MySQL enum data type?

The best solution I've found in this is to create a lookup table with the possible values as a primary key, and create a foreign key to the lookup table.

Predefined type 'System.ValueTuple´2´ is not defined or imported

We were seeing this same issue in one of our old projects that was targeting Framework 4.5.2. I tried several scenarios including all of the ones listed above: target 4.6.1, add System.ValueTuple package, delete bin, obj, and .vs folders. No dice. Repeat the same process for 4.7.2. Then tried removing the System.ValueTuple package since I was targeting 4.7.2 as one commenter suggested. Still nothing. Checked csproj file reference path. Looks right. Even dropped back down to 4.5.2 and installing the package again. All this with several VS restarts and deleting the same folders several times. Literally nothing worked.

I had to refactor to use a struct instead. I hope others don't continue to run into this issue in the future but thought this might be helpful if you end up as stumped up as we were.

Get width in pixels from element with style set with %?

You can use offsetWidth. Refer to this post and question for more.

_x000D_
_x000D_
console.log("width:" + document.getElementsByTagName("div")[0].offsetWidth + "px");
_x000D_
div {border: 1px solid #F00;}
_x000D_
<div style="width: 100%; height: 10px;"></div>
_x000D_
_x000D_
_x000D_

How do I combine 2 select statements into one?

I think that's what you're looking for:

SELECT CASE WHEN BoolField05 = 1 THEN Status ELSE 'DELETED' END AS MyStatus, t1.*
FROM WorkItems t1
WHERE (TextField01, TimeStamp) IN(
  SELECT TextField01, MAX(TimeStamp)
  FROM WorkItems t2
  GROUP BY t2.TextField01
  )
AND TimeStamp > '2009-02-12 18:00:00'

If you're in Oracle or in MS SQL 2005 and above, then you could do:

SELECT *
FROM (
  SELECT CASE WHEN BoolField05 = 1 THEN Status ELSE 'DELETED' END AS MyStatus, t1.*,
     ROW_NUMBER() OVER (PARTITION BY TextField01 ORDER BY TimeStamp DESC) AS rn
  FROM WorkItems t1
) to
WHERE rn = 1

, it's more efficient.

Convert Unicode data to int in python

In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.

So to convert string limit="100" to a number, you need to do

limit = int(limit) # will return new object (integer) and assign to "limit"

If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:

def int_in_place(mutable):
    mutable[0] = int(mutable[0])

mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer

But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).

Multiple -and -or in PowerShell Where-Object statement

By wrapping your comparisons in {} in your first example you are creating ScriptBlocks; so the PowerShell interpreter views it as Where-Object { <ScriptBlock> -and <ScriptBlock> }. Since the -and operator operates on boolean values, PowerShell casts the ScriptBlocks to boolean values. In PowerShell anything that is not empty, zero or null is true. The statement then looks like Where-Object { $true -and $true } which is always true.

Instead of using {}, use parentheses ().

Also you want to use -eq instead of -match since match uses regex and will be true if the pattern is found anywhere in the string (try: 'xlsx' -match 'xls').

Invoke-Command -computername SERVERNAME { 
    Get-ChildItem -path E:\dfsroots\datastore2\public | 
        Where-Object {($_.extension -eq ".xls" -or $_.extension -eq ".xlk") -and ($_.creationtime -ge "06/01/2014")}
}

A better option is to filter the extensions at the Get-ChildItem command.

Invoke-Command -computername SERVERNAME { 
    Get-ChildItem -path E:\dfsroots\datastore2\public\* -Include *.xls, *.xlk | 
        Where-Object {$_.creationtime -ge "06/01/2014"}
}

How to create a fixed-size array of objects

If what you want is a fixed size array, and initialize it with nil values, you can use an UnsafeMutableBufferPointer, allocate memory for 64 nodes with it, and then read/write from/to the memory by subscripting the pointer type instance. This also has the benefit of avoiding checking if the memory must be reallocated, which Array does. I would however be surprised if the compiler doesn't optimize that away for arrays that don't have any more calls to methods that may require resizing, other than at the creation site.

let count = 64
let sprites = UnsafeMutableBufferPointer<SKSpriteNode>.allocate(capacity: count)

for i in 0..<count {
    sprites[i] = ...
}

for sprite in sprites {
    print(sprite!)
}

sprites.deallocate()

This is however not very user friendly. So, let's make a wrapper!

class ConstantSizeArray<T>: ExpressibleByArrayLiteral {
    
    typealias ArrayLiteralElement = T
    
    private let memory: UnsafeMutableBufferPointer<T>
    
    public var count: Int {
        get {
            return memory.count
        }
    }
    
    private init(_ count: Int) {
        memory = UnsafeMutableBufferPointer.allocate(capacity: count)
    }
    
    public convenience init(count: Int, repeating value: T) {
        self.init(count)
        
        memory.initialize(repeating: value)
    }
    
    public required convenience init(arrayLiteral: ArrayLiteralElement...) {
        self.init(arrayLiteral.count)
        
        memory.initialize(from: arrayLiteral)
    }
    
    deinit {
        memory.deallocate()
    }
    
    public subscript(index: Int) -> T {
        set(value) {
            precondition((0...endIndex).contains(index))
            
            memory[index] = value;
        }
        get {
            precondition((0...endIndex).contains(index))
            
            return memory[index]
        }
    }
}

extension ConstantSizeArray: MutableCollection {
    public var startIndex: Int {
        return 0
    }
    
    public var endIndex: Int {
        return count - 1
    }
    
    func index(after i: Int) -> Int {
        return i + 1;
    }
}

Now, this is a class, and not a structure, so there's some reference counting overhead incurred here. You can change it to a struct instead, but because Swift doesn't provide you with an ability to use copy initializers and deinit on structures, you'll need a deallocation method (func release() { memory.deallocate() }), and all copied instances of the structure will reference the same memory.

Now, this class may just be good enough. Its use is simple:

let sprites = ConstantSizeArray<SKSpriteNode?>(count: 64, repeating: nil)

for i in 0..<sprites.count {
    sprite[i] = ...
}

for sprite in sprites {
    print(sprite!)
}

For more protocols to implement conformance to, see the Array documentation (scroll to Relationships).

Can you use if/else conditions in CSS?

You can use php if you write css in the Tag

<style>
    section {
        position: fixed;
        top: <?php if ($test == $tset) { echo '10px' }; ?>;
    }
</style

How Do I Take a Screen Shot of a UIView?

I have created usable extension for UIView to take screenshot in Swift:

extension UIView{

var screenshot: UIImage{

    UIGraphicsBeginImageContext(self.bounds.size);
    let context = UIGraphicsGetCurrentContext();
    self.layer.renderInContext(context)
    let screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenShot
}
}

To use it just type:

let screenshot = view.screenshot

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

initialize the Start property in the constructor

Start = DateTime.Now;

This worked for me when I was trying to add few new fields to the ASP .Net Identity Framework's Users table (AspNetUsers) using Code First. I updated the Class - ApplicationUser in IdentityModels.cs and I added a field lastLogin of type DateTime.

public class ApplicationUser : IdentityUser
    {
        public ApplicationUser()
        {
            CreatedOn = DateTime.Now;
            LastPassUpdate = DateTime.Now;
            LastLogin = DateTime.Now;
        }
        public String FirstName { get; set; }
        public String MiddleName { get; set; }
        public String LastName { get; set; }
        public String EmailId { get; set; }
        public String ContactNo { get; set; }
        public String HintQuestion { get; set; }
        public String HintAnswer { get; set; }
        public Boolean IsUserActive { get; set; }

        //Auditing Fields
        public DateTime CreatedOn { get; set; }
        public DateTime LastPassUpdate { get; set; }
        public DateTime LastLogin { get; set; }
    }

Django ManyToMany filter()

Just restating what Tomasz said.

There are many examples of FOO__in=... style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:

users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])

# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])

The double underscore (__) syntax is used all over the place when working with querysets.

how to create a Java Date object of midnight today and midnight tomorrow?

java.util.Calendar

// today    
Calendar date = new GregorianCalendar();
// reset hour, minutes, seconds and millis
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);

// next day
date.add(Calendar.DAY_OF_MONTH, 1);

JDK 8 - java.time.LocalTime and java.time.LocalDate

LocalTime midnight = LocalTime.MIDNIGHT;
LocalDate today = LocalDate.now(ZoneId.of("Europe/Berlin"));
LocalDateTime todayMidnight = LocalDateTime.of(today, midnight);
LocalDateTime tomorrowMidnight = todayMidnight.plusDays(1);

Joda-Time

If you're using a JDK < 8, I recommend Joda Time, because the API is really nice:

DateTime date = new DateTime().toDateMidnight().toDateTime();
DateTime tomorrow = date.plusDays(1);

Since version 2.3 of Joda Time DateMidnight is deprecated, so use this:

DateTime today = new DateTime().withTimeAtStartOfDay();
DateTime tomorrow = today.plusDays(1).withTimeAtStartOfDay();

Pass a time zone if you don't want the JVM’s current default time zone.

DateTimeZone timeZone = DateTimeZone.forID("America/Montreal");
DateTime today = new DateTime(timeZone).withTimeAtStartOfDay(); // Pass time zone to constructor.

Regex to extract substring, returning 2 results for some reason

match returns an array.

The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:

var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test[1]);

EOFException - how to handle?

Alternatively, you could write out the number of elements first (as a header) using:

out.writeInt(prices.length);

When you read the file, you first read the header (element count):

int elementCount = in.readInt();

for (int i = 0; i < elementCount; i++) {
     // read elements
}

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Mac OS apps cannot read bash environment variables. Look at this question Setting environment variables in OS X? to expose M2_HOME to all applications including IntelliJ. You do need to restart after doing this.

How does one target IE7 and IE8 with valid CSS?

Explicitly Target IE versions without hacks using HTML and CSS

Use this approach if you don't want hacks in your CSS. Add a browser-unique class to the <html> element so you can select based on browser later.

Example

<!doctype html>
<!--[if IE]><![endif]-->
<!--[if lt IE 7 ]> <html lang="en" class="ie6">    <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="ie7">    <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="ie8">    <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="ie9">    <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
    <head></head>
    <body></body>
</html>

Then in your CSS you can very strictly access your target browser.

Example

.ie6 body { 
    border:1px solid red;
}
.ie7 body { 
    border:1px solid blue;
}

For more information check out http://html5boilerplate.com/

Target IE versions with CSS "Hacks"

More to your point, here are the hacks that let you target IE versions.

Use "\9" to target IE8 and below.
Use "*" to target IE7 and below.
Use "_" to target IE6.

Example:

body { 
border:1px solid red; /* standard */
border:1px solid blue\9; /* IE8 and below */
*border:1px solid orange; /* IE7 and below */
_border:1px solid blue; /* IE6 */
}

Update: Target IE10

IE10 does not recognize the conditional statements so you can use this to apply an "ie10" class to the <html> element

<!doctype html>
    <html lang="en">
    <!--[if !IE]><!--><script>if (/*@cc_on!@*/false) {document.documentElement.className+=' ie10';}</script><!--<![endif]-->
        <head></head>
        <body></body>
</html>

libxml/tree.h no such file or directory

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

How to center body on a page?

Also apply text-align: center; on the html element like so:

html {
  text-align: center;
}

A better approach though is to have an inner container div, which will be centralized, and not the body.

How to get a substring of text?

if you need it in rails you can use first (source code)

'1234567890'.first(5) # => "12345"

there is also last (source code)

'1234567890'.last(2) # => "90"

alternatively check from/to (source code):

"hello".from(1).to(-2) # => "ell"

Understanding the Gemfile.lock file

in regards to the exclamation mark I just found out it's on gems fetched via :git, e.g.

gem "foo", :git => "[email protected]:company/foo.git"

How to declare a variable in a PostgreSQL query

There is no such feature in PostgreSQL. You can do it only in pl/PgSQL (or other pl/*), but not in plain SQL.

An exception is WITH () query which can work as a variable, or even tuple of variables. It allows you to return a table of temporary values.

WITH master_user AS (
    SELECT
      login,
      registration_date
    FROM users
    WHERE ...
)

SELECT *
FROM users
WHERE master_login = (SELECT login
                      FROM master_user)
      AND (SELECT registration_date
           FROM master_user) > ...;

How to compare type of an object in Python?

First, avoid all type comparisons. They're very, very rarely necessary. Sometimes, they help to check parameter types in a function -- even that's rare. Wrong type data will raise an exception, and that's all you'll ever need.

All of the basic conversion functions will map as equal to the type function.

type(9) is int
type(2.5) is float
type('x') is str
type(u'x') is unicode
type(2+3j) is complex

There are a few other cases.

isinstance( 'x', basestring )
isinstance( u'u', basestring )
isinstance( 9, int )
isinstance( 2.5, float )
isinstance( (2+3j), complex )

None, BTW, never needs any of this kind of type checking. None is the only instance of NoneType. The None object is a Singleton. Just check for None

variable is None

BTW, do not use the above in general. Use ordinary exceptions and Python's own natural polymorphism.

Make scrollbars only visible when a Div is hovered over?

This will work:

#div{
     max-height:300px;
     overflow:hidden;
}
#div:hover{
     overflow-y:scroll;
}

getResourceAsStream returns null

@Emracool... I'd suggest you an alternative. Since you seem to be trying to load a *.txt file. Better to use FileInputStream() rather then this annoying getClass().getClassLoader().getResourceAsStream() or getClass().getResourceAsStream(). At least your code will execute properly.

Count the number of times a string appears within a string

Probably not the most efficient, but think it's a neat way to do it.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true"));
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "false"));

    }

    static Int32 CountAllTheTimesThisStringAppearsInThatString(string orig, string find)
    {
        var s2 = orig.Replace(find,"");
        return (orig.Length - s2.Length) / find.Length;
    }
}

n-grams in python, four, five, six grams?

You can easily whip up your own function to do this using itertools:

from itertools import izip, islice, tee
s = 'spam and eggs'
N = 3
trigrams = izip(*(islice(seq, index, None) for index, seq in enumerate(tee(s, N))))
list(trigrams)
# [('s', 'p', 'a'), ('p', 'a', 'm'), ('a', 'm', ' '),
# ('m', ' ', 'a'), (' ', 'a', 'n'), ('a', 'n', 'd'),
# ('n', 'd', ' '), ('d', ' ', 'e'), (' ', 'e', 'g'),
# ('e', 'g', 'g'), ('g', 'g', 's')]

What is unit testing and how do you do it?

What exactly IS unit testing? Is it built into code or run as separate programs? Or something else?

From MSDN: The primary goal of unit testing is to take the smallest piece of testable software in the application, isolate it from the remainder of the code, and determine whether it behaves exactly as you expect.

Essentially, you are writing small bits of code to test the individual bits of your code. In the .net world, you would run these small bits of code using something like NUnit or MBunit or even the built in testing tools in visual studio. In Java you might use JUnit. Essentially the test runners will build your project, load and execute the unit tests and then let you know if they pass or fail.

How do you do it?

Well it's easier said than done to unit test. It takes quite a bit of practice to get good at it. You need to structure your code in a way that makes it easy to unit test to make your tests effective.

When should it be done? Are there times or projects not to do it? Is everything unit-testable?

You should do it where it makes sense. Not everything is suited to unit testing. For example UI code is very hard to unit test and you often get little benefit from doing so. Business Layer code however is often very suitable for tests and that is where most unit testing is focused.

Unit testing is a massive topic and to fully get an understanding of how it can best benefit you I'd recommend getting hold of a book on unit testing such as "Test Driven Development by Example" which will give you a good grasp on the concepts and how you can apply them to your code.

"This operation requires IIS integrated pipeline mode."

I was having the same issue and I solved it doing the following:

  1. In Visual Studio, select "Project properties".

  2. Select the "Web" Tab.

  3. Select "Use Local IIS Web server".

  4. Check "Use IIS Express"

Python Pandas counting and summing specific conditions

You didn't mention the fancy indexing capabilities of dataframes, e.g.:

>>> df = pd.DataFrame({"class":[1,1,1,2,2], "value":[1,2,3,4,5]})
>>> df[df["class"]==1].sum()
class    3
value    6
dtype: int64
>>> df[df["class"]==1].sum()["value"]
6
>>> df[df["class"]==1].count()["value"]
3

You could replace df["class"]==1by another condition.

How can I specify my .keystore file with Spring Boot and Tomcat?

Starting with Spring Boot 1.2, you can configure SSL using application.properties or application.yml. Here's an example for application.properties:

server.port = 8443
server.ssl.key-store = classpath:keystore.jks
server.ssl.key-store-password = secret
server.ssl.key-password = another-secret

Same thing with application.yml:

server:
  port: 8443
  ssl:
    key-store: classpath:keystore.jks
    key-store-password: secret
    key-password: another-secret

Here's a link to the current reference documentation.

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

For use the syntax like return Post::getAll(); you should have a magic function __callStatic in your class where handle all static calls:

public static function __callStatic($method, $parameters)
{
    return (new static)->$method(...$parameters);
}

How do you store Java objects in HttpSession?

You are not adding the object to the session, instead you are adding it to the request.
What you need is:

HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);

In Servlets you have 4 scopes where you can store data.

  1. Application
  2. Session
  3. Request
  4. Page

Make sure you understand these. For more look here

how to pass list as parameter in function

You need to do it like this,

void Yourfunction(List<DateTime> dates )
{

}

How does the communication between a browser and a web server take place?

Your browser is sitting on top of TCP/IP, as the web is based on standards, usually port 80, what happens is when you enter an address, such as google.com, your computer where the browser is running on, creates packets of data, encapsulated at each layer accordingly to the OSI standards, (think of envelopes of different sizes, packed into each envelope of next size), OSI defines 7 layers, in one of the envelopes contains the source address and destination address(that is the website) encoded in binary.

As it reaches the 1st layer, in OSI terms, it gets transmitted across the media transmitter (such as cable, DSL).

If you are connected via ISP, the layered pack of envelopes gets transmitted to the ISP, the ISP's network system, peeks through the layered pack of envelopes by decoding in reverse order to find out the address, then the ISP checks their Domain Name System database to find out if they have a route to that address (cached in memory, if it does, it forwards it across the internet network - again layered pack of envelopes).

If it doesn't, the ISP interrogates the top level DNS server to say 'Hey, get me the route for the address as supplied by you, ie. the browser', the top level DNS server then passes the route to the ISP which is then stored in the ISP's server memory.

The layered pack of envelopes are transmitted and received by the website server after successful routing of the packets (think of routing as signposts for directions to get to the server), which in turn, unpacks the layered pack of envelopes, extracts the source address and says 'Aha, that is for me, right, I know the destination address (that is you, the browser), then the server packetizes the webpages into a packed layered envelopes and sends it back (usually in reverse route, but not always the case).

Your browser than receives the packetized envelopes and unpacks each of them. Then your computer descrambles the data and your browser renders the pages on the screen.

I hope this answer is sufficient enough for your understanding.

How to run ~/.bash_profile in mac terminal

As @kojiro said, you don't want to "run" this file. Source it as he says. It should get "sourced" at startup. Sourcing just means running every line in the file, including the one you want to get run. If you want to make sure a folder is in a certain path environment variable (as it seems you want from one of your comments on another solution), execute

$ echo $PATH

At the command line. If you want to check that your ~/.bash_profile is being sourced, either at startup as it should be, or when you source it manually, enter the following line into your ~/.bash_profile file:

$ echo "Hello I'm running stuff in the ~/.bash_profile!"

React JSX: selecting "selected" on selected <select> option

With React 16.8. We can do this with hooks like the following example

Codesandbox link

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const options = [
    "Monty Python and the Holy Grail",
    "Monty Python's Life of Brian",
    "Monty Python's The Meaning of Life"
  ];
  const filmsByTati = [
    {
      id: 1,
      title: "Jour de fête",
      releasedYear: 1949
    },
    {
      id: 2,
      title: "Play time",
      releasedYear: 1967
    },
    {
      id: 3,
      releasedYear: 1958,
      title: "Mon Oncle"
    }
  ];
  const [selectedOption, setSelectedOption] = useState(options[0]);
  const [selectedTatiFilm, setSelectedTatiFilm] = useState(filmsByTati[0]);
  return (
    <div className="App">
      <h1>Select Example</h1>
      <select
        value={selectedOption}
        onChange={(e) => setSelectedOption(e.target.value)}
      >
        {options.map((option) => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </select>
      <span>Selected option: {selectedOption}</span>

      <select
        value={selectedTatiFilm}
        onChange={(e) =>
          setSelectedTatiFilm(
            filmsByTati.find(film => (film.id == e.target.value))
          )
        }
      >
        {filmsByTati.map((film) => (
          <option key={film.id} value={film.id}>
            {film.title}
          </option>
        ))}
      </select>
      <span>Selected option: {selectedTatiFilm.title}</span>
    </div>
  );
}

HTML5 Form Input Pattern Currency Format

How about :

^\d+\.\d{2}$

This matches one or more digits, a dot and 2 digits after the dot.

To match also comma as thousands delimiter :

^\d+(?:,\d{3})*\.\d{2}$

Using IQueryable with Linq

Marc Gravell's answer is very complete, but I thought I'd add something about this from the user's point of view, as well...


The main difference, from a user's perspective, is that, when you use IQueryable<T> (with a provider that supports things correctly), you can save a lot of resources.

For example, if you're working against a remote database, with many ORM systems, you have the option of fetching data from a table in two ways, one which returns IEnumerable<T>, and one which returns an IQueryable<T>. Say, for example, you have a Products table, and you want to get all of the products whose cost is >$25.

If you do:

 IEnumerable<Product> products = myORM.GetProducts();
 var productsOver25 = products.Where(p => p.Cost >= 25.00);

What happens here, is the database loads all of the products, and passes them across the wire to your program. Your program then filters the data. In essence, the database does a SELECT * FROM Products, and returns EVERY product to you.

With the right IQueryable<T> provider, on the other hand, you can do:

 IQueryable<Product> products = myORM.GetQueryableProducts();
 var productsOver25 = products.Where(p => p.Cost >= 25.00);

The code looks the same, but the difference here is that the SQL executed will be SELECT * FROM Products WHERE Cost >= 25.

From your POV as a developer, this looks the same. However, from a performance standpoint, you may only return 2 records across the network instead of 20,000....

mysql query: SELECT DISTINCT column1, GROUP BY column2

you can use COUNT(DISTINCT ip), this will only count distinct values

Get folder name from full file path

In this case the file which you want to get is stored in the strpath variable:

string strPath = Server.MapPath(Request.ApplicationPath) + "/contents/member/" + strFileName;

How to get input text value on click in ReactJS

There are two ways to go about doing this.

  1. Create a state in the constructor that contains the text input. Attach an onChange event to the input box that updates state each time. Then onClick you could just alert the state object.

  2. handleClick: function() { alert(this.refs.myInput.value); },

How to use DISTINCT and ORDER BY in same SELECT statement?

If the output of MAX(CreationDate) is not wanted - like in the example of the original question - the only answer is the second statement of Prashant Gupta's answer:

SELECT [Category] FROM [MonitoringJob] 
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC

Explanation: you can't use the ORDER BY clause in an inline function, so the statement in the answer of Prutswonder is not useable in this case, you can't put an outer select around it and discard the MAX(CreationDate) part.

How to get list of all installed packages along with version in composer?

If you want to install Symfony2.2, you can see the complete change in your composer.json on the Symfony blog.

Just update your file according to that and run composer update after that. That will install all new dependencies and Symfony2.2 on your project.


If you don't want to update to Symfony2.2, but have dependency errors, you should post these, so we can help you further.

JSLint says "missing radix parameter"

It always a good practice to pass radix with parseInt -

parseInt(string, radix)

For decimal -

parseInt(id.substring(id.length - 1), 10)

If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with "0x", the radix is 16 (hexadecimal)
  • If the string begins with "0", the radix is 8 (octal). This feature is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)

(Reference)

How to list all functions in a Python module?

Use the inspect module:

from inspect import getmembers, isfunction

from somemodule import foo
print(getmembers(foo, isfunction))

Also see the pydoc module, the help() function in the interactive interpreter and the pydoc command-line tool which generates the documentation you are after. You can just give them the class you wish to see the documentation of. They can also generate, for instance, HTML output and write it to disk.

How To Include CSS and jQuery in my WordPress plugin?

Accepted answer is incomplete. You should use the right hook: wp_enqueue_scripts

Example:

    function add_my_css_and_my_js_files(){
        wp_enqueue_script('your-script-name', $this->urlpath  . '/your-script-filename.js', array('jquery'), '1.2.3', true);
        wp_enqueue_style( 'your-stylesheet-name', plugins_url('/css/new-style.css', __FILE__), false, '1.0.0', 'all');
    }
    add_action('wp_enqueue_scripts', "add_my_css_and_my_js_files");

How to compile and run C files from within Notepad++ using NppExec plugin?

I've made a single powerfull script that will:

-Compile and run multi language code like C, C++, Java, Python and C#.
-Delete the old executable before compiling code.
-Only run the code if it's compiled successfully.

I've also made a very noob friendly tutorial Transform Notepad++ to Powerful Multi Languages IDE which contains some additional scripts like to only run or Compile the code, run code inside CMD etc.

npp_console 1               //open console
NPP_CONSOLE -               //disable output of commands
npe_console m-              //disable unnecessary output
con_colour bg= 191919 fg= F5F5F5    //set console colors
npp_save                //save the file
cd $(CURRENT_DIRECTORY)         //follow current directory
NPP_CONSOLE +               //enable output
IF $(EXT_PART)==.c GOTO C       //if .c file goto C label
IF $(EXT_PART)==.cpp GOTO CPP       //if .cpp file goto CPP label
IF $(EXT_PART)==.java GOTO JAVA     //if .java file goto JAVA label
IF $(EXT_PART)==.cs GOTO C#     //if .cs file goto C# label
IF $(EXT_PART)==.py GOTO PYTHON     //if .py file goto PYTHON label
echo FILE SAVED
GOTO EXITSCRIPT             // else treat it as a text file and goto EXITSCRIPT
//C label
:C                                                                  
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"//delete existing executable file if exists
gcc "$(FILE_NAME)" -o $(NAME_PART)              //compile file
IF $(EXITCODE) != 0 GOTO EXITSCRIPT             //if any compilation error then abort
echo C CODE COMPILED SUCCESSFULLY:              //print message on console
$(NAME_PART)                                            //run file in cmd, set color to green and pause cmd after output
GOTO EXITSCRIPT                         //finally exits

:CPP
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"
g++ "$(FILE_NAME)" -o $(NAME_PART)
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo C++ CODE COMPILED SUCCESSFULLY:
$(NAME_PART)
GOTO EXITSCRIPT

:JAVA
cmd /C if exist "$(NAME_PART).class" cmd /c del "$(NAME_PART).class"
javac $(FILE_NAME) -Xlint
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo JAVA CODE COMPILED SUCCESSFULLY:
java $(NAME_PART)
GOTO EXITSCRIPT

:C#
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"
csc $(FILE_NAME)
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo C# CODE COMPILED SUCCESSFULLY:
$(NAME_PART)
GOTO EXITSCRIPT

:PYTHON
echo RUNNING PYTHON SCRIPT IN CMD:              //python is a script so no need to compile
python $(NAME_PART).py
GOTO EXITSCRIPT

:EXITSCRIPT
// that's all, folks!

Best practice multi language website

I had the same probem a while ago, before starting using Symfony framework.

  1. Just use a function __() which has arameters pageId (or objectId, objectTable described in #2), target language and an optional parameter of fallback (default) language. The default language could be set in some global config in order to have an easier way to change it later.

  2. For storing the content in database i used following structure: (pageId, language, content, variables).

    • pageId would be a FK to your page you want to translate. if you have other objects, like news, galleries or whatever, just split it into 2 fields objectId, objectTable.

    • language - obviously it would store the ISO language string EN_en, LT_lt, EN_us etc.

    • content - the text you want to translate together with the wildcards for variable replacing. Example "Hello mr. %%name%%. Your account balance is %%balance%%."

    • variables - the json encoded variables. PHP provides functions to quickly parse these. Example "name: Laurynas, balance: 15.23".

    • you mentioned also slug field. you could freely add it to this table just to have a quick way to search for it.

  3. Your database calls must be reduced to minimum with caching the translations. It must be stored in PHP array, because it is the fastest structure in PHP language. How you will make this caching is up to you. From my experience you should have a folder for each language supported and an array for each pageId. The cache should be rebuilt after you update the translation. ONLY the changed array should be regenerated.

  4. i think i answered that in #2

  5. your idea is perfectly logical. this one is pretty simple and i think will not make you any problems.

URLs should be translated using the stored slugs in the translation table.

Final words

it is always good to research the best practices, but do not reinvent the wheel. just take and use the components from well known frameworks and use them.

take a look at Symfony translation component. It could be a good code base for you.

What is reflection and why is it useful?

Reflection is a set of functions which allows you to access the runtime information of your program and modify it behavior (with some limitations).

It's useful because it allows you to change the runtime behavior depending on the meta information of your program, that is, you can check the return type of a function and change the way you handle the situation.

In C# for example you can load an assembly (a .dll) in runtime an examine it, navigating through the classes and taking actions according to what you found. It also let you create an instance of a class on runtime, invoke its method, etc.

Where can it be useful? Is not useful every time but for concrete situations. For example you can use it to get the name of the class for logging purposes, to dynamically create handlers for events according to what's specified on a configuration file and so on...

Difference between Hive internal tables and external tables?

The only difference in behaviour (not the intended usage) based on my limited research and testing so far (using Hive 1.1.0 -cdh5.12.0) seems to be that when a table is dropped

  • the data of the Internal (Managed) tables gets deleted from the HDFS file system
  • while the data of the External tables does NOT get deleted from the HDFS file system.

(NOTE: See Section 'Managed and External Tables' in https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL which list some other difference which I did not completely understand)

I believe Hive chooses the location where it needs to create the table based on the following precedence from top to bottom

  1. Location defined during the Table Creation
  2. Location defined in the Database/Schema Creation in which the table is created.
  3. Default Hive Warehouse Directory (Property hive.metastore.warehouse.dir in hive.site.xml)

When the "Location" option is not used during the "creation of a hive table", the above precedence rule is used. This is applicable for both Internal and External tables. This means an Internal table does not necessarily have to reside in the Warehouse directory and can reside anywhere else.

Note: I might have missed some scenarios, but based on my limited exploration, the behaviour of both Internal and Extenal table seems to be the same except for the one difference (data deletion) described above. I tried the following scenarios for both Internal and External tables.

  1. Creating table with and without Location option
  2. Creating table with and without Partition Option
  3. Adding new data using the Hive Load and Insert Statements
  4. Adding data files to the Table location outside of Hive (using HDFS commands) and refreshing the table using the "MSCK REPAIR TABLE command
  5. Dropping the tables

Find and replace specific text characters across a document with JS

How about this, replacing @ with $:

$("body").children().each(function () {
    $(this).html( $(this).html().replace(/@/g,"$") );
});

http://jsfiddle.net/maximua/jp96C/1/

Finding absolute value of a number without using Math.abs()

If you look inside Math.abs you can probably find the best answer:

Eg, for floats:

    /*
     * Returns the absolute value of a {@code float} value.
     * If the argument is not negative, the argument is returned.
     * If the argument is negative, the negation of the argument is returned.
     * Special cases:
     * <ul><li>If the argument is positive zero or negative zero, the
     * result is positive zero.
     * <li>If the argument is infinite, the result is positive infinity.
     * <li>If the argument is NaN, the result is NaN.</ul>
     * In other words, the result is the same as the value of the expression:
     * <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))}
     *
     * @param   a   the argument whose absolute value is to be determined
     * @return  the absolute value of the argument.
     */
    public static float abs(float a) {
        return (a <= 0.0F) ? 0.0F - a : a;
    }

Reload .profile in bash shell script (in unix)?

The bash script runs in a separate subshell. In order to make this work you will need to source this other script as well.

Finding the median of an unsorted array

Let the problem be: finding the Kth largest element in an unsorted array.

Divide the array into n/5 groups where each group consisting of 5 elements.

Now a1,a2,a3....a(n/5) represent the medians of each group.

x = Median of the elements a1,a2,.....a(n/5).

Now if k<n/2 then we can remove the largets, 2nd largest and 3rd largest element of the groups whose median is greater than the x. We can now call the function again with 7n/10 elements and finding the kth largest value.

else if k>n/2 then we can remove the smallest ,2nd smallest and 3rd smallest element of the group whose median is smaller than the x. We can now call the function of again with 7n/10 elements and finding the (k-3n/10)th largest value.

Time Complexity Analysis: T(n) time complexity to find the kth largest in an array of size n.

T(n) = T(n/5) + T(7n/10) + O(n)

if you solve this you will find out that T(n) is actually O(n)

n/5 + 7n/10 = 9n/10 < n

VMWare Player vs VMWare Workstation

re: VMware Workstation support for physical disks vs virtual disks.

I run Player with the VM Disk files on their own dedicated fast hard drive, independent from the OS hard drive. This allows both the OS and Player to simultaneously independently read/write to their own drives, the performance difference is noticeable, and a second WD Black or Raptor or SSD is cheap. Placing the VM disk file on a second drive also works with Microsoft Virtual PC.

How to retrieve data from a SQL Server database in C#?

create a class called DbManager:

Class DbManager
{
 SqlConnection connection;
 SqlCommand command;

       public DbManager()
      {
        connection = new SqlConnection();
        connection.ConnectionString = @"Data Source=.     \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
        command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = CommandType.Text;
     } // constructor

 public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
     {
        bool returnvalue = false;
        try
        {
            command.CommandText = "select * from TableName where firstname=@firstname and lastname=@lastname";
            command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
 command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname; 
            connection.Open();
            SqlDataReader reader= command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {

                    lastname = reader.GetString(1);
                    firstname = reader.GetString(2);

                    age = reader.GetString(3);


                }
            }
            returnvalue = true;
        }
        catch
        { }
        finally
        {
            connection.Close();
        }
        return returnvalue;

    }

then double click the retrieve button(e.g btnretrieve) on your form and insert the following code:

 private void btnretrieve_Click(object sender, EventArgs e)
    {
        try
        {
            string lastname = null;
            string firstname = null;
            string age = null;

            DbManager db = new DbManager();

            bool status = db.GetUsersData(ref surname, ref firstname, ref age);
                if (status)
                {
                txtlastname.Text = surname;
                txtfirstname.Text = firstname;
                txtAge.Text = age;       
               }
          }
       catch
          {

          }
   }

Is an empty href valid?

Indeed, you can leave it empty (W3 validator doesn't complain).

Taking the idea one step further: leave out the ="". The advantage of this is that the link isn't treated as an anchor to the current page.

<a href>sth</a>

How do I use IValidatableObject?

I liked cocogza's answer except that calling base.IsValid resulted in a stack overflow exception as it would re-enter the IsValid method again and again. So I modified it to be for a specific type of validation, in my case it was for an e-mail address.

[AttributeUsage(AttributeTargets.Property)]
class ValidEmailAddressIfTrueAttribute : ValidationAttribute
{
    private readonly string _nameOfBoolProp;

    public ValidEmailAddressIfTrueAttribute(string nameOfBoolProp)
    {
        _nameOfBoolProp = nameOfBoolProp;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (validationContext == null)
        {
            return null;
        }

        var property = validationContext.ObjectType.GetProperty(_nameOfBoolProp);
        if (property == null)
        {
            return new ValidationResult($"{_nameOfBoolProp} not found");
        }

        var boolVal = property.GetValue(validationContext.ObjectInstance, null);

        if (boolVal == null || boolVal.GetType() != typeof(bool))
        {
            return new ValidationResult($"{_nameOfBoolProp} not boolean");
        }

        if ((bool)boolVal)
        {
            var attribute = new EmailAddressAttribute {ErrorMessage = $"{value} is not a valid e-mail address."};
            return attribute.GetValidationResult(value, validationContext);
        }
        return null;
    }
}

This works much better! It doesn't crash and produces a nice error message. Hope this helps someone!

Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

OpenCV HSV range is: H: 0 to 179 S: 0 to 255 V: 0 to 255

On Gimp (or other photo manipulation sw) Hue range from 0 to 360, since opencv put color info in a single byte, the maximum number value in a single byte is 255 therefore openCV Hue values are equivalent to Hue values from gimp divided by 2.

I found when trying to do object detection based on HSV color space that a range of 5 (opencv range) was sufficient to filter out a specific color. I would advise you to use an HSV color palate to figure out the range that works best for your application.

HSV color palate with color detection in HSV space

Group By Multiple Columns

Ok got this as:

var query = (from t in Transactions
             group t by new {t.MaterialID, t.ProductID}
             into grp
                    select new
                    {
                        grp.Key.MaterialID,
                        grp.Key.ProductID,
                        Quantity = grp.Sum(t => t.Quantity)
                    }).ToList();

How to copy a file to a remote server in Python using SCP or SSH?

Try this if you wan't to use SSL certificates:

import subprocess

try:
    # Set scp and ssh data.
    connUser = 'john'
    connHost = 'my.host.com'
    connPath = '/home/john/'
    connPrivateKey = '/home/user/myKey.pem'

    # Use scp to send file from local to host.
    scp = subprocess.Popen(['scp', '-i', connPrivateKey, 'myFile.txt', '{}@{}:{}'.format(connUser, connHost, connPath)])

except CalledProcessError:
    print('ERROR: Connection to host failed!')

not:first-child selector

not(:first-child) does not seem to work anymore. At least with the more recent versions of Chrome and Firefox.

Instead, try this:

ul:not(:first-of-type) {}

Use String.split() with multiple delimiters

The string you give split is the string form of a regular expression, so:

private void getId(String pdfName){
    String[]tokens = pdfName.split("[\\-.]");
}

That means to split on any character in the [] (we have to escape - with a backslash because it's special inside []; and of course we have to escape the backslash because this is a string). (Conversely, . is normally special but isn't special inside [].)

final keyword in method parameters

If you declare any parameter as final, you cannot change the value of it.

class Bike11 {  
    int cube(final int n) {  
        n=n+2;//can't be changed as n is final  
        n*n*n;  
     }  
    public static void main(String args[]) {  
        Bike11 b=new Bike11();  
        b.cube(5);  
    }  
}   

Output: Compile Time Error

For more details, please visit my blog: http://javabyroopam.blogspot.com

How do I make a WPF TextBlock show my text on multiple lines?

Use the property TextWrapping of the TextBlock element:

<TextBlock Text="StackOverflow Forum"
           Width="100"
           TextWrapping="WrapWithOverflow"/>

What is a unix command for deleting the first N characters of a line?

I think awk would be the best tool for this as it can both filter and perform the necessary string manipulation functions on filtered lines:

tail -f logfile | awk '/org.springframework/ {print substr($0, 6)}'

or

tail -f logfile | awk '/org.springframework/ && sub(/^.{5}/,"",$0)'

How do I remove trailing whitespace using a regular expression?

If using Visual Studio 2012 and later (which uses .NET regular expressions), you can remove trailing whitespace without removing blank lines by using the following regex

Replace (?([^\r\n])\s)+(\r?\n)

With $1

Enter image description here


Some explanation

The reason you need the rather complicated expression is that the character class \s matches spaces, tabs and newline characters, so \s+ will match a group of lines containing only whitespace. It doesn't help adding a $ termination to this regex, because this will still match a group of lines containing only whitespace and newline characters.

You may also want to know (as I did) exactly what the (?([^\r\n])\s) expression means. This is an Alternation Construct, which effectively means match to the whitespace character class if it is not a carriage return or linefeed.

Alternation constructs normally have a true and false part,

(?( expression ) yes | no )

but in this case the false part is not specified.

How can I save a screenshot directly to a file in Windows?

As far as I know in XP, yes you must use some other app to actually save it.

Vista comes with the Snipping tool, that simplifies the process a bit!

_tkinter.TclError: no display name and no $DISPLAY environment variable

In order to see images, plots and anything displayed on windows on your remote machine you need to connect to it like this:

ssh -X user@hostname

That way you enable the access to the X server. The X server is a program in the X Window System that runs on local machines (i.e., the computers used directly by users) and handles all access to the graphics cards, display screens and input devices (typically a keyboard and mouse) on those computers.

More info here.

Image Greyscale with CSS & re-color on mouse-over?

I use the following code on http://www.diagnomics.com/

Smooth transition from b/w to color with magnifying effect (scale)

    img.color_flip {
      filter: url(filters.svg#grayscale); /* Firefox 3.5+ */
      filter: gray; /* IE5+ */
      -webkit-filter: grayscale(1); /* Webkit Nightlies & Chrome Canary */
      -webkit-transition: all .5s ease-in-out;
    }

    img.color_flip:hover {
      filter: none;
      -webkit-filter: grayscale(0);
      -webkit-transform: scale(1.1);
    }

SQL Server IF NOT EXISTS Usage?

Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.

set nocount on

create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)

insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)

declare @PersonID int
set @PersonID = 1

IF EXISTS    
    (
    SELECT 1    
    FROM Timesheet_Hours    
    WHERE Posted_Flag = 1    
        AND Staff_Id = @PersonID    
    )    
    BEGIN
        RAISERROR('Timesheets have already been posted!', 16, 1)
        ROLLBACK TRAN
    END
ELSE
    IF NOT EXISTS
        (
        SELECT 1
        FROM Timesheet_Hours
        WHERE Staff_Id = @PersonID
        )
        BEGIN
            RAISERROR('Default list has not been loaded!', 16, 1)
            ROLLBACK TRAN
        END
    ELSE
        print 'No problems here'

drop table Timesheet_Hours

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

Create the certificate chain file with the intermediate and root ca.

cat intermediate/certs/intermediate.cert.pem certs/ca.cert.pem > intermediate/certs/ca-chain.cert.pem

chmod 444 intermediate/certs/ca-chain.cert.pem

Then verfify

openssl verify -CAfile intermediate/certs/ca-chain.cert.pem \
  intermediate/certs/www.example.com.cert.pem

www.example.com.cert.pem: OK Deploy the certific

What is the easiest way to parse an INI file in Java?

Or with standard Java API you can use java.util.Properties:

Properties props = new Properties();
try (FileInputStream in = new FileInputStream(path)) {
    props.load(in);
}

How do I convert a float to an int in Objective C?

what's wrong with:

int myInt = myFloat;

bear in mind this'll use the default rounding rule, which is towards zero (i.e. -3.9f becomes -3)

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

The error is try to fix a Youtube error.

The solution to avoid your Javascript-Console-Error complex is to accept that Youtube (and also other webpages) can have Javascript errors that you can't fix.

That is all.

C# Remove object from list of objects

There are two problems with this code:

  • Capacity represents the number of items the list can contain before resizing is required, not the actual count; you need to use Count instead, and
  • When you remove from the list, you should go backwards, otherwise you could skip the second item when two identical items are next to each other.

500 internal server error, how to debug

Try writing all the errors to a file.

error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");

Something like that.

java Arrays.sort 2d array

It is really simple, there are just some syntax you have to keep in mind.

Arrays.sort(contests, (a, b) -> Integer.compare(a[0],b[0]));//increasing order ---1

Arrays.sort(contests, (b, a) -> Integer.compare(b[0],a[0]));//increasing order ---2

Arrays.sort(contests, (a, b) -> Integer.compare(b[0],a[0]));//decreasing order ---3

Arrays.sort(contests, (b, a) -> Integer.compare(a[0],b[0]));//decreasing order ---4

If you notice carefully, then it's the change in the order of 'a' and 'b' that affects the result. For line 1, the set is of (a,b) and Integer.compare(a[0],b[0]), so it is increasing order. Now if we change the order of a and b in any one of them, suppose the set of (a,b) and Integer.compare(b[0],a[0]) as in line 3, we get decreasing order.

Oracle ORA-12154: TNS: Could not resolve service name Error?

It has nothing to do with a space embedded in the folder structure.

I had the same problem. But when I created an environmental variable (defined both at the system- and user-level) called TNS_HOME and made it to point to the folder where TNSNAMES.ORA existed, the problem was resolved. Voila!

venki

SQL Server equivalent of MySQL's NOW()?

getdate() or getutcdate().

Using Bootstrap Tooltip with AngularJS

You can do this with AngularStrap which

is a set of native directives that enables seamless integration of Bootstrap 3.0+ into your AngularJS 1.2+ app."

You can inject the entire library like this:

var app = angular.module('MyApp', ['mgcrea.ngStrap']); 

Or only pull in the tooltip feature like this:

var app = angular.module('MyApp', ['mgcrea.ngStrap.tooltip']); 

Demo in Stack Snippets

_x000D_
_x000D_
var app = angular.module('MyApp', ['mgcrea.ngStrap']);  
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.2/angular-strap.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.2/angular-strap.tpl.min.js"></script>_x000D_
_x000D_
<div ng-app="MyApp" class="container" >_x000D_
_x000D_
  <button type="button" _x000D_
          class="btn btn-default" _x000D_
          data-trigger="hover" _x000D_
          data-placement="right"_x000D_
          data-title="Tooltip on right"_x000D_
          bs-tooltip>_x000D_
    MyButton_x000D_
  </button>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Failed to resolve: com.android.support:appcompat-v7:28.0

my problem was just network connection. using VPN solved the issue.

How to zoom in/out an UIImage object when user pinches screen?

Keep in mind that you're NEVER zooming in on a UIImage. EVER.

Instead, you're zooming in and out on the view that displays the UIImage.

In this particular case, you chould choose to create a custom UIView with custom drawing to display the image, a UIImageView which displays the image for you, or a UIWebView which will need some additional HTML to back it up.

In all cases, you'll need to implement touchesBegan, touchesMoved, and the like to determine what the user is trying to do (zoom, pan, etc.).

How do I get elapsed time in milliseconds in Ruby?

Time.now.to_f can help you but it returns seconds.

In general, when working with benchmarks I:

  • put in variable the current time;
  • insert the block to test;
  • put in a variable the current time, subtracting the preceding current-time value;

It's a very simple process, so I'm not sure you were really asking this...

How to disable mouse scroll wheel scaling with Google Maps API

A simple solution:

_x000D_
_x000D_
// DISABLE MOUSE SCROLL IN MAPS_x000D_
// enable the pointer events only on click;_x000D_
$('.gmap-wrapper').on('click', function () {_x000D_
  $('.gmap-wrapper iframe').removeClass('scrolloff'); // set the pointer events true on click_x000D_
});_x000D_
// you want to disable pointer events when the mouse leave the canvas area;_x000D_
$(".gmap-wrapper").mouseleave(function () {_x000D_
  $('.gmap-wrapper iframe').addClass('scrolloff'); // set the pointer events to none when mouse leaves the map area_x000D_
});
_x000D_
.scrolloff{ pointer-events: none; }
_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="gmap-wrapper">_x000D_
<iframe class="scrolloff" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d44754.55736493158!2d9.151166379101554!3d45.486726!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4786bfca7e8fb1cb%3A0xee8d99c9d153be98!2sCorsidia!5e0!3m2!1sit!2sit!4v1496947992608" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>_x000D_
</div>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Source: https://github.com/Corsidia/scrolloff

How to change a <select> value from JavaScript

this solved my issue, it was working fine with

var value = item[index].id;
$("#select2").val(value);

but not showing selected value, so

$("#select2").val(value).change();

works fine for me.

When is the init() function run?

See this picture. :)

import --> const --> var --> init()

  1. If a package imports other packages, the imported packages are initialized first.

  2. Current package's constant initialized then.

  3. Current package's variables are initialized then.

  4. Finally, init() function of current package is called.

A package can have multiple init functions (either in a single file or distributed across multiple files) and they are called in the order in which they are presented to the compiler.


A package will be initialised only once even if it is imported from multiple packages.

How to convert QString to std::string?

The simplest way would be QString::toStdString().

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

MVC, MVP, MVVM

MVC (old one)

MVP (more modular because of its low-coupling. Presenter is a mediator between the View and Model)

MVVM (You already have two-way binding between VM and UI component, so it is more automated than MVP) enter image description here

Another image: enter image description here

Color different parts of a RichTextBox string

Using Selection in WPF, aggregating from several other answers, no other code is required (except Severity enum and GetSeverityColor function)

 public void Log(string msg, Severity severity = Severity.Info)
    {
        string ts = "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
        string msg2 = ts + msg + "\n";
        richTextBox.AppendText(msg2);

        if (severity > Severity.Info)
        {
            int nlcount = msg2.ToCharArray().Count(a => a == '\n');
            int len = msg2.Length + 3 * (nlcount)+2; //newlines are longer, this formula works fine
            TextPointer myTextPointer1 = richTextBox.Document.ContentEnd.GetPositionAtOffset(-len);
            TextPointer myTextPointer2 = richTextBox.Document.ContentEnd.GetPositionAtOffset(-1);

            richTextBox.Selection.Select(myTextPointer1,myTextPointer2);
            SolidColorBrush scb = new SolidColorBrush(GetSeverityColor(severity));
            richTextBox.Selection.ApplyPropertyValue(TextElement.BackgroundProperty, scb);

        }

        richTextBox.ScrollToEnd();
    }

Remove Unnamed columns in pandas dataframe

The pandas.DataFrame.dropna function removes missing values (e.g. NaN, NaT).

For example the following code would remove any columns from your dataframe, where all of the elements of that column are missing.

df.dropna(how='all', axis='columns')

How to push JSON object in to array using javascript

can you try something like this. You have to put each json in the data not json[i], because in the way you are doing it you are getting and putting only the properties of each json. Put the whole json instead in the data

 var my_json;
    $.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
    console.log(json1);
        var data = [];
    json1.feeds.forEach(function(feed,i){
        console.log("\n The details of " + i + "th Object are :  \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);      
        my_json = feed;
        console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
        data.push(my_json);
    }); 

How to align the text middle of BUTTON

This is more predictable then "line-height"

_x000D_
_x000D_
.loginBtn {_x000D_
    background:url(images/loginBtn-center.jpg) repeat-x;_x000D_
    width:175px;_x000D_
    height:65px;_x000D_
    margin:20px auto;_x000D_
    border-radius:10px;_x000D_
    -webkit-border-radius:10px;_x000D_
    box-shadow:0 1px 2px #5e5d5b;_x000D_
}_x000D_
_x000D_
.loginBtn span {_x000D_
    display: block;_x000D_
    padding-top: 22px;_x000D_
    text-align: center;_x000D_
    line-height: 1em;_x000D_
}
_x000D_
<div id="loginBtn" class="loginBtn"><span>Log in</span></div>
_x000D_
_x000D_
_x000D_

EDIT (2018): use flexbox

.loginBtn {
    display: flex;
    align-items: center;
    justify-content: center;
}

Getting the Username from the HKEY_USERS values

Done it, by a bit of creative programming,

  1. Enum the Keys in HKEY_USERS for those funny number keys...

  2. Enum the keys in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\

and you will find the same numbers.... Now in those keys look at the String value: ProfileImagePath = "SomeValue" where the values are either:

"%systemroot%\system32\config\systemprofile"... not interested in this one... as its not a directory path...

%SystemDrive%\Documents and Settings\LocalService - "Local Services" %SystemDrive%\Documents and Settings\NetworkService "NETWORK SERVICE"

or

%SystemDrive%\Documents and Settings\USER_NAME, which translates directly to the "USERNAME" values in most un-tampered systems, ie. where the user has not changed the their user name after a few weeks or altered the paths explicitly...

Search for executable files using find command

So as to have another possibility1 to find the files that are executable by the current user:

find . -type f -exec test -x {} \; -print

(the test command here is the one found in PATH, very likely /usr/bin/test, not the builtin).


1 Only use this if the -executable flag of find is not available! this is subtly different from the -perm +111 solution.

JavaScript and getElementById for multiple elements with the same ID

If you're using d3 for handling multiple objects with the same class / id

You can remove a subset of class elements by using d3.selectAll(".classname");

For example the donut graph here on http://medcorp.co.nz utilizes copies of an arc object with class name "arc" and there's a single line of d3, d3.selectAll(".arc").remove(); to remove all those objects;

using document.getElementById("arc").remove(); only removes a single element and would have to be called multiple times (as is with the suggestions above he creates a loop to remove the objects n times)

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

Differences between TCP sockets and web sockets, one more time

When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.

But there are more important differences on the receiving side of things. When the receiver does a recv (or read) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.

Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.

Adding attributes to an XML node

The latest and supposedly greatest way to construct the XML is by using LINQ to XML:

using System.Xml.Linq

       var xmlNode =
            new XElement("Login",
                         new XElement("id",
                             new XAttribute("userName", "Tushar"),
                             new XAttribute("password", "Tushar"),
                             new XElement("Name", "Tushar"),
                             new XElement("Age", "24")
                         )
            );
       xmlNode.Save("Tushar.xml");

Supposedly this way of coding should be easier, as the code closely resembles the output (which Jon's example above does not). However, I found that while coding this relatively easy example I was prone to lose my way between the cartload of comma's that you have to navigate among. Visual studio's auto spacing of code does not help either.

How to empty a file using Python

Alternate form of the answer by @rumpel

with open(filename, 'w'): pass

How to "add existing frameworks" in Xcode 4?

As per Apple's documentation:

  1. In the project navigator, select your project.
  2. Select your target.
  3. Select the "Build Phases" tab.
  4. Open "Link Binaries With Libraries" expander.
  5. Click the + button.
  6. Select your framework.
  7. (optional) Drag and drop the added framework to the "Frameworks" group.

SQLite - UPSERT *not* INSERT or REPLACE

The best approach I know is to do an update, followed by an insert. The "overhead of a select" is necessary, but it is not a terrible burden since you are searching on the primary key, which is fast.

You should be able to modify the below statements with your table & field names to do what you want.

--first, update any matches
UPDATE DESTINATION_TABLE DT
SET
  MY_FIELD1 = (
              SELECT MY_FIELD1
              FROM SOURCE_TABLE ST
              WHERE ST.PRIMARY_KEY = DT.PRIMARY_KEY
              )
 ,MY_FIELD2 = (
              SELECT MY_FIELD2
              FROM SOURCE_TABLE ST
              WHERE ST.PRIMARY_KEY = DT.PRIMARY_KEY
              )
WHERE EXISTS(
            SELECT ST2.PRIMARY_KEY
            FROM
              SOURCE_TABLE ST2
             ,DESTINATION_TABLE DT2
            WHERE ST2.PRIMARY_KEY = DT2.PRIMARY_KEY
            );

--second, insert any non-matches
INSERT INTO DESTINATION_TABLE(
  MY_FIELD1
 ,MY_FIELD2
)
SELECT
  ST.MY_FIELD1
 ,NULL AS MY_FIELD2  --insert NULL into this field
FROM
  SOURCE_TABLE ST
WHERE NOT EXISTS(
                SELECT DT2.PRIMARY_KEY
                FROM DESTINATION_TABLE DT2
                WHERE DT2.PRIMARY_KEY = ST.PRIMARY_KEY
                );

Best way to select random rows PostgreSQL

Add a column called r with type serial. Index r.

Assume we have 200,000 rows, we are going to generate a random number n, where 0 < n <= 200, 000.

Select rows with r > n, sort them ASC and select the smallest one.

Code:

select * from YOUR_TABLE 
where r > (
    select (
        select reltuples::bigint AS estimate
        from   pg_class
        where  oid = 'public.YOUR_TABLE'::regclass) * random()
    )
order by r asc limit(1);

The code is self-explanatory. The subquery in the middle is used to quickly estimate the table row counts from https://stackoverflow.com/a/7945274/1271094 .

In application level you need to execute the statement again if n > the number of rows or need to select multiple rows.

Is there a stopwatch in Java?

Simple out of the box Stopwatch class:

import java.time.Duration;
import java.time.Instant;

public class StopWatch {

    Instant startTime, endTime;
    Duration duration;
    boolean isRunning = false;

    public void start() {
        if (isRunning) {
            throw new RuntimeException("Stopwatch is already running.");
        }
        this.isRunning = true;
        startTime = Instant.now();
    }

    public Duration stop() {
        this.endTime = Instant.now();
        if (!isRunning) {
            throw new RuntimeException("Stopwatch has not been started yet");
        }
        isRunning = false;
        Duration result = Duration.between(startTime, endTime);
        if (this.duration == null) {
            this.duration = result;
        } else {
            this.duration = duration.plus(result);
        }

        return this.getElapsedTime();
    }

    public Duration getElapsedTime() {
        return this.duration;
    }

    public void reset() {
        if (this.isRunning) {
            this.stop();
        }
        this.duration = null;
    }
}

Usage:

StopWatch sw = new StopWatch();
sw.start();
    // doWork()
sw.stop();
System.out.println( sw.getElapsedTime().toMillis() + "ms");

How do I install Eclipse Marketplace in Eclipse Classic?

The steps below are for Eclipse Indigo Classic Version.

  1. Help->Install New Software...
  2. Point to Eclipse Indigo Site, If not available add the site "Indigo - http://download.eclipse.org/releases/indigo"
  3. Work with the above site
  4. Look at "General Purpose Tools"->Marketplace Client
  5. After installing, restart Eclipse and you can find Marketplace in "Help->Eclipse Marketplace..."

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

None of the above helped for me.

I am using Kubernetes on Google Cloud with tesla k-80 gpu.

Follow along this guide to ensure you installed everything correctly: https://cloud.google.com/kubernetes-engine/docs/how-to/gpus

I was missing few important things:

  1. Installing NVIDIA GPU device drivers On your NODES. To do this use:

For COS node:

kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/container-engine-accelerators/master/nvidia-driver-installer/cos/daemonset-preloaded.yaml

For UBUNTU node:

kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/container-engine-accelerators/master/nvidia-driver-installer/ubuntu/daemonset-preloaded.yaml

Make sure an update was rolled to your nodes. Restart them if upgrades are off.

  1. I use this image nvidia/cuda:10.1-base-ubuntu16.04 in my docker

  2. You have to set gpu limit! This is the only way the node driver can communicate with the pod. In your yaml configuration add this under your container:

    resources:
      limits:
        nvidia.com/gpu: 1
    

Spring Data JPA map the native query result to Non-Entity POJO

In my computer, I get this code works.It's a little different from Daimon's answer.

_x000D_
_x000D_
@SqlResultSetMapping(_x000D_
    name="groupDetailsMapping",_x000D_
    classes={_x000D_
        @ConstructorResult(_x000D_
            targetClass=GroupDetails.class,_x000D_
            columns={_x000D_
                @ColumnResult(name="GROUP_ID",type=Integer.class),_x000D_
                @ColumnResult(name="USER_ID",type=Integer.class)_x000D_
            }_x000D_
        )_x000D_
    }_x000D_
)_x000D_
_x000D_
@NamedNativeQuery(name="User.getGroupDetails", query="SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", resultSetMapping="groupDetailsMapping")
_x000D_
_x000D_
_x000D_

How to center a checkbox in a table cell?

If you don't support legacy browsers, I'd use flexbox because it's well supported and will simply solve most of your layout problems.

#table-id td:nth-child(1) { 
    /* nth-child(1) is the first column, change to fit your needs */
    display: flex;
    justify-content: center;
}

This centers all content in the first <td> of every row.

What are the obj and bin folders (created by Visual Studio) used for?

Be careful with setup projects if you're using them; Visual Studio setup projects Primary Output pulls from the obj folder rather than the bin.

I was releasing applications I thought were obfuscated and signed in msi setups for quite a while before I discovered that the deployed application files were actually neither obfuscated nor signed as I as performing the post-build procedure on the bin folder assemblies and should have been targeting the obj folder assemblies instead.

This is far from intuitive imho, but the general setup approach is to use the Primary Output of the project and this is the obj folder. I'd love it if someone could shed some light on this btw.

Correct way of getting Client's IP Addresses from http.Request

According to Mozilla MDN: "The X-Forwarded-For (XFF) header is a de-facto standard header for identifying the originating IP address of a client."
They publish clear information in their X-Forwarded-For article.

How to show an empty view with a RecyclerView?

For my projects I made this solution (RecyclerView with setEmptyView method):

public class RecyclerViewEmptySupport extends RecyclerView {
    private View emptyView;

    private AdapterDataObserver emptyObserver = new AdapterDataObserver() {


        @Override
        public void onChanged() {
            Adapter<?> adapter =  getAdapter();
            if(adapter != null && emptyView != null) {
                if(adapter.getItemCount() == 0) {
                    emptyView.setVisibility(View.VISIBLE);
                    RecyclerViewEmptySupport.this.setVisibility(View.GONE);
                }
                else {
                    emptyView.setVisibility(View.GONE);
                    RecyclerViewEmptySupport.this.setVisibility(View.VISIBLE);
                }
            }

        }
    };

    public RecyclerViewEmptySupport(Context context) {
        super(context);
    }

    public RecyclerViewEmptySupport(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RecyclerViewEmptySupport(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setAdapter(Adapter adapter) {
        super.setAdapter(adapter);

        if(adapter != null) {
            adapter.registerAdapterDataObserver(emptyObserver);
        }

        emptyObserver.onChanged();
    }

    public void setEmptyView(View emptyView) {
        this.emptyView = emptyView;
    }
}

And you should use it instead of RecyclerView class:

<com.maff.utils.RecyclerViewEmptySupport android:id="@+id/list1"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    />

<TextView android:id="@+id/list_empty"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Empty"
    />

and

RecyclerViewEmptySupport list = 
    (RecyclerViewEmptySupport)rootView.findViewById(R.id.list1);
list.setLayoutManager(new LinearLayoutManager(context));
list.setEmptyView(rootView.findViewById(R.id.list_empty));

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

If you are on unix-like systems.

Starting in MongoDB 4.4, a startup error is generated if the ulimit value for number of open files is under 64000. View the current val

$ ulimit -n

Change value

$ ulimit -n <val>

Nginx: stat() failed (13: permission denied)

This is how i fixed this

sudo chmod o+x /home/ec2-user

How can you find out which process is listening on a TCP or UDP port on Windows?

  1. Open a command prompt window (as Administrator) From "Start\Search box" Enter "cmd" then right-click on "cmd.exe" and select "Run as Administrator"

  2. Enter the following text then hit Enter.

    netstat -abno

    -a Displays all connections and listening ports.

    -b Displays the executable involved in creating each connection or listening port. In some cases well-known executables host multiple independent components, and in these cases the sequence of components involved in creating the connection or listening port is displayed. In this case the executable name is in [] at the bottom, on top is the component it called, and so forth until TCP/IP was reached. Note that this option can be time-consuming and will fail unless you have sufficient permissions.

    -n Displays addresses and port numbers in numerical form.

    -o Displays the owning process ID associated with each connection.

  3. Find the Port that you are listening on under "Local Address"

  4. Look at the process name directly under that.

NOTE: To find the process under Task Manager

  1. Note the PID (process identifier) next to the port you are looking at.

  2. Open Windows Task Manager.

  3. Select the Processes tab.

  4. Look for the PID you noted when you did the netstat in step 1.

    • If you don’t see a PID column, click on View / Select Columns. Select PID.

    • Make sure “Show processes from all users” is selected.

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

How to getText on an input in protractor

You have to use Promise to print or store values of element.

 var ExpectedValue:string ="AllTestings.com";
          element(by.id("xyz")).getAttribute("value").then(function (Text) {

                        expect(Text.trim()).toEqual("ExpectedValue", "Wrong page navigated");//Assertion
        console.log("Text");//Print here in Console

                    });

Python JSON encoding

I think you are simply exchanging dumps and loads.

>>> import json
>>> data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]

The first returns as a (JSON encoded) string its data argument:

>>> encoded_str = json.dumps( data )
>>> encoded_str
'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'

The second does the opposite, returning the data corresponding to its (JSON encoded) string argument:

>>> decoded_data = json.loads( encoded_str )
>>> decoded_data
[[u'apple', u'cat'], [u'banana', u'dog'], [u'pear', u'fish']]
>>> decoded_data == data
True

How to delete all instances of a character in a string in python?

Strings are immutable in Python, which means once a string is created, you cannot alter the contents of the strings. If at all, you need to change it, a new instance of the string will be created with the alterations.

Having that in mind, we have so many ways to solve this

  1. Using str.replace,

    >>> "it is icy".replace("i", "")
    't s cy'
    
  2. Using str.translate,

    >>> "it is icy".translate(None, "i")
    't s cy'
    
  3. Using Regular Expression,

    >>> import re
    >>> re.sub(r'i', "", "it is icy")
    't s cy'
    
  4. Using comprehension as a filter,

    >>> "".join([char for char in "it is icy" if char != "i"])
    't s cy'
    
  5. Using filter function

    >>> "".join(filter(lambda char: char != "i", "it is icy"))
    't s cy'
    

Timing comparison

def findreplace(m_string, char):
    m_string = list(m_string)
    for k in m_string:
        if k == char:
            del(m_string[m_string.index(k)])
    return "".join(m_string)

def replace(m_string, char):
    return m_string.replace("i", "")

def translate(m_string, char):
    return m_string.translate(None, "i")

from timeit import timeit

print timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
print timeit("replace('it is icy','i')", "from __main__ import replace")
print timeit("translate('it is icy','i')", "from __main__ import translate")

Result

1.64474582672
0.29278588295
0.311302900314

str.replace and str.translate methods are 8 and 5 times faster than the accepted answer.

Note: Comprehension method and filter methods are expected to be slower, for this case, since they have to create list and then they have to be traversed again to construct a string. And re is a bit overkill for a single character replacement. So, they all are excluded from the timing comparison.

How do I POST a x-www-form-urlencoded request using Fetch?

You can use react-native-easy-app that is easier to send http request and formulate interception request.

import { XHttp } from 'react-native-easy-app';

* Synchronous request
const params = {name:'rufeng',age:20}
const response = await XHttp().url(url).param(params).formEncoded().execute('GET');
const {success, json, message, status} = response;


* Asynchronous requests
XHttp().url(url).param(params).formEncoded().get((success, json, message, status)=>{
    if (success){
       this.setState({content: JSON.stringify(json)});
    } else {
       showToast(msg);
    }
});

Draw Circle using css alone

  • Create a div with a set height and width (so, for a circle, use the same height and width), forming a square
  • add a border-radius of 50% which will make it circular in shape. (note: no prefix has been required for a long time)
  • You can then play around with background-color / gradients / (even pseudo elements) to create something like this:

_x000D_
_x000D_
.red {_x000D_
  background-color: red;_x000D_
}_x000D_
.green {_x000D_
  background-color: green;_x000D_
}_x000D_
.blue {_x000D_
  background-color: blue;_x000D_
}_x000D_
.yellow {_x000D_
  background-color: yellow;_x000D_
}_x000D_
.sphere {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border-radius: 50%;_x000D_
  text-align: center;_x000D_
  vertical-align: middle;_x000D_
  font-size: 500%;_x000D_
  position: relative;_x000D_
  box-shadow: inset -10px -10px 100px #000, 10px 10px 20px black, inset 0px 0px 10px black;_x000D_
  display: inline-block;_x000D_
  margin: 5%;_x000D_
}_x000D_
.sphere::after {_x000D_
  background-color: rgba(255, 255, 255, 0.3);_x000D_
  content: '';_x000D_
  height: 45%;_x000D_
  width: 12%;_x000D_
  position: absolute;_x000D_
  top: 4%;_x000D_
  left: 15%;_x000D_
  border-radius: 50%;_x000D_
  transform: rotate(40deg);_x000D_
}
_x000D_
<div class="sphere red"></div>_x000D_
<div class="sphere green"></div>_x000D_
<div class="sphere blue"></div>_x000D_
<div class="sphere yellow"></div>_x000D_
<div class="sphere"></div>
_x000D_
_x000D_
_x000D_

Reading rows from a CSV file in Python

The Easiest way is this way :

from csv import reader

# open file in read mode
with open('file.csv', 'r') as read_obj:
    # pass the file object to reader() to get the reader object
    csv_reader = reader(read_obj)
    # Iterate over each row in the csv using reader object
    for row in csv_reader:
        # row variable is a list that represents a row in csv
        print(row)

output:
['Year:', 'Dec:', 'Jan:']
['1', '50', '60']
['2', '25', '50']
['3', '30', '30']
['4', '40', '20']
['5', '10', '10']

An error occurred while signing: SignTool.exe not found

After upgrading build tools in DevOps build agent to visual studio 2019, we started getting the below error for 64-bit build step of a WPF application.

C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(3975,5): error MSB3482: An error occurred while signing: SignTool.exe was not found at path

I tried all the above answers except the ones to disable signing or signing security and nothing helped.

Disabled the default MSBUILD step enter image description here

Added a cmd prompt step enter image description here

The path is "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\MsBuild.exe"

Note: Removed amd64 from the path above.

This is still a workaround. I hope Microsoft will fix it in the following release.

Running ASP.Net on a Linux based server

Now a days .Net is run in multiple platforms,like linux ,Mac os etc. but mono is not fully platform independent ,Because to deploy .NET in another OS required third party software.so it is not like java platform independent.

Mono is running in different platform ,because of JIT is there in different os.

Mono is not fully success in moonlight(silver light in .NET) .Not only Research is going on.

Mono uses XSP2 server or apache . some of the big companies are using this project,Some of the robotic project are also running on mono.

For more details http://www.mono-project.com/Main_Page.

Bootstrap modal - close modal when "call to action" button is clicked

Use data-dismiss="modal". In the version of Bootstrap I am using v3.3.5, when data-dismiss="modal" is added to the desired button like shown below it calls my external Javascript (JQuery) function beautifully and magically closes the modal. Its soo Sweet, I was worried I would have to call some modal hide in another function and chain that to the real working function

 <a href="#" id="btnReleaseAll" class="btn btn-primary btn-default btn-small margin-right pull-right" data-dismiss="modal">Yes</a>

In some external script file, and in my doc ready there is of course a function for the click of that identifier ID

 $("#divExamListHeader").on('click', '#btnReleaseAll', function () {
               // Do DatabaseMagic Here for a call a MVC ActionResult

How to skip over an element in .map()?

if it null or undefined in one line ES5/ES6

//will return array of src 
images.filter(p=>!p.src).map(p=>p.src);//p = property


//in your condition
images.filter(p=>p.src.split('.').pop() !== "json").map(p=>p.src);

How to read file with async/await properly?

To use await/async you need methods that return promises. The core API functions don't do that without wrappers like promisify:

const fs = require('fs');
const util = require('util');

// Convert fs.readFile into Promise version of same    
const readFile = util.promisify(fs.readFile);

function getStuff() {
  return readFile('test');
}

// Can't use `await` outside of an async function so you need to chain
// with then()
getStuff().then(data => {
  console.log(data);
})

As a note, readFileSync does not take a callback, it returns the data or throws an exception. You're not getting the value you want because that function you supply is ignored and you're not capturing the actual return value.

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

non-null assertion operator

With the non-null assertion operator we can tell the compiler explicitly that an expression has value other than null or undefined. This is can be useful when the compiler cannot infer the type with certainty but we more information than the compiler.

Example

TS code

function simpleExample(nullableArg: number | undefined | null) {
   const normal: number = nullableArg; 
    //   Compile err: 
    //   Type 'number | null | undefined' is not assignable to type 'number'.
    //   Type 'undefined' is not assignable to type 'number'.(2322)

   const operatorApplied: number = nullableArg!; 
    // compiles fine because we tell compiler that null | undefined are excluded 
}

Compiled JS code

Note that the JS does not know the concept of the Non-null assertion operator since this is a TS feature

_x000D_
_x000D_
"use strict";
function simpleExample(nullableArg) {
    const normal = nullableArg;
    const operatorApplied = nullableArg;
 }
_x000D_
_x000D_
_x000D_

Python: subplot within a loop: first panel appears in wrong position

Using your code with some random data, this would work:

fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)

axs = axs.ravel()

for i in range(10):

    axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
    axs[i].set_title(str(250+i))

The layout is off course a bit messy, but that's because of your current settings (the figsize, wspace etc).

enter image description here

How to run html file using node js

Just install http-server globally

npm install -g http-server

where ever you need to run a html file run the command http-server For ex: your html file is in /home/project/index.html you can do /home/project/$ http-server

That will give you a link to accessyour webpages: http-server Starting up http-server, serving ./ Available on: http://127.0.0.1:8080 http://192.168.0.106:8080

What does the NS prefix mean?

From Cocoa_(API) Wikipedia:

(emphasis added)

Cocoa classes begin with the acronym "NS" (standing either for the NeXT-Sun creation of OpenStep, or for the original proprietary term for the OpenStep framework, NeXTSTEP): NSString, NSArray, etc.

Foundation Kit, or more commonly simply Foundation, first appeared in OpenStep. On Mac OS X, it is based on Core Foundation. Foundation is a generic object-oriented library providing string and value manipulation, containers and iteration, distributed computing, run loops, and other functions that are not directly tied to the graphical user interface. The "NS" prefix, used for all classes and constants in the framework, comes from Cocoa's OPENSTEP heritage, which was jointly developed by NeXT and Sun.

send bold & italic text on telegram bot with html

For JS:

First, if you haven't installed telegram bot just install with the command

npm i messaging-api-telegram

Now, initialize its client with

const client = new TelegramClient({
    accessToken: process.env.<TELEGRAM_ACCESS_TOKEN>
});

Then, to send message use sendMessage() async function like below -

    const resp = await client.sendMessage(chatId, msg, {
        disableWebPagePreview: false,
        disableNotification: false,
        parseMode: "HTML"
    });

Here parse mode by default would be plain text but with parseOptions parseMode we can do 1. "HTML" and "MARKDOWN" to let use send messages in stylish way. Also get your access token of bot from telegram page and chatId or group chat Id from same.

How to check if a character is upper-case in Python?

x="Alpha_beta_Gamma"
is_uppercase_letter = True in map(lambda l: l.isupper(), x)
print is_uppercase_letter
>>>>True

So you can write it in 1 string

Getting the WordPress Post ID of current post

In some cases, such as when you're outside The Loop, you may need to use get_queried_object_id() instead of get_the_ID().

$postID = get_queried_object_id();

ORA-12170: TNS:Connect timeout occurred

[Gathering the answers in the comments]

The problem is that the Oracle service is running on a IP address, and the host is configured with another IP address.

To see the IP address of the Oracle service, issue an lsnrctl status command and check the address reported (in this case is 127.0.0.1, the localhost):

(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1521)))

To see the host IP address, issue the ipconfig (under windows) or ifconfig (under linux) command.

Howewer, in my installation, the Oracle service does not work if set on localhost address, I must set the real host IP address (for example 192.168.10.X).

To avoid this problem in the future, do not use DHCP for assigning an IP address of the host, but use a static one.

Facebook user url by id

UPDATE 2: This information is no more given by facebook. There is an official announcement for the behavior change (https://developers.facebook.com/blog/post/2018/04/19/facebook-login-changes-address-abuse/) but none for its alternative.

Yes, Just use this link and append your ID to the id parameter:

https://facebook.com/profile.php?id=<UID>

So for example:

https://facebook.com/profile.php?id=4

Will redirect you automatically to https://www.facebook.com/zuck Which is Mark Zuckerberg's profile.

If you want to do this for all your ids, then you can do it using a loop.

If you'd like, I can provide you with a snippet.

UPDATE: Alternatively, You can also do this:

https://facebook.com/<UID>

So that would be: https://facebook.com/4 which would automatically redirect to Zuck!

Failed to Connect to MySQL at localhost:3306 with user root

It worked for me this way:

Step1: Open System Preference > MySQL > Initialize Database.

Step2: Put password you used while installing MySQL.

Step3: Start MySQL server.

Step4: Come back to MySQL Workbench and double connect/ create a new one.

Is there a way to represent a directory tree in a Github README.md?

I wrote a small script that does the trick:

#!/bin/bash

#File: tree-md

tree=$(tree -tf --noreport -I '*~' --charset ascii $1 |
       sed -e 's/| \+/  /g' -e 's/[|`]-\+/ */g' -e 's:\(* \)\(\(.*/\)\([^/]\+\)\):\1[\4](\2):g')

printf "# Project tree\n\n${tree}"

Example:

Original tree command:

$ tree
.
+-- dir1
¦   +-- file11.ext
¦   +-- file12.ext
+-- dir2
¦   +-- file21.ext
¦   +-- file22.ext
¦   +-- file23.ext
+-- dir3
+-- file_in_root.ext
+-- README.md

3 directories, 7 files

Markdown tree command:

$ ./tree-md .
# Project tree

.
 * [tree-md](./tree-md)
 * [dir2](./dir2)
   * [file21.ext](./dir2/file21.ext)
   * [file22.ext](./dir2/file22.ext)
   * [file23.ext](./dir2/file23.ext)
 * [dir1](./dir1)
   * [file11.ext](./dir1/file11.ext)
   * [file12.ext](./dir1/file12.ext)
 * [file_in_root.ext](./file_in_root.ext)
 * [README.md](./README.md)
 * [dir3](./dir3)

Rendered result:

(Links are not visible in Stackoverflow...)

Project tree
  • tree-md
  • dir2
    • file21.ext
    • file22.ext
    • file23.ext
  • dir1
    • file11.ext
    • file12.ext
  • file_in_root.ext
  • README.md
  • dir3

How to terminate script execution when debugging in Google Chrome?

As of April 2018, you can stop infinite loops in Chrome:

  1. Open the Sources panel in Developer Tools (Ctrl+Shift+I**).
  2. Click the Pause button to Pause script execution.

Also note the shortcut keys: F8 and Ctrl+\

enter image description here

Change the Textbox height?

Some of you were close but changing designer code like that is annoying because you always have to go back and change it again.

The original OP was likely using an older version of .net because version 4 autosizes the textbox height to fit the font, but does not size comboboxes and textboxes the same which is a completely different problem but drew me here.

This is the problem I faced when placing textboxes next to comboboxes on a form. This is a bit irritating because who wants two controls side-by-side with different heights? Or different fonts to force heights? Step it up Microsoft, this should be simple!

I'm using .net framework 4 in VS2012 and the following was the simplest solution for me.

In the form load event (or anywhere as long as fired after InitializeComponent): textbox.AutoSize = false Then set the height to whatever you want. For me I wanted my text boxes and combo boxes to be the same height so textbox.height = combobox.height did the trick for me.

Notes:

1) The designer will not be affected so it will require you to start your project to see the end result, so there may be some trial and error.

2) Align the tops of your comboboxes and textboxes if you want them to be aligned properly after the resize because the textboxes will grow down.

How to run Gulp tasks sequentially one after the other

It's not an official release yet, but the coming up Gulp 4.0 lets you easily do synchronous tasks with gulp.series. You can simply do it like this:

gulp.task('develop', gulp.series('clean', 'coffee'))

I found a good blog post introducing how to upgrade and make a use of those neat features: migrating to gulp 4 by example

Where do I find the current C or C++ standard documents?

ISO standards cost money, from a moderate amount (for a PDF version), to a bit more (for a book version).

While they aren't finalised however, they can usually be found online, as drafts. Most of the times the final version doesn't differ significantly from the last draft, so while not perfect, they'll suit just fine.

Check if string has space in between (or anywhere)

How about:

myString.Any(x => Char.IsWhiteSpace(x))

Or if you like using the "method group" syntax:

myString.Any(Char.IsWhiteSpace)

Media Player called in state 0, error (-38,0)

You get this message in the logs, because you do something that is not allowed in the current state of your MediaPlayer instance.

Therefore you should always register an error handler to catch those things (as @tidbeck suggested).

At first, I advice you to take a look at the documentation for the MediaPlayer class and get an understanding of what that with states means. See: http://developer.android.com/reference/android/media/MediaPlayer.html#StateDiagram

Your mistake here could well be one of the common ones, the others wrote here, but in general, I would take a look at the documentation of what methods are valid to call in what state: http://developer.android.com/reference/android/media/MediaPlayer.html#Valid_and_Invalid_States

In my example it was the method mediaPlayer.CurrentPosition, that I called while the media player was in a state, where it was not allowed to call this property.

Reading integers from binary file in Python

An alternative method which does not make use of 'struct.unpack()' would be to use NumPy:

import numpy as np

f = open("file.bin", "r")
a = np.fromfile(f, dtype=np.uint32)

'dtype' represents the datatype and can be int#, uint#, float#, complex# or a user defined type. See numpy.fromfile.

Personally prefer using NumPy to work with array/matrix data as it is a lot faster than using Python lists.

How to change credentials for SVN repository in Eclipse?

I was able unable to locate the svn.simple file, but was able to change credentials using the following three steps:

Checkout project from SVN

enter image description here

Select the repository you need to change the credentials on (note: you will not perform an checkout, but this will bring you to the screen to enter a username/password combination).

enter image description here

Finally, enter the new username and password credentials:

enter image description here

It's a bit confusing, because you begin the process of initializing a new project, but you're only resetting the repository credentials.

Asserting successive calls to a mock method

I always have to look this one up time and time again, so here is my answer.


Asserting multiple method calls on different objects of the same class

Suppose we have a heavy duty class (which we want to mock):

In [1]: class HeavyDuty(object):
   ...:     def __init__(self):
   ...:         import time
   ...:         time.sleep(2)  # <- Spends a lot of time here
   ...:     
   ...:     def do_work(self, arg1, arg2):
   ...:         print("Called with %r and %r" % (arg1, arg2))
   ...:  

here is some code that uses two instances of the HeavyDuty class:

In [2]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(13, 17)
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(23, 29)
   ...:    


Now, here is a test case for the heavy_work function:

In [3]: from unittest.mock import patch, call
   ...: def test_heavy_work():
   ...:     expected_calls = [call.do_work(13, 17),call.do_work(23, 29)]
   ...:     
   ...:     with patch('__main__.HeavyDuty') as MockHeavyDuty:
   ...:         heavy_work()
   ...:         MockHeavyDuty.return_value.assert_has_calls(expected_calls)
   ...:  

We are mocking the HeavyDuty class with MockHeavyDuty. To assert method calls coming from every HeavyDuty instance we have to refer to MockHeavyDuty.return_value.assert_has_calls, instead of MockHeavyDuty.assert_has_calls. In addition, in the list of expected_calls we have to specify which method name we are interested in asserting calls for. So our list is made of calls to call.do_work, as opposed to simply call.

Exercising the test case shows us it is successful:

In [4]: print(test_heavy_work())
None


If we modify the heavy_work function, the test fails and produces a helpful error message:

In [5]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(113, 117)  # <- call args are different
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(123, 129)  # <- call args are different
   ...:     

In [6]: print(test_heavy_work())
---------------------------------------------------------------------------
(traceback omitted for clarity)

AssertionError: Calls not found.
Expected: [call.do_work(13, 17), call.do_work(23, 29)]
Actual: [call.do_work(113, 117), call.do_work(123, 129)]


Asserting multiple calls to a function

To contrast with the above, here is an example that shows how to mock multiple calls to a function:

In [7]: def work_function(arg1, arg2):
   ...:     print("Called with args %r and %r" % (arg1, arg2))

In [8]: from unittest.mock import patch, call
   ...: def test_work_function():
   ...:     expected_calls = [call(13, 17), call(23, 29)]    
   ...:     with patch('__main__.work_function') as mock_work_function:
   ...:         work_function(13, 17)
   ...:         work_function(23, 29)
   ...:         mock_work_function.assert_has_calls(expected_calls)
   ...:    

In [9]: print(test_work_function())
None


There are two main differences. The first one is that when mocking a function we setup our expected calls using call, instead of using call.some_method. The second one is that we call assert_has_calls on mock_work_function, instead of on mock_work_function.return_value.

How to fill DataTable with SQL Table

The answers above are correct, but I thought I would expand another answer by offering a way to do the same if you require to pass parameters into the query.

The SqlDataAdapter is quick and simple, but only works if you're filling a table with a static request ie: a simple SELECT without parameters.

Here is my way to do the same, but using a parameter to control the data I require in my table. And I use it to populate a DropDownList.

//populate the Programs dropdownlist according to the student's study year / preference
DropDownList ddlPrograms = (DropDownList)DetailsView1.FindControl("ddlPrograms");
if (ddlPrograms != null)
{
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ATCNTV1ConnectionString"].ConnectionString))
    {
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "SELECT ProgramID, ProgramName FROM tblPrograms WHERE ProgramCatID > 0 AND ProgramStatusID = (CASE WHEN @StudyYearID = 'VPR' THEN 10 ELSE 7 END) AND ProgramID NOT IN (23,112,113) ORDER BY ProgramName";
            cmd.Parameters.Add("@StudyYearID", SqlDbType.Char).Value = "11";
            DataTable wsPrograms = new DataTable();
            wsPrograms.Load(cmd.ExecuteReader());

            //populate the Programs ddl list
            ddlPrograms.DataSource = wsPrograms;
            ddlPrograms.DataTextField = "ProgramName";
            ddlPrograms.DataValueField = "ProgramID";
            ddlPrograms.DataBind();
            ddlPrograms.Items.Insert(0, new ListItem("<Select Program>", "0"));
        }
        catch (Exception ex)
        {
            // Handle the error
        }
    }
}

Enjoy

How to open a link in new tab using angular?

<a [routerLink]="" (click)="openSite(SiteUrl)">{{SiteUrl}}</a>

and in your Component.ts

openSite(siteUrl) {
   window.open("//" + siteUrl, '_blank');
}

How to Position a table HTML?

As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.

To position an element, a <table> in your case you want to use either padding or margins.

the difference between margins and paddings can be seen as the "box model":

box model image

Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.

I highly recommend the article above if you need to learn how to use CSS.

To move the table down and right I would use margins like so:

table{
    margin:25px 0 0 25px;
}

This is in shorthand so the margins are as follows:

margin: top right bottom left;

Using AES encryption in C#

For a more complete example that performs key derivation in addition to the AES encryption, see the answer and links posted in Getting AES encryption to work across Javascript and C#.

EDIT
a side note: Javascript Cryptography considered harmful. Worth the read.

PowerShell: how to grep command output?

I think this solution is easier and better, use directly the function findstr:

alias | findstr -i Write

You can also make an alias to use grep word:

new-alias grep findstr

How do I implement JQuery.noConflict() ?

In addition to that, passing true to $.noConflict(true); will also restore previous (if any) global variable jQuery, so that plugins can be initialized with correct jQuery version when multiple versions are being used.

Difference between declaring variables before or in loop?

I think it depends on the compiler and is hard to give a general answer.

replacing text in a file with Python

Faster way of writing it would be...

in = open('path/to/input/file').read()
out = open('path/to/input/file', 'w')
replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}
for i in replacements.keys():
    in = in.replace(i, replacements[i])
out.write(in)
out.close

This eliminated a lot of the iterations that the other answers suggest, and will speed up the process for longer files.

Create a list with initial capacity in Python

def doAppend( size=10000 ):
    result = []
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result.append(message)
    return result

def doAllocate( size=10000 ):
    result=size*[None]
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result[i]= message
    return result

Results. (evaluate each function 144 times and average the duration)

simple append 0.0102
pre-allocate  0.0098

Conclusion. It barely matters.

Premature optimization is the root of all evil.

Stored procedure with default parameters

I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc

Option 1

Create Procedure [Test] AS
    DECLARE @StartDate varchar(10)
    DECLARE @EndDate varchar(10)
    Set @StartDate = '201620' --Define start YearWeek
    Set @EndDate  = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Option 2

Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Then run exec test '2016-01-01','2016-01-25'

Remove a prefix from a string

I think you can use methods of the str type to do this. There's no need for regular expressions:

def remove_prefix(text, prefix):
    if text.startswith(prefix): # only modify the text if it starts with the prefix
         text = text.replace(prefix, "", 1) # remove one instance of prefix
    return text

Android Room - simple select query - Cannot access database on the main thread

With the Jetbrains Anko library, you can use the doAsync{..} method to automatically execute database calls. This takes care of the verbosity problem you seemed to have been having with mcastro's answer.

Example usage:

    doAsync { 
        Application.database.myDAO().insertUser(user) 
    }

I use this frequently for inserts and updates, however for select queries I reccommend using the RX workflow.

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

or defined by a module not included in the server configuration

Check to make sure you have mod_rewrite enabled.

From: https://webdevdoor.com/php/mod_rewrite-windows-apache-url-rewriting

  1. Find the httpd.conf file (usually you will find it in a folder called conf, config or something along those lines)
  2. Inside the httpd.conf file uncomment the line LoadModule rewrite_module modules/mod_rewrite.so (remove the pound '#' sign from in front of the line)
  3. Also find the line ClearModuleList is uncommented then find and make sure that the line AddModule mod_rewrite.c is not commented out.

If the LoadModule rewrite_module modules/mod_rewrite.so line is missing from the httpd.conf file entirely, just add it.

Sample command

To enable the module in a standard ubuntu do this:

a2enmod rewrite
systemctl restart apache2

is the + operator less performant than StringBuffer.append()

Yes it's true but you shouldn't care. Go with the one that's easier to read. If you have to benchmark your app, then focus on the bottlenecks.

I would guess that string concatenation isn't going to be your bottleneck.

git status shows fatal: bad object HEAD

This is unlikely to be the source of your problem - but if you happen to be working in .NET you'll end up with a bunch of obj/ folders. Sometimes it is helpful to delete all of these obj/ folders in order to resolve a pesky build issue.

I received the same fatal: bad object HEAD on my current branch (master) and was unable to run git status or to checkout any other branch (I always got an error refs/remote/[branch] does not point to a valid object).

If you want to delete all of your obj folders, don't get lazy and allow .git/objects into the mix. That folder is where all of the actual contents of your git commits go.

After being close to giving up I decided to look at which files were in my recycle bin, and there it was. Restored the file and my local repository was like new.

How to enumerate an object's properties in Python?

for one-liners:

print vars(theObject)

How to import NumPy in the Python shell

The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.