Build the Effective Service ID String for SELECT query
@param {RightTrackDB} db The Right Track DB to query
@param {int} date Date Integer (yyyymmdd)
@param {function} callback Callback function(err, serviceIdString)
@private
338705
function _buildEffectiveServiceIDString(db, date, callback) {

  // Query the Calendar for effective services
  CalendarTable.getServicesEffective(db, date, function(err, services) {

    // Database Query Error
    if ( err ) {
      return callback(err);
    }

    // Build Service ID String
    let serviceIds = [];
    for ( let i = 0; i < services.length; i++ ) {
      serviceIds.push(services[i].id);
    }
    let serviceIdString = "('" + serviceIds.join("', '") + "')";

    // Return Service ID String
    return callback(null, serviceIdString);

  });

}
263268
def cast_callback(value):
        
        # Postgresql / MySQL drivers change the format on 'TIMESTAMP' columns;

        if 'T' in value:
            value = value.replace('T', ' ')

        return datetime.strptime(value.split('.')[0], '%Y-%m-%d %H:%M:%S')
840317
function connect_cb(err, db) {
	if (err) {
	    next(err);
	} else {
	    if (db && db instanceof sqlite) {     // Sqlite only
		app.db = db;
		// Use the query escaping facilities of mysql
		app.db.escape = SqliteString.escape;
		app.db.escapeId = SqliteString.escapeId;
		app.db.format = SqliteString.format;
		// Wrap exec with a signature similar to mysql's
		// prepared queries
		app.db.query = function(sql, values, callback) {
		    // prepare the statement
		    if (typeof values == 'function') {
			callback = values;
		    } else {
			sql = app.db.format(sql, values);
		    }
		    // Log some info
		    console.log('SQL query:', sql);
		    // execute the statement
		    app.db.exec(sql, callback);
		};
		app.db.end = function() {};
	    } else {                              // MySql only
		app.db.format = MySqlString.format;
		// Wrap qyery with some logging some logging 
		var _query = app.db.query;
		app.db.query = function(sql, values, callback) {
		    var _sql = sql;
		    // prepare the statement (just for logging)
		    if (typeof values != 'function')
			_sql = app.db.format(sql, values);
		    // Log some info
		    console.log('SQL query:', _sql);
		    // execute the statement
		    return _query.call(this, sql, values, callback);
		};
	    }
	    next();
	}
    }
1289292
function buildIndex(indexName, db) {
  return db.query(indexName, {
    limit: 0
  }).catch(function(err) {
    console.log(`index error: ${JSON.stringify(err, null, 2)}`);
  });
}
1249803
function(id) {
        var date = this.getDateFieldsByCellId(id);
        return (date) ? DateMath.getDate(date[0],date[1]-1,date[2]) : null;
    }
1240456
function (id, callback) {
    var idIsArr = Array.isArray(id);

    if (!id || (idIsArr && id.length === 0)) {
      return _handleErr('Id required for id API call', callback);
    }

    // If an array of Id's was passed, generate a comma delimited string for
    // the query string.
    if (idIsArr) {
      id = id.join();
    }

    return this._request({
      api: 'gifs',
      query: {
        ids: id
      }
    }, callback);
  }
495959
public static function displaySingleItemByID ($id, $callback = null, array $callback_params = array())
    {
        $item = get_post($id);
        if (!is_null($item)) {
            global $post;
            $post = $item;
            setup_postdata($post);
            if ($callback !== null)
                call_user_func_array($callback, array_merge(array($post), $callback_params));
            wp_reset_postdata();
        }
        return $item;
    }
756139
function(id, dateStr) {
		var onSelect,
			target = $(id),
			inst = this._getInst(target[0]);

		dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
		if (inst.input) {
			inst.input.val(dateStr);
		}
		this._updateAlternate(inst);

		onSelect = this._get(inst, "onSelect");
		if (onSelect) {
			onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
		} else if (inst.input) {
			inst.input.trigger("change"); // fire the change event
		}

		if (inst.inline){
			this._updateDatepicker(inst);
		} else {
			this._hideDatepicker();
			this._lastInput = inst.input[0];
			if (typeof(inst.input[0]) !== "object") {
				inst.input.focus(); // restore focus
			}
			this._lastInput = null;
		}
	}
133995
public String createDateString(Date date) {
        if (date == null) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "Null Date object provided; returning null");
            }
            return null;
        }
        if (tc.isDebugEnabled()) {
            Tr.debug(tc, "Creating date string based on date: " + date);
        }
        String formatted = simpleDateFormat.format(date);
        return formatted;
    }
1058732
function  doQuery(option, inQuery, cb)  {
	var  expr = option.expr,
		 tables = toTableArrays(expr.table),
		 mainTable = tables[0].alias || tables[0].name;
	//console.log('table names are:\n%s', JSON.stringify(tables, null, 4));

	getQueryTableSchema(tables, function(err, tableSchema) {
		if (err)
			return cb(err);

		//console.log('table schema:\n%s', JSON.stringify(tableSchema, null, 4));
		// now we can move on to analyze the query
		// first, we need to collect filter columns...
		var  noColumnSpecified = !(expr.columns || option.raw),
			 whereCol = [];
		if (expr.filters)
			collectFilterColumns(mainTable, expr.filters, whereCol);

		var  colInfo = scanColumns(tableSchema, mainTable, expr.columns, whereCol),
			 isSqlCol = colInfo.nc.length === 0,
			 isSqlFilter = matchSQLFilter(tableSchema, whereCol);
		//console.log('colInfo is:\n%s', JSON.stringify(colInfo, null, 4));
		//console.log('whereCol is:\n%s', JSON.stringify(whereCol, null, 4));

		if (isSqlCol && isSqlFilter)  {
			// all query column are 'inertia', go ahead to do SQL query
			//console.log('doing standard SQL query');
			//option.debug = true;
			soar.execute( option, inQuery, function(err, result) {
				if (noColumnSpecified && result)  {
					// user does not specify what columns to be returned.
					// return all columns and json_columns are extracted/added
					if (tableSchema[mainTable].columns.indexOf('_c_json') >= 0)
						mergeJsonColumns(option.op === 'query'  ?  [result] : result);
				}
				//console.log('query result is:\n%s', JSON.stringify(result, null, 4));
				cb(err, result);
			});
		}
		else  {
			// there are variable columns, we have to reconstruct the query terms to make them SQL only
			var  schema = tableSchema[mainTable],
				 sqlExpr = cloneObj(expr),
				 sqlCmd = {op: 'list', expr: sqlExpr};
				 
			sqlExpr.columns = colInfo.cc;
			//sqlCmd.range = sqlCmd.range || soar.range(1, _queryLimit);

			if (!isSqlFilter)
				sqlExpr.filters = buildSqlFilter(expr.filters, schema.columns);
			//console.log('The adjusted SQL expression is\n%s', JSON.stringify(sqlCmd, null, 2));

			// now we're ready to perform SQL query
			var  listQuery = sqlExpr.filters  ?  inQuery : null;
			
			var  pgIdx = 1,
				 hasMore = true,
				 listSum = [];
			async.whilst(
				function()  {return  hasMore;},
				function(cb)  {
					sqlCmd.range = soar.range(pgIdx++, _queryPageSize);
					//sqlCmd.debug = true;
					soar.execute( sqlCmd, listQuery, function(err, result, count) {
						if (err)  {
							console.log( err.stack );
							return cb(err);
						}
						
						hasMore = result.length === _queryPageSize;
		
						//console.log('result of adjusted SQL:\n%s', JSON.stringify(result, null, 2));
						if (!isSqlCol)
							// add back specified non-sql properties
							mergeSelectedJsonColumns(colInfo, result);
						else
							// user does not specify what columns to be returned.
							// return all columns and json_columns are extracted/added
							mergeJsonColumns(result);
						//console.log('result before final filtering\n%s', JSON.stringify(result, null, 2));
		
						if (!isSqlFilter)  {
							// ok, let's run a JSON-FP program to get the final result
							var  rdQuery = {},
								 reducedF = reduceFilter(mainTable, expr.filters, schema.columns, colInfo.nc, inQuery, rdQuery);
							//console.log('filter is\n%s', JSON.stringify(reducedF, null, 2));
							//console.log('query value is\n%s', JSON.stringify(rdQuery, null, 2));
							result = jsonQ.filter( result, reducedF, rdQuery );
						}
						//console.log('result after final filtering\n%s', JSON.stringify(result, null, 2));
		
						if (colInfo.more.length)  {
							// remove auto-added columns
							var  rmc = colInfo.more;
							result.forEach(function(data) {
								for (var i in rmc)
									delete  data[rmc[i]];
							});
						}
		
						// not using listSum = listSum.concat(result) for potential performance gains
						for (var i in result)
							listSum.push( result[i] );
							
						//console.log('current size: %d, accumulated size: %d, total size: %d, hasMore: %s', result.length, listSum.length, count, hasMore);
						cb();
					});
				},
				function(err)  {
					cb(err, listSum);
				}
			);
		}
	});
}
1366053
function(callback) {
        dataIndex = {};

        var pos = 0;

        enamdictData.split("\n").forEach(function(line) {
            var parts = line.split("|");
            var cleanName = parts[0];
            var romaji = parts[1];

            if (!(cleanName in dataIndex)) {
                dataIndex[cleanName] = pos;
            }

            if (!(romaji in dataIndex)) {
                dataIndex[romaji] = pos;
            }

            // +1 for the \n
            pos += line.length + 1;
        });

        callback(null, this);
    }
924791
function (name, callback) {
    var formattedDate = name.split('-')[0].replace('/', '');
    formattedDate = moment(formattedDate, 'YYYY-MM-DD HH:mm:ss');
    formattedDate = moment(formattedDate).format('YYYY-MM-DD HH:mm:ss');
    var command = util.format('INSERT INTO %s  (name, ran_on) VALUES (\'%s\', \'%s\')', internals.migrationTable, name, formattedDate);
    return this.runSql(command).nodeify(callback);
  }
1328635
function findById(id, cb) {
  db.getClient(function(err, client, done) {
    client.query(SELECT_ID, [id], function(err, r) {
      var result = r && r.rows[0];
      if(!err && !result) err = new exceptions.NotFound();
      if(err) {
        cb(err);
        done(err);
      } else {
        cb(null, result);
        done();
      }
    });
  });
}
163708
def formatDateQuery(context, date_id):
    
    from_date = context.REQUEST.get('%s_fromdate' % date_id, None)
    if from_date:
        from_date = from_date + ' 00:00'
    to_date = context.REQUEST.get('%s_todate' % date_id, None)
    if to_date:
        to_date = to_date + ' 23:59'

    date_query = {}
    if from_date and to_date:
        date_query = {'query': [from_date, to_date],
                      'range': 'min:max'}
    elif from_date or to_date:
        date_query = {'query': from_date or to_date,
                      'range': from_date and 'min' or 'max'}

    return date_query
983867
function (query, callback) {
    if (!callback) {
      callback = query;
      query = null;
    }

    if (typeof query === 'string') {
      query = { aggregateId: query };
    }

    this.store.getLastEvent(query, callback);
  }
1276035
function getDatabase(callback) {
    node.log(`Getting database:\n${dbName}\n`);
    var dbdef = {id : dbName};
        return new Promise((resolve, reject) => {
            client.readDatabase(databaseUrl, (err, result) => {
                if (err) {
                    if (err.code == HttpStatusCodes.NOTFOUND) {
                        client.createDatabase(dbdef, (err, created) => {
                            if (err) reject(err)
                            else resolve(created);
                        });
                    } else {
                        reject(err);
                    }
                } else {
                    resolve(result);
                }
            });
        });
    }
849194
function(db) {
		var methods_uuid = uuid();
		debug.assert(methods_uuid).is('uuid');

		return db.query('CREATE SEQUENCE methods_seq')
			.query(['CREATE TABLE IF NOT EXISTS methods (',
					"	id uuid PRIMARY KEY NOT NULL default uuid_generate_v5('"+methods_uuid+"', nextval('methods_seq'::regclass)::text),",
					'	types_id uuid REFERENCES types,',
					'	type text NOT NULL,',
					'	name text NOT NULL,',
					'	body text NOT NULL,',
					'	meta json NOT NULL,',
					'	active BOOLEAN DEFAULT TRUE,',
					'	created timestamptz NOT NULL default now(),',
					'	modified timestamptz NOT NULL default now(),',
					'	CONSTRAINT active_not_false CHECK(active != false)',
					')'
				].join('\n'))
			.query('ALTER SEQUENCE methods_seq OWNED BY methods.id')
			.query('CREATE INDEX methods_types_id ON methods (types_id)')
			.query('CREATE INDEX methods_types_id_name ON methods (types_id,name)')
			.query('CREATE INDEX methods_type ON methods (type)')
			.query('CREATE INDEX methods_type_name ON methods (type,name)')
			.query('CREATE UNIQUE INDEX ON methods USING btree(types_id, name, active nulls LAST);')
			.query('CREATE TRIGGER methods_modified BEFORE UPDATE ON methods FOR EACH ROW EXECUTE PROCEDURE moddatetime (modified)')
			.query(
				[
	'CREATE OR REPLACE FUNCTION ensure_only_one_active_row_trigger()',
	'RETURNS trigger',
	'AS $function$',
	'BEGIN',
	  // Disable the currently enabled row
	"  IF (TG_OP = 'UPDATE') THEN",
	     // Nothing to do if updating the row currently enabled'
	"    IF (OLD.active = true AND OLD.name = NEW.name) THEN",
	'      RETURN NEW;',
	'    END IF;',
	"    EXECUTE format('UPDATE %I.%I SET active = null WHERE active = true AND name = %L;', TG_TABLE_SCHEMA, TG_TABLE_NAME, OLD.name);",
	"    IF (OLD.name != NEW.name) THEN",
	"      EXECUTE format('UPDATE %I.%I SET active = null WHERE active = true AND name = %L;', TG_TABLE_SCHEMA, TG_TABLE_NAME, NEW.name);",
	'    END IF;',
	'  ELSE',
	"    EXECUTE format('UPDATE %I.%I SET active = null WHERE active = true AND name = %L;', TG_TABLE_SCHEMA, TG_TABLE_NAME, NEW.name);",
	'  END IF;',
	   // Enable new row
	'  NEW.active := true;',
	'  RETURN NEW;',
	'END;',
	'$function$',
	'LANGUAGE plpgsql'
				].join('\n')
			)
			.query('CREATE TRIGGER methods_only_one_active_row'+
				' BEFORE INSERT OR UPDATE OF active ON methods'+
				' FOR EACH ROW WHEN (NEW.active = true)'+
				' EXECUTE PROCEDURE ensure_only_one_active_row_trigger()'
			);
	}