file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
ospf_sh_request_list.pb.go | /*
Copyright 2019 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... | 0x0f, 0x3a, 0x6d, 0xb1, 0x45, 0x36, 0x85, 0x41, 0x67, 0x71, 0x25, 0x7d, 0x62, 0x08, 0xce, 0x52,
0xb2, 0xb7, 0x30, 0xf1, 0x86, 0x90, 0x35, 0x1a, 0xab, 0x48, 0x15, 0x5b, 0x6e, 0x74, 0x65, 0xd1,
0xf8, 0xdc, 0x4f, 0x5a, 0x61, 0xf1, 0x97, 0xaf, 0x1d, 0x66, 0x73, 0x38, 0xf3, 0xbd, 0xd4, 0xac,
0x75, 0xd1, 0xac, 0x4b, 0x95... | 0x9e, 0x13, 0x47, 0xa1, 0xbe, 0x68, 0xcb, 0xb3, 0x9f, 0x7d, 0x18, 0x85, 0xb4, 0xd7, 0x24, 0x38,
0x55, 0x39, 0x7b, 0x09, 0xa3, 0x0c, 0x85, 0x44, 0xe3, 0x2a, 0x76, 0x57, 0x86, 0x98, 0xc3, 0xb6,
0xfc, 0x91, 0xc4, 0xa7, 0x5d, 0x89, 0xec, 0x39, 0x9c, 0xdc, 0xf0, 0xc4, 0xb6, 0x8d, 0x3b, 0x5c, | random_line_split |
ospf_sh_request_list.pb.go | /*
Copyright 2019 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... |
func (m *OspfShRequestList) GetRequestInterfaceName() string {
if m != nil {
return m.RequestInterfaceName
}
return ""
}
func (m *OspfShRequestList) GetRequest() []*OspfShLsaSum {
if m != nil {
return m.Request
}
return nil
}
func init() {
proto.RegisterType((*OspfShRequestList_KEYS)(nil), "cisco_ios_xr_... | {
if m != nil {
return m.RequestNeighborAddress
}
return ""
} | identifier_body |
ospf_sh_request_list.pb.go | /*
Copyright 2019 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... | () string {
if m != nil {
return m.InterfaceName
}
return ""
}
func (m *OspfShRequestList_KEYS) GetNeighborAddress() string {
if m != nil {
return m.NeighborAddress
}
return ""
}
type OspfShLsaSum struct {
HeaderLsaType string `protobuf:"bytes,1,opt,name=header_lsa_type,json=headerLsaType,proto... | GetInterfaceName | identifier_name |
login.go | package handler
import (
"encoding/json"
"errors"
"fmt"
"log"
"math/rand"
"net"
"net/http"
database "projectname_projectmanager/driver"
model "projectname_projectmanager/model"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
_ "github.com/go-sql-driver/mysql" //blank import
"gopkg.in/ldap.v3"
)
var jwtK... | (w http.ResponseWriter, r *http.Request) {
fmt.Println("123")
SetupResponse(&w, r)
if (*r).Method == "OPTIONS" {
w.Header().Set("Access-Control-Max-Age", "86400")
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("Content-Type", "application/json")
claims := &model.Claims{}
type refresh struct {
Acces... | Refresh | identifier_name |
login.go | package handler
import (
"encoding/json"
"errors"
"fmt"
"log"
"math/rand"
"net"
"net/http"
database "projectname_projectmanager/driver"
model "projectname_projectmanager/model"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
_ "github.com/go-sql-driver/mysql" //blank import
"gopkg.in/ldap.v3"
)
var jwtK... |
defer conn.Close()
// perform initial read-only bind
if err = conn.Bind(c.ROUser.Name, c.ROUser.Password); err != nil {
WriteLogFile(err)
return err
}
// find the user attempting to login
results, err := conn.Search(ldap.NewSearchRequest(
c.BaseDN, ldap.ScopeWholeSubtree,
ldap.NeverDerefAliases,
0, 0... | {
WriteLogFile(err)
return err
} | conditional_block |
login.go | package handler
import (
"encoding/json"
"errors"
"fmt"
"log"
"math/rand"
"net"
"net/http"
database "projectname_projectmanager/driver"
model "projectname_projectmanager/model"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
_ "github.com/go-sql-driver/mysql" //blank import
"gopkg.in/ldap.v3"
)
var jwtK... |
// SignIn : for user sign-in through LDAP
func (c *Commander) SignIn(w http.ResponseWriter, r *http.Request) {
var client model.Client
var err error
var error model.Error
db := database.DbConn()
defer db.Close()
// create a new client
if client, err = New(model.Config{
BaseDN: "DC=sls,DC=ads,DC=valuelabs,DC=... | {
var error model.Error
db := database.DbConn()
defer db.Close()
if Role == "project manager" {
selDB, err := db.Query("SELECT project_manager_email from project_manager WHERE project_manager_email =? ", username)
defer selDB.Close()
if err != nil {
WriteLogFile(err)
w.WriteHeader(http.StatusBadRequest)... | identifier_body |
login.go | package handler
import (
"encoding/json"
"errors"
"fmt"
"log"
"math/rand"
"net"
"net/http"
database "projectname_projectmanager/driver"
model "projectname_projectmanager/model"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
_ "github.com/go-sql-driver/mysql" //blank import
"gopkg.in/ldap.v3"
)
var jwtK... | length := 20
var bRefresh strings.Builder
for i := 0; i < length; i++ {
bRefresh.WriteRune(chars[rand.Intn(len(chars))])
}
var jwtTokenRefresh model.JwtToken
jwtTokenRefresh.AccessToken = tokenStringRefresh
jwtTokenRefresh.TokenType = "bearer"
jwtTokenRefresh.Expiry = "3600"
jwtTokenRefresh.RefreshToken = bR... | "abcdefghijklmnopqrstuvwxyz%*" +
"0123456789") | random_line_split |
shotsAlarm_asynchronous_with_hue.py | import Private
import Tkinter as tkinter
import ttk
import sys
import time
import threading
import Queue
from gpiozero import Button, DigitalOutputDevice
import spotipy
import spotipy.util as util
from datetime import datetime, timedelta
from phue import Bridge
from RPLCD.gpio import CharLCD
from RPi import GPIO
# glo... |
# runs once an hour to make sure
# count doesn't get too big
def workerThread2(self):
while self.running:
time.sleep(3600)
if self.count >= 3600:
# make sure we have access to shared resource
with self.lock:
self.count = 0... | with self.lock:
# make sure shots is activated
if self.shotsFired:
# make sure we haven't been counting longer than the song length
if (self.count <= self.songLength):
# update queue with count if countdown stage or go stage... | conditional_block |
shotsAlarm_asynchronous_with_hue.py | import Private
import Tkinter as tkinter
import ttk
import sys
import time
import threading
import Queue
from gpiozero import Button, DigitalOutputDevice
import spotipy
import spotipy.util as util
from datetime import datetime, timedelta
from phue import Bridge
from RPLCD.gpio import CharLCD
from RPi import GPIO
# glo... |
def updateDoor(self, command):
self.b.set_group(5, command)
def updateHW(self, command):
self.b.set_group(6, command)
def updateKitchen(self, command):
self.b.set_group(2, command)
def flashLights(self, color, delay, seconds):
command = {'transitiontime': 1, 'xy': co... | self.b.set_group(4, command) | identifier_body |
shotsAlarm_asynchronous_with_hue.py | import Private
import Tkinter as tkinter
import ttk
import sys
import time
import threading
import Queue
from gpiozero import Button, DigitalOutputDevice
import spotipy
import spotipy.util as util
from datetime import datetime, timedelta
from phue import Bridge
from RPLCD.gpio import CharLCD
from RPi import GPIO
# glo... | # if we haven't already canceled
if self.shotsFired:
print("alarm canceled")
# keep track of alarm activation
self.shotsFired = 0
self.flashed = 1
self.flashed2 = 1
# make sure we have access to shared resource
with s... | with self.lock:
self.count = 0
def alarmCancel(self): | random_line_split |
shotsAlarm_asynchronous_with_hue.py | import Private
import Tkinter as tkinter
import ttk
import sys
import time
import threading
import Queue
from gpiozero import Button, DigitalOutputDevice
import spotipy
import spotipy.util as util
from datetime import datetime, timedelta
from phue import Bridge
from RPLCD.gpio import CharLCD
from RPi import GPIO
# glo... | (self):
if not self.guiVisible:
self.master.update()
self.master.deiconify()
if fullscreen:
self.master.geometry("{}x{}+0+0".format(self.w, self.h))
# keep track of gui visibility
self.guiVisible = 1
##########################
... | GUIshow | identifier_name |
spark-recordcount.py | #!/usr/bin/env python
#
# Copyright (C) 2015 The Regents of the University of California.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# ... |
peers_data[sig][1] += 1
# the time in the output row is truncated down to a multiple of
# RESULT_GRANULARITY so that slices can be merged correctly
start_time = \
int(math.floor(start_time/RESULT_GRANULARITY) * RESULT_GRANULARITY)
# for each peer that we processed data for, cr... | peers_data[sig][2] += 1 # increment the coll_record_cnt
first = False | conditional_block |
spark-recordcount.py | #!/usr/bin/env python
#
# Copyright (C) 2015 The Regents of the University of California.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# ... | ():
parser = argparse.ArgumentParser(description="""
Script that uses PyBGPStream and Spark to analyze historical BGP data and
extract high-level statistics.
""")
parser.add_argument('-s', '--start-time', nargs='?', required=True,
type=int,
help='Star... | main | identifier_name |
spark-recordcount.py | #!/usr/bin/env python
#
# Copyright (C) 2015 The Regents of the University of California.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# ... |
def analyze(start_time, end_time, data_type, outdir,
collector=None, num_cores=None, memory=None):
# round start time down to nearest day
start_time = \
int(math.floor(start_time/RESULT_GRANULARITY) * RESULT_GRANULARITY)
# round end time up to nearest day
rounded = int(math.floor... | return (row[0][0]), row[1] | identifier_body |
spark-recordcount.py | #!/usr/bin/env python
#
# Copyright (C) 2015 The Regents of the University of California.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# ... | w.writerow([ts, "ALL-COLLECTORS", "ALL-PEERS", elems, records])
reduced_time_collector_peer.unpersist()
reduced_time_collector.unpersist()
sc.stop()
return
def main():
parser = argparse.ArgumentParser(description="""
Script that uses PyBGPStream and Spark to analyze historical BGP... | for key in final_time:
(ts) = key
(elems, records) = final_time[key] | random_line_split |
battle_traits.ts | import { tagAs } from 'factions/metatagger'
import {
CHARGE_PHASE,
COMBAT_PHASE,
DURING_GAME,
END_OF_MOVEMENT_PHASE,
END_OF_SETUP,
HERO_PHASE,
MOVEMENT_PHASE,
SAVES_PHASE,
SHOOTING_PHASE,
START_OF_HERO_PHASE,
TURN_FIVE_HERO_PHASE,
TURN_ONE_HERO_PHASE,
TURN_THREE_HERO_PHASE,
} from 'types/phase... | desc: `At the start of your hero phase, you can say that your army intends to complete one of the following agendas before the start of your next hero phase. You must tell your opponent which agenda you intend to complete, and you cannot complete the same agenda more than once per battle.
If a friendly... | name: `Agendas of Anarchy`, | random_line_split |
Logistic regression.py |
# coding: utf-8
# # Logistic Regression
#
# Logistic Regression is a Machine Learning classification algorithm that is used to predict the probability of a categorical dependent variable. In logistic regression, the dependent variable is a binary variable that contains data coded as 1 (yes, success, etc.) or 0 (no, ... | In[23]:
plot_classes()
# Build the model, and keep it on `logreg`.
# In[24]:
X_train, X_test, y_train, y_test = train_test_split(data.balance,
data.default,
test_size=0.3,
... | show();
# | conditional_block |
Logistic regression.py |
# coding: utf-8
# # Logistic Regression
#
# Logistic Regression is a Machine Learning classification algorithm that is used to predict the probability of a categorical dependent variable. In logistic regression, the dependent variable is a binary variable that contains data coded as 1 (yes, success, etc.) or 0 (no, ... | (data):
fig = plt.figure(figsize=(9, 4))
gs = GridSpec(1, 3, width_ratios=[3, 1, 1])
ax0 = plt.subplot(gs[0])
ax0 = plt.scatter(data.balance[data.default==0],
data.income[data.default==0],
label='default=No',
marker='.', c='red', alpha... | plot_descriptive | identifier_name |
Logistic regression.py |
# coding: utf-8
# # Logistic Regression
#
# Logistic Regression is a Machine Learning classification algorithm that is used to predict the probability of a categorical dependent variable. In logistic regression, the dependent variable is a binary variable that contains data coded as 1 (yes, success, etc.) or 0 (no, ... |
def print_metainformation(meta):
print('Available types:', meta['description']['dtype'].unique())
print('{} Features'.format(meta['description'].shape[0]))
print('{} categorical features'.format(len(meta['categorical_features'])))
print('{} numerical features'.format(len(meta['numerical_features'])))
... | meta = dict()
descr = pd.DataFrame({'dtype': df.dtypes, 'NAs': df.isna().sum()})
categorical_features = descr.loc[descr['dtype'] == 'object'].index.values.tolist()
numerical_features = descr.loc[descr['dtype'] != 'object'].index.values.tolist()
numerical_features_na = descr.loc[(descr['dtype'] != 'objec... | identifier_body |
Logistic regression.py | # coding: utf-8
# # Logistic Regression
#
# Logistic Regression is a Machine Learning classification algorithm that is used to predict the probability of a categorical dependent variable. In logistic regression, the dependent variable is a binary variable that contains data coded as 1 (yes, success, etc.) or 0 (no, f... |
# And now represent where is the model setting the separation function between the two classes.
# In[25]:
def plot_sigmoid():
plt.figure(figsize=(10,4))
plt.subplot(1, 2, 1)
plot_classes(show=False)
plt.plot(sigm.x.values, sigm.y.values, color='black', linewidth=3);
plt.title('Sigmoid')
pl... | print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred)) | random_line_split |
common.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: common/common.proto
package common
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a c... |
return ""
}
func (m *KeyEnvelope) GetAesKey() []byte {
if m != nil {
return m.AesKey
}
return nil
}
type Location struct {
// Latitude.
Latitude float64 `protobuf:"fixed64,1,opt,name=latitude,proto3" json:"latitude,omitempty"`
// Longitude.
Longitude float64 `protobuf:"fixed64,2,opt,name=longitude,proto3" ... | {
return m.KekLabel
} | conditional_block |
common.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: common/common.proto
package common
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a c... |
type Region int32
const (
// EU868
Region_EU868 Region = 0
// US915
Region_US915 Region = 2
// CN779
Region_CN779 Region = 3
// EU433
Region_EU433 Region = 4
// AU915
Region_AU915 Region = 5
// CN470
Region_CN470 Region = 6
// AS923
Region_AS923 Region = 7
// KR920
Region_KR920 Region = 8
// IN865
... | {
return fileDescriptor_8f954d82c0b891f6, []int{0}
} | identifier_body |
common.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: common/common.proto
package common
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a c... | () {
xxx_messageInfo_Location.DiscardUnknown(m)
}
var xxx_messageInfo_Location proto.InternalMessageInfo
func (m *Location) GetLatitude() float64 {
if m != nil {
return m.Latitude
}
return 0
}
func (m *Location) GetLongitude() float64 {
if m != nil {
return m.Longitude
}
return 0
}
func (m *Location) Get... | XXX_DiscardUnknown | identifier_name |
common.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: common/common.proto
package common
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a c... | XXX_sizecache int32 `json:"-"`
}
func (m *KeyEnvelope) Reset() { *m = KeyEnvelope{} }
func (m *KeyEnvelope) String() string { return proto.CompactTextString(m) }
func (*KeyEnvelope) ProtoMessage() {}
func (*KeyEnvelope) Descriptor() ([]byte, []int) {
return fileDescriptor_8f954d82c0b891f6, []int... | // 'Key Transport Security' section.
AesKey []byte `protobuf:"bytes,2,opt,name=aes_key,json=aesKey,proto3" json:"aes_key,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"` | random_line_split |
lib.rs | /*
* This is NearDice contract:
*
*
*
*/
// To conserve gas, efficient serialization is achieved through Borsh (http://borsh.io/)
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::wee_alloc;
use near_sdk::json_types::{U64, U128};
use near_sdk::serde::{Deserialize, Serialize};
use near... | (&mut self, target: u8) -> HumanReadableDiceResult {
// check called by real user NOT from other contracts
let account_id = env::predecessor_account_id();
assert_eq!(
account_id.clone(),
env::signer_account_id(),
"This method must be called directly from user... | roll_dice | identifier_name |
lib.rs | /*
* This is NearDice contract:
*
*
*
*/
// To conserve gas, efficient serialization is achieved through Borsh (http://borsh.io/)
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::wee_alloc;
use near_sdk::json_types::{U64, U128};
use near_sdk::serde::{Deserialize, Serialize};
use near... | else {
self.accounts.insert(&account_id, &leftover);
}
// always update jack_pod before rolling dice
self.jack_pod += self.rolling_fee;
// rolling dice here
let random_u8: u8 = env::random_seed().iter().fold(0_u8, |acc, x| acc.wrapping_add(*x));
let dice_poi... | {
self.accounts.remove(&account_id);
} | conditional_block |
lib.rs | /*
* This is NearDice contract:
*
*
*
*/
// To conserve gas, efficient serialization is achieved through Borsh (http://borsh.io/)
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::wee_alloc;
use near_sdk::json_types::{U64, U128};
use near_sdk::serde::{Deserialize, Serialize};
use near... |
//***********************/
// view functions
//***********************/
fn get_hr_info(&self, index: u64) -> HumanReadableWinnerInfo {
let info = self.win_history.get(index).expect("Error: no this item in winner history!");
HumanReadableWinnerInfo {
user: info.user.clone()... | {
let account_id = env::signer_account_id();
// Use env::log to record logs permanently to the blockchain!
env::log(format!("Saving greeting '{}' for account '{}'", message, account_id,).as_bytes());
} | identifier_body |
lib.rs | /*
* This is NearDice contract:
*
*
*
*/
// To conserve gas, efficient serialization is achieved through Borsh (http://borsh.io/)
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::wee_alloc;
use near_sdk::json_types::{U64, U128};
use near_sdk::serde::{Deserialize, Serialize};
use near... | // always update jack_pod before rolling dice
self.jack_pod += self.rolling_fee;
// rolling dice here
let random_u8: u8 = env::random_seed().iter().fold(0_u8, |acc, x| acc.wrapping_add(*x));
let dice_point = self.dice_number as u16 * 6_u16 * random_u8 as u16 / 0x100_u16 + 1;
... | if leftover == 0 {
self.accounts.remove(&account_id);
} else {
self.accounts.insert(&account_id, &leftover);
} | random_line_split |
lambda_function.py | import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import json
import datetime
import time
import seaborn as sns
import matplotlib.pyplot as plt
from io import StringIO, BytesIO
import boto3
# Extracting Job Title, Company Details, Location, Salary and Job Description for Analysis
de... | (soup, jobs, rows):
for div in rows:
for a in div.find_all(name='a', attrs={'data-tn-element': 'jobTitle'}):
jobs.append(a['title'])
return (jobs)
def extract_company(soup, companies, rows):
for div in rows:
company = div.find_all(name='span', attrs={'class': 'company'})
... | extract_job_title | identifier_name |
lambda_function.py | import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import json
import datetime
import time
import seaborn as sns
import matplotlib.pyplot as plt
from io import StringIO, BytesIO
import boto3
# Extracting Job Title, Company Details, Location, Salary and Job Description for Analysis
de... |
def extract_company(soup, companies, rows):
for div in rows:
company = div.find_all(name='span', attrs={'class': 'company'})
if len(company) > 0:
for b in company:
companies.append(b.text.strip())
else:
sec_try = div.find_all(name='span', attrs={'cl... | for div in rows:
for a in div.find_all(name='a', attrs={'data-tn-element': 'jobTitle'}):
jobs.append(a['title'])
return (jobs) | identifier_body |
lambda_function.py | import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import json
import datetime
import time
import seaborn as sns
import matplotlib.pyplot as plt
from io import StringIO, BytesIO
import boto3
# Extracting Job Title, Company Details, Location, Salary and Job Description for Analysis
de... | job_data['job_title'] = job_data['job_title'].str.lower()
job_data.loc[job_data['job_title'].str.contains(
'data scientist|data science|data science & insights|data science and insights'), 'Job_Title_Category'] = 'Data Scientist'
job_data.loc[job_data['job_title'].str.contains(
'analyst|ana... | def extract_specialization(job_data):
# Categorizing job titles into specialization type.
job_data['Job_Title_Category'] = np.nan | random_line_split |
lambda_function.py | import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import json
import datetime
import time
import seaborn as sns
import matplotlib.pyplot as plt
from io import StringIO, BytesIO
import boto3
# Extracting Job Title, Company Details, Location, Salary and Job Description for Analysis
de... |
return (jobs)
def extract_company(soup, companies, rows):
for div in rows:
company = div.find_all(name='span', attrs={'class': 'company'})
if len(company) > 0:
for b in company:
companies.append(b.text.strip())
else:
sec_try = div.find_all(name=... | for a in div.find_all(name='a', attrs={'data-tn-element': 'jobTitle'}):
jobs.append(a['title']) | conditional_block |
store.go | package headerfs
import (
"bytes"
"encoding/hex"
"sync"
"github.com/pkt-cash/pktd/btcutil/er"
"github.com/pkt-cash/pktd/pktlog/log"
"github.com/pkt-cash/pktd/blockchain"
"github.com/pkt-cash/pktd/chaincfg/chainhash"
"github.com/pkt-cash/pktd/pktwallet/waddrmgr"
"github.com/pkt-cash/pktd/pktwallet/walletdb"
... |
}
// If our on disk state and the provided header assertion don't match,
// then we'll purge this state so we can sync it anew once we fully
// start up.
if failed {
if err := f.deleteBuckets(tx); err != nil {
return true, err
} else {
return true, f.createBuckets(tx)
}
}
return false, nil
}
// F... | {
hdrhash := hdr.Header.blockHeader.BlockHash()
he := hdr.Header
if bh, err := nhs.FetchBlockHeaderByHeight1(tx, hdr.Height); err != nil {
if ErrHashNotFound.Is(err) {
log.Warnf("We have filter header number %v but no block header, "+
"resetting filter headers", hdr.Height)
failed = true
... | conditional_block |
store.go | package headerfs
import (
"bytes"
"encoding/hex"
"sync"
"github.com/pkt-cash/pktd/btcutil/er"
"github.com/pkt-cash/pktd/pktlog/log"
"github.com/pkt-cash/pktd/blockchain"
"github.com/pkt-cash/pktd/chaincfg/chainhash"
"github.com/pkt-cash/pktd/pktwallet/waddrmgr"
"github.com/pkt-cash/pktd/pktwallet/walletdb"
... |
// ChainTip returns the best known block header and height for the
// blockHeaderStore.
//
// NOTE: Part of the BlockHeaderStore interface.
func (h *NeutrinoDBStore) BlockChainTip() (*wire.BlockHeader, uint32, er.R) {
var bh *wire.BlockHeader
var height uint32
return bh, height, walletdb.View(h.Db, func(tx walletdb... |
/////
///// | random_line_split |
store.go | package headerfs
import (
"bytes"
"encoding/hex"
"sync"
"github.com/pkt-cash/pktd/btcutil/er"
"github.com/pkt-cash/pktd/pktlog/log"
"github.com/pkt-cash/pktd/blockchain"
"github.com/pkt-cash/pktd/chaincfg/chainhash"
"github.com/pkt-cash/pktd/pktwallet/waddrmgr"
"github.com/pkt-cash/pktd/pktwallet/walletdb"
... | (
tx walletdb.ReadWriteTx,
headerStateAssertion *FilterHeader,
nhs *NeutrinoDBStore,
) (bool, er.R) {
failed := false
if headerStateAssertion != nil {
// First, we'll attempt to locate the header at this height. If no such
// header is found, then we'll exit early.
assertedHeader, err := f.FetchFilterHeade... | maybeResetHeaderState | identifier_name |
store.go | package headerfs
import (
"bytes"
"encoding/hex"
"sync"
"github.com/pkt-cash/pktd/btcutil/er"
"github.com/pkt-cash/pktd/pktlog/log"
"github.com/pkt-cash/pktd/blockchain"
"github.com/pkt-cash/pktd/chaincfg/chainhash"
"github.com/pkt-cash/pktd/pktwallet/waddrmgr"
"github.com/pkt-cash/pktd/pktwallet/walletdb"
... |
// FetchHeader returns the filter header that corresponds to the passed block
// height.
func (f *NeutrinoDBStore) FetchFilterHeader(hash *chainhash.Hash) (*chainhash.Hash, er.R) {
var out *chainhash.Hash
return out, walletdb.View(f.Db, func(tx walletdb.ReadTx) er.R {
var err er.R
out, err = f.FetchFilterHeader... | {
failed := false
if headerStateAssertion != nil {
// First, we'll attempt to locate the header at this height. If no such
// header is found, then we'll exit early.
assertedHeader, err := f.FetchFilterHeaderByHeight(headerStateAssertion.Height)
if assertedHeader == nil {
if !ErrHeaderNotFound.Is(err) {
... | identifier_body |
algo_2_2.py | """
Created on Sat Oct 14 09:33:14 2017
@author: Ola
"""
"""
This algorithm is an original that considers standard deviation in selecting
households. The SD of weekly consumption is calculated, and households who
consume above a threshold (mean + 2*SD) during a hour of shedding are omitted
from the shedding! Thus, th... | (df):
global NRML
result = {}
for g1,n1 in df.groupby([df.index.month]) :
result[g1] = {}
mxs = {}
for g2,n2 in n1.groupby([n1.index.weekday]) :
result[g1][g2] = {}
for g3,n3 in n2.groupby([n2.index.hour]) :
result[g1][g2][g3] = {}
... | group_A | identifier_name |
algo_2_2.py | """
Created on Sat Oct 14 09:33:14 2017
@author: Ola
"""
"""
This algorithm is an original that considers standard deviation in selecting
households. The SD of weekly consumption is calculated, and households who
consume above a threshold (mean + 2*SD) during a hour of shedding are omitted
from the shedding! Thus, th... | #
# p1 = plt.bar(x, yx, LOAD_SEG/2.0, color='b',label = 'Max')
# p2 = plt.bar(x, ym, LOAD_SEG/2.0, color='r',bottom=yx)
# plt.xlabel('Every 100 shedding events')
# plt.ylabel('Number of households shed')
# plt.xticks(x, rotation='horizontal')
# plt.legend((p1[0], p2[0]),('Number of sheds of ... | # plt.ylim([0, max(y)* 1.3])
# plt.show() | random_line_split |
algo_2_2.py | """
Created on Sat Oct 14 09:33:14 2017
@author: Ola
"""
"""
This algorithm is an original that considers standard deviation in selecting
households. The SD of weekly consumption is calculated, and households who
consume above a threshold (mean + 2*SD) during a hour of shedding are omitted
from the shedding! Thus, th... |
def load_set():
'''
Load the data
'''
df = pd.read_hdf(FILE_PATH)
calc_normalized()
'''
Calculate the hourly average
'''
date_hour_groups = df.groupby(['date','hour'])
total_cons = [date_hour_groups.get_group((a,b))['value'].sum() for a,b in date... | global take_always
take_always = None
if NO_LISTS:
houses = [[row['house_id'],row['value'],datetime.strptime(row['date']+'-'+str(row['hour']),DATE_FORMAT)] for index,row in date_hour_group.iterrows()]
else :
#Iterate the rows
if len(exclude_a) == len(date_hour_group.index) :
... | identifier_body |
algo_2_2.py | """
Created on Sat Oct 14 09:33:14 2017
@author: Ola
"""
"""
This algorithm is an original that considers standard deviation in selecting
households. The SD of weekly consumption is calculated, and households who
consume above a threshold (mean + 2*SD) during a hour of shedding are omitted
from the shedding! Thus, th... |
groups.append(group)
if sum([ h[1] for h in groups[-1] ]) < cut :
groups = groups[:-1]
return groups[:1],shedding
def load_set():
'''
Load the data
'''
df = pd.read_hdf(FILE_PATH)
calc_normalized()
'''
Calculate the hourly average
'''
... | i = 0
group.append(houses[i]+[shedding.get(houses[i][0],0)])
shedding[houses[i][0]] = shedding.get(houses[i][0],0)
del houses[i] | conditional_block |
api.go | // Copyright (c) 2017-2018 The qitmeer developers
// Copyright (c) 2013-2016 The btcsuite developers
// Copyright (c) 2017-2018 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package node
import (
"fmt"
"github.com/Qitmeer/qitmeer/common/math"... | gsups[p.Network][1] = p.GraphStateDur
}
if p.GraphStateDur < gsups[p.Network][2] {
gsups[p.Network][2] = p.GraphStateDur
}
}
if p.Services&protocol.Relay > 0 {
info.Relays++
}
}
for k, gu := range gsups {
info, ok := infos[k]
if !ok {
continue
}
if info.Connecteds > 0 {
avegs :... | gsups[p.Network][0] = gsups[p.Network][0] + p.GraphStateDur
if p.GraphStateDur > gsups[p.Network][1] { | random_line_split |
api.go | // Copyright (c) 2017-2018 The qitmeer developers
// Copyright (c) 2013-2016 The btcsuite developers
// Copyright (c) 2017-2018 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package node
import (
"fmt"
"github.com/Qitmeer/qitmeer/common/math"... |
return jrs, nil
}
func GetGraphStateResult(gs *blockdag.GraphState) *json.GetGraphStateResult {
if gs != nil {
mainTip := gs.GetMainChainTip()
tips := []string{mainTip.String() + " main"}
for k := range gs.GetTips().GetMap() {
if k.IsEqual(mainTip) {
continue
}
tips = append(tips, k.String())
}... | {
jrs = append(jrs, v.ToJson())
} | conditional_block |
api.go | // Copyright (c) 2017-2018 The qitmeer developers
// Copyright (c) 2013-2016 The btcsuite developers
// Copyright (c) 2017-2018 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package node
import (
"fmt"
"github.com/Qitmeer/qitmeer/common/math"... | {
err := common.ParseAndSetDebugLevels(level)
if err != nil {
return nil, err
}
return level, nil
} | identifier_body | |
api.go | // Copyright (c) 2017-2018 The qitmeer developers
// Copyright (c) 2013-2016 The btcsuite developers
// Copyright (c) 2017-2018 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package node
import (
"fmt"
"github.com/Qitmeer/qitmeer/common/math"... | () (interface{}, error) {
bl := api.node.node.peerServer.GetBanlist()
bls := []*json.GetBanlistResult{}
for k, v := range bl {
bls = append(bls, &json.GetBanlistResult{ID: k, Bads: v})
}
return bls, nil
}
// RemoveBan
func (api *PrivateBlockChainAPI) RemoveBan(id *string) (interface{}, error) {
ho := ""
if id... | Banlist | identifier_name |
createHeatmap.py | #!/usr/bin/env python
import math, os, commands, shutil, sys, re
import matplotlib as matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.backends.backend_agg
import numpy as np
import argparse
# Summarize the CrossCorr toplist
# 02016-07-19 (JD 2457589)
# g r ... | twoDarray = firstTwoDarray
else:
'flipAxes not configured correctly'
return twoDarray
# Check plotting families
if args.texMode:
from matplotlib import rc
rc('font', **{'family':'serif','serif':['Times']})
rc('text',usetex=True)
summarizer(args) | def takeAxisAndRotate(threeDarray, zIndex, takeAxisIndex, flipAxes):
firstTwoDarray = np.take(threeDarray, zIndex, takeAxisIndex)
if (flipAxes == 1):
twoDarray = firstTwoDarray.T
elif (flipAxes == 0): | random_line_split |
createHeatmap.py | #!/usr/bin/env python
import math, os, commands, shutil, sys, re
import matplotlib as matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.backends.backend_agg
import numpy as np
import argparse
# Summarize the CrossCorr toplist
# 02016-07-19 (JD 2457589)
# g r ... | (args):
headJobName = args.nameToplist
verboseSummaryFile = 'verbose_summary-' + str(args.fCenter) +'.txt'
if args.bypassSummary:
print 'Bypassing summary file creation'
os.system('cat ' + headJobName + ' > ' + verboseSummaryFile)
# Defined by 'print_crossCorrBinaryline_to_str' in Cro... | summarizer | identifier_name |
createHeatmap.py | #!/usr/bin/env python
import math, os, commands, shutil, sys, re
import matplotlib as matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.backends.backend_agg
import numpy as np
import argparse
# Summarize the CrossCorr toplist
# 02016-07-19 (JD 2457589)
# g r ... |
# Check plotting families
if args.texMode:
from matplotlib import rc
rc('font', **{'family':'serif','serif':['Times']})
rc('text',usetex=True)
summarizer(args)
| firstTwoDarray = np.take(threeDarray, zIndex, takeAxisIndex)
if (flipAxes == 1):
twoDarray = firstTwoDarray.T
elif (flipAxes == 0):
twoDarray = firstTwoDarray
else:
'flipAxes not configured correctly'
return twoDarray | identifier_body |
createHeatmap.py | #!/usr/bin/env python
import math, os, commands, shutil, sys, re
import matplotlib as matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.backends.backend_agg
import numpy as np
import argparse
# Summarize the CrossCorr toplist
# 02016-07-19 (JD 2457589)
# g r ... |
else:
print 'Incompatible options'
# In the toplist, columns change from the right (big-endian)
# They are listed f, t, a,
# Python reads in entries in the order f0t0a0, f0t0a1, f0t1a0,...
FLen = len(np.unique(fArray))
TLen = len(np.unique(tpArray))
... | xArray = fArray
yArray = modArray
zArray = tpArray
zIndex = args.TIndex
takeAxisIndex = 1
flipAxes = 0 | conditional_block |
entitymap.go | // This work is subject to the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
// license. Its contents can be found at:
// http://creativecommons.org/publicdomain/zero/1.0/
package xmlx
/*
These routines offer conversions between xml entities and their respective
unicode representations.
eg:
♣ -> ♣... | r err os.Error
var num int
entity = entity[2 : len(entity)-1]
if num, err = strconv.Atoi(entity); err != nil {
return "&#" + entity + ";"
}
var arr [4]byte
if size := utf8.EncodeRune(arr[:], num); size == 0 {
return "&#" + entity + ";"
}
return string(arr[:])
}
// Converts a single Go utf8-token... | eturn "&" + entity[2:len(entity)-1] + ";"
}
va | conditional_block |
entitymap.go | // This work is subject to the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
// license. Its contents can be found at:
// http://creativecommons.org/publicdomain/zero/1.0/
package xmlx
/*
These routines offer conversions between xml entities and their respective
unicode representations.
eg:
♣ -> ♣... | http://www.w3.org/TR/html4/sgml/entities.html
Portions © International Organization for Standardization 1986
Permission to copy in any form is granted for use with
conforming SGML systems and applications as defined in
ISO 8879, provided this notice is included in all copies.
*/
func namedEntityToUtf8(name string)... | "pi"] = "\u03c0"
em["nabla"] = "\u2207"
em["isin"] = "\u2208"
em["loz"] = "\u25ca"
em["prop"] = "\u221d"
em["para"] = "\u00b6"
em["Aring"] = "\u00c5"
em["euro"] = "\u20ac"
em["sup3"] = "\u00b3"
em["sup2"] = "\u00b2"
em["sup1"] = "\u00b9"
em["prod"] = "\u220f"
em["gamma"] = "\u03b3"
em["perp"] = "\u22a5"
e... | identifier_body |
entitymap.go | // This work is subject to the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
// license. Its contents can be found at:
// http://creativecommons.org/publicdomain/zero/1.0/
package xmlx
/*
These routines offer conversions between xml entities and their respective
unicode representations.
eg:
♣ -> ♣... | ty string) string {
var ok bool
if ok = reg_entnamed.MatchString(entity); ok {
return namedEntityToUtf8(entity[1 : len(entity)-1])
}
if ok = reg_entnumeric.MatchString(entity); !ok {
return "&" + entity[2:len(entity)-1] + ";"
}
var err os.Error
var num int
entity = entity[2 : len(entity)-1]
if num, ... | yToUtf8(enti | identifier_name |
entitymap.go | // This work is subject to the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
// license. Its contents can be found at:
// http://creativecommons.org/publicdomain/zero/1.0/
package xmlx
/*
These routines offer conversions between xml entities and their respective
unicode representations.
eg:
♣ -> ♣... | case "zwj":
return "\u200d"
case "mu":
return "\u03bc"
case "Ccedil":
return "\u00c7"
case "infin":
return "\u221e"
case "ouml":
return "\u00f6"
case "rfloor":
return "\u230b"
case "pound":
return "\u00a3"
case "szlig":
return "\u00df"
case "thorn":
return "\u00fe"
case "forall":
return "\... | case "tilde":
return "\u02dc"
case "Uuml":
return "\u00dc" | random_line_split |
parser.rs | use nom::{bytes::complete as bytes, character::complete as character, combinator, IResult};
use super::{
finder::FileSearcher,
github::{GitHubIssue, GitHubPatch},
};
use serde::Deserialize;
use std::{collections::HashMap, fs::File, io::prelude::*, path::Path};
pub mod issue;
pub mod langs;
pub mod source;
us... | let desc_lines = todo
.desc_lines
.iter()
.map(|s| s.to_string())
.collect::<Vec<_>>();
issue.body.descs_and_srcs.push((desc_lines, loc));
}
pub fn from_files_in_directory(
dir: &str,
excludes: &Vec<String>,
) -> Result<IssueMa... | random_line_split | |
parser.rs | use nom::{bytes::complete as bytes, character::complete as character, combinator, IResult};
use super::{
finder::FileSearcher,
github::{GitHubIssue, GitHubPatch},
};
use serde::Deserialize;
use std::{collections::HashMap, fs::File, io::prelude::*, path::Path};
pub mod issue;
pub mod langs;
pub mod source;
us... | (&mut self, todo: &ParsedTodo, loc: FileTodoLocation) {
let title = todo.title.to_string();
let issue = self
.todos
.entry(title.clone())
.or_insert(Issue::new((), title));
if let Some(assignee) = todo.assignee.map(|s| s.to_string()) {
if !issue.h... | add_parsed_todo | identifier_name |
parser.rs | use nom::{bytes::complete as bytes, character::complete as character, combinator, IResult};
use super::{
finder::FileSearcher,
github::{GitHubIssue, GitHubPatch},
};
use serde::Deserialize;
use std::{collections::HashMap, fs::File, io::prelude::*, path::Path};
pub mod issue;
pub mod langs;
pub mod source;
us... |
let languages = languages.expect("impossible!");
// Open the file and load the contents
let mut file = File::open(path)
.map_err(|e| format!("could not open file: {}\n{}", path.display(), e))?;
let mut contents = String::new();
file.read_to_s... | {
// TODO: Deadletter the file name as unsupported
println!("possible TODO found in unsupported file: {:#?}", path);
continue;
} | conditional_block |
nvm_buffer.rs | use std::cmp;
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::ptr;
use block::{AlignedBytes, BlockSize};
use nvm::NonVolatileMemory;
use {ErrorKind, Result};
/// ジャーナル領域用のバッファ.
///
/// 内部の`NonVolatileMemory`実装のアライメント制約(i.e., ストレージのブロック境界に揃っている)を満たしつつ、
/// ジャーナル領域への追記を効率化するのが目的.
#[derive(Debug)]
pub struct ... | tState,
"self.position={}, write_len={}, self.len={}",
self.position(),
write_len,
self.capacity()
);
Ok(())
}
}
impl<N: NonVolatileMemory> NonVolatileMemory for JournalNvmBuffer<N> {
fn sync(&mut self) -> Result<()> {
track!(self.flush_wri... | ),
ErrorKind::Inconsisten | conditional_block |
nvm_buffer.rs | use std::cmp;
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::ptr;
use block::{AlignedBytes, BlockSize};
use nvm::NonVolatileMemory;
use {ErrorKind, Result};
/// ジャーナル領域用のバッファ.
///
/// 内部の`NonVolatileMemory`実装のアライメント制約(i.e., ストレージのブロック境界に揃っている)を満たしつつ、
/// ジャーナル領域への追記を効率化するのが目的.
#[derive(Debug)]
pub struct ... | ))?;
assert_eq!(&buffer.nvm().as_bytes()[0..6], b"foobar");
Ok(())
}
#[test]
fn write_seek_write_flush() -> TestResult {
// "連続"の判定は、ブロック単位で行われる
// (シークしてもブロックを跨がないと"連続していない"と判定されない)
let mut buffer = new_buffer();
track_io!(buffer.write_all(b"foo"))?;
... | lush( | identifier_name |
nvm_buffer.rs | use std::cmp;
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::ptr;
use block::{AlignedBytes, BlockSize};
use nvm::NonVolatileMemory;
use {ErrorKind, Result};
/// ジャーナル領域用のバッファ.
///
/// 内部の`NonVolatileMemory`実装のアライメント制約(i.e., ストレージのブロック境界に揃っている)を満たしつつ、
/// ジャーナル領域への追記を効率化するのが目的.
#[derive(Debug)]
pub struct ... | // - 書き込みバッファのカバー範囲に重複する領域に対して、読み込み要求が発行された場合:
// - 書き込みバッファの内容をフラッシュして、内部NVMに同期した後に、該当読み込み命令を処理
// - 書き込みバッファのカバー範囲に重複しない領域に対して、書き込み要求が発行された場合:
// - 現状の書き込みバッファのデータ構造では、ギャップ(i.e., 連続しない複数部分領域)を表現することはできない
// - そのため、一度古いバッファの内容をフラッシュした後に、該当書き込み要求を処理するためのバッファを作成する
//
// ジャーナル領域が発行した書き込み... | // - ジャーナル領域は定期的に本メソッドを呼び出す | random_line_split |
nvm_buffer.rs | use std::cmp;
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::ptr;
use block::{AlignedBytes, BlockSize};
use nvm::NonVolatileMemory;
use {ErrorKind, Result};
/// ジャーナル領域用のバッファ.
///
/// 内部の`NonVolatileMemory`実装のアライメント制約(i.e., ストレージのブロック境界に揃っている)を満たしつつ、
/// ジャーナル領域への追記を効率化するのが目的.
#[derive(Debug)]
pub struct ... | ite_buf.aligned_resize(end);
(&mut self.write_buf[start..end]).copy_from_slice(buf);
self.position += buf.len() as u64;
self.maybe_dirty = true;
Ok(buf.len())
} else {
// 領域に重複がないので、一度バッファの中身を書き戻す
track!(self.flush_write_buf())?;
... | et) as usize;
let end = start + buf.len();
self.wr | identifier_body |
bootstrap.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import collections
import json
import logging
import multiprocessing
import subprocess
import sys
import time
import co... | 'enable_auto_commit': False, # We don't actually commit but this is just for good measure
}
consumer = KafkaConsumer(**consumer_config)
# This call populates topic metadata for all topics in the cluster.
# Needed as missing topic metadata can cause the below call to retrieve
# partition in... | random_line_split | |
bootstrap.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import collections
import json
import logging
import multiprocessing
import subprocess
import sys
import time
import co... |
if repositories_to_clone:
logger.error('did not receive expected sync messages for %s' % repositories_to_clone)
# Add errors to audit output
for repo in repositories_to_clone:
outputdata[repo].append('did not receive sync message')
# Process clones... | logger.info('processing messages for partition %s' % partition)
for message in messages:
payload = message.value
# Ignore heartbeat messages
if payload['name'] == 'heartbeat-1':
continue
if payload['path'] in repositories_... | conditional_block |
bootstrap.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import collections
import json
import logging
import multiprocessing
import subprocess
import sys
import time
import co... | ():
'''hgweb component of the vcsreplicator bootstrap procedure. Takes a
vcsreplicator config path on the CLI and takes a JSON data structure
on stdin'''
import argparse
# Parse CLI args
parser = argparse.ArgumentParser()
parser.add_argument('config', help='Path of config file to load')
... | hgweb | identifier_name |
bootstrap.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import collections
import json
import logging
import multiprocessing
import subprocess
import sys
import time
import co... |
def hgssh():
'''hgssh component of the vcsreplicator bootstrap procedure.'''
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('config', help='Path to config file')
parser.add_argument('hg', help='Path to hg executable for use in bootstrap process')
parser.add_argument('... | '''Process events using the message handler in the order they
arrived in the queue
'''
for config, payload in events:
message_handler(config, payload) | identifier_body |
linked_list.rs | //! An intrusive linked list.
//!
//! ```ignore
//! use intrusive::{define_list_node, linked_list::{List, ListLink}};
//! use std::sync::Arc;
//!
//! struct Thread {
//! id: usize,
//! link: ListLink<ThreadsNode>,
//! }
//!
//! define_list_node!(ThreadsNode, Arc<Thread>, link);
//!
//! let mut threads = List::<... |
link.prev.set(self.tail);
link.next.set(None);
self.tail = Some(link_ptr);
Ok(())
}
}
/// Pops the element at the beginning of the list. `O(1)`.
pub fn pop_front(&mut self) -> Option<L::Elem> {
match self.head {
Some(head) => uns... | {
self.head = Some(link_ptr);
} | conditional_block |
linked_list.rs | //! An intrusive linked list.
//!
//! ```ignore
//! use intrusive::{define_list_node, linked_list::{List, ListLink}};
//! use std::sync::Arc;
//!
//! struct Thread {
//! id: usize, | //!
//! let mut threads = List::<ThreadsNode>::new();
//! let thread1 = Arc::new(Thread { id: 1, link: Default::default() });
//! threads.push_back(thread1);
//! ```
//!
use core::cell::Cell;
use core::fmt::{self, Debug, Formatter};
use core::marker::PhantomData;
use core::ops::ControlFlow;
use core::ptr::NonNull;
use ... | //! link: ListLink<ThreadsNode>,
//! }
//!
//! define_list_node!(ThreadsNode, Arc<Thread>, link); | random_line_split |
linked_list.rs | //! An intrusive linked list.
//!
//! ```ignore
//! use intrusive::{define_list_node, linked_list::{List, ListLink}};
//! use std::sync::Arc;
//!
//! struct Thread {
//! id: usize,
//! link: ListLink<ThreadsNode>,
//! }
//!
//! define_list_node!(ThreadsNode, Arc<Thread>, link);
//!
//! let mut threads = List::<... | (&self) -> Iter<'_, L> {
Iter {
current: self.head,
_pd: &PhantomData,
}
}
}
impl<L: ListNode> Default for List<L> {
fn default() -> Self {
Self::new()
}
}
pub struct Iter<'a, L: ListNode> {
current: Option<NonNull<ListLink<L>>>,
_pd: &'a PhantomData... | iter | identifier_name |
view.rs | // Copyright (c) 2021 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be ... | (&self, _sampler: &Sampler) -> bool {
true /* FIXME */
}
}
unsafe impl<I> ImageViewAbstract for ImageView<I>
where
I: ImageAccess,
{
#[inline]
fn image(&self) -> &dyn ImageAccess {
&self.image
}
#[inline]
fn inner(&self) -> &UnsafeImageView {
&self.inner
}
... | can_be_sampled | identifier_name |
view.rs | // Copyright (c) 2021 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be ... |
/// Returns true if the view doesn't use components swizzling.
///
/// Must be true when the view is used as a framebuffer attachment or TODO: I don't remember
/// the other thing.
fn identity_swizzle(&self) -> bool;
/// Returns the [`ImageViewType`] of this image view.
fn ty(&self) -> Ima... | fn array_layers(&self) -> Range<u32>;
/// Returns the format of this view. This can be different from the parent's format.
fn format(&self) -> Format; | random_line_split |
view.rs | // Copyright (c) 2021 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be ... |
#[inline]
fn format(&self) -> Format {
(**self).format()
}
#[inline]
fn identity_swizzle(&self) -> bool {
(**self).identity_swizzle()
}
#[inline]
fn ty(&self) -> ImageViewType {
(**self).ty()
}
#[inline]
fn can_be_sampled(&self, sampler: &Sampler)... | {
(**self).array_layers()
} | identifier_body |
documentDeltaConnection.ts | /*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import { assert } from "@fluidframework/common-utils";
import {
IAnyDriverError,
IDocumentDeltaConnection,
IDocumentDeltaConnectionEvents,
} from "@fluidframework/driver-definitions";
import { cr... | extends EventEmitterWithErrorHandling<IDocumentDeltaConnectionEvents>
implements IDocumentDeltaConnection, IDisposable
{
static readonly eventsToForward = ["nack", "op", "signal", "pong"];
// WARNING: These are critical events that we can't miss, so registration for them has to be in place at all times!
// Includ... | */
export class DocumentDeltaConnection | random_line_split |
documentDeltaConnection.ts | /*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import { assert } from "@fluidframework/common-utils";
import {
IAnyDriverError,
IDocumentDeltaConnection,
IDocumentDeltaConnectionEvents,
} from "@fluidframework/driver-definitions";
import { cr... | () {
assert(
this._disposed || this.socket.connected,
0x244 /* "Socket is closed, but connection is not!" */,
);
return this._disposed;
}
/**
* Flag to indicate whether the DocumentDeltaConnection is expected to still be capable of sending messages.
* After disconnection, we flip this to prevent any ... | disposed | identifier_name |
documentDeltaConnection.ts | /*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import { assert } from "@fluidframework/common-utils";
import {
IAnyDriverError,
IDocumentDeltaConnection,
IDocumentDeltaConnectionEvents,
} from "@fluidframework/driver-definitions";
import { cr... |
private removeTrackedListeners() {
for (const [event, listener] of this.trackedListeners.entries()) {
this.socket.off(event, listener);
}
// removeTrackedListeners removes all listeners, including connection listeners
this.removeConnectionListeners();
this.removeEarlyOpHandler();
this.removeEarlySign... | {
this.socket.on(event, listener);
assert(!this.trackedListeners.has(event), 0x20e /* "double tracked listener" */);
this.trackedListeners.set(event, listener);
} | identifier_body |
documentDeltaConnection.ts | /*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import { assert } from "@fluidframework/common-utils";
import {
IAnyDriverError,
IDocumentDeltaConnection,
IDocumentDeltaConnectionEvents,
} from "@fluidframework/driver-definitions";
import { cr... |
this.closeSocketCore(error);
}
protected closeSocketCore(error: IAnyDriverError) {
this.disconnect(error);
}
/**
* Disconnect from the websocket, and permanently disable this DocumentDeltaConnection and close the socket.
* However the OdspDocumentDeltaConnection differ in dispose as in there we don't clo... | {
// This would be rare situation due to complexity around socket emitting events.
return;
} | conditional_block |
acc.js | //初始化加载.
var proc;
proc=this.parent.proc;
var serialNumber ={num1:"登记编号",num2:"归档号",num3:"房地产证号"};
var activName = "受理";//proc.activName;
var proc_node = "受理";//proc.activName;
//var activName = "初审";
var proc_id = 1000025915;//proc.procId;
//var proc_id = 1000016427;
//var proc_id = 1;
var _init_form_data; //... | length==0){
// message= '请选择起始日期!';
// result.message=message;
// result.result=false;
// return result;
//
// }
// if($.trim(zzrq).length==0){
//
// message= '请选择终止日期!';
// result.message=message;
// result.result=false;
// return result;
//
// }
// if($.trim(fwxz).length==0){
// m... | 1.string5){
// alert($("#add_app_form").serialize());
var djjk = $("#djjk").val();
var qdfs = $('input[name="get_mode"]').val();
var synx = $("#synx").val();
var qsrq = $('input[name="start_date"]').val();
var zzrq = $('input[name="end_date"]').val();
var fwxz = $('input[name="house_attr"]').val();
var ... | identifier_body |
acc.js | //初始化加载.
var proc;
proc=this.parent.proc;
var serialNumber ={num1:"登记编号",num2:"归档号",num3:"房地产证号"};
var activName = "受理";//proc.activName;
var proc_node = "受理";//proc.activName;
//var activName = "初审";
var proc_id = 1000025915;//proc.procId;
//var proc_id = 1000016427;
//var proc_id = 1;
var _init_form_data; //... | field : 'app_tel'
}, {
title : '法定代表人',
field : 'legal_name'
}, {
title : '代理人',
field : 'agent_name'
},
{
title : '代理人证件类型',
field : 'agent_cer_type',
formatter : function(value) {
if(value == '001'){
return '身份证';
};
if(value == '002'){
... |
}, {
title : '联系电话', | random_line_split |
acc.js | //初始化加载.
var proc;
proc=this.parent.proc;
var serialNumber ={num1:"登记编号",num2:"归档号",num3:"房地产证号"};
var activName = "受理";//proc.activName;
var proc_node = "受理";//proc.activName;
//var activName = "初审";
var proc_id = 1000025915;//proc.procId;
//var proc_id = 1000016427;
//var proc_id = 1;
var _init_form_data; //... | 名称: dowatch
*功能说明: 查看登记单元详细信息
*参数说明: 无
*返 回 值: 无
*函数作者: xuzz
*创建日期: 2014-03-27
*修改历史:
***********************************************************************************/
function dowatch(button){
var row = $('#table_house').datagrid('getSelected');
var obj={};
obj.WHERE_CODE=row.CODE;
obj.REG_... | *
*函数 | identifier_name |
acc.js | //初始化加载.
var proc;
proc=this.parent.proc;
var serialNumber ={num1:"登记编号",num2:"归档号",num3:"房地产证号"};
var activName = "受理";//proc.activName;
var proc_node = "受理";//proc.activName;
//var activName = "初审";
var proc_id = 1000025915;//proc.procId;
//var proc_id = 1000016427;
//var proc_id = 1;
var _init_form_data; //... | if(data){
//alert(JSON.stringify(data));
$("#fdczh").val(data.cer_no);
$("#djjk").val(data.reg_value);
$("#qdfs").combodict('setValue',data.get_mode);
$("#synx").val(data.lu_term);
if(data.start_date){
var qsrq = data.start_date;
$("#qsrq").datebox('setValue',qsr... | nership.action?time="+new Date()+"&proc_id="+proc_id,
success:function(data){
| conditional_block |
PerceptronClassifier.py | #!/usr/bin/env python
# encoding: utf-8
"""
@version: V1.2
@author: muyeby
@contact: bxf_hit@163.com
@site: http://muyeby.github.io
@software: PyCharm
@file: assignment2.py
@time: 16-7-7 下午8:44
"""
from __future__ import print_function
from copy import copy
import time
class PerceptronClassifier(object):
# The per... | # print '初始预测:', Z, self._score(X, Z), 'Y的分数', self._score(X, Y)
# print self.W[Y]
tmp = self._score(X,Y)
# Your code here. If the predict is incorrect, perform the perceptron update
n_errors += 1
fo... | Z = self._predict(X)
if Z != Y: | random_line_split |
PerceptronClassifier.py | #!/usr/bin/env python
# encoding: utf-8
"""
@version: V1.2
@author: muyeby
@contact: bxf_hit@163.com
@site: http://muyeby.github.io
@software: PyCharm
@file: assignment2.py
@time: 16-7-7 下午8:44
"""
from __future__ import print_function
from copy import copy
import time
class PerceptronClassifier(object):
# The per... | self.best_W = copy(self.W)
def extract_features(self, words, i, prev_tag=None, add=True):
'''
Extract features from words and prev POS tag, if `add` is True, also insert the feature
string to the feature_alphabet.
Parameters
----------
words: list(str)
... | rors = 0
print('training iteration #%d' % it)
for X, Y in instances:
# Your code here, ake a prediction and give it to Z
Z = self._predict(X)
if Z != Y:
# print '初始预测:', Z, self._score(X, Z), 'Y的分数', self._score(X, Y)
... | conditional_block |
PerceptronClassifier.py | #!/usr/bin/env python
# encoding: utf-8
"""
@version: V1.2
@author: muyeby
@contact: bxf_hit@163.com
@site: http://muyeby.github.io
@software: PyCharm
@file: assignment2.py
@time: 16-7-7 下午8:44
"""
from __future__ import print_function
from copy import copy
import time
class PerceptronClassifier(object):
# The per... | ):
'''
Extract features from words and prev POS tag, if `add` is True, also insert the feature
string to the feature_alphabet.
Parameters
----------
words: list(str)
The words list
i: int
The position
prev_tag: str
Prev... | g=None, add=True | identifier_name |
PerceptronClassifier.py | #!/usr/bin/env python
# encoding: utf-8
"""
@version: V1.2
@author: muyeby
@contact: bxf_hit@163.com
@site: http://muyeby.github.io
@software: PyCharm
@file: assignment2.py
@time: 16-7-7 下午8:44
"""
from __future__ import print_function
from copy import copy
import time
class PerceptronClassifier(object):
# The per... | ag=None):
'''
Make prediction on list of words
Parameters
----------
words: list(str)
The words list
i: int
The position
prev_tag: str
Previous POS tag
Return
------
y: int
The predicted lab... | n features and label t
Parameters
----------
features: list(int)
The hashed features
t: int
The index of label
Return
------
best_y: int
The highest scored label's index
'''
pred_scores = [self._score(features,... | identifier_body |
contSpec.py | #
# 7/2023: allowing an optional weight column in the input data file
# improving encapsulation of functions
# Help to find continuous spectrum
# March 2019 major update:
# (i) added plateau modulus G0 (also in pyReSpect-time) calculation
# (ii) following Hansen Bayesian interpretation of Tikhonov to extrac... | #
par = readInput('inp.dat')
H, lamC = getContSpec(par) | # Read input parameters from file "inp.dat" | random_line_split |
contSpec.py | #
# 7/2023: allowing an optional weight column in the input data file
# improving encapsulation of functions
# Help to find continuous spectrum
# March 2019 major update:
# (i) added plateau modulus G0 (also in pyReSpect-time) calculation
# (ii) following Hansen Bayesian interpretation of Tikhonov to extrac... | (H, kernMat):
"""
Function: kernelD(input)
outputs the (n*ns) dimensional matrix DK(H)(t)
It approximates dK_i/dH_j = K * e(H_j):
Input: H = substituted CRS,
kernMat = matrix for faster kernel evaluation
Output: DK = Jacobian of H
"""
n = kern... | kernelD | identifier_name |
contSpec.py | #
# 7/2023: allowing an optional weight column in the input data file
# improving encapsulation of functions
# Help to find continuous spectrum
# March 2019 major update:
# (i) added plateau modulus G0 (also in pyReSpect-time) calculation
# (ii) following Hansen Bayesian interpretation of Tikhonov to extrac... |
else:
lamC, lam, rho, eta, logP, Hlam = lcurve(Gexp, wexp, Hgs, kernMat, par)
else:
lamC = par['lamC']
if par['verbose']:
te = time.time() - tic
print('({1:.1f} seconds)\n(*) Extracting CRS, ...\n\t... lamC = {0:0.3e}; '.
format(lamC, te), end="")
... | lamC, lam, rho, eta, logP, Hlam = lcurve(Gexp, wexp, Hgs, kernMat, par, G0) | conditional_block |
contSpec.py | #
# 7/2023: allowing an optional weight column in the input data file
# improving encapsulation of functions
# Help to find continuous spectrum
# March 2019 major update:
# (i) added plateau modulus G0 (also in pyReSpect-time) calculation
# (ii) following Hansen Bayesian interpretation of Tikhonov to extrac... |
def kernelD(H, kernMat):
"""
Function: kernelD(input)
outputs the (n*ns) dimensional matrix DK(H)(t)
It approximates dK_i/dH_j = K * e(H_j):
Input: H = substituted CRS,
kernMat = matrix for faster kernel evaluation
Output: DK = Jacobian of H
"""
... | """
HELPER FUNCTION for optimization: Get Jacobian J
returns a (n+nl * ns) matrix Jr; (ns + 1) if G0 is also supplied.
Jr_(i, j) = dr_i/dH_j
It uses kernelD, which approximates dK_i/dH_j, where K is the kernel
"""
n = kernMat.shape[0];
ns = kernMat.shape[1];
nl = ... | identifier_body |
cipher_functions.py | # Functions for running an encryption or decryption.
# The values of the two jokers.
JOKER1 = 27
JOKER2 = 28
# Write your functions here:
def clean_message(message):
'''(str) -> str
REQ: message contains only 1 line of text.
REQ: len(message) > 0
>>> clean_message('fighting,.,.,.,!!Easy5747291-... |
def swap_cards(deck_of_crds, index):
'''
(list of int, int) -> NoneType
REQ: len(d_of_crds) >= 1
REQ: 0 < index < len(d_of_crds)
>>> swap_cards([1,2,4,6], 2)
[1,2,6,4]
>>> swap_cards([1,2,4,5,6,7,8,9,10,12,21], 10)
[21, 2, 4, 5, 6, 7, 8, 9, 10, 12, 1]
Return... | decripted_vlue = chr(decripted_vlue + 65)
return decripted_vlue | random_line_split |
cipher_functions.py | # Functions for running an encryption or decryption.
# The values of the two jokers.
JOKER1 = 27
JOKER2 = 28
# Write your functions here:
def clean_message(message):
'''(str) -> str
REQ: message contains only 1 line of text.
REQ: len(message) > 0
>>> clean_message('fighting,.,.,.,!!Easy5747291-... | '''(file open for reading) -> list of int
REQ: len(file) > 0
REQ: file must contain atleast 1 line, and must all be int
Read and return the contents of the file as a list of int.
'''
counter = 0
# create a empty list
list_of_str = list()
# Read through all the lines in the file
... | identifier_body | |
cipher_functions.py | # Functions for running an encryption or decryption.
# The values of the two jokers.
JOKER1 = 27
JOKER2 = 28
# Write your functions here:
def clean_message(message):
'''(str) -> str
REQ: message contains only 1 line of text.
REQ: len(message) > 0
>>> clean_message('fighting,.,.,.,!!Easy5747291-... |
# Find the last index number and store it
last_idx_vlue = (len(deck_of_crds) -1)
while (index_joker_1 < last_idx_vlue):
# Store the values before JOKER1 and place them at top of deck.
values_bfr_JOKER1 = deck_of_crds.pop()
deck_of_crds.... | values_bfr_JOKER1 = deck_of_crds.pop(0)
# Insert those values before JOKER1
deck_of_crds.insert(index_joker_1, values_bfr_JOKER1)
counter +=1 | conditional_block |
cipher_functions.py | # Functions for running an encryption or decryption.
# The values of the two jokers.
JOKER1 = 27
JOKER2 = 28
# Write your functions here:
def clean_message(message):
'''(str) -> str
REQ: message contains only 1 line of text.
REQ: len(message) > 0
>>> clean_message('fighting,.,.,.,!!Easy5747291-... | (deck_of_crds):
'''(list of int) -> int
REQ: len(deck_of_crds) > 0
REQ: FIle contains JOKER1 and JOKER2
>>> get_next_value([1 ,4 ,7 ,10 ,13 ,16 ,19 ,22 ,25 ,28 ,3, 6, 9 ,
12 ,15 ,18 ,21 ,24 ,27, 2, 5, 8 ,11 ,14 ,17 ,20 ,23, 26]}
11
Return the next potential keystream value.
'''
... | get_next_value | identifier_name |
types.rs | //! Перечисляемые типы данных, используемые при работе с библиотекой
use std::u32;
/// Возможные типы данных базы данных
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(deprecated)]// Позволяем deprecated внутри перечисления из-за https://github.com/rust-lang/ru... | /// Specifies the various modes of operation
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(dead_code)]
pub enum AuthMode {
/// In this mode, the user session context returned can only ever be set with the server context
/// specified in `svchp`. For encoding, the server handle uses the setting in the environ... | }
impl Default for AttachMode {
fn default() -> Self { AttachMode::Default }
} | random_line_split |
types.rs | //! Перечисляемые типы данных, используемые при работе с библиотекой
use std::u32;
/// Возможные типы данных базы данных
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(deprecated)]// Позволяем deprecated внутри перечисления из-за https://github.com/rust-lang/ru... | /// For encoding, this value tells the server handle to use the setting in the environment handle.
Default = 0,
/// Use connection pooling.
CPool = 1 << 9,
}
impl Default for AttachMode {
fn default() -> Self { AttachMode::Default }
}
/// Specifies the various modes of operation
#[derive(Clone, Copy, Debug, P... | de {
| identifier_name |
traits.rs | //! Architecture trait
use crate::analysis::{Disasm, Mappable, RequisiteSet, Result, Trace};
use crate::arch::ArchName;
use crate::ast::Literal;
use crate::cli::Nameable;
use crate::maths::{Numerical, Popcount};
use crate::memory::{Memory, Offset, Pointer, PtrNum};
use crate::reg::{Bitwise, State};
use num::Bounded;
u... | at: Self::PtrVal,
bus: &Memory<Self>,
state: State<Self>,
trace: &mut Trace<Self>,
) -> Result<(State<Self>, Self::PtrVal), Self>;
}
/// Trait for type-erased structures that accept an architecture parameter and
/// are intended to be accessed with the `with_architecture!` macro.
pu... | &self, | random_line_split |
api.py | # -*- coding: utf-8 -*-
import os
import datetime
import arrow
import functools
import pandas as pd
import numpy as np
from jaqs.data import DataApi
from urllib.parse import urlencode
from carp.util import log
try:
import simplejson as json
except ImportError:
import json
#__CARP_ROOT_PATH = '/tmp'
#
#LOCAL_C... | # TURNOVER = 'turnover'
# VWAP = 'vwap'
# OI = 'oi'
# SETTLE = 'settle'
#
# def __init__(self, df):
# BaseDataFrame.__init__(self, df)
# self.set_index(BarDataFrame.TRADE_DATE)
#
def singleton(cls):
instance = {}
def geninstance(*args, **kwargs):
if cls not in instance:
... | # CLOSE = 'close'
# VOLUME = 'volume' | random_line_split |
api.py | # -*- coding: utf-8 -*-
import os
import datetime
import arrow
import functools
import pandas as pd
import numpy as np
from jaqs.data import DataApi
from urllib.parse import urlencode
from carp.util import log
try:
import simplejson as json
except ImportError:
import json
#__CARP_ROOT_PATH = '/tmp'
#
#LOCAL_C... | fields=_fields)
log.debug('request bar')
return df
# industry failed
# def industry(self, **industrys):
# df, msg = self.__api.query(
# view="lb.secIndustry",
# fields="",
# #filter="industry1_name=金融&industry2_name=金融&industry_s... | y_login()
df, msg = self.__api.bar(symbol=_symbol,
trade_date=_trade_date,
freq=_freq,
| identifier_body |
api.py | # -*- coding: utf-8 -*-
import os
import datetime
import arrow
import functools
import pandas as pd
import numpy as np
from jaqs.data import DataApi
from urllib.parse import urlencode
from carp.util import log
try:
import simplejson as json
except ImportError:
import json
#__CARP_ROOT_PATH = '/tmp'
#
#LOCAL_C... | data_format='pandas')
log.debug('request jz.instrumentInfo')
return df
# 停复牌resu_date 未设置
# def secsusp(self, _filter="", _fields=""):
# self.__lazy_login()
# df, msg = self.__api.query(
# view="lb.secSusp",
# fields=_fields,
# ... | def instrumentinfo(self, _fields="", _filter="inst_type=1&status=1&market=SH,SZ"):
self.__lazy_login()
df, msg = self.__api.query(view="jz.instrumentInfo", fields=_fields,
filter=_filter,
| conditional_block |
api.py | # -*- coding: utf-8 -*-
import os
import datetime
import arrow
import functools
import pandas as pd
import numpy as np
from jaqs.data import DataApi
from urllib.parse import urlencode
from carp.util import log
try:
import simplejson as json
except ImportError:
import json
#__CARP_ROOT_PATH = '/tmp'
#
#LOCAL_C... | log.debug('request bar')
return df
# industry failed
# def industry(self, **industrys):
# df, msg = self.__api.query(
# view="lb.secIndustry",
# fields="",
# #filter="industry1_name=金融&industry2_name=金融&industry_src=中证",
# #filter... | ields)
| identifier_name |
ChineseCheckersBoard.py | #Class ChineseCheckers: This is the actual Distributed Chinese Checkers
#Game Board. This class has alot of get and set functions to change the state
#of the game board and manipulate it.
#
#**NOTE**
# The design of this class is that such the AI will be the only one to
#manipulate the 'state' of the board. Important ... | (self, squareNum, newState):
self.squareList[squareNum].setState(newState)
def setStateOffset(self, squareNum, newState):
self.squareList[squareNum-1].setState(newState)
def getAdjacent(self, squareNum):
return self.squareList[squareNum].adjacent
def getAdjacentOffset(self, squareNum... | setState | identifier_name |
ChineseCheckersBoard.py | #Class ChineseCheckers: This is the actual Distributed Chinese Checkers
#Game Board. This class has alot of get and set functions to change the state
#of the game board and manipulate it.
#
#**NOTE**
# The design of this class is that such the AI will be the only one to
#manipulate the 'state' of the board. Important ... | return self.adjacent
def setState(self, newState):
self.state = newState
def getState(self):
return self.state
def getNum(self):
return self.tileNum | self.adjacent.append(x)
def getAdjacent(self): | random_line_split |
ChineseCheckersBoard.py | #Class ChineseCheckers: This is the actual Distributed Chinese Checkers
#Game Board. This class has alot of get and set functions to change the state
#of the game board and manipulate it.
#
#**NOTE**
# The design of this class is that such the AI will be the only one to
#manipulate the 'state' of the board. Important ... |
#---------------------------------------------------------------#
#CheckersSquare: This is the base object for
#a square inside of a chinese checkers game. By 'square', I mean
#a movable location to which a peice can be placed or moved to.
#
#A Square has possible 7 states
# A state of 0 ... | self.squareList[x].setState(squares[x]) | conditional_block |
ChineseCheckersBoard.py | #Class ChineseCheckers: This is the actual Distributed Chinese Checkers
#Game Board. This class has alot of get and set functions to change the state
#of the game board and manipulate it.
#
#**NOTE**
# The design of this class is that such the AI will be the only one to
#manipulate the 'state' of the board. Important ... |
def getAdjacent(self, squareNum):
return self.squareList[squareNum].adjacent
def getAdjacentOffset(self, squareNum):
return self.squareList[squareNum-1].adjacent
def getStates(self):
retList = []
for x in range(121):
retList.append(self.squareList[x].getState())
... | self.squareList[squareNum-1].setState(newState) | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.