Programs & Examples On #Sqldatatypes

Concerns data types used with SQL.

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

The (m) indicates the column display width; applications such as the MySQL client make use of this when showing the query results.

For example:

| v   | a   |  b  |   c |
+-----+-----+-----+-----+
| 1   | 1   |  1  |   1 |
| 10  | 10  | 10  |  10 |
| 100 | 100 | 100 | 100 |

Here a, b and c are using TINYINT(1), TINYINT(2) and TINYINT(3) respectively. As you can see, it pads the values on the left side using the display width.

It's important to note that it does not affect the accepted range of values for that particular type, i.e. TINYINT(1) still accepts [-128 .. 127].

Is there any boolean type in Oracle databases?

Not at the SQL level and that's a pity There is one in PLSQL though

How to convert Nvarchar column to INT

CONVERT takes the column name, not a string containing the column name; your current expression tries to convert the string A.my_NvarcharColumn to an integer instead of the column content.

SELECT convert (int, N'A.my_NvarcharColumn') FROM A;

should instead be

SELECT convert (int, A.my_NvarcharColumn) FROM A;

Simple SQLfiddle here.

Boolean Field in Oracle

In our databases we use an enum that ensures we pass it either TRUE or FALSE. If you do it either of the first two ways it is too easy to either start adding new meaning to the integer without going through a proper design, or ending up with that char field having Y, y, N, n, T, t, F, f values and having to remember which section of code uses which table and which version of true it is using.

How to display two digits after decimal point in SQL Server

select cast(your_float_column as decimal(10,2))
from your_table

decimal(10,2) means you can have a decimal number with a maximal total precision of 10 digits. 2 of them after the decimal point and 8 before.
The biggest possible number would be 99999999.99

Best data type to store money values in MySQL

You can use DECIMAL or NUMERIC both are same

The DECIMAL and NUMERIC types store exact numeric data values. These types are used when it is important to preserve exact precision, for example with monetary data. In MySQL, NUMERIC is implemented as DECIMAL, so the following remarks about DECIMAL apply equally to NUMERIC. : MySQL

i.e. DECIMAL(10,2)

Example settings

Good read

SQL Server Text type vs. varchar data type

In SQL server 2005 new datatypes were introduced: varchar(max) and nvarchar(max) They have the advantages of the old text type: they can contain op to 2GB of data, but they also have most of the advantages of varchar and nvarchar. Among these advantages are the ability to use string manipulation functions such as substring().

Also, varchar(max) is stored in the table's (disk/memory) space while the size is below 8Kb. Only when you place more data in the field, it's is stored out of the table's space. Data stored in the table's space is (usually) retrieved quicker.

In short, never use Text, as there is a better alternative: (n)varchar(max). And only use varchar(max) when a regular varchar is not big enough, ie if you expect teh string that you're going to store will exceed 8000 characters.

As was noted, you can use SUBSTRING on the TEXT datatype,but only as long the TEXT fields contains less than 8000 characters.

Which MySQL data type to use for storing boolean values

You can use BOOL, BOOLEAN data type for storing boolean values.

These types are synonyms for TINYINT(1)

However, the BIT(1) data type makes more sense to store a boolean value (either true[1] or false[0]) but TINYINT(1) is easier to work with when you're outputting the data, querying and so on and to achieve interoperability between MySQL and other databases. You can also check this answer or thread.

MySQL also converts BOOL, BOOLEAN data types to TINYINT(1).

Further, read documentation

Conversion failed when converting the varchar value to data type int in sql

Your problem seams to be located here:

SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,LEN(Voucher_No)- LEN(@Prefix)) AS INT)) AS varchar(100)) FROM dbo.Journal_Entry;
SET @sCode=CAST(@maxCode AS INT)

As the error says, you're casting a string that contains a letter 'J' to an INT which for obvious reasons is not possible.

Either fix SUBSTRING or don't store the letter 'J' in the database and only prepend it when reading.

Appropriate datatype for holding percent values?

Assuming two decimal places on your percentages, the data type you use depends on how you plan to store your percentages. If you are going to store their fractional equivalent (e.g. 100.00% stored as 1.0000), I would store the data in a decimal(5,4) data type with a CHECK constraint that ensures that the values never exceed 1.0000 (assuming that is the cap) and never go below 0 (assuming that is the floor). If you are going to store their face value (e.g. 100.00% is stored as 100.00), then you should use decimal(5,2) with an appropriate CHECK constraint. Combined with a good column name, it makes it clear to other developers what the data is and how the data is stored in the column.

Should I use the datetime or timestamp data type in MySQL?

A DATETIME carries no timezone information with it and will always display the same independent of the timezone that is in effect for the session, which defaults to the server's timezone unless you have explicitly changed it. However, if I initialize a DATETIME column with a function such as NOW() rather than a literal such as '2020-01-16 12:15:00', then the value stored will, of course, be the current date and time localized to the session's timezone.

A TIMESTAMP by contrast does implicitly carry timezone information: When you initialize a TIMESTAMP column with a value, that value is converted to UTC before it is stored. If the value being stored is a literal such as '2020-01-16 12:15:00', it is interpreted as being in the session's current timezone for conversion purposes. Conversely, when a TIMESTAMP column is displayed, it will first be converted from UTC to the session's current timezone.

When to use one or the other? A Case Study

A Website for a community theater group is presenting several performances of a play for which it is selling tickets. The dates and times of these performances will appear in a drop down from which a customer wishing to buy tickets for a performance will select one. It would make sense for database column performance_date_and_time to be a DATETIME type. If the performance is in New York, there is an understanding that there is an implicit timezone involved ("New York local time") and ideally we would want the date and time to display as 'December 12, 2019 at 8:00 PM' regardless of the session's timezone and without having to go to the trouble of having to do any timezone conversions.

On the other hand, once the December 12th, 2019 8 PM performance began, we might no longer want to sell tickets for it and thus no longer display that performance in the drop down. So, we would like to be able to know whether '2019-12-12 20:00:00' has occurred or not. That would argue for having a TIMESTAMP column, setting the timezone for the session to 'America/New_York' with set session time_zone='America/New_York' and then storing '2019-12-12 20:00:00' into the TIMESTAMP column. Henceforth we can test for whether the performance has begun by comparing this column with NOW() independent of the current session timezone.

Or it might make sense to have a DATETIME and a TIMESTAMP column for these two separate purposes. Or not. Clearly, either one could serve both purposes. If you go with just a DATETIME column, then you must set the current timezone to your local timezone before comparing with NOW(). If you go with just a TIMESTAMP column, you must set the session timezone to your local timezone before displaying the column.

How do you create a yes/no boolean field in SQL server?

You can use the data type bit

Values inserted which are greater than 0 will be stored as '1'

Values inserted which are less than 0 will be stored as '1'

Values inserted as '0' will be stored as '0'

This holds true for MS SQL Server 2012 Express

How to get a list column names and datatypes of a table in PostgreSQL?

To get information about the table's column, you can use:

\dt+ [tablename]

To get information about the datatype in the table, you can use:

\dT+ [datatype]

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

To answer you first question:
Yes, it means that 1 byte allocates for 1 character. Look at this example

SQL> conn / as sysdba
Connected.
SQL> create table test (id number(10), v_char varchar2(10));

Table created.

SQL> insert into test values(11111111111,'darshan');
insert into test values(11111111111,'darshan')
*
ERROR at line 1:
ORA-01438: value larger than specified precision allows for this column


SQL> insert into test values(11111,'darshandarsh');
insert into test values(11111,'darshandarsh')
*
ERROR at line 1:
ORA-12899: value too large for column "SYS"."TEST"."V_CHAR" (actual: 12,
maximum: 10)


SQL> insert into test values(111,'Darshan');

1 row created.

SQL> 

And to answer your next one: The difference between varchar2 and varchar :

  1. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.
  2. If we declare datatype as VARCHAR then it will occupy space for NULL values, In case of VARCHAR2 datatype it will not occupy any space.

What is the difference between varchar and varchar2 in Oracle?

Taken from the latest stable Oracle production version 12.2: Data Types

The major difference is that VARCHAR2 is an internal data type and VARCHAR is an external data type. So we need to understand the difference between an internal and external data type...

Inside a database, values are stored in columns in tables. Internally, Oracle represents data in particular formats known as internal data types.

In general, OCI (Oracle Call Interface) applications do not work with internal data type representations of data, but with host language data types that are predefined by the language in which they are written. When data is transferred between an OCI client application and a database table, the OCI libraries convert the data between internal data types and external data types.

External types provide a convenience for the programmer by making it possible to work with host language types instead of proprietary data formats. OCI can perform a wide range of data type conversions when transferring data between an Oracle database and an OCI application. There are more OCI external data types than Oracle internal data types.

The VARCHAR2 data type is a variable-length string of characters with a maximum length of 4000 bytes. If the init.ora parameter max_string_size is default, the maximum length of a VARCHAR2 can be 4000 bytes. If the init.ora parameter max_string_size = extended, the maximum length of a VARCHAR2 can be 32767 bytes

The VARCHAR data type stores character strings of varying length. The first 2 bytes contain the length of the character string, and the remaining bytes contain the string. The specified length of the string in a bind or a define call must include the two length bytes, so the largest VARCHAR string that can be received or sent is 65533 bytes long, not 65535.

A quick test in a 12.2 database suggests that as an internal data type, Oracle still treats a VARCHAR as a pseudotype for VARCHAR2. It is NOT a SYNONYM which is an actual object type in Oracle.

SQL> select substr(banner,1,80) from v$version where rownum=1;
Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production    

SQL> create table test (my_char varchar(20));
Table created.

SQL> desc test
Name                 Null?    Type
MY_CHAR                       VARCHAR2(20)

There are also some implications of VARCHAR for ProC/C++ Precompiler options. For programmers who are interested, the link is at: Pro*C/C++ Programmer's Guide

Best data type for storing currency values in a MySQL database

It is also important to work out how many decimal places maybe required for your calculations.

I worked on a share price application that required the calculation of the price of one million shares. The quoted share price had to be stored to 7 digits of accuracy.

Is there any difference between DECIMAL and NUMERIC in SQL Server?

Joakim Backman's answer is specific, but this may bring additional clarity to it.

There is a minor difference. As per SQL For Dummies, 8th Edition (2013):

The DECIMAL data type is similar to NUMERIC. ... The difference is that your implementation may specify a precision greater than what you specify — if so, the implementation uses the greater precision. If you do not specify precision or scale, the implementation uses default values, as it does with the NUMERIC type.

It seems that the difference on some implementations of SQL is in data integrity. DECIMAL allows overflow from what is defined based on some system defaults, where as NUMERIC does not.

Check if $_POST exists

isset($_POST['fromPerson']) 

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

When you define a Foreign Key in table B referencing the Primary Key of table A it means that when a value is in B, it must be in A. This is to prevent unconsistent modifications to the tables.

In your example, your tables contain:

tblDomare with PRIMARY KEY (PersNR):

PersNR     |fNamn     |eNamn      |Erfarenhet
-----------|----------|-----------|----------
6811034679 |'Bengt'   |'Carlberg' |10
7606091347 |'Josefin' |'Backman'  |4
8508284163 |'Johanna' |'Backman'  |1
---------------------------------------------

tblBana:

BanNR
-----
1
2
3
-----

This statement:

ALTER TABLE tblDomare
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);

says that any line in tblDomare with key PersNR must have a correspondence in table tblBana on key BanNR. Your error is because you have lines inserted in tblDomare with no correspondence in tblBana.

2 solutions to fix your issue:

  • either add lines in tblBana with BanNR in (6811034679, 7606091347, 8508284163)
  • or remove all lines in tblDomare that have no correspondence in tblBana (but your table would be empty)

General advice: you should have the Foreign Key constraint before populating the tables. Foreign keys are here to prevent the user of the table from filling the tables with inconsistencies.

How to restart a single container with docker-compose

Simple 'docker' command knows nothing about 'worker' container. Use command like this

docker-compose -f docker-compose.yml restart worker

How To fix white screen on app Start up?

White background is caused because of the Android starts while the app loads on memory, and it can be avoided if you just add this 2 line of code under SplashTheme.

<item name="android:windowDisablePreview">true</item>
<item name="android:windowIsTranslucent">true</item>

Moment.js - two dates difference in number of days

From the moment.js docs: format('E') stands for day of week. thus your diff is being computed on which day of the week, which has to be between 1 and 7.

From the moment.js docs again, here is what they suggest:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

Here is a JSFiddle for your particular case:

_x000D_
_x000D_
$('#test').click(function() {_x000D_
  var startDate = moment("13.04.2016", "DD.MM.YYYY");_x000D_
  var endDate = moment("28.04.2016", "DD.MM.YYYY");_x000D_
_x000D_
  var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
  $('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: #ffb;_x000D_
  padding: 10px;_x000D_
  border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
_x000D_
_x000D_

What is a blob URL and why it is used?

This Javascript function purports to show the difference between the Blob File API and the Data API to download a JSON file in the client browser:

_x000D_
_x000D_
/**_x000D_
 * Save a text as file using HTML <a> temporary element and Blob_x000D_
 * @author Loreto Parisi_x000D_
 */_x000D_
_x000D_
var saveAsFile = function(fileName, fileContents) {_x000D_
    if (typeof(Blob) != 'undefined') { // Alternative 1: using Blob_x000D_
        var textFileAsBlob = new Blob([fileContents], {type: 'text/plain'});_x000D_
        var downloadLink = document.createElement("a");_x000D_
        downloadLink.download = fileName;_x000D_
        if (window.webkitURL != null) {_x000D_
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);_x000D_
        } else {_x000D_
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);_x000D_
            downloadLink.onclick = document.body.removeChild(event.target);_x000D_
            downloadLink.style.display = "none";_x000D_
            document.body.appendChild(downloadLink);_x000D_
        }_x000D_
        downloadLink.click();_x000D_
    } else { // Alternative 2: using Data_x000D_
        var pp = document.createElement('a');_x000D_
        pp.setAttribute('href', 'data:text/plain;charset=utf-8,' +_x000D_
            encodeURIComponent(fileContents));_x000D_
        pp.setAttribute('download', fileName);_x000D_
        pp.onclick = document.body.removeChild(event.target);_x000D_
        pp.click();_x000D_
    }_x000D_
} // saveAsFile_x000D_
_x000D_
/* Example */_x000D_
var jsonObject = {"name": "John", "age": 30, "car": null};_x000D_
saveAsFile('out.json', JSON.stringify(jsonObject, null, 2));
_x000D_
_x000D_
_x000D_

The function is called like saveAsFile('out.json', jsonString);. It will create a ByteStream immediately recognized by the browser that will download the generated file directly using the File API URL.createObjectURL.

In the else, it is possible to see the same result obtained via the href element plus the Data API, but this has several limitations that the Blob API has not.

Extract number from string with Oracle function

If you are looking for 1st Number with decimal as string has correct decimal places, you may try regexp_substr function like this:

regexp_substr('stack12.345overflow', '\.*[[:digit:]]+\.*[[:digit:]]*')

How to retrieve the first word of the output of a command in bash?

As perl incorporates awk's functionality this can be solved with perl too:

echo " word1 word2" | perl -lane 'print $F[0]'

Android soft keyboard covers EditText field

If EditText Field is been covered by the KeyBoard Use the following code:

    EditText= findViewById(R.id.edittext)
    EditText?.getParent()?.requestChildFocus(EditText,EditText)

If you want the Cursor to be in the Focused EditText than use EditText.requestFocus() after the EditText?.getParent()?.requestChildFocus(EditText,EditText) which helps to get the focus and Cursor in the Focused EditText.

How to move all files including hidden files into parent directory via *

I think this is the most elegant, as it also does not try to move ..:

mv /source/path/{.[!.],}* /destination/path

JavaScript module pattern with example

Here https://toddmotto.com/mastering-the-module-pattern you can find the pattern thoroughly explained. I would add that the second thing about modular JavaScript is how to structure your code in multiple files. Many folks may advice you here to go with AMD, yet I can say from experience that you will end up on some point with slow page response because of numerous HTTP requests. The way out is pre-compilation of your JavaScript modules (one per file) into a single file following CommonJS standard. Take a look at samples here http://dsheiko.github.io/cjsc/

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

Ben is right. I also can't think of any way to do this. I'd suggest either the method Ben recommends, or the following to strip the Workbook name off.

Dim cell As Range
Dim address As String
Set cell = Worksheets(1).Cells.Range("A1")
address = cell.address(External:=True)
address = Right(address, Len(address) - InStr(1, address, "]"))

Why do we need the "finally" clause in Python?

You can use finally to make sure files or resources are closed or released regardless of whether an exception occurs, even if you don't catch the exception. (Or if you don't catch that specific exception.)

myfile = open("test.txt", "w")

try:
    myfile.write("the Answer is: ")
    myfile.write(42)   # raises TypeError, which will be propagated to caller
finally:
    myfile.close()     # will be executed before TypeError is propagated

In this example you'd be better off using the with statement, but this kind of structure can be used for other kinds of resources.

A few years later, I wrote a blog post about an abuse of finally that readers may find amusing.

Cannot catch toolbar home button click event

If you want to know when home is clicked is an AppCompatActivity then you should try it like this:

First tell Android you want to use your Toolbar as your ActionBar:

setSupportActionBar(toolbar);

Then set Home to be displayed via setDisplayShowHomeEnabled like this:

getSupportActionBar().setDisplayShowHomeEnabled(true);

Finally listen for click events on android.R.id.home like usual:

@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
    if (menuItem.getItemId() == android.R.id.home) {
        Timber.d("Home pressed");
    }
    return super.onOptionsItemSelected(menuItem);
}

If you want to know when the navigation button is clicked on a Toolbar in a class other than AppCompatActivity you can use these methods to set a navigation icon and listen for click events on it. The navigation icon will appear on the left side of your Toolbar where the the "home" button used to be.

toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_nav_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d("cek", "home selected");
    }
});

If you want to know when the hamburger is clicked and when the drawer opens, you're already listening for these events via onDrawerOpened and onDrawerClosed so you'll want to see if those callbacks fit your requirements.

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

The SSL errors are often thrown by network management software such as Cyberroam.

To answer your question,

you will have to enter badidea into Chrome every time you visit a website.

You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors

Making Enter key on an HTML form submit instead of activating button

You don't need JavaScript to choose your default submit button or input. You just need to mark it up with type="submit", and the other buttons mark them with type="button". In your example:

<button type="button" onclick="return myFunc1()">Button 1</button>
<input type="submit" name="go" value="Submit"/>

How to tell if a string is not defined in a Bash shell script

Advanced bash scripting guide, 10.2. Parameter Substitution:

  • ${var+blahblah}: if var is defined, 'blahblah' is substituted for the expression, else null is substituted
  • ${var-blahblah}: if var is defined, it is itself substituted, else 'blahblah' is substituted
  • ${var?blahblah}: if var is defined, it is substituted, else the function exists with 'blahblah' as an error message.


to base your program logic on whether the variable $mystr is defined or not, you can do the following:

isdefined=0
${mystr+ export isdefined=1}

now, if isdefined=0 then the variable was undefined, if isdefined=1 the variable was defined

This way of checking variables is better than the above answer because it is more elegant, readable, and if your bash shell was configured to error on the use of undefined variables (set -u), the script will terminate prematurely.


Other useful stuff:

to have a default value of 7 assigned to $mystr if it was undefined, and leave it intact otherwise:

mystr=${mystr- 7}

to print an error message and exit the function if the variable is undefined:

: ${mystr? not defined}

Beware here that I used ':' so as not to have the contents of $mystr executed as a command in case it is defined.

"document.getElementByClass is not a function"

The getElementByClass does not exists, probably you want to use getElementsByClassName. However you can use alternative approach (used in angular/vue/react... templates)

_x000D_
_x000D_
function stop(ta) {_x000D_
  console.log(ta.value) // document['player'].stopMusicExt(ta.value);_x000D_
  ta.value='';_x000D_
}
_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 1'>_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 2'>
_x000D_
_x000D_
_x000D_

Redirect to an external URL from controller action in Spring MVC

In short "redirect://yahoo.com" will lend you to yahoo.com.

where as "redirect:yahoo.com" will lend you your-context/yahoo.com ie for ex- localhost:8080/yahoo.com

Switch on Enum in Java

You actually can switch on enums, but you can't switch on Strings until Java 7. You might consider using polymorphic method dispatch with Java enums rather than an explicit switch. Note that enums are objects in Java, not just symbols for ints like they are in C/C++. You can have a method on an enum type, then instead of writing a switch, just call the method - one line of code: done!

enum MyEnum {
    SOME_ENUM_CONSTANT {
        @Override
        public void method() {
            System.out.println("first enum constant behavior!");
        }
    },
    ANOTHER_ENUM_CONSTANT {
        @Override
        public void method() {
            System.out.println("second enum constant behavior!");
        }
    }; // note the semi-colon after the final constant, not just a comma!
    public abstract void method(); // could also be in an interface that MyEnum implements
}

void aMethodSomewhere(final MyEnum e) {
    doSomeStuff();
    e.method(); // here is where the switch would be, now it's one line of code!
    doSomeOtherStuff();
}

What does "control reaches end of non-void function" mean?

Always build with at least minimal optimization. With -O0, all analysis that the compiler could use to determine that execution cannot reach the end of the function has been disabled. This is why you're seeing the warning. The only time you should ever use -O0 is for step-by-line debugging, which is usually not a good debugging approach anyway, but it's what most people who got started with MSVC learned on...

How can I compare strings in C using a `switch` statement?

I think the best way to do this is separate the 'recognition' from the functionality:

struct stringcase { char* string; void (*func)(void); };

void funcB1();
void funcAzA();

stringcase cases [] = 
{ { "B1", funcB1 }
, { "AzA", funcAzA }
};

void myswitch( char* token ) {
  for( stringcases* pCase = cases
     ; pCase != cases + sizeof( cases ) / sizeof( cases[0] )
     ; pCase++ )
  {
    if( 0 == strcmp( pCase->string, token ) ) {
       (*pCase->func)();
       break;
    }
  }

}

Send data from a textbox into Flask?

Declare a Flask endpoint to accept POST input type and then do necessary steps. Use jQuery to post the data.

from flask import request

@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data(data):
    if request.method == "POST":
         #perform action here
var value = $('.textbox').val();
$.ajax({
  type: 'POST',
  url: "{{ url_for('parse_data') }}",
  data: JSON.stringify(value),
  contentType: 'application/json',
  success: function(data){
    // do something with the received data
  }
});

How to print exact sql query in zend framework ?

Select objects have a __toString() method in Zend Framework.

From the Zend Framework manual:

$select = $db->select()
             ->from('products');

$sql = $select->__toString();
echo "$sql\n";

// The output is the string:
//   SELECT * FROM "products"

An alternative solution would be to use the Zend_Db_Profiler. i.e.

$db->getProfiler()->setEnabled(true);

// your code
$this->update($up_value,'customer_id ='.$userid.' and address_id <> '.$data['address_Id']); 

Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQuery());
Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQueryParams());
$db->getProfiler()->setEnabled(false);

http://framework.zend.com/manual/en/zend.db.select.html

Count how many rows have the same value

If you want to have the result for all values of NUM:

SELECT `NUM`, COUNT(*) AS `count` 
FROM yourTable
GROUP BY `NUM`

Or just for one specific:

SELECT `NUM`, COUNT(*) AS `count` 
FROM yourTable
WHERE `NUM`=1

Convert UIImage to NSData and convert back to UIImage in Swift?

Use imageWithData: method, which gets translated to Swift as UIImage(data:)

let image : UIImage = UIImage(data: imageData)

Singletons vs. Application Context in Android?

Consider both at the same time:

  • having singleton objects as static instances inside the classes.
  • having a common class (Context) that returns the singleton instances for all the singelton objects in your application, which has the advantage that the method names in Context will be meaningful for example: context.getLoggedinUser() instead of User.getInstance().

Furthermore, I suggest that you expand your Context to include not only access to singleton objects but some functionalities that need to be accessed globally, like for example: context.logOffUser(), context.readSavedData(), etc. Probably renaming the Context to Facade would make sense then.

How to download fetch response in react as file

I have faced the same problem once too. I have solved it by creating on empty link with a ref to it like so:

linkRef = React.createRef();
render() {
    return (
        <a ref={this.linkRef}/>
    );
}

and in my fetch function i have done something like this:

fetch(/*your params*/)
    }).then(res => {
        return res.blob();
    }).then(blob => {
        const href = window.URL.createObjectURL(blob);
        const a = this.linkRef.current;
        a.download = 'Lebenslauf.pdf';
        a.href = href;
        a.click();
        a.href = '';
    }).catch(err => console.error(err));

basically i have assigned the blobs url(href) to the link, set the download attribute and enforce one click on the link. As far as i understand this is the "basic" idea of the answer provided by @Nate. I dont know if this is a good idea to do it this way... I did.

Google Maps API v3: Can I setZoom after fitBounds?

I use this to ensure the zoom level does not exceed a set level so that I know satellite images will be available.

Add a listener to the zoom_changed event. This has the added benefit of controlling the zoom control on the UI also.

Only execute setZoom if you need to, so an if statement is preferable to Math.max or to Math.min

   google.maps.event.addListener(map, 'zoom_changed', function() { 
      if ( map.getZoom() > 19 ) { 
        map.setZoom(19); 
      } 
    });
    bounds = new google.maps.LatLngBounds( ... your bounds ... )
    map.fitBounds(bounds);

To prevent zooming out too far:

   google.maps.event.addListener(map, 'zoom_changed', function() { 
      if ( map.getZoom() < 6 ) { 
        map.setZoom(6); 
      } 
    });
    bounds = new google.maps.LatLngBounds( ... your bounds ... )
    map.fitBounds(bounds);

Visual Studio popup: "the operation could not be completed"

Restarting Visual Studio solved my problem :)

Close a div by clicking outside

An other way which makes then your jsfiddle less buggy (needed double click on open).

This doesn't use any delegated event to body level

Set tabindex="-1" to DIV .popup ( and for style CSS outline:0 )

DEMO

$(".link").click(function(e){
    e.preventDefault();
    $(".popup").fadeIn(300,function(){$(this).focus();});
});

$('.close').click(function() {
   $(".popup").fadeOut(300);
});
$(".popup").on('blur',function(){
    $(this).fadeOut(300);
});

ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

For me the problem was that I was using different versions of Python in the same Eclipse project. My setup was not consistent with the Project Properties and the Run Configuration Python versions.

In Project > Properties > PyDev, I had the Interpreter set to Python2.7.11.

In Run Configurations > Interpreter, I was using the Default Interpreter. Changing it to Python 2.7.11 fixed the problem.

Creating layout constraints programmatically

When using Auto Layout in code, setting the frame does nothing. So the fact that you specified a width of 200 on the view above, doesn't mean anything when you set constraints on it. In order for a view's constraint set to be unambiguous, it needs four things: an x-position, a y-position, a width, and a height for any given state.

Currently in the code above, you only have two (height, relative to the superview, and y-position, relative to the superview). In addition to this, you have two required constraints that could conflict depending on how the view's superview's constraints are setup. If the superview were to have a required constraint that specifies it's height be some value less than 748, you will get an "unsatisfiable constraints" exception.

The fact that you've set the width of the view before setting constraints means nothing. It will not even take the old frame into account and will calculate a new frame based on all of the constraints that it has specified for those views. When dealing with autolayout in code, I typically just create a new view using initWithFrame:CGRectZero or simply init.

To create the constraint set required for the layout you verbally described in your question, you would need to add some horizontal constraints to bound the width and x-position in order to give a fully-specified layout:

[self.view addConstraints:[NSLayoutConstraint
    constraintsWithVisualFormat:@"V:|-[myView(>=748)]-|"
    options:NSLayoutFormatDirectionLeadingToTrailing
    metrics:nil
    views:NSDictionaryOfVariableBindings(myView)]];

[self.view addConstraints:[NSLayoutConstraint
    constraintsWithVisualFormat:@"H:[myView(==200)]-|"
    options:NSLayoutFormatDirectionLeadingToTrailing
    metrics:nil
    views:NSDictionaryOfVariableBindings(myView)]];

Verbally describing this layout reads as follows starting with the vertical constraint:

myView will fill its superview's height with a top and bottom padding equal to the standard space. myView's superview has a minimum height of 748pts. myView's width is 200pts and has a right padding equal to the standard space against its superview.

If you would simply like the view to fill the entire superview's height without constraining the superview's height, then you would just omit the (>=748) parameter in the visual format text. If you think that the (>=748) parameter is required to give it a height - you don't in this instance: pinning the view to the superview's edges using the bar (|) or bar with space (|-, -|) syntax, you are giving your view a y-position (pinning the view on a single-edge), and a y-position with height (pinning the view on both edges), thus satisfying your constraint set for the view.

In regards to your second question:

Using NSDictionaryOfVariableBindings(self.myView) (if you had an property setup for myView) and feeding that into your VFL to use self.myView in your VFL text, you will probably get an exception when autolayout tries to parse your VFL text. It has to do with the dot notation in dictionary keys and the system trying to use valueForKeyPath:. See here for a similar question and answer.

How to update /etc/hosts file in Docker image during "docker build"

Just a quick answer to run your container using:

docker exec -it <container name> /bin/bash

once the container is open:

cd ..

then

`cd etc`

and then you can

cat hosts

or:

apt-get update
apt-get vim

or any editor you like and open it in vim, here you can modify say your startup ip to 0.0.0.0

How to unzip a list of tuples into individual lists?

If you want a list of lists:

>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]

If a list of tuples is OK:

>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]

What's the difference between & and && in MATLAB?

Both are logical AND operations. The && though, is a "short-circuit" operator. From the MATLAB docs:

They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.

See more here.

fatal: does not appear to be a git repository

I had a similar problem when using TFS 2017. I was not able to push or pull GIT repositories. Eventually I reinstalled TFS 2017, making sure that I installed TFS 2017 with an SSH Port different from 22 (in my case, I chose 8022). After that, push and pull became possible against TFS using SSH.

How to sort a list of objects based on an attribute of the objects?

# To sort the list in place...
ut.sort(key=lambda x: x.count, reverse=True)

# To return a new list, use the sorted() built-in function...
newlist = sorted(ut, key=lambda x: x.count, reverse=True)

More on sorting by keys.

Export to CSV via PHP

Just for the record, concatenation is waaaaaay faster (I mean it) than fputcsv or even implode; And the file size is smaller:

// The data from Eternal Oblivion is an object, always
$values = (array) fetchDataFromEternalOblivion($userId, $limit = 1000);

// ----- fputcsv (slow)
// The code of @Alain Tiemblo is the best implementation
ob_start();
$csv = fopen("php://output", 'w');
fputcsv($csv, array_keys(reset($values)));
foreach ($values as $row) {
    fputcsv($csv, $row);
}
fclose($csv);
return ob_get_clean();

// ----- implode (slow, but file size is smaller)
$csv = implode(",", array_keys(reset($values))) . PHP_EOL;
foreach ($values as $row) {
    $csv .= '"' . implode('","', $row) . '"' . PHP_EOL;
}
return $csv;
// ----- concatenation (fast, file size is smaller)
// We can use one implode for the headers =D
$csv = implode(",", array_keys(reset($values))) . PHP_EOL;
$i = 1;
// This is less flexible, but we have more control over the formatting
foreach ($values as $row) {
    $csv .= '"' . $row['id'] . '",';
    $csv .= '"' . $row['name'] . '",';
    $csv .= '"' . date('d-m-Y', strtotime($row['date'])) . '",';
    $csv .= '"' . ($row['pet_name'] ?: '-' ) . '",';
    $csv .= PHP_EOL;
}
return $csv;

This is the conclusion of the optimization of several reports, from ten to thousands rows. The three examples worked fine under 1000 rows, but fails when the data was bigger.

Create a CSV File for a user in PHP

Create your file then return a reference to it with the correct header to trigger the Save As - edit the following as needed. Put your CSV data into $csvdata.

$fname = 'myCSV.csv';
$fp = fopen($fname,'wb');
fwrite($fp,$csvdata);
fclose($fp);

header('Content-type: application/csv');
header("Content-Disposition: inline; filename=".$fname);
readfile($fname);

C# HttpClient 4.5 multipart/form-data upload

my result looks like this:

public static async Task<string> Upload(byte[] image)
{
     using (var client = new HttpClient())
     {
         using (var content =
             new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
         {
             content.Add(new StreamContent(new MemoryStream(image)), "bilddatei", "upload.jpg");

              using (
                 var message =
                     await client.PostAsync("http://www.directupload.net/index.php?mode=upload", content))
              {
                  var input = await message.Content.ReadAsStringAsync();

                  return !string.IsNullOrWhiteSpace(input) ? Regex.Match(input, @"http://\w*\.directupload\.net/images/\d*/\w*\.[a-z]{3}").Value : null;
              }
          }
     }
}

How to continue a Docker container which has exited

If you have a named container then it can be started by running

docker container start container_name

where container_name is name of the container that must be given at the time of creating container. You can replace container_name with the container id in case the container is not named. The container ID can be found by running:

docker ps -a

How to create a remote Git repository from a local one?

You need to create a directory on a remote server. Then use "git init" command to set it as a repository. This should be done for each new project you have (each new folder)

Assuming you have already setup and used git using ssh keys, I wrote a small Python script, which when executed from a working directory will set up a remote and initialize the directory as a git repo. Of course, you will have to edit script (only once) to tell it server and Root path for all repositories.

Check here - https://github.com/skbobade/ocgi

Best way to format if statement with multiple conditions

In Perl you could do this:

{
  ( VeryLongCondition_1 ) or last;
  ( VeryLongCondition_2 ) or last;
  ( VeryLongCondition_3 ) or last;
  ( VeryLongCondition_4 ) or last;
  ( VeryLongCondition_5 ) or last;
  ( VeryLongCondition_6 ) or last;

  # Guarded code goes here
}

If any of the conditions fail it will just continue on, after the block. If you are defining any variables that you want to keep around after the block, you will need to define them before the block.

How do I return JSON without using a template in Django?

I think the issue has gotten confused regarding what you want. I imagine you're not actually trying to put the HTML in the JSON response, but rather want to alternatively return either HTML or JSON.

First, you need to understand the core difference between the two. HTML is a presentational format. It deals more with how to display data than the data itself. JSON is the opposite. It's pure data -- basically a JavaScript representation of some Python (in this case) dataset you have. It serves as merely an interchange layer, allowing you to move data from one area of your app (the view) to another area of your app (your JavaScript) which normally don't have access to each other.

With that in mind, you don't "render" JSON, and there's no templates involved. You merely convert whatever data is in play (most likely pretty much what you're passing as the context to your template) to JSON. Which can be done via either Django's JSON library (simplejson), if it's freeform data, or its serialization framework, if it's a queryset.

simplejson

from django.utils import simplejson

some_data_to_dump = {
   'some_var_1': 'foo',
   'some_var_2': 'bar',
}

data = simplejson.dumps(some_data_to_dump)

Serialization

from django.core import serializers

foos = Foo.objects.all()

data = serializers.serialize('json', foos)

Either way, you then pass that data into the response:

return HttpResponse(data, content_type='application/json')

[Edit] In Django 1.6 and earlier, the code to return response was

return HttpResponse(data, mimetype='application/json')

[EDIT]: simplejson was remove from django, you can use:

import json

json.dumps({"foo": "bar"})

Or you can use the django.core.serializers as described above.

DataTables: Cannot read property style of undefined

POSSIBLE CAUSES

  • Number of th elements in the table header or footer differs from number of columns in the table body or defined using columns option.
  • Attribute colspan is used for th element in the table header.
  • Incorrect column index specified in columnDefs.targets option.

SOLUTIONS

  • Make sure that number of th elements in the table header or footer matches number of columns defined in the columns option.
  • If you use colspan attribute in the table header, make sure you have at least two header rows and one unique th element for each column. See Complex header for more information.
  • If you use columnDefs.targets option, make sure that zero-based column index refers to existing columns.

LINKS

See jQuery DataTables: Common JavaScript console errors - TypeError: Cannot read property ‘style’ of undefined for more information.

Resize UIImage and change the size of UIImageView

I think what you want is a different content mode. Try using UIViewContentModeScaleToFill. This will scale the content to fit the size of ur UIImageView by changing the aspect ratio of the content if necessary.

Have a look to the content mode section on the official doc to get a better idea of the different content mode available (it is illustrated with images).

How can I delete a service in Windows?

Use services.msc or (Start > Control Panel > Administrative Tools > Services) to find the service in question. Double-click to see the service name and the path to the executable.

Check the exe version information for a clue as to the owner of the service, and use Add/Remove programs to do a clean uninstall if possible.

Failing that, from the command prompt:

sc stop servicexyz
sc delete servicexyz

No restart should be required.

Passing an array by reference in C?

In C arrays are passed as a pointer to the first element. They are the only element that is not really passed by value (the pointer is passed by value, but the array is not copied). That allows the called function to modify the contents.

void reset( int *array, int size) {
   memset(array,0,size * sizeof(*array));
}
int main()
{
   int array[10];
   reset( array, 10 ); // sets all elements to 0
}

Now, if what you want is changing the array itself (number of elements...) you cannot do it with stack or global arrays, only with dynamically allocated memory in the heap. In that case, if you want to change the pointer you must pass a pointer to it:

void resize( int **p, int size ) {
   free( *p );
   *p = malloc( size * sizeof(int) );
}
int main() {
   int *p = malloc( 10 * sizeof(int) );
   resize( &p, 20 );
}

In the question edit you ask specifically about passing an array of structs. You have two solutions there: declare a typedef, or make explicit that you are passing an struct:

struct Coordinate {
   int x;
   int y;
};
void f( struct Coordinate coordinates[], int size );
typedef struct Coordinate Coordinate;  // generate a type alias 'Coordinate' that is equivalent to struct Coordinate
void g( Coordinate coordinates[], int size ); // uses typedef'ed Coordinate

You can typedef the type as you declare it (and it is a common idiom in C):

typedef struct Coordinate {
   int x;
   int y;
} Coordinate;

How to get current moment in ISO 8601 format with date, hour, and minute?

As of Java 8 you can simply do:

Instant.now().toString();

From the java.time.Instant docs:

now

public static Instant now()

Obtains the current instant from the system clock.

This will query the system UTC clock to obtain the current instant.

 

toString

public String toString()

A string representation of this instant using ISO-8601 representation.

The format used is the same as DateTimeFormatter.ISO_INSTANT.

Get all mysql selected rows into an array

you can call mysql_fetch_array() for no_of_row time

How to extract Month from date in R

you can convert it into date format by-

new_date<- as.Date(old_date, "%m/%d/%Y")} 

from new_date, you can get the month by strftime()

month<- strftime(new_date, "%m")

old_date<- "01/01/1979"
new_date<- as.Date(old_date, "%m/%d/%Y")
new_date
#[1] "1979-01-01"
month<- strftime(new_date,"%m")
month
#[1] "01"
year<- strftime(new_date, "%Y")
year
#[1] "1979"

Difference between angle bracket < > and double quotes " " while including header files in C++?

It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the specification (Section 6.10.2):

A preprocessing directive of the form

  # include <h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

  # include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

  # include <h-char-sequence> new-line

with the identical contained sequence (including > characters, if any) from the original directive.

So on most compilers, using the "" first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <> starts the search with system headers.

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Normally, you run IE 32 bit.
However, on 64-bit versions of Windows, there is a separate link in the Start Menu to Internet Explorer (64 bit). There's no real reason to use it, though.

In Help, About, the 64-bit version of IE will say 64-bit Edition (just after the full version string).

The 32-bit and 64-bit versions of IE have separate addons lists (because 32-bit addons cannot be loaded in 64-bit IE, and vice-versa), so you should make sure that Java appears on both lists.

In general, you can tell whether a process is 32-bit or 64-bit by right-clicking the application in Task Manager and clicking Go To Process. 32-bit processes will end with *32.

Create an empty object in JavaScript with {} or new Object()?

Var Obj = {};

This is the most used and simplest method.

Using

var Obj = new Obj() 

is not preferred.

There is no need to use new Object().

For simplicity, readability and execution speed, use the first one (the object literal method).

Origin is not allowed by Access-Control-Allow-Origin

You may make it work without modifiying the server by making the broswer including the header Access-Control-Allow-Origin: * in the HTTP OPTIONS' responses.

In Chrome, use this extension. If you are on Mozilla check this answer.

download file using an ajax request

Decoding a filename from the header is a little bit more complex...

    var filename = "default.pdf";
    var disposition = req.getResponseHeader('Content-Disposition');

    if (disposition && disposition.indexOf('attachment') !== -1) 
    {
       var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
       var matches = filenameRegex.exec(disposition);

       if (matches != null && matches[1]) 
           filename = matches[1].replace(/['"]/g, '');
    }

Overwriting my local branch with remote branch

git reset --hard

This is to revert all your local changes to the origin head

Py_Initialize fails - unable to load the file system codec

From python3k, the startup need the encodings module, which can be found in PYTHONHOME\Lib directory. In fact, the API Py_Initialize () do the init and import the encodings module. Make sure PYTHONHOME\Lib is in sys.path and check the encodings module is there.

Only Add Unique Item To List

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T> on the custom class or overriding the Equals. It's a good idea to also implement GetHashCode in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

grep exclude multiple strings

Two examples of filtering out multiple lines with grep:

Put this in filename.txt:

abc
def
ghi
jkl

grep command using -E option with a pipe between tokens in a string:

grep -Ev 'def|jkl' filename.txt

prints:

abc
ghi

Command using -v option with pipe between tokens surrounded by parens:

egrep -v '(def|jkl)' filename.txt

prints:

abc
ghi

How to get a certain element in a list, given the position?

Not very efficient, but if you must use a list, you can deference the iterator

*myList.begin()+N

How to redirect output to a file and stdout

$ program [arguments...] 2>&1 | tee outfile

2>&1 dumps the stderr and stdout streams. tee outfile takes the stream it gets and writes it to the screen and to the file "outfile".

This is probably what most people are looking for. The likely situation is some program or script is working hard for a long time and producing a lot of output. The user wants to check it periodically for progress, but also wants the output written to a file.

The problem (especially when mixing stdout and stderr streams) is that there is reliance on the streams being flushed by the program. If, for example, all the writes to stdout are not flushed, but all the writes to stderr are flushed, then they'll end up out of chronological order in the output file and on the screen.

It's also bad if the program only outputs 1 or 2 lines every few minutes to report progress. In such a case, if the output was not flushed by the program, the user wouldn't even see any output on the screen for hours, because none of it would get pushed through the pipe for hours.

Update: The program unbuffer, part of the expect package, will solve the buffering problem. This will cause stdout and stderr to write to the screen and file immediately and keep them in sync when being combined and redirected to tee. E.g.:

$ unbuffer program [arguments...] 2>&1 | tee outfile

Turn off iPhone/Safari input element rounding

I used a simple border-radius: 0; to remove the rounded corners for the text input types.

text-align: right on <select> or <option>

The best solution for me was to make

select {
    direction: rtl;
}

and then

option {
    direction: ltr;
}

again. So there is no change in how the text is read in a screen reader or and no formatting-problem.

@UniqueConstraint annotation in Java

   @Entity @Table(name = "stock", catalog = "mkyongdb",
   uniqueConstraints = @UniqueConstraint(columnNames =
   "STOCK_NAME"),@UniqueConstraint(columnNames = "STOCK_CODE") }) public
   class Stock implements java.io.Serializable {

   }

Unique constraints used only for creating composite key ,which will be unique.It will represent the table as primary key combined as unique.

Add vertical scroll bar to panel

Try this instead for 'only' scrolling vertical.
(auto scroll needs to be false before it will accept changes)

mypanel.AutoScroll = false;
mypanel.HorizontalScroll.Enabled = false;
mypanel.HorizontalScroll.Visible = false;
mypanel.HorizontalScroll.Maximum = 0;
mypanel.AutoScroll = true;

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

jeues answer helped me nothing :-( after hours I finally found the solution for my system and I think this will help other people too. I had to set the LD_LIBRARY_PATH like this:

   export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/

after that everything worked very well, even without any "-extension RANDR" switch.

Dependency injection with Jersey 2.0

Late but I hope this helps someone.

I have my JAX RS defined like this:

@Path("/examplepath")
@RequestScoped //this make the diference
public class ExampleResource {

Then, in my code finally I can inject:

@Inject
SomeManagedBean bean;

In my case, the SomeManagedBean is an ApplicationScoped bean.

Hope this helps to anyone.

jquery fill dropdown with json data

Here is an example of code, that attempts to featch AJAX data from /Ajax/_AjaxGetItemListHelp/ URL. Upon success, it removes all items from dropdown list with id = OfferTransModel_ItemID and then it fills it with new items based on AJAX call's result:

if (productgrpid != 0) {    
    $.ajax({
        type: "POST",
        url: "/Ajax/_AjaxGetItemListHelp/",
        data:{text:"sam",OfferTransModel_ItemGrpid:productgrpid},
        contentType: "application/json",              
        dataType: "json",
        success: function (data) {
            $("#OfferTransModel_ItemID").empty();

            $.each(data, function () {
                $("#OfferTransModel_ItemID").append($("<option>                                                      
                </option>").val(this['ITEMID']).html(this['ITEMDESC']));
            });
        }
    });
}

Returned AJAX result is expected to return data encoded as AJAX array, where each item contains ITEMID and ITEMDESC elements. For example:

{
    {
        "ITEMID":"13",
        "ITEMDESC":"About"
    },
    {
        "ITEMID":"21",
        "ITEMDESC":"Contact"
    }
}

The OfferTransModel_ItemID listbox is populated with above data and its code should look like:

<select id="OfferTransModel_ItemID" name="OfferTransModel[ItemID]">
    <option value="13">About</option>
    <option value="21">Contact</option>
</select>

When user selects About, form submits 13 as value for this field and 21 when user selects Contact and so on.

Fell free to modify above code if your server returns URL in a different format.

Detecting arrow key presses in JavaScript

Arrow Keys are triggered on keyup

$(document).on("keyup", "body", function(e) {
 if (e.keyCode == 38) {
    // up arrow
    console.log("up arrow")
  }
  if (e.keyCode == 40) {
      // down arrow
      console.log("down arrow")
  }
  if (e.keyCode == 37) {
    // left arrow
    console.log("lefy arrow")
  }
  if (e.keyCode == 39) {
    // right arrow
    console.log("right arrow")
  }
})

onkeydown allows ctrl, alt, shits

onkeyup allows tab, up arrows, down arrows, left arrows, down arrows

How to serialize Joda DateTime with Jackson JSON processor?

In the object you're mapping:

@JsonSerialize(using = CustomDateSerializer.class)
public DateTime getDate() { ... }

In CustomDateSerializer:

public class CustomDateSerializer extends JsonSerializer<DateTime> {

    private static DateTimeFormatter formatter = 
        DateTimeFormat.forPattern("dd-MM-yyyy");

    @Override
    public void serialize(DateTime value, JsonGenerator gen, 
                          SerializerProvider arg2)
        throws IOException, JsonProcessingException {

        gen.writeString(formatter.print(value));
    }
}

Python Threading String Arguments

I hope to provide more background knowledge here.

First, constructor signature of the of method threading::Thread:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

args is the argument tuple for the target invocation. Defaults to ().

Second, A quirk in Python about tuple:

Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).

On the other hand, a string is a sequence of characters, like 'abc'[1] == 'b'. So if send a string to args, even in parentheses (still a sting), each character will be treated as a single parameter.

However, Python is so integrated and is not like JavaScript where extra arguments can be tolerated. Instead, it throws an TypeError to complain.

SQLAlchemy: What's the difference between flush() and commit()?

Use flush when you need to write, for example to get a primary key ID from an autoincrementing counter.

john=Person(name='John Smith', parent=None)
session.add(john)
session.flush()

son=Person(name='Bill Smith', parent=john.id)

Without flushing, john would never get an ID from the DB and so couldn't represent the parent/child relationship in code.

Like others have said, without commit() none of this will be permanently persisted to DB.

How do I exit a WPF application programmatically?

As wuminqi said, Application.Current.Shutdown(); is irreversible, and I believe it is typically used to force an application to close at times such as when a user is logging off or shutting down Windows.

Instead, call this.close() in your main window. This is the same as pressing Alt + F4 or the close [x] button on the window. This will cause all other owned windows to close and will end up calling Application.Current.Shutdown(); so long as the close action wasn't cancelled. Please see the MSDN documentation on Closing a Window.

Also, because this.close() is cancellable you can put in a save changes confirmation dialog in the closing event handler. Simply make an event handler for <Window Closing="..."> and change e.Cancel accordingly. (See the MSDN documentation for more details on how to do this.)

Python NoneType object is not callable (beginner)

Why does it give me that error?

Because your first parameter you pass to the loop function is None but your function is expecting an callable object, which None object isn't.

Therefore you have to pass the callable-object which is in your case the hi function object.

def hi():     
  print 'hi'

def loop(f, n):         #f repeats n times
  if n<=0:
    return
  else:
    f()             
    loop(f, n-1)    

loop(hi, 5)

ImportError: No module named tensorflow

Instead of using the doc's command (conda create -n tensorflow pip python=2.7 # or python=3.3, etc.) which wanted to install python2.7 in the conda environment, and kept erroring out saying the module can't be found when following the installation validation steps, I used conda create -n tensorflow pip python=3 to make sure python3 was installed in the environment.

Doing this, I only had to type python instead of python3 when validating the installation and the error went away.

Mysql SELECT CASE WHEN something then return field

You are mixing the 2 different CASE syntaxes inappropriately.

Use this style (Searched)

  CASE  
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Or this style (Simple)

  CASE u.nnmu 
  WHEN '0' THEN mu.naziv_mesta
  WHEN '1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Not This (Simple but with boolean search predicates)

  CASE u.nnmu 
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

In MySQL this will end up testing whether u.nnmu is equal to the value of the boolean expression u.nnmu ='0' itself. Regardless of whether u.nnmu is 1 or 0 the result of the case expression itself will be 1

For example if nmu = '0' then (nnmu ='0') evaluates as true (1) and (nnmu ='1') evaluates as false (0). Substituting these into the case expression gives

 SELECT CASE  '0'
  WHEN 1 THEN '0'
  WHEN 0 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

if nmu = '1' then (nnmu ='0') evaluates as false (0) and (nnmu ='1') evaluates as true (1). Substituting these into the case expression gives

 SELECT CASE  '1'
  WHEN 0 THEN '0'
  WHEN 1 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

C++ String Declaring

C++ supplies a string class that can be used like this:

#include <string>
#include <iostream>

int main() {
    std::string Something = "Some text";
    std::cout << Something << std::endl;
}

What is the difference between field, variable, attribute, and property in Java POJOs?

Actually these two terms are often used to represent same thing, but there are some exceptional situations. A field can store the state of an object. Also all fields are variables. So it is clear that there can be variables which are not fields. So looking into the 4 type of variables (class variable, instance variable, local variable and parameter variable) we can see that class variables and instance variables can affect the state of an object. In other words if a class or instance variable changes,the state of object changes. So we can say that class variables and instance variables are fields while local variables and parameter variables are not.

If you want to understand more deeply, you can head over to the source below:-

http://sajupauledayan.com/java/fields-vs-variables-in-java

Where does Oracle SQL Developer store connections?

If you have previously installed SQL Developer then it will store the connection details in the 'connection.xml' which will be located in below mentioned path.

C:\Users\Username\AppData\Roaming\SQL Developer\system3.1.07.42\o.jdeveloper.db.connection.11.1.1.4.37.59.48

Once you get that 'connection.xml' try to import it into SQLDeveloper by right clicking to CONNECTIONS.

Compile to stand alone exe for C# app in Visual Studio 2010

Are you sure you selected Console Application? I'm running VS 2010 and with the vanilla settings a C# console app builds to \bin\debug. Try to create a new Console Application project, with the language set to C#. Build the project, and go to Project/[Console Application 1]Properties. In the Build tab, what is the Output path? It should default to bin\debug, unless you have some restricted settings on your workstation,etc. Also review the build output window and see if any errors are being thrown - in which case nothing will be built to the output folder, of course...

nvm keeps "forgetting" node in new terminal session

If you have tried everything still no luck you can try this :_

1 -> Uninstall NVM

rm -rf ~/.nvm

2 -> Remove npm dependencies by following this

3 -> Install NVM

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

4 -> Set ~/.bash_profile configuration

Run sudo nano ~/.bash_profile

Copy and paste following this

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

5 -> CONTROL + X save the changes

6 -> Run . ~/.bash_profile

7 -> Now you should have nvm installed on your machine, to install node run nvm install v7.8.0 this will be default node version or you can install any version of node

Ideal way to cancel an executing AsyncTask

With reference to Yanchenko's answer on 29 April '10: Using a 'while(running)' approach is neat when your code under 'doInBackground' has to be executed multiple times during every execution of the AsyncTask. If your code under 'doInBackground' has to be executed only once per execution of the AsyncTask, wrapping all your code under 'doInBackground' in a 'while(running)' loop will not stop the background code (background thread) from running when the AsyncTask itself is cancelled, because the 'while(running)' condition will only be evaluated once all the code inside the while loop has been executed at least once. You should thus either (a.) break up your code under 'doInBackground' into multiple 'while(running)' blocks or (b.) perform numerous 'isCancelled' checks throughout your 'doInBackground' code, as explained under "Cancelling a task" at https://developer.android.com/reference/android/os/AsyncTask.html.

For option (a.) one can thus modify Yanchenko's answer as follows:

public class MyTask extends AsyncTask<Void, Void, Void> {

private volatile boolean running = true;

//...

@Override
protected void onCancelled() {
    running = false;
}

@Override
protected Void doInBackground(Void... params) {

    // does the hard work

    while (running) {
        // part 1 of the hard work
    }

    while (running) {
        // part 2 of the hard work
    }

    // ...

    while (running) {
        // part x of the hard work
    }
    return null;
}

// ...

For option (b.) your code in 'doInBackground' will look something like this:

public class MyTask extends AsyncTask<Void, Void, Void> {

//...

@Override
protected Void doInBackground(Void... params) {

    // part 1 of the hard work
    // ...
    if (isCancelled()) {return null;}

    // part 2 of the hard work
    // ...
    if (isCancelled()) {return null;}

    // ...

    // part x of the hard work
    // ...
    if (isCancelled()) {return null;}
}

// ...

C++11 thread-safe queue

According to the standard condition_variables are allowed to wakeup spuriously, even if the event hasn't occured. In case of a spurious wakeup it will return cv_status::no_timeout (since it woke up instead of timing out), even though it hasn't been notified. The correct solution for this is of course to check if the wakeup was actually legit before proceding.

The details are specified in the standard §30.5.1 [thread.condition.condvar]:

—The function will unblock when signaled by a call to notify_one(), a call to notify_all(), expiration of the absolute timeout (30.2.4) speci?ed by abs_time, or spuriously.

...

Returns: cv_status::timeout if the absolute timeout (30.2.4) speci?edby abs_time expired, other-ise cv_status::no_timeout.

How can I copy the output of a command directly into my clipboard?

on Wayland xcopy doesn't seem to work, use wl-clipboard instead. e.g. on fedora

sudo dnf install wl-clipboard

tree | wl-copy

wl-paste > file

Given a view, how do I get its viewController?

The fast and generic way in Swift 3:

extension UIResponder {
    func parentController<T: UIViewController>(of type: T.Type) -> T? {
        guard let next = self.next else {
            return nil
        }
        return (next as? T) ?? next.parentController(of: T.self)
    }
}

//Use:
class MyView: UIView {
    ...
    let parentController = self.parentController(of: MyViewController.self)
}

How to center a component in Material-UI and make it responsive?

The @Nadun's version did not work for me, sizing wasn't working well. Removed the direction="column" or changing it to row, helps with building vertical login forms with responsive sizing.

<Grid
  container
  spacing={0}
  alignItems="center"
  justify="center"
  style={{ minHeight: "100vh" }}
>
  <Grid item xs={6}></Grid>
</Grid>;

Why would one use nested classes in C++?

Nested classes are cool for hiding implementation details.

List:

class List
{
    public:
        List(): head(nullptr), tail(nullptr) {}
    private:
        class Node
        {
              public:
                  int   data;
                  Node* next;
                  Node* prev;
        };
    private:
        Node*     head;
        Node*     tail;
};

Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.

Look at std::list or std::map they all contain hidden classes (or do they?). The point is they may or may not, but because the implementation is private and hidden the builders of the STL were able to update the code without affecting how you used the code, or leaving a lot of old baggage laying around the STL because they need to maintain backwards compatibility with some fool who decided they wanted to use the Node class that was hidden inside list.

SSRS expression to format two decimal places does not show zeros

Actually, I needed the following...get rid of the decimals without rounding so "12.23" needs to show as "12". In SSRS, do not format the number as a percent. Leave the formatting as default (no formatting applied) then in the expression do the following: =Fix(Fields!PctAmt.Value*100))

Multiply the number by 100 then apply the FIX function in SSRS which returns only the integer portion of a number.

How to call a vue.js function on page load

Beware that when the mounted event is fired on a component, not all Vue components are replaced yet, so the DOM may not be final yet.

To really simulate the DOM onload event, i.e. to fire after the DOM is ready but before the page is drawn, use vm.$nextTick from inside mounted:

mounted: function () {
  this.$nextTick(function () {
    // Will be executed when the DOM is ready
  })
}

How to Maximize window in chrome using webDriver (python)

Nothing worked for me except:

driver.set_window_size(1024, 600)
driver.maximize_window()

I found this by inspecting selenium/webdriver/remote/webdriver.py. I've never found any useful documentation, but reading the code has been marginally effective.

What do \t and \b do?

This behaviour is terminal-specific and specified by the terminal emulator you use (e.g. xterm) and the semantics of terminal that it provides. The terminal behaviour has been very stable for the last 20 years, and you can reasonably rely on the semantics of \b.

Rotating videos with FFmpeg

Have you tried transpose yet? Like (from the other answer)

 ffmpeg -i input -vf transpose=2 output

If you are using an old version, you have to update ffmpeg if you want to use the transpose feature, as it was added in October 2011.

The FFmpeg download page offers static builds that you can directly execute without having to compile them.

How to access data/data folder in Android device?

The easiest way (just one simple step) to pull a file from your debuggable application folder (let's say /data/data/package.name/databases/file) on an unrooted Android 5.0+ device is by using this command:

adb exec-out run-as package.name cat databases/file > file

Toolbar overlapping below status bar

Use android:fitsSystemWindows="true" in the root view of your layout (LinearLayout in your case). And android:fitsSystemWindows is an

internal attribute to adjust view layout based on system windows such as the status bar. If true, adjusts the padding of this view to leave space for the system windows. Will only take effect if this view is in a non-embedded activity.

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol fitsSystemWindows.

How to import .py file from another directory?

You can add to the system-path at runtime:

import sys
sys.path.insert(0, 'path/to/your/py_file')

import py_file

This is by far the easiest way to do it.

Python List & for-each access (Find/Replace in built-in list)

Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.

As noted in the comments, when you loop over a list with something like for member in my_list the member variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:

my_list = [1,2,3]
for member in my_list:
    member = 42
print my_list

Output:

[1, 2, 3]

If you want to change a list containing immutable types, you need to do something like:

my_list = [1,2,3]
for ndx, member in enumerate(my_list):
    my_list[ndx] += 42
print my_list

Output:

[43, 44, 45]

If your list contains mutable objects, you can modify the current member object directly:

class C:
    def __init__(self, n):
        self.num = n
    def __repr__(self):
        return str(self.num)

my_list = [C(i) for i in xrange(3)]
for member in my_list:
    member.num += 42
print my_list

[42, 43, 44]

Note that you are still not changing the list, simply modifying the objects in the list.

You might benefit from reading Naming and Binding.

Why won't my PHP app send a 404 error?

That is correct behaviour, it's up to you to create the contents for the 404 page.
The 404 header is used by spiders and download-managers to determine if the file exists.
(A page with a 404 header won't be indexed by google or other search-engines)

Normal users however don't look at http-headers and use the page as a normal page.

How to declare a global variable in a .js file

As mentioned above, there are issues with using the top-most scope in your script file. Here is another issue: The script file might be run from a context that is not the global context in some run-time environment.

It has been proposed to assign the global to window directly. But that is also run-time dependent and does not work in Node etc. It goes to show that portable global variable management needs some careful consideration and extra effort. Maybe they will fix it in future ECMS versions!

For now, I would recommend something like this to support proper global management for all run-time environments:

/**
 * Exports the given object into the global context.
 */
var exportGlobal = function(name, object) {
    if (typeof(global) !== "undefined")  {
        // Node.js
        global[name] = object;
    }
    else if (typeof(window) !== "undefined") {
        // JS with GUI (usually browser)
        window[name] = object;
    }
    else {
        throw new Error("Unkown run-time environment. Currently only browsers and Node.js are supported.");
    }
};


// export exportGlobal itself
exportGlobal("exportGlobal", exportGlobal);

// create a new global namespace
exportGlobal("someothernamespace", {});

It's a bit more typing, but it makes your global variable management future-proof.

Disclaimer: Part of this idea came to me when looking at previous versions of stacktrace.js.

I reckon, one can also use Webpack or other tools to get more reliable and less hackish detection of the run-time environment.

PermissionError: [Errno 13] in python

For me, I was writing to a file that is opened in Excel.

What is the meaning of @_ in Perl?

The question was what @_ means in Perl. The answer to that question is that, insofar as $_ means it in Perl, @_ similarly means they.

No one seems to have mentioned this critical aspect of its meaning — as well as theirs.

They’re consequently both used as pronouns, or sometimes as topicalizers.

They typically have nominal antecedents, although not always.

Rebase feature branch onto another feature branch

Note: if you were on Branch1, you will with Git 2.0 (Q2 2014) be able to type:

git checkout Branch2
git rebase -

See commit 4f40740 by Brian Gesiak modocache:

rebase: allow "-" short-hand for the previous branch

Teach rebase the same shorthand as checkout and merge to name the branch to rebase the current branch on; that is, that "-" means "the branch we were previously on".

How to add minutes to current time in swift

In case you want unix timestamp

        let now : Date = Date()
        let currentCalendar : NSCalendar = Calendar.current as NSCalendar

        let nowPlusAddTime : Date = currentCalendar.date(byAdding: .second, value: accessTime, to: now, options: .matchNextTime)!

        let unixTime = nowPlusAddTime.timeIntervalSince1970

Why can't I initialize non-const static member or static array in class?

Why I can't initialize static data members in class?

The C++ standard allows only static constant integral or enumeration types to be initialized inside the class. This is the reason a is allowed to be initialized while others are not.

Reference:
C++03 9.4.2 Static data members
§4

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

What are integral types?

C++03 3.9.1 Fundamental types
§7

Types bool, char, wchar_t, and the signed and unsigned integer types are collectively called integral types.43) A synonym for integral type is integer type.

Footnote:

43) Therefore, enumerations (7.2) are not integral; however, enumerations can be promoted to int, unsigned int, long, or unsigned long, as specified in 4.5.

Workaround:

You could use the enum trick to initialize an array inside your class definition.

class A 
{
    static const int a = 3;
    enum { arrsize = 2 };

    static const int c[arrsize] = { 1, 2 };

};

Why does the Standard does not allow this?

Bjarne explains this aptly here:

A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

Why are only static const integral types & enums allowed In-class Initialization?

The answer is hidden in Bjarne's quote read it closely,
"C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects."

Note that only static const integers can be treated as compile time constants. The compiler knows that the integer value will not change anytime and hence it can apply its own magic and apply optimizations, the compiler simply inlines such class members i.e, they are not stored in memory anymore, As the need of being stored in memory is removed, it gives such variables the exception to rule mentioned by Bjarne.

It is noteworthy to note here that even if static const integral values can have In-Class Initialization, taking address of such variables is not allowed. One can take the address of a static member if (and only if) it has an out-of-class definition.This further validates the reasoning above.

enums are allowed this because values of an enumerated type can be used where ints are expected.see citation above


How does this change in C++11?

C++11 relaxes the restriction to certain extent.

C++11 9.4.2 Static data members
§3

If a static data member is of const literal type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

Also, C++11 will allow(§12.6.2.8) a non-static data member to be initialized where it is declared(in its class). This will mean much easy user semantics.

Note that these features have not yet been implemented in latest gcc 4.7, So you might still get compilation errors.

PHP Curl UTF-8 Charset

Simple: When you use curl it encodes the string to utf-8 you just need to decode them..

Description

string utf8_decode ( string $data )

This function decodes data , assumed to be UTF-8 encoded, to ISO-8859-1.

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Registering for Push Notifications in Xcode 8/Swift 3.0?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    if #available(iOS 10, *) {

        //Notifications get posted to the function (delegate):  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)"


        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in

            guard error == nil else {
                //Display Error.. Handle Error.. etc..
                return
            }

            if granted {
                //Do stuff here..

                //Register for RemoteNotifications. Your Remote Notifications can display alerts now :)
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            }
            else {
                //Handle user denying permissions..
            }
        }

        //Register for remote notifications.. If permission above is NOT granted, all notifications are delivered silently to AppDelegate.
        application.registerForRemoteNotifications()
    }
    else {
        let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
    }

    return true
}

Multiple arguments to function called by pthread_create()?

The args of print_the_arguments is arguments, so you should use:

struct arg_struct *args = (struct arg_struct *)arguments. 

Using headers with the Python requests library's get method

Seems pretty straightforward, according to the docs on the page you linked (emphasis mine).

requests.get(url, params=None, headers=None, cookies=None, auth=None, timeout=None)

Sends a GET request. Returns Response object.

Parameters:

  • url – URL for the new Request object.
  • params – (optional) Dictionary of GET Parameters to send with the Request.
  • headers – (optional) Dictionary of HTTP Headers to send with the Request.
  • cookies – (optional) CookieJar object to send with the Request.
  • auth – (optional) AuthObject to enable Basic HTTP Auth.
  • timeout – (optional) Float describing the timeout of the request.

.NET Console Application Exit Event

Here is a complete, very simple .Net solution that works in all versions of windows. Simply paste it into a new project, run it and try CTRL-C to view how it handles it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace TestTrapCtrlC{
    public class Program{
        static bool exitSystem = false;

        #region Trap application termination
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

        private delegate bool EventHandler(CtrlType sig);
        static EventHandler _handler;

        enum CtrlType {
         CTRL_C_EVENT = 0,
         CTRL_BREAK_EVENT = 1,
         CTRL_CLOSE_EVENT = 2,
         CTRL_LOGOFF_EVENT = 5,
         CTRL_SHUTDOWN_EVENT = 6
         }

        private static bool Handler(CtrlType sig) {
            Console.WriteLine("Exiting system due to external CTRL-C, or process kill, or shutdown");

            //do your cleanup here
            Thread.Sleep(5000); //simulate some cleanup delay

            Console.WriteLine("Cleanup complete");

            //allow main to run off
             exitSystem = true;

            //shutdown right away so there are no lingering threads
            Environment.Exit(-1);

            return true;
        }
        #endregion

        static void Main(string[] args) {
            // Some biolerplate to react to close window event, CTRL-C, kill, etc
            _handler += new EventHandler(Handler);
            SetConsoleCtrlHandler(_handler, true);

            //start your multi threaded program here
            Program p = new Program();
            p.Start();

            //hold the console so it doesn’t run off the end
            while(!exitSystem) {
                Thread.Sleep(500);
            }
        }

        public void Start() {
            // start a thread and start doing some processing
            Console.WriteLine("Thread started, processing..");
        }
    }
 }

How to secure the ASP.NET_SessionId cookie?

If the entire site uses HTTPS, your sessionId cookie is as secure as the HTTPS encryption at the very least. This is because cookies are sent as HTTP headers, and when using SSL, the HTTP headers are encrypted using the SSL when being transmitted.

How to remove all characters after a specific character in python?

Split on your separator at most once, and take the first piece:

sep = '...'
stripped = text.split(sep, 1)[0]

You didn't say what should happen if the separator isn't present. Both this and Alex's solution will return the entire string in that case.

Reading a text file with SQL Server

if you want to read the file into a table at one time you should use BULK INSERT. ON the other hand if you preffer to parse the file line by line to make your own checks, you should take a look at this web: https://www.simple-talk.com/sql/t-sql-programming/reading-and-writing-files-in-sql-server-using-t-sql/ It is possible that you need to activate your xp_cmdshell or other OLE Automation features. Simple Google it and the script will appear. Hope to be useful.

Why isn't Python very good for functional programming?

The question you reference asks which languages promote both OO and functional programming. Python does not promote functional programming even though it works fairly well.

The best argument against functional programming in Python is that imperative/OO use cases are carefully considered by Guido, while functional programming use cases are not. When I write imperative Python, it's one of the prettiest languages I know. When I write functional Python, it becomes as ugly and unpleasant as your average language that doesn't have a BDFL.

Which is not to say that it's bad, just that you have to work harder than you would if you switched to a language that promotes functional programming or switched to writing OO Python.

Here are the functional things I miss in Python:


  • No pattern matching and no tail recursion mean your basic algorithms have to be written imperatively. Recursion is ugly and slow in Python.
  • A small list library and no functional dictionaries mean that you have to write a lot of stuff yourself.
  • No syntax for currying or composition means that point-free style is about as full of punctuation as explicitly passing arguments.
  • Iterators instead of lazy lists means that you have to know whether you want efficiency or persistence, and to scatter calls to list around if you want persistence. (Iterators are use-once)
  • Python's simple imperative syntax, along with its simple LL1 parser, mean that a better syntax for if-expressions and lambda-expressions is basically impossible. Guido likes it this way, and I think he's right.

How to import module when module name has a '-' dash or hyphen in it?

Like other said you can't use the "-" in python naming, there are many workarounds, one such workaround which would be useful if you had to add multiple modules from a path is using sys.path

For example if your structure is like this:

foo-bar
+-- barfoo.py
+-- __init__.py

import sys
sys.path.append('foo-bar')

import barfoo

Moving Average Pandas

To get the moving average in pandas we can use cum_sum and then divide by count.

Here is the working example:

import pandas as pd
import numpy as np

df = pd.DataFrame({'id': range(5),
                   'value': range(100,600,100)})

# some other similar statistics
df['cum_sum'] = df['value'].cumsum()
df['count'] = range(1,len(df['value'])+1)
df['mov_avg'] = df['cum_sum'] / df['count']

# other statistics
df['rolling_mean2'] = df['value'].rolling(window=2).mean()

print(df)

output

   id  value  cum_sum  count  mov_avg     rolling_mean2
0   0    100      100      1    100.0           NaN
1   1    200      300      2    150.0           150.0
2   2    300      600      3    200.0           250.0
3   3    400     1000      4    250.0           350.0
4   4    500     1500      5    300.0           450.0

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

Where do I get servlet-api.jar from?

You can find a recent servlet-api.jar in Tomcat 6 or 7 lib directory. If you don't have Tomcat on your machine, download the binary distribution of version 6 or 7 from http://tomcat.apache.org/download-70.cgi

How do I drag and drop files into an application?

Some sample code:

  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      this.AllowDrop = true;
      this.DragEnter += new DragEventHandler(Form1_DragEnter);
      this.DragDrop += new DragEventHandler(Form1_DragDrop);
    }

    void Form1_DragEnter(object sender, DragEventArgs e) {
      if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
    }

    void Form1_DragDrop(object sender, DragEventArgs e) {
      string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
      foreach (string file in files) Console.WriteLine(file);
    }
  }

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

Wait -- did you actually mean that "the same number of rows ... are being processed" or that "the same number of rows are being returned"? In general, the outer join would process many more rows, including those for which there is no match, even if it returns the same number of records.

MySQL InnoDB not releasing disk space after deleting data rows from table

If you don't use innodb_file_per_table, reclaiming disk space is possible, but quite tedious, and requires a significant amount of downtime.

The How To is pretty in-depth - but I pasted the relevant part below.

Be sure to also retain a copy of your schema in your dump.

Currently, you cannot remove a data file from the system tablespace. To decrease the system tablespace size, use this procedure:

Use mysqldump to dump all your InnoDB tables.

Stop the server.

Remove all the existing tablespace files, including the ibdata and ib_log files. If you want to keep a backup copy of the information, then copy all the ib* files to another location before the removing the files in your MySQL installation.

Remove any .frm files for InnoDB tables.

Configure a new tablespace.

Restart the server.

Import the dump files.

Remove all line breaks from a long string of text

The canonic answer, in Python, would be :

s = ''.join(s.splitlines())

It splits the string into lines (letting Python doing it according to its own best practices). Then you merge it. Two possibilities here:

  • replace the newline by a whitespace (' '.join())
  • or without a whitespace (''.join())

Where could I buy a valid SSL certificate?

You are really asking a couple of questions here:

1) Why does the price of SSL certificates vary so much

2) Where can I get good, cheap SSL certificates?

The first question is a good one. For example, the type of SSL certificate you buy is important. Many SSL certificates are domain verified only - that is, the company issuing the certificate only validate that you own the domain. They don't validate your identity, so people visiting your site might know that the domain has a SSL certificate, but that doesn't mean the person behing the website isn't a scammer or phisher, for example. This is why the Verisign solution is much more expensive - you are getting a cert that not only secures your site, but validates the identity of the owner of the site (well, that's the claim).

You can read more on this subject here

For your second question, I can personally recommend RapidSSL. I've bought several certificates from them in the past and they are, well, rapid. However, you should always do your research first. A company based in France might be better for you to deal with as you can get support in your local hours, etc.

textarea's rows, and cols attribute in CSS

width and height are used when going the css route.

<!DOCTYPE html>
<html>
    <head>
        <title>Setting Width and Height on Textareas</title>
        <style>
            .comments { width: 300px; height: 75px }
        </style>
    </head>
    <body>
        <textarea class="comments"></textarea>
    </body>
</html>

Get the current date in java.sql.Date format

all you have to do is this

    Calendar currenttime = Calendar.getInstance();               //creates the Calendar object of the current time
    Date sqldate = new Date((currenttime.getTime()).getTime());  //creates the sql Date of the above created object
    pstm.setDate(6, (java.sql.Date) date);              //assign it to the prepared statement (pstm in this case)

pythonw.exe or python.exe?

I was struggling to get this to work for a while. Once you change the extension to .pyw, make sure that you open properties of the file and direct the "open with" path to pythonw.exe.

What is the most efficient way to create HTML elements using jQuery?

You'll have to understand that the significance of element creation performance is irrelevant in the context of using jQuery in the first place.

Keep in mind, there's no real purpose of creating an element unless you're actually going to use it.

You may be tempted to performance test something like $(document.createElement('div')) vs. $('<div>') and get great performance gains from using $(document.createElement('div')) but that's just an element that isn't in the DOM yet.

However, in the end of the day, you'll want to use the element anyway so the real test should include f.ex. .appendTo();

Let's see, if you test the following against each other:

var e = $(document.createElement('div')).appendTo('#target');
var e = $('<div>').appendTo('#target');
var e = $('<div></div>').appendTo('#target');
var e = $('<div/>').appendTo('#target');

You will notice the results will vary. Sometimes one way is better performing than the other. And this is only because the amount of background tasks on your computer change over time.

Test yourself here

So, in the end of the day, you do want to pick the smallest and most readable way of creating an element. That way, at least, your script files will be smallest possible. Probably a more significant factor on the performance point than the way of creating an element before you use it in the DOM.

How to check for palindrome using Python logic

I tried using this:

def palindrome_numer(num):
num_str = str(num)
str_list = list(num_str)
if str_list[0] == str_list[-1]:
    return True
return False

and it worked for a number but I don't know if a string

Correct MIME Type for favicon.ico?

When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:

<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />

or the same with image/vnd.microsoft.icon, and it will work with all browsers.

Note: There is no IANA specification for the MIME-type image/x-icon, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon.

The only case in which there is a difference is if you were trying to use an .ico file in an <img> tag (which is pretty unusual). Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico files as images, use png.

Using regular expressions to do mass replace in Notepad++ and Vim

It may help if you're less specific. Your expression there is "greedy", which may be interpreted different ways by different programs. Try this in vim:

%s/^<[^>]+>//

getting file size in javascript

You cannot.

JavaScript cannot access files on the local computer for security reasons, even to check their size.

The only thing you can do is use JavaScript to submit the form with the file field to a server-side script, which can then measure its size and return it.

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

I had the same problem, and resolved it. In my case it was error due to the non-proper format. Please check the first and last coordinates array in geometry coordinates they must be same then and only then it will work. Hope it may help you!

How can I change the default Mysql connection timeout when connecting through python?

I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the _mysql.connect call. For example,

con = _mysql.connect(host='localhost', user='dell-pc', passwd='', db='test',
          connect_timeout=1000)

Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.

For detail about different arguments that you can pass to _mysql.connect, see MySQLdb API documentation

Connecting to Postgresql in a docker container from outside

You can run Postgres this way (map a port):

docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres

So now you have mapped the port 5432 of your container to port 5432 of your server. -p <host_port>:<container_port> .So now your postgres is accessible from your public-server-ip:5432

To test: Run the postgres database (command above)

docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                     NAMES
05b3a3471f6f        postgres            "/docker-entrypoint.s"   1 seconds ago       Up 1 seconds        0.0.0.0:5432->5432/tcp    some-postgres

Go inside your container and create a database:

docker exec -it 05b3a3471f6f bash
root@05b3a3471f6f:/# psql -U postgres
postgres-# CREATE DATABASE mytest;
postgres-# \q

Go to your localhost (where you have some tool or the psql client).

psql -h public-ip-server -p 5432 -U postgres

(password mysecretpassword)

postgres=# \l

                             List of databases
   Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges
-----------+----------+----------+------------+------------+-----------------------
 mytest    | postgres | UTF8     | en_US.utf8 | en_US.utf8 |
 postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 |
 template0 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres   

So you're accessing the database (which is running in docker on a server) from your localhost.

In this post it's expained in detail.

Prevent Caching in ASP.NET MVC for specific actions using an attribute

You can use the built in cache attribute to prevent caching.

For .net Framework: [OutputCache(NoStore = true, Duration = 0)]

For .net Core: [ResponseCache(NoStore = true, Duration = 0)]

Be aware that it is impossible to force the browser to disable caching. The best you can do is provide suggestions that most browsers will honor, usually in the form of headers or meta tags. This decorator attribute will disable server caching and also add this header: Cache-Control: public, no-store, max-age=0. It does not add meta tags. If desired, those can be added manually in the view.

Additionally, JQuery and other client frameworks will attempt to trick the browser into not using it's cached version of a resource by adding stuff to the url, like a timestamp or GUID. This is effective in making the browser ask for the resource again but doesn't really prevent caching.

On a final note. You should be aware that resources can also be cached in between the server and client. ISP's, proxies, and other network devices also cache resources and they often use internal rules without looking at the actual resource. There isn't much you can do about these. The good news is that they typically cache for shorter time frames, like seconds or minutes.

Seeing the underlying SQL in the Spring JdbcTemplate?

I'm not 100% sure what you're getting at since usually you will pass in your SQL queries (parameterized or not) to the JdbcTemplate, in which case you would just log those. If you have PreparedStatements and you don't know which one is being executed, the toString method should work fine. But while we're on the subject, there's a nice Jdbc logger package here which will let you automatically log your queries as well as see the bound parameters each time. Very useful. The output looks something like this:

executing PreparedStatement: 'insert into ECAL_USER_APPT
(appt_id, user_id, accepted, scheduler, id) values (?, ?, ?, ?, null)'
     with bind parameters: {1=25, 2=49, 3=1, 4=1} 

AssertionError: View function mapping is overwriting an existing endpoint function: main

use flask 0.9 instead use the following commands sudo pip uninstall flask

sudo pip install flask==0.9

Using a SELECT statement within a WHERE clause

The principle of subqueries is not at all bad, but I don't think that you should use it in your example. If I understand correctly you want to get the maximum score for each date. In this case you should use a GROUP BY.

add a string prefix to each value in a string column using Pandas

As an alternative, you can also use an apply combined with format (or better with f-strings) which I find slightly more readable if one e.g. also wants to add a suffix or manipulate the element itself:

df = pd.DataFrame({'col':['a', 0]})

df['col'] = df['col'].apply(lambda x: "{}{}".format('str', x))

which also yields the desired output:

    col
0  stra
1  str0

If you are using Python 3.6+, you can also use f-strings:

df['col'] = df['col'].apply(lambda x: f"str{x}")

yielding the same output.

The f-string version is almost as fast as @RomanPekar's solution (python 3.6.4):

df = pd.DataFrame({'col':['a', 0]*200000})

%timeit df['col'].apply(lambda x: f"str{x}")
117 ms ± 451 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit 'str' + df['col'].astype(str)
112 ms ± 1.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Using format, however, is indeed far slower:

%timeit df['col'].apply(lambda x: "{}{}".format('str', x))
185 ms ± 1.07 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

JVM option -Xss - What does it do exactly?

Each thread in a Java application has its own stack. The stack is used to hold return addresses, function/method call arguments, etc. So if a thread tends to process large structures via recursive algorithms, it may need a large stack for all those return addresses and such. With the Sun JVM, you can set that size via that parameter.

Writing to a new file if it doesn't exist, and appending to a file if it does

Have you tried mode 'a+'?

with open(filename, 'a+') as f:
    f.write(...)

Note however that f.tell() will return 0 in Python 2.x. See https://bugs.python.org/issue22651 for details.

How to auto-format code in Eclipse?

right-click on the project > Properties > Java Editor > Save Actions

How to find list intersection?

Make a set out of the larger one:

_auxset = set(a)

Then,

c = [x for x in b if x in _auxset]

will do what you want (preserving b's ordering, not a's -- can't necessarily preserve both) and do it fast. (Using if x in a as the condition in the list comprehension would also work, and avoid the need to build _auxset, but unfortunately for lists of substantial length it would be a lot slower).

If you want the result to be sorted, rather than preserve either list's ordering, an even neater way might be:

c = sorted(set(a).intersection(b))

JavaScript - Hide a Div at startup (load)

Why not add "display: none;" to the divs style attribute? Thats all JQuery's .hide() function does.

Indirectly referenced from required .class file

This issue happen because of few jars are getting references from other jar and reference jar is missing .

Example : Spring framework

Description Resource    Path    Location    Type
The project was not built since its build path is incomplete. Cannot find the class file for org.springframework.beans.factory.annotation.Autowire. Fix the build path then try building this project   SpringBatch     Unknown Java Problem

In this case "org.springframework.beans.factory.annotation.Autowire" is missing.

Spring-bean.jar is missing

Once you add dependency in your class path issue will resolve.

Why is document.write considered a "bad practice"?

Pro:

  • It's the easiest way to embed inline content from an external (to your host/domain) script.
  • You can overwrite the entire content in a frame/iframe. I used to use this technique a lot for menu/navigation pieces before more modern Ajax techniques were widely available (1998-2002).

Con:

  • It serializes the rendering engine to pause until said external script is loaded, which could take much longer than an internal script.
  • It is usually used in such a way that the script is placed within the content, which is considered bad-form.

What encoding/code page is cmd.exe using?

Command CHCP shows the current codepage. It has three digits: 8xx and is different from Windows 12xx. So typing a English-only text you wouldn't see any difference, but an extended codepage (like Cyrillic) will be printed wrongly.

Best way to require all files from a directory in ruby?

How about:

Dir["/path/to/directory/*.rb"].each {|file| require file }

FCM getting MismatchSenderId

For eliminate this error for mismatch sender Id In fcm

{"multicast_id":7751536172966571167,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

there is error occured,

  1. So we required first, In FCM, register Application e.g MyDemoApplication

  2. After that FCM will generate server key i.e AIzaSyB9krC8mLHzO_TtECb5qg7NDZPxeG03jHU and sender Id i.e 346252831806 these format like these.

  3. After In Android Studio, our project is connect to these FCM created project i.e MyDemoApplication

  4. And most important step is there required to device token or registration id. These token must created in Android Studio..

  5. After that using Sender Id and API key in web API project u will be definitely getting notification

MySQL - Get row number on select

You can use MySQL variables to do it. Something like this should work (though, it consists of two queries).

SELECT 0 INTO @x;

SELECT itemID, 
       COUNT(*) AS ordercount, 
       (@x:=@x+1) AS rownumber 
FROM orders 
GROUP BY itemID 
ORDER BY ordercount DESC; 

How to use a DataAdapter with stored procedure and parameter

   public DataSet Myfunction(string Myparameter)
    {
        config.cmd.Connection = config.cnx;
        config.cmd.CommandText = "ProcName";
        config.cmd.CommandType = CommandType.StoredProcedure;
        config.cmd.Parameters.Add("parameter", SqlDbType.VarChar, 10);
        config.cmd.Parameters["parameter"].Value = Myparameter;

        config.dRadio = new SqlDataAdapter(config.cmd);
        config.dRadio.Fill(config.ds,"Table");

        return config.ds;


    }

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

Export query result to .csv file in SQL Server 2008

One more method worth to mention here:

SQLCMD -S SEVERNAME -E -Q "SELECT COLUMN FROM TABLE" -s "," -o "c:\test.csv"

NOTE: I don't see any network admin let you run powershell scripts

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Get content of a cell given the row and column numbers

It took me a while, but here's how I made it dynamic. It doesn't depend on a sorted table.

First I started with a column of state names (Column A) and a column of aircraft in each state (Column B). (Row 1 is a header row).

Finding the cell that contains the number of aircraft was:

=MATCH(MAX($B$2:$B$54),$B$2:$B$54,0)+MIN(ROW($B$2:$B$54))-1

I put that into a cell and then gave that cell a name, "StateRow" Then using the tips from above, I wound up with this:

=INDIRECT(ADDRESS(StateRow,1))

This returns the name of the state from the dynamic value in row "StateRow", column 1

Now, as the values in the count column change over time as more data is entered, I always know which state has the most aircraft.

Is there a way to break a list into columns?

The CSS solution is: http://www.w3.org/TR/css3-multicol/

The browser support is exactly what you'd expect..

It works "everywhere" except Internet Explorer 9 or older: http://caniuse.com/multicolumn

ul {
    -moz-column-count: 4;
    -moz-column-gap: 20px;
    -webkit-column-count: 4;
    -webkit-column-gap: 20px;
    column-count: 4;
    column-gap: 20px;
}

See: http://jsfiddle.net/pdExf/

If IE support is required, you'll have to use JavaScript, for example:

http://welcome.totheinter.net/columnizer-jquery-plugin/

Another solution is to fallback to normal float: left for only IE. The order will be wrong, but at least it will look similar:

See: http://jsfiddle.net/NJ4Hw/

<!--[if lt IE 10]>
<style>
li {
    width: 25%;
    float: left
}
</style>
<![endif]-->

You could apply that fallback with Modernizr if you're already using it.

How do I create the small icon next to the website tab for my site?

This is for the icon in the browser (most of the sites omit the type):

<link rel="icon" type="image/vnd.microsoft.icon"
     href="http://example.com/favicon.ico" />

or

<link rel="icon" type="image/png"
     href="http://example.com/image.png" />

or

<link rel="apple-touch-icon"
     href="http://example.com//apple-touch-icon.png">

for the shortcut icon:

<link rel="shortcut icon"
     href="http://example.com/favicon.ico" />

Place them in the <head></head> section.

Edit may 2019 some additional examples from MDN

Finding rows that don't contain numeric data in Oracle

In contrast to SGB's answer, I prefer doing the regexp defining the actual format of my data and negating that. This allows me to define values like $DDD,DDD,DDD.DD In the OPs simple scenario, it would look like

SELECT * 
FROM table_with_column_to_search 
WHERE NOT REGEXP_LIKE(varchar_col_with_non_numerics, '^[0-9]+$');

which finds all non-positive integers. If you wau accept negatiuve integers also, it's an easy change, just add an optional leading minus.

SELECT * 
FROM table_with_column_to_search 
WHERE NOT REGEXP_LIKE(varchar_col_with_non_numerics, '^-?[0-9]+$');

accepting floating points...

SELECT * 
FROM table_with_column_to_search 
WHERE NOT REGEXP_LIKE(varchar_col_with_non_numerics, '^-?[0-9]+(\.[0-9]+)?$');

Same goes further with any format. Basically, you will generally already have the formats to validate input data, so when you will desire to find data that does not match that format ... it's simpler to negate that format than come up with another one; which in case of SGB's approach would be a bit tricky to do if you want more than just positive integers.

autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete

<input type="password" placeholder="Enter Password" class="form-control" autocomplete="new-password">

Here you go.

php variable in html no other way than: <?php echo $var; ?>

Use the HEREDOC syntax. You can mix single and double quotes, variables and even function calls with unaltered / unescaped html markup.

echo <<<MYTAG
  <tr><td> <input type="hidden" name="type" value="$var1" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var2" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var3" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var4" ></td></tr>
MYTAG;

Execute a batch file on a remote PC using a batch file on local PC

Use microsoft's tool for remote commands executions: PsExec

If there isn't your bat-file on remote host, copy it first. For example:

copy D:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat \\RemoteServerNameOrIP\d$\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\

And then execute:

psexec \\RemoteServerNameOrIP d:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat

Note: filepath for psexec is path to file on remote server, not your local.

How to add font-awesome to Angular 2 + CLI project

Thought I would throw in my resolution to this since font-awesome is now installed differently according to their documentation.

npm install --save-dev @fortawesome/fontawesome-free

Why it is fortawesome now escapes me but thought I would stick with the most recent version rather than falling back to the old font-awesome.

Then I imported it into my scss

$fa-font-path: "../node_modules/@fortawesome/fontawesome-free/webfonts";
@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/brands";
@import "~@fortawesome/fontawesome-free/scss/regular";
@import "~@fortawesome/fontawesome-free/scss/solid";
@import "~@fortawesome/fontawesome-free/scss/v4-shims";

Hope this helps

putting a php variable in a HTML form value

You can do it like this,

<input type="text" name="name" value="<?php echo $name;?>" />

But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.

<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />

How to use function srand() with time.h?

Try to call randomize() before rand() to initialize random generator.

(look at: srand() — why call it only once?)

How to unset a JavaScript variable?

I am bit confused. If all you are wanting is for a variables value to not pass to another script then there is no need to delete the variable from the scope. Simply nullify the variable then explicit check if it is or is not null. Why go through the trouble of deleting the variable from scope? What purpose does this server that nullifying can not?

foo = null;
if(foo === null) or if(foo !== null)

smooth scroll to top

Here is my proposal implemented with ES6

const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};
scrollToTop();

Tip: for slower motion of the scrolling, increase the hardcoded number 8. The bigger the number - the smoother/slower the scrolling.

how to get the attribute value of an xml node using java

Since your question is more generic so try to implement it with XML Parsers available in Java .If you need it in specific to parsers, update your code here what you have tried yet

<?xml version="1.0" encoding="UTF-8"?>
<ep>
    <source type="xml">TEST</source>
    <source type="text"></source>
</ep>
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("uri to xmlfile");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//ep/source[@type]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

for (int i = 0; i < nl.getLength(); i++)
{
    Node currentItem = nl.item(i);
    String key = currentItem.getAttributes().getNamedItem("type").getNodeValue();
    System.out.println(key);
}

Using Python String Formatting with Lists

You should take a look to the format method of python. You could then define your formatting string like this :

>>> s = '{0} BLAH BLAH {1} BLAH {2} BLAH BLIH BLEH'
>>> x = ['1', '2', '3']
>>> print s.format(*x)
'1 BLAH BLAH 2 BLAH 3 BLAH BLIH BLEH'

Postgresql column reference "id" is ambiguous

SELECT vg.id, 
       vg.name
  FROM v_groups vg INNER JOIN  
       people2v_groups p2vg ON vg.id = p2vg.v_group_id
 WHERE p2vg.people_id = 0;

python convert list to dictionary

Not sure whether it would help you or not but it works to me:

l = ["a", "b", "c", "d", "e"]
outRes = dict((l[i], l[i+1]) if i+1 < len(l) else (l[i], '') for i in xrange(len(l)))

Using FileSystemWatcher to monitor a directory

The reason may be that watcher is declared as local variable to a method and it is garbage collected when the method finishes. You should declare it as a class member. Try the following:

FileSystemWatcher watcher;

private void watch()
{
  watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                         | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
  //Copies file to another directory.
}

creating a new list with subset of list using index in python

The following definition might be more efficient than the first solution proposed

def new_list_from_intervals(original_list, *intervals):
    n = sum(j - i for i, j in intervals)
    new_list = [None] * n
    index = 0
    for i, j in intervals :
        for k in range(i, j) :
            new_list[index] = original_list[k]
            index += 1

    return new_list

then you can use it like below

new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))

Using the star sign in grep

Try grep -E for extended regular expression support

Also take a look at:

The grep man page

Struct memory layout in C

In C, the compiler is allowed to dictate some alignment for every primitive type. Typically the alignment is the size of the type. But it's entirely implementation-specific.

Padding bytes are introduced so every object is properly aligned. Reordering is not allowed.

Possibly every remotely modern compiler implements #pragma pack which allows control over padding and leaves it to the programmer to comply with the ABI. (It is strictly nonstandard, though.)

From C99 §6.7.2.1:

12 Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.

13 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

How to list files using dos commands?

If you just want to get the file names and not directory names then use :

dir /b /a-d > file.txt

Can I grep only the first n lines of a file?

You have a few options using programs along with grep. The simplest in my opinion is to use head:

head -n10 filename | grep ...

head will output the first 10 lines (using the -n option), and then you can pipe that output to grep.

VBA, if a string contains a certain letter

Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.

If InStr(myString, "A") > 0 Then

InStr MSDN Website

For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.

Left(oldStr, InStr(oldStr, "A"))

How to upload (FTP) files to server in a bash script?

Working Example to Put Your File on Root ...........see its very simple

#!/bin/sh
HOST='ftp.users.qwest.net'
USER='yourid'
PASSWD='yourpw'
FILE='file.txt'

ftp -n $HOST <<END_SCRIPT
quote USER $USER
quote PASS $PASSWD
put $FILE
quit
END_SCRIPT
exit 0

Extract directory path and filename

Using bash "here string":

$ fspec="/exp/home1/abc.txt" 
$ tr  "/"  "\n"  <<< $fspec | tail -1
abc.txt
$ filename=$(tr  "/"  "\n"  <<< $fspec | tail -1)
$ echo $filename
abc.txt

The benefit of the "here string" is that it avoids the need/overhead of running an echo command. In other words, the "here string" is internal to the shell. That is:

$ tr <<< $fspec

as opposed to:

$ echo $fspec | tr

How to get a thread and heap dump of a Java process on Windows that's not running in a console

If you can't (or don't want) to use the console/terminal for some reason, there is an alternative solution. You can make the Java application print the thread dump for you. The code that collects the Stack Trace is reasonable simple and can be attached to a button or a web interface.

private static String getThreadDump() {
    Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();

    StringBuilder out = new StringBuilder();
    for (Map.Entry<Thread, StackTraceElement[]> entry : allStackTraces.entrySet()) {
        Thread thread = entry.getKey();
        StackTraceElement[] elements = entry.getValue();
        out.append(String.format("%s | prio=%d | %s", thread.getName(), thread.getPriority(), thread.getState()));
        out.append('\n');

        for (StackTraceElement element : elements) {
            out.append(element.toString()).append('\n');
        }
        out.append('\n');
    }
    return out.toString();
}

This method will return a string that looks like this:

main | prio=5 | RUNNABLE
java.lang.Thread.dumpThreads(Native Method)
java.lang.Thread.getAllStackTraces(Thread.java:1607)
Main.getThreadDump(Main.java:8)
Main.main(Main.java:36)

Monitor Ctrl-Break | prio=5 | RUNNABLE
java.net.PlainSocketImpl.initProto(Native Method)
java.net.PlainSocketImpl.<clinit>(PlainSocketImpl.java:45)
java.net.Socket.setImpl(Socket.java:503)
java.net.Socket.<init>(Socket.java:424)
java.net.Socket.<init>(Socket.java:211)
com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:59)

Finalizer | prio=8 | WAITING
java.lang.Object.wait(Native Method)
java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)

Reference Handler | prio=10 | WAITING
java.lang.Object.wait(Native Method)
java.lang.Object.wait(Object.java:502)
java.lang.ref.Reference.tryHandlePending(Reference.java:191)
java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

For those interested in a Java 8 version with streams, the code is even more compact:

private static String getThreadDump() {
    Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
    StringBuilder out = new StringBuilder();
    allStackTraces.forEach((thread, elements) -> {
        out.append(String.format("%s | prio=%d | %s", thread.getName(), thread.getPriority(), thread.getState()));
        out.append('\n');

        Arrays.stream(elements).forEach(element -> out.append(element.toString()).append('\n'));
        out.append('\n');
    });
    return out.toString();
}

You can easily test this code with:

System.out.print(getThreadDump());

What is the use of a cursor in SQL Server?

I would argue you might want to use a cursor when you want to do comparisons of characteristics that are on different rows of the return set, or if you want to write a different output row format than a standard one in certain cases. Two examples come to mind:

  1. One was in a college where each add and drop of a class had its own row in the table. It might have been bad design but you needed to compare across rows to know how many add and drop rows you had in order to determine whether the person was in the class or not. I can't think of a straight forward way to do that with only sql.

  2. Another example is writing a journal total line for GL journals. You get an arbitrary number of debits and credits in your journal, you have many journals in your rowset return, and you want to write a journal total line every time you finish a journal to post it into a General Ledger. With a cursor you could tell when you left one journal and started another and have accumulators for your debits and credits and write a journal total line (or table insert) that was different than the debit/credit line.

How can I export a GridView.DataSource to a datatable or dataset?

Assuming your DataSource is of type DataTable, you can just do this:

myGridView.DataSource as DataTable

Getting list of Facebook friends with latest API

Just a heads up for anyone stumbling across this question using v2.0 of the Graph API: This will not work anymore. In v2.0, calling /me/friends only returns a list the person's friends who also use the app:

  • A user access token with user_friends permission is required to view the current person's friends.
  • This will only return any friends who have used (via Facebook Login) the app making the request.
  • If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person.

ALTER TABLE on dependent column

you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.

enter image description here

laravel the requested url was not found on this server

Alternatively you could replace all the contents in your .htaccess file

Options +FollowSymLinks -Indexes
RewriteEngine On
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

See the docs here. https://laravel.com/docs/5.8/installation#web-server-configuration

What's the best practice using a settings file in Python?

The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.

To use the yaml module is extremely simple:

import yaml
config = yaml.safe_load(open("path/to/config.yml"))

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

The answer by baldy below is correct, but you may also need to enable 32-bit applications in your AppPool.

Source: http://www.alexjamesbrown.com/uncategorized/could-not-load-file-or-assembly-chilkatdotnet2-or-one-of-its-dependencies-an-attempt-was-made-to-load-a-program-with-an-incorrect-format/

Whilst setting up an application to run on my local machine (running Vista 64bit) I encountered this error:

Could not load file or assembly ChilkatDotNet2 or one of its dependencies. An attempt was made to load a program with an incorrect format.

Obviously, the application uses ChilKat components, but it would seem that the version we are using, is only the 32bit version.

To resolve this error, I set my app pool in IIS to allow 32bit applications. Open up IIS Manager, right click on the app pool, and select Advanced Settings (See below)

enter image description here

Then set "Enable 32-bit Applications" to True.

enter image description here

All done!

How to convert an entire MySQL database characterset and collation to UTF-8?

If you cannot get your tables to convert or your table is always set to some non-utf8 character set, but you want utf8, your best bet might be to wipe it out and start over again and explicitly specify:

create database database_name character set utf8;

How to merge remote master to local branch

I found out it was:

$ git fetch upstream
$ git merge upstream/master

How to create a hash or dictionary object in JavaScript

Use the in operator: e.g. "key1" in a.

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

SOLVED: Always be sure to update your Xcode folks!

Protip: And don't do it from the apple store (but always do it from an official apple website of course)

tip from: http://ericasadun.com/2016/03/22/xcode-upgrades-lessons-learned/

official apple download page: https://developer.apple.com/download/more/

For those who are unable to resolve with above method

  1. Go to project settings in Xcode. Menu File->Project Settings

  2. Go to per-User Project Settings section.

  3. Click on advanced.

  4. Select Xcode Default option. previously this used to be Legacy for my project.

I have analysed on similar lines and concluded that clean is causing the archive to fail. So, the new build system is not clearing the custom/legacy build directory.

delete the build/ folder in ios/ and rerun if that doesn't do any change then
File -> Project Settings (or WorkSpace Settings) -> Build System -> Legacy Build System
Rerun and voilà!

If it still Fails you need to clean full project

Do the following:

  • Delete ios dir manually
  • Clean cache Run npm cache clean --force
  • Run react-native eject
  • Re-install all packages npm install
  • Run the link command react-native link
  • Finally run react-native run-ios

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

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

See Appendix C - Fatal Error Log

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

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

Capture event onclose browser

Events onunload or onbeforeunload you can't use directly - they do not differ between window close, page refresh, form submit, link click or url change.

The only working solution is How to capture the browser window close event?

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

I had the same exception and I was excluding javassist because of its issue with powermock. Then I was adding it again as below but it was not working:

<dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-module-junit4</artifactId>
   <version>1.7.0</version>
   <scope>test</scope>
   <exclusions>
      <exclusion>
         <groupId>org.javassist</groupId>
         <artifactId>javassist</artifactId>
      </exclusion>
   </exclusions>
</dependency>

<dependency>
   <groupId>org.javassist</groupId>
   <artifactId>javassist</artifactId>
   <version>3.20.0-GA</version>
   <scope>test</scope>
</dependency>

Finally I found out that I have to remove <scope>test</scope> from javassist dependency. Hope it helps someone.