Programs & Examples On #Boolean operations

Boolean algebra is the algebra of truth values 0 and 1. The operations are usually taken to be conjunction ∧, disjunction ∨, and negation ¬, with constants 0 and 1.

Using NOT operator in IF conditions

try like this

if (!(a | b)) {
    //blahblah
}

It's same with

if (a | b) {}
else {
    // blahblah
}

Boolean operators && and ||

The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, && and || only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{} construction and to direct program control rather than construct new vectors.. The & and the | operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.

When the arguments to && or || are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.

> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3

The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.

OR, AND Operator

if(A == "haha" && B == "hihi") {
//hahahihi?
}

if(A == "haha" || B != "hihi") {
//hahahihi!?
}

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

How to set text size in a button in html

Try this, its working in FF

body,
input,
select,
button {
 font-family: Arial,Helvetica,sans-serif;
 font-size: 14px;
}

resize font to fit in a div (on one line)

There is a jquery plugin available on github that probably just do what you want. It is called jquery-quickfit. It uses Jquery to provide a quick and dirty approach to fitting text into its surrounding container.

HTML:

<div id="quickfit">Text to fit*</div>

Javascript:

<script src=".../jquery.min.js" type="text/javascript" />
<script src="../script/jquery.quickfit.js" type="text/javascript" />

<script type="text/javascript">
  $(function() {
    $('#quickfit').quickfit();
  });
</script>

More information: https://github.com/chunksnbits/jquery-quickfit

Is there a decorator to simply cache function return values?

There is fastcache, which is "C implementation of Python 3 functools.lru_cache. Provides speedup of 10-30x over standard library."

Same as chosen answer, just different import:

from fastcache import lru_cache
@lru_cache(maxsize=128, typed=False)
def f(a, b):
    pass

Also, it comes installed in Anaconda, unlike functools which needs to be installed.

How to uncheck a radio button?

You can use this JQuery for uncheck radiobutton

$('input:radio[name="IntroducerType"]').removeAttr('checked');
                $('input:radio[name="IntroducerType"]').prop('checked', false);

"Are you missing an assembly reference?" compile error - Visual Studio

I found this issue in Visual Studio 2019 Version 16.4.4

I resolved most issues by discovering that the

packages.config

was missing the appropriate reference

eg:

<package id="System.Runtime" version="4.3.0" targetFramework="net461" />

How to download a file from my server using SSH (using PuTTY on Windows)

if you install git with git bash, you get SCP available on windows.

jQuery get values of checked checkboxes into array

DEMO: http://jsfiddle.net/PBhHK/

$(document).ready(function(){

    var searchIDs = $('input:checked').map(function(){

      return $(this).val();

    });
    console.log(searchIDs.get());

});

Just call get() and you'll have your array as it is written in the specs: http://api.jquery.com/map/

$(':checkbox').map(function() {
      return this.id;
    }).get().join();

How to apply multiple transforms in CSS?

You have to put them on one line like this:

li:nth-child(2) {
    transform: rotate(15deg) translate(-20px,0px);
}

When you have multiple transform directives, only the last one will be applied. It's like any other CSS rule.


Keep in mind multiple transform one line directives are applied from right to left.

This: transform: scale(1,1.5) rotate(90deg);
and: transform: rotate(90deg) scale(1,1.5);

will not produce the same result:

_x000D_
_x000D_
.orderOne, .orderTwo {_x000D_
  font-family: sans-serif;_x000D_
  font-size: 22px;_x000D_
  color: #000;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.orderOne {_x000D_
  transform: scale(1, 1.5) rotate(90deg);_x000D_
}_x000D_
_x000D_
.orderTwo {_x000D_
  transform: rotate(90deg) scale(1, 1.5);_x000D_
}
_x000D_
<div class="orderOne">_x000D_
  A_x000D_
</div>_x000D_
_x000D_
<div class="orderTwo">_x000D_
  A_x000D_
</div>
_x000D_
_x000D_
_x000D_

What does operator "dot" (.) mean?

There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:

MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary.

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I have just faced with similar issue building LLVM 3.7 version. first check whether you have installed the required library on your system:

$locate libstdc++.so.6.*

Then add the found location to your $LD_LIBRARY_PATH environment variable.

How to close a web page on a button click, a hyperlink or a link button click?

To close a windows form (System.Windows.Forms.Form) when one of its button is clicked: in Visual Studio, open the form in the designer, right click on the button and open its property page, then select the field DialogResult an set it to OK or the appropriate value.

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

If you are using the updated Microsoft.Web.RedisSessionStateProvider(starting from 3.0.2) you can add this to your web.config to allow concurrent sessions.

<appSettings>
    <add key="aspnet:AllowConcurrentRequestsPerSession" value="true"/>
</appSettings>

Source

Performing Inserts and Updates with Dapper

Instead of using any 3rd party library for query operations, I would rather suggest writing queries on your own. Because using any other 3rd party packages would take away the main advantage of using dapper i.e. flexibility to write queries.

Now, there is a problem with writing Insert or Update query for the entire object. For this, one can simply create helpers like below:

InsertQueryBuilder:

 public static string InsertQueryBuilder(IEnumerable < string > fields) {


  StringBuilder columns = new StringBuilder();
  StringBuilder values = new StringBuilder();


  foreach(string columnName in fields) {
   columns.Append($ "{columnName}, ");
   values.Append($ "@{columnName}, ");

  }
  string insertQuery = $ "({ columns.ToString().TrimEnd(',', ' ')}) VALUES ({ values.ToString().TrimEnd(',', ' ')}) ";

  return insertQuery;
 }

Now, by simply passing the name of the columns to insert, the whole query will be created automatically, like below:

List < string > columns = new List < string > {
 "UserName",
 "City"
}
//QueryBuilder is the class having the InsertQueryBuilder()
string insertQueryValues = QueryBuilderUtil.InsertQueryBuilder(columns);

string insertQuery = $ "INSERT INTO UserDetails {insertQueryValues} RETURNING UserId";

Guid insertedId = await _connection.ExecuteScalarAsync < Guid > (insertQuery, userObj);

You can also modify the function to return the entire INSERT statement by passing the TableName parameter.

Make sure that the Class property names match with the field names in the database. Then only you can pass the entire obj (like userObj in our case) and values will be mapped automatically.

In the same way, you can have the helper function for UPDATE query as well:

  public static string UpdateQueryBuilder(List < string > fields) {
   StringBuilder updateQueryBuilder = new StringBuilder();

   foreach(string columnName in fields) {
    updateQueryBuilder.AppendFormat("{0}=@{0}, ", columnName);
   }
   return updateQueryBuilder.ToString().TrimEnd(',', ' ');
  }

And use it like:

List < string > columns = new List < string > {
 "UserName",
 "City"
}
//QueryBuilder is the class having the UpdateQueryBuilder()
string updateQueryValues = QueryBuilderUtil.UpdateQueryBuilder(columns);

string updateQuery =  $"UPDATE UserDetails SET {updateQueryValues} WHERE UserId=@UserId";

await _connection.ExecuteAsync(updateQuery, userObj);

Though in these helper functions also, you need to pass the name of the fields you want to insert or update but at least you have full control over the query and can also include different WHERE clauses as and when required.

Through this helper functions, you will save the following lines of code:

For Insert Query:

 $ "INSERT INTO UserDetails (UserName,City) VALUES (@UserName,@City) RETURNING UserId";

For Update Query:

$"UPDATE UserDetails SET UserName=@UserName, City=@City WHERE UserId=@UserId";

There seems to be a difference of few lines of code, but when it comes to performing insert or update operation with a table having more than 10 fields, one can feel the difference.

You can use the nameof operator to pass the field name in the function to avoid typos

Instead of:

List < string > columns = new List < string > {
 "UserName",
 "City"
}

You can write:

List < string > columns = new List < string > {
nameof(UserEntity.UserName),
nameof(UserEntity.City),
}

Converting XDocument to XmlDocument and vice versa

You could try writing the XDocument to an XmlWriter piped to an XmlReader for an XmlDocument.

If I understand the concepts properly, a direct conversion is not possible (the internal structure is different / simplified with XDocument). But then, I might be wrong...

JSON character encoding

If you're using StringEntity try this, using your choice of character encoding. It handles foreign characters as well.

How does the bitwise complement operator (~ tilde) work?

The bit-wise operator is a unary operator which works on sign and magnitude method as per my experience and knowledge.

For example ~2 would result in -3.

This is because the bit-wise operator would first represent the number in sign and magnitude which is 0000 0010 (8 bit operator) where the MSB is the sign bit.

Then later it would take the negative number of 2 which is -2.

-2 is represented as 1000 0010 (8 bit operator) in sign and magnitude.

Later it adds a 1 to the LSB (1000 0010 + 1) which gives you 1000 0011.

Which is -3.

How to adjust the size of y axis labels only in R?

Don't know what you are doing (helpful to show what you tried that didn't work), but your claim that cex.axis only affects the x-axis is not true:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data = foo, cex.axis = 3)

at least for me with:

> sessionInfo()
R version 2.11.1 Patched (2010-08-17 r52767)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8    
 [5] LC_MONETARY=C              LC_MESSAGES=en_GB.UTF-8   
 [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
[1] ggplot2_0.8.8 proto_0.3-8   reshape_0.8.3 plyr_1.2.1   

loaded via a namespace (and not attached):
[1] digest_0.4.2 tools_2.11.1

Also, cex.axis affects the labelling of tick marks. cex.lab is used to control what R call the axis labels.

plot(Y ~ X, data = foo, cex.lab = 3)

but even that works for both the x- and y-axis.


Following up Jens' comment about using barplot(). Check out the cex.names argument to barplot(), which allows you to control the bar labels:

dat <- rpois(10, 3) names(dat) <- LETTERS[1:10] barplot(dat, cex.names = 3, cex.axis = 2)

As you mention that cex.axis was only affecting the x-axis I presume you had horiz = TRUE in your barplot() call as well? As the bar labels are not drawn with an axis() call, applying Joris' (otherwise very useful) answer with individual axis() calls won't help in this situation with you using barplot()

HTH

Windows batch command(s) to read first line from text file

Here is a workaround using powershell:

powershell (Get-Content file.txt)[0]

(You can easily read also a range of lines with powershell (Get-Content file.txt)[0..3])

If you need to set a variable inside a batch script as the first line of file.txt you may use:

for /f "usebackq delims=" %%a in (`powershell ^(Get-Content file.txt^)[0]`) do (set "head=%%a")

Using a custom typeface in Android

Is there a way to do this from the XML?

No, sorry. You can only specify the built-in typefaces through XML.

Is there a way to do it from code in one place, to say that the whole application and all the components should use the custom typeface instead of the default one?

Not that I am aware of.

There are a variety of options for these nowadays:

  • Font resources and backports in the Android SDK, if you are using appcompat

  • Third-party libraries for those not using appcompat, though not all will support defining the font in layout resources

PHP function to generate v4 UUID

In my search for a creating a v4 uuid, I came first to this page, then found this on http://php.net/manual/en/function.com-create-guid.php

function guidv4()
{
    if (function_exists('com_create_guid') === true)
        return trim(com_create_guid(), '{}');

    $data = openssl_random_pseudo_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

credit: pavel.volyntsev

Edit: to clarify, this function will always give you a v4 uuid (PHP >= 5.3.0).

When the com_create_guid function is available (usually only on Windows), it will use that and strip the curly braces.

If not present (Linux), it will fall back on this strong random openssl_random_pseudo_bytes function, it will then uses vsprintf to format it into v4 uuid.

How to check if a string contains an element from a list in Python

extensionsToCheck = ('.pdf', '.doc', '.xls')

'test.doc'.endswith(extensionsToCheck)   # returns True

'test.jpg'.endswith(extensionsToCheck)   # returns False

Loop X number of times

See this link. It shows you how to dynamically create variables in PowerShell.

Here is the basic idea:

Use New-Variable and Get-Variable,

for ($i=1; $i -le 5; $i++)
{
    New-Variable -Name "var$i" -Value $i
    Get-Variable -Name "var$i" -ValueOnly
}

(It is taken from the link provided, and I don't take credit for the code.)

Merge, update, and pull Git branches without using checkouts

The question is simple and the answer should be as simple. All the OP is asking is to merge the upstream origin/branchB into his current branch without switching branches.

TL;DR:

git fetch
git merge origin/branchB

The full answer:

git pull does a fetch + merge. It's roughly the the same the two commands below, where <remote> is usually origin (default), and the remote tracking branch starts with <remote>/ followed by the remote branch name:

git fetch [<remote>]
git merge @{u}

The @{u} notation is the configured remote tracking branch for the current branch. If branchB tracks origin/branchB then @{u} from branchB is the same as typing origin/branchB (see git rev-parse --help for more info).

Since you already merge with origin/branchB, all that is missing is the git fetch (which can run from any branch) to update that remote-tracking branch.

Note though that if there was any merge from the pull to include, you should rather merge branchB into branchA after having done a pull from branchB (and eventually push the changes to orign/branchB), but as long as they're fast-forward they would remain the same.

Keep in mind the local branchB will not be updated until you switch to it and do an actual pull, however as long as there are no local commits added to this branch it will just remain a fast-forward to the remote branch.

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

This also can happen if the device you are trying to run on has some older version of the provisioning profile you are using that points to an old, expired or revoked certificate or a certificate without associated private key. Delete any invalid Provisioning Profiles under your device section in Xcode organizer.

How to create Drawable from resource

You must get it via compatible way, others are deprecated:

Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), R.drawable.my_drawable, null);

Leader Not Available Kafka in Console Producer

We tend to get this message when we try to subscribe to a topic that has not been created yet. We generally rely on topics to be created a priori in our deployed environments, but we have component tests that run against a dockerized kafka instance, which starts clean every time.

In that case, we use AdminUtils in our test setup to check if the topic exists and create it if not. See this other stack overflow for more about setting up AdminUtils.

Angular2 QuickStart npm start is not working correctly

Try this:

  1. Install Latest versions npm/nodejs I purged my npm installation
  2. After that, install tsd npm install -g tsd
  3. Then clone https://github.com/johnpapa/angular2-tour-of-heroes.git
  4. Finally npm i and npm start

Compare a string using sh shell

-eq is the shell comparison operator for comparing integers. For comparing strings you need to use =.

sql delete statement where date is greater than 30 days

To delete records from a table that have a datetime value in Date_column older than 30 days use this query:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < GETDATE() - 30

...or this:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(dd,-30,GETDATE())

To delete records from a table that have a datetime value in Date_column older than 12 hours:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(hh,-12,GETDATE())

To delete records from a table that have a datetime value in Date_column older than 15 minutes:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(mi,-15,GETDATE())

From: http://zarez.net/?p=542

C++ template constructor

try doing something like

template<class T, int i> class A{

    A(){
          A(this)
    }

    A( A<int, 1>* a){
          //do something
    }
    A( A<float, 1>* a){
         //do something
    }
.
.
.
};

Display unescaped HTML in Vue.js

You have to use v-html directive for displaying html content inside a vue component

<div v-html="html content data property"></div>

Why is textarea filled with mysterious white spaces?

To make it look a bit cleaner, consider using the ternary operator:

<textarea><?=( $siteLink_val ? $siteLink_val : '' );?></textarea>

Can I hide the HTML5 number input’s spin box?

This like your css code:

input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

Web link to specific whatsapp contact

The solution that worked for me is here in PHP:

$android = stripos($_SERVER['HTTP_USER_AGENT'], "android");
$iphone = stripos($_SERVER['HTTP_USER_AGENT'], "iphone");
$ipad = stripos($_SERVER['HTTP_USER_AGENT'], "ipad");

$whatsappNumber = '1234597891';
$whatsappLink = '';
if($android !== false || $ipad !== false || $iphone !== false) {//For mobile
    $whatsappLink = '<a href="https://api.whatsapp.com/send?phone='.$whatsappNumber.'">'.$whatsappNumber.'</a>';
} else {//For desktop
    $whatsappLink = '<a href="https://web.whatsapp.com/send?phone='.$whatsappNumber.'">'.$whatsappNumber.'</a>';
}

Updating Anaconda fails: Environment Not Writable Error

Open this folder "C:\ProgramData\" and right-click on "\Anaconda3". go to properties -> security and check all the boxes for each user. This worked for me.

How to obtain the number of CPUs/cores in Linux from the command line?

Use below query to get core details

[oracle@orahost](TESTDB)$ grep -c ^processor /proc/cpuinfo
8

How can I get current date in Android?

I am providing the modern answer.

java.time and ThreeTenABP

To get the current date:

    LocalDate today = LocalDate.now(ZoneId.of("America/Hermosillo"));

This gives you a LocalDate object, which is what you should use for keeping a date in your program. A LocalDate is a date without time of day.

Only when you need to display the date to a user, format it into a string suitable for the user’s locale:

    DateTimeFormatter userFormatter
            = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
    System.out.println(today.format(userFormatter));

When I ran this snippet today in US English locale, output was:

July 13, 2019

If you want it shorter, specify FormatStyle.MEDIUM or even FormatStyle.SHORT. DateTimeFormatter.ofLocalizedDate uses the default formatting locale, so the point is that it will give output suitable for that locale, different for different locales.

If your user has very special requirements for the output format, use a format pattern string:

    DateTimeFormatter userFormatter = DateTimeFormatter.ofPattern(
            "d-MMM-u", Locale.forLanguageTag("ar-AE"));

13-???-2019

I am using and recommending java.time, the modern Java date and time API. DateFormat, SimpleDateFormat, Date and Calendar used in the question and/or many of the other answers, are poorly designed and long outdated. And java.time is so much nicer to work with.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

How do I add images in laravel view?

You should store your images, css and JS files in a public directory. To create a link to any of them, use asset() helper:

{{ asset('img/myimage.png') }}

https://laravel.com/docs/5.1/helpers#method-asset

As alternative, you could use amazing Laravel Collective package for building forms and HTML elements, so your code will look like this:

{{ HTML::image('img/myimage.png', 'a picture') }}

Whitespaces in java

If you can use apache.commons.lang in your project, the easiest way would be just to use the method provided there:

public static boolean containsWhitespace(CharSequence seq)

Check whether the given CharSequence contains any whitespace characters.

Parameters:

seq - the CharSequence to check (may be null) 

Returns:

true if the CharSequence is not empty and contains at least 1 whitespace character

It handles empty and null parameters and provides the functionality at a central place.

how do I query sql for a latest record date for each user

SELECT *
FROM ReportStatus c
inner join ( SELECT 
  MAX(Date) AS MaxDate
  FROM ReportStatus ) m
on  c.date = m.maxdate

Plot different DataFrames in the same figure

Although Chang's answer explains how to plot multiple times on the same figure, in this case you might be better off in this case using a groupby and unstacking:

(Assuming you have this in dataframe, with datetime index already)

In [1]: df
Out[1]:
            value  
datetime                         
2010-01-01      1  
2010-02-01      1  
2009-01-01      1  

# create additional month and year columns for convenience
df['Month'] = map(lambda x: x.month, df.index)
df['Year'] = map(lambda x: x.year, df.index)    

In [5]: df.groupby(['Month','Year']).mean().unstack()
Out[5]:
       value      
Year    2009  2010
Month             
1          1     1
2        NaN     1

Now it's easy to plot (each year as a separate line):

df.groupby(['Month','Year']).mean().unstack().plot()

Printing out a linked list using toString

I do it the following way:

public static void main(String[] args) {

    LinkedList list = new LinkedList();
    list.insertFront(1);
    list.insertFront(2);
    list.insertFront(3);
    System.out.println(list.toString());
}

String toString() {
    StringBuilder result = new StringBuilder();
    for(Object item:this) {
        result.append(item.toString());
        result.append("\n"); //optional
    }
    return result.toString();
}

AngularJS - pass function to directive

I had to use the "=" binding instead of "&" because that was not working. Strange behavior.

Counting Number of Letters in a string variable

If you don't need the leading and trailing spaces :

str.Trim().Length

Git merge without auto commit

Note the output while doing the merge - it is saying Fast Forward

In such situations, you want to do:

git merge v1.0 --no-commit --no-ff

ORACLE: Updating multiple columns at once

It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?

Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:

UPDATE INVOICE
   SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
     , INV_TOTAL    = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)     
WHERE INV_ID = I_INV_ID;

        

Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.

Passing a URL with brackets to curl

I was getting this error though there were no (obvious) brackets in my URL, and in my situation the --globoff command will not solve the issue.

For example (doing this on on mac in iTerm2):

for endpoint in $(grep some_string output.txt); do curl "http://1.2.3.4/api/v1/${endpoint}" ; done

I have grep aliased to "grep --color=always". As a result, the above command will result in this error, with some_string highlighted in whatever colour you have grep set to:

curl: (3) bad range in URL position 31:
http://1.2.3.4/api/v1/lalalasome_stringlalala

The terminal was transparently translating the [colour\codes]some_string[colour\codes] into the expected no-special-characters URL when viewed in terminal, but behind the scenes the colour codes were being sent in the URL passed to curl, resulting in brackets in your URL.

Solution is to not use match highlighting.

Extract only right most n letters from a string

var str = "PER 343573";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty 
             : str.Length < 6 ? str 
             : str.Substring(str.Length - 6); // "343573"
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // "343573"

this supports any number of character in the str. the alternative code not support null string. and, the first is faster and the second is more compact.

i prefer the second one if knowing the str containing short string. if it's long string the first one is more suitable.

e.g.

var str = "";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty 
             : str.Length < 6 ? str 
             : str.Substring(str.Length - 6); // ""
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // ""

or

var str = "123";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty 
             : str.Length < 6 ? str 
             : str.Substring(str.Length - 6); // "123"
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // "123"

How to reload the current route with the angular 2 router

reload current route in angular 2 very helpful link to reload current route in angualr 2 or 4

in this define two technique to do this

  1. with dummy query params
  2. with dummy route

for more see above link

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

C language leaves compiler some freedom about the location of the structural elements in the memory:

  • memory holes may appear between any two components, and after the last component. It was due to the fact that certain types of objects on the target computer may be limited by the boundaries of addressing
  • "memory holes" size included in the result of sizeof operator. The sizeof only doesn't include size of the flexible array, which is available in C/C++
  • Some implementations of the language allow you to control the memory layout of structures through the pragma and compiler options

The C language provides some assurance to the programmer of the elements layout in the structure:

  • compilers required to assign a sequence of components increasing memory addresses
  • Address of the first component coincides with the start address of the structure
  • unnamed bit fields may be included in the structure to the required address alignments of adjacent elements

Problems related to the elements alignment:

  • Different computers line the edges of objects in different ways
  • Different restrictions on the width of the bit field
  • Computers differ on how to store the bytes in a word (Intel 80x86 and Motorola 68000)

How alignment works:

  • The volume occupied by the structure is calculated as the size of the aligned single element of an array of such structures. The structure should end so that the first element of the next following structure does not the violate requirements of alignment

p.s More detailed info are available here: "Samuel P.Harbison, Guy L.Steele C A Reference, (5.6.2 - 5.6.7)"

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

If you don't have non-ASCII characters (codepoints 128 and above) in your file, UTF-8 without BOM is the same as ASCII, byte for byte - so Notepad++ will guess wrong.

What you need to do is to specify the character encoding when serving the AJAX response - e.g. with PHP, you'd do this:

header('Content-Type: application/json; charset=utf-8');

The important part is to specify the charset with every JS response - else IE will fall back to user's system default encoding, which is wrong most of the time.

Setting an image button in CSS - image:active

This is what worked for me.

<!DOCTYPE html> 
<form action="desired Link">
  <button>  <img src="desired image URL"/>
  </button>
</form>
<style> 

</style>

How do I get specific properties with Get-AdUser

This worked for me as well:

Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"

Maven: best way of linking custom external JAR to my project?

Note that all of the example that use

<repository>...</respository> 

require outer

<repositories>...</repositories> 

enclosing tags. It's not clear from some of the examples.

Android open pdf file

The reason you don't have permissions to open file is because you didn't grant other apps to open or view the file on your intent. To grant other apps to open the downloaded file, include the flag(as shown below): FLAG_GRANT_READ_URI_PERMISSION

Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setDataAndType(getUriFromFile(localFile), "application/pdf");
browserIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|
Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(browserIntent);

And for function:

getUriFromFile(localFile)

private Uri getUriFromFile(File file){
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        return Uri.fromFile(file);
    }else {
        return FileProvider.getUriForFile(itemView.getContext(), itemView.getContext().getApplicationContext().getPackageName() + ".provider", file);
    }
}

Change color of Label in C#

You can try this with Color.FromArgb:

Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));

How to fill OpenCV image with one solid color?

Use numpy.full. Here's a Python that creates a gray, blue, green and red image and shows in a 2x2 grid.

import cv2
import numpy as np

gray_img = np.full((100, 100, 3), 127, np.uint8)

blue_img = np.full((100, 100, 3), 0, np.uint8)
green_img = np.full((100, 100, 3), 0, np.uint8)
red_img = np.full((100, 100, 3), 0, np.uint8)

full_layer = np.full((100, 100), 255, np.uint8)

# OpenCV goes in blue, green, red order
blue_img[:, :, 0] = full_layer
green_img[:, :, 1] = full_layer
red_img[:, :, 2] = full_layer

cv2.imshow('2x2_grid', np.vstack([
    np.hstack([gray_img, blue_img]), 
    np.hstack([green_img, red_img])
]))
cv2.waitKey(0)
cv2.destroyWindow('2x2_grid')

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Suppose we have streaming in video tag and id is video - <video id="video"></video> then we should have following code -

var videoEl = document.getElementById('video');
// now get the steam 
stream = videoEl.srcObject;
// now get all tracks
tracks = stream.getTracks();
// now close each track by having forEach loop
tracks.forEach(function(track) {
   // stopping every track
   track.stop();
});
// assign null to srcObject of video
videoEl.srcObject = null;

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

If using maven, usually you put log4j.properties under java or resources?

Add the below code from the resources tags in your pom.xml inside build tags. so it means resources tags must be inside of build tags in your pom.xml

<build>
    <resources>
        <resource>
            <directory>src/main/java/resources</directory>
                <filtering>true</filtering> 
         </resource>
     </resources>
<build/>

How to add rows dynamically into table layout

The way you have added a row into the table layout you can add multiple TableRow instances into your tableLayout object

tl.addView(row1);
tl.addView(row2);

etc...

Equivalent of SQL ISNULL in LINQ?

Looks like the type is boolean and therefore can never be null and should be false by default.

List vs tuple, when to use each?

The first thing you need to decide is whether the data structure needs to be mutable or not. As has been mentioned, lists are mutable, tuples are not. This also means that tuples can be used for dictionary keys, wheres lists cannot.

In my experience, tuples are generally used where order and position is meaningful and consistant. For example, in creating a data structure for a choose your own adventure game, I chose to use tuples instead of lists because the position in the tuple was meaningful. Here is one example from that data structure:

pages = {'foyer': {'text' : "some text", 
          'choices' : [('open the door', 'rainbow'),
                     ('go left into the kitchen', 'bottomless pit'),
                     ('stay put','foyer2')]},}

The first position in the tuple is the choice displayed to the user when they play the game and the second position is the key of the page that choice goes to and this is consistent for all pages.

Tuples are also more memory efficient than lists, though I'm not sure when that benefit becomes apparent.

Also check out the chapters on lists and tuples in Think Python.

How to negate the whole regex?

Assuming you only want to disallow strings that match the regex completely (i.e., mmbla is okay, but mm isn't), this is what you want:

^(?!(?:m{2}|t)$).*$

(?!(?:m{2}|t)$) is a negative lookahead; it says "starting from the current position, the next few characters are not mm or t, followed by the end of the string." The start anchor (^) at the beginning ensures that the lookahead is applied at the beginning of the string. If that succeeds, the .* goes ahead and consumes the string.

FYI, if you're using Java's matches() method, you don't really need the the ^ and the final $, but they don't do any harm. The $ inside the lookahead is required, though.

Convert MFC CString to integer

A _ttoi function can convert CString to integer, both wide char and ansi char can work. Below is the details:

CString str = _T("123");
int i = _ttoi(str);

Determine if a cell (value) is used in any formula

On Excel 2010 try this:

  1. select the cell you want to check if is used somewhere in a formula;
  2. Formulas -> Trace Dependents (on Formula Auditing menu)

How do I create a shortcut via command-line in Windows?

Cannot be done with pure batch.Check the shortcutJS.bat - it is a jscript/bat hybrid and should be used with .bat extension:

call shortcutJS.bat -linkfile "%~n0.lnk" -target  "%~f0" -linkarguments "some arguments"

With -help you can check the other options (you can set icon , admin permissions and etc.)

Angular 2 optional route parameter

rerezz's answer is pretty nice but it has one serious flaw. It causes User component to re-run the ngOnInit method.

It might be problematic when you do some heavy stuff there and don't want it to be re-run when you switch from the non-parametric route to the parametric one. Though those two routes are meant to imitate an optional url parameter, not become 2 separate routes.

Here's what I suggest to solve the problem:

const routes = [
  {
    path: '/user',
    component: User,
    children: [
      { path: ':id', component: UserWithParam, name: 'Usernew' }
    ]
  }
];

Then you can move the logic responsible for handling the param to the UserWithParam component and leave the base logic in the User component. Whatever you do in User::ngOnInit won't be run again when you navigate from /user to /user/123.

Don't forget to put the <router-outlet></router-outlet> in the User's template.

Read CSV file column by column

Finds all files in folder and write that data to ArrayList row.

Initialize

ArrayList<ArrayList<String>> row=new ArrayList<ArrayList<String>>();
BufferedReader br=null;

For Accessing row

for(ArrayList<String> data:row){
data.get(col no); 
}
or row.get(0).get(0) // getting first row first col

Functions that reads all files from folders and concatenate them row.

static void readData(){
String path="C:\\Users\\Galaxy Computers\\Desktop\\Java project\\Nasdaq\\";
File files=new File(path);
String[] list=files.list();

try {
        String sCurrentLine;
       char check;
       for(String filename:list){ 
        br = new BufferedReader(new FileReader(path+filename));
        br.readLine();//If file contains uneccessary first line.
        while ((sCurrentLine = br.readLine()) != null) {

           row.add(splitLine(sCurrentLine));
        }
        }
        }

    } catch (IOException e) {
        e.printStackTrace();
    } 
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


   static ArrayList<String> splitLine(String line){
   String[] ar=line.split(",");
   ArrayList<String> d=new ArrayList<String>();
   for(String data:ar){
    d.add(data);
   }

   return d; 
   } 

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

How to check type of object in Python?

use isinstance(v, type_name) or type(v) is type_name or type(v) == type_name,

where type_name can be one of the following:

  • None
  • bool
  • int
  • float
  • complex
  • str
  • list
  • tuple
  • set
  • dict

and, of course,

  • custom types (classes)

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

Angular 4.3 - HttpClient set params

Before 5.0.0-beta.6

let httpParams = new HttpParams();
Object.keys(data).forEach(function (key) {
     httpParams = httpParams.append(key, data[key]);
});

Since 5.0.0-beta.6

Since 5.0.0-beta.6 (2017-09-03) they added new feature (accept object map for HttpClient headers & params)

Going forward the object can be passed directly instead of HttpParams.

getCountries(data: any) {
    // We don't need any more these lines
    // let httpParams = new HttpParams();
    // Object.keys(data).forEach(function (key) {
    //     httpParams = httpParams.append(key, data[key]);
    // });

    return this.httpClient.get("/api/countries", {params: data})
}

Argument list too long error for rm, cp, mv commands

The below option seems simple to this problem. I got this info from some other thread but it helped me.

for file in /usr/op/data/Software/temp/application/openpages-storage/*; do
    cp "$file" /opt/sw/op-storage/
done

Just run the above one command and it will do the task.

Get IPv4 addresses from Dns.GetHostEntry()

    public Form1()
    {
        InitializeComponent();

        string myHost = System.Net.Dns.GetHostName();
        string myIP = null;

        for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
        {
            if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
            {
                myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
            }
        }
    }

Declare myIP and myHost in public Variable and use in any function of the form.

How to host a Node.Js application in shared hosting

Connect with SSH and follow these instructions to install Node on a shared hosting

In short you first install NVM, then you install the Node version of your choice with NVM.

wget -qO- https://cdn.rawgit.com/creationix/nvm/master/install.sh | bash

Your restart your shell (close and reopen your sessions). Then you

nvm install stable

to install the latest stable version for example. You can install any version of your choice. Check node --version for the node version you are currently using and nvm list to see what you've installed.

In bonus you can switch version very easily (nvm use <version>)

There's no need of PHP or whichever tricky workaround if you have SSH.

Do something if screen width is less than 960 px

nope, none of this will work. What you need is this!!!

Try this:

if (screen.width <= 960) {
  alert('Less than 960');
} else if (screen.width >960) {
  alert('More than 960');
}

Git vs Team Foundation Server

On top of everything that's been said (

https://stackoverflow.com/a/4416666/172109

https://stackoverflow.com/a/4894099/172109

https://stackoverflow.com/a/4415234/172109

), which is correct, TFS isn't just a VCS. One major feature that TFS provides is natively integrated bug tracking functionality. Changesets are linked to issues and could be tracked. Various policies for check-ins are supported, as well as integration with Windows domain, which is what people who run TFS have. Tightly integrated GUI with Visual Studio is another selling point, which appeals to less than average mouse and click developer and his manager.

Hence comparing Git to TFS isn't a proper question to ask. Correct, though impractical, question is to compare Git with just VCS functionality of TFS. At that, Git blows TFS out of the water. However, any serious team needs other tools and this is where TFS provides one stop destination.

How can I suppress the newline after a print statement?

Because python 3 print() function allows end="" definition, that satisfies the majority of issues.

In my case, I wanted to PrettyPrint and was frustrated that this module wasn't similarly updated. So i made it do what i wanted:

from pprint import PrettyPrinter

class CommaEndingPrettyPrinter(PrettyPrinter):
    def pprint(self, object):
        self._format(object, self._stream, 0, 0, {}, 0)
        # this is where to tell it what you want instead of the default "\n"
        self._stream.write(",\n")

def comma_ending_prettyprint(object, stream=None, indent=1, width=80, depth=None):
    """Pretty-print a Python object to a stream [default is sys.stdout] with a comma at the end."""
    printer = CommaEndingPrettyPrinter(
        stream=stream, indent=indent, width=width, depth=depth)
    printer.pprint(object)

Now, when I do:

comma_ending_prettyprint(row, stream=outfile)

I get what I wanted (substitute what you want -- Your Mileage May Vary)

How to prevent XSS with HTML/PHP?

Many frameworks help handle XSS in various ways. When rolling your own or if there's some XSS concern, we can leverage filter_input_array (available in PHP 5 >= 5.2.0, PHP 7.) I typically will add this snippet to my SessionController, because all calls go through there before any other controller interacts with the data. In this manner, all user input gets sanitized in 1 central location. If this is done at the beginning of a project or before your database is poisoned, you shouldn't have any issues at time of output...stops garbage in, garbage out.

/* Prevent XSS input */
$_GET   = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
/* I prefer not to use $_REQUEST...but for those who do: */
$_REQUEST = (array)$_POST + (array)$_GET + (array)$_REQUEST;

The above will remove ALL HTML & script tags. If you need a solution that allows safe tags, based on a whitelist, check out HTML Purifier.


If your database is already poisoned or you want to deal with XSS at time of output, OWASP recommends creating a custom wrapper function for echo, and using it EVERYWHERE you output user-supplied values:

//xss mitigation functions
function xssafe($data,$encoding='UTF-8')
{
   return htmlspecialchars($data,ENT_QUOTES | ENT_HTML401,$encoding);
}
function xecho($data)
{
   echo xssafe($data);
}

How to reference a .css file on a razor view?

You can this structure in Layout.cshtml file

<link href="~/YourCssFolder/YourCssStyle.css" rel="stylesheet" type="text/css" />

Output Django queryset as JSON

For a efficient solution, you can use .values() function to get a list of dict objects and then dump it to json response by using i.e. JsonResponse (remember to set safe=False).

Once you have your desired queryset object, transform it to JSON response like this:

...
data = list(queryset.values())
return JsonResponse(data, safe=False)

You can specify field names in .values() function in order to return only wanted fields (the example above will return all model fields in json objects).

HTML select form with option to enter custom value

If the datalist option doesn't fulfill your requirements, take a look to the Select2 library and the "Dynamic option creation"

_x000D_
_x000D_
$(".js-example-tags").select2({_x000D_
  tags: true_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>_x000D_
_x000D_
_x000D_
<select class="form-control js-example-tags">_x000D_
  <option selected="selected">orange</option>_x000D_
  <option>white</option>_x000D_
  <option>purple</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Create a basic matrix in C (input by user !)

You need to dynamically allocate your matrix. For instance:

int* mat;
int dimx,dimy;
scanf("%d", &dimx);
scanf("%d", &dimy);
mat = malloc(dimx * dimy * sizeof(int));

This creates a linear array which can hold the matrix. At this point you can decide whether you want to access it column or row first. I would suggest making a quick macro which calculates the correct offset in the matrix.

Get list from pandas dataframe column or row?

Example conversion:

Numpy Array -> Panda Data Frame -> List from one Panda Column

Numpy Array

data = np.array([[10,20,30], [20,30,60], [30,60,90]])

Convert numpy array into Panda data frame

dataPd = pd.DataFrame(data = data)
    
print(dataPd)
0   1   2
0  10  20  30
1  20  30  60
2  30  60  90

Convert one Panda column to list

pdToList = list(dataPd['2'])

Get the IP Address of local computer

Winsock specific:

// Init WinSock
WSADATA wsa_Data;
int wsa_ReturnCode = WSAStartup(0x101,&wsa_Data);

// Get the local hostname
char szHostName[255];
gethostname(szHostName, 255);
struct hostent *host_entry;
host_entry=gethostbyname(szHostName);
char * szLocalIP;
szLocalIP = inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
WSACleanup();

How do I URl encode something in Node.js?

Use the escape function of querystring. It generates a URL safe string.

var escaped_str = require('querystring').escape('Photo on 30-11-12 at 8.09 AM #2.jpg');
console.log(escaped_str);
// prints 'Photo%20on%2030-11-12%20at%208.09%20AM%20%232.jpg'

Get sum of MySQL column in PHP

I have replace your Code and it works well

$sum=0;
while ($row = mysql_fetch_assoc($result)){
    $value = $row['Value'];

    $sum += $value;
}

echo $sum;

PHP cURL, extract an XML response

simple load xml file ..

$xml = @simplexml_load_string($retValuet);

$status = (string)$xml->Status; 
$operator_trans_id = (string)$xml->OPID;
$trns_id = (string)$xml->TID;

?>

How to fix curl: (60) SSL certificate: Invalid certificate chain

After updating to OS X 10.9.2, I started having invalid SSL certificate issues with Homebrew, Textmate, RVM, and Github.

When I initiate a brew update, I was getting the following error:

fatal: unable to access 'https://github.com/Homebrew/homebrew/': SSL certificate problem: Invalid certificate chain
Error: Failure while executing: git pull -q origin refs/heads/master:refs/remotes/origin/master

I was able to alleviate some of the issue by just disabling the SSL verification in Git. From the console (a.k.a. shell or terminal):

git config --global http.sslVerify false

I am leary to recommend this because it defeats the purpose of SSL, but it is the only advice I've found that works in a pinch.

I tried rvm osx-ssl-certs update all which stated Already are up to date.

In Safari, I visited https://github.com and attempted to set the certificate manually, but Safari did not present the options to trust the certificate.

Ultimately, I had to Reset Safari (Safari->Reset Safari... menu). Then afterward visit github.com and select the certificate, and "Always trust" This feels wrong and deletes the history and stored passwords, but it resolved my SSL verification issues. A bittersweet victory.

What's the difference between .bashrc, .bash_profile, and .environment?

A good place to look at is the man page of bash. Here's an online version. Look for "INVOCATION" section.

How to pass props to {this.props.children}

None of the answers address the issue of having children that are NOT React components, such as text strings. A workaround could be something like this:

// Render method of Parent component
render(){
    let props = {
        setAlert : () => {alert("It works")}
    };
    let childrenWithProps = React.Children.map( this.props.children, function(child) {
        if (React.isValidElement(child)){
            return React.cloneElement(child, props);
        }
          return child;
      });
    return <div>{childrenWithProps}</div>

}

JOptionPane YES/No Options Confirm Dialog Box Issue

Try this,

int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
  System.out.println("Yes option");
} else {
  System.out.println("No Option");
} 

How to run a PowerShell script from a batch file

You need the -ExecutionPolicy parameter:

Powershell.exe -executionpolicy remotesigned -File  C:\Users\SE\Desktop\ps.ps1

Otherwise PowerShell considers the arguments a line to execute and while Set-ExecutionPolicy is a cmdlet, it has no -File parameter.

How to SELECT a dropdown list item by value programmatically

Ian Boyd (above) had a great answer -- Add this to Ian Boyd's class "WebExtensions" to select an item in a dropdownlist based on text:

/// <summary>
/// Selects the item in the list control that contains the specified text, if it exists.
/// </summary>
/// <param name="dropDownList"></param>
/// <param name="selectedText">The text of the item in the list control to select</param>
/// <returns>Returns true if the value exists in the list control, false otherwise</returns>
public static Boolean SetSelectedText(this DropDownList dropDownList, String selectedText)
{
    ListItem selectedListItem = dropDownList.Items.FindByText(selectedText);
    if (selectedListItem != null)
    {
        selectedListItem.Selected = true;
        return true;
    }
    else
        return false;
}

To call it:

WebExtensions.SetSelectedText(MyDropDownList, "MyValue");

How to print (using cout) a number in binary form?

Reusable function:

template<typename T>
static std::string toBinaryString(const T& x)
{
    std::stringstream ss;
    ss << std::bitset<sizeof(T) * 8>(x);
    return ss.str();
}

Usage:

int main(){
  uint16_t x=8;
  std::cout << toBinaryString(x);
}

This works with all kind of integers.

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

Remove "track by index" from the ng-repeat and it would refresh the DOM

How can I calculate the difference between two dates?

You may want to use something like this:

NSDateComponents *components;
NSInteger days;

components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit 
        fromDate: startDate toDate: endDate options: 0];
days = [components day];

I believe this method accounts for situations such as dates that span a change in daylight savings.

how to sort pandas dataframe from one column

Use sort_values to sort the df by a specific column's values:

In [18]:
df.sort_values('2')

Out[18]:
        0          1     2
4    85.6    January   1.0
3    95.5   February   2.0
7   104.8      March   3.0
0   354.7      April   4.0
8   283.5        May   5.0
6   238.7       June   6.0
5   152.0       July   7.0
1    55.4     August   8.0
11  212.7  September   9.0
10  249.6    October  10.0
9   278.8   November  11.0
2   176.5   December  12.0

If you want to sort by two columns, pass a list of column labels to sort_values with the column labels ordered according to sort priority. If you use df.sort_values(['2', '0']), the result would be sorted by column 2 then column 0. Granted, this does not really make sense for this example because each value in df['2'] is unique.

SET NOCOUNT ON usage

if (set no count== off)

{ then it will keep data of how many records affected so reduce performance } else { it will not track the record of changes hence improve perfomace } }

Running an executable in Mac Terminal

Unix will only run commands if they are available on the system path, as you can view by the $PATH variable

echo $PATH

Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such

./my-exec

Where my-exec is the name of your program.

How to add time to DateTime in SQL

Try this

SELECT DATEADD(MINUTE,HOW_MANY_MINUTES,TO_WHICH_TIME)

Here MINUTE is constant which indicates er are going to add/subtract minutes from TO_WHICH_TIME specifier. HOW_MANY_MINUTES is the interval by which we need to add minutes, if it is specified negative, time will be subtracted, else would be added to the TO_WHICH_TIME specifier and TO_WHICH_TIME is the original time to which you are adding MINUTE.

Hope this helps.

MySQL SELECT query string matching

Just turn the LIKE around

SELECT * FROM customers
WHERE 'Robert Bob Smith III, PhD.' LIKE CONCAT('%',name,'%')

What and When to use Tuple?

The difference between a tuple and a class is that a tuple has no property names. This is almost never a good thing, and I would only use a tuple when the arguments are fairly meaningless like in an abstract math formula Eg. abstract calculus over 5,6,7 dimensions might take a tuple for the coordinates.

Why is it important to override GetHashCode when Equals method is overridden?

Below using reflection seems to me a better option considering public properties as with this you don't have have to worry about addition / removal of properties (although not so common scenario). This I found to be performing better also.(Compared time using Diagonistics stop watch).

    public int getHashCode()
    {
        PropertyInfo[] theProperties = this.GetType().GetProperties();
        int hash = 31;
        foreach (PropertyInfo info in theProperties)
        {
            if (info != null)
            {
                var value = info.GetValue(this,null);
                if(value != null)
                unchecked
                {
                    hash = 29 * hash ^ value.GetHashCode();
                }
            }
        }
        return hash;  
    }

How do I convert from a money datatype in SQL server?

you could either use

SELECT PARSENAME('$'+ Convert(varchar,Convert(money,@MoneyValue),1),2)

or

SELECT CurrencyNoDecimals = '$'+ LEFT( CONVERT(varchar, @MoneyValue,1),    
       LEN (CONVERT(varchar, @MoneyValue,1)) - 2)

Use multiple @font-face rules in CSS

Note, you may also be interested in:

Custom web font not working in IE9

Which includes a more descriptive breakdown of the CSS you see below (and explains the tweaks that make it work better on IE6-9).


@font-face {
  font-family: 'Bumble Bee';
  src: url('bumblebee-webfont.eot');
  src: local('?'), 
       url('bumblebee-webfont.woff') format('woff'), 
       url('bumblebee-webfont.ttf') format('truetype'), 
       url('bumblebee-webfont.svg#webfontg8dbVmxj') format('svg');
}

@font-face {
  font-family: 'GestaReFogular';
  src: url('gestareg-webfont.eot');
  src: local('?'), 
       url('gestareg-webfont.woff') format('woff'), 
       url('gestareg-webfont.ttf') format('truetype'), 
       url('gestareg-webfont.svg#webfontg8dbVmxj') format('svg');
}

body {
  background: #fff url(../images/body-bg-corporate.gif) repeat-x;
  padding-bottom: 10px;
  font-family: 'GestaRegular', Arial, Helvetica, sans-serif;
}

h1 {
  font-family: "Bumble Bee", "Times New Roman", Georgia, Serif;
}

And your follow-up questions:

Q. I would like to use a font such as "Bumble bee," for example. How can I use @font-face to make that font available on the user's computer?

Note that I don't know what the name of your Bumble Bee font or file is, so adjust accordingly, and that the font-face declaration should precede (come before) your use of it, as I've shown above.

Q. Can I still use the other @font-face typeface "GestaRegular" as well? Can I use both in the same stylesheet?

Just list them together as I've shown in my example. There is no reason you can't declare both. All that @font-face does is instruct the browser to download and make a font-family available. See: http://iliadraznin.com/2009/07/css3-font-face-multiple-weights

Default value for field in Django model

You can also use a callable in the default field, such as:

b = models.CharField(max_length=7, default=foo)

And then define the callable:

def foo():
    return 'bar'

Visual Studio Code cannot detect installed git

This can happen after upgrading macOS. Try running git from a terminal and see if the error message begins with:

xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) ...

If so the fix is to run

xcode-select --install

from the terminal. see this answer for more details

Static variable inside of a function in C

6 7

x is a global variable that is visible only from foo(). 5 is its initial value, as stored in the .data section of the code. Any subsequent modification overwrite previous value. There is no assignment code generated in the function body.

I want to delete all bin and obj folders to force all projects to rebuild everything

I use to always add a new target on my solutions for achieving this.

<Target Name="clean_folders">
  <RemoveDir Directories=".\ProjectName\bin" />
  <RemoveDir Directories=".\ProjectName\obj" />
  <RemoveDir Directories="$(ProjectVarName)\bin" />
  <RemoveDir Directories="$(ProjectVarName)\obj" />
</Target>

And you can call it from command line

msbuild /t:clean_folders

This can be your batch file.

msbuild /t:clean_folders
PAUSE

Access HTTP response as string in Go

bs := string(body) should be enough to give you a string.

From there, you can use it as a regular string.

A bit as in this thread:

var client http.Client
resp, err := client.Get(url)
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

if resp.StatusCode == http.StatusOK {
    bodyBytes, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    bodyString := string(bodyBytes)
    log.Info(bodyString)
}

See also GoByExample.

As commented below (and in zzn's answer), this is a conversion (see spec).
See "How expensive is []byte(string)?" (reverse problem, but the same conclusion apply) where zzzz mentioned:

Some conversions are the same as a cast, like uint(myIntvar), which just reinterprets the bits in place.

Sonia adds:

Making a string out of a byte slice, definitely involves allocating the string on the heap. The immutability property forces this.
Sometimes you can optimize by doing as much work as possible with []byte and then creating a string at the end. The bytes.Buffer type is often useful.

Run Java Code Online

Some new java online compiler and runner:

  1. Java Launch
  2. Srikanthdaggumalli

These sites are in under development. But you can view the compilation errors, Runtime Exceptions as well as output of a java program by clicking on the TryItYourself link.

Why does corrcoef return a matrix?

corrcoef returns the normalised covariance matrix.

The covariance matrix is the matrix

Cov( X, X )    Cov( X, Y )

Cov( Y, X )    Cov( Y, Y )

Normalised, this will yield the matrix:

Corr( X, X )    Corr( X, Y )

Corr( Y, X )    Corr( Y, Y )

correlation1[0, 0 ] is the correlation between Strategy1Returns and itself, which must be 1. You just want correlation1[ 0, 1 ].

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

Got this from - http://blog.cedarsoft.com/2010/11/setting-java-library-path-programmatically/

If set the java.library.path, need to have the following lines in order to work.

Field fieldSysPath;
fieldSysPath = ClassLoader.class.getDeclaredField( "sys_paths" );
fieldSysPath.setAccessible( true );
fieldSysPath.set( null, null );

Hadoop "Unable to load native-hadoop library for your platform" warning

For installing Hadoop it is soooooo much easier installing the free version from Cloudera. It comes with a nice GUI that makes it simple to add nodes, there is no compiling or stuffing around with dependencies, it comes with stuff like hive, pig etc.

http://www.cloudera.com/content/support/en/downloads.html

Steps are: 1) Download 2) Run it 3) Go to web GUI (1.2.3.4:7180) 4) Add extra nodes in the web gui (do NOT install the cloudera software on other nodes, it does it all for you) 5) Within the web GUI go to Home, click Hue and Hue Web UI. This gives you access to Hive, Pig, Sqoop etc.

Remove warning messages in PHP

in Core Php to hide warning message set error_reporting(0) at top of common include file or individual file.

In Wordpress hide Warnings and Notices add following code in wp-config.php file

ini_set('log_errors','On');
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

How do I declare a 2d array in C++ using new?

I don't know for sure if the following answer wasn't provided but I decided to add some local optimizations to the allocation of 2d array (e.g., a square matrix is done through only one allocation): int** mat = new int*[n]; mat[0] = new int [n * n];

However, deletion goes like this because of linearity of the allocation above: delete [] mat[0]; delete [] mat;

How to redirect DNS to different ports

You can use SRV records:

_service._proto.name. TTL class SRV priority weight port target.

Service: the symbolic name of the desired service.

Proto: the transport protocol of the desired service; this is usually either TCP or UDP.

Name: the domain name for which this record is valid, ending in a dot.

TTL: standard DNS time to live field.

Class: standard DNS class field (this is always IN).

Priority: the priority of the target host, lower value means more preferred.

Weight: A relative weight for records with the same priority.

Port: the TCP or UDP port on which the service is to be found.

Target: the canonical hostname of the machine providing the service, ending in a dot.

Example:

_sip._tcp.example.com. 86400 IN SRV 0 5 5060 sipserver.example.com.

So what I think you're looking for is to add something like this to your DNS hosts file:

_sip._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25566 tekkit.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25567 pvp.arboristal.com.

On a side note, I highly recommend you go with a hosting company rather than hosting the servers yourself. It's just asking for trouble with your home connection (DDoS and Bandwidth/Connection Speed), but it's up to you.

How do you easily create empty matrices javascript?

Coffeescript to the rescue!

[1..9].map -> [1..9].map -> null

How to generate sample XML documents from their DTD or XSD?

XMLBlueprint 7.5 can do the following: - generate sample xml from dtd - generate sample xml from relax ng schema - generate sample xml from xml schema

Need table of key codes for android and presenter

You can find a complete list of Key Codes and an explanation here: http://code.google.com/p/androhid/wiki/Keycodes

How does createOrReplaceTempView work in Spark?

SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.

In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.

In order to create the view, developer need an utility called createOrReplaceTempView

Regular expression include and exclude special characters

You haven't actually asked a question, but assuming you have one, this could be your answer...

Assuming all characters, except the "Special Characters" are allowed you can write

String regex = "^[^<>'\"/;`%]*$";

VIM Disable Automatic Newline At End Of File

And for vim 7.4+ you can use (preferably on your .vimrc) (thanks to ??? for that last bit of news!):

:set nofixendofline

Now regarding older versions of vim.

Even if the file was already saved with new lines at the end:

vim -b file and once in vim:

:set noeol
:wq

done.

alternatively you can open files in vim with :e ++bin file

Yet another alternative:

:set binary
:set noeol
:wq

see more details at Why do I need vim in binary mode for 'noeol' to work?

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

What is output buffering?

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

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

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

Consider this example:

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

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

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

Consider this example:

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

Get a list of all the files in a directory (recursive)

Newer versions of Groovy (1.7.2+) offer a JDK extension to more easily traverse over files in a directory, for example:

import static groovy.io.FileType.FILES
def dir = new File(".");
def files = [];
dir.traverse(type: FILES, maxDepth: 0) { files.add(it) };

See also [1] for more examples.

[1] http://mrhaki.blogspot.nl/2010/04/groovy-goodness-traversing-directory.html

Google Maps Api v3 - find nearest markers

I'd like to expand on Leor's suggestion for anyone confused on how to compute the nearest location and actually provide a working solution:

I'm using markers in a markers array e.g. var markers = [];.

Then let's have our position as something like var location = new google.maps.LatLng(51.99, -0.74);

Then we simply reduce our markers against the location we have like so:

markers.reduce(function (prev, curr) {

    var cpos = google.maps.geometry.spherical.computeDistanceBetween(location.position, curr.position);
    var ppos = google.maps.geometry.spherical.computeDistanceBetween(location.position, prev.position);

    return cpos < ppos ? curr : prev;

}).position

What pops out is your closest marker LatLng object.

Number of processors/cores in command line

If you want to do this so it works on linux and OS X, you can do:

CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)

Clone Object without reference javascript

A and B reference the same object, so A.a and B.a reference the same property of the same object.

Edit

Here's a "copy" function that may do the job, it can do both shallow and deep clones. Note the caveats. It copies all enumerable properties of an object (not inherited properties), including those with falsey values (I don't understand why other approaches ignore them), it also doesn't copy non–existent properties of sparse arrays.

There is no general copy or clone function because there are many different ideas on what a copy or clone should do in every case. Most rule out host objects, or anything other than Objects or Arrays. This one also copies primitives. What should happen with functions?

So have a look at the following, it's a slightly different approach to others.

/* Only works for native objects, host objects are not
** included. Copies Objects, Arrays, Functions and primitives.
** Any other type of object (Number, String, etc.) will likely give 
** unexpected results, e.g. copy(new Number(5)) ==> 0 since the value
** is stored in a non-enumerable property.
**
** Expects that objects have a properly set *constructor* property.
*/
function copy(source, deep) {
   var o, prop, type;

  if (typeof source != 'object' || source === null) {
    // What do to with functions, throw an error?
    o = source;
    return o;
  }

  o = new source.constructor();

  for (prop in source) {

    if (source.hasOwnProperty(prop)) {
      type = typeof source[prop];

      if (deep && type == 'object' && source[prop] !== null) {
        o[prop] = copy(source[prop]);

      } else {
        o[prop] = source[prop];
      }
    }
  }
  return o;
}

Jquery click not working with ipad

We have a similar problem: the click event on a button doesn't work, as long as the user has not scrolled the page. The bug appears only on iOS.

We solved it by scrolling the page a little bit:

$('#modal-window').animate({scrollTop:$("#next-page-button-anchor").offset().top}, 500);

(It doesn't answer the ultimate cause, though. Maybe some kind of bug in Safari mobile ?)

Get random integer in range (x, y]?

How about:

Random generator = new Random();
int i = 10 - generator.nextInt(10);

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

Initially used only ViewDidLoad with tableView. On testing with loss of Wifi, by setting device to airplane mode, realized that the table did not refresh with return of Wifi. In fact, there appears to be no way to refresh tableView on the device even by hitting the home button with background mode set to YES in -Info.plist.

My solution:

-(void) viewWillAppear: (BOOL) animated { [self.tableView reloadData];}

Create file path from variables

Yes there is such a built-in function: os.path.join.

>>> import os.path
>>> os.path.join('/my/root/directory', 'in', 'here')
'/my/root/directory/in/here'

Error: " 'dict' object has no attribute 'iteritems' "

The purpose of .iteritems() was to use less memory space by yielding one result at a time while looping. I am not sure why Python 3 version does not support iteritems()though it's been proved to be efficient than .items()

If you want to include a code that supports both the PY version 2 and 3,

try:
    iteritems
except NameError:
    iteritems = items

This can help if you deploy your project in some other system and you aren't sure about the PY version.

Permutation of array

Here is one using arrays and Java 8+

import java.util.Arrays;
import java.util.stream.IntStream;

public class HelloWorld {

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 5};
        permutation(arr, new int[]{});
    }

    static void permutation(int[] arr, int[] prefix) {
        if (arr.length == 0) {
            System.out.println(Arrays.toString(prefix));
        }
        for (int i = 0; i < arr.length; i++) {
            int i2 = i;
            int[] pre = IntStream.concat(Arrays.stream(prefix), IntStream.of(arr[i])).toArray();
            int[] post = IntStream.range(0, arr.length).filter(i1 -> i1 != i2).map(v -> arr[v]).toArray();
            permutation(post, pre);
        }
    }
}

How to compare two dates?

datetime.date(2011, 1, 1) < datetime.date(2011, 1, 2) will return True.

datetime.date(2011, 1, 1) - datetime.date(2011, 1, 2) will return datetime.timedelta(-1).

datetime.date(2011, 1, 1) + datetime.date(2011, 1, 2) will return datetime.timedelta(1).

see the docs.

Getting URL parameter in java and extract a specific text from that URL

If you are using Jersey (which I was, my server component needs to make outbound HTTP requests) it contains the following public method:

var multiValueMap = UriComponent.decodeQuery(uri, true);

It is part of org.glassfish.jersey.uri.UriComponent, and the javadoc is here. Whilst you may not want all of Jersey, it is part of the Jersey common package which isn't too bad on dependencies...

Disable JavaScript error in WebBrowser control

I just found this :

 private static bool TrySetSuppressScriptErrors(WebBrowser webBrowser, bool value)
    {
        FieldInfo field = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
        if (field != null)
        {
            object axIWebBrowser2 = field.GetValue(webBrowser);
            if (axIWebBrowser2 != null)
            {
                axIWebBrowser2.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, axIWebBrowser2, new object[] { value });
                return true;
            }
        }

        return false;
    }

usage example to set webBrowser to silent : TrySetSuppressScriptErrors(webBrowser,true)

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

Processing Symbol Files in Xcode

It compares crash logs retrieved from the device to archived (symbolized to be correct) version of your applications to try to retrieved where on your code the crash occurred.

Look at xcode symbol file location for details

Eclipse Indigo - Cannot install Android ADT Plugin

Head over to Help -> Install New Software. Click on Available software sites. Delete the Android repo. Uncheck Indigo & Eclipse updates & recheck them. Now head back to Help -> Check for updates. Once done, add the Android repo again. Accept the license & you should be good to go.

(Had to do the same yesterday after getting Indigo)

Converting List<String> to String[] in Java

You want

String[] strarray = strlist.toArray(new String[0]);

See here for the documentation and note that you can also call this method in such a way that it populates the passed array, rather than just using it to work out what type to return. Also note that maybe when you print your array you'd prefer

System.out.println(Arrays.toString(strarray));

since that will print the actual elements.

How to copy files across computers using SSH and MAC OS X Terminal

You may also want to look at rsync if you're doing a lot of files.

If you're going to making a lot of changes and want to keep your directories and files in sync, you may want to use a version control system like Subversion or Git. See http://xoa.petdance.com/How_to:_Keep_your_home_directory_in_Subversion

Re-doing a reverted merge in Git

Instead of using git-revert you could have used this command in the devel branch to throw away (undo) the wrong merge commit (instead of just reverting it).

git checkout devel
git reset --hard COMMIT_BEFORE_WRONG_MERGE

This will also adjust the contents of the working directory accordingly. Be careful:

  • Save your changes in the develop branch (since the wrong merge) because they too will be erased by the git-reset. All commits after the one you specify as the git reset argument will be gone!
  • Also, don't do this if your changes were already pulled from other repositories because the reset will rewrite history.

I recommend to study the git-reset man-page carefully before trying this.

Now, after the reset you can re-apply your changes in devel and then do

git checkout devel
git merge 28s

This will be a real merge from 28s into devel like the initial one (which is now erased from git's history).

How to set 'X-Frame-Options' on iframe?

(I'm resurrecting this answer because I would like to share the workaround I created to solve this issue)

If you don't have access to the website hosting the web page you want to serve within the <iframe> element, you can circumvent the X-Frame-Options SAMEORIGIN restrictions by using a CORS-enabled reverse proxy that could request the web page(s) from the web server (upstream) and serve them to the end-user.

Here's a visual diagram of the concept:

enter image description here

Since I was unhappy with the CORS proxies I found, I ended up creating one myself, which I called CORSflare: it has been designed to run in a Cloudflare Worker (serverless computing), therefore it's a 100% free workaround - as long as you don't need it to accept more than 100.000 request per day.

You can find the proxy source code on GitHub; the full documentation, including the installation instruction, can be found in this post of my blog.

Launching Spring application Address already in use

Right click in console and click Terminate/Disconnect All option.

OR

Click on 'Display selected console' icon on top right corner of the console window and, choose and terminate the console which holds the port still.

Call a "local" function within module.exports from another function in module.exports?

You could declare your functions outside of the module.exports block.

var foo = function (req, res, next) {
  return ('foo');
}

var bar = function (req, res, next) {
  return foo();
}

Then:

module.exports = {
  foo: foo,
  bar: bar
}

How to reload a page after the OK click on the Alert Page

Try this code..

IN PHP Code

echo "<script type='text/javascript'>".
      "alert('Success to add the task to a project.');
       location.reload;".
     "</script>";

IN Javascript

function refresh()
{
    alert("click ok to refresh  page");
    location.reload();
}

R: Print list to a text file

depending on your tastes, an alternative to nico's answer:

d<-lapply(mylist, write, file=" ... ", append=T);

How to query DATETIME field using only date in Microsoft SQL Server?

Simple answer;

select * from test where cast ([date] as date) = '03/19/2014';

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

async for loop in node.js

I like to use the recursive pattern for this scenario. For example, something like this:

// If config is an array of queries
var config = JSON.parse(queries.querrryArray);   

// Array of results
var results;

processQueries(config);

function processQueries(queries) {
    var searchQuery;

    if (queries.length == 0) {
        // All queries complete
        res.writeHead(200, {'content-type': 'application/json'});
        res.end(JSON.stringify({results: results}));
        return;
    }

    searchQuery = queries.pop();

    search(searchQuery, function(result) {
        results.push(JSON.stringify({result: result}); 
        processQueries();            
    });

}

processQueries is a recursive function that will pull a query element out of an array of queries to process. Then the callback function calls processQueries again when the query is complete. The processQueries knows to end when there are no queries left.

It is easiest to do this using arrays, but it could be modified to work with object key/values I imagine.

Combine two columns of text in pandas dataframe

As many have mentioned previously, you must convert each column to string and then use the plus operator to combine two string columns. You can get a large performance improvement by using NumPy.

%timeit df['Year'].values.astype(str) + df.quarter
71.1 ms ± 3.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit df['Year'].astype(str) + df['quarter']
565 ms ± 22.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Edittext change border color with shape.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
     android:shape="rectangle">
     <solid android:color="#ffffff" />
     <stroke android:width="1dip" android:color="#ff9900" />
 </selector>

You have to remove > this from selector root tag, like below

   <selector xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">

As well as move your code to shape from selector.

Convert Mercurial project to Git

Some notes of my experience converting Mercurial to Git.

1. hg-fast-export

Using hg-fast-export failed and I needed --force as noted above. Next I got this error:

error: cannot lock ref 'refs/heads/stable': 'refs/heads/stable/sub-branch-name' exists; cannot create 'refs/heads/stable'

Upon completion of the hg-fast-export I ended up with an amputated repo. I think that this repo had a good few orphaned branches and that hg-fast-export needs a somewhat idealised repo. This all seemed a bit rough around the edges, so I moved on to Kiln Harmony (http://blog.fogcreek.com/announcing-kiln-harmony-the-future-of-dvcs/)

2. Kiln

Kiln Harmony does not appear to exist on a free tier account as suggested above. I could choose between Git-only and Mercurial-only repos and there is no option to switch. I raised a support ticket and will share the result if they reply.

3. hg-git

The Hg-Git mercurial plugin (http://hg-git.github.io/) did work for me. FYI on Mac OSX I installed hg-git via macports as follows:

  • sudo port install python27
  • sudo port select --set python python27
  • sudo port install py27-hggit
  • vi ~/.hgrc

.hgrc needs these lines:

[ui]
username = Name Surname <[email protected]>

[extensions]
hgext.bookmarks =
hggit = 

I then had success with:

hg push git+ssh://[email protected]:myaccount/myrepo.git

4. Caveat: Know your repo

All the above are blunt instruments and I only pushed ahead because it took enough time to get the team to use git properly.

Upon first pushing the project per (3) I ended up with all new changes missing. This is because this line of code must be viewed as a guide only:

$ hg bookmark -r default master # make a bookmark of master for default, so a ref gets created

The theory is that the default branch can be deemed to be master when pushing to git, and in my case I inherited a repo where they used 'stable' as the equivalent of master. Moreover, I also discovered that the tip of the repo was a hotfix not yet merged with the 'stable' branch.

Without properly understanding both Mercurial and the repo to be converted, you are probably better off not doing the conversion.

I did the following in order to get the repo ready for a second conversion attempt:

hg update -C stable
hg merge stable/hotfix-feature
hg ci -m "Merge with stable branch"
hg push git+ssh://[email protected]:myaccount/myrepo.git

After this I had a verifiably equivalent project in git, however all the orphaned branches I mentioned earlier are gone. I don't think that is too serious, but I may well live to regret this as an oversight. Therefore my final thought is to keep the original anyway.

Edit: If you just want the latest commit in git, this is simpler than the above merge:

hg book -r tip master
hg push git+ssh://[email protected]:myaccount/myrepo.git

How to launch multiple Internet Explorer windows/tabs from batch file?

This worked for me:

start /d IEXPLORE.EXE www.google.com
start /d IEXPLORE.EXE www.yahoo.com

But for some reason opened them up in Firefox instead?!?

I tried this but it merely opened up sites in two different windows:

start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.google.com
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.yahoo.com

What does %5B and %5D in POST requests stand for?

To take a quick look, you can percent-en/decode using this online tool.

Convert integer to hexadecimal and back again

Print integer in hex-value with zero-padding (if needed) :

int intValue = 1234;

Console.WriteLine("{0,0:D4} {0,0:X3}", intValue); 

https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros

What are ABAP and SAP?

In addition to all the regular confusion around SAP issues might also stem form the fact that SAP used to have their own DBMS ..

It used to be called Adabas (marketed originally by Nixdorf and then by Software AG) and was a quite popular DBMS for smaller SAP (the ERP solution) installations in Germany. At some point (AFAIK around 2000) SAP started to co-develop/support/take over Adabas and marketed it as SAP DB and later MaxDB under commercial and open-source licenses. There also was/is some agreement with MySQL.

But when people talk about SAP, they usually refer to the ERP solution as the other posters have noted.

UTF-8 encoding in JSP page

Page encoding or anything else do not matter a lot. ISO-8859-1 is a subset of UTF-8, therefore you never have to convert ISO-8859-1 to UTF-8 because ISO-8859-1 is already UTF-8,a subset of UTF-8 but still UTF-8. Plus, all that do not mean a thing if You have a double encoding somewhere. This is my "cure all" recipe for all things encoding and charset related:

        String myString = "heartbroken ð";

//String is double encoded, fix that first.

                myString = new String(myString.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                String cleanedText = StringEscapeUtils.unescapeJava(myString);
                byte[] bytes = cleanedText.getBytes(StandardCharsets.UTF_8);
                String text = new String(bytes, StandardCharsets.UTF_8);
                Charset charset = Charset.forName("UTF-8");
                CharsetDecoder decoder = charset.newDecoder();
                decoder.onMalformedInput(CodingErrorAction.IGNORE);
                decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                CharsetEncoder encoder = charset.newEncoder();
                encoder.onMalformedInput(CodingErrorAction.IGNORE);
                encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                try {
                    // The new ByteBuffer is ready to be read.
                    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(text));
                    // The new ByteBuffer is ready to be read.
                    CharBuffer cbuf = decoder.decode(bbuf);
                    String str = cbuf.toString();
                } catch (CharacterCodingException e) {
                    logger.error("Error Message if you want to");

                } 

Compare two objects in Java with possible null values

For these cases it would be better to use Apache Commons StringUtils#equals, it already handles null strings. Code sample:

public boolean compare(String s1, String s2) {
    return StringUtils.equals(s1, s2);
}

If you dont want to add the library, just copy the source code of the StringUtils#equals method and apply it when you need it.

How to store and retrieve a dictionary with redis

As the basic answer has already give by other people, I would like to add some to it.

Following are the commands in REDIS to perform basic operations with HashMap/Dictionary/Mapping type values.

  1. HGET => Returns value for single key passed
  2. HSET => set/updates value for the single key
  3. HMGET => Returns value for single/multiple keys passed
  4. HMSET => set/updates values for the multiple key
  5. HGETALL => Returns all the (key, value) pairs in the mapping.

Following are their respective methods in redis-py library :-

  1. HGET => hget
  2. HSET => hset
  3. HMGET => hmget
  4. HMSET => hmset
  5. HGETALL => hgetall

All of the above setter methods creates the mapping, if it doesn't exists. All of the above getter methods doesn't raise error/exceptions, if mapping/key in mapping doesn't exists.

Example:
=======
In [98]: import redis
In [99]: conn = redis.Redis('localhost')

In [100]: user = {"Name":"Pradeep", "Company":"SCTL", "Address":"Mumbai", "Location":"RCP"}

In [101]: con.hmset("pythonDict", {"Location": "Ahmedabad"})
Out[101]: True

In [102]: con.hgetall("pythonDict")
Out[102]:
{b'Address': b'Mumbai',
 b'Company': b'SCTL',
 b'Last Name': b'Rajpurohit',
 b'Location': b'Ahmedabad',
 b'Name': b'Mangu Singh'}

In [103]: con.hmset("pythonDict", {"Location": "Ahmedabad", "Company": ["A/C Pri
     ...: sm", "ECW", "Musikaar"]})
Out[103]: True

In [104]: con.hgetall("pythonDict")
Out[104]:
{b'Address': b'Mumbai',
 b'Company': b"['A/C Prism', 'ECW', 'Musikaar']",
 b'Last Name': b'Rajpurohit',
 b'Location': b'Ahmedabad',
 b'Name': b'Mangu Singh'}

In [105]: con.hget("pythonDict", "Name")
Out[105]: b'Mangu Singh'

In [106]: con.hmget("pythonDict", "Name", "Location")
Out[106]: [b'Mangu Singh', b'Ahmedabad']

I hope, it makes things more clear.

Uploading both data and files in one form using Ajax?

A Simple but more effective way:
new FormData() is itself like a container (or a bag). You can put everything attr or file in itself. The only thing you'll need to append the attribute, file, fileName eg:

let formData = new FormData()
formData.append('input', input.files[0], input.files[0].name)

and just pass it in AJAX request. Eg:

    let formData = new FormData()
    var d = $('#fileid')[0].files[0]

    formData.append('fileid', d);
    formData.append('inputname', value);

    $.ajax({
        url: '/yourroute',
        method: 'POST',
        contentType: false,
        processData: false,
        data: formData,
        success: function(res){
            console.log('successfully')
        },
        error: function(){
            console.log('error')
        }
    })

You can append n number of files or data with FormData.

and if you're making AJAX Request from Script.js file to Route file in Node.js beware of using
req.body to access data (ie text)
req.files to access file (ie image, video etc)

DateTime to javascript date

JavaScript Date constructor accepts number of milliseconds since Unix epoch (1 January 1970 00:00:00 UTC). Here’s C# extension method that converts .Net DateTime object to JavaScript date:

public static class DateTimeJavaScript
{
   private static readonly long DatetimeMinTimeTicks =
      (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;

   public static long ToJavaScriptMilliseconds(this DateTime dt)
   {
      return (long)((dt.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000);
   }
}

JavaScript Usage:

var dt = new Date(<%= DateTime.Today.ToJavaScriptMilliseconds() %>);
alert(dt);

C#: what is the easiest way to subtract time?

Use the TimeSpan object to capture your initial time element and use the methods such as AddHours or AddMinutes. To substract 3 hours, you will do AddHours(-3). To substract 45 mins, you will do AddMinutes(-45)

How do I remove a MySQL database?

For Visual Studio, in the package manager console:

 drop-database

SQL to Query text in access with an apostrophe in it

When you include a string literal in a query, you can enclose the string in either single or double quotes; Access' database engine will accept either. So double quotes will avoid the problem with a string which contains a single quote.

SELECT * FROM tblStudents WHERE [name] Like "Daniel O'Neal";

If you want to keep the single quotes around your string, you can double up the single quote within it, as mentioned in other answers.

SELECT * FROM tblStudents WHERE [name] Like 'Daniel O''Neal';

Notice the square brackets surrounding name. I used the brackets to lessen the chance of confusing the database engine because name is a reserved word.

It's not clear why you're using the Like comparison in your query. Based on what you've shown, this should work instead.

SELECT * FROM tblStudents WHERE [name] = "Daniel O'Neal";

c++ boost split string

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

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

What happened is the machine actually printed this:

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

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

Python base64 data decode

i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?

How to change the blue highlight color of a UITableViewCell?

If you want to change it app wide, you can add the logic to your App Delegate

class AppDelegate: UIResponder, UIApplicationDelegate {

    //... truncated

   func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {

        // set up your background color view
        let colorView = UIView()
        colorView.backgroundColor = UIColor.yellowColor()

        // use UITableViewCell.appearance() to configure 
        // the default appearance of all UITableViewCells in your app
        UITableViewCell.appearance().selectedBackgroundView = colorView

        return true
    }

    //... truncated
}

How to clear the logs properly for a Docker container?

Use:

truncate -s 0 /var/lib/docker/containers/*/*-json.log

You may need sudo

sudo sh -c "truncate -s 0 /var/lib/docker/containers/*/*-json.log"

ref. Jeff S. How to clear the logs properly for a Docker container?

Reference: Truncating a file while it's being used (Linux)

Downloading Java JDK on Linux via wget is shown license page instead

I solve this (for Debian based Linux distros) by making packages using java-package a few times (for various architectures), then distributing them internally.

The big plus side is that this method always works; no matter how crazy Oracle's web pages become. Oracle can no longer break my build!

The downside is that it's a bit more work to set up initially.

  • Download the tar.gz files manually in a browser (thus "accepting" their terms)
  • Run make-jpkg jdk-7u51-linux-x64.tar.gz. This creates oracle-java8-jdk_8_amd64.deb
  • Distribute it within your organization

For distribution over the Internet, I suggest using a password protected apt repository or provide raw packages using symmetric encryption:

passphrase="Hard to crack string. Use /dev/urandom for inspiration."
gpg --batch --symmetric --force-mdc --passphrase-fd 0 \
   oracle-java8-jdk_8_amd64.deb <<< "$passphrase"

Of course providing (unencrypted) .deb packages on the internet is probably a violation of your license agreement with Oracle, which states:

... Oracle grants you a ... license ... to reproduce and use internally the Software complete and unmodified for the sole purpose of running Programs"

On the receiving end, if you have a password protected apt repo, all you need to do is apt-get install it. If you have raw packages, download, decrypt and dpkg -i them. Works like a charm!

Yes or No confirm box using jQuery

I had trouble getting the answer back from the dialog box but eventually came up with a solution by combining the answer from this other question display-yes-and-no-buttons-instead-of-ok-and-cancel-in-confirm-box with part of the code from the modal-confirmation dialog

This is what was suggested for the other question:

Create your own confirm box:

<div id="confirmBox">
    <div class="message"></div>
    <span class="yes">Yes</span>
    <span class="no">No</span>
</div>

Create your own confirm() method:

function doConfirm(msg, yesFn, noFn)
{
    var confirmBox = $("#confirmBox");
    confirmBox.find(".message").text(msg);
    confirmBox.find(".yes,.no").unbind().click(function()
    {
        confirmBox.hide();
    });
    confirmBox.find(".yes").click(yesFn);
    confirmBox.find(".no").click(noFn);
    confirmBox.show();
}

Call it by your code:

doConfirm("Are you sure?", function yes()
{
    form.submit();
}, function no()
{
    // do nothing
});

MY CHANGES I have tweaked the above so that instead of calling confirmBox.show() I used confirmBox.dialog({...}) like this

confirmBox.dialog
    ({
      autoOpen: true,
      modal: true,
      buttons:
        {
          'Yes': function () {
            $(this).dialog('close');
            $(this).find(".yes").click();
          },
          'No': function () {
            $(this).dialog('close');
            $(this).find(".no").click();
          }
        }
    });

The other change I made was to create the confirmBox div within the doConfirm function, like ThulasiRam did in his answer.

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

In a project, my client would like a floating box in another div, so I use margin-top CSS property rather than top in order to my floating box stay in its parent.

How do I base64 encode a string efficiently using Excel VBA?

This code works very fast. It comes from here

Option Explicit

Private Const clOneMask = 16515072          '000000 111111 111111 111111
Private Const clTwoMask = 258048            '111111 000000 111111 111111
Private Const clThreeMask = 4032            '111111 111111 000000 111111
Private Const clFourMask = 63               '111111 111111 111111 000000

Private Const clHighMask = 16711680         '11111111 00000000 00000000
Private Const clMidMask = 65280             '00000000 11111111 00000000
Private Const clLowMask = 255               '00000000 00000000 11111111

Private Const cl2Exp18 = 262144             '2 to the 18th power
Private Const cl2Exp12 = 4096               '2 to the 12th
Private Const cl2Exp6 = 64                  '2 to the 6th
Private Const cl2Exp8 = 256                 '2 to the 8th
Private Const cl2Exp16 = 65536              '2 to the 16th

Public Function Encode64(sString As String) As String

    Dim bTrans(63) As Byte, lPowers8(255) As Long, lPowers16(255) As Long, bOut() As Byte, bIn() As Byte
    Dim lChar As Long, lTrip As Long, iPad As Integer, lLen As Long, lTemp As Long, lPos As Long, lOutSize As Long

    For lTemp = 0 To 63                                 'Fill the translation table.
        Select Case lTemp
            Case 0 To 25
                bTrans(lTemp) = 65 + lTemp              'A - Z
            Case 26 To 51
                bTrans(lTemp) = 71 + lTemp              'a - z
            Case 52 To 61
                bTrans(lTemp) = lTemp - 4               '1 - 0
            Case 62
                bTrans(lTemp) = 43                      'Chr(43) = "+"
            Case 63
                bTrans(lTemp) = 47                      'Chr(47) = "/"
        End Select
    Next lTemp

    For lTemp = 0 To 255                                'Fill the 2^8 and 2^16 lookup tables.
        lPowers8(lTemp) = lTemp * cl2Exp8
        lPowers16(lTemp) = lTemp * cl2Exp16
    Next lTemp

    iPad = Len(sString) Mod 3                           'See if the length is divisible by 3
    If iPad Then                                        'If not, figure out the end pad and resize the input.
        iPad = 3 - iPad
        sString = sString & String(iPad, Chr(0))
    End If

    bIn = StrConv(sString, vbFromUnicode)               'Load the input string.
    lLen = ((UBound(bIn) + 1) \ 3) * 4                  'Length of resulting string.
    lTemp = lLen \ 72                                   'Added space for vbCrLfs.
    lOutSize = ((lTemp * 2) + lLen) - 1                 'Calculate the size of the output buffer.
    ReDim bOut(lOutSize)                                'Make the output buffer.

    lLen = 0                                            'Reusing this one, so reset it.

    For lChar = LBound(bIn) To UBound(bIn) Step 3
        lTrip = lPowers16(bIn(lChar)) + lPowers8(bIn(lChar + 1)) + bIn(lChar + 2)    'Combine the 3 bytes
        lTemp = lTrip And clOneMask                     'Mask for the first 6 bits
        bOut(lPos) = bTrans(lTemp \ cl2Exp18)           'Shift it down to the low 6 bits and get the value
        lTemp = lTrip And clTwoMask                     'Mask for the second set.
        bOut(lPos + 1) = bTrans(lTemp \ cl2Exp12)       'Shift it down and translate.
        lTemp = lTrip And clThreeMask                   'Mask for the third set.
        bOut(lPos + 2) = bTrans(lTemp \ cl2Exp6)        'Shift it down and translate.
        bOut(lPos + 3) = bTrans(lTrip And clFourMask)   'Mask for the low set.
        If lLen = 68 Then                               'Ready for a newline
            bOut(lPos + 4) = 13                         'Chr(13) = vbCr
            bOut(lPos + 5) = 10                         'Chr(10) = vbLf
            lLen = 0                                    'Reset the counter
            lPos = lPos + 6
        Else
            lLen = lLen + 4
            lPos = lPos + 4
        End If
    Next lChar

    If bOut(lOutSize) = 10 Then lOutSize = lOutSize - 2 'Shift the padding chars down if it ends with CrLf.

    If iPad = 1 Then                                    'Add the padding chars if any.
        bOut(lOutSize) = 61                             'Chr(61) = "="
    ElseIf iPad = 2 Then
        bOut(lOutSize) = 61
        bOut(lOutSize - 1) = 61
    End If

    Encode64 = StrConv(bOut, vbUnicode)                 'Convert back to a string and return it.

End Function

Public Function Decode64(sString As String) As String

    Dim bOut() As Byte, bIn() As Byte, bTrans(255) As Byte, lPowers6(63) As Long, lPowers12(63) As Long
    Dim lPowers18(63) As Long, lQuad As Long, iPad As Integer, lChar As Long, lPos As Long, sOut As String
    Dim lTemp As Long

    sString = Replace(sString, vbCr, vbNullString)      'Get rid of the vbCrLfs.  These could be in...
    sString = Replace(sString, vbLf, vbNullString)      'either order.

    lTemp = Len(sString) Mod 4                          'Test for valid input.
    If lTemp Then
        Call Err.Raise(vbObjectError, "MyDecode", "Input string is not valid Base64.")
    End If

    If InStrRev(sString, "==") Then                     'InStrRev is faster when you know it's at the end.
        iPad = 2                                        'Note:  These translate to 0, so you can leave them...
    ElseIf InStrRev(sString, "=") Then                  'in the string and just resize the output.
        iPad = 1
    End If

    For lTemp = 0 To 255                                'Fill the translation table.
        Select Case lTemp
            Case 65 To 90
                bTrans(lTemp) = lTemp - 65              'A - Z
            Case 97 To 122
                bTrans(lTemp) = lTemp - 71              'a - z
            Case 48 To 57
                bTrans(lTemp) = lTemp + 4               '1 - 0
            Case 43
                bTrans(lTemp) = 62                      'Chr(43) = "+"
            Case 47
                bTrans(lTemp) = 63                      'Chr(47) = "/"
        End Select
    Next lTemp

    For lTemp = 0 To 63                                 'Fill the 2^6, 2^12, and 2^18 lookup tables.
        lPowers6(lTemp) = lTemp * cl2Exp6
        lPowers12(lTemp) = lTemp * cl2Exp12
        lPowers18(lTemp) = lTemp * cl2Exp18
    Next lTemp

    bIn = StrConv(sString, vbFromUnicode)               'Load the input byte array.
    ReDim bOut((((UBound(bIn) + 1) \ 4) * 3) - 1)       'Prepare the output buffer.

    For lChar = 0 To UBound(bIn) Step 4
        lQuad = lPowers18(bTrans(bIn(lChar))) + lPowers12(bTrans(bIn(lChar + 1))) + _
                lPowers6(bTrans(bIn(lChar + 2))) + bTrans(bIn(lChar + 3))           'Rebuild the bits.
        lTemp = lQuad And clHighMask                    'Mask for the first byte
        bOut(lPos) = lTemp \ cl2Exp16                   'Shift it down
        lTemp = lQuad And clMidMask                     'Mask for the second byte
        bOut(lPos + 1) = lTemp \ cl2Exp8                'Shift it down
        bOut(lPos + 2) = lQuad And clLowMask            'Mask for the third byte
        lPos = lPos + 3
    Next lChar

    sOut = StrConv(bOut, vbUnicode)                     'Convert back to a string.
    If iPad Then sOut = Left$(sOut, Len(sOut) - iPad)   'Chop off any extra bytes.
    Decode64 = sOut

End Function

How should I make my VBA code compatible with 64-bit Windows?

This answer is likely wrong wrong the context. I thought VBA now run on the CLR these days, but it does not. In any case, this reply may be useful to someone. Or not.


If you run Office 2010 32-bit mode then it's the same as Office 2007. (The "issue" is Office running in 64-bit mode). It's the bitness of the execution context (VBA/CLR) which is important here and the bitness of the loaded VBA/CLR depends upon the bitness of the host process.

Between 32/64-bit calls, most notable things that go wrong are using long or int (constant-sized in CLR) instead of IntPtr (dynamic sized based on bitness) for "pointer types".

The ShellExecute function has a signature of:

HINSTANCE ShellExecute(
  __in_opt  HWND hwnd,
  __in_opt  LPCTSTR lpOperation,
  __in      LPCTSTR lpFile,
  __in_opt  LPCTSTR lpParameters,
  __in_opt  LPCTSTR lpDirectory,
  __in      INT nShowCmd
);

In this case, it is important HWND is IntPtr (this is because a HWND is a "HANDLE" which is void*/"void pointer") and not long. See pinvoke.net ShellExecute as an example. (While some "solutions" are shady on pinvoke.net, it's a good place to look initially).

Happy coding.


As far as any "new syntax", I have no idea.

HTML form submit to PHP script

<form method="POST" action="chk_kw.php">
    <select name="website_string"> 
        <option selected="selected"></option>
        <option value="abc">abc</option>
        <option value="def">def</option>
        <option value="hij">hij</option>   
    </select>
    <input type="submit">
</form>


  • As your form gets more complex, you can a quick check at top of your php script using print_r($_POST);, it'll show what's being submitted an the respective element name.
  • To get the submitted value of the element in question do:

    $website_string = $_POST['website_string'];

How to set app icon for Electron / Atom Shell App

Please be aware that the examples for icon file path tend to assume that main.js is under the base directory. If the file is not in the base directory of the app, the path specification must account for that fact.

For example, if the main.js is under the src/ subdirectory, and the icon is under assets/icons/, this icon path specification will work:

icon: __dirname + "../assets/icons/icon.png"

CSS scale down image to fit in containing div, without specifing original size

You can use a background image to accomplish this;

From MDN - Background Size: Contain:

This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.

Demo

CSS:

#im {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url("path/to/img");
    background-repeat: no-repeat;
    background-size: contain;
}

HTML:

<div id="wrapper">
    <div id="im">
    </div>
</div>

How to build a Horizontal ListView with RecyclerView?

Complete example

enter image description here

The only real difference between a vertical RecyclerView and a horizontal one is how you set up the LinearLayoutManager. Here is the code snippet. The full example is below.

LinearLayoutManager horizontalLayoutManagaer = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(horizontalLayoutManagaer);

This fuller example is modeled after my vertical RecyclerView answer.

Update Gradle dependencies

Make sure the following dependencies are in your app gradle.build file:

implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'

You can update the version numbers to whatever is the most current.

Create activity layout

Add the RecyclerView to your xml layout.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvAnimals"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Create item layout

Each item in our RecyclerView is going to have a single a colored View over a TextView. Create a new layout resource file.

recyclerview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <View
        android:id="@+id/colorView"
        android:layout_width="100dp"
        android:layout_height="100dp"/>

    <TextView
        android:id="@+id/tvAnimalName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>

</LinearLayout>

Create the adapter

The RecyclerView needs an adapter to populate the views in each row (horizontal item) with your data. Create a new java file.

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private List<Integer> mViewColors;
    private List<String> mAnimals;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    MyRecyclerViewAdapter(Context context, List<Integer> colors, List<String> animals) {
        this.mInflater = LayoutInflater.from(context);
        this.mViewColors = colors;
        this.mAnimals = animals;
    }

    // inflates the row layout from xml when needed
    @Override
    @NonNull
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the view and textview in each row
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        int color = mViewColors.get(position);
        String animal = mAnimals.get(position);
        holder.myView.setBackgroundColor(color);
        holder.myTextView.setText(animal);
    }

    // total number of rows
    @Override
    public int getItemCount() {
        return mAnimals.size();
    }

    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        View myView;
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myView = itemView.findViewById(R.id.colorView);
            myTextView = itemView.findViewById(R.id.tvAnimalName);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // convenience method for getting data at click position
    public String getItem(int id) {
        return mAnimals.get(id);
    }

    // allows clicks events to be caught
    public void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

Notes

  • Although not strictly necessary, I included the functionality for listening for click events on the items. This was available in the old ListViews and is a common need. You can remove this code if you don't need it.

Initialize RecyclerView in Activity

Add the following code to your main activity.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    private MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        ArrayList<Integer> viewColors = new ArrayList<>();
        viewColors.add(Color.BLUE);
        viewColors.add(Color.YELLOW);
        viewColors.add(Color.MAGENTA);
        viewColors.add(Color.RED);
        viewColors.add(Color.BLACK);

        ArrayList<String> animalNames = new ArrayList<>();
        animalNames.add("Horse");
        animalNames.add("Cow");
        animalNames.add("Camel");
        animalNames.add("Sheep");
        animalNames.add("Goat");

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvAnimals);
        LinearLayoutManager horizontalLayoutManager
                = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(horizontalLayoutManager);
        adapter = new MyRecyclerViewAdapter(this, viewColors, animalNames);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on item position " + position, Toast.LENGTH_SHORT).show();
    }
}

Notes

  • Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle item click events in onItemClick.

Finished

That's it. You should be able to run your project now and get something similar to the image at the top.

Notes

How to remove jar file from local maven repository which was added with install:install-file?

At least on the current maven version you need to add the switch -DreResolve=false if you intend to remove the dependencies from your local repo without re-downloading them.

mvn dependency:purge-local-repository -DreResolve=false

removes the dependencies without downloading them again.

Laravel migration: unique key is too long, even if specified

I added to the migration itself

Schema::defaultStringLength(191);
Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

yes, I know I need to consider it on every migration but I would rather that than have it tucked away in some completely unrelated service provider

Google Chrome Printing Page Breaks

If you are using Chrome with Bootstrap Css the classes that control the grid layout eg col-xs-12 etc use "float: left" which, as others have pointed out, wrecks the page breaks. Remove these from your page for printing. It worked for me. (On Chrome version = 49.0.2623.87)

How do I remove whitespace from the end of a string in Python?

You can use strip() or split() to control the spaces values as in the following:

words = "   first  second   "

# Remove end spaces
def remove_end_spaces(string):
    return "".join(string.rstrip())


# Remove the first and end spaces
def remove_first_end_spaces(string):
    return "".join(string.rstrip().lstrip())


# Remove all spaces
def remove_all_spaces(string):
    return "".join(string.split())


# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))

Exploring Docker container's file system

None of the existing answers address the case of a container that exited (and can't be restarted) and/or doesn't have any shell installed (e.g. distroless ones). This one works as long has you have root access to the Docker host.

For a real manual inspection, find out the layer IDs first:

docker inspect my-container | jq '.[0].GraphDriver.Data'

In the output, you should see something like

"MergedDir": "/var/lib/docker/overlay2/03e8df748fab9526594cfdd0b6cf9f4b5160197e98fe580df0d36f19830308d9/merged"

Navigate into this folder (as root) to find the current visible state of the container filesystem.

How many bits is a "word"?

On x86/x64 processors, a byte is 8 bits, and there are 256 possible binary states in 8 bits, 0 thru 255. This is how the OS translates your keyboard key strokes into letters on the screen. When you press the 'A' key, the keyboard sends a binary signal equal to the number 97 to the computer, and the computer prints a lowercase 'a' on the screen. You can confirm this in any Windows text editing software by holding an ALT key, typing 97 on the NUMPAD, then releasing the ALT key. If you replace '97' with any number from 0 to 255, you will see the character associated with that number on the system's character code page printed on the screen.

If a character is 8 bits, or 1 byte, then a WORD must be at least 2 characters, so 16 bits or 2 bytes. Traditionally, you might think of a word as a varying number of characters, but in a computer, everything that is calculable is based on static rules. Besides, a computer doesn't know what letters and symbols are, it only knows how to count numbers. So, in computer language, if a WORD is equal to 2 characters, then a double-word, or DWORD, is 2 WORDs, which is the same as 4 characters or bytes, which is equal to 32 bits. Furthermore, a quad-word, or QWORD, is 2 DWORDs, same as 4 WORDs, 8 characters, or 64 bits.

Note that these terms are limited in function to the Windows API for developers, but may appear in other circumstances (eg. the Linux dd command uses numerical suffixes to compound byte and block sizes, where c is 1 byte and w is bytes).

Could not find a version that satisfies the requirement tensorflow

(as of Jan 1st, 2021)

Any over version 3.9.x there is no support for TensorFlow 2. If you are installing packages via pip with 3.9, you simply get a "package doesn't exist" message. After reverting to the latest 3.8.x. Thought I would drop this here, I will update when 3.9.x is working with Tensorflow 2.x

mvn command is not recognized as an internal or external command

For Windows you need to do the following:

  1. Windows and type env

  2. Open the edit environment panel

  3. Click Environment Variables

  4. In the system variables section, double click Path

  5. In the dialog, create a System Variable under Path like below ->

    MVN_HOME: C:\Users<username>\Documents\Project\Software\apache-maven-3.6.3\bin

  6. Open a new command prompt and hit mvn, you should be able to now.

Set background image in CSS using jquery

You have to remove the semicolon in the css rule string:

$(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");

Intercept and override HTTP requests from WebView

Try this, I've used it in a personal wiki-like app:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith("foo://")) {
            // magic
            return true;
        }
        return false;
    }
});

ListView with OnItemClickListener

setClickable as false to ImageButton like this

imagebutton.setClickable(false);

and then perform OnItemClickListener to listview.

Show hide div using codebehind

Another method (which it appears no-one has mentioned thus far), is to add an additional KeyValue pair to the element's Style array. i.e

Div.Style.Add("display", "none");

This has the added benefit of merely hiding the element, rather than preventing it from being written to the DOM to begin with - unlike the "Visible" property. i.e.

Div.Visible = false

results in the div never being written to the DOM.

Edit: This should be done in the 'code-behind', I.e. The *.aspx.cs file.

Check if string ends with one of the strings from a list

Though not widely known, str.endswith also accepts a tuple. You don't need to loop.

>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True