Posts

Showing posts with the label query

Arrange posts by "order" attribute in WordPress

It's just simple as this function: function my_get_posts( $query ) {     if ( is_home() && false == $query->query_vars['suppress_filters'] )                 $query->set('orderby', 'menu_order');                 $query->set('order', 'ASC');      return $query; } Basically, you need to order the posts by menu_order attribute.

Auto merge data from multiple sheets in a google spreadsheet

Image
Ok, so I heard that you want to merge multiple sheets (let's say 2) in a google spreadsheet? That's easy (after hours of trying :"D) Assuming you have 2 sheets as following: Sheet1 Sheet2: In the merged list or master list you need these information: First Name, Last Name, Company, Job Title, Email Address 1. First thing you need to do is to find out a field to use as merge key . It's Email Address in this case. You also should be noticed that there should be no duplicate email addresses. So in order to get all the unique email addresses from 2 sheets, you need to use UNIQUE. But UNIQUE will also give you a blank row (ending row), so FILTER will do the job: =FILTER(UNIQUE({Sheet1!H2:H;Sheet2!E2:E}),NOT(ISBLANK(unique({Sheet1!H2:H;Sheet2!E2:E})))) Notes: Look at how I refer to another sheet (Sheet!H2:H...) You only enter the formula in cell E2 of the Master list, all the email addresses will be filled in other rows automatically. 2. Then ...

MySQL query results to a CSV file

You can use this syntax to output your MySQL query results to a CSV file, for example: SELECT blog_id, path, registered, last_updated      INTO OUTFILE '/tmp/test.csv'      FIELDS TERMINATED BY ','      OPTIONALLY ENCLOSED BY '"'      ESCAPED BY '\\'      LINES TERMINATED BY '\n'  FROM wp_blogs  WHERE path IN ('/105102/','/105095/','/103206/'); Note: It's better to output the file to /tmp directory because mysql user has permission to write there.

Get all MS Active Directory group members's email addresses using python

Using python-ldap you can get pretty much out of your MS Active Directory. For example, the following snippet can help you get all the members of a AD group: Usage: $ python ad_utils.py "your group name"

Query only enabled users in MS Active Directory

You can use this filter to query only enabled users in MS Active Direcotory: (&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))

Using jQuery to sort table by a pseudo column

In many cases, the web engine that generates data tables (html) is close-sourced and you cannot sort those tables. It is not because the engine does not have a mechanism to sort data. It's just that its behaviors does not satisfy your need. For example, the PowerSchool customization engine. In PowerSchool, I can output a table of lunch balance information of a student using this template syntax: ~[tlist;gldetail;studentid=~(curstudid);alternatecolor;sortcmd;date, > ,time, > ;]   <td>~(date)</td>   <td>~(time)</td>   <td>~(neteffect)</td>   <td>~(runninglunchtotalbalance.students)</td>   <td colspan="3">~(transdescription)</td> Did you see the >  (greater than) sign? It says that the table will sort by the date and time columns in ascending order. What I want is to make it sort date and time in descending order. So I tried to replace the > with the < (less than) ho...

Querying Oracle to get students that do not have parent accounts in PowerSchool

You can use this SQL query to get all the students that do not have parent account linked to them in PowerSchool: SELECT s.LASTFIRST, s.STUDENT_NUMBER, s.FAMILY_IDENT, s.FATHER,                                           u.SSIS_FATHER_EMAIL, s.MOTHER, u.SSIS_MOTHER_EMAIL FROM students s INNER JOIN u_studentsuserfields u ON s.DCID = u.STUDENTSDCID WHERE s.DCID not in (SELECT g.STUDENTSDCID FROM guardianstudent g)        AND s.ENROLL_STATUS = 0;

Showing student custom field data in classattendance page in PowerSchool Teachers

I was trying to display some custom field data (I will take ssis_student_nickname as an example in this article) in the classattendance.html page in PowerSchool Teachers. But, to be honest, I'm not sure about the customization syntax of PowerSchool. I couldn't make it work with this following syntax: ~([01]ssis_student_nickname) or ~([Students.U_STUDENTSUSERFIELDS]ssis_student_nickname) As fas as I acknowledged, the classattendance page accessing the attendance database using some javascript. So, in the end, I have to do some hack to display the custom field in that page. Here is the details: 1. Add an additional column in the page, and name it: ...              <th align="left" class="cvDemarcation">~[text]psx.html.teachers.classattendance.students[/text]</th>             <th class="cvDemarcation">Student Nick Name</th> ...             <tr class="s...

Get all users in moodle (2.x)

To get all users in moodle using the API(s), you can use the following snippet: #! /user/bin/php <?php define('CLI_SCRIPT', true); require_once('config.php'); // if you call DB inside a function, you'll need: // global $DB; $allusers = $DB->get_records('user'); foreach($allusers as $user) {      echo "User id $user->id is $user->username\n"; } ?>

PowerSchool - Query Oracle DB to get a list of students with their siblings

In Oracle database of PowerSchool, to get a list of students with their siblings who also students, you can use the following query: The important parts of the above query are: * Group the students of a same family based on the FAMILY_IDENT column of the STUDENTS table: SELECT STUDENTS.FAMILY_IDENT AS FAMILY_IDENT, '<ul>' || listagg('<li>' || STUDENTS.LASTFIRST || ' (' || STUDENTS.GRADE_LEVEL || ')' || ',</li>', '')  WITHIN GROUP ( ORDER BY STUDENTS.GRADE_LEVEL DESC, Upper(Trim(STUDENTS.LASTFIRST)) ) || '</ul>' AS SIBLINGS FROM STUDENTS WHERE STUDENTS.ENROLL_STATUS = 0 GROUP BY STUDENTS.FAMILY_IDENT The result will be something like this: ------------------------------------------------------------------------------------------------------- | FAMILY_IDENT | SIBLINGS                                                 ...

SQLAlchemy - Get and delete object

These are some utility methods to make a query with SQLAlchemy: I gonna use the MyDatabaseConnector class from the previous blog post : db =  MyDatabaseConnector () * Get object: def get _obj (db, pk): session = db.get_session() try: obj = session.query(MyObjModel).get(pk) except: print "Object not found" finally: session.commit() db.close() * Delete object: def delete_obj (db, pk): session = db.get_session() try: obj = session.query(MyObjModel).get(pk) except: print "Object not found" else: session.delete(obj) finally: session.commit() db.close() Reference:   http://docs.sqlalchemy.org/en/rel_0_9/orm/query.html

SQLAlchemy - DetachedInstanceError

I got this error when trying to retrieve all the database records in a table: DetachedInstanceError: Instance <CoursesMerger at 0x37fa950> is not bound to a Session; attribute refresh operation cannot proceed and this is how I query the database: rs = session.query(MyTable).all() To avoid this error, remember to set expire_on_commit = False when initialize the session: from sqlalchemy import * from sqlalchemy.orm import * DB_HOST = 'localhost' DBMS = 'mysql' DB_PORT = '3306' DB_NAME = 'mydatabase' DB_USER = 'myuser' DB_PWD = 'mypassword' DB_ENGINE_URL = '%s://%s:%s@%s:%s/%s' % (DBMS, DB_USER, DB_PWD, DB_HOST,  DB_PORT, DB_NAME) class MyDatabaseConnector (object): engine = None Session = None def __init__ (self): self.connect() def connect (self): if self.engine is None: self.engine = create_engine(DB_ENGINE_URL, echo=False, \ pool_size = 100, pool_recycle=3600) if se...

Google App Engine SDK for Python - Using datastore query at local for testing

When I tried to do some test of datastore query in the python console: query = MyModel.all() query.filter("username =", "myusername") result = query.get( ) I got this error" BadArgumentError: app must not be empty. After googling around, I found this solution: before execute the query, run these following commands: import os os.environ['APPLICATION_ID'] = 'dangtrinhnt'                                datastore_file = '/dev/null' from google.appengine.api import apiproxy_stub_map,datastore_file_stub apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() stub = datastore_file_stub.DatastoreFileStub('dangtrinhnt', datastore_file, '/') apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub) Then, execute any query I want, for example the query at the beginning of this blog post (the blue lines). Refere...

PowerSchool - Get data in a custom page (HTML)

PowerSchool is a huge student information system which is used worldwide in International Schools. It's not open-source but It provides us a lot of features. One of them is pages customization. + In a custom page, you can make a SQL query to get the data. For example: to get all the teachers (staffstatus=1) of Elementary School (schoolid=3) which are still active (status=1), and order the result by last name: ~[tlist_sql;     SELECT DISTINCT t.Last_Name, t.First_Name     FROM Users t, SchoolStaff ss     WHERE t.DCID=ss.Users_DCID         AND ss.StaffStatus=1         AND ss.Status=1         AND ss.SchoolID=3     ORDER BY lower(t.Last_Name) ]     <p>~(t.Last_Name), ~(t.First_Name)</p> [/tlist_sql] (PowerSchool v7.8.2) PowerSchool's official website:  http://www.pearsonschoolsystems.com/products/powerschool/

Django - Get a list of users of a certain group

To get a list of users of a certain group (let's call it 'MyGroup'): from django.contrib.auth import User, Group users = User.objects.filter(groups=Group.objects.get(name='MyGroup')) or: users = User.objects.filter(groups__name__in=['MyGroup'])

ORACLE - Get updatable columns of a table

Image
If you want check if a table in your Oracle database can be update, insert or delete, you can use the following query: SELECT * FROM USER_UPDATABLE_COLUMNS WHERE TABLE_NAME='STUDENTS'; And you'll get something like this: