class Author(db.Model): id = Column(Integer, primary_key=True) name = Column(String(255), nullable=False) books = relationship('Book') @staticmethod def search(name): author = Author.query.filter_by(name=name).first() if author is not None: return author return None # staticn method to return instance of unknown author - TOTO optimize to singleton @staticmethod def unknown_author(): return Author.default('Unknown Author') # Check if author exists, if not create a new author @staticmethod def default(name): author = Author.search(name) if author is None: # Author is not known author = Author(name=name) db.session.add(author) db.session.commit() return author def as_dict(self): return {col.name: getattr(self, col.name) for col in self.__table__.columns}
class User(Base): __tablename__ = "user" id = Column(Integer, primary_key=True, autoincrement=True) username = Column(String(50), nullable=False) def __repr__(self): return self.username
def get_hitting_time(graph, edges, max_length): c = Column(1, 'numerical') value = dict() for edge in edges: value[edge] = __expected_steps(graph, edge, max_length) c.value = value return c
class ShopListView(PicotableListView): model = Shop default_columns = [ Column("logo", _(u"Logo"), display="logo", class_name="text-center", raw=True, ordering=1, sortable=False), Column("name", _(u"Name"), sort_field="translations__name", display="name", filter_config=TextFilter( filter_field="translations__name", placeholder=_("Filter by name...") )), Column("domain", _(u"Domain")), Column("identifier", _(u"Identifier")), Column("status", _(u"Status"), filter_config=ChoicesFilter(choices=ShopStatus.choices)), ] toolbar_buttons_provider_key = "shop_list_toolbar_provider" mass_actions_provider_key = "shop_list_mass_actions_provider" def get_queryset(self): return Shop.objects.get_for_user(self.request.user) def get_toolbar(self): if E-CommerceSettings.get_setting("E-Commerce_ENABLE_MULTIPLE_SHOPS"): return super(ShopListView, self).get_toolbar() else: return Toolbar.for_view(self)
class AvailabilityExceptionListView(PicotableListView): model = AvailabilityException url_identifier = "discounts_availability_exception" default_columns = [ Column( "name", _("Exception Name"), sort_field="name", display="name", filter_config=TextFilter(filter_field="name", placeholder=_("Filter by name...")) ), Column( "start_datetime", _("Start Date and Time"), display="format_start_datetime", filter_config=DateRangeFilter() ), Column( "end_datetime", _("End Date and Time"), display="format_end_datetime", filter_config=DateRangeFilter() ) ] def get_queryset(self): return AvailabilityException.objects.filter(shops=get_shop(self.request)) def format_start_datetime(self, instance, *args, **kwargs): return get_locally_formatted_datetime(instance.start_datetime) if instance.start_datetime else "" def format_end_datetime(self, instance, *args, **kwargs): return get_locally_formatted_datetime(instance.end_datetime) if instance.end_datetime else ""
class PageListView(PicotableListView): url_identifier = "simple_cms.page" model = Page default_columns = [ Column( "title", _(u"Title"), sort_field="translations__title", display="title", linked=True, filter_config=TextFilter( operator="startswith", filter_field="translations__title" ) ), Column("available_from", _(u"Available from")), Column("available_to", _(u"Available to")), Column("created_by", _(u"Created by")), Column("created_on", _(u"Date created")), ] def get_object_abstract(self, instance, item): return [ {"text": "%s" % (instance or _("Page")), "class": "header"}, {"title": _(u"Available from"), "text": item.get("available_from")}, {"title": _(u"Available to"), "text": item.get("available_to")} if instance.available_to else None ] def get_queryset(self): return super(PageListView, self).get_queryset().for_shop(get_shop(self.request)).not_deleted()
def _get_column(self, model, field, known_names, identifier): if not self._valid_field(field.name): return None field_name = field.verbose_name.title() if field_name in known_names: field_name = "%s %s" % (model.__name__, field_name) display = "%s__%s" % (identifier, field.name) if identifier else field.name column = Column( "%s_%s" % (model.__name__.lower(), field.name), field_name, display=display ) column, is_special = self.handle_special_column(field, column) if not is_special: if isinstance(field, CharField): column.filter_config = TextFilter(placeholder=field_name) if isinstance(field, EnumIntegerField): column.filter_config = ChoicesFilter(field.choices) if isinstance(field, BooleanField): column.filter_config = true_or_false_filter return column
def get_all_node_degree(graph): c = Column(1, 'numerical') value = dict() for v in graph.nodes(): value[v] = graph.degree(v) c.value = value return c
def read_feature_column_major(filename, column_type): with open(filename, 'r') as f: line = f.readline().strip() entry = line.split(',') column_name = entry[1:] column_num = len(column_name) assert len(column_type) == column_num # generate the list of Columns for later usage columns = list() for t in column_type: c = Column(1, t) c.value = dict() columns.append(c) # read in rows for line in f: entry = (line.strip()).split(',') assert len(entry) == (column_num + 1) row_id = int(entry[0]) for i, column in enumerate(columns): value = entry[i+1].strip() if len(value) == 0 or value == 'None': continue if column.type == 'categorical': column.value[row_id] = value elif column.type == 'numerical': column.value[row_id] = float(value) return (columns, column_name)
class ContactGroupListView(PicotableListView): model = ContactGroup default_columns = [ Column("name", _(u"Name"), sort_field="translations__name", display="name", filter_config=TextFilter( filter_field="translations__name", placeholder=_("Filter by name...") )), Column("n_members", _(u"Number of Members")), ] toolbar_buttons_provider_key = "contact_group_list_toolbar_provider" mass_actions_provider_key = "contact_group_list_mass_actions_provider" def get_queryset(self): return ContactGroup.objects.all_except_defaults().annotate(n_members=Count("members")) def get_context_data(self, **kwargs): context = super(ContactGroupListView, self).get_context_data(**kwargs) if self.request.user.is_superuser: settings_button = SettingsActionButton.for_model(ContactGroup, return_url="contact_group") else: settings_button = None context["toolbar"] = Toolbar([ NewActionButton("E-Commerce_admin:contact_group.new"), settings_button ], view=self) return context
def get_common_categories_col(converted_column, pairs): if converted_column.type != 'categorical': return None c = Column(1, 'numerical') value = dict() for pair in pairs: n1 = pair[0] n2 = pair[1] if n1 in converted_column.value: f1 = converted_column.value[n1] # a set of integers else: f1 = set() if n2 in converted_column.value: f2 = converted_column.value[n2] # a set of integers else: f2 = set() union = f1 | f2 intersect = f1 & f2 if len(union) != 0 and len(intersect) != 0: value[pair] = float(len(intersect)) / len(union) else: pass #value[pair] = 0.0 c.value = value return c
def get_edge_embeddedness(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: value[pair] = len(list(nx.common_neighbors(graph, pair[0], pair[1]))) c.value = value return c
class CampaignListView(PicotableListView): default_columns = [ Column( "name", _(u"Title"), sort_field="name", display="name", linked=True, filter_config=TextFilter(operator="startswith") ), Column("start_datetime", _("Starts")), Column("end_datetime", _("Ends")), Column("active", _("Active"), filter_config=ChoicesFilter(choices=[(0, _("No")), (1, _("Yes"))])), ] toolbar_buttons_provider_key = "campaign_list_toolbar_provider" mass_actions_provider_key = "campaign_list_actions_provider" def get_queryset(self): return self.model.objects.filter(shop=get_shop(self.request)) def start_datetime(self, instance, *args, **kwargs): if not instance.start_datetime: return "" return self._formatted_datetime(instance.start_datetime) def end_datetime(self, instance, *args, **kwargs): if not instance.end_datetime: return "" return self._formatted_datetime(instance.end_datetime) def _formatted_datetime(self, dt): return format_datetime(localtime(dt), locale=get_current_babel_locale()) def get_object_abstract(self, instance, item): return [ {"text": "%s" % (instance or _("CatalogCampaign")), "class": "header"}, ]
class Salary(Base): __tablename__ = 'salary' id = Column(Integer, primary_key=True) date = Column(Date) emp_id = Column(Integer, ForeignKey('employees.emp_id')) basic = Column(Integer) awards = Column(Integer)
class User_property(Base): # 用户管理的主机以及主机组,主机和主机组只能填一个 __tablename__ = 'user_property' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('user_info.id')) server_id = Column(Integer, ForeignKey('server_info.id')) server_group = Column(Integer, ForeignKey('server_group.id'))
class SupplierListView(PicotableListView): model = Supplier default_columns = [ Column( "name", _(u"Name"), sort_field="name", display="name", filter_config=TextFilter( filter_field="name", placeholder=_("Filter by name...") ) ), Column("type", _(u"Type")), Column("module_identifier", _(u"Module"), display="get_module_display", sortable=True) ] toolbar_buttons_provider_key = "supplier_list_toolbar_provider" mass_actions_provider_key = "supplier_list_mass_actions_provider" def get_queryset(self): return Supplier.objects.filter(Q(shops=get_shop(self.request)) | Q(shops__isnull=True)).not_deleted() def get_module_display(self, instance): return instance.module.name or _("No %s module") % self.model._meta.verbose_name def get_toolbar(self): if settings.E-Commerce_ENABLE_MULTIPLE_SUPPLIERS: return super(SupplierListView, self).get_toolbar() else: return Toolbar.for_view(self)
def get_common_categories_col(converted_column, pairs): if converted_column.type != 'categorical': return None c = Column(1, 'numerical') value = dict() for pair in pairs: n1 = pair[0] n2 = pair[1] if n1 in converted_column.value: f1 = converted_column.value[n1] # a set of integers else: f1 = set() if n2 in converted_column.value: f2 = converted_column.value[n2] # a set of integers else: f2 = set() # TODO Task 6: find the number of common categories, and normalize it # Assume f1,f2 are the set of categories of node1 and node2 respectively # we want to calculate |f1 intersect f2| / |f1 union f2| # (if f1 union f2 is empty set, then the value is 0.0) c.value = value return c
def get_adamic_adar_score(graph, pairs): c = Column(1, 'numerical') # TODO Task_4: EDIT HERE, finish the get_adamic_adar_score function # hint: you can copy the structure from other function # you may use 'math' module in python c.value[pairs[0]] = 1 # delete this line return c
def get_adamic_adar_score(graph, pairs): c = Column(1, 'numerical') # TODO Task_4: EDIT HERE, finish the get_adamic_adar_score function # hint: you can copy the structure from other function # you may use 'math' module in python c.value[pairs[0]] = 1 # delete this line return c
def get_common_categories_col(converted_column, pairs): if converted_column.type != 'categorical': return None c = Column(1, 'numerical') value = dict() for pair in pairs: n1 = pair[0] n2 = pair[1] if n1 in converted_column.value: f1 = converted_column.value[n1] # a set of integers else: f1 = set() if n2 in converted_column.value: f2 = converted_column.value[n2] # a set of integers else: f2 = set() union = f1 | f2 intersect = f1 & f2 if len(union) != 0 and len(intersect) != 0: value[pair] = float(len(intersect)) / len(union) else: pass #value[pair] = 0.0 c.value = value return c
class Employees(Base): __tablename__ = 'employees' emp_id = Column(Integer, primary_key=True) emp_name = Column(String(20)) birth_date = Column(Date) email = Column(String(50)) dep_id = Column(Integer, ForeignKey('departments.dep_id'))
class CurrencyListView(PicotableListView): model = Currency default_columns = [ Column("name", _("Name"), display="get_currency_display", sortable=False), Column( "code", _(u"Code"), sort_field="code", filter_config=TextFilter( filter_field="code", placeholder=_("Filter by code"), ) ), Column( "decimal_places", _("Decimal places"), display="format_decimal_places", ) ] toolbar_buttons_provider_key = "currency_list_toolbar_provider" mass_actions_provider_key = "currency_list_mass_actions_provider" def format_decimal_places(self, instance): return "{0}".format(instance.decimal_places) def get_currency_display(self, instance): locale = get_current_babel_locale() return locale.currencies.get(instance.code, instance.code)
class ManufacturerListView(PicotableListView): model = Manufacturer default_columns = [ Column( "logo", _(u"Logo"), display="logo", class_name="text-center", raw=True, ordering=1, sortable=False), Column( "name", _(u"Name"), sort_field="name", display="name", filter_config=TextFilter( filter_field="name", placeholder=_("Filter by name...") ) ), ] toolbar_buttons_provider_key = "manufacturer_list_toolbar_provider" mass_actions_provider_key = "manufacturer_list_mass_actions_provider" def get_queryset(self): return Manufacturer.objects.filter(Q(shops=get_shop(self.request)) | Q(shops__isnull=True))
def get_hitting_time(graph, pairs, trials, max_step): c = Column(1, 'numerical') value = dict() pairs_set = set(pairs) hitting_time = dict() for n in graph.nodes(): hitting_time[n] = defaultdict(float) # calculating hitting time for n1 in graph.nodes(): print(n1) # run random walks for given starting node expected_steps = random_walk(graph, n1, trials, max_step) for n2 in expected_steps.keys(): if (n1, n2) in pairs_set or (n2, n1) in pairs_set: hitting_time[n1][n2] = expected_steps[n2] for pair in pairs: n1 = pair[0] n2 = pair[1] if n2 in hitting_time[n1] and n1 in hitting_time[n2]: if hitting_time[n1][n2] == 0.0: hitting_time[n1][n2] = NO_PATH_LENGTH if hitting_time[n2][n1] == 0.0: hitting_time[n2][n1] = NO_PATH_LENGTH value[pair] = hitting_time[n1][n2] + hitting_time[n2][n1] c.value = value return c
def get_hitting_time(graph, pairs, trials, max_step): c = Column(1, 'numerical') value = dict() pairs_set = set(pairs) hitting_time = dict() for n in graph.nodes(): hitting_time[n] = defaultdict(float) # calculating hitting time for n1 in graph.nodes(): print(n1) # run random walks for given starting node expected_steps = random_walk(graph, n1, trials, max_step) for n2 in expected_steps.keys(): if (n1,n2) in pairs_set or (n2,n1) in pairs_set: hitting_time[n1][n2] = expected_steps[n2] for pair in pairs: n1 = pair[0] n2 = pair[1] if n2 in hitting_time[n1] and n1 in hitting_time[n2]: if hitting_time[n1][n2] == 0.0: hitting_time[n1][n2] = NO_PATH_LENGTH if hitting_time[n2][n1] == 0.0: hitting_time[n2][n1] = NO_PATH_LENGTH value[pair] = hitting_time[n1][n2] + hitting_time[n2][n1] c.value = value return c
def vendor(rowCount): t = Table.Table('ecomm_shop', 'vendor') t.add(Column.Column('vendor_id', cDmy.DT_NUM, '999', '', cDmy.FMT_4d)) t.add(Column.Column('vendor_name', cDmy.DT_STR, 'vend-', '', cDmy.FMT_4d)) sql = SqlStatement.SqlStatement(t) return sql.generateInsert() + sql.generateSelect(rowCount)
class User(UserMixin, SurrogatePK, Model): """A user of the app.""" __tablename__ = 'users' username = Column(db.String(80), unique=True, nullable=False) email = Column(db.String(80), unique=True, nullable=False) #: The hashed password password = Column(db.Binary(128), nullable=True) created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) active = Column(db.Boolean(), default=False) def __init__(self, username, email, password=None, **kwargs): """Create instance.""" db.Model.__init__(self, username=username, email=email, **kwargs) if password: self.set_password(password) else: self.password = None def set_password(self, password): """Set password.""" self.password = bcrypt.generate_password_hash(password) def check_password(self, value): """Check password.""" return bcrypt.check_password_hash(self.password, value) @property def full_name(self): """Full user name.""" return '{0} {1}'.format(self.first_name, self.last_name) def __repr__(self): """Represent instance as a unique string.""" return '<User({username!r})>'.format(username=self.username)
class Series(db.Model): id = Column(Integer, primary_key=True) name = Column(String(255), nullable=False) sequence = Column(Integer, default=0) books = relationship('Book') def as_dict(self): return {col.name: getattr(self, col.name) for col in self.__table__.columns}
class StocksListView(PicotableListView): template_name = "E-Commerce/simple_supplier/admin/base_picotable.jinja" model = Product default_columns = [ Column( "sku", _("SKU"), sort_field="product__sku", display="product__sku", linked=True, filter_config=TextFilter(filter_field="product__sku", placeholder=_("Filter by SKU...")) ), Column( "name", _("Name"), sort_field="product__translations__name", display="product__name", linked=True, filter_config=TextFilter(filter_field="product__translations__name", placeholder=_("Filter by name...")) ), Column( "supplier", _("Supplier"), display="supplier", linked=False, filter_config=ChoicesFilter(Supplier.objects.enabled().filter(module_identifier="simple_supplier")) ), Column( "stock_information", _("Stock information"), display="get_stock_information", linked=False, sortable=False, raw=True ), Column( "adjust_stock", _("Adjust stock"), display="get_stock_adjustment_form", sortable=False, linked=False, raw=True ) ] def __init__(self): super(StocksListView, self).__init__() self.columns = self.default_columns def get_object_abstract(self, instance, item): item.update({"_linked_in_mobile": False, "_url": ""}) return [ {"text": item.get("name"), "class": "header"}, {"title": "", "text": item.get("sku")}, {"title": "", "text": " ", "raw": item.get("stock_information")}, {"title": "", "text": " ", "raw": item.get("adjust_stock")}, ] def get_queryset(self): return StockCount.objects.filter( supplier__module_identifier="simple_supplier", supplier__enabled=True, supplier__stock_managed=True, product__deleted=False ).order_by("product__id") def get_context_data(self, **kwargs): context = super(PicotableListView, self).get_context_data(**kwargs) context["toolbar"] = None context["title"] = _("Stock management") return context def get_stock_information(self, instance): return get_stock_information_html(instance.supplier, instance.product) def get_stock_adjustment_form(self, instance): return get_stock_adjustment_div(self.request, instance.supplier, instance.product)
def get_preferential_score(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: nei_x = graph.neighbors(pair[0]) nei_y = graph.neighbors(pair[1]) value[pair] = (len(nei_x) + 1) * (len(nei_y) + 1) c.value = value return c
def get_preferential_score(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: nei_x = graph.neighbors(pair[0]) nei_y = graph.neighbors(pair[1]) value[pair] = (len(nei_x) + 1) * (len(nei_y) + 1) c.value = value return c
def get_edge_embeddedness(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: n1 = pair[0] n2 = pair[1] value[pair] = len(list(nx.common_neighbors(graph, n1, n2))) c.value = value return c
class LabelListView(PicotableListView): model = Label url_identifier = "label" default_columns = [ Column("identifier", _("Identifier")), Column("name", _("Name")), Column("created_on", _("Created on")), Column("modified_on", _("Modified on")), ]
def get_edge_embeddedness(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: # TODO Task_2: EDIT HERE, please find the number of # common neighbors of pair[0] and pair[1] # value[pair] = ooxx pass c.value = value return c
def get_shortest_path_length(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: try: value[pair] = nx.shortest_path_length(graph, pair[0], pair[1]) except: pass c.value = value return c
class ExampleUserModel(UserMixin, PkModel): """Example model class for a user.""" __tablename__ = "testusers" username = Column(db.String(80), unique=True, nullable=False) email = Column(db.String(80), unique=True, nullable=False) def __init__(self, username, email): """Create instance.""" super().__init__(username=username, email=email)
def product(rowCount): t = Table.Table('ecomm_shop', 'product') t.add(Column.Column('product_id', cDmy.DT_NUM, '999', '', cDmy.FMT_4d)) t.add(Column.Column('product_code', cDmy.DT_STR, 'pc-', '', cDmy.FMT_3d)) t.add( Column.Column('description', cDmy.DT_STR, 'prod-desc-', '', cDmy.FMT_16d)) sql = SqlStatement.SqlStatement(t) return sql.generateInsert() + sql.generateSelect(rowCount)
def customer(rowCount): t = Table.Table('ecomm_shop', 'customer') t.add(Column.Column('customer_id', cDmy.DT_NUM, '999', '', cDmy.FMT_4d)) t.add(Column.Column('login_id', cDmy.DT_STR, 'cust_', '', cDmy.FMT_3d)) t.add(Column.Column('password', cDmy.DT_STR, 'pass', '', cDmy.FMT_3d)) sql = SqlStatement.SqlStatement(t) return sql.generateInsert() + sql.generateSelect(rowCount)
def vendor_product_image(rowCount): t = Table.Table('ecomm_shop', 'vendor_product_image') t.add(Column.Column('vendor_product_id', cDmy.DT_NUM, '999', '', cDmy.tbd)) t.add(Column.Column('iteration', cDmy.DT_NUM, '', '1', cDmy.FMT_EMPTY)) t.add( Column.Column('image_path', cDmy.DT_STR, '', '/var/tmp', cDmy.FMT_EMPTY)) sql = SqlStatement.SqlStatement(t) return sql.generateInsert() + sql.generateSelect(rowCount)
def get_jaccards_coefficient(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: nei_x = set(graph.neighbors(pair[0])) nei_y = set(graph.neighbors(pair[1])) # TODO Task_3: EDIT HERE, caculate jaccards_coefficient # for pair[0] and pair[1] # value[pair] = ooxx c.value = value return c
def get_adamic_adar_score(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: common_nei = nx.common_neighbors(graph, pair[0], pair[1]) score = 0.0 for n in common_nei: score += 1.0 / math.log(len(graph.neighbors(n)) + 1) value[pair] = score c.value = value return c
def get_edge_embeddedness(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: n1 = pair[0] n2 = pair[1] # TODO Task_2: EDIT HERE, please find the number of # common neighbors of n1 and n2 # value[pair] = ooxx c.value = value return c
def get_cc_score(graph, pairs): c = Column(1, 'numerical') value = dict() # TODO Task_5: Calculate clustering coefficient score for all pairs # cc = nx.ooooxxxx(graph) # for pair in pairs: # n1 = pair[0] # n2 = pair[1] # value[pair] = xxxxxx value[pairs[0]] = 1 # delete this line c.value = value return c
def get_cc_score(graph, pairs): c = Column(1, 'numerical') value = dict() # calculate clustering coefficient scores for all nodes cc = nx.clustering(graph) for pair in pairs: x = pair[0] y = pair[1] value[pair] = cc[x] + cc[y] c.value = value return c
def get_shortest_path_length(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: try: # TODO Task_1: EDIT HERE, please find shortest # path from pair[0] to pair[1] # value[pair] = ooxx except: pass c.value = value return c
def get_shortest_path_length(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: n1 = pair[0] n2 = pair[1] try: value[pair] = nx.shortest_path_length(graph, n1, n2) except: value[pair] = NO_PATH_LENGTH c.value = value return c
def get_jaccards_coefficient(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: nei_x = set(graph.neighbors(pair[0])) nei_y = set(graph.neighbors(pair[1])) if len(nei_x) == 0 or len(nei_y) == 0: value[pair] = 0.0 else: union = nei_x | nei_y intersect = nei_x & nei_y value[pair] = float(len(intersect)) / len(union) c.value = value return c
def get_shortest_path_length(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: n1 = pair[0] n2 = pair[1] try: # TODO Task_1: EDIT HERE, please find shortest # path from n1 to n2 # value[pair] = ooxx pass except: value[pair] = NO_PATH_LENGTH c.value = value return c
def get_jaccards_coefficient(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: n1 = pair[0] n2 = pair[1] nei_x = set(graph.neighbors(n1)) nei_y = set(graph.neighbors(n2)) # TODO Task_3: EDIT HERE, caculate jaccards_coefficient # for n1 and n2 # value[pair] = ooxxa # Please notice nei_x or nei_y could be empty set value[pair] = 0 #delete this line c.value = value return c
def get_katz_score(graph, edges, beta, max_length): c = Column(1, 'numerical') value = dict() cnt = 0 shortest_path_length = nx.all_pairs_shortest_path_length(graph) for edge in edges: count = __number_of_path(graph, edge, max_length, shortest_path_length) score = 0.0 base = 1.0 for i in range(1, len(count)): base = base * beta score += base * count[i] value[edge] = score cnt += 1 c.value = value return c
def Indels(fil): BadColum = [] columns=Column.column(fil) for k in columns: Indel = re.findall('-',columns[k]) LenIndel = len(Indel) LenColumn = len(columns[k]) if float(LenIndel)/LenColumn>0.5: Pos=int(k) BadColum.append(Pos) else: pass return BadColum
def get_edge_embeddedness(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: # TODO Task_2: EDIT HERE, please find the number of # common neighbors of pair[0] and pair[1] # value[pair] = ooxx c.value = value return c # get all jaccards_coefficent for all pairs def get_jaccards_coefficient(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: nei_x = set(graph.neighbors(pair[0])) nei_y = set(graph.neighbors(pair[1])) # TODO Task_3: EDIT HERE, caculate jaccards_coefficient # for pair[0] and pair[1] # value[pair] = ooxx c.value = value return c # get all adamic/adar scores for all pairs def get_adamic_adar_score(graph, pairs): # TODO Task_4: EDIT HERE, finish the get_adamic_adar_score function return c # get all preferetial scores for all pairs def get_preferential_score(graph, pairs): c = Column(1, 'numerical') value = dict() for pair in pairs: nei_x = graph.neighbors(pair[0]) nei_y = graph.neighbors(pair[1]) value[pair] = (len(nei_x) + 1) * (len(nei_y) + 1) c.value = value return c
def Unique(fil): BadColum = [] columns=Column.column(fil) for k in columns: results=collections.Counter(columns[k]) cunter=0 for key in results: if results[key]==1: cunter=cunter+1 else: pass if float(cunter)/len(columns[k])>=0.5: Pos=int(k) BadColum.append(Pos) else: pass return BadColum
def MoreThan2(fil): BadColum = [] columns=Column.column(fil) for k in columns: results=collections.Counter(columns[k]) number=[] for key in results: number.append(results[key]) greater2=[] for i in range(len(number)): if int(number[i])>2: greater2.append(number[i]) else: pass if len(greater2)==0: Pos=int(k) BadColum.append(Pos) else: pass return BadColum
def get_all_edge_betweenness_centrality(graph): c = Column(1, 'numerical') c.value = nx.edge_betweenness_centrality(graph) return c