Programs & Examples On #Idref

An idref is used in a Document Type Definition(DTD) or XML Schema Definition(XSD) to bind the ID attribute value of a specified element to a separate attribute of one or more unrelated elements.

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

Firebase Permission Denied

Go to database, next to title there are 2 options:

Cloud Firestore, Realtime database

Select Realtime database and go to rules

Change rules to true.

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

The annotation mappedBy ideally should always be used in the Parent side (Company class) of the bi directional relationship, in this case it should be in Company class pointing to the member variable 'company' of the Child class (Branch class)

The annotation @JoinColumn is used to specify a mapped column for joining an entity association, this annotation can be used in any class (Parent or Child) but it should ideally be used only in one side (either in parent class or in Child class not in both) here in this case i used it in the Child side (Branch class) of the bi directional relationship indicating the foreign key in the Branch class.

below is the working example :

parent class , Company

@Entity
public class Company {


    private int companyId;
    private String companyName;
    private List<Branch> branches;

    @Id
    @GeneratedValue
    @Column(name="COMPANY_ID")
    public int getCompanyId() {
        return companyId;
    }

    public void setCompanyId(int companyId) {
        this.companyId = companyId;
    }

    @Column(name="COMPANY_NAME")
    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    @OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL,mappedBy="company")
    public List<Branch> getBranches() {
        return branches;
    }

    public void setBranches(List<Branch> branches) {
        this.branches = branches;
    }


}

child class, Branch

@Entity
public class Branch {

    private int branchId;
    private String branchName;
    private Company company;

    @Id
    @GeneratedValue
    @Column(name="BRANCH_ID")
    public int getBranchId() {
        return branchId;
    }

    public void setBranchId(int branchId) {
        this.branchId = branchId;
    }

    @Column(name="BRANCH_NAME")
    public String getBranchName() {
        return branchName;
    }

    public void setBranchName(String branchName) {
        this.branchName = branchName;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="COMPANY_ID")
    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }


}

Can I make a function available in every controller in angular?

You can also combine them I guess:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
        var myApp = angular.module('myApp', []);

        myApp.factory('myService', function() {
            return {
                foo: function() {
                    alert("I'm foo!");
                }
            };
        });

        myApp.run(function($rootScope, myService) {
            $rootScope.appData = myService;
        });

        myApp.controller('MainCtrl', ['$scope', function($scope){

        }]);

    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="appData.foo()">Call foo</button>
</body>
</html>

Full width layout with twitter bootstrap

I think you could just use class "col-md-12" it has required left and right paddings and 100% width. Looks like this is a good replacement for container-fluid from 2nd bootstrap.

Deep copy in ES6 using the spread syntax

Instead use this for deep copy

var newObject = JSON.parse(JSON.stringify(oldObject))

_x000D_
_x000D_
var oldObject = {_x000D_
  name: 'A',_x000D_
  address: {_x000D_
    street: 'Station Road',_x000D_
    city: 'Pune'_x000D_
  }_x000D_
}_x000D_
var newObject = JSON.parse(JSON.stringify(oldObject));_x000D_
_x000D_
newObject.address.city = 'Delhi';_x000D_
console.log('newObject');_x000D_
console.log(newObject);_x000D_
console.log('oldObject');_x000D_
console.log(oldObject);
_x000D_
_x000D_
_x000D_

Get type of all variables

You can use class(x) to check the variable type. If requirement is to check all variables type of a data frame then sapply(x, class) can be used.

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

ImportError: No module named BeautifulSoup

if you got two version of python, maybe my situation could help you

this is my situation

1-> mac osx

2-> i have two version python , (1) system default version 2.7 (2) manually installed version 3.6

3-> i have install the beautifulsoup4 with sudo pip install beautifulsoup4

4-> i run the python file with python3 /XXX/XX/XX.py

so this situation 3 and 4 are the key part, i have install beautifulsoup4 with "pip" but this module was installed for python verison 2.7, and i run the python file with "python3". so you should install beautifulsoup4 for the python 3.6;

with the sudo pip3 install beautifulsoup4 you can install the module for the python 3.6

How to increase buffer size in Oracle SQL Developer to view all records?

After you fetch the first 50 rows in the query windows, simply click on any column to get focus on the query window, then once selected do ctrl + end key

This will load the full result set (all rows)

List comprehension vs map

If you plan on writing any asynchronous, parallel, or distributed code, you will probably prefer map over a list comprehension -- as most asynchronous, parallel, or distributed packages provide a map function to overload python's map. Then by passing the appropriate map function to the rest of your code, you may not have to modify your original serial code to have it run in parallel (etc).

Using setattr() in python

I'm here in general only to find out that through dict it is necessary to work inside setattr XD

Synchronization vs Lock

You can achieve everything the utilities in java.util.concurrent do with the low-level primitives like synchronized, volatile, or wait / notify

However, concurrency is tricky, and most people get at least some parts of it wrong, making their code either incorrect or inefficient (or both).

The concurrent API provides a higher-level approach, which is easier (and as such safer) to use. In a nutshell, you should not need to use synchronized, volatile, wait, notify directly anymore.

The Lock class itself is on the lower-level side of this toolbox, you may not even need to use that directly either (you can use Queues and Semaphore and stuff, etc, most of the time).

How can I check if character in a string is a letter? (Python)

You can use str.isalpha().

For example:

s = 'a123b'

for char in s:
    print(char, char.isalpha())

Output:

a True
1 False
2 False
3 False
b True

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

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

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

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

variable is not declared it may be inaccessible due to its protection level

If I remember correctly, this is the default property for controls.

Can you try by going into Design-View for the admin_reasons that contains the specified Control, then changing the control's Modifiers property to Public or Internal.

functional way to iterate over range (ES6/7)

ES7 Proposal

Warning: Unfortunately I believe most popular platforms have dropped support for comprehensions. See below for the well-supported ES6 method

You can always use something like:

[for (i of Array(7).keys()) i*i];

Running this code on Firefox:

[ 0, 1, 4, 9, 16, 25, 36 ]

This works on Firefox (it was a proposed ES7 feature), but it has been dropped from the spec. IIRC, Babel 5 with "experimental" enabled supports this.

This is your best bet as array-comprehension are used for just this purpose. You can even write a range function to go along with this:

var range = (u, l = 0) => [ for( i of Array(u - l).keys() ) i + l ]

Then you can do:

[for (i of range(5)) i*i] // 0, 1, 4, 9, 16, 25
[for (i of range(5,3)) i*i] // 9, 16, 25

ES6

A nice way to do this any of:

[...Array(7).keys()].map(i => i * i);
Array(7).fill().map((_,i) => i*i);
[...Array(7)].map((_,i) => i*i);

This will output:

[ 0, 1, 4, 9, 16, 25, 36 ]

How to use SharedPreferences in Android to store, fetch and edit values

To store and retrieve global variables in a function way. To test, make sure you have Textview items on your page, uncomment the two lines in the code and run. Then comment the two lines again, and run.
Here the id of the TextView is username and password.

In every Class where you want to use it, add these two routines at the end. I would like this routine to be global routines, but do not know how. This works.

The variabels are available everywhere. It stores the variables in "MyFile". You may change it your way.

You call it using

 storeSession("username","frans");
 storeSession("password","!2#4%");***

the variable username will be filled with "frans" and the password with "!2#4%". Even after a restart they are available.

and you retrieve it using

 password.setText(getSession(("password")));
 usernames.setText(getSession(("username")));

below the entire code of my grid.java

    package nl.yentel.yenteldb2;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;

    public class Grid extends AppCompatActivity {
    private TextView usernames;
    private TextView password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_grid);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

      ***//  storeSession("username","[email protected]");
        //storeSession("password","mijn wachtwoord");***
        password = (TextView) findViewById(R.id.password);
        password.setText(getSession(("password")));
        usernames=(TextView) findViewById(R.id.username);
        usernames.setText(getSession(("username")));
    }

    public void storeSession(String key, String waarde) { 
        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(key, waarde);
        editor.commit();
    }

    public String getSession(String key) {
//http://androidexample.com/Android_SharedPreferences_Basics/index.php?view=article_discription&aid=126&aaid=146
        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        String output = pref.getString(key, null);
        return output;
    }

    }

below you find the textview items

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="usernames"
    android:id="@+id/username"
    android:layout_below="@+id/textView"
    android:layout_alignParentStart="true"
    android:layout_marginTop="39dp"
    android:hint="hier komt de username" />

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="password"
    android:id="@+id/password"
    android:layout_below="@+id/user"
    android:layout_alignParentStart="true"
    android:hint="hier komt het wachtwoord" />

SQL Server NOLOCK and joins

I was pretty sure that you need to specify the NOLOCK for each JOIN in the query. But my experience was limited to SQL Server 2005.

When I looked up MSDN just to confirm, I couldn't find anything definite. The below statements do seem to make me think, that for 2008, your two statements above are equivalent though for 2005 it is not the case:

[SQL Server 2008 R2]

All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

[SQL Server 2005]

In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

Additionally, point to note - and this applies to both 2005 and 2008:

The table hints are ignored if the table is not accessed by the query plan. This may be caused by the optimizer choosing not to access the table at all, or because an indexed view is accessed instead. In the latter case, accessing an indexed view can be prevented by using the OPTION (EXPAND VIEWS) query hint.

Error Code: 1406. Data too long for column - MySQL

MySQL will truncate any insert value that exceeds the specified column width.

to make this without error try switch your SQL mode to not use STRICT.

Mysql reference manual


EDIT:

To change the mode

This can be done in two ways:

  1. Open your my.ini (Windows) or my.cnf (Unix) file within the MySQL installation directory, and look for the text "sql-mode".

Find:

Code:

# Set the SQL mode to strict 
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Replace with:

Code:

# Set the SQL mode to strict 
sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Or

  1. You can run an SQL query within your database management tool, such as phpMyAdmin:

Code:

SET @@global.sql_mode= '';

Show red border for all invalid fields after submitting form angularjs

I have created a working CodePen example to demonstrate how you might accomplish your goals.

I added ng-click to the <form> and removed the logic from your button:

<form name="addRelation" data-ng-click="save(model)">
...
<input class="btn" type="submit" value="SAVE" />

Here's the updated template:

<section ng-app="app" ng-controller="MainCtrl">
  <form class="well" name="addRelation" data-ng-click="save(model)">
    <label>First Name</label>
    <input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
    <label>Last Name</label>
    <input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
    <label>Email</label>
    <input type="email" placeholder="Email" data-ng-model="model.email" id="Email" name="Email" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.email">Email address is not valid</span><br/>
    <input class="btn" type="submit" value="SAVE" />  
  </form>
</section>

and controller code:

app.controller('MainCtrl', function($scope) {  
  $scope.save = function(model) {
    $scope.addRelation.submitted = true;

    if($scope.addRelation.$valid) {
      // submit to db
      console.log(model); 
    } else {
      console.log('Errors in form data');
    }
  };
});

I hope this helps.

Controlling Maven final name of jar artifact

@Maxim
try this...

pom.xml

 <groupId>org.opensource</groupId>
 <artifactId>base</artifactId>
 <version>1.0.0.SNAPSHOT</version>

  ..............
<properties>
    <my.version>4.0.8.8</my.version>
</properties>

<build>
    <finalName>my-base-project</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <version>2.3.1</version>
            <executions>
                <execution>
                    <goals>
                        <goal>install-file</goal>
                    </goals>
                    <phase>install</phase>
                    <configuration>
                        <file>${project.build.finalName}.${project.packaging}</file>
                        <generatePom>false</generatePom>
                        <pomFile>pom.xml</pomFile>
                        <version>${my.version}</version>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</plugins>
</build>

Commnad mvn clean install

Output

[INFO] --- maven-jar-plugin:2.3.1:jar (default-jar) @ base ---
[INFO] Building jar: D:\dev\project\base\target\my-base-project.jar
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install (default-install) @ base ---
[INFO] Installing D:\dev\project\base\target\my-base-project.jar to H:\dev\.m2\repository\org\opensource\base\1.0.0.SNAPSHOT\base-1.0.0.SNAPSHOT.jar
[INFO] Installing D:\dev\project\base\pom.xml to H:\dev\.m2\repository\org\opensource\base\1.0.0.SNAPSHOT\base-1.0.0.SNAPSHOT.pom
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install-file (default) @ base ---
[INFO] Installing D:\dev\project\base\my-base-project.jar to H:\dev\.m2\repository\org\opensource\base\4.0.8.8\base-4.0.8.8.jar
[INFO] Installing D:\dev\project\base\pom.xml to H:\dev\.m2\repository\org\opensource\base\4.0.8.8\base-4.0.8.8.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------


Reference

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

In php 7 you can do:

$_POST['value'] ?? null;

If value is equal to '' as said in other answers it will also send you null.

How do I remove blank pages coming between two chapters in Appendix?

If you specify the option 'openany' in the \documentclass declaration each chapter in the book (I'm guessing you're using the book class as chapters open on the next page in reports and articles don't have chapters) will open on a new page, not necessarily the next odd-numbered page.

Of course, that's not quite what you want. I think you want to set openany for chapters in the appendix. 'fraid I don't know how to do that, I suspect that you need to roll up your sleeves and wrestle with TeX itself

How to check 'undefined' value in jQuery

JQuery library was developed specifically to simplify and to unify certain JavaScript functionality.

However if you need to check a variable against undefined value, there is no need to invent any special method, since JavaScript has a typeof operator, which is simple, fast and cross-platform:

if (typeof value === "undefined") {
    // ...
}

It returns a string indicating the type of the variable or other unevaluated operand. The main advantage of this method, compared to if (value === undefined) { ... }, is that typeof will never raise an exception in case if variable value does not exist.

Closing pyplot windows

Please use

plt.show(block=False)
plt.close('all')

Checking if a double (or float) is NaN in C++

First solution: if you are using C++11

Since this was asked there were a bit of new developments: it is important to know that std::isnan() is part of C++11

Synopsis

Defined in header <cmath>

bool isnan( float arg ); (since C++11)
bool isnan( double arg ); (since C++11)
bool isnan( long double arg ); (since C++11)

Determines if the given floating point number arg is not-a-number (NaN).

Parameters

arg: floating point value

Return value

true if arg is NaN, false otherwise

Reference

http://en.cppreference.com/w/cpp/numeric/math/isnan

Please note that this is incompatible with -fast-math if you use g++, see below for other suggestions.


Other solutions: if you using non C++11 compliant tools

For C99, in C, this is implemented as a macro isnan(c)that returns an int value. The type of x shall be float, double or long double.

Various vendors may or may not include or not a function isnan().

The supposedly portable way to check for NaN is to use the IEEE 754 property that NaN is not equal to itself: i.e. x == x will be false for x being NaN.

However the last option may not work with every compiler and some settings (particularly optimisation settings), so in last resort, you can always check the bit pattern ...

Determining the size of an Android view at runtime

Are you calling getWidth() before the view is actually laid out on the screen?

A common mistake made by new Android developers is to use the width and height of a view inside its constructor. When a view’s constructor is called, Android doesn’t know yet how big the view will be, so the sizes are set to zero. The real sizes are calculated during the layout stage, which occurs after construction but before anything is drawn. You can use the onSizeChanged() method to be notified of the values when they are known, or you can use the getWidth() and getHeight() methods later, such as in the onDraw() method.

Dynamically update values of a chartjs chart

So simple, Just replace the chart canvas element.

$('#canvas').replaceWith(' id="canvas" height="200px" width="368px">');

Temporarily change current working directory in bash to run a command

bash has a builtin

pushd SOME_PATH
run_stuff
...
...
popd 

How to debug apk signed for release?

Add the following to your app build.gradle and select the specified release build variant and run

signingConfigs {
        config {
            keyAlias 'keyalias'
            keyPassword 'keypwd'
            storeFile file('<<KEYSTORE-PATH>>.keystore')
            storePassword 'pwd'
        }
    }
    buildTypes {
      release {
          debuggable true
          signingConfig signingConfigs.config
          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

'npm' is not recognized as internal or external command, operable program or batch file

I ran into this problem the other day on my Windows 7 machine. Problem wasn't my path, but I had to use escaped forward slashes instead of backslashes like this:

"scripts": {
    "script": ".\\bin\\script.sh"
}

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

Get top n records for each group of grouped results

How about using self-joining:

CREATE TABLE mytable (person, groupname, age);
INSERT INTO mytable VALUES('Bob',1,32);
INSERT INTO mytable VALUES('Jill',1,34);
INSERT INTO mytable VALUES('Shawn',1,42);
INSERT INTO mytable VALUES('Jake',2,29);
INSERT INTO mytable VALUES('Paul',2,36);
INSERT INTO mytable VALUES('Laura',2,39);

SELECT a.* FROM mytable AS a
  LEFT JOIN mytable AS a2 
    ON a.groupname = a2.groupname AND a.age <= a2.age
GROUP BY a.person
HAVING COUNT(*) <= 2
ORDER BY a.groupname, a.age DESC;

gives me:

a.person    a.groupname  a.age     
----------  -----------  ----------
Shawn       1            42        
Jill        1            34        
Laura       2            39        
Paul        2            36      

I was strongly inspired by the answer from Bill Karwin to Select top 10 records for each category

Also, I'm using SQLite, but this should work on MySQL.

Another thing: in the above, I replaced the group column with a groupname column for convenience.

Edit:

Following-up on the OP's comment regarding missing tie results, I incremented on snuffin's answer to show all the ties. This means that if the last ones are ties, more than 2 rows can be returned, as shown below:

.headers on
.mode column

CREATE TABLE foo (person, groupname, age);
INSERT INTO foo VALUES('Paul',2,36);
INSERT INTO foo VALUES('Laura',2,39);
INSERT INTO foo VALUES('Joe',2,36);
INSERT INTO foo VALUES('Bob',1,32);
INSERT INTO foo VALUES('Jill',1,34);
INSERT INTO foo VALUES('Shawn',1,42);
INSERT INTO foo VALUES('Jake',2,29);
INSERT INTO foo VALUES('James',2,15);
INSERT INTO foo VALUES('Fred',1,12);
INSERT INTO foo VALUES('Chuck',3,112);


SELECT a.person, a.groupname, a.age 
FROM foo AS a 
WHERE a.age >= (SELECT MIN(b.age)
                FROM foo AS b 
                WHERE (SELECT COUNT(*)
                       FROM foo AS c
                       WHERE c.groupname = b.groupname AND c.age >= b.age) <= 2
                GROUP BY b.groupname)
ORDER BY a.groupname ASC, a.age DESC;

gives me:

person      groupname   age       
----------  ----------  ----------
Shawn       1           42        
Jill        1           34        
Laura       2           39        
Paul        2           36        
Joe         2           36        
Chuck       3           112      

How to ignore SSL certificate errors in Apache HttpClient 4.0

For the record, tested with httpclient 4.3.6 and compatible with Executor of fluent api:

CloseableHttpClient httpClient = HttpClients.custom().
                    setHostnameVerifier(new AllowAllHostnameVerifier()).
                    setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
                    {
                        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
                        {
                            return true;
                        }
                    }).build()).build();

How to install lxml on Ubuntu

Step 1

Install latest python updates using this command.

sudo apt-get install python-dev

Step 2

Add first dependency libxml2 version 2.7.0 or later

sudo apt-get install libxml2-dev

Step 3

Add second dependency libxslt version 1.1.23 or later

sudo apt-get install libxslt1-dev

Step 4

Install pip package management tool first. and run this command.

pip install lxml

If you have any doubt Click Here

WPF What is the correct way of using SVG files as icons in WPF

Windows 10 build 15063 "Creators Update" natively supports SVG images (though with some gotchas) to UWP/UAP applications targeting Windows 10.

If your application is a WPF app rather than a UWP/UAP, you can still use this API (after jumping through quite a number of hoops): Windows 10 build 17763 "October 2018 Update" introduced the concept of XAML islands (as a "preview" technology but I believe allowed in the app store; in all cases, with Windows 10 build 18362 "May 2019 Update" XAML islands are no longer a preview feature and are fully supported) allowing you to use UWP APIs and controls in your WPF applications.

You need to first add the references to the WinRT APIs, and to use certain Windows 10 APIs that interact with user data or the system (e.g. loading images from disk in a Windows 10 UWP webview or using the toast notification API to show toasts), you also need to associate your WPF application with a package identity, as shown here (immensely easier in Visual Studio 2019). This shouldn't be necessary to use the Windows.UI.Xaml.Media.Imaging.SvgImageSource class, though.

Usage (if you're on UWP or you've followed the directions above and added XAML island support under WPF) is as simple as setting the Source for an <Image /> to the path to the SVG. That is equivalent to using SvgImageSource, as follows:

<Image>
    <Image.Source>
        <SvgImageSource UriSource="Assets/svg/icon.svg" />
    </Image.Source>
</Image>

However, SVG images loaded in this way (via XAML) may load jagged/aliased. One workaround is to specify a RasterizePixelHeight or RasterizePixelWidth value that is double+ your actual height/width:

<SvgImageSource RasterizePixelHeight="300" RasterizePixelWidth="300" UriSource="Assets/svg/icon.svg" /> <!-- presuming actual height or width is under 150 -->

This can be worked around dynamically by creating a new SvgImageSource in the ImageOpened event for the base image:

var svgSource = new SvgImageSource(new Uri("ms-appx://" + Icon));
PrayerIcon.ImageOpened += (s, e) =>
{
    var newSource = new SvgImageSource(svgSource.UriSource);
    newSource.RasterizePixelHeight = PrayerIcon.DesiredSize.Height * 2;
    newSource.RasterizePixelWidth = PrayerIcon.DesiredSize.Width * 2;
    PrayerIcon2.Source = newSource;
};
PrayerIcon.Source = svgSource;

The aliasing may be hard to see on non high-dpi screens, but here's an attempt to illustrate it.

This is the result of the code above: an Image that uses the initial SvgImageSource, and a second Image below it that uses the SvgImageSource created in the ImageOpened event:

enter image description here

This is a blown up view of the top image:

enter image description here

Whereas this is a blown-up view of the bottom (antialiased, correct) image:

enter image description here

(you'll need to open the images in a new tab and view at full size to appreciate the difference)

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

SELECT t.*,
       @rownum := @rownum +1 AS rank
  FROM TBL_FOO t
  JOIN (SELECT @rownum := 0) r
 WHERE t.name = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

Accessing the web page's HTTP Headers in JavaScript

Using mootools, you can use this.xhr.getAllResponseHeaders()

What's the best free C++ profiler for Windows?

Microsoft has the Windows Performance Toolkit.

It does require Windows Vista, Windows Server 2008, or Windows 7.

How to check if an element is off-screen

Well... I've found some issues in every proposed solution here.

  • You should be able to choose if you want entire element to be on screen or just any part of it
  • Proposed solutions fails if element is higher/wider than window and kinda covers browser window.

Here is my solution that include jQuery .fn instance function and expression. I've created more variables inside my function than I could, but for complex logical problem I like to divide it into smaller, clearly named pieces.

I'm using getBoundingClientRect method that returns element position relatively to the viewport so I don't need to care about scroll position

Useage:

$(".some-element").filter(":onscreen").doSomething();
$(".some-element").filter(":entireonscreen").doSomething();
$(".some-element").isOnScreen(); // true / false
$(".some-element").isOnScreen(true); // true / false (partially on screen)
$(".some-element").is(":onscreen"); // true / false (partially on screen)
$(".some-element").is(":entireonscreen"); // true / false 

Source:

$.fn.isOnScreen = function(partial){

    //let's be sure we're checking only one element (in case function is called on set)
    var t = $(this).first();

    //we're using getBoundingClientRect to get position of element relative to viewport
    //so we dont need to care about scroll position
    var box = t[0].getBoundingClientRect();

    //let's save window size
    var win = {
        h : $(window).height(),
        w : $(window).width()
    };

    //now we check against edges of element

    //firstly we check one axis
    //for example we check if left edge of element is between left and right edge of scree (still might be above/below)
    var topEdgeInRange = box.top >= 0 && box.top <= win.h;
    var bottomEdgeInRange = box.bottom >= 0 && box.bottom <= win.h;

    var leftEdgeInRange = box.left >= 0 && box.left <= win.w;
    var rightEdgeInRange = box.right >= 0 && box.right <= win.w;


    //here we check if element is bigger then window and 'covers' the screen in given axis
    var coverScreenHorizontally = box.left <= 0 && box.right >= win.w;
    var coverScreenVertically = box.top <= 0 && box.bottom >= win.h;

    //now we check 2nd axis
    var topEdgeInScreen = topEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );
    var bottomEdgeInScreen = bottomEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );

    var leftEdgeInScreen = leftEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );
    var rightEdgeInScreen = rightEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );

    //now knowing presence of each edge on screen, we check if element is partially or entirely present on screen
    var isPartiallyOnScreen = topEdgeInScreen || bottomEdgeInScreen || leftEdgeInScreen || rightEdgeInScreen;
    var isEntirelyOnScreen = topEdgeInScreen && bottomEdgeInScreen && leftEdgeInScreen && rightEdgeInScreen;

    return partial ? isPartiallyOnScreen : isEntirelyOnScreen;

};

$.expr.filters.onscreen = function(elem) {
  return $(elem).isOnScreen(true);
};

$.expr.filters.entireonscreen = function(elem) {
  return $(elem).isOnScreen(true);
};

Pandas sum by groupby, but exclude certain columns

You can select the columns of a groupby:

In [11]: df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
Out[11]:
                       Y1961  Y1962  Y1963
Country     Item_Code
Afghanistan 15            10     20     30
            25            10     20     30
Angola      15            30     40     50
            25            30     40     50

Note that the list passed must be a subset of the columns otherwise you'll see a KeyError.

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

As already mentioned, compiling the app in x64 gives you far more available memory.

But in the case one must build an app in x86, there is a way to raise the memory limit from 1,2GB to 4GB (which is the actual limit for 32 bit processes):

In the VC/bin folder of the Visual Studio installation directory, there must be an editbin.exe file. So in my default installation I find it under

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\editbin.exe

In order to make the program work, maybe you must execute vcvars32.bat in the same directory first. Then a

editbin /LARGEADDRESSAWARE <your compiled exe file>

is enough to let your program use 4GB RAM. <your compiled exe file> is the exe, which VS generated while compiling your project.

If you want to automate this behavior every time you compile your project, use the following Post-Build event for the executed project:

if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
   call "$(DevEnvDir)..\tools\vsvars32.bat"
   editbin /largeaddressaware "$(TargetPath)"
)

Sidenote: The same can be done with the devenv.exe to let Visual Studio also use 4GB RAM instead of 1.2GB (but first backup the old devenv.exe).

How to [recursively] Zip a directory in PHP?

Here Is my code For Zip the folders and its sub folders and its files and make it downloadable in zip Format

function zip()
 {
$source='path/folder'// Path To the folder;
$destination='path/folder/abc.zip'// Path to the file and file name ; 
$include_dir = false;
$archive = 'abc.zip'// File Name ;

if (!extension_loaded('zip') || !file_exists($source)) {
    return false;
}

if (file_exists($destination)) {
    unlink ($destination);
}

$zip = new ZipArchive;

if (!$zip->open($archive, ZipArchive::CREATE)) {
    return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{

    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

    if ($include_dir) {

        $arr = explode("/",$source);
        $maindir = $arr[count($arr)- 1];

        $source = "";
        for ($i=0; $i < count($arr) - 1; $i++) { 
            $source .= '/' . $arr[$i];
        }

        $source = substr($source, 1);

        $zip->addEmptyDir($maindir);

    }

    foreach ($files as $file)
    {
        $file = str_replace('\\', '/', $file);

        // Ignore "." and ".." folders
        if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
            continue;

        $file = realpath($file);

        if (is_dir($file) === true)
        {
            $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
        }
        else if (is_file($file) === true)
        {
            $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
        }
    }
}
else if (is_file($source) === true)
{
    $zip->addFromString(basename($source), file_get_contents($source));
}
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
}

If Any Issue With the Code Let Me know.

Django: TemplateSyntaxError: Could not parse the remainder

For me it was using {{ }} instead of {% %}:

href="{{ static 'bootstrap.min.css' }}"  # wrong
href="{% static 'bootstrap.min.css' %}"  # right

OrderBy pipe issue

I've created an OrderBy pipe that does just what you need. It supports being able to sort on multiple columns of an enumerable of objects as well.

<li *ngFor="#todo in todos | orderBy : ['completed']">{{todo.name}} {{todo.completed}}</li>

This pipe does allow for adding more items to the array after rendering the page, and will sort the array with the updates dynamically.

I have a write up on the process here.

And here's a working demo: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby and https://plnkr.co/edit/DHLVc0?p=info

Check whether a variable is a string in Ruby

I think a better way is to create some predicate methods. This will also save your "Single Point of Control".

class Object
 def is_string?
   false
 end
end

class String
 def is_string?
   true
 end
end

print "test".is_string? #=> true
print 1.is_string?      #=> false

The more duck typing way ;)

Fastest check if row exists in PostgreSQL

Use the EXISTS key word for TRUE / FALSE return:

select exists(select 1 from contact where id=12)

How to get PID of process I've just started within java program?

Using JNA, supporting old and new JVM to get process id

public static long getProcessId(Process p){
    long pid = -1;
    try {
      pid = p.pid();
    } catch (NoSuchMethodError e) {
        try
        {
            //for windows
            if (p.getClass().getName().equals("java.lang.Win32Process") || p.getClass().getName().equals("java.lang.ProcessImpl")) {
                Field f = p.getClass().getDeclaredField("handle");
                f.setAccessible(true);              
                long handl = f.getLong(p);
                Kernel32 kernel = Kernel32.INSTANCE;
                WinNT.HANDLE hand = new WinNT.HANDLE();
                hand.setPointer(Pointer.createConstant(handl));
                pid = kernel.GetProcessId(hand);
                f.setAccessible(false);
            }
            //for unix based operating systems
            else if (p.getClass().getName().equals("java.lang.UNIXProcess")) 
            {
                Field f = p.getClass().getDeclaredField("pid");
                f.setAccessible(true);
                pid = f.getLong(p);
                f.setAccessible(false);
            }
        }
        catch(Exception ex)
        {
            pid = -1;
        }
    }        
    return pid;
}

Embed website into my site

You might want to check HTML frames, which can do pretty much exactly what you are looking for. They are considered outdated however.

how to split the ng-repeat data with three columns using bootstrap

this answers the original question which is how to get 1,2,3 in a column. – asked by kuppu Feb 8 '14 at 13:47

angularjs code:

function GetStaffForFloor(floor) {
    var promiseGet = Directory_Service.getAllStaff(floor);
    promiseGet.then(function (pl) {
        $scope.staffList = chunk(pl.data, 3); //pl.data; //
    },
    function (errorOD) {
        $log.error('Errored while getting staff list.', errorOD);
    });
}
function chunk(array, columns) {
    var numberOfRows = Math.ceil(array.length / columns);

    //puts 1, 2, 3 into column
    var newRow = []; //array is row-based.
    for (var i = 0; i < array.length; i++) {
        var columnData = new Array(columns);
        if (i == numberOfRows) break;
        for (j = 0; j < columns; j++)
        {
            columnData[j] = array[i + numberOfRows * j];
        }
        newRow.push(columnData); 
    }
    return newRow;

    ////this works but 1, 2, 3 is in row
    //var newRow = [];
    //for (var i = 0; i < array.length; i += columns) {
    //    newRow.push(array.slice(i, i + columns)); //push effectively does the pivot. array is row-based.
    //}
    //return newRow;
};

View Code (note: using bootstrap 3):

<div class="staffContainer">
    <div class="row" ng-repeat="staff in staffList">
        <div class="col-md-4" ng-repeat="item in staff">{{item.FullName.length > 0 ? item.FullName + ": Rm " + item.RoomNumber : ""}}</div>
    </div>
</div>

Logical XOR operator in C++?

Proper manual logical XOR implementation depends on how closely you want to mimic the general behavior of other logical operators (|| and &&) with your XOR. There are two important things about these operators: 1) they guarantee short-circuit evaluation, 2) they introduce a sequence point, 3) they evaluate their operands only once.

XOR evaluation, as you understand, cannot be short-circuited since the result always depends on both operands. So 1 is out of question. But what about 2? If you don't care about 2, then with normalized (i.e. bool) values operator != does the job of XOR in terms of the result. And the operands can be easily normalized with unary !, if necessary. Thus !A != !B implements the proper XOR in that regard.

But if you care about the extra sequence point though, neither != nor bitwise ^ is the proper way to implement XOR. One possible way to do XOR(a, b) correctly might look as follows

a ? !b : b

This is actually as close as you can get to making a homemade XOR "similar" to || and &&. This will only work, of course, if you implement your XOR as a macro. A function won't do, since the sequencing will not apply to function's arguments.

Someone might say though, that the only reason of having a sequence point at each && and || is to support the short-circuited evaluation, and thus XOR does not need one. This makes sense, actually. Yet, it is worth considering having a XOR with a sequence point in the middle. For example, the following expression

++x > 1 && x < 5

has defined behavior and specificed result in C/C++ (with regard to sequencing at least). So, one might reasonably expect the same from user-defined logical XOR, as in

XOR(++x > 1, x < 5)

while a !=-based XOR doesn't have this property.

How can get the text of a div tag using only javascript (no jQuery)

You can use innerHTML(then parse text from HTML) or use innerText.

let textContentWithHTMLTags = document.querySelector('div').innerHTML; 
let textContent = document.querySelector('div').innerText;

console.log(textContentWithHTMLTags, textContent);

innerHTML and innerText is supported by all browser(except FireFox < 44) including IE6.

Text File Parsing with Python

There are a few ways to go about this. One option would be to use inputfile.read() instead of inputfile.readlines() - you'd need to write separate code to strip the first four lines, but if you want the final output as a single string anyway, this might make the most sense.

A second, simpler option would be to rejoin the strings after striping the first four lines with my_text = ''.join(my_text). This is a little inefficient, but if speed isn't a major concern, the code will be simplest.

Finally, if you actually want the output as a list of strings instead of a single string, you can just modify your data parser to iterate over the list. That might looks something like this:

def data_parser(lines, dic):
    for i, j in dic.iteritems():
        for (k, line) in enumerate(lines):
            lines[k] = line.replace(i, j)
    return lines

Generating random number between 1 and 10 in Bash Shell Script

To generate random numbers with bash use the $RANDOM internal Bash function. Note that $RANDOM should not be used to generate an encryption key. $RANDOM is generated by using your current process ID (PID) and the current time/date as defined by the number of seconds elapsed since 1970.

 echo $RANDOM % 10 + 1 | bc

How can I uninstall Ruby on ubuntu?

Uninstall the make install software when make uninstall invalid.

  • make install will create file '.installed.list'
  • Choose to clean up the files described in .installed.list (need to be careful if you have multiple versions)
  • Case: ruby2.4 switch to ruby2.3, thinking directly delete all ruby software, and then re-make install 2.3, see: Ruby # Installation Guide
  • make install -> .installed.list
  • see .installed.list file, delete all install files.

rm -rf /usr/local/include/ruby-*
rm -rf /usr/local/lib/ruby
rm /usr/local/bin/erb /usr/local/bin/gem /usr/local/bin/irb /usr/local/bin/rdoc /usr/local/bin/ri /usr/local/bin/ruby
rm /usr/local/share/man/man1/erb.1 /usr/local/share/man/man1/irb.1 /usr/local/share/man/man1/ri.1 /usr/local/share/man/man1/ruby.1
rm /usr/local/lib/libruby-static.a
rm -rf /usr/local/lib/pkgconfig/ruby-*
which ruby
pkg-config --list-all|grep ruby

Set order of columns in pandas dataframe

Add the 'columns' parameter:

frame = pd.DataFrame({
        'one thing':[1,2,3,4],
        'second thing':[0.1,0.2,1,2],
        'other thing':['a','e','i','o']},
        columns=['one thing', 'second thing', 'other thing']
)

Windows batch: formatted date into variable

If you have Python installed, you can do

python -c "import datetime;print(datetime.date.today().strftime('%Y-%m-%d'))"

You can easily adapt the format string to your needs.

SELECT with LIMIT in Codeigniter

Try this...

function nationList($limit=null, $start=null) {
    if ($this->session->userdata('language') == "it") {
        $this->db->select('nation.id, nation.name_it as name');
    }

    if ($this->session->userdata('language') == "en") {
        $this->db->select('nation.id, nation.name_en as name');
    }

    $this->db->from('nation');
    $this->db->order_by("name", "asc");

    if ($limit != '' && $start != '') {
       $this->db->limit($limit, $start);
    }
    $query  = $this->db->get();

    $nation = array();
    foreach ($query->result() as $row) {
        array_push($nation, $row);
    }

    return $nation;     
}

Call js-function using JQuery timer

Might want to check out jQuery Timer to manage one or multiple timers.

http://code.google.com/p/jquery-timer/

var timer = $.timer(yourfunction, 10000);

function yourfunction() { alert('test'); }

Then you can control it with:

timer.play();
timer.pause();
timer.toggle();
timer.once();
etc...

How can I find the latitude and longitude from address?

public LatLang getLatLangFromAddress(String strAddress){
    Geocoder coder = new Geocoder(this, Locale.getDefault());
    List<Address> address;
    try {
        address = coder.getFromLocationName(strAddress,5);
        if (address == null) {
                return new LatLang(-10000, -10000);
            }
            Address location = address.get(0);
            return new LatLang(location.getLatitude(), location.getLongitude());
        } catch (IOException e) {
            return new LatLang(-10000, -10000);
        }
    }            

LatLang is a pojo class in this case.

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> permission is not required.

Easiest way to detect Internet connection on iOS?

Seeing as this thread is the top google result for this type of question, I figured I would provide the solution that worked for me. I was already using AFNetworking, but searching didn't reveal how to accomplish this task with AFNetworking until midway through my project.

What you want is the AFNetworkingReachabilityManager.

// -- Start monitoring network reachability (globally available) -- //
[[AFNetworkReachabilityManager sharedManager] startMonitoring];

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

    NSLog(@"Reachability changed: %@", AFStringFromNetworkReachabilityStatus(status));


    switch (status) {
        case AFNetworkReachabilityStatusReachableViaWWAN:
        case AFNetworkReachabilityStatusReachableViaWiFi:
            // -- Reachable -- //
            NSLog(@"Reachable");
            break;
        case AFNetworkReachabilityStatusNotReachable:
        default:
            // -- Not reachable -- //
            NSLog(@"Not Reachable");
            break;
    }

}];

You can also use the following to test reachability synchronously (once monitoring has started):

-(BOOL) isInternetReachable
{
    return [AFNetworkReachabilityManager sharedManager].reachable;
}

convert htaccess to nginx

Have not tested it yet, but the looks are better than the one Alex mentions.

The description at winginx.com/en/htaccess says:

About the htaccess to nginx converter

The service is to convert an Apache's .htaccess to nginx configuration instructions.

First of all, the service was thought as a mod_rewrite to nginx converter. However, it allows you to convert some other instructions that have reason to be ported from Apache to nginx.

Note server instructions (e.g. php_value, etc.) are ignored.

The converter does not check syntax, including regular expressions and logic errors.

Please, check the result manually before use.

Deserializing a JSON into a JavaScript object

If you paste the string in server-side into the html don't need to do nothing:

For plain java in jsp:

var jsonObj=<%=jsonStringInJavaServlet%>;

For jsp width struts:

var jsonObj=<s:property value="jsonStringInJavaServlet" escape="false" escapeHtml="false"/>;

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

Take a look at FileSaver.js. It provides a handy saveAs function which takes care of most browser specific quirks.

ggplot2 legend to bottom and horizontal

If you want to move the position of the legend please use the following code:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
    theme(legend.position="bottom")

This should give you the desired result. Legend at bottom

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

CSS: stretching background image to 100% width and height of screen?

You need to set the height of html to 100%

body {
    background-image:url("../images/myImage.jpg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}
html {
    height: 100%
}

http://jsfiddle.net/8XUjP/

regex string replace

Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:

str = str.replace(/[^-a-z0-9]+/g, "");

Also, if you need to match upper-case letters along with lower case, you should use:

str = str.replace(/[^-a-zA-Z0-9]+/g, "");

Understanding esModuleInterop in tsconfig file

esModuleInterop generates the helpers outlined in the docs. Looking at the generated code, we can see exactly what these do:

//ts 
import React from 'react'
//js 
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));

__importDefault: If the module is not an es module then what is returned by require becomes the default. This means that if you use default import on a commonjs module, the whole module is actually the default.

__importStar is best described in this PR:

TypeScript treats a namespace import (i.e. import * as foo from "foo") as equivalent to const foo = require("foo"). Things are simple here, but they don't work out if the primary object being imported is a primitive or a value with call/construct signatures. ECMAScript basically says a namespace record is a plain object.

Babel first requires in the module, and checks for a property named __esModule. If __esModule is set to true, then the behavior is the same as that of TypeScript, but otherwise, it synthesizes a namespace record where:

  1. All properties are plucked off of the require'd module and made available as named imports.
  2. The originally require'd module is made available as a default import.

So we get this:

// ts
import * as React from 'react'

// emitted js
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));

allowSyntheticDefaultImports is the companion to all of this, setting this to false will not change the emitted helpers (both of them will still look the same). But it will raise a typescript error if you are using default import for a commonjs module. So this import React from 'react' will raise the error Module '".../node_modules/@types/react/index"' has no default export. if allowSyntheticDefaultImports is false.

Delete empty rows

DELETE FROM table WHERE edit_user IS NULL;

Why do I get PLS-00302: component must be declared when it exists?

I came here because I had the same problem.
What was the problem for me was that the procedure was defined in the package body, but not in the package header.
I was executing my function with a lose BEGIN END statement.

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

For those who's working with latest webpack and has options property on there configuration. You cannot use query and options at the same time. You will get this error if both is present

Error: Provided options and query in use

Instead, add new property to options name generatorOpts, then add the property compact under it.

loaders: [
   { test: /\.js$/, loader: 'babel', option: { generatorOpts: { compact: false } } }
]

And for those who's working with next (like me). You need to do something like this

config.module.rules.filter((rule) => rule.use && rule.use.loader === 'next-babel-loader')
.map((loader) => {
    loader.use.options.generatorOpts = { compact: false };
    return loader;
});

Freely convert between List<T> and IEnumerable<T>

List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myEnumerable.ToList();

Getting command-line password input in Python

Use getpass for this purpose.

getpass.getpass - Prompt the user for a password without echoing

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

simple we are going to wait for 5 seconds for some event to happen (that would be indicated by done variable set to true somewhere else in the code) or when timeout expires that we will check every 100ms

    var timeout=5000; //will wait for 5 seconds or untildone
    var scope = this; //bind this to scope variable
    (function() {
        if (timeout<=0 || scope.done) //timeout expired or done
        {
            scope.callback();//some function to call after we are done
        }
        else
        {
            setTimeout(arguments.callee,100) //call itself again until done
            timeout -= 100;
        }
    })();

How to clean up R memory (without the need to restart my PC)?

I've found it helpful to go into my "tmp" folder and delete all hanging rsession files. This usually frees any memory that seems to be "stuck".

How to count the number of lines of a string in javascript

Better solution, as str.split("\n") function creates new array of strings split by "\n" which is heavier than str.match(/\n\g). str.match(/\n\g) creates array of matching elements only. Which is "\n" in our case.

var totalLines = (str.match(/\n/g) || '').length + 1;

How do I create a MongoDB dump of my database?

Backup/Restore Mongodb with timing.

Backup:

sudo mongodump --db db_name --out /path_of_your_backup/`date +"%m-%d-%y"`

--db argument for databse name

--out argument for path of output

Restore:

sudo mongorestore --db db_name --drop /path_of_your_backup/01-01-19/db_name/

--drop argument for drop databse before restore

Timing:

You can use crontab for timing backup:

sudo crontab -e

It opens with editor(e.g. nano)

3 3 * * * mongodump --out /path_of_your_backup/`date +"%m-%d-%y"`

backup every day at 03:03 AM

Depending on your MongoDB database sizes you may soon run out of disk space with too many backups. That's why it's also recommended to clean the old backups regularly or to compress them. For example, to delete all the backups older than 7 days you can use the following bash command:

3 1 * * * find /path_of_your_backup/ -mtime +7 -exec rm -rf {} \;

delete all the backups older than 7 days

Good Luck.

ref: https://www.digitalocean.com/community/tutorials/how-to-back-up-restore-and-migrate-a-mongodb-database-on-ubuntu-14-04

Difference between r+ and w+ in fopen()

This diagram will be faster to read next time. Maybe someone else will find that helpful too. This is clearly explained the difference between. enter image description here

How to retrieve data from sqlite database in android and display it in TextView

You may use this following code actually it is rough but plz check it out

db = openOrCreateDatabase("sms.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor cc = db.rawQuery("SELECT * FROM datatable", null);
final ArrayList<String> row1 = new ArrayList<String>();
final ArrayList<String> row2 = new ArrayList<String>();

if(cc!=null) {
    cc.moveToFirst();   
    startManagingCursor(cc);
    for (int i=0; i<cc.getCount(); i++) {

    String number  = cc.getString(0);
    String message = cc.getString(1);
    row1.add(number);
    row2.add(message);

    final EditText et3 = (EditText) findViewById(R.id.editText3);
    final EditText et4 = (EditText) findViewById(R.id.editText4);
    Button bt1 = (Button) findViewById(R.id.button1);
    bt1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            switch (v.getId()) {
                case R.id.button1:
                    et3.setText(row1.get(count));
                    et4.setText(row2.get(count));
                    count++;
                    break;
                default:
                    break;
            }

        }
    });

cc.moveToNext();
}

How to show PIL Image in ipython notebook

You can open an image using the Image class from the package PIL and display it with plt.imshow directly.

# First import libraries.
from PIL import Image
import matplotlib.pyplot as plt

# The folliwing line is useful in Jupyter notebook
%matplotlib inline

# Open your file image using the path
img = Image.open(<path_to_image>)

# Since plt knows how to handle instance of the Image class, just input your loaded image to imshow method
plt.imshow(img)

In Powershell what is the idiomatic way of converting a string to an int?

Using .net

[int]$b = $null #used after as refence
$b
0
[int32]::TryParse($a , [ref]$b ) # test if is possible to cast and put parsed value in reference variable
True
$b
10
$b.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

note this (powershell coercing feature)

$a = "10"
$a + 1 #second value is evaluated as [string]
101 

11 + $a # second value is evaluated as [int]
21

How do I plot only a table in Matplotlib?

If you just wanted to change the example and put the table at the top, then loc='top' in the table declaration is what you need,

the_table = ax.table(cellText=cell_text,
                      rowLabels=rows,
                      rowColours=colors,
                      colLabels=columns,
                      loc='top')

Then adjusting the plot with,

plt.subplots_adjust(left=0.2, top=0.8)

A more flexible option is to put the table in its own axis using subplots,

import numpy as np
import matplotlib.pyplot as plt


fig, axs =plt.subplots(2,1)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs[0].axis('tight')
axs[0].axis('off')
the_table = axs[0].table(cellText=clust_data,colLabels=collabel,loc='center')

axs[1].plot(clust_data[:,0],clust_data[:,1])
plt.show()

which looks like this,

enter image description here

You are then free to adjust the locations of the axis as required.

How to run Rake tasks from within Rake tasks?

task :invoke_another_task do
  # some code
  Rake::Task["another:task"].invoke
end

How can I control the speed that bootstrap carousel slides in items?

If you need to do it programmatically to change (for example) the speed based on certain conditions on perhaps only one of many carousels, you could do something like this:

If the Html is like this:

<div id="theSlidesList" class="carousel-inner" role="listbox">
  <div id="Slide_00" class="item active"> ...
  <div id="Slide_01" class="item"> ...
  ...
</div>

JavaScript would be like this:

$( "#theSlidesList" ).find( ".item" ).css( "-webkit-transition", "transform 1.9s ease-in-out 0s" ).css( "transition", "transform 1.9s ease-in-out 0s" )

Add more .css( ... ) to include other browsers.

Synchronizing a local Git repository with a remote one

Sounds like you want a mirror of the remote repository:

git clone --mirror url://to/remote.git local.git

That command creates a bare repository. If you don't want a bare repository, things get more complicated.

The name 'ViewBag' does not exist in the current context

As @Wilson Vallecilla already mentioned. Please do the below steps to delete the cache:

Please follow below path to discover the files:

C:\Users\your.name.here\AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache

Delete all four files:

  • Microsoft.VisualStudio.Default.cache
  • Microsoft.VisualStudio.Default.catalogs
  • Microsoft.VisualStudio.Default.err
  • Microsoft.VisualStudio.Default.external

I closed my project, deleted the files on that path and reopened my project, cleaned the solution and built it again and the problem was solved

Deleting your Temporary ASP.NET Files also helps. C:\Users\your.name.here\AppData\Local\Temp\Temporary ASP.NET Files.

This works for me.

Thanks!

How can I get selector from jQuery object

Taking in account some answers read here I'd like to propose this:

function getSelectorFromElement($el) {
  if (!$el || !$el.length) {
    return ;
  }

  function _getChildSelector(index) {
    if (typeof index === 'undefined') {
      return '';
    }

    index = index + 1;
    return ':nth-child(' + index + ')';
  }

  function _getIdAndClassNames($el) {
    var selector = '';

    // attach id if exists
    var elId = $el.attr('id');
    if(elId){
      selector += '#' + elId;
    }

    // attach class names if exists
    var classNames = $el.attr('class');
    if(classNames){
      selector += '.' + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, '.');
    }

    return selector;
  }

  // get all parents siblings index and element's tag name,
  // except html and body elements
  var selector = $el.parents(':not(html,body)')
    .map(function() {
      var parentIndex = $(this).index();

      return this.tagName + _getChildSelector(parentIndex);
    })
    .get()
    .reverse()
    .join(' ');

  if (selector) {
    // get node name from the element itself
    selector += ' ' + $el[0].nodeName +
      // get child selector from element ifself
      _getChildSelector($el.index());
  }

  selector += _getIdAndClassNames($el);

  return selector;
}

Maybe useful to create a jQuery plugin?

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

I faced the same issue 2 days ago and today I was able to solve it like this:

  1. Go to this path C:\Users\user_name\.gradle\wrapper\dists where user_name is your username if its you own PC or your company's name.

  2. Delete the latest gradle-****-all files since your latest update of android studio (ex. 2.3 or another version).

  3. If your android studio is open, close it then reopen it. A newer Gradle version will be downloaded, it will take time depending on your internet speed, the download size is around 150-200 MB before extraction so if android studio takes a long time to refresh just know its downloading. (To check the download progress right click on the new gradle folder, go to properties and check the size).

Combine multiple JavaScript files into one JS file

Copy this script to notepad and save as .vbs file. Drag&Drop .js files on this script.

ps. This will work only on windows.

set objArgs = Wscript.Arguments
set objFso = CreateObject("Scripting.FileSystemObject")
content = ""

'Iterate through all the arguments passed
for i = 0 to objArgs.count  
    on error resume next
    'Try and treat the argument like a folder
    Set folder = objFso.GetFolder(objArgs(i))
    'If we get an error, we know it is a file
    if err.number <> 0 then
        'This is not a folder, treat as file
        content = content & ReadFile(objArgs(i))
    else
        'No error? This is a folder, process accordingly
        for each file in folder.Files
            content = content & ReadFile(file.path)
        next
    end if
    on error goto 0
next

'Get system Temp folder path
set tempFolderPath = objFso.GetSpecialFolder(2)
'Generate a random filename to use for a temporary file
strTempFileName = objFso.GetTempName
'Create temporary file in Temp folder
set objTempFile = tempFolderPath.CreateTextFile(strTempFileName)
'Write content from JavaScript files to temporary file
objTempFile.WriteLine(content)
objTempFile.Close

'Open temporary file in Notepad
set objShell = CreateObject("WScript.Shell")
objShell.Run("Notepad.exe " & tempFolderPath & "\" & strTempFileName)


function ReadFile(strFilePath)
    'If file path ends with ".js", we know it is JavaScript file
    if Right(strFilePath, 3) = ".js" then       
        set objFile = objFso.OpenTextFile(strFilePath, 1, false)
        'Read entire contents of a JavaScript file and returns it as a string
        ReadFile = objFile.ReadAll & vbNewLine
        objFile.Close
    else
        'Return empty string
        ReadFile = ""
    end if  
end function

Hibernate Error: a different object with the same identifier value was already associated with the session

Most probably its because the B objects are not referring to the same Java C object instance. They are referring to the same row in the database (i.e. the same primary key) but they're different copies of it.

So what is happening is that the Hibernate session, which is managing the entities would be keeping track of which Java object corresponds to the row with the same primary key.

One option would be to make sure that the Entities of objects B that refer to the same row are actually referring to the same object instance of C. Alternatively turn off cascading for that member variable. This way when B is persisted C is not. You will have to save C manually separately though. If C is a type/category table, then it probably makes sense to be that way.

Convert object to JSON in Android

As of Android 3.0 (API Level 11) Android has a more recent and improved JSON Parser.

http://developer.android.com/reference/android/util/JsonReader.html

Reads a JSON (RFC 4627) encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document. Within JSON objects, name/value pairs are represented by a single token.

html tables & inline styles

Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.

Codepen

Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px

I start my line :

<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
   <tr style="height:40px; width:450px; margin:0;">
     <td style="height:40px; width:40px; margin:0;">
        <img src="" style="width=40px;height40;margin:0;display:block"
     </td>
     <td style="height:40px; width:10px; margin:0;">        
     </td>
     <td style="height:40px; width:400px; margin:0;">
     <p style=" margin:0;"> my text   </p>
     </td>
   </tr>
</table>

Default value in Doctrine

Database default values are not "portably" supported. The only way to use database default values is through the columnDefinition mapping attribute where you specify the SQL snippet (DEFAULT cause inclusive) for the column the field is mapped to.

You can use:

<?php
/**
 * @Entity
 */
class myEntity {
    /**
     * @var string
     *
     * @Column(name="myColumn", type="string", length="50")
     */
    private $myColumn = 'myDefaultValue';
    ...
}

PHP-level default values are preferred as these are also properly available on newly created and persisted objects (Doctrine will not go back to the database after persisting a new object to get the default values).

Static methods in Python?

Yep, using the staticmethod decorator

class MyClass(object):
    @staticmethod
    def the_static_method(x):
        print(x)

MyClass.the_static_method(2)  # outputs 2

Note that some code might use the old method of defining a static method, using staticmethod as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3)

class MyClass(object):
    def the_static_method(x):
        print(x)
    the_static_method = staticmethod(the_static_method)

MyClass.the_static_method(2)  # outputs 2

This is entirely identical to the first example (using @staticmethod), just not using the nice decorator syntax

Finally, use staticmethod sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.


The following is verbatim from the documentation::

A static method does not receive an implicit first argument. To declare a static method, use this idiom:

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see classmethod().

For more information on static methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

New in version 2.2.

Changed in version 2.4: Function decorator syntax added.

jQuery .val() vs .attr("value")

The proper way to set and get the value of a form field is using .val() method.

$('#field').val('test'); // Set
var value = $('#field').val(); // Get

With jQuery 1.6 there is a new method called .prop().

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

How do I rename the extension for a bunch of files?

For Ubuntu Users :

rename 's/\.html$/\.txt/' *.html

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

Python BeautifulSoup extract text between element

Learn more about how to navigate through the parse tree in BeautifulSoup. Parse tree has got tags and NavigableStrings (as THIS IS A TEXT). An example

from BeautifulSoup import BeautifulSoup 
doc = ['<html><head><title>Page title</title></head>',
       '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
       '<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
       '</html>']
soup = BeautifulSoup(''.join(doc))

print soup.prettify()
# <html>
#  <head>
#   <title>
#    Page title
#   </title>
#  </head>
#  <body>
#   <p id="firstpara" align="center">
#    This is paragraph
#    <b>
#     one
#    </b>
#    .
#   </p>
#   <p id="secondpara" align="blah">
#    This is paragraph
#    <b>
#     two
#    </b>
#    .
#   </p>
#  </body>
# </html>

To move down the parse tree you have contents and string.

  • contents is an ordered list of the Tag and NavigableString objects contained within a page element

  • if a tag has only one child node, and that child node is a string, the child node is made available as tag.string, as well as tag.contents[0]

For the above, that is to say you can get

soup.b.string
# u'one'
soup.b.contents[0]
# u'one'

For several children nodes, you can have for instance

pTag = soup.p
pTag.contents
# [u'This is paragraph ', <b>one</b>, u'.']

so here you may play with contents and get contents at the index you want.

You also can iterate over a Tag, this is a shortcut. For instance,

for i in soup.body:
    print i
# <p id="firstpara" align="center">This is paragraph <b>one</b>.</p>
# <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

You are looking for a bit. It stores 1 or 0 (or NULL).

Alternatively, you could use the strings 'true' and 'false' in place of 1 or 0, like so-

declare @b1 bit = 'false'
print @b1                    --prints 0

declare @b2 bit = 'true'
print @b2                    --prints 1

Also, any non 0 value (either positive or negative) evaluates to (or converts to in some cases) a 1.

declare @i int = -42
print cast(@i as bit)    --will print 1, because @i is not 0

Note that SQL Server uses three valued logic (true, false, and NULL), since NULL is a possible value of the bit data type. Here are the relevant truth tables -

enter image description here

More information on three valued logic-

Example of three valued logic in SQL Server

http://www.firstsql.com/idefend3.htm

https://www.simple-talk.com/sql/learn-sql-server/sql-and-the-snare-of-three-valued-logic/

Hibernate error - QuerySyntaxException: users is not mapped [from users]

In your Query you have to use class name(User) not table name(users) so your query is "from User"

Setting TIME_WAIT TCP

TIME_WAIT might not be the culprit.

int listen(int sockfd, int backlog);

According to Unix Network Programming Volume1, backlog is defined to be the sum of completed connection queue and incomplete connection queue.

Let's say the backlog is 5. If you have 3 completed connections (ESTABLISHED state), and 2 incomplete connections (SYN_RCVD state), and there is another connect request with SYN. The TCP stack just ignores the SYN packet, knowing it'll be retransmitted some other time. This might be causing the degradation.

At least that's what I've been reading. ;)

Is there any option to limit mongodb memory usage?

One thing you can limit is the amount of memory mongodb uses while building indexes. This is set using the maxIndexBuildMemoryUsageMegabytes setting. An example of how its set is below:

mongo --eval "db.adminCommand( { setParameter: 1, maxIndexBuildMemoryUsageMegabytes: 70000 } )"

IIS Request Timeout on long ASP.NET operation

I'm posting this here, because I've spent like 3 and 4 hours on it, and I've only found answers like those one above, that say do add the executionTime, but it doesn't solve the problem in the case that you're using ASP .NET Core. For it, this would work:

At web.config file, add the requestTimeout attribute at aspNetCore node.

<system.webServer>
  <aspNetCore requestTimeout="00:10:00" ... (other configs goes here) />
</system.webServer>

In this example, I'm setting the value for 10 minutes.

Reference: https://docs.microsoft.com/en-us/aspnet/core/hosting/aspnet-core-module#configuring-the-asp-net-core-module

Password hash function for Excel VBA

Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from http://vb.wikia.com/wiki/SHA-1.bas, with changes to support passing it a string, and executable from formulas in Excel cells.

' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
 Wend
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
 Else
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function

How to find patterns across multiple lines using grep?

you can use grep incase you are not keen in the sequence of the pattern.

grep -l "pattern1" filepattern*.* | xargs grep "pattern2"

example

grep -l "vector" *.cpp | xargs grep "map"

grep -l will find all the files which matches the first pattern, and xargs will grep for the second pattern. Hope this helps.

Mock MVC - Add Request Parameter to test

If anyone came to this question looking for ways to add multiple parameters at the same time (my case), you can use .params with a MultivalueMap instead of adding each .param :

LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");

mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())

Fragments onResume from back stack

The following section at Android Developers describes a communication mechanism Creating event callbacks to the activity. To quote a line from it:

A good way to do that is to define a callback interface inside the fragment and require that the host activity implement it. When the activity receives a callback through the interface, it can share the information with other fragments in the layout as necessary.

Edit: The fragment has an onStart(...) which is invoked when the fragment is visible to the user. Similarly an onResume(...) when visible and actively running. These are tied to their activity counterparts. In short: use onResume()

How to disable all div content

The disabled attribute is not part of the W3C spec for DIV elements, only for form elements.

The jQuery approach suggested by Martin is the only foolproof way you're going to accomplish this.

Converting float to char*

typedef union{
    float a;
    char b[4];
} my_union_t;

You can access to float data value byte by byte and send it through 8-bit output buffer (e.g. USART) without casting.

Uncaught TypeError: Cannot read property 'top' of undefined

The problem you are most likely having is that there is a link somewhere in the page to an anchor that does not exist. For instance, let's say you have the following:

<a href="#examples">Skip to examples</a>

There has to be an element in the page with that id, example:

<div id="examples">Here are the examples</div>

So make sure that each one of the links are matched inside the page with it's corresponding anchor.

1067 error on attempt to start MySQL

when looked at mysql log (.err file under data folder), i could see the following

21:41:47 UTC - mysqld got exception 0xc0000005 ; This could be because you hit a bug. It is also possible that this binary or one of the libraries it was linked against is corrupt, improperly built, or misconfigured. This error can also be caused by malfunctioning hardware. Attempting to collect some information that could help diagnose the problem. As this is a crash and something is definitely wrong, the information collection process might fail.

I realized i was starting the service while i plugged usb. To be honest, the problem was resolved after i restarted my machine followed by restarting the service. In addition i removed ib_logfile0 and ib_logfile1 files before my restart. Though the event logger indicated "InnoDB: Your database may be corrupt or you may have copied the InnoDB tablespace but not the InnoDB log files. Please refer to http://dev.mysql.com/doc/refman/5.7/en/forcing-innodb-recovery.html for information

Blockquote

about forcing recovery.For more information, see Help and Support Center at http://www.mysql.com", i do not think so because i never changed any configurations.

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is available only on IE browser. So every other useragent will throw an error

On modern browser you could use instead File API or File writer API (currently implemented only on Chrome)

Disable activity slide-in animation when launching new activity?

The FLAG_ACTIVITY_NO_ANIMATION flag works fine for disabling the animation when starting activities.

To disable the similar animation that is triggered when calling finish() on an Activity, i.e the animation slides from right to left instead, you can call overridePendingTransition(0, 0) after calling finish() and the next animation will be excluded.

This also works on the in-animation if you call overridePendingTransition(0, 0) after calling startActivity(...).

Encrypt and Decrypt text with RSA in PHP

I have difficulty in decrypting a long string that is encrypted in python. Here is the python encryption function:

def RSA_encrypt(public_key, msg, chunk_size=214):
    """
    Encrypt the message by the provided RSA public key.

    :param public_key: RSA public key in PEM format.
    :type public_key: binary
    :param msg: message that to be encrypted
    :type msg: string
    :param chunk_size: the chunk size used for PKCS1_OAEP decryption, it is determined by \
    the private key length used in bytes - 42 bytes.
    :type chunk_size: int
    :return: Base 64 encryption of the encrypted message
    :rtype: binray
    """
    rsa_key = RSA.importKey(public_key)
    rsa_key = PKCS1_OAEP.new(rsa_key)

    encrypted = b''
    offset = 0
    end_loop = False

    while not end_loop:
        chunk = msg[offset:offset + chunk_size]

        if len(chunk) % chunk_size != 0:
            chunk += " " * (chunk_size - len(chunk))
            end_loop = True

        encrypted += rsa_key.encrypt(chunk.encode())
        offset += chunk_size

    return base64.b64encode(encrypted)

The decryption in PHP:

/**
 * @param  base64_encoded string holds the encrypted message.
 * @param  Resource your private key loaded using openssl_pkey_get_private
 * @param  integer Chunking by bytes to feed to the decryptor algorithm.
 * @return String decrypted message.
 */
public function RSADecyrpt($encrypted_msg, $ppk, $chunk_size=256){
    if(is_null($ppk))
        throw new Exception("Returned message is encrypted while you did not provide private key!");
    $encrypted_msg = base64_decode($encrypted_msg);

    $offset = 0;
    $chunk_size = 256;

    $decrypted = "";
    while($offset < strlen($encrypted_msg)){
        $decrypted_chunk = "";
        $chunk = substr($encrypted_msg, $offset, $chunk_size);

        if(openssl_private_decrypt($chunk, $decrypted_chunk, $ppk, OPENSSL_PKCS1_OAEP_PADDING))
            $decrypted .= $decrypted_chunk;
        else 
            throw new exception("Problem decrypting the message");
        $offset += $chunk_size;
    }
    return $decrypted;
}

Center Plot title in ggplot2

From the release news of ggplot 2.2.0: "The main plot title is now left-aligned to better work better with a subtitle". See also the plot.title argument in ?theme: "left-aligned by default".

As pointed out by @J_F, you may add theme(plot.title = element_text(hjust = 0.5)) to center the title.

ggplot() +
  ggtitle("Default in 2.2.0 is left-aligned")

enter image description here

ggplot() +
  ggtitle("Use theme(plot.title = element_text(hjust = 0.5)) to center") +
  theme(plot.title = element_text(hjust = 0.5))

enter image description here

How unique is UUID?

The answer to this may depend largely on the UUID version.

Many UUID generators use a version 4 random number. However, many of these use Pseudo a Random Number Generator to generate them.

If a poorly seeded PRNG with a small period is used to generate the UUID I would say it's not very safe at all. Some random number generators also have poor variance. i.e. favouring certain numbers more often than others. This isn't going to work well.

Therefore, it's only as safe as the algorithms used to generate it.

On the flip side, if you know the answer to these questions then I think a version 4 uuid should be very safe to use. In fact I'm using it to identify blocks on a network block file system and so far have not had a clash.

In my case, the PRNG I'm using is a mersenne twister and I'm being careful with the way it's seeded which is from multiple sources including /dev/urandom. Mersenne twister has a period of 2^19937 - 1. It's going to be a very very long time before I see a repeat uuid.

So pick a good library or generate it yourself and make sure you use a decent PRNG algorithm.

How can I check if a program exists from a Bash script?

To mimic Bash's type -P cmd, we can use the POSIX compliant env -i type cmd 1>/dev/null 2>&1.

man env
# "The option '-i' causes env to completely ignore the environment it inherits."
# In other words, there are no aliases or functions to be looked up by the type command.

ls() { echo 'Hello, world!'; }

ls
type ls
env -i type ls

cmd=ls
cmd=lsx
env -i type $cmd 1>/dev/null 2>&1 || { echo "$cmd not found"; exit 1; }

Fastest way to list all primes below N

Fastest prime sieve in Pure Python:

from itertools import compress

def half_sieve(n):
    """
    Returns a list of prime numbers less than `n`.
    """
    if n <= 2:
        return []
    sieve = bytearray([True]) * (n // 2)
    for i in range(3, int(n ** 0.5) + 1, 2):
        if sieve[i // 2]:
            sieve[i * i // 2::i] = bytearray((n - i * i - 1) // (2 * i) + 1)
    primes = list(compress(range(1, n, 2), sieve))
    primes[0] = 2
    return primes

I optimised Sieve of Eratosthenes for speed and memory.

Benchmark

from time import clock
import platform

def benchmark(iterations, limit):
    start = clock()
    for x in range(iterations):
        half_sieve(limit)
    end = clock() - start
    print(f'{end/iterations:.4f} seconds for primes < {limit}')

if __name__ == '__main__':
    print(platform.python_version())
    print(platform.platform())
    print(platform.processor())
    it = 10
    for pw in range(4, 9):
        benchmark(it, 10**pw)

Output

>>> 3.6.7
>>> Windows-10-10.0.17763-SP0
>>> Intel64 Family 6 Model 78 Stepping 3, GenuineIntel
>>> 0.0003 seconds for primes < 10000
>>> 0.0021 seconds for primes < 100000
>>> 0.0204 seconds for primes < 1000000
>>> 0.2389 seconds for primes < 10000000
>>> 2.6702 seconds for primes < 100000000

How do you wait for input on the same Console.WriteLine() line?

As Matt has said, use Console.Write. I would also recommend explicitly flushing the output, however - I believe WriteLine does this automatically, but I'd seen oddities when just using Console.Write and then waiting. So Matt's code becomes:

Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();

Signed to unsigned conversion in C - is it always safe?

Horrible Answers Galore

Ozgur Ozcitak

When you cast from signed to unsigned (and vice versa) the internal representation of the number does not change. What changes is how the compiler interprets the sign bit.

This is completely wrong.

Mats Fredriksson

When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.

This is also wrong. Unsigned ints may be promoted to ints should they have equal precision due to padding bits in the unsigned type.

smh

Your addition operation causes the int to be converted to an unsigned int.

Wrong. Maybe it does and maybe it doesn't.

Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)

Wrong. It is either undefined behavior if it causes overflow or the value is preserved.

Anonymous

The value of i is converted to unsigned int ...

Wrong. Depends on the precision of an int relative to an unsigned int.

Taylor Price

As was previously answered, you can cast back and forth between signed and unsigned without a problem.

Wrong. Trying to store a value outside the range of a signed integer results in undefined behavior.

Now I can finally answer the question.

Should the precision of int be equal to unsigned int, u will be promoted to a signed int and you will get the value -4444 from the expression (u+i). Now, should u and i have other values, you may get overflow and undefined behavior but with those exact numbers you will get -4444 [1]. This value will have type int. But you are trying to store that value into an unsigned int so that will then be cast to an unsigned int and the value that result will end up having would be (UINT_MAX+1) - 4444.

Should the precision of unsigned int be greater than that of an int, the signed int will be promoted to an unsigned int yielding the value (UINT_MAX+1) - 5678 which will be added to the other unsigned int 1234. Should u and i have other values, which make the expression fall outside the range {0..UINT_MAX} the value (UINT_MAX+1) will either be added or subtracted until the result DOES fall inside the range {0..UINT_MAX) and no undefined behavior will occur.

What is precision?

Integers have padding bits, sign bits, and value bits. Unsigned integers do not have a sign bit obviously. Unsigned char is further guaranteed to not have padding bits. The number of values bits an integer has is how much precision it has.

[Gotchas]

The macro sizeof macro alone cannot be used to determine precision of an integer if padding bits are present. And the size of a byte does not have to be an octet (eight bits) as defined by C99.

[1] The overflow may occur at one of two points. Either before the addition (during promotion) - when you have an unsigned int which is too large to fit inside an int. The overflow may also occur after the addition even if the unsigned int was within the range of an int, after the addition the result may still overflow.

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

In my case, turn out to be that the version of mysql-connector-java was too old.

In my demo, I somehow use mysql-connector-java like this:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.9</version>
</dependency>

But in the develop environment, I use this:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.31</version>
</dependency>

And my MySQL version was 5.1.48(yes, it is old, just for mimic the product version). So I met the same error.

Since the reason is found, the solution is found, too. Match the version!

Programmatically Add CenterX/CenterY Constraints

Center in container

enter image description here

The code below does the same thing as centering in the Interface Builder.

override func viewDidLoad() {
    super.viewDidLoad()

    // set up the view
    let myView = UIView()
    myView.backgroundColor = UIColor.blue
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)

    // Add code for one of the constraint methods below
    // ...
}

Method 1: Anchor Style

myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

Method 2: NSLayoutConstraint Style

NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0).isActive = true

Notes

  • Anchor style is the preferred method over NSLayoutConstraint Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint Style.
  • You will also need to add length and width constraints.
  • My full answer is here.

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

numpy: most efficient frequency counts for unique values in an array

This is by far the most general and performant solution; surprised it hasn't been posted yet.

import numpy as np

def unique_count(a):
    unique, inverse = np.unique(a, return_inverse=True)
    count = np.zeros(len(unique), np.int)
    np.add.at(count, inverse, 1)
    return np.vstack(( unique, count)).T

print unique_count(np.random.randint(-10,10,100))

Unlike the currently accepted answer, it works on any datatype that is sortable (not just positive ints), and it has optimal performance; the only significant expense is in the sorting done by np.unique.

How to call Stored Procedure in Entity Framework 6 (Code-First)?

.NET Core 5.0 does not have FromSql instead it has FromSqlRaw

All below worked for me. Account class here is Entity in C# with exact same table and column names as in the database.

App configuration class as below

class AppConfiguration
{
    public AppConfiguration()
    {
        var configBuilder = new ConfigurationBuilder();
        var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
        configBuilder.AddJsonFile(path, false);
        var root = configBuilder.Build();
        var appSetting = root.GetSection("ConnectionStrings:DefaultConnection");
        sqlConnectionString = appSetting.Value;
    }

    public string sqlConnectionString { get; set; }
}

DbContext class:

public class DatabaseContext : DbContext
{
    public class OptionsBuild
    {
        public OptionsBuild()
        {
            setting = new AppConfiguration();
            opsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
            opsBuilder.UseSqlServer(setting.sqlConnectionString);
            dbOptions = opsBuilder.Options;
        }

        public DbContextOptionsBuilder<DatabaseContext> opsBuilder { get; set; }
        public DbContextOptions<DatabaseContext> dbOptions { get; set; }

        private AppConfiguration setting { get; set; }
    }

    public static OptionsBuild ops = new OptionsBuild();

    public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
    {
        //disable initializer
        //  Database.SetInitializer<DatabaseContext>(null);
    }

    public DbSet<Account> Account { get; set; }
}

This code should be in your data access layer:

List<Account> accounts = new List<Account>();
var context = new DatabaseContext(DatabaseContext.ops.dbOptions);
accounts = await context.Account.ToListAsync();   //direct select from a table

var param = new SqlParameter("@FirstName", "Bill");
accounts = await context.Account.FromSqlRaw<Account>("exec Proc_Account_Select", 
param).ToListAsync();            //procedure call with parameter
        
accounts = context.Account.FromSqlRaw("SELECT * FROM dbo.Account").ToList();  //raw query

Synchronously waiting for an async operation, and why does Wait() freeze the program here

With small custom synchronization context, sync function can wait for completion of async function, without creating deadlock. Here is small example for WinForms app.

Imports System.Threading
Imports System.Runtime.CompilerServices

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        SyncMethod()
    End Sub

    ' waiting inside Sync method for finishing async method
    Public Sub SyncMethod()
        Dim sc As New SC
        sc.WaitForTask(AsyncMethod())
        sc.Release()
    End Sub

    Public Async Function AsyncMethod() As Task(Of Boolean)
        Await Task.Delay(1000)
        Return True
    End Function

End Class

Public Class SC
    Inherits SynchronizationContext

    Dim OldContext As SynchronizationContext
    Dim ContextThread As Thread

    Sub New()
        OldContext = SynchronizationContext.Current
        ContextThread = Thread.CurrentThread
        SynchronizationContext.SetSynchronizationContext(Me)
    End Sub

    Dim DataAcquired As New Object
    Dim WorkWaitingCount As Long = 0
    Dim ExtProc As SendOrPostCallback
    Dim ExtProcArg As Object

    <MethodImpl(MethodImplOptions.Synchronized)>
    Public Overrides Sub Post(d As SendOrPostCallback, state As Object)
        Interlocked.Increment(WorkWaitingCount)
        Monitor.Enter(DataAcquired)
        ExtProc = d
        ExtProcArg = state
        AwakeThread()
        Monitor.Wait(DataAcquired)
        Monitor.Exit(DataAcquired)
    End Sub

    Dim ThreadSleep As Long = 0

    Private Sub AwakeThread()
        If Interlocked.Read(ThreadSleep) > 0 Then ContextThread.Resume()
    End Sub

    Public Sub WaitForTask(Tsk As Task)
        Dim aw = Tsk.GetAwaiter

        If aw.IsCompleted Then Exit Sub

        While Interlocked.Read(WorkWaitingCount) > 0 Or aw.IsCompleted = False
            If Interlocked.Read(WorkWaitingCount) = 0 Then
                Interlocked.Increment(ThreadSleep)
                ContextThread.Suspend()
                Interlocked.Decrement(ThreadSleep)
            Else
                Interlocked.Decrement(WorkWaitingCount)
                Monitor.Enter(DataAcquired)
                Dim Proc = ExtProc
                Dim ProcArg = ExtProcArg
                Monitor.Pulse(DataAcquired)
                Monitor.Exit(DataAcquired)
                Proc(ProcArg)
            End If
        End While

    End Sub

     Public Sub Release()
         SynchronizationContext.SetSynchronizationContext(OldContext)
     End Sub

End Class

Permission is only granted to system app

In Eclipse:

Window -> Preferences -> Android -> Lint Error Checking.

In the list find an entry with ID = ProtectedPermission. Set the Severity to something lower than Error. This way you can still compile the project using Eclipse.

In Android Studio:

File -> Settings -> Editor -> Inspections

Under Android Lint, locate Using system app permission. Either uncheck the checkbox or choose a Severity lower than Error.

Left function in c#

use substring function:

yourString.Substring(0, length);

How can I store HashMap<String, ArrayList<String>> inside a list?

Always try to use interface reference in Collection, this adds more flexibility.
What is the problem with the below code?

List<Map<String,List<String>>> list = new ArrayList<Map<String,List<String>>>();//This is the final list you need
Map<String, List<String>> map1 = new HashMap<String, List<String>>();//This is one instance of the  map you want to store in the above list.
List<String> arraylist1 = new ArrayList<String>();
arraylist1.add("Text1");//And so on..
map1.put("key1",arraylist1);
//And so on...
list.add(map1);//In this way you can add.

You can easily do it like the above.

How do I update a GitHub forked repository?

Use these commands (in lucky case)

git remote -v
git pull
git fetch upstream
git checkout master
git merge upstream/master --no-ff
git add .
git commit -m"Sync with upstream repository."
git push -v

What's a good hex editor/viewer for the Mac?

  1. Open file with Xcode and press Command + Shift + J
  2. Right click file name in left pane
  3. Open as -> Hex

Android set height and width of Custom view programmatically

On Kotlin you can set width and height of any view directly using their virtual properties:

someView.layoutParams.width = 100
someView.layoutParams.height = 200

How to get HQ youtube thumbnails?

Are you referring to the full resolution one?:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

I don't believe you can get 'multiple' images of HQ because the one you have is the one.

Check the following answer out for more information on the URLs: How do I get a YouTube video thumbnail from the YouTube API?

For live videos use https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault_live.jpg

- cornips

How do I use Join-Path to combine more than two strings into a file path?

The following approach is more concise than piping Join-Path statements:

$p = "a"; "b", "c", "d" | ForEach-Object -Process { $p = Join-Path $p $_ }

$p then holds the concatenated path 'a\b\c\d'.

(I just noticed that this is the exact same approach as Mike Fair's, sorry.)

Show tables, describe tables equivalent in redshift

You can simply use the command below to describe a table.

desc table-name

or

desc schema-name.table-name

My Routes are Returning a 404, How can I Fix Them?

On my Ubuntu LAMP installation, I solved this problem with the following 2 changes.

  1. Enable mod_rewrite on the apache server: sudo a2enmod rewrite.
  2. Edit /etc/apache2/apache2.conf, changing the "AllowOverride" directive for the /var/www directory (which is my main document root): AllowOverride All

Then restart the Apache server: service apache2 restart

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

How to rebuild docker container in docker-compose.yml?

Only:

$ docker-compose restart [yml_service_name]

How do I get TimeSpan in minutes given two Dates?

See TimeSpan.TotalMinutes:

Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.

Read files from a Folder present in project

string myFile= File.ReadAllLines(Application.StartupPath.ToString() + @"..\..\..\Data\myTxtFile.txt")

Java : Sort integer array without using Arrays.sort()

Array Sorting without using built in functions in java ......just make new File unsing this name -> (ArraySorting.java) ..... Run the Project and Enjoy it !!!!!

    import java.io.*;
    import java.util.Arrays;
    import java.util.Scanner;
    public class ArraySorting 
    {
    public static void main(String args[])
    {
      int temp=0;   
      Scanner user_input=new Scanner(System.in);
       System.out.println("enter Size of Array...");
    int Size=user_input.nextInt();

    int[] a=new int[Size];
    System.out.println("Enter element Of an Array...");
    for(int j=0;j<Size;j++)
    {
        a[j]=user_input.nextInt();
    }     
    for(int index=0;index<a.length;index++)
    {
        for(int j=index+1;j<a.length;j++)
        {
             if(a[index] > a[j] ) 
             {
                 temp = a[index];
                 a[index] = a[j];
                 a[j] = temp;
             }
        }
    }
    System.out.print("Output is:- ");
    for(int i=0;i<a.length;i++)
    {
        System.out.println(a[i]);
    }

}
}

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

This worked for me:

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

[Serializable]
public class BankPayment : Payment {} 

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

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

Multiple condition in single IF statement

Yes that is valid syntax but it may well not do what you want.

Execution will continue after your RAISERROR except if you add a RETURN. So you will need to add a block with BEGIN ... END to hold the two statements.

Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.

Finally I'd simplify the conditions using IN

CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
                                            @UserType TINYINT,
                                            @UserName NVARCHAR(100),
                                            @Password NVARCHAR(100))
AS
  BEGIN
      IF ( @TenantId IS NULL
           AND @UserType IN ( 0, 1 ) )
        BEGIN
            RAISERROR('The value for @TenantID should not be null',15,1);

            RETURN;
        END
  END 

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

You can check that theHref is defined by checking against undefined.

if (undefined !== theHref && theHref.length) {
    // `theHref` is not undefined and has truthy property _length_
    // do stuff
} else {
    // do other stuff
}

If you want to also protect yourself against falsey values like null then check theHref is truthy, which is a little shorter

if (theHref && theHref.length) {
    // `theHref` is truthy and has truthy property _length_
}

How to change title of Activity in Android?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.Main_Activity);
    this.setTitle("Title name");
}

Using sed and grep/egrep to search and replace

My use case was I wanted to replace foo:/Drive_Letter with foo:/bar/baz/xyz In my case I was able to do it with the following code. I was in the same directory location where there were bulk of files.

find . -name "*.library" -print0 | xargs -0 sed -i '' -e 's/foo:\/Drive_Letter:/foo:\/bar\/baz\/xyz/g'

hope that helped.

UPDATE s|foo:/Drive_letter:|foo:/ba/baz/xyz|g

wget command to download a file and save as a different filename

Use the -O file option.

E.g.

wget google.com
...
16:07:52 (538.47 MB/s) - `index.html' saved [10728]

vs.

wget -O foo.html google.com
...
16:08:00 (1.57 MB/s) - `foo.html' saved [10728]

Show "loading" animation on button click

I know this a very much late reply but I saw this query recently And found a working scenario,

OnClick of Submit use the below code:

 $('#Submit').click(function ()
 { $(this).html('<img src="icon-loading.gif" />'); // A GIF Image of Your choice
 return false });

To Stop the Gif use the below code:

$('#Submit').ajaxStop();

How to compile python script to binary executable

# -*- mode: python -*-

block_cipher = None

a = Analysis(['SCRIPT.py'],
             pathex=[
                 'folder path',
                 'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_50c6cb8431e7428f',
                 'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_c4f50889467f081d'
             ],
             binaries=[(''C:\\Users\\chromedriver.exe'')],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='NAME OF YOUR EXE',
          debug=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=True )

How to reposition Chrome Developer Tools

Keyboard shortcut to toggle the docking position (side/bottom)

CTRL+SHIFT+D

And there are many shortcuts you can see them by going to

Settings » Shortcuts, as displayed here:
Settings screenshot

Alternatively, use CTRL + ? to go to the settings, from there one can reach the "Shortcuts" sub-item on the left or use the Official reference.

c# why can't a nullable int be assigned null as a value

What Harry S says is exactly right, but

int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));

would also do the trick. (We Resharper users can always spot each other in crowds...)

Why can't I use a list as a dict key in python?

Why can't I use a list as a dict key in python?

>>> d = {repr([1,2,3]): 'value'}
{'[1, 2, 3]': 'value'}

(for anybody who stumbles on this question looking for a way around it)

as explained by others here, indeed you cannot. You can however use its string representation instead if you really want to use your list.

How to use Elasticsearch with MongoDB?

River is a good solution once you want to have a almost real time synchronization and general solution.

If you have data in MongoDB already and want to ship it very easily to Elasticsearch like "one-shot" you can try my package in Node.js https://github.com/itemsapi/elasticbulk.

It's using Node.js streams so you can import data from everything what is supporting streams (i.e. MongoDB, PostgreSQL, MySQL, JSON files, etc)

Example for MongoDB to Elasticsearch:

Install packages:

npm install elasticbulk
npm install mongoose
npm install bluebird

Create script i.e. script.js:

const elasticbulk = require('elasticbulk');
const mongoose = require('mongoose');
const Promise = require('bluebird');
mongoose.connect('mongodb://localhost/your_database_name', {
  useMongoClient: true
});

mongoose.Promise = Promise;

var Page = mongoose.model('Page', new mongoose.Schema({
  title: String,
  categories: Array
}), 'your_collection_name');

// stream query 
var stream = Page.find({
}, {title: 1, _id: 0, categories: 1}).limit(1500000).skip(0).batchSize(500).stream();

elasticbulk.import(stream, {
  index: 'my_index_name',
  type: 'my_type_name',
  host: 'localhost:9200',
})
.then(function(res) {
  console.log('Importing finished');
})

Ship your data:

node script.js

It's not extremely fast but it's working for millions of records (thanks to streams).

awk - concatenate two string variable and assign to a third

Could use sprintf to accomplish this:

awk '{str = sprintf("%s %s", $1, $2)} END {print str}' file

eslint: error Parsing error: The keyword 'const' is reserved

If using Visual Code one option is to add this to the settings.json file:

"eslint.options": {
    "useEslintrc": false,
    "parserOptions": {
        "ecmaVersion": 2017
    },
    "env": {
        "es6": true
    }
}

How to monitor the memory usage of Node.js?

Also, if you'd like to know global memory rather than node process':

var os = require('os');

os.freemem();
os.totalmem();

See documentation

How can I retrieve a table from stored procedure to a datatable?

string connString = "<your connection string>";
string sql = "name of your sp";

using(SqlConnection conn = new SqlConnection(connString)) 
{
    try 
    {
        using(SqlDataAdapter da = new SqlDataAdapter()) 
        {
            da.SelectCommand = new SqlCommand(sql, conn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;

            DataSet ds = new DataSet();   
            da.Fill(ds, "result_name");

            DataTable dt = ds.Tables["result_name"];

            foreach (DataRow row in dt.Rows) {
                //manipulate your data
            }
        }    
    } 
    catch(SQLException ex) 
    {
        Console.WriteLine("SQL Error: " + ex.Message);
    }
    catch(Exception e) 
    {
        Console.WriteLine("Error: " + e.Message);
    }
}

Modified from Java Schools Example

How to assign colors to categorical variables in ggplot2 that have stable mapping?

The easiest solution is to convert your categorical variable to a factor prior to the subsetting. Bottomline is that you need a factor variable with exact the same levels in all your subsets.

library(ggplot2)
dataset <- data.frame(category = rep(LETTERS[1:5], 100), 
    x = rnorm(500, mean = rep(1:5, 100)), y = rnorm(500, mean = rep(1:5, 100)))
dataset$fCategory <- factor(dataset$category)
subdata <- subset(dataset, category %in% c("A", "D", "E"))

With a character variable

ggplot(dataset, aes(x = x, y = y, colour = category)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = category)) + geom_point()

With a factor variable

ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()

Setting cursor at the end of any text of a textbox

For Windows Forms you can control cursor position (and selection) with txtbox.SelectionStart and txtbox.SelectionLength properties. If you want to set caret to end try this:

txtbox.SelectionStart = txtbox.Text.Length;
txtbox.SelectionLength = 0;

For WPF see this question.

What is the proper way to re-attach detached objects in Hibernate?

Session.contains(Object obj) checks the reference and will not detect a different instance that represents the same row and is already attached to it.

Here my generic solution for Entities with an identifier property.

public static void update(final Session session, final Object entity)
{
    // if the given instance is in session, nothing to do
    if (session.contains(entity))
        return;

    // check if there is already a different attached instance representing the same row
    final ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(entity.getClass());
    final Serializable identifier = classMetadata.getIdentifier(entity, (SessionImplementor) session);

    final Object sessionEntity = session.load(entity.getClass(), identifier);
    // override changes, last call to update wins
    if (sessionEntity != null)
        session.evict(sessionEntity);
    session.update(entity);
}

This is one of the few aspects of .Net EntityFramework I like, the different attach options regarding changed entities and their properties.

How to check if MySQL returns null/empty?

if ( (strlen($ownerID) == 0) || ($ownerID == '0') || (empty($ownerID )) )

if $ownerID is NULL it will be triggered by the empty() test

https://www.php.net/empty

Reloading .env variables without restarting server (Laravel 5, shared hosting)

In case anybody stumbles upon this question who cannot reload their webserver (long running console command like a queue runner) or needs to reload their .env file mid-request, i found a way to properly reload .env variables in laravel 5.

use Dotenv;
use InvalidArgumentException;

try {
    Dotenv::makeMutable();
    Dotenv::load(app()->environmentPath(), app()->environmentFile());
    Dotenv::makeImmutable();
} catch (InvalidArgumentException $e) {
    //
}

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

Run a mySQL query as a cron job?

It depends on what runs cron on your system, but all you have to do to run a php script from cron is to do call the location of the php installation followed by the script location. An example with crontab running every hour:

# crontab -e
00 * * * * /usr/local/bin/php /home/path/script.php

On my system, I don't even have to put the path to the php installation:

00 * * * * php /home/path/script.php

On another note, you should not be using mysql extension because it is deprecated, unless you are using an older installation of php. Read here for a comparison.

mongodb group values by multiple fields

TLDR Summary

In modern MongoDB releases you can brute force this with $slice just off the basic aggregation result. For "large" results, run parallel queries instead for each grouping ( a demonstration listing is at the end of the answer ), or wait for SERVER-9377 to resolve, which would allow a "limit" to the number of items to $push to an array.

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 },
    { "$project": {
        "books": { "$slice": [ "$books", 2 ] },
        "count": 1
    }}
])

MongoDB 3.6 Preview

Still not resolving SERVER-9377, but in this release $lookup allows a new "non-correlated" option which takes an "pipeline" expression as an argument instead of the "localFields" and "foreignFields" options. This then allows a "self-join" with another pipeline expression, in which we can apply $limit in order to return the "top-n" results.

db.books.aggregate([
  { "$group": {
    "_id": "$addr",
    "count": { "$sum": 1 }
  }},
  { "$sort": { "count": -1 } },
  { "$limit": 2 },
  { "$lookup": {
    "from": "books",
    "let": {
      "addr": "$_id"
    },
    "pipeline": [
      { "$match": { 
        "$expr": { "$eq": [ "$addr", "$$addr"] }
      }},
      { "$group": {
        "_id": "$book",
        "count": { "$sum": 1 }
      }},
      { "$sort": { "count": -1  } },
      { "$limit": 2 }
    ],
    "as": "books"
  }}
])

The other addition here is of course the ability to interpolate the variable through $expr using $match to select the matching items in the "join", but the general premise is a "pipeline within a pipeline" where the inner content can be filtered by matches from the parent. Since they are both "pipelines" themselves we can $limit each result separately.

This would be the next best option to running parallel queries, and actually would be better if the $match were allowed and able to use an index in the "sub-pipeline" processing. So which is does not use the "limit to $push" as the referenced issue asks, it actually delivers something that should work better.


Original Content

You seem have stumbled upon the top "N" problem. In a way your problem is fairly easy to solve though not with the exact limiting that you ask for:

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 }
])

Now that will give you a result like this:

{
    "result" : [
            {
                    "_id" : "address1",
                    "books" : [
                            {
                                    "book" : "book4",
                                    "count" : 1
                            },
                            {
                                    "book" : "book5",
                                    "count" : 1
                            },
                            {
                                    "book" : "book1",
                                    "count" : 3
                            }
                    ],
                    "count" : 5
            },
            {
                    "_id" : "address2",
                    "books" : [
                            {
                                    "book" : "book5",
                                    "count" : 1
                            },
                            {
                                    "book" : "book1",
                                    "count" : 2
                            }
                    ],
                    "count" : 3
            }
    ],
    "ok" : 1
}

So this differs from what you are asking in that, while we do get the top results for the address values the underlying "books" selection is not limited to only a required amount of results.

This turns out to be very difficult to do, but it can be done though the complexity just increases with the number of items you need to match. To keep it simple we can keep this at 2 matches at most:

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 },
    { "$unwind": "$books" },
    { "$sort": { "count": 1, "books.count": -1 } },
    { "$group": {
        "_id": "$_id",
        "books": { "$push": "$books" },
        "count": { "$first": "$count" }
    }},
    { "$project": {
        "_id": {
            "_id": "$_id",
            "books": "$books",
            "count": "$count"
        },
        "newBooks": "$books"
    }},
    { "$unwind": "$newBooks" },
    { "$group": {
      "_id": "$_id",
      "num1": { "$first": "$newBooks" }
    }},
    { "$project": {
        "_id": "$_id",
        "newBooks": "$_id.books",
        "num1": 1
    }},
    { "$unwind": "$newBooks" },
    { "$project": {
        "_id": "$_id",
        "num1": 1,
        "newBooks": 1,
        "seen": { "$eq": [
            "$num1",
            "$newBooks"
        ]}
    }},
    { "$match": { "seen": false } },
    { "$group":{
        "_id": "$_id._id",
        "num1": { "$first": "$num1" },
        "num2": { "$first": "$newBooks" },
        "count": { "$first": "$_id.count" }
    }},
    { "$project": {
        "num1": 1,
        "num2": 1,
        "count": 1,
        "type": { "$cond": [ 1, [true,false],0 ] }
    }},
    { "$unwind": "$type" },
    { "$project": {
        "books": { "$cond": [
            "$type",
            "$num1",
            "$num2"
        ]},
        "count": 1
    }},
    { "$group": {
        "_id": "$_id",
        "count": { "$first": "$count" },
        "books": { "$push": "$books" }
    }},
    { "$sort": { "count": -1 } }
])

So that will actually give you the top 2 "books" from the top two "address" entries.

But for my money, stay with the first form and then simply "slice" the elements of the array that are returned to take the first "N" elements.


Demonstration Code

The demonstration code is appropriate for usage with current LTS versions of NodeJS from v8.x and v10.x releases. That's mostly for the async/await syntax, but there is nothing really within the general flow that has any such restriction, and adapts with little alteration to plain promises or even back to plain callback implementation.

index.js

const { MongoClient } = require('mongodb');
const fs = require('mz/fs');

const uri = 'mongodb://localhost:27017';

const log = data => console.log(JSON.stringify(data, undefined, 2));

(async function() {

  try {
    const client = await MongoClient.connect(uri);

    const db = client.db('bookDemo');
    const books = db.collection('books');

    let { version } = await db.command({ buildInfo: 1 });
    version = parseFloat(version.match(new RegExp(/(?:(?!-).)*/))[0]);

    // Clear and load books
    await books.deleteMany({});

    await books.insertMany(
      (await fs.readFile('books.json'))
        .toString()
        .replace(/\n$/,"")
        .split("\n")
        .map(JSON.parse)
    );

    if ( version >= 3.6 ) {

    // Non-correlated pipeline with limits
      let result = await books.aggregate([
        { "$group": {
          "_id": "$addr",
          "count": { "$sum": 1 }
        }},
        { "$sort": { "count": -1 } },
        { "$limit": 2 },
        { "$lookup": {
          "from": "books",
          "as": "books",
          "let": { "addr": "$_id" },
          "pipeline": [
            { "$match": {
              "$expr": { "$eq": [ "$addr", "$$addr" ] }
            }},
            { "$group": {
              "_id": "$book",
              "count": { "$sum": 1 },
            }},
            { "$sort": { "count": -1 } },
            { "$limit": 2 }
          ]
        }}
      ]).toArray();

      log({ result });
    }

    // Serial result procesing with parallel fetch

    // First get top addr items
    let topaddr = await books.aggregate([
      { "$group": {
        "_id": "$addr",
        "count": { "$sum": 1 }
      }},
      { "$sort": { "count": -1 } },
      { "$limit": 2 }
    ]).toArray();

    // Run parallel top books for each addr
    let topbooks = await Promise.all(
      topaddr.map(({ _id: addr }) =>
        books.aggregate([
          { "$match": { addr } },
          { "$group": {
            "_id": "$book",
            "count": { "$sum": 1 }
          }},
          { "$sort": { "count": -1 } },
          { "$limit": 2 }
        ]).toArray()
      )
    );

    // Merge output
    topaddr = topaddr.map((d,i) => ({ ...d, books: topbooks[i] }));
    log({ topaddr });

    client.close();

  } catch(e) {
    console.error(e)
  } finally {
    process.exit()
  }

})()

books.json

{ "addr": "address1",  "book": "book1"  }
{ "addr": "address2",  "book": "book1"  }
{ "addr": "address1",  "book": "book5"  }
{ "addr": "address3",  "book": "book9"  }
{ "addr": "address2",  "book": "book5"  }
{ "addr": "address2",  "book": "book1"  }
{ "addr": "address1",  "book": "book1"  }
{ "addr": "address15", "book": "book1"  }
{ "addr": "address9",  "book": "book99" }
{ "addr": "address90", "book": "book33" }
{ "addr": "address4",  "book": "book3"  }
{ "addr": "address5",  "book": "book1"  }
{ "addr": "address77", "book": "book11" }
{ "addr": "address1",  "book": "book1"  }

Make JQuery UI Dialog automatically grow or shrink to fit its contents

This works with jQuery UI v1.10.3

$("selector").dialog({height:'auto', width:'auto'});

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

amustill's answer as a knockout handler:

ko.bindingHandlers.preventParentScroll = {
    init: function (element, valueAccessor, allBindingsAccessor, context) {
        $(element).mousewheel(function (e, d) {
            var t = $(this);
            if (d > 0 && t.scrollTop() === 0) {
                e.preventDefault();
            }
            else {
                if (d < 0 && (t.scrollTop() == t.get(0).scrollHeight - t.innerHeight())) {
                    e.preventDefault();
                }
            }
        });
    }
};

Letter Count on a string

Your return is in your for loop! Be careful with indentation, you want the line return count to be outside the loop. Because the for loop goes through all characters in word, the outer while loop is completely unneeded.

A cleaned-up version:

def count_letters(word, to_find):
    count = 0
    for char in word:
        if char == to_find:
            count += 1
    return count

Link to the issue number on GitHub within a commit message

github adds a reference to the commit if it contains #issuenbr (discovered this by chance).

SQL UPDATE with sub-query that references the same table in MySQL

Some reference for you http://dev.mysql.com/doc/refman/5.0/en/update.html

UPDATE user_account student 
INNER JOIN user_account teacher ON
   teacher.user_account_id = student.teacher_id 
   AND teacher.user_type = 'ROLE_TEACHER'
SET student.student_education_facility_id = teacher.education_facility_id

Font size of TextView in Android application changes on changing font size from native settings

simple way to prevent the whole app from getting effected by system font size is to updateConfiguration using a base activity.

//in base activity add this code.
public  void adjustFontScale( Configuration configuration) {

    configuration.fontScale = (float) 1.0;
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);
    metrics.scaledDensity = configuration.fontScale * metrics.density;
    getBaseContext().getResources().updateConfiguration(configuration, metrics);

}

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    adjustFontScale( getResources().getConfiguration());
}

Symfony - generate url with parameter in controller

Get the router from the container.

$router = $this->get('router');

Then use the router to generate the Url

$uri = $router->generate('blog_show', array('slug' => 'my-blog-post'));

Subtract days, months, years from a date in JavaScript

You are simply reducing the values from a number. So substracting 6 from 3 (date) will return -3 only.

You need to individually add/remove unit of time in date object

var date = new Date();
date.setDate( date.getDate() - 6 );
date.setFullYear( date.getFullYear() - 1 );
$("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));

bind/unbind service example (android)

Add these methods to your Activity:

private MyService myServiceBinder;
public ServiceConnection myConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder binder) {
        myServiceBinder = ((MyService.MyBinder) binder).getService();
        Log.d("ServiceConnection","connected");
        showServiceData();
    }

    public void onServiceDisconnected(ComponentName className) {
        Log.d("ServiceConnection","disconnected");
        myService = null;
    }
};

public Handler myHandler = new Handler() {
    public void handleMessage(Message message) {
        Bundle data = message.getData();
    }
};

public void doBindService() {
    Intent intent = null;
    intent = new Intent(this, BTService.class);
    // Create a new Messenger for the communication back
    // From the Service to the Activity
    Messenger messenger = new Messenger(myHandler);
    intent.putExtra("MESSENGER", messenger);

    bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}

And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.

@Override
protected void onResume() {

    Log.d("activity", "onResume");
    if (myService == null) {
        doBindService();
    }
    super.onResume();
}

@Override
protected void onPause() {
    //FIXME put back

    Log.d("activity", "onPause");
    if (myService != null) {
        unbindService(myConnection);
        myService = null;
    }
    super.onPause();
}

Note, that when binding to a service only the onCreate() method is called in the service class. In your Service class you need to define the myBinder method:

private final IBinder mBinder = new MyBinder();
private Messenger outMessenger;

@Override
public IBinder onBind(Intent arg0) {
    Bundle extras = arg0.getExtras();
    Log.d("service","onBind");
    // Get messager from the Activity
    if (extras != null) {
        Log.d("service","onBind with extra");
        outMessenger = (Messenger) extras.get("MESSENGER");
    }
    return mBinder;
}

public class MyBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}

After you defined these methods you can reach the methods of your service at your Activity:

private void showServiceData() {  
    myServiceBinder.myMethod();
}

and finally you can start your service when some event occurs like _BOOT_COMPLETED_

public class MyReciever  extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals("android.intent.action.BOOT_COMPLETED")) {
            Intent service = new Intent(context, myService.class);
            context.startService(service);
        }
    }
}

note that when starting a service the onCreate() and onStartCommand() is called in service class and you can stop your service when another event occurs by stopService() note that your event listener should be registerd in your Android manifest file:

<receiver android:name="MyReciever" android:enabled="true" android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
</receiver>

Finding and removing non ascii characters from an Oracle Varchar2

The select may look like the following sample:

select nvalue from table
where length(asciistr(nvalue))!=length(nvalue)  
order by nvalue;

How to convert XML to java.util.Map and vice versa

Now it's 2017, The latest version of XStream requires a converter to make it works as your expected.

A converter supports nested map:

public class MapEntryConverter implements Converter {

    @Override
    public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) {
        AbstractMap map = (AbstractMap) value;
        for (Object obj : map.entrySet()) {
            Map.Entry entry = (Map.Entry) obj;
            writer.startNode(entry.getKey().toString());
            Object val = entry.getValue();
            if (val instanceof Map) {
                marshal(val, writer, marshallingContext);
            } else if (null != val) {
                writer.setValue(val.toString());
            }
            writer.endNode();
        }
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext unmarshallingContext) {
        Map<String, Object> map = new HashMap<>();

        while(reader.hasMoreChildren()) {
            reader.moveDown();

            String key = reader.getNodeName(); // nodeName aka element's name
            String value = reader.getValue().replaceAll("\\n|\\t", "");
            if (StringUtils.isBlank(value)) {
                map.put(key, unmarshal(reader, unmarshallingContext));
            } else {
                map.put(key, value);
            }

            reader.moveUp();
        }

        return map;
    }

    @Override
    public boolean canConvert(Class clazz) {
        return AbstractMap.class.isAssignableFrom(clazz);
    }
} 

Assign width to half available screen width declaratively

give width as 0dp to make sure its size is exactly as per its weight this will make sure that even if content of child views get bigger, they'll still be limited to exactly half(according to is weight)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1"
     >

    <Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="click me"
    android:layout_weight="0.5"/>


    <TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Hello World"
    android:layout_weight="0.5"/>
  </LinearLayout>

Pandas read_csv low_memory and dtype options

As the error says, you should specify the datatypes when using the read_csv() method. So, you should write

file = pd.read_csv('example.csv', dtype='unicode')

How to avoid using Select in Excel VBA

IMHO use of .select comes from people, who like me started learning VBA by necessity through recording macros and then modifying the code without realizing that .select and subsequent selection is just an unnecessary middle-men.

.select can be avoided, as many posted already, by directly working with the already existing objects, which allows various indirect referencing like calculating i and j in a complex way and then editing cell(i,j), etc.

Otherwise, there is nothing implicitly wrong with .select itself and you can find uses for this easily, e.g. I have a spreadsheet that I populate with date, activate macro that does some magic with it and exports it in an acceptable format on a separate sheet, which, however, requires some final manual (unpredictable) inputs into an adjacent cell. So here comes the moment for .select that saves me that additional mouse movement and click.

Maximum on http header values?

As vartec says above, the HTTP spec does not define a limit, however many servers do by default. This means, practically speaking, the lower limit is 8K. For most servers, this limit applies to the sum of the request line and ALL header fields (so keep your cookies short).

It's worth noting that nginx uses the system page size by default, which is 4K on most systems. You can check with this tiny program:

pagesize.c:

#include <unistd.h>
#include <stdio.h>

int main() {
    int pageSize = getpagesize();
    printf("Page size on your system = %i bytes\n", pageSize);
    return 0;
}

Compile with gcc -o pagesize pagesize.c then run ./pagesize. My ubuntu server from Linode dutifully informs me the answer is 4k.

Add table row in jQuery

In a simple way:

$('#yourTableId').append('<tr><td>your data1</td><td>your data2</td><td>your data3</td></tr>');

SSH to Elastic Beanstalk instance

There is a handy 'Connect' option in the 'Instance Actions' menu for the EC2 instance. It will give you the exact SSH command to execute with the correct url for the instance. Jabley's overall instructions are correct.

Chrome:The website uses HSTS. Network errors...this page will probably work later

One very quick way around this is, when you're viewing the "Your connection is not private" screen:

type badidea

type thisisunsafe (credit to The Java Guy for finding the new passphrase)

That will allow the security exception when Chrome is otherwise not allowing the exception to be set via clickthrough, e.g. for this HSTS case.

This is only recommended for local connections and local-network virtual machines, obviously, but it has the advantage of working for VMs being used for development (e.g. on port-forwarded local connections) and not just direct localhost connections.

Note: the Chrome developers have changed this passphrase in the past, and may do so again. If badidea ceases to work, please leave a note here if you learn the new passphrase. I'll try to do the same.

Edit: as of 30 Jan 2018 this passphrase appears to no longer work.

If I can hunt down a new one I'll post it here. In the meantime I'm going to take the time to set up a self-signed certificate using the method outlined in this stackoverflow post:

How to create a self-signed certificate with openssl?

Edit: as of 1 Mar 2018 and Chrome Version 64.0.3282.186 this passphrase works again for HSTS-related blocks on .dev sites.

Edit: as of 9 Mar 2018 and Chrome Version 65.0.3325.146 the badidea passphrase no longer works.

Edit 2: the trouble with self-signed certificates seems to be that, with security standards tightening across the board these days, they cause their own errors to be thrown (nginx, for example, refuses to load an SSL/TLS cert that includes a self-signed cert in the chain of authority, by default).

The solution I'm going with now is to swap out the top-level domain on all my .app and .dev development sites with .test or .localhost. Chrome and Safari will no longer accept insecure connections to standard top-level domains (including .app).

The current list of standard top-level domains can be found in this Wikipedia article, including special-use domains:

Wikipedia: List of Internet Top Level Domains: Special Use Domains

These top-level domains seem to be exempt from the new https-only restrictions:

  • .local
  • .localhost
  • .test
  • (any custom/non-standard top-level domain)

See the answer and link from codinghands to the original question for more information:

answer from codinghands

Find value in an array

I know this question has already been answered, but I came here looking for a way to filter elements in an Array based on some criteria. So here is my solution example: using select, I find all constants in Class that start with "RUBY_"

Class.constants.select {|c| c.to_s =~ /^RUBY_/ }

UPDATE: In the meantime I have discovered that Array#grep works much better. For the above example,

Class.constants.grep /^RUBY_/

did the trick.

How to select between brackets (or quotes or ...) in Vim?

This method of selection is built-in and well covered in the Vim help. It covers XML tags and more.

See :help text-objects.

How do I replace text in a selection?

This frustrated the heck out of me, and none of the above answers really got me what I wanted. I finally found the answer I was looking for, on a mac if you do ? + option + F it will bring up a Find-Replace bar at the bottom of your editor which is local to the file you have open.

There is an icon option which when hovered over says "In Selection" that you can select to find and replace within a selection. I've pointed to the correct icon in the screenshot below.

enter image description here

Hit replace all, and voila, all instances of '0' will be replaced with '255'.

Note: this feature is ONLY available when you use ? + option + F.

It does NOT appear when you use ? + shift + F.

Note: this will replace all instances of '0' with '255'. If you wanted to replace 0 (without the quotes) with 255, then just put 0 (without quotes) and 255 in the Find What: and Replace With: fields respectively.

Note:

option key is also labeled as the alt key.

? key is also labeled as the command key.

Input from the keyboard in command line application

In general readLine() function is used for scanning input from console. But it will not work in normal iOS project until or unless you add "command-line tool".

The best way for testing, you can do :

1. Create an macOS file

enter image description here

2. Use the readLine() func to scan optional String from console

 import Foundation

 print("Please enter some input\n")

 if let response = readLine() {
    print("output :",response)
 } else {
    print("Nothing")
 }

Output :

Please enter some input

Hello, World
output : Hello, World
Program ended with exit code: 0

enter image description here

Iterating over and deleting from Hashtable in Java

So you know the key, value pair that you want to delete in advance? It's just much clearer to do this, then:

 table.delete(key);
 for (K key: table.keySet()) {
    // do whatever you need to do with the rest of the keys
 }

Add MIME mapping in web.config for IIS Express

I was having a problem getting my ASP.NET 5.0/MVC 6 app to serve static binary file types or browse virtual directories. It looks like this is now done in Configure() at startup. See http://docs.asp.net/en/latest/fundamentals/static-files.html for a quick primer.

Javascript (+) sign concatenates instead of giving sum of variables

Simple as easy ... every input type if not defined in HTML is considered as string. Because of this the Plus "+" operator is concatenating.

Use parseInt(i) than the value of "i" will be casted to Integer.

Than the "+" operator will work like addition.

In your case do this :-

divID = "question-" + parseInt(i)+1;

Apply global variable to Vuejs

If the global variable should not be written to by anything, including Vuejs, you can use Object.freeze to freeze your object. Adding it to Vue's viewmodel won't unfreeze it. Another option is to provide Vuejs with a frozen copy of the object, if the object is intended to be written globally but just not by Vue: var frozenCopy = Object.freeze(Object.assign({}, globalObject))

Dependency injection with Jersey 2.0

Dependency required for jersey restful service and Tomcat is the server. where ${jersey.version} is 2.29.1

    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>2.0.SP1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
        <version>${jersey.version}</version>
    </dependency>

The basic code will be as follows:

@RequestScoped
@Path("test")
public class RESTEndpoint {

   @GET
   public String getMessage() {

Function to return only alpha-numeric characters from string?

Warning: Note that English is not restricted to just A-Z.

Try this to remove everything except a-z, A-Z and 0-9:

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);

If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.

Try this to leave only A-Z:

$result = preg_replace("/[^A-Z]+/", "", $s);

The reason for the warning is that words like résumé contains the letter é that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.

Cannot install signed apk to device manually, got error "App not installed"

In Android Studio 3.0 and Above

As described here

Note: The Run button builds an APK with testOnly="true", which means the APK can only be installed via adb (which Android Studio uses). If you want a debuggable APK that people can install without adb, select your debug variant and click Build Bundle(s) / APK(s) > Build APK(s).

Add android:testOnly="false" inside Application tag in AndroidManifest.xml

Reference: https://commonsware.com/blog/2017/10/31/android-studio-3p0-flag-test-only.html

Comparing two NumPy arrays for equality, element-wise

The (A==B).all() solution is very neat, but there are some built-in functions for this task. Namely array_equal, allclose and array_equiv.

(Although, some quick testing with timeit seems to indicate that the (A==B).all() method is the fastest, which is a little peculiar, given it has to allocate a whole new array.)

How do I vertically align text in a div?

Hmm, there're obviously many ways to solve this.

But I have a <div> that's positioned absolutely, height:100% (actually, top:0;bottom:0 and fixed width) and display:table-cell just didn't work to center text vertically. My solution did require an inner span element, but I see many of the other solutions do also, so I might as well add it:

My container is a .label and I want the number vertically centered in it. I did it by positioning absolutely at top:50% and setting line-height:0

<div class="label"><span>1.</span></div>

And the CSS is as follows:

.label {
    position:absolute;
    top:0;
    bottom:0;
    width:30px;
}

.label>span {
    position:absolute;
    top:50%;
    line-height:0;
}

See it in action: http://jsfiddle.net/jcward/7gMLx/

How do you test your Request.QueryString[] variables?

if(!string.IsNullOrEmpty(Request.QueryString["id"]))
{
//querystring contains id
}

How can I print message in Makefile?

$(info your_text) : Information. This doesn't stop the execution.

$(warning your_text) : Warning. This shows the text as a warning.

$(error your_text) : Fatal Error. This will stop the execution.

How can I hide select options with JavaScript? (Cross browser)

Three years late, but my Googling brought me here so hopefully my answer will be useful for someone else.

I just created a second option (which I hid with CSS) and used Javascript to move the s backwards and forwards between them.

<select multiple id="sel1">
  <option class="set1">Blah</option>
</select>
<select multiple id="sel2" style="display:none">
  <option class="set2">Bleh</option>
</select>

Something like that, and then something like this will move an item onto the list (i.e., make it visible). Obviously adapt the code as needed for your purpose.

$('#sel2 .set2').appendTo($('#sel1'))