Programs & Examples On #Ora 01722

ORA-01722: invalid number in Oracle. Cause: The attempted conversion of a character string to a number failed because the character string was not a valid numeric literal. Only numeric fields or character fields containing numeric data may be used in arithmetic functions or expressions. Only numeric fields may be added to or subtracted from dates.

Oracle date to string conversion

If your column is of type DATE (as you say), then you don't need to convert it into a string first (in fact you would convert it implicitly to a string first, then explicitly to a date and again explicitly to a string):

SELECT TO_CHAR(COL1, 'mm/dd/yyyy') FROM TABLE1

The date format your seeing for your column is an artifact of the tool your using (TOAD, SQL Developer etc.) and it's language settings.

SQL error "ORA-01722: invalid number"

This happened to me too, but the problem was actually different: file encoding.

The file was correct, but the file encoding was wrong. It was generated by the export utility of SQL Server and I saved it as Unicode.

The file itself looked good in the text editor, but when I opened the *.bad file that the SQL*loader generated with the rejected lines, I saw it had bad characters between every original character. Then I though about the encoding.

I opened the original file with Notepad++ and converted it to ANSI, and everything loaded properly.

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

I would suggest Travis for Open source project. It's just simple to configure and use.

Simple steps to setup:

  1. Should have GITHUB account and register in Travis CI website using your GITHUB account.
  2. Add .travis.yml file in root of your project. Add Travis as service in your repository settings page.

Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.

Remove Elements from a HashSet while Iterating

Here's the more modern streams approach:

myIntegerSet.stream().filter((it) -> it % 2 != 0).collect(Collectors.toSet())

However, this makes a new set, so memory constraints might be an issue if it's a really huge set.

EDIT: previous version of this answer suggested Apache CollectionUtils but that was before steams came about.

Set the maximum character length of a UITextField

The Problem with some of the answer given above is, For example I have a text field and I have to set a limit of 15 characters input, then it stops after entering 15th Character. but they Don't allow to delete. That is the delete button also don't work. As I was facing the same problem. Came out with the solution , Given Below. Works Perfect for Me

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
 if(textField.tag==6)
 {
    if ([textField.text length]<=30)
    {
        return YES;   
    }
    else if([@"" isEqualToString:string])
    {
        textField.text=[textField.text substringToIndex:30 ];
    }

    return NO;
 }
 else
 {
    return YES;
 }
}

I am having a text field, whose tag I have set "6" and I have restricted the max char limit = 30 ; works fine in every case

Table with fixed header and fixed column on pure css

All of these suggestions are great and all, but they're either only fixing either the header or a column, not both, or they're using javascript. The reason - it don't believe it can be done in pure CSS. The reason:

If it were possible to do it, you would need to nest several scrollable divs one inside the other, each with a scroll in a different direction. Then you would need to split your table into three parts - the fixed header, the fixed column and the rest of the data.

Fine. But now the problem - you can make one of them stay put when you scroll, but the other one is nested inside the scrolling area of first and is therefore subject to being scrolled out of sight itself, so can't be fixed in place on the screen. 'Ah-ha' you say 'but I can somehow use absolute or fixed position to do that' - no you can't. As soon as you do that you lose the ability to scroll that container. It's a chicken and egg situation - you can't have both, they cancel each other out.

I believe the only solution is through javascript. You need to completely seperate out the three elements and keep their positions in sync through javascript. There are good examples in other posts on this page. This one is also worth a look:

http://tympanus.net/codrops/2014/01/09/sticky-table-headers-columns/

How to open spss data files in excel?

You can use online converter, developed by me at N'counter.

This is the easiest way to open SPSS file in Excel.

1) You just have to upload your file to SPSS coN'verter at https://secure.ncounter.de/SpssConverter

2) Select some options

3) And your converted Excel file will be downloaded

No information about your file contents is retained on our server. The file travels to our server, is converted in-memory, and is immediately discarded: We don't peer into your data at any time!

print memory address of Python variable

id is the method you want to use: to convert it to hex:

hex(id(variable_here))

For instance:

x = 4
print hex(id(x))

Gave me:

0x9cf10c

Which is what you want, right?

(Fun fact, binding two variables to the same int may result in the same memory address being used.)
Try:

x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print hex(id(x))
print hex(id(y))
print hex(id(w))
print hex(id(v))
print hex(id(a))
print hex(id(b))

This gave me identical pairs, even for the large integers.

Bootstrap Columns Not Working

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="col-md-4">  
                    <a href="">About</a>
                </div>
                <div class="col-md-4">
                    <img src="image.png">
                </div>
                <div class="col-md-4"> 
                    <a href="#myModal1" data-toggle="modal">SHARE</a>
                </div>
            </div>
        </div>
    </div>
</div>

You need to nest the interior columns inside of a row rather than just another column. It offsets the padding caused by the column with negative margins.

A simpler way would be

<div class="container">
   <div class="row">
       <div class="col-md-4">  
          <a href="">About</a>
       </div>
       <div class="col-md-4">
          <img src="image.png">
       </div>
       <div class="col-md-4"> 
           <a href="#myModal1" data-toggle="modal">SHARE</a>
       </div>
    </div>
</div>

AngularJS - $http.post send data as json

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
  $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

since npm 5.2.0, there's a new command "npx" included with npm that makes this much simpler, if you run:

npx mocha <args>

Note: the optional args are forwarded to the command being executed (mocha in this case)

this will automatically pick the executable "mocha" command from your locally installed mocha (always add it as a dev dependency to ensure the correct one is always used by you and everyone else).

Be careful though that if you didn't install mocha, this command will automatically fetch and use latest version, which is great for some tools (like scaffolders for example), but might not be the most recommendable for certain dependencies where you might want to pin to a specific version.

You can read more on npx here


Now, if instead of invoking mocha directly, you want to define a custom npm script, an alias that might invoke other npm binaries...

you don't want your library tests to fail depending on the machine setup (mocha as global, global mocha version, etc), the way to use the local mocha that works cross-platform is:

node node_modules/.bin/mocha

npm puts aliases to all the binaries in your dependencies on that special folder. Finally, npm will add node_modules/.bin to the PATH automatically when running an npm script, so in your package.json you can do just:

"scripts": {
  "test": "mocha"
}

and invoke it with

npm test

Android widget: How to change the text of a button

I was able to change the button's text like this:

import android.widget.RemoteViews;

//grab the layout, then set the text of the Button called R.id.Counter:
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(R.id.Counter, "Set button text here");

REST API Best practice: How to accept list of parameter values as input

The standard way to pass a list of values as URL parameters is to repeat them:

http://our.api.com/Product?id=101404&id=7267261

Most server code will interpret this as a list of values, although many have single value simplifications so you may have to go looking.

Delimited values are also okay.

If you are needing to send JSON to the server, I don't like seeing it in in the URL (which is a different format). In particular, URLs have a size limitation (in practice if not in theory).

The way I have seen some do a complicated query RESTfully is in two steps:

  1. POST your query requirements, receiving back an ID (essentially creating a search criteria resource)
  2. GET the search, referencing the above ID
  3. optionally DELETE the query requirements if needed, but note that they requirements are available for reuse.

How to use boolean 'and' in Python

As pointed out, "&" in python performs a bitwise and operation, just as it does in C#. and is the appropriate equivalent to the && operator.

Since we're dealing with booleans (i == 5 is True and ii == 10 is also True), you may wonder why this didn't either work anyway (True being treated as an integer quantity should still mean True & True is a True value), or throw an exception (eg. by forbidding bitwise operations on boolean types)

The reason is operator precedence. The "and" operator binds more loosely than ==, so the expression: "i==5 and ii==10" is equivalent to: "(i==5) and (ii==10)"

However, bitwise & has a higher precedence than "==" (since you wouldn't want expressions like "a & 0xff == ch" to mean "a & (0xff == ch)"), so the expression would actually be interpreted as:

if i == (5 & ii) == 10:

Which is using python's operator chaining to mean: does the valuee of ii anded with 5 equal both i and 10. Obviously this will never be true.

You would actually get (seemingly) the right answer if you had included brackets to force the precedence, so:

if (i==5) & (ii=10)

would cause the statement to be printed. It's the wrong thing to do, however - "&" has many different semantics to "and" - (precedence, short-cirtuiting, behaviour with integer arguments etc), so it's fortunate that you caught this here rather than being fooled till it produced less obvious bugs.

Why is Thread.Sleep so harmful

Sleep is used in cases where independent program(s) that you have no control over may sometimes use a commonly used resource (say, a file), that your program needs to access when it runs, and when the resource is in use by these other programs your program is blocked from using it. In this case, where you access the resource in your code, you put your access of the resource in a try-catch (to catch the exception when you can't access the resource), and you put this in a while loop. If the resource is free, the sleep never gets called. But if the resource is blocked, then you sleep for an appropriate amount of time, and attempt to access the resource again (this why you're looping). However, bear in mind that you must put some kind of limiter on the loop, so it's not a potentially infinite loop. You can set your limiting condition to be N number of attempts (this is what I usually use), or check the system clock, add a fixed amount of time to get a time limit, and quit attempting access if you hit the time limit.

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

This technique solved my problem:

In parent form:

frmEmployee frm = new frmEmployee();
frm.MdiParent = this;
frm.Dock = DockStyle.Fill;
frm.Show();

In the child form (Load event):

this.WindowState = FormWindowState.Maximized;

Open a URL in a new tab (and not a new window)

There is an answer to this question and it is not no.

I found an easy work around:

Step 1: Create an invisible link:

<a id="yourId" href="yourlink.html" target="_blank" style="display: none;"></a>

Step 2: Click on that link programmatically:

document.getElementById("yourId").click();

Here you go! Works a charm for me.

How to pass table value parameters to stored procedure from .net code

Further to Ryan's answer you will also need to set the DataColumn's Ordinal property if you are dealing with a table-valued parameter with multiple columns whose ordinals are not in alphabetical order.

As an example, if you have the following table value that is used as a parameter in SQL:

CREATE TYPE NodeFilter AS TABLE (
  ID int not null
  Code nvarchar(10) not null,
);

You would need to order your columns as such in C#:

table.Columns["ID"].SetOrdinal(0);
// this also bumps Code to ordinal of 1
// if you have more than 2 cols then you would need to set more ordinals

If you fail to do this you will get a parse error, failed to convert nvarchar to int.

Python "SyntaxError: Non-ASCII character '\xe2' in file"

I had the same issue and just added this to the top of my file (in Python 3 I didn't have the problem but do in Python 2

#!/usr/local/bin/python
# coding: latin-1

how to get current location in google map android

         import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {

    private GoogleMap mMap;
    private FusedLocationProviderClient client;
    double latit;
    double longi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        client = LocationServices.getFusedLocationProviderClient(this);
    }
@RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;



        try {
            setupMap();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
 client = LocationServices.getFusedLocationProviderClient(this);

        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return;
        }
        client.getLastLocation()
                .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        // Got last known location. In some rare situations this can be null.
                        if (location != null) {

                            //    local=findViewById(R.id.tv5);

                            double la=location.getLatitude();
                            double lo=location.getLongitude();

                            LatLng curre=new LatLng(la,lo);
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curre,18));

                        }
                    }
                });



    }
    }

How to create text file and insert data to that file on Android

If you want to create a file and write and append data to it many times, then use the below code, it will create file if not exits and will append data if it exists.

 SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
        Date now = new Date();
        String fileName = formatter.format(now) + ".txt";//like 2016_01_12.txt


         try
            {
                File root = new File(Environment.getExternalStorageDirectory()+File.separator+"Music_Folder", "Report Files");
                //File root = new File(Environment.getExternalStorageDirectory(), "Notes");
                if (!root.exists()) 
                {
                    root.mkdirs();
                }
                File gpxfile = new File(root, fileName);


                FileWriter writer = new FileWriter(gpxfile,true);
                writer.append(sBody+"\n\n");
                writer.flush();
                writer.close();
                Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
            }
            catch(IOException e)
            {
                 e.printStackTrace();

            }

Twig for loop for arrays with keys

I guess you want to do the "Iterating over Keys and Values"

As the doc here says, just add "|keys" in the variable you want and it will magically happen.

{% for key, user in users %}
    <li>{{ key }}: {{ user.username|e }}</li>
{% endfor %}

It never hurts to search before asking :)

How do I change db schema to dbo

Move table from dbo schema to MySchema:

 ALTER SCHEMA MySchema TRANSFER dbo.MyTable


Move table from MySchema to dbo schema:

 ALTER SCHEMA dbo TRANSFER MySchema.MyTable

'Conda' is not recognized as internal or external command

I have just launched anaconda-navigator and run the conda commands from there.

Javascript dynamic array of strings

Just initialize an array and push the element on the array. It will automatic scale the array.

var a = [ ];

a.push('Some string'); console.log(a); // ['Some string'] 
a.push('another string'); console.log(a); // ['Some string', 'another string'] 
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']

How to get phpmyadmin username and password

Try changing the following lines with new values

$cfg['Servers'][$i]['user'] = 'NEW_USERNAME';
$cfg['Servers'][$i]['password'] = 'NEW_PASSWORD';

Updated due to the absence of the above lines in the config file

Stop the MySQL server

sudo service mysql stop

Start mysqld

sudo mysqld --skip-grant-tables &

Login to MySQL as root

mysql -u root mysql

Change MYSECRET with your new root password

UPDATE user SET Password=PASSWORD('MYSECRET') WHERE User='root'; FLUSH PRIVILEGES; exit;

Kill mysqld

sudo pkill mysqld

Start mysql

sudo service mysql start

Login to phpmyadmin as root with your new password

How to show imageView full screen on imageView click?

That didn't work for me, I used some code parts from web, what I did:

new activity: FullScreenImage with:

package yourpackagename;
import yourpackagename.R;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class FullScreenImage  extends Activity {


@SuppressLint("NewApi")



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.layout_full);

    Bundle extras = getIntent().getExtras();
    Bitmap bmp = (Bitmap) extras.getParcelable("imagebitmap");

    ImageView imgDisplay;
    Button btnClose;


    imgDisplay = (ImageView) findViewById(R.id.imgDisplay);
    btnClose = (Button) findViewById(R.id.btnClose);


   btnClose.setOnClickListener(new View.OnClickListener() {            
    public void onClick(View v) {
    FullScreenImage.this.finish();
}
});


 imgDisplay.setImageBitmap(bmp );

}   


}

Then create a xml: layout_full

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

<ImageView
    android:id="@+id/imgDisplay"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="fitCenter" />

<Button
    android:id="@+id/btnClose"
    android:layout_width="wrap_content"
    android:layout_height="30dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginRight="15dp"
    android:layout_marginTop="15dp"
    android:paddingTop="2dp"
    android:paddingBottom="2dp"
    android:textColor="#ffffff"
    android:text="Close" />

   </RelativeLayout>

And finally, send the image name from your mainactivity

   final ImageView im = (ImageView)findViewById(R.id.imageView1) ; 
   im.setBackgroundDrawable(getResources().getDrawable(id1));

   im.setOnClickListener(new OnClickListener() {

      @Override
       public void onClick(View view) {
       Intent intent = new Intent(NAMEOFYOURCURRENTACTIVITY.this, FullScreenImage.class);

       im.buildDrawingCache();
       Bitmap image= im.getDrawingCache();

       Bundle extras = new Bundle();
       extras.putParcelable("imagebitmap", image);
       intent.putExtras(extras);
       startActivity(intent);

                                }
                            });

Use the auto keyword in C++ STL

If you want a code that is readable by all programmers (c++, java, and others) use the original old form instead of cryptographic new features

atp::ta::DataDrawArrayInfo* ddai;
for(size_t i = 0; i < m_dataDraw->m_dataDrawArrayInfoList.size(); i++) {
    ddai = m_dataDraw->m_dataDrawArrayInfoList[i];
    //...
}

Java String to SHA1

It is not printing correctly because you need to use Base64 encoding. With Java 8 you can encode using Base64 encoder class.

public static String toSHA1(byte[] convertme) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    return Base64.getEncoder().encodeToString(md.digest(convertme));
}

Result

This will give you your expected output of 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8

Why is my element value not getting changed? Am I using the wrong function?

As the plural in getElementsByName() implies, does it always return list of elements that have this name. So when you have an input element with that name:

<input type="text" name="Tue">

And it is the first one with that name, you have to use document.getElementsByName('Tue')[0] to get the first element of the list of elements with this name.

Beside that are properties case sensitive and the correct spelling of the value property is .value.

Save base64 string as PDF at client side with JavaScript

_x000D_
_x000D_
dataURItoBlob(dataURI) {_x000D_
      const byteString = window.atob(dataURI);_x000D_
      const arrayBuffer = new ArrayBuffer(byteString.length);_x000D_
      const int8Array = new Uint8Array(arrayBuffer);_x000D_
      for (let i = 0; i < byteString.length; i++) {_x000D_
        int8Array[i] = byteString.charCodeAt(i);_x000D_
      }_x000D_
      const blob = new Blob([int8Array], { type: 'application/pdf'});_x000D_
      return blob;_x000D_
    }_x000D_
_x000D_
// data should be your response data in base64 format_x000D_
_x000D_
const blob = this.dataURItoBlob(data);_x000D_
const url = URL.createObjectURL(blob);_x000D_
_x000D_
// to open the PDF in a new window_x000D_
window.open(url, '_blank');
_x000D_
_x000D_
_x000D_

How to connect to SQL Server from another computer?

If you want to connect to SQL server remotly you need to use a software - like Sql Server Management studio.

The computers doesn't need to be on the same network - but they must be able to connect each other using a communication protocol like tcp/ip, and the server must be set up to support incoming connection of the type you choose.

if you want to connect to another computer (to browse files ?) you use other tools, and not sql server (you can map a drive and access it through there ect...)

To Enable SQL connection using tcp/ip read this article:

For Sql Express: express For Sql 2008: 2008

Make sure you enable access through the machine firewall as well.

You might need to install either SSMS or Toad on the machine your using to connect to the server. both you can download from their's company web site.

Difference between Spring MVC and Spring Boot

Here is some main point which differentiate Spring, Spring MVC and Spring Boot :

Spring :

  1. Main Difference is "Test-ability".
  2. Spring come with the DI and IOC. Through which all hard-work done by system we don't need to do any kind of work(like, normally we define object of class manually but through Di we just annotate with @Service or @Component - matching class manage those).
  3. Through @Autowired annotation we easily mock() it at unit testing time.
  4. Duplication and Plumbing code. In JDBC we writing same code multiple time to perform any kind of database operation Spring solve that issue through Hibernate and ORM.
  5. Good Integration with other frameworks. Like Hibernate, ORM, Junit & Mockito.

Spring MVC

  1. Spring MVC framework is module of spring which provide facility HTTP oriented web application development.
  2. Spring MVC have clear code separation on input logic(controller), business logic(model), and UI logic(view).
  3. Spring MVC pattern help to develop flexible and loosely coupled web applications.
  4. Provide various hard coded way to customise your application based on your need.

Spring Boot :

  1. Create of Quick Application so that, instead of manage single big web application we divide them individually into different Microservices which have their own scope & capability.
  2. Auto Configuration using Web Jar : In normal Spring there is lot of configuration like DispatcherServlet, Component Scan, View Resolver, Web Jar, XMLs. (For example if I would like to configure datasource, Entity Manager Transaction Manager Factory). Configure automatically when it's not available using class-path.
  3. Comes with Default Spring Starters, which come with some default Spring configuration dependency (like Spring Core, Web-MVC, Jackson, Tomcat, Validation, Data Binding, Logging). Don't worry about versioning issue as well.

(Evolution like : Spring -> Spring MVC -> Spring Boot, So newer version have the compatibility of old version features.) Note : It doesn't contain all point.

jquery change div text

best and simple way is to put title inside a span and replace then.

'<div id="'+div_id+'" class="widget" style="height:60px;width:110px">\n\
        <div class="widget-head ui-widget-header" 
                style="cursor:move;height:20px;width:130px">'+
     '<span id="'+span_id+'" style="float:right; cursor:pointer" 
            class="dialog_link ui-icon ui-icon-newwin ui-icon-pencil"></span>' +
      '<span id="spTitle">'+
      dialog_title+ '</span>'
 '</div></div>

now you can simply use this:

$('#'+div_id+' .widget-head sp#spTitle').text("new dialog title");

Why is "throws Exception" necessary when calling a function?

The throws Exception declaration is an automated way of keeping track of methods that might throw an exception for anticipated but unavoidable reasons. The declaration is typically specific about the type or types of exceptions that may be thrown such as throws IOException or throws IOException, MyException.

We all have or will eventually write code that stops unexpectedly and reports an exception due to something we did not anticipate before running the program, like division by zero or index out of bounds. Since the errors were not expected by the method, they could not be "caught" and handled with a try catch clause. Any unsuspecting users of the method would also not know of this possibility and their programs would also stop.

When the programmer knows certain types of errors may occur but would like to handle these exceptions outside of the method, the method can "throw" one or more types of exceptions to the calling method instead of handling them. If the programmer did not declare that the method (might) throw an exception (or if Java did not have the ability to declare it), the compiler could not know and it would be up to the future user of the method to know about, catch and handle any exceptions the method might throw. Since programs can have many layers of methods written by many different programs, it becomes difficult (impossible) to keep track of which methods might throw exceptions.

Even though Java has the ability to declare exceptions, you can still write a new method with unhandled and undeclared exceptions, and Java will compile it and you can run it and hope for the best. What Java won't let you do is compile your new method if it uses a method that has been declared as throwing exception(s), unless you either handle the declared exception(s) in your method or declare your method as throwing the same exception(s) or if there are multiple exceptions, you can handle some and throw the rest.

When a programmer declares that the method throws a specific type of exception, it is just an automated way of warning other programmers using the method that an exception is possible. The programmer can then decide to handled the exception or pass on the warning by declaring the calling method as also throwing the same exception. Since the compiler has been warned the exception is possible in this new method, it can automatically check if future callers of the new method handle the exception or declare it and enforcing one or the other to happen.

The nice thing about this type of solution is that when the compiler reports Error: Unhandled exception type java.io.IOException it gives the file and line number of the method that was declared to throw the exception. You can then choose to simply pass the buck and declare your method also "throws IOException". This can be done all the way up to main method where it would then cause the program to stop and report the exception to the user. However, it is better to catch the exception and deal with it in a nice way such as explaining to the user what has happened and how to fix it. When a method does catch and handle the exception, it no longer has to declare the exception. The buck stops there so to speak.

ng is not recognized as an internal or external command

I faced same issue when i tried to install angular cli locally with command

npm install @angular/cli@latest

After that i got same issue C:\Users\vi1kumar\Desktop\tus\ANGULAR\AngularForms>ng -v 'ng' is not recognized as an internal or external command, operable program or batch file

Than i tried to install it globally

npm install -g @angular/cli@latest

In this case case it worked i was wondering that is it not possible to install cli globally ?

After doing some research i found this article very helpful hope it will help someone facing similar issue

Working with multiple versions of Angular CLI

Convert Pandas Series to DateTime in a DataFrame

df=pd.read_csv("filename.csv" , parse_dates=["<column name>"])

type(df.<column name>)

example: if you want to convert day which is initially a string to a Timestamp in Pandas

df=pd.read_csv("weather_data2.csv" , parse_dates=["day"])

type(df.day)

The output will be pandas.tslib.Timestamp

How do you validate a URL with a regular expression in Python?

urlparse quite happily takes invalid URLs, it is more a string string-splitting library than any kind of validator. For example:

from urlparse import urlparse
urlparse('http://----')
# returns: ParseResult(scheme='http', netloc='----', path='', params='', query='', fragment='')

Depending on the situation, this might be fine..

If you mostly trust the data, and just want to verify the protocol is HTTP, then urlparse is perfect.

If you want to make the URL is actually a legal URL, use the ridiculous regex

If you want to make sure it's a real web address,

import urllib
try:
    urllib.urlopen(url)
except IOError:
    print "Not a real URL"

Can Json.NET serialize / deserialize to / from a stream?

The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:

public static object DeserializeFromStream(Stream stream)
{
    var serializer = new JsonSerializer();

    using (var sr = new StreamReader(stream))
    using (var jsonTextReader = new JsonTextReader(sr))
    {
        return serializer.Deserialize(jsonTextReader);
    }
}

Documentation: Deserialize JSON from a file stream

Convert character to ASCII code in JavaScript

You can enter a character and get Ascii Code Using this Code

For Example Enter a Character Like A You Get Ascii Code 65

_x000D_
_x000D_
function myFunction(){_x000D_
    var str=document.getElementById("id1");_x000D_
    if (str.value=="") {_x000D_
       str.focus();_x000D_
       return;_x000D_
    }_x000D_
    var a="ASCII Code is == >  ";_x000D_
document.getElementById("demo").innerHTML =a+str.value.charCodeAt(0);_x000D_
}
_x000D_
<p>Check ASCII code</p>_x000D_
_x000D_
<p>_x000D_
  Enter any character:  _x000D_
  <input type="text" id="id1" name="text1" maxLength="1"> </br>_x000D_
</p>_x000D_
_x000D_
<button onclick="myFunction()">Get ASCII code</button>_x000D_
_x000D_
<p id="demo" style="color:red;"></p>
_x000D_
_x000D_
_x000D_

Checking length of dictionary object

This question is confusing. A regular object, {} doesn't have a length property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).

Meaning, you have to get the "length" by a for..in statement on the object, since length is not set, and increment a counter.

I'm confused as to why you need the length. Are you manually setting 0 on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';. If the latter, again, why the need for length?

Edit #1: Why can't you just do this?

list = [ {name:'john'}, {name:'bob'} ];

Then iterate over list? The length is already set.

Conditional Formatting (IF not empty)

Does this work for you:

enter image description here

You find this dialog on the Home ribbon, under the Styles group, the Conditional Formatting menu, New rule....

How can you search Google Programmatically Java API

Indeed there is an API to search google programmatically. The API is called google custom search. For using this API, you will need an Google Developer API key and a cx key. A simple procedure for accessing google search from java program is explained in my blog.

Now dead, here is the Wayback Machine link.

Setup a Git server with msysgit on Windows

I am not sure why anyone hasn't suggested http://gitblit.com. Pure java based solution, allow HTTP protocol and really easy to setup.

How to delete all the rows in a table using Eloquent?

simple solution:

 Mymodel::query()->delete();

How do I get a list of locked users in an Oracle database?

Found it!

SELECT username, 
       account_status
  FROM dba_users;

How to get a cookie from an AJAX response?

Similar to yebmouxing I could not the

 xhr.getResponseHeader('Set-Cookie');

method to work. It would only return null even if I had set HTTPOnly to false on my server.

I too wrote a simple js helper function to grab the cookies from the document. This function is very basic and only works if you know the additional info (lifespan, domain, path, etc. etc.) to add yourself:

function getCookie(cookieName){
  var cookieArray = document.cookie.split(';');
  for(var i=0; i<cookieArray.length; i++){
    var cookie = cookieArray[i];
    while (cookie.charAt(0)==' '){
      cookie = cookie.substring(1);
    }
    cookieHalves = cookie.split('=');
    if(cookieHalves[0]== cookieName){
      return cookieHalves[1];
    }
  }
  return "";
}

Invalid attempt to read when no data is present

I used the code below and it worked for me.

String email="";
    SqlDataReader reader=cmd.ExecuteReader();
    if(reader.Read()){
        email=reader["Email"].ToString();
    }

String To=email;

pip install - locale.Error: unsupported locale setting

Someone may find it useful. You could put those locale settings in .bashrc file, which usually located in the home directory.
Just add this command in .bashrc:
export LC_ALL=C
then type source .bashrc
Now you don't need to call this command manually every time, when you connecting via ssh for example.

How to copy and paste code without rich text formatting?

I use OpenOffice.org and that offers a paste special option, where you can omit the formatting altogether. If you are not bound to MS Word, it's IMO worth a try and it's free :-)

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

I have lots of trouble getting this to work.

Using the following allows you to update it regardless of your user permission.

sudo sysctl -w fs.inotify.max_user_watches=100000

Edit

Just saw this from another user also on another stackexchange site (both work, but this version permanently updates the system setting, rather than temporarily):

echo fs.inotify.max_user_watches=100000 | sudo tee -a /etc/sysctl.conf; 
sudo sysctl -p

Use a JSON array with objects with javascript

This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:

var arrayOfObjects = [{
  "id": 28,
  "Title": "Sweden"
}, {
  "id": 56,
  "Title": "USA"
}, {
  "id": 89,
  "Title": "England"
}];

for (var i = 0; i < arrayOfObjects.length; i++) {
  var object = arrayOfObjects[i];
  for (var property in object) {
    alert('item ' + i + ': ' + property + '=' + object[property]);
  }
  // If property names are known beforehand, you can also just do e.g.
  // alert(object.id + ',' + object.Title);
}

If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.

var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...

To learn more about JSON, check MDN web docs: Working with JSON .

How can I get the height and width of an uiimage?

let imageView: UIImageView = //this is your existing imageView

let imageViewHeight: CGFloat = imageView.frame.height

let imageViewWidth: CGFloat = imageView.frame.width

Property 'catch' does not exist on type 'Observable<any>'

With RxJS 5.5+, the catch operator is now deprecated. You should now use the catchError operator in conjunction with pipe.

RxJS v5.5.2 is the default dependency version for Angular 5.

For each RxJS Operator you import, including catchError you should now import from 'rxjs/operators' and use the pipe operator.

Example of catching error for an Http request Observable

import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
...

export class ExampleClass {
  constructor(private http: HttpClient) {
    this.http.request(method, url, options).pipe(
      catchError((err: HttpErrorResponse) => {
        ...
      }
    )
  }
  ...
}

Notice here that catch is replaced with catchError and the pipe operator is used to compose the operators in similar manner to what you're used to with dot-chaining.


See the rxjs documentation on pipable (previously known as lettable) operators for more info.

Insert NULL value into INT column

2 ways to do it

insert tbl (other, col1, intcol) values ('abc', 123, NULL)

or just omit it from the column list

insert tbl (other, col1) values ('abc', 123)

MySQL - Replace Character in Columns

Just running the SELECT statement will have no effect on the data. You have to use an UPDATE statement with the REPLACE to make the change occur:

UPDATE photos
   SET caption = REPLACE(caption,'"','\'')

Here is a working sample: http://sqlize.com/7FjtEyeLAh

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

Change $db['default']['dbdriver'] = 'mysql' to $db['default']['dbdriver'] = 'mysqli'

In Python, what does dict.pop(a,b) mean?

>>> def func(a, *args, **kwargs):
...   print 'a %s, args %s, kwargs %s' % (a, args, kwargs)
... 
>>> func('one', 'two', 'three', four='four', five='five')
a one, args ('two', 'three'), kwargs {'four': 'four', 'five': 'five'}

>>> def anotherfunct(beta, *args):
...   print 'beta %s, args %s' % (beta, args)
... 
>>> def func(a, *args, **kwargs):
...   anotherfunct(a, *args)
... 
>>> func('one', 'two', 'three', four='four', five='five')
beta one, args ('two', 'three')
>>> 

change PATH permanently on Ubuntu

Add the following line in your .profile file in your home directory (using vi ~/.profile):

PATH=$PATH:/home/me/play
export PATH

Then, for the change to take effect, simply type in your terminal:

$ . ~/.profile

Trying to retrieve first 5 characters from string in bash error?

Depending on your shell, you may be able to use the following syntax:

expr substr $string $position $length

So for your example:

TESTSTRINGONE="MOTEST"
echo `expr substr ${TESTSTRINGONE} 0 5`

Alternatively,

echo 'MOTEST' | cut -c1-5

or

echo 'MOTEST' | awk '{print substr($0,0,5)}'

How to make a cross-module variable?

I could achieve cross-module modifiable (or mutable) variables by using a dictionary:

# in myapp.__init__
Timeouts = {} # cross-modules global mutable variables for testing purpose
Timeouts['WAIT_APP_UP_IN_SECONDS'] = 60

# in myapp.mod1
from myapp import Timeouts

def wait_app_up(project_name, port):
    # wait for app until Timeouts['WAIT_APP_UP_IN_SECONDS']
    # ...

# in myapp.test.test_mod1
from myapp import Timeouts

def test_wait_app_up_fail(self):
    timeout_bak = Timeouts['WAIT_APP_UP_IN_SECONDS']
    Timeouts['WAIT_APP_UP_IN_SECONDS'] = 3
    with self.assertRaises(hlp.TimeoutException) as cm:
        wait_app_up(PROJECT_NAME, PROJECT_PORT)
    self.assertEqual("Timeout while waiting for App to start", str(cm.exception))
    Timeouts['WAIT_JENKINS_UP_TIMEOUT_IN_SECONDS'] = timeout_bak

When launching test_wait_app_up_fail, the actual timeout duration is 3 seconds.

How to use cURL in Java?

Some people have already mentioned HttpURLConnection, URL and URLConnection. If you need all the control and extra features that the curl library provides you (and more), I'd recommend Apache's httpclient.

Image re-size to 50% of original size in HTML

You did not do anything wrong here, it will any other thing that is overriding the image size.

You can check this working fiddle.

And in this fiddle I have alter the image size using %, and it is working.

Also try using this code:

<img src="image.jpg" style="width: 50%; height: 50%"/>?

Here is the example fiddle.

Multipart File upload Spring Boot

   @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("5120MB");
        factory.setMaxRequestSize("5120MB");
        return factory.createMultipartConfig();
    }

put it in class where you are defining beans

Declaring variable workbook / Worksheet vba

Use Sheets rather than Sheet and activate them sequentially:

Sub kl()
    Dim wb As Workbook
    Dim ws As Worksheet
    Set wb = ActiveWorkbook
    Set ws = Sheets("Sheet1")
    wb.Activate
    ws.Select
End Sub

Default property value in React component using TypeScript

For those having optional props that need default values. Credit here :)

interface Props {
  firstName: string;
  lastName?: string;
}

interface DefaultProps {
  lastName: string;
}

type PropsWithDefaults = Props & DefaultProps;

export class User extends React.Component<Props> {
  public static defaultProps: DefaultProps = {
    lastName: 'None',
  }

  public render () {
    const { firstName, lastName } = this.props as PropsWithDefaults;

    return (
      <div>{firstName} {lastName}</div>
    )
  }
}

Real differences between "java -server" and "java -client"?

From Goetz - Java Concurrency in Practice:

  1. Debugging tip: For server applications, be sure to always specify the -server JVM command line switch when invoking the JVM, even for development and testing. The server JVM performs more optimization than the client JVM, such as hoisting variables out of a loop that are not modified in the loop; code that might appear to work in the development environment (client JVM) can break in the deployment environment (server JVM). For example, had we “forgotten” to declare the variable asleep as volatile in Listing 3.4, the server JVM could hoist the test out of the loop (turning it into an infinite loop), but the client JVM would not. An infinite loop that shows up in development is far less costly than one that only shows up in production.

Listing 3.4. Counting sheep.

volatile boolean asleep; ... while (!asleep) countSomeSheep();

My emphasis. YMMV

How to convert an array to object in PHP?

Best Method in the WORLD :)

function arrayToObject($conArray)
{
    if(is_array($conArray)){
        /*
        * Return array converted to object
        * Using __FUNCTION__ (Magic constant)
        * for recursive call
        */
        return (object) array_map(__FUNCTION__, $conArray);
    }else{
        // Return object
        return $conArray;
    }
}

if you use different methods you will have problems. This is the best method. You have ever seen.

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

Try the command

sudo mysql_secure_installation

press enter and assign a new password for root in mysql/mariadb.

If you get an error like

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

enable the service with

service mysql start

now if you re-enter with

mysql -u root -p

if you follow the problem enter with sudo su and mysql -u root -p now apply permissions to root

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '<password>';

this fixed my problem in MariaDB.

Good luck

How to set a variable to be "Today's" date in Python/Pandas

If you want a string mm/dd/yyyy instead of the datetime object, you can use strftime (string format time):

>>> dt.datetime.today().strftime("%m/%d/%Y")
                   # ^ note parentheses
'02/12/2014'

Vue equivalent of setTimeout?

If you want to use the this keyword in your function, you need to write the setTimeout function in ES6

setTimeout(() => {
   this.filters.max_budget_gt_eq = this.budgetHigherValue;
}, 1000);

com.jcraft.jsch.JSchException: UnknownHostKey

You can also simply do

session.setConfig("StrictHostKeyChecking", "no");

It's not secure and it's a workaround not suitable for live environment as it will disable globally known host keys checking.

Print all properties of a Python Class

try ppretty:

from ppretty import ppretty


class Animal(object):
    def __init__(self):
        self.legs = 2
        self.name = 'Dog'
        self.color= 'Spotted'
        self.smell= 'Alot'
        self.age  = 10
        self.kids = 0


print ppretty(Animal(), seq_length=10)

Output:

__main__.Animal(age = 10, color = 'Spotted', kids = 0, legs = 2, name = 'Dog', smell = 'Alot')

How to adjust an UIButton's imageSize?

When changing icon size with UIEdgeInsetsMake(top, left, bottom, right), keep in mind button dimensions and the ability of UIEdgeInsetsMake to work with negative values as if they are positive.

Example: Two buttons with height 100 and aspect 1:1.

left.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
right.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)

enter image description here

left.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
right.imageEdgeInsets = UIEdgeInsetsMake(45, 0, 45, 0)

enter image description here

left.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
right.imageEdgeInsets = UIEdgeInsetsMake(60, 0, 60, 0)

enter image description here

Examples 1 and 3 are identical since ABS(100 - (40 + 40)) = ABS(100 - (60 + 60))

How to find patterns across multiple lines using grep?

Sadly, you can't. From the grep docs:

grep searches the named input FILEs (or standard input if no files are named, or if a single hyphen-minus (-) is given as file name) for lines containing a match to the given PATTERN.

Shadow Effect for a Text in Android?

Perhaps you'd consider using android:shadowColor, android:shadowDx, android:shadowDy, android:shadowRadius; alternatively setShadowLayer() ?

How to clear or stop timeInterval in angularjs?

You can store the promise returned by the interval and use $interval.cancel() to that promise, which cancels the interval of that promise. To delegate the starting and stopping of the interval, you can create start() and stop() functions whenever you want to stop and start them again from a specific event. I have created a snippet below showing the basics of starting and stopping an interval, by implementing it in view through the use of events (e.g. ng-click) and in the controller.

_x000D_
_x000D_
angular.module('app', [])_x000D_
_x000D_
  .controller('ItemController', function($scope, $interval) {_x000D_
  _x000D_
    // store the interval promise in this variable_x000D_
    var promise;_x000D_
  _x000D_
    // simulated items array_x000D_
    $scope.items = [];_x000D_
    _x000D_
    // starts the interval_x000D_
    $scope.start = function() {_x000D_
      // stops any running interval to avoid two intervals running at the same time_x000D_
      $scope.stop(); _x000D_
      _x000D_
      // store the interval promise_x000D_
      promise = $interval(setRandomizedCollection, 1000);_x000D_
    };_x000D_
  _x000D_
    // stops the interval_x000D_
    $scope.stop = function() {_x000D_
      $interval.cancel(promise);_x000D_
    };_x000D_
  _x000D_
    // starting the interval by default_x000D_
    $scope.start();_x000D_
 _x000D_
    // stops the interval when the scope is destroyed,_x000D_
    // this usually happens when a route is changed and _x000D_
    // the ItemsController $scope gets destroyed. The_x000D_
    // destruction of the ItemsController scope does not_x000D_
    // guarantee the stopping of any intervals, you must_x000D_
    // be responsible for stopping it when the scope is_x000D_
    // is destroyed._x000D_
    $scope.$on('$destroy', function() {_x000D_
      $scope.stop();_x000D_
    });_x000D_
            _x000D_
    function setRandomizedCollection() {_x000D_
      // items to randomize 1 - 11_x000D_
      var randomItems = parseInt(Math.random() * 10 + 1); _x000D_
        _x000D_
      // empties the items array_x000D_
      $scope.items.length = 0; _x000D_
      _x000D_
      // loop through random N times_x000D_
      while(randomItems--) {_x000D_
        _x000D_
        // push random number from 1 - 10000 to $scope.items_x000D_
        $scope.items.push(parseInt(Math.random() * 10000 + 1)); _x000D_
      }_x000D_
    }_x000D_
  _x000D_
  });
_x000D_
<div ng-app="app" ng-controller="ItemController">_x000D_
  _x000D_
  <!-- Event trigger to start the interval -->_x000D_
  <button type="button" ng-click="start()">Start Interval</button>_x000D_
  _x000D_
  <!-- Event trigger to stop the interval -->_x000D_
  <button type="button" ng-click="stop()">Stop Interval</button>_x000D_
  _x000D_
  <!-- display all the random items -->_x000D_
  <ul>_x000D_
    <li ng-repeat="item in items track by $index" ng-bind="item"></li>_x000D_
  </ul>_x000D_
  <!-- end of display -->_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
_x000D_
_x000D_
_x000D_

cmake - find_library - custom library location

I've encountered a similar scenario. I solved it by adding in this following code just before find_library():

set(CMAKE_PREFIX_PATH /the/custom/path/to/your/lib/)

then it can find the library location.

Using LIKE in an Oracle IN clause

No, you cannot do this. The values in the IN clause must be exact matches. You could modify the select thusly:

SELECT *
  FROM tbl
 WHERE my_col LIKE %val1%
    OR my_col LIKE %val2%
    OR my_col LIKE %val3%
 ...

If the val1, val2, val3... are similar enough, you might be able to use regular expressions in the REGEXP_LIKE operator.

How to display Woocommerce product price by ID number on a custom page?

Other answers work, but

To get the full/default price:

$product->get_price_html();

Filter element based on .data() key/value

Sounds like more work than its worth.

1) Why not just have a single JavaScript variable that stores a reference to the currently selected element\jQuery object.

2) Why not add a class to the currently selected element. Then you could query the DOM for the ".active" class or something.

How to specify "does not contain" in dplyr filter

Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)

What port is a given program using?

TCPView can do what you asked for.

asp.net: How can I remove an item from a dropdownlist?

myDropDown.Items.Remove(myDropDown.Items.FindByText("Chicago"));

Reverse ip, find domain names on ip address

You can use nslookup on the IP. Reverse DNS is defined with the .in-addr.arpa domain.

Example:

nslookup somedomain.com

yields 123.21.2.3, and then you do:

nslookup 123.21.2.3

this will ask 3.2.21.123.in-addr.arpa and yield the domain name (if there is one defined for reverse DNS).

Reading a text file and splitting it into single words in python

As supplementary, if you are reading a vvvvery large file, and you don't want read all of the content into memory at once, you might consider using a buffer, then return each word by yield:

def read_words(inputfile):
    with open(inputfile, 'r') as f:
        while True:
            buf = f.read(10240)
            if not buf:
                break

            # make sure we end on a space (word boundary)
            while not str.isspace(buf[-1]):
                ch = f.read(1)
                if not ch:
                    break
                buf += ch

            words = buf.split()
            for word in words:
                yield word
        yield '' #handle the scene that the file is empty

if __name__ == "__main__":
    for word in read_words('./very_large_file.txt'):
        process(word)

How should I import data from CSV into a Postgres table using pgAdmin 3?

pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.

enter image description here

enter image description here

Is there a way to run Bash scripts on Windows?

Best option? Windows 10. Native Bash support!

chai test array equality doesn't work as expected

For expect, .equal will compare objects rather than their data, and in your case it is two different arrays.

Use .eql in order to deeply compare values. Check out this link.
Or you could use .deep.equal in order to simulate same as .eql.
Or in your case you might want to check .members.

For asserts you can use .deepEqual, link.

How to append text to a text file in C++?

I use this code. It makes sure that file gets created if it doesn't exist and also adds bit of error checks.

static void appendLineToFile(string filepath, string line)
{
    std::ofstream file;
    //can't enable exception now because of gcc bug that raises ios_base::failure with useless message
    //file.exceptions(file.exceptions() | std::ios::failbit);
    file.open(filepath, std::ios::out | std::ios::app);
    if (file.fail())
        throw std::ios_base::failure(std::strerror(errno));

    //make sure write fails with exception if something is wrong
    file.exceptions(file.exceptions() | std::ios::failbit | std::ifstream::badbit);

    file << line << std::endl;
}

Connect to mysql on Amazon EC2 from a remote server

For some configurations of ubuntu, the bind-address needs be changed in this file:

/etc/mysql/mysql.conf.d/mysqld.cnf 

semaphore implementation

Please check this out below sample code for semaphore implementation(Lock and unlock).

    #include<stdio.h>
    #include<stdlib.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include<string.h>
    #include<malloc.h>
    #include <sys/sem.h>
    int main()
    {
            int key,share_id,num;
            char *data;
            int semid;
            struct sembuf sb={0,-1,0};
            key=ftok(".",'a');
            if(key == -1 ) {
                    printf("\n\n Initialization Falied of shared memory \n\n");
                    return 1;
            }
            share_id=shmget(key,1024,IPC_CREAT|0744);
            if(share_id == -1 ) {
                    printf("\n\n Error captured while share memory allocation\n\n");
                    return 1;
            }
            data=(char *)shmat(share_id,(void *)0,0);
            strcpy(data,"Testing string\n");
            if(!fork()) { //Child Porcess
                 sb.sem_op=-1; //Lock
                 semop(share_id,(struct sembuf *)&sb,1);

                 strncat(data,"feeding form child\n",20);

                 sb.sem_op=1;//Unlock
                 semop(share_id,(struct sembuf *)&sb,1);
                 _Exit(0);
            } else {     //Parent Process
              sb.sem_op=-1; //Lock
              semop(share_id,(struct sembuf *)&sb,1);

               strncat(data,"feeding form parent\n",20);

              sb.sem_op=1;//Unlock
              semop(share_id,(struct sembuf *)&sb,1);

            }
            return 0;
    }

Share data between AngularJS controllers

Just do it simple (tested with v1.3.15):

<article ng-controller="ctrl1 as c1">
    <label>Change name here:</label>
    <input ng-model="c1.sData.name" />
    <h1>Control 1: {{c1.sData.name}}, {{c1.sData.age}}</h1>
</article>
<article ng-controller="ctrl2 as c2">
    <label>Change age here:</label>
    <input ng-model="c2.sData.age" />
    <h1>Control 2: {{c2.sData.name}}, {{c2.sData.age}}</h1>
</article>

<script>
    var app = angular.module("MyApp", []);

    var dummy = {name: "Joe", age: 25};

    app.controller("ctrl1", function () {
        this.sData = dummy;
    });

    app.controller("ctrl2", function () {
        this.sData = dummy;
    });
</script>

Getting parts of a URL (Regex)

I know you're claiming language-agnostic on this, but can you tell us what you're using just so we know what regex capabilities you have?

If you have the capabilities for non-capturing matches, you can modify hometoast's expression so that subexpressions that you aren't interested in capturing are set up like this:

(?:SOMESTUFF)

You'd still have to copy and paste (and slightly modify) the Regex into multiple places, but this makes sense--you're not just checking to see if the subexpression exists, but rather if it exists as part of a URL. Using the non-capturing modifier for subexpressions can give you what you need and nothing more, which, if I'm reading you correctly, is what you want.

Just as a small, small note, hometoast's expression doesn't need to put brackets around the 's' for 'https', since he only has one character in there. Quantifiers quantify the one character (or character class or subexpression) directly preceding them. So:

https?

would match 'http' or 'https' just fine.

How can I change the font-size of a select option?

Add a CSS class to the <option> tag to style it: http://jsfiddle.net/Ahreu/

Currently WebKit browsers don't support this behavior, as it's undefined by the spec. Take a look at this: How to style a select tag's option element?

Iterating over Typescript Map

This worked for me. TypeScript Version: 2.8.3

for (const [key, value] of Object.entries(myMap)) { 
    console.log(key, value);
}

Effects of the extern keyword on C functions

IOW, extern is redundant, and does nothing.

That is why, 10 years later:

See commit ad6dad0, commit b199d71, commit 5545442 (29 Apr 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 4aeeef3, 13 May 2019)

*.[ch]: remove extern from function declarations using spatch

There has been a push to remove extern from function declarations.

Remove some instances of "extern" for function declarations which are caught by Coccinelle.
Note that Coccinelle has some difficulty with processing functions with __attribute__ or varargs so some extern declarations are left behind to be dealt with in a future patch.

This was the Coccinelle patch used:

  @@
    type T;
    identifier f;
    @@
    - extern
    T f(...);

and it was run with:

  $ git ls-files \*.{c,h} |
    grep -v ^compat/ |
    xargs spatch --sp-file contrib/coccinelle/noextern.cocci --in-place

This is not always straightforward though:

See commit 7027f50 (04 Sep 2019) by Denton Liu (Denton-L).
(Merged by Denton Liu -- Denton-L -- in commit 7027f50, 05 Sep 2019)

compat/*.[ch]: remove extern from function declarations using spatch

In 5545442 (*.[ch]: remove extern from function declarations using spatch, 2019-04-29, Git v2.22.0-rc0), we removed externs from function declarations using spatch but we intentionally excluded files under compat/ since some are directly copied from an upstream and we should avoid churning them so that manually merging future updates will be simpler.

In the last commit, we determined the files which taken from an upstream so we can exclude them and run spatch on the remainder.

This was the Coccinelle patch used:

@@
type T;
identifier f;
@@
- extern
  T f(...);

and it was run with:

$ git ls-files compat/\*\*.{c,h} |
    xargs spatch --sp-file contrib/coccinelle/noextern.cocci --in-place
$ git checkout -- \
    compat/regex/ \
    compat/inet_ntop.c \
    compat/inet_pton.c \
    compat/nedmalloc/ \
    compat/obstack.{c,h} \
    compat/poll/

Coccinelle has some trouble dealing with __attribute__ and varargs so we ran the following to ensure that no remaining changes were left behind:

$ git ls-files compat/\*\*.{c,h} |
    xargs sed -i'' -e 's/^\(\s*\)extern \([^(]*([^*]\)/\1\2/'
$ git checkout -- \
    compat/regex/ \
    compat/inet_ntop.c \
    compat/inet_pton.c \
    compat/nedmalloc/ \
    compat/obstack.{c,h} \
    compat/poll/

Note that with Git 2.24 (Q4 2019), any spurious extern is dropped.

See commit 65904b8 (30 Sep 2019) by Emily Shaffer (nasamuffin).
Helped-by: Jeff King (peff).
See commit 8464f94 (21 Sep 2019) by Denton Liu (Denton-L).
Helped-by: Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 59b19bc, 07 Oct 2019)

promisor-remote.h: drop extern from function declaration

During the creation of this file, each time a new function declaration was introduced, it included an extern.
However, starting from 5545442 (*.[ch]: remove extern from function declarations using spatch, 2019-04-29, Git v2.22.0-rc0), we've been actively trying to prevent externs from being used in function declarations because they're unnecessary.

Remove these spurious externs.

Stop a youtube video with jquery?

My solution to this that works for the modern YouTube embed format is as follows.

Assuming the iframe your video is playing in has id="#video", this simple bit of Javascript will do the job.

$(document).ready(function(){
  var stopVideo = function(player) {
    var vidSrc = player.prop('src');
    player.prop('src', ''); // to force it to pause
    player.prop('src', vidSrc);
  };

  // at some appropriate time later in your code
  stopVideo($('#video'));

});

I've seen proposed solutions to this issue involving use of the YouTube API, but if your site is not an https site, or your video is embedded using the modern format recommended by YouTube, or if you have the no-cookies option set, then those solutions don't work and you get the "TV set to a dead channel" effect instead of your video.

I've tested the above on every browser I could lay my hands on and it works very reliably.

C#: Dynamic runtime cast

The opensource framework Dynamitey has a static method that does late binding using DLR including cast conversion among others.

dynamic Cast(object obj, Type castTo){
    return Dynamic.InvokeConvert(obj, castTo, explict:true);
}

The advantage of this over a Cast<T> called using reflection, is that this will also work for any IDynamicMetaObjectProvider that has dynamic conversion operators, ie. TryConvert on DynamicObject.

How to for each the hashmap?

Map.values():

HashMap<String, HashMap<SomeInnerKeyType, String>> selects =
    new HashMap<String, HashMap<SomeInnerKeyType, String>>();

...

for(HashMap<SomeInnerKeyType, String> h : selects.values())
{
   ComboBox cb = new ComboBox();
   for(String s : h.values())
   {
      cb.items.add(s);
   }
}

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

how to get the child node in div using javascript

var tds = document.getElementById("ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a").getElementsByTagName("td");
time = tds[0].firstChild.value;
address = tds[3].firstChild.value;

Creating a SearchView that looks like the material design guidelines

It is actually quite easy to do this, if you are using android.support.v7 library.

Step - 1

Declare a menu item

<item android:id="@+id/action_search"
    android:title="Search"
    android:icon="@drawable/abc_ic_search_api_mtrl_alpha"
    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView" />

Step - 2

Extend AppCompatActivity and in the onCreateOptionsMenu setup the SearchView.

import android.support.v7.widget.SearchView;

...

public class YourActivity extends AppCompatActivity {

    ...

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        // Retrieve the SearchView and plug it into SearchManager
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
        SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        return true;
    }

    ... 

}

Result

enter image description here

enter image description here

Find element's index in pandas Series

I'm impressed with all the answers here. This is not a new answer, just an attempt to summarize the timings of all these methods. I considered the case of a series with 25 elements and assumed the general case where the index could contain any values and you want the index value corresponding to the search value which is towards the end of the series.

Here are the speed tests on a 2013 MacBook Pro in Python 3.7 with Pandas version 0.25.3.

In [1]: import pandas as pd                                                

In [2]: import numpy as np                                                 

In [3]: data = [406400, 203200, 101600,  76100,  50800,  25400,  19050,  12700, 
   ...:          9500,   6700,   4750,   3350,   2360,   1700,   1180,    850, 
   ...:           600,    425,    300,    212,    150,    106,     75,     53, 
   ...:            38]                                                                               

In [4]: myseries = pd.Series(data, index=range(1,26))                                                

In [5]: myseries[21]                                                                                 
Out[5]: 150

In [7]: %timeit myseries[myseries == 150].index[0]                                                   
416 µs ± 5.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [8]: %timeit myseries[myseries == 150].first_valid_index()                                        
585 µs ± 32.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [9]: %timeit myseries.where(myseries == 150).first_valid_index()                                  
652 µs ± 23.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [10]: %timeit myseries.index[np.where(myseries == 150)[0][0]]                                     
195 µs ± 1.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [11]: %timeit pd.Series(myseries.index, index=myseries)[150]                 
178 µs ± 9.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [12]: %timeit myseries.index[pd.Index(myseries).get_loc(150)]                                    
77.4 µs ± 1.41 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [13]: %timeit myseries.index[list(myseries).index(150)]
12.7 µs ± 42.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [14]: %timeit myseries.index[myseries.tolist().index(150)]                   
9.46 µs ± 19.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

@Jeff's answer seems to be the fastest - although it doesn't handle duplicates.

Correction: Sorry, I missed one, @Alex Spangher's solution using the list index method is by far the fastest.

Update: Added @EliadL's answer.

Hope this helps.

Amazing that such a simple operation requires such convoluted solutions and many are so slow. Over half a millisecond in some cases to find a value in a series of 25.

How to Parse JSON Array with Gson

Some of the answers of this post are valid, but using TypeToken, the Gson library generates a Tree objects whit unreal types for your application.

To get it I had to read the array and convert one by one the objects inside the array. Of course this method is not the fastest and I don't recommend to use it if you have the array is too big, but it worked for me.

It is necessary to include the Json library in the project. If you are developing on Android, it is included:

/**
 * Convert JSON string to a list of objects
 * @param sJson String sJson to be converted
 * @param tClass Class
 * @return List<T> list of objects generated or null if there was an error
 */
public static <T> List<T> convertFromJsonArray(String sJson, Class<T> tClass){

    try{
        Gson gson = new Gson();
        List<T> listObjects = new ArrayList<>();

        //read each object of array with Json library
        JSONArray jsonArray = new JSONArray(sJson);
        for(int i=0; i<jsonArray.length(); i++){

            //get the object
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            //get string of object from Json library to convert it to real object with Gson library
            listObjects.add(gson.fromJson(jsonObject.toString(), tClass));
        }

        //return list with all generated objects
        return listObjects;

    }catch(Exception e){
        e.printStackTrace();
    }

    //error: return null
    return null;
}

Convert True/False value read from file to boolean

The cleanest solution that I've seen is:

from distutils.util import strtobool
def string_to_bool(string):
    return bool(strtobool(str(string)))

Sure, it requires an import, but it has proper error handling and requires very little code to be written (and tested).

Submit form using a button outside the <form> tag

<form method="get" id="form1" action="something.php">

</form>

<!-- External button-->
<button type="submit" form="form1">Click me!</button>

This worked for me, to have a remote submit button for a form.

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

This is an annoying problem, that can take some time to find out the root case. The way you should proceed is @CommonsWare answer.

I faced this problem recently and found it hard to resolve.

My problem was i was including a library by "+" version in build.gradle. Latest version of library contained one of older dex and bang.

I reverted to older version of library and solved it.

It is good to run your androidDependencies and see what is really happening. Its also good to search in your build folder.

Above all Android Studio 2.2 provide in build features to track this problem.

Happy Coding Guys

How do I translate an ISO 8601 datetime string into a Python datetime object?

You should keep an eye on the timezone information, as you might get into trouble when comparing non-tz-aware datetimes with tz-aware ones.

It's probably the best to always make them tz-aware (even if only as UTC), unless you really know why it wouldn't be of any use to do so.

#-----------------------------------------------
import datetime
import pytz
import dateutil.parser
#-----------------------------------------------

utc = pytz.utc
BERLIN = pytz.timezone('Europe/Berlin')
#-----------------------------------------------

def to_iso8601(when=None, tz=BERLIN):
  if not when:
    when = datetime.datetime.now(tz)
  if not when.tzinfo:
    when = tz.localize(when)
  _when = when.strftime("%Y-%m-%dT%H:%M:%S.%f%z")
  return _when[:-8] + _when[-5:] # Remove microseconds
#-----------------------------------------------

def from_iso8601(when=None, tz=BERLIN):
  _when = dateutil.parser.parse(when)
  if not _when.tzinfo:
    _when = tz.localize(_when)
  return _when
#-----------------------------------------------

How do you compare structs for equality in C?

It depends on whether the question you are asking is:

  1. Are these two structs the same object?
  2. Do they have the same value?

To find out if they are the same object, compare pointers to the two structs for equality. If you want to find out in general if they have the same value you have to do a deep comparison. This involves comparing all the members. If the members are pointers to other structs you need to recurse into those structs too.

In the special case where the structs do not contain pointers you can do a memcmp to perform a bitwise comparison of the data contained in each without having to know what the data means.

Make sure you know what 'equals' means for each member - it is obvious for ints but more subtle when it comes to floating-point values or user-defined types.

How to unlock a file from someone else in Team Foundation Server

Team Foundation Sidekicks has a Status sidekick that allows you to query for checked out work items. Once a work item is selected, click the "Undo lock" buttons on the toolbar.

Rights

Keep in mind that you will need the appropriate rights. The permissions are called "Undo other users' changes" and "Unlock other users' changes". These permissions can be viewed by:

  1. Right-clicking the desired project, folder, or file in Source Control Explorer
  2. Select Properties
  3. Select the Security tab
  4. Select the appropriate user or group in the Users and Groups section at the top
  5. View the "Permissions for [user/group]:" section at the bottom

Screenshot of unlocking a file using Team Foundation Sidekicks

Disclaimer: this answer is an edited repost of Brett Roger's answer to a similar question.

How to make a ssh connection with python?

Twisted has SSH support : http://www.devshed.com/c/a/Python/SSH-with-Twisted/

The twisted.conch package adds SSH support to Twisted. This chapter shows how you can use the modules in twisted.conch to build SSH servers and clients.

Setting Up a Custom SSH Server

The command line is an incredibly efficient interface for certain tasks. System administrators love the ability to manage applications by typing commands without having to click through a graphical user interface. An SSH shell is even better, as it’s accessible from anywhere on the Internet.

You can use twisted.conch to create an SSH server that provides access to a custom shell with commands you define. This shell will even support some extra features like command history, so that you can scroll through the commands you’ve already typed.

How Do I Do That? Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver , but with higher-level features for controlling the terminal.

Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver, but with higher-level features for controlling the terminal.

To make your shell available through SSH, you need to implement a few different classes that twisted.conch needs to build an SSH server. First, you need the twisted.cred authentication classes: a portal, credentials checkers, and a realm that returns avatars. Use twisted.conch.avatar.ConchUser as the base class for your avatar. Your avatar class should also implement twisted.conch.interfaces.ISession , which includes an openShell method in which you create a Protocol to manage the user’s interactive session. Finally, create a twisted.conch.ssh.factory.SSHFactory object and set its portal attribute to an instance of your portal.

Example 10-1 demonstrates a custom SSH server that authenticates users by their username and password. It gives each user a shell that provides several commands.

Example 10-1. sshserver.py

from twisted.cred import portal, checkers, credentials
from twisted.conch import error, avatar, recvline, interfaces as conchinterfaces
from twisted.conch.ssh import factory, userauth, connection, keys, session, common from twisted.conch.insults import insults from twisted.application import service, internet
from zope.interface import implements
import os

class SSHDemoProtocol(recvline.HistoricRecvLine):
    def __init__(self, user):
        self.user = user

    def connectionMade(self) : 
     recvline.HistoricRecvLine.connectionMade(self)
        self.terminal.write("Welcome to my test SSH server.")
        self.terminal.nextLine() 
        self.do_help()
        self.showPrompt()

    def showPrompt(self): 
        self.terminal.write("$ ")

    def getCommandFunc(self, cmd):
        return getattr(self, ‘do_’ + cmd, None)

    def lineReceived(self, line):
        line = line.strip()
        if line: 
            cmdAndArgs = line.split()
            cmd = cmdAndArgs[0]
            args = cmdAndArgs[1:]
            func = self.getCommandFunc(cmd)
            if func: 
               try:
                   func(*args)
               except Exception, e: 
                   self.terminal.write("Error: %s" % e)
                   self.terminal.nextLine()
            else:
               self.terminal.write("No such command.")
               self.terminal.nextLine()
        self.showPrompt()

    def do_help(self, cmd=”):
        "Get help on a command. Usage: help command"
        if cmd: 
            func = self.getCommandFunc(cmd)
            if func:
                self.terminal.write(func.__doc__)
                self.terminal.nextLine()
                return

        publicMethods = filter(
            lambda funcname: funcname.startswith(‘do_’), dir(self)) 
        commands = [cmd.replace(‘do_’, ”, 1) for cmd in publicMethods] 
        self.terminal.write("Commands: " + " ".join(commands))
        self.terminal.nextLine()

    def do_echo(self, *args):
        "Echo a string. Usage: echo my line of text"
        self.terminal.write(" ".join(args)) 
        self.terminal.nextLine()

    def do_whoami(self):
        "Prints your user name. Usage: whoami"
        self.terminal.write(self.user.username)
        self.terminal.nextLine()

    def do_quit(self):
        "Ends your session. Usage: quit" 
        self.terminal.write("Thanks for playing!")
        self.terminal.nextLine() 
        self.terminal.loseConnection()

    def do_clear(self):
        "Clears the screen. Usage: clear" 
        self.terminal.reset()

class SSHDemoAvatar(avatar.ConchUser): 
    implements(conchinterfaces.ISession)

    def __init__(self, username): 
        avatar.ConchUser.__init__(self) 
        self.username = username 
        self.channelLookup.update({‘session’:session.SSHSession})

    def openShell(self, protocol): 
        serverProtocol = insults.ServerProtocol(SSHDemoProtocol, self)
        serverProtocol.makeConnection(protocol)
        protocol.makeConnection(session.wrapProtocol(serverProtocol))

    def getPty(self, terminal, windowSize, attrs):
        return None

    def execCommand(self, protocol, cmd): 
        raise NotImplementedError

    def closed(self):
        pass

class SSHDemoRealm:
    implements(portal.IRealm)

    def requestAvatar(self, avatarId, mind, *interfaces):
        if conchinterfaces.IConchUser in interfaces:
            return interfaces[0], SSHDemoAvatar(avatarId), lambda: None
        else:
            raise Exception, "No supported interfaces found."

def getRSAKeys():
    if not (os.path.exists(‘public.key’) and os.path.exists(‘private.key’)):
        # generate a RSA keypair
        print "Generating RSA keypair…" 
        from Crypto.PublicKey import RSA 
        KEY_LENGTH = 1024
        rsaKey = RSA.generate(KEY_LENGTH, common.entropy.get_bytes)
        publicKeyString = keys.makePublicKeyString(rsaKey) 
        privateKeyString = keys.makePrivateKeyString(rsaKey)
        # save keys for next time
        file(‘public.key’, ‘w+b’).write(publicKeyString)
        file(‘private.key’, ‘w+b’).write(privateKeyString)
        print "done."
    else:
        publicKeyString = file(‘public.key’).read()
        privateKeyString = file(‘private.key’).read() 
    return publicKeyString, privateKeyString

if __name__ == "__main__":
    sshFactory = factory.SSHFactory() 
    sshFactory.portal = portal.Portal(SSHDemoRealm())
    users = {‘admin’: ‘aaa’, ‘guest’: ‘bbb’}
    sshFactory.portal.registerChecker(
 checkers.InMemoryUsernamePasswordDatabaseDontUse(**users))

    pubKeyString, privKeyString =
getRSAKeys()
    sshFactory.publicKeys = {
        ‘ssh-rsa’: keys.getPublicKeyString(data=pubKeyString)}
    sshFactory.privateKeys = {
        ‘ssh-rsa’: keys.getPrivateKeyObject(data=privKeyString)}

    from twisted.internet import reactor 
    reactor.listenTCP(2222, sshFactory) 
    reactor.run()

{mospagebreak title=Setting Up a Custom SSH Server continued}

sshserver.py will run an SSH server on port 2222. Connect to this server with an SSH client using the username admin and password aaa, and try typing some commands:

$ ssh admin@localhost -p 2222 
admin@localhost’s password: aaa

>>> Welcome to my test SSH server.  
Commands: clear echo help quit whoami
$ whoami
admin
$ help echo
Echo a string. Usage: echo my line of text
$ echo hello SSH world!
hello SSH world!
$ quit

Connection to localhost closed.

How to find which git branch I am on when my disk is mounted on other server

.git/HEAD contains the path of the current ref, the working directory is using as HEAD.

Firefox 'Cross-Origin Request Blocked' despite headers

I came across this question having found requests in Firefox were being blocked with the message:

Reason: CORS request did not succeed

After pulling my hair out I found out that a newly installed Firefox extension, Privacy Badger, was blocking the requests.

If you come to this question after scratching your head, try checking to see what extensions you have installed to see if any of them are blocking requests.

See Reason: CORS request did not succeed on MDN for details.

jquery datatables hide column

Hope this will help you. I am using this solution for Search on some columns but i don't want to display them on frontend.

$(document).ready(function() {
        $('#example').dataTable({
            "scrollY": "500px",
            "scrollCollapse": true,
            "scrollX": false,
            "bPaginate": false,
            "columnDefs": [
                { 
                    "width": "30px", 
                    "targets": 0,
                },
                { 
                    "width": "100px", 
                    "targets": 1,
                },
                { 
                    "width": "100px", 
                    "targets": 2,
                },              
                { 
                    "width": "76px",
                    "targets": 5, 
                },
                { 
                    "width": "80px", 
                    "targets": 6,
                },
                {
                    "targets": [ 7 ],
                    "visible": false,
                    "searchable": true
                },
                {
                    "targets": [ 8 ],
                    "visible": false,
                    "searchable": true
                },
                {
                    "targets": [ 9 ],
                    "visible": false,
                    "searchable": true
                },
              ]
        });
    });

Why doesn't wireshark detect my interface?

On Fedora 29 with Wireshark 3.0.0 only adding a user to the wireshark group is required:

sudo usermod -a -G wireshark $USER

Then log out and log back in (or reboot), and Wireshark should work correctly.

How do I sort a list of datetime or date objects?

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

What is a serialVersionUID and why should I use it?

Firstly to answer your question, when we don't declare SerialVersionUID in our class, Java runtime generates it for us, but that process is sensitive to many class meta data including number of fields, type of fields, access modifier of fields, interface implemented by class etc. Therefore it is recommended to declare it ourselves and Eclipse is warning you about the same.

Serialization: We often work with important objects whose state (data in the variables of the object) is so important that we can not risk to lose it due to power/system failures (or) network failures in case of sending the object state to other machine. The solution for this problem is named "Persistence" which simply means persisting (holding/saving) the data. Serialization is one of many other ways to achieve persistence (by saving data to disk/memory). When saving the state of the object, it is important to create an identity for the object, to be able to properly read it back (de-serialization). This unique identification is ID is SerialVersionUID.

Proxy Basic Authentication in C#: HTTP 407 error

try this

        var YourURL = "http://yourUrl/";

         HttpClientHandler handler = new HttpClientHandler() 
         { 
             Proxy = new WebProxy("http://127.0.0.1:8888"), 
             UseProxy = true, 
         }; 

         Console.WriteLine(YourURL); 

         HttpClient client = new HttpClient(handler); 

Difference between dates in JavaScript

You can also use it

export function diffDateAndToString(small: Date, big: Date) {


    // To calculate the time difference of two dates 
    const Difference_In_Time = big.getTime() - small.getTime()

    // To calculate the no. of days between two dates 
    const Days = Difference_In_Time / (1000 * 3600 * 24)
    const Mins = Difference_In_Time / (60 * 1000)
    const Hours = Mins / 60

    const diffDate = new Date(Difference_In_Time)

    console.log({ date: small, now: big, diffDate, Difference_In_Days: Days, Difference_In_Mins: Mins, Difference_In_Hours: Hours })

    var result = ''

    if (Mins < 60) {
        result = Mins + 'm'
    } else if (Hours < 24) result = diffDate.getMinutes() + 'h'
    else result = Days + 'd'
    return { result, Days, Mins, Hours }
}

results in { result: '30d', Days: 30, Mins: 43200, Hours: 720 }

How can I select rows by range?

You can use rownum :

SELECT * FROM table WHERE rownum > 10 and rownum <= 20

HttpServletRequest to complete URL

Use the following methods on HttpServletRequest object

java.lang.String getRequestURI() -Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.

java.lang.StringBuffer getRequestURL() -Reconstructs the URL the client used to make the request.

java.lang.String getQueryString() -Returns the query string that is contained in the request URL after the path.

set the iframe height automatically

If the sites are on separate domains, the calling page can't access the height of the iframe due to cross-browser domain restrictions. If you have access to both sites, you may be able to use the [document domain hack].1 Then anroesti's links should help.

How to make shadow on border-bottom?

funny, that in the most answer you create a box with the text (or object), instead of it create the text (or object) div and under that a box with 100% width (or at least what it should) and with height what equal with your "border" px... So, i think this is the most simple and perfect answer:

<h3>Your Text</h3><div class="border-shadow"></div>

and the css:

    .shadow {
        width:100%;
        height:1px; // = "border height (without the shadow)!"
        background:#000; // = "border color!"
        -webkit-box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"
        -moz-box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"
        box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"

}

Here you can experiment with the radius, etc. easy: https://www.cssmatic.com/box-shadow

Replacing some characters in a string with another character

You might find this link helpful:

http://tldp.org/LDP/abs/html/string-manipulation.html

In general,

To replace the first match of $substring with $replacement:

${string/substring/replacement}

To replace all matches of $substring with $replacement:

${string//substring/replacement}

EDIT: Note that this applies to a variable named $string.

How to remove anaconda from windows completely?

Since I didn't have the uninstaller listed - the solution turned out to be to reinstall Anaconda and then uninstall it.

get the value of input type file , and alert if empty

<script type="text/javascript">
$(document).ready(function() {
    $('#upload').bind("click",function() 
    { 
        var imgVal = $('#uploadImage').val(); 
        if(imgVal=='') 
        { 
            alert("empty input file"); 

        } 
        return false; 

    }); 
});
</script> 

<input type="file" name="image" id="uploadImage" size="30" /> 
<input type="submit" name="upload" id="upload"  class="send_upload" value="upload" /> 

GitHub authentication failing over https, returning wrong email address

It may happen in Windows if you stored a different credentials before. Go to Credential Manager and delete stored github credentials

Bootstrap 3: how to make head of dropdown link clickable in navbar

Just add the class disabled on your anchor:

<a class="dropdown-toggle disabled" href="{your link}">
Dropdown</a>

And you are free to go.

Laravel 5 How to switch from Production mode

Laravel 5 gets its enviroment related variables from the .env file located in the root of your project. You just need to set APP_ENV to whatever you want, for example:

APP_ENV=development

This is used to identify the current enviroment. If you want to display errors, you'll need to enable debug mode in the same file:

APP_DEBUG=true

The role of the .env file is to allow you to have different settings depending on which machine you are running your application. So on your production server, the .env file settings would be different from your local development enviroment.

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

Solution (Updated: 24-may-2016): Change build.gradle (project)

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:X.X.X-lastVersionGradle'
    classpath 'com.google.gms:google-services:X.X.X-lastVersionGServices' // If use google-services

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

X.X.X-lastVersionGradle: For example: 2.1.0

X.X.X-lastVersionGServices: For example: 3.0.0 (support Firebase Analytics)

Note: if you're using the google-services plugin has to be the same version (if there)

Warning!! -> 2.2.0-alpha throws Unsupported major.minor version 52.0 if you don't use java JDK 8u91 and NetBeans 8.1

How do I convert a calendar week into a date in Excel?

For ISO week numbers you can use this formula to get the Monday

=DATE(A2,1,-2)-WEEKDAY(DATE(A2,1,3))+B2*7

assuming year in A2 and week number in B2

it's the same as my answer here https://stackoverflow.com/a/10855872/1124287

Difference between a Structure and a Union

A union is useful in a couple scenarios. union can be a tool for very low level manipulation like writing device drivers for a kernel.

An example of that is dissecting a float number by using union of a struct with bitfields and a float. I save a number in the float, and later I can access particular parts of the float through that struct. The example shows how union is used to have different angles to look at data.

#include <stdio.h>                                                                                                                                       

union foo {
    struct float_guts {
        unsigned int fraction : 23;
        unsigned int exponent : 8;
        unsigned int sign     : 1;
    } fg;
    float f;
};

void print_float(float f) {
    union foo ff;
    ff.f = f;
    printf("%f: %d 0x%X 0x%X\n", f, ff.fg.sign, ff.fg.exponent, ff.fg.fraction);

}

int main(){
    print_float(0.15625);
    return 0;
}

Take a look at single precision description on wikipedia. I used the example and the magic number 0.15625 from there.


union can also be used to implement an algebraic data type that has multiple alternatives. I found an example of that in the "Real World Haskell" book by O'Sullivan, Stewart, and Goerzen. Check it out in the The discriminated union section.

Cheers!

How to fit in an image inside span tag?

Try this.

<span style="padding-right:3px; padding-top: 3px; display:inline-block;">

<img class="manImg" src="images/ico_mandatory.gif"></img>

</span>

What does java.lang.Thread.interrupt() do?

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. A very good referance: https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

Android, How can I Convert String to Date?

     import java.text.ParseException;
     import java.text.SimpleDateFormat;
     import java.util.Date;
     public class MyClass 
     {
     public static void main(String args[]) 
     {
     SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");

     String dateInString = "Wed Mar 14 15:30:00 EET 2018";

     SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");


     try {

        Date date = formatter.parse(dateInString);
        System.out.println(date);
        System.out.println(formatterOut.format(date));

         } catch (ParseException e) {
        e.printStackTrace();
         }
    }
    }

here is your Date object date and the output is :

Wed Mar 14 13:30:00 UTC 2018

14 Mar 2018

How to escape single quotes within single quoted strings

I don't see the entry on his blog (link pls?) but according to the gnu reference manual:

Enclosing characters in single quotes (‘'’) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

so bash won't understand:

alias x='y \'z '

however, you can do this if you surround with double quotes:

alias x="echo \'y "
> x
> 'y

How to set order of repositories in Maven settings.xml

As far as I know, the order of the repositories in your pom.xml will also decide the order of the repository access.

As for configuring repositories in settings.xml, I've read that the order of repositories is interestingly enough the inverse order of how the repositories will be accessed.

Here a post where someone explains this curiosity:
http://community.jboss.org/message/576851

HTML image bottom alignment inside DIV container

<div> with some proportions

div {
  position: relative;
  width: 100%;
  height: 100%;
}

<img>'s with their own proportions

img {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: auto; /* to keep proportions */
  height: auto; /* to keep proportions */
  max-width: 100%; /* not to stand out from div */
  max-height: 100%; /* not to stand out from div */
  margin: auto auto 0; /* position to bottom and center */
}

Better way to represent array in java properties file

I can suggest using delimiters and using the

String.split(delimiter)

Example properties file:

MON=0800#Something#Something1, Something2

prop.load(new FileInputStream("\\\\Myseccretnetwork\\Project\\props.properties"));
String[]values = prop.get("MON").toString().split("#");

Hope that helps

How to obtain the start time and end time of a day?

I think the easiest would be something like:

// Joda Time

DateTime dateTime=new DateTime(); 

StartOfDayMillis = dateTime.withMillis(System.currentTimeMillis()).withTimeAtStartOfDay().getMillis();
EndOfDayMillis = dateTime.withMillis(StartOfDayMillis).plusDays(1).minusSeconds(1).getMillis();

These millis can be then converted into Calendar,Instant or LocalDate as per your requirement with Joda Time.

Razor view engine - How can I add Partial Views

You partial looks much like an editor template so you could include it as such (assuming of course that your partial is placed in the ~/views/controllername/EditorTemplates subfolder):

@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)

Or if this is not the case simply:

@Html.Partial("nameOfPartial", Model)

php - add + 7 days to date format mm dd, YYYY

The "+1 month" issue with strtotime

As noted in several blogs, strtotime() solves the "+1 month" ("next month") issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.

$dt = date("Y-m-d");
echo date( "Y-m-d", strtotime( "$dt +1 day" ) ); // PHP:  2009-03-04
echo date( "Y-m-d", strtotime( "2009-01-31 +2 month" ) ); // PHP:  2009-03-31

Difference between onCreate() and onStart()?

onCreate() method gets called when activity gets created, and its called only once in whole Activity life cycle. where as onStart() is called when activity is stopped... I mean it has gone to background and its onStop() method is called by the os. onStart() may be called multiple times in Activity life cycle.More details here

HTML Mobile -forcing the soft keyboard to hide

example how i made it , After i fill a Maximum length it will blur from my Field (and the Keyboard will disappear ) , if you have more than one field , you can just add the line that i add '//'

var MaxLength = 8;
    $(document).ready(function () {
        $('#MyTB').keyup(function () {
            if ($(this).val().length >= MaxLength) {
               $('#MyTB').blur();
             //  $('#MyTB2').focus();
         }
          }); });

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

How to print float to n decimal places including trailing 0s?

Floating point numbers lack precision to accurately represent "1.6" out to that many decimal places. The rounding errors are real. Your number is not actually 1.6.

Check out: http://docs.python.org/library/decimal.html

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

One solution is to first encode data and then decode it in the same file:

$string =json_encode($input, JSON_UNESCAPED_UNICODE) ; 
echo $decoded = html_entity_decode( $string );

How to remove specific session in asp.net?

you can use Session.Remove() method; Session.Remove

Session.Remove("yourSessionName");

CSS image resize percentage of itself?

Try zoom property

<img src="..." style="zoom: 0.5" />

Edit: Apparently, FireFox doesn't support zoom property. You should use;

-moz-transform: scale(0.5);

for FireFox.

If conditions in a Makefile, inside a target

There are several problems here, so I'll start with my usual high-level advice: Start small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work. (I really ought to have that hotkeyed.)

You're mixing Make syntax and shell syntax in a way that is just dizzying. You should never have let it get this big without testing. Let's start from the outside and work inward.

UNAME := $(shell uname -m)

all:
    $(info Checking if custom header is needed)
    ifeq ($(UNAME), x86_64)
    ... do some things to build unistd_32.h
    endif

    @make -C $(KDIR) M=$(PWD) modules

So you want unistd_32.h built (maybe) before you invoke the second make, you can make it a prerequisite. And since you want that only in a certain case, you can put it in a conditional:

ifeq ($(UNAME), x86_64)
all: unistd_32.h
endif

all:
    @make -C $(KDIR) M=$(PWD) modules

unistd_32.h:
    ... do some things to build unistd_32.h

Now for building unistd_32.h:

F1_EXISTS=$(shell [ -e /usr/include/asm/unistd_32.h ] && echo 1 || echo 0 )
ifeq ($(F1_EXISTS), 1)
    $(info Copying custom header)
    $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm/unistd_32.h > unistd_32.h)
else    
    F2_EXISTS=$(shell [[ -e /usr/include/asm-i386/unistd.h ]] && echo 1 || echo 0 )
    ifeq ($(F2_EXISTS), 1)
        $(info Copying custom header)
        $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm-i386/unistd.h > unistd_32.h)
    else
        $(error asm/unistd_32.h and asm-386/unistd.h does not exist)
    endif
endif

You are trying to build unistd.h from unistd_32.h; the only trick is that unistd_32.h could be in either of two places. The simplest way to clean this up is to use a vpath directive:

vpath unistd.h /usr/include/asm /usr/include/asm-i386

unistd_32.h: unistd.h
    sed -e 's/__NR_/__NR32_/g' $< > $@

Python - List of unique dictionaries

We can do with pandas

import pandas as pd
yourdict=pd.DataFrame(L).drop_duplicates().to_dict('r')
Out[293]: [{'age': 34, 'id': 1, 'name': 'john'}, {'age': 30, 'id': 2, 'name': 'hanna'}]

Notice slightly different from the accept answer.

drop_duplicates will check all column in pandas , if all same then the row will be dropped .

For example :

If we change the 2nd dict name from john to peter

L=[
    {'id': 1, 'name': 'john', 'age': 34},
    {'id': 1, 'name': 'peter', 'age': 34},
    {'id': 2, 'name': 'hanna', 'age': 30},
]
pd.DataFrame(L).drop_duplicates().to_dict('r')
Out[295]: 
[{'age': 34, 'id': 1, 'name': 'john'},
 {'age': 34, 'id': 1, 'name': 'peter'},# here will still keeping the dict in the out put 
 {'age': 30, 'id': 2, 'name': 'hanna'}]

Drop rows containing empty cells from a pandas DataFrame

You can use this variation:

import pandas as pd
vals = {
    'name' : ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'],
    'gender' : ['m', 'f', 'f', 'f',  'f', 'c', 'c'],
    'age' : [39, 12, 27, 13, 36, 29, 10],
    'education' : ['ma', None, 'school', None, 'ba', None, None]
}
df_vals = pd.DataFrame(vals) #converting dict to dataframe

This will output(** - highlighting only desired rows):

   age education gender name
0   39        ma      m   n1 **
1   12      None      f   n2    
2   27    school      f   n3 **
3   13      None      f   n4
4   36        ba      f   n5 **
5   29      None      c   n6
6   10      None      c   n7

So to drop everything that does not have an 'education' value, use the code below:

df_vals = df_vals[~df_vals['education'].isnull()] 

('~' indicating NOT)

Result:

   age education gender name
0   39        ma      m   n1
2   27    school      f   n3
4   36        ba      f   n5

How to configure static content cache per folder and extension in IIS7?

You can set specific cache-headers for a whole folder in either your root web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- Note the use of the 'location' tag to specify which 
       folder this applies to-->
  <location path="images">
    <system.webServer>
      <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
      </staticContent>
    </system.webServer>
  </location>
</configuration>

Or you can specify these in a web.config file in the content folder:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
    </staticContent>
  </system.webServer>
</configuration>

I'm not aware of a built in mechanism to target specific file types.

Pushing to Git returning Error Code 403 fatal: HTTP request failed

In my case, I was getting the above error for my email id with github was not verified yet. GitHub was giving this warning of un-verified email.

Verifying the email, and then pushing worked for me.

Python Pandas - Find difference between two data frames

For rows, try this, where Name is the joint index column (can be a list for multiple common columns, or specify left_on and right_on):

m = df1.merge(df2, on='Name', how='outer', suffixes=['', '_'], indicator=True)

The indicator=True setting is useful as it adds a column called _merge, with all changes between df1 and df2, categorized into 3 possible kinds: "left_only", "right_only" or "both".

For columns, try this:

set(df1.columns).symmetric_difference(df2.columns)

Check if object exists in JavaScript

set Textbox value to one frame to inline frame using div alignmnt tabbed panel. So first of all, before set the value we need check selected tabbed panels frame available or not using following codes:

Javascript Code :

/////////////////////////////////////////
<script>

function set_TextID()
            {
                try
                    {
                        if(!parent.frames["entry"])
                            {
                            alert("Frame object not found");    
                            }
                            else
                            {
                                var setText=document.getElementById("formx").value;
                                parent.frames["entry"].document.getElementById("form_id").value=setText;
                            }
                            if(!parent.frames["education"])
                            {
                            alert("Frame object not found");    

                            }
                            else
                            {
                                var setText=document.getElementById("formx").value;
                                parent.frames["education"].document.getElementById("form_id").value=setText;
                            }
                            if(!parent.frames["contact"])
                            {
                            alert("Frame object not found");    

                            }
                            else
                            {
                                var setText=document.getElementById("formx").value;
                                parent.frames["contact"].document.getElementById("form_id").value=setText;
                            }

                        }catch(exception){}
                }

</script>

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

This code helped find my problem when I had issue with my Entity VAlidation Erros. It told me the exact problem with my Entity Definition. Try following code where you need to cover storeDB.SaveChanges(); in following try catch block.

  try
{
         if (TryUpdateModel(theEvent))
         {
             storeDB.SaveChanges();
             return RedirectToAction("Index");
         }
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
    Exception raise = dbEx;
    foreach (var validationErrors in dbEx.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            string message = string.Format("{0}:{1}", 
                validationErrors.Entry.Entity.ToString(),
                validationError.ErrorMessage);
            // raise a new exception nesting
            // the current instance as InnerException
            raise = new InvalidOperationException(message, raise);
        }
    }
    throw raise;
}

Multiple "order by" in LINQ

I have created some extension methods (below) so you don't have to worry if an IQueryable is already ordered or not. If you want to order by multiple properties just do it as follows:

// We do not have to care if the queryable is already sorted or not. 
// The order of the Smart* calls defines the order priority
queryable.SmartOrderBy(i => i.Property1).SmartOrderByDescending(i => i.Property2);

This is especially helpful if you create the ordering dynamically, f.e. from a list of properties to sort.

public static class IQueryableExtension
{
    public static bool IsOrdered<T>(this IQueryable<T> queryable) {
        if(queryable == null) {
            throw new ArgumentNullException("queryable");
        }

        return queryable.Expression.Type == typeof(IOrderedQueryable<T>);
    }

    public static IQueryable<T> SmartOrderBy<T, TKey>(this IQueryable<T> queryable, Expression<Func<T, TKey>> keySelector) {
        if(queryable.IsOrdered()) {
            var orderedQuery = queryable as IOrderedQueryable<T>;
            return orderedQuery.ThenBy(keySelector);
        } else {
            return queryable.OrderBy(keySelector);
        }
    }

    public static IQueryable<T> SmartOrderByDescending<T, TKey>(this IQueryable<T> queryable, Expression<Func<T, TKey>> keySelector) {
        if(queryable.IsOrdered()) {
            var orderedQuery = queryable as IOrderedQueryable<T>;
            return orderedQuery.ThenByDescending(keySelector);
        } else {
            return queryable.OrderByDescending(keySelector);
        }
    }
}

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

Create a branch in Git from another branch

Switch to the develop branch:

$ git checkout develop

Creates feature/foo branch of develop.

$ git checkout -b feature/foo develop

merge the changes to develop without a fast-forward

$ git checkout develop
$ git merge --no-ff myFeature

Now push changes to the server

$ git push origin develop
$ git push origin feature/foo

Toad for Oracle..How to execute multiple statements?

Wrap the multiple statements in a BEGIN END block to make them one statement and add a slash after the END; clause.

BEGIN
  insert into books
  (id, title, author)
  values
  (books_seq.nextval, 'The Bite in the Apple', 'Chrisann Brennan');

  insert into books
  (id, title, author)
  values
  (books_seq.nextval, 'The Restaurant at the End of the Universe', 'Douglas Adams');
END;
/

That way, it is just ctrl-a then ctrl-enter and it goes.

SQL UPDATE all values in a field with appended string CONCAT not working

UPDATE mytable SET spares = CONCAT(spares, ',', '818') WHERE id = 1

not working for me.

spares is NULL by default but its varchar

Use Ant for running program with command line arguments

What I did in the end is make a batch file to extract the CLASSPATH from the ant file, then run java directly using this:

In my build.xml:

<target name="printclasspath">
    <pathconvert property="classpathProp" refid="project.class.path"/>
    <echo>${classpathProp}</echo>
</target>

In another script called 'run.sh':

export CLASSPATH=$(ant -q printclasspath | grep echo | cut -d \  -f 7):build
java "$@"

It's no longer cross-platform, but at least it's relatively easy to use, and one could provide a .bat file that does the same as the run.sh. It's a very short batch script. It's not like migrating the entire build to platform-specific batch files.

I think it's a shame there's not some option in ant whereby you could do something like:

ant -- arg1 arg2 arg3

mpirun uses this type of syntax; ssh also can use this syntax I think.

Bytes of a string in Java

A String instance allocates a certain amount of bytes in memory. Maybe you're looking at something like sizeof("Hello World") which would return the number of bytes allocated by the datastructure itself?

In Java, there's usually no need for a sizeof function, because we never allocate memory to store a data structure. We can have a look at the String.java file for a rough estimation, and we see some 'int', some references and a char[]. The Java language specification defines, that a char ranges from 0 to 65535, so two bytes are sufficient to keep a single char in memory. But a JVM does not have to store one char in 2 bytes, it only has to guarantee, that the implementation of char can hold values of the defines range.

So sizeof really does not make any sense in Java. But, assuming that we have a large String and one char allocates two bytes, then the memory footprint of a String object is at least 2 * str.length() in bytes.

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

The error was due to the way that I configured the Application Pool in IIS.

My web service uses an Application Tool configured for v2.0.50727. This resulted in the error message.

When I changed it to v4.0.30319, I did not get the error.

Insert data into table with result from another select query

Below is an example of such a query:

INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

CSS: Position loading indicator in the center of the screen

You can use this OnLoad or during fetch infos from DB

In HTML Add following code:

<div id="divLoading">
<p id="loading">
    <img src="~/images/spinner.gif">
</p>

In CSS add following Code:

#divLoading {
  margin: 0px;
  display: none;
  padding: 0px;
  position: absolute;
  right: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  background-color: rgb(255, 255, 255);
  z-index: 30001;
  opacity: 0.8;}

#loading {
   position: absolute;
   color: White;
  top: 50%;
  left: 45%;}

if you want to show and hide from JS:

  document.getElementById('divLoading').style.display = 'none'; //Not Visible
  document.getElementById('divLoading').style.display = 'block';//Visible

How can I plot data with confidence intervals?

Here is a plotrix solution:

set.seed(0815)
x <- 1:10
F <- runif(10,1,2) 
L <- runif(10,0,1)
U <- runif(10,2,3)

require(plotrix)
plotCI(x, F, ui=U, li=L)

enter image description here

And here is a ggplot solution:

set.seed(0815)
df <- data.frame(x =1:10,
                 F =runif(10,1,2),
                 L =runif(10,0,1),
                 U =runif(10,2,3))

require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
  geom_point(size = 4) +
  geom_errorbar(aes(ymax = U, ymin = L))

enter image description here

UPDATE: Here is a base solution to your edits:

set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
                 y = x + rnorm(20))

plot(y ~ x, data = df)

# model
mod <- lm(y ~ x, data = df)

# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx), 
                 interval = 'confidence')

# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')

enter image description here

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

If you are getting this message from a Maven built war change the scope of the JDBC driver to provided, and put a copy of it in the lib directory. Like this:

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.18</version>
  <!-- put a copy in /usr/share/tomcat7/lib -->
  <scope>provided</scope>
</dependency>

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Determining Referer in PHP

Using $_SERVER['HTTP_REFERER']

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

if (!empty($_SERVER['HTTP_REFERER'])) {
    header("Location: " . $_SERVER['HTTP_REFERER']);
} else {
    header("Location: index.php");
}
exit;

MySql sum elements of a column

 select sum(A),sum(B),sum(C) from mytable where id in (1,2,3);

Task continuation on UI thread

Call the continuation with TaskScheduler.FromCurrentSynchronizationContext():

    Task UITask= task.ContinueWith(() =>
    {
     this.TextBlock1.Text = "Complete"; 
    }, TaskScheduler.FromCurrentSynchronizationContext());

This is suitable only if the current execution context is on the UI thread.

How to implement if-else statement in XSLT?

The most straight-forward approach is to do a second if-test but with the condition inverted. This technique is shorter, easier on the eyes, and easier to get right than a choose-when-otherwise nested block:

<xsl:variable name="CreatedDate" select="@createDate"/>
     <xsl:variable name="IDAppendedDate" select="2012-01-01" />
     <b>date: <xsl:value-of select="$CreatedDate"/></b> 
     <xsl:if test="$CreatedDate &gt; $IDAppendedDate">
        <h2> mooooooooooooo </h2>
     </xsl:if>
     <xsl:if test="$CreatedDate &lt;= $IDAppendedDate">
        <h2> dooooooooooooo </h2>
     </xsl:if>

Here's a real-world example of the technique being used in the style-sheet for a government website: http://w1.weather.gov/xml/current_obs/latest_ob.xsl

How to change the type of a field?

The only way to change the $type of the data is to perform an update on the data where the data has the correct type.

In this case, it looks like you're trying to change the $type from 1 (double) to 2 (string).

So simply load the document from the DB, perform the cast (new String(x)) and then save the document again.

If you need to do this programmatically and entirely from the shell, you can use the find(...).forEach(function(x) {}) syntax.


In response to the second comment below. Change the field bad from a number to a string in collection foo.

db.foo.find( { 'bad' : { $type : 1 } } ).forEach( function (x) {   
  x.bad = new String(x.bad); // convert field to string
  db.foo.save(x);
});

How should I have explained the difference between an Interface and an Abstract class?

Nothing is perfect in this world. They may have been expecting more of a practical approach.

But after your explanation you could add these lines with a slightly different approach.

  1. Interfaces are rules (rules because you must give an implementation to them that you can't ignore or avoid, so that they are imposed like rules) which works as a common understanding document among various teams in software development.

  2. Interfaces give the idea what is to be done but not how it will be done. So implementation completely depends on developer by following the given rules (means given signature of methods).

  3. Abstract classes may contain abstract declarations, concrete implementations, or both.

  4. Abstract declarations are like rules to be followed and concrete implementations are like guidelines (you can use it as it is or you can ignore it by overriding and giving your own implementation to it).

  5. Moreover which methods with same signature may change the behaviour in different context are provided as interface declarations as rules to implement accordingly in different contexts.

Edit: Java 8 facilitates to define default and static methods in interface.

public interface SomeInterfaceOne {

    void usualAbstractMethod(String inputString);

    default void defaultMethod(String inputString){
        System.out.println("Inside SomeInterfaceOne defaultMethod::"+inputString);
    }
}

Now when a class will implement SomeInterface, it is not mandatory to provide implementation for default methods of interface.

If we have another interface with following methods:

public interface SomeInterfaceTwo {

    void usualAbstractMethod(String inputString);

    default void defaultMethod(String inputString){
        System.out.println("Inside SomeInterfaceTwo defaultMethod::"+inputString);
    }

}

Java doesn’t allow extending multiple classes because it results in the “Diamond Problem” where compiler is not able to decide which superclass method to use. With the default methods, the diamond problem will arise for interfaces too. Because if a class is implementing both

SomeInterfaceOne and SomeInterfaceTwo

and doesn’t implement the common default method, compiler can’t decide which one to chose. To avoid this problem, in java 8 it is mandatory to implement common default methods of different interfaces. If any class is implementing both the above interfaces, it has to provide implementation for defaultMethod() method otherwise compiler will throw compile time error.

How to configure postgresql for the first time?

This is my solution:

su root
su postgres
psql

How do I exit from the text window in Git?

On Windows 10 this worked for me for VIM and VI using git bash

"Esc" + ":wq!"

or

"Esc" + ":q!"

Convert date to UTC using moment.js

Don't you need something to compare and then retrieve the milliseconds?

For instance:

let enteredDate = $("#txt-date").val(); // get the date entered in the input
let expires = moment.utc(enteredDate); // convert it into UTC

With that you have the expiring date in UTC. Now you can get the "right-now" date in UTC and compare:

var rightNowUTC = moment.utc(); // get this moment in UTC based on browser
let duration = moment.duration(rightNowUTC.diff(expires)); // get the diff
let remainingTimeInMls = duration.asMilliseconds();

String representation of an Enum

Option 1:

public sealed class FormsAuth
{
     public override string ToString{return "Forms Authtentication";}
}
public sealed class WindowsAuth
{
     public override string ToString{return "Windows Authtentication";}
}

public sealed class SsoAuth
{
     public override string ToString{return "SSO";}
}

and then

object auth = new SsoAuth(); //or whatever

//...
//...
// blablabla

DoSomethingWithTheAuth(auth.ToString());

Option 2:

public enum AuthenticationMethod
{
        FORMS = 1,
        WINDOWSAUTHENTICATION = 2,
        SINGLESIGNON = 3
}

public class MyClass
{
    private Dictionary<AuthenticationMethod, String> map = new Dictionary<AuthenticationMethod, String>();
    public MyClass()
    {
         map.Add(AuthenticationMethod.FORMS,"Forms Authentication");
         map.Add(AuthenticationMethod.WINDOWSAUTHENTICATION ,"Windows Authentication");
         map.Add(AuthenticationMethod.SINGLESIGNON ,"SSo Authentication");
    }
}

getting the index of a row in a pandas apply function

To answer the original question: yes, you can access the index value of a row in apply(). It is available under the key name and requires that you specify axis=1 (because the lambda processes the columns of a row and not the rows of a column).

Working example (pandas 0.23.4):

>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
   b  c
a      
1  2  3
4  5  6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
   b  c  index_x10
a                 
1  2  3         10
4  5  6         40

PHP's array_map including keys

$array = [
  'category1' => 'first category',
  'category2' => 'second category',
];
 
$new = array_map(function($key, $value) {
  return "{$key} => {$value}";
}, array_keys($array), $array);

jQuery set radio button

You can try the following code:

$("input[name=cols][value=" + value + "]").attr('checked', 'checked');

This will set the attribute checked for the radio columns and value as specified.

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

For the warning by warning case, It's wise to restore it to default at some point, since you are doing it on a case by case basis.

#pragma warning(disable: 4996) /* Disable deprecation */
// Code that causes it goes here
#pragma warning(default: 4996) /* Restore default */

querySelector, wildcard element match?

Set the tagName as an explicit attribute:

for(var i=0,els=document.querySelectorAll('*'); i<els.length;
          els[i].setAttribute('tagName',els[i++].tagName) );

I needed this myself, for an XML Document, with Nested Tags ending in _Sequence. See JaredMcAteer answer for more details.

document.querySelectorAll('[tagName$="_Sequence"]')

I didn't say it would be pretty :) PS: I would recommend to use tag_name over tagName, so you do not run into interferences when reading 'computer generated', implicit DOM attributes.

How do I consume the JSON POST data in an Express application

For those getting an empty object in req.body

I had forgotten to set headers: {"Content-Type": "application/json"} in the request. Changing it solved the problem.

Mvn install or Mvn package

mvn install is the option that is most often used.
mvn package is seldom used, only if you're debugging some issue with the maven build process.

See: http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

Note that mvn package will only create a jar file.
mvn install will do that and install the jar (and class etc.) files in the proper places if other code depends on those jars.

I usually do a mvn clean install; this deletes the target directory and recreates all jars in that location.
The clean helps with unneeded or removed stuff that can sometimes get in the way.
Rather then debug (some of the time) just start fresh all of the time.

How to query a CLOB column in Oracle

This works

select DBMS_LOB.substr(myColumn, 3000) from myTable

How to configure port for a Spring Boot application

Using mvn shell command line, spring-boot 2:

mvn spring-boot:run -Dspring-boot.run.jvmArguments='-Dserver.port=8085'

req.query and req.param in ExpressJS

req.query is the query string sent to the server, example /page?test=1, req.param is the parameters passed to the handler.

app.get('/user/:id', handler);, going to /user/blah, req.param.id would return blah;

Comment out HTML and PHP together

The <!-- --> is only for HTML commenting and the PHP will still run anyway...

Therefore the best thing I would do is also to comment out the PHP...

How to check if an element does NOT have a specific class?

I don't know why, but the accepted answer didn't work for me. Instead this worked:

if ($(this).hasClass("test") !== false) {}

Shell - How to find directory of some command?

~$ echo $PATH
/home/jack/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
~$ whereis lshw
lshw: /usr/bin/lshw /usr/share/man/man1/lshw.1.gz

Command /usr/bin/codesign failed with exit code 1

The real FIX for me was:
The only problem is I had my Provisioning Profile "invalid" in member center, because that old provisioning profile was generated by old certificate.
Once you regenerate your certificate, or regenerate your Provisioning Profile, make sure you download them and feed them to Xcode.

Convert from lowercase to uppercase all values in all character variables in dataframe

A side comment here for those using any of these answers. Juba's answer is great, as it's very selective if your variables are either numberic or character strings. If however, you have a combination (e.g. a1, b1, a2, b2) etc. It will not convert the characters properly.

As @Trenton Hoffman notes,

library(dplyr)
df <- mutate_each(df, funs(toupper))

affects both character and factor classes and works for "mixed variables"; e.g. if your variable contains both a character and a numberic value (e.g. a1) both will be converted to a factor. Overall this isn't too much of a concern, but if you end up wanting match data.frames for example

df3 <- df1[df1$v1 %in% df2$v1,]

where df1 has been has been converted and df2 contains a non-converted data.frame or similar, this may cause some problems. The work around is that you briefly have to run

df2 <- df2 %>% mutate_each(funs(toupper), v1)
#or
df2 <- df2 %>% mutate_each(df2, funs(toupper))
#and then
df3 <- df1[df1$v1 %in% df2$v1,]

If you work with genomic data, this is when knowing this can come in handy.

How can I run code on a background thread on Android?

class Background implements Runnable {
    private CountDownLatch latch = new CountDownLatch(1);
    private  Handler handler;

    Background() {
        Thread thread = new Thread(this);
        thread.start();
        try {
            latch.await();
        } catch (InterruptedException e) {
           /// e.printStackTrace();
        }
    }

    @Override
    public void run() {
        Looper.prepare();
        handler = new Handler();
        latch.countDown();
        Looper.loop();
    }

    public Handler getHandler() {
        return handler;
    }
}

How to export/import PuTTy sessions list?

  1. Launch Run, then type in the Open drop down window: regedit

  2. Navigate to, just like in Window's Explorer:
    HKEY_CURRENT_USER\Software\SimonTatham

  3. Right click on 'SimonTatham' key (directory icon), select Export
    Give the file a name (say) putty.reg and save it to your location for
    later use.
  4. Close Registry Editor.

Done.

How to set Spring profile from system variable?

You can set the spring profile by supplying -Dspring.profiles.active=<env>

For java files in source(src) directory, you can use by System.getProperty("spring.profiles.active")

For java files in test directory you can supply

  • SPRING_PROFILES_ACTIVE to <env>

OR

Since, "environment", "jvmArgs" and "systemProperties" are ignored for the "test" task. In root build.gradle add a task to set jvm property and environment variable.

test {
    def profile = System.properties["spring.profiles.active"]
    systemProperty "spring.profiles.active",profile
    environment "SPRING.PROFILES_ACTIVE", profile
    println "Running ${project} tests with profile: ${profile}"
}

What are my options for storing data when using React Native? (iOS and Android)

Here's what I've learned as I determine the best way to move forward with a couple of my current app projects.

Async Storage (formerly "built-in" to React Native, now moved on its own)

I use AsyncStorage for an in-production app. Storage stays local to the device, is unencrypted (as mentioned in another answer), goes away if you delete the app, but should be saved as part of your device's backups and persists during upgrades (both native upgrades ala TestFlight and code upgrades via CodePush).

Conclusion: Local storage; you provide your own sync/backup solution.

SQLite

Other projects I have worked on have used sqlite3 for app storage. This gives you an SQL-like experience, with compressible databases that can also be transmitted to and from the device. I have not had any experience with syncing them to a back end, but I imagine various libraries exist. There are RN libraries for connecting to SQLite.

Data is stored in your traditional database format with databases, tables, keys, indices, etc. all saved to disk in a binary format. Direct access to the data is available via command line or apps that have SQLite drivers.

Conclusion: Local storage; you supply the sync and backup.

Firebase

Firebase offers, among other things, a real time noSQL database along with a JSON document store (like MongoDB) meant for keeping from 1 to n number of clients synchronized. The docs talk about offline persistence, but only for native code (Swift/Obj-C, Java). Google's own JavaScript option ("Web") which is used by React Native does not provide a cached storage option (see 2/18 update below). The library is written with the assumption that a web browser is going to be connecting, and so there will be a semi-persistent connection. You could probably write a local caching mechanism to supplement the Firebase storage calls, or you could write a bridge between the native libraries and React Native.

Update 2/2018 I have since found React Native Firebase which provides a compatible JavaScript interface to the native iOS and Android libraries (doing what Google probably could/should have done), giving you all the goodies of the native libraries with the bonus of React Native support. With Google's introduction of a JSON document store beside the real-time database, I'm giving Firebase a good second look for some real-time apps I plan to build.

The real-time database is stored as a JSON-like tree that you can edit on the website and import/export pretty simply.

Conclusion: With react-native-firebase, RN gets same benefits as Swift and Java. [/update] Scales well for network-connected devices. Low cost for low utilization. Combines nicely with other Google cloud offerings. Data readily visible and editable from their interface.

Realm

Update 4/2020 MongoDB has acquired Realm and is planning to combine it with MongoDB Stitch (discussed below). This looks very exciting.

Update 9/2020 Having used Realm vs. Stitch: Stitch API's essentially allowed a JS app (React Native or web) to talk directly to the Mongo database instead of going through an API server you build yourself.

Realm was meant to synchronize portions of the database whenever changes were made.

The combination of the two gets a little confusing. The formerly-known-as-Stitch API's still work like your traditional Mongo query and update calls, whereas the newer Realm stuff attaches to objects in code and handles synchronization all by itself... mostly. I'm still working through the right way to do things in one project, which is using SwiftUI, so it's a bit off-topic. But promising and neat nonetheless.


Also a real time object store with automagic network synchronization. They tout themselves as "device first" and the demo video shows how the devices handle sporadic or lossy network connectivity.

They offer a free version of the object store that you host on your own servers or in a cloud solution like AWS or Azure. You can also create in-memory stores that do not persist with the device, device-only stores that do not sync up with the server, read-only server stores, and the full read-write option for synchronization across one or more devices. They have professional and enterprise options that cost more up front per month than Firebase.

Unlike Firebase, all Realm capabilities are supported in React Native and Xamarin, just as they are in Swift/ObjC/Java (native) apps.

Your data is tied to objects in your code. Because they are defined objects, you do have a schema, and version control is a must for code sanity. Direct access is available via GUI tools Realm provides. On-device data files are cross-platform compatible.

Conclusion: Device first, optional synchronization with free and paid plans. All features supported in React Native. Horizontal scaling more expensive than Firebase.

iCloud

I honestly haven't done a lot of playing with this one, but will be doing so in the near future.

If you have a native app that uses CloudKit, you can use CloudKit JS to connect to your app's containers from a web app (or, in our case, React Native). In this scenario, you would probably have a native iOS app and a React Native Android app.

Like Realm, this stores data locally and syncs it to iCloud when possible. There are public stores for your app and private stores for each customer. Customers can even chose to share some of their stores or objects with other users.

I do not know how easy it is to access the raw data; the schemas can be set up on Apple's site.

Conclusion: Great for Apple-targeted apps.

Couchbase

Big name, lots of big companies behind it. There's a Community Edition and Enterprise Edition with the standard support costs.

They've got a tutorial on their site for hooking things up to React Native. I also haven't spent much time on this one, but it looks to be a viable alternative to Realm in terms of functionality. I don't know how easy it is to get to your data outside of your app or any APIs you build.

[Edit: Found an older link that talks about Couchbase and CouchDB, and CouchDB may be yet another option to consider. The two are historically related but presently completely different products. See this comparison.]

Conclusion: Looks to have similar capabilities as Realm. Can be device-only or synced. I need to try it out.

MongoDB

Update 4/2020

Mongo acquired Realm and plans to combine MongoDB Stitch (discussed below) with Realm (discussed above).


I'm using this server side for a piece of the app that uses AsyncStorage locally. I like that everything is stored as JSON objects, making transmission to the client devices very straightforward. In my use case, it's used as a cache between an upstream provider of TV guide data and my client devices.

There is no hard structure to the data, like a schema, so every object is stored as a "document" that is easily searchable, filterable, etc. Similar JSON objects could have additional (but different) attributes or child objects, allowing for a lot of flexibility in how you structure your objects/data.

I have not tried any client to server synchronization features, nor have I used it embedded. React Native code for MongoDB does exist.

Conclusion: Local only NoSQL solution, no obvious sync option like Realm or Firebase.

Update 2/2019

MongoDB has a "product" (or service) called Stitch. Since clients (in the sense of web browsers and phones) shouldn't be talking to MongoDB directly (that's done by code on your server), they created a serverless front-end that your apps can interface with, should you choose to use their hosted solution (Atlas). Their documentation makes it appear that there is a possible sync option.

This writeup from Dec 2018 discusses using React Native, Stitch, and MongoDB in a sample app, with other samples linked in the document (https://www.mongodb.com/blog/post/building-ios-and-android-apps-with-the-mongodb-stitch-react-native-sdk).

Twilio Sync

Another NoSQL option for synchronization is Twilio's Sync. From their site: "Sync lets you manage state across any number of devices in real time at scale without having to handle any backend infrastructure."

I looked at this as an alternative to Firebase for one of the aforementioned projects, especially after talking to both teams. I also like their other communications tools, and have used them for texting updates from a simple web app.


[Edit] I've spent some time with Realm since I originally wrote this. I like how I don't have to write an API to sync the data between the app and the server, similar to Firebase. Serverless functions also look to be really helpful with these two, limiting the amount of backend code I have to write.

I love the flexibility of the MongoDB data store, so that is becoming my choice for the server side of web-based and other connection-required apps.

I found RESTHeart, which creates a very simple, scalable RESTful API to MongoDB. It shouldn't be too hard to build a React (Native) component that reads and writes JSON objects to RESTHeart, which in turn passes them to/from MongoDB.


[Edit] I added info about how the data is stored. Sometimes it's important to know how much work you might be in for during development and testing if you've got to tweak and test the data.


Edits 2/2019 I experimented with several of these options when designing a high-concurrency project this past year (2018). Some of them mention hard and soft concurrency limits in their documentation (Firebase had a hard one at 10,000 connections, I believe, while Twilio's was a soft limit that could be bumped, according to discussions with both teams at AltConf).

If you are designing an app for tens to hundreds of thousands of users, be prepared to scale the data backend accordingly.