Beispiel #1
0
def set_mark(request):
    from templatetags.marks_chart import get_mark
    pupil = get_object_or_404(Pupil,
        id = int(request.GET.get('pupil', 0)),
        grade = request.user.current_grade)
    lesson = get_object_or_404(Lesson,
        id = int(request.GET.get('lesson', 0)),
        teacher = request.user)
    mark = unicode(request.GET.get('mark', 0)).lower()

    Mark.objects.filter(pupil = pupil, lesson = lesson).delete()
    m = Mark(pupil = pupil, lesson = lesson)
    tr_id = 'p-%d-%d' % (pupil.id, lesson.id)
    if mark not in ['1', '2', '3', '4', '5', 'n', u'н', '', u'б', u'b']:
        return HttpResponse(demjson.encode({'id': tr_id, 'mark': 'no'}))
    if mark == '':
        return HttpResponse(demjson.encode({'id': tr_id, 'mark': ''}))
    if mark in [u'n', u'н', u'b', u'б']:
        m.absent = True
        if mark in [u'б', u'b']:
            m.sick = True
    else:
        m.mark = int(mark)
    m.save()
    pupil.get_groups()
    if lesson.attendance and lesson.attendance.subject_id in pupil.groups and lesson.attendance.group != pupil.groups[lesson.attendance.subject_id].value:
        mail_admins("lesson cognetive dissonans", "Lesson id#%d, mark id#%d" % (lesson.id, m.id))
    return HttpResponse(demjson.encode({'id': tr_id,
                                        'mark': get_mark(pupil, [lesson,]),
                                        'mark_value': str(m).strip(),
                                        'mark_type': m.get_type()
    }, encoding='utf8'))
Beispiel #2
0
def carrier(request, carrier):
	"""Carrier method (carrier): gets general info."""
	username = None
	password = None

	if request.GET.has_key("username"):
		username = request.GET["username"]
	if request.GET.has_key("password"):
		password = request.GET["password"]

	carriers = Consumo.carrier_classes()
	if not carriers.has_key(carrier):
		return HttpResponseNotFound("<h1>Unknown carrier</h1>")
	
	obj = carriers[carrier][1]

	try:
		server = obj(username, password)
		server.parse()

		return HttpResponse(demjson.encode(server.data()),
			mimetype="application/json")
	except Consumo.ConsumoException, e:
		# FIXME: better error handling (authentication!).
		return HttpResponse(demjson.encode(e), status = 500)
Beispiel #3
0
def getfourgpackageqry(user_id): #4G套餐变更查询
    method = 'com.aop.method.fourgpackageqry'
    config = {'targetproducttype':'01'}

    result = getuinfo.getresult(method,user_id,**config)

    print demjson.encode(result)
Beispiel #4
0
 def __getDataDemoFromString__(self,jsonStr): 
     self.crawlerTime = datetime.datetime.now()
     dataDemo = jsonDataDemo()
     items =[]
     variables =[]
     text = demjson.decode(jsonStr)
     dataDemo.__setTableName__('tableName',text.get('tableName'))
     dataDemo.__setPrimaryKey__('primaryKey',text.get('primaryKey'))
     # replace DataTime to Now
     startUrl = text.get('URL')
     startUrl = startUrl.replace("##year", str(self.crawlerTime.year))
     startUrl = startUrl.replace("##month", str(self.crawlerTime.month))
     startUrl = startUrl.replace("##day", str(self.crawlerTime.day))
     startUrl = startUrl.replace("##hour", str(self.crawlerTime.hour))
     startUrl = startUrl.replace("##minute", str(self.crawlerTime.minute))
     startUrl = startUrl.replace("##second", str(self.crawlerTime.second))
     
     dataDemo.__setURL__('URL',startUrl)
     
     dataDemo.__setTask__('task',text.get('task'))
     for item in text.get('items'):
         items.append(demjson.decode(demjson.encode(item)))
         dataDemo.__setItems__('items',items)
     for variable in text.get('variables'):
         variables.append(demjson.decode(demjson.encode(variable)))
     dataDemo.__setVariables__('variables',variables)
     
     chirdrenObjs = []
     for chirdren in text.get('chirdren'):
         chirdrenJson = json.dumps(chirdren)
         chirdrenObj = self.__getDataDemoFromString__(chirdrenJson)
         chirdrenObjs.append(chirdrenObj)
     dataDemo.__setChirdren__(chirdrenObjs)
     return dataDemo
        def extractData(map,doc):

            data = {}

            for k,v in map.iteritems():

                if isinstance(v,dict):
                    if 'each' not in v:
                        v = ast.literal_eval(demjson.encode(v))
                        v['each'] = "div[contains(@class,'assignment')]"
                        v = demjson.decode(json.dumps(v))
                    
                    val = doc.xpath(v['each'])
                    del v['each']
                    data[k] = []
            
                    for doc in val:    data[k].append( extractData(v,doc) ) 

                else:  
                    key = ast.literal_eval(demjson.encode(k))
                    val = doc.xpath(v)[0].strip()
                    if key not in PIPELINES.keys():    data[k] = val
                    else:    
                        data[k] = PIPELINES.get(key)(val) 
                        
                        if key == 'course':  data['teacher'] = PIPELINES.get('teacher')(val)
                        #elif key == 'grade': data['comment'] = PIPELINES.get('grade')(val, True)

            return data
Beispiel #6
0
    def _snarf_names_from_parse_res (self, pr):
        n = pr['firstname']
        if n and n != 'nil':
            self.set_firstname(unesc_str(chompq(n)))

        n = pr['lastname']
        if n and n != 'nil':
            self.set_lastname(unesc_str(chompq(n)))

        try:
            affix = pr['affix']
            if affix and affix != 'nil':
                str_re = self.get_store().get_str_re()
                affix = re.findall(str_re, affix)
                self.set_suffix(unesc_str(chompq(affix[0])))

                if len(affix) > 1:
                    aff = demjson.encode([unesc_str(chompq(x)) for x in affix[1:]])
                    ## FIXME: Do we need to escape the quotes in json encoding
                    ## as in the except clause?
                    self.add_custom('affix', aff)
        except KeyError, e:
            ## FIXME: There should be a better way to handle the format
            ## differences.... for now we'll put up with the hacks
            affix = self.get_custom('affix')

            if affix:
                affix = demjson.decode(affix)
                if len(affix) > 0:
                    self.set_suffix(affix[0])
                    affix = affix[1:]
                    if len(affix) > 0:
                        aff = demjson.encode(affix)
                        self.add_custom('affix', aff)
Beispiel #7
0
    def _snarf_names_from_parse_res (self, pr):
        n = pr['firstname']
        if n and n != 'nil':
            self.set_firstname(chompq(n))

        n = pr['lastname']
        if n and n != 'nil':
            self.set_lastname(chompq(n))

        try:
            affix = pr['affix']
            if affix and affix != 'nil':
                str_re = self.get_store().get_str_re()
                affix = re.findall(str_re, affix)
                self.set_suffix(chompq(affix[0]))

                if len(affix) > 1:
                    aff = demjson.encode([chompq(x) for x in affix[1:]])
                    self.add_custom('affix', aff)
        except KeyError, e:
            ## FIXME: There should be a better way to handle the format
            ## differences.... for now we'll put up with the hacks
            affix = self.get_custom('affix')

            if affix:
                affix = demjson.decode(affix)
                if len(affix) > 0:
                    self.set_suffix(affix[0])
                    affix = affix[1:]
                    if len(affix) > 0:
                        aff = demjson.encode(affix)
                        aff = string.replace(aff, '"', r'\"')
                        self.add_custom('affix', aff)
Beispiel #8
0
 def DELETE(self):
      input_data = web.data()
      data = urlparse.parse_qs(input_data)
      v_ct_fids = db.query("select distinct t.source_fid,t.target_fid,t.type_fid,t.owner,t.family_id from t_ci_relation t where t.family_id=$fid and t.endtime=$endtime",vars={'endtime':ENDTIME,'fid':data['fid'][0]})
      json_en = demjson.encode(v_ct_fids)
      json_de = demjson.decode(json_en)
      v_ct_fid_num = len(json_de)
      if v_ct_fid_num == 0:
          return 2 #there is no records to delete in table T_CI_RELATION
      elif v_ct_fid_num > 1:
          return 3 #there are more than one records to delete in table T_CI_RELATION
      
      v_curtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
      #Notice;if the relation is composition and the target ci exists, we should delete the relative ci
      v_target_fids = db.query("select t.family_id, crt.relation from t_ci t, t_ci_relation_type crt where t.family_id=$target_fid and t.endtime=$endtime and crt.family_id=$type_fid and crt.endtime=$endtime and crt.relation='COMPOSITION'",vars={'endtime':ENDTIME,'target_fid':json_de[0]['TARGET_FID'],'type_fid':json_de[0]['TYPE_FID']})
      target_json_en = demjson.encode(v_target_fids)
      target_json_de = demjson.decode(target_json_en)
      v_target_num = len(target_json_de)
      if v_target_num <> 0:
          #delete the existed ci. It will also delete the relative ci_attribute and ci_relation.
          n = webci.fn_delete_ci(json_de[0]['TARGET_FID'], v_curtime, data['change_log'][0])
      else:
          #delete t_ci_relation
          n = fn_delete_cirela(data['fid'][0],v_curtime,data['change_log'][0])
      
      return n
Beispiel #9
0
	def extractNouns(text):
		taggedWords = pos_tag(text.split())
		l = [word for word,pos in taggedWords if pos == 'NN']
		outRes = dict((str(i), l[i]) for i in range(0,len(l)))
		if bool(outRes):
			print demjson.encode(outRes)
		else:
			return False
Beispiel #10
0
 def testEncodeStringLike(self):
     import UserString
     class LikeString(UserString.UserString):
         pass
     mystring = LikeString('hello')
     self.assertEqual(demjson.encode(mystring), '"hello"')
     mystring = LikeString(u'hi\u2012there')
     self.assertEqual(demjson.encode(mystring, escape_unicode=True, encoding='utf-8'), r'"hi\u2012there"')
Beispiel #11
0
    def logActive(self, record, msgvalue):

        msgdict = {}
        for k, v in msgvalue.items():
            msgdict[k] = unicode(v) if type(v) not in (str, unicode, float, bool, int) else v

        self.log_file_pointer.write(
            "%s: %s => %s\n"
            % (record.getID(), demjson.encode(msgdict), demjson.encode(record.getValues(class_to_string=True)))
        )
Beispiel #12
0
def main(argv):
    from optparse import OptionParser

    parser = OptionParser()
    (options, args) = parser.parse_args()
    fname = args[0]
    raw_str = open(fname).read()
    py_obj = yaml.load(raw_str)
    pprint.pprint(py_obj)
    print demjson.encode(py_obj)

    pass
Beispiel #13
0
 def testEncodeStringRawUnicode(self):
     self.assertEqual(demjson.encode(u'\u00e0', escape_unicode=False, encoding='utf-8'),
                      '"\xc3\xa0"')
     self.assertEqual(demjson.encode(u'\u00e0', escape_unicode=False, encoding='ucs4le'),
                      '"\x00\x00\x00\xe0\x00\x00\x00"\x00\x00\x00')
     self.assertEqual(demjson.encode(u'\u00e0', escape_unicode=False, encoding='ucs4be'),
                      '\x00\x00\x00"\x00\x00\x00\xe0\x00\x00\x00"')
     self.assertEqual(demjson.encode(u'\u00e0', escape_unicode=False, encoding='utf-32be'),
                      '\x00\x00\x00"\x00\x00\x00\xe0\x00\x00\x00"')
     self.assert_(demjson.encode(u'\u00e0', escape_unicode=False, encoding='ucs4')
                  in ['\x00\x00\xfe\xff\x00\x00\x00"\x00\x00\x00\xe0\x00\x00\x00"',
                      '\xff\xfe\x00\x00"\x00\x00\x00\xe0\x00\x00\x00"\x00\x00\x00'] )
Beispiel #14
0
def fourgpackagechg(user_id): #4G套餐变更
    method = 'com.aop.method.fourgpackagechg'
    config = {'busitype':'24',
              'targetproduct':
                  [{"productid":"99999830",
                   "productname":'76元基本套餐',
                   "producttype":"01"}],
              'busiorder':'BUSI001602291525318960109881'}


    result = getuinfo.getchgresult(method,user_id,**config)

    print demjson.encode(result)
Beispiel #15
0
 def craw(self, root):
     for i in range(1, 6):
         url = root + '?page=' + str(i)
         self.urls.add_new_url(url)
     while self.urls.is_empty():
         try:
             new_url = self.urls.get_url()
             logging.info(new_url)
             html_content = self.htmldownload.download_html(new_url)
             data = self.parse.parse(html_content)
             self.data_output.collect_data(data)
         except:
             pass
     print demjson.encode(self.data_output.datas)
  def send(self, sendUri, message, correlation_id, group_id):
    mng = Messenger()
    mng.start()

    msg = Message()
    msg.address = sendUri
    msg.correlation_id = correlation_id
    msg.group_id = group_id
    msg.body = unicode(demjson.encode(message))
    mng.put(msg)

    mng.send()
    print "sent:" + demjson.encode(message)
    mng.stop()
    return
Beispiel #17
0
def main():
	con = mdb.connect(host='localhost', user='******',passwd='root',db='scrapy')
	cur = con.cursor()
	sql = "select * from lens"
	cur.execute(sql)
	results = cur.fetchall()
	# p = re.compile(r'<tr>.*?price.*?(\d+).*?Aperture')
	p1 = re.compile(r'<tr>(.*?)</tr>')
	p2 = re.compile(r'')
	items = []
	for result in results:
		item = {}
		item['name'] = result[0]
		item['image'] = result[1]
		item['url'] = result[2]
		tables = demjson.decode(result[3])
		for table in tables:
			tree = etree.HTML(table) 
			tr_nodes = tree.xpath("//tr")
			for tr_node in tr_nodes:
				kv = tr_node.xpath("./td/text()")
				if len(kv) == 2:
					item[kv[0]] = kv[1].replace(u'\xa0', u' ').encode("ascii").strip()
		print item
		sql = "INSERT INTO `lens_kv`(`name`, `kv`) VALUES(%s,%s)"
		cur.execute(sql,(result[0],demjson.encode(item)))
		
	con.close()
Beispiel #18
0
 def event(self, recipients, body, json=True, retry=True):
     if not self.connected:
         self.connect()
     try:
         if json:
             body = encode(body)
         if not self.socket:
             raise IOError("ConnectionLost")
         try:
             self.id += 1
             self.sendline(self.version)
             self.sendline('Event')
             self.sendline('id: %s' % self.id)
             for recipient in recipients:
                 self.sendline('recipient: %s' % (str(recipient)))
             self.sendline('length: %s' % len(body))
             self.sendline()
             self.socket.send(body)
             return self.read_response()
         except socket.error:
             # self.disconnect()
             raise IOError("ConnectionLost")
     except IOError, e:
         if retry:
             self.reconnect()
             self.event(recipients, body, json, False)
         else:
             raise
Beispiel #19
0
 def on_key_release(self, symbol, modifiers):
   if self.client:
     if symbol == key.LEFT:
       self.client.action("stop_moving_left")
     elif symbol == key.RIGHT:
       self.client.action("stop_moving_right")
     
     elif symbol == key.Z:
       self.client.action("stop_jump")
     
     elif symbol == key.X:
       self.client.action("stop_fire")
       
     elif symbol == key.L:
       self.client.action("stop_lol")
     
     
     elif symbol == key.F:
       self.set_fullscreen(not self.fullscreen)
     
     elif symbol == key.S:
       layerfile = pyglet.resource.file('levels/foolevel/main.layer', 'r')
       old = demjson.decode(layerfile.read())
       layerfile.close()
     
       old["map"] = self.server.game.level.main_layer.tilemap.map
     
       new = demjson.encode(old)
     
     
       layerfile = pyglet.resource.file('levels/foolevel/main.layer', 'w')
       layerfile.write(new)
       layerfile.close()
       print "sparade!"
Beispiel #20
0
    def saveTicket(self, project, category, status, severity, name, description, files=[], **kwargs):
        """Save newly created ticket into the database"""
        con = getConnection()
        checkProjectCategoryLogin(con, project, category)
        cursor = con.cursor()

        categoryCode = {'bug' : 1, 'feature' : 2}
        
        # if ticket is created with status "being taken care of" or "solved", then the user is an admin
        # he is considered as the one who solved or is taking care of the issue.
        idMaintainer = 0
        if int(status) == 1 or int(status) == 2 :
            idMaintainer = cherrypy.session.get(str(project)+'_idUser')
        
        # saving ticket and getting the id of that ticket
        query = """
        INSERT INTO Ticket(project, category, name, description, status, severity, creator, maintainer)
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s);
        SELECT lastval();
        """
        cursor.execute(query, (
            cherrypy.session.get(str(project)+'_projectCode'),
            categoryCode[category],
            name,
            formatText(description),
            status,
            severity,
            cherrypy.session.get(str(project)+'_idUser'),
            idMaintainer)
        )
        
        # id of that last ticket created
        id = int(cursor.fetchone()[0])
        
        # relativeID of that last ticket
        query = """
        SELECT relativeID FROM Ticket WHERE id = %s"""
        cursor.execute(query, (id, ))
        relativeID = int(cursor.fetchone()[0])
        
        # attaching files to the ticket
        query = """
        UPDATE File
        SET ticket = %s
        WHERE id = %s"""
        args = []
        
        if type(files) == type('dummy'):
            args.append((id, files))
        elif type(files) == type(['dummy', 'dummy']):        
            for fileID in files :
                args.append( (id, fileID) )
        cursor.executemany(query, args)
        con.commit()
        
        con.close()
        
        data = {'error_code': 0,
                'relativeID': relativeID};
        return demjson.encode(data);
def jdumps(obj, encoding='utf-8'):
    # Do 'serialize' test at some point for other classes
    global demjson
    if demjson:
        return demjson.encode(obj)
    else:
        return json.dumps(obj, encoding=encoding)
Beispiel #22
0
 def POST(self):
     shift_list = shift.Shift().shift_all_list(None)
     lists=[]
     for shifts in shift_list:
         classes_list=classes.Classes().classes_get_csid_list(shifts.csid)
         classesdict = {}
         classeslist=[]
         for classessub in classes_list:
             classesdict.setdefault('ccid',classessub.ccid)
             classesdict.setdefault('classesname',classessub.classesname)
             classeslist.append(classesdict)
             classesdict={}
         shifts.setdefault('classes',classeslist)
         shiftsdict = {}
         shiftsdict.setdefault('shiftyear',shifts.shiftyear)
         shiftsdict.setdefault('shiftname',shifts.shiftname)
         shiftsdict.setdefault('csid',shifts.csid)
         shiftsdict.setdefault('shifttype',shifts.shifttype)
         shiftsdict.setdefault('classes',shifts.classes)
         lists.append(shiftsdict)
     path='./static/json/menu.json'
     f=open(path,'w')
     f.write(demjson.encode(lists))
     f.close()
     fileexist=os.path.exists(path)
     flag=False
     if fileexist==True:
         msg=up.upload(path)
     else:
          msg='文件不存在,创建失败'
     msgdict = {'success':flag,'msg':msg}
     msgjson = json.dumps(msgdict,sort_keys=True)
     return msgjson
Beispiel #23
0
 def POST(self):
     shift_list = shift.Shift().shift_all_list(1)
     lists=[]
     for shifts in shift_list:
         shiftsdict = {}
         shiftsdict.setdefault('shiftyear',shifts.shiftyear)
         shiftsdict.setdefault('shiftname',shifts.shiftname)
         shiftsdict.setdefault('csid',shifts.csid)
         shiftsdict.setdefault('shifttype',shifts.shifttype)
         shiftsdict.setdefault('classtime',shifts.classtime)
         shiftsdict.setdefault('classplace',shifts.classplace)
         shiftsdict.setdefault('teachermobile',shifts.teachermobile)
         shiftsdict.setdefault('teacher',shifts.username)
         shiftsdict.setdefault('busroute',shifts.busroute)
         shiftsdict.setdefault('createtime',shifts.createtime)
         lists.append(shiftsdict)
     path='./static/json/shift.json'
     f=open(path,'w')
     f.write(demjson.encode(lists))
     f.close()
     fileexist=os.path.exists(path)
     flag=False
     if fileexist==True:
         msg=up.upload(path)
     else:
          msg='文件不存在,创建失败'
     msgdict = {'success':flag,'msg':msg}
     msgjson = json.dumps(msgdict,sort_keys=True)
     return msgjson
Beispiel #24
0
def getDataPredict(start, end):
    engine = create_engine('mysql://*****:*****@zhuke1993.vicp.cc:3306/stock_predict?charset=utf8')
    sql = "select date, close from stock_data_predict where date between '%s' and '%s' order by date asc" % (start, end)
    DB_Session = sessionmaker(bind=engine)
    session = DB_Session()
    list = session.execute(sql).fetchall()
    return demjson.encode(list)
Beispiel #25
0
    def dumps(self, data, compactly=False):
        """
        Wrapper for json library. Dump dict to a json string

        :param dict data: Python dict to convert to json
        :param compactly: set to True to return unindented JSON (no newlines
                          between key/values),

        :returns: Converted json string
        :rtype: str

        """

        # We start with the default python json library to encode as
        # it is *MUCH* faster than demjson. However, if we run into issues
        # with being unable to serialize, we are going to use demjson
        # since it handles such data much better.

        try:
            if compactly is True:
                indent = None
            else:
                indent = 4
            return json.dumps(data, indent=indent)
        except TypeError:
            return demjson.encode(data, encode_bytes=str, compactly=compactly)
Beispiel #26
0
def preProcess():
    filepath1 = "/Users/windwild/sina_data/sinavip.txt"
    filepath2 = "/Users/windwild/sina_data/user_rel.csv"
    filepath3 = "/Users/windwild/Google Drive/CUHK/sina_data/json_text"
    filepath4 = "/Users/windwild/sina_data/done.txt"
    
    
    
    fp = open(filepath2,"r")
    fp2 = open(filepath4,"w")
    fp2.write('')
    fp2.close()
    fp2 = open(filepath4,"w+")
    line = fp.readline()
    array_list = {}
    for i in range(0,3000000):
        array_list['fui'] = []
        try:
            line = fp.readline()
        except:
            break
        line_arr = line.split('"')
        uid = line_arr[0][:-1]
        line = line_arr[1]
        line = line.replace("u'","'")
        items = demjson.decode(line)
        for key in items:
            array_list[key] = items[key]
        json_string = demjson.encode(array_list['fui'])
        fp2.write("%s,%s\n"%(uid,json_string))
        if(i%500==0):
            print i
        
    fp.close()
    fp2.close()
Beispiel #27
0
def save_result(uid,result_arr):
    con = mdb.connect('localhost','root','root','weibo_ranker')
    cur = con.cursor()
    sql = "INSERT INTO results_buffer VALUES(%d,'%s')"%(uid,demjson.encode(result_arr))
    cur.execute(sql)
    con.commit()
    con.close()
Beispiel #28
0
 def test_save_integers(self):
   d = ['A', 'B', 'C']
   self.save_and_check(
     {'model-codes': d}
   , 'models'
   , [(encode(d),)]
   )
    def index(self):
        query = request.params['query']

        connection = httplib.HTTPConnection('www.last.fm')
        jsonrequest = connection.request('GET', '/search/autocomplete?q=%s' % urllib.quote(query))
        jsonresponse = connection.getresponse()

        documents = demjson.decode(jsonresponse.read())['response']['docs']

        artists = []
        artists_found = set([])

        for document in documents:
		if not document.has_key('artist'):
			continue

                artist = document['artist']
                if not artist in artists_found:
                        artists.append({'id': artist, 'value': artist})
                        artists_found.add(artist)

        result = {
            'query': query,
            'suggestions': artists
        }

        return demjson.encode(result)

        return query
Beispiel #30
0
def json_approved_budgets(request):
  factor = authenticate(request, VALID_FACTORS)
  admin = is_admin_factor(factor)

  if request.method != 'GET':
    raise Http400()
  
  num_per_page = int(request.GET.get('num',20))
  budgets = Budget.objects.select_related().order_by('-created_on').filter(approved = 1)
  paginator = Paginator(budgets, num_per_page)
  page_num = int(request.GET.get('page',1))
  if page_num == -1:
    page = paginator.page(paginator.num_pages)
  else:
    page = paginator.page(page_num)
  
  object_list = page.object_list
  resultant = []
  for b in object_list:
    resultant.append({
        'id' : b.id,
        'signator' : unicode(b.organization.signator),
        'organization' : unicode(b.organization.name),
        'requested' : unicode("$%.2f" % b.requested),
        'allocated' : unicode("$%.2f" % b.allocated),
        'created' : unicode(b.created_on.strftime("%d-%m-%Y")),
        'modified' : unicode(b.modified_on.strftime("%d-%m-%Y"))
        })
  
  return HttpResponse(demjson.encode(resultant), mimetype="text/javascript")
 def hide_app(cls):
     """
     hide flow launcher
     """
     print(
         demjson.encode({
             "method": "Flow.Launcher.HideApp",
             "parameters": []
         }))
Beispiel #32
0
Datei: base.py Projekt: zz38/mETL
    def logActive(self, ftr, record, is_filtered):

        if not is_filtered:
            return

        self.log_file_pointer.write(
            '%s: %s\n' %
            (record.getID(),
             demjson.encode(record.getValues(class_to_string=True))))
 def close_app(cls):
     """
     close flow launcher
     """
     print(
         demjson.encode({
             "method": "Flow.Launcher.CloseApp",
             "parameters": []
         }))
 def show_app(cls):
     """
     show flow launcher
     """
     print(
         demjson.encode({
             "method": "Flow.Launcher.ShowApp",
             "parameters": []
         }))
Beispiel #35
0
    def __init__(self, itemJson, api):
        """
        Constructor of Item class:

        :param itemJson: Json string that describes the item
        :type itemJson: Json
        """
        self._props = json.loads(demjson.encode(itemJson))
        self.api = api
 def shell_run(cls, cmd):
     """
     run shell commands
     """
     print(
         demjson.encode({
             "method": "Flow.Launcher.ShellRun",
             "parameters": [cmd]
         }))
Beispiel #37
0
	def export(self, filename, append=True):
		import demjson
		js = demjson.encode(self.data)
		if filename.split('.')[-1] != '.json':
			filename += '.json'
		mode = 'a' if append else 'w'
		with open(filename, mode) as f:
			f.write(js)
		f.close()
Beispiel #38
0
    def find_frequent(self, support, min_set_size=2, max_set_size=math.inf):

        assert self.data is not None and self.out is not None, "data or out path is None"
        self.sigma = support
        self.min_set = min_set_size
        self.max_set = max_set_size
        self.frequent[1] = self._generate_data()
        self.associative = {}
        temp = defaultdict(Counter)

        k = 2
        # there must be at least k itemsets of size k-1 already found to
        # be frequent for there to be any frequent k-itemsets
        while len(self.frequent[k - 1]) >= k and k <= self.max_set:

            for i in range(len(self.previous)):
                # find per-transaction candidates of size k-1. groups generated
                # on previous pass, and checked against frequent itemsets now
                k_minus_1 = [
                    group for group in self.previous[i]
                    if group in self.frequent[k - 1]
                ]

                # order is cruicial: items in tuples are sorted here, while
                # ordering of tuples was established on the first pass
                cand = [
                    tuple(sorted(set(x).union(y))) for x in k_minus_1
                    for y in k_minus_1 if x < y and x[:-1] == y[:-1]
                ]

                # only those candidates need to be considered on the next pass
                self.previous[i] = cand

                # increment counts
                for group in cand:
                    self.frequent[k][group] += 1

            # drop infrequent keys
            self.frequent[k] = self._drop_infrequent(k)

            k += 1

        for key in self.frequent.keys():
            if self.min_set <= key <= self.max_set:
                for group, k in self.frequent[key].items():
                    for item_x in group:
                        other = tuple(
                            sorted([
                                item for item in group if not item == item_x
                            ]))
                        temp[item_x][other] += k / self.frequent[len(group)
                                                                 - 1][other]
        for k, v in temp.items():
            self.associative[k] = sorted(v, key=v.get, reverse=True)
        with open(self.out, "w") as f:
            f.write(demjson.encode(self.associative, strict=False))
        return
 def reload_plugins(cls):
     """
     reload all flow launcher plugins
     """
     print(
         demjson.encode({
             "method": "Flow.Launcher.ReloadPlugins",
             "parameters": []
         }))
Beispiel #40
0
	def Rewritemsg(self, line):
		switch = {
			"txt": lambda line:self.__txtwrite(line, 'w'),
			"csv": lambda line:self.__csvwrite(line, 'w'),
			"json": lambda line:self.__jsonwrite('['+demjson.encode(line)+']', 'w')
		}
		try:
			switch[self.type](line)
		except KeyError as e:
			pass
Beispiel #41
0
def ws_message(message):

    json = message.content['text']
    data = demjson.decode(json)
    #确认消息只需记录一下,不用返回
    if data['type'] == 0:
        process_request.process(json)
    else:
        message.reply_channel.send(demjson.encode({'type': '0','request_id':data['request_id']}))
        process_request.process(message,data)
Beispiel #42
0
def sheriff_vote(r_id, u_id, o_id):
    glob.room_sheriff_select[r_id][u_id] = o_id
    glob.room_select_num[r_id] = glob.room_select_num[r_id] + 1

    if glob.room_select_num[r_id] == glob.room_alive_num[r_id]:

        list = glob.room_sheriff_select[r_id]
        v = list.values()
        temp = Counter(v).most_common(2)
        #平票
        if (len(temp) > 1 and temp[0][1] == temp[1][1]):
            message = {
                'type': '9',
                'room_request_id': str(glob.room_request_id[r_id]),
                'result': 'false',
                'sheriff_id': '-1',
                'list': list
            }
            json = demjson.encode(message)
            send_message.send(r_id, json)
        else:
            result = Counter(v).most_common(1)[0][0]
            glob.room_sheriff_id[r_id] = result
            room = RoomInfo.objects.get(room_id=r_id)
            room.sheriff_id = o_id
            room.save()
            message = {
                'type': '9',
                'room_request_id': str(glob.room_request_id[r_id]),
                'result': 'true',
                'sheriff_id': str(result),
                'list': list
            }
            json = demjson.encode(message)
            send_message.send(r_id, json)
            room_state_change.change(0, r_id)

        #glob.room_request_content[r_id].append(json)
        glob.room_select_num[r_id] = 0
        glob.room_sheriff_list[r_id] = []
        glob.room_sheriff_select[r_id] = {}

    return
def attendence_mark():
    db = Db()
    lid = request.form['lid']
    workid = request.form['work_id']
    q = db.insert("insert into attendance values('','" + str(lid) + "','" +
                  str(workid) + "',curdate())")
    res = {}
    res['status'] = "ok"
    res['data'] = q
    return demjson.encode(res)
def add_rating():
    db = Db()
    lid = request.form['lid']
    rating = request.form['rating']
    review = request.form['review']
    q = db.insert("insert into review values ('','" + str(lid) + "','" +
                  str(review) + "','" + str(rating) + "',now())")
    res = {}
    res['status'] = "ok"
    return demjson.encode(res)
Beispiel #45
0
def getPatientsBasicInfo(request):
    if request.method == 'POST':
        data = {}
        message = []
        if 'D_id' in request.session:
            data['D_id'] = request.session['D_id']
            message = select.getPatientsBasicInfo(data['D_id'])
        js = demjson.encode(message)

        return HttpResponse(js)
Beispiel #46
0
def getblist():
    if request.method == 'GET':
        args = request.args.to_dict()
        keyt = str(args.get('keytype').encode('utf-8')).strip()
        keyw = str(args.get('keyword').encode('utf-8')).strip()
        areaname = str(args.get('areaname').encode('utf-8')).strip()

        bookamount = {'result': getBookList(keyt, keyw, areaname)}

    return demjson.encode(bookamount)
Beispiel #47
0
def getbooks():
    if request.method == 'GET':
        args = request.args.to_dict()
        keyt = str(args.get('keytype').encode('utf-8')).strip()
        keyw = str(args.get('keyword').encode('utf-8')).strip()
        page = int(args.get('page').encode('utf-8'))

        bookarry = {'result': getBookInfo(keyt, keyw, page)}

    return demjson.encode(bookarry)
Beispiel #48
0
def getborrowinfos():
    if request.method == 'GET':
        args = request.args.to_dict()
        isbn = str(args.get('isbn').encode('utf-8')).strip()
        borrowuser = str(args.get('borrowuser').encode('utf-8')).strip()
        areaname = str(args.get('areaname').encode('utf-8')).strip()

        borrowarry = {'result': getBorrowInfo(isbn, borrowuser, areaname)}

    return demjson.encode(borrowarry)
Beispiel #49
0
 def __cancel(self, total):
     if self.isCanceled: return
     self.isCanceled = True
     sendData = {
         'action': 'cancel',
         'appKey': int(self.appKey),
         'orderID': int(self.orderID),
     }
     self.sender.publish(self.sendOrderCh, JSON.encode(sendData))
     self.logger.write('trade_' + self.appKey, Logger.INFO, 'OrderForecast[cancel]', sendData)
Beispiel #50
0
	def brief(self):
		return demjson.encode({'data.size' : len(self.data), \
								'freq' : self.freq, \
								'cA6.size' : len(self.cA6), \
								'cD5.size' : len(self.cD5), \
								'cD4.size' : len(self.cD4), \
								'cD3.size' : len(self.cD3), \
								'cD2.size' : len(self.cD2), \
								'cD1.size' : len(self.cD1), \
								'result' : self.result})
def send_complaint():
    db = Db()
    lid = request.form['lid']
    wid = request.form['workid']
    com = request.form['complaint']
    q = db.insert("insert into complaint values ('','" + str(wid) + "','" +
                  com + "',curdate(),'pending','pending','" + str(lid) + "')")
    res = {}
    res['status'] = "ok"
    return demjson.encode(res)
Beispiel #52
0
def register(request):
    if request.method == 'POST':
        data = demjson.decode(request.POST['data'])
        data['password'] = tools.md5(data['password'])
        if insert.addDoctorInfo(data) == True:
            result = 0
        else:
            result = -1
        js = demjson.encode({'result':result})
        return HttpResponse(js)
def view_leave_status():
    db = Db()
    lid = request.form['lid']
    q = db.select(
        "select * from worker_leave,worker WHERE worker.workerid=worker_leave.worker_id and worker_leave.worker_id='"
        + str(lid) + "' order by apply_date desc")
    res = {}
    res['status'] = "ok"
    res['leave'] = q
    return demjson.encode(res)
Beispiel #54
0
def repeatCheck(request):
    if request.method == 'POST':
        data = demjson.decode(request.POST['data'])
        if select.checkExist(data['key'],data['value']):
            result = -1
        else:
            result = 0
        js = demjson.encode({'result':result})

        return HttpResponse(js)
def viewservice():
    db = Db()
    res = {}
    qry = db.select("select * from service WHERE status='1'")
    if len(qry) == 0:
        res['status'] = "Sorry"
    else:
        res['data'] = qry
        res['status'] = "ok"
    return demjson.encode(res)
Beispiel #56
0
def updateClinicInfo(request):
    if request.method == 'POST':
        data = demjson.decode(request.POST['data'])
        message = {'result': -1}
        if 'D_id' in request.session:
            if update.updateClinicInfo(data):
                message['result'] = 0

        js = demjson.encode(message)
        return HttpResponse(js)
Beispiel #57
0
 def error(self, data):
     self.endOrder(self.iid)
     self.sender.publish(
         self.sendOrderRspCh,
         JSON.encode({
             'mid': self.mid,
             'successVol': self.successVol
         }))
     # self.toDB()
     self.service.stop()
Beispiel #58
0
def deleteQuestionnaireInfo(request):
    if request.method == 'POST':
        data = demjson.decode(request.POST['data'])
        message = {'result': -1}
        if 'D_id' in request.session:
            if delete.deleteQuestionnaireInfo(data['type'],data['id']):
                message['result'] = 0

        js = demjson.encode(message)
        return HttpResponse(js)
Beispiel #59
0
 def get_dubbo_result(self, data):
     headers = {
         'Content-Type': 'application/json',
         'X-Request-Protocol': 'dubbo'
     }
     data = demjson.encode(data)
     url = '{}/soa/{}/{}'.format(self.tether_host, self.interface,
                                 self.method)
     response = requests.post(url, headers=headers, data=data)
     return demjson.decode(response.text)
Beispiel #60
0
	def Addmsg(self, line):
		switch = {
			"txt": lambda line:self.__txtwrite(line + '\n', 'a'),
			"csv": lambda line:self.__csvwrite(line + '\n', 'a'),
			"json": lambda line:self.__typeErrorReport(demjson.encode(line))
		}
		try:
			switch[self.type](line)
		except KeyError as e:
			pass