Programs & Examples On #Right justified

Right justify is text or page formatting that aligns text along the right side of a page. This layout has a ragged right edge and a straight left edge.

SELECT * WHERE NOT EXISTS

SELECT * from employees
WHERE NOT EXISTS (SELECT name FROM eotm_dyn)

Never returns any records unless eotm_dyn is empty. You need to some kind of criteria on SELECT name FROM eotm_dyn like

SELECT * from employees
WHERE NOT EXISTS (
    SELECT name FROM eotm_dyn WHERE eotm_dyn.employeeid = employees.employeeid
)

assuming that the two tables are linked by a foreign key relationship. At this point you could use a variety of other options including a LEFT JOIN. The optimizer will typically handle them the same in most cases, however.

How to do SQL Like % in Linq?

Contains is used in Linq ,Just like Like is used in SQL .

string _search="/12/";

. . .

.Where(s => s.Hierarchy.Contains(_search))

You can write your SQL script in Linq as Following :

 var result= Organizations.Join(OrganizationsHierarchy.Where(s=>s.Hierarchy.Contains("/12/")),s=>s.Id,s=>s.OrganizationsId,(org,orgH)=>new {org,orgH});

How to find the process id of a running Java process on Windows? And how to kill the process alone?

You can use the jps utility that is included in the JDK to find the process id of a Java process. The output will show you the name of the executable JAR file or the name of the main class.

Then use the Windows task manager to terminate the process. If you want to do it on the command line, use

TASKKILL /PID %PID%

rbenv not changing ruby version

run:

rbenv init

After I ran that, when i set my local rbenv version:

rbenv local 2.4.0

then my ruby -v and my rbenv local versions coincided.

Note: You might also want to exit the directory you're in and then go back into it, i've noticed that was necessary for me in order to get things to work.

Detecting an undefined object property

In recent JavaScript release there is new chaining operator introduced, which is most probably best way to check if property exists else it will give you undefined

see example below

  const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined

We can replace this old syntax

if (response && response.data && response.data.someData && response.data.someData.someMoreData) {}

with this neater syntax

if( response?.data?.someData?.someMoreData) {}

This syntax is not supported in IE, Opera, safari & samsund android

for more detail you can check this URL

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

I ran into this issue and found that mysqlclient needs to know where to find openssl, and OSX hides this by default.

Locate openssl with brew info openssl, and then add the path to your openssl bin to your PATH:

export PATH="/usr/local/opt/openssl/bin:$PATH"

I recommend adding that to your .zshrc or .bashrc so you don't need to worry about it in the future. Then, with that variable exported (which may meed closing and re-opening your bash session), add two more env variables:

# in terminal
export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"

Then, finally, run:

pipenv install mysqlclient

and it should install just fine.

Source: https://medium.com/@shandou/pipenv-install-mysqlclient-on-macosx-7c253b0112f2

Is < faster than <=?

For floating point code, the <= comparison may indeed be slower (by one instruction) even on modern architectures. Here's the first function:

int compare_strict(double a, double b) { return a < b; }

On PowerPC, first this performs a floating point comparison (which updates cr, the condition register), then moves the condition register to a GPR, shifts the "compared less than" bit into place, and then returns. It takes four instructions.

Now consider this function instead:

int compare_loose(double a, double b) { return a <= b; }

This requires the same work as compare_strict above, but now there's two bits of interest: "was less than" and "was equal to." This requires an extra instruction (cror - condition register bitwise OR) to combine these two bits into one. So compare_loose requires five instructions, while compare_strict requires four.

You might think that the compiler could optimize the second function like so:

int compare_loose(double a, double b) { return ! (a > b); }

However this will incorrectly handle NaNs. NaN1 <= NaN2 and NaN1 > NaN2 need to both evaluate to false.

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

This should work:

int hh, mm, ss;
struct tm when = {0};

sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);


when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;

time_t converted;
converted = mktime(&when);

Modify as needed.

addEventListener for keydown on Canvas

encapsulate all of your js code within a window.onload function. I had a similar issue. Everything is loaded asynchronously in javascript so some parts load quicker than others, including your browser. Putting all of your code inside the onload function will ensure everything your code will need from the browser will be ready to use before attempting to execute.

Remove characters from NSString?

If you want to support more than one space at a time, or support any whitespace, you can do this:

NSString* noSpaces =
    [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
                           componentsJoinedByString:@""];

AngularJS - Create a directive that uses ng-model

Creating an isolate scope is undesirable. I would avoid using the scope attribute and do something like this. scope:true gives you a new child scope but not isolate. Then use parse to point a local scope variable to the same object the user has supplied to the ngModel attribute.

app.directive('myDir', ['$parse', function ($parse) {
    return {
        restrict: 'EA',
        scope: true,
        link: function (scope, elem, attrs) {
            if(!attrs.ngModel) {return;}
            var model = $parse(attrs.ngModel);
            scope.model = model(scope);
        }
    };
}]);

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

Inline Javascript:

<button onclick="window.location='http://www.example.com';">Visit Page Now</button>

Defining a function in Javascript:

<script>
    function visitPage(){
        window.location='http://www.example.com';
    }
</script>
<button onclick="visitPage();">Visit Page Now</button>

or in Jquery

<button id="some_id">Visit Page Now</button>

$('#some_id').click(function() {
  window.location='http://www.example.com';
});

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

The answer is correct, however the perl documentation on how to handle deadlocks is a bit sparse and perhaps confusing with PrintError, RaiseError and HandleError options. It seems that rather than going with HandleError, use on Print and Raise and then use something like Try:Tiny to wrap your code and check for errors. The below code gives an example where the db code is inside a while loop that will re-execute an errored sql statement every 3 seconds. The catch block gets $_ which is the specific err message. I pass this to a handler function "dbi_err_handler" which checks $_ against a host of errors and returns 1 if the code should continue (thereby breaking the loop) or 0 if its a deadlock and should be retried...

$sth = $dbh->prepare($strsql);
my $db_res=0;
while($db_res==0)
{
   $db_res=1;
   try{$sth->execute($param1,$param2);}
   catch
   {
       print "caught $_ in insertion to hd_item_upc for upc $upc\n";
       $db_res=dbi_err_handler($_); 
       if($db_res==0){sleep 3;}
   }
}

dbi_err_handler should have at least the following:

sub dbi_err_handler
{
    my($message) = @_;
    if($message=~ m/DBD::mysql::st execute failed: Deadlock found when trying to get lock; try restarting transaction/)
    {
       $caught=1;
       $retval=0; # we'll check this value and sleep/re-execute if necessary
    }
    return $retval;
}

You should include other errors you wish to handle and set $retval depending on whether you'd like to re-execute or continue..

Hope this helps someone -

Android "Only the original thread that created a view hierarchy can touch its views."

RunOnUIThread didn't seem to work for me but the following ended up solving my issues.

            _ = MainThread.InvokeOnMainThreadAsync(async () =>
           {
               this.LoadApplication(Startup.Init(this.ConfigureServices));

               var authenticationService = App.ServiceProvider.GetService<AuthenticationService>();
               if (authenticationService.AuthenticationResult == null)
               {
                   await authenticationService.AuthenticateAsync(AuthenticationUserFlow.SignUpSignIn, CrossCurrentActivity.Current.Activity).ConfigureAwait(false);
               }
           });

Within the Startup.Init method there is ReactiveUI routing and this needs to be invoked on the main thread. This Invoke method also accepts async/await better than RunOnUIThread.

So anywhere I need to invoke methods on the mainthread I use this.

Please comment on this if anyone knows something I don't and can help me improve my application.

How to get the current taxonomy term ID (not the slug) in WordPress?

<?php 
$terms = get_the_terms( $post->ID, 'taxonomy');
foreach ( $terms as $term ) {
    $termID[] = $term->term_id;
}
echo $termID[0]; 
?>

SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)

Same way for tolerance

=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")

python list by value not by reference

In terms of performance my favorite answer would be:

b.extend(a)

Check how the related alternatives compare with each other in terms of performance:

In [1]: import timeit

In [2]: timeit.timeit('b.extend(a)', setup='b=[];a=range(0,10)', number=100000000)
Out[2]: 9.623248100280762

In [3]: timeit.timeit('b = a[:]', setup='b=[];a=range(0,10)', number=100000000)
Out[3]: 10.84756088256836

In [4]: timeit.timeit('b = list(a)', setup='b=[];a=range(0,10)', number=100000000)
Out[4]: 21.46313500404358

In [5]: timeit.timeit('b = [elem for elem in a]', setup='b=[];a=range(0,10)', number=100000000)
Out[5]: 66.99795293807983

In [6]: timeit.timeit('for elem in a: b.append(elem)', setup='b=[];a=range(0,10)', number=100000000)
Out[6]: 67.9775960445404

In [7]: timeit.timeit('b = deepcopy(a)', setup='from copy import deepcopy; b=[];a=range(0,10)', number=100000000)
Out[7]: 1216.1108016967773

Unix shell script find out which directory the script file resides?

An earlier comment on an answer said it, but it is easy to miss among all the other answers.

When using bash:

echo this file: "$BASH_SOURCE"
echo this dir: "$(dirname "$BASH_SOURCE")"

Bash Reference Manual, 5.2 Bash Variables

Jmeter - get current date and time

Use this format: ${__time(yyyy-MM-dd'T'hh:mm:ss.SS'Z')}

Which will give you: 2018-01-16T08:32:28.75Z

PHP string concatenation

while ($personCount < 10) {
    $result .= ($personCount++)." people ";
}

echo $result;

How to hide output of subprocess in Python 2.7

Why not use commands.getoutput() instead?

import commands

text = "Mario Balotelli" 
output = 'espeak "%s"' % text
print text
a = commands.getoutput(output)

Add Custom Headers using HttpWebRequest

You should do ex.StackTrace instead of ex.ToString()

How to display pandas DataFrame of floats using a format string for columns?

Similar to unutbu above, you could also use applymap as follows:

import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])

df = df.applymap("${0:.2f}".format)

jQuery - Fancybox: But I don't want scrollbars!

Just wanted to say Magnus' answer above did it for me, but for the second "overlay" that needs to be "overflow"

helpers : {
  overlay : {
    css : { 'overflow' : 'hidden' }
  }
}

How to build query string with Javascript

If you don't want to use a library, this should cover most/all of the same form element types.

function serialize(form) {
  if (!form || !form.elements) return;

  var serial = [], i, j, first;
  var add = function (name, value) {
    serial.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));
  }

  var elems = form.elements;
  for (i = 0; i < elems.length; i += 1, first = false) {
    if (elems[i].name.length > 0) { /* don't include unnamed elements */
      switch (elems[i].type) {
        case 'select-one': first = true;
        case 'select-multiple':
          for (j = 0; j < elems[i].options.length; j += 1)
            if (elems[i].options[j].selected) {
              add(elems[i].name, elems[i].options[j].value);
              if (first) break; /* stop searching for select-one */
            }
          break;
        case 'checkbox':
        case 'radio': if (!elems[i].checked) break; /* else continue */
        default: add(elems[i].name, elems[i].value); break;
      }
    }
  }

  return serial.join('&');
}

Unable to merge dex

I also had the problem.

I was able to solve by changing compileSdkVersion and targetSdkVersion to latest version.

Remote desktop connection protocol error 0x112f

Resized VM with more memory fixed this issue.

PHP: trying to create a new line with "\n"

This works perfectly for me...

echo nl2br("\n");

Reference: http://www.w3schools.com/php/func_string_nl2br.asp

Hope it helps :)

Can functions be passed as parameters?

I hope the below example will provide more clarity.

package main

type EmployeeManager struct{
    category            string
    city                string
    calculateSalary     func() int64
}


func NewEmployeeManager() (*EmployeeManager,error){

    return &EmployeeManager{
        category : "MANAGEMENT",
        city : "NY",
        calculateSalary: func() int64 {
            var calculatedSalary int64
            // some formula
            return calculatedSalary
        },
    },nil
}

func (self *EmployeeManager) emWithSalaryCalculation(){
    self.calculateSalary = func() int64 {
        var calculatedSalary int64
        // some new formula
        return calculatedSalary
    }
}

func updateEmployeeInfo(em EmployeeManager){
    // Some code
}

func processEmployee(){
    updateEmployeeInfo(struct {
        category        string
        city            string
        calculateSalary func() int64
    }{category: "", city: "", calculateSalary: func() int64 {
        var calculatedSalary int64
        // some new formula
        return calculatedSalary
    }})
}

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Since you're using PHP, you will probably need to use the CURLOPT_PORT option, like so:

curl_setopt($ch, CURLOPT_PORT, 11740);

Bear in mind, you may face problems with SELinux:

Unable to make php curl request with port number

How to add content to html body using JS?

You're probably using

document.getElementById('element').innerHTML = "New content"

Try this instead:

document.getElementById('element').innerHTML += "New content"

Or, preferably, use DOM Manipulation:

document.getElementById('element').appendChild(document.createElement("div"))

Dom manipulation would be preferred compared to using innerHTML, because innerHTML simply dumps a string into the document. The browser will have to reparse the entire document to get it's stucture.

C++ delete vector, objects, free memory

If you need to use the vector over and over again and your current code declares it repeatedly within your loop or on every function call, it is likely that you will run out of memory. I suggest that you declare it outside, pass them as pointers in your functions and use:

my_arr.resize()

This way, you keep using the same memory sequence for your vectors instead of requesting for new sequences every time. Hope this helped. Note: resizing it to different sizes may add random values. Pass an integer such as 0 to initialise them, if required.

Inserting a text where cursor is using Javascript/jquery

Use this, from here:

_x000D_
_x000D_
function insertAtCaret(areaId, text) {_x000D_
  var txtarea = document.getElementById(areaId);_x000D_
  if (!txtarea) {_x000D_
    return;_x000D_
  }_x000D_
_x000D_
  var scrollPos = txtarea.scrollTop;_x000D_
  var strPos = 0;_x000D_
  var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?_x000D_
    "ff" : (document.selection ? "ie" : false));_x000D_
  if (br == "ie") {_x000D_
    txtarea.focus();_x000D_
    var range = document.selection.createRange();_x000D_
    range.moveStart('character', -txtarea.value.length);_x000D_
    strPos = range.text.length;_x000D_
  } else if (br == "ff") {_x000D_
    strPos = txtarea.selectionStart;_x000D_
  }_x000D_
_x000D_
  var front = (txtarea.value).substring(0, strPos);_x000D_
  var back = (txtarea.value).substring(strPos, txtarea.value.length);_x000D_
  txtarea.value = front + text + back;_x000D_
  strPos = strPos + text.length;_x000D_
  if (br == "ie") {_x000D_
    txtarea.focus();_x000D_
    var ieRange = document.selection.createRange();_x000D_
    ieRange.moveStart('character', -txtarea.value.length);_x000D_
    ieRange.moveStart('character', strPos);_x000D_
    ieRange.moveEnd('character', 0);_x000D_
    ieRange.select();_x000D_
  } else if (br == "ff") {_x000D_
    txtarea.selectionStart = strPos;_x000D_
    txtarea.selectionEnd = strPos;_x000D_
    txtarea.focus();_x000D_
  }_x000D_
_x000D_
  txtarea.scrollTop = scrollPos;_x000D_
}
_x000D_
<textarea id="textareaid"></textarea>_x000D_
<a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a>
_x000D_
_x000D_
_x000D_

Variable's memory size in Python

Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).

>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)

Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get

>>> import math, sys
>>> a=0
>>> sys.getsizeof(a)
24
>>> a=2**100
>>> sys.getsizeof(a)
40
>>> a=2**1000
>>> sys.getsizeof(a)
160
>>> 24+4*math.ceil(100/30)
40
>>> 24+4*math.ceil(1000/30)
160

There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.

If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).

How can I scale an image in a CSS sprite

Use transform: scale(0.8); with the value you need instead of 0.8

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

Have a look at ImmutableMap JavaDoc: doc

There is information about that there:

Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.

how to remove only one style property with jquery

You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.

Show Current Location and Update Location in MKMapView in Swift

MyLocation is a Swift iOS Demo.

You can use this demo for the following:

  1. Show the current location.

  2. Choose other location: in this case stop tracking the location.

  3. Add a push pin to a MKMapView(iOS) when touching.

How to Set Variables in a Laravel Blade Template

You can set a variable in the view file, but it will be printed just as you set it. Anyway, there is a workaround. You can set the variable inside an unused section. Example:

@section('someSection')
  {{ $yourVar = 'Your value' }}
@endsection

Then {{ $yourVar }} will print Your value anywhere you want it to, but you don't get the output when you save the variable.

EDIT: naming the section is required otherwise an exception will be thrown.

What charset does Microsoft Excel use when saving files?

You could use this Visual Studio VB.Net code to get the encoding:

Dim strEncryptionType As String = String.Empty
Dim myStreamRdr As System.IO.StreamReader = New System.IO.StreamReader(myFileName, True)
Dim myString As String = myStreamRdr.ReadToEnd()
strEncryptionType = myStreamRdr.CurrentEncoding.EncodingName

How to add multiple font files for the same font?

/*
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# dejavu sans
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
/*default version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans.ttf'); /* IE9 Compat Modes */
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'), /* Duplicated name with hyphen */
        url('dejavu/DejaVuSans.ttf') 
        format('truetype');
}
/*bold version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-Bold.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-Bold.ttf') 
        format('truetype');
    font-weight: bold;
}
/*italic version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-Oblique.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-Oblique.ttf') 
        format('truetype');
    font-style: italic;
}
/*bold italic version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-BoldOblique.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-BoldOblique.ttf') 
        format('truetype');
    font-weight: bold;
    font-style: italic;
}

List of foreign keys and the tables they reference in Oracle DB

Its a bit late to anwser, but I hope my answer been useful for someone, who needs to select Composite foreign keys.

SELECT
    "C"."CONSTRAINT_NAME",
    "C"."OWNER" AS "SCHEMA_NAME",
    "C"."TABLE_NAME",
    "COL"."COLUMN_NAME",
    "REF_COL"."OWNER" AS "REF_SCHEMA_NAME",
    "REF_COL"."TABLE_NAME" AS "REF_TABLE_NAME",
    "REF_COL"."COLUMN_NAME" AS "REF_COLUMN_NAME"
FROM
    "USER_CONSTRAINTS" "C"
INNER JOIN "USER_CONS_COLUMNS" "COL" ON "COL"."OWNER" = "C"."OWNER"
 AND "COL"."CONSTRAINT_NAME" = "C"."CONSTRAINT_NAME"
INNER JOIN "USER_CONS_COLUMNS" "REF_COL" ON "REF_COL"."OWNER" = "C"."R_OWNER"
 AND "REF_COL"."CONSTRAINT_NAME" = "C"."R_CONSTRAINT_NAME"
 AND "REF_COL"."POSITION" = "COL"."POSITION"
WHERE "C"."TABLE_NAME" = 'TableName' AND "C"."CONSTRAINT_TYPE" = 'R'

SQL Server replace, remove all after certain character

Use LEFT combined with CHARINDEX:

UPDATE MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

Note that the WHERE clause skips updating rows in which there is no semicolon.

Here is some code to verify the SQL above works:

declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
insert into @MyTable ([id], MyText)
select 1, 'some text; some more text'
union all select 2, 'text again; even more text'
union all select 3, 'text without a semicolon'
union all select 4, null -- test NULLs
union all select 5, '' -- test empty string
union all select 6, 'test 3 semicolons; second part; third part;'
union all select 7, ';' -- test semicolon by itself    

UPDATE @MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

select * from @MyTable

I get the following results:

id MyText
-- -------------------------
1  some text
2  text again
3  text without a semicolon
4  NULL
5        (empty string)
6  test 3 semicolons
7        (empty string)

".addEventListener is not a function" why does this error occur?

The problem with your code is that the your script is executed prior to the html element being available. Because of the that var comment is an empty array.

So you should move your script after the html element is available.

Also, getElementsByClassName returns html collection, so if you need to add event Listener to an element, you will need to do something like following

comment[0].addEventListener('click' , showComment , false ) ; 

If you want to add event listener to all the elements, then you will need to loop through them

for (var i = 0 ; i < comment.length; i++) {
   comment[i].addEventListener('click' , showComment , false ) ; 
}

PyTorch: How to get the shape of a Tensor as a list of int

If you're a fan of NumPyish syntax, then there's tensor.shape.

In [3]: ar = torch.rand(3, 3)

In [4]: ar.shape
Out[4]: torch.Size([3, 3])

# method-1
In [7]: list(ar.shape)
Out[7]: [3, 3]

# method-2
In [8]: [*ar.shape]
Out[8]: [3, 3]

# method-3
In [9]: [*ar.size()]
Out[9]: [3, 3]

P.S.: Note that tensor.shape is an alias to tensor.size(), though tensor.shape is an attribute of the tensor in question whereas tensor.size() is a function.

How can query string parameters be forwarded through a proxy_pass with nginx?

github gist https://gist.github.com/anjia0532/da4a17f848468de5a374c860b17607e7

#set $token "?"; # deprecated

set $token ""; # declar token is ""(empty str) for original request without args,because $is_args concat any var will be `?`

if ($is_args) { # if the request has args update token to "&"
    set $token "&";
}

location /test {
    set $args "${args}${token}k1=v1&k2=v2"; # update original append custom params with $token
    # if no args $is_args is empty str,else it's "?"
    # http is scheme
    # service is upstream server
    #proxy_pass http://service/$uri$is_args$args; # deprecated remove `/`
    proxy_pass http://service$uri$is_args$args; # proxy pass
}

#http://localhost/test?foo=bar ==> http://service/test?foo=bar&k1=v1&k2=v2

#http://localhost/test/ ==> http://service/test?k1=v1&k2=v2

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

If origin points to a bare repository on disk, this error can happen if that directory has been moved (even if you update the working copy's remotes). For example

$ mv /path/to/origin /somewhere/else
$ git remote set-url origin /somewhere/else
$ git diff origin/master
fatal: ambiguous argument 'origin': unknown revision or path not in the working tree.

Pulling once from the new origin solves the problem:

$ git stash
$ git pull origin master
$ git stash pop

How do I change the android actionbar title and icon

You just need to add these 3 lines of code. Replace the icon with your own icon. If you want to generate icons use this

getSupportActionBar().setHomeAsUpIndicator(R.drawable.icon_back_arrow);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);

startForeground fail after upgrade to Android 8.1

Alternative answer: if it's a Huawei device and you have implemented requirements needed for Oreo 8 Android and there are still issues only with Huawei devices than it's only device issue, you can read https://dontkillmyapp.com/huawei

Add Auto-Increment ID to existing table?

ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT primary key FIRST

Vertically center text in a 100% height div?

Vertical align, dynamic height combined with absolute position is except some special conditions not possible without a few lines of JS (eg. jQuery). (can possibly be solved with backend code in some cases, or min-height combined with sensible top or margin styles, but not perfect)

I mostly only use absolute position when something is supposed to "popup" in relation to something else which is in the float, I think that's the best way to use it so you don't have to fiddle with things like this.

No offense, but most answers in here are way off.

How to import a jar in Eclipse

Here are the steps:

  1. click File > Import. The Import window opens.

  2. Under Select an import source, click J2EE > App Client JAR file.

  3. Click Next.

  4. In the Application Client file field, enter the location and name of the application client JAR file that you want to import. You can click the Browse button to select the JAR file from the file system.

  5. In the Application Client project field, type a new project name or select an application client project from the drop-down list. If you type a new name in this field, the application client project will be created based on the version of the application client JAR file, and it will use the default location.

  6. In the Target runtime drop-down list, select the application server that you want to target for your development. This selection affects the run time settings by modifying the class path entries for the project.

  7. If you want to add the new module to an enterprise application project, select the Add project to an EAR check box and then select an existing enterprise application project from the list or create a new one by clicking New.

    Note: If you type a new enterprise application project name, the enterprise application project will be created in the default location with the lowest compatible J2EE version based on the version of the project being created. If you want to specify a different version or a different location for the enterprise application, you must use the New Enterprise Application Project wizard.

  8. Click Finish to import the application client JAR file.

Extract filename and extension in Bash

I use the following script

$ echo "foo.tar.gz"|rev|cut -d"." -f3-|rev
foo

Package signatures do not match the previously installed version

Go to android studio -> AVD manager -> Select your AVD and wipe user data

No need to re-install the entire AVD.

How do I ignore files in Subversion?

  1. open you use JetBrains Product(i.e. Pycharm)
  2. then click the 'commit' button on the top toolbar or use shortcut 'ctrl + k' screenshot_toolbar
  3. on the commit interface, move your unwanted files to another change list as follows. screenshot_commit_change
  4. next time you can only commit default change list.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    Again stressing that this is pseudo-code.

How to get table cells evenly spaced?

Take the width of the table and divide it by the number of cell ().

PerformanceTable {width:500px;}    
PerformanceTable.td {width:100px;}

If the table dynamically widens or shrinks you could dynamically increase the cell size with a little javascript.

MySQL string replace

UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/')
WHERE your_field LIKE '%articles/updates/%'

Now rows that were like

http://www.example.com/articles/updates/43

will be

http://www.example.com/articles/news/43

http://www.electrictoolbox.com/mysql-find-replace-text/

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

Python error "ImportError: No module named"

I had the same problem (Python 2.7 Linux), I have found the solution and i would like to share it. In my case i had the structure below:

Booklet
-> __init__.py
-> Booklet.py
-> Question.py
default
-> __init_.py
-> main.py

In 'main.py' I had tried unsuccessfully all the combinations bellow:

from Booklet import Question
from Question import Question
from Booklet.Question import Question
from Booklet.Question import *
import Booklet.Question
# and many othet various combinations ...

The solution was much more simple than I thought. I renamed the folder "Booklet" into "booklet" and that's it. Now Python can import the class Question normally by using in 'main.py' the code:

from booklet.Booklet import Booklet
from booklet.Question import Question
from booklet.Question import AnotherClass

From this I can conclude that Package-Names (folders) like 'booklet' must start from lower-case, else Python confuses it with Class names and Filenames.

Apparently, this was not your problem, but John Fouhy's answer is very good and this thread has almost anything that can cause this issue. So, this is one more thing and I hope that maybe this could help others.

ASP.NET Bundles how to disable minification

Here's how to disable minification on a per-bundle basis:

bundles.Add(new StyleBundleRaw("~/Content/foobarcss").Include("/some/path/foobar.css"));
bundles.Add(new ScriptBundleRaw("~/Bundles/foobarjs").Include("/some/path/foobar.js"));

Sidenote: The paths used for your bundles must not coincide with any actual path in your published builds otherwise nothing will work. Also make sure to avoid using .js, .css and/or '.' and '_' anywhere in the name of the bundle. Keep the name as simple and as straightforward as possible, like in the example above.

The helper classes are shown below. Notice that in order to make these classes future-proof we surgically remove the js/css minifying instances instead of using .clear() and we also insert a mime-type-setter transformation without which production builds are bound to run into trouble especially when it comes to properly handing over css-bundles (firefox and chrome reject css bundles with mime-type set to "text/html" which is the default):

internal sealed class StyleBundleRaw : StyleBundle
{
        private static readonly BundleMimeType CssContentMimeType = new BundleMimeType("text/css");

        public StyleBundleRaw(string virtualPath) : this(virtualPath, cdnPath: null)
        {
        }

        public StyleBundleRaw(string virtualPath, string cdnPath) : base(virtualPath, cdnPath)
        {
                 Transforms.Add(CssContentMimeType); //0 vital
                 Transforms.Remove(Transforms.FirstOrDefault(x => x is CssMinify)); //0
        }
        //0 the guys at redmond in their infinite wisdom plugged the mimetype "text/css" right into cssminify    upon unwiring the minifier we
        //  need to somehow reenable the cssbundle to specify its mimetype otherwise it will advertise itself as html and wont load
}

internal sealed class ScriptBundleRaw : ScriptBundle
{
        private static readonly BundleMimeType JsContentMimeType = new BundleMimeType("text/javascript");

        public ScriptBundleRaw(string virtualPath) : this(virtualPath, cdnPath: null)
        {
        }

        public ScriptBundleRaw(string virtualPath, string cdnPath) : base(virtualPath, cdnPath)
        {
                 Transforms.Add(JsContentMimeType); //0 vital
                 Transforms.Remove(Transforms.FirstOrDefault(x => x is JsMinify)); //0
        }
        //0 the guys at redmond in their infinite wisdom plugged the mimetype "text/javascript" right into jsminify   upon unwiring the minifier we need
        //  to somehow reenable the jsbundle to specify its mimetype otherwise it will advertise itself as html causing it to be become unloadable by the browsers in published production builds
}

internal sealed class BundleMimeType : IBundleTransform
{
        private readonly string _mimeType;

        public BundleMimeType(string mimeType) { _mimeType = mimeType; }

        public void Process(BundleContext context, BundleResponse response)
        {
                 if (context == null)
                          throw new ArgumentNullException(nameof(context));
                 if (response == null)
                          throw new ArgumentNullException(nameof(response));

         response.ContentType = _mimeType;
        }
}

To make this whole thing work you need to install (via nuget):

WebGrease 1.6.0+ Microsoft.AspNet.Web.Optimization 1.1.3+

And your web.config should be enriched like so:

<runtime>
       [...]
       <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-x.y.z.t" newVersion="x.y.z.t" />
       </dependentAssembly>
       <dependentAssembly>
              <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-x.y.z.t" newVersion="x.y.z.t" />
       </dependentAssembly>
        [...]
</runtime>

<!-- setting mimetypes like we do right below is absolutely vital for published builds because for some reason the -->
<!-- iis servers in production environments somehow dont know how to handle otf eot and other font related files   -->
<system.webServer>
        [...]
        <staticContent>
      <!-- in case iis already has these mime types -->
      <remove fileExtension=".otf" />
      <remove fileExtension=".eot" />
      <remove fileExtension=".ttf" />
      <remove fileExtension=".woff" />
      <remove fileExtension=".woff2" />

      <mimeMap fileExtension=".otf" mimeType="font/otf" />
      <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
      <mimeMap fileExtension=".ttf" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
      </staticContent>

      <!-- also vital otherwise published builds wont work  https://stackoverflow.com/a/13597128/863651  -->
      <modules runAllManagedModulesForAllRequests="true">
         <remove name="BundleModule" />
         <add name="BundleModule" type="System.Web.Optimization.BundleModule" />
      </modules>
      [...]
</system.webServer>

Note that you might have to take extra steps to make your css-bundles work in terms of fonts etc. But that's a different story.

jQuery: How to get to a particular child of a parent?

You could use .each() with .children() and a selector within the parenthesis:

//Grab Each Instance of Box.
$(".box").each(function(i){

    //For Each Instance, grab a child called .something1. Fade It Out.
    $(this).children(".something1").fadeOut();
});

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

Import CSV into SQL Server (including automatic table creation)

SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.

You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...

From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.

If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/

How to communicate between iframe and the parent site?

With different domains, it is not possible to call methods or access the iframe's content document directly.

You have to use cross-document messaging.

For example in the top window:

 myIframe.contentWindow.postMessage('hello', '*');

and in the iframe:

window.onmessage = function(e){
    if (e.data == 'hello') {
        alert('It works!');
    }
};

If you are posting message from iframe to parent window

window.top.postMessage('hello', '*')

Anaconda Navigator won't launch (windows 10)

You need to update Anaconda using:

conda update

and

conda update anaconda-navigator

Try these commands on anaconda prompt and then try to launch navigator from the prompt itself using following command:

anaconda-navigator

If still the problem doesn't get solved, share the anaconda prompt logs here if they have any errors.

Force “landscape” orientation mode

screen.orientation.lock('landscape');

Will force it to change to and stay in landscape mode. Tested on Nexus 5.

http://www.w3.org/TR/screen-orientation/#examples

What, why or when it is better to choose cshtml vs aspx?

As other people have answered, .cshtml (or .vbhtml if that's your flavor) provides a handler-mapping to load the MVC engine. The .aspx extension simply loads the aspnet_isapi.dll that performs the compile and serves up web forms. The difference in the handler mapping is simply a method of allowing the two to co-exist on the same server allowing both MVC applications and WebForms applications to live under a common root.

This allows http://www.mydomain.com/MyMVCApplication to be valid and served with MVC rules along with http://www.mydomain.com/MyWebFormsApplication to be valid as a standard web form.

Edit:
As for the difference in the technologies, the MVC (Razor) templating framework is intended to return .Net pages to a more RESTful "web-based" platform of templated views separating the code logic between the model (business/data objects), the view (what the user sees) and the controllers (the connection between the two). The WebForms model (aspx) was an attempt by Microsoft to use complex javascript embedding to simulate a more stateful application similar to a WinForms application complete with events and a page lifecycle that would be capable of retaining its own state from page to page.

The choice to use one or the other is always going to be a contentious one because there are arguments for and against both systems. I for one like the simplicity in the MVC architecture (though routing is anything but simple) and the ease of the Razor syntax. I feel the WebForms architecture is just too heavy to be an effective web platform. That being said, there are a lot of instances where the WebForms framework provides a very succinct and usable model with a rich event structure that is well defined. It all boils down to the needs of the application and the preferences of those building it.

What is the meaning of "POSIX"?

In 1985, individuals from companies throughout the computer industry joined together to develop the POSIX (Portable Operating System Interface for Computer Environments) standard, which is based largely on the UNIX System V Interface Definition (SVID) and other earlier standardization efforts. These efforts were spurred by the U.S. government, which needed a standard computing environment to minimize its training and procurement costs. Released in 1988, POSIX is a group of IEEE standards that define the API, shell, and utility interfaces for an operating system. Although aimed at UNIX-like systems, the standards can apply to any compatible operating system. Now that these stan- dards have gained acceptance, software developers are able to develop applications that run on all conforming versions of UNIX, Linux, and other operating systems.

From the book: A Practical Guide To Linux

How to give environmental variable path for file appender in configuration file in log4j

Log4j entry

#- File to log to and log format

log4j.appender.file.File=${LOG_PATH}/mylogfile.log

Java program
String log4jConfPath        = "path/log4j.properties";
File log4jFile              = new File(log4jConfPath);
if (log4jFile.exists()) {
    System.setProperty("LOG_PATH", "c:/temp/");
    PropertyConfigurator.configure(log4jFile.getAbsolutePath());
    logger.trace("test123");
}

R Apply() function on specific dataframe columns

As mentioned, you simply want the standard R apply function applied to columns (MARGIN=2):

wifi[,4:9] <- apply(wifi[,4:9], MARGIN=2, FUN=A)

Or, for short:

wifi[,4:9] <- apply(wifi[,4:9], 2, A)

This updates columns 4:9 in-place using the A() function. Now, let's assume that na.rm is an argument to A(), which it probably should be. We can pass na.rm=T to remove NA values from the computation like so:

wifi[,4:9] <- apply(wifi[,4:9], MARGIN=2, FUN=A, na.rm=T)

The same is true for any other arguments you want to pass to your custom function.

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

How do I push amended commit to the remote Git repository?

I had the same problem.

  • Accidentally amended the last commit that was already pushed
  • Done a lot of changes locally, committed some five times
  • Tried to push, got an error, panicked, merged remote, got a lot of not-my-files, pushed, failed, etc.

As a Git-newbie, I thought it was complete FUBAR.

Solution: Somewhat like @bara suggested + created a local backup branch

# Rewind to commit just before the pushed-and-amended one.
# Replace <hash> with the needed hash.
# --soft means: leave all the changes there, so nothing is lost.
git reset --soft <hash>

# Create new branch, just for a backup, still having all changes in it.
# The branch was feature/1234, new one - feature/1234-gone-bad
git checkout -b feature/1234-gone-bad

# Commit all the changes (all the mess) not to lose it & not to carry around
git commit -a -m "feature/1234 backup"

# Switch back to the original branch
git checkout feature/1234

# Pull the from remote (named 'origin'), thus 'repairing' our main problem
git pull origin/feature/1234

# Now you have a clean-and-non-diverged branch and a backup of the local changes.
# Check the needed files from the backup branch
git checkout feature/1234-gone-bad -- the/path/to/file.php

Maybe it's not a fast and clean solution, and I lost my history (1 commit instead of 5), but it saved a day's work.

Excel: the Incredible Shrinking and Expanding Controls

Some of these problems may be due to controls resizing themselves when populated. I tend to the turn the IntegralHeight property of controls such as list boxes from True (default) to False to prevent automated resizing of the control height at runtime.

Regular expression for URL validation (in JavaScript)

This REGEX is a patch from @Aamir answer that worked for me

/((?:(?:http?|ftp)[s]*:\/\/)?[a-z0-9-%\/\&=?\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?)/gi

It matches these URL formats

  1. yourwebsite.com
  2. yourwebsite.com/4564564/546564/546564?=adsfasd
  3. www.yourwebsite.com
  4. http://yourwebsite.com
  5. https://yourwebsite.com
  6. ftp://www.yourwebsite.com
  7. ftp://yourwebsite.com
  8. http://yourwebsite.com/4564564/546564/546564?=adsfasd

What is the difference between C# and .NET?

C# is a programming language, .NET is the framework that the language is built on.

CSS no text wrap

Use the css property overflow . For example:

  .item{
    width : 100px;
    overflow:hidden;
  }

The overflow property can have one of many values like ( hidden , scroll , visible ) .. you can als control the overflow in one direction only using overflow-x or overflow-y.

I hope this helps.

Angular 5, HTML, boolean on checkbox is checked

Work with checkboxes using observables

You could even choose to use a behaviourSubject to utilize the power of observables so you can start a certain chain of reaction starting at the isChecked$ observable.

In your component.ts:

public isChecked$ = new BehaviorSubject(false);
toggleChecked() {
  this.isChecked$.next(!this.isChecked$.value)
}

In your template

<input type="checkbox" [checked]="isChecked$ | async" (change)="toggleChecked()">

No function matches the given name and argument types

That error means that a function call is only matched by an existing function if all its arguments are of the same type and passed in same order. So if the next f() function

create function f() returns integer as $$ 
    select 1;
$$ language sql;

is called as

select f(1);

It will error out with

ERROR:  function f(integer) does not exist
LINE 1: select f(1);
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

because there is no f() function that takes an integer as argument.

So you need to carefully compare what you are passing to the function to what it is expecting. That long list of table columns looks like bad design.

Get CPU Usage from Windows Command Prompt

typeperf "\processor(_total)\% processor time"

does work on Win7, you just need to extract the percent value yourself from the last quoted string.

A free tool to check C/C++ source code against a set of coding standards?

The only tool I know is Vera. Haven't used it, though, so can't comment how viable it is. Demo looks promising.

Pressed <button> selector

Should we include a little JS? Because CSS was not basically created for this job. CSS was just a style sheet to add styles to the HTML, but its pseudo classes can do something that the basic CSS can't do. For example button:active active is pseudo.

Reference:

http://css-tricks.com/pseudo-class-selectors/ You can learn more about pseudo here!

Your code:

The code that you're having the basic but helpfull. And yes :active will only occur once the click event is triggered.

button {
font-size: 18px;
border: 2px solid gray;
border-radius: 100px;
width: 100px;
height: 100px;
}

button:active {
font-size: 18px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}

This is what CSS would do, what rlemon suggested is good, but that would as he suggested would require a tag.

How to use CSS:

You can use :focus too. :focus would work once the click is made and would stay untill you click somewhere else, this was the CSS, you were trying to use CSS, so use :focus to make the buttons change.

What JS would do:

The JavaScript's jQuery library is going to help us for this code. Here is the example:

$('button').click(function () {
  $(this).css('border', '1px solid red');
}

This will make sure that the button stays red even if the click gets out. To change the focus type (to change the color of red to other) you can use this:

$('button').click(function () {
  $(this).css('border', '1px solid red');
  // find any other button with a specific id, and change it back to white like
  $('button#red').css('border', '1px solid white');
}

This way, you will create a navigation menu. Which will automatically change the color of the tabs as you click on them. :)

Hope you get the answer. Good luck! Cheers.

How can I count the number of matches for a regex?

If you want to use Java 8 streams and are allergic to while loops, you could try this:

public static int countPattern(String references, Pattern referencePattern) {
    Matcher matcher = referencePattern.matcher(references);
    return Stream.iterate(0, i -> i + 1)
            .filter(i -> !matcher.find())
            .findFirst()
            .get();
}

Disclaimer: this only works for disjoint matches.

Example:

public static void main(String[] args) throws ParseException {
    Pattern referencePattern = Pattern.compile("PASSENGER:\\d+");
    System.out.println(countPattern("[ \"PASSENGER:1\", \"PASSENGER:2\", \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\", \"PASSENGER:1\" ]", referencePattern));
    System.out.println(countPattern("[  ]", referencePattern));
}

This prints out:

2
0
1
0

This is a solution for disjoint matches with streams:

public static int countPattern(String references, Pattern referencePattern) {
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
            new Iterator<Integer>() {
                Matcher matcher = referencePattern.matcher(references);
                int from = 0;

                @Override
                public boolean hasNext() {
                    return matcher.find(from);
                }

                @Override
                public Integer next() {
                    from = matcher.start() + 1;
                    return 1;
                }
            },
            Spliterator.IMMUTABLE), false).reduce(0, (a, c) -> a + c);
}

Creating a border like this using :before And :after Pseudo-Elements In CSS?

#footer:after
{
   content: "";
    width: 40px;
    height: 3px;
    background-color: #529600;
    left: 0;
    position: relative;
    display: block;
    top: 10px;
}

Node.js: Difference between req.query[] and req.params

I want to mention one important note regarding req.query , because currently I am working on pagination functionality based on req.query and I have one interesting example to demonstrate to you...

Example:

// Fetching patients from the database
exports.getPatients = (req, res, next) => {

const pageSize = +req.query.pageSize;
const currentPage = +req.query.currentPage;

const patientQuery = Patient.find();
let fetchedPatients;

// If pageSize and currentPage are not undefined (if they are both set and contain valid values)
if(pageSize && currentPage) {
    /**
     * Construct two different queries 
     * - Fetch all patients 
     * - Adjusted one to only fetch a selected slice of patients for a given page
     */
    patientQuery
        /**
         * This means I will not retrieve all patients I find, but I will skip the first "n" patients
         * For example, if I am on page 2, then I want to skip all patients that were displayed on page 1,
         * 
         * Another example: if I am displaying 7 patients per page , I want to skip 7 items because I am on page 2,
         * so I want to skip (7 * (2 - 1)) => 7 items
         */
        .skip(pageSize * (currentPage - 1))

        /**
         * Narrow dont the amound documents I retreive for the current page
         * Limits the amount of returned documents
         * 
         * For example: If I got 7 items per page, then I want to limit the query to only
         * return 7 items. 
         */
        .limit(pageSize);
}
patientQuery.then(documents => {
    res.status(200).json({
        message: 'Patients fetched successfully',
        patients: documents
    });
  });
};

You will noticed + sign in front of req.query.pageSize and req.query.currentPage

Why? If you delete + in this case, you will get an error, and that error will be thrown because we will use invalid type (with error message 'limit' field must be numeric).

Important: By default if you extracting something from these query parameters, it will always be a string, because it's coming the URL and it's treated as a text.

If we need to work with numbers, and convert query statements from text to number, we can simply add a plus sign in front of statement.

How to filter data in dataview

DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";

// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");

Ref: http://www.csharp-examples.net/dataview-rowfilter/

http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx

Classes cannot be accessed from outside package

Note that the default when you make a class is not public as far as packages are considered. Make sure that you actually write public class [MyClass] { when defining your class. I've made this mistake more times than I care to admit.

LINQ to SQL - How to select specific columns and return strongly typed list

Make a call to the DB searching with myid (Id of the row) and get back specific columns:

var columns = db.Notifications
                .Where(x => x.Id == myid)
                .Select(n => new { n.NotificationTitle, 
                                   n.NotificationDescription, 
                                   n.NotificationOrder });

Detect if a Form Control option button is selected in VBA

You should remove .Value from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.

If you want to run action code when the optionbutton is clicked then don't write an if loop for that.

EXAMPLE:

Sub CommandButton1_Click
    If OptionButton1 = true then
        (action code...)
    End if
End sub

Sub OptionButton1_Click   
    (action code...)
End sub

How to clone git repository with specific revision/changeset?

If you mean you want to fetch everything from the beginning up to a particular point, Charles Bailey's answer is perfect. If you want to do the reverse and retrieve a subset of the history going back from the current date, you can use git clone --depth [N] where N is the number of revs of history you want. However:

--depth

Create a shallow clone with a history truncated to the specified number of revisions. A shallow repository has a number of limitations (you cannot clone or fetch from it, nor push from nor into it), but is adequate if you are only interested in the recent history of a large project with a long history, and would want to send in fixes as patches.

How to generate entire DDL of an Oracle schema (scriptable)?

First export the schema metadata:

expdp dumpfile=filename logfile=logname directory=dir_name schemas=schema_name

and then import by using the sqlfile option (it will not import data it will just write the schema DDL to that file)

impdp dumpfile=filename logfile=logname directory=dir_name sqlfile=ddl.sql

Adding a column after another column within SQL

It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:

ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;

SQL: how to use UNION and order by a specific select?

@Adrian's answer is perfectly suitable, I just wanted to share another way of achieving the same result:

select nvl(a.id, b.id)
from a full outer join b on a.id = b.id
order by b.id;

How do you change the character encoding of a postgres database?

To change the encoding of your database:

  1. Dump your database
  2. Drop your database,
  3. Create new database with the different encoding
  4. Reload your data.

Make sure the client encoding is set correctly during all this.

Source: http://archives.postgresql.org/pgsql-novice/2006-03/msg00210.php

Is it possible to use if...else... statement in React render function?

The shorthand for an if else structure works as expected in JSX

this.props.hasImage ? <MyImage /> : <SomeotherElement>

You can find other options on this blogpost of DevNacho, but it's more common to do it with the shorthand. If you need to have a bigger if clause you should write a function that returns or component A or component B.

for example:

this.setState({overlayHovered: true});

renderComponentByState({overlayHovered}){
    if(overlayHovered) {
        return <overlayHoveredComponent />
    }else{
        return <overlayNotHoveredComponent />
    }
}

You can destructure your overlayHovered from this.state if you give it as parameter. Then execute that function in your render() method:

renderComponentByState(this.state)

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

It turns out Java does not accept a bare Date value as DateTime. Using LocalDate instead of LocalDateTime solves the issue:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate dt = LocalDate.parse("20140218", formatter);

SQL Server - How to lock a table until a stored procedure finishes

Use the TABLOCKX lock hint for your transaction. See this article for more information on locking.

How to use multiprocessing pool.map with multiple arguments?

Another way is to pass a list of lists to a one-argument routine:

import os
from multiprocessing import Pool

def task(args):
    print "PID =", os.getpid(), ", arg1 =", args[0], ", arg2 =", args[1]

pool = Pool()

pool.map(task, [
        [1,2],
        [3,4],
        [5,6],
        [7,8]
    ])

One can than construct a list lists of arguments with one's favorite method.

Convert string to ASCII value python

you can actually do it with numpy:

import numpy as np
a = np.fromstring('hi', dtype=np.uint8)
print(a)

Chrome, Javascript, window.open in new tab

You can use this code to open in new tab..

function openWindow( url )
{
  window.open(url, '_blank');
  window.focus();
}

I got it from stackoverflow..

How can I put a ListView into a ScrollView without it collapsing?

hey I had a similar issue. I wanted to display a list view that didn't scroll and I found that manipulating the parameters worked but was inefficient and would behave differently on different devices.. as a result, this is a piece of my schedule code which actually does this very efficiently.

db = new dbhelper(this);

 cursor = db.dbCursor();
int count = cursor.getCount();
if (count > 0)
{    
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.layoutId);
startManagingCursor(YOUR_CURSOR);

YOUR_ADAPTER(**or SimpleCursorAdapter **) adapter = new YOUR_ADAPTER(this,
    R.layout.itemLayout, cursor, arrayOrWhatever, R.id.textViewId,
    this.getApplication());

int i;
for (i = 0; i < count; i++){
  View listItem = adapter.getView(i,null,null);
  linearLayout.addView(listItem);
   }
}

Note: if you use this, notifyDataSetChanged(); will not work as intended as the views will not be redrawn. Do this if you need a work around

adapter.registerDataSetObserver(new DataSetObserver() {

            @Override
            public void onChanged() {
                super.onChanged();
                removeAndRedrawViews();

            }

        });

Callback functions in C++

A Callback function is a method that is passed into a routine, and called at some point by the routine to which it is passed.

This is very useful for making reusable software. For example, many operating system APIs (such as the Windows API) use callbacks heavily.

For example, if you wanted to work with files in a folder - you can call an API function, with your own routine, and your routine gets run once per file in the specified folder. This allows the API to be very flexible.

Is it possible to write data to file using only JavaScript?

Yes its possible Here the code is

_x000D_
_x000D_
const fs = require('fs') 
let data = "Learning how to write in a file."
fs.writeFile('Output.txt', data, (err) => { 
      
    // In case of a error throw err. 
    if (err) throw err; 
}) 
_x000D_
_x000D_
_x000D_

Python: how can I check whether an object is of type datetime.date?

right way is

import datetime
isinstance(x, datetime.date)

When I try this on my machine it works fine. You need to look into why datetime.date is not a class. Are you perhaps masking it with something else? or not referencing it correctly for your import?

Changing permissions via chmod at runtime errors with "Operation not permitted"

In order to perform chmod, you need to be owner of the file you are trying to modify, or the root user.

Check if value exists in dataTable?

You can use LINQ-to-DataSet with Enumerable.Any:

String author = "John Grisham";
bool contains = tbl.AsEnumerable().Any(row => author == row.Field<String>("Author"));

Another approach is to use DataTable.Select:

DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");
if(foundAuthors.Length != 0)
{
    // do something...
}

Q: what if we do not know the columns Headers and we want to find if any cell value PEPSI exist in any rows'c columns? I can loop it all to find out but is there a better way? –

Yes, you can use this query:

DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray();
bool anyFieldContainsPepsi = tbl.AsEnumerable()
    .Any(row => columns.Any(col => row[col].ToString() == "PEPSI"));

How to check if any flags of a flag combination are set?

You could just check if the value is not zero.

if ((Int32)(letter & Letters.AB) != 0) { }

But I would consider it a better solution to introduce a new enumeration value with value zero and compare agains this enumeration value (if possible because you must be able to modify the enumeration).

[Flags]
enum Letters
{
    None = 0,
    A    = 1,
    B    = 2,
    C    = 4,
    AB   =  A | B,
    All  = AB | C
}

if (letter != Letters.None) { }

UPDATE

Missread the question - fixed the first suggestion and just ignore the second suggestion.

How to remove listview all items

An other approach after trying the solutions below. When you need it clear, just initialise your list to new clear new list.

List<ModelData> dataLists = new ArrayList<>();
                RaporAdapter adapter = new RaporAdapter(AyrintiliRapor.this, dataLists);
                listview.setAdapter(adapter);

Or set visibility to Gone / Invisible up to need

img_pdf.setVisibility(View.INVISIBLE);

Android: How can I get the current foreground activity (from a service)?

Update: this no longer works with other apps' activities as of Android 5.0


Here's a good way to do it using the activity manager. You basically get the runningTasks from the activity manager. It will always return the currently active task first. From there you can get the topActivity.

Example here

There's an easy way of getting a list of running tasks from the ActivityManager service. You can request a maximum number of tasks running on the phone, and by default, the currently active task is returned first.

Once you have that you can get a ComponentName object by requesting the topActivity from your list.

Here's an example.

    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    Log.d("topActivity", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName());
    ComponentName componentInfo = taskInfo.get(0).topActivity;
    componentInfo.getPackageName();

You will need the following permission on your manifest:

<uses-permission android:name="android.permission.GET_TASKS"/>

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

How to use concerns in Rails 4

This post helped me understand concerns.

# app/models/trader.rb
class Trader
  include Shared::Schedule
end

# app/models/concerns/shared/schedule.rb
module Shared::Schedule
  extend ActiveSupport::Concern
  ...
end

Saving changes after table edit in SQL Server Management Studio

To work around this problem, use SQL statements to make the changes to the metadata structure of a table.

This problem occurs when "Prevent saving changes that require table re-creation" option is enabled.

Source: Error message when you try to save a table in SQL Server 2008: "Saving changes is not permitted"

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

Count distinct value pairs in multiple columns in SQL

Another (probably not production-ready or recommended) method I just came up with is to concat the values to a string and count this string distinctively:

SELECT count(DISTINCT concat(id, name, address)) FROM mytable;

How to inject window into a service?

As of today (April 2016), the code in the previous solution doesn't work, I think it is possible to inject window directly into App.ts and then gather the values you need into a service for global access in the App, but if you prefer to create and inject your own service, a way simpler solution is this.

https://gist.github.com/WilldelaVega777/9afcbd6cc661f4107c2b74dd6090cebf

//--------------------------------------------------------------------------------------------------
// Imports Section:
//--------------------------------------------------------------------------------------------------
import {Injectable} from 'angular2/core'
import {window} from 'angular2/src/facade/browser';

//--------------------------------------------------------------------------------------------------
// Service Class:
//--------------------------------------------------------------------------------------------------
@Injectable()
export class WindowService
{
    //----------------------------------------------------------------------------------------------
    // Constructor Method Section:
    //----------------------------------------------------------------------------------------------
    constructor(){}

    //----------------------------------------------------------------------------------------------
    // Public Properties Section:
    //----------------------------------------------------------------------------------------------
    get nativeWindow() : Window
    {
        return window;
    }
}

Prepend text to beginning of string

You can use

var mystr = "Doe";
mystr = "John " + mystr;
console.log(mystr)

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

FXCop typically prefers OrdinalIgnoreCase. But your requirements may vary.

For English there is very little difference. It is when you wander into languages that have different written language constructs that this becomes an issue. I am not experienced enough to give you more than that.

OrdinalIgnoreCase

The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames. http://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase.aspx

InvariantCultureIgnoreCase

The StringComparer returned by the InvariantCultureIgnoreCase property compares strings in a linguistically relevant manner that ignores case, but it is not suitable for display in any particular culture. Its major application is to order strings in a way that will be identical across cultures. http://msdn.microsoft.com/en-us/library/system.stringcomparer.invariantcultureignorecase.aspx

The invariant culture is the CultureInfo object returned by the InvariantCulture property.

The InvariantCultureIgnoreCase property actually returns an instance of an anonymous class derived from the StringComparer class.

Compare a date string to datetime in SQL Server?

SELECT  *
FROM    table1
WHERE   CONVERT(varchar(10),columnDatetime,121) = 
        CONVERT(varchar(10),CONVERT('14 AUG 2008' ,smalldatetime),121)

This will convert the datatime and the string into varchars of the format "YYYY-MM-DD".

This is very ugly, but should work

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

To add .pch file-

1) Add new .pch file to your project->New file->other->PCH file

2) Goto your project's build setting.

3) Search "prefix header". You can find that under Apple LLVM.

4) Paste this in the field $(SRCROOT)/yourPrefixHeaderFileName.pch

5) Clean and build the project. That's it!!!

enter image description here

How do you remove all the options of a select box and then add one option and select it with jQuery?

Another way:

$('#select').empty().append($('<option>').text('---------').attr('value',''));

Under this link, there are good practices https://api.jquery.com/select/

How to run cron once, daily at 10pm

To run once, daily at 10PM you should do something like this:

0 22 * * *

enter image description here

Full size image: http://i.stack.imgur.com/BeXHD.jpg

Source: softpanorama.org

How to use System.Net.HttpClient to post a complex type?

Make a service call like this:

public async void SaveActivationCode(ActivationCodes objAC)
{
    var client = new HttpClient();
    client.BaseAddress = new Uri(baseAddress);
    HttpResponseMessage response = await client.PutAsJsonAsync(serviceAddress + "/SaveActivationCode" + "?apiKey=445-65-1216", objAC);
} 

And Service method like this:

public HttpResponseMessage PutSaveActivationCode(ActivationCodes objAC)
{
}

PutAsJsonAsync takes care of Serialization and deserialization over the network

Include .so library in apk in android studio

To include native libraries you need:

  1. create "jar" file with special structure containing ".so" files;
  2. include that file in dependencies list.

To create jar file, use the following snippet:

task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'
}

tasks.withType(Compile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}

To include resulting file, paste the following line into "dependencies" section in "build.gradle" file:

compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

Where is the visual studio HTML Designer?

The default HTML editor (for static HTML) doesn't have a design view. To set the default editor to the Web forms editor which does have a design view,

  1. Right click any HTML file in the Solution Explorer in Visual Studio and click on Open with
  2. Select the HTML (web forms) editor
  3. Click on Set as default
  4. Click on the OK button

Once you have done that, all you need to do is click on design or split view as shown below:

Screenshot showing the location of said options

SQL Query NOT Between Two Dates

Your logic is backwards.

SELECT 
    *
FROM 
    `test_table`
WHERE
        start_date NOT BETWEEN CAST('2009-12-15' AS DATE) and CAST('2010-01-02' AS DATE)
    AND end_date NOT BETWEEN CAST('2009-12-15' AS DATE) and CAST('2010-01-02' AS DATE)

stdlib and colored output in C

You can assign one color to every functionality to make it more useful.

#define Color_Red "\33[0:31m\\]" // Color Start
#define Color_end "\33[0m\\]" // To flush out prev settings
#define LOG_RED(X) printf("%s %s %s",Color_Red,X,Color_end)

foo()
{
LOG_RED("This is in Red Color");
}

Like wise you can select different color codes and make this more generic.

Magento - How to add/remove links on my account navigation?

Also, you need to do something like this in config.xml if you are developing a customized module

    <frontend>
        <layout>
            <updates>
                <hpcustomer>
                    <file>hpcustomer.xml</file>
                </hpcustomer>
            </updates>
        </layout>
    </frontend>

How to change column datatype in SQL database without losing data

I can modify the table field's datatype, with these following query: and also in the Oracle DB,

ALTER TABLE table_name
MODIFY column_name datatype;

How can I load webpage content into a div on page load?

This is possible to do without an iframe specifically. jQuery is utilised since it's mentioned in the title.

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Load remote content into object element</title>
  </head>
  <body>
    <div id="siteloader"></div>?
    <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script>
      $("#siteloader").html('<object data="http://tired.com/">');
    </script>
  </body>
</html>

Why is the Android emulator so slow? How can we speed up the Android emulator?

Try scaling down the emulator, it makes it a bit faster, even if it doesn't it really feels faster.

docker run <IMAGE> <MULTIPLE COMMANDS>

Just to make a proper answer from the @Eddy Hernandez's comment and which is very correct since Alpine comes with ash not bash.

The question now referes to Starting a shell in the Docker Alpine container which implies using sh or ash or /bin/sh or /bin/ash/.

Based on the OP's question:

docker run image sh -c "cd /path/to/somewhere && python a.py"

How to make URL/Phone-clickable UILabel?

Use UITextView instead of UILabel and it has a property to convert your text to hyperlink

Swift code:

yourTextView.editable = false
yourTextView.dataDetectorTypes = UIDataDetectorTypes.All
//or
yourTextView.dataDetectorTypes = UIDataDetectorTypes.PhoneNumber
//or
yourTextView.dataDetectorTypes = UIDataDetectorTypes.Link

Arrow operator (->) usage in C

I'd just add to the answers the "why?".

. is standard member access operator that has a higher precedence than * pointer operator.

When you are trying to access a struct's internals and you wrote it as *foo.bar then the compiler would think to want a 'bar' element of 'foo' (which is an address in memory) and obviously that mere address does not have any members.

Thus you need to ask the compiler to first dereference whith (*foo) and then access the member element: (*foo).bar, which is a bit clumsy to write so the good folks have come up with a shorthand version: foo->bar which is sort of member access by pointer operator.

Difference between break and continue in PHP?

BREAK:

break ends execution of the current for, foreach, while, do-while or switch structure.

CONTINUE:

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

So depending on your need, you can reset the position currently being executed in your code to a different level of the current nesting.

Also, see here for an artical detailing Break vs Continue with a number of examples

Laravel Controller Subfolder routing

Just found a way how to do it:

Just add the paths to the /app/start/global.php

ClassLoader::addDirectories(array(

    app_path().'/commands',
    app_path().'/controllers',
    app_path().'/controllers/product',
    app_path().'/models',
    app_path().'/database/seeds',

));

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "192.18.0.246";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            jsch.addIdentity(privateKey);
            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
            // 
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            session.connect();
            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");
            c.exit();
            System.out.println("done");

        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

How do I load an org.w3c.dom.Document from XML in a string?

Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.

private String DOC_ROOT="root";
String xml=getXmlString();
Document xmlDoc=loadXMLFrom(xml);
Element template=xmlDoc.getDocumentElement();
NodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);

public static Document loadXMLFrom(String xml) throws Exception {
        InputSource is= new InputSource(new StringReader(xml));
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = null;
        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);
        return doc;
    }

How to select all records from one table that do not exist in another table?

See query:

SELECT * FROM Table1 WHERE
id NOT IN (SELECT 
        e.id
    FROM
        Table1 e
            INNER JOIN
        Table2 s ON e.id = s.id);

Conceptually would be: Fetching the matching records in subquery and then in main query fetching the records which are not in subquery.

Android - How to download a file from a webserver

Using Async task

call when you want to download file : new DownloadFileFromURL().execute(file_url);

public class MainActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;
    public static final int progress_bar_type = 0;

    // File url to download
    private static String file_url = "http://www.qwikisoft.com/demo/ashade/20001.kml";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        new DownloadFileFromURL().execute(file_url);

    }

    /**
     * Showing Dialog
     * */

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type: // we set this to 0
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
        }
    }

    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection connection = url.openConnection();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int lenghtOfFile = connection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);

                // Output stream
                OutputStream output = new FileOutputStream(Environment
                        .getExternalStorageDirectory().toString()
                        + "/2011.kml");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

        }

    }
}

if not working in 4.0 then add:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 

How to count objects in PowerShell?

This will get you count:

get-alias | measure

You can work with the result as with object:

$m = get-alias | measure
$m.Count

And if you would like to have aliases in some variable also, you can use Tee-Object:

$m = get-alias | tee -Variable aliases | measure
$m.Count
$aliases

Some more info on Measure-Object cmdlet is on Technet.

Do not confuse it with Measure-Command cmdlet which is for time measuring. (again on Technet)

Moment.js - tomorrow, today and yesterday

const date = moment(YOUR_DATE)
return (moment().diff(date, 'days') >= 2) ? date.fromNow() : date.calendar().split(' ')[0]

Remove all whitespace in a string

In addition, strip has some variations:

Remove spaces in the BEGINNING and END of a string:

sentence= sentence.strip()

Remove spaces in the BEGINNING of a string:

sentence = sentence.lstrip()

Remove spaces in the END of a string:

sentence= sentence.rstrip()

All three string functions strip lstrip, and rstrip can take parameters of the string to strip, with the default being all white space. This can be helpful when you are working with something particular, for example, you could remove only spaces but not newlines:

" 1. Step 1\n".strip(" ")

Or you could remove extra commas when reading in a string list:

"1,2,3,".strip(",")

How to determine the Schemas inside an Oracle Data Pump Export file

Update (2008-09-19 10:05) - Solution:

My Solution: Social engineering, I dug real hard and found someone who knew the schema name.
Technical Solution: Searching the .dmp file did yield the schema name.
Once I knew the schema name, I searched the dump file and learned where to find it.

Places the Schemas name were seen, in the .dmp file:

  • <OWNER_NAME>SOURCE_SCHEMA</OWNER_NAME> This was seen before each table name/definition.

  • SCHEMA_LIST 'SOURCE_SCHEMA' This was seen near the end of the .dmp.

Interestingly enough, around the SCHEMA_LIST 'SOURCE_SCHEMA' section, it also had the command line used to create the dump, directories used, par files used, windows version it was run on, and export session settings (language, date formats).

So, problem solved :)

how to change text in Android TextView

setting the text to sam textview twice is overwritting the first written text. So the second time when we use settext we just append the new string like

textview.append("Step Two: fry egg");

Biggest differences of Thrift vs Protocol Buffers?

Protocol Buffers seems to have a more compact representation, but that's only an impression I get from reading the Thrift whitepaper. In their own words:

We decided against some extreme storage optimizations (i.e. packing small integers into ASCII or using a 7-bit continuation format) for the sake of simplicity and clarity in the code. These alterations can easily be made if and when we encounter a performance-critical use case that demands them.

Also, it may just be my impression, but Protocol Buffers seems to have some thicker abstractions around struct versioning. Thrift does have some versioning support, but it takes a bit of effort to make it happen.

How to change Android usb connect mode to charge only?

The HTC devices have the PCSII.apk which allow them to select usb connect mode. For your device, you can set it manually:

Use SQLite Editor to open /data/data/com.android.providers.setting/databases/settings.db

open table secure

turn settings starting with mount_ums_ to 0, then restart devices.

UPDATE: If it still doesn't work, try turning on debug mode.

Aligning label and textbox on same line (left and right)

you can use style

   <td  colspan="2">
     <div style="float:left; width:80px"><asp:Label ID="Label6" runat="server" Text="Label"></asp:Label></div>

    <div style="float: right; width:100px">    
            <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    </div>

     <div style="clear:both"></div>

    </td>

Representing EOF in C code?

The answer is NO, but...

You may confused because of the behavior of fgets()

From http://www.cplusplus.com/reference/cstdio/fgets/ :

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

Why is the gets function so dangerous that it should not be used?

Why is gets() dangerous

The first internet worm (the Morris Internet Worm) escaped about 30 years ago (1988-11-02), and it used gets() and a buffer overflow as one of its methods of propagating from system to system. The basic problem is that the function doesn't know how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may overflow the bounds of the buffer it was given.

You should forget you ever heard that gets() existed.

The C11 standard ISO/IEC 9899:2011 eliminated gets() as a standard function, which is A Good Thing™ (it was formally marked as 'obsolescent' and 'deprecated' in ISO/IEC 9899:1999/Cor.3:2007 — Technical Corrigendum 3 for C99, and then removed in C11). Sadly, it will remain in libraries for many years (meaning 'decades') for reasons of backwards compatibility. If it were up to me, the implementation of gets() would become:

char *gets(char *buffer)
{
    assert(buffer != 0);
    abort();
    return 0;
}

Given that your code will crash anyway, sooner or later, it is better to head the trouble off sooner rather than later. I'd be prepared to add an error message:

fputs("obsolete and dangerous function gets() called\n", stderr);

Modern versions of the Linux compilation system generates warnings if you link gets() — and also for some other functions that also have security problems (mktemp(), …).

Alternatives to gets()

fgets()

As everyone else said, the canonical alternative to gets() is fgets() specifying stdin as the file stream.

char buffer[BUFSIZ];

while (fgets(buffer, sizeof(buffer), stdin) != 0)
{
    ...process line of data...
}

What no-one else yet mentioned is that gets() does not include the newline but fgets() does. So, you might need to use a wrapper around fgets() that deletes the newline:

char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
    if (fgets(buffer, buflen, fp) != 0)
    {
        size_t len = strlen(buffer);
        if (len > 0 && buffer[len-1] == '\n')
            buffer[len-1] = '\0';
        return buffer;
    }
    return 0;
}

Or, better:

char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
    if (fgets(buffer, buflen, fp) != 0)
    {
        buffer[strcspn(buffer, "\n")] = '\0';
        return buffer;
    }
    return 0;
}

Also, as caf points out in a comment and paxdiablo shows in his answer, with fgets() you might have data left over on a line. My wrapper code leaves that data to be read next time; you can readily modify it to gobble the rest of the line of data if you prefer:

        if (len > 0 && buffer[len-1] == '\n')
            buffer[len-1] = '\0';
        else
        {
             int ch;
             while ((ch = getc(fp)) != EOF && ch != '\n')
                 ;
        }

The residual problem is how to report the three different result states — EOF or error, line read and not truncated, and partial line read but data was truncated.

This problem doesn't arise with gets() because it doesn't know where your buffer ends and merrily tramples beyond the end, wreaking havoc on your beautifully tended memory layout, often messing up the return stack (a Stack Overflow) if the buffer is allocated on the stack, or trampling over the control information if the buffer is dynamically allocated, or copying data over other precious global (or module) variables if the buffer is statically allocated. None of these is a good idea — they epitomize the phrase 'undefined behaviour`.


There is also the TR 24731-1 (Technical Report from the C Standard Committee) which provides safer alternatives to a variety of functions, including gets():

§6.5.4.1 The gets_s function

Synopsis

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
char *gets_s(char *s, rsize_t n);

Runtime-constraints

s shall not be a null pointer. n shall neither be equal to zero nor be greater than RSIZE_MAX. A new-line character, end-of-file, or read error shall occur within reading n-1 characters from stdin.25)

3 If there is a runtime-constraint violation, s[0] is set to the null character, and characters are read and discarded from stdin until a new-line character is read, or end-of-file or a read error occurs.

Description

4 The gets_s function reads at most one less than the number of characters specified by n from the stream pointed to by stdin, into the array pointed to by s. No additional characters are read after a new-line character (which is discarded) or after end-of-file. The discarded new-line character does not count towards number of characters read. A null character is written immediately after the last character read into the array.

5 If end-of-file is encountered and no characters have been read into the array, or if a read error occurs during the operation, then s[0] is set to the null character, and the other elements of s take unspecified values.

Recommended practice

6 The fgets function allows properly-written programs to safely process input lines too long to store in the result array. In general this requires that callers of fgets pay attention to the presence or absence of a new-line character in the result array. Consider using fgets (along with any needed processing based on new-line characters) instead of gets_s.

25) The gets_s function, unlike gets, makes it a runtime-constraint violation for a line of input to overflow the buffer to store it. Unlike fgets, gets_s maintains a one-to-one relationship between input lines and successful calls to gets_s. Programs that use gets expect such a relationship.

The Microsoft Visual Studio compilers implement an approximation to the TR 24731-1 standard, but there are differences between the signatures implemented by Microsoft and those in the TR.

The C11 standard, ISO/IEC 9899-2011, includes TR24731 in Annex K as an optional part of the library. Unfortunately, it is seldom implemented on Unix-like systems.


getline() — POSIX

POSIX 2008 also provides a safe alternative to gets() called getline(). It allocates space for the line dynamically, so you end up needing to free it. It removes the limitation on line length, therefore. It also returns the length of the data that was read, or -1 (and not EOF!), which means that null bytes in the input can be handled reliably. There is also a 'choose your own single-character delimiter' variation called getdelim(); this can be useful if you are dealing with the output from find -print0 where the ends of the file names are marked with an ASCII NUL '\0' character, for example.

What is the difference between an abstract function and a virtual function?

An abstract function has no implemention and it can only be declared on an abstract class. This forces the derived class to provide an implementation.

A virtual function provides a default implementation and it can exist on either an abstract class or a non-abstract class.

So for example:

public abstract class myBase
{
    //If you derive from this class you must implement this method. notice we have no method body here either
    public abstract void YouMustImplement();

    //If you derive from this class you can change the behavior but are not required to
    public virtual void YouCanOverride()
    { 
    }
}

public class MyBase
{
   //This will not compile because you cannot have an abstract method in a non-abstract class
    public abstract void YouMustImplement();
}

What is an MvcHtmlString and when should I use it?

ASP.NET 4 introduces a new code nugget syntax <%: %>. Essentially, <%: foo %> translates to <%= HttpUtility.HtmlEncode(foo) %>. The team is trying to get developers to use <%: %> instead of <%= %> wherever possible to prevent XSS.

However, this introduces the problem that if a code nugget already encodes its result, the <%: %> syntax will re-encode it. This is solved by the introduction of the IHtmlString interface (new in .NET 4). If the foo() in <%: foo() %> returns an IHtmlString, the <%: %> syntax will not re-encode it.

MVC 2's helpers return MvcHtmlString, which on ASP.NET 4 implements the interface IHtmlString. Therefore when developers use <%: Html.*() %> in ASP.NET 4, the result won't be double-encoded.

Edit:

An immediate benefit of this new syntax is that your views are a little cleaner. For example, you can write <%: ViewData["anything"] %> instead of <%= Html.Encode(ViewData["anything"]) %>.

ReactJS - .JS vs .JSX

As already mentioned, there is no difference, if you create a file with .jsx or .js.

I would like to bring another expect of creating the files as .jsx while creating a component.

This is not mandatory, but an architectural approach that we can follow. So, in large projects we divide our components as Presentational components or Container components. Just to brief, in container components we write the logic to get data for the component and render the Presentational component with props. In presentational components, we usually donot write functional logic, presentational components are used to represent the UI with required props.

So, if you check the definition on JSX in React documents.

It says,

const element = <h1>Hello, world!</h1>;

It is called JSX, and it is a syntax extension to JavaScript. 
We recommend using it with React to describe what the UI should look like. 
JSX may remind you of a template language, but it comes with the full power of JavaScript.

JSX produces React “elements”. Instead of artificially separating technologies by putting
markup and logic in separate files, React separates concerns with loosely coupled units 
called “components” that contain both. 

React doesn’t require using JSX, but most people find it helpful as a visual aid when 
working with UI inside the JavaScript code. It also allows React to show more useful 
error and warning messages.

It means, It's not mandatory but you can think of creating presentational components with '.jsx' as it actually binds the props with the UI. and container components, as .js files as those contains logic to get the data.

It's a convention that you can follow while creating the .jsx or .js files, to logically and physically separate the code.

@UniqueConstraint and @Column(unique = true) in hibernate annotation

In addition to @Boaz's and @vegemite4me's answers....

By implementing ImplicitNamingStrategy you may create rules for automatically naming the constraints. Note you add your naming strategy to the metadataBuilder during Hibernate's initialization:

metadataBuilder.applyImplicitNamingStrategy(new MyImplicitNamingStrategy());

It works for @UniqueConstraint, but not for @Column(unique = true), which always generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).

There is a bug report to solve this issue, so if you can, please vote there to have this implemented. Here: https://hibernate.atlassian.net/browse/HHH-11586

Thanks.

Bash loop ping successful

I liked paxdiablo's script, but wanted a version that ran indefinitely. This version runs ping until a connection is established and then prints a message saying so.

echo "Testing..."

PING_CMD="ping -t 3 -c 1 google.com > /dev/null 2>&1"

eval $PING_CMD

if [[ $? -eq 0 ]]; then
    echo "Already connected."
else
    echo -n "Waiting for connection..."

    while true; do
        eval $PING_CMD

        if [[ $? -eq 0 ]]; then
            echo
            echo Connected.
            break
        else
            sleep 0.5
            echo -n .
        fi
    done
fi

I also have a Gist of this script which I'll update with fixes and improvements as needed.

SQL query for today's date minus two months

If you are using SQL Server try this:

SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())

Based on your update it would be:

SELECT * FROM FB WHERE Dte <  DATEADD(month, -2, GETDATE())

Merging two arrays in .NET

I think you can use Array.Copy for this. It takes a source index and destination index so you should be able to append the one array to the other. If you need to go more complex than just appending one to the other, this may not be the right tool for you.

Select elements by attribute in CSS

If you mean using an attribute selector, sure, why not:

[data-role="page"] {
    /* Styles */
}

There are a variety of attribute selectors you can use for various scenarios which are all covered in the document I link to. Note that, despite custom data attributes being a "new HTML5 feature",

  • browsers typically don't have any problems supporting non-standard attributes, so you should be able to filter them with attribute selectors; and

  • you don't have to worry about CSS validation either, as CSS doesn't care about non-namespaced attribute names as long as they don't break the selector syntax.

Can a constructor in Java be private?

Yes, class can have a private constructor. It is needed as to disallow to access the constructor from other classes and remain it accessible within defined class.

Why would you want objects of your class to only be created internally? This could be done for any reason, but one possible reason is that you want to implement a singleton. A singleton is a design pattern that allows only one instance of your class to be created, and this can be accomplished by using a private constructor.

jQuery select by attribute using AND and OR operators

JQuery uses CSS selectors to select elements, so you just need to use more than one rule by separating them with commas, as so:

a=$('[myc="blue"], [myid="1"], [myid="3"]');

Edit:

Sorry, you wanted blue and 1 or 3. How about:

a=$('[myc="blue"][myid="1"],  [myid="3"]');

Putting the two attribute selectors together gives you AND, using a comma gives you OR.

How do I change the title of the "back" button on a Navigation Bar

Swift version:

In your child ViewController:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.navigationBar.backItem?.title = "TEXT"
}

Render basic HTML view?

For plain html you don't require any npm package or middleware

just use this:

app.get('/', function(req, res) {
    res.sendFile('index.html');
});

Android: why is there no maxHeight for a View?

if you guys want to make a non-overflow scrollview or listview, just but it on a RelativeLayout with a topview and bottomview on top and bottom for it:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/topview"
    android:layout_below="@+id/bottomview" >

How can I delete an item from an array in VB.NET?

That depends on what you mean by delete. An array has a fixed size, so deleting doesn't really make sense.

If you want to remove element i, one option would be to move all elements j > i one position to the left (a[j - 1] = a[j] for all j, or using Array.Copy) and then resize the array using ReDim Preserve.

So, unless you are forced to use an array by some external constraint, consider using a data structure more suitable for adding and removing items. List<T>, for example, also uses an array internally but takes care of all the resizing issues itself: For removing items, it uses the algorithm mentioned above (without the ReDim), which is why List<T>.RemoveAt is an O(n) operation.

There's a whole lot of different collection classes in the System.Collections.Generic namespace, optimized for different use cases. If removing items frequently is a requirement, there are lots of better options than an array (or even List<T>).

How can I check if PostgreSQL is installed or not via Linux script?

Go to bin directory of postgres db such as /opt/postgresql/bin & run below command :

[...bin]# ./psql --version

psql (PostgreSQL) 9.0.4

Here you go . .

Java int to String - Integer.toString(i) vs new Integer(i).toString()

In terms of performance measurement, if you are considering the time performance then the Integer.toString(i); is expensive if you are calling less than 100 million times. Else if it is more than 100 million calls then the new Integer(10).toString() will perform better.

Below is the code through u can try to measure the performance,

public static void main(String args[]) {
            int MAX_ITERATION = 10000000;
        long starttime = System.currentTimeMillis();
        for (int i = 0; i < MAX_ITERATION; ++i) {
            String s = Integer.toString(10);
        }
        long endtime = System.currentTimeMillis();
        System.out.println("diff1: " + (endtime-starttime));

        starttime = System.currentTimeMillis();
        for (int i = 0; i < MAX_ITERATION; ++i) {
            String s1 = new Integer(10).toString();
        }
        endtime = System.currentTimeMillis();
        System.out.println("diff2: " + (endtime-starttime));
    }

In terms of memory, the

new Integer(i).toString();

will take more memory as it will create the object each time, so memory fragmentation will happen.

How can I remove 3 characters at the end of a string in php?

Just do:

echo substr($string, 0, -3);

You don't need to use a strlen call, since, as noted in the substr docs:

If length is given and is negative, then that many characters will be omitted from the end of string

Git refusing to merge unrelated histories on rebase

I got this error when I set up a local repository first. Then I went to GitHub and created a new repository. Then I ran

git remote add origin <repository url>

When I tried to push or pull, I got the same fatal: unrelated_histories error every time.

Here is how I fixed it:

git pull origin master --allow-unrelated-histories
git merge origin origin/master
... add and commit here...
git push origin master

Accessing elements by type in javascript

In plain-old JavaScript you can do this:

var inputs = document.getElementsByTagName('input');

for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].type.toLowerCase() == 'text') {
        alert(inputs[i].value);
    }
}

In jQuery, you would just do:

// select all inputs of type 'text' on the page
$("input:text")

// hide all text inputs which are descendants of div class="foo"
$("div.foo input:text").hide();

How to access at request attributes in JSP?

Using JSTL:

<c:set var="message" value='${requestScope["Error_Message"]}' />

Here var sets the variable name and request.getAttribute is equal to requestScope. But it's not essential. ${Error_Message} will give you the same outcome. It'll search every scope. If you want to do some operation with content you take from Error_Message you have to do it using message. like below one.

<c:out value="${message}"/>

Assert that a WebElement is not present using Selenium WebDriver with java

Not an answer to the very question but perhaps an idea for the underlying task:

When your site logic should not show a certain element, you could insert an invisible "flag" element that you check for.

if condition
    renderElement()
else
    renderElementNotShownFlag() // used by Selenium test

Why does Maven have such a bad rep?

My answer: most users complains about maven because they were looking for its pros, but don't have time (or they don't want endure) in setting up their "company environment". That's a personal choice, it can depend from personal patience, the job environment(bosses never understand that a well done thing waste less time than an eternal bugfix cycle), etc..

However, In the following cases you can have only maven on your workstation without getting mad:

  1. a simple library with some beans.
  2. a simple "all-in-one" war.
  3. even a multi-module project, that has the "standard" dependencies (spring, hibernate,apache stuffs and whatever you can find in the central repository) but DOESN'T HAVE any dependencies on YOUR libraries.

The problems starts to come when you want more, like create your wrappers to standard frameworks classes, or reusable component libraries, you always want to use a set of plugins you like, etc..

In that case you have to invest your time in learning: I read in previous posts that someone talk about wasting half day or 2 days...that is not enough, at all: we are talking about modify your poms continuously for at least 1 month.

If you wanna use maven in complex projects, you should in order:

  1. have your internal repository: it's not an option, it's mandatory. I tried Artifactory and Nexus, they can create troubles at the beginning but when you setup them once, you forget them.
  2. create a "master pom" containing all the plugins (with relative version specified) you need, but you must avoid to put there your standard dependencies if you don't wanna get in trouble (for that, see the scope=import in dependenciesManagement ). this is the hardest part, but you can start copying a master pom of a famous project (spring, tapestry, ecc...) and strip what you don't need.
  3. if you have a complex project, you must think at what you want before you start to create the artifacts. For example, in a project that has a (war + WebServices Client) + (Webservice Server + spring + hibernate + Jbpm + whateverelse....) it's a good idea to create an "api" module that is referred by both the client and the server, but that contains only model+interfaces and does't bring the "server side" dependencies in the client side and the opposite. Fail in that, and maven will become a living hell on earth.
  4. if you use Eclipse, m2e plugin is essential: ok, it can be slow, sometimes you should refresh the project and update the project configuration, etc... but finding the "project build path" already setted up is worth of everything. And in the worst case, the command line will always works.
  5. While a Continuous Integration server is optional, it's strongly recomended at least for your common libraries. Putting a web application on CI can be too much(you don't reuse a webapp on several projects), but putting on CI your standard base classes, your "always used" entity beans, etc.. is priceless. Remember that these components are not used only by you, but they can be used even by your team mates while you are busy on other parts of code and that you can forget (i often do) to deploy manually in the company repository to make them available to the team members.

To have all these setted up... well, you can even spend months at the beginning, but once you get used to that, you will speed up a lot your development.

Personally I didn't use Gradle yet, I don't know if it's better or worst than Maven.

Read binary file as string in Ruby

To avoid leaving the file open, it is best to pass a block to File.open. This way, the file will be closed after the block executes.

contents = File.open('path-to-file.tar.gz', 'rb') { |f| f.read }

Binding a generic list to a repeater - ASP.NET

You may want to create a subRepeater.

<asp:Repeater ID="SubRepeater" runat="server" DataSource='<%# Eval("Fields") %>'>
  <ItemTemplate>
    <span><%# Eval("Name") %></span>
  </ItemTemplate>
</asp:Repeater>

You can also cast your fields

<%# ((ArrayFields)Container.DataItem).Fields[0].Name %>

Finally you could do a little CSV Function and write out your fields with a function

<%# GetAsCsv(((ArrayFields)Container.DataItem).Fields) %>

public string GetAsCsv(IEnumerable<Fields> fields)
{
  var builder = new StringBuilder();
  foreach(var f in fields)
  {
    builder.Append(f);
    builder.Append(",");
  }
  builder.Remove(builder.Length - 1);
  return builder.ToString();
}

Write Base64-encoded image to file

Try this:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;

public class WriteImage 
{   
    public static void main( String[] args )
    {
        BufferedImage image = null;
        try {

            URL url = new URL("URL_IMAGE");
            image = ImageIO.read(url);

            ImageIO.write(image, "jpg",new File("C:\\out.jpg"));
            ImageIO.write(image, "gif",new File("C:\\out.gif"));
            ImageIO.write(image, "png",new File("C:\\out.png"));

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Done");
    }
}

What underlies this JavaScript idiom: var self = this?

function Person(firstname, lastname) {
  this.firstname = firstname;

  this.lastname = lastname;
  this.getfullname = function () {
    return `${this.firstname}   ${this.lastname}`;
  };

  let that = this;
  this.sayHi = function() {
    console.log(`i am this , ${this.firstname}`);
    console.log(`i am that , ${that.firstname}`);
  };
}

let thisss = new Person('thatbetty', 'thatzhao');

let thatt = {firstname: 'thisbetty', lastname: 'thiszhao'};

thisss.sayHi.call(thatt);

how to set default main class in java?

As a comment, I had to allow a customer to execute a class in a jar which meant that the manifest file couldn't be modified (they couldn't be expected to do that). Thanks to the post by Anthony and samy-delux's comment, this is what the customer can now run to access the main of the specific class:

java -cp c:\path\to\jar\jarFile.jar com.utils.classpath -e -v textString

Rename all files in directory from $filename_h to $filename_half?

Use the rename utility:

rc@bvm3:/tmp/foo $ touch 05_h.png 06_h.png
rc@bvm3:/tmp/foo $ rename 's/_h/_half/' * 
rc@bvm3:/tmp/foo $ ls -l
total 0
-rw-r--r-- 1 rc rc 0 2011-09-17 00:15 05_half.png
-rw-r--r-- 1 rc rc 0 2011-09-17 00:15 06_half.png

Forcing a postback

You can try redirecting to same page.

Response.Redirect(Request.RawUrl);

The source was not found, but some or all event logs could not be searched

Launch Developer command line "As an Administrator". This account has full access to Security log

Oracle client ORA-12541: TNS:no listener

According to oracle online documentation

ORA-12541: TNS:no listener

Cause: The connection request could not be completed because the listener is not running.

Action: Ensure that the supplied destination address matches one of the addresses used by 
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or  
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on 
the remote machine.

What is reflection and why is it useful?

Java Reflection is quite powerful and can be very useful. Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.

A quick Java Reflection example to show you what using reflection looks like:

Method[] methods = MyObject.class.getMethods();

    for(Method method : methods){
        System.out.println("method = " + method.getName());
    }

This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names.

Exactly how all this works is explained here

Edit: After almost 1 year I am editing this answer as while reading about reflection I got few more uses of Reflection.

  • Spring uses bean configuration such as:


<bean id="someID" class="com.example.Foo">
    <property name="someField" value="someValue" />
</bean>

When the Spring context processes this < bean > element, it will use Class.forName(String) with the argument "com.example.Foo" to instantiate that Class.

It will then again use reflection to get the appropriate setter for the < property > element and set its value to the specified value.

  • Junit uses Reflection especially for testing Private/Protected methods.

For Private methods,

Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);

For private fields,

Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);

Get week of year in JavaScript like in PHP

With Luxon (https://github.com/moment/luxon) :

import { DateTime } from 'luxon';
const week: number = DateTime.fromJSDate(new Date()).weekNumber;

How to select a schema in postgres when using psql?

Use schema name with period in psql command to obtain information about this schema.

Setup:

test=# create schema test_schema;
CREATE SCHEMA
test=# create table test_schema.test_table (id int);
CREATE TABLE
test=# create table test_schema.test_table_2 (id int);
CREATE TABLE

Show list of relations in test_schema:

test=# \dt test_schema.
               List of relations
   Schema    |     Name     | Type  |  Owner   
-------------+--------------+-------+----------
 test_schema | test_table   | table | postgres
 test_schema | test_table_2 | table | postgres
(2 rows)

Show test_schema.test_table definition:

test=# \d test_schema.test_table
Table "test_schema.test_table"
 Column |  Type   | Modifiers 
--------+---------+-----------
 id     | integer | 

Show all tables in test_schema:

test=# \d test_schema.
Table "test_schema.test_table"
 Column |  Type   | Modifiers 
--------+---------+-----------
 id     | integer | 

Table "test_schema.test_table_2"
 Column |  Type   | Modifiers 
--------+---------+-----------
 id     | integer | 

etc...

file_get_contents() how to fix error "Failed to open stream", "No such file"

The actual problem of this error has nothing to do with file_get_content, the problem is the requested url if the url is not throwing content of the page and redirecting the request to some where else file_get_content says "Failed to open stream", just before file_get_contents check whether the url is working and not redirecting, here is the code:

function checkRedirect404($url) {

$ch = curl_init();

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_URL, $url);
    $out = curl_exec($ch);

    // line endings is the wonkiest piece of this whole thing
    $out = str_replace("\r", "", $out);

    // only look at the headers
    $headers_end = strpos($out, "\n\n");
    if( $headers_end !== false ) { 
        $out = substr($out, 0, $headers_end);
    }   

    $headers = explode("\n", $out);
    foreach($headers as $header) {
        if( substr($header, 0, 10) == "Location: " ) { 
            $target = substr($header, 10);

            //echo "Redirects: $target<br>";

            return true;
        }   
    }   

    return false;

}

Count unique values with pandas per groups

IIUC you want the number of different ID for every domain, then you can try this:

output = df.drop_duplicates()
output.groupby('domain').size()

output:

    domain
facebook.com    1
google.com      1
twitter.com     2
vk.com          3
dtype: int64

You could also use value_counts, which is slightly less efficient.But the best is Jezrael's answer using nunique:

%timeit df.drop_duplicates().groupby('domain').size()
1000 loops, best of 3: 939 µs per loop
%timeit df.drop_duplicates().domain.value_counts()
1000 loops, best of 3: 1.1 ms per loop
%timeit df.groupby('domain')['ID'].nunique()
1000 loops, best of 3: 440 µs per loop

Remove space above and below <p> tag HTML

Look here: http://www.w3schools.com/tags/tag_p.asp

The p element automatically creates some space before and after itself. The space is automatically applied by the browser, or you can specify it in a style sheet.

you could remove the extra space by using css

p {
   margin: 0px;
   padding: 0px;
}

or use the element <span> which has no default margins and is an inline element.

Breaking up long strings on multiple lines in Ruby without stripping newlines

You can use \ to indicate that any line of Ruby continues on the next line. This works with strings too:

string = "this is a \
string that spans lines"

puts string.inspect

will output "this is a string that spans lines"

Get and Set Screen Resolution

in Winforms, there is a Screen class you can use to get data about screen dimensions and color depth for all displays connected to the computer. Here's the docs page: http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx

CHANGING the screen resolution is trickier. There is a Resolution third party class that wraps the native code you'd otherwise hook into. Use its CResolution nested class to set the screen resolution to a new height and width; but understand that doing this will only work for height/width combinations the display actually supports (800x600, 1024x768, etc, not 817x435).

remove None value from a list without removing the 0 value

Say the list is like below

iterator = [None, 1, 2, 0, '', None, False, {}, (), []]

This will return only those items whose bool(item) is True

print filter(lambda item: item, iterator)
# [1, 2]

This is equivalent to

print [item for item in iterator if item]

To just filter None:

print filter(lambda item: item is not None, iterator)
# [1, 2, 0, '', False, {}, (), []]

Equivalent to:

print [item for item in iterator if item is not None]

To get all the items that evaluate to False

print filter(lambda item: not item, iterator)
# Will print [None, '', 0, None, False, {}, (), []]

Multiple IF statements between number ranges

I suggest using vlookup function to get the nearest match.


Step 1

Prepare data range and name it: 'numberRange':

enter image description here

Select the range. Go to menu: Data ? Named ranges... ? define the new named range.

Step 2

Use this simple formula:

=VLOOKUP(A2,numberRange,2)

enter image description here


This way you can ommit errors, and easily correct the result.

Output in a table format in Java's System.out

Check this out. The author provides a simple but elegant solution which doesn't require any 3rd party library. http://www.ksmpartners.com/2013/08/nicely-formatted-tabular-output-in-java/

An example of the TableBuilder and sample output

Why do I keep getting Delete 'cr' [prettier/prettier]?

in the file .eslintrc.json in side roles add this code it will solve this issue

      "rules": {
    "prettier/prettier": ["error",{
      "endOfLine": "auto"}
    ]

  }

Static linking vs dynamic linking

I agree with the points dnmckee mentions, plus:

  • Statically linked applications might be easier to deploy, since there are fewer or no additional file dependencies (.dll / .so) that might cause problems when they're missing or installed in the wrong place.

ActionController::InvalidAuthenticityToken

too late to answer but I found the solution.

When you define you own html form then you miss authentication token string that should be sent to controller for security reasons. But when you use rails form helper to generate a form you get something like following

<form accept-charset="UTF-8" action="/login/signin" method="post">
  <div style="display:none">
    <input name="utf8" type="hidden" value="&#x2713;">
    <input name="authenticity_token" type="hidden" 
      value="x37DrAAwyIIb7s+w2+AdoCR8cAJIpQhIetKRrPgG5VA=">
    .
    .
    .
  </div>
</form>

So the solution to the problem is either to add authenticity_token field or use rails form helpers rather then removing , downgrading or upgrading rails.

Getting cursor position in Python

sudo add-apt-repository ppa:deadsnakes
sudo apt-get update
sudo apt-get install python3.5 python3.5-tk
# or 2.7, 3.6 etc
# sudo apt-get install python2.7 python2.7-tk
# mouse_position.py
import Tkinter
p=Tkinter.Tk()
print(p.winfo_pointerxy()

Or with one-liner from the command line:

python -c "import Tkinter; p=Tkinter.Tk(); print(p.winfo_pointerxy())"
(1377, 379)

Oracle query execution time

One can issue the SQL*Plus command SET TIMING ON to get wall-clock times, but one can't take, for example, fetch time out of that trivially.

The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.

Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".

How to change symbol for decimal point in double.ToString()?

Some shortcut is to create a NumberFormatInfo class, set its NumberDecimalSeparator property to "." and use the class as parameter to ToString() method whenever u need it.

using System.Globalization;

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";

value.ToString(nfi);

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

This worked for me:

[XmlInclude(typeof(BankPayment))]
[Serializable]
public abstract class Payment { }    

[Serializable]
public class BankPayment : Payment {} 

[Serializable]
public class Payments : List<Payment>{}

XmlSerializer serializer = new XmlSerializer(typeof(Payments), new Type[]{typeof(Payment)});