def run(teamID, cur): url = 'https://stats.nba.com/stats/teamdetails' res = requests.get(url, params={'teamID': teamID}, headers={'User-Agent': UserAgent.userAgent}) data = res.json() row = data['resultSets'][0]['rowSet'][0] try: cur.execute( "UPDATE team SET nick_name={0},city={1} WHERE team_id={2};".format( change(row[1]), change(row[4]), change(teamID))) except Exception: print('Error ' + str(teamID))
def run(self): self.conn.connect() for season in range(self.startSeason, self.endSeason + 1): values = [] for game in range(self.startGame, self.endGame + 1): self.season = season self.gameID = genGameID(season, game) print("processing " + str(self.gameID)) self.params['GameID'] = self.gameID req = requests.get(self.url, params=self.params, headers={'User-Agent': self.userAgent}) try: self.data = req.json() gameData = self.getGameData() except Exception: Log.log(__file__, 'run', self.gameID) continue value = '(' + ','.join([change(d) for d in gameData]) + ')' values.append(value) sql = Sql.insertValues.format(table='game', colNames=self.colNames, values=','.join(values)) try: #print(sql) self.conn.cursor.execute(sql) except: Log.log(__file__, "run") self.conn.rollback() self.conn.commit()
def insertSql(data): #print(data) value = ','.join([change(d) for d in data]) #print(value) sql = Sql.insertValue.format(table='game_base_data', colNames=','.join(GameBase.colNames), value=value) return sql
def writePlayer(self, data): if data[0] not in self.playerIds: self.conn.cursor.execute( Sql.insertIgnoreValue.format(table='player', colNames="player_id, name", value=','.join( [change(d) for d in data]))) self.playerIds.append(data[0])
def number_change(request): if request.method == 'POST': form = NumberForm(request.POST) if form.is_valid(): your_number = form.cleaned_data['your_number'] number_in_words = change(your_number) response = JsonResponse({'normal_number': your_number, 'number_in_words': number_in_words}) return response else: form = NumberForm(request.POST) return render(request, 'numberapp/base.html', {'form': form})
def run(self): conn = DatabaseConnector() conn.connect() try: teams = self.data.json()['resultSets'][0]['rowSet'] for team in teams: print('processing team %r' % team[0]) value = ','.join([change(team[0]), change(team[1])]) colNames = ','.join(['team_id', 'name']) sql = Sql.insertValue.format(table='team', colNames=colNames, value=value) print(sql) conn.cursor.execute(sql) conn.commit() except Exception: Log.log(__file__, "run", 65) conn.rollback() finally: conn.close()
def run(self): self.conn.connect() for season in range(self.startSeason, self.endSeason + 1): gameIDs = self.getGameID(season) for gameID in gameIDs: #self.conn.cursor.execute("SELECT COUNT(*) FROM box_score WHERE game_id = \'{0}\';".format(gameID)) #if self.conn.cursor.fetchone()[0] == 0: # continue print("processing " + str(gameID)) self.params['GameID'] = str(gameID) self.params['Season'] = genSeason(season) try: self.data = requests.get(self.url, params=self.params, headers={ 'User-Agent': self.userAgent }).json() except Exception: Log.log(__file__, "run", gameID) continue self.dict = genDict(self.data['resultSets'][0]['headers']) for row in self.data['resultSets'][0]['rowSet']: values = [] #gameBaseID= 0 gameBaseID = self.writeGameBase(row) self.writePlayer(self.getPlayerIdName(row)) values.append("(" + ','.join([ change(row[self.dict['GAME_ID']]), change(row[self.dict['TEAM_ID']]), change(row[self.dict['PLAYER_ID']]), change(gameBaseID), change(row[self.dict['START_POSITION']]) ]) + ")") #print(values) self.writeBoxScore(values)
def index_data(index_df): index_df = index_df.set_index(u'证券代码') index_df[u'涨跌'] = index_df[u'涨跌幅(%)'].map(lambda x: utils.change(x)) # 债券重命名 index_df[u'证券简称'] = index_df[u'证券简称'].map( lambda x: x.replace(u'财富(总值)', '').replace(u'总', '')) index_df['content'] = '' for index in index_df.index: index_df.loc[index, 'content'] = u'%s%s,收于%.2f点' % ( index_df.loc[index, u'证券简称'], index_df.loc[index, u'涨跌'], index_df.loc[index, u'收盘']) content = [] content.append(oversea_stock_market(index_df)) content.append(domestic_stock_market(index_df)) content.append(bond_market(index_df)) content.append(commodity_market(index_df)) with open(u'%s/市场回顾.txt' % (const.DESKTOP_DIR), 'w') as f: f.write('\n'.join(content).encode('utf-8'))
def main(): args = sys.argv if ("--help" in args) or (len(sys.argv) < 2): if len(sys.argv) < 2: print("ERROR: show_mutants requires at least one argument\n") print( "USAGE: prune_mutants <infile> <outfile> <pruning config file> [--mutantDir <dir>] [--sourceDir <dir>]" ) print( " --mutantDir: directory with all mutants; defaults to current directory" ) print( " --sourceDir: directory of source files; defaults to current directory" ) sys.exit(0) infile = sys.argv[1] outfile = sys.argv[2] config = sys.argv[3] mdir = "" try: mdirpos = args.index("--mutantDir") except ValueError: mdirpos = -1 if mdirpos != -1: mdir = args[mdirpos + 1] args.remove("--mutantDir") args.remove(mdir) mdir += "/" sdir = "" try: sdirpos = args.index("--sourceDir") except ValueError: sdirpos = -1 if sdirpos != -1: sdir = args[sdirpos + 1] args.remove("--sourceDir") args.remove(sdir) sdir += "/" mutants = [] with open(infile, 'r') as mfile: for line in mfile: name = line[:-1] suffix = "." + name.split(".")[-1] mpart = ".mutant." + name.split(".mutant.")[1] original = sdir + name.replace(mpart, suffix) mutants.append(utils.readMutant(name, original, mutantDir=mdir)) print("READ", len(mutants), "MUTANTS") constraints = {} constraints["orig"] = [] constraints["mutant"] = [] constraints["change"] = [] constraints["function"] = [] constraints["contract"] = [] constraints["source"] = [] constraints["line"] = [] for v in constraints.keys(): constraints["!" + v] = [] for v in constraints.keys(): constraints[v + "_RE"] = [] baseTypes = set() with open(config, 'r') as cfile: for line in cfile: if line[-1] == "\n": r = line[:-1] (ctype, crule) = r.split(": ", 1) if ctype not in constraints: print("INVALID CONSTRAINT TYPE IN PRUNING RULE:", line) if "_RE" in ctype: crule = re.compile(crule) baseTypes.add(ctype.replace("_RE", "").replace("!", "")) constraints[ctype].append(crule) pruned = [] properties = {} for m in mutants: prunedYet = False (mfile, sourcefile, pos, orig, mutant) = m properties["orig"] = orig properties["mutant"] = mutant properties["line"] = pos properties["source"] = sourcefile if "change" in baseTypes: properties["change"] = utils.change(m) if "function" in baseTypes: properties["function"] = utils.solidityFunction(m) if "contract" in baseTypes: properties["contract"] = utils.solidityContract(m) for ctype in constraints: field = ctype.replace("_RE", "").replace("!", "") negated = ctype[0] == "!" regexp = "_RE" in ctype for c in constraints[ctype]: if "line" in ctype: cstart = int(c.split("-")[0]) cend = int(c.split("-")[1]) matched = (properties[field] >= cstart) and (properties[field] <= cend) elif not regexp: matched = c in properties[field] else: matched = regexp.search(c, properties[field]) result = not ((matched is None) or (matched is False)) if negated: result = not result if result: print("=" * 80) print("PRUNING MUTANT DUE TO RULE:", ctype + ":", c) utils.show(m) pruned.append(mfile) prunedYet = True break if prunedYet: break print("=" * 80) print("PRUNED", len(pruned), "MUTANTS") with open(outfile, 'w') as newmfile: for m in mutants: if m[0] not in pruned: newmfile.write(m[0] + "\n")
from utils import change print change( 200, ( 1, 2, 5, 10, 20, 50, 100, 200 ) )
from utils import change print change( 50, coins=( 1, 2, 3, 4 ) ) # DOABLE
from utils import change print change( 100, xrange( 1, 100 ) )