Programs & Examples On #Misspelling

Vue equivalent of setTimeout?

Arrow Function

The best and simplest way to solve this problem is by using an arrow function () => {}:

    addToBasket() {
        var item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        // now 'this' is referencing the Vue object and not the 'setTimeout' scope
        setTimeout(() => this.basketAddSuccess = false, 2000);
    }

This works because the this of arrow functions is bound to the this of its enclosing scope- in Vue, that's the parent/ enclosing component. Inside a traditional function called by setTimeout, however, this refers to the window object (which is why you ran into errors when you tried to access this.basketAddSuccess in that context).

Argument Passing

Another way of doing this would be passing this as an arg to your function through setTimeout's prototype using its setTimeout(callback, delay, arg1, arg2, ...) form:

    addToBasket() {
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        //Add scope argument to func, pass this after delay in setTimeout
        setTimeout(function(scope) {
             scope.basketAddSuccess = false;
        }, 2000, this);
    }

(It's worth noting that the arg passing syntax is incompatible with IE 9 and below, however.)

How to throw RuntimeException ("cannot find symbol")

You need to create the instance of the RuntimeException, using new the same way you would to create an instance of most other classes:

throw new RuntimeException(msg);

Comparing strings by their alphabetical order

Take a look at the String.compareTo method.

s1.compareTo(s2)

From the javadocs:

The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.

Get Country of IP Address with PHP

Install and use PHP's GeoIP extension if you can. On debian lenny:

sudo wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
sudo gunzip GeoLiteCity.dat.gz
sudo mkdir -v /usr/share/GeoIP
sudo mv -v GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat

sudo apt-get install php5-geoip
# or sudo apt-get install php-geoip for PHP7

and then try it in PHP:

$ip = $_SERVER['REMOTE_ADDR'];
$country = geoip_country_name_by_name($ip);
echo 'The current user is located in: ' . $country;

returns:

The current user is located in: Cameroon

Is there a date format to display the day of the week in java?

tl;dr

LocalDate.of( 2018 , Month.JANUARY , 23 )
         .format( DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US )  )

java.time

The modern approach uses the java.time classes.

LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;

Note how we specify a Locale such as Locale.CANADA_FRENCH to determine the human language used to translate the name of the day.

DateTimeFormatter f = DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US ) ;
String output = ld.format( f ) ;

ISO 8601

By the way, you may be interested in the standard ISO 8601 week numbering scheme: yyyy-Www-d.

2018-W01-2

Week # 1 has the first Thursday of the calendar-year. Week starts on a Monday. A year has either 52 or 53 weeks. The last/first few days of a calendar-year may land in the next/previous week-based-year.

The single digit on the end is day-of-week, 1-7 for Monday-Sunday.

Add the ThreeTen-Extra library class to your project for the YearWeek class.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Python 3 - Encode/Decode vs Bytes/Str

Neither is better than the other, they do exactly the same thing. However, using .encode() and .decode() is the more common way to do it. It is also compatible with Python 2.

how to change language for DataTable

You have to either create a language file and then set it using :

"oLanguage": {
  "sUrl": "media/language/your_file.txt"
}

Im not sure what server language you are using but something like this would work in PHP :

"oLanguage": {
  "sUrl": "media/language/custom_lang_<?php echo $language ?>.txt"
}

Where language matches the file name for a specific language.

or change individual settings :

"oLanguage": {
  "sLengthMenu": "Display _MENU_ records per page",
  "sZeroRecords": "Nothing found - sorry",
  "sInfo": "Showing _START_ to _END_ of _TOTAL_ records",
  "sInfoEmpty": "Showing 0 to 0 of 0 records",
  "sInfoFiltered": "(filtered from _MAX_ total records)"
}

For more details read this : http://datatables.net/plug-ins/i18n

How to replace a string in multiple files in linux command line

I'd just like to add a note to do two things at once - find a file that contains a string and then do a replace, using the find 'chaining' method:

find  . -type f -iname \*.php -exec fgrep -l "www." {} \; -exec sed -i "s|www||g" {} \;      
  • In this real case, remove the anachronistic 'www' from urls found in PHP files.

  • The 'fgrep -l' only triggers if it finds at least one match in a file, it produces no other output. Don't forget the '\;' separators!

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

for ORA-01031: insufficient privileges. Some of the more common causes are:

  1. You tried to change an Oracle username or password without having the appropriate privileges.
  2. You tried to perform an UPDATE to a table, but you only have SELECT access to the table.
  3. You tried to start up an Oracle database using CONNECT INTERNAL.
  4. You tried to install an Oracle database without having the appropriate privileges to the operating-system.

The option(s) to resolve this Oracle error are:

  1. You can have the Oracle DBA grant you the appropriate privileges that you are missing.
  2. You can have the Oracle DBA execute the operation for you.
  3. If you are having trouble starting up Oracle, you may need to add the Oracle user to the dba group.

For ORA-00942: table or view does not exist. You tried to execute a SQL statement that references a table or view that either does not exist, that you do not have access to, or that belongs to another schema and you didn't reference the table by the schema name.

If this error occurred because the table or view does not exist, you will need to create the table or view.

You can check to see if the table exists in Oracle by executing the following SQL statement:

select *
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'OBJECT_NAME';

For example, if you are looking for a suppliers table, you would execute:

select *
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'SUPPLIERS';

OPTION #2

If this error occurred because you do not have access to the table or view, you will need to have the owner of the table/view, or a DBA grant you the appropriate privileges to this object.

OPTION #3

If this error occurred because the table/view belongs to another schema and you didn't reference the table by the schema name, you will need to rewrite your SQL to include the schema name.

For example, you may have executed the following SQL statement:

select *
from suppliers;

But the suppliers table is not owned by you, but rather, it is owned by a schema called app, you could fix your SQL as follows:

select *
from app.suppliers;

If you do not know what schema the suppliers table/view belongs to, you can execute the following SQL to find out:

select owner
from all_objects
where object_type in ('TABLE','VIEW')
and object_name = 'SUPPLIERS';

This will return the schema name who owns the suppliers table.

How to remove all .svn directories from my application directories

As an important issue, when you want to utilize shell to delete .svn folders You need -depth argument to prevent find command entering the directory that was just deleted and showing error messages like e.g.

"find: ./.svn: No such file or directory"

As a result, You can use find command like below:

cd [dir_to_delete_svn_folders]
find . -depth -name .svn -exec rm -fr {} \;

Waiting until the task finishes

Use dispatch group

dispatchGroup.enter()
FirstOperation(completion: { _ in
    dispatchGroup.leave()
})
dispatchGroup.enter()
SecondOperation(completion: { _ in
    dispatchGroup.leave()
})
dispatchGroup.wait() // Waits here on this thread until the two operations complete executing.

The character encoding of the plain text document was not declared - mootool script

In your HTML it is a good pratice to provide the encoding like using the following meta like this for example:

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

But your warning that you see may be trigged by one of multiple files. it might not be your HTML document. It might be something in a javascript file or css file. if you page is made of up multiples php files included together it may be only 1 of those files.

I dont think this error has anything to do with mootools. you see this message in your firefox console window. not mootools script.

maybe you simply need to re-save your html pages using a code editor that lets you specify the correct character encoding.

CKEditor instance already exists

For this to work you need to pass boolean parameter true when destroying instance:

    var editor = CKEDITOR.instances[name];
    if (editor) { editor.destroy(true); }
    CKEDITOR.replace(name);

Query Mongodb on month, day, year... of a datetime

how about storing the month in its own property since you need to query for it? less elegant than $where, but likely to perform better since it can be indexed.

Fixing Sublime Text 2 line endings?

The comment states

// Determines what character(s) are used to terminate each line in new files.
// Valid values are 'system' (whatever the OS uses), 'windows' (CRLF) and
// 'unix' (LF only).

You are setting

"default_line_ending": "LF",

You should set

"default_line_ending": "unix",

How to use onClick() or onSelect() on option tag in a JSP page?

The answer you gave above works but it is confusing because you have used two names twice and you have an unnecessary line of code. you are doing a process that is not necessary.

it's a good idea when debugging code to get pen and paper and draw little boxes to represent memory spaces (i.e variables being stored) and then to draw arrows to indicate when a variable goes into a little box and when it comes out, if it gets overwritten or is a copy made etc.

if you do this with the code below you will see that

var selectBox = document.getElementById("selectBox");

gets put in a box and stays there you don't do anything with it afterwards.

and

var selectBox = document.getElementById("selectBox");

is hard to debug and is confusing when you have a select id of selectBox for the options list . ---- which selectBox do you want to manipulate / query / etc is it the local var selectBox that will disappear or is it the selectBox id you have assigned to the select tag

your code works until you add to it or modify it then you can easily loose track and get all mixed up

<html>
<head>
<script type="text/javascript">

function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}

</script>
</head>

<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>

a leaner way that works also is:

<html>
<head>
<script type="text/javascript">

function changeFunc() {

var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}

</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>

and it's a good idea to use descriptive names that match the program and task you are working on am currently writing a similar program to accept and process postcodes using your code and modifying it with descriptive names the object is to make computer language as close to natural language as possible.

<script type="text/javascript">

function Mapit(){

var actualPostcode=getPostcodes.options[getPostcodes.selectedIndex].value;

alert(actualPostcode);

// alert is for debugging only next we go on to process and do something
// in this developing program it will placing markers on a map

}

</script>

<select id="getPostcodes" onchange="Mapit();">

<option>London North Inner</option>

<option>N1</option>

<option>London North Outer</option>

<option>N2</option>
<option>N3</option>
<option>N4</option>

// a lot more options follow 
// with text in options to divide into areas and nothing will happen 
// if visitor clicks on the text function Mapit() will ignore
// all clicks on the divider text inserted into option boxes

</select>

How to find if a given key exists in a C++ std::map

I know this question already has some good answers but I think my solution is worth of sharing.

It works for both std::map and std::vector<std::pair<T, U>> and is available from C++11.

template <typename ForwardIterator, typename Key>
bool contains_key(ForwardIterator first, ForwardIterator last, Key const key) {
    using ValueType = typename std::iterator_traits<ForwardIterator>::value_type;

    auto search_result = std::find_if(
        first, last,
        [&key](ValueType const& item) {
            return item.first == key;
        }
    );

    if (search_result == last) {
        return false;
    } else {
        return true;
    }
}

Change CSS class properties with jQuery

Didn't find the answer I wanted, so I solved it myself:
modify a container div!

<div class="rotation"> <!-- Set the container div's css -->
  <div class="content" id='content-1'>This div gets scaled on hover</div>
</div>

<!-- Since there is no parent here the transform doesnt have specificity! -->
<div class="rotation content" id='content-2'>This div does not</div>

css you want to persist after executing $target.css()

.content:hover {
    transform: scale(1.5);
}

modify content's containing div with css()

$(".rotation").css("transform", "rotate(" + degrees + "deg)");

Codepen example

How to get the current plugin directory in WordPress?

To get the plugin directory you can use the Wordpress function plugin_basename($file). So you would use is as follows to extract the folder and filename of the plugin:

$plugin_directory = plugin_basename(__FILE__); 

You can combine this with the URL or the server path of the plugin directory. Therefor you can use the constants WP_PLUGIN_URL to get the plugin directory url or WP_PLUGIN_DIR to get the server path. But as Mark Jaquith mentioned in a comment below this only works if the plugins resides in the Wordpress plugin directory.

Read more about it in the Wordpress codex.

How does the communication between a browser and a web server take place?

Your browser first resolves the servername via DNS to an IP. Then it opens a TCP connection to the webserver and tries to communicate via HTTP. Usually that is on TCP-port 80 but you can specify a different one (http://server:portnumber).

HTTP looks like this:

Once it is connected, it sends the request, which looks like:

GET /site HTTP/1.0
Header1: bla
Header2: blub
{emptyline}

E.g., a header might be Authorization or Range. See here for more.

Then the server responds like this:

200 OK
Header3: foo
Header4: bar

content following here...

E.g., a header might be Date or Content-Type. See here for more.

Look at Wikipedia for HTTP for some more information about this protocol.

Limiting Python input strings to certain characters and lengths

if any( [ i>'z' or i<'a' for i in raw_input]):
    print "Error: Contains illegal characters"
elif len(raw_input)>15:
    print "Very long string"

How to store Java Date to Mysql datetime with JPA

I still prefer the method in one line

new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())

Should I use int or Int32

Also consider Int16. If you need to store an Integer in memory in your application and you are concerned about the amount of memory used, then you could go with Int16 since it uses less memeory and has a smaller min/max range than Int32 (which is what int is.)

Java Scanner String input

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

I suggest you call scan.nextLine() before you print your next prompt to discard the rest of the line.

How to make in CSS an overlay over an image?

You could use a pseudo element for this, and have your image on a hover:

_x000D_
_x000D_
.image {_x000D_
  position: relative;_x000D_
  height: 300px;_x000D_
  width: 300px;_x000D_
  background: url(http://lorempixel.com/300/300);_x000D_
}_x000D_
.image:before {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  transition: all 0.8s;_x000D_
  opacity: 0;_x000D_
  background: url(http://lorempixel.com/300/200);_x000D_
  background-size: 100% 100%;_x000D_
}_x000D_
.image:hover:before {_x000D_
  opacity: 0.8;_x000D_
}
_x000D_
<div class="image"></div>
_x000D_
_x000D_
_x000D_

The calling thread cannot access this object because a different thread owns it

You need to do it on the UI thread. Use:

Dispatcher.BeginInvoke(new Action(() => {GetGridData(null, 0)})); 

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

[] and {} vs list() and dict(), which is better?

The dict literal might be a tiny bit faster as its bytecode is shorter:

In [1]: import dis
In [2]: a = lambda: {}
In [3]: b = lambda: dict()

In [4]: dis.dis(a)
  1           0 BUILD_MAP                0
              3 RETURN_VALUE

In [5]: dis.dis(b)
  1           0 LOAD_GLOBAL              0 (dict)
              3 CALL_FUNCTION            0
              6 RETURN_VALUE

Same applies to the list vs []

What is the equivalent of Java static methods in Kotlin?

Top-level / companion object for static properties

Top-level

When the properties are somewhat related to a class, define them as top-level properties just before the class declaration:

const val MAX_ATTEMPTS = 3
private const val DEFAULT_NAME = "Guest"
private const val MIN_AGE = 16

data class User(val id: String, val name: String = DEFAULT_NAME)

This is similar to the static properties in Java.

When the properties are completely independent of any class, you can define them as top-level in a separate file without the class.

companion object

When the properties are closely related to a class and will be used only in that class, define them inside a companion object:

data class User(val id: String, val name: String = DEFAULT_NAME) {
    companion object {
        const val DEFAULT_NAME = "Guest"
        const val MIN_AGE = 16
    }
}

Top-level / companion object for static methods

Top-level

Similar to the properties above, when the functions are somewhat related to a class, define them just above the class:

fun getAllUsers() { }

fun getProfileFor(userId: String) { }

data class User(val id: String, val name: String)

Usage:

val userList = getAllUsers()

companion object

When the functions are closely related to a class, define them inside a companion object:

data class User(val id: String, val name: String) {

    companion object {

        fun getAll() { }

        fun profileFor(userId: String) { }
    }
}

Usage:

val userProfile = User.profileFor("34")

This is similar to the static methods in Java.

The top-level functions are often more idiomatic to Kotlin. A better reason to define functions inside the companion object is when you are extending a companion object with an interface. An example of this is shown in the singleton section.


Nested class for static class

When the classes with related functionalities belong together, they can be grouped together by nesting:

class User(val id: String, val name: String) {
    class UserAccess : UserDao {
        override fun add(user: User) { }
        override fun remove(id: String) { }
    }
}

This is equivalent to the static nested classes in Java. The UserAccess class here implements an interface UserDao.

Usage:

fun main() {
    val john = User("34", "John")
    val userAccess = User.UserAccess()
    userAccess.add(john)
}

Singleton object for static INSTANCE

Top-level

When you just want a single object of a class, you no longer need to create a static INSTANCE inside a class like in Java. Simply use a top-level object declaration:

object UserAccess : UserDao {
    override fun add(user: User) { }
    override fun remove(id: String) { }
}

Notice also how easy it is to extend an interface or a class in a singleton.

The code above, under the hood, produces the following static INSTANCE singleton pattern in Java (simplified):

public final class UserAccess implements UserDao {
   public static final UserAccess INSTANCE;

   public void add(User user) { }

   public void remove(String id) { }

   private UserAccess() { }

   static { INSTANCE = new UserAccess();}
}

companion object

When the singleton is closely related to a class use companion object:

data class User(val id: String, val name: String) {
    companion object : UserDao {
        override fun add(user: User) { }
        override fun remove(id: String) { }
    }
}

This way you get more elegant naming: User.add(john). Also, you make the intent clear that this singleton is only used as a utility for the User class. You can also use the object without the companion keyword inside the class, if you want multiple singletons or groups of functions/properties.


companion object for static factory

Factory functions in Koltin are created using the companion object. Factory functions are useful when you want to provide multiple ways to create an object where the object construction process is complex or when multiple constructors are not expressive enough.

For example, the newInstance() factory function in the following snippet creates a user by generating the id automatically:

class User private constructor(val id: Long, val name: String) {
    companion object {
        private var currentId = 0L;
        fun newInstance(name: String) = User(currentId++, name)
    }
}

This is equivalent to the static factory methods in Java.

The constructor is kept private but the companion object has access to the constructor.

In the code above, consistency of the next id generation is guaranteed because a companion object is a singleton, only one object will keep track of the id, there won't be any duplicate ids.

Also notice that companion objects can have properties (currentId in this case) to represent state.

Usage:

val john = User.newInstance("John")

@JvmStatic for Java interoperability

The static concept of Java doesn't exist in Kotlin. A companion object is an instance of a real class called Companion. So, when you call the Kotlin code from Java, an object of the Companion class is first instantiated behind the scenes. You need to call the function using the Companion object in Java:

Profile userProfile = User.Companion.profileFor("34");

For the idiomatic Java naming and less verbosity, use @JvmStatic annotation on that function or property:

companion object {
    @JvmStatic
    fun profileFor(userId: String): Profile { }
}

The @JvmStatic annotation creates a separate pure static copy of the getProfileFor() function. Now you can use it from Java with regular syntax:

Profile userProfile = User.profileFor("34");

That's it! Hope the examples are useful for your projects.

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

Thanks Pablo, just what I was looking for! However, if I can take the liberty of improving your script slightly, I suggest replacing your ^V macro with the following:

; Use backslash instead of backtick (yes, I am a C++ programmer).
#EscapeChar \

; Paste in command window.
^V::
StringReplace clipboard2, clipboard, \r\n, \n, All
SendInput {Raw}%clipboard2%
return

The advantage of using SendInput is that

  • it doesn't rely on the command prompt system menu having an "Alt+Space E P" menu item to do the pasting (works for English and Spanish, but not for all languages).
  • it avoids that nasty flicker you get as the menu is created and destroyed.

Note, it's important to include the "{Raw}" in the SendInput command, in case the clipboard happens to contain "!", "+", "^" or "#".

Note, it uses StringReplace to remove excess Windows carriage return characters. Thanks hugov for that suggestion!

How to reset sequence in postgres and fill id column with new data?

Even the auto-increment column is not PK ( in this example it is called seq - aka sequence ) you could achieve that with a trigger :

DROP TABLE IF EXISTS devops_guide CASCADE;

SELECT 'create the "devops_guide" table'
;
   CREATE TABLE devops_guide (
      guid           UUID NOT NULL DEFAULT gen_random_uuid()
    , level          integer NULL
    , seq            integer NOT NULL DEFAULT 1
    , name           varchar (200) NOT NULL DEFAULT 'name ...'
    , description    text NULL
    , CONSTRAINT pk_devops_guide_guid PRIMARY KEY (guid)
    ) WITH (
      OIDS=FALSE
    );

-- START trg_devops_guide_set_all_seq
CREATE OR REPLACE FUNCTION fnc_devops_guide_set_all_seq()
    RETURNS TRIGGER
    AS $$
       BEGIN
         UPDATE devops_guide SET seq=col_serial FROM
         (SELECT guid, row_number() OVER ( ORDER BY seq) AS col_serial FROM devops_guide ORDER BY seq) AS tmp_devops_guide
         WHERE devops_guide.guid=tmp_devops_guide.guid;

         RETURN NEW;
       END;
    $$ LANGUAGE plpgsql;

 CREATE TRIGGER trg_devops_guide_set_all_seq
  AFTER UPDATE OR DELETE ON devops_guide
  FOR EACH ROW
  WHEN (pg_trigger_depth() < 1)
  EXECUTE PROCEDURE fnc_devops_guide_set_all_seq();

Getting DOM element value using pure JavaScript

Pass the object:

doSomething(this)

You can get all data from object:

function(obj){
    var value = obj.value;
    var id = obj.id;
}

Or pass the id only:

doSomething(this.id)

Get the object and after that value:

function(id){
    var value = document.getElementById(id).value;  
}

How do I make a burn down chart in Excel?

But why would you use excel when you could do it all online and have your boss check your dynamic link.

We are using this new tool since last week. http://www.burndown-charts.com/

What I do is I send my boss the link to my chart and he plays around with the links to see if we will be on time...

http://www.burndown-charts.com/teams/dreamteam/sprints/prototype-x

MySQL: NOT LIKE

I don't know why

cfg_name_unique NOT LIKE '%categories%' 

still returns those two values, but maybe exclude them explicit:

SELECT *
    FROM developer_configurations_cms

    WHERE developer_configurations_cms.cat_id = '1'
    AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
    AND developer_configurations_cms.cfg_name_unique NOT LIKE '%categories%'
    AND developer_configurations_cms.cfg_name_unique NOT IN ('categories_posts', 'categories_news')

How are zlib, gzip and zip related? What do they have in common and how are they different?

ZIP is a file format used for storing an arbitrary number of files and folders together with lossless compression. It makes no strict assumptions about the compression methods used, but is most frequently used with DEFLATE.

Gzip is both a compression algorithm based on DEFLATE but less encumbered with potential patents et al, and a file format for storing a single compressed file. It supports compressing an arbitrary number of files and folders when combined with tar. The resulting file has an extension of .tgz or .tar.gz and is commonly called a tarball.

zlib is a library of functions encapsulating DEFLATE in its most common LZ77 incarnation.

xcode library not found

In XCode 10.1, I had to set "Library Search Paths" to something like $(PROJECT_DIR)/.../path/to/your/library

Import regular CSS file in SCSS file?

If I am correct css is compatible with scss so you can change the extension of a css to scss and it should continue to work. Once you change the extension you can import it and it will be included in the file.

If you don't do that sass will use the css @import which is something you don't want.

MSVCP140.dll missing

Either make your friends download the runtime DLL (@Kay's answer), or compile the app with static linking.

In visual studio, go to Project tab -> properties - > configuration properties -> C/C++ -> Code Generation on runtime library choose /MTd for debug mode and /MT for release mode.

This will cause the compiler to embed the runtime into the app. The executable will be significantly bigger, but it will run without any need of runtime dlls.

Effects of the extern keyword on C functions

The reason it has no effect is because at the link-time the linker tries to resolve the extern definition (in your case extern int f()). It doesn't matter if it finds it in the same file or a different file, as long as it is found.

Hope this answers your question.

How do I reformat HTML code using Sublime Text 2?

You don't need any plugins to do this. Just select all lines (Ctrl A) and then from the menu select Edit → Line → Reindent. This will work if your file is saved with an extension that contains HTML like .html or .php.

If you do this often, you may find this key mapping useful:

{ "keys": ["ctrl+shift+r"], "command": "reindent" , "args": { "single_line": false } }

If your file is not saved (e.g. you just pasted in a snippet to a new window), you can manually set the language for indentation by selecting the menu View → Syntax → language of choice before selecting the reindent option.

Volley - POST/GET parameters

For the GET parameters there are two alternatives:

First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:

String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s",
                           num1,
                           num2);

StringRequest myReq = new StringRequest(Method.GET,
                                        uri,
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener());
queue.add(myReq);

where num1 and num2 are String variables that contain your values.

Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8")); to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.

For the POST parameters probably sometimes will be easier than the accepted answer to do it like:

StringRequest myReq = new StringRequest(Method.POST,
                                        "http://somesite.com/some_endpoint.php",
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener()) {

    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("param1", num1);
        params.put("param2", num2);
        return params;
    };
};
queue.add(myReq);

e.g. to just override the getParams() method.

You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.

Connect to external server by using phpMyAdmin

at version 4.0 or above, we need to create one 'config.inc.php' or rename the 'config.sample.inc.php' to 'config.inc.php';

In my case, I also work with one mysql server for each environment (dev and production):

/* others code*/  
$whoIam = gethostname();
switch($whoIam) {
    case 'devHost':
        $cfg['Servers'][$i]['host'] = 'localhost';
        break;
    case 'MasterServer':
        $cfg['Servers'][$i]['host'] = 'masterMysqlServer';
        break;
} /* others code*/ 

Moving Panel in Visual Studio Code to right side

For Visual Studio Code v1.31.1, you can toggle the panel session via the View menu.

  • Go to the View Menu.
  • Via the Appearance option, click on Toggle Panel Position

enter image description here

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

I had a similar issue (using Jackson, lombok, gradle) and a POJO without no args constructor - the solution was to add

lombok.anyConstructor.addConstructorProperties=true

to the lombok.config file

Best way to work with dates in Android SQLite

The best way is to store the dates as a number, received by using the Calendar command.

//Building the table includes:
StringBuilder query=new StringBuilder();
query.append("CREATE TABLE "+TABLE_NAME+ " (");
query.append(COLUMN_ID+"int primary key autoincrement,");
query.append(COLUMN_DATETIME+" int)");

//And inserting the data includes this:
values.put(COLUMN_DATETIME, System.currentTimeMillis()); 

Why do this? First of all, getting values from a date range is easy. Just convert your date into milliseconds, and then query appropriately. Sorting by date is similarly easy. The calls to convert among various formats are also likewise easy, as I included. Bottom line is, with this method, you can do anything you need to do, no problems. It will be slightly difficult to read a raw value, but it more than makes up that slight disadvantage with being easily machine readable and usable. And in fact, it is relatively easy to build a reader (And I know there are some out there) that will automatically convert the time tag to date as such for easy of reading.

It's worth mentioning that the values that come out of this should be long, not int. Integer in sqlite can mean many things, anything from 1-8 bytes, but for almost all dates 64 bits, or a long, is what works.

EDIT: As has been pointed out in the comments, you have to use the cursor.getLong() to properly get the timestamp if you do this.

Where is virtualenvwrapper.sh after pip install?

In OS X 10.8.2, with Python 2.7:

/Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh

How to add http:// if it doesn't exist in the URL

<?php
    if (!preg_match("/^(http|ftp):/", $_POST['url'])) {
        $_POST['url'] = 'http://'.$_POST['url'];
    }
    $url = $_POST['url'];
?>

This code will add http:// to the URL if it’s not there.

Download old version of package with NuGet

As the original question does not state which NuGet frontend should be used, I would like to mention that NuGet 3.5 adds support for updating to a specific version via the command line client (which works for downgrades, too):

NuGet.exe update Common.Logging -Version 1.2.0

How to use OR condition in a JavaScript IF statement?

You can use Like

if(condition1 || condition2 || condition3 || ..........)
{       
     enter code here
}

Angular2 - Radio Button Binding

This may be not the correct solution but this one is also option hope it will help someone.

Till now i had getting the value of radioButtons using (click) method like following:

<input type="radio" name="options" #male (click)="onChange(male.value)">Male
<input type="radio" name="options" #female (click)="onChange(female.value)">Female

and in the .ts file i have set the value of predefined variable to getter value of onChange function.

But after searching i found good method i have't tried yet but it seems this one is good using [(ng-model)] link is here to github here. this is using RadioControlValueAccessor for the radio as well as checkbox too. here is the working #plnkr# for this method here .

finding and replacing elements in a list

The answers for this old but relevant question are wildly variable in speed.

The fastest of the solution posted by kxr.

However, this is even faster and otherwise not here:

def f1(arr, find, replace):
    # fast and readable
    base=0
    for cnt in range(arr.count(find)):
        offset=arr.index(find, base)
        arr[offset]=replace
        base=offset+1

Here is timing for the various solutions. The faster ones are 3X faster than accepted answer and 5X faster than the slowest answer here.

To be fair, all methods needed to do inlace replacement of the array sent to the function.

Please see timing code below:

def f1(arr, find, replace):
    # fast and readable
    base=0
    for cnt in range(arr.count(find)):
        offset=arr.index(find, base)
        arr[offset]=replace
        base=offset+1
        
def f2(arr,find,replace):
    # accepted answer
    for i,e in enumerate(arr):
        if e==find: 
            arr[i]=replace
        
def f3(arr,find,replace):
    # in place list comprehension
    arr[:]=[replace if e==find else e for e in arr]
    
def f4(arr,find,replace):
    # in place map and lambda -- SLOW
    arr[:]=list(map(lambda x: x if x != find else replace, arr))
    
def f5(arr,find,replace):
    # find index with comprehension
    for i in [i for i, e in enumerate(arr) if e==find]:
        arr[i]=replace
        
def f6(arr,find,replace):
    # FASTEST but a little les clear
    try:
        while True:
            arr[arr.index(find)]=replace
    except ValueError:
        pass    

def f7(lst, old, new):
    """replace list elements (inplace)"""
    i = -1
    try:
        while 1:
            i = lst.index(old, i + 1)
            lst[i] = new
    except ValueError:
        pass
    
    
import time     

def cmpthese(funcs, args=(), cnt=1000, rate=True, micro=True):
    """Generate a Perl style function benchmark"""                   
    def pprint_table(table):
        """Perl style table output"""
        def format_field(field, fmt='{:,.0f}'):
            if type(field) is str: return field
            if type(field) is tuple: return field[1].format(field[0])
            return fmt.format(field)     

        def get_max_col_w(table, index):
            return max([len(format_field(row[index])) for row in table])         

        col_paddings=[get_max_col_w(table, i) for i in range(len(table[0]))]
        for i,row in enumerate(table):
            # left col
            row_tab=[row[0].ljust(col_paddings[0])]
            # rest of the cols
            row_tab+=[format_field(row[j]).rjust(col_paddings[j]) for j in range(1,len(row))]
            print(' '.join(row_tab))                

    results={}
    for i in range(cnt):
        for f in funcs:
            start=time.perf_counter_ns()
            f(*args)
            stop=time.perf_counter_ns()
            results.setdefault(f.__name__, []).append(stop-start)
    results={k:float(sum(v))/len(v) for k,v in results.items()}     
    fastest=sorted(results,key=results.get, reverse=True)
    table=[['']]
    if rate: table[0].append('rate/sec')
    if micro: table[0].append('\u03bcsec/pass')
    table[0].extend(fastest)
    for e in fastest:
        tmp=[e]
        if rate:
            tmp.append('{:,}'.format(int(round(float(cnt)*1000000.0/results[e]))))

        if micro:
            tmp.append('{:,.1f}'.format(results[e]/float(cnt)))

        for x in fastest:
            if x==e: tmp.append('--')
            else: tmp.append('{:.1%}'.format((results[x]-results[e])/results[e]))
        table.append(tmp) 

    pprint_table(table)                    



if __name__=='__main__':
    import sys
    import time 
    print(sys.version)
    cases=(
        ('small, found', 9, 100),
        ('small, not found', 99, 100),
        ('large, found', 9, 1000),
        ('large, not found', 99, 1000)
    )
    for txt, tgt, mul in cases:
        print(f'\n{txt}:')
        arr=[1,2,3,4,5,6,7,8,9,0]*mul 
        args=(arr,tgt,'X')
        cmpthese([f1,f2,f3, f4, f5, f6, f7],args)   

And the results:

3.9.1 (default, Feb  3 2021, 07:38:02) 
[Clang 12.0.0 (clang-1200.0.32.29)]

small, found:
   rate/sec µsec/pass     f4     f3     f5     f2     f6     f7     f1
f4  133,982       7.5     -- -38.8% -49.0% -52.5% -78.5% -78.6% -82.9%
f3  219,090       4.6  63.5%     -- -16.6% -22.4% -64.8% -65.0% -72.0%
f5  262,801       3.8  96.1%  20.0%     --  -6.9% -57.8% -58.0% -66.4%
f2  282,259       3.5 110.7%  28.8%   7.4%     -- -54.6% -54.9% -63.9%
f6  622,122       1.6 364.3% 184.0% 136.7% 120.4%     --  -0.7% -20.5%
f7  626,367       1.6 367.5% 185.9% 138.3% 121.9%   0.7%     -- -19.9%
f1  782,307       1.3 483.9% 257.1% 197.7% 177.2%  25.7%  24.9%     --

small, not found:
   rate/sec µsec/pass     f4     f5     f2     f3     f6     f7     f1
f4   13,846      72.2     -- -40.3% -41.4% -47.8% -85.2% -85.4% -86.2%
f5   23,186      43.1  67.5%     --  -1.9% -12.5% -75.2% -75.5% -76.9%
f2   23,646      42.3  70.8%   2.0%     -- -10.8% -74.8% -75.0% -76.4%
f3   26,512      37.7  91.5%  14.3%  12.1%     -- -71.7% -72.0% -73.5%
f6   93,656      10.7 576.4% 303.9% 296.1% 253.3%     --  -1.0%  -6.5%
f7   94,594      10.6 583.2% 308.0% 300.0% 256.8%   1.0%     --  -5.6%
f1  100,206      10.0 623.7% 332.2% 323.8% 278.0%   7.0%   5.9%     --

large, found:
   rate/sec µsec/pass     f4     f2     f5     f3     f6     f7     f1
f4      145   6,889.4     -- -33.3% -34.8% -48.6% -85.3% -85.4% -85.8%
f2      218   4,593.5  50.0%     --  -2.2% -22.8% -78.0% -78.1% -78.6%
f5      223   4,492.4  53.4%   2.3%     -- -21.1% -77.5% -77.6% -78.2%
f3      282   3,544.0  94.4%  29.6%  26.8%     -- -71.5% -71.6% -72.3%
f6      991   1,009.5 582.4% 355.0% 345.0% 251.1%     --  -0.4%  -2.8%
f7      995   1,005.4 585.2% 356.9% 346.8% 252.5%   0.4%     --  -2.4%
f1    1,019     981.3 602.1% 368.1% 357.8% 261.2%   2.9%   2.5%     --

large, not found:
   rate/sec µsec/pass     f4     f5     f2     f3     f6     f7     f1
f4      147   6,812.0     -- -35.0% -36.4% -48.9% -85.7% -85.8% -86.1%
f5      226   4,424.8  54.0%     --  -2.0% -21.3% -78.0% -78.1% -78.6%
f2      231   4,334.9  57.1%   2.1%     -- -19.6% -77.6% -77.7% -78.2%
f3      287   3,484.0  95.5%  27.0%  24.4%     -- -72.1% -72.2% -72.8%
f6    1,028     972.3 600.6% 355.1% 345.8% 258.3%     --  -0.4%  -2.7%
f7    1,033     968.2 603.6% 357.0% 347.7% 259.8%   0.4%     --  -2.3%
f1    1,057     946.2 619.9% 367.6% 358.1% 268.2%   2.8%   2.3%     --

Convert Unix timestamp to a date string

This solution works with versions of date which do not support date -d @. It does not require AWK or other commands. A Unix timestamp is the number of seconds since Jan 1, 1970, UTC so it is important to specify UTC.

date -d '1970-01-01 1357004952 sec UTC'
Mon Dec 31 17:49:12 PST 2012

If you are on a Mac, then use:

date -r 1357004952

Command for getting epoch:

date +%s
1357004952

Credit goes to Anton: BASH: Convert Unix Timestamp to a Date

'nuget' is not recognized but other nuget commands working

In Visual Studio:

Tools -> Nuget Package Manager -> Package Manager Console.

In PM:

Install-Package NuGet.CommandLine

Close Visual Studio and open it again.

How can I center <ul> <li> into div

Could either be

div ul
{
 width: [INSERT FIXED WIDTH]
 margin: 0 auto;
}

or

div li
{
text-align: center;
}

depends on how it should look like (or combining those)

Exit/save edit to sudoers file? Putty SSH

Be careful to type exactly :wq as Wouter Verleur said at step 7. After type enter, you will save the changes and exit the visudo editor to bash.

PHPMailer AddAddress()

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddAddress($email, $name);
}

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

Counting Chars in EditText Changed Listener

This is a slightly more general answer with more explanation for future viewers.

Add a text changed listener

If you want to find the text length or do something else after the text has been changed, you can add a text changed listener to your edit text.

EditText editText = (EditText) findViewById(R.id.testEditText);
editText.addTextChangedListener(new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count)  {

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});

The listener needs a TextWatcher, which requires three methods to be overridden: beforeTextChanged, onTextChanged, and afterTextChanged.

Counting the characters

You can get the character count in onTextChanged or beforeTextChanged with

charSequence.length()

or in afterTextChanged with

editable.length()

Meaning of the methods

The parameters are a little confusing so here is a little extra explanation.

beforeTextChanged

beforeTextChanged(CharSequence charSequence, int start, int count, int after)

  • charSequence: This is the text content before the pending change is made. You should not try to change it.
  • start: This is the index of where the new text will be inserted. If a range is selected, then it is the beginning index of the range.
  • count: This is the length of selected text that is going to be replaced. If nothing is selected then count will be 0.
  • after: this is the length of the text to be inserted.

onTextChanged

onTextChanged(CharSequence charSequence, int start, int before, int count)

  • charSequence: This is the text content after the change was made. You should not try to modify this value here. Modify the editable in afterTextChanged if you need to.
  • start: This is the index of the start of where the new text was inserted.
  • before: This is the old value. It is the length of previously selected text that was replaced. This is the same value as count in beforeTextChanged.
  • count: This is the length of text that was inserted. This is the same value as after in beforeTextChanged.

afterTextChanged

afterTextChanged(Editable editable)

Like onTextChanged, this is called after the change has already been made. However, now the text may be modified.

  • editable: This is the editable text of the EditText. If you change it, though, you have to be careful not to get into an infinite loop. See the documentation for more details.

Supplemental image from this answer

enter image description here

How to make div same height as parent (displayed as table-cell)

Another option is to set your child div to display: inline-block;

.content {
    display: inline-block;
    height: 100%;
    width: 100%;
    background-color: blue;
}

_x000D_
_x000D_
.container {_x000D_
  display: table;_x000D_
}_x000D_
.child {_x000D_
  width: 30px;_x000D_
  background-color: red;_x000D_
  display: table-cell;_x000D_
  vertical-align: top;_x000D_
}_x000D_
.content {_x000D_
  display: inline-block;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="child">_x000D_
    a_x000D_
    <br />a_x000D_
    <br />a_x000D_
  </div>_x000D_
  <div class="child">_x000D_
    a_x000D_
    <br />a_x000D_
    <br />a_x000D_
    <br />a_x000D_
    <br />a_x000D_
    <br />a_x000D_
    <br />a_x000D_
  </div>_x000D_
  <div class="child">_x000D_
    <div class="content">_x000D_
      a_x000D_
      <br />a_x000D_
      <br />a_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


JSFiddle Demo

How to "Open" and "Save" using java

First off, you'll want to go through Oracle's tutorial to learn how to do basic I/O in Java.

After that, you will want to look at the tutorial on how to use a file chooser.

What does a bitwise shift (left or right) do and what is it used for?

Left bit shifting to multiply by any power of two. Right bit shifting to divide by any power of two.

x = x << 5; // Left shift
y = y >> 5; // Right shift

In C/C++ it can be written as,

#include <math.h>

x = x * pow(2, 5);
y = y / pow(2, 5);

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

Python: "Indentation Error: unindent does not match any outer indentation level"

I had this issue with code that I copied from a blog. I got rid of the issue on PyCharm by Shift+Tab'ing(unindenting) the last error-throwing code-block all the way to the left, and then Tab'ing it back to where it was. I suppose is somehow indirectly working the same as the 'reformat code' comment above.

T-SQL loop over query results

try this:

declare @i tinyint = 0,
    @count tinyint,
    @id int,
    @name varchar(max)

select @count = count(*) from table
while (@i < @count)
begin
    select @id = id, @name = name from table
    order by nr asc offset @i rows fetch next 1 rows only

    exec stored_proc @varName = @id, @otherVarName = 'test', @varForName = @name

    set @i = @i + 1
end

Adding header for HttpURLConnection

I have used the following code in the past and it had worked with basic authentication enabled in TomCat:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();

String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));

myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);

You can try the above code. The code above is for POST, and you can modify it for GET

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

I had this issue today. I'll add a workaround that uses <script defer> as I didn't see the other answers mention it.

//on a JS file somewhere (i.e partial-view-caller.js)
(() => <your partial view script>)();

//in your Partial View
<script src="~/partial-view-caller.js" defer></script>

//you can actually just straight call your partial view script living in an external file - I just prefer having an initialization method :)

Code above is an excerpt from a quick post I made about this question.

Quoting backslashes in Python string literals

What Harley said, except the last point - it's not actually necessary to change the '/'s into '\'s before calling open. Windows is quite happy to accept paths with forward slashes.

infile = open('c:/folder/subfolder/file.txt')

The only time you're likely to need the string normpathed is if you're passing to to another program via the shell (using os.system or the subprocess module).

Removing all script tags from html with JS Regular Expression

If you want to remove all JavaScript code from some HTML text, then removing <script> tags isn't enough, because JavaScript can still live in "onclick", "onerror", "href" and other attributes.

Try out this npm module which handles all of this: https://www.npmjs.com/package/strip-js

Accessing Google Account Id /username via Android

There is a sample from google, which lists the existing google accounts and generates an access token upon selection , you can send that access token to server to retrieve the related details from it to identify the user.

You can also get the email id from access token , for that you need to modify the SCOPE

Please go through My Post

Async/Await Class Constructor

I made this test-case based on @Downgoat's answer.
It runs on NodeJS. This is Downgoat's code where the async part is provided by a setTimeout() call.

'use strict';
const util = require( 'util' );

class AsyncConstructor{

  constructor( lapse ){
    this.qqq = 'QQQ';
    this.lapse = lapse;
    return ( async ( lapse ) => {
      await this.delay( lapse );
      return this;
    })( lapse );
  }

  async delay(ms) {
    return await new Promise(resolve => setTimeout(resolve, ms));
  }

}

let run = async ( millis ) => {
  // Instatiate with await, inside an async function
  let asyncConstructed = await new AsyncConstructor( millis );
  console.log( 'AsyncConstructor: ' + util.inspect( asyncConstructed ));
};

run( 777 );

My use case is DAOs for the server-side of a web application.
As I see DAOs, they are each one associated to a record format, in my case a MongoDB collection like for instance a cook.
A cooksDAO instance holds a cook's data.
In my restless mind I would be able to instantiate a cook's DAO providing the cookId as an argument, and the instantiation would create the object and populate it with the cook's data.
Thus the need to run async stuff into the constructor.
I wanted to write:

let cook = new cooksDAO( '12345' );  

to have available properties like cook.getDisplayName().
With this solution I have to do:

let cook = await new cooksDAO( '12345' );  

which is very similar to the ideal.
Also, I need to do this inside an async function.

My B-plan was to leave the data loading out of the constructor, based on @slebetman suggestion to use an init function, and do something like this:

let cook = new cooksDAO( '12345' );  
async cook.getData();

which doesn't break the rules.

pandas loc vs. iloc vs. at vs. iat?

There are two primary ways that pandas makes selections from a DataFrame.

  • By Label
  • By Integer Location

The documentation uses the term position for referring to integer location. I do not like this terminology as I feel it is confusing. Integer location is more descriptive and is exactly what .iloc stands for. The key word here is INTEGER - you must use integers when selecting by integer location.

Before showing the summary let's all make sure that ...

.ix is deprecated and ambiguous and should never be used

There are three primary indexers for pandas. We have the indexing operator itself (the brackets []), .loc, and .iloc. Let's summarize them:

  • [] - Primarily selects subsets of columns, but can select rows as well. Cannot simultaneously select rows and columns.
  • .loc - selects subsets of rows and columns by label only
  • .iloc - selects subsets of rows and columns by integer location only

I almost never use .at or .iat as they add no additional functionality and with just a small performance increase. I would discourage their use unless you have a very time-sensitive application. Regardless, we have their summary:

  • .at selects a single scalar value in the DataFrame by label only
  • .iat selects a single scalar value in the DataFrame by integer location only

In addition to selection by label and integer location, boolean selection also known as boolean indexing exists.


Examples explaining .loc, .iloc, boolean selection and .at and .iat are shown below

We will first focus on the differences between .loc and .iloc. Before we talk about the differences, it is important to understand that DataFrames have labels that help identify each column and each row. Let's take a look at a sample DataFrame:

df = pd.DataFrame({'age':[30, 2, 12, 4, 32, 33, 69],
                   'color':['blue', 'green', 'red', 'white', 'gray', 'black', 'red'],
                   'food':['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 'Melon', 'Beans'],
                   'height':[165, 70, 120, 80, 180, 172, 150],
                   'score':[4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2],
                   'state':['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']
                   },
                  index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean', 'Christina', 'Cornelia'])

enter image description here

All the words in bold are the labels. The labels, age, color, food, height, score and state are used for the columns. The other labels, Jane, Nick, Aaron, Penelope, Dean, Christina, Cornelia are used as labels for the rows. Collectively, these row labels are known as the index.


The primary ways to select particular rows in a DataFrame are with the .loc and .iloc indexers. Each of these indexers can also be used to simultaneously select columns but it is easier to just focus on rows for now. Also, each of the indexers use a set of brackets that immediately follow their name to make their selections.

.loc selects data only by labels

We will first talk about the .loc indexer which only selects data by the index or column labels. In our sample DataFrame, we have provided meaningful names as values for the index. Many DataFrames will not have any meaningful names and will instead, default to just the integers from 0 to n-1, where n is the length(number of rows) of the DataFrame.

There are many different inputs you can use for .loc three out of them are

  • A string
  • A list of strings
  • Slice notation using strings as the start and stop values

Selecting a single row with .loc with a string

To select a single row of data, place the index label inside of the brackets following .loc.

df.loc['Penelope']

This returns the row of data as a Series

age           4
color     white
food      Apple
height       80
score       3.3
state        AL
Name: Penelope, dtype: object

Selecting multiple rows with .loc with a list of strings

df.loc[['Cornelia', 'Jane', 'Dean']]

This returns a DataFrame with the rows in the order specified in the list:

enter image description here

Selecting multiple rows with .loc with slice notation

Slice notation is defined by a start, stop and step values. When slicing by label, pandas includes the stop value in the return. The following slices from Aaron to Dean, inclusive. Its step size is not explicitly defined but defaulted to 1.

df.loc['Aaron':'Dean']

enter image description here

Complex slices can be taken in the same manner as Python lists.

.iloc selects data only by integer location

Let's now turn to .iloc. Every row and column of data in a DataFrame has an integer location that defines it. This is in addition to the label that is visually displayed in the output. The integer location is simply the number of rows/columns from the top/left beginning at 0.

There are many different inputs you can use for .iloc three out of them are

  • An integer
  • A list of integers
  • Slice notation using integers as the start and stop values

Selecting a single row with .iloc with an integer

df.iloc[4]

This returns the 5th row (integer location 4) as a Series

age           32
color       gray
food      Cheese
height       180
score        1.8
state         AK
Name: Dean, dtype: object

Selecting multiple rows with .iloc with a list of integers

df.iloc[[2, -2]]

This returns a DataFrame of the third and second to last rows:

enter image description here

Selecting multiple rows with .iloc with slice notation

df.iloc[:5:3]

enter image description here


Simultaneous selection of rows and columns with .loc and .iloc

One excellent ability of both .loc/.iloc is their ability to select both rows and columns simultaneously. In the examples above, all the columns were returned from each selection. We can choose columns with the same types of inputs as we do for rows. We simply need to separate the row and column selection with a comma.

For example, we can select rows Jane, and Dean with just the columns height, score and state like this:

df.loc[['Jane', 'Dean'], 'height':]

enter image description here

This uses a list of labels for the rows and slice notation for the columns

We can naturally do similar operations with .iloc using only integers.

df.iloc[[1,4], 2]
Nick      Lamb
Dean    Cheese
Name: food, dtype: object

Simultaneous selection with labels and integer location

.ix was used to make selections simultaneously with labels and integer location which was useful but confusing and ambiguous at times and thankfully it has been deprecated. In the event that you need to make a selection with a mix of labels and integer locations, you will have to make both your selections labels or integer locations.

For instance, if we want to select rows Nick and Cornelia along with columns 2 and 4, we could use .loc by converting the integers to labels with the following:

col_names = df.columns[[2, 4]]
df.loc[['Nick', 'Cornelia'], col_names] 

Or alternatively, convert the index labels to integers with the get_loc index method.

labels = ['Nick', 'Cornelia']
index_ints = [df.index.get_loc(label) for label in labels]
df.iloc[index_ints, [2, 4]]

Boolean Selection

The .loc indexer can also do boolean selection. For instance, if we are interested in finding all the rows where age is above 30 and return just the food and score columns we can do the following:

df.loc[df['age'] > 30, ['food', 'score']] 

You can replicate this with .iloc but you cannot pass it a boolean series. You must convert the boolean Series into a numpy array like this:

df.iloc[(df['age'] > 30).values, [2, 4]] 

Selecting all rows

It is possible to use .loc/.iloc for just column selection. You can select all the rows by using a colon like this:

df.loc[:, 'color':'score':2]

enter image description here


The indexing operator, [], can slice can select rows and columns too but not simultaneously.

Most people are familiar with the primary purpose of the DataFrame indexing operator, which is to select columns. A string selects a single column as a Series and a list of strings selects multiple columns as a DataFrame.

df['food']

Jane          Steak
Nick           Lamb
Aaron         Mango
Penelope      Apple
Dean         Cheese
Christina     Melon
Cornelia      Beans
Name: food, dtype: object

Using a list selects multiple columns

df[['food', 'score']]

enter image description here

What people are less familiar with, is that, when slice notation is used, then selection happens by row labels or by integer location. This is very confusing and something that I almost never use but it does work.

df['Penelope':'Christina'] # slice rows by label

enter image description here

df[2:6:2] # slice rows by integer location

enter image description here

The explicitness of .loc/.iloc for selecting rows is highly preferred. The indexing operator alone is unable to select rows and columns simultaneously.

df[3:5, 'color']
TypeError: unhashable type: 'slice'

Selection by .at and .iat

Selection with .at is nearly identical to .loc but it only selects a single 'cell' in your DataFrame. We usually refer to this cell as a scalar value. To use .at, pass it both a row and column label separated by a comma.

df.at['Christina', 'color']
'black'

Selection with .iat is nearly identical to .iloc but it only selects a single scalar value. You must pass it an integer for both the row and column locations

df.iat[2, 5]
'FL'

How to suppress Update Links warning?

UPDATE:

After all the details summarized and discussed, I spent 2 fair hours in checking the options, and this update is to dot all is.

Preparations

First of all, I performed a clean Office 2010 x86 install on Clean Win7 SP1 Ultimate x64 virtual machine powered by VMWare (this is usual routine for my everyday testing tasks, so I have many of them deployed).

Then, I changed only the following Excel options (i.e. all the other are left as is after installation):

  • Advanced > General > Ask to update automatic links checked:

Ask to update automatic links

  • Trust Center > Trust Center Settings... > External Content > Enable All... (although that one that relates to Data Connections is most likely not important for the case):

External Content

Preconditions

I prepared and placed to C:\ a workbook exactly as per @Siddharth Rout suggestions in his updated answer (shared for your convenience): https://www.dropbox.com/s/mv88vyc27eljqaq/Book1withLinkToBook2.xlsx Linked book was then deleted so that link in the shared book is unavailable (for sure).

Manual Opening

The above shared file shows on opening (having the above listed Excel options) 2 warnings - in the order of appearance:

WARNING #1

This workbook contains links to other data sources

After click on Update I expectedly got another:

WARNING #2

This workbook contains one or more links that cannot be updated

So, I suppose my testing environment is now pretty much similar to OP's) So far so good, we finally go to

VBA Opening

Now I'll try all possible options step by step to make the picture clear. I'll share only relevant lines of code for simplicity (complete sample file with code will be shared in the end).

1. Simple Application.Workbooks.Open

Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"

No surprise - this produces BOTH warnings, as for manual opening above.

2. Application.DisplayAlerts = False

Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True

This code ends up with WARNING #1, and either option clicked (Update / Don't Update) produces NO further warnings, i.e. Application.DisplayAlerts = False suppresses WARNING #2.

3. Application.AskToUpdateLinks = False

Application.AskToUpdateLinks = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.AskToUpdateLinks = True

Opposite to DisplayAlerts, this code ends up with WARNING #2 only, i.e. Application.AskToUpdateLinks = False suppresses WARNING #1.

4. Double False

Application.AskToUpdateLinks = False
Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True

Apparently, this code ends up with suppressing BOTH WARNINGS.

5. UpdateLinks:=False

Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx", UpdateLinks:=False

Finally, this 1-line solution (originally proposed by @brettdj) works the same way as Double False: NO WARNINGS are shown!

Conclusions

Except a good testing practice and very important solved case (I may face such issues everyday while sending my workbooks to 3rd party, and now I'm prepared), 2 more things learned:

  1. Excel options DO matter, regardless of version - especially when we come to VBA solutions.
  2. Every trouble has short and elegant solution - together with not obvious and complicated one. Just one more proof for that!)

Thanks very much to everyone who contributed to the solution, and especially OP who raised the question. Hope my investigations and thoroughly described testing steps were helpful not only for me)

Sample file with the above code samples is shared (many lines are commented deliberately): https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm

Original answer (tested for Excel 2007 with certain options):

This code works fine for me - it loops through ALL Excel files specified using wildcards in the InputFolder:

Sub WorkbookOpening2007()

Dim InputFolder As String
Dim LoopFileNameExt As String

InputFolder = "D:\DOCUMENTS\" 'Trailing "\" is required!

LoopFileNameExt = Dir(InputFolder & "*.xls?")
Do While LoopFileNameExt <> ""

Application.DisplayAlerts = False
Application.Workbooks.Open (InputFolder & LoopFileNameExt)
Application.DisplayAlerts = True

LoopFileNameExt = Dir
Loop

End Sub

I tried it with books with unavailable external links - no warnings.

Sample file: https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

In your eclipse.ini file, you need to update the path to the VM to point to the same location where javaw.exe is installed on your machine.

How can I return NULL from a generic method in C#?

You can just adjust your constraints:

where T : class

Then returning null is allowed.

Constructors in JavaScript objects

I found this tutorial very useful. This approach is used by most of jQuery plug-ins.

http://www.htmlgoodies.com/html5/tutorials/create-an-object-oriented-javascript-class-constructor.html#fbid=OVYAQL_TDpK

var Class = function(methods) {   
    var klass = function() {    
        this.initialize.apply(this, arguments);          
    };  

    for (var property in methods) { 
       klass.prototype[property] = methods[property];
    }

    if (!klass.prototype.initialize) klass.prototype.initialize = function(){};      

    return klass;    
};

Now ,

var Person = Class({ 
    initialize: function(name, age) {
        this.name = name;
        this.age  = age;
    },
    toString: function() {
        return "My name is "+this.name+" and I am "+this.age+" years old.";
    }
}); 

var alice = new Person('Alice', 26);
alert(alice.name); //displays "Alice"
alert(alice.age); //displays "26"
alert(alice.toString()); //displays "My name is Alice and I am 26 years old" in most browsers.
//IE 8 and below display the Object's toString() instead! "[Object object]"

AppendChild() is not a function javascript

 function createQuestionPanel() {

        var element = document.createElement("Input");
        element.setAttribute("type", "button");
        element.setAttribute("value", "button");
        element.setAttribute("name", "button");


        var div = document.createElement("div"); <------- Create DIv Node
        div.appendChild(element);<--------------------
        document.body.appendChild(div) <------------- Then append it to body

    }

    function formvalidate() {

    }

How do I open phone settings when a button is clicked?

SWIFT 5

if let settingsUrl = URL(string: UIApplication.openSettingsURLString) {

   UIApplication.shared.open(settingsUrl)

 }

In iOS 8+ you can do the following:

 func buttonClicked(sender:UIButton)
    {
        UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString))
    }

Swift 4

    let settingsUrl = URL(string: UIApplicationOpenSettingsURLString)!
    UIApplication.shared.open(settingsUrl)

Iterating over dictionaries using 'for' loops

This will print the output in sorted order by values in ascending order.

d = {'x': 3, 'y': 1, 'z': 2}

def by_value(item):
    return item[1]

for key, value in sorted(d.items(), key=by_value):
    print(key, '->', value)

Output:

y -> 1
z -> 2
x -> 3

Find row where values for column is maximal in a pandas DataFrame

mx.iloc[0].idxmax()

This one line of code will give you how to find the maximum value from a row in dataframe, here mx is the dataframe and iloc[0] indicates the 0th index.

Why does visual studio 2012 not find my tests?

I copy-pasted the method declaration, which included an input string parameter. Forgot to delete the input parameter.

  public void ExtractValueFromLineTest(string input) {}//test not discovered because of the string input param

How to make an element in XML schema optional?

Try this

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />

if you want 0 or 1 "description" elements, Or

<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />

if you want 0 to infinity number of "description" elements.

Insert HTML with React Variable Statements (JSX)

To avoid linter errors, I use it like this:

  render() {
    const props = {
      dangerouslySetInnerHTML: { __html: '<br/>' },
    };
    return (
        <div {...props}></div>
    );
  }

How I can get web page's content and save it into the string variable

You can use the WebClient

Using System.Net;
    
WebClient client = new WebClient();
string downloadString = client.DownloadString("http://www.gooogle.com");

Difference between Divide and Conquer Algo and Dynamic Programming

I assume you have already read Wikipedia and other academic resources on this, so I won't recycle any of that information. I must also caveat that I am not a computer science expert by any means, but I'll share my two cents on my understanding of these topics...

Dynamic Programming

Breaks the problem down into discrete subproblems. The recursive algorithm for the Fibonacci sequence is an example of Dynamic Programming, because it solves for fib(n) by first solving for fib(n-1). In order to solve the original problem, it solves a different problem.

Divide and Conquer

These algorithms typically solve similar pieces of the problem, and then put them together at the end. Mergesort is a classic example of divide and conquer. The main difference between this example and the Fibonacci example is that in a mergesort, the division can (theoretically) be arbitrary, and no matter how you slice it up, you are still merging and sorting. The same amount of work has to be done to mergesort the array, no matter how you divide it up. Solving for fib(52) requires more steps than solving for fib(2).

How to parse JSON in Kotlin?

Kotin Seriazation

Kotlin specific library by Jetbrains for all supported platforms – Android, JVM, JavaScript, Native

https://github.com/Kotlin/kotlinx.serialization

Moshi

Moshi is a JSON library for Android and Java by Square.

https://github.com/square/moshi

Jackson

https://github.com/FasterXML/jackson

Gson

Most popular but almost deprecated

https://github.com/google/gson

JSON to Java

http://www.jsonschema2pojo.org/

JSON to Kotlin

IntelliJ plugin - https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-

How do you resize a form to fit its content automatically?

This might be useful. It resizes a new form to a user control, and then anchors the user control to the new form:

Form f = new Form();
MyUserControl muc = new MyUserControl();
f.ClientSize = muc.Size;
f.Controls.Add(muc);
muc.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
f.ShowDialog();

Sending images using Http Post

I struggled a lot trying to implement posting a image from Android client to servlet using httpclient-4.3.5.jar, httpcore-4.3.2.jar, httpmime-4.3.5.jar. I always got a runtime error. I found out that basically you cannot use these jars with Android as Google is using older version of HttpClient in Android. The explanation is here http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html. You need to get the httpclientandroidlib-1.2.1 jar from android http-client library. Then change your imports from or.apache.http.client to ch.boye.httpclientandroidlib. Hope this helps.

Java: Static Class?

  • Final class and private constructor (good but not essential)
  • Public static methods

store return value of a Python script in a bash script

Do not use sys.exit like this. When called with a string argument, the exit code of your process will be 1, signaling an error condition. The string is printed to standard error to indicate what the error might be. sys.exit is not to be used to provide a "return value" for your script.

Instead, you should simply print the "return value" to standard output using a print statement, then call sys.exit(0), and capture the output in the shell.

How to copy file from HDFS to the local file system

bin/hadoop fs -put /localfs/destination/path /hdfs/source/path 

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

Note that git checkout --ours|--theirs will overwrite the files entirely, by choosing either theirs or ours version, which might be or might not be what you want to do (if you have any non-conflicted changes coming from the other side, they will be lost).

If instead you want to perform a three-way merge on the file, and only resolve the conflicted hunks using --ours|--theirs, while keeping non-conflicted hunks from both sides in place, you may want to resort to git merge-file; see details in this answer.

HTML Entity Decode

A more functional approach to @William Lahti's answer:

var entities = {
  'amp': '&',
  'apos': '\'',
  '#x27': '\'',
  '#x2F': '/',
  '#39': '\'',
  '#47': '/',
  'lt': '<',
  'gt': '>',
  'nbsp': ' ',
  'quot': '"'
}

function decodeHTMLEntities (text) {
  return text.replace(/&([^;]+);/gm, function (match, entity) {
    return entities[entity] || match
  })
}

How to do a recursive find/replace of a string with awk or sed?

To replace all content matching string_1 with string_2 of all .c and .h files in the current directory and subdirectories (excluding .git/).

This works on Mac:

find . -type f -path "*.git*" -prune -o -name '*\.[ch]' -exec \
sed -i '' -e 's/'$1'/'$2'/g' {} +

This should work on Linux (Have not tested yet):

find . -type f -path "*.git*" -prune -o -name '*\.[ch]' -exec \
sed -i 's/string_1/string_2/g' {} +

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

Flipper isn't working on 0.61.x, so commenting out/removing initializeFlipper(this) in your MainApplication.java should do the trick.

Chill Pill.

What is the 'realtime' process priority setting for?

A realtime priority thread can never be pre-empted by timer interrupts and runs at a higher priority than any other thread in the system. As such a CPU bound realtime priority thread can totally ruin a machine.

Creating realtime priority threads requires a privilege (SeIncreaseBasePriorityPrivilege) so it can only be done by administrative users.

For Vista and beyond, one option for applications that do require that they run at realtime priorities is to use the Multimedia Class Scheduler Service (MMCSS) and let it manage your threads priority. The MMCSS will prevent your application from using too much CPU time so you don't have to worry about tanking the machine.

CLEAR SCREEN - Oracle SQL Developer shortcut?

To clear the SQL window you can use:

clear screen;

which can also be shortened to

cl scr;

Is there a way to know your current username in mysql?

You can also use : mysql> select user,host from mysql.user;

+---------------+-------------------------------+
| user          | host                          |
+---------------+-------------------------------+
| fkernel       | %                             |
| nagios        | %                             |
| readonly      | %                             |
| replicant     | %                             |
| reporting     | %                             |
| reporting_ro  | %                             |
| nagios        | xx.xx.xx.xx                 |
| haproxy_root  | xx.xx.xx.xx
| root          | 127.0.0.1                     |
| nagios        | localhost                     |
| root          | localhost                     |
+---------------+-------------------------------+

What is the difference between a URI, a URL and a URN?

I found:


A uniform resource identifier(URI) represents something of a big picture. You can split URIs/ URIs can be classified as locators (uniform resource locators- URL), or as names (uniform resource name-URN), or either both. So basically, a URN functions like a person's name and the URL depicts that person's address. So long story short, a URN defines an item's identity, while the URL provides defines the method for finding it, finally encapsulating these two concepts is the URI

Interesting 'takes exactly 1 argument (2 given)' Python error

The call

e.extractAll("th")

for a regular method extractAll() is indeed equivalent to

Extractor.extractAll(e, "th")

These two calls are treated the same in all regards, including the error messages you get.

If you don't need to pass the instance to a method, you can use a staticmethod:

@staticmethod
def extractAll(tag):
    ...

which can be called as e.extractAll("th"). But I wonder why this is a method on a class at all if you don't need to access any instance.

In WPF, what are the differences between the x:Name and Name attributes?

x:Name means: create a field in the code behind to hold a reference to this object.

Name means: set the name property of this object.

round a single column in pandas

If you are doing machine learning and use tensorflow, many float are of 'float32', not 'float64', and none of the methods mentioned in this thread likely to work. You will have to first convert to float64 first.

x.astype('float')

before round(...).

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

Concatenate rows of two dataframes in pandas

call concat and pass param axis=1 to concatenate column-wise:

In [5]:

pd.concat([df_a,df_b], axis=1)
Out[5]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

There is a useful guide to the various methods of merging, joining and concatenating online.

For example, as you have no clashing columns you can merge and use the indices as they have the same number of rows:

In [6]:

df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

And for the same reasons as above a simple join works too:

In [7]:

df_a.join(df_b)
Out[7]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

Convert RGB values to Integer

To get individual colour values you can use Color like following for pixel(x,y).

import java.awt.Color;
import java.awt.image.BufferedImage;

Color c = new Color(buffOriginalImage.getRGB(x,y));
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();

The above will give you the integer values of Red, Green and Blue in range of 0 to 255.

To set the values from RGB you can do so by:

Color myColour = new Color(red, green, blue);
int rgb = myColour.getRGB();

//Change the pixel at (x,y) ti rgb value
image.setRGB(x, y, rgb);

Please be advised that the above changes the value of a single pixel. So if you need to change the value entire image you may need to iterate over the image using two for loops.

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

If the given solutions does not work, create a new project with 'KOTLIN' as the language even if your work is on java. Then replace the 'main' folder of the new project with the 'main' folder of the old.

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

Try to use a

  • $(window).load event

or

  • $(document).ready

    because the initial values may be inconstant because of changes that occur during the parsing or during the DOM load.

Could pandas use column as index?

Yes, with set_index you can make Locality your row index.

data.set_index('Locality', inplace=True)

If inplace=True is not provided, set_index returns the modified dataframe as a result.

Example:

> import pandas as pd
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
                     ['ABERFELDIE', 534000, 600000]],
                    columns=['Locality', 2005, 2006])

> df
     Locality    2005    2006
0  ABBOTSFORD  427000  448000
1  ABERFELDIE  534000  600000

> df.set_index('Locality', inplace=True)
> df
              2005    2006
Locality                  
ABBOTSFORD  427000  448000
ABERFELDIE  534000  600000

> df.loc['ABBOTSFORD']
2005    427000
2006    448000
Name: ABBOTSFORD, dtype: int64

> df.loc['ABBOTSFORD'][2005]
427000

> df.loc['ABBOTSFORD'].values
array([427000, 448000])

> df.loc['ABBOTSFORD'].tolist()
[427000, 448000]

How can I delete all cookies with JavaScript?

There is no 100% solution to delete browser cookies.

The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".

Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!

However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:

function clearCookie(name, domain, path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};

Differences between utf8 and latin1

UTF-8 is prepared for world domination, Latin1 isn't.

If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).

Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4.

Travel/Hotel API's?

You could probably trying using Yahoo or Google's APIs. They are generic, but by specifying the right set of parameters, you could probably narrow down the results to just hotels. Check out Yahoo's Local Search API and Google's Local Search API

How to pass boolean parameter value in pipeline to downstream jobs?

Jenkins "boolean" parameters are really just a shortcut for the "choice parameter" type with the choices hardcoded to the strings "true" and "false", and with a checkbox to set the string variable. But in the end, it is just that: a string variable, with nothing to do with a true boolean. That's why you need to convert the string to a boolean if you don't want to do a string comparison like:

if (myBoolean == "true")

@Value annotation type casting to Integer from String

I had the exact same situation. It was caused by not having a PropertySourcesPlaceholderConfigurer in the Spring context, which resolves values against the @Value annotation inside of classes.

Include a property placeholder to solve the problem, no need to use Spring expressions for integers (the property file does not have to exist if you use ignore-resource-not-found="true"):

<context:property-placeholder location="/path/to/my/app.properties"
    ignore-resource-not-found="true" />

Fitting polynomial model to data in R

Which model is the "best fitting model" depends on what you mean by "best". R has tools to help, but you need to provide the definition for "best" to choose between them. Consider the following example data and code:

x <- 1:10
y <- x + c(-0.5,0.5)

plot(x,y, xlim=c(0,11), ylim=c(-1,12))

fit1 <- lm( y~offset(x) -1 )
fit2 <- lm( y~x )
fit3 <- lm( y~poly(x,3) )
fit4 <- lm( y~poly(x,9) )
library(splines)
fit5 <- lm( y~ns(x, 3) )
fit6 <- lm( y~ns(x, 9) )

fit7 <- lm( y ~ x + cos(x*pi) )

xx <- seq(0,11, length.out=250)
lines(xx, predict(fit1, data.frame(x=xx)), col='blue')
lines(xx, predict(fit2, data.frame(x=xx)), col='green')
lines(xx, predict(fit3, data.frame(x=xx)), col='red')
lines(xx, predict(fit4, data.frame(x=xx)), col='purple')
lines(xx, predict(fit5, data.frame(x=xx)), col='orange')
lines(xx, predict(fit6, data.frame(x=xx)), col='grey')
lines(xx, predict(fit7, data.frame(x=xx)), col='black')

Which of those models is the best? arguments could be made for any of them (but I for one would not want to use the purple one for interpolation).

How to convert time milliseconds to hours, min, sec format in JavaScript?

Human-readable code for human-readable output and you can extend this to light years or nanoseconds or what have you very intuitively. Obviously you'd want to convert this to a function and re-use some of those intermediate modulo calls.

second = 1000 
minute = second * 60
hour = minute * 60 
day = hour * 24

test = 3 * day + 2 * hour + 11 * minute + 58 * second

console.log(Math.floor(test / day))
console.log(Math.floor(test % day / hour))
console.log(Math.floor(test % day % hour / minute))
console.log(Math.floor(test % day % hour % minute / second))

TERM environment variable not set

You can see if it's really not set. Run the command set | grep TERM.

If not, you can set it like that: export TERM=xterm

How to encode the filename parameter of Content-Disposition header in HTTP?

There is discussion of this, including links to browser testing and backwards compatibility, in the proposed RFC 5987, "Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters."

RFC 2183 indicates that such headers should be encoded according to RFC 2184, which was obsoleted by RFC 2231, covered by the draft RFC above.

How to create a link to a directory

Symbolic or soft link (files or directories, more flexible and self documenting)

#     Source                             Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard link (files only, less flexible and not self documenting)

#   Source                             Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

More information: man ln


/home/jake/xxx is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:

  1. cd /home/jake/
  2. ln -s /home/jake/doc/test/2000/something xxx

How can I programmatically get the MAC address of an iphone

@Grantland This "pretty clean solution" looks similar to my own improvement over iPhoneDeveloperTips solution.

You can see my step here: https://gist.github.com/1409855/

/* Original source code courtesy John from iOSDeveloperTips.com */

#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

+ (NSString *)getMacAddress
{
    int                 mgmtInfoBase[6];
    char                *msgBuffer = NULL;
    NSString            *errorFlag = NULL;
    size_t              length;

    // Setup the management Information Base (mib)
    mgmtInfoBase[0] = CTL_NET;        // Request network subsystem
    mgmtInfoBase[1] = AF_ROUTE;       // Routing table info
    mgmtInfoBase[2] = 0;              
    mgmtInfoBase[3] = AF_LINK;        // Request link layer information
    mgmtInfoBase[4] = NET_RT_IFLIST;  // Request all configured interfaces

    // With all configured interfaces requested, get handle index
    if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0) 
        errorFlag = @"if_nametoindex failure";
    // Get the size of the data available (store in len)
    else if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0) 
        errorFlag = @"sysctl mgmtInfoBase failure";
    // Alloc memory based on above call
    else if ((msgBuffer = malloc(length)) == NULL)
        errorFlag = @"buffer allocation failure";
    // Get system information, store in buffer
    else if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
    {
        free(msgBuffer);
        errorFlag = @"sysctl msgBuffer failure";
    }
    else
    {
        // Map msgbuffer to interface message structure
        struct if_msghdr *interfaceMsgStruct = (struct if_msghdr *) msgBuffer;

        // Map to link-level socket structure
        struct sockaddr_dl *socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);

        // Copy link layer address data in socket structure to an array
        unsigned char macAddress[6];
        memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);

        // Read from char array into a string object, into traditional Mac address format
        NSString *macAddressString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                                      macAddress[0], macAddress[1], macAddress[2], macAddress[3], macAddress[4], macAddress[5]];
        NSLog(@"Mac Address: %@", macAddressString);

        // Release the buffer memory
        free(msgBuffer);

        return macAddressString;
    }

    // Error...
    NSLog(@"Error: %@", errorFlag);

    return nil;
}

How to run DOS/CMD/Command Prompt commands from VB.NET?

I was inspired by Steve's answer but thought I'd add a bit of flare to it. I like to do the work up front of writing extension methods so later I have less work to do calling the method.

For example with the modified version of Steve's answer below, instead of making this call...

MyUtilities.RunCommandCom("DIR", "/W", true)

I can actually just type out the command and call it from my strings like this...

Directly in code.

Call "CD %APPDATA% & TREE".RunCMD()

OR

From a variable.

Dim MyCommand = "CD %APPDATA% & TREE"
MyCommand.RunCMD()

OR

From a textbox.

textbox.text.RunCMD(WaitForProcessComplete:=True)


Extension methods will need to be placed in a Public Module and carry the <Extension> attribute over the sub. You will also want to add Imports System.Runtime.CompilerServices to the top of your code file.

There's plenty of info on SO about Extension Methods if you need further help.


Extension Method

Public Module Extensions
''' <summary>
''' Extension method to run string as CMD command.
''' </summary>
''' <param name="command">[String] Command to run.</param>
''' <param name="ShowWindow">[Boolean](Default:False) Option to show CMD window.</param>
''' <param name="WaitForProcessComplete">[Boolean](Default:False) Option to wait for CMD process to complete before exiting sub.</param>
''' <param name="permanent">[Boolean](Default:False) Option to keep window visible after command has finished. Ignored if ShowWindow is False.</param>
<Extension>
Public Sub RunCMD(command As String, Optional ShowWindow As Boolean = False, Optional WaitForProcessComplete As Boolean = False, Optional permanent As Boolean = False)
    Dim p As Process = New Process()
    Dim pi As ProcessStartInfo = New ProcessStartInfo()
    pi.Arguments = " " + If(ShowWindow AndAlso permanent, "/K", "/C") + " " + command
    pi.FileName = "cmd.exe"
    pi.CreateNoWindow = Not ShowWindow
    If ShowWindow Then
        pi.WindowStyle = ProcessWindowStyle.Normal
    Else
        pi.WindowStyle = ProcessWindowStyle.Hidden
    End If
    p.StartInfo = pi
    p.Start()
    If WaitForProcessComplete Then Do Until p.HasExited : Loop
End Sub
End Module

java.util.Date and getYear()

The java documentation suggests to make use of Calendar class instead of this deprecated way Here is the sample code to set up the calendar object

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());

Here is the sample code to get the year, month, etc.

System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.MONTH));

Calendar also has support for many other useful information like, TIME, DAY_OF_MONTH, etc. Here the documentation listing all of them Please note that the month are 0 based. January is 0th month.

Simplest way to download and unzip files in Node.js cross-platform?

yauzl is a robust library for unzipping. Design principles:

  • Follow the spec. Don't scan for local file headers. Read the central directory for file metadata.
  • Don't block the JavaScript thread. Use and provide async APIs.
  • Keep memory usage under control. Don't attempt to buffer entire files in RAM at once.
  • Never crash (if used properly). Don't let malformed zip files bring down client applications who are trying to catch errors.
  • Catch unsafe filenames entries. A zip file entry throws an error if its file name starts with "/" or /[A-Za-z]:// or if it contains ".." path segments or "\" (per the spec).

Currently has 97% test coverage.

Passing parameter to controller action from a Html.ActionLink

Addition to the accepted answer:

if you are going to use

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 },null)

this will create actionlink where you can't create new custom attribute or style for the link.

However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 }, new { @class = "btn btn-info", @target = "_blank" })

mysql query result in php variable

I personally use prepared statements.

Why is it important?

Well it's important because of security. It's very easy to do an SQL injection on someone who use variables in the query.

Instead of using this code:

$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);

You should use this

$stmt = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password); //You need the variables to do something as well.
$stmt->execute();

Learn more about prepared statements on:

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php MySQLI

http://php.net/manual/en/pdo.prepared-statements.php PDO

Not class selector in jQuery

You need the :not() selector:

$('div[class^="first-"]:not(.first-bar)')

or, alternatively, the .not() method:

$('div[class^="first-"]').not('.first-bar');

IF-THEN-ELSE statements in postgresql

In general, an alternative to case when ... is coalesce(nullif(x,bad_value),y) (that cannot be used in OP's case). For example,

select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
from (     (select 'abc' as x, '' as y)
 union all (select 'def' as x, 'ghi' as y)
 union all (select '' as x, 'jkl' as y)
 union all (select null as x, 'mno' as y)
 union all (select 'pqr' as x, null as y)
) q

gives:

 coalesce | coalesce |  x  |  y  
----------+----------+-----+-----
 abc      | abc      | abc | 
 ghi      | def      | def | ghi
 jkl      | jkl      |     | jkl
 mno      | mno      |     | mno
 pqr      | pqr      | pqr | 
(5 rows)

How do I disable a jquery-ui draggable?

The following is what this would look like inside of .draggable({});

$("#yourDraggable").draggable({
    revert: "invalid" ,
    start: function(){ 
        $(this).css("opacity",0.3);
    },
    stop: function(){ 
        $(this).draggable( 'disable' )
    },
    opacity: 0.7,
    helper: function () { 
        $copy = $(this).clone(); 
        $copy.css({
            "list-style":"none",
            "width":$(this).outerWidth()
        }); 
        return $copy; 
    },
    appendTo: 'body',
    scroll: false
});

How to render an ASP.NET MVC view as a string?

To repeat from a more unknown question, take a look at MvcIntegrationTestFramework.

It makes saves you writing your own helpers to stream result and is proven to work well enough. I'd assume this would be in a test project and as a bonus you would have the other testing capabilities once you've got this setup. Main bother would probably be sorting out the dependency chain.

 private static readonly string mvcAppPath = 
     Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory 
     + "\\..\\..\\..\\MyMvcApplication");
 private readonly AppHost appHost = new AppHost(mvcAppPath);

    [Test]
    public void Root_Url_Renders_Index_View()
    {
        appHost.SimulateBrowsingSession(browsingSession => {
            RequestResult result = browsingSession.ProcessRequest("");
            Assert.IsTrue(result.ResponseText.Contains("<!DOCTYPE html"));
        });
}

Oracle Add 1 hour in SQL

To add/subtract from a DATE, you have 2 options :

Method #1 : The easiest way is to use + and - to add/subtract days, hours, minutes, seconds, etc.. from a DATE, and ADD_MONTHS() function to add/subtract months and years from a DATE. Why ? That's because from days, you can get hours and any smaller unit (1 hour = 1/24 days), (1 minute = 1/1440 days), etc... But you cannot get months and years, as that depends on the month and year themselves, hence ADD_MONTHS() and no add_years(), because from months, you can get years (1 year = 12 months).

Let's try them :

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS')             FROM dual;        -- prints current date:    19-OCT-2019 20:42:02 
SELECT TO_CHAR((SYSDATE + 1/24), 'DD-MON-YYYY HH24:MI:SS')    FROM dual;        -- prints date + 1 hour:   19-OCT-2019 21:42:02
SELECT TO_CHAR((SYSDATE + 1/1440), 'DD-MON-YYYY HH24:MI:SS')  FROM dual;        -- prints date + 1 minute: 19-OCT-2019 20:43:02 
SELECT TO_CHAR((SYSDATE + 1/86400), 'DD-MON-YYYY HH24:MI:SS') FROM dual;        -- prints date + 1 second: 19-OCT-2019 20:42:03 
-- Same goes for subtraction.

SELECT SYSDATE                  FROM dual;       -- prints current date:     19-OCT-19
SELECT ADD_MONTHS(SYSDATE, 1)   FROM dual;       -- prints date + 1 month:   19-NOV-19
SELECT ADD_MONTHS(SYSDATE, 12)  FROM dual;       -- prints date + 1 year:    19-OCT-20
SELECT ADD_MONTHS(SYSDATE, -3)  FROM dual;       -- prints date - 3 months:  19-JUL-19

Method #2 : Using INTERVALs, you can or subtract an interval (duration) from a date easily. More than that, you can combine to add or subtract multiple units at once (e.g 5 hours and 6 minutes, etc..) Examples :

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS')                                        FROM dual;        -- prints current date:                 19-OCT-2019 21:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' HOUR), 'DD-MON-YYYY HH24:MI:SS')                  FROM dual;        -- prints date + 1 hour:                19-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' MINUTE), 'DD-MON-YYYY HH24:MI:SS')                FROM dual;        -- prints date + 1 minute:              19-OCT-2019 21:35:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' SECOND), 'DD-MON-YYYY HH24:MI:SS')                FROM dual;        -- prints date + 1 second:              19-OCT-2019 21:34:16
SELECT TO_CHAR((SYSDATE + INTERVAL '01:05:00' HOUR TO SECOND), 'DD-MON-YYYY HH24:MI:SS') FROM dual;        -- prints date + 1 hour and 5 minutes:  19-OCT-2019 22:39:15
SELECT TO_CHAR((SYSDATE + INTERVAL '3 01' DAY TO HOUR), 'DD-MON-YYYY HH24:MI:SS')        FROM dual;        -- prints date + 3 days and 1 hour:     22-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE - INTERVAL '10-3' YEAR TO MONTH), 'DD-MON-YYYY HH24:MI:SS')      FROM dual;        -- prints date - 10 years and 3 months: 19-JUL-2009 21:34:15

Is it possible to have empty RequestParam values use the defaultValue?

You can keep primitive type by setting default value, in the your case just add "required = false" property:

@RequestParam(value = "i", required = false, defaultValue = "10") int i

P.S. This page from Spring documentation might be useful: Annotation Type RequestParam

What is the difference between a data flow diagram and a flow chart?

Data flow diagram shows the flow of data between the different entities and datastores in a system while a flow chart shows the steps involved to carried out a task. In a sense, data flow diagram provides a very high level view of the system, while a flow chart is a lower level view (basically showing the algorithm).

Whether you use data flow diagram or flow charts depends on figuring out what is it that you are trying to show.

SQL Server : error converting data type varchar to numeric

If you are running SQL Server 2012 or newer you can also use the new TRY_PARSE() function:

Returns the result of an expression, translated to the requested data type, or null if the cast fails in SQL Server. Use TRY_PARSE only for converting from string to date/time and number types.

Or TRY_CONVERT/TRY_CAST:

Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

Convert double to string

Try c.ToString("F6");

(For a full explanation of numeric formatting, see MSDN)

Add a space (" ") after an element using :after

Turns out it needs to be specified via escaped unicode. This question is related and contains the answer.

The solution:

h2:after {
    content: "\00a0";
}

How to convert file to base64 in JavaScript?

JavaScript btoa() function can be used to convert data into base64 encoded string

MySQL 'Order By' - sorting alphanumeric correctly

This type of question has been asked previously.

The type of sorting you are talking about is called "Natural Sorting". The data on which you want to do sort is alphanumeric. It would be better to create a new column for sorting.

For further help check natural-sort-in-mysql

Playing mp3 song on python

A simple solution:

import webbrowser
webbrowser.open("C:\Users\Public\Music\Sample Music\Kalimba.mp3")

cheers...

What does the M stand for in C# Decimal literal notation?

It means it's a decimal literal, as others have said. However, the origins are probably not those suggested elsewhere in this answer. From the C# Annotated Standard (the ECMA version, not the MS version):

The decimal suffix is M/m since D/d was already taken by double. Although it has been suggested that M stands for money, Peter Golde recalls that M was chosen simply as the next best letter in decimal.

A similar annotation mentions that early versions of C# included "Y" and "S" for byte and short literals respectively. They were dropped on the grounds of not being useful very often.

jQuery - passing value from one input to another

Get input1 data to send them to input2 immediately

<div>
<label>Input1</label>
 <input type="text" id="input1" value="">
</div>

</br>
<label>Input2</label>
<input type="text" id="input2" value="">

<script type="text/javascript">
        $(document).ready(function () {
            $("#input1").keyup(function () {
                var value = $(this).val();
                $("#input2").val(value);
            });
        });
</script>

Maven compile with multiple src directories

While the answer from evokk is basically correct, it is missing test classes. You must add test classes with goal add-test-source:

<execution>
    <phase>generate-sources</phase>
    <goals>
        <goal>add-test-source</goal>
    </goals>
    <configuration>
       <sources>
            <source>target/generated/some-test-classes</source>
        </sources>
    </configuration>
</execution>

HttpRequest maximum allowable size in tomcat?

The connector section has the parameter

maxPostSize

The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than or equal to 0. If not specified, this attribute is set to 2097152 (2 megabytes).

Another Limit is:

maxHttpHeaderSize The maximum size of the request and response HTTP header, specified in bytes. If not specified, this attribute is set to 4096 (4 KB).

You find them in

$TOMCAT_HOME/conf/server.xml

Getting IPV4 address from a sockaddr structure

Just cast the entire sockaddr structure to a sockaddr_in. Then you can use:

char *ip = inet_ntoa(their_addr.sin_addr)

To retrieve the standard ip representation.

Escape double quotes in a string

One solution, is to add support to the csharp language so that "" isn't the only scheme used for strings.

For another string terminator to the C# language - I'm a fan of backtick in ES6.

string test = `He said to me, "Hello World". How are you?`;

But also, the doubling idea in Markdown might be better:

string test = ""He said to me, "Hello World". How are you?"";

The code does not work at the date of this post. This post is a solution where the visitors to this Q&A jump onto this csharplank ticket for C# and upvote it - https://github.com/dotnet/csharplang/discussions/3917

Xcode variables

The best source is probably Apple's official documentation. The specific variable you are looking for is CONFIGURATION.

Parsing time string in Python

It has discussed many times in SO. In short, "%z" is not supported because platform not support it. My solution is a new one, just skip the time zone.:

    datetime.datetime.strptime(re.sub(r"[+-]([0-9])+", "", "Tue May 08 15:14:45 +0800 2012"),"%a %b %d %H:%M:%S %Y")

Convert SQL Server result set into string

Both answers are valid, but don't forget to initializate the value of the variable, by default is NULL and with T-SQL:

NULL + "Any text" => NULL

It's a very common mistake, don't forget it!

Also is good idea to use ISNULL function:

SELECT @result = @result + ISNULL(StudentId + ',', '') FROM Student

Prevent WebView from displaying "web page not available"

try this shouldOverrideUrlLoading , before redirect to another url check for internet conncetion based on that page should be loaded or not.

Uncaught Typeerror: cannot read property 'innerHTML' of null

Looks like the script executes before the DOM loads. Try loading the script asynchronously.

 <script src="yourcode.js" async></script>

How to declare strings in C

Strings in C are represented as arrays of characters.

char *p = "String";

You are declaring a pointer that points to a string stored some where in your program (modifying this string is undefined behavior) according to the C programming language 2 ed.

char p2[] = "String";

You are declaring an array of char initialized with the string "String" leaving to the compiler the job to count the size of the array.

char p3[5] = "String";

You are declaring an array of size 5 and initializing it with "String". This is an error be cause "String" don't fit in 5 elements.

char p3[7] = "String"; is the correct declaration ('\0' is the terminating character in c strings).

http://c-faq.com/~scs/cclass/notes/sx8.html

Difference between DTO, VO, POJO, JavaBeans?

POJO : It is a java file(class) which doesn't extend or implement any other java file(class).

Bean: It is a java file(class) in which all variables are private, methods are public and appropriate getters and setters are used for accessing variables.

Normal class: It is a java file(class) which may consist of public/private/default/protected variables and which may or may not extend or implement another java file(class).

Relative imports in Python 3

I had a similar problem: I needed a Linux service and cgi plugin which use common constants to cooperate. The 'natural' way to do this is to place them in the init.py of the package, but I cannot start the cgi plugin with the -m parameter.

My final solution was similar to Solution #2 above:

import sys
import pathlib as p
import importlib

pp = p.Path(sys.argv[0])
pack = pp.resolve().parent

pkg = importlib.import_module('__init__', package=str(pack))

The disadvantage is that you must prefix the constants (or common functions) with pkg:

print(pkg.Glob)

Set initially selected item in Select list in Angular2

Okay, so I figured out what the problem was, and the approach I believe works best. In my case, because the two objects weren't identical from a Javascript perspective, as in: they may have shared the same values, but they were different actual objects, e.g. originalObject was instantiated entirely separately from objects which was essentially an array of reference data (to populate the dropdown).

I found that the approach that worked best for me was to compare a unique property of the objects, rather than directly compare the two entire objects. This comparison is done in the bound property selected:

<select [ngModel]="originalObject">
    <option *ngFor="let object of objects" [ngValue]="object" [selected]="object.uniqueId === originalObject.uniqueId">{{object.name}}</option>
</select>

MySQL Trigger: Delete From Table AFTER DELETE

Why not set ON CASCADE DELETE on Foreign Key patron_info.pid?

SQLException : String or binary data would be truncated

In general, there isn't a way to determine which particular statement caused the error. If you're running several, you could watch profiler and look at the last completed statement and see what the statement after that might be, though I have no idea if that approach is feasible for you.

In any event, one of your parameter variables (and the data inside it) is too large for the field it's trying to store data in. Check your parameter sizes against column sizes and the field(s) in question should be evident pretty quickly.

Controlling a USB power supply (on/off) with Linux

You could use my tool uhubctl to control USB power per port for compatible USB hubs.

Asynchronous Process inside a javascript for loop

_x000D_
_x000D_
var i = 0;_x000D_
var length = 10;_x000D_
_x000D_
function for1() {_x000D_
  console.log(i);_x000D_
  for2();_x000D_
}_x000D_
_x000D_
function for2() {_x000D_
  if (i == length) {_x000D_
    return false;_x000D_
  }_x000D_
  setTimeout(function() {_x000D_
    i++;_x000D_
    for1();_x000D_
  }, 500);_x000D_
}_x000D_
for1();
_x000D_
_x000D_
_x000D_

Here is a sample functional approach to what is expected here.

codeigniter, result() vs. result_array()

result_array() is faster, result() is easier

postgresql return 0 if returned value is null

use coalesce

COALESCE(value [, ...])
The COALESCE function returns the first of its arguments that is not null.  
Null is returned only if all arguments are null. It is often
used to substitute a default value for null values when data is
retrieved for display.

Edit

Here's an example of COALESCE with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5

IMHO COALESCE should not be use with AVG because it modifies the value. NULL means unknown and nothing else. It's not like using it in SUM. In this example, if we replace AVG by SUM, the result is not distorted. Adding 0 to a sum doesn't hurt anyone but calculating an average with 0 for the unknown values, you don't get the real average.

In that case, I would add price IS NOT NULL in WHERE clause to avoid these unknown values.

How do I change the default location for Git Bash on Windows?

If you're like me, and the way you get to Git is windows key + G + I + Enter, then you can simply hit the windows key, search for Git, right click on the resulting Git Bash icon, select properties, and change the Start in: field.

I'm not exactly sure what this does, because I'm not exactly sure what Git on Windows is (a facade on top of sh which itself is a facade on cmd?), but in any case, you can now pin the shortcut that Windows pulls up on a search for "Git" to your taskbar, or to your desktop, and it will still start in whatever directory you set it to.

git rebase: "error: cannot stat 'file': Permission denied"

Using SourceTree in Win 10, fixed the problem by closing Atom editor.

Error reproduce:

  1. In branch B, create a md file, using Atom edit it, save and commit.
  2. Switch to branch A, pull down new commits from server.
  3. Try Switch back, Opps, it says “error: cannot stat 'file': Permission denied”.

What does ':' (colon) do in JavaScript?

You guys are forgetting that the colon is also used in the ternary operator (though I don't know if jquery uses it for this purpose).

the ternary operator is an expression form (expressions return a value) of an if/then statement. it's used like this:

var result = (condition) ? (value1) : (value2) ;

A ternary operator could also be used to produce side effects just like if/then, but this is profoundly bad practice.

Select option padding not working in chrome

I just found a way to get padding applied to the select input in chrome

select{
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    padding: 5px;
}

Seems to work in the current chrome 39.0.2171.71 (64-bit) and safari (I only tested this on a mac).

This seems to remove the default styling added to the select input (it also removed the drop down arrow), but allows you to then use your own styling without chrome overriding it.

I stumbled across this fix while using code from here: http://fettblog.eu/style-select-elements/

CSS: How can I set image size relative to parent height?

Use max-width property of CSS, like this :

img{
  max-width:100%;
}

How to update MySql timestamp column to current timestamp on PHP?

Use this query:

UPDATE `table` SET date_date=now();

Sample code can be:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("UPDATE `table` SET date_date=now()");

mysql_close($con);
?>

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

My system version: ubuntu 20.04 LTS.

  • I solved this by generate a new MOK and enroll it into shim.

  • Without disable of Secure Boot, although it also really works for me.

  • Simply execute this command and follow what it suggests:

    sudo update-secureboot-policy --enroll-key
    

According to ubuntu's wiki: How can I do non-automated signing of drivers

Is it possible to read from a InputStream with a timeout?

If your InputStream is backed by a Socket, you can set a Socket timeout (in milliseconds) using setSoTimeout. If the read() call doesn't unblock within the timeout specified, it will throw a SocketTimeoutException.

Just make sure that you call setSoTimeout on the Socket before making the read() call.

handle textview link click in my android app

Here is a more generic solution based on @Arun answer

public abstract class TextViewLinkHandler extends LinkMovementMethod {

    public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
        if (event.getAction() != MotionEvent.ACTION_UP)
            return super.onTouchEvent(widget, buffer, event);

        int x = (int) event.getX();
        int y = (int) event.getY();

        x -= widget.getTotalPaddingLeft();
        y -= widget.getTotalPaddingTop();

        x += widget.getScrollX();
        y += widget.getScrollY();

        Layout layout = widget.getLayout();
        int line = layout.getLineForVertical(y);
        int off = layout.getOffsetForHorizontal(line, x);

        URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
        if (link.length != 0) {
            onLinkClick(link[0].getURL());
        }
        return true;
    }

    abstract public void onLinkClick(String url);
}

To use it just implement onLinkClick of TextViewLinkHandler class. For instance:

    textView.setMovementMethod(new TextViewLinkHandler() {
        @Override
        public void onLinkClick(String url) {
            Toast.makeText(textView.getContext(), url, Toast.LENGTH_SHORT).show();
        }
    });

Regex not operator

Not quite, although generally you can usually use some workaround on one of the forms

  • [^abc], which is character by character not a or b or c,
  • or negative lookahead: a(?!b), which is a not followed by b
  • or negative lookbehind: (?<!a)b, which is b not preceeded by a

Launch an app from within another (iPhone)

No it's not. Besides the documented URL handlers, there's no way to communicate with/launch another app.

How to iterate through SparseArray?

If you use Kotlin, you can use extension functions as such, for example:

fun <T> LongSparseArray<T>.valuesIterator(): Iterator<T> {
    val nSize = this.size()
    return object : Iterator<T> {
        var i = 0
        override fun hasNext(): Boolean = i < nSize
        override fun next(): T = valueAt(i++)
    }
}

fun <T> LongSparseArray<T>.keysIterator(): Iterator<Long> {
    val nSize = this.size()
    return object : Iterator<Long> {
        var i = 0
        override fun hasNext(): Boolean = i < nSize
        override fun next(): Long = keyAt(i++)
    }
}

fun <T> LongSparseArray<T>.entriesIterator(): Iterator<Pair<Long, T>> {
    val nSize = this.size()
    return object : Iterator<Pair<Long, T>> {
        var i = 0
        override fun hasNext(): Boolean = i < nSize
        override fun next() = Pair(keyAt(i), valueAt(i++))
    }
}

You can also convert to a list, if you wish. Example:

sparseArray.keysIterator().asSequence().toList()

I think it might even be safe to delete items using remove on the LongSparseArray itself (not on the iterator), as it is in ascending order.


EDIT: Seems there is even an easier way, by using collection-ktx (example here) . It's implemented in a very similar way to what I wrote, actally.

Gradle requires this:

implementation 'androidx.core:core-ktx:#'
implementation 'androidx.collection:collection-ktx:#'

Here's the usage for LongSparseArray :

    val sparse= LongSparseArray<String>()
    for (key in sparse.keyIterator()) {
    }
    for (value in sparse.valueIterator()) {
    }
    sparse.forEach { key, value -> 
    }

And for those that use Java, you can use LongSparseArrayKt.keyIterator , LongSparseArrayKt.valueIterator and LongSparseArrayKt.forEach , for example. Same for the other cases.

c++ Read from .csv file

That because your csv file is in invalid format, maybe the line break in your text file is not the \n or \r

and, using c/c++ to parse text is not a good idea. try awk:

 $awk -F"," '{print "ID="$1"\tName="$2"\tAge="$3"\tGender="$4}' 1.csv
 ID=0   Name=Filipe Age=19  Gender=M
 ID=1   Name=Maria  Age=20  Gender=F
 ID=2   Name=Walter Age=60  Gender=M

Console.WriteLine and generic List

list.ForEach(x=>Console.WriteLine(x));

How do I create dynamic variable names inside a loop?

 var marker+i = "some stuff";

coudl be interpreted like this: create a variable named marker (undefined); then add to i; then try to assign a value to to the result of an expression, not possible. What firebug is saying is this: var marker; i = 'some stuff'; this is what firebug expects a comma after marker and before i; var is a statement and don't (apparently) accepts expressions. Not so good an explanation but i hope it helps.

How to redirect the output of print to a TXT file

Building on previous answers, I think it's a perfect use case for doing it (simple) context manager style:

import sys

class StdoutRedirection:
    """Standard output redirection context manager"""

    def __init__(self, path):
        self._path = path

    def __enter__(self):
        sys.stdout = open(self._path, mode="w")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.close()
        sys.stdout = sys.__stdout__

and then:

with StdoutRedirection("path/to/file"):
    print("Hello world")

Also it would be really easy to add some functionality to StdoutRedirection class (e.g. a method that lets you change the path)

What is the difference between Html.Hidden and Html.HiddenFor

The Html.Hidden creates a hidden input but you have to specify the name and all the attributes you want to give that field and value. The Html.HiddenFor creates a hidden input for the object that you pass to it, they look like this:

Html.Hidden("yourProperty",model.yourProperty);

Html.HiddenFor(m => m.yourProperty)

In this case the output is the same!

Can overridden methods differ in return type?

class Phone {
    public Phone getMsg() {
        System.out.println("phone...");
        return new Phone();
    }
}

class Samsung extends Phone{
    @Override
    public Samsung getMsg() {
        System.out.println("samsung...");
        return new Samsung();
    }
    
    public static void main(String[] args) {
        Phone p=new Samsung();
        p.getMsg();
    }
}

Regular expression for checking if capital letters are found consecutively in a string?

Whenever one writes [A-Z] or [a-z], one explicitly commits to processing nothing but 7-bit ASCII data from the 1960s. If that’s really ok, then fine. But if it’s not ok, then Unicode character properties exist to help you with handling modern character data.

There are three cases in Unicode, not two. Furthermore, you also have noncased letters. Letters in general are specified by the \pL property, and each of these also belongs to exactly one of five subcategories:

  1. uppercase letters, specified with \p{Lu}; eg: AÇ?ÞSSS??ST
  2. titlecase letters, specified with \p{Lt}; eg: ??Ss?St (actually Ss and St are an upper- and then a lowercase letter, but they are what you get if you ask for the titlecase of ß and ?, respectively)
  3. lowercase letters, specified with \p{Ll}; eg: aaç??sþß??
  4. modifier letters, specified with \p{Lm}; eg: ????"'???
  5. other letters, specified with \p{Lo}; eg: ?????

You can take the complement of any of these, but do be careful, because something like \P{Lu} does not mean a letter that isn’t uppercase! It means any character that isn’t an uppercase letter.

For a letter that’s either of uppercase or titlecase, use [\p{Lu}\p{Lt}]. So you could use for your pattern:

 ^([\p{Lu}\p{Lt}]\p{Ll}+)+$

If you don’t mean to limit the letters following the first to the “casing” letters alone, then you might prefer:

 ^([\p{Lu}\p{Lt}][\p{Ll}\p{Lm}\p{Lo}]+)+$

If you’re trying to match so-called “CamelCase” identifiers, then the actual rules depend on the programming language, but usually include the underscore character and the decimal numbers (\p{Nd}), and may also include a literal dollar sign and other language-dependent characters. If so, you may wish to add some of these to one or the other of the two character classes provided above.

For example, you may wish to add underscore to both but digits only to the second, leaving you with:

 ^([_\p{Lu}\p{Lt}][_\p{Nd}\p{Ll}\p{Lm}\p{Lo}]+)+$

If, though, you are dealing with certain “words” from various RFCs and ISO standards, these are often specified as containing ASCII only. If so, you can get by with the literal [A-Z] idea. It’s just not kind to impose that restriction if it doesn’t actually exist.

How to only get file name with Linux 'find'?

Honestly basename and dirname solutions are easier, but you can also check this out :

find . -type f | grep -oP "[^/]*$"

or

find . -type f | rev | cut -d '/' -f1 | rev

or

find . -type f | sed "s/.*\///"

How do I share variables between different .c files?

if the variable is :

int foo;

in the 2nd C file you declare:

extern int foo;

How to overplot a line on a scatter plot in python?

Another way to do it, using axes.get_xlim():

import matplotlib.pyplot as plt
import numpy as np

def scatter_plot_with_correlation_line(x, y, graph_filepath):
    '''
    http://stackoverflow.com/a/34571821/395857
    x does not have to be ordered.
    '''
    # Create scatter plot
    plt.scatter(x, y)

    # Add correlation line
    axes = plt.gca()
    m, b = np.polyfit(x, y, 1)
    X_plot = np.linspace(axes.get_xlim()[0],axes.get_xlim()[1],100)
    plt.plot(X_plot, m*X_plot + b, '-')

    # Save figure
    plt.savefig(graph_filepath, dpi=300, format='png', bbox_inches='tight')

def main():
    # Data
    x = np.random.rand(100)
    y = x + np.random.rand(100)*0.1

    # Plot
    scatter_plot_with_correlation_line(x, y, 'scatter_plot.png')

if __name__ == "__main__":
    main()
    #cProfile.run('main()') # if you want to do some profiling

enter image description here

What is the difference between HTTP and REST?

From You don't know the difference between HTTP and REST

So REST architecture and HTTP 1.1 protocol are independent from each other, but the HTTP 1.1 protocol was built to be the ideal protocol to follow the principles and constraints of REST. One way to look at the relationship between HTTP and REST is, that REST is the design, and HTTP 1.1 is an implementation of that design.

Fundamental difference between Hashing and Encryption algorithms

A hash function could be considered the same as baking a loaf of bread. You start out with inputs (flour, water, yeast, etc...) and after applying the hash function (mixing + baking), you end up with an output: a loaf of bread.

Going the other way is extraordinarily difficult - you can't really separate the bread back into flour, water, yeast - some of that was lost during the baking process, and you can never tell exactly how much water or flour or yeast was used for a particular loaf, because that information was destroyed by the hashing function (aka the oven).

Many different variants of inputs will theoretically produce identical loaves (e.g. 2 cups of water and 1 tsbp of yeast produce exactly the same loaf as 2.1 cups of water and 0.9tsbp of yeast), but given one of those loaves, you can't tell exactly what combo of inputs produced it.

Encryption, on the other hand, could be viewed as a safe deposit box. Whatever you put in there comes back out, as long as you possess the key with which it was locked up in the first place. It's a symmetric operation. Given a key and some input, you get a certain output. Given that output, and the same key, you'll get back the original input. It's a 1:1 mapping.

HTML5 form validation pattern alphanumeric with spaces?

Use below code for HTML5 validation pattern alphanumeric without / with space :-

for HTML5 validation pattern alphanumeric without space :- onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90"

for HTML5 validation pattern alphanumeric with space :-

onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90 || event.charCode == 32"

Tokenizing strings in C

You can simplify the code by introducing an extra variable.

#include <string.h>
#include <stdio.h>

int main()
{
    char str[100], *s = str, *t = NULL;

    strcpy(str, "a space delimited string");
    while ((t = strtok(s, " ")) != NULL) {
        s = NULL;
        printf(":%s:\n", t);
    }
    return 0;
}

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

As @Sean said, fcntl() is largely standardized, and therefore available across platforms. The ioctl() function predates fcntl() in Unix, but is not standardized at all. That the ioctl() worked for you across all the platforms of relevance to you is fortunate, but not guaranteed. In particular, the names used for the second argument are arcane and not reliable across platforms. Indeed, they are often unique to the particular device driver that the file descriptor references. (The ioctl() calls used for a bit-mapped graphics device running on an ICL Perq running PNX (Perq Unix) of twenty years ago never translated to anything else anywhere else, for example.)

Remove legend ggplot 2.2

If your chart uses both fill and color aesthetics, you can remove the legend with:

+ guides(fill=FALSE, color=FALSE)

Changing ViewPager to enable infinite page scrolling

infinite slider adapter skeleton based on previous samples

some critical issues:

  • remember original (relative) position in page view (tag used in sample), so we will look this position to define relative position of view. otherwise child order in pager is mixed
  • have to fill first time absolute view inside adapter. (the rest of times this fill will be invalid) found no way to force it fill from pager handler. the rest times absolute view will be overriden from pager handler with correct values.
  • when pages are slided quickly, side page (actually left) is not filled from pager handler. no workaround for the moment, just use empty view, it will be filled with actual values when drag is stopped. upd: quick workaround: disable adapter's destroyItem.

you may look at the logcat to understand whats happening in this sample

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

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/calendar_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:padding="5dp"
        android:layout_gravity="center_horizontal"
        android:text="Text Text Text"
    />

</RelativeLayout>

And then:

public class ActivityCalendar extends Activity
{
    public class CalendarAdapter extends PagerAdapter
    {
        @Override
        public int getCount()
        {
            return 3;
        }

        @Override
        public boolean isViewFromObject(View view, Object object)
        {
            return view == ((RelativeLayout) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            LayoutInflater inflater = (LayoutInflater)ActivityCalendar.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View viewLayout = inflater.inflate(R.layout.layout_calendar, container, false);
            viewLayout.setTag(new Integer(position));

            //TextView tv = (TextView) viewLayout.findViewById(R.id.calendar_text);
            //tv.setText(String.format("Text Text Text relative: %d", position));

            if (!ActivityCalendar.this.scrolledOnce)
            {
                // fill here only first time, the rest will be overriden in pager scroll handler
                switch (position)
                {
                    case 0:
                        ActivityCalendar.this.setPageContent(viewLayout, globalPosition - 1);
                        break;
                    case 1:
                        ActivityCalendar.this.setPageContent(viewLayout, globalPosition);
                        break;
                    case 2:
                        ActivityCalendar.this.setPageContent(viewLayout, globalPosition + 1);
                        break;
                }
            }

            ((ViewPager) container).addView(viewLayout);

            //Log.i("instantiateItem", String.format("position = %d", position));

            return viewLayout;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            ((ViewPager) container).removeView((RelativeLayout) object);

            //Log.i("destroyItem", String.format("position = %d", position));
        }
    }

    public void setPageContent(View viewLayout, int globalPosition)
    {
        if (viewLayout == null)
            return;
        TextView tv = (TextView) viewLayout.findViewById(R.id.calendar_text);
        tv.setText(String.format("Text Text Text global %d", globalPosition));
    }

    private boolean scrolledOnce = false;
    private int focusedPage = 0;
    private int globalPosition = 0;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calendar);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);

        viewPager.setOnPageChangeListener(new OnPageChangeListener()
        {
            @Override
            public void onPageSelected(int position)
            {
                focusedPage = position;
                // actual page change only when position == 1
                if (position == 1)
                    setTitle(String.format("relative: %d, global: %d", position, globalPosition));
                Log.i("onPageSelected", String.format("focusedPage/position = %d, globalPosition = %d", position, globalPosition));
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
            {
                //Log.i("onPageScrolled", String.format("position = %d, positionOffset = %f", position, positionOffset));
            }

            @Override
            public void onPageScrollStateChanged(int state)
            {
                Log.i("onPageScrollStateChanged", String.format("state = %d, focusedPage = %d", state, focusedPage));
                if (state == ViewPager.SCROLL_STATE_IDLE)
                {
                    if (focusedPage == 0)
                        globalPosition--;
                    else if (focusedPage == 2)
                        globalPosition++;

                    scrolledOnce = true;

                    for (int i = 0; i < viewPager.getChildCount(); i++)
                    {
                        final View v = viewPager.getChildAt(i);
                        if (v == null)
                            continue;

                        // reveal correct child position
                        Integer tag = (Integer)v.getTag();
                        if (tag == null)
                            continue;

                        switch (tag.intValue())
                        {
                            case 0:
                                setPageContent(v, globalPosition - 1);
                                break;
                            case 1:
                                setPageContent(v, globalPosition);
                                break;
                            case 2:
                                setPageContent(v, globalPosition + 1);
                                break;
                        }
                    }

                    Log.i("onPageScrollStateChanged", String.format("globalPosition = %d", globalPosition));

                    viewPager.setCurrentItem(1, false);
                }
            }
        });

        CalendarAdapter calendarAdapter = this.new CalendarAdapter();
        viewPager.setAdapter(calendarAdapter);

        // center item
        viewPager.setCurrentItem(1, false);
    }
}

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

Android LinearLayout Gradient Background

It is also possible to have the third color (center). And different kinds of shapes.

For example in drawable/gradient.xml:

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#000000"
        android:centerColor="#5b5b5b"
        android:endColor="#000000"
        android:angle="0" />
</shape>

This gives you black - gray - black (left to right) which is my favorite dark background atm.

Remember to add gradient.xml as background in your layout xml:

android:background="@drawable/gradient"

It is also possible to rotate, with:

angle="0"

gives you a vertical line

and with

angle="90"

gives you a horizontal line

Possible angles are:

0, 90, 180, 270.

Also there are few different kind of shapes:

android:shape="rectangle"

Rounded shape:

android:shape="oval"

and problably a few more.

Hope it helps, cheers!

Copying files from server to local computer using SSH

Your question is a bit confusing, but I am assuming - you are first doing 'ssh' to find out which files or rather specifically directories are there and then again on your local computer, you are trying to scp 'all' files in that directory to local path. you should simply do scp -r.

So here in your case it'd be something like

local> scp -r [email protected]:/path/to/dir local/path 

If youare using some other executable that provides 'scp like functionality', refer to it's manual for recursively copying files.

How can you check for a #hash in a URL using JavaScript?

Partridge and Gareths comments above are great. They deserve a separate answer. Apparently, hash and search properties are available on any html Link object:

<a id="test" href="foo.html?bar#quz">test</a>
<script type="text/javascript">
   alert(document.getElementById('test').search); //bar
   alert(document.getElementById('test').hash); //quz
</script>

Or

<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>

Should you need this on a regular string variable and happen to have jQuery around, this should work:

var mylink = "foo.html?bar#quz";

if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
    // do stuff
}

(but its maybe a bit overdone .. )

Remove duplicate elements from array in Ruby

Try using the XOR operator, without using built-in functions:

a = [3,2,3,2,3,5,6,7].sort!

result = a.reject.with_index do |ele,index|
  res = (a[index+1] ^ ele)
  res == 0
end

print result

With built-in functions:

a = [3,2,3,2,3,5,6,7]

a.uniq

How to set time to 24 hour format in Calendar

tl;dr

LocalTime.parse( "10:30" )  // Parsed as 24-hour time.

java.time

Avoid the troublesome old date-time classes such as Date and Calendar that are now supplanted by the java.time classes.

LocalTime

The java.time classes provide a way to represent the time-of-day without a date and without a time zone: LocalTime

LocalTime lt = LocalTime.of( 10 , 30 );  // 10:30 AM.
LocalTime lt = LocalTime.of( 22 , 30 );  // 22:30 is 10:30 PM.

ISO 8601

The java.time classes use standard ISO 8601 formats by default when generating and parsing strings. These formats use 24-hour time.

String output = lt.toString();

LocalTime.of( 10 , 30 ).toString() : 10:30

LocalTime.of( 22 , 30 ).toString() : 22:30

So parsing 10:30 will be interpreted as 10:30 AM.

LocalTime lt = LocalTime.parse( "10:30" );  // 10:30 AM.

DateTimeFormatter

If you need to generate or parse strings in 12-hour click format with AM/PM, use the DateTimeFormatter class. Tip: make a habit of specifying a Locale.

Gridview get Checkbox.Checked value

Try this,

Using foreach Loop:

foreach (GridViewRow row in GridView1.Rows)
{
     CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
     if (chk != null && chk.Checked)
     {
       // ...
     }
}

Use it in OnRowCommand event and get checked CheckBox value.

GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];

How can I see function arguments in IPython Notebook Server 3?

Try Shift-Tab-Tab a bigger documentation appears, than with Shift-Tab. It's the same but you can scroll down.

Shift-Tab-Tab-Tab and the tooltip will linger for 10 seconds while you type.

Shift-Tab-Tab-Tab-Tab and the docstring appears in the pager (small part at the bottom of the window) and stays there.

How to read a text file from server using JavaScript?

You can use hidden frame, load the file in there and parse its contents.

HTML:

<iframe id="frmFile" src="test.txt" onload="LoadFile();" style="display: none;"></iframe>

JavaScript:

<script type="text/javascript">
function LoadFile() {
    var oFrame = document.getElementById("frmFile");
    var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML;
    while (strRawContents.indexOf("\r") >= 0)
        strRawContents = strRawContents.replace("\r", "");
    var arrLines = strRawContents.split("\n");
    alert("File " + oFrame.src + " has " + arrLines.length + " lines");
    for (var i = 0; i < arrLines.length; i++) {
        var curLine = arrLines[i];
        alert("Line #" + (i + 1) + " is: '" + curLine + "'");
    }
}
</script>

Note: in order for this to work in Chrome browser, you should start it with the --allow-file-access-from-files flag. credit.

Recursively find all files newer than a given time

You can find every file what is created/modified in the last day, use this example:

find /directory -newermt $(date +%Y-%m-%d -d '1 day ago') -type f -print

for finding everything in the last week, use '1 week ago' or '7 day ago' anything you want

How do I print part of a rendered HTML page in JavaScript?

You could use a print stylesheet, but this will affect all print functions.

You could try having a print stylesheet externalally, and it is included via JavaScript when a button is pressed, and then call window.print(), then after that remove it.

How to add an action to a UIAlertView button using Swift iOS

See my code:

 @IBAction func foundclicked(sender: AnyObject) {

            if (amountTF.text.isEmpty)
            {
                let alert = UIAlertView(title: "Oops! Empty Field", message: "Please enter the amount", delegate: nil, cancelButtonTitle: "OK")

                alert.show()
            }

            else {

            var alertController = UIAlertController(title: "Confirm Bid Amount", message: "Final Bid Amount : "+amountTF.text , preferredStyle: .Alert)
            var okAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.Default) {
                UIAlertAction in

                JHProgressHUD.sharedHUD.loaderColor = UIColor.redColor()
                        JHProgressHUD.sharedHUD.showInView(self.view, withHeader: "Amount registering" , andFooter: "Loading")
                }
            var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
                UIAlertAction in

                alertController .removeFromParentViewController()
            }
                            alertController.addAction(okAction)
                            alertController.addAction(cancelAction)

                self.presentViewController(alertController, animated: true, completion: nil)

            }

        }

How do I iterate through table rows and cells in JavaScript?

You can use .querySelectorAll() to select all td elements, then loop over these with .forEach(). Their values can be retrieved with .innerHTML:

_x000D_
_x000D_
const cells = document.querySelectorAll('td');_x000D_
cells.forEach(function(cell) {_x000D_
  console.log(cell.innerHTML);_x000D_
})
_x000D_
<table name="mytab" id="mytab1">_x000D_
  <tr> _x000D_
    <td>col1 Val1</td>_x000D_
    <td>col2 Val2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col1 Val3</td>_x000D_
    <td>col2 Val4</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

If you want to only select columns from a specific row, you can make use of the pseudo-class :nth-child() to select a specific tr, optionally in conjunction with the child combinator (>) (which can be useful if you have a table within a table):

_x000D_
_x000D_
const cells = document.querySelectorAll('tr:nth-child(2) > td');_x000D_
cells.forEach(function(cell) {_x000D_
  console.log(cell.innerHTML);_x000D_
})
_x000D_
<table name="mytab" id="mytab1">_x000D_
  <tr> _x000D_
    <td>col1 Val1</td>_x000D_
    <td>col2 Val2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col1 Val3</td>_x000D_
    <td>col2 Val4</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_