Programs & Examples On #Terminator

What is the easiest way to install BLAS and LAPACK for scipy?

Either use SciPy whl, download the appropriate one and run pip install <whl_file>

OR

Read through SciPy Windows issue and run one of the methods.

OR

Use Miniconda.

Additionally, install Visual C++ compiler for python2.7 in-case it asks for it.

TypeError: list indices must be integers or slices, not str

First, array_length should be an integer and not a string:

array_length = len(array_dates)

Second, your for loop should be constructed using range:

for i in range(array_length):  # Use `xrange` for python 2.

Third, i will increment automatically, so delete the following line:

i += 1

Note, one could also just zip the two lists given that they have the same length:

import csv

dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']

csv_file_patch = '/path/to/filename.csv'

with open(csv_file_patch, 'w') as fout:
    csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
    result_array = zip(dates, urls)
    csv_file.writerows(result_array)

Warning comparison between pointer and integer

It should be

if (*message == '\0')

In C, simple quotes delimit a single character whereas double quotes are for strings.

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

The listener supports no services

The database registers its service name(s) with the listener when it starts up. If it is unable to do so then it tries again periodically - so if the listener starts after the database then there can be a delay before the service is recognised.

If the database isn't running, though, nothing will have registered the service, so you shouldn't expect the listener to know about it - lsnrctl status or lsnrctl services won't report a service that isn't registered yet.

You can start the database up without the listener; from the Oracle account and with your ORACLE_HOME, ORACLE_SID and PATH set you can do:

sqlplus /nolog

Then from the SQL*Plus prompt:

connect / as sysdba
startup

Or through the Grid infrastructure, from the grid account, use the srvctl start database command:

srvctl start database -d db_unique_name [-o start_options] [-n node_name]

You might want to look at whether the database is set to auto-start in your oratab file, and depending on what you're using whether it should have started automatically. If you're expecting it to be running and it isn't, or you try to start it and it won't come up, then that's a whole different scenario - you'd need to look at the error messages, alert log, possibly trace files etc. to see exactly why it won't start, and if you can't figure it out, maybe ask on Database Adminsitrators rather than on Stack Overflow.


If the database can't see +DATA then ASM may not be running; you can see how to start that here; or using srvctl start asm. As the documentation says, make sure you do that from the grid home, not the database home.

powershell is missing the terminator: "

Look closely at the two dashes in

unzipRelease –Src '$ReleaseFile' -Dst '$Destination'

This first one is not a normal dash but an en-dash (&ndash; in HTML). Replace that with the dash found before Dst.

How do I set default terminal to terminator?

From within a terminal, try

sudo update-alternatives --config x-terminal-emulator

Select the desired terminal from the list of alternatives.

Import CSV file into SQL Server

All of the answers here work great if your data is "clean" (no data constraint violations, etc.) and you have access to putting the file on the server. Some of the answers provided here stop at the first error (PK violation, data-loss error, etc.) and give you one error at a time if using SSMS's built in Import Task. If you want to gather all errors at once (in case you want to tell the person that gave you the .csv file to clean up their data), I recommend the following as an answer. This answer also gives you complete flexibility as you are "writing" the SQL yourself.

Note: I'm going to assume you are running a Windows OS and have access to Excel and SSMS. If not, I'm sure you can tweak this answer to fit your needs.

  1. Using Excel, open your .csv file. In an empty column you will write a formula that will build individual INSERTstatements like =CONCATENATE("INSERT INTO dbo.MyTable (FirstName, LastName) VALUES ('", A1, "', '", B1,"')", CHAR(10), "GO") where A1 is a cell that has the first name data and A2 has the last name data for example.

    • CHAR(10) adds a newline character to the final result and GO will allow us to run this INSERT and continue to the next even if there are any errors.
  2. Highlight the cell with your =CONCATENATION() formula

  3. Shift + End to highlight the same column in the rest of your rows

  4. In the ribbon > Home > Editing > Fill > Click Down

    • This applies the formula all the way down the sheet so you don't have to copy-paste, drag, etc. down potentially thousands of rows by hand
  5. Ctrl + C to copy the formulated SQL INSERT statements

  6. Paste into SSMS

  7. You will notice Excel, probably unexpectedly, added double quotes around each of your INSERT and GO commands. This is a "feature" (?) of copying multi-line values out of Excel. You can simply find and replace "INSERT and GO" with INSERT and GO respectively to clean that up.

  8. Finally you are ready to run your import process

  9. After the process completes, check the Messages window for any errors. You can select all the content (Ctrl + A) and copy into Excel and use a column filter to remove any successful messages and you are left with any and all the errors.

This process will definitely take longer than other answers here, but if your data is "dirty" and full of SQL violations, you can at least gather all the errors at one time and send them to the person that gave you the data, if that is your scenario.

Cannot bulk load. Operating system error code 5 (Access is denied.)

This is what worked for me:

Log on SSIS with Windows authentication.

1. Open services and find MSSQL NT Service account name and copy it:

enter image description here

2. Open folder from which SQL server should read from. Security - Group or user names tab - Add and paste there copied account:**

enter image description here

  1. You will probably get "Multiple names found error", just select MSSQL user:

enter image description here

Your BULK INSERT query should run fine now. If problem persists try adding SQL Server Agent account to folder permissions in same way. Make sure you restart MSSQL server in services after you are done.

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

The above options works for Google big query file also. I exported a table data to goodle cloud storage and downloaded from there. While loading the same to sql server was facing this issue and could successfully load the file after specifying the row delimiter as

ROWTERMINATOR = '0x0a' 

Pay attention to header record as well and specify

FIRSTROW = 2

My final block for data file export from google bigquery looks like this.

BULK INSERT TABLENAME
        FROM 'C:\ETL\Data\BigQuery\In\FILENAME.csv'
        WITH
        (
         FIRSTROW = 2,
         FIELDTERMINATOR = ',',  --CSV field delimiter
         ROWTERMINATOR = '0x0a',--Files are generated with this row terminator in Google Bigquery
         TABLOCK
        )

Bulk Insert Correctly Quoted CSV File in SQL Server

I had the same problem, however, it worked for me with the following settings:

bulk insert schema.table
from '\\your\data\source.csv'
with (
datafiletype = 'char'
,format = 'CSV'
,firstrow = 2
,fieldterminator = '|'
,rowterminator = '\n'
,tablock
)

My CSV-File looks like this:

"col1"|"col2"
"val1"|"val2"
"val3"|"val4"

My problem was, I had rowterminator set to '0x0a' before, it did not work. Once I changed it to '\n', it started working...

BULK INSERT with identity (auto-increment) column

This is a very old post to answer, but none of the answers given solves the problem without changing the posed conditions, which I can't do.

I solved it by using the OPENROWSET variant of BULK INSERT. This uses the same format file and works in the same way, but it allows the data file be read with a SELECT statement.

Create your table:

CREATE TABLE target_table(
id bigint IDENTITY(1,1),
col1 varchar(256) NULL,
col2 varchar(256) NULL,
col3 varchar(256) NULL)

Open a command window an run:

bcp dbname.dbo.target_table format nul -c -x -f C:\format_file.xml -t; -T

This creates the format file based on how the table looks.

Now edit the format file and remove the entire rows where FIELD ID="1" and COLUMN SOURCE="1", since this does not exist in our data file.
Also adjust terminators as may be needed for your data file:

<?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <RECORD>
  <FIELD ID="2" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="256" COLLATION="Finnish_Swedish_CI_AS"/>
  <FIELD ID="3" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="256" COLLATION="Finnish_Swedish_CI_AS"/>
  <FIELD ID="4" xsi:type="CharTerm" TERMINATOR="\r\n" MAX_LENGTH="256" COLLATION="Finnish_Swedish_CI_AS"/>
 </RECORD>
 <ROW>
  <COLUMN SOURCE="2" NAME="col1" xsi:type="SQLVARYCHAR"/>
  <COLUMN SOURCE="3" NAME="col2" xsi:type="SQLVARYCHAR"/>
  <COLUMN SOURCE="4" NAME="col3" xsi:type="SQLVARYCHAR"/>
 </ROW>
</BCPFORMAT>

Now we can bulk load the data file into our table with a select, thus having full controll over the columns, in this case by not inserting data into the identity column:

INSERT INTO target_table (col1,col2, col3)
SELECT * FROM  openrowset(
bulk 'C:\data_file.txt',
formatfile='C:\format_file.xml') as t;

End of File (EOF) in C

That's a lot of questions.

  1. Why EOF is -1: usually -1 in POSIX system calls is returned on error, so i guess the idea is "EOF is kind of error"

  2. any boolean operation (including !=) returns 1 in case it's TRUE, and 0 in case it's FALSE, so getchar() != EOF is 0 when it's FALSE, meaning getchar() returned EOF.

  3. in order to emulate EOF when reading from stdin press Ctrl+D

null terminating a string

'\0' is the way to go. It's a character, which is what's wanted in a string and has the null value.

When we say null terminated string in C/C++, it really means 'zero terminated string'. The NULL macro isn't intended for use in terminating strings.

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

Sorry to dig up an old question but in case someone stumbles onto this thread and wants a quicker solution.

Bulk inserting a unknown width file with \n row terminators into a temp table that is created outside of the EXEC statement.

DECLARE     @SQL VARCHAR(8000)

IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
    DROP TABLE #BulkInsert
END

CREATE TABLE #BulkInsert
(
    Line    VARCHAR(MAX)
)

SET @SQL = 'BULK INSERT #BulkInser FROM ''##FILEPATH##'' WITH (ROWTERMINATOR = ''\n'')'
EXEC (@SQL)

SELECT * FROM #BulkInsert

Further support that dynamic SQL within an EXEC statement has access to temp tables outside of the EXEC statement. http://sqlfiddle.com/#!3/d41d8/19343

DECLARE     @SQL VARCHAR(8000)

IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
    DROP TABLE #BulkInsert
END

CREATE TABLE #BulkInsert
(
    Line    VARCHAR(MAX)
)
INSERT INTO #BulkInsert
(
    Line
)
SELECT 1
UNION SELECT 2
UNION SELECT 3

SET @SQL = 'SELECT * FROM #BulkInsert'
EXEC (@SQL)

Further support, written for MSSQL2000 http://technet.microsoft.com/en-us/library/aa175921(v=sql.80).aspx

Example at the bottom of the link

DECLARE @cmd VARCHAR(1000), @ExecError INT
CREATE TABLE #ErrFile (ExecError INT)
SET @cmd = 'EXEC GetTableCount ' + 
'''pubs.dbo.authors''' + 
'INSERT #ErrFile VALUES(@@ERROR)'
EXEC(@cmd)
SET @ExecError = (SELECT * FROM #ErrFile)
SELECT @ExecError AS '@@ERROR'

Reading large text files with streams in C#

This should be enough to get you started.

class Program
{        
    static void Main(String[] args)
    {
        const int bufferSize = 1024;

        var sb = new StringBuilder();
        var buffer = new Char[bufferSize];
        var length = 0L;
        var totalRead = 0L;
        var count = bufferSize; 

        using (var sr = new StreamReader(@"C:\Temp\file.txt"))
        {
            length = sr.BaseStream.Length;               
            while (count > 0)
            {                    
                count = sr.Read(buffer, 0, bufferSize);
                sb.Append(buffer, 0, count);
                totalRead += count;
            }                
        }

        Console.ReadKey();
    }
}

SQL Bulk Insert with FIRSTROW parameter skips the following line

You can use the below snippet

BULK INSERT TextData
FROM 'E:\filefromabove.txt'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = '|',  --CSV field delimiter
ROWTERMINATOR = '\n',   --Use to shift the control to next row
ERRORFILE = 'E:\ErrorRows.csv',
TABLOCK
)

How can I change a file's encoding with vim?

Just like your steps, setting fileencoding should work. However, I'd like to add one "set bomb" to help editor consider the file as UTF8.

$ vim file
:set bomb
:set fileencoding=utf-8
:wq

RegEx to parse or validate Base64 data

From the RFC 4648:

Base encoding of data is used in many situations to store or transfer data in environments that, perhaps for legacy reasons, are restricted to US-ASCII data.

So it depends on the purpose of usage of the encoded data if the data should be considered as dangerous.

But if you’re just looking for a regular expression to match Base64 encoded words, you can use the following:

^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.

Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?

This seems to be related to Unable to install Python libraries

See Dominique Barton's answer:

Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.

On Debian-based systems I'd try:

apt-get update && apt-get upgrade python-pip

On Red Hat Linux-based systems:

yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)

On Mac:

sudo easy_install -U pip

You can also try to update openssl separately.

Install a Python package into a different directory using pip?

To add to the already good advice, as I had an issue installing IPython when I didn't have write permissions to /usr/local.

pip uses distutils to do its install and this thread discusses how that can cause a problem as it relies on the sys.prefix setting.

My issue happened when the IPython install tried to write to '/usr/local/share/man/man1' with Permission denied. As the install failed it didn't seem to write the IPython files in the bin directory.

Using "--user" worked and the files were written to ~/.local. Adding ~/.local/bin to the $PATH meant I could use "ipython" from there.

However I'm trying to install this for a number of users and had been given write permission to the /usr/local/lib/python2.7 directory. I created a "bin" directory under there and set directives for distutils:

vim ~/.pydistutils.cfg

[install]
install-data=/usr/local/lib/python2.7
install-scripts=/usr/local/lib/python2.7/bin

then (-I is used to force the install despite previous failures/.local install):

pip install -I ipython

Then I added /usr/local/lib/python2.7/bin to $PATH.

I thought I'd include this in case anyone else has similar issues on a machine they don't have sudo access to.

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

For those using MooTools, here is equivalent code:

            'mousewheel': function(event){
            var height = this.getSize().y;
            height -= 2;    // Not sure why I need this bodge
            if ((this.scrollTop === (this.scrollHeight - height) && event.wheel < 0) || 
                (this.scrollTop === 0 && event.wheel > 0)) {
                event.preventDefault();
            }

Bear in mind that I, like some others, had to tweak a value by a couple of px, that is what the height -= 2 is for.

Basically the main difference is that in MooTools, the delta info comes from event.wheel instead of an extra parameter passed to the event.

Also, I had problems if I bound this code to anything (event.target.scrollHeight for a bound function does not equal this.scrollHeight for a non-bound one)

Hope this helps someone as much as this post helped me ;)

Shorten string without cutting words in JavaScript

Typescript, and with ellipses :)

export const sliceByWord = (phrase: string, length: number, skipEllipses?: boolean): string => {
  if (phrase.length < length) return phrase
  else {
    let trimmed = phrase.slice(0, length)
    trimmed = trimmed.slice(0, Math.min(trimmed.length, trimmed.lastIndexOf(' ')))
    return skipEllipses ? trimmed : trimmed + '…'
  }
}

How to send only one UDP packet with netcat?

If you are using bash, you might as well write

echo -n "hello" >/dev/udp/localhost/8000

and avoid all the idiosyncrasies and incompatibilities of netcat.

This also works sending to other hosts, ex:

echo -n "hello" >/dev/udp/remotehost/8000

These are not "real" devices on the file system, but bash "special" aliases. There is additional information in the Bash Manual.

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

You are mixing code that was compiled with /MD (use DLL version of CRT) with code that was compiled with /MT (use static CRT library). That cannot work, all source code files must be compiled with the same setting. Given that you use libraries that were pre-compiled with /MD, almost always the correct setting, you must compile your own code with this setting as well.

Project + Properties, C/C++, Code Generation, Runtime Library.

Beware that these libraries were probably compiled with an earlier version of the CRT, msvcr100.dll is quite new. Not sure if that will cause trouble, you may have to prevent the linker from generating a manifest. You must also make sure to deploy the DLLs you need to the target machine, including msvcr100.dll

How to remove leading and trailing whitespace in a MySQL field?

Please understand the use case before using this solution:

trim does not work while doing select query

This works

select replace(name , ' ','') from test;

While this doesn't

select trim(name) from test;

Prevent form redirect OR refresh on submit?

If you want to see the default browser errors being displayed, for example, those triggered by HTML attributes (showing up before any client-code JS treatment):

<input name="o" required="required" aria-required="true" type="text">

You should use the submit event instead of the click event. In this case a popup will be automatically displayed requesting "Please fill out this field". Even with preventDefault:

$('form').on('submit', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will show up a "Please fill out this field" pop-up before my_form_treatment

As someone mentioned previously, return false would stop propagation (i.e. if there are more handlers attached to the form submission, they would not be executed), but, in this case, the action triggered by the browser will always execute first. Even with a return false at the end.

So if you want to get rid of these default pop-ups, use the click event on the submit button:

$('form input[type=submit]').on('click', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will NOT show any popups related to HTML attributes

How do I view the SSIS packages in SQL Server Management Studio?

When you start SSMS, it allows you to choose a Server Type and Server Name. In the server type dropdown, choose "Integration Services" and connect to the server.

Then you'll be able to see what packages are in the db.

Difference between View and ViewGroup in Android

  1. A ViewGroup is a special view that can contain other views (called children.) The view group is the base class for layouts and views containers. This class also defines the ViewGroup.LayoutParams class which serves as the base class for layouts parameters.

    View class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.).

  2. Example : ViewGroup (LinearLayout), View (TextView)

Reference

int to unsigned int conversion

This conversion is well defined and will yield the value UINT_MAX - 61. On a platform where unsigned int is a 32-bit type (most common platforms, these days), this is precisely the value that others are reporting. Other values are possible, however.

The actual language in the standard is

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type).

Removing ul indentation with CSS

Remove this from #info:

    margin-left:auto;

Add this for your header:

#info p {
    text-align: center;
}

Do you need the fixed width etc.? I removed the in my opinion not necessary stuff and centered the header with text-align.

Sample
http://jsfiddle.net/Vc8CB/

Should __init__() call the parent class's __init__()?

In Anon's answer:
"If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__ , you must call it yourself, since that will not happen automatically"

It's incredible: he is wording exactly the contrary of the principle of inheritance.


It is not that "something from super's __init__ (...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__ is overriden by the definition of the derived-clas __init__

So then, WHY defining a derived_class' __init__ , since it overrides what is aimed at when someone resorts to inheritance ??

It's because one needs to define something that is NOT done in the base-class' __init__ , and the only possibility to obtain that is to put its execution in a derived-class' __init__ function.
In other words, one needs something in base-class' __init__ in addition to what would be automatically done in the base-classe' __init__ if this latter wasn't overriden.
NOT the contrary.


Then, the problem is that the desired instructions present in the base-class' __init__ are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__ , in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__ . That's exactly what is said in the official doc:

An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments).
http://docs.python.org/tutorial/classes.html#inheritance

That's all the story:

  • when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__ function in the derived class

  • when the aim is to REPLACE the initialization performed by the base-class, __init__ must be defined in the derived-class

  • when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__ must be defined , comprising an explicit call to the base-class __init__


What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.

Changing font size and direction of axes text in ggplot2

Using "fill" attribute helps in cases like this. You can remove the text from axis using element_blank()and show multi color bar chart with a legend. I am plotting a part removal frequency in a repair shop as below

ggplot(data=df_subset,aes(x=Part,y=Removal_Frequency,fill=Part))+geom_bar(stat="identity")+theme(axis.text.x  = element_blank())

I went for this solution in my case as I had many bars in bar chart and I was not able to find a suitable font size which is both readable and also small enough not to overlap each other.

Get week number (in the year) from a date PHP

I have tried to solve this question for years now, I thought I found a shorter solution but had to come back again to the long story. This function gives back the right ISO week notation:

/**
 * calcweek("2018-12-31") => 1901
 * This function calculates the production weeknumber according to the start on 
 * monday and with at least 4 days in the new year. Given that the $date has
 * the following format Y-m-d then the outcome is and integer.
 *
 * @author M.S.B. Bachus
 *
 * @param date-notation PHP "Y-m-d" showing the data as yyyy-mm-dd
 * @return integer
 **/
function calcweek($date) {
  // 1. Convert input to $year, $month, $day
  $dateset      = strtotime($date);
  $year         = date("Y", $dateset);
  $month        = date("m", $dateset);
  $day          = date("d", $dateset);

  $referenceday = getdate(mktime(0,0,0, $month, $day, $year));
  $jan1day      = getdate(mktime(0,0,0,1,1,$referenceday[year]));

  // 2. check if $year is a  leapyear
  if ( ($year%4==0 && $year%100!=0) || $year%400==0) {
    $leapyear = true;
  } else {
    $leapyear = false;
  }

  // 3. check if $year-1 is a  leapyear
  if ( (($year-1)%4==0 && ($year-1)%100!=0) || ($year-1)%400==0 ) {
    $leapyearprev = true;
  } else {
    $leapyearprev = false;
  }

  // 4. find the dayofyearnumber for y m d
  $mnth = array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);
  $dayofyearnumber = $day + $mnth[$month-1];
  if ( $leapyear && $month > 2 ) { $dayofyearnumber++; }

  // 5. find the jan1weekday for y (monday=1, sunday=7)
  $yy = ($year-1)%100;
  $c  = ($year-1) - $yy;
  $g  = $yy + intval($yy/4);
  $jan1weekday = 1+((((intval($c/100)%4)*5)+$g)%7);

  // 6. find the weekday for y m d
  $h = $dayofyearnumber + ($jan1weekday-1);
  $weekday = 1+(($h-1)%7);

  // 7. find if y m d falls in yearnumber y-1, weeknumber 52 or 53
  $foundweeknum = false;
  if ( $dayofyearnumber <= (8-$jan1weekday) && $jan1weekday > 4 ) {
    $yearnumber = $year - 1;
    if ( $jan1weekday = 5 || ( $jan1weekday = 6 && $leapyearprev )) {
      $weeknumber = 53;
    } else {
      $weeknumber = 52;
    }
    $foundweeknum = true;
  } else {
    $yearnumber = $year;
  }

  // 8. find if y m d falls in yearnumber y+1, weeknumber 1
  if ( $yearnumber == $year && !$foundweeknum) {
    if ( $leapyear ) {
      $i = 366;
    } else {
      $i = 365;
    }
    if ( ($i - $dayofyearnumber) < (4 - $weekday) ) {
      $yearnumber = $year + 1;
      $weeknumber = 1;
      $foundweeknum = true;
    }
  }

  // 9. find if y m d falls in yearnumber y, weeknumber 1 through 53
  if ( $yearnumber == $year && !$foundweeknum ) {
    $j = $dayofyearnumber + (7 - $weekday) + ($jan1weekday - 1);
    $weeknumber = intval( $j/7 );
    if ( $jan1weekday > 4 ) { $weeknumber--; }
  }

  // 10. output iso week number (YYWW)
  return ($yearnumber-2000)*100+$weeknumber;
}

I found out that my short solution missed the 2018-12-31 as it gave back 1801 instead of 1901. So I had to put in this long version which is correct.

How to select data where a field has a min value in MySQL?

This also works:

SELECT
  pieces.*
FROM
  pieces inner join (select min(price) as minprice from pieces) mn
  on pieces.price = mn.minprice

(since this version doesn't have a where condition with a subquery, it could be used if you need to UPDATE the table, but if you just need to SELECT i would reccommend to use John Woo solution)

A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

https://pypi.python.org/pypi/oct2py

It requires GNU Octave, which is highly compatible with MATLAB.

https://www.gnu.org/software/octave/

Creating new database from a backup of another Database on the same server?

It's even possible to restore without creating a blank database at all.

In Sql Server Management Studio, right click on Databases and select Restore Database... enter image description here

In the Restore Database dialog, select the Source Database or Device as normal. Once the source database is selected, SSMS will populate the destination database name based on the original name of the database.

It's then possible to change the name of the database and enter a new destination database name.

enter image description here

With this approach, you don't even need to go to the Options tab and click the "Overwrite the existing database" option.

Also, the database files will be named consistently with your new database name and you still have the option to change file names if you want.

Add days Oracle SQL

You can use the plus operator to add days to a date.

order_date + 20

Create PostgreSQL ROLE (user) if it doesn't exist

Here is a generic solution using plpgsql:

CREATE OR REPLACE FUNCTION create_role_if_not_exists(rolename NAME) RETURNS TEXT AS
$$
BEGIN
    IF NOT EXISTS (SELECT * FROM pg_roles WHERE rolname = rolename) THEN
        EXECUTE format('CREATE ROLE %I', rolename);
        RETURN 'CREATE ROLE';
    ELSE
        RETURN format('ROLE ''%I'' ALREADY EXISTS', rolename);
    END IF;
END;
$$
LANGUAGE plpgsql;

Usage:

posgres=# SELECT create_role_if_not_exists('ri');
 create_role_if_not_exists 
---------------------------
 CREATE ROLE
(1 row)
posgres=# SELECT create_role_if_not_exists('ri');
 create_role_if_not_exists 
---------------------------
 ROLE 'ri' ALREADY EXISTS
(1 row)

http://localhost/phpMyAdmin/ unable to connect

You dont start phpmyadmin from your webbrowser. When you want to start PHPMyAdmin you have to do so from the XAMPP control-panel. When you've started phpmyadmin from your control-panel you can access it from the web-browser.

Setting default permissions for newly created files and sub-directories under a directory in Linux?

It's ugly, but you can use the setfacl command to achieve exactly what you want.

On a Solaris machine, I have a file that contains the acls for users and groups. Unfortunately, you have to list all of the users (at least I couldn't find a way to make this work otherwise):

user::rwx
user:user_a:rwx
user:user_b:rwx
...
group::rwx
mask:rwx
other:r-x
default:user:user_a:rwx
default:user:user_b:rwx
....
default:group::rwx
default:user::rwx
default:mask:rwx
default:other:r-x

Name the file acl.lst and fill in your real user names instead of user_X.

You can now set those acls on your directory by issuing the following command:

setfacl -f acl.lst /your/dir/here

How do I get into a Docker container's shell?

Another option is to use nsenter.

PID=$(docker inspect --format {{.State.Pid}} <container_name_or_ID>)
nsenter --target $PID --mount --uts --ipc --net --pid

getFilesDir() vs Environment.getDataDirectory()

From the HERE and HERE

public File getFilesDir ()

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

public static File getExternalStorageDirectory ()

Return the primary external storage directory. This directory may not currently be accessible if it has been mounted by the user on their computer, has been removed from the device, or some other problem has happened. You can determine its current state with getExternalStorageState().

Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.

On devices with multiple users (as described by UserManager), each user has their own isolated external storage. Applications only have access to the external storage for the user they're running as.

If you want to get your application path use getFilesDir() which will give you path /data/data/your package/files

You can get the path using the Environment var of your data/package using the

getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath(); which will return the path from the root directory of your external storage as /storage/sdcard/Android/data/your pacakge/files/data

To access the external resources you have to provide the permission of WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE in your manifest.

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

Check out the Best Documentation to get the paths of direcorty

Is there a CSS selector for elements containing certain text?

If I read the specification correctly, no.

You can match on an element, the name of an attribute in the element, and the value of a named attribute in an element. I don't see anything for matching content within an element, though.

How can I create a Java method that accepts a variable number of arguments?

You could write a convenience method:

public PrintStream print(String format, Object... arguments) {
    return System.out.format(format, arguments);
}

But as you can see, you've simply just renamed format (or printf).

Here's how you could use it:

private void printScores(Player... players) {
    for (int i = 0; i < players.length; ++i) {
        Player player = players[i];
        String name   = player.getName();
        int    score  = player.getScore();
        // Print name and score followed by a newline
        System.out.format("%s: %d%n", name, score);
    }
}

// Print a single player, 3 players, and all players
printScores(player1);
System.out.println();
printScores(player2, player3, player4);
System.out.println();
printScores(playersArray);

// Output
Abe: 11

Bob: 22
Cal: 33
Dan: 44

Abe: 11
Bob: 22
Cal: 33
Dan: 44

Note there's also the similar System.out.printf method that behaves the same way, but if you peek at the implementation, printf just calls format, so you might as well use format directly.

Access Control Request Headers, is added to header in AJAX request with jQuery

What you saw in Firefox was not the actual request; note that the HTTP method is OPTIONS, not POST. It was actually the 'pre-flight' request that the browser makes to determine whether a cross-domain AJAX request should be allowed:

http://www.w3.org/TR/cors/

The Access-Control-Request-Headers header in the pre-flight request includes the list of headers in the actual request. The server is then expected to report back whether these headers are supported in this context or not, before the browser submits the actual request.

Making a flex item float right

You don't need floats. In fact, they're useless because floats are ignored in flexbox.

You also don't need CSS positioning.

There are several flex methods available. auto margins have been mentioned in another answer.

Here are two other options:

  • Use justify-content: space-between and the order property.
  • Use justify-content: space-between and reverse the order of the divs.

_x000D_
_x000D_
.parent {_x000D_
    display: flex;_x000D_
    justify-content: space-between;_x000D_
}_x000D_
_x000D_
.parent:first-of-type > div:last-child { order: -1; }_x000D_
_x000D_
p { background-color: #ddd;}
_x000D_
<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>_x000D_
_x000D_
<div class="parent">_x000D_
    <div class="child" style="float:right"> Ignore parent? </div>_x000D_
    <div>another child </div>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of _x000D_
             divs in the mark-up</p>_x000D_
_x000D_
<div class="parent">_x000D_
    <div>another child </div>_x000D_
    <div class="child" style="float:right"> Ignore parent? </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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

I get this same error on my Windows 7 machine when the permissions on my cacerts file in my C:\Program Files\Java\jdk1.7.0_51\jre\lib\security folder are not set correctly.

To resolve the issue, I allow the SERVICE and INTERACTIVE users to have all modify permissions on cacerts except "change permissions" and "take ownership" (from Advanced Settings, in the Security properties). I assume that allowing these services to both read and write extended attributes may have something to do with the error going away.

How to name and retrieve a stash by name in git?

use git stash push -m aNameForYourStash to save it. Then use git stash list to learn the index of the stash that you want to apply. Then use git stash pop --index 0 to pop the stash and apply it.

note: I'm using git version 2.21.0.windows.1

Calculate business days

A function to add or subtract business days from a given date, this doesn't account for holidays.

function dateFromBusinessDays($days, $dateTime=null) {
  $dateTime = is_null($dateTime) ? time() : $dateTime;
  $_day = 0;
  $_direction = $days == 0 ? 0 : intval($days/abs($days));
  $_day_value = (60 * 60 * 24);

  while($_day !== $days) {
    $dateTime += $_direction * $_day_value;

    $_day_w = date("w", $dateTime);
    if ($_day_w > 0 && $_day_w < 6) {
      $_day += $_direction * 1; 
    }
  }

  return $dateTime;
}

use like so...

echo date("m/d/Y", dateFromBusinessDays(-7));
echo date("m/d/Y", dateFromBusinessDays(3, time() + 3*60*60*24));

How to add jQuery code into HTML Page

Before the closing body tag add this (reference to jQuery library). Other hosted libraries can be found here

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

And this

<script>
  //paste your code here
</script>

It should look something like this

<body>
 ........
 ........
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script> Your code </script>
</body>

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

Generally, bash works better than python only in those environments where python is not available. :)

Seriously, I have to deal with both languages daily, and will take python instantly over bash if given the choice. Alas, I am forced to use bash on certain "small" platforms because someone has (mistakenly, IMHO) decided that python is "too large" to fit.

While it is true that bash might be faster than python for some select tasks, it can never be as quick to develop with, or as easy to maintain (at least after you get past 10 lines of code or so). Bash's sole strong point wrt python or ruby or lua, etc., is its ubiquity.

Git Pull vs Git Rebase

git-pull - Fetch from and integrate with another repository or a local branch GIT PULL

Basically you are pulling remote branch to your local, example:

git pull origin master

Will pull master branch into your local repository

git-rebase - Forward-port local commits to the updated upstream head GIT REBASE

This one is putting your local changes on top of changes done remotely by other users. For example:

  • You have committed some changes on your local branch for example called SOME-FEATURE
  • Your friend in the meantime was working on other features and he merged his branch into master

Now you want to see his and your changes on your local branch. So then you checkout master branch:

git checkout master

then you can pull:

git pull origin master

and then you go to your branch:

git checkout SOME-FEATURE

and you can do rebase master to get lastest changes from it and put your branch commits on top:

git rebase master

I hope now it's a bit more clear for you.

How to make matrices in Python?

I got a simple fix to this by casting the lists into strings and performing string operations to get the proper print out of the matrix.

Creating the function

By creating a function, it saves you the trouble of writing the for loop every time you want to print out a matrix.

def print_matrix(matrix):
    for row in matrix:
        new_row = str(row)
        new_row = new_row.replace(',','')
        new_row = new_row.replace('[','')
        new_row = new_row.replace(']','')
        print(new_row)

Examples

Example of a 5x5 matrix with 0 as every entry:

>>> test_matrix = [[0] * 5 for i in range(5)]
>>> print_matrix(test_matrix)
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0 

Example of a 2x3 matrix with 0 as every entry:

>>> test_matrix = [[0] * 3 for i in range(2)]
>>> print_matrix(test_matrix)
0 0 0
0 0 0

EDIT

If you want to make it print:

A A A A A
B B B B B
C C C C C
D D D D D 
E E E E E

I suggest you just change the way you enter your data into your lists within lists. In my method, each list within the larger list represents a line in the matrix, not columns.

Simple prime number generator in Python

To my opinion it is always best to take the functional approach,

So I create a function first to find out if the number is prime or not then use it in loop or other place as necessary.

def isprime(n):
      for x in range(2,n):
        if n%x == 0:
            return False
    return True

Then run a simple list comprehension or generator expression to get your list of prime,

[x for x in range(1,100) if isprime(x)]

How do I use setsockopt(SO_REUSEADDR)?

Depending on the libc release it could be needed to set both SO_REUSEADDR and SO_REUSEPORT socket options as explained in socket(7) documentation :

   SO_REUSEPORT (since Linux 3.9)
          Permits multiple AF_INET or AF_INET6 sockets to be bound to an
          identical socket address.  This option must be set on each
          socket (including the first socket) prior to calling bind(2)
          on the socket.  To prevent port hijacking, all of the
          processes binding to the same address must have the same
          effective UID.  This option can be employed with both TCP and
          UDP sockets.

As this socket option appears with kernel 3.9 and raspberry use 3.12.x, it will be needed to set SO_REUSEPORT.

You can set theses two options before calling bind like this :

    int reuse = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
        perror("setsockopt(SO_REUSEADDR) failed");

#ifdef SO_REUSEPORT
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0) 
        perror("setsockopt(SO_REUSEPORT) failed");
#endif

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

I catched the same error message today. The solution was to change the document from UTF-8 with BOM to UTF-8 without BOM

How to change JAVA.HOME for Eclipse/ANT

Also be sure to set your JAVA_HOME environment variable. In fact, I usually set the JAVA_HOME, then prepend the string "%JAVA_HOME%\bin" to the system's PATH environment variable so that if Java ever gets upgraded or changed, only the JAVA_HOME variable will need to be changed.

And make sure that you close any command prompt windows or open applications that may read your environment variables, as changes to environment variables are normally not noticed until an application is re-launched.

What’s the best RESTful method to return total number of items in an object?

As of "X-"-Prefix was deprecated. (see: https://tools.ietf.org/html/rfc6648)

We found the "Accept-Ranges" as being the best bet to map the pagination ranging: https://tools.ietf.org/html/rfc7233#section-2.3 As the "Range Units" may either be "bytes" or "token". Both do not represent a custom data type. (see: https://tools.ietf.org/html/rfc7233#section-4.2) Still, it is stated that

HTTP/1.1 implementations MAY ignore ranges specified using other units.

Which indicates: using custom Range Units is not against the protocol, but it MAY be ignored.

This way, we would have to set the Accept-Ranges to "members" or whatever ranged unit type, we'd expect. And in addition, also set the Content-Range to the current range. (see: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.12)

Either way, I would stick to the recommendation of RFC7233 (https://tools.ietf.org/html/rfc7233#page-8) to send a 206 instead of 200:

If all of the preconditions are true, the server supports the Range
header field for the target resource, and the specified range(s) are
valid and satisfiable (as defined in Section 2.1), the server SHOULD
send a 206 (Partial Content) response with a payload containing one
or more partial representations that correspond to the satisfiable
ranges requested, as defined in Section 4.

So, as a result, we would have the following HTTP header fields:

For Partial Content:

206 Partial Content
Accept-Ranges: members
Content-Range: members 0-20/100

For full Content:

200 OK
Accept-Ranges: members
Content-Range: members 0-20/20

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

How do I add a custom script to my package.json file that runs a javascript file?

Lets say in scripts you want to run 2 commands with a single command:

"scripts":{
  "start":"any command",
  "singleCommandToRunTwoCommand":"some command here && npm start"
}

Now go to your terminal and run there npm run singleCommandToRunTwoCommand.

Eloquent: find() and where() usage laravel

Your code looks fine, but there are a couple of things to be aware of:

Post::find($id); acts upon the primary key, if you have set your primary key in your model to something other than id by doing:

protected  $primaryKey = 'slug';

then find will search by that key instead.

Laravel also expects the id to be an integer, if you are using something other than an integer (such as a string) you need to set the incrementing property on your model to false:

public $incrementing = false;

Jquery button click() function is not working

After making the id unique across the document ,You have to use event delegation

$("#container").on("click", "buttonid", function () {
  alert("Hi");
});

MySQL 'create schema' and 'create database' - Is there any difference

Mysql documentation says : CREATE SCHEMA is a synonym for CREATE DATABASE as of MySQL 5.0.2.


this all goes back to an ANSI standard for SQL in the mid-80s.

That standard had a "CREATE SCHEMA" command, and it served to introduce multiple name spaces for table and view names. All tables and views were created within a "schema". I do not know whether that version defined some cross-schema access to tables and views, but I assume it did. AFAIR, no product (at least back then) really implemented it, that whole concept was more theory than practice.

OTOH, ISTR this version of the standard did not have the concept of a "user" or a "CREATE USER" command, so there were products that used the concept of a "user" (who then had his own name space for tables and views) to implement their equivalent of "schema".

This is an area where systems differ.

As far as administration is concerned, this should not matter too much, because here you have differences anyway.

As far as you look at application code, you "only" have to care about cases where one application accesses tables from multiple name spaces. AFAIK, all systems support a syntax ".", and for this it should not matter whether the name space is that of a user, a "schema", or a "database".

How to use bluetooth to connect two iPhone?

Check out the BeamIt open source project. It will connect via bluetooth and WIFI (although it claims it does not do WIFI) and I have verified that it works well in my projects. It will allow peer to peer contact easily.

As for multiple connections, it is possible, but you will have to edit the BeamIt source code to make it possible. I suggest reading the GameKit programming guide

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

This issue occurred when I switched to Android Studio 3.4 with Android Gradle plugin 3.4.0. which works with the R8 compiler.

The Android Gradle plugin includes additional predefined ProGuard rules files, but it is recommended that you use proguard-android-optimize.txt. More info here.

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile(
          'proguard-android-optimize.txt'),
          // List additional ProGuard rules for the given build type here. By default,
          // Android Studio creates and includes an empty rules file for you (located
          // at the root directory of each module).
          'proguard-rules.pro'
    }
}

Can I replace groups in Java regex?

Sorry to beat a dead horse, but it is kind-of weird that no-one pointed this out - "Yes you can, but this is the opposite of how you use capturing groups in real life".

If you use Regex the way it is meant to be used, the solution is as simple as this:

"6 example input 4".replaceAll("(?:\\d)(.*)(?:\\d)", "number$11");

Or as rightfully pointed out by shmosel below,

"6 example input 4".replaceAll("\d(.*)\d", "number$11");

...since in your regex there is no good reason to group the decimals at all.

You don't usually use capturing groups on the parts of the string you want to discard, you use them on the part of the string you want to keep.

If you really want groups that you want to replace, what you probably want instead is a templating engine (e.g. moustache, ejs, StringTemplate, ...).


As an aside for the curious, even non-capturing groups in regexes are just there for the case that the regex engine needs them to recognize and skip variable text. For example, in

(?:abc)*(capture me)(?:bcd)*

you need them if your input can look either like "abcabccapture mebcdbcd" or "abccapture mebcd" or even just "capture me".

Or to put it the other way around: if the text is always the same, and you don't capture it, there is no reason to use groups at all.

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

Try this:

PM> Enable-migrations -force
PM> Add-migration MigrationName
PM> Update-database -force

How can I create a simple index.html file which lists all files/directories?

There's a free php script made by Celeron Dude that can do this called Celeron Dude Indexer 2. It doesn't require .htaccess The source code is easy to understand and provides a good starting point.

Here's a download link: https://gitlab.com/desbest/celeron-dude-indexer/

celeron dude indexer

CREATE TABLE LIKE A1 as A2

CREATE TABLE new_table LIKE old_table;

or u can use this

CREATE TABLE new_table as SELECT * FROM old_table WHERE 1 GROUP BY [column to remove duplicates by];

Search for string within text column in MySQL

Why not use LIKE?

SELECT * FROM items WHERE items.xml LIKE '%123456%'

SQL: set existing column as Primary Key in MySQL

If you want to do it with phpmyadmin interface:

Select the table -> Go to structure tab -> On the row corresponding to the column you want, click on the icon with a key

How to check cordova android version of a cordova/phonegap project?

Run

cordova -v 

to see the currently running version. Run the npm info command

npm info cordova

for a longer listing that includes the current version along with other available version numbers

How do you get a directory listing in C?

The strict answer is "you can't", as the very concept of a folder is not truly cross-platform.

On MS platforms you can use _findfirst, _findnext and _findclose for a 'c' sort of feel, and FindFirstFile and FindNextFile for the underlying Win32 calls.

Here's the C-FAQ answer:

http://c-faq.com/osdep/readdir.html

Android studio - Failed to find target android-18

What worked for me in Android Studio (0.8.1):

  1. Right click on project name and open Module Settings
  2. Verify SDK Locations SDK
  3. Verify Gradle and Plugin Versions (Review the error message hints for the proper version to use) Gradke
  4. On the app Module set the Compile SDK Version to android-L (latest)
  5. Set the Build Tools version to largest available value (in my case 20.0.0) Build

These changes via the UI make the equivalent changes represented in other answers but is a better way to proceed because on close, all appropriate files (current and future) will be updated automatically (which is helpful when confronted by the many places where issues can occur).

NB: It is very important to review the Event Log and note that Android Studio provides helpful messages on alternative ways to resolve such issues.

How to install Ruby 2.1.4 on Ubuntu 14.04

Best is to install it using rvm(ruby version manager).
Run following commands in a terminal:

sudo apt-get update
sudo apt-get install build-essential make curl
\curl -L https://get.rvm.io | bash -s stable
source ~/.bash_profile
rvm install ruby-2.1.4

Then check ruby versions installed and in use:

rvm list
rvm use --default ruby-2.1.4

Also you can directly add ruby bin path to PATH variable. Ruby is installed in

$HOME/.rvm/rubies export PATH=$PATH:$HOME/.rvm/rubies/ruby-2.1.4/bin

Is the LIKE operator case-sensitive with MSSQL Server?

Try running,

SELECT SERVERPROPERTY('COLLATION')

Then find out if your collation is case sensitive or not.

Verify object attribute value with mockito

New feature added to Mockito makes this even easier,

ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());

Take a look at Mockito documentation


In case when there are more than one parameters, and capturing of only single param is desired, use other ArgumentMatchers to wrap the rest of the arguments:

verify(mock).doSomething(eq(someValue), eq(someOtherValue), argument.capture());
assertEquals("John", argument.getValue().getName());

Select Multiple Fields from List in Linq

This is task for which anonymous types are very well suited. You can return objects of a type that is created automatically by the compiler, inferred from usage.

The syntax is of this form:

new { Property1 = value1, Property2 = value2, ... }

For your case, try something like the following:

var listObject = getData();
var catNames = listObject.Select(i =>
    new { CatName = i.category_name, Item1 = i.item1, Item2 = i.item2 })
    .Distinct().OrderByDescending(s => s).ToArray();

What is a JavaBean exactly?

In practice, Beans are just objects which are handy to use. Serializing them means to be able easily to persist them (store in a form that is easily recovered).

Typical uses of Beans in real world:

  • simple reusable objects POJO (Plain Old Java Objects)
  • visual objects
  • Spring uses Beans for objects to handle (for instance, User object that needs to be serialized in session)
  • EJB (Enterprise Java Beans), more complex objects, like JSF Beans (JSF is old quite outdated technology) or JSP Beans

So in fact, Beans are just a convention / standard to expect something from a Java object that it would behave (serialization) and give some ways to change it (setters for properties) in a certain way.

How to use them, is just your invention, but most common cases I enlisted above.

DataGridView changing cell background color

protected void grdDataListeDetay_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[3].Text != "0")
        {
            for (int i = 0; i <= e.Row.Cells.Count - 1; i++)
            {
                e.Row.Cells[i].BackColor = System.Drawing.Color.Beige;
            }
        }
    }
}

jquery: get elements by class name and add css to each of them

You can try this

 $('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});

The $('div.easy_editor') refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.

Where does Console.WriteLine go in ASP.NET?

This is confusing for everyone when it comes IISExpress. There is nothing to read console messages. So for example, in the ASPCORE MVC apps it configures using appsettings.json which does nothing if you are using IISExpress.

For right now you can just add loggerFactory.AddDebug(LogLevel.Debug); in your Configure section and it will at least show you your logs in the Debug Output window.

Good news CORE 2.0 this will all be changing: https://github.com/aspnet/Announcements/issues/255

Create a tar.xz in one command

Try this: tar -cf file.tar file-to-compress ; xz -z file.tar

Note:

  1. tar.gz and tar.xz are not the same; xz provides better compression.
  2. Don't use pipe | because this runs commands simultaneously. Using ; or & executes commands one after another.

When should we use intern method of String on String literals

you should make out two period time which are compile time and runtime time.for example:

//example 1 
"test" == "test" // --> true 
"test" == "te" + "st" // --> true

//example 2 
"test" == "!test".substring(1) // --> false
"test" == "!test".substring(1).intern() // --> true

in the one hand,in the example 1,we find the results are all return true,because in the compile time,the jvm will put the "test" to the pool of literal strings,if the jvm find "test" exists,then it will use the exists one,in example 1,the "test" strings are all point to the same memory address,so the example 1 will return true. in the other hand,in the example 2,the method of substring() execute in the runtime time, in the case of "test" == "!test".substring(1),the pool will create two string object,"test" and "!test",so they are different reference objects,so this case will return false,in the case of "test" == "!test".substring(1).intern(),the method of intern() will put the ""!test".substring(1)" to the pool of literal strings,so in this case,they are same reference objects,so will return true.

jQuery to retrieve and set selected option value of html select element

When setting with JQM, don't forget to update the UI:

$('#selectId').val('newValue').selectmenu('refresh', true);

How can I bind to the change event of a textarea in jQuery?

Try to do it with focusout

$("textarea").focusout(function() {
   alert('textarea focusout');
});

How to check whether an object has certain method/property?

To avoid AmbiguousMatchException, I would rather say

objectToCheck.GetType().GetMethods().Count(m => m.Name == method) > 0

Rotating a view in Android

Rotating view with rotate() will not affect your view's measured size. As result, rotated view be clipped or not fit into the parent layout. This library fixes it though:

https://github.com/rongi/rotate-layout

enter image description here

Turn on torch/flash on iPhone

Swift 2.0 version:

func setTorchLevel(torchLevel: Float)
{
    self.captureSession?.beginConfiguration()
    defer {
        self.captureSession?.commitConfiguration()
    }

    if let device = backCamera?.device where device.hasTorch && device.torchAvailable {
        do {
            try device.lockForConfiguration()
            defer {
                device.unlockForConfiguration()
            }

            if torchLevel <= 0.0 {
                device.torchMode = .Off
            }
            else if torchLevel >= 1.0 {
                try device.setTorchModeOnWithLevel(min(torchLevel, AVCaptureMaxAvailableTorchLevel))
            }
        }
        catch let error {
            print("Failed to set up torch level with error \(error)")
            return
        }
    }
}

iText - add content to existing PDF file

Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, 
        new FileOutputStream("E:/TextFieldForm.pdf"));
    document.open();

    PdfPTable table = new PdfPTable(2);
    table.getDefaultCell().setPadding(5f); // Code 1
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    PdfPCell cell;      

    // Code 2, add name TextField       
    table.addCell("Name"); 
    TextField nameField = new TextField(writer, 
        new Rectangle(0,0,200,10), "nameField");
    nameField.setBackgroundColor(Color.WHITE);
    nameField.setBorderColor(Color.BLACK);
    nameField.setBorderWidth(1);
    nameField.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    nameField.setText("");
    nameField.setAlignment(Element.ALIGN_LEFT);
    nameField.setOptions(TextField.REQUIRED);               
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(nameField.getTextField(), 
        200, writer));
    table.addCell(cell);

    // force upper case javascript
    writer.addJavaScript(
        "var nameField = this.getField('nameField');" +
        "nameField.setAction('Keystroke'," +
        "'forceUpperCase()');" +
        "" +
        "function forceUpperCase(){" +
        "if(!event.willCommit)event.change = " +
        "event.change.toUpperCase();" +
        "}");


    // Code 3, add empty row
    table.addCell("");
    table.addCell("");


    // Code 4, add age TextField
    table.addCell("Age");
    TextField ageComb = new TextField(writer, new Rectangle(0,
         0, 30, 10), "ageField");
    ageComb.setBorderColor(Color.BLACK);
    ageComb.setBorderWidth(1);
    ageComb.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    ageComb.setText("12");
    ageComb.setAlignment(Element.ALIGN_RIGHT);
    ageComb.setMaxCharacterLength(2);
    ageComb.setOptions(TextField.COMB | 
        TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(ageComb.getTextField(), 
        30, writer));
    table.addCell(cell);

    // validate age javascript
    writer.addJavaScript(
        "var ageField = this.getField('ageField');" +
        "ageField.setAction('Validate','checkAge()');" +
        "function checkAge(){" +
        "if(event.value < 12){" +
        "app.alert('Warning! Applicant\\'s age can not" +
        " be younger than 12.');" +
        "event.value = 12;" +
        "}}");      



    // add empty row
    table.addCell("");
    table.addCell("");


    // Code 5, add age TextField
    table.addCell("Comment");
    TextField comment = new TextField(writer, 
        new Rectangle(0, 0,200, 100), "commentField");
    comment.setBorderColor(Color.BLACK);
    comment.setBorderWidth(1);
    comment.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    comment.setText("");
    comment.setOptions(TextField.MULTILINE | 
        TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(100);
    cell.setCellEvent(new FieldCell(comment.getTextField(), 
        200, writer));
    table.addCell(cell);


    // check comment characters length javascript
    writer.addJavaScript(
        "var commentField = " +
        "this.getField('commentField');" +
        "commentField" +
        ".setAction('Keystroke','checkLength()');" +
        "function checkLength(){" +
        "if(!event.willCommit && " +
        "event.value.length > 100){" +
        "app.alert('Warning! Comment can not " +
        "be more than 100 characters.');" +
        "event.change = '';" +
        "}}");          

    // add empty row
    table.addCell("");
    table.addCell("");


    // Code 6, add submit button    
    PushbuttonField submitBtn = new PushbuttonField(writer,
            new Rectangle(0, 0, 35, 15),"submitPOST");
    submitBtn.setBackgroundColor(Color.GRAY);
    submitBtn.
        setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
    submitBtn.setText("POST");
    submitBtn.setOptions(PushbuttonField.
        VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField submitField = submitBtn.getField();
    submitField.setAction(PdfAction
    .createSubmitForm("",null, PdfAction.SUBMIT_HTML_FORMAT));

    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(submitField, 35, writer));
    table.addCell(cell);



    // Code 7, add reset button
    PushbuttonField resetBtn = new PushbuttonField(writer,
            new Rectangle(0, 0, 35, 15), "reset");
    resetBtn.setBackgroundColor(Color.GRAY);
    resetBtn.setBorderStyle(
        PdfBorderDictionary.STYLE_BEVELED);
    resetBtn.setText("RESET");
    resetBtn
    .setOptions(
        PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField resetField = resetBtn.getField();
    resetField.setAction(PdfAction.createResetForm(null, 0));
    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(resetField, 35, writer));
    table.addCell(cell);        

    document.add(table);
    document.close();
}


class FieldCell implements PdfPCellEvent{

    PdfFormField formField;
    PdfWriter writer;
    int width;

    public FieldCell(PdfFormField formField, int width, 
        PdfWriter writer){
        this.formField = formField;
        this.width = width;
        this.writer = writer;
    }

    public void cellLayout(PdfPCell cell, Rectangle rect, 
        PdfContentByte[] canvas){
        try{
            // delete cell border
            PdfContentByte cb = canvas[PdfPTable
                .LINECANVAS];
            cb.reset();

            formField.setWidget(
                new Rectangle(rect.left(), 
                    rect.bottom(), 
                    rect.left()+width, 
                    rect.top()), 
                    PdfAnnotation
                    .HIGHLIGHT_NONE);

            writer.addAnnotation(formField);
        }catch(Exception e){
            System.out.println(e);
        }
    }
}

Python os.path.join() on a list

Assuming join wasn't designed that way (which it is, as ATOzTOA pointed out), and it only took two parameters, you could still use the built-in reduce:

>>> reduce(os.path.join,["c:/","home","foo","bar","some.txt"])
'c:/home\\foo\\bar\\some.txt'

Same output like:

>>> os.path.join(*["c:/","home","foo","bar","some.txt"])
'c:/home\\foo\\bar\\some.txt' 

Just for completeness and educational reasons (and for other situations where * doesn't work).

Hint for Python 3

reduce was moved to the functools module.

Underscore prefix for property and method names in JavaScript

Welcome to 2019!

It appears a proposal to extend class syntax to allow for # prefixed variable to be private was accepted. Chrome 74 ships with this support.

_ prefixed variable names are considered private by convention but are still public.

This syntax tries to be both terse and intuitive, although it's rather different from other programming languages.

Why was the sigil # chosen, among all the Unicode code points?

  • @ was the initial favorite, but it was taken by decorators. TC39 considered swapping decorators and private state sigils, but the committee decided to defer to the existing usage of transpiler users.
  • _ would cause compatibility issues with existing JavaScript code, which has allowed _ at the start of an identifier or (public) property name for a long time.

This proposal reached Stage 3 in July 2017. Since that time, there has been extensive thought and lengthy discussion about various alternatives. In the end, this thought process and continued community engagement led to renewed consensus on the proposal in this repository. Based on that consensus, implementations are moving forward on this proposal.

See https://caniuse.com/#feat=mdn-javascript_classes_private_class_fields

How does cellForRowAtIndexPath work?

Basically it's designing your cell, The cellforrowatindexpath is called for each cell and the cell number is found by indexpath.row and section number by indexpath.section . Here you can use a label, button or textfied image anything that you want which are updated for all rows in the table. Answer for second question In cell for row at index path use an if statement

In Objective C

-(UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

 NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  if(tableView == firstTableView)
  {
      //code for first table view 
      [cell.contentView addSubview: someView];
  }

  if(tableview == secondTableView)
  {
      //code for secondTableView 
      [cell.contentView addSubview: someView];
  }
  return cell;
}

In Swift 3.0

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
  let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!

  if(tableView == firstTableView)   {
     //code for first table view 
  }

  if(tableview == secondTableView)      {
     //code for secondTableView 
  }

  return cell
}

Launching a website via windows commandline

To open a URL with the default browser, you can execute:

rundll32 url.dll,FileProtocolHandler https://www.google.com

I had issues with URL parameters with the other solutions. However, this one seemed to work correctly.

How to connect to LocalDB in Visual Studio Server Explorer?

With SQL Server 2017 and Visual Studio 2015, I used localhost\SQLEXPRESS

enter image description here

How to prevent vim from creating (and leaving) temporary files?

I'd strongly recommend to keep working with swap files (in case Vim crashes).

You can set the directory where the swap files are stored, so they don't clutter your normal directories:

set swapfile
set dir=~/tmp

See also

:help swap-file

dispatch_after - GCD in Swift?

In Swift 4

Use this snippet:

    let delayInSec = 1.0
    DispatchQueue.main.asyncAfter(deadline: .now() + delayInSec) {
       // code here
       print("It works")
    }

MySQL Trigger after update only if row has changed

I cant comment, so just beware, that if your column supports NULL values, OLD.x<>NEW.x isnt enough, because

SELECT IF(1<>NULL,1,0)

returns 0 as same as

NULL<>NULL 1<>NULL 0<>NULL 'AAA'<>NULL

So it will not track changes FROM and TO NULL

The correct way in this scenario is

((OLD.x IS NULL AND NEW.x IS NOT NULL) OR (OLD.x IS NOT NULL AND NEW.x IS NULL) OR (OLD.x<>NEW.x))

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

As the others mentioned you can change the SubSystem to Console and the error will go away.

Or if you want to keep the Windows subsystem you can just hint at what your entry point is, because you haven't defined ___tmainCRTStartup. You can do this by adding the following to Properties -> Linker -> Command line:

/ENTRY:"mainCRTStartup"

This way you get rid of the console window.

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

What is the relative performance difference of if/else versus switch statement in Java?

I totally agree with the opinion that premature optimization is something to avoid.

But it's true that the Java VM has special bytecodes which could be used for switch()'s.

See WM Spec (lookupswitch and tableswitch)

So there could be some performance gains, if the code is part of the performance CPU graph.

get client time zone from browser

you could use moment-timezone to guess the timezone:

> moment.tz.guess()
"America/Asuncion"

Openstreetmap: embedding map in webpage (like Google Maps)

Take a look at mapstraction. This can give you more flexibility to provide maps based on google, osm, yahoo, etc however your code won't have to change.

Import a custom class in Java

Import by using the import keyword:

import package.myclass;

But since it's the default package and same, you just create a new instance like:

elf ob = new elf(); //Instance of elf class

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

This link has the break down

http://clang.llvm.org/docs/AutomaticReferenceCounting.html#ownership.spelling.property

assign implies __unsafe_unretained ownership.

copy implies __strong ownership, as well as the usual behavior of copy semantics on the setter.

retain implies __strong ownership.

strong implies __strong ownership.

unsafe_unretained implies __unsafe_unretained ownership.

weak implies __weak ownership.

SQL Server convert select a column and convert it to a string

+------+----------------------+
| type |        names         |
+------+----------------------+
| cat  | Felon                |
| cat  | Purz                 |
| dog  | Fido                 |
| dog  | Beethoven            |
| dog  | Buddy                |
| bird | Tweety               |
+------+----------------------+

select group_concat(name) from Pets
group by type

Here you can easily get the answer in single SQL and by using group by in your SQL you can separate the result based on that column value. Also you can use your own custom separator for splitting values

Result:

+------+----------------------+
| type |        names         |
+------+----------------------+
| cat  | Felon,Purz           |
| dog  | Fido,Beethoven,Buddy |
| bird | Tweety               |
+------+----------------------+

SQLException : String or binary data would be truncated

Generally it is that you are inserting a value that is greater than the maximum allowed value. Ex, data column can only hold up to 200 characters, but you are inserting 201-character string

How can I call a shell command in my Perl script?

As you become more experienced with using Perl, you'll find that there are fewer and fewer occasions when you need to run shell commands. For example, one way to get a list of files is to use Perl's built-in glob function. If you want the list in sorted order you could combine it with the built-in sort function. If you want details about each file, you can use the stat function. Here's an example:

#!/usr/bin/perl

use strict;
use warnings;

foreach my $file ( sort glob('/home/grant/*') ) {
    my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
        = stat($file);
    printf("%-40s %8u bytes\n", $file, $size);
}

What is Java Servlet?

You just got the answer for a normally servlet. However, I want to share you about something about Servlet 3.0

What is first a Servlet?

A servlet is a Web component that is managed by a container and generates dynamic content. Servlets are Java classes that are compiled to byte code that can be loaded dynamically into and run by a Java technology-enabled Web server or Servlet container.

Servlet 3.0 is an update to the existing Servlet 2.5 specification. Servlet 3.0 required API of the Java Platform, Enterprise Edition 6. Servlet 3.0 is focussed on extensibility and web framework pluggability. Servlet 3.0 bring you up some extensions such as Ease of Development (EoD), Pluggability, Async Support and Security Enhancements

Ease of Development

You can declare Servlets, Filter, Listeners, Init Params, and almost everything can be configured by using annotations

Pluggability

You can create a sub-project or a module with a web-fragment.xml. It means that it allows to implement pluggable functional requirements independently.

Async Support

Servlet 3.0 provides the ability of asynchronous processing, for example: Waiting for a resource to become available, Generating response asynchronously.

Security Enhancements

Support for the authenticate, login and logout servlet security methods

I found it from Java Servlet Tutorial

Status bar and navigation bar appear over my view's bounds in iOS 7

If you want the view to have the translucent nav bar (which is kind of nice) you have to setup a contentInset or similar.

Here is how I do it:

// Check if we are running on ios7
if([[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."][0] intValue] >= 7) {
      CGRect statusBarViewRect = [[UIApplication sharedApplication] statusBarFrame];
      float heightPadding = statusBarViewRect.size.height+self.navigationController.navigationBar.frame.size.height;

      myContentView.contentInset = UIEdgeInsetsMake(heightPadding, 0.0, 0.0, 0.0);
}

Left join only selected columns in R with the merge() function

I think it's a little simpler to use the dplyr functions select and left_join ; at least it's easier for me to understand. The join function from dplyr are made to mimic sql arguments.

 library(tidyverse)

 DF2 <- DF2 %>%
   select(client, LO)

 joined_data <- left_join(DF1, DF2, by = "Client")

You don't actually need to use the "by" argument in this case because the columns have the same name.

Matplotlib: Specify format of floats for tick labels

In matplotlib 3.1, you can also use ticklabel_format. To prevents scientific notation without offsets:

plt.gca().ticklabel_format(axis='both', style='plain', useOffset=False)

What is tail call optimization?

Note first of all that not all languages support it.

TCO applys to a special case of recursion. The gist of it is, if the last thing you do in a function is call itself (e.g. it is calling itself from the "tail" position), this can be optimized by the compiler to act like iteration instead of standard recursion.

You see, normally during recursion, the runtime needs to keep track of all the recursive calls, so that when one returns it can resume at the previous call and so on. (Try manually writing out the result of a recursive call to get a visual idea of how this works.) Keeping track of all the calls takes up space, which gets significant when the function calls itself a lot. But with TCO, it can just say "go back to the beginning, only this time change the parameter values to these new ones." It can do that because nothing after the recursive call refers to those values.

Intent from Fragment to Activity

use this

public void goToAttract(View v)
{
    Intent intent = new Intent(getActivity(), MainActivityList.class);
    startActivity(intent);
}

be sure you've registered MainActivityList in you Manifest

What is Bootstrap?

Bootstrap is Open source HTML Framework. which compatible at almost every Browser. Basically Large Screen Browser width is >992px and extra Large 1200px. so by using Bootstrap defined classes we can adjust screen resolution for displaying contents at every screen from small mobiles to Larger Screen. I tried to explain very short. for Example :

<div class="col-sm-3">....</div>
<div class="col-sm-9">....</div>

How to set column header text for specific column in Datagridview C#

If you work with visual studio designer, you will probably have defined fields for each columns in the YourForm.Designer.cs file e.g.:

private System.Windows.Forms.DataGridViewCheckBoxColumn dataGridViewCheckBoxColumn1;    
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; 

If you give them useful names, you can set the HeaderText easily:

usefulNameForDataGridViewTextBoxColumn.HeaderText = "Useful Header Text";

How can I set NODE_ENV=production on Windows?

You can use

npm run env NODE_ENV=production

It is probably the best way to do it, because it's compatible on both Windows and Unix.

From the npm run-script documentation:

The env script is a special built-in command that can be used to list environment variables that will be available to the script at runtime. If an "env" command is defined in your package it will take precedence over the built-in.

What does it mean "No Launcher activity found!"

I had this same problem and it turns out I had a '\' instead of a '/' in the xml tag. It still gave the same error but just due to a syntax problem.

CSS: background-color only inside the margin

If your margin is set on the body, then setting the background color of the html tag should color the margin area

html { background-color: black; }
body { margin:50px; background-color: white; }

http://jsfiddle.net/m3zzb/

Or as dmackerman suggestions, set a margin of 0, but a border of the size you want the margin to be and set the border-color

Stash just a single file

If you do not want to specify a message with your stashed changes, pass the filename after a double-dash.

$ git stash -- filename.ext

If it's an untracked/new file, you will have to stage it first.

However, if you do want to specify a message, use push.

git stash push -m "describe changes to filename.ext" filename.ext

Both methods work in git versions 2.13+

How to refresh an access form

"Requery" is indeed what you what you want to run, but you could do that in Form A's "On Got Focus" event. If you have code in your Form_Load, perhaps you can move it to Form_Got_Focus.

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

Recently,I also encountered this problem. That's because I used qt(x64) in vs win32. If you want to use qt application x64, you could choose vs x64--as the above. If you want to use win32 and perhaps you haven't,you need to download qt(32bit),then correctly set your enviroment, such as the lib directory, etc.(note: maybe you are is old set in x64(other version), if you convert your win32 or x64 into another, Additional Dependencies includes the old directory!)

How to generate a random int in C?

FWIW, the answer is that yes, there is a stdlib.h function called rand; this function is tuned primarily for speed and distribution, not for unpredictability. Almost all built-in random functions for various languages and frameworks use this function by default. There are also "cryptographic" random number generators that are much less predictable, but run much slower. These should be used in any sort of security-related application.

Bash checking if string does not contain other string

Use !=.

if [[ ${testmystring} != *"c0"* ]];then
    # testmystring does not contain c0
fi

See help [[ for more information.

How to use systemctl in Ubuntu 14.04

So you want to remove dangling images? Am I correct?

systemctl enable docker-container-cleanup.timer
systemctl start docker-container-cleanup.timer
systemctl enable docker-image-cleanup.timer 
systemctl start docker-image-cleanup.timer

https://github.com/larsks/docker-tools/tree/master/docker-maintenance-units

Search for value in DataGridView in a column

It's better also to separate your logic in another method, or maybe in another class.

This method will help you retreive the DataGridViewCell object in which the text was found.

    /// <summary>
    /// Check if a given text exists in the given DataGridView at a given column index
    /// </summary>
    /// <param name="searchText"></param>
    /// <param name="dataGridView"></param>
    /// <param name="columnIndex"></param>
    /// <returns>The cell in which the searchText was found</returns>
    private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
    {
        DataGridViewCell cellWhereTextIsMet = null;

        // For every row in the grid (obviously)
        foreach (DataGridViewRow row in dataGridView.Rows)
        {
            // I did not test this case, but cell.Value is an object, and objects can be null
            // So check if the cell is null before using .ToString()
            if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
            {
                // the searchText is equals to the text in this cell.
                cellWhereTextIsMet = row.Cells[columnIndex];
                break;
            }
        }

        return cellWhereTextIsMet;
    }

    private void button_click(object sender, EventArgs e)
    {
        DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
        if (cell != null)
        {
            // Value exists in the grid
            // you can do extra stuff on the cell
            cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
        }
        else
        {
            // Value does not exist in the grid
        }
    }

Boto3 to download all files from a S3 Bucket

import os
import boto3

#initiate s3 resource
s3 = boto3.resource('s3')

# select bucket
my_bucket = s3.Bucket('my_bucket_name')

# download file into current directory
for s3_object in my_bucket.objects.all():
    # Need to split s3_object.key into path and file name, else it will give error file not found.
    path, filename = os.path.split(s3_object.key)
    my_bucket.download_file(s3_object.key, filename)

How to add an element to Array and shift indexes?

The most simple way of doing this is to use an ArrayList<Integer> and use the add(int, T) method.

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);

// Now, we will insert the number
list.add(4, 87);

How can I list ALL DNS records?

host -a works well, similar to dig any.

EG:

$ host -a google.com
Trying "google.com"
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 10403
;; flags: qr rd ra; QUERY: 1, ANSWER: 18, AUTHORITY: 0, ADDITIONAL: 0


;; QUESTION SECTION:
;google.com.            IN  ANY

;; ANSWER SECTION:
google.com.     1165    IN  TXT "v=spf1 include:_spf.google.com ip4:216.73.93.70/31 ip4:216.73.93.72/31 ~all"
google.com.     53965   IN  SOA ns1.google.com. dns-admin.google.com. 2014112500 7200 1800 1209600 300
google.com.     231 IN  A   173.194.115.73
google.com.     231 IN  A   173.194.115.78
google.com.     231 IN  A   173.194.115.64
google.com.     231 IN  A   173.194.115.65
google.com.     231 IN  A   173.194.115.66
google.com.     231 IN  A   173.194.115.67
google.com.     231 IN  A   173.194.115.68
google.com.     231 IN  A   173.194.115.69
google.com.     231 IN  A   173.194.115.70
google.com.     231 IN  A   173.194.115.71
google.com.     231 IN  A   173.194.115.72
google.com.     128 IN  AAAA    2607:f8b0:4000:809::1001
google.com.     40766   IN  NS  ns3.google.com.
google.com.     40766   IN  NS  ns4.google.com.
google.com.     40766   IN  NS  ns1.google.com.
google.com.     40766   IN  NS  ns2.google.com.

what is the use of $this->uri->segment(3) in codeigniter pagination

In your code $this->uri->segment(3) refers to the pagination offset which you use in your query. According to your $config['base_url'] = base_url().'index.php/papplicant/viewdeletedrecords/' ;, $this->uri->segment(3) i.e segment 3 refers to the offset. The first segment is the controller, second is the method, there after comes the parameters sent to the controllers as segments.

Html.EditorFor Set Default Value

In the constructor method of your model class set the default value whatever you want. Then in your first action create an instance of the model and pass it to your view.

    public ActionResult VolunteersAdd()
    {
        VolunteerModel model = new VolunteerModel(); //to set the default values
        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult VolunteersAdd(VolunteerModel model)
    {


        return View(model);
    }

HTML5 and frameborder

As per the other posting here, the best solution is to use the CSS entry of

style="border:0;"

How can I get Docker Linux container information from within the container itself?

I've found that in 17.09 there is a simplest way to do it within docker container:

$ cat /proc/self/cgroup | head -n 1 | cut -d '/' -f3
4de1c09d3f1979147cd5672571b69abec03d606afcc7bdc54ddb2b69dec3861c

Or like it has already been told, a shorter version with

$ cat /etc/hostname
4de1c09d3f19

Or simply:

$ hostname
4de1c09d3f19

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

We should also use 'use strict' in the scope function to make sure that the code should be executed in "strict mode". Sample code shown below

(function() {
    'use strict';

    //Your code from here
})();

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

The version I'm using I think is the good one, since is the exact same as the Android Developer Docs, except for the name of the string, they used "view" and I used "webview", for the rest is the same

No, it is not.

The one that is new to the N Developer Preview has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)

The one that is supported by all Android versions, including N, has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, String url)

So why should I do to make it work on all versions?

Override the deprecated one, the one that takes a String as the second parameter.

Node.js get file extension

Update

Since the original answer, extname() has been added to the path module, see Snowfish answer

Original answer:

I'm using this function to get a file extension, because I didn't find a way to do it in an easier way (but I think there is) :

function getExtension(filename) {
    var ext = path.extname(filename||'').split('.');
    return ext[ext.length - 1];
}

you must require 'path' to use it.

another method which does not use the path module :

function getExtension(filename) {
    var i = filename.lastIndexOf('.');
    return (i < 0) ? '' : filename.substr(i);
}

How to use WinForms progress bar?

Since .NET 4.5 you can use combination of async and await with Progress for sending updates to UI thread:

private void Calculate(int i)
{
    double pow = Math.Pow(i, i);
}

public void DoWork(IProgress<int> progress)
{
    // This method is executed in the context of
    // another thread (different than the main UI thread),
    // so use only thread-safe code
    for (int j = 0; j < 100000; j++)
    {
        Calculate(j);

        // Use progress to notify UI thread that progress has
        // changed
        if (progress != null)
            progress.Report((j + 1) * 100 / 100000);
    }
}

private async void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;

    var progress = new Progress<int>(v =>
    {
        // This lambda is executed in context of UI thread,
        // so it can safely update form controls
        progressBar1.Value = v;
    });

    // Run operation in another thread
    await Task.Run(() => DoWork(progress));

    // TODO: Do something after all calculations
}

Tasks are currently the preferred way to implement what BackgroundWorker does.

Tasks and Progress are explained in more detail here:

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

How to copy part of an array to another array in C#?

See this question. LINQ Take() and Skip() are the most popular answers, as well as Array.CopyTo().

A purportedly faster extension method is described here.

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

Just change your default port 8080 to something else like below example

SQL> begin
 2   dbms_xdb.sethttpport('9090');
 3   end;
 4  /

Adjust UILabel height to text

Following on @Anorak answer, i added this extension to String and sent an inset as a parameter, because a lot of times you will need a padding to your text. Anyway, maybe some you will find this usefull.

extension String {

    func heightForWithFont(font: UIFont, width: CGFloat, insets: UIEdgeInsets) -> CGFloat {

        let label:UILabel = UILabel(frame: CGRectMake(0, 0, width + insets.left + insets.right, CGFloat.max))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping
        label.font = font
        label.text = self

        label.sizeToFit()
        return label.frame.height + insets.top + insets.bottom
    }
}

What’s the difference between Response.Write() andResponse.Output.Write()?

Response.write() don't give formatted output. The latter one allows you to write formatted output.

Response.write - it writes the text stream Response.output.write - it writes the HTTP Output Stream.

How to get object size in memory?

I don't think you can get it directly, but there are a few ways to find it indirectly.

One way is to use the GC.GetTotalMemory method to measure the amount of memory used before and after creating your object. This won't be perfect, but as long as you control the rest of the application you may get the information you are interested in.

Apart from that you can use a profiler to get the information or you could use the profiling api to get the information in code. But that won't be easy to use I think.

See Find out how much memory is being used by an object in C#? for a similar question.

How to generate unique ID with node.js

The solutions here are old and now deprecated: https://github.com/uuidjs/uuid#deep-requires-now-deprecated

Use this:

npm install uuid

//add these lines to your code
const { v4: uuidv4 } = require('uuid');
var your_uuid = uuidv4();
console.log(your_uuid);

Simpler way to check if variable is not equal to multiple string values?

For your first code, you can use a short alteration of the answer given by @ShankarDamodaran using in_array():

if ( !in_array($some_variable, array('uk','in'), true ) ) {

or even shorter with [] notation available since php 5.4 as pointed out by @Forty in the comments

if ( !in_array($some_variable, ['uk','in'], true ) ) {

is the same as:

if ( $some_variable !== 'uk' && $some_variable !== 'in' ) {

... but shorter. Especially if you compare more than just 'uk' and 'in'. I do not use an additional variable (Shankar used $os) but instead define the array in the if statement. Some might find that dirty, i find it quick and neat :D

The problem with your second code is that it can easily be exchanged with just TRUE since:

if (true) {

equals

if ( $some_variable !== 'uk' || $some_variable !== 'in' ) {

You are asking if the value of a string is not A or Not B. If it is A, it is definitely not also B and if it is B it is definitely not A. And if it is C or literally anything else, it is also not A and not B. So that statement always (not taking into account schrödingers law here) returns true.

What is the difference between XML and XSD?

Basically an XSD file defines how the XML file is going to look like. It's a Schema file which defines the structure of the XML file. So it specifies what the possible fields are and what size they are going to be.

An XML file is an instance of XSD as it uses the rules defined in the XSD.

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

You could add in your code a call system with the new definition:

sprintf(newdef,"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:%s:%s",ld1,ld2);
system(newdef);

But, I don't know it that is the rigth solution but it works.

Regards

Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

Finally I imported my Gradle project. These are the steps:

  1. I switched from local Gradle distrib to Intellij Idea Gradle Wrapper (gradle-2.14).
  2. I pointed system variable JAVA_HOME to JDK 8 (it was 7th previously) as I had figured out by experiments that Gradle Wrapper could process the project with JDK 8 only.
  3. I deleted previously manually created file gradle.properties (with org.gradle.java.homevariable) in windows user .gradle directory as, I guessed, it didn't bring any additional value to Gradle.

How can I open a .db file generated by eclipse(android) form DDMS-->File explorer-->data--->data-->packagename-->database?

One of the way to browse your database is to use questoid sqlite manager.

# 1. Download questoid manager from this link .

# 2. Drop this file into your eclipse --> dropins.

# 3. Restart your eclipse.

# 4. Now go to your file explorer and click your database. you can find a blue database icon enabled in the top right corner.

# 5. Double click the icon and you can see ur inserted fields/tables/ in the database

How do I read CSV data into a record array in NumPy?

You can use Numpy's genfromtxt() method to do so, by setting the delimiter kwarg to a comma.

from numpy import genfromtxt
my_data = genfromtxt('my_file.csv', delimiter=',')

More information on the function can be found at its respective documentation.

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

jQuery remove options from select

For jquery < 1.8 you can use :

$('#selectedId option').slice(index1,index2).remove()

to remove a especific range of the select options.

How to deal with the URISyntaxException

A general solution requires parsing the URL into a RFC 2396 compliant URI (note that this is an old version of the URI standard, which java.net.URI uses).

I have written a Java URL parsing library that makes this possible: galimatias. With this library, you can achieve your desired behaviour with this code:

String urlString = //...
URLParsingSettings settings = URLParsingSettings.create()
  .withStandard(URLParsingSettings.Standard.RFC_2396);
URL url = URL.parse(settings, urlString);

Note that galimatias is in a very early stage and some features are experimental, but it is already quite solid for this use case.

Django auto_now and auto_now_add

I needed something similar today at work. Default value to be timezone.now(), but editable both in admin and class views inheriting from FormMixin, so for created in my models.py the following code fulfilled those requirements:

from __future__ import unicode_literals
import datetime

from django.db import models
from django.utils.functional import lazy
from django.utils.timezone import localtime, now

def get_timezone_aware_now_date():
    return localtime(now()).date()

class TestDate(models.Model):
    created = models.DateField(default=lazy(
        get_timezone_aware_now_date, datetime.date)()
    )

For DateTimeField, I guess remove the .date() from the function and change datetime.date to datetime.datetime or better timezone.datetime. I haven't tried it with DateTime, only with Date.

Why is IoC / DI not common in Python?

pytest fixtures all based on DI (source)

Create intermediate folders if one doesn't exist

You have to actually call some method to create the directories. Just creating a file object will not create the corresponding file or directory on the file system.

You can use File#mkdirs() method to create the directory: -

theFile.mkdirs();

Difference between File#mkdir() and File#mkdirs() is that, the later will create any intermediate directory if it does not exist.

Python Create unix timestamp five minutes in the future

Note that solutions with timedelta.total_seconds() work on python-2.7+. Use calendar.timegm(future.utctimetuple()) for lower versions of Python.

Skipping Incompatible Libraries at compile

That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.

Of course, if you're also getting an error along the lines of can't find lPI-Http then you have a problem :-)

It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:

  1. Just to check: usually you would add flags to CFLAGS rather than CTAGS - are you sure this is correct? (What you have may be correct - this will depend on your build system!)
  2. Often the flag needs to be passed to the linker too - so you may also need to modify LDFLAGS

If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx etc) that was being executed?

Can a for loop increment/decrement by more than one?

You certainly can. Others have pointed out correctly that you need to do i += 3. You can't do what you have posted because all you are doing here is adding i + 3 but never assigning the result back to i. i++ is just a shorthand for i = i + 1, similarly i +=3 is a shorthand for i = i + 3.

Removing a model in rails (reverse of "rails g model Title...")

bundle exec rake db:rollback    
rails destroy model <model_name>

When you generate a model, it creates a database migration. If you run 'destroy' on that model, it will delete the migration file, but not the database table. So before run

bundle exec rake db:rollback

How to find the privileges and roles granted to a user in Oracle?

In addition to VAV's answer, The first one was most useful in my environment

select * from USER_ROLE_PRIVS where USERNAME='SAMPLE';
select * from USER_TAB_PRIVS where Grantee = 'SAMPLE';
select * from USER_SYS_PRIVS where USERNAME = 'SAMPLE';

Change text color with Javascript?

use ONLY

function init() { 
    about = document.getElementById("about");
    about.style.color = 'blue';
}

.innerHTML() sets or gets the HTML syntax describing the element's descendants., All you need is an object here.

Demo

Correct way to use Modernizr to detect IE?

Well, after doing more research on this topic I ended up using following solution for targeting IE 10+. As IE10&11 are the only browsers which support the -ms-high-contrast media query, that is a good option without any JS:

@media screen and (-ms-high-contrast: active), screen and (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
}

Works perfectly.

Url decode UTF-8 in Python

You can achieve an expected result with requests library as well:

import requests

url = "http://www.mywebsite.org/Data%20Set.zip"

print(f"Before: {url}")
print(f"After:  {requests.utils.unquote(url)}")

Output:

$ python3 test_url_unquote.py

Before: http://www.mywebsite.org/Data%20Set.zip
After:  http://www.mywebsite.org/Data Set.zip

Might be handy if you are already using requests, without using another library for this job.

Adding a rule in iptables in debian to open a new port

(I presume that you've concluded that it's an iptables problem by dropping the firewall completely (iptables -P INPUT ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F) and confirmed that you can connect to the MySQL server from your Windows box?)

Some previous rule in the INPUT table is probably rejecting or dropping the packet. You can get around that by inserting the new rule at the top, although you might want to review your existing rules to see whether that's sensible:

iptables -I INPUT 1 -p tcp --dport 3306 -j ACCEPT

Note that iptables-save won't save the new rule persistently (i.e. across reboots) - you'll need to figure out something else for that. My usual route is to store the iptables-save output in a file (/etc/network/iptables.rules or similar) and then load then with a pre-up statement in /etc/network/interfaces).

In a URL, should spaces be encoded using %20 or +?

You can use either - which means most people opt for "+" as it's more human readable.

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

How enable auto-format code for Intellij IDEA?

if you want, you can use a saveActions plugin. You can reformat file, optimized the imports and more things, it's really customizable and easy to setup.

java : convert float to String and String to float

well this method is not a good one, but easy and not suggested. Maybe i should say this is the least effective method and the worse coding practice but, fun to use,

float val=10.0;
String str=val+"";

the empty quotes, add a null string to the variable str, upcasting 'val' to the string type.

Sorting HashMap by values

You don't, basically. A HashMap is fundamentally unordered. Any patterns you might see in the ordering should not be relied on.

There are sorted maps such as TreeMap, but they traditionally sort by key rather than value. It's relatively unusual to sort by value - especially as multiple keys can have the same value.

Can you give more context for what you're trying to do? If you're really only storing numbers (as strings) for the keys, perhaps a SortedSet such as TreeSet would work for you?

Alternatively, you could store two separate collections encapsulated in a single class to update both at the same time?

Include PHP file into HTML file

You would have to configure your webserver to utilize PHP as handler for .html files. This is typically done by modifying your with AddHandler to include .html along with .php.

Note that this could have a performance impact as this would cause ALL .html files to be run through PHP handler even if there is no PHP involved. So you might strongly consider using .php extension on these files and adding a redirect as necessary to route requests to specific .html URL's to their .php equivalents.

Iterate all files in a directory using a 'for' loop

There is a subtle difference between running FOR from the command line and from a batch file. In a batch file, you need to put two % characters in front of each variable reference.

From a command line:

FOR %i IN (*) DO ECHO %i

From a batch file:

FOR %%i IN (*) DO ECHO %%i

Vuejs and Vue.set(), update array

As stated before - VueJS simply can't track those operations(array elements assignment). All operations that are tracked by VueJS with array are here. But I'll copy them once again:

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

During development, you face a problem - how to live with that :).

push(), pop(), shift(), unshift(), sort() and reverse() are pretty plain and help you in some cases but the main focus lies within the splice(), which allows you effectively modify the array that would be tracked by VueJs. So I can share some of the approaches, that are used the most working with arrays.

You need to replace Item in Array:

// note - findIndex might be replaced with some(), filter(), forEach() 
// or any other function/approach if you need 
// additional browser support, or you might use a polyfill
const index = this.values.findIndex(item => {
          return (replacementItem.id === item.id)
        })
this.values.splice(index, 1, replacementItem)

Note: if you just need to modify an item field - you can do it just by:

this.values[index].itemField = newItemFieldValue

And this would be tracked by VueJS as the item(Object) fields would be tracked.

You need to empty the array:

this.values.splice(0, this.values.length)

Actually you can do much more with this function splice() - w3schools link You can add multiple records, delete multiple records, etc.

Vue.set() and Vue.delete()

Vue.set() and Vue.delete() might be used for adding field to your UI version of data. For example, you need some additional calculated data or flags within your objects. You can do this for your objects, or list of objects(in the loop):

 Vue.set(plan, 'editEnabled', true) //(or this.$set)

And send edited data back to the back-end in the same format doing this before the Axios call:

 Vue.delete(plan, 'editEnabled') //(or this.$delete)

How do I cancel an HTTP fetch() request?

As of Feb 2018, fetch() can be cancelled with the code below on Chrome (read Using Readable Streams to enable Firefox support). No error is thrown for catch() to pick up, and this is a temporary solution until AbortController is fully adopted.

fetch('YOUR_CUSTOM_URL')
.then(response => {
  if (!response.body) {
    console.warn("ReadableStream is not yet supported in this browser.  See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream")
    return response;
  }

  // get reference to ReadableStream so we can cancel/abort this fetch request.
  const responseReader = response.body.getReader();
  startAbortSimulation(responseReader);

  // Return a new Response object that implements a custom reader.
  return new Response(new ReadableStream(new ReadableStreamConfig(responseReader)));
})
.then(response => response.blob())
.then(data => console.log('Download ended. Bytes downloaded:', data.size))
.catch(error => console.error('Error during fetch()', error))


// Here's an example of how to abort request once fetch() starts
function startAbortSimulation(responseReader) {
  // abort fetch() after 50ms
  setTimeout(function() {
    console.log('aborting fetch()...');
    responseReader.cancel()
    .then(function() {
      console.log('fetch() aborted');
    })
  },50)
}


// ReadableStream constructor requires custom implementation of start() method
function ReadableStreamConfig(reader) {
  return {
    start(controller) {
      read();
      function read() {
        reader.read().then(({done,value}) => {
          if (done) {
            controller.close();
            return;
          }
          controller.enqueue(value);
          read();
        })
      }
    }
  }
}

Rails 4: assets not loading in production

I'm running Ubuntu Server 14.04, Ruby 2.2.1 and Rails 4.2.4 I have followed a deploy turorial from DigitalOcean and everything went well but when I go to the browser and enter the IP address of my VPS my app is loaded but without styles and javascript.

The app is running with Unicorn and Nginx. To fix this problem I entered my server using SSH with my user 'deployer' and go to my app path which is '/home/deployer/apps/blog' and run the following command:

RAILS_ENV=production bin/rake assets:precompile

Then I just restart the VPS and that's it! It works for me!

Hope it could be useful for somebody else!

R adding days to a date

In addition to the simple addition shown by others, you can also use seq.Date or seq.POSIXt to find other increments or decrements (the POSIXt version does seconds, minutes, hours, etc.):

> seq.Date( Sys.Date(), length=2, by='3 months' )[2]
[1] "2012-07-25"

AngularJs $http.post() does not send data

I know has accepted answer. But, following might help to future readers, if the answer doesn't suit them for any reason.

Angular doesn't do ajax same as jQuery. While I tried to follow the guide to modify angular $httpprovider , I encountered other problems. E.g. I use codeigniter in which $this->input->is_ajax_request() function always failed (which was written by another programmer and used globally, so cant change) saying this was not real ajax request.

To solve it, I took help of deferred promise. I tested it in Firefox, and ie9 and it worked.

I have following function defined outside any of the angular code. This function makes regular jquery ajax call and returns deferred/promise (I'm still learning) object.

function getjQueryAjax(url, obj){
    return $.ajax({
        type: 'post',
        url: url,
        cache: true,
        data: obj
    });
}

Then I'm calling it angular code using the following code. Please note that we have to update the $scope manually using $scope.$apply() .

    var data = {
        media: "video",
        scope: "movies"
    };
    var rPromise = getjQueryAjax("myController/getMeTypes" , data);
    rPromise.success(function(response){
        console.log(response);
        $scope.$apply(function(){
            $scope.testData = JSON.parse(response);
            console.log($scope.testData);
        });
    }).error(function(){
        console.log("AJAX failed!");
    });

This may not be the perfect answer, but it allowed me to use jquery ajax calls with angular and allowed me to update the $scope.

Create a variable name with "paste" in R?

In my case function eval() works very good. Below I generate 10 variables and assign them 10 values.

lhs <- rnorm(10)
rhs <- paste("perf.a", 1:10, "<-", lhs, sep="")
eval(parse(text=rhs))

How do I get the directory that a program is running from?

Boost Filesystem's initial_path() behaves like POSIX's getcwd(), and neither does what you want by itself, but appending argv[0] to either of them should do it.

You may note that the result is not always pretty--you may get things like /foo/bar/../../baz/a.out or /foo/bar//baz/a.out, but I believe that it always results in a valid path which names the executable (note that consecutive slashes in a path are collapsed to one).

I previously wrote a solution using envp (the third argument to main() which worked on Linux but didn't seem workable on Windows, so I'm essentially recommending the same solution as someone else did previously, but with the additional explanation of why it is actually correct even if the results are not pretty.

Creating a Menu in Python

This should do it. You were missing a ) and you only need """ not 4 of them. Also you don't need a elif at the end.

ans=True
while ans:
    print("""
    1.Add a Student
    2.Delete a Student
    3.Look Up Student Record
    4.Exit/Quit
    """)
    ans=raw_input("What would you like to do? ")
    if ans=="1":
      print("\nStudent Added")
    elif ans=="2":
      print("\n Student Deleted")
    elif ans=="3":
      print("\n Student Record Found")
    elif ans=="4":
      print("\n Goodbye") 
      ans = None
    else:
       print("\n Not Valid Choice Try again")

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Here is another, very manual solution. You can define the size of the axis and paddings are considered accordingly (including legend and tickmarks). Hope it is of use to somebody.

Example (axes size are the same!):

enter image description here

Code:

#==================================================
# Plot table

colmap = [(0,0,1) #blue
         ,(1,0,0) #red
         ,(0,1,0) #green
         ,(1,1,0) #yellow
         ,(1,0,1) #magenta
         ,(1,0.5,0.5) #pink
         ,(0.5,0.5,0.5) #gray
         ,(0.5,0,0) #brown
         ,(1,0.5,0) #orange
         ]


import matplotlib.pyplot as plt
import numpy as np

import collections
df = collections.OrderedDict()
df['labels']        = ['GWP100a\n[kgCO2eq]\n\nasedf\nasdf\nadfs','human\n[pts]','ressource\n[pts]'] 
df['all-petroleum long name'] = [3,5,2]
df['all-electric']  = [5.5, 1, 3]
df['HEV']           = [3.5, 2, 1]
df['PHEV']          = [3.5, 2, 1]

numLabels = len(df.values()[0])
numItems = len(df)-1
posX = np.arange(numLabels)+1
width = 1.0/(numItems+1)

fig = plt.figure(figsize=(2,2))
ax = fig.add_subplot(111)
for iiItem in range(1,numItems+1):
  ax.bar(posX+(iiItem-1)*width, df.values()[iiItem], width, color=colmap[iiItem-1], label=df.keys()[iiItem])
ax.set(xticks=posX+width*(0.5*numItems), xticklabels=df['labels'])

#--------------------------------------------------
# Change padding and margins, insert legend

fig.tight_layout() #tight margins
leg = ax.legend(loc='upper left', bbox_to_anchor=(1.02, 1), borderaxespad=0)
plt.draw() #to know size of legend

padLeft   = ax.get_position().x0 * fig.get_size_inches()[0]
padBottom = ax.get_position().y0 * fig.get_size_inches()[1]
padTop    = ( 1 - ax.get_position().y0 - ax.get_position().height ) * fig.get_size_inches()[1]
padRight  = ( 1 - ax.get_position().x0 - ax.get_position().width ) * fig.get_size_inches()[0]
dpi       = fig.get_dpi()
padLegend = ax.get_legend().get_frame().get_width() / dpi 

widthAx = 3 #inches
heightAx = 3 #inches
widthTot = widthAx+padLeft+padRight+padLegend
heightTot = heightAx+padTop+padBottom

# resize ipython window (optional)
posScreenX = 1366/2-10 #pixel
posScreenY = 0 #pixel
canvasPadding = 6 #pixel
canvasBottom = 40 #pixel
ipythonWindowSize = '{0}x{1}+{2}+{3}'.format(int(round(widthTot*dpi))+2*canvasPadding
                                            ,int(round(heightTot*dpi))+2*canvasPadding+canvasBottom
                                            ,posScreenX,posScreenY)
fig.canvas._tkcanvas.master.geometry(ipythonWindowSize) 
plt.draw() #to resize ipython window. Has to be done BEFORE figure resizing!

# set figure size and ax position
fig.set_size_inches(widthTot,heightTot)
ax.set_position([padLeft/widthTot, padBottom/heightTot, widthAx/widthTot, heightAx/heightTot])
plt.draw()
plt.show()
#--------------------------------------------------
#==================================================

How to update TypeScript to latest version with npm?

Open command prompt (cmd.exe/git bash)

Recommended:

npm install -g typescript@latest

or

yarn global add typescript@latest  // if you use yarn package manager

This will install the latest typescript version if not already installed, otherwise it will update the current installation to the latest version.

And then verify which version is installed:

tsc -v

enter image description here


If you have typescript already installed you could also use the following command to update to latest version, but as commentators have reported and I confirm it that the following command does not update to latest (as of now [ Feb 10 '17])!

npm update -g typescript@latest

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

I had this issue and tried many things but still din't work. Eventually I decided to generate another SSH KEY and boom - it worked. Follow this article by github to guide you on how to generate your SSH KEY.

Lastly don't forget to add it to your github settings. Click here for a guide on how to add your SSH KEY to your github account.

How do I set a VB.Net ComboBox default value

If ComboBox1.SelectedIndex = -1 Then
    ComboBox1.SelectedIndex = 0    
End If

Redirecting from cshtml page

Would be safer to do this.

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

So the controller for that action runs as well, to populate any model the view needs.

Source
Redirect from a view to another view

Although as @Satpal mentioned, I do recommend you do the redirecting on your controller.

What's the difference between 'git merge' and 'git rebase'?

I found one really interesting article on git rebase vs merge, thought of sharing it here

  • If you want to see the history completely same as it happened, you should use merge. Merge preserves history whereas rebase rewrites it.
  • Merging adds a new commit to your history
  • Rebasing is better to streamline a complex history, you are able to change the commit history by interactive rebase.

python: How do I know what type of exception occurred?

Your question is: "How can I see exactly what happened in the someFunction() that caused the exception to happen?"

It seems to me that you are not asking about how to handle unforeseen exceptions in production code (as many answers assumed), but how to find out what is causing a particular exception during development.

The easiest way is to use a debugger that can stop where the uncaught exception occurs, preferably not exiting, so that you can inspect the variables. For example, PyDev in the Eclipse open source IDE can do that. To enable that in Eclipse, open the Debug perspective, select Manage Python Exception Breakpoints in the Run menu, and check Suspend on uncaught exceptions.

How to find all the subclasses of a class given its name?

Here's a version without recursion:

def get_subclasses_gen(cls):

    def _subclasses(classes, seen):
        while True:
            subclasses = sum((x.__subclasses__() for x in classes), [])
            yield from classes
            yield from seen
            found = []
            if not subclasses:
                return

            classes = subclasses
            seen = found

    return _subclasses([cls], [])

This differs from other implementations in that it returns the original class. This is because it makes the code simpler and:

class Ham(object):
    pass

assert(issubclass(Ham, Ham)) # True

If get_subclasses_gen looks a bit weird that's because it was created by converting a tail-recursive implementation into a looping generator:

def get_subclasses(cls):

    def _subclasses(classes, seen):
        subclasses = sum(*(frozenset(x.__subclasses__()) for x in classes))
        found = classes + seen
        if not subclasses:
            return found

        return _subclasses(subclasses, found)

    return _subclasses([cls], [])

Find row in datatable with specific id

Make a string criteria to search for, like this:

string searchExpression = "ID = 5"

Then use the .Select() method of the DataTable object, like this:

DataRow[] foundRows = YourDataTable.Select(searchExpression);

Now you can loop through the results, like this:

int numberOfCalls;
bool result;
foreach(DataRow dr in foundRows)
{
    // Get value of Calls here
    result = Int32.TryParse(dr["Calls"], out numberOfCalls);

    // Optionally, you can check the result of the attempted try parse here
    // and do something if you wish
    if(result)
    {
        // Try parse to 32-bit integer worked

    }
    else
    {
        // Try parse to 32-bit integer failed

    }
}

Reload a DIV without reloading the whole page

Your code works, but the fadeIn doesn't, because it's already visible. I think the effect you want to achieve is: fadeOutloadfadeIn:

var auto_refresh = setInterval(function () {
    $('.View').fadeOut('slow', function() {
        $(this).load('/echo/json/', function() {
            $(this).fadeIn('slow');
        });
    });
}, 15000); // refresh every 15000 milliseconds

Try it here: http://jsfiddle.net/kelunik/3qfNn/1/

Additional notice: As Khanh TO mentioned, you may need to get rid of the browser's internal cache. You can do so using $.ajax and $.ajaxSetup ({ cache: false }); or the random-hack, he mentioned.

Mount current directory as a volume in Docker on Windows 10

This works for me in PowerShell:

docker run --rm -v ${PWD}:/data alpine ls /data

Is there any way I can define a variable in LaTeX?

add the following to you preamble:

\newcommand{\newCommandName}{text to insert}

Then you can just use \newCommandName{} in the text

For more info on \newcommand, see e.g. wikibooks

Example:

\documentclass{article}
\newcommand\x{30}
\begin{document}
\x
\end{document}

Output:

30

Curl : connection refused

Try curl -v http://localhost:8080/ instead of 127.0.0.1

Limit the height of a responsive image with css

I set the below 3 styles to my img tag

max-height: 500px;
height: 70%;
width: auto;

What it does that for desktop screen img doesn't grow beyond 500px but for small mobile screens, it will shrink to 70% of the outer container. Works like a charm.

It also works width property.

How to use global variable in node.js?

Most people advise against using global variables. If you want the same logger class in different modules you can do this

logger.js

  module.exports = new logger(customConfig);

foobar.js

  var logger = require('./logger');
  logger('barfoo');

If you do want a global variable you can do:

global.logger = new logger(customConfig);

iPhone app could not be installed at this time

Missing icon could be a problem. My manifest file points to a non-existing image and it fails the installation process. Placing an icon at the corresponding path solved the issue for me.

Convert float to double without losing precision

I've encountered this issue today and could not use refactor to BigDecimal, because the project is really huge. However I found solution using

Float result = new Float(5623.23)
Double doubleResult = new FloatingDecimal(result.floatValue()).doubleValue()

And this works.

Note that calling result.doubleValue() returns 5623.22998046875

But calling doubleResult.doubleValue() returns correctly 5623.23

But I am not entirely sure if its a correct solution.

How to position the form in the center screen?

i hope this will be helpful.

put this on the top of source code :

import java.awt.Toolkit;

and then write this code :

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
    int lebar = this.getWidth()/2;
    int tinggi = this.getHeight()/2;
    int x = (Toolkit.getDefaultToolkit().getScreenSize().width/2)-lebar;
    int y = (Toolkit.getDefaultToolkit().getScreenSize().height/2)-tinggi;
    this.setLocation(x, y);
}

good luck :)

Update with two tables?

For Microsoft Access

UPDATE TableA A
    INNER JOIN TableB B
    ON A.ID = B.ID
SET A.Name = B.Name

How to decode a QR-code image in (preferably pure) Python?

For Windows using ZBar

Pre-requisites:

To decode:

from PIL import Image
from pyzbar import pyzbar

img = Image.open('My-Image.jpg')
output = pyzbar.decode(img)
print(output)

Alternatively, you can also try using ZBarLight by setting it up as mentioned here:
https://pypi.org/project/zbarlight/

How to concatenate strings in twig

To mix strings, variables and translations I simply do the following:

    {% set add_link = '
    <a class="btn btn-xs btn-icon-only" 
       title="' ~ 'string.to_be_translated'|trans ~ '" 
       href="' ~ path('acme_myBundle_link',{'link':link.id})  ~ '">
    </a>
    ' %}

Despite everything being mixed up, it works like a charm.

How to play a notification sound on websites?

2021 solution

function playSound(url) {
  const audio = new Audio(url);
  audio.play();
}
<button onclick="playSound('https://your-file.mp3');">Play</button>  

Browser support

Edge 12+, Firefox 20+, Internet Explorer 9+, Opera 15+, Safari 4+, Chrome

Codecs Support

Just use MP3


Old solution

(for legacy browsers)

function playSound(filename){
  var mp3Source = '<source src="' + filename + '.mp3" type="audio/mpeg">';
  var oggSource = '<source src="' + filename + '.ogg" type="audio/ogg">';
  var embedSource = '<embed hidden="true" autostart="true" loop="false" src="' + filename +'.mp3">';
  document.getElementById("sound").innerHTML='<audio autoplay="autoplay">' + mp3Source + oggSource + embedSource + '</audio>';
}
<button onclick="playSound('bing');">Play</button>  
<div id="sound"></div>

Browser support

Codes used

  • MP3 for Chrome, Safari and Internet Explorer.
  • OGG for Firefox and Opera.

Spring Boot REST service exception handling

For people that want to response according to http status code, you can use the ErrorController way:

@Controller
public class CustomErrorController extends BasicErrorController {

    public CustomErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    @Override
    public ResponseEntity error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status.equals(HttpStatus.INTERNAL_SERVER_ERROR)){
            return ResponseEntity.status(status).body(ResponseBean.SERVER_ERROR);
        }else if (status.equals(HttpStatus.BAD_REQUEST)){
            return ResponseEntity.status(status).body(ResponseBean.BAD_REQUEST);
        }
        return super.error(request);
    }
}

The ResponseBean here is my custom pojo for response.

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

python: SyntaxError: EOL while scanning string literal

Most previous answers are correct and my answer is very similar to aaronasterling, you could also do 3 single quotations s1='''some very long string............'''

IntelliJ: Working on multiple projects

Press "F4" on windows which will open up "Project Structure" and then click "+" icon or "Alt + Insert" to select a new project to be imported; then click OK button...

Format specifier %02x

%x is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.

%02x means if your provided value is less than two digits then 0 will be prepended.

You provided value 16843009 and it has been converted to 1010101 which a hex value.

C# 4.0 optional out/ref arguments

As already mentioned, this is simply not allowed and I think it makes a very good sense. However, to add some more details, here is a quote from the C# 4.0 Specification, section 21.1:

Formal parameters of constructors, methods, indexers and delegate types can be declared optional:

fixed-parameter:
    attributesopt parameter-modifieropt type identifier default-argumentopt
default-argument:
    = expression

  • A fixed-parameter with a default-argument is an optional parameter, whereas a fixed-parameter without a default-argument is a required parameter.
  • A required parameter cannot appear after an optional parameter in a formal-parameter-list.
  • A ref or out parameter cannot have a default-argument.

Android Eclipse - Could not find *.apk

This fixed my problem. I kept getting the console error in eclipse "Could not find com_android_vending_licensing.apk" and even though it didnt seem to effect the way my app ran, it was annoying. So going into the com_android_vending_licensing project properties and unchecking the "is library" option, building the project to produce the needed apk and then going back into the com_android_vending_licensing project properties and re checking the "is library" check box fixed the problem.

How to get hostname from IP (Linux)?

Another simple way I found for using in LAN is

ssh [username@ip] uname -n

If you need to login command line will be

sshpass -p "[password]" ssh [username@ip] uname -n

How do I format a String in an email so Outlook will print the line breaks?

The \n largely works for us, but Outlook does sometimes take it upon itself to remove the line breaks as you say.

How to use Switch in SQL Server

    select 
       @selectoneCount = case @Temp
       when 1 then (@selectoneCount+1)
       when 2 then (@selectoneCount+1)
       end

   select  @selectoneCount 

How to create a signed APK file using Cordova command line interface?

For Windows, I've created a build.cmd file:

(replace the keystore path and alias)

For Cordova:

@echo off 
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%

And for Ionic:

@echo off 
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && ionic build --prod && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%

Save it in the ptoject's directory, you can double click or open it with cmd.

How does one check if a table exists in an Android SQLite database?

I know nothing about the Android SQLite API, but if you're able to talk to it in SQL directly, you can do this:

create table if not exists mytable (col1 type, col2 type);

Which will ensure that the table is always created and not throw any errors if it already existed.

Angular - ui-router get previous state

I use a similar approach to what Endy Tjahjono does.

What I do is to save the value of the current state before making a transition. Lets see on an example; imagine this inside a function executed when cliking to whatever triggers the transition:

$state.go( 'state-whatever', { previousState : { name : $state.current.name } }, {} );

The key here is the params object (a map of the parameters that will be sent to the state) -> { previousState : { name : $state.current.name } }

Note: note that Im only "saving" the name attribute of the $state object, because is the only thing I need for save the state. But we could have the whole state object.

Then, state "whatever" got defined like this:

.state( 'user-edit', {
  url : 'whatever'
  templateUrl : 'whatever',
  controller: 'whateverController as whateverController',
  params : {
    previousState: null,
  }
});

Here, the key point is the params object.

params : {
  previousState: null,
}

Then, inside that state, we can get the previous state like this:

$state.params.previousState.name

How can I check for IsPostBack in JavaScript?

You can create a hidden textbox with a value of 0. Put the onLoad() code in a if block that checks to make sure the hidden text box value is 0. if it is execute the code and set the textbox value to 1.