Programs & Examples On #Sql server performance

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

Private properties in JavaScript ES6 classes

I use this pattern and it's always worked for me

_x000D_
_x000D_
class Test {_x000D_
    constructor(data) {_x000D_
        class Public {_x000D_
            constructor(prv) {_x000D_
_x000D_
                // public function (must be in constructor on order to access "prv" variable)_x000D_
                connectToDb(ip) {_x000D_
                    prv._db(ip, prv._err);_x000D_
                } _x000D_
            }_x000D_
_x000D_
            // public function w/o access to "prv" variable_x000D_
            log() {_x000D_
                console.log("I'm logging");_x000D_
            }_x000D_
        }_x000D_
_x000D_
        // private variables_x000D_
        this._data = data;_x000D_
        this._err = function(ip) {_x000D_
            console.log("could not connect to "+ip);_x000D_
        }_x000D_
    }_x000D_
_x000D_
    // private function_x000D_
    _db(ip, err) {_x000D_
        if(!!ip) {_x000D_
      console.log("connected to "+ip+", sending data '"+this.data+"'");_x000D_
   return true;_x000D_
  }_x000D_
        else err(ip);_x000D_
    }_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
var test = new Test(10),_x000D_
  ip = "185.167.210.49";_x000D_
test.connectToDb(ip); // true_x000D_
test.log(); // I'm logging_x000D_
test._err(ip); // undefined_x000D_
test._db(ip, function() { console.log("You have got hacked!"); }); // undefined
_x000D_
_x000D_
_x000D_

Code coverage for Jest built on top of Jasmine

If you are having trouble with --coverage not working it may also be due to having coverageReporters enabled without 'text' or 'text-summary' being added. From the docs: "Note: Setting this option overwrites the default values. Add "text" or "text-summary" to see a coverage summary in the console output." Source

Check whether variable is number or string in JavaScript

This solution resolves many of the issues raised here!

This is by far the most reliable method I have used by far. I did not invent this, and cannot recall where I originally found it. But it works where other techniques fail:

// Begin public utility /getVarType/
// Returns 'Function', 'Object', 'Array',
// 'String', 'Number', 'Boolean', or 'Undefined'
getVarType = function ( data ){
  if (undefined === data ){ return 'Undefined'; }
  if (data === null ){ return 'Null'; }
  return {}.toString.call(data).slice(8, -1);
};  
// End public utility /getVarType/

Example of correctness

var str = new String();
console.warn( getVarType(str) ); // Reports "String"    
console.warn( typeof str );      // Reports "object"

var num = new Number();
console.warn( getVarType(num) ); // Reports "Number"
console.warn( typeof num );      // Reports "object"

var list = [];
console.warn( getVarType( list ) ); // Reports "Array"
console.warn( typeof list );        // Reports "object"

Ping site and return result in PHP

Using shell_exec:

<?php
$output = shell_exec('ping -c1 google.com');
echo "<pre>$output</pre>";
?>

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

Here's a one-liner slim way for layering text on top of an input in jQuery using ES6 syntax.

_x000D_
_x000D_
$('.input-group > input').focus(e => $(e.currentTarget).parent().find('.placeholder').hide()).blur(e => { if (!$(e.currentTarget).val()) $(e.currentTarget).parent().find('.placeholder').show(); });
_x000D_
* {
  font-family: sans-serif;
}

.input-group {
  position: relative;
}

.input-group > input {
  width: 150px;
  padding: 10px 0px 10px 25px;
}

.input-group > .placeholder {
  position: absolute;
  top: 50%;
  left: 25px;
  transform: translateY(-50%);
  color: #929292;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group">
  <span class="placeholder">Username</span>
  <input>
</div>
_x000D_
_x000D_
_x000D_

Python socket receive - incoming packets always have a different size

Note that exact reason why your code is frozen is not because you set too high request.recv() buffer size. Here is explained What means buffer size in socket.recv(buffer_size)

This code will work until it'll receive an empty TCP message (if you'd print this empty message, it'd show b''):

while True:    
  data = self.request.recv(1024)
  if not data: break

And note, that there is no way to send empty TCP message. socket.send(b'') simply won't work.

Why? Because empty message is sent only when you type socket.close(), so your script will loop as long as you won't close your connection. As Hans L pointed out here are some good methods to end message.

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

:last-child not working as expected?

:last-child will not work if the element is not the VERY LAST element

In addition to Harry's answer, I think it's crucial to add/emphasize that :last-child will not work if the element is not the VERY LAST element in a container. For whatever reason it took me hours to realize that, and even though Harry's answer is very thorough I couldn't extract that information from "The last-child selector is used to select the last child element of a parent."

Suppose this is my selector: a:last-child {}

This works:

<div>
    <a></a>
    <a>This will be selected</a>
</div>

This doesn't:

<div>
    <a></a>
    <a>This will no longer be selected</a>
    <div>This is now the last child :'( </div>
</div>

It doesn't because the a element is not the last element inside its parent.

It may be obvious, but it was not for me...

What is the best way to redirect a page using React Router?

One of the simplest way: use Link as follows:

import { Link } from 'react-router-dom';

<Link to={`your-path`} activeClassName="current">{your-link-name}</Link>

If we want to cover the whole div section as link:

 <div>
     <Card as={Link} to={'path-name'}>
         .... 
           card content here
         ....
     </Card>
 </div>

Convert an integer to an array of digits

I can not add comments to the decision of Vladimir, but you can immediately make an array deployed in the right direction. Here is my solution:

public static int[] splitAnIntegerIntoAnArrayOfNumbers (int a) {
    int temp = a;
    ArrayList<Integer> array = new ArrayList<Integer>();
    do{
        array.add(temp % 10);
        temp /= 10;
    } while  (temp > 0);

    int[] arrayOfNumbers = new int[array.size()];
    for(int i = 0, j = array.size()-1; i < array.size(); i++,j--) 
        arrayOfNumbers [j] = array.get(i);
    return arrayOfNumbers;
}

Important: This solution will not work for negative integers.

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

In IIS 8.5/ Windows 2012R2, Nothing mentioned here worked for me. I don't know what is meant by Removing WebDAV but that didn't solve the issue for me.

What helped me is the below steps;

  1. I went to IIS manager.
  2. In the left panel selected the site.
  3. In the left working area, selected the WebDAV, Opened it double clicking.
  4. In the right most panel, disabled it.

Now everything is working.

yii2 redirect in controller action does not work?

You can redirect by this method also:

return Yii::$app->response->redirect(['user/index', 'id' => 10]);

If you want to send the Header information immediately use with send().This method adds a Location header to the current response.

return Yii::$app->response->redirect(['user/index', 'id' => 10])->send();

If you want the complete URL then use like Url::to(['user/index', 'id' => 302]) with the header of use yii\helpers\Url;.

For more information check Here. Hope this will help someone.

Using multiprocessing.Process with a maximum number of simultaneous processes

It might be most sensible to use multiprocessing.Pool which produces a pool of worker processes based on the max number of cores available on your system, and then basically feeds tasks in as the cores become available.

The example from the standard docs (http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers) shows that you can also manually set the number of cores:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)              # start 4 worker processes
    result = pool.apply_async(f, [10])    # evaluate "f(10)" asynchronously
    print result.get(timeout=1)           # prints "100" unless your computer is *very* slow
    print pool.map(f, range(10))          # prints "[0, 1, 4,..., 81]"

And it's also handy to know that there is the multiprocessing.cpu_count() method to count the number of cores on a given system, if needed in your code.

Edit: Here's some draft code that seems to work for your specific case:

import multiprocessing

def f(name):
    print 'hello', name

if __name__ == '__main__':
    pool = multiprocessing.Pool() #use all available cores, otherwise specify the number you want as an argument
    for i in xrange(0, 512):
        pool.apply_async(f, args=(i,))
    pool.close()
    pool.join()

Can't load IA 32-bit .dll on a AMD 64-bit platform

Had same issue in win64bit and JVM 64bit

Was solved by uploading dll to system32

Calculating Page Load Time In JavaScript

Why so complicated? When you can do:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;

If you need more times check out the window.performance object:

console.log(window.performance);

Will show you the timing object:

connectEnd                 Time when server connection is finished.
connectStart               Time just before server connection begins.
domComplete                Time just before document readiness completes.
domContentLoadedEventEnd   Time after DOMContentLoaded event completes.
domContentLoadedEventStart Time just before DOMContentLoaded starts.
domInteractive             Time just before readiness set to interactive.
domLoading                 Time just before readiness set to loading.
domainLookupEnd            Time after domain name lookup.
domainLookupStart          Time just before domain name lookup.
fetchStart                 Time when the resource starts being fetched.
loadEventEnd               Time when the load event is complete.
loadEventStart             Time just before the load event is fired.
navigationStart            Time after the previous document begins unload.
redirectCount              Number of redirects since the last non-redirect.
redirectEnd                Time after last redirect response ends.
redirectStart              Time of fetch that initiated a redirect.
requestStart               Time just before a server request.
responseEnd                Time after the end of a response or connection.
responseStart              Time just before the start of a response.
timing                     Reference to a performance timing object.
navigation                 Reference to performance navigation object.
performance                Reference to performance object for a window.
type                       Type of the last non-redirect navigation event.
unloadEventEnd             Time after the previous document is unloaded.
unloadEventStart           Time just before the unload event is fired.

Browser Support

More Info

jQuery - how can I find the element with a certain id?

If you're trying to find an element by id, you don't need to search the table only - it should be unique on the page, and so you should be able to use:

var verificaHorario = $('#' + horaInicial);

If you need to search only in the table for whatever reason, you can use:

var verificaHorario = $("#tbIntervalos").find("td#" + horaInicial)

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

Enable IIS7 gzip

You will need to enable the feature in the Windows Features control panel:

IIS feature screenshot

How do I get the dialer to open with phone number displayed?

As @ashishduh mentioned above, using android:autoLink="phone is also a good solution. But this option comes with one drawback, it doesn't work with all phone number lengths. For instance, a phone number of 11 numbers won't work with this option. The solution is to prefix your phone numbers with the country code.

Example:

08034448845 won't work

but +2348034448845 will

Which characters need to be escaped in HTML?

Basically, there are three main characters which should be always escaped in your HTML and XML files, so they don't interact with the rest of the markups, so as you probably expect, two of them gonna be the syntax wrappers, which are <>, they are listed as below:

 1)  &lt; (<)
    
 2)  &gt; (>)
    
 3)  &amp; (&)

Also we may use double-quote (") as " and the single quote (') as &apos

Avoid putting dynamic content in <script> and <style>.These rules are not for applied for them. For example, if you have to include JSON in a , replace < with \x3c, the U+2028 character with \u2028, and U+2029 with \u2029 after JSON serialisation.)

HTML Escape Characters: Complete List: http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php

So you need to escape <, or & when followed by anything that could begin a character reference. Also The rule on ampersands is the only such rule for quoted attributes, as the matching quotation mark is the only thing that will terminate one. But if you don’t want to terminate the attribute value there, escape the quotation mark.

Changing to UTF-8 means re-saving your file:

Using the character encoding UTF-8 for your page means that you can avoid the need for most escapes and just work with characters. Note, however, that to change the encoding of your document, it is not enough to just change the encoding declaration at the top of the page or on the server. You need to re-save your document in that encoding. For help understanding how to do that with your application read Setting encoding in web authoring applications.

Invisible or ambiguous characters:

A particularly useful role for escapes is to represent characters that are invisible or ambiguous in presentation.

One example would be Unicode character U+200F RIGHT-TO-LEFT MARK. This character can be used to clarify directionality in bidirectional text (eg. when using the Arabic or Hebrew scripts). It has no graphic form, however, so it is difficult to see where these characters are in the text, and if they are lost or forgotten they could create unexpected results during later editing. Using ? (or its numeric character reference equivalent ?) instead makes it very easy to spot these characters.

An example of an ambiguous character is U+00A0 NO-BREAK SPACE. This type of space prevents line breaking, but it looks just like any other space when used as a character. Using   makes it quite clear where such spaces appear in the text.

How to determine the screen width in terms of dp or dip at runtime in Android?

Your problem is with casting the float to an int, losing precision. You should also multiply with the factor and not divide.

Do this:

int dp = (int)(pixel*getResources().getDisplayMetrics().density);

Android change SDK version in Eclipse? Unable to resolve target android-x

In Build: v22.6.2-1085508 ADT you need to add(select Android 4.4.2)

Goto project --> properties --> Android(This is second in listed item order leftPanel) and in the RightPanel Project Build Target, select Android 4.4.2 as Target name and apply changes It will rebuild the workspace.

In my case unable to resolve target 'android-17' eclipse was being shown as compile error and in code: import java.util.HashMap was not being referenced.

Creating a dictionary from a CSV file

Open the file by calling open and then using csv.DictReader.

input_file = csv.DictReader(open("coors.csv"))

You may iterate over the rows of the csv file dict reader object by iterating over input_file.

for row in input_file:
    print(row)

OR To access first line only

dictobj = csv.DictReader(open('coors.csv')).next() 

UPDATE In python 3+ versions, this code would change a little:

reader = csv.DictReader(open('coors.csv'))
dictobj = next(reader) 

Zooming MKMapView to fit annotation pins?

Thanks to jowie I've updated my old category to more elegant solution. Sharing complete, almost copy&paste ready solution

MKMapView+AnnotationsRegion.h

#import <MapKit/MapKit.h>

@interface MKMapView (AnnotationsRegion)

-(void)updateRegionForCurrentAnnotationsAnimated:(BOOL)animated;
-(void)updateRegionForCurrentAnnotationsAnimated:(BOOL)animated edgePadding:(UIEdgeInsets)edgePadding;

-(void)updateRegionForAnnotations:(NSArray *)annotations animated:(BOOL)animated;
-(void)updateRegionForAnnotations:(NSArray *)annotations animated:(BOOL)animated edgePadding:(UIEdgeInsets)edgePadding;

@end

MKMapView+AnnotationsRegion.m

#import "MKMapView+AnnotationsRegion.h"

@implementation MKMapView (AnnotationsRegion)

-(void)updateRegionForCurrentAnnotationsAnimated:(BOOL)animated{
    [self updateRegionForCurrentAnnotationsAnimated:animated edgePadding:UIEdgeInsetsZero];
}
-(void)updateRegionForCurrentAnnotationsAnimated:(BOOL)animated edgePadding:(UIEdgeInsets)edgePadding{
    [self updateRegionForAnnotations:self.annotations animated:animated edgePadding:edgePadding];
}

-(void)updateRegionForAnnotations:(NSArray *)annotations animated:(BOOL)animated{
    [self updateRegionForAnnotations:annotations animated:animated edgePadding:UIEdgeInsetsZero];
}
-(void)updateRegionForAnnotations:(NSArray *)annotations animated:(BOOL)animated edgePadding:(UIEdgeInsets)edgePadding{
    MKMapRect zoomRect = MKMapRectNull;
    for(id<MKAnnotation> annotation in annotations){
        MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
        MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);
        zoomRect = MKMapRectUnion(zoomRect, pointRect);
    }
    [self setVisibleMapRect:zoomRect edgePadding:edgePadding animated:animated];
}

@end

Hope it helps someone and thanks again jowie!

Use stored procedure to insert some data into a table

If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.

insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)

There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:

CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int

AS 

If you want to know what the ID of the newly inserted record is add

SELECT @@IDENTITY

to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx

You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.

P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.

How many spaces will Java String.trim() remove?

Javadoc for String has all the details. Removes white space (space, tabs, etc ) from both end and returns a new string.

How to convert binary string value to decimal

private static int convertBinaryToDecimal(String strOfBinary){
        int flag = 1, binary=0;
        char binaryOne = '1';
        char[] charArray = strOfBinary.toCharArray();
        for(int i=charArray.length-1;i>=0;i--){
            if(charArray[i] == binaryOne){
                binary+=flag;
            }
            flag*=2;
        }
        return binary;
    }

printf a variable in C

As Shafik already wrote you need to use the right format because scanf gets you a char. Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/

Hint: It's faster/nicer to write x=x+1; the shorter way: x++;

Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.

How to encode text to base64 in python

Whilst you can of course use the base64 module, you can also to use the codecs module (referred to in your error message) for binary encodings (meaning non-standard & non-text encodings).

For example:

import codecs
my_bytes = b"Hello World!"
codecs.encode(my_bytes, "base64")
codecs.encode(my_bytes, "hex")
codecs.encode(my_bytes, "zip")
codecs.encode(my_bytes, "bz2")

This can come in useful for large data as you can chain them to get compressed and json-serializable values:

my_large_bytes = my_bytes * 10000
codecs.decode(
    codecs.encode(
        codecs.encode(
            my_large_bytes,
            "zip"
        ),
        "base64"),
    "utf8"
)

Refs:

DB2 Timestamp select statement

You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.

SELECT * FROM <table_name> WHERE id = 1 
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';

If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':

hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')

Hive Alter table change Column Name

Change Column Name/Type/Position/Comment:

ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]

Example:

CREATE TABLE test_change (a int, b int, c int);

// will change column a's name to a1
ALTER TABLE test_change CHANGE a a1 INT;

Testing if a site is vulnerable to Sql Injection

SQL injection is the attempt to issue SQL commands to a database through a website interface, to gain other information. Namely, this information is stored database information such as usernames and passwords.

First rule of securing any script or page that attaches to a database instance is Do not trust user input.

Your example is attempting to end a misquoted string in an SQL statement. To understand this, you first need to understand SQL statements. In your example of adding a ' to a paramater, your 'injection' is hoping for the following type of statement:

SELECT username,password FROM users WHERE username='$username'

By appending a ' to that statement, you could then add additional SQL paramaters or queries.: ' OR username --

SELECT username,password FROM users WHERE username='' OR username -- '$username

That is an injection (one type of; Query Reshaping). The user input becomes an injected statement into the pre-written SQL statement.

Generally there are three types of SQL injection methods:

  • Query Reshaping or redirection (above)
  • Error message based (No such user/password)
  • Blind Injections

Read up on SQL Injection, How to test for vulnerabilities, understanding and overcoming SQL injection, and this question (and related ones) on StackOverflow about avoiding injections.

Edit:

As far as TESTING your site for SQL injection, understand it gets A LOT more complex than just 'append a symbol'. If your site is critical, and you (or your company) can afford it, hire a professional pen tester. Failing that, this great exaxmple/proof can show you some common techniques one might use to perform an injection test. There is also SQLMap which can automate some tests for SQL Injection and database take over scenarios.

Use of String.Format in JavaScript?

Here is a useful string formatting function using regular expressions and captures:

function format (fmtstr) {
  var args = Array.prototype.slice.call(arguments, 1);
  return fmtstr.replace(/\{(\d+)\}/g, function (match, index) {
    return args[index];
  });
}

Strings can be formatted like C# String.Format:

var str = format('{0}, {1}!', 'Hello', 'world');
console.log(str); // prints "Hello, world!"

the format will place the correct variable in the correct spot, even if they appear out of order:

var str = format('{1}, {0}!', 'Hello', 'world');
console.log(str); // prints "world, Hello!"

Hope this helps!

How to hide only the Close (x) button?

Well you can hide the close button by changing the FormBorderStyle from the properties section or programmatically in the constructor using:

public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
}

then you create a menu strip item to exit the application.

cheers

How to split a string to 2 strings in C

If you're open to changing the original string, you can simply replace the delimiter with \0. The original pointer will point to the first string and the pointer to the character after the delimiter will point to the second string. The good thing is you can use both pointers at the same time without allocating any new string buffers.

How to extract hours and minutes from a datetime.datetime object?

If the time is 11:03, then the accepted answer will print 11:3.

You could zero-pad the minutes:

"Created at {:d}:{:02d}".format(tdate.hour, tdate.minute)

Or go another way and use tdate.time() and only take the hour/minute part:

str(tdate.time())[0:5]

How to allow only numeric (0-9) in HTML inputbox using jQuery?

It may be overkill for what you are looking for, yet I suggest a jQuery plugin called autoNumeric() - it is great!

You can limit to only numbers, decimal precision, max / min values and more.

http://www.decorplanit.com/plugin/

LINQ to Entities how to update a record

Just modify one of the returned entities:

Customer c = (from x in dataBase.Customers
             where x.Name == "Test"
             select x).First();
c.Name = "New Name";
dataBase.SaveChanges();

Note, you can only update an entity (something that extends EntityObject, not something that you have projected using something like select new CustomObject{Name = x.Name}

How do I restart my C# WinForm Application?

You could also use Restarter.

Restarter is an application that automatically monitor and restarts crashed or hung programs and applications. It was originally developed to monitor and restart game servers, but it will do the job for any console or form based program or application

How can I add a username and password to Jenkins?

Go to Manage Jenkins > Configure Global Security and select the Enable Security checkbox.

For the basic username/password authentication, I would recommend selecting Jenkins Own User Database for the security realm and then selecting Logged in Users can do anything or a matrix based strategy (in case when you have multiple users with different permissions) for the Authorization.

Visual Studio Copy Project

After trying above solutions & creating copy for MVC projects

For MVC projects please update the port numbers in .csproj file, you can take help of iis applicationhost.config to check the port numbers. Same port numbers will cause assembly loading issue in IIS.

Change the background color in a twitter bootstrap modal?

When modal appears, it will trigger event show.bs.modal before appearing. I tried at Safari 13.1.2 on MacOS 10.15.6. When show.bs.modal event triggered, the .modal-backgrop is not inserted into body yet.

So, I give up to addClass, and removeClass to .modal-backdrop dynamically.

After viewing a lot articles on the Internet, I found a code snippet. It addClass and removeClass to the body, which is the parent of .modal-backdrop, when show.bs.modal and hide.bs.modal events triggered.

ps: I use Bootstrap 4.5.

CSS

// In order to addClass/removeClass on the `body`. The parent of `.modal-backdrop`
.no-modal-bg .modal-backdrop {
    background: none;
}

Javascript

$('#myModalId').on('show.bs.modal', function(e) {
     $('body').addClass('no-modal-bg');
}).on('hidden.bs.modal', function(e) {
     // 'hide.bs.modal' or 'hidden.bs.modal', depends on your needs.
     $('body').removeClass('no-modal-bg');
});

References

  1. The code snippet after google
  2. Bootstrap 4.5, modal, #events
  3. Bootstrap 4.5 documents

How to use data-binding with Fragment

Try this in Android DataBinding

FragmentMainBinding binding;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false);
        View rootView = binding.getRoot();
        initInstances(savedInstanceState);
        return rootView;
}

Find most frequent value in SQL column

Below query seems to work good for me in SQL Server database:

select column, COUNT(column) AS MOST_FREQUENT
from TABLE_NAME
GROUP BY column
ORDER BY COUNT(column) DESC

Result:

column          MOST_FREQUENT
item1           highest count
item2           second highest 
item3           third higest
..
..

How can I convert a DateTime to the number of seconds since 1970?

You probably want to use DateTime.UtcNow to avoid timezone issue

TimeSpan span= DateTime.UtcNow.Subtract(new DateTime(1970,1,1,0,0,0)); 

Hashcode and Equals for Hashset

  1. There's no need to call equals if hashCode differs.
  2. There's no need to call hashCode if (obj1 == obj2).
  3. There's no need for hashCode and/or equals just to iterate - you're not comparing objects
  4. When needed to distinguish in between objects.

POST Content-Length exceeds the limit

I suggest that you should change to post_max_size from 8M to 32M in the php.ini file.

How do I get a file name from a full path with PHP?

The basename function should give you what you want:

Given a string containing a path to a file, this function will return the base name of the file.

For instance, quoting the manual's page:

<?php
    $path = "/home/httpd/html/index.php";
    $file = basename($path);         // $file is set to "index.php"
    $file = basename($path, ".php"); // $file is set to "index"
?>

Or, in your case:

$full = 'F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map';
var_dump(basename($full));

You'll get:

string(10) "Output.map"

What's the difference between commit() and apply() in SharedPreferences

The difference between commit() and apply()

We might be confused by those two terms, when we are using SharedPreference. Basically they are probably the same, so let’s clarify the differences of commit() and apply().

1.Return value:

apply() commits without returning a boolean indicating success or failure. commit() returns true if the save works, false otherwise.

  1. Speed:

apply() is faster. commit() is slower.

  1. Asynchronous v.s. Synchronous:

apply(): Asynchronous commit(): Synchronous

  1. Atomic:

apply(): atomic commit(): atomic

  1. Error notification:

apply(): No commit(): Yes

How to listen state changes in react.js?

If you use hooks like const [ name , setName ] = useState (' '), you can try the following:

 useEffect(() => {
      console.log('Listening: ', name);
    }, [name]);

How to add an UIViewController's view as subview

I feel like all of these answers are slightly incomplete, so here's the proper way to add a viewController's view as a subview of another viewController's view:

    [self addChildViewController:viewControllerToAdd];
    [self.view addSubview:viewControllerToAdd.view];
    [viewControllerToAdd didMoveToParentViewController:self];

If you'd like, you can copy this into your code as a snippet. SO doesn't seem to understand code replacement formatting, but they will show up clean in Xcode:

    [self addChildViewController:<#viewControllerToAdd#>];
    [self.view addSubview:<#viewControllerToAdd#>.view];
    [<#viewControllerToAdd#> didMoveToParentViewController:self];

willMove is called automatically w/ addChild. Thanks @iOSSergey

When your custom container calls the addChildViewController: method, it automatically calls the willMoveToParentViewController: method of the view controller to be added as a child before adding it.

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

WebAPI 2 now has a package for CORS which can be installed using : Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebServic

Once this is installed, follow this for the code :http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

The SQL OVER() clause - when and why is it useful?

So in simple words: Over clause can be used to select non aggregated values along with Aggregated ones.

Partition BY, ORDER BY inside, and ROWS or RANGE are part of OVER() by clause.

partition by is used to partition data and then perform these window, aggregated functions, and if we don't have partition by the then entire result set is considered as a single partition.

OVER clause can be used with Ranking Functions(Rank, Row_Number, Dense_Rank..), Aggregate Functions like (AVG, Max, Min, SUM...etc) and Analytics Functions like (First_Value, Last_Value, and few others).

Let's See basic syntax of OVER clause

OVER (   
       [ <PARTITION BY clause> ]  
       [ <ORDER BY clause> ]   
       [ <ROW or RANGE clause> ]  
      )  

PARTITION BY: It is used to partition data and perform operations on groups with the same data.

ORDER BY: It is used to define the logical order of data in Partitions. When we don't specify Partition, entire resultset is considered as a single partition

: This can be used to specify what rows are supposed to be considered in a partition when performing the operation.

Let's take an example:

Here is my dataset:

Id          Name                                               Gender     Salary
----------- -------------------------------------------------- ---------- -----------
1           Mark                                               Male       5000
2           John                                               Male       4500
3           Pavan                                              Male       5000
4           Pam                                                Female     5500
5           Sara                                               Female     4000
6           Aradhya                                            Female     3500
7           Tom                                                Male       5500
8           Mary                                               Female     5000
9           Ben                                                Male       6500
10          Jodi                                               Female     7000
11          Tom                                                Male       5500
12          Ron                                                Male       5000

So let me execute different scenarios and see how data is impacted and I'll come from difficult syntax to simple one

Select *,SUM(salary) Over(order by salary RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_sal from employees

Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
6           Aradhya                                            Female     3500        3500
5           Sara                                               Female     4000        7500
2           John                                               Male       4500        12000
3           Pavan                                              Male       5000        32000
1           Mark                                               Male       5000        32000
8           Mary                                               Female     5000        32000
12          Ron                                                Male       5000        32000
11          Tom                                                Male       5500        48500
7           Tom                                                Male       5500        48500
4           Pam                                                Female     5500        48500
9           Ben                                                Male       6500        55000
10          Jodi                                               Female     7000        62000

Just observe the sum_sal part. Here I am using order by Salary and using "RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW". In this case, we are not using partition so entire data will be treated as one partition and we are ordering on salary. And the important thing here is UNBOUNDED PRECEDING AND CURRENT ROW. This means when we are calculating the sum, from starting row to the current row for each row. But if we see rows with salary 5000 and name="Pavan", ideally it should be 17000 and for salary=5000 and name=Mark, it should be 22000. But as we are using RANGE and in this case, if it finds any similar elements then it considers them as the same logical group and performs an operation on them and assigns value to each item in that group. That is the reason why we have the same value for salary=5000. The engine went up to salary=5000 and Name=Ron and calculated sum and then assigned it to all salary=5000.

Select *,SUM(salary) Over(order by salary ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_sal from employees


   Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
6           Aradhya                                            Female     3500        3500
5           Sara                                               Female     4000        7500
2           John                                               Male       4500        12000
3           Pavan                                              Male       5000        17000
1           Mark                                               Male       5000        22000
8           Mary                                               Female     5000        27000
12          Ron                                                Male       5000        32000
11          Tom                                                Male       5500        37500
7           Tom                                                Male       5500        43000
4           Pam                                                Female     5500        48500
9           Ben                                                Male       6500        55000
10          Jodi                                               Female     7000        62000

So with ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW The difference is for same value items instead of grouping them together, It calculates SUM from starting row to current row and it doesn't treat items with same value differently like RANGE

Select *,SUM(salary) Over(order by salary) as sum_sal from employees

Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
6           Aradhya                                            Female     3500        3500
5           Sara                                               Female     4000        7500
2           John                                               Male       4500        12000
3           Pavan                                              Male       5000        32000
1           Mark                                               Male       5000        32000
8           Mary                                               Female     5000        32000
12          Ron                                                Male       5000        32000
11          Tom                                                Male       5500        48500
7           Tom                                                Male       5500        48500
4           Pam                                                Female     5500        48500
9           Ben                                                Male       6500        55000
10          Jodi                                               Female     7000        62000

These results are the same as

Select *, SUM(salary) Over(order by salary RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_sal from employees

That is because Over(order by salary) is just a short cut of Over(order by salary RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) So wherever we simply specify Order by without ROWS or RANGE it is taking RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW as default.

Note: This is applicable only to Functions that actually accept RANGE/ROW. For example, ROW_NUMBER and few others don't accept RANGE/ROW and in that case, this doesn't come into the picture.

Till now we saw that Over clause with an order by is taking Range/ROWS and syntax looks something like this RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW And it is actually calculating up to the current row from the first row. But what If it wants to calculate values for the entire partition of data and have it for each column (that is from 1st row to last row). Here is the query for that

Select *,sum(salary) Over(order by salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as sum_sal from employees

Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
1           Mark                                               Male       5000        62000
2           John                                               Male       4500        62000
3           Pavan                                              Male       5000        62000
4           Pam                                                Female     5500        62000
5           Sara                                               Female     4000        62000
6           Aradhya                                            Female     3500        62000
7           Tom                                                Male       5500        62000
8           Mary                                               Female     5000        62000
9           Ben                                                Male       6500        62000
10          Jodi                                               Female     7000        62000
11          Tom                                                Male       5500        62000
12          Ron                                                Male       5000        62000

Instead of CURRENT ROW, I am specifying UNBOUNDED FOLLOWING which instructs the engine to calculate till the last record of partition for each row.

Now coming to your point on what is OVER() with empty braces?

It is just a short cut for Over(order by salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)

Here we are indirectly specifying to treat all my resultset as a single partition and then perform calculations from the first record to the last record of each partition.

Select *,Sum(salary) Over() as sum_sal from employees

Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
1           Mark                                               Male       5000        62000
2           John                                               Male       4500        62000
3           Pavan                                              Male       5000        62000
4           Pam                                                Female     5500        62000
5           Sara                                               Female     4000        62000
6           Aradhya                                            Female     3500        62000
7           Tom                                                Male       5500        62000
8           Mary                                               Female     5000        62000
9           Ben                                                Male       6500        62000
10          Jodi                                               Female     7000        62000
11          Tom                                                Male       5500        62000
12          Ron                                                Male       5000        62000

I did create a video on this and if you are interested you can visit it. https://www.youtube.com/watch?v=CvVenuVUqto&t=1177s

Thanks, Pavan Kumar Aryasomayajulu HTTP://xyzcoder.github.io

Swift add icon/image in UITextField

You can put this function your global file or above your class so you can access it in entire application. After this procedure you can call this function as per your requirement in application.

        func SetLeftSIDEImage(TextField: UITextField, ImageName: String){

                let leftImageView = UIImageView()
                leftImageView.contentMode = .scaleAspectFit

                let leftView = UIView()

                leftView.frame = CGRect(x: 20, y: 0, width: 30, height: 20)
                leftImageView.frame = CGRect(x: 13, y: 0, width: 15, height: 20)
                TextField.leftViewMode = .always
                TextField.leftView = leftView

                let image = UIImage(named: ImageName)?.withRenderingMode(.alwaysTemplate)
                leftImageView.image = image
                leftImageView.tintColor = UIColor(red: 106/255, green: 79/255, blue: 131/255, alpha: 1.0)
                leftImageView.tintColorDidChange()

                leftView.addSubview(leftImageView)
            }

            SetLeftSIDEImage(TextField: Your_textField, ImageName: “YourImageName”) // call function

jQuery: Wait/Delay 1 second without executing code

Only javascript It will work without jQuery

<!DOCTYPE html>
<html>
    <head>
        <script>
            function sleep(miliseconds) {
                var currentTime = new Date().getTime();
                while (currentTime + miliseconds >= new Date().getTime()) {
                }
            }

            function hello() {
                sleep(5000);
                alert('Hello');
            }
            function hi() {
                sleep(10000);
                alert('Hi');
            }
        </script>
    </head>
    <body>
        <a href="#" onclick="hello();">Say me hello after 5 seconds </a>
        <br>
        <a href="#" onclick="hi();">Say me hi after 10 seconds </a>


    </body>
</html>

Determine direct shared object dependencies of a Linux binary?

ldd -v prints the dependency tree under "Version information:' section. The first block in that section are the direct dependencies of the binary.

See Hierarchical ldd(1)

OpenSSL and error in reading openssl.conf file

set OPENSSL_CONF=c:/{path to openSSL}/bin/openssl.cfg

take care of the right extension (openssl.cfg not cnf)!

I have installed OpenSSL from here: http://slproweb.com/products/Win32OpenSSL.html

Factory Pattern. When to use factory methods?

Factory methods should be considered as an alternative to constructors - mostly when constructors aren't expressive enough, ie.

class Foo{
  public Foo(bool withBar);
}

is not as expressive as:

class Foo{
  public static Foo withBar();
  public static Foo withoutBar();
}

Factory classes are useful when you need a complicated process for constructing the object, when the construction need a dependency that you do not want for the actual class, when you need to construct different objects etc.

Is there a simple way that I can sort characters in a string in alphabetical order

You can use this

string x = "ABCGH"

char[] charX = x.ToCharArray();

Array.Sort(charX);

This will sort your string.

React-Native: Application has not been registered error

All the given answers did not work for me.

I had another node process running in another terminal, i closed that command terminal and everything worked as expected.

How to Migrate to WKWebView?

Swift is not a requirement, everything works fine with Objective-C. UIWebView will continue to be supported, so there is no rush to migrate if you want to take your time. However, it will not get the javascript and scrolling performance enhancements of WKWebView.

For backwards compatibility, I have two properties for my view controller: a UIWebView and a WKWebView. I use the WKWebview only if the class exists:

if ([WKWebView class]) {
    // do new webview stuff
} else {
    // do old webview stuff
}

Whereas I used to have a UIWebViewDelegate, I also made it a WKNavigationDelegate and created the necessary methods.

SVN Commit specific files

Besides listing the files explicitly as shown by unwind and Wienczny, you can setup change lists and checkin these. These allow you to manage disjunct sets of changes to the same working copy.

You can read about them in the online version of the excellent SVN book.

Want custom title / image / description in facebook share link from a flash app

You can't, it just doesn't support it.

I have to ask, why those calculations need to happen Only inside the flash app?

You have to be navigating to an URL that clearly relates to the metadata you get from the flash app. Otherwise how would the flash app know to get the values depending on the URL you hit.

Options are:

  • calculate on the page: When serving the page you need to do those same calculations on the server and send the title, etc on the page metadata.
  • send metadata in the query string to your site: If you really must keep the calculation off the server, an alternative trick would be to explicitly set the metadata in the URL the users click to get to your site from Facebook. When processing the page, you just copy it back in the metadata sections (don't forget to encode appropriately). That is clearly limited because of the url size restrictions.
  • send the calculation results in the query string to your site: if those calculations just give you a couple numbers that are used in the metadata, you could include just that in the query string of the URL the users click back to your site. That's more likely to not give you problems with URL sizes.

re

Why is this upvoted? It's wrong. You CAN - it IS supported to add custom title, description and images to your share. I do it all the time. – Dustin Fineout 3 hours ago

The OP very clearly stated that he already knew you could serve that from a page, but wanted to pass the values directly to facebook (not through the target page).

Besides, note that I gave 3 different options to work around the issue, one of which is what you posted as an answer later. Your option isn't how the OP was trying to do it, its just a workaround because of facebook restrictions.

Finally, just as I did, you should mention that particular solution is flawed because you can easily hit the URL size restriction.

CSS Font "Helvetica Neue"

Helvetica Neue is a paid font, so you shouldn't @font-face it, as you'd be freely distributing a copyrighted font. It's included in Mac systems but not in windows/linux ones, so yes, plenty of your users wont have it installed. Anyway, you can use 'Arial Narrow' as a windows substitute, which is it's windows equivalent.

jQuery DIV click, with anchors

I know that if you were to change that to an href you'd do:

$("a#link1").click(function(event) {
  event.preventDefault();
  $('div.link1').show();
  //whatever else you want to do
});

so if you want to keep it with the div, I'd try

$("div.clickable").click(function(event) {
  event.preventDefault();
  window.location = $(this).attr("url");
});

Using Selenium Web Driver to retrieve value of a HTML input

As was mentioned before, you could do something like that

public String getVal(WebElement webElement) {
    JavascriptExecutor e = (JavascriptExecutor) driver;
    return (String) e.executeScript(String.format("return $('#%s').val();", webElement.getAttribute("id")));
}

But as you can see, your element must have an id attribute, and also, jquery on your page.

What is the attribute property="og:title" inside meta tag?

Probably part of Open Graph Protocol for Facebook.

Edit: guess not only Facebook - that's only one example of using it.

Position a div container on the right side

Is this what you wanted? - http://jsfiddle.net/jomanlk/x5vyC/3/

Floats on both sides now

#wrapper{
    background:red;
    overflow:auto;
}

#c1{
   float:left;
   background:blue;
}

#c2{
    background:green;
    float:right;
}?

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

Long press on UITableView

Answer in Swift 5 (Continuation of Ricky's answer in Swift)

Add the UIGestureRecognizerDelegate to your ViewController

 override func viewDidLoad() {
    super.viewDidLoad()

    //Long Press
    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
    longPressGesture.minimumPressDuration = 0.5
    self.tableView.addGestureRecognizer(longPressGesture)
 }

And the function:

@objc func handleLongPress(longPressGesture: UILongPressGestureRecognizer) {
    let p = longPressGesture.location(in: self.tableView)
    let indexPath = self.tableView.indexPathForRow(at: p)
    if indexPath == nil {
        print("Long press on table view, not row.")
    } else if longPressGesture.state == UIGestureRecognizer.State.began {
        print("Long press on row, at \(indexPath!.row)")
    }
}

How to save CSS changes of Styles panel of Chrome Developer Tools?

You can save your CSS changes from Chrome Dev Tools itself. Chrome now allows you to add local folders to your Workspace. After allowing Chrome access to the folder and adding the folder to the local workspace, you can map a web resource to a local resource.

  • Navigate to the Sources panel of the Developer Tools, Right-click in the left panel (where the files are listed) and select Add Folder to Workspace. You can get to a stylesheet in the Sources panel quickly by clicking the stylesheet at the top-right of each CSS rule for a selected element in the Elements panel.

enter image description here

  • After adding the folder, you'll have to give Chrome access to the folder. Allow chrome access

  • Next, you need to map the network resource to the local resource.

enter image description here

  • After reloading the page, Chrome now loads the local resources for the mapped files. To make things simpler, Chrome only shows you the local resources (so you don't get confused on as to whether you are editing the local or the network resource). To save your changes, press CTRL + S when editing the file.

p.s.

You may have to open the mapped file(s) and start editing to get Chrome apply the local version (date 201604.12).

VS 2017 Metadata file '.dll could not be found

For me what worked was:

Uninstall and then reinstall the referenced Nuget package that has the error.

ReactJS: "Uncaught SyntaxError: Unexpected token <"

Add type="text/babel" to the script that includes the .jsx file and add this: <script src="https://npmcdn.com/[email protected]/browser.min.js"></script>

Can I fade in a background image (CSS: background-image) with jQuery?

It's not possible to do it just like that, but you can overlay an opaque div between the div with the background-image and the text and fade that one out, hence giving the appearance that the background is fading in.

How to get just the date part of getdate()?

If you are using SQL Server 2008 or later

select convert(date, getdate())

Otherwise

select convert(varchar(10), getdate(),120)

Getting the .Text value from a TextBox

Did you try using t.Text?

What does "select count(1) from table_name" on any database tables mean?

You can test like this:

create table test1(
 id number,
 name varchar2(20)
);

insert into test1 values (1,'abc');
insert into test1 values (1,'abc');

select * from test1;
select count(*) from test1;
select count(1) from test1;
select count(ALL 1) from test1;
select count(DISTINCT 1) from test1;

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

I had a hard time making this work too, the solution for me was to use both hyui and konstantin answers,

class ExampleTask extends AsyncTask<String, String, String> {

// Your onPreExecute method.

@Override
protected String doInBackground(String... params) {
    // Your code.
    if (condition_is_true) {
        this.publishProgress("Show the dialog");
    }
    return "Result";
}

@Override
protected void onProgressUpdate(String... values) {

    super.onProgressUpdate(values);
    YourActivity.this.runOnUiThread(new Runnable() {
       public void run() {
           alertDialog.show();
       }
     });
 }

}

How to make a HTTP request using Ruby on Rails?

OpenURI is the best; it's as simple as

require 'open-uri'
response = open('http://example.com').read

Split data frame string column into multiple columns

here is a one liner along the same lines as aniko's solution, but using hadley's stringr package:

do.call(rbind, str_split(before$type, '_and_'))

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

https://fettblog.eu/gulp-4-parallel-and-series/

Because gulp.task(name, deps, func) was replaced by gulp.task(name, gulp.{series|parallel}(deps, func)).

You are using the latest version of gulp but older code. Modify the code or downgrade.

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

goto command prompt

netstat -aon

for linux

netstat -tulpn | grep 'your_port_number'

it will show you something like

 TCP    192.1.200.48:2053      24.43.246.60:443       ESTABLISHED     248
 TCP    192.1.200.48:2055      24.43.246.60:443       ESTABLISHED     248
 TCP    192.1.200.48:2126      213.146.189.201:12350  ESTABLISHED     1308
 TCP    192.1.200.48:3918      192.1.200.2:8073       ESTABLISHED     1504
 TCP    192.1.200.48:3975      192.1.200.11:49892     TIME_WAIT       0
 TCP    192.1.200.48:3976      192.1.200.11:49892     TIME_WAIT       0
 TCP    192.1.200.48:4039      209.85.153.100:80      ESTABLISHED     248
 TCP    192.1.200.48:8080      209.85.153.100:80      ESTABLISHED     248

check which process has binded your port. here in above example its 248 now if you are sure that you need to kill that process fire

Linux:

kill -9 248

Windows:

taskkill /f /pid 248

it will kill that process

Getting the last n elements of a vector. Is there a better way than using the length() function?

You can do exactly the same thing in R with two more characters:

x <- 0:9
x[-5:-1]
[1] 5 6 7 8 9

or

x[-(1:5)]

How do you convert epoch time in C#?

If you are not using 4.6, this may help Source: System.IdentityModel.Tokens

    /// <summary>
    /// DateTime as UTV for UnixEpoch
    /// </summary>
    public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

    /// <summary>
    /// Per JWT spec:
    /// Gets the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the desired date/time.
    /// </summary>
    /// <param name="datetime">The DateTime to convert to seconds.</param>
    /// <remarks>if dateTimeUtc less than UnixEpoch, return 0</remarks>
    /// <returns>the number of seconds since Unix Epoch.</returns>
    public static long GetIntDate(DateTime datetime)
    {
        DateTime dateTimeUtc = datetime;
        if (datetime.Kind != DateTimeKind.Utc)
        {
            dateTimeUtc = datetime.ToUniversalTime();
        }

        if (dateTimeUtc.ToUniversalTime() <= UnixEpoch)
        {
            return 0;
        }

        return (long)(dateTimeUtc - UnixEpoch).TotalSeconds;
    }    

How to insert a new key value pair in array in php?

Try this:

foreach($array as $k => $obj) { 
    $obj->{'newKey'} = "value"; 
}

C - split string into an array of strings

Since you've already looked into strtok just continue down the same path and split your string using space (' ') as a delimiter, then use something as realloc to increase the size of the array containing the elements to be passed to execvp.

See the below example, but keep in mind that strtok will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy or similar function.

char    str[]= "ls -l";
char ** res  = NULL;
char *  p    = strtok (str, " ");
int n_spaces = 0, i;


/* split string and append tokens to 'res' */

while (p) {
  res = realloc (res, sizeof (char*) * ++n_spaces);

  if (res == NULL)
    exit (-1); /* memory allocation failed */

  res[n_spaces-1] = p;

  p = strtok (NULL, " ");
}

/* realloc one extra element for the last NULL */

res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;

/* print the result */

for (i = 0; i < (n_spaces+1); ++i)
  printf ("res[%d] = %s\n", i, res[i]);

/* free the memory allocated */

free (res);

res[0] = ls
res[1] = -l
res[2] = (null)

remove None value from a list without removing the 0 value

For Python 2.7 (See Raymond's answer, for Python 3 equivalent):

Wanting to know whether something "is not None" is so common in python (and other OO languages), that in my Common.py (which I import to each module with "from Common import *"), I include these lines:

def exists(it):
    return (it is not None)

Then to remove None elements from a list, simply do:

filter(exists, L)

I find this easier to read, than the corresponding list comprehension (which Raymond shows, as his Python 2 version).

Converting a datetime string to timestamp in Javascript

Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond]) constructor signature of the Date object.

var dateString = '17-09-2013 10:08',
    dateTimeParts = dateString.split(' '),
    timeParts = dateTimeParts[1].split(':'),
    dateParts = dateTimeParts[0].split('-'),
    date;

date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);

console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400

You could also use a regular expression with capturing groups to parse the date string in one line.

var dateParts = '17-09-2013 10:08'.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/);

console.log(dateParts); // ["17-09-2013 10:08", "17", "09", "2013", "10", "08"]

Check if a string contains a string in C++

You can also use the System namespace. Then you can use the contains method.

#include <iostream>
using namespace System;

int main(){
    String ^ wholeString = "My name is Malindu";

    if(wholeString->ToLower()->Contains("malindu")){
        std::cout<<"Found";
    }
    else{
        std::cout<<"Not Found";
    }
}

Is there a way to programmatically minimize a window

FormName.WindowState = FormWindowState.Minimized;

jQuery UI - Draggable is not a function?

I went through both your question and a another duplicate.
In the end, the following answer helped me sorting things out:
uncaught-typeerror-draggable-is-not-a-function

To get rid of :

$(".draggable").draggable is not a function anymore

I had to put links to Javascript libraries above the script tag I expected to be working.

My code:

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js" />
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" />

<script>
    $(function(){
        $("#container-speed").draggable();
    });
</script>

<div class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="rowbackground"style="width: 600px; height: 400px; margin: 0 auto">
                <div id="container-speed" style="width: 300px; height: 200px; float: left"></div>
                <div id="container-rpm" style="width: 300px; height: 200px; float: left"></div>
            </div>
        </div>
    </div>
</div>

Could not create work tree dir 'example.com'.: Permission denied

I think you don't have your permissions set up correctly for /var/www Change the ownership of the folder.

sudo chown -R **yourusername** /var/www

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.

Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

Copy table from one database to another

If migrating constantly between two databases, then insert into an already existing table structure is a possibility. If so, then:

Use the following syntax:

insert into DESTINATION_DB.dbo.destination_table
select *
  from SOURCE_DB.dbo.source_table
[where x ...]

If migrating a LOT of tables (or tables with foreign keys constraints) I'd recommend:

  • Generating Scripts with the Advanced option / Types of data to script : Data only OR
  • Resort using a third party tool.

Hope it helps!

How to calculate a time difference in C++

You can also use the clock_gettime. This method can be used to measure:

  1. System wide real-time clock
  2. System wide monotonic clock
  3. Per Process CPU time
  4. Per process Thread CPU time

Code is as follows:

#include < time.h >
#include <iostream>
int main(){
  timespec ts_beg, ts_end;
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_beg);
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_end);
  std::cout << (ts_end.tv_sec - ts_beg.tv_sec) + (ts_end.tv_nsec - ts_beg.tv_nsec) / 1e9 << " sec";
}

`

Adding days to a date in Python

This might help:

from datetime import date, timedelta
date1 = date(2011, 10, 10)
date2 = date + timedelta(days=5)
print (date2)

How to make Git "forget" about a file that was tracked but is now in .gitignore?

In my case here, I had several .lock files in several directories that I needed to remove. I ran the following and it worked without having to go into each directory to remove them:

git rm -r --cached **/*.lock

Doing this went into each folder under the 'root' of where I was at and excluded all files that matched the pattern.

Hope this helps others!

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

A popular Linux library which has similar functionality would be ncurses.

Nexus 5 USB driver

Nexus 5 with Win7 x64

-USB computer connection : Uncheck MTP and PTP

-Use a 2.0 USB port.

-Try to use the original USB cable.

Now device manager will detect nexus 5 as an androide device with ADB driver.

Find child element in AngularJS directive

In your link function, do this:

// link function
function (scope, element, attrs) {
  var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}

Also, in your link function, don't name your scope variable using a $. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.

ERROR 1044 (42000): Access denied for 'root' With All Privileges

Try to comment string "sql-mode=..." in file my.cnf and than restart mysql.

Printing list elements on separated lines in Python

Use the print function (Python 3.x) or import it (Python 2.6+):

from __future__ import print_function

print(*sys.path, sep='\n')

React JS get current date

OPTION 1: if you want to make a common utility function then you can use this

export function getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

and use it by just importing it as

import {getCurrentDate} from './utils'
console.log(getCurrentDate())

OPTION 2: or define and use in a class directly

getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

How do I create a foreign key in SQL Server?

I always use this syntax to create the foreign key constraint between 2 tables

Alter Table ForeignKeyTable
Add constraint `ForeignKeyTable_ForeignKeyColumn_FK`
`Foreign key (ForeignKeyColumn)` references `PrimaryKeyTable (PrimaryKeyColumn)`

i.e.

Alter Table tblEmployee
Add constraint tblEmployee_DepartmentID_FK
foreign key (DepartmentID) references tblDepartment (ID)

How to get the width and height of an android.widget.ImageView?

I could get image width and height by its drawable;

int width = imgView.getDrawable().getIntrinsicWidth();
int height = imgView.getDrawable().getIntrinsicHeight();

Count textarea characters

$("#textarea").keyup(function(){
  $("#count").text($(this).val().length);
});

The above will do what you want. If you want to do a count down then change it to this:

$("#textarea").keyup(function(){
  $("#count").text("Characters left: " + (500 - $(this).val().length));
});

Alternatively, you can accomplish the same thing without jQuery using the following code. (Thanks @Niet)

document.getElementById('textarea').onkeyup = function () {
  document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
};

Side-by-side list items as icons within a div (css)

I used a combination of the above to achieve a working result; Change float to Left and display Block the li itself HTML:

<ol class="foo">
    <li>bar1</li>
    <li>bar2</li>
</ol>

CSS:

.foo li {
    display: block;
    float: left;
    width: 100px;
    height: 100px;
    border: 1px solid black;
    margin: 2px;
}

How to create a GUID / UUID

One line solution using Blobs.

window.URL.createObjectURL(new Blob([])).substring(31);

The value at the end (31) depends on the length of the URL.

Is it .yaml or .yml?

.yaml is apparently the official extension, because some applications fail when using .yml. On the other hand I am not familiar with any applications which use YAML code, but fail with a .yaml extension.

I just stumbled across this, as I was used to writing .yml in Ansible and Docker Compose. Out of habit I used .yml when writing Netplan files which failed silently. I finally figured out my mistake. The author of a popular Ansible Galaxy role for Netplan makes the same assumption in his code:

- name: Capturing Existing Configurations
  find:
    paths: /etc/netplan
    patterns: "*.yml,*.yaml"
  register: _netplan_configs

Yet any files with a .yml extension get ignored by Netplan in the same way as files with a .bak extension. As Netplan is very quiet, and gives no feedback whatsoever on success, even with netplan apply --debug, a config such as 01-netcfg.yml will fail silently without any meaningful feedback.

Skip to next iteration in loop vba

I use Goto

  For x= 1 to 20

       If something then goto continue

       skip this code

  Continue:

  Next x

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

Understanding Matlab FFT example

1) Why does the x-axis (frequency) end at 500? How do I know that there aren't more frequencies or are they just ignored?

It ends at 500Hz because that is the Nyquist frequency of the signal when sampled at 1000Hz. Look at this line in the Mathworks example:

f = Fs/2*linspace(0,1,NFFT/2+1);

The frequency axis of the second plot goes from 0 to Fs/2, or half the sampling frequency. The Nyquist frequency is always half the sampling frequency, because above that, aliasing occurs: Aliasing illustration

The signal would "fold" back on itself, and appear to be some frequency at or below 500Hz.

2) How do I know the frequencies are between 0 and 500? Shouldn't the FFT tell me, in which limits the frequencies are?

Due to "folding" described above (the Nyquist frequency is also commonly known as the "folding frequency"), it is physically impossible for frequencies above 500Hz to appear in the FFT; higher frequencies will "fold" back and appear as lower frequencies.

Does the FFT only return the amplitude value without the frequency?

Yes, the MATLAB FFT function only returns one vector of amplitudes. However, they map to the frequency points you pass to it.

Let me know what needs clarification so I can help you further.

Java error: Only a type can be imported. XYZ resolves to a package

Are there more details? (Is this in a JSP as in the linked webpage?)

If so, you can always just use the fully qualified class name.
rather than:

import foo.bar.*;
Baz myBaz;

you can use

foo.bar.Baz myBaz;

jQuery Array of all selected checkboxes (by class)

You can also add underscore.js to your project and will be able to do it in one line:

_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})

How to assign a value to a TensorFlow variable?

Use Tensorflow eager execution mode which is latest.

import tensorflow as tf
tf.enable_eager_execution()
my_int_variable = tf.get_variable("my_int_variable", [1, 2, 3])
print(my_int_variable)

How to add a spinner icon to button when it's in the Loading state?

These are mine, based on pure SVG and CSS animations. Don't pay attention to JS code in the snippet bellow, it's just for demoing purposes. Feel free to make your custom ones basing on mine, it's super easy.

_x000D_
_x000D_
var svg = d3.select("svg"),_x000D_
    columnsCount = 3;_x000D_
_x000D_
['basic', 'basic2', 'basic3', 'basic4', 'loading', 'loading2', 'spin', 'chrome', 'chrome2', 'flower', 'flower2', 'backstreet_boys'].forEach(function(animation, i){_x000D_
  var x = (i%columnsCount+1) * 200-100,_x000D_
      y = 20 + (Math.floor(i/columnsCount) * 200);_x000D_
  _x000D_
  _x000D_
  svg.append("text")_x000D_
    .attr('text-anchor', 'middle')_x000D_
    .attr("x", x)_x000D_
    .attr("y", y)_x000D_
    .text((i+1)+". "+animation);_x000D_
  _x000D_
  svg.append("circle")_x000D_
    .attr("class", animation)_x000D_
    .attr("cx",  x)_x000D_
    .attr("cy",  y+40)_x000D_
    .attr("r",  16)_x000D_
});
_x000D_
circle {_x000D_
  fill: none;_x000D_
  stroke: #bbb;_x000D_
  stroke-width: 4_x000D_
}_x000D_
_x000D_
.basic {_x000D_
  animation: basic 0.5s linear infinite;_x000D_
  stroke-dasharray: 20 80;_x000D_
}_x000D_
_x000D_
@keyframes basic {_x000D_
  0%    {stroke-dashoffset: 100;}_x000D_
  100%  {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic2 {_x000D_
  animation: basic2 0.5s linear infinite;_x000D_
  stroke-dasharray: 80 20;_x000D_
}_x000D_
_x000D_
@keyframes basic2 {_x000D_
  0%    {stroke-dashoffset: 100;}_x000D_
  100%  {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic3 {_x000D_
  animation: basic3 0.5s linear infinite;_x000D_
  stroke-dasharray: 20 30;_x000D_
}_x000D_
_x000D_
@keyframes basic3 {_x000D_
  0%    {stroke-dashoffset: 100;}_x000D_
  100%  {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic4 {_x000D_
  animation: basic4 0.5s linear infinite;_x000D_
  stroke-dasharray: 10 23.3;_x000D_
}_x000D_
_x000D_
@keyframes basic4 {_x000D_
  0%    {stroke-dashoffset: 100;}_x000D_
  100%  {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.loading {_x000D_
  animation: loading 1s linear infinite;_x000D_
  stroke-dashoffset: 25;_x000D_
}_x000D_
_x000D_
@keyframes loading {_x000D_
  0%    {stroke-dashoffset: 0;    stroke-dasharray: 50 0; }_x000D_
  50%   {stroke-dashoffset: -100; stroke-dasharray: 0 50;}_x000D_
  100%  { stroke-dashoffset: -200;stroke-dasharray: 50 0;}_x000D_
}_x000D_
_x000D_
.loading2 {_x000D_
  animation: loading2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes loading2 {_x000D_
  0% {stroke-dasharray: 5 28.3;   stroke-dashoffset: 75;}_x000D_
  50% {stroke-dasharray: 45 5;    stroke-dashoffset: -50;}_x000D_
  100% {stroke-dasharray: 5 28.3; stroke-dashoffset: -125; }_x000D_
}_x000D_
_x000D_
.spin {_x000D_
  animation: spin 1s linear infinite;_x000D_
  stroke-dashoffset: 25;_x000D_
}_x000D_
_x000D_
@keyframes spin {_x000D_
  0%    {stroke-dashoffset: 0;    stroke-dasharray: 33.3 0; }_x000D_
  50%   {stroke-dashoffset: -100; stroke-dasharray: 0 33.3;}_x000D_
  100%  { stroke-dashoffset: -200;stroke-dasharray: 33.3 0;}_x000D_
}_x000D_
_x000D_
.chrome {_x000D_
  animation: chrome 2s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes chrome {_x000D_
  0%    {stroke-dasharray: 0 100; stroke-dashoffset: 25;}_x000D_
  25%   {stroke-dasharray: 75 25; stroke-dashoffset: 0;}_x000D_
  50%   {stroke-dasharray: 0 100;  stroke-dashoffset: -125;}_x000D_
  75%    {stroke-dasharray: 75 25; stroke-dashoffset: -150;}_x000D_
  100%   {stroke-dasharray: 0 100; stroke-dashoffset: -275;}_x000D_
}_x000D_
_x000D_
.chrome2 {_x000D_
  animation: chrome2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes chrome2 {_x000D_
  0%    {stroke-dasharray: 0 100; stroke-dashoffset: 25;}_x000D_
  25%   {stroke-dasharray: 50 50; stroke-dashoffset: 0;}_x000D_
  50%   {stroke-dasharray: 0 100;  stroke-dashoffset: -50;}_x000D_
  75%   {stroke-dasharray: 50 50;  stroke-dashoffset: -125;}_x000D_
  100%  {stroke-dasharray: 0 100;  stroke-dashoffset: -175;}_x000D_
}_x000D_
_x000D_
.flower {_x000D_
  animation: flower 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes flower {_x000D_
  0%    {stroke-dasharray: 0  20; stroke-dashoffset: 25;}_x000D_
  50%   {stroke-dasharray: 20 0;  stroke-dashoffset: -50;}_x000D_
  100%  {stroke-dasharray: 0 20;  stroke-dashoffset: -125;}_x000D_
}_x000D_
_x000D_
.flower2 {_x000D_
  animation: flower2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes flower2 {_x000D_
  0%    {stroke-dasharray: 5 20;  stroke-dashoffset: 25;}_x000D_
  50%   {stroke-dasharray: 20 5;  stroke-dashoffset: -50;}_x000D_
  100%  {stroke-dasharray: 5 20;  stroke-dashoffset: -125;}_x000D_
}_x000D_
_x000D_
.backstreet_boys {_x000D_
  animation: backstreet_boys 3s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes backstreet_boys {_x000D_
  0%    {stroke-dasharray: 5 28.3;  stroke-dashoffset: -225;}_x000D_
  15%    {stroke-dasharray: 5 28.3;  stroke-dashoffset: -300;}_x000D_
  30%   {stroke-dasharray: 5 20;  stroke-dashoffset: -300;}_x000D_
  45%    {stroke-dasharray: 5 20;  stroke-dashoffset: -375;}_x000D_
  60%   {stroke-dasharray: 5 15;  stroke-dashoffset: -375;}_x000D_
  75%    {stroke-dasharray: 5 15;  stroke-dashoffset: -450;}_x000D_
  90%   {stroke-dasharray: 5 15;  stroke-dashoffset: -525;}_x000D_
  100%   {stroke-dasharray: 5 28.3;  stroke-dashoffset: -925;}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>_x000D_
<svg width="600px" height="700px"></svg>
_x000D_
_x000D_
_x000D_

Also available on CodePen: https://codepen.io/anon/pen/PeRazr

How can I make my custom objects Parcelable?

It is very easy, you can use a plugin on android studio to make objects Parcelables.

public class Persona implements Parcelable {
String nombre;
int edad;
Date fechaNacimiento;

public Persona(String nombre, int edad, Date fechaNacimiento) {
    this.nombre = nombre;
    this.edad = edad;
    this.fechaNacimiento = fechaNacimiento;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(this.nombre);
    dest.writeInt(this.edad);
    dest.writeLong(fechaNacimiento != null ? fechaNacimiento.getTime() : -1);
}

protected Persona(Parcel in) {
    this.nombre = in.readString();
    this.edad = in.readInt();
    long tmpFechaNacimiento = in.readLong();
    this.fechaNacimiento = tmpFechaNacimiento == -1 ? null : new Date(tmpFechaNacimiento);
}

public static final Parcelable.Creator<Persona> CREATOR = new Parcelable.Creator<Persona>() {
    public Persona createFromParcel(Parcel source) {
        return new Persona(source);
    }

    public Persona[] newArray(int size) {
        return new Persona[size];
    }
};}

How do you check in python whether a string contains only numbers?

You'll want to use the isdigit method on your str object:

if len(isbn) == 10 and isbn.isdigit():

From the isdigit documentation:

str.isdigit()

Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

Tests not running in Test Explorer

I had a different solution to get my tests to run. My global packages folder didn't match what was in my .csproj This is what my .csproj looked like: UnitTest .csproj

I had to change my Version to 16.5.0 which i found was installed in my global packages folder. Now my tests are able to run: .nuget folder explorer

Can we have functions inside functions in C++?

You cannot define a free function inside another in C++.

How to allow <input type="file"> to accept only image files?

In html;

<input type="file" accept="image/*">

This will accept all image formats but no other file like pdf or video.

But if you are using django, in django forms.py;

image_field = forms.ImageField(Here_are_the_parameters)

Not able to start Genymotion device

For me it was related to the lack of virtual resources (Ram and CPU). Go to the virtual box, right click on device -> Setting and increase the value of each resource.

How to determine if a decimal/double is an integer?

Mark Rushakoff's answer may be simpler, but the following also work and may be more efficient since there is no implicit division operation:

     bool isInteger = (double)((int)f) == f ;

and

     bool isInteger = (decimal)((int)d) == d ;

If you want a single expression for both types, perhaps

     bool isInteger = (double)((int)val) == (double)val ;

Iterating on a file doesn't work the second time

Yes, that is normal behavior. You basically read to the end of the file the first time (you can sort of picture it as reading a tape), so you can't read any more from it unless you reset it, by either using f.seek(0) to reposition to the start of the file, or to close it and then open it again which will start from the beginning of the file.

If you prefer you can use the with syntax instead which will automatically close the file for you.

e.g.,

with open('baby1990.html', 'rU') as f:
  for line in f:
     print line

once this block is finished executing, the file is automatically closed for you, so you could execute this block repeatedly without explicitly closing the file yourself and read the file this way over again.

What is Activity.finish() method doing exactly?

When calling finish() on an activity, the method onDestroy() is executed. This method can do things like:

  1. Dismiss any dialogs the activity was managing.
  2. Close any cursors the activity was managing.
  3. Close any open search dialog

Also, onDestroy() isn't a destructor. It doesn't actually destroy the object. It's just a method that's called based on a certain state. So your instance is still alive and very well* after the superclass's onDestroy() runs and returns.Android keeps processes around in case the user wants to restart the app, this makes the startup phase faster. The process will not be doing anything and if memory needs to be reclaimed, the process will be killed

Metadata file '.dll' could not be found

In my case, I deleted the git folder and removed Git (Azure DevOps). This was the only method that I did that worked.

I tried clean, rebuild, reconfigure build, deleting bin and obj folders; nothing worked. When I removed solution of Git, voilá! It worked for me.

I don't understand, but this solved it for me.

Android set bitmap to Imageview

There is a library named Picasso which can efficiently load images from a URL. It can also load an image from a file.

Examples:

  1. Load URL into ImageView without generating a bitmap:

    Picasso.with(context) // Context
           .load("http://abc.imgur.com/gxsg.png") // URL or file
           .into(imageView); // An ImageView object to show the loaded image
    
  2. Load URL into ImageView by generating a bitmap:

    Picasso.with(this)
           .load(artistImageUrl)
           .into(new Target() {
               @Override
               public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
                   /* Save the bitmap or do something with it here */
    
                   // Set it in the ImageView
                   theView.setImageBitmap(bitmap)
               }
    
               @Override
               public void onBitmapFailed(Drawable errorDrawable) {
    
               }
    
               @Override
               public void onPrepareLoad(Drawable placeHolderDrawable) {
    
               }
           });
    

There are many more options available in Picasso. Here is the documentation.

Python code to remove HTML tags from a string

There's a simple way to this in any C-like language. The style is not Pythonic but works with pure Python:

def remove_html_markup(s):
    tag = False
    quote = False
    out = ""

    for c in s:
            if c == '<' and not quote:
                tag = True
            elif c == '>' and not quote:
                tag = False
            elif (c == '"' or c == "'") and tag:
                quote = not quote
            elif not tag:
                out = out + c

    return out

The idea based in a simple finite-state machine and is detailed explained here: http://youtu.be/2tu9LTDujbw

You can see it working here: http://youtu.be/HPkNPcYed9M?t=35s

PS - If you're interested in the class(about smart debugging with python) I give you a link: https://www.udacity.com/course/software-debugging--cs259. It's free!

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

This post is high up when you google that error message, which I got when installing security patch KB4505224 on SQL Server 2017 Express i.e. None of the above worked for me, but did consume several hours trying.

The solution for me, partly from here was:

  1. uninstall SQL Server
  2. in Regional Settings / Management / System Locale, "Beta: UTF-8 support" should be OFF
  3. re-install SQL Server
  4. Let Windows install the patch.

And all was well.

More on this here.

How to Set a Custom Font in the ActionBar Title?

Try using This

TextView headerText= new TextView(getApplicationContext());
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
headerText.setLayoutParams(lp);
headerText.setText("Welcome!");
headerText.setTextSize(20);
headerText.setTextColor(Color.parseColor("#FFFFFF"));
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/wesfy_regular.ttf");
headerText.setTypeface(tf);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(headerText);

How to print in C

printf is a fair bit more complicated than that. You have to supply a format string, and then the variables to apply to the format string. If you just supply one variable, C will assume that is the format string and try to print out all the bytes it finds in it until it hits a terminating nul (0x0).

So if you just give it an integer, it will merrily march through memory at the location your integer is stored, dumping whatever garbage is there to the screen, until it happens to come across a byte containing 0.

For a Java programmer, I'd imagine this is a rather rude introduction to C's lack of type checking. Believe me, this is only the tip of the iceberg. This is why, while I applaud your desire to expand your horizons by learning C, I highly suggest you do whatever you can to avoid writing real programs in it.

(This goes for everyone else reading this too.)

How to run multiple .BAT files within a .BAT file

Running multiple scripts in one I had the same issue. I kept having it die on the first one not realizing that it was exiting on the first script.

:: OneScriptToRunThemAll.bat
CALL ScriptA.bat
CALL ScriptB.bat
EXIT

:: ScriptA.bat
Do Foo
EXIT
::ScriptB.bat
Do bar
EXIT

I removed all 11 of my scripts EXIT lines and tried again and all 11 ran in order one at a time in the same command window.

:: OneScriptToRunThemAll.bat
CALL ScriptA.bat
CALL ScriptB.bat
EXIT

::ScriptA.bat
Do Foo

::ScriptB.bat
Do bar

How to initialize a vector in C++

With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do:

std::vector<int> v { 34,23 };
// or
// std::vector<int> v = { 34,23 };

Or even:

std::vector<int> v(2);
v = { 34,23 };

On compilers that don't support this feature (initializer lists) yet you can emulate this with an array:

int vv[2] = { 12,43 };
std::vector<int> v(&vv[0], &vv[0]+2);

Or, for the case of assignment to an existing vector:

int vv[2] = { 12,43 };
v.assign(&vv[0], &vv[0]+2);

Like James Kanze suggested, it's more robust to have functions that give you the beginning and end of an array:

template <typename T, size_t N>
T* begin(T(&arr)[N]) { return &arr[0]; }
template <typename T, size_t N>
T* end(T(&arr)[N]) { return &arr[0]+N; }

And then you can do this without having to repeat the size all over:

int vv[] = { 12,43 };
std::vector<int> v(begin(vv), end(vv));

Why is HttpContext.Current null?

In IIS7 with integrated mode, Current is not available in Application_Start. There is a similar thread here.

Adding item to Dictionary within loop

As per my understanding you want data in dictionary as shown below:

key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3

for this you can use list for each dictionary keys:

case_list = {}
for entry in entries_list:
    if key in case_list:
        case_list[key1].append(value)
    else:
        case_list[key1] = [value]

What is the most accurate way to retrieve a user's correct IP address in PHP?

Here is a shorter, cleaner way to get the IP address:

function get_ip_address(){
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(',', $_SERVER[$key]) as $ip){
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                    return $ip;
                }
            }
        }
    }
}

Your code seems to be pretty complete already, I cannot see any possible bugs in it (aside from the usual IP caveats), I would change the validate_ip() function to rely on the filter extension though:

public function validate_ip($ip)
{
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false)
    {
        return false;
    }

    self::$ip = sprintf('%u', ip2long($ip)); // you seem to want this

    return true;
}

Also your HTTP_X_FORWARDED_FOR snippet can be simplified from this:

// check for IPs passing through proxies
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
    // check if multiple ips exist in var
    if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false)
    {
        $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        
        foreach ($iplist as $ip)
        {
            if ($this->validate_ip($ip))
                return $ip;
        }
    }
    
    else
    {
        if ($this->validate_ip($_SERVER['HTTP_X_FORWARDED_FOR']))
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
}

To this:

// check for IPs passing through proxies
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
    $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        
    foreach ($iplist as $ip)
    {
        if ($this->validate_ip($ip))
            return $ip;
    }
}

You may also want to validate IPv6 addresses.

When to use StringBuilder in Java

Some compilers may not replace any string concatenations with StringBuilder equivalents. Be sure to consider which compilers your source will use before relying on compile time optimizations.

How do I import modules or install extensions in PostgreSQL 9.1+?

Into psql terminal put:

\i <path to contrib files>

in ubuntu it usually is /usr/share/postgreslq/<your pg version>/contrib/<contrib file>.sql

Numpy matrix to array

A, = np.array(M.T)

depends what you mean by elegance i suppose but thats what i would do

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

If you've SQLServer Reporting Services running locally then you need to stop that also..

How to set image on QPushButton?

Just use this code

QPixmap pixmap("path_to_icon");
QIcon iconBack(pixmap);

Note that:"path_to_icon" is the path of image icon in file .qrc of your project You can find how to add .qrc file here

Bootstrap table striped: How do I change the stripe background colour?

You have two options, either you override the styles with a custom stylesheet, or you edit the main bootstrap css file. I prefer the former.

Your custom styles should be linked after bootstrap.

<link rel="stylesheet" src="bootstrap.css">
<link rel="stylesheet" src="custom.css">

In custom.css

.table-striped>tr:nth-child(odd){
   background-color:red;
}

CSS3 100vh not constant in mobile browser

The VH 100 does not work well on mobile as it does not factor in the iOS bar (or similar functionality on other platforms).

One solution that works well is to use JavaScript "window.innerHeight".

Simply assign the height of the element to this value e.g. $('.element-name').height(window.innerHeight);

Note: It may be useful to create a function in JS, so that the height can change when the screen is resized. However, I would suggest only calling the function when the width of the screen is changed, this way the element will not jump in height when the iOS bar disappears when the user scrolls down the page.

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

You may also get this error if you have a name clash of a view and a module. I've got the error when i distribute my view files under views folder, /views/view1.py, /views/view2.py and imported some model named table.py in view2.py which happened to be a name of a view in view1.py. So naming the view functions as v_table(request,id) helped.

Keylistener in Javascript

The code is

document.addEventListener('keydown', function(event){
    alert(event.keyCode);
} );

This return the ascii code of the key. If you need the key representation, use event.key (This will return 'a', 'o', 'Alt'...)

Checking host availability by using ping in bash scripts

I liked the idea of checking a list like:

for i in `cat Hostlist`
do  
  ping -c1 -w2 $i | grep "PING" | awk '{print $2,$3}'
done

but that snippet doesn't care if a host is unreachable, so is not a great answer IMHO.

I ran with it and wrote

for i in `cat Hostlist`
do
  ping -c1 -w2 $i >/dev/null 2>&1 ; echo $i $?
done

And I can then handle each accordingly.

How to use the CSV MIME-type?

You could try to force the browser to open a "Save As..." dialog by doing something like:

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');
echo "cell 1, cell 2";

Which should work across most major browsers.

Can you do a partial checkout with Subversion?

Indeed, thanks to the comments to my post here, it looks like sparse directories are the way to go. I believe the following should do it:

svn checkout --depth empty http://svnserver/trunk/proj
svn update --set-depth infinity proj/foo
svn update --set-depth infinity proj/bar
svn update --set-depth infinity proj/baz

Alternatively, --depth immediates instead of empty checks out files and directories in trunk/proj without their contents. That way you can see which directories exist in the repository.


As mentioned in @zigdon's answer, you can also do a non-recursive checkout. This is an older and less flexible way to achieve a similar effect:

svn checkout --non-recursive http://svnserver/trunk/proj
svn update trunk/foo
svn update trunk/bar
svn update trunk/baz

Can Mysql Split a column?

You may get what you want by using the MySQL REGEXP or LIKE.

See the MySQL Docs on Pattern Matching

How to pick just one item from a generator?

I don't believe there's a convenient way to retrieve an arbitrary value from a generator. The generator will provide a next() method to traverse itself, but the full sequence is not produced immediately to save memory. That's the functional difference between a generator and a list.

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

I'd try something like:

#!/usr/bin/python
from __future__ import print_function

import shlex
from subprocess import Popen, PIPE

def shlep(cmd):
    '''shlex split and popen
    '''
    parsed_cmd = shlex.split(cmd)
    ## if parsed_cmd[0] not in approved_commands:
    ##    raise ValueError, "Bad User!  No output for you!"
    proc = Popen(parsed_command, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    return (proc.returncode, out, err)

... In other words let shlex.split() do most of the work. I would NOT attempt to parse the shell's command line, find pipe operators and set up your own pipeline. If you're going to do that then you'll basically have to write a complete shell syntax parser and you'll end up doing an awful lot of plumbing.

Of course this raises the question, why not just use Popen with the shell=True (keyword) option? This will let you pass a string (no splitting nor parsing) to the shell and still gather up the results to handle as you wish. My example here won't process any pipelines, backticks, file descriptor redirection, etc that might be in the command, they'll all appear as literal arguments to the command. Thus it is still safer then running with shell=True ... I've given a silly example of checking the command against some sort of "approved command" dictionary or set --- through it would make more sense to normalize that into an absolute path unless you intend to require that the arguments be normalized prior to passing the command string to this function.

how to use Blob datatype in Postgres

I think this is the most comprehensive answer on the PostgreSQL wiki itself: https://wiki.postgresql.org/wiki/BinaryFilesInDB

Read the part with the title 'What is the best way to store the files in the Database?'

Using JAXB to unmarshal/marshal a List<String>

If you are using maven in the jersey project add below in pom.xml and update project dependencies so that Jaxb is able to detect model class and convert list to Media type application XML:

<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.2.11</version>
</dependency>

Rearrange columns using cut

Using join:

join -t $'\t' -o 1.2,1.1 file.txt file.txt

Notes:

  • -t $'\t' In GNU join the more intuitive -t '\t' without the $ fails, (coreutils v8.28 and earlier?); it's probably a bug that a workaround like $ should be necessary. See: unix join separator char.

  • join needs two filenames, even though there's just one file being worked on. Using the same name twice tricks join into performing the desired action.

  • For systems with low resources join offers a smaller footprint than some of the tools used in other answers:

    wc -c $(realpath `which cut join sed awk perl`) | head -n -1
      43224 /usr/bin/cut
      47320 /usr/bin/join
     109840 /bin/sed
     658072 /usr/bin/gawk
    2093624 /usr/bin/perl
    

Understanding the results of Execute Explain Plan in Oracle SQL Developer

The output of EXPLAIN PLAN is a debug output from Oracle's query optimiser. The COST is the final output of the Cost-based optimiser (CBO), the purpose of which is to select which of the many different possible plans should be used to run the query. The CBO calculates a relative Cost for each plan, then picks the plan with the lowest cost.

(Note: in some cases the CBO does not have enough time to evaluate every possible plan; in these cases it just picks the plan with the lowest cost found so far)

In general, one of the biggest contributors to a slow query is the number of rows read to service the query (blocks, to be more precise), so the cost will be based in part on the number of rows the optimiser estimates will need to be read.

For example, lets say you have the following query:

SELECT emp_id FROM employees WHERE months_of_service = 6;

(The months_of_service column has a NOT NULL constraint on it and an ordinary index on it.)

There are two basic plans the optimiser might choose here:

  • Plan 1: Read all the rows from the "employees" table, for each, check if the predicate is true (months_of_service=6).
  • Plan 2: Read the index where months_of_service=6 (this results in a set of ROWIDs), then access the table based on the ROWIDs returned.

Let's imagine the "employees" table has 1,000,000 (1 million) rows. Let's further imagine that the values for months_of_service range from 1 to 12 and are fairly evenly distributed for some reason.

The cost of Plan 1, which involves a FULL SCAN, will be the cost of reading all the rows in the employees table, which is approximately equal to 1,000,000; but since Oracle will often be able to read the blocks using multi-block reads, the actual cost will be lower (depending on how your database is set up) - e.g. let's imagine the multi-block read count is 10 - the calculated cost of the full scan will be 1,000,000 / 10; Overal cost = 100,000.

The cost of Plan 2, which involves an INDEX RANGE SCAN and a table lookup by ROWID, will be the cost of scanning the index, plus the cost of accessing the table by ROWID. I won't go into how index range scans are costed but let's imagine the cost of the index range scan is 1 per row; we expect to find a match in 1 out of 12 cases, so the cost of the index scan is 1,000,000 / 12 = 83,333; plus the cost of accessing the table (assume 1 block read per access, we can't use multi-block reads here) = 83,333; Overall cost = 166,666.

As you can see, the cost of Plan 1 (full scan) is LESS than the cost of Plan 2 (index scan + access by rowid) - which means the CBO would choose the FULL scan.

If the assumptions made here by the optimiser are true, then in fact Plan 1 will be preferable and much more efficient than Plan 2 - which disproves the myth that FULL scans are "always bad".

The results would be quite different if the optimiser goal was FIRST_ROWS(n) instead of ALL_ROWS - in which case the optimiser would favour Plan 2 because it will often return the first few rows quicker, at the cost of being less efficient for the entire query.

Kotlin - How to correctly concatenate a String

Try this, I think this is a natively way to concatenate strings in Kotlin:

val result = buildString{
    append("a")
    append("b")
}

println(result)

// you will see "ab" in console.

How to completely DISABLE any MOUSE CLICK

The easiest way to freeze the UI would be to make the AJAX call synchronous.

Usually synchronous AJAX calls defeat the purpose of using AJAX because it freezes the UI, but if you want to prevent the user from interacting with the UI, then do it.

javascript convert int to float

toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.

var fval = 4;

console.log(fval.toFixed(2)); // prints 4.00

Return multiple values in JavaScript?

In JS, we can easily return a tuple with an array or object, but do not forget! => JS is a callback oriented language, and there is a little secret here for "returning multiple values" that nobody has yet mentioned, try this:

var newCodes = function() {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    return dCodes, dCodes2;
};

becomes

var newCodes = function(fg, cb) {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    cb(null, dCodes, dCodes2);
};

:)

bam! This is simply another way of solving your problem.

C# Checking if button was clicked

i am very new to this website. I am an undergraduate student, doing my Bachelor Of Computer Application. I am doing a simple program in Visual Studio using C# and I came across the same problem, how to check whether a button is clicked? I wanted to do this,

if(-button1 is clicked-) then
{
this should happen;
}
if(-button2 is clicked-) then
{
this should happen;
}

I didn't know what to do, so I tried searching for the solution in the internet. I got many solutions which didn't help me. So, I tried something on my own and did this,

int i;
private void button1_Click(object sender, EventArgs e)
        {
            i = 1;
            label3.Text = "Principle";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Simple Interest";
        }


private void button2_Click(object sender, EventArgs e)
        {
            i = 2;
            label3.Text = "SI";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Principle";
        }
private void button5_Click(object sender, EventArgs e)
        {

            try
            {
                if (i == 1)
                {
                    si = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text)) / 100;
                    textBox4.Text = Convert.ToString(si);
                }
                if (i == 2)
                {
                    p = (Convert.ToInt32(textBox1.Text) * 100) / (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text));
                    textBox4.Text = Convert.ToString(p);
                }

I declared a variable "i" and assigned it with different values in different buttons and checked the value of i in the if function. It worked. Give your suggestions if any. Thank you.

Textarea onchange detection

You can listen to event on change of textarea and do the changes as per you want. Here is one example.

_x000D_
_x000D_
const textArea = document.getElementById('my_text_area');
textArea.addEventListener('input', () => {
    var textLn =  textArea.value.length;
    if(textLn >= 100) {
        textArea.style.fontSize = '10pt';
    }
})
_x000D_
<html>
    <textarea id='my_text_area' rows="4" cols="50" style="font-size:40pt">
This text will change font after 100.
    </textarea>
</html>
_x000D_
_x000D_
_x000D_

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Try this, it must be work, otherwise you need to print the error to specify your problem

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT * from Users WHERE UserName LIKE '$username'";
$result = mysql_query($sql,$con);

while($row = mysql_fetch_array($result))
{
    echo $row['FirstName'];
}

TypeScript and React - children type?

The general way to find any type is by example. The beauty of typescript is that you have access to all types, so long as you have the correct @types/ files.

To answer this myself I just thought of a component react uses that has the children prop. The first thing that came to mind? How about a <div />?

All you need to do is open vscode and create a new .tsx file in a react project with @types/react.

import React from 'react';

export default () => (
  <div children={'test'} />
);

Hovering over the children prop shows you the type. And what do you know -- Its type is ReactNode (no need for ReactNode[]).

enter image description here

Then if you click into the type definition it brings you straight to the definition of children coming from DOMAttributes interface.

// node_modules/@types/react/index.d.ts
interface DOMAttributes<T> {
  children?: ReactNode;
  ...
}

Note: This process should be used to find any unknown type! All of them are there just waiting for you to find them :)

PHP - Insert date into mysql

Unless you want to insert different dates than "today", you can use CURDATE():

$sql = 'INSERT INTO data_tables (title, date_of_event) VALUES ("%s", CURDATE())';
$sql = sprintf ($sql, $_POST['post_title']);

PS! Please do not forget to sanitize your MySQL input, especially via mysql_real_escape_string ()

How to temporarily disable a click handler in jQuery?

This is a more idiomatic alternative to the artificial state variable solutions:

$("#button_id").one('click', DoSomething);

function DoSomething() {
  // do something.

  $("#button_id").one('click', DoSomething);
}

One will only execute once (until attached again). More info here: http://docs.jquery.com/Events/one

Fast Linux file count for a large number of files

Surprisingly for me, a bare-bones find is very much comparable to ls -f

> time ls -f my_dir | wc -l
17626

real    0m0.015s
user    0m0.011s
sys     0m0.009s

versus

> time find my_dir -maxdepth 1 | wc -l
17625

real    0m0.014s
user    0m0.008s
sys     0m0.010s

Of course, the values on the third decimal place shift around a bit every time you execute any of these, so they're basically identical. Notice however that find returns one extra unit, because it counts the actual directory itself (and, as mentioned before, ls -f returns two extra units, since it also counts . and ..).

How can one change the timestamp of an old commit in Git?

You can do an interactive rebase and choose edit for the commit whose date you would like to alter. When the rebase process stops for amending the commit you type in for instance:

git commit --amend --date="Wed Feb 16 14:00 2011 +0100"

Afterwards you continue your interactive rebase.

UPDATE (in response to the comment of studgeek): to change the commit date instead of the author date:

GIT_COMMITTER_DATE="Wed Feb 16 14:00 2011 +0100" git commit --amend

The lines above set an environment variable GIT_COMMITTER_DATE which is used in amend commit.

Everything is tested in Git Bash.

Github "Updates were rejected because the remote contains work that you do not have locally."

If you are using Visual S2019, Create a new local branch as shown in following, and then push the changes to the repo.

VS2019 local branch

How to get Spinner value?

The Spinner should fire an "OnItemSelected" event when something is selected:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        Object item = parent.getItemAtPosition(pos);
    }
    public void onNothingSelected(AdapterView<?> parent) {
    }
});

Remove last character from C++ string

str.erase(str.begin() + str.size() - 1)

str.erase(str.rbegin()) does not compile unfortunately, since reverse_iterator cannot be converted to a normal_iterator.

C++11 is your friend in this case.

How to use ESLint with Jest

some of the answers assume you have 'eslint-plugin-jest' installed, however without needing to do that, you can simply do this in your .eslintrc file, add:

  "globals": {
    "jest": true,
  }

How to select true/false based on column value?

What does the UDF EntityHasProfile() do?

Typically you could do something like this with a LEFT JOIN:

SELECT EntityId, EntityName, CASE WHEN EntityProfileIs IS NULL THEN 0 ELSE 1 END AS Has Profile
FROM Entities
LEFT JOIN EntityProfiles
    ON EntityProfiles.EntityId = Entities.EntityId

This should eliminate a need for a costly scalar UDF call - in my experience, scalar UDFs should be a last resort for most database design problems in SQL Server - they are simply not good performers.

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

When I use junit5, it's working. But every time I execute gradle --clean, I get Class not found error. Then I add this to build.gradle to resolve my problem and I can still use junit4:

test {
}

Laravel redirect back to original destination after login

Here is my solution for 5.1. I needed someone to click a "Like" button on a post, get redirected to login, then return to the original page. If they were already logged in, the href of the "Like" button was intercepted with JavaScript and turned into an AJAX request.

The button is something like <a href="/like/931">Like This Post!</a>. /like/931 is handled by a LikeController that requires the auth middleware.

In the Authenticate middleware (the handle() function), add something like this at the start:

    if(!str_contains($request->session()->previousUrl(), "/auth/login")) {
        $request->session()->put('redirectURL', $request->session()->previousUrl());
        $request->session()->save();
    }

Change /auth/login to whatever your URL is for logging in. This code saves the original page's URL in the session unless the URL is the login URL. This is required because it appears as though this middleware gets called twice. I am not sure why or if that's true. But if you don't check for that conditional, it will be equal to the correct original page, and then somehow get chanced to /auth/login. There is probably a more elegant way to do this.

Then, in the LikeController or whatever controller you have that handles the URL for the button pushed on the original page:

//some code here that adds a like to the database
//...
return redirect($request->session()->get('redirectURL'));

This method is super simple, doesn't require overriding any existing functions, and works great. It is possible there is some easier way for Laravel to do this, but I am not sure what it is. Using the intended() function doesn't work in my case because the LikeController needed to also know what the previous URL was to redirect back to it. Essentially two levels of redirection backwards.

How to convert std::string to LPCSTR?

These are Microsoft defined typedefs which correspond to:

LPCSTR: pointer to null terminated const string of char

LPSTR: pointer to null terminated char string of char (often a buffer is passed and used as an 'output' param)

LPCWSTR: pointer to null terminated string of const wchar_t

LPWSTR: pointer to null terminated string of wchar_t (often a buffer is passed and used as an 'output' param)

To "convert" a std::string to a LPCSTR depends on the exact context but usually calling .c_str() is sufficient.

This works.

void TakesString(LPCSTR param);

void f(const std::string& param)
{
    TakesString(param.c_str());
}

Note that you shouldn't attempt to do something like this.

LPCSTR GetString()
{
    std::string tmp("temporary");
    return tmp.c_str();
}

The buffer returned by .c_str() is owned by the std::string instance and will only be valid until the string is next modified or destroyed.

To convert a std::string to a LPWSTR is more complicated. Wanting an LPWSTR implies that you need a modifiable buffer and you also need to be sure that you understand what character encoding the std::string is using. If the std::string contains a string using the system default encoding (assuming windows, here), then you can find the length of the required wide character buffer and perform the transcoding using MultiByteToWideChar (a Win32 API function).

e.g.

void f(const std:string& instr)
{
    // Assumes std::string is encoded in the current Windows ANSI codepage
    int bufferlen = ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), NULL, 0);

    if (bufferlen == 0)
    {
        // Something went wrong. Perhaps, check GetLastError() and log.
        return;
    }

    // Allocate new LPWSTR - must deallocate it later
    LPWSTR widestr = new WCHAR[bufferlen + 1];

    ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), widestr, bufferlen);

    // Ensure wide string is null terminated
    widestr[bufferlen] = 0;

    // Do something with widestr

    delete[] widestr;
}

PHP Fatal error when trying to access phpmyadmin mb_detect_encoding

I had the same problem on my windows7- 32 bit:

1."PHP Fatal error: Call to undefined function mb_detect_encoding() in /usr/share/php/gettext/gettext.inc on line 177"

when i opened my php.ini file , "extension_dir" line looked like following :

extension_dir = "C:/wamp/bin/php/php5.4.16/ext/"

which i changed to :

extension_dir = "C:\wamp\bin\php\php5.4.16\ext\"

and it worked.

Wait for page load in Selenium

Use class WebDriverWait

Also see here

You can expect to show some element. something like in C#:

WebDriver _driver = new WebDriver();
WebDriverWait _wait = new WebDriverWait(_driver, new TimeSpan(0, 1, 0));

_wait.Until(d => d.FindElement(By.Id("Id_Your_UIElement"));

How to convert 'binary string' to normal string in Python3?

Decode it.

>>> b'a string'.decode('ascii')
'a string'

To get bytes from string, encode it.

>>> 'a string'.encode('ascii')
b'a string'

Sort an Array by keys based on another Array?

Just use array_merge or array_replace. Array_merge works by starting with the array you give it (in the proper order) and overwriting/adding the keys with data from your actual array:

$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';

$properOrderedArray = array_merge(array_flip(array('name', 'dob', 'address')), $customer);
//Or:
$properOrderedArray = array_replace(array_flip(array('name', 'dob', 'address')), $customer);

//$properOrderedArray -> array('name' => 'Tim', 'address' => '123 fake st', 'dob' => '12/08/1986', 'dontSortMe' => 'this value doesnt need to be sorted')

ps - I'm answering this 'stale' question, because I think all the loops given as previous answers are overkill.

Cosine Similarity between 2 Number Lists

I don't suppose performance matters much here, but I can't resist. The zip() function completely recopies both vectors (more of a matrix transpose, actually) just to get the data in "Pythonic" order. It would be interesting to time the nuts-and-bolts implementation:

import math
def cosine_similarity(v1,v2):
    "compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||)"
    sumxx, sumxy, sumyy = 0, 0, 0
    for i in range(len(v1)):
        x = v1[i]; y = v2[i]
        sumxx += x*x
        sumyy += y*y
        sumxy += x*y
    return sumxy/math.sqrt(sumxx*sumyy)

v1,v2 = [3, 45, 7, 2], [2, 54, 13, 15]
print(v1, v2, cosine_similarity(v1,v2))

Output: [3, 45, 7, 2] [2, 54, 13, 15] 0.972284251712

That goes through the C-like noise of extracting elements one-at-a-time, but does no bulk array copying and gets everything important done in a single for loop, and uses a single square root.

ETA: Updated print call to be a function. (The original was Python 2.7, not 3.3. The current runs under Python 2.7 with a from __future__ import print_function statement.) The output is the same, either way.

CPYthon 2.7.3 on 3.0GHz Core 2 Duo:

>>> timeit.timeit("cosine_similarity(v1,v2)",setup="from __main__ import cosine_similarity, v1, v2")
2.4261788514654654
>>> timeit.timeit("cosine_measure(v1,v2)",setup="from __main__ import cosine_measure, v1, v2")
8.794677709375264

So, the unpythonic way is about 3.6 times faster in this case.

Margin between items in recycler view Android

If you want to do it in XML, jus set paddingTopand paddingLeft to your RecyclerView and equal amount of layoutMarginBottom and layoutMarginRight to the item you inflate into your RecyclerView(or vice versa).

Fixing Segmentation faults in C++

Before the problem arises, try to avoid it as much as possible:

  • Compile and run your code as often as you can. It will be easier to locate the faulty part.
  • Try to encapsulate low-level / error prone routines so that you rarely have to work directly with memory (pay attention to the modelization of your program)
  • Maintain a test-suite. Having an overview of what is currently working, what is no more working etc, will help you to figure out where the problem is (Boost test is a possible solution, I don't use it myself but the documentation can help to understand what kind of information must be displayed).

Use appropriate tools for debugging. On Unix:

  • GDB can tell you where you program crash and will let you see in what context.
  • Valgrind will help you to detect many memory-related errors.
  • With GCC you can also use mudflap With GCC, Clang and since October experimentally MSVC you can use Address/Memory Sanitizer. It can detect some errors that Valgrind doesn't and the performance loss is lighter. It is used by compiling with the-fsanitize=address flag.

Finally I would recommend the usual things. The more your program is readable, maintainable, clear and neat, the easiest it will be to debug.

Copy every nth line from one sheet to another

If your original data is in column form with multiple columns and the first entry of your original data in C42, and you want your new (down-sampled) data to be in column form as well, but only every seventh row, then you will also need to subtract out the row number of the first entry, like so:

=OFFSET(C$42,(ROW(C42)-ROW(C$42))*7,0)

Which Android IDE is better - Android Studio or Eclipse?

Both are equally good. With Android Studio you have ADT tools integrated, and with eclipse you need to integrate them manually. With Android Studio, it feels like a tool designed from the outset with Android development in mind. Go ahead, they have same features.

Sass Variable in CSS calc() function

you can use your verbal #{your verbal}

python: order a list of numbers without built-in sort, min, max function

How do I keep looping through until the len(new_list) = len(data_list)

while len(new_list) != len(data_list):
    # ...

Maybe like this?

And no, it’s not necessary to create a new list; most sorting algorithms work by changing the list in place.

What you probably trying to do is Selection sort with a separate list. See the Wikipedia article for more information about that sorting algorithm and you’ll see how it works with a single list, and how efficient it is (spoiler: it isn’t).

Android: alternate layout xml for landscape mode

The layouts in /res/layout are applied to both portrait and landscape, unless you specify otherwise. Let’s assume we have /res/layout/home.xml for our homepage and we want it to look differently in the 2 layout types.

  1. create folder /res/layout-land (here you will keep your landscape adjusted layouts)
  2. copy home.xml there
  3. make necessary changes to it

Source

Android emulator doesn't take keyboard input - SDK tools rev 20

In Android Studio, open AVD Manager (Tools > Android > AVD Manager). Tap the Edit button of the emulator: enter image description here

Select "Show Advanced Settings" enter image description here

Check "Enable keyboard input" enter image description here

Click Finish and start the emulator to enjoy the keyboard input.

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I have solved this issue by below steps:

  1. Right click the Maven Project -> Build Path -> Configure Build Path
  2. In Order and Export tab, you can see the message like '2 build path entries are missing'
  3. Now select 'JRE System Library' and 'Maven Dependencies' checkbox
  4. Click OK

Now you can see below in all type of Explorers (Package or Project or Navigator)

src/main/java

src/main/resources

src/test/java

Java Synchronized list

It will give consistent behavior for add/remove operations. But while iterating you have to explicitly synchronized. Refer this link

What's the best way to store a group of constants that my program uses?

If these Constants are service references or switches that effect the application behavior I would set them up as Application user settings. That way if they need to be changed you do not have to recompile and you can still reference them through the static properties class.

Properties.Settings.Default.ServiceRef

How do I pass data to Angular routed components?

say you have

  1. component1.ts
  2. component1.html

and you want to pass data to component2.ts.

  • in component1.ts is a variable with data say

      //component1.ts
      item={name:"Nelson", bankAccount:"1 million dollars"}
    
      //component1.html
       //the line routerLink="/meter-readings/{{item.meterReadingId}}" has nothing to 
      //do with this , replace that with the url you are navigating to
      <a
        mat-button
        [queryParams]="{ params: item | json}"
        routerLink="/meter-readings/{{item.meterReadingId}}"
        routerLinkActive="router-link-active">
        View
      </a>
    
      //component2.ts
      import { ActivatedRoute} from "@angular/router";
      import 'rxjs/add/operator/filter';
    
      /*class name etc and class boiler plate */
      data:any //will hold our final object that we passed 
      constructor(
      private route: ActivatedRoute,
      ) {}
    
     ngOnInit() {
    
     this.route.queryParams
      .filter(params => params.reading)
      .subscribe(params => {
      console.log(params); // DATA WILL BE A JSON STRING- WE PARSE TO GET BACK OUR 
                           //OBJECT
    
      this.data = JSON.parse(params.item) ;
    
      console.log(this.data,'PASSED DATA'); //Gives {name:"Nelson", bankAccount:"1 
                                            //million dollars"}
       });
      }
    

Concatenation of strings in Lua

As other answers have said, the string concatenation operator in Lua is two dots.

Your simple example would be written like this:

filename = "checkbook"
filename = filename .. ".tmp"

However, there is a caveat to be aware of. Since strings in Lua are immutable, each concatenation creates a new string object and copies the data from the source strings to it. That makes successive concatenations to a single string have very poor performance.

The Lua idiom for this case is something like this:

function listvalues(s)
    local t = { }
    for k,v in ipairs(s) do
        t[#t+1] = tostring(v)
    end
    return table.concat(t,"\n")
end

By collecting the strings to be concatenated in an array t, the standard library routine table.concat can be used to concatenate them all up (along with a separator string between each pair) without unnecessary string copying.

Update: I just noticed that I originally wrote the code snippet above using pairs() instead of ipairs().

As originally written, the function listvalues() would indeed produce every value from the table passed in, but not in a stable or predictable order. On the other hand, it would include values who's keys were not positive integers in the span of 1 to #s. That is what pairs() does: it produces every single (key,value) pair stored in the table.

In most cases where you would be using something like listvaluas() you would be interested in preserving their order. So a call written as listvalues{13, 42, 17, 4} would produce a string containing those value in that order. However, pairs() won't do that, it will itemize them in some order that depends on the underlying implementation of the table data structure. It is known that the order not only depends on the keys, but also on the order in which the keys were inserted and other keys removed.

Of course ipairs() isn't a perfect answer either. It only enumerates those values of the table that form a "sequence". That is, those values who's keys form an unbroken block spanning from 1 to some upper bound, which is (usually) also the value returned by the # operator. (In many cases, the function ipairs() itself is better replaced by a simpler for loop that just counts from 1 to #s. This is the recommended practice in Lua 5.2 and in LuaJIT where the simpler for loop can be more efficiently implemented than the ipairs() iterator.)

If pairs() really is the right approach, then it is usually the case that you want to print both the key and the value. This reduces the concerns about order by making the data self-describing. Of course, since any Lua type (except nil and the floating point NaN) can be used as a key (and NaN can also be stored as a value) finding a string representation is left as an exercise for the student. And don't forget about trees and more complex structures of tables.

How do I check if a file exists in Java?

You can use the following: File.exists()

How to play or open *.mp3 or *.wav sound file in c++ program?

If you want to play the *.mp3 or *.wav file, i think the easiest way would be to use SFML.

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

I haven't figure out the reason but reinstalling the .pfx certificate(both in current user and local machine) works for me.

How can I get href links from HTML using Python?

Try with Beautifulsoup:

from BeautifulSoup import BeautifulSoup
import urllib2
import re

html_page = urllib2.urlopen("http://www.yourwebsite.com")
soup = BeautifulSoup(html_page)
for link in soup.findAll('a'):
    print link.get('href')

In case you just want links starting with http://, you should use:

soup.findAll('a', attrs={'href': re.compile("^http://")})

In Python 3 with BS4 it should be:

from bs4 import BeautifulSoup
import urllib.request

html_page = urllib.request.urlopen("http://www.yourwebsite.com")
soup = BeautifulSoup(html_page, "html.parser")
for link in soup.findAll('a'):
    print(link.get('href'))

How to debug Spring Boot application with Eclipse?

With eclipse or any other IDE, just right click on your main spring boot application and click "debug as java application"

How to move a marker in Google Maps API

moveBus() is getting called before initialize(). Try putting that line at the end of your initialize() function. Also Lat/Lon 0,0 is off the map (it's coordinates, not pixels), so you can't see it when it moves. Try 54,54. If you want the center of the map to move to the new location, use panTo().

Demo: http://jsfiddle.net/ThinkingStiff/Rsp22/

HTML:

<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>

CSS:

#map-canvas 
{ 
height: 400px; 
width: 500px;
}

Script:

function initialize() {

    var myLatLng = new google.maps.LatLng( 50, 50 ),
        myOptions = {
            zoom: 4,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            },
        map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ),
        marker = new google.maps.Marker( {position: myLatLng, map: map} );

    marker.setMap( map );
    moveBus( map, marker );

}

function moveBus( map, marker ) {

    marker.setPosition( new google.maps.LatLng( 0, 0 ) );
    map.panTo( new google.maps.LatLng( 0, 0 ) );

};

initialize();

How to write an XPath query to match two attributes?

//div[@id='..' and @class='...]

should do the trick. That's selecting the div operators that have both attributes of the required value.

It's worth using one of the online XPath testbeds to try stuff out.