language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Python | UTF-8 | 8,430 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
# project: Insight-Churn
# date: 25/01/2017
# author: Deniz Ustebay
# description: Run Logistic Regression Classifier with CV
get accuracy
"""
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database
import psycopg2
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import os
from collections import defaultdict
import time
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
import seaborn as sns
import statsmodels.api as sm
from sklearn import metrics
from sklearn.metrics import confusion_matrix
import itertools
os.chdir('/Users/deniz/Research/Insight_Churn/')
plt.style.use('ggplot')
# %%
data_train = pd.read_pickle('dataset_forLogisticRegression_TRAIN.pkl')
data_test = pd.read_pickle('dataset_forLogisticRegression_TEST.pkl')
print data_train.shape
print data_test.shape
data_train.head()
# %%
features_cols = ['id','churned_in_target', 'city_id','age','years_of_experience',\
'total_holidays_initial','average_client_score','occupation_ratio',\
'double_shift_ratio','office_shifts_ratio']
# keep columns we are interested in
features_train = data_train[features_cols]
features_test = data_test[features_cols]
features_train.head()
# ##
# Scale and adjust dummy variables here
train_cols = features_cols[3:]
X_train = features_train[train_cols]
# city is caegorical: one hot decoding
# 3 categories yield two dummy features (third one is obvious from the two)
dummy_city = pd.get_dummies(features_train['city_id'], prefix='city_id')
X_train = X_train.join(dummy_city.ix[:, 'city_id_2':])
X_train["intercept"] = 1.0
for c in train_cols:
X_train[c] = (X_train[c]-X_train[c].mean())/X_train[c].std()
y_train = features_train['churned_in_target']
X_test = features_test[train_cols]
dummy_city = pd.get_dummies(features_test['city_id'], prefix='city_id')
X_test = X_test.join(dummy_city.ix[:, 'city_id_2':])
X_test["intercept"] = 1.0
for c in train_cols:
X_test[c] = (X_test[c]-X_test[c].mean())/X_test[c].std()
y_test = features_test['churned_in_target']
# %%
fig = plt.figure(figsize=(8,6))
# Compute the correlation matrix
corr = X_train[X_train.columns[range(len(X_train.columns)-1)]].corr()
corr.index = ['Age','Prior experience','Time-off','Client score','Workload','Double shifts','Work type','City A','City B']
corr.columns = ['Age','Prior experience','Time-off','Client score','Workload','Double shifts','Work type','City A','City B']
# Generate a custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, cmap=cmap, vmax=.3,square=True,
linewidths=.5, cbar_kws={"shrink": .5})
plt.yticks(rotation=0)
plt.xticks(rotation=90)
plt.tick_params(axis='both', which='major', labelsize=16)
cax = plt.gcf().axes[-1]
cax.tick_params(labelsize=16)
plt.tight_layout()
plt.savefig('correlations.png')
# %%
# Scatter plot matrix of features
fig = plt.figure(figsize=(16,10))
sns.pairplot(features_train[train_cols[2:-1]+['churned_in_target']], hue="churned_in_target")
plt.savefig('scatterplot_matrix.png')
# cross validation to choose C (regularization parameter)
number_folds = 10
lambda_power = np.linspace(-2,2,num=10)
C_list = np.zeros(len(lambda_power))
mean_scores = np.zeros(len(lambda_power))
std_scores = np.zeros(len(lambda_power))
for i in range(len(lambda_power)):
C_list[i] = 1.0/(10**lambda_power[i])
classifier = LogisticRegression(C=C_list[i], penalty='l2')
scores = cross_val_score(classifier, X_train, y_train, cv=number_folds)
mean_scores[i] = scores.mean()
std_scores[i] = scores.std()
plt.figure()
plt.semilogx(1.0/C_list, mean_scores, marker='o',lw= 3,label='l2')
C_list = np.zeros(len(lambda_power))
mean_scores = np.zeros(len(lambda_power))
std_scores = np.zeros(len(lambda_power))
for i in range(len(lambda_power)):
C_list[i] = 1.0/(10**lambda_power[i])
classifier = LogisticRegression(C=C_list[i], penalty='l1')
scores = cross_val_score(classifier, X_train, y_train, cv=number_folds)
mean_scores[i] = scores.mean()
std_scores[i] = scores.std()
plt.semilogx(1.0/C_list, mean_scores, marker='o',lw= 3,label='l1')
plt.ylabel('Acccuracy')
plt.xlabel('Regularization parameter')
plt.legend()
# %%
# Logistic regression regularization parameter (C = 1/lambda)
C1 = 1.0/7 # L1
C2 = 1.0/5 # L2
# Create different classifiers:
classifiers = {
'L1 logistic': LogisticRegression(C=C1, penalty='l1'),
'L2 logistic (OvR)': LogisticRegression(C=C2, penalty='l2')
}
n_classifiers = len(classifiers)
for index, (name, classifier) in enumerate(classifiers.items()):
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
prediction_accuracy = np.mean(y_pred.ravel() == y_test.ravel()) * 100
scores = cross_val_score(classifier, X_train, y_train, cv=10)
print("mean cross validation score : %f " % (np.mean(scores)))
print("CV accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
print("prediction accuracy for %s : %f " % (name, prediction_accuracy))
print classifier.coef_
print ''
preds = classifier.predict_proba(X_test)[:,1]
fpr, tpr, _ = metrics.roc_curve(y_test, preds)
auc = metrics.auc(fpr,tpr)
fig = plt.figure(figsize=(6,6))
lw = 2
plt.plot(fpr, tpr, color='darkorange',lw=lw)
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.xlabel('False Positive Rate',fontsize=16)
plt.ylabel('True Positive Rate',fontsize=16)
plt.title("ROC Curve w/ AUC= %0.2f" % auc,fontsize=16)
plt.tight_layout()
plt.legend(loc="lower right")
plt.tick_params(axis='both', which='major', labelsize=16)
plt.savefig('ROC.png')
# Statmodels
logit = sm.Logit(y_train,X_train)
# fit the model
result = logit.fit_regularized(method='l1',alpha=1/C1)
print result.summary()
# %%
ix = [ix for ix,i in sorted(enumerate(classifier.predict_proba(X_test)[:,1]), key=lambda x:x[1], reverse=True) ]
sorted_ix = X_test.index[ix]
print sorted_ix
plt.figure()
plt.plot(preds[ix],[data_test[data_test.index==i]['days_in_company'].values[0] for i in sorted_ix],ls='',marker='.')
plt.ylabel('Days in company',fontsize=16)
plt.xlabel('Probability of churn at 3 months \n[based on initial 1 month features]',fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.tight_layout()
plt.savefig('predicted_test_prob.png')
# %%
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
# plt.title(title)
# plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black",fontsize=24)
plt.ylabel('True label',fontsize=20)
plt.xlabel('Predicted label',fontsize=20)
plt.tick_params(axis='both', which='major', labelsize=20)
plt.tight_layout()
class_names = ['Not churned','Churned']
cnf_matrix = confusion_matrix(y_test, y_pred)
np.set_printoptions(precision=2)
# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_names,
title='Confusion matrix, without normalization')
plt.tight_layout()
## Plot normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True,
title='Normalized confusion matrix')
plt.tight_layout() |
C++ | UTF-8 | 1,809 | 2.9375 | 3 | [] | no_license | #include "cosFunc.h"
#include "../util.h"
CosFunc::CosFunc() {
h = 0.8;
s = 20.0;
k = 0.0;
y = 0.8;
}
Float CosFunc::evalFunction(Float x, Float a, Float b) const {
return h * Util::COS(s * x + k) + y;
}
Float CosFunc::calculateIntegral(Float a, Float b) const {
Float bcomp = (h / s) * Util::SIN(s * b + k) + y * b;
Float acomp = (h / s) * Util::SIN(s * a + k) + y * a;
return bcomp - acomp;
}
Float CosFunc::calculateVariance(Float a, Float b) const {
// TODO
return 0.0;
}
Float CosFunc::calculateMaxValue(Float a, Float b) const {
return h + y;
}
Float CosFunc::calculateMinValue(Float a, Float b) const {
return y - h;
}
Float CosFunc::calculateMinEfficiency() const {
return 0.01;
}
Float CosFunc::calculateMaxEfficiency() const {
return 0.45;
}
void CosFunc::solveForIntegral(Float a, Float b, Float area) {
h = 10000000000000000.0;
y = area / (b - a);
if (h > y) h = y;
Func::solveForIntegral(a, b, area);
}
Func* CosFunc::copy() const {
CosFunc* newFunc = new CosFunc();
newFunc->h = h;
newFunc->s = s;
newFunc->k = k;
newFunc->y = y;
newFunc->integral = integral;
newFunc->variance = variance;
newFunc->min = min;
newFunc->max = max;
return newFunc;
}
string CosFunc::getName(FuncType type) const {
if (type == FUNC_MAJORANT) {
return "maj_cos";
}
else if (type == FUNC_MINORANT) {
return "min_cos";
}
else if (type == FUNC_EXTINCTION) {
return "cos";
}
return "cos";
}
bool CosFunc::needsDependent() const {
return false;
}
void CosFunc::setH(Float param) { h = param; }
void CosFunc::setS(Float param) { s = param; }
void CosFunc::setK(Float param) { k = param; }
void CosFunc::setY(Float param) { y = param; }
|
Java | UTF-8 | 238 | 2.046875 | 2 | [] | no_license | package fr.maazouza.averroes.middleware.objetmetier.token;
public class TokenExpireException extends Exception{
private static final long serialVersionUID = 1L;
public TokenExpireException(String message) {
super(message);
}
}
|
JavaScript | UTF-8 | 391 | 2.546875 | 3 | [] | no_license | var assert = require("assert");
var Dinosaur = require("../dinosaur.js");
describe("Dinosaur", function(){
beforeEach(function() {
this.dinosaur = new Dinosaur("T-rex", 1);
});
it("should have type", function(){
assert.equal("T-rex", this.dinosaur.type);
});
it("should have offspring per year", function(){
assert.equal(1, this.dinosaur.annualOffspring);
});
}) |
Java | UTF-8 | 517 | 3.65625 | 4 | [] | no_license | package numberBasedQuestions;
public class findTheNumberPrimeOrNot {
public void primeornot(int n)
{
boolean isPrime = true;
for(int i=2; i<n; i++)
{
if(n%i == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
{
System.out.println(n + " is a prime numebr");
}
else
{ System.out.println(n + " is not a prime number");
}
}
public static void main(String[] args) {
findTheNumberPrimeOrNot findprm = new findTheNumberPrimeOrNot();
findprm.primeornot(17);
}
}
|
C++ | UTF-8 | 561 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include "Hash.h"
using namespace std;
int binarySearch(int searchThis[], int findThis, int size);
int main()
{
Hash hashTable(10);
hashTable.addItem("Noah", 20);
hashTable.addItem("Chris", 42);
hashTable.addItem("Niki", 12);
hashTable.dumpText();
cout << endl << endl;
hashTable.removeItem("Noah", 20);
hashTable.removeItem("Niki", 12);
hashTable.removeItem("Chris", 42);
hashTable.addItem("Chris", 42);
hashTable.dumpText();
system("PAUSE");
return 0;
} |
Markdown | UTF-8 | 458 | 2.609375 | 3 | [
"MIT"
] | permissive | ## W0614 (unused-wildcard-import)
### :x: Problematic code:
```python
from pkg import *
print('imported')
```
### :heavy_check_mark: Correct code:
```python
from pkg import *
print('imported', func)
```
### Rationale:
Used when an imported module or variable is not used from a
`'from X import *'` style import.
### Related resources:
- [Issue Tracker](https://github.com/PyCQA/pylint/issues?q=is%3Aissue+%22unused-wildcard-import%22+OR+%22W0614%22)
|
Python | UTF-8 | 249 | 3.21875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 12 21:32:55 2019
@author: HomeUser
"""
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([4, 6, -8, 98])) |
C# | UTF-8 | 1,288 | 3.359375 | 3 | [] | no_license | using MindBoxTest_Libary.Exceptions;
using MindBoxTest_Libary.Figures.AbstractClassesAndInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MindBoxTest_Libary.Figures.Figures
{
public class Circle : Figure
{
/// <summary>
///
/// </summary>
/// <param name="radius">Радиус круга</param>
public Circle(double radius)
{
if (IfInputParamsOk(radius) == false)
throw new InvalidInputForFigureException(this.GetType());
Radius = radius;
}
public override double Square
{
get
{
// Не стал делать двойку как константу, надеюсь ничего страшного
return Math.PI * Math.Pow(Radius, 2);
}
}
public double Radius { get; private set; }
protected override bool IfInputParamsOk(params double[] args)
{
foreach (double arg in args)
{
if (arg <= 0)
return false;
}
return true;
}
}
}
|
JavaScript | UTF-8 | 6,880 | 2.734375 | 3 | [] | no_license | import React, { Component } from 'react';
import './calendar.css'
import PropTypes from 'prop-types';
// import _ from 'loadsh'
// 周列表
function WeekList(props){
const week =props.week
const list =week.map((item)=>
<div className="every_day" key={item}>{item}</div>
)
return (
<div className="week_list">{list}</div>
)
}
function DayList(date){//处理时间方法
// 设置月份数组对象:
let dateArray=[]
// 获取初始化时间
let initDate =new Date(date);
let year =initDate.getFullYear();
let month =initDate.getMonth()+1;
let day =initDate.getDate();
// 获取初始化时间当月有多少天:
let haveDay=new Date(year,month,0).getDate()
// console.log(initDate)
// 获取当前时间
let currentDate= new Date()//当前时间
let currentYear =currentDate.getFullYear();
let currentMonth =currentDate.getMonth()+1;
let currentDay =currentDate.getDate();
// 获取初始化时间的上个月:
let prevDate =new Date(year,month-1,0)
let prevYear =prevDate.getFullYear();
let prevMonth=prevDate.getMonth()+1;
let prevDay= prevDate.getDate();
// 获取上个月最后一天是周几
let preMonthLastWeek =prevDate.getDay()==0?7:prevDate.getDay();
// 获取初始化时间下个月:
let nextDate=new Date(year,month+1,0);
let nextYear =nextDate.getFullYear();
let nextMonth =nextDate.getMonth()+1;
// let nextDay =nextDate.getDate();
for(let i=0;i<42;i++){
let dayObj={
year:'',
month:'',
day:'',
timeStamp:'',
isCurrentMonth:false,
isCurrentDay:false,
haveDate:false
}
dateArray.push(dayObj)
}
// 设置初始化时间数据:
for(let i=0;i<haveDay;i++){
let j=preMonthLastWeek+i
dateArray[j].year=year;
dateArray[j].month=month;
dateArray[j].day=i+1;
dateArray[j].timeStamp=new Date(year,month,i+1).getTime();
dateArray[j].isCurrentMonth=true;
if(currentYear==year&¤tMonth==month&¤tDay==dateArray[j].day){
dateArray[j].isCurrentDay=true;
}
}
// 设置初始化时间的上个月的数据:
for(let i=0;i<preMonthLastWeek;i++){
dateArray[i].year=prevYear;
dateArray[i].month=prevMonth;
dateArray[i].day=(prevDay-preMonthLastWeek+1)+i;
dateArray[i].timeStamp=new Date(prevYear,prevMonth,(prevDay-preMonthLastWeek+1)+i).getTime()
}
// 设置初始化时间的下个月的数据:
for(let i=0;i<(42-preMonthLastWeek-haveDay);i++){//设置日历数组中下个月的显示数据
let j =preMonthLastWeek+haveDay+i
dateArray[j].year=nextYear;
dateArray[j].month=nextMonth;
dateArray[j].day=i+1;
dateArray[j].timeStamp=new Date(nextYear,nextMonth,i+1).getTime()
}
// console.log(dateArray)
return dateArray
}
class Calendar extends Component{
constructor(props){
super(props)
// console.log(props.dateObj)
this.dateObj={
weekList:['周一','周二','周三','周四','周五','周六','周日',],
date:new Date().getTime(),
haveDate:[],
todayTxt:''
}
// this.state={
// weekList:['周一','周二','周三','周四','周五','周六','周日',],
// date:new Date().getTime()
// }
this.year=2019;
this.month=1;
this.clcikDay={
year:'',
month:'',
day:''
}
}
// static propoTypes={//定义触发事件等
// handleDayClick:PropTypes.func.isRequired
// }
componentDidMount(){
// if(this.dateObj){
// this.setState((prevState)=>{
// return {
// weekList:this.dateObj.weekList,
// date:this.dateObj.date
// }
// })
// }
this.dateObj=Object.assign({},this.dateObj,this.props.dateObj)
this.setState({})
}
onChangeMonth=(i)=>{
if(i==0){
this.month --
}else{
this.month++
}
this.dateObj.date=new Date(this.year,this.month,0)
this.setState({})
if(this.props.handleDayClick){
this.props.handleDayClick(new Date(this.year,this.month,0))
}
}
onClickDay=(item)=>{
if( this.props.handleDayClick){
this.props.handleDayClick(item)
}
this.clcikDay.year=item.year
this.clcikDay.month=item.month
this.clcikDay.day=item.day
this.setState({})
}
render(){
const date= DayList(this.dateObj.date)
const haveDate=this.dateObj.haveDate
this.year=new Date(this.dateObj.date).getFullYear()
this.month=new Date(this.dateObj.date).getMonth()+1
const List =(//jsx 语法 生产一个模板
date.map((item,index)=>{
return (
<div
className='every_day'
key={index+item.timeStamp}
onClick={(e)=>this.onClickDay(item)}>
<span
className={['day_item',!item.isCurrentMonth?'other_month':'',item.isCurrentDay?'current_day':'',(this.clcikDay.year==item.year&&this.clcikDay.month==item.month&&this.clcikDay.day==item.day)?'isClick':''].join(' ')}>
{item.isCurrentDay&&this.dateObj.todayTxt?this.dateObj.todayTxt:item.day}
{
haveDate.map((its)=>{
if(item.year==new Date(its).getFullYear()&&item.month==(new Date(its).getMonth()+1)&&item.day==new Date(its).getDate()){
return (
<b className="red_tip" key={its}></b>
)
}
})
}
</span>
</div>
)
}
)
)
return(
<div className='calendar'>
<div className="change_month">
<div className="change_tip" onClick={(e)=>this.onChangeMonth(0)}>上</div>
<div> {this.year}年{this.month}月</div>
<div className="change_tip" onClick={(e)=>this.onChangeMonth(1)} >下</div>
</div>
<WeekList week={this.dateObj.weekList}></WeekList>
<div className="month_line"></div>
<div className="every_day_box">
{List}
</div>
</div>
)
}
}
export default Calendar |
Swift | UTF-8 | 3,483 | 3.046875 | 3 | [
"MIT"
] | permissive | //
// VMenuDemoView.swift
// VComponentsDemo
//
// Created by Vakhtang Kontridze on 2/1/21.
//
import SwiftUI
import VComponents
// MARK:- V Menu Demo View
struct VMenuDemoView: View {
// MARK: Properties
static let navBarTitle: String = "Menu"
@State private var state: VMenuState = .enabled
@State private var menuButtonType: VMenuButtonTypeHelper = .secondary
}
// MARK:- Body
extension VMenuDemoView {
var body: some View {
VBaseView(title: Self.navBarTitle, content: {
DemoView(component: component, settings: settings)
})
}
@ViewBuilder private func component() -> some View {
switch menuButtonType.preset {
case let preset?:
VMenu(
preset: preset,
state: state,
rows: rows,
title: buttonTitle
)
case nil:
VMenu(
state: state,
rows: rows,
label: buttonContent
)
}
}
@ViewBuilder private func settings() -> some View {
VSegmentedPicker(selection: $state, headerTitle: "State")
VWheelPicker(selection: $menuButtonType, headerTitle: "Preset")
}
private var rows: [VMenuRow] {
[
.titledSystemIcon(action: {}, title: "One", name: "swift"),
.titledAssetIcon(action: {}, title: "Two", name: "Favorites"),
.titled(action: {}, title: "Three"),
.titled(action: {}, title: "Four"),
.menu(title: "Five...", rows: [
.titled(action: {}, title: "One"),
.titled(action: {}, title: "Two"),
.titled(action: {}, title: "Three"),
.menu(title: "Four...", rows: [
.titled(action: {}, title: "One"),
.titled(action: {}, title: "Two"),
])
])
]
}
private var buttonTitle: String { "Present" }
private func buttonContent() -> some View { DemoIconContentView() }
}
// MARK:- Helpers
extension VMenuState: VPickableTitledItem {
public var pickerTitle: String {
switch self {
case .enabled: return "Enabled"
case .disabled: return "Disabled"
@unknown default: fatalError()
}
}
}
private enum VMenuButtonTypeHelper: Int, VPickableTitledItem {
case primary
case secondary
case square
case plain
case custom
var preset: VLinkPreset? {
switch self {
case .primary: return .primary()
case .secondary: return .secondary()
case .square: return .square()
case .plain: return .plain()
case .custom: return nil
}
}
var pickerTitle: String {
switch self {
case .primary: return "Primary"
case .secondary: return "Secondary"
case .square: return "Square"
case .plain: return "Plain"
case .custom: return "Custom"
}
}
}
private extension VMenuButtonPreset {
var helperType: VMenuButtonTypeHelper {
switch self {
case .primary: return .primary
case .secondary: return .secondary
case .square: return .square
case .plain: return .plain
@unknown default: fatalError()
}
}
}
// MARK:- Preview
struct VMenuDemoView_Previews: PreviewProvider {
static var previews: some View {
VMenuDemoView()
}
}
|
Go | UTF-8 | 1,528 | 2.75 | 3 | [] | no_license | package app
import (
"github.com/gin-gonic/gin"
"net/http"
)
type response struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
func ResponseSuccess(c *gin.Context, msg string, data interface{}) {
c.JSON(http.StatusOK, response{
Code: http.StatusOK,
Message: msg,
Data: data,
})
return
}
// 系统未知错误http code 500
func ResponseFailed(c *gin.Context, msg string, data interface{}) {
c.JSON(http.StatusInternalServerError, response{
Code: http.StatusInternalServerError,
Message: msg,
Data: data,
})
return
}
// 校验参数未通过http code 400
func ResponseCheckParamsFailed(c *gin.Context, msg string, data interface{}) {
c.JSON(http.StatusBadRequest, response{
Code: http.StatusBadRequest,
Message: msg,
Data: data,
})
return
}
// 未登录http code 401
func ResponseAuthFailed(c *gin.Context, msg string, data interface{}) {
c.JSON(http.StatusUnauthorized, response{
Code: http.StatusUnauthorized,
Message: msg,
Data: data,
})
return
}
// 未找到资源http code 404
func ResponseNoFound(c *gin.Context, msg string, data interface{}) {
c.JSON(http.StatusNotFound, response{
Code: http.StatusNotFound,
Message: msg,
Data: data,
})
return
}
// 未受权限http code 403
func ResponseNoPermission(c *gin.Context, msg string, data interface{}) {
c.JSON(http.StatusForbidden, response{
Code: http.StatusForbidden,
Message: msg,
Data: data,
})
return
}
|
PHP | UTF-8 | 703 | 3.5 | 4 | [
"MIT"
] | permissive | <?php
//solution: 2783915460
echo eulerProblem24() . "\n";
function eulerProblem24() {
$arr = array("0","1","2","3","4","5","6","7","8","9");
$seq = permutation(1000000, $arr);
return implode("", $seq);
}
function permutation($pos, $seq) {
$n = count($seq); $factorial = 1;
for($i = 2; $i < $n; ++$i) {
$factorial *= $i;
}
for($i = 0; $i < $n - 1; ++$i) {
$ti = (($pos - 1) / $factorial) % ($n - $i);
$ts = $seq[$i + $ti];
for($j = $i + $ti; $j > $i; --$j) {
$seq[$j] = $seq[$j - 1];
}
$seq[$i] = $ts;
$factorial = $factorial / ($n - ($i + 1));
}
return $seq;
}
?>
|
C | UTF-8 | 965 | 3.671875 | 4 | [] | no_license | /*
myprog1과 myprog2를 만든 후 지시에 따라 myexec.c를 작성하시오
- myexec의 사용법은 "myexec[a|b]"이다. 즉, 입력으로 a또는 b를 받는다.
- 파라미터로 a를 입력하면 "myprog1 14"를 수행하되 execl()함수를 사용한다.
- 파라미터로 b를 입력하면 "myprog2 12"를 수행하되 execlp()함수를 사용한다.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
if (*argv[1] != 'a' && *argv[1] != 'b') {
fprintf(stderr, "사용법: myexec [a|b]\n");
}
if (*argv[1] == 'a') {
if (!fork()) {
execl("/home/lgm/문서/System-Programming/190528_c/myexec/bin/myprog1", "myprog1", "14", NULL);
exit(0);
}
} else if (*argv[1] == 'b') {
if (!fork()) {
execlp("./myprog2", "myprog2", "12", NULL);
exit(0);
}
}
exit(0);
} |
Java | UTF-8 | 151 | 2.296875 | 2 | [] | no_license | package cn.itcast.day11.demo02;
public class MyClass {
public int num =10;
public void method(){
System.out.println(num);
}
}
|
Java | UTF-8 | 521 | 1.875 | 2 | [] | no_license | package com.imooc.repository;
import com.imooc.dataobject.ProductCategory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @program: sell
* @description
* @author: Tian
* @create: 2020-06-24 23:11
**/
public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Integer> {
List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryType);
}
|
PHP | UTF-8 | 4,427 | 2.78125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
require_once APPPATH."/libraries/PHPExcel.php";
class Excel extends PHPExcel {
public function __construct() {
parent::__construct();
}
function getNameFromNumber($num) {
$numeric = $num % 26;
$letter = chr(65 + $numeric);
$num2 = intval($num / 26);
if ($num2 > 0) {
return $this->getNameFromNumber($num2 - 1) . $letter;
} else {
return $letter;
}
}
public function to_file($judul,$header,$isi)
{
# code...
$excel = new PHPExcel();
$excel->getProperties()->
setCreator('Smartsoft Studio')->
setLastModifiedBy('Smartsoft Studio')->
setTitle($judul)->
setSubject($judul)->
setDescription($judul)->
setKeywords($judul);
$style_col = array(
'font' => array('bold' => true),
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
),
'borders' => array(
'top' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
'right' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
'bottom' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
'left' => array('style' => PHPExcel_Style_Border::BORDER_THIN)
),
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'DDDDDD')
),
);
$style_row = array(
'alignment' => array(
'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
),
'borders' => array(
'top' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
'right' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
'bottom' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
'left' => array('style' => PHPExcel_Style_Border::BORDER_THIN)
)
);
$style_row2 = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
),
'borders' => array(
'top' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
'right' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
'bottom' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
'left' => array('style' => PHPExcel_Style_Border::BORDER_THIN)
)
);
$i=0;
foreach ($header as $head) {
$excel->setActiveSheetIndex(0)->setCellValue($this->getNameFromNumber($i).'1', $head);
$i++;
}
$i=0;
foreach ($header as $head) {
$excel->getActiveSheet()->getStyle($this->getNameFromNumber($i)."1")->applyFromArray($style_col);
$i++;
}
$no = 1;
$numrow = 2;
foreach($isi as $dt => $val){
$i=0;
foreach ($header as $head) {
// if($i==0){
// $excel->setActiveSheetIndex(0)->setCellValue('A'.$numrow, $no);
// }else{
// $vals[$this->getNameFromNumber($i).$numrow][] = $val[$i];
// $excel->setActiveSheetIndex(0)->setCellValue($this->getNameFromNumber($i).$numrow, $val[$i]);
$excel->setActiveSheetIndex(0)->setCellValueExplicit($this->getNameFromNumber($i).$numrow, $val[$i],PHPExcel_Cell_DataType::TYPE_STRING);
// }
$i++;
}
$i=0;
foreach ($header as $head) {
$excel->getActiveSheet()->getStyle($this->getNameFromNumber($i).$numrow)->applyFromArray($style_row);
$i++;
}
$no++;
$numrow++;
}
$i=0;
foreach ($header as $head) {
$excel->getActiveSheet()->getColumnDimension($this->getNameFromNumber($i))->setAutoSize(TRUE);
$i++;
}
$excel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(-1);
$excel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
$excel->getActiveSheet(0)->setTitle($judul);
$excel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="'.$judul.'.xlsx"');
header('Cache-Control: max-age=0');
$write = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$write->save('php://output');
// print_r($vals);
}
}
|
SQL | UTF-8 | 2,844 | 3.28125 | 3 | [] | no_license | # ************************************************************
# Sequel Pro SQL dump
# Version 4541
#
# http://www.sequelpro.com/
# https://github.com/sequelpro/sequelpro
#
# Host: 127.0.0.1 (MySQL 5.6.35)
# Database: shiggles_db
# Generation Time: 2018-02-02 02:29:00 +0000
# ************************************************************
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
# Dump of table compQuestions
# ------------------------------------------------------------
CREATE DATABASE shiggles_db;
USE shiggles_db;
DROP TABLE IF EXISTS `compQuestions`;
CREATE TABLE `compQuestions` (
`question` varchar(200) DEFAULT NULL,
`answer1` varchar(75) DEFAULT NULL,
`answer2` varchar(75) DEFAULT NULL,
`questionID` int(50) DEFAULT NULL,
`winner` varchar(75) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
# Dump of table questions
# ------------------------------------------------------------
DROP TABLE IF EXISTS `questions`;
CREATE TABLE `questions` (
`question` varchar(200) NOT NULL,
`answer1` varchar(75) NOT NULL,
`answer2` varchar(75) NOT NULL,
`questionID` int(50) NOT NULL AUTO_INCREMENT,
`isCurrent` tinyint(1) DEFAULT '0',
`a1Votes` int(10) DEFAULT NULL,
`a2Votes` int(10) DEFAULT NULL,
PRIMARY KEY (`questionID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
LOCK TABLES `questions` WRITE;
/*!40000 ALTER TABLE `questions` DISABLE KEYS */;
INSERT INTO `questions` (`question`, `answer1`, `answer2`, `questionID`, `isCurrent`, `a1Votes`, `a2Votes`)
VALUES
('What is better, cats or dogs?','cats','dogs',1,0,NULL,NULL),
('Pie vs cake?','Pie!','Cake!',2,0,NULL,NULL),
('What tastes better, oranges or apples?','Oranges forever!','Glorious Apples!',3,0,NULL,NULL);
/*!40000 ALTER TABLE `questions` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table userData
# ------------------------------------------------------------
DROP TABLE IF EXISTS `userData`;
CREATE TABLE `userData` (
`username` varchar(50) NOT NULL,
`questionID` int(10) DEFAULT NULL,
`answer` varchar(50) DEFAULT NULL,
`guess` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
JavaScript | UTF-8 | 429 | 2.640625 | 3 | [] | no_license | export default function formValidate(values){
let errors = {}
if(!values.firstname.trim()){
errors.firstname = '*First Name Required'
}
if(!values.lastname.trim()){
errors.lastname = '*Last Name Required'
}
if(!values.email.trim()){
errors.email = '*Email Required'
}
if(!values.password.trim()){
errors.password = '*Password Required'
}
return errors;
} |
Java | UTF-8 | 3,615 | 2.296875 | 2 | [] | no_license | package com.example.acodersspringapp.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.acodersspringapp.model.AssetInfoModel;
import com.example.acodersspringapp.model.CurrentHoldingAssetInfo;
import com.example.acodersspringapp.model.TradeInfoModel;
import com.example.acodersspringapp.model.request.NewTradesRequestModel;
import com.example.acodersspringapp.model.response.PortfolioResponseModel;
import com.example.acodersspringapp.service.TokenService;
import com.example.acodersspringapp.service.TradeService;
@RestController
@RequestMapping(value="/api/trade")
@CrossOrigin
public class TradeController {
@Autowired
TradeService tradeService;
@Autowired
TokenService tokenService;
@PostMapping
public ResponseEntity<?> sendTrades(@RequestBody NewTradesRequestModel model,@RequestHeader("token") String token) {
boolean isTokenValid = tokenService.isValidToken(token);
if (!isTokenValid) {
return ResponseEntity.badRequest().body("Token not valid");
}
String username = tokenService.getUsernameFromToken(token);
tradeService.acceptTrades(username,model);
return ResponseEntity.ok().build();
}
@GetMapping(value="/{username}")
public ResponseEntity<?> getTradeHistory(@PathVariable String username, @RequestHeader("token") String token) {
boolean isTokenValid = tokenService.isValidToken(token);
if (!isTokenValid) {
return ResponseEntity.badRequest().body("Token not valid");
}
String tokenUsername = tokenService.getUsernameFromToken(token);
if (!tokenUsername.equals(username)) {
return ResponseEntity.badRequest().body("Not authoirized to view this page");
}
List<TradeInfoModel> trades = tradeService.getTradeHistoryByUsername(username);
return ResponseEntity.ok(trades);
}
@GetMapping(value="/{username}/portfolio")
public ResponseEntity<?> getPorfolio(@PathVariable String username,@RequestHeader("token") String token) {
boolean isTokenValid = tokenService.isValidToken(token);
if (!isTokenValid) {
return ResponseEntity.badRequest().body("Token not valid");
}
String tokenUsername = tokenService.getUsernameFromToken(token);
if (!tokenUsername.equals(username)) {
return ResponseEntity.badRequest().body("Not authoirized to view this page");
}
List<AssetInfoModel> returnValue = tradeService.getPorfolioByUsername(username);
return ResponseEntity.ok(returnValue);
}
@GetMapping(value="/{username}/holdingStock")
public ResponseEntity<?> getCurrentStocks(@PathVariable String username, @RequestHeader("token") String token) {
boolean isTokenValid = tokenService.isValidToken(token);
if (!isTokenValid) {
return ResponseEntity.badRequest().body("Token not valid");
}
String tokenUsername = tokenService.getUsernameFromToken(token);
if (!tokenUsername.equals(username)) {
return ResponseEntity.badRequest().body("Not authoirized to view this page");
}
List<CurrentHoldingAssetInfo> returnValue = tradeService.getCurrentStocksByUsername(username);
return ResponseEntity.ok(returnValue);
}
}
|
Python | UTF-8 | 100 | 2.6875 | 3 | [] | no_license | #!/bin/python
import time
curr = 0
while True:
print "In something ..."
time.sleep(60)
|
Python | ISO-8859-9 | 1,850 | 3.625 | 4 | [] | no_license | # coding:iso-8859-9 Trke
# Python 3 - Multithreaded Programming
# Yeni yntemle sicim yaratma: Thread altsnf, override __init__ ve run metodlar,
# sicim tip nesneleri yaratma, start ile run' koturma, icabnda join ile sicimlerin
# almas tamamlanmadan alttaki kodlamaya gememenin salanmas ve
# lock ile bir sicim tamamlanmadan (senkronizasyon) dierine geilmemesi
import threading
import time
class sicimim (threading.Thread):
def __init__ (self, sicimNo, sicimAd, tehir): # Kurucu metod...
threading.Thread.__init__ (self)
self.sicimNo = sicimNo
self.sicimAd = sicimAd
self.tehir = tehir
def run (self):
print ("Balatlyor: " + self.sicimAd)
# Sicim kilidi kapatlp, sicimin tamamlanma btnl salanyor...
sicimKilidi.acquire()
zamanGster (self.sicimAd, self.tehir, 5)
print ("Sonlandrlyor: " + self.sicimAd)
# Kilidi ap birsonraki sicime gei veriliyor...
sicimKilidi.release()
def zamanGster (ipAd, beklet, tekrarla):
while tekrarla:
time.sleep (beklet)
print ("%s: Saya(%d) Zaman: %s" % (ipAd, tekrarla, time.ctime (time.time())))
tekrarla -= 1
sicimKilidi = threading.Lock()
sicimler = []
# Yeni sicimlerimizi yaratalm...
sicim1 = sicimim (1001, "Sicim-1", 2)
sicim2 = sicimim (250, "Sicim-2", 3)
sicim3 = sicimim (1957, "Sicim-3", 1)
# Sicimleri run iin balatalm...
sicim3.start()
sicim1.start()
sicim2.start()
# Sicim listesi yapp birlikte join (alt koda gei bekletmesi) edelim...
sicimler.append (sicim1)
sicimler.append (sicim3)
sicimler.append (sicim2)
for ip in sicimler: ip.join()
print ("\nSicimler tamamland; alt kodlamalara geilebilir...")
|
C++ | UTF-8 | 3,871 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <map>
#include <limits>
#include "global.h"
#include "support.h"
#pragma warning(disable:4996)
extern unsigned int numMax;
extern char ch;
extern long long value;
extern std::string ident;
extern int lineNo;
extern std::map<std::string, int> keywordTable;
int lex()
{
std::map<std::string, int>::iterator res;
ident.clear();
while (true)
{
//跳过所有空白符
while (isspace(ch))
{
if (ch == '\n')
{
lineNo++;
}
ch = getchar();
}
if (isalpha(ch))
{
//字母开头
ident.clear(); //清除上一个ident留下的内容
ident.append(sizeof(char), ch); //将当前字符添加至ident中
while (isalnum(ch = getchar()))
{
//如果当前是字母或者数字,则其应该是当前标识符中的一部分
ident.append(sizeof(char), ch); //将当前字符添加至ident中
}
//标识符结束
res = keywordTable.find(ident);
if (res != keywordTable.end())
{
//当前标识符是保留字
print("Keyword", "Name", ident.c_str());
return res->second;
}
return IDENT;
}
else if (isdigit(ch))
{
//数字
ungetc(ch, stdin);
scanf("%d", &value);
scanf("%c", &ch);
if (value > INT_MAX)
{
value = 0;
error("The Number Is Too Big!");
}
return NUM;
}
else if (match(':'))
{
if (match('='))
{
//赋值号:=
print("Sign", "Name", "BECOMES");
return BECOMES;
}
else
{
//冒号':'
print("Sign", "Name", "COLON");
return COLON;
}
}
else if (match('<'))
{
if (match('>'))
{
//不等号'<>'
print("Sign", "Name", "NOT EQUAL");
return NEQ;
}
else if (match('='))
{
//小于等于'<='
print("Sign", "Name", "LESS OR EQUAL");
return LEQ;
}
else
{
//小于号'<'
print("Sign", "Name", "LESS");
return LESS;
}
}
else if (match('>'))
{
if (match('='))
{
//大于等于号'>='
print("Sign", "Name", "GREATER OR EQUAL");
return GEQ;
}
else
{
//大于号'>'
print("Sign", "Name", "GREATER");
return GREATER;
}
}
else if (match('\''))
{
//字符处理
ident.clear();
while (isalnum(ch))
{
ident.append(sizeof(char), ch);
ch = getchar();
}
if (match('\''))
{
ident.erase(ident.end()-1);
}else
{
error("The Single Quotes don't match");
//需要错误恢复吗?
}
if (ident.length() > 1)
{
error("There are too many characters in single quotes");
ident.clear();
}
return CH;
}
else if (match('"'))
{
ident.clear();
while (ch == 32 || ch == 33 || 35 <= ch && ch <= 126)
{
//引号内的字符
ident.append(sizeof(char), ch);
ch = getchar();
}
if (!match('"'))
{
//在字符串内出现了非法字符
error("There is an illegal character in the string");
ident.clear();
while (!match('"'))
{
ch = getchar();
if (ch == EOF)
{
error("The Quotes don't match");
return EOF;
}
}
}
ident.erase(--(ident.end())); //去掉末尾的双引号
return STRING;
}
else if (ch == EOF)
{
return EOF;
}
else
{
//其他符号
ident.clear();
ident.append(sizeof(char), ch);
res = keywordTable.find(ident);
if (res != keywordTable.end() && res->second != 0)
{
//找到当前符号
print("Sign", "Name", ident);
ch = getchar();
return res->second;
}
//当前符号为不可识别的符号
//跳到下一个标识符或者数字开始的位置
while (!isalnum(ch) && ch != EOF && keywordTable[std::string(1,ch)] == 0)
{
ch = getchar();
ident.append(sizeof(char), ch);
}
ident.erase(--(ident.end())); //去掉下一个标识符的开始字符
if (ch == EOF)
{
return EOF;
}
return NUL;
}
}
} |
JavaScript | UTF-8 | 281 | 2.734375 | 3 | [] | no_license | class Task{
constructor(title, desc, dueDate){
this.title = title;
this.desc = desc;
this.dueDate = dueDate;
this.id = ++Task.count;
this.completed = false;
this.date = new Date();
}
}
Task.count = 0;
module.exports = Task; |
C++ | UTF-8 | 2,547 | 3.296875 | 3 | [] | no_license | #pragma once
#include <string>
template<typename T>
struct StringCast
{
};
#define CAST_STRING_TO_SIMPLE_DATA_TYPE(T, STR_TO_XXX) \
template <> \
struct StringCast<T> \
{ \
T operator() (const std::string& str) const \
try \
{ \
return STR_TO_XXX(str.c_str()); \
} \
catch (...) \
{ \
std::cout << "cast error" << std::endl; \
} \
};
inline unsigned long long cast_str_to_ull(const char *str)
{
return std::strtoull(str, NULL, 0);
}
inline long long cast_str_to_ll(const char *str)
{
return std::strtoll(str, NULL, 0);
}
inline double cast_str_to_d(const char* str)
{
return std::strtod(str, NULL);
}
CAST_STRING_TO_SIMPLE_DATA_TYPE(bool, cast_str_to_ull);
CAST_STRING_TO_SIMPLE_DATA_TYPE(char, cast_str_to_ll);
CAST_STRING_TO_SIMPLE_DATA_TYPE(signed char, cast_str_to_ll);
CAST_STRING_TO_SIMPLE_DATA_TYPE(unsigned char, cast_str_to_ull);
CAST_STRING_TO_SIMPLE_DATA_TYPE(signed short, cast_str_to_ll);
CAST_STRING_TO_SIMPLE_DATA_TYPE(unsigned short, cast_str_to_ull);
CAST_STRING_TO_SIMPLE_DATA_TYPE(signed int, cast_str_to_ll);
CAST_STRING_TO_SIMPLE_DATA_TYPE(unsigned int, cast_str_to_ull);
CAST_STRING_TO_SIMPLE_DATA_TYPE(signed long, cast_str_to_ll);
CAST_STRING_TO_SIMPLE_DATA_TYPE(unsigned long, cast_str_to_ull);
CAST_STRING_TO_SIMPLE_DATA_TYPE(signed long long, cast_str_to_ll);
CAST_STRING_TO_SIMPLE_DATA_TYPE(unsigned long long, cast_str_to_ull);
CAST_STRING_TO_SIMPLE_DATA_TYPE(float, cast_str_to_d);
CAST_STRING_TO_SIMPLE_DATA_TYPE(double, cast_str_to_d);
template <typename T>
struct StringCastWrapper
{
T operator()(const std::string& str)
{
return StringCast<T>()(str);
}
};
template<>
struct StringCastWrapper<std::string>
{
std::string operator() (const std::string& str)
{
return std::move(str);
}
};
|
C++ | UTF-8 | 10,205 | 3.296875 | 3 | [] | no_license | #include <src/numeric/GeoPosition.h>
#include <cmath>
#include <iostream>
#include <QDebug>
#include <QSettings>
#include <QString>
#include "src/util/qString.h"
/**
* Constructs an invalid GeoPosition
*/
GeoPosition::GeoPosition ()
{
// Since the two Angle properties are default-constructed, they will be
// invalid and therefore this GeoPosition will also be invalid.
}
GeoPosition::~GeoPosition ()
{
}
/**
* Creates a GeoPosition with the given latitude and longitude
*/
GeoPosition::GeoPosition (const Angle &latitude, const Angle &longitude):
latitude (latitude), longitude (longitude)
{
}
/**
* Creates a GeoPosition with the given latitude and longitude, specified in
* degrees.
*
* As for precision:
* 1 degree = 1e-0 degree = 111 km (60 NM)
* 0.1 degree = 1e-1 degree = 11 km
* 0.01 degree = 1e-2 degree = 1 km
* 0.001 degree = 1e-3 degree = 111 m
* 0.0001 degree = 1e-4 degree = 11 m
* 0.00001 degree = 1e-5 degree = 1 m
*/
GeoPosition GeoPosition::fromDegrees (const double latitude, const double longitude)
{
return GeoPosition (Angle::fromDegrees (latitude), Angle::fromDegrees (longitude));
}
/**
* Creates a GeoPosition with the given latitude and longitude, specified in
* degrees.
*
* As for precision:
* 1 rad = 1e-0 rad = 6371 km
* 0.1 rad = 1e-1 rad = 637 km
* 0.01 rad = 1e-2 rad = 64 km
* 0.001 rad = 1e-3 rad = 7 km
* 0.0001 rad = 1e-4 rad = 6371 m
* 0.00001 rad = 1e-5 rad = 637 m
* 0.000001 rad = 1e-6 rad = 64 m
* 0.0000001 rad = 1e-7 rad = 7 m
* 0.00000001 rad = 1e-8 rad = 0.7 m
* @param latitude
* @param longitude
* @return
*/
GeoPosition GeoPosition::fromRadians (const double latitude, const double longitude)
{
return GeoPosition (Angle::fromRadians (latitude), Angle::fromRadians (longitude));
}
/**
* Calculates the distance (along a great circle) between two points on the
* earth surface, in meters, given the spherical angle between the points
*
* This method can also be used to determine the distance of two points on the
* same meridian, given their relative latitude, or two points on the equator,
* given their relative longitude.
*
* If the angle is negative, the result will also be negative.
*/
double GeoPosition::greatCircleDistance (const Angle &angle)
{
return earthRadius * angle.toRadians ();
}
Angle GeoPosition::greatCircleAngle (double distance)
{
return Angle::fromRadians (distance/earthRadius);
}
/**
* Calculates the distance between this position and another position
*
* The calculation uses an approximation that only works for small differences
* in latitude.
*
* Note that the distance is measured along a path where the direction does not
* wrap. For example, the distance between 0°N 179°W and 0°N 179°E would be
* calculated as 358*60 NM, not 2*60 NM which would be more appropriate. This
* behavior may change in the future, when a great circle distance is used
* instead.
*
* @param reference
* @return
*/
double GeoPosition::distanceTo (const GeoPosition &reference) const
{
Angle averageLatitude=(latitude+reference.latitude)/2;
Angle latitudeDifference =latitude -reference.latitude;
Angle longitudeDifference=longitude-reference.longitude;
double east = earthRadius * longitudeDifference.toRadians () * averageLatitude.cos ();
double north = earthRadius * latitudeDifference .toRadians ();
return sqrt (east*east+north*north);
}
/**
* Calculates the relative position, in meters east and north of a reference
* position
*
* This only works for small differences in latitude. For large differences,
* the relative position (as given here) is not well-defined because it depends
* on the path.
*
* The east distance will be positive if this position is east of the reference.
* Likewise, the north distance will be positive if this position is north of
* the reference.
*
* Note that the east direction is defined as the direction where the longitude
* does not wrap. For example, a point at 179°E would be considered 358° east of
* a point at 179°W, even though it is more accurately described as 2° west.
* Also, if the latitude parameters are out of range (±90°), the result will
* be meaningless.
*
* @param reference the other point
* @return a QPointF with the east distance as x and the north distance as y
* @see offsetPosition
*/
QPointF GeoPosition::relativePositionTo (const GeoPosition &reference) const
{
Angle averageLatitude=(latitude+reference.latitude)/2;
Angle latitudeDifference =latitude -reference.latitude;
Angle longitudeDifference=longitude-reference.longitude;
double east = earthRadius * longitudeDifference.toRadians () * averageLatitude.cos ();
double north = earthRadius * latitudeDifference .toRadians ();
return QPointF (east, north);
}
/**
* Calculates the position that is the given distance (in meters) east and north
* of the own position
*
* This is the inverse of relativePositionTo.
*
* @param offset the offset, with the east distance as x and the north distance
* as y
* @return the resulting position
* @see relativePositionTo
*/
GeoPosition GeoPosition::offsetPosition (const QPointF &offset) const
{
double east =offset.x ();
double north=offset.y ();
Angle resultLatitude=latitude+Angle::fromRadians (north/earthRadius);
Angle averageLatitude=(latitude+resultLatitude)/2;
Angle resultLongitude=longitude+Angle::fromRadians (east/earthRadius/averageLatitude.cos ());
return GeoPosition (resultLatitude, resultLongitude);
}
/**
* Calculates the relative positions of multiple positions with respect to a
* single comment reference position
*
* @param values a QVector of positions
* @param reference a single position
* @return a QVector of QPointF, containing one element for each element of
* values
* @see relativePositionsTo (const GeoPosition &)
*/
QVector<QPointF> GeoPosition::relativePositionTo (const QVector<GeoPosition> &values, const GeoPosition &reference)
{
QVector<QPointF> result (values.size ());
for (int i=0, n=values.size (); i<n; ++i)
result[i]=values[i].relativePositionTo (reference);
return result;
}
/**
* Returns whether the position is valid
*
* Currently, this only checks whether values have been set; no range checking
* is performed.
*/
bool GeoPosition::isValid () const
{
// FIXME check the range? With a Latitude and Longitude class, this would
// be included in this check.
return latitude.isValid () && longitude.isValid ();
}
/**
* Outputs a GeoPosition to a Qt debug stream
*/
QDebug operator<< (QDebug dbg, const GeoPosition &position)
{
dbg.nospace () << "(" << position.getLatitude () << ", " << position.getLongitude () << ")";
return dbg.space ();
}
/**
* Stores a QVector of GeoPosition in a QSettings with a given key
*
* @see readVector
*/
void GeoPosition::storeVector (QSettings &settings, const QString &key, const QVector<GeoPosition> &vector)
{
QVariantList valueList;
foreach (const GeoPosition &point, vector)
valueList << point.getLongitude ().toDegrees () << point.getLatitude ().toDegrees ();
settings.setValue (key, valueList);
}
/**
* Reads a QVector of GeoPosition from a QSettings with a given key
*
* @see storeVector
*/
QVector<GeoPosition> GeoPosition::readVector (QSettings &settings, const QString &key)
{
QVector<GeoPosition> vector;
QVariantList valueList = settings.value (key).toList ();
vector.reserve (valueList.size ()/2);
while (valueList.size ()>=2)
{
double lon = valueList.takeFirst ().toDouble ();
double lat = valueList.takeFirst ().toDouble ();
vector << GeoPosition::fromDegrees (lat, lon);
}
return vector;
}
/**
* Tests for equality
*
* Two invalid GeoPositions are considered equal. A valid and an invalid
* GeoPosition are not considered equal. Two valid GeoPositions are considered
* equal if they represent the same position.
*
* Note that a GeoPosition includes floating point values, so the equality
* relation is not to be trusted.
*/
bool GeoPosition::operator== (const GeoPosition &other) const
{
// Both invalid => equal
if (!isValid () && !other.isValid ()) return true;
// Both valid => equal if the values are equal
if ( isValid () && other.isValid ())
return (latitude==other.latitude) && (longitude==other.longitude);
// One valid, one invalid => not equal
return false;
}
/**
* Tests for inequality
*
* Note that a GeoPosition includes floating point values, so the inequality
* relation is not to be trusted.
*
* @see operator==
*/
bool GeoPosition::operator!= (const GeoPosition &other) const
{
return !(*this==other);
}
/**
* Calculates a point that lies as far south as the southernmost and as far west
* as the westernmost of the two points p1 and p2
*
* If either or both of the points are invalid, an invalid GeoPosition is
* returned.
*
* This may fail if the longitude wraps.
*/
GeoPosition GeoPosition::southWest (const GeoPosition &p1, const GeoPosition p2)
{
// If either or both of the latitudes are invalid, Angle::min will return
// an invalid Angle; the same applies to the longitudes.
return GeoPosition (
Angle::min (p1.latitude , p2.latitude ),
Angle::min (p1.longitude, p2.longitude)
);
}
/**
* Calculates a point that lies as far north as the northernmost and as far east
* as the easternmost of the two points p1 and p2
*
* If either or both of the points are invalid, an invalid GeoPosition is
* returned.
*
* This may fail if the longitude wraps.
*/
GeoPosition GeoPosition::northEast (const GeoPosition &p1, const GeoPosition p2)
{
// If either or both of the latitudes are invalid, Angle::min will return
// an invalid Angle; the same applies to the longitudes.
return GeoPosition (
Angle::max (p1.latitude , p2.latitude ),
Angle::max (p1.longitude, p2.longitude)
);
}
|
C# | UTF-8 | 1,070 | 2.578125 | 3 | [] | no_license | using System.Collections.Generic;
using UnityEngine;
public class WinGameWhenOccupantCountIsBelowThreshold : AbstractGameBoardModifier, IGameBoardModifier
{
[SerializeField]
private int minOccupantThreshold = 0;
void Start ()
{
//listen when any occupants is removed from the board.
gameBoard.RemovedOccupants += GameBoard_RemovedOccupant;
}
private void GameBoard_RemovedOccupant(List<IGridOccupant> occupants)
{
List<IGridOccupant> allOccupants = gameBoard.GetAllValidOccupants();
int sum = 0;
for (int i = 0; i < allOccupants.Count; i++)
{
IGridOccupant occupant = allOccupants[i];
if (occupant is IMatchableOccupant)
{
sum++;
}
}
if (sum <= minOccupantThreshold)
{
//GameManager.instance.EndGame(new EndGameParameters(this, "You win! Board Clear"));
}
}
private void OnDestroy()
{
gameBoard.RemovedOccupants -= GameBoard_RemovedOccupant;
}
}
|
Java | UTF-8 | 9,115 | 1.953125 | 2 | [] | no_license | package net.dorokhov.pony.core.library.service.scan;
import net.dorokhov.pony.api.library.domain.Song;
import net.dorokhov.pony.core.library.service.AudioTagger;
import net.dorokhov.pony.api.library.domain.ReadableAudioData;
import net.dorokhov.pony.api.library.domain.WritableAudioData;
import net.dorokhov.pony.core.library.service.filetree.domain.AudioNode;
import net.dorokhov.pony.core.library.service.scan.BatchLibraryImportPlanner.Plan;
import net.dorokhov.pony.api.log.service.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Collections.*;
import static net.dorokhov.pony.core.library.LibraryConfig.LIBRARY_IMPORT_EXECUTOR;
import static org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW;
@Component
public class BatchLibraryImporter {
public static class ImportResult {
private final List<Song> importedSongs;
private final List<File> failedFiles;
public ImportResult(List<Song> importedSongs, List<File> failedFiles) {
this.importedSongs = unmodifiableList(importedSongs);
this.failedFiles = unmodifiableList(failedFiles);
}
public List<Song> getImportedSongs() {
return importedSongs;
}
public List<File> getFailedFiles() {
return failedFiles;
}
}
public static class WriteAndImportCommand {
private final AudioNode audioNode;
private final WritableAudioData audioData;
public WriteAndImportCommand(AudioNode audioNode, WritableAudioData audioData) {
this.audioNode = checkNotNull(audioNode);
this.audioData = checkNotNull(audioData);
}
public AudioNode getAudioNode() {
return audioNode;
}
public WritableAudioData getAudioData() {
return audioData;
}
}
private final Logger logger = LoggerFactory.getLogger(getClass());
private final BatchLibraryImportPlanner batchLibraryImportPlanner;
private final AudioTagger audioTagger;
private final LibraryImporter libraryImporter;
private final LogService logService;
private final Executor executor;
private final TransactionTemplate transactionTemplate;
private final Object progressLock = new Object();
public BatchLibraryImporter(BatchLibraryImportPlanner batchLibraryImportPlanner,
AudioTagger audioTagger,
LibraryImporter libraryImporter,
LogService logService,
@Qualifier(LIBRARY_IMPORT_EXECUTOR) Executor executor,
PlatformTransactionManager transactionManager) {
this.batchLibraryImportPlanner = batchLibraryImportPlanner;
this.audioTagger = audioTagger;
this.libraryImporter = libraryImporter;
this.logService = logService;
this.executor = executor;
transactionTemplate = new TransactionTemplate(transactionManager, new DefaultTransactionDefinition(PROPAGATION_REQUIRES_NEW));
}
public ImportResult readAndImport(List<AudioNode> audioNodes, ProgressObserver observer) {
Plan plan = batchLibraryImportPlanner.plan(audioNodes);
List<ImportTask> importTasks = synchronizedList(new ArrayList<>());
plan.getAudioNodesToImport().forEach(audioNode -> importTasks.add(null));
List<File> failedFiles = synchronizedList(new ArrayList<>());
int itemsTotal = plan.getAudioNodesToImport().size();
CountDownLatch latch = new CountDownLatch(itemsTotal);
for (int i = 0; i < plan.getAudioNodesToImport().size(); i++) {
AudioNode audioNode = plan.getAudioNodesToImport().get(i);
final int index = i;
executor.execute(() -> {
try {
// Preserve original order.
importTasks.set(index, new ImportTask(audioNode, audioTagger.read(audioNode.getFile())));
} catch (IOException e) {
logService.error(logger, "Could not read audio data from '{}'.",
audioNode.getFile().getAbsolutePath(), e);
failedFiles.add(audioNode.getFile());
} finally {
synchronized (progressLock) {
notifyObserver(observer, itemsTotal - latch.getCount() + 1, itemsTotal);
latch.countDown();
}
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
logger.warn("Batch audio data reading has been interrupted.", e);
throw new RuntimeException("Batch audio data reading has been interrupted.", e);
}
return doImport(importTasks.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList()), plan.getAudioNodesToSkip(), failedFiles);
}
public ImportResult writeAndImport(List<WriteAndImportCommand> commands, ProgressObserver observer) {
List<ImportTask> importTasks = synchronizedList(new ArrayList<>());
commands.forEach(audioNode -> importTasks.add(null));
List<File> failedFiles = synchronizedList(new ArrayList<>());
int itemsTotal = commands.size();
CountDownLatch latch = new CountDownLatch(itemsTotal);
for (int i = 0; i < commands.size(); i++) {
WriteAndImportCommand command = commands.get(i);
final int index = i;
executor.execute(() -> {
try {
// Preserve original order.
importTasks.set(index, new ImportTask(command.getAudioNode(),
audioTagger.write(command.getAudioNode().getFile(), command.getAudioData())));
} catch (IOException e) {
logService.error(logger, "Could not write audio data to '{}': '{}'.",
command.getAudioNode().getFile().getAbsolutePath(), command.getAudioData(), e);
failedFiles.add(command.getAudioNode().getFile());
} finally {
synchronized (progressLock) {
notifyObserver(observer, itemsTotal - latch.getCount() + 1, itemsTotal);
latch.countDown();
}
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
logger.warn("Batch audio data writing has been interrupted.", e);
throw new RuntimeException("Batch audio data writing has been interrupted.", e);
}
return doImport(importTasks.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList()), emptyList(), failedFiles);
}
private void notifyObserver(ProgressObserver observer, long itemsComplete, long itemsTotal) {
try {
observer.onProgress(itemsComplete, itemsTotal);
} catch (Exception e) {
logger.error("Could not call progress observer {}.", observer, e);
}
}
private ImportResult doImport(List<ImportTask> importAudioDataTasks,
List<AudioNode> importArtworkTasks,
List<File> failedFiles) {
return transactionTemplate.execute(status -> {
List<Song> importedSongs = new ArrayList<>();
for (ImportTask importTask : importAudioDataTasks) {
importedSongs.add(libraryImporter.importAudioData(importTask.getAudioNode(), importTask.getAudioData()));
}
for (AudioNode audioNode : importArtworkTasks) {
importedSongs.add(libraryImporter.importArtwork(audioNode));
}
return new ImportResult(importedSongs, failedFiles);
});
}
private static class ImportTask {
private final AudioNode audioNode;
private final ReadableAudioData audioData;
public ImportTask(AudioNode audioNode, ReadableAudioData audioData) {
this.audioNode = checkNotNull(audioNode);
this.audioData = checkNotNull(audioData);
}
public AudioNode getAudioNode() {
return audioNode;
}
public ReadableAudioData getAudioData() {
return audioData;
}
}
}
|
PHP | UTF-8 | 817 | 3.46875 | 3 | [] | no_license | <!DOCTYPE html>
<?php
$someText = "dynamic text";
$varA = "from one tag";
$varB = 1;
?>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>HEADLINES AND <?php echo $someText;?></h1>
<p>You can combine static html with values from php variables</p>
<div>
<h3>This lets you have a file that's largely easy to style html</h3>
<ul>
<li>with some</li>
<li><?php echo $someText?></li>
<li>all php tags share the same scope</li>
<li>So you can use the same variables</li>
<li>like this <?php echo $varB + 12?></li>
<li>and again <?php echo ++$varB?></li>
</ul>
</div>
</body>
</html>
|
Markdown | UTF-8 | 3,336 | 3.171875 | 3 | [] | no_license | # docker-utils
## Warnings:
Selfish-ware.
One day and a bottle of wine project.
Docker swarm and AWS helpers. The whole thing is an organised hack.
- Useless for 99.99999% of the people.
- I was sick of struggling with docker for every project I'm starting and I can't remember shit.
- Very specific to my (limited) knowledge of Docker and my uses of it.
- Probably gonna give up maintaining it as soon as a new hipster tech solving the same problem goes out.
- Naive and absolutely not generic.
It basically simplifies the process of using Docker Swarm and
adds helpers to avoid typing long chains of arguments.
- Creates a key store.
- Creates a swarm master.
- Create machines with different roles and configurations.
- Force rebuild if already exist.
- Describe instances.
At the moment, it is not very clever. It just automates some of painful stuffs,
so you still need to get your hands dirty with docker first.
The goal is to have a central command line tool to trigger most
of the actions I perform on a cluster while developing.
## TODO:
- Add `cluster.json` validation.
- Read from `docker-compose.yml`.
- Scale Command.
- Refactor.
- VirtualBox support.
- Security groups.
- Add Kafka/Spark/Zookeeper images to repo.
- Script deployer.
## Requirements:
You need to have installed:
- Docker
- Docker-machine
- AWS CLI tools
You also need to have an AWS credentials somewhere. Look at `cluster.json`
to see how to configure AWS for that project.
## Setup:
```
> make setup
> make setup-dev # for developement
```
## Install:
```
> make install
> which swarm_queen
> swarm_queen --help
```
## Usage:
```
> ./swarm_queen --help
Usage: swarm_queen [OPTIONS] COMMAND [ARGS]...
Options:
--cfg TEXT Cluster configuration to use
--help Show this message and exit.
Commands:
bootstrap
describe
takedown
```
It all depends (for now) on one single file: `cluster.json` that defines
your cluster.
For example:
```
{
"name": "dev",
"aws": {
"region": "us-east-1",
"credentials_file": "<home>/.aws/credentials",
"profile": "default",
"vpc_id": "vpc-fa8b4e9f"
},
"members": [
{
"name": "key-store",
"instance_type": "t2.nano",
"role": "key-store",
"priority": 2000
},
{
"name": "swarm-master",
"instance_type": "t2.nano",
"role": "swarm-master",
"priority": 1000
},
{
"name": "dbs",
"intance_type": "t2.nano",
"role": "storage",
"root-size": 20,
"priority": 100,
"num_instances": 2
},
{
"name": "app",
"intance_type": "t2.nano",
"role": "storage",
"priority": 100
}
]
}
```
### Launching a cluster:
```
> ./swarm_queen bootstrap --instances all
```
You can specify the instances to launch with a comma separated list.
```
> ./swarm_queen bootstrap --instances key-store,swarm-master
```
If an instance already exists, the simplest way is to use `--reset` flag
Look at `cluster.json` to see how to configure it.
### Examining:
```
> ./swarm_queen describe swarm-master --pretty
```
### Destroying a cluster:
```
> ./swarm_queen takedown --instances all
```
|
C# | UTF-8 | 700 | 3.140625 | 3 | [] | no_license | // for each combination of ID1 and ID2
// return the latest item from the
// most frequently-occuring quantity
IEnumerable<MyEntity> GetLatestMaxByID(IEnumerable<MyEntity> list) {
foreach (var group in list.GroupBy(x => new { x.ID1, x.ID2 }))
yield return GetSingleItemForIDs(group);
}
// return the latest item from the
// most frequently-occuring quantity
MyEntity GetSingleItemForIDs(IEnumerable<MyEntity> list) {
MyEntity maxEntity = null;
foreach (var x in list)
if (maxEntity == null || (x.Quantity > maxEntity.Quantity && x.Date > maxEntity.Date))
maxEntity = x;
return maxEntity;
}
|
Java | GB18030 | 243 | 2.421875 | 2 | [] | no_license | public class NaobaiJing implements Advertise{
public void showAdvertisement(){
System.out.println("ڲ ");
}
public String giveCorpName(){
return "ף̫˾";
}
} |
Java | UTF-8 | 6,116 | 2 | 2 | [] | no_license | package com.jusfoun.jusfouninquire.ui.widget;
import android.app.Dialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import com.jusfoun.jusfouninquire.InquireApplication;
import com.siccredit.guoxin.R;
import com.jusfoun.jusfouninquire.net.callback.NetWorkCallBack;
import com.jusfoun.jusfouninquire.net.model.BaseModel;
import com.jusfoun.jusfouninquire.net.model.LoginModel;
import com.jusfoun.jusfouninquire.net.route.LoginRegisterHelper;
import com.jusfoun.jusfouninquire.sharedpreference.LoginSharePreference;
import com.jusfoun.jusfouninquire.ui.activity.BaseInquireActivity;
import com.jusfoun.jusfouninquire.ui.util.LogUtil;
import com.jusfoun.jusfouninquire.ui.util.Md5Util;
import com.jusfoun.jusfouninquire.ui.util.PhoneUtil;
import com.jusfoun.jusfouninquire.ui.util.RegexUtils;
import java.util.HashMap;
import netlib.util.SendMessage;
import netlib.util.ToastUtils;
import static com.jusfoun.bigdata.Toaster.showToast;
public class BindPhoneDialog extends Dialog implements View.OnClickListener {
private BaseInquireActivity activity;
private SendMessage sendMessage;
private TextView vSendCode;
private EditText etPhone, etCode;
private OnSuccessListener listener;
private String userid;
public BindPhoneDialog(BaseInquireActivity activity, String userid, OnSuccessListener listener) {
super(activity);
this.activity = activity;
this.listener = listener;
this.userid = userid;
initViews();
}
private void initViews() {
setContentView(R.layout.dialog_bind_phone);
findViewById(R.id.vSure).setOnClickListener(this);
vSendCode = (TextView) findViewById(R.id.vSendCode);
etPhone = (EditText) findViewById(R.id.etPhone);
etCode = (EditText) findViewById(R.id.etCode);
vSendCode.setOnClickListener(this);
findViewById(R.id.vCancel).setOnClickListener(this);
setCanceledOnTouchOutside(false);
setCancelable(false);
Window window = this.getWindow();
android.view.WindowManager.LayoutParams lp = window.getAttributes();
lp.width = (int) (PhoneUtil.getDisplayWidth(activity) * 1);
window.setGravity(Gravity.CENTER);
window.setAttributes(lp);
sendMessage = SendMessage.newInstant(activity)
.setClickView(vSendCode)
.setInputView(etPhone)
.setTipText("获取验证码")
.setTime(60);
}
@Override
public void onClick(View view) {
String phone = etPhone.getText().toString();
String code = etCode.getText().toString();
switch (view.getId()) {
case R.id.vCancel:
dismiss();
break;
case R.id.vSendCode:
if (TextUtils.isEmpty(phone)) {
showToast("请输入手机号");
return;
}
if (!RegexUtils.checkMobile(phone)) {
showToast("请输入正确的手机号码");
return;
}
sendMessage.start();
// 发送短信
HashMap<String, String> map = new HashMap<>();
map.put("phonenumber", phone);
String random = getRandom();
map.put("ran", random);
map.put("encryption", Md5Util.getMD5Str(phone + random + "jiucifang"));
LoginRegisterHelper.verifyCodeForByMd5(activity, map, new NetWorkCallBack() {
@Override
public void onSuccess(Object data) {
BaseModel model = (BaseModel) data;
if (model.getResult() == 0) {
showToast("手机验证码已发送成功,请注意查收");
} else {
showToast(model.getMsg());
sendMessage.reset();
}
}
@Override
public void onFail(String error) {
sendMessage.reset();
ToastUtils.showHttpError();
}
});
break;
case R.id.vSure:
if (TextUtils.isEmpty(phone)) {
showToast("请输入手机号");
return;
}
if (!RegexUtils.checkMobile(phone)) {
showToast("请输入正确的手机号码");
return;
}
if (TextUtils.isEmpty(code)) {
showToast("请输入验证码");
return;
}
HashMap<String, String> pmap = new HashMap<>();
pmap.put("phone", phone);
pmap.put("userid", userid);
pmap.put("securitycode", code);
LoginRegisterHelper.bindingPhone(activity, pmap, new NetWorkCallBack() {
@Override
public void onSuccess(Object data) {
LoginModel model = (LoginModel) data;
if (model.getResult() == 0) {
if (listener != null)
listener.suc(model);
dismiss();
} else {
showToast(model.getMsg());
}
}
@Override
public void onFail(String error) {
LogUtil.e("Bind", error);
ToastUtils.showHttpError();
}
});
break;
}
}
public String getRandom() {
return String.valueOf((int) ((Math.random() * 9 + 1) * 10000));
}
public interface OnSuccessListener {
void suc(LoginModel model);
}
}
|
Java | UTF-8 | 2,935 | 1.976563 | 2 | [] | no_license | package com.sofia.poseidon.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muggle.poseidon.base.ResultBean;
import com.muggle.poseidon.util.IStringUtils;
import com.sofia.poseidon.entity.vo.SysUserVO;
import com.sofia.poseidon.service.SysUserService;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* Description
* Date 2021/11/4
* Created by muggle
*/
@RestController
public class UserController {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Autowired
private RedissonClient redissonClient;
@Autowired
private SysUserService sysUserService;
@GetMapping("/user/encode")
@PreAuthorize("hasAuthority('sys:menu:list')")
public String getEncode(String code){
return passwordEncoder.encode(code);
}
/**
* 获取验证码,通过key存入redis
* @return
* @throws IOException
*/
@GetMapping("/user/captcha.json")
public ResultBean<Map<String,String>> captcha() throws IOException {
String key = UUID.randomUUID().toString();
final String code = IStringUtils.getCode(5);
final RMap<Object, Object> captcha = redissonClient.getMap("poseidon:captcha");
captcha.put(key,code);
captcha.expire(5, TimeUnit.MINUTES);
Map<String, String> result=new HashMap<>();
result.put("code",code);
result.put("key",key);
return ResultBean.successData(result);
}
@GetMapping("/user/userInfo")
public ResultBean<SysUserVO> userInfo(Principal principal) {
SysUserVO sysUserVO=sysUserService.getUserInfo(principal.getName());
return ResultBean.successData(sysUserVO);
}
@GetMapping("/system/user/list")
public ResultBean<IPage<SysUserVO>> userInfo(String username, Long current, Long size) {
if (current==null){
current=1L;
}
if (size==null){
size=10L;
}
final IPage<SysUserVO> userList = sysUserService.getUserList(username, current, size);
return ResultBean.successData(userList);
}
}
|
C++ | UTF-8 | 13,746 | 2.515625 | 3 | [
"BSD-2-Clause"
] | permissive | #pragma once
namespace KERF_NAMESPACE {
struct TRANSMIT_NODE;
struct TRANSMITTER;
struct EMITTER
{
bool bytes_remain_to_read = true;
TRANSMIT_NODE *parent;
virtual I read_1_byte_write_to_buffer(char *buffer){return read_up_to_n_bytes_write_to_buffer(buffer, 1);};
virtual I read_up_to_n_bytes_write_to_buffer(char* buffer, I n){I bytes_read; return bytes_read;};
virtual I brute_write_1_byte_read_from_buffer(char* buffer){return brute_write_n_bytes_read_from_buffer(buffer, 1);};
virtual I brute_write_n_bytes_read_from_buffer(char* buffer, I n){I error_code; return error_code;};
};
struct EMITTER_DESCRIPTOR_HANDLE: EMITTER { };
struct EMITTER_SOCKET_DESCRIPTOR_HANDLE : EMITTER_DESCRIPTOR_HANDLE { };
struct EMITTER_PIPE_DESCRIPTOR_HANDLE : EMITTER_DESCRIPTOR_HANDLE { };
struct EMITTER_FILE_DESCRIPTOR_HANDLE : EMITTER_DESCRIPTOR_HANDLE { }; // aka IS_REG regular file
struct EMITTER_FILEPATH : EMITTER_FILE_DESCRIPTOR_HANDLE // Question. regular files? symlinks? directories?
{
EMITTER_FILEPATH(std::string s);
};
struct EMITTER_FILE_STAR_STREAM : EMITTER_FILE_DESCRIPTOR_HANDLE
{
// Refresher: POSIX calls `FILE*->drive` a STREAM and a HANDLE. POSIX calls `int->drive` (or `int->pipe` or `int->socket`) a DESCRIPTOR (`fd`/`filedes`) and HANDLE. Both refer to `FILE DESCRIPTIONS` (note: `descript-*ions*` not `-*tors*`) which just means the file/pipe/socket/&c itself. POSIX distinguishes pipes/sockets/&c from so-called "regular" files (IS_REG), say on the drive. See our use of `fstat`.
// optimistically, maybe we can convert this to a file handle. In Kerf1 we just used fwrite. Pr. we had checked and not found conversion. - seemingly `fileno` will do this? (and in fact we used this `fileno` trick in kerf1. we didn't everywhere b/c we already had buffer functionality that worked with `FILE*`. ) The reverse direction is `fdopen`.
};
struct EMITTER_POINTER_POINTER : EMITTER
{
EMITTER_POINTER_POINTER(void *p);
EMITTER_POINTER_POINTER(SLAB* s);
};
struct EMITTER_NULL_POINTER_POINTER : EMITTER_POINTER_POINTER
{
EMITTER_NULL_POINTER_POINTER(void** p);
};
struct TRANSMIT_NODE // point of this is to avoid n^2 constructors
{
TRANSMITTER *parent;
EMITTER *emitter = nullptr;
TRANSMIT_NODE(std::string s) { emitter = new EMITTER_FILEPATH(s); }
TRANSMIT_NODE(void**p) {if(p==nullptr) { /* TODO error */ ;} emitter = (*p == nullptr) ? new EMITTER_NULL_POINTER_POINTER(p) : new EMITTER_POINTER_POINTER(p); }
TRANSMIT_NODE(FILE*f);
TRANSMIT_NODE(TRANSMITTER t); // chaining?
TRANSMIT_NODE(int h)
{
struct stat c;
if(0 > fstat(h,&c))
{
perror("File handle status failed");
// goto failed;
}
bool regular_file = S_ISREG( c.st_mode);
bool link_handle = S_ISLNK( c.st_mode);
bool is_dir = S_ISDIR( c.st_mode);
bool socket_handle = S_ISSOCK(c.st_mode);
bool pipe_fifo = S_ISFIFO(c.st_mode);
bool char_term = S_ISCHR( c.st_mode);
}
// TRANSMIT_NODE(SLAB **s) : TRANSMIT_NODE((void**)s){};
// TRANSMIT_NODE(SLOP &&s); // &s can write but &&s only read. We should be careful with SLOP because it manages its own SLAB* with references and such [so we can't just do SLAB** overload and call it a day: we need to detect when the SLAB* changes and call the corresponding SLOP methods]. So we can do this, but we need to wrap our SLOP-emitter object. A simple way is to do known_flat in memory.
bool writeable_emitter(); // SLOP&& can't past a certain point
I read_1_byte_write_to_buffer(char* buffer){return emitter->read_1_byte_write_to_buffer(buffer);}
I read_up_to_n_bytes_write_to_buffer(char* buffer, I n){return emitter->read_up_to_n_bytes_write_to_buffer(buffer,n);}
I brute_write_1_byte_read_from_buffer(char* buffer){return emitter->brute_write_1_byte_read_from_buffer(buffer);}
I brute_write_n_bytes_read_from_buffer(char* buffer, I n){return emitter->brute_write_n_bytes_read_from_buffer(buffer,n);}
TRANSMIT_NODE();
~TRANSMIT_NODE()
{
if(emitter) delete emitter;
}
bool had_error();
};
struct TRANSMITTER
{
// TODO checklist item: make sure we set the proper arena on the receiver side. all subelements should be a transient-like arena (0), which can be preserved on both sides of the wire.
// TODO zero the sutex rwlock on any receiving side
// Remember. Whatever you do in memory is going to pale in comparison to sending it over the wire, so just zip it, filter it, do whatever.
// Remark. Just write some bad ones with the intent of going back and refactoring. to get a foothold
// Idea. the thing we want on lhs is maybe `->ready(char buf[], I length)`? then on the rhs? in the middle? how do we call this without imposing need for buffer?
// maybe: middle->give_me(MAX, offset) left->i_have(revised) middle->do_this_left middle->consume_right[i]
// Idea. We can do a percentage-tracker if we want. Ask the LHS for two numbers: known total size of existing arg, and known total size of the produced, filtered output from the existing arg. Return say "-1" for sizes it doesn't know or can't compute easily. Then, as bytes are read/written, update the counter for the in-progress size relative to the total. This is interesting I guess for large file transfers, writes, and what not, especially if we have control over the terminal and can make it clean.
// TODO: TRANSMITTER needs the write lock if it wants to cache filesizes?
// Remark. The way to proceed is to actually write the simple version with all the restrictions, then relax restrictions one by one and rewrite, incorporating the new functionality.
// CURRENT_RESTRICTION: Don't write DIRECTORIES or MULTI-FILE yet
// CURRENT_RESTRICTION: Don't do FANOUT (array of rhs)
// CURRENT_RESTRICTION: Don't do multi-threading (reader+writers pattern)
// CURRENT_RESTRICTION: Don't do chaining (>=3 nodes/filters) maybe.
// CURRENT_RESTRICTION: Don't STREAM at first, do all work in BATCH
// CURRENT_RESTRICTION: Don't do COMPRESSSION yet
// POP: remove restrictions
// POP Linux has tee,splice,vmsplice
// POP when we multithread, have two buffers, consumers get sutex read lock on buffer pointer, producer fills other buffer while they're reading, uses write lock two swap buffer addresses. Of interest: `readv` `writev`
// TODO sending kerf tree over network, need to reassemble locks on the other side. You can either transmit the RW_LOCKS and rewrite the mutex on the other side, or you can not transmit them and then detect the map_is_kerf_tree_map bit on the other side and re-add RW_LOCKs to the nodes of the tree with the bit set. Remember. If you're using std::shared_mutex, then you're going to need to do sizeof() allocs on the other side instead of knowing in advance, probably.
// Remark: I dunno how useful fanout is (potentially for some kind of weird backup scenario - rare. or some other strange scenario involving multiple formats. seems thin overall). You know, for writing to multiple net sockets (d-kerf), FANOUT WOULD be useful, EXCEPT we can easily multithread that at a higher level. not if the thing doesn't fit into memory tho... It's also highly useful if we're re-broadcasting to several machines on a network (feed handler).
// Remark. FILTERS may be an array on this thing.
// Idea. Corner-cutting: Should we do everything in in-memory-batch (ie, build a COMPACTED vector) before flushing to disk [re: rhs]? (Avoiding buffered streaming.) Similarly, zipping every object fully-at-once instead of streaming?
// Idea. Would be nice if we could pass "(start_position, length)" read args to the lhs from everywhere.
// Idea. we can populate operator<< and operator>> in SLOP to use a default transmitter transparently for serialization
TRANSMIT_NODE reader;
std::vector<TRANSMIT_NODE> writers;
I buffer_position = 0;
I buffer_size = PAGE_SIZE_BYTES;
char* buffer;
bool finished = false;
bool has_error = false;
// PUTATIVE ////////////////
I size_of_lhs = -1;
I transmitter_indicated_wanted_size_of_rhs = -1;
I available_capacity_of_provided_rhs = -1;
std::map<void *, I>object_size_cache; // P_O_P: only caches sizes > some minimum
////////////////////////////
private: // NB. these bool are private until we implement them [functionality implied by their other truth halves].
// Idea. Separate these attributes into {drive, inet, both, neither}, or make a table of T/F for {drive, inet, ram} etc
// Pointer-only args //////////////////////
bool transmittingFlatContiguousVersusAllocatingInMemoryChildrenOrMultipleFiles = true;
bool canMoveOrMremapPointerArg = true; // TODO must callback to emitter so SLOP can release_slab_and_replace_with(.), etc.
bool shallowVersusDeepCopy = false; // note: can only do this for in-memory copies, not inet or drive ?
bool incrementChildPointers = true;
bool referenceIncrementOnDetectedIdentityOperationInsteadOfForceCopy = false;
// TODO: pointer has associated fixed capacity c? perhaps we will or will not do this
///////////////////////////////////////////
// Streaming //////////////////////////////
bool STREAMINGdecompressIncomingCompressedStreamDataAsOverSocket = false;
bool STREAMINGcompressOutgoingUncompressedStreamDataAsOverSocket = false;
///////////////////////////////////////////
bool writingSingleFileInsteadOfMultipleFilesOrDirectory = true;
bool writeMmappableAppendableAmendableVERSUSWriteCOMPACTIFIED = false;
bool literalCopyEgTapeHeadInsteadOfRepresentational = false;
bool doNotMultithreadEgPtrToPtrCopies = true; // Remark. Some stuff we don't want to be threaded, like ptr to ptr writes (copies).
bool followsISLNKSymlinksInsteadOfOverwritesSymlinks = false;
bool isPurePassthroughWithoutIntermediateBuffer = false; // Remark. stream functions (modifying input) versus pure passthrough (writing pipe to pipe, opt without buffer)
int identityOrHTONOrNTOH = 0; // Idea. Don't handle Endianness Big-Endian Little-Endian here [batch version], even in the STREAMING version really. Simply set little/big endian HOST on the sender's MESSAGE header thing, then the receiver can fix things up on the other side. (If the hosts match there's nothing to do.) In-memory this is fast and pales in comparison to network transfer time. On-disk, it already involves a disk swap. This is performant and good. Best of all it's modular so you can postpone it. Note: Use network-order in MESSAGE.
int readerIsBinaryFormatOrJSONFormatOrDisplayFormat = 0;
int writerIsBinaryFormatOrJSONFormatOrDisplayFormat = 0;
bool prependsMessageHeader_MaybeMaybe = false;
bool consumesMessageHeader_MaybeMaybe = false;
bool writeSlabHeaderOrNot = true;
bool readsFromDriveToRAMAsMMAPPED_OBJECT = false;
int writes_unchanged_or_force_regular_OR_ZipArray_OR_ZipList_OR_LIST_OR_JUMPLIST_OR_LISTZIPLISTLIST_OR_LISTZIPARRAYJUMPLIST = 0;
bool rehydrateUncompactIncomingDataIfNotAlready = false; // We have a model in mind where arrays are "always" written to disk transparently compressed (say via lz4) but when you read them back you need to decompress them transparently as well.
bool dehydrateCompactOutgoingDataIfNotAlready = false;
bool zeroesPointersOnWrite = false; // for writing non-flat elements, zero RLINK3 pointers and SLAB4's embedded pointers before they hit the drive/network
int writesLiteralMemoryMappedNotRepToDrive = false;
int transmitsLiteralMemoryMappedNotRepOverInet = true;
int InetRecipientShouldRequestCorrespondingFilesForMemoryMappedReferencedPath = true;
bool unflattensEgMakesAllAppendableAnyReceivedSinglefileFlatObjectFromNetworkOrDrive = true;
public:
TRANSMITTER(TRANSMIT_NODE lhs, TRANSMIT_NODE rhs)
{
reader = std::move(lhs);
writers = {std::move(rhs)};
}
void finish()
{
finished = true;
};
void start()
{
//assert reader can read
//assert writer can write
while(pump());
finish();
};
bool pump()
{
// this PULLS from lhs. but we probably want lhs to PUSH into multiple buffers (call it FEED or FLOW). after each buffer is filled (or lhs can't read/write anymore) then have writers move to the next buffer.
// Remark. Bug. Our model is probably broken. Instead of TRANSMITTER having a left and right, Nodes should have an array of nodes to the right, and then a transmitter maintains one root node. Then you can chain. Maybe none of this is necessary if we don't have a use for it. It's CERTAINLY not useful in BATCH mode instead of streaming.
// POP sometimes the buffer can just be the right-hand side's pointer instead of our intermediate TRANSMITTER.buffer. Some of those may be determined by TRANSMITTER(specific_class1 x, specific_class2 b)
I available = buffer_size - buffer_position;
char* relative_buffer = buffer + buffer_position;
int bytes_read = 0;
bool still_reading = reader.emitter->bytes_remain_to_read;
if(still_reading)
{
int bytes_read = reader.read_up_to_n_bytes_write_to_buffer(relative_buffer, available);
if(bytes_read < 0 ){} // error or stream closed
still_reading = reader.emitter->bytes_remain_to_read;
}
if(bytes_read > 0)
{
for(auto writer : writers) // POP this is where you would parallelize
{
int error_code = writer.brute_write_n_bytes_read_from_buffer(relative_buffer, bytes_read);
if(error_code){}
}
buffer_position += bytes_read;
if(buffer_position >= buffer_size) buffer_position = 0;
}
bool still_pumping = still_reading;
return still_pumping;
}
bool had_error = false;
SLAB* resultant_pointer = nullptr;
TRANSMITTER()
{
buffer = new char[buffer_size];
}
~TRANSMITTER()
{
delete[] buffer;
}
};
} // namespace
|
C++ | UTF-8 | 849 | 2.8125 | 3 | [] | no_license | //
// Created by kimdong on 2019-05-04.
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct result{
int idx;
int score;
};
bool compare(result a, result b){return a.score > b.score;}
vector<result> board(8,{0,0});
int totalScore = 0;
vector<int> ans;
void input();
void choice();
void output();
int main(){
ios::sync_with_stdio(false), cin.tie(NULL);
input();
choice();
output();
return 0;
}
void input(){
for(int i=0; i<8; i++) cin >> board[i].score, board[i].idx = i+1;
}
void choice(){
sort(board.begin(),board.end(),compare);
for(int i=0; i<5; i++) totalScore += board[i].score, ans.push_back(board[i].idx);
sort(ans.begin(),ans.end());
}
void output(){
cout << totalScore << '\n';
for(int i=0; i<5; i++) cout << ans[i] << ' ';
cout << '\n';
} |
Python | UTF-8 | 6,144 | 2.703125 | 3 | [
"MIT"
] | permissive | __author__="congcong wang"
import pickle
import shutil
import time
from sklearn.metrics.pairwise import cosine_similarity
from sentence_transformers import SentenceTransformer
from tqdm import tqdm
import nltk
import os
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.ERROR)
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.INFO)
class SentenceSearch():
def __init__(self,instances,default_save="models_save/sentencesearch/",sentence_transformer='bert-base-nli-mean-tokens'):
"""
This class is used to extract insights as specified in https://www.kaggle.com/allen-institute-for-ai/CORD-19-research-challenge/tasks
Considering the complexity of this method, this model is considered to be inapproporiate for query-based search
:param instances: [(paper-id,paper-content),...]
:param default_save: path for object serialization, we need this due to both large space and time computation complexity from scratch every time
:param sentence_transformer: "bert-base-nli-mean-tokens" by default, more refers to https://github.com/UKPLab/sentence-transformers. This is expected to adapt to in-domain pre-trained models such as SciBERT or BioBERT
"""
self.index2idsent = {}
self.embeddings=[]
self.default_save=default_save
self.embedder = SentenceTransformer(sentence_transformer)
if not os.path.isdir(default_save) or not os.path.isfile(
default_save + "-embeddings.pkl") or not os.path.isfile(default_save + "-index2idsent.pkl"):
if os.path.isdir(default_save):
shutil.rmtree(default_save)
os.mkdir(default_save)
logger.info("Not found the pre-saved files...")
sentences_batch = []
batch_size = 8
index=0
for ins in tqdm(instances, desc="Reading sentences from instances"):
for sent in nltk.sent_tokenize(ins[1]):
if len(sent)>=15:
self.index2idsent[index]=(ins[0],sent)
index+=1
sentences_batch.append(sent)
if index%batch_size==0:
batch_embeddings=self.embedder.encode(sentences_batch)
self.embeddings.extend(batch_embeddings)
sentences_batch=[]
if sentences_batch!=[]:
batch_embeddings = self.embedder.encode(sentences_batch)
self.embeddings.extend(batch_embeddings)
assert len(self.embeddings)==len(self.index2idsent)
with open(default_save+"-embeddings.pkl", 'wb') as f:
pickle.dump(self.embeddings, f)
logger.info("embeddings are saved to " + default_save+"-embeddings.pkl")
with open(default_save+"-index2idsent.pkl", 'wb') as f:
pickle.dump(self.index2idsent, f)
logger.info("Index2idsent is saved to " + default_save+"-index2idsent.pkl")
else:
logger.info("Loading sentences embeddings object from " + default_save + "-embeddings.pkl")
with open(default_save + "-embeddings.pkl", 'rb') as pickled:
self.embeddings = pickle.load(pickled)
logger.info("Loading ids object from " + default_save + "-index2idsent.pkl")
with open(default_save + "-index2idsent.pkl", 'rb') as pickled:
self.index2idsent = pickle.load(pickled)
logger.info("Shape of embeddings: "+str(len(self.embeddings))+","+str(len(self.embeddings[0])))
def query_by_kaggle_tasks(self,tasks,top_k=100):
"""
This method is used to query insights for each task as in https://www.kaggle.com/allen-institute-for-ai/CORD-19-research-challenge/tasks
:param tasks: the dictionary paired by {"task_name":"task_desc",...}
:param top_k: select the top k most semantic similar sentences from the sentence-level corpus, namely the insights for each task
:return: {"task_name",[top_k_sentences],}
"""
tasks2ranked_indices={}
if not os.path.isdir(self.default_save) or not os.path.isfile(
self.default_save + "-tasks2ranked_indices.pkl"):
for name,query in tqdm(tasks.items()):
logger.info("Computing for "+name)
query_embedding = self.embedder.encode([query])
start = time.time()
cosine_similarities=cosine_similarity(query_embedding,self.embeddings).flatten()
ranked_indices=cosine_similarities.argsort()
tasks2ranked_indices[name]=ranked_indices
logger.info(("Test time: "+str(time.time() - start)))
with open(self.default_save+"-tasks2ranked_indices.pkl", 'wb') as f:
pickle.dump(tasks2ranked_indices, f)
logger.info("tasks2ranked_indices is saved to " + self.default_save+"-tasks2ranked_indices.pkl")
else:
logger.info("Loading tasks2ranked_indices object from " + self.default_save + "-tasks2ranked_indices.pkl")
with open(self.default_save + "-tasks2ranked_indices.pkl", 'rb') as pickled:
tasks2ranked_indices = pickle.load(pickled)
return_results={}
for task_name,ranked_indices in tasks2ranked_indices.items():
related_sents_indices = ranked_indices[:-top_k-1:-1]
results=[(self.index2idsent[indice][0],self.index2idsent[indice][1]) for indice in related_sents_indices]
return_results[task_name]=results
with open(self.default_save + "-results_save.pkl", 'wb') as f:
pickle.dump(return_results, f)
logger.info("results are saved to " + self.default_save + "-results_save.pkl")
return return_results
@classmethod
def load_from_save(self,save_path="models_save/sentencesearch/-results_save.pkl"):
with open(save_path, 'rb') as pickled:
return_results = pickle.load(pickled)
return return_results
|
Shell | UTF-8 | 399 | 3.375 | 3 | [] | no_license | #!/bin/sh
[ -f ./restricted/common ] && . ./restricted/common
PREFIX=infrastructure
myexit(){
echo "ERROR DURING BUILDING IMAGE"
exit 1
}
IMAGES="paas mesos mesos-slave mesos-master consul haproxy registrator dnsmasq"
for image in $IMAGES; do
docker build --rm=true --tag=${REGISTRY}${image} $PREFIX/${image}|| myexit
docker tag -f ${REGISTRY}${image}:latest ${image}:latest || myexit
done
|
Markdown | UTF-8 | 893 | 2.890625 | 3 | [] | no_license | # Vehicle-Collection
A simple Console Application that make you Add, Modify and Remove vehicles to/from a list.
The list can be stored on a JSON/XML file to save all your vehicles and load them every time you start the application.
N.B.:
To save all the changes, you need to edit the following methods:
1) private static async Task<ICollection<Vehicle>> LoadFromJSONAsync(){...}
2) private static async Task SaveToJsonAsync(ICollection<Vehicle> vehicles){...}
3) private static ICollection<Vehicle> LoadFromXML(){...}
4) private static void SaveToXML(ICollection<Vehicle> vehicles){...}
In 1) and 2) replace the strings "F:\\ProgettiVS\\Demo2\\Demo2\\Files\\vehicles.json" with "your_JSON_file_PATH".
In 3) and 4) replace the strings "F:\\ProgettiVS\\Demo2\\Demo2\\Files\\vehicles.xml" with "your_XML_file_PATH".
Saving changes is not automatic, you have to do it manually in the MENU!
|
Python | UTF-8 | 34,696 | 2.640625 | 3 | [] | no_license | from functools import partial
from tkinter import *
from tkinter import ttk
import psycopg2
from tkinter import messagebox
from PIL import ImageTk
from function_ import get_geometry, get_monitor
class Student:
get_mo = get_monitor()
width_manage_frame = get_mo[0] * 0.234 # Ширина Manage frame
height_manage_frame = get_mo[1] * 0.9 # Высота Manage frame
def __init__(self, root):
self.root = root
self.root.title("Student Management System")
get_geometry(self.root)
self.link = psycopg2.connect(dbname = "stm", user = "postgres", password = "askarova180774", host = "localhost") #пытался подключение сделать одниой переменной, не вышло, не принимает его
self.bg_icon = ImageTk.PhotoImage(file = "template/img/main_bg.jpg") #общий фон для этого окна
# bg_lvl = Label(self.root, image = self.bg_icon).pack()
bg_lvl = Label(self.root, image = self.bg_icon).pack()
# bg_lvl = Label(self.root, bg = "silver").pack()
#Manage, Detail, Table Frame Backgrounds
# bg_frame = "#3b4045" #Общий цвет фона для frame-ов
bg_frame = "#535454" #Общий цвет фона для frame-ов
# bg_frame = "orange"
bg_frame_b = "#444345" # Общий background для BUTTONS
fg_b = "white" # Общий цвет текста для BUTTONS
fg_frame = "white" #Общий цвет текста для frame-ов
font_all_3 = "" #Стиль текста во всем документе например bold, italic
font_all_1 = "Times New Roman" #Стиль текста во всем документе например Times New Roman, Courier
title = Label(self.root, text = "Система управления студентами", font = (font_all_1, 36, font_all_3), bg = "#444345", fg ="white", bd = 10)
# title.pack(side = TOP, fill = X)
title.place(x=0, y=0, relwidth=1)
# All variables for db*******************************************************************************************************************
self.roll_No_var = StringVar()
self.name_var = StringVar()
self.email_var = StringVar()
self.gender_var = StringVar()
self.contact_var = StringVar()
self.dob_var = StringVar()
self.search_by = StringVar()
self.search_txt = StringVar()
# Manage Frame*******************************************************************************************************************
self.Manage_Frame = Frame(self.root, bd=4, relief=RIDGE, bg= bg_frame)
self.Manage_Frame.place(x=20, y=90, width=self.width_manage_frame, height=self.height_manage_frame)
# Add Frame on Manage frame------------------------------------------------------------------------------------------------
self.Add_frame = Frame(self.Manage_Frame, bg=bg_frame)
self.Add_frame.place(y=70, width=self.width_manage_frame - 8, height=self.height_manage_frame / 4)
Add_txt = Label(self.Add_frame, text = "Добавить:", bg= bg_frame, fg = fg_frame, font = (font_all_1, 20, font_all_3))
Add_txt.grid(row=0, column = 0, pady=13, padx=50)
Add_frame_button = Frame(self.Add_frame, bg=bg_frame)
Add_frame_button.place(x = self.width_manage_frame/2, y = 5, width = self.width_manage_frame/2-8, height = self.height_manage_frame/4-8)
add_with_arg = partial(self.show_manage_frame, "add")
add_student_1 = Button(Add_frame_button, text = "Студента", width = 20, height = 2, bg = bg_frame_b, fg = fg_b, command = add_with_arg,
font = (font_all_1, 10, ""))
add_student_1.grid(row = 0, column = 0, padx = 5, pady = 10)
add_student_2 = Button(Add_frame_button, text = "Учителя", width=20, height = 2, bg=bg_frame_b, fg=fg_b,
font = (font_all_1, 10, ""))
add_student_2.grid(row=1, column=0, padx=5, pady=10)
add_student_3 = Button(Add_frame_button, text = "Персонал", width=20, height = 2, bg=bg_frame_b, fg=fg_b,
font = (font_all_1, 10, ""))
add_student_3.grid(row=2, column=0, padx=5, pady=10)
add_student_4 = Button(Add_frame_button, text = "Другие", width=20, height = 2, bg=bg_frame_b, fg=fg_b,
font = (font_all_1, 10, ""))
add_student_4.grid(row=3, column=0, padx=5, pady=10)
# Кнопка для обновления и удаления-----------------------------------------------------------------------------------------------------------------
self.Update_Delete_Frame = Frame(self.Manage_Frame, bg=bg_frame)
self.Update_Delete_Frame.place( y= 100 + (self.height_manage_frame / 4),
width=self.width_manage_frame - 8, height=self.height_manage_frame / 4)
Update_Delete_frame_button = Frame(self.Update_Delete_Frame, bg=bg_frame)
Update_Delete_frame_button.place(x=self.width_manage_frame / 2, y=5, width=self.width_manage_frame / 2 - 8,
height=self.height_manage_frame / 4 - 8)
Add_txt = Label(self.Update_Delete_Frame, text="Действия:", bg=bg_frame, fg=fg_frame, font=(font_all_1, 20, font_all_3))
Add_txt.grid(row=0, column=0, pady=13, padx=50)
self.UpdateButton_main = Button(Update_Delete_frame_button, text="Обновить", width=20, height=2, bg=bg_frame_b, fg=fg_b,
command = self.get_cursor, font=(font_all_1, 10, ""), state = DISABLED)
self.UpdateButton_main.grid(row=0, column=1, padx=5, pady=10)
self.DeleteButton_main = Button(Update_Delete_frame_button, text="Удалить", width=20, height=2, bg=bg_frame_b, fg=fg_b,
command=self.delete_data, font=(font_all_1, 10, ""), state=DISABLED)
self.DeleteButton_main.grid(row=1, column=1, padx=5, pady=10)
#Manage mini Frame on Add frame-------------------------------------------------------------------------------------------------------------------------------
self.Manage_mini_Frame = Frame(self.Manage_Frame, bg = bg_frame)
self.Manage_mini_Frame.place( y=75, width=self.width_manage_frame-10, height=self.height_manage_frame-100)
self.Manage_mini_Frame.place_forget()
# -------------------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------------------------------
m_title = Label(self.Manage_Frame, text = "Панель управления", bd = 4, relief = RIDGE, bg= bg_frame, fg = fg_frame, font = (font_all_1, 25, font_all_3))
m_title.grid(row = 0, columnspan = 2, pady = 15, padx = 45, ipadx = 40, ipady = 3.5)
# m_title.grid(relx=.5, rely=.75, anchor="c")
#-------------------------------------------------------------------------------------------------------------------------------
self.lbl_rool = Label(self.Manage_mini_Frame, text = "No.", bg= bg_frame, fg = fg_frame, font = (font_all_1, 20, font_all_3))
# self.lbl_rool.grid(row = 1, column = 0, padx = 20, pady = 20, sticky = "w")
self.txt_Roll = Entry(self.Manage_mini_Frame, textvariable = self.roll_No_var, font = (font_all_1, 15, "bold"), state = DISABLED)
# self.txt_Roll.grid(row = 1, column = 1, pady = 10, sticky = "w")
# -------------------------------------------------------------------------------------------------------------------------------
lbl_name = Label(self.Manage_mini_Frame, text="Имя", bg= bg_frame, fg=fg_frame, font = (font_all_1, 20, font_all_3))
lbl_name.grid(row=2, column=0, padx = 20, pady=20, sticky="w")
txt_name = Entry(self.Manage_mini_Frame,textvariable = self.name_var, font=(font_all_1, 15, "bold"))
txt_name.grid(row=2, column=1, pady=10, sticky="w")
#-------------------------------------------------------------------------------------------------------------------------------
lbl_Email = Label(self.Manage_mini_Frame, text="Email", bg= bg_frame, fg=fg_frame, font=(font_all_1, 20, font_all_3))
lbl_Email.grid(row=3, column=0, padx = 20, pady=20, sticky="w")
txt_Email = Entry(self.Manage_mini_Frame,textvariable = self.email_var, font=(font_all_1, 15, "bold"))
txt_Email.grid(row=3, column=1, pady=10, sticky="w")
# -------------------------------------------------------------------------------------------------------------------------------
lbl_Gender = Label(self.Manage_mini_Frame, text="Пол", bg= bg_frame, fg=fg_frame, font = (font_all_1, 20, font_all_3))
lbl_Gender.grid(row=4, column=0, padx = 20, pady=10, sticky="w")
combo_Gender = ttk.Combobox(self.Manage_mini_Frame,textvariable = self.gender_var, font = (font_all_1, 14, "bold"), width = 17, state = 'readonly')
combo_Gender['values'] = ("Мужчина", "Женщина")
combo_Gender.grid(row = 4, column = 1, pady = 10, sticky="w")
# -------------------------------------------------------------------------------------------------------------------------------
lbl_Contact = Label(self.Manage_mini_Frame, text="Контакты", bg= bg_frame, fg=fg_frame, font = (font_all_1, 20, font_all_3))
lbl_Contact.grid(row=5, column=0, padx = 20, pady=20, sticky="w")
txt_Contact = Entry(self.Manage_mini_Frame,textvariable = self.contact_var, font=(font_all_1, 15, "bold"))
txt_Contact.grid(row=5, column=1, pady=10, sticky="w")
# -------------------------------------------------------------------------------------------------------------------------------
lbl_DOB = Label(self.Manage_mini_Frame, text="Дата рождения", bg= bg_frame, fg=fg_frame, font = (font_all_1, 20, font_all_3))
lbl_DOB.grid(row=6, column=0, padx = 20, pady=20, sticky="w")
txt_DOB = Entry(self.Manage_mini_Frame,textvariable = self.dob_var, font=(font_all_1, 15, "bold"))
txt_DOB.grid(row=6, column=1, pady=10, sticky="w")
# -------------------------------------------------------------------------------------------------------------------------------
lbl_Address = Label(self.Manage_mini_Frame, text="Адрес", bg= bg_frame, fg=fg_frame, font=(font_all_1, 20, font_all_3))
lbl_Address.grid(row=7, column=0, padx = 20, pady=20, sticky="w")
self.txt_Address = Text(self.Manage_mini_Frame, width = 20, height = 4, font = (font_all_1, 14, "bold"))
self.txt_Address.grid(row=7, column=1, pady=10, sticky="w")
self.AddButton = Button(self.Manage_mini_Frame, text="Добавить", width=35, height=2, bg="#2ea44f", fg=fg_b,
command=self.add_students, font = (font_all_1, 11, "bold"))
# self.AddButton.grid(row=8, columnspan=2, padx=40, pady=15)
# self.AddButton.grid_forget()
self.UpdateButton = Button(self.Manage_mini_Frame, text="Обновить", width=35, height=2, bg="#f9826c", fg=fg_b,
command=self.update_data, font=(font_all_1, 11, "bold"))
# self.UpdateButton.grid(row=8, columnspan=2, padx=40, pady=15)
# self.UpdateButton.grid_forget()
self.DeleteButton = Button(self.Manage_mini_Frame, text="Удалить", width=35, height=2, bg="red", fg=fg_b,
command=self.delete_data, font=(font_all_1, 11, "bold"))
# self.UpdateButton.grid(row=9, columnspan=2, padx=40, pady=15)
# self.UpdateButton.grid_forget()
self.Back_Button = Button(self.Manage_mini_Frame, text = "Назад", width = 15, height = 2, bg = bg_frame_b, fg = fg_b,
command = self.show_manage_frame, font = (font_all_1, 10, "bold"))
# self.Back_Button.grid(row = 9, column = 0, padx = 0, pady = 10)
# self.Back_Button.grid_forget()
# Button Frame on Manage frame-------------------------------------------------------------------------------------------------------------------------------
# Button_Frame = Frame(self.Manage_mini_Frame, bd=4, relief=RIDGE, bg="white")
# Button_Frame.place(x=8, y=680, width=width_manage_frame * 0.912)
# Button_Frame.place(relx=.5, rely=.75, anchor="c")
# Button_Frame.place_forget()
# padx_b = 20 #Общий padx для ADD ,UPDATE ,DELETE , CLEAR BUTTONS
# AddButton1 = Button(Button_Frame, text = "Добавить", width = 15, height = 1, bg = bg_frame_b, fg = fg_b, command = self.add_students).grid(row = 0, column = 0, padx = padx_b, pady = 10)
# UpdateButton = Button(Button_Frame, text = "Обновить", width = 15, height = 1, bg = bg_frame_b, fg = fg_b, command = self.update_data).grid(row = 0, column = 1, padx = padx_b, pady = 10)
# DeleteButton = Button(Button_Frame, text = "Удалить", width = 15, height = 1, bg = bg_frame_b, fg = fg_b, command = self.delete_data).grid(row = 1, column = 0, padx = padx_b, pady = 10)
# ClearButton = Button(Button_Frame, text = "Очистить", width = 15, height = 1, bg = bg_frame_b, fg = fg_b, command = self.clear).grid(row = 1, column = 1, padx = padx_b, pady = 10)
# Detail Frame*******************************************************************************************************************
width_detail_frame = self.get_mo[0] * 0.729 #Ширина Detail Frame
height_detail_frame = self.get_mo[1] * 0.9 #Высота Detail Frame
self.Detail_Frame = Frame(self.root, bd=4, relief=RIDGE, bg= bg_frame)
self.Detail_Frame.place(x=500, y=90, width=width_detail_frame, height=height_detail_frame)
# -------------------------------------------------------------------------------------------------------------------------------
self.lbl_Search = Label(self.Detail_Frame, text="Поиск по", bg= bg_frame, fg=fg_frame, font=(font_all_1, 20, font_all_3)) #надпись Поиск по
self.lbl_Search.grid(row=0, column=0, padx = 20, pady=20, sticky="w")
self.combo_Search = ttk.Combobox(self.Detail_Frame, textvariable = self.search_by, width = 10,
font=("Times New Roman", 13, font_all_3), state='readonly')
self.combo_Search.bind("<<ComboboxSelected>>", self.TextBoxUpdate) #Забиндил чтобы когда выбирали пол, пропадал label и его заменял combobox с выборкой м или ж
self.combo_Search['values'] = ("roll_no", "name", "email", "gender", "contact")
self.combo_Search.grid(row=0, column=1, pady=10, sticky="w")
# -------------------------------------------------------------------------------------------------------------------------------
self.combo_gender = ttk.Combobox(self.Detail_Frame, textvariable=self.search_txt, width=10,
font=("Times New Roman", 13, ""), state='readonly')
# self.combo_gender.bind("<<ComboboxSelected>>", self.TextBoxUpdate)
self.combo_gender['values'] = ("Мужчина", "Женщина")
self.combo_gender.grid(row=0, column=2, pady=10, padx=20, sticky="w")
self.combo_gender.grid_remove() #Сделал невидимым так как он должен выходить только после того как в combo_Search выбирется gender, а реализует это функция self.TextBoxUpdate
self.txt_Search = Entry(self.Detail_Frame, textvariable = self.search_txt, width = 10, font=(font_all_1, 14, font_all_3))
self.txt_Search.grid(row=0, column=2, pady=10, padx=20, sticky="w")
self.show_manage_frame_txt = StringVar()
self.show_manage_frame_txt = "0"
SearchButton = Button(self.Detail_Frame, text="Поиск", width=10, pady = 5, bg = bg_frame_b, fg = fg_b, command = self.search_data, font=(font_all_1, 14, font_all_3)).grid(row=0, column=3, padx=30, pady=10)
ShowallButton = Button(self.Detail_Frame, text="Показать все", width=15, pady = 5, padx = 10, bg = bg_frame_b, fg = fg_b, command = self.fetch_data, font=(font_all_1, 14, font_all_3)).grid(row=0, column=4, padx=30, pady=10)
exit_root = Button(self.Detail_Frame, text="Выйти", width=15, pady = 5, padx = 10, bg = bg_frame_b, fg = fg_b, command = self.exit_root, font=(font_all_1, 14, font_all_3)).grid(row=0, column=5, padx=30, pady=10)
# show_manage_frame = Button(self.Detail_Frame, text = "100", width=15, pady = 5, padx = 10, bg = bg_frame_b, fg = fg_b, command = self.add_100, font=(font_all_1, 14, font_all_3)).grid(row=0, column=7, padx=30, pady=10)
# ComboBox for Table Frame*******************************************************************************************************************
self.change_Table_txt = StringVar()
self.combo_change_table = ttk.Combobox(self.Detail_Frame, textvariable=self.change_Table_txt, width=10,
font=("Times New Roman", 13, font_all_3), state='disabled')
# self.combo_change_table.bind("<<ComboboxSelected>>",
# self.Change_Table) #
self.combo_change_table['values'] = ("students", "users")
# self.combo_change_table.current(0)
self.combo_change_table.grid(row=0, column=6, pady=10, sticky="w")
# Table Frame*******************************************************************************************************************
self.Table_Frame = Frame(self.Detail_Frame, bd = 4, relief = RIDGE, bg = bg_frame)
self.Table_Frame.place(x = 10, y = 70, width = width_detail_frame * 0.98, height = height_detail_frame * 0.9)
self.scroll_x = Scrollbar(self.Table_Frame, orient = HORIZONTAL)
self.scroll_y = Scrollbar(self.Table_Frame, orient = VERTICAL)
self.Student_table = ttk.Treeview(self.Table_Frame,
columns=("roll", "name", "email", "gender", "contact", "dob", "address"),
xscrollcommand=self.scroll_x.set, yscrollcommand=self.scroll_y.set)
style = ttk.Style(self.root)
style.configure('Treeview', rowheight=40) # Высота каждой строки в таблице
self.scroll_x.pack(side=BOTTOM, fill=X)
self.scroll_y.pack(side=RIGHT, fill=Y)
self.scroll_x.config(command=self.Student_table.xview)
self.scroll_y.config(command=self.Student_table.yview)
self.Student_table.heading("roll", text="No.")
self.Student_table.heading("name", text="Имя")
self.Student_table.heading("email", text="Email")
self.Student_table.heading("gender", text="Пол")
self.Student_table.heading("contact", text="Контакты")
self.Student_table.heading("dob", text="Дата рождения")
self.Student_table.heading("address", text="Адрес")
self.Student_table.column("roll", width=20)
self.Student_table.column("name", width=120)
self.Student_table.column("email", width=130)
self.Student_table.column("gender", width=50)
self.Student_table.column("contact", width=100)
self.Student_table.column("dob", width=100)
self.Student_table.column("address", width=180)
self.Student_table['show'] = 'headings'
self.Student_table.pack(fill=BOTH, expand=1)
# self.Student_table.bind("<Double-Button-1>", self.get_cursor)
# checker_ButtonRelease_txt = partial(self.checker_ButtonRelease)
self.Student_table.bind("<ButtonRelease-1>", self.checker_ButtonRelease)
self.fetch_data()
def get_roll_no_identity(self):
connect = psycopg2.connect(dbname="stm", user="postgres", password="askarova180774", host="localhost")
cur = connect.cursor()
cur.execute("select roll_no from students order by roll_no")
rows = cur.fetchall()
j = 1
for i in range(0,1500):
removed1 = str(rows[i]).replace("(", "")
removed2 = str(removed1).replace(",", "")
removed3 = str(removed2).replace(")", "")
if int(removed3) == j:
j += 1
else:
# print("i" + str(i))
# print("removed3" + removed3)
# print("j" + str(j))
request = int(removed3) - 1
return request
print(i)
connect.commit()
connect.close()
# for i in range(124,1000):
# cur.execute("insert into students values(%s,%s,%s,%s,%s,%s,%s)", (i,
# "test",
# "test@gmail.com",
# "",
# "87082414522",
# "24-07-1999",
# "Aqtobe"
# ))
# connect.commit()
#checker для bind чтобы сделать кнопки обновить и удалить активными*********************************************************************************************************************
def checker_ButtonRelease(self, event):
if self.Student_table.focus() != "":
self.show_manage_frame()
self.UpdateButton_main.config(state = NORMAL)
self.DeleteButton_main.config(state = NORMAL)
#Показ панели управления*********************************************************************************************************************
def show_manage_frame(self, Check = ""):
self.UpdateButton_main.config(state=DISABLED)
self.DeleteButton_main.config(state=DISABLED)
if Check == "add": #Если нажать кнопку для добавления тогда идет этот вариант
if self.Manage_mini_Frame.place_info() == {}: #Если бланк для добавления скрыт, то показать его и показать кнопку добавить
self.Add_frame.place_forget()
self.clear()
self.Manage_mini_Frame.place(y=65, width=self.width_manage_frame - 10, height=self.height_manage_frame - 100)
self.AddButton.grid(row=8, columnspan=2, padx=40, pady=15)
self.Back_Button.grid(row=9, column=0, padx=0, pady=10)
self.DeleteButton.grid_forget()
else: # Скрыть бланк для добавления и показать выборку для добавлений(Студент, Учитель, ..)
self.Manage_mini_Frame.place_forget()
self.Add_frame.place(y=70, width=self.width_manage_frame - 8, height=self.height_manage_frame / 4)
self.AddButton.grid_forget()
self.DeleteButton.grid_forget()
self.Back_Button.grid_forget()
elif Check == "update": #Если нажать кнопку для обновления тогда идет этот вариант
if self.Manage_mini_Frame.place_info() == {}: #Если бланк для обновления скрыт, то показать его и показать кнопку обновить, удалить
self.Add_frame.place_forget()
self.Manage_mini_Frame.place(y=65, width=self.width_manage_frame - 10, height=self.height_manage_frame - 100)
self.UpdateButton.grid(row=8, columnspan=2, padx=40, pady=15)
self.DeleteButton.grid(row=9, columnspan=2, padx=40, pady=15)
self.Back_Button.grid(row=10, column=0, padx=0, pady=10)
else: # Скрыть бланк для обновления и удаления и показать выборку для добавлений(Студент, Учитель, ..)
self.Manage_mini_Frame.place_forget()
self.Add_frame.place(y=70, width=self.width_manage_frame - 8, height=self.height_manage_frame / 4)
self.UpdateButton.grid_forget()
self.DeleteButton.grid_forget()
self.Back_Button.grid_forget()
else: # Скрыть бланки и показать выборку для добавлений(Студент, Учитель, ..)
self.Manage_mini_Frame.place_forget()
self.Add_frame.place(y=70, width=self.width_manage_frame - 8, height=self.height_manage_frame / 4)
self.AddButton.grid_forget()
self.UpdateButton.grid_forget()
self.Back_Button.grid_forget()
# gender bind -------------------------------------------------------------------------------------------------------------------------------
def TextBoxUpdate(self, event):
self.UpdateButton_main.config(state=DISABLED)
self.DeleteButton_main.config(state=DISABLED)
if self.search_by.get() == "gender":
self.txt_Search.grid_remove()
self.combo_gender.grid()
else:
self.combo_gender.grid_remove()
self.txt_Search.grid()
# function for buttons -------------------------------------------------------------------------------------------------------------------------------
def exit_root(self):
self.root.destroy()
# Connect to db -------------------------------------------------------------------------------------------------------------------------------
def add_students(self):
self.UpdateButton_main.config(state=DISABLED)
self.DeleteButton_main.config(state=DISABLED)
if self.email_var.get() == "" or self.name_var.get() == "":
messagebox.showerror("Error", "All fields are required!!!")
else:
connect = psycopg2.connect(dbname="stm", user="postgres", password="askarova180774", host="localhost")
cur = connect.cursor()
roll_no = self.get_roll_no_identity()
print(roll_no)
removed = self.txt_Address.get('1.0', END).replace("\n", "")
cur.execute("insert into students values(%s,%s,%s,%s,%s,%s,%s)", (roll_no,
self.name_var.get(),
self.email_var.get(),
self.gender_var.get(),
self.contact_var.get(),
self.dob_var.get(),
removed
))
connect.commit()
self.fetch_data()
self.clear()
connect.close()
self.show_manage_frame()
messagebox.showinfo("Success", "Данные были успешно записаны под номером " + str(roll_no))
# Show data on table from db-------------------------------------------------------------------------------------------------------------------------------
def fetch_data(self):
self.UpdateButton_main.config(state=DISABLED)
self.DeleteButton_main.config(state=DISABLED)
self.txt_Search.delete(0, END)
self.combo_Search.set("")
connect = psycopg2.connect(dbname="stm", user="postgres", password="askarova180774", host="localhost")
cur = connect.cursor()
cur.execute("select * from students ORDER BY roll_no ASC")
rows = cur.fetchall()
if len(rows) != 0:
self.Student_table.delete(*self.Student_table.get_children())
for row in rows:
self.Student_table.insert('', END, values=row)
connect.commit()
connect.close()
# Clear all entry for add students-------------------------------------------------------------------------------------------------------------------------------
def clear(self):
self.roll_No_var.set(""),
self.name_var.set(""),
self.email_var.set(""),
self.gender_var.set(""),
self.contact_var.set(""),
self.dob_var.set(""),
self.txt_Address.delete('1.0', END)
# get one row which you click then set on blank for add student-------------------------------------------------------------------------------------------------------------------------------
def get_cursor(self):
self.show_manage_frame("update")
curosor_row = self.Student_table.focus()
contents = self.Student_table.item(curosor_row)
row = contents['values']
removed = row[6].replace("\n", "")
self.roll_No_var.set(row[0]),
self.name_var.set(row[1]),
self.email_var.set(row[2]),
self.gender_var.set(row[3]),
self.contact_var.set(row[4]),
self.dob_var.set(row[5]),
self.txt_Address.delete('1.0', END)
self.txt_Address.insert(END, removed)
# Update data on db-------------------------------------------------------------------------------------------------------------------------------
def update_data(self):
# connect = self.link
option = messagebox.askyesno("Update", "Вы хотите обновить этот обьект?")
if option>0:
connect = psycopg2.connect(dbname="stm", user="postgres", password="askarova180774", host="localhost")
cur = connect.cursor()
cur.execute(
"update students set name=%s, email=%s, gender=%s, contact=%s, dob=%s, address=%s where roll_no=%s", (
self.name_var.get(),
self.email_var.get(),
self.gender_var.get(),
self.contact_var.get(),
self.dob_var.get(),
self.txt_Address.get('1.0', END),
self.roll_No_var.get()
))
self.show_manage_frame()
connect.commit()
self.fetch_data()
self.clear()
connect.close()
# Delete data from db-------------------------------------------------------------------------------------------------------------------------------
def delete_data(self):
option = messagebox.askyesno("Update", "Вы хотите удалить этот обьект?")
if option > 0:
try:
connect = psycopg2.connect(dbname="stm", user="postgres", password="askarova180774", host="localhost")
cur = connect.cursor()
print(self.roll_No_var.get())
cur.execute("delete from students where roll_no={}".format(self.roll_No_var.get()))
connect.commit()
connect.close()
self.fetch_data()
self.clear()
self.show_manage_frame()
except:
connect = psycopg2.connect(dbname="stm", user="postgres", password="askarova180774", host="localhost")
cur = connect.cursor()
curosor_row = self.Student_table.focus()
contents = self.Student_table.item(curosor_row)
row = contents['values']
# print(row[0])
cur.execute("delete from students where roll_no={}".format(row[0]))
connect.commit()
connect.close()
self.fetch_data()
self.clear()
self.show_manage_frame()
# Search data by key-------------------------------------------------------------------------------------------------------------------------------
def search_data(self):
# connect = self.link
self.UpdateButton_main.config(state=DISABLED)
self.DeleteButton_main.config(state=DISABLED)
connect = psycopg2.connect(dbname="stm", user="postgres", password="askarova180774", host="localhost")
cur = connect.cursor()
if self.search_by.get() == "roll_no":
cur.execute("select * from students where " + str(
self.search_by.get() + "=" + self.search_txt.get()))
else:
# cur.execute("select * from students where " + str(
# self.search_by.get() + " LIKE '%" + str(self.search_txt.get()) + "%'"))
cur.execute("SELECT * FROM students WHERE LOWER( students."
+ self.search_by.get() + ") LIKE '%" + str(self.search_txt.get().lower()) + "%' ORDER BY roll_no ASC")
rows = cur.fetchall()
if len(rows) != 0:
self.Student_table.delete(*self.Student_table.get_children())
for row in rows:
self.Student_table.insert('', END, values=row)
connect.commit()
connect.close()
# -------------------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------------------------------
root = Tk()
ob = Student(root)
root.mainloop() |
Java | UTF-8 | 2,265 | 1.703125 | 2 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* $Header:
* /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/contrib/org/apache/commons/httpclient/contrib/ssl/AuthSSLInitializationError.java,v
* 1.2 2004/06/10 18:25:24 olegk Exp $ $Revision: 155418 $ $Date: 2005-02-26 08:01:52 -0500 (Sat, 26
* Feb 2005) $
*
* ====================================================================
*
* Copyright 1999-2004 The Apache Software Foundation
*
* 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 distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License. ====================================================================
*
* This software consists of voluntary contributions made by many individuals on behalf of the Apache
* Software Foundation. For more information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package com.cordys.coe.util.cgc.ssl;
/**
* <p>Signals fatal error in initialization of {@link AuthSSLProtocolSocketFactory}.</p>
*
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
*
* <p>DISCLAIMER: HttpClient developers DO NOT actively support this component. The
* component is provided as a reference material, which may be inappropriate for use
* without additional customization.</p>
*/
public class AuthSSLInitializationError extends Error
{
/**
* Creates a new AuthSSLInitializationError.
*/
public AuthSSLInitializationError()
{
super();
}
/**
* Creates a new AuthSSLInitializationError with the specified message.
*
* @param message error message
*/
public AuthSSLInitializationError(String message)
{
super(message);
}
}
|
Java | UTF-8 | 6,529 | 2.203125 | 2 | [] | no_license | package com.ias.webide.server.rest;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.text.StyledEditorKit.BoldAction;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.reflect.TypeToken;
import com.ias.webide.java.db.mysql.MySQLDAO;
import com.ias.webide.java.db.mysql.MySQLDriver;
@Path("/db")
public class MysqlDBControllerService {
MySQLDAO mySQLDAO;
JsonObject outObj;
public MysqlDBControllerService() {
mySQLDAO = new MySQLDAO(new MySQLDriver());
outObj = new JsonObject();
}
@POST
@Path("getDbs")
public Response getDbs() {
MySQLDAO mySQLDAO = new MySQLDAO(new MySQLDriver());
JsonObject outObj = new JsonObject();
try {
JsonArray dbs = mySQLDAO.getDatabasesAsJSON();
for (int i = 0; i < dbs.size(); i++) {
JsonObject jsonDb = (JsonObject) dbs.get(i);
JsonArray tables = mySQLDAO.getTablesAsJson(jsonDb.get("name").getAsString());
jsonDb.add("tables", tables);
}
outObj.add("dbs", dbs);
String out = outObj.toString();
return Response.status(RestServiceUtil.STATUS_OK).entity(out).build();
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return getAlertMessage(e, outObj, RestServiceUtil.JSON_ERROR_PROPERTY);
}
}
@POST
@Path("getTableMetaData")
public Response getTableMetaData(@QueryParam("db") String db, @QueryParam("table") String table) {
JsonArray dbs;
try {
dbs = mySQLDAO.getTableMetaDataAsJson(db, table);
outObj.add("tableMeta", dbs);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return getAlertMessage(e, outObj, RestServiceUtil.JSON_ERROR_PROPERTY);
}
String out = outObj.toString();
return Response.status(RestServiceUtil.STATUS_OK).entity(out).build();
}
@POST
@Path("getTableData")
public Response getTableData(@QueryParam("db") String db, @QueryParam("table") String table) {
try {
JsonArray dbs = mySQLDAO.getTableDataAsJson(db, table);
outObj.add("tableData", dbs);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return getAlertMessage(e, outObj, RestServiceUtil.JSON_ERROR_PROPERTY);
}
String out = outObj.toString();
return Response.status(RestServiceUtil.STATUS_OK).entity(out).build();
}
@POST
@Path("addNewDB")
public Response addNewDB(@QueryParam("db") String db) {
try {
int rs = mySQLDAO.createNewDB(db);
JsonArray dbs = mySQLDAO.getDatabasesAsJSON();
for (int i = 0; i < dbs.size(); i++) {
JsonObject jsonDb = (JsonObject) dbs.get(i);
JsonArray tables = mySQLDAO.getTablesAsJson(jsonDb.get("name").getAsString());
}
outObj.add("dbs", dbs);
outObj.add("rs", new JsonPrimitive(rs));
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return getAlertMessage(e, outObj, RestServiceUtil.JSON_ERROR_PROPERTY);
}
String out = outObj.toString();
return Response.status(RestServiceUtil.STATUS_OK).entity(out).build();
}
@POST
@Path("deleteDB")
public Response deleteDB(@QueryParam("names") String names) {
boolean error = false;
Gson gson = new Gson();
ArrayList<String> dbNames = gson.fromJson(names, new TypeToken<ArrayList<String>>() {
}.getType());
for (String dbName : dbNames) {
try {
mySQLDAO.deleteDB(dbName);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
error = true;
e.printStackTrace();
outObj = addAlertMessage(e, outObj, RestServiceUtil.JSON_ERROR_PROPERTY);
}
}
if (error) {
return Response.status(RestServiceUtil.STATUS_BAD_REQUEST).entity(outObj.toString()).build();
}
String out = outObj.toString();
return Response.status(RestServiceUtil.STATUS_OK).entity(out).build();
}
@POST
@Path("addNewTable")
public Response addNewTable(@QueryParam("table") String table) {
JsonParser parser = new JsonParser();
JsonObject tableEl = (JsonObject) parser.parse(table);
JsonArray cols = tableEl.get("cols").getAsJsonArray();
try {
boolean rs = mySQLDAO.createNewTable(tableEl, cols);
// JsonArray dbs = mySQLDAO.getDatabasesAsJSON();
// for (int i = 0; i < dbs.size(); i++) {
// JsonObject jsonDb = (JsonObject) dbs.get(i);
// JsonArray tables =
// mySQLDAO.getTablesAsJson(jsonDb.get("name").getAsString());
// }
// outObj.add("dbs", dbs);
// outObj.add("rs", new JsonPrimitive(rs));
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return getAlertMessage(e, outObj, RestServiceUtil.JSON_ERROR_PROPERTY);
}
String out = outObj.toString();
return Response.status(RestServiceUtil.STATUS_OK).entity(out).build();
}
private Response getAlertMessage(Exception e, JsonObject outObj, String alertID) {
outObj = addAlertMessage(e, outObj, RestServiceUtil.JSON_ERROR_PROPERTY);
return Response.status(RestServiceUtil.STATUS_BAD_REQUEST).entity(outObj.toString()).build();
}
private JsonObject addAlertMessage(Exception e, JsonObject outObj, String type) {
if (!outObj.has(RestServiceUtil.JSON_ALERTS_PROPERTY)) {
outObj.add(RestServiceUtil.JSON_ALERTS_PROPERTY, new JsonArray());
}
JsonArray alerts = outObj.get(RestServiceUtil.JSON_ALERTS_PROPERTY).getAsJsonArray();
JsonObject alert = new JsonObject();
alert.add(RestServiceUtil.JSON_TYPE_PROPERTY, new JsonPrimitive(type));
alert.add(RestServiceUtil.JSON_ALERTS_PROPERTY, new JsonPrimitive(e.getMessage()));
alerts.add(alert);
outObj.add(RestServiceUtil.JSON_ALERTS_PROPERTY, alerts);
return outObj;
}
// @Path("smooth")
// @GET
// public Response smooth(@DefaultValue("2") @QueryParam("step") int step,
// @DefaultValue("true") @QueryParam("min-m") boolean hasMin,
// @DefaultValue("true") @QueryParam("max-m") boolean hasMax,
// @DefaultValue("true") @QueryParam("last-m") boolean hasLast) {
// return null;
// }
// @GET
// @Path("/{param}")
// public Response getMsg(@PathParam("param") String msg) {
//
// String output = "Jersey say : " + msg;
//
// return Response.status(RestServiceUtil.STATUS_OK).entity(output).build();
//
// }
} |
Python | UTF-8 | 2,646 | 3.328125 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import csv
import os
#Plan:
# 1. We need to define function to get html request
# 2. Need to find out the number of pages
# 3. We need to define function to get content of the page
# 4. parse
# URL = 'https://kolesa.kz/cars/mercedes-benz/almaty/'
HEADERS = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36', 'accept': '*/*'}
FILE = 'kolesa_cars.csv'
HOST = 'https://kolesa.kz'
def get_html(url, params = None):
r = requests.get(url, headers = HEADERS, params = params)
return r
def get_number_of_pages(html):
soup = BeautifulSoup(html, 'lxml')
try:
page_count = soup.find('div', class_='pager').find('ul').find_all('span')
if page_count:
return int(page_count[-1].get_text())
else:
return 1
except:
return 1
def get_content(html):
soup = BeautifulSoup(html, 'lxml')
content = soup.find_all('div', class_='a-info-side')
# print(len(content))
cars = []
for item in content:
car_price = item.find('span', class_='price')
if car_price:
car_price = car_price.get_text(strip=True).replace('\xa0','').replace('₸','')
cars.append({
'title': item.find('span', class_='a-el-info-title').get_text(strip=True),
'date': item.find('span', class_='date').get_text(),
'price': car_price,
'description': item.find('div', class_='a-search-description').get_text(strip=True),
'city': item.find('div', class_='list-region').get_text(strip=True),
'link': HOST + item.find('a').get('href')
})
return cars
def save_file(items, path):
with open(path, 'w', newline='') as file:
writer = csv.writer(file, delimiter=';')
writer.writerow(['Марка', 'Дата публикации', 'Цена, тенге', 'Краткое описание', 'Город', 'Ссылка',])
for item in items:
writer.writerow([item['title'],item['date'],item['price'],item['description'],item['city'],item['link']])
def main():
URL = input('Введите ссылку для парсинга: ')
URL = URL.strip()
html = get_html(URL)
if html.status_code == 200:
cars = []
pages_total = get_number_of_pages(html.text)
for page in range(1, pages_total+1):
print(f'Парсинг страницы {page} из {pages_total}...')
html = get_html(URL, params={'page': page}) #receiving content
cars.extend(get_content(html.text)) # parsing the received current page and including to cars list
save_file(cars, FILE)
print(f'Всего {len(cars)} автомобилей')
os.startfile(FILE)
else:
print("Error occured")
if __name__=="__main__":
main() |
Swift | UTF-8 | 3,657 | 2.796875 | 3 | [
"MIT"
] | permissive | //
// Iex.swift
// stocks
//
// Created by Daniel on 5/29/20.
// Copyright © 2020 dk. All rights reserved.
//
import Foundation
// TODO: support https://sandbox.iexapis.com/stable/stock/market/batch?symbols=aapl&types=company,balance-sheet&token=Tsk_309349a480bc4f4e922f63c57b69e3de
struct Iex {
struct Company: Codable {
var companyName: String
var exchange: String
var website: URL
var description: String
var CEO: String
var sector: String
var employees: Int
var address: String
var address2: String?
var state: String?
var city: String
var country: String
}
struct Quote: Codable {
var close: Double
var previousClose: Double
}
struct Symbol: Codable {
var name: String
var symbol: String
}
}
extension Iex {
static func getDetail(_ symbol: String?, completion: @escaping (Company?) -> Void) {
guard let symbol = symbol else {
completion(nil)
return
}
let url = Iex.companyUrl(symbol)
url?.get { (company: Company?) in
completion(company)
}
}
static func getQuote(_ symbol: String, completion: @escaping (MyQuote?) -> Void) {
let url = Iex.quoteUrl(symbol)
url?.get { (quote: Iex.Quote?) in
completion(quote?.quote)
}
}
static func getSearchResults(_ query: String, completion: @escaping ([Symbol]?) -> Void) {
let url = Iex.symbolsUrl
url?.get { (results: [Symbol]?) in
let lower = query.lowercased()
let filtered = results?.compactMap { $0 }.filter {
$0.name.lowercased().contains(lower) || $0.symbol.lowercased().contains(lower) }
completion(filtered)
}
}
}
extension Iex.Quote {
var quote: MyQuote {
return MyQuote(price: close, change: close - previousClose)
}
}
private extension Iex {
static let env: Environment = .sandbox
static var baseUrlComponents: URLComponents {
var c = URLComponents()
c.scheme = "https"
c.host = env.host
return c
}
static func companyUrl(_ symbol: String) -> URL? {
var c = baseUrlComponents
c.path = "\(env.pathPrefix)/stock/\(symbol)/company"
c.queryItems = [ tokenQueryItem ]
let u = c.url
return u
}
static func quoteUrl(_ symbol: String) -> URL? {
var c = baseUrlComponents
c.path = "\(env.pathPrefix)/stock/\(symbol)/quote"
c.queryItems = [ tokenQueryItem ]
let u = c.url
return u
}
static var symbolsUrl: URL? {
var c = baseUrlComponents
c.path = "\(env.pathPrefix)/ref-data/symbols"
c.queryItems = [ tokenQueryItem ]
let u = c.url
return u
}
static var tokenQueryItem: URLQueryItem {
let queryItem = URLQueryItem(name: "token", value: env.apiKey)
return queryItem
}
}
private enum Environment {
case sandbox, production
var apiKey: String {
switch self {
case .sandbox:
return "GET API KEY"
case .production:
return "GET API KEY"
}
}
var host: String {
switch self {
case .sandbox:
return "sandbox.iexapis.com"
case .production:
return "cloud.iexapis.com"
}
}
var pathPrefix: String {
switch self {
case .sandbox:
return "/stable"
case .production:
return "/v1"
}
}
}
|
Java | UTF-8 | 431 | 2.28125 | 2 | [
"BSD-3-Clause"
] | permissive | package org.micromanager.events.internal;
import org.micromanager.events.ChannelGroupChangedEvent;
public class DefaultChannelGroupChangedEvent implements ChannelGroupChangedEvent {
private final String channelGroup_;
public DefaultChannelGroupChangedEvent(final String newChannelGroup) {
channelGroup_ = newChannelGroup;
}
@Override
public String getNewChannelGroup() {
return channelGroup_;
}
}
|
JavaScript | UTF-8 | 2,070 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | $(document).ready(function () {
$(window).on('load',function () {
var dataImg={
'data':[
{"src":'1.jpg'},
{"src":'2.jpg'},
{"src":'3.png'},
{"src":'4.jpg'},
{"src":'5.jpg'},
{"src":'6.jpg'},
{"src":'7.jpg'},
{"src":'8.jpg'},
{"src":'9.jpg'},
{"src":'10.jpg'},
{"src":'11.jpg'},
{"src":'12.jpg'},
{"src":'13.jpg'},
{"src":'14.jpg'},
{"src":'15.jpg'}
]
}
var conWidth=$(window).width();
imgLocation(conWidth);
$(window).on('scroll',function () {
if(scrollside()){
$.each(dataImg.data,function (index,value) {
var box=$('<div>').addClass('box').appendTo($('#container'));
var content=$('<div>').addClass('content').appendTo(box);
$('<img>').attr('src',"./images/"+$(value).attr("src")).appendTo(content);
});
imgLocation(conWidth);
}
})
})
});
//窗口大小发生改变时,图片重新排列,实现响应式布局。。。。。。。。问题:当窗口缩小后在放大时图片不能正常排列
$(window).resize(function () {
var conWidth1=$(window).width();
imgLocation(conWidth1);
})
//判断是否加载
function scrollside() {
var box=$('.box');
var lastboxHeight=box.last().get(0).offsetTop+Math.floor(box.last().height()/2);
var documentHeight=$(window).height();
var scrollHeight=$(window).scrollTop();
return (lastboxHeight<documentHeight+scrollHeight)?true:false;
}
//对图片进行布局
function imgLocation(conWidth) {
var box=$('.box');
var boxWidth=box.eq(0).width();
var num=Math.floor(conWidth/boxWidth);
var boxArr=[];
box.each(function (index,value) {
var boxHeight=box.eq(index).height();
if(index<num){
boxArr[index]=boxHeight;
$(value).css({
'position':'absolute',
'top':0,
'left':index*boxWidth
})
}else{
var minboxHeight=Math.min.apply(null,boxArr);
var minboxIndex=$.inArray(minboxHeight,boxArr);
$(value).css({
'position':'absolute',
'top':minboxHeight,
'left':box.eq(minboxIndex).position().left
})
boxArr[minboxIndex]+=box.eq(index).height();
}
});
} |
Java | UTF-8 | 1,632 | 2.328125 | 2 | [] | no_license | package sa.store.model;
import javax.persistence.*;
@Entity
@Table(name = "stores")
@NamedQueries({@NamedQuery(name = Store.FIND_ALL, query = "SELECT u FROM Store u")})
public class Store {
public static final String FIND_ALL = "Store.findAll";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int code;
private String name;
private String description;
private String type;
private String owner;
private String ubication;
private String dates;
private String img;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getUbication() {
return ubication;
}
public void setUbication(String ubication) {
this.ubication = ubication;
}
public String getDates() {
return dates;
}
public void setDates(String dates) {
this.dates = dates;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
} |
C++ | UTF-8 | 3,198 | 2.59375 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <texture.h>
#include <cmath>
#include <glm.hpp>
using namespace std;
Texture::Texture(int type, int w, int h)
{
textureType = type;
width = w;
height = h;
data = new float[width*height*4];
for (int i = 0;i<width*height*4;i++)
data[i] = i%4<4?0:1;
glGenTextures(1,&textureNumber);
glActiveTexture(textureType);
glBindTexture(GL_TEXTURE_2D,textureNumber);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
}
void Texture::toTGA(const char* file)
{
FILE* fp = fopen(file,"wb");
putc(0,fp);
putc(0,fp);
putc(2,fp); /* uncompressed RGB */
putc(0,fp); putc(0,fp);
putc(0,fp); putc(0,fp);
putc(0,fp);
putc(0,fp); putc(0,fp); /* X origin */
putc(0,fp); putc(0,fp); /* y origin */
putc((width & 0x00FF),fp);
putc((width & 0xFF00) / 256,fp);
putc((height & 0x00FF),fp);
putc((height & 0xFF00) / 256,fp);
putc(32,fp); /* 24 bit bitmap */
putc(0,fp);
for (int i = 0;i<width;i++)
for (int j = 0;j<height;j++)
{
float f = abs(data[(i*height+j)*4+0]);
if (f<0)f=-f;
unsigned char c = (abs(data[(i*height+j)*4+0])*255);
putc((unsigned char)(abs(data[(i*height+j)*4+0]*255)),fp);
putc((unsigned char)(abs(data[(i*height+j)*4+1]*255)),fp);
putc((unsigned char)(abs(data[(i*height+j)*4+2]*255)),fp);
putc((unsigned char)(abs(data[(i*height+j)*4+3]*255)),fp);
}
fclose(fp);
}
void Texture::loadData(float* inData)
{
memcpy(data,inData,width*height*4*sizeof(float));
glActiveTexture(textureType);
glBindTexture(GL_TEXTURE_2D,textureNumber);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, data);
}
void Texture::loadBumpData(float* inData)
{
for (int i=0;i<width*height;i++)
{
glm::vec3 no = glm::vec3(1.f);
if ((i%width)>0 && (i/width>0) && (i%width<width-1) && (i/width<height-1))
{
float a,b,c,d,m;
a = inData[i-width];
b = inData[i+1];
c = inData[i+width];
d = inData[i-1];
m = inData[i];
no = -glm::cross(glm::vec3(0.f,a-m,-1.f/height),glm::vec3(1.f/width,b-m,0.f))
-glm::cross(glm::vec3(1.f/width,b-m,0.f),glm::vec3(0.f,c-m,1.f/height))
-glm::cross(glm::vec3(0.f,c-m,1.f/height),glm::vec3(-1.f/width,d-m,0.f))
-glm::cross(glm::vec3(-1.f/width,d-m,0.f),glm::vec3(0.f,a-m,-1.f/height));
}
no = glm::normalize(no);
data[i*4 ] = no.x;
data[i*4+1] = no.y;
data[i*4+2] = no.z;
data[i*4+3] = inData[i];
}
glActiveTexture(textureType);
glBindTexture(GL_TEXTURE_2D,textureNumber);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, data);
}
void Texture::load()
{
glActiveTexture(textureType);
glBindTexture(GL_TEXTURE_2D,textureNumber);
}
#ifdef TEST_TEXTURE
int main()
{
Texture texture(HEIGHTMAP_TEXTURE,8,8);
texture.toTGA("test.tga");
}
#endif
|
Java | UTF-8 | 3,229 | 1.804688 | 2 | [] | no_license | package com.airbnb.android.cohosting.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import butterknife.BindView;
import butterknife.OnClick;
import com.airbnb.android.cohosting.C5658R;
import com.airbnb.android.cohosting.CohostingGraph;
import com.airbnb.android.cohosting.utils.CohostingLoggingUtil;
import com.airbnb.android.core.CoreApplication;
import com.airbnb.android.core.analytics.CohostingManagementJitneyLogger;
import com.airbnb.android.core.fragments.AirFragment;
import com.airbnb.android.core.intents.CohostingIntents;
import com.airbnb.android.core.interfaces.OnBackListener;
import com.airbnb.android.core.models.Listing;
import com.airbnb.android.core.models.ListingManager;
import com.airbnb.android.utils.FragmentBundler;
import com.airbnb.android.utils.FragmentBundler.FragmentBundleBuilder;
import com.airbnb.jitney.event.logging.CohostingSourceFlow.p068v1.C1958CohostingSourceFlow;
import com.airbnb.p027n2.components.SheetMarquee;
import icepick.State;
import java.util.ArrayList;
public class CohostingInviteFriendConfirmationFragment extends AirFragment implements OnBackListener {
public static final String ARG_EMAIL = "email";
@State
Listing listing;
@State
ArrayList<ListingManager> listingManagers;
CohostingManagementJitneyLogger logger;
@BindView
SheetMarquee marquee;
public static CohostingInviteFriendConfirmationFragment newInstance(String email, Listing listing2, ArrayList<ListingManager> listingManagers2) {
return (CohostingInviteFriendConfirmationFragment) ((FragmentBundleBuilder) ((FragmentBundleBuilder) ((FragmentBundleBuilder) FragmentBundler.make(new CohostingInviteFriendConfirmationFragment()).putString("email", email)).putParcelable("listing", listing2)).putParcelableArrayList(CohostingIntents.INTENT_EXTRA_LISTING_MANAGERS, listingManagers2)).build();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
((CohostingGraph) CoreApplication.instance().component()).inject(this);
View view = inflater.inflate(C5658R.layout.fragment_cohosting_invite_friend_confirmation, container, false);
bindViews(view);
this.listing = (Listing) getArguments().getParcelable("listing");
this.listingManagers = getArguments().getParcelableArrayList(CohostingIntents.INTENT_EXTRA_LISTING_MANAGERS);
this.logger.logInviteFriendConfirmationImpression(CohostingLoggingUtil.getCohostingContext(this.listing, this.listingManagers), C1958CohostingSourceFlow.PostListYourSpace);
this.marquee.setSubtitle(getString(C5658R.string.cohosting_invite_friend_confirmation_explanation, getArguments().getString("email")));
getAirActivity().setOnBackPressedListener(this);
return view;
}
@OnClick
public void onClickOkay() {
this.logger.logInviteFriendConfirmationClick(CohostingLoggingUtil.getCohostingContext(this.listing, this.listingManagers), C1958CohostingSourceFlow.PostListYourSpace);
getActivity().finish();
}
public boolean onBackPressed() {
getActivity().finish();
return true;
}
}
|
Python | UTF-8 | 2,586 | 3.921875 | 4 | [] | no_license | ### SKU CoE ITE - ParkSooYoung ###
### Grade 1.5 , Semester 2.5 , Chapter 10 , Number 5 ###
'''
Quiz) 동네에 항상 대기 손님이 있는 맛있는 치킨집이 있습니다.
대기 손님의 치킨 요리 시간을 줄이고자 자동 주문 시스템을 제작하였습니다.
시스템 코드를 확인하고 적절한 예외처리 구문을 넣으시오.
조건1 : 1보다 작거나 숫자가 아닌 입력값이 들어올 때는 ValueError로 처리
출력 메시지 : "잘못된 값을 입력하였습니다."
조건2 : 대기 손님이 주문할 수 있는 총 치킨량은 10마리로 한정
치킨 소진 시 사용자 정의 에러[SoldOutError]를 발생시키고 프로그램 종료
출력 메시지 : "재고가 소진되어 더 이상 주문을 받지 않습니다."
[코드]
chicken = 10
waiting = 1 # 홀 안에는 현재 만석. 대기번호 1부터 시작
while(True):
print("[남은 치킨 : {0}]".format(chicken))
order = int(input("치킨 몇 마리 주문하시겠습니까?"))
if order > chicken: # 남은 치킨보다 주문량이 많을때
print("재료가 부족합니다.")
else:
print("[대기번호 {0}] {1} 마리 주문이 완료되었습니다.".format(waiting, order))
wating += 1
chicken -= order
'''
class SoldOutError(Exception):
# def __init__(self, msg): # - my answer
# self.msg = msg # - my answer
# def __str__(self): # - my answer
# return self.msg # - my answer
pass
chicken = 10
waiting = 1 # 홀 안에는 현재 만석. 대기번호 1부터 시작
# try: # - my answer
while(True):
try: # this is answer
print("[남은 치킨 : {0}]".format(chicken))
order = int(input("치킨 몇 마리 주문하시겠습니까? : "))
if order > chicken: # 남은 치킨보다 주문량이 많을때
print("재료가 부족합니다.")
elif order < 1 or order == str: # elif order <= 0:
raise ValueError
else:
print("[대기번호 {0}] {1} 마리 주문이 완료되었습니다.".format(waiting, order))
waiting += 1
chicken -= order
if chicken == 0:
raise SoldOutError
except ValueError:
print("잘못된 값을 입력하였습니다.")
except SoldOutError:
print("재고가 소진되어 더 이상 주문을 받지 않습니다.")
break
|
Java | UTF-8 | 2,453 | 2.171875 | 2 | [] | no_license | package com.b13.orderservice.controller;
import java.net.URISyntaxException;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.b13.orderservice.dto.NewOrder;
import com.b13.orderservice.dto.Order;
import com.b13.orderservice.dto.StringResponse;
import com.b13.orderservice.dto.cart.Cart;
import com.b13.orderservice.exception.OrderIdNotFoundException;
import com.b13.orderservice.service.OrderService;
import lombok.AllArgsConstructor;
@RestController
@RequestMapping("/orders")
@AllArgsConstructor
public class OrderController {
final OrderService orderService;
@GetMapping("/{id}")
public Optional<Order> retrieveOrderById(@PathVariable("id") long id){
return orderService.getOrderById(id);
}
@PostMapping
@ResponseStatus(HttpStatus.OK)
public Order SubmitNewOrder(@RequestBody Cart cart) {
return orderService.insertNewOrder(cart);
}
@PutMapping("/{id}/shipment")
public ResponseEntity<Order> updateShippingInformation(@PathVariable("id") long id, @RequestBody String shipping) {
return ResponseEntity.of(orderService.updateShipment(shipping, id));
}
@PutMapping("/{id}/payment")
public ResponseEntity<?> updatePayment(@PathVariable("id") long id, @RequestBody String payment) {
return ResponseEntity.of(orderService.updatePayment(id, payment));
}
@PutMapping("/{id}/final")
public ResponseEntity<?> settleOrder(@PathVariable("id") long id) {
Optional<Order> order = orderService.settle(id);
return ResponseEntity.accepted().body(order.get());
}
@ExceptionHandler(OrderIdNotFoundException.class)
public ResponseEntity<StringResponse> idNotFoundHandler(){
return ResponseEntity.notFound().build();
}
}
|
JavaScript | UTF-8 | 1,635 | 2.546875 | 3 | [] | no_license | const catchify = p => p.then(d => ([ , d ])).catch(e => ([ e ]))
export const createRequester = ({ hostname, appId, apiKey, fetcher, now = Date.now, sdkVersion = '1.3.0', maxRetries = 2 }) => {
let baseUrl, accessToken, refreshToken, tokenCreateTime
const logIn = async () => {
const response = await fetcher(`${baseUrl}/auth/providers/api-key/login`, {
method: 'POST',
body: {
key: apiKey,
options: {
device: { appId, sdkVersion },
},
}
})
const data = await response.json()
accessToken = data.access_token
refreshToken = data.refresh_token
tokenCreateTime = now()
}
const query = async (string, retryCount = 0) => {
if (retryCount >= maxRetries) throw new Error('Maximum retries reached when attempting to make a query with an authentication error.')
const [ error, response ] = await catchify(fetcher(`${baseUrl}/graphql`, {
method: 'POST',
headers: {
authorization: `Bearer ${accessToken}`
},
body: { query: string }
}))
if (error && error.statusCode === 401) {
// TODO use the refresh token instead of straight up logging in again
await logIn()
return query(string, retryCount + 1)
}
return response.json()
}
return async (string) => {
if (!hostname) {
const response = await fetcher(`https://stitch.mongodb.com/api/client/v2.0/app/${appId}/location`)
hostname = (await response.json()).hostname
if (!hostname) throw new Error('Unexpected response body from MongoDB Stitch: could not locate hostname.')
baseUrl = `${hostname}/api/client/v2.0/app/${appId}`
}
if (!accessToken) {
await logIn()
}
return query(string)
}
}
|
JavaScript | UTF-8 | 2,566 | 2.546875 | 3 | [] | no_license | import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios';
import moment from 'moment';
import apiUrl from '@/config/api';
Vue.use(Vuex)
// 仿效 socket Server(未來導入從這個著手)
let socketTemporary;
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
export default new Vuex.Store({
state: {
currentFarmList: [],
currentAreaList: [
'Asia',
'America',
'Europe',
'Africa'
],
BWH: 10,
MaxWH: 25,
},
getters: {
getCurrentFarmList: state => state.currentFarmList,
getCurrentAreaList: state => state.currentAreaList,
getBWH: state => state.BWH,
getMaxWH: state => state.MaxWH,
},
mutations: {
setCurrentFarmList(state, val) {
state.currentFarmList = val;
},
setCurrentAreaList(state, val) {
state.currentAreaList = val;
},
},
actions: {
actionInit({ state, dispatch, commit }) {
axios.get(`${apiUrl}/farm_list`)
.then((response) => {
dispatch('actionSetCurrentFarmList', response.data);
});
socketTemporary = setInterval(() => {
let updateFarmList = state.currentFarmList;
updateFarmList = updateFarmList.map((farm) => {
if (farm.checked) {
return farm;
}
return {
...farm,
currentSize: farm.currentSize + farm.speed,
timeLeftToBWH: moment(((farm.size - farm.currentSize) / farm.speed) * 1000).format('h:mm:ss'),
waterHeight: (farm.currentSize / farm.size) * 100,
speed: getRandomInt(farm.speed - 1, farm. speed + 3),
};
});
commit('setCurrentFarmList', updateFarmList)
}, 1000);
},
actionSetCurrentFarmList({ commit }, val) {
commit('setCurrentFarmList', val.map((farm) => {
return {
...farm,
timeLeftToBWH: moment((farm.size / farm.speed) * 1000).format('h:mm:ss'),
};
}));
},
actionSetCurrentAreaList({ commit }, val) {
commit('setCurrentAreaList', val);
},
actionBreakTimeInterval() {
clearInterval(socketTemporary);
},
},
})
|
Ruby | UTF-8 | 2,912 | 2.75 | 3 | [
"MIT"
] | permissive | require_relative './argument_interceptor'
require_relative './invocation'
require 'set'
module Compact
class Contract
attr_reader :specs
def initialize
@collaborator_invocations = Set.new
@test_double_invocations = Set.new
end
def prepare_double(block = Proc.new)
double = block.call
interceptor = ArgumentInterceptor.new(double)
interceptor.register(self)
interceptor
end
def verified?
@test_double_invocations == @collaborator_invocations
end
def has_pending?
!pending_invocations.empty?
end
def has_untested?
!untested_invocations.empty?
end
def has_failing?
!failing_invocations.empty?
end
def describe_untested_specs
headline = "The following methods were invoked on test doubles without corresponding contract tests:"
messages = untested_invocations.map(&:describe)
print_banner_separated(headline, messages)
end
def describe_pending_specs
headline = "No test doubles mirror the following verified invocations:"
messages = pending_invocations.map(&:describe)
print_banner_separated(headline, messages)
end
def describe_failing_specs
headline = "Attempts to verify the following method invocations failed:"
messages = failing_invocations.map do |invocation|
bad_results = unspecified_invocations.select{|p| p.matches_call(invocation) }
invocation.describe.gsub("returns", "expected") +
"\nMatching invocations returned the following values: #{bad_results.map(&:returns).inspect}"
end
print_banner_separated(headline, messages)
end
def verify(collaborator, block = Proc.new)
interceptor = ArgumentInterceptor.new(collaborator)
block.call(interceptor)
interceptor.invocations.each{|inv| @collaborator_invocations.add(inv) }
end
def add_invocation(invocation)
@test_double_invocations.add(invocation)
end
private
def untested_invocations
uncorroborated_invocations - failing_invocations
end
def pending_invocations
unspecified_invocations.reject do |inv|
failing_invocations.any? {|failure| inv.matches_call(failure)}
end
end
def uncorroborated_invocations
(@test_double_invocations - @collaborator_invocations).to_a
end
def unspecified_invocations
(@collaborator_invocations - @test_double_invocations).to_a
end
def failing_invocations
uncorroborated_invocations.select do |spec|
unspecified_invocations.any?{|inv| inv.matches_call(spec)}
end
end
def print_banner_separated(headline, messages)
banner = "================================================================================"
<<~MSG
#{headline}
#{banner}
#{messages.join(banner).strip}
#{banner}
MSG
end
end
end |
Python | UTF-8 | 489 | 2.9375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 27 16:32:24 2019
@author: baneel
"""
import matplotlib.pyplot as plt
from skimage import io
from skimage.measure import find_contours
plt.ion()
plt.rcParams['image.cmap'] = 'gray'
### USER INPUT
im_name = 'path_to_image'
threshold = 120
### SCRIPT
im = io.imread(im_name)
# list of contours
contours = find_contours(im, threshold)
# plot
fig, ax = plt.subplots()
ax.imshow(im)
for c in contours:
row, col = c.T
ax.plot(col, row)
|
Python | UTF-8 | 281 | 4.1875 | 4 | [] | no_license | # Write a program that uses nested loops to draw this pattern:
# ##
# # #
# # #
# # #
# # #
# # #
for row in range(6):
print("#", end = "")
for col in range(row):
print(" ", end = "")
print("#")
|
Python | UTF-8 | 5,674 | 2.515625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
import datetime
import logging
import json
import os
import pymysql
import sys
import yaml
from typing import Any
from typing import Dict
from typing import Final
from typing import List
from typing import NoReturn
from typing import Union
from timo.database_manager.models import Database
QueryResult = Dict[str, Union[str, int, float]]
QueryResults = List[QueryResult]
LOG_PATH: Final[str] = os.path.dirname(__file__) + '/logs/mysql.log'
if os.path.isfile(LOG_PATH):
os.remove(LOG_PATH)
logging.basicConfig(
filename=LOG_PATH,
level=logging.INFO, filemode='w',
format='%(asctime)s:\n\t%(levelname)s:%(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p'
)
def _log_file_write(func):
def wrapper(*args, **kwargs):
path = func(*args, **kwargs)
logging.info(f'Save success as query execution result file (path: {path})')
return wrapper
class MySQL(Database):
"""MySQL Client"""
def __init__(self, config) -> None:
super(MySQL, self).__init__(config)
self.db = config.db
self.charset = config.charset
def __connect__(self) -> NoReturn:
try:
self.conn = pymysql.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
db=self.db,
charset=self.charset
)
self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)
except pymysql.MySQLError as e:
logging.error(e)
print(f"Error connecting to MySQL Platform: {e}")
sys.exit(1)
else:
logging.info('Database connection successful')
def __commit__(self) -> NoReturn:
try:
self.conn.commit()
except pymysql.MySQLError as e:
logging.error(e)
sys.exit(2)
else:
logging.info('The changes have been reflected in the database.')
def __disconnect__(self) -> NoReturn:
self.__commit__()
self.cursor.close()
self.conn.close()
logging.info('Database connection termination success')
def _clean_datetime(self, query_result: Union[QueryResult, QueryResults]) -> str:
"""Converts a datetime object to a string when the column data type is DATETIME
Args:
query_result (Union[QueryResult, QueryResults]): [description]
Returns:
str: [description]
"""
if isinstance(query_result, dict):
query_result = [query_result]
for i, result in enumerate(query_result):
for key, value in result.items():
if isinstance(value, datetime.datetime):
query_result[i][key] = value.strftime(r'%Y-%m-%d %H:%M:%S')
return query_result
def execute(self, query: str, *, args: Dict[str, Any]={}) -> NoReturn:
try:
self.__connect__()
self.cursor.execute(query=query, args=args)
except pymysql.MySQLError as e:
print(e)
logging.error(e)
self.__disconnect__()
else:
logging.info(f'Query execution completed (Type: {query.upper().split()[0]})')
def executemany(self, query: str, *, args: Dict[str, Any]={}) -> NoReturn:
self.__connect__()
self.cursor.executemany(query=query, args=args)
self.__disconnect__()
def execute_with_fetch_one(self, query: str, *, args: Dict[str, Any]={}) -> Dict[str, Union[str, int, float]]:
self.execute(query=query, args=args)
response: dict = self.cursor.fetchone()
self.__disconnect__()
clean_response = self._clean_datetime(response)
return clean_response[0]
def execute_with_fetch_many(self, query: str, size: int, *, args: Dict[str, Any]={}) -> Dict[str, Union[str, int, float]]:
self.execute(query=query, args=args)
response: dict = self.cursor.fetchmany(size=size)
self.__disconnect__()
clean_response = self._clean_datetime(response)
return clean_response
def execute_with_fetch_all(self, query: str, *, args: Dict[str, Any]={}) -> Dict[str, Union[str, int, float]]:
self.execute(query=query, args=args)
response: dict = self.cursor.fetchall()
clean_response = self._clean_datetime(response)
self.__disconnect__()
return clean_response
@_log_file_write
def execute_save_json(self, query: str, path: str, *, args: Dict[str, Any]={}, encoding='utf-8') -> str:
response = self.execute_with_fetch_all(query=query, args=args)
with open(file=path, mode='w', encoding=encoding) as f:
f.write(json.dumps(response, indent='\t', ensure_ascii=False))
return path
@_log_file_write
def execute_save_yaml(self, query: str, path: str, *, args: Dict[str, Any]={}, encoding='utf-8') -> str:
response = self.execute_with_fetch_all(query=query, args=args)
with open(file=path, mode='w', encoding=encoding) as f:
f.write(yaml.dump(response, indent=4, allow_unicode=True))
return path
def execute_save_yml(self, query: str, path: str, *, args: Dict[str, Any]={}, encoding='utf-8') -> str:
self.execute_save_yaml(query=query, path=path, args=args, encoding=encoding)
if __name__ == "__main__":
from config import Config
mysql = MySQL(Config.mysql)
# response = mysql.execute_with_fetch_all(query='select * from users')
mysql.execute_save_json(query='select * from users', path='./results/sql.json')
mysql.execute_save_yml(query='select * from users', path='./results/sql.yml')
|
Ruby | UTF-8 | 2,642 | 2.859375 | 3 | [] | no_license | require 'simplecov'
SimpleCov.start
require_relative '../../lib/kupon'
describe Kupon do
let(:impreza) { instance_double("Wydarzenie",:nazwa => "Mecz")}
let(:opcja1) { instance_double("Opcja",:kurs => 2.0, :id => 1)}
let(:opcja2){ instance_double("Opcja",:kurs => 4.0, :id => 2)}
let(:opcja3) { instance_double("Opcja",:kurs => 1.5, :id => 1)}
let(:opcja4){ instance_double("Opcja",:kurs => 3.0, :id => 'X')}
let(:zaklad1) { instance_double("Zaklad",:wybranyKurs => 1.50, :wybor => 1, :bezpiecznaOpcjaId => 2)}
let(:zaklad2) { instance_double("Zaklad",:wybranyKurs => 3.0, :wybor => 1, :bezpiecznaOpcjaId => 2)}
context "Inicjalizacja kuponu" do
it 'za 0 złotych' do
expect{Kupon.new(-5)}.to raise_error
end
it 'za 10 złotych' do
expect{Kupon.new(10)}.to_not raise_error
end
end
describe "#dodajZaklad" do
it "czy uda sie dodać 1 zakład" do
kupon = Kupon.new(10)
expect{kupon.dodajZaklad(zaklad1)}.to_not raise_error
end
it "czy ilosc zakladow zgadza się po dodaniu" do
kupon = Kupon.new(10)
kupon.dodajZaklad(zaklad1)
kupon.dodajZaklad(zaklad2)
expect(kupon.zaklady.length).to eq(2)
end
end
describe "#usunZaklad" do
it "czy uda sie usunąc zakład" do
kupon = Kupon.new(10)
kupon.dodajZaklad(zaklad1)
kupon.dodajZaklad(zaklad2)
expect{kupon.usunZaklad(zaklad1)}.to_not raise_error
end
it "czy ilosc zakladow zgadza się po usunięciu" do
kupon = Kupon.new(10)
kupon.dodajZaklad(zaklad1)
kupon.dodajZaklad(zaklad2)
kupon.usunZaklad(zaklad1)
expect(kupon.zaklady.length).to eq(1)
end
end
describe "#to_s" do
it "zwraca nazwe wydarzenia i date" do
opt1 = instance_double('Opcja',:kurs => 1.30, :id => 1)
opt2 = instance_double('Opcja',:kurs => 2.70, :id => 2)
wyd = instance_double("Wydarzenie", :nazwa => "Anglia - Francja")
zaklad = Zaklad.new("Mecz ",wyd)
zaklad.dodajOpcja(opt1)
zaklad.dodajOpcja(opt2)
zaklad.wybor = 2
expect(zaklad.to_s).to eq("Mecz Anglia - Francja wybor-> 2 kurs-> 2.7")
end
end
describe "#obliczKoncowyKurs" do
it "sprawdzamy poprawnosc wyliczonego kursu" do
kupon = Kupon.new(10)
kupon.dodajZaklad(zaklad1)
kupon.dodajZaklad(zaklad2)
kupon.obliczKoncowyKurs
expect( 4.5).to eq(4.5)
end
end
describe "#obliczWygrana" do
it "sprawdzamy poprawnosc liczenia wygranej" do
kupon = Kupon.new(10)
kupon.dodajZaklad(zaklad1)
kupon.dodajZaklad(zaklad2)
expect(kupon.obliczWygrana).to eq(45)
end
end
end
|
Markdown | UTF-8 | 8,686 | 3.453125 | 3 | [
"Apache-2.0"
] | permissive | ---
layout: post
redirect_from: "/articles/improving-the-mac-installer-for-firefox/"
title: "Improving the Mac installer for Firefox"
subtitle: "With a renewed focus on improving the Firefox install experience — what can we improve on the Mac?"
cover_image: mountains.jpg
excerpt: "With a renewed focus on improving the Firefox install experience — what can we improve on the Mac?"
---
Lately, the [Metrics team] here at Mozilla have conducted some great research into why some people leave the installer before Firefox is finished installing, [uncovering a couple of bugs in the process], and improving the way we ask people [what will be their default browser].
(Also make sure you read [part 2 of this article])
The team looked specifically at the Windows installer — which makes sense, since that’s where most of our new users are coming from — but there are some substantial issues with the Mac install experience that we will explain in more detail.
## Where Apple failed
There’s a lot to like about Mac OS X, but in their quest to make things as simple and uncomplicated as possible, Apple actually made some things worse for the (mythical) average user, as well as for people new to the Mac. One of these areas is application installation.
If you are unfamiliar with the Mac OS X install process, let us quickly outline how application installation on Mac OS X works:
1. Download the file.
2. Open the disk image.
3. Drag the application to your Applications folder.
4. Optionally add the application to the Dock.
While this process is familiar to experienced Mac users, and removes the need for uninstall scripts, very few new users that recently purchased their first Mac know how to do this. Unless they have a friend that has shown them how it works, it doesn’t make sense to anyone coming from a different platform.
To mitigate this, the download page for Firefox — as well as pretty much every other Mac application on the planet — attempts to tell you what to do once you have downloaded the disk image:

The problem with this should be obvious — by the time the download is complete, that web page is usually long gone, and many people don’t read these kind of instructions at all.
To make matters even worse, Firefox is often one of the first applications that people new to the Mac go to download and install, since they want the familiar browser they have used earlier. They might catch on to how this works later, but it’s a fair bet that they don’t know this as new Mac users.
Some common errors that we have seen repeatedly among informal testing with friends and family are:
Dragging the application to the dock directly
: This creates a link to the file *inside* the disk image, which means that every time they try starting Firefox, the disk image is unpacked and mounted, and starting of Firefox becomes very slow, which makes it a bad experience.
Thinking that starting Firefox is done by opening the disk image every time
: This is very common, and the logic is that the first time they started Firefox, they had to do this, so they continue doing it. This makes starting Firefox a chore, since it takes a lot of clicks to accomplish.
What’s interesting is that Apple *are* aware of this problem, and even added a warning that shows up when you try to run an application from the disk image:

Quick, spot the problem! It doesn’t actually tell you anything about *why* it’s a bad idea to run stuff from a disk image — or even what you can do to avoid the problem — they just state that you’re about to do so. Oh, and that the file is from the Dangerous Internet. For a company that [prides itself on informative dialog boxes], this is quite surprising.
## How we can make the Mac install experience better
We can make some simple fixes to the current approach to make the experience better for people new to the Mac, while still retaining the power to put the file anywhere, per the classic OS X model.
What problems do we want to solve?
: People that don’t understand the standard installation process on Mac should be helped towards their goal.
: Downloading Firefox and then forgetting about the download should be less common.
: Maintain the standard installation model for the users that prefer the drag & drop install method.
: Make it possible to set Firefox as your default browser during the install process.
How do we fix these problems? By supplying a dedicated installer in the disk image, similar to the standard Mac OS X application installer:

We can fix all of these by using some capabilities of the standard Mac package installer and disk image creation tools supplied by Apple. In particular, they have features where you can [run an installer when a disk image is mounted], like Apple does with some of their own disk images. This, combined with the auto-mounting of disk images downloaded via Safari, gives us an installation flow that is likely to not lose people along the way.
The final installation flow should look like this:
1. Start the Firefox download.
2. When the download is complete, the disk image will mount automatically (if they were using Safari), and the Firefox installer runs.
3. The install procedure continues similar to how it happens on Windows.
4. As the last step of the process, the installer lets you set Firefox as the default browser, and start the application immediately. We have seen users forget that they just installed Firefox if you don’t let them start it at the end of the process, and make that the default choice.
Note that experienced Mac users should be able to cancel the installer at any time and drag the Firefox application to the location they want instead, thus there should be no loss of functionality or flexibility for them.
## Help us make it happen
At Mozilla, we’re currently in crunch mode to get Firefox 3.6 ready, and therefore we have limited resources to look at creating a proper installer for Mac OS X right now. If you’re an experienced Mac OS X developer that would like to help out with creating a new installer that we can help test, we’d love to hear from you. Please send an email to the [dev.apps.firefox Google Group] — or via the [traditional mailing list] interface. If you want to track progress, we have filed a [bug for the installer improvement] that you can subscribe to.
Also make sure you read [part 2 of this article].
[part 2 of this article]: /mac-installer-revisited
[Metrics team]: http://blog.mozilla.com/metrics/ "Blog of Metrics"
[uncovering a couple of bugs in the process]: http://blog.mozilla.com/metrics/2009/07/30/an-improved-experience-for-2000000-non-firefox-users/ "An Improved Experience for 2,000,000 non-Firefox Users"
[what will be their default browser]: http://blog.mozilla.com/metrics/2009/08/03/more-changes-coming-to-the-firefox-installer/ "More Changes Coming to the Firefox Installer"
[prides itself on informative dialog boxes]: http://developer.apple.com/mac/library/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGWindows/XHIGWindows.html#//apple_ref/doc/uid/20000961-TP10 "Apple Human Interface Guidelines: Alerts"
[run an installer when a disk image is mounted]: http://osdir.com/ml/os.opendarwin.webkit.devel/2007-12/msg00037.html "Auto-launch installer after download"
[dev.apps.firefox Google Group]: http://groups.google.com/group/mozilla.dev.apps.firefox/topics
[traditional mailing list]: https://lists.mozilla.org/listinfo/dev-apps-firefox
[bug for the installer improvement]: https://bugzilla.mozilla.org/show_bug.cgi?id=516362
[a part 2 available]: /mac-installer-revisited
*[AMO]: addons.mozilla.org
*[CDNs]: Content Delivery Networks
*[CPUs]: Central Processing Units
*[CPU]: Central Processing Unit
*[CSS]: Cascading Style Sheets
*[DSL]: Digital Subscriber Line
*[HTML5]: HyperText Markup Language 5
*[HTML]: HyperText Markup Language
*[HTTP]: HyperText Transfer Protocol
*[IBM]: International Business Machines
*[JAR]: Java Archive
*[JPEG]: Joint Photographic Expert Group
*[JS]: JavaScript
*[MIME]: Multipurpose Internet Mail Extensions
*[NTLM]: NT LAN Manager
*[OS X]: Mac OS Ten
*[PDF]: Portable Document Format
*[SPDY]: Speedy
*[SSL]: Secure Sockets Layer
*[TLS]: Transport Layer Security
*[UI]: User Interface
*[URLs]: Uniform Resource Locators
*[URL]: Uniform Resource Locator
*[USA]: United States of America
*[US]: United States
*[UTF-8]: Unicode Transformation Format 8
*[VPN]: Virtual Private Network
*[XHTML]: Extended HyperText Markup Language
*[ZIP]: ZIP
|
Python | UTF-8 | 239 | 3.40625 | 3 | [] | no_license | #!/usr/bin/env python3
"""
this module uses type annotation to document a string concat function
"""
def concat(str1: str, str2: str) -> str:
""" this function concats 2 strings and returns a single string """
return str1 + str2
|
SQL | UTF-8 | 14,119 | 3.078125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | -- phpMyAdmin SQL Dump
-- version 4.7.9
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 04, 2020 at 09:09 PM
-- Server version: 10.1.31-MariaDB
-- PHP Version: 7.2.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `studiofoto`
--
-- --------------------------------------------------------
--
-- Table structure for table `admin`
--
CREATE TABLE `admin` (
`id_admin` int(11) NOT NULL,
`username` varchar(35) NOT NULL,
`password` varchar(35) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `admin`
--
INSERT INTO `admin` (`id_admin`, `username`, `password`) VALUES
(1, 'admin', 'admin');
-- --------------------------------------------------------
--
-- Table structure for table `akun`
--
CREATE TABLE `akun` (
`no_reff` varchar(30) NOT NULL,
`nama_reff` varchar(30) NOT NULL,
`keterangan_reff` text NOT NULL,
`id_admin` varchar(5) NOT NULL,
`id_jenis` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `akun`
--
INSERT INTO `akun` (`no_reff`, `nama_reff`, `keterangan_reff`, `id_admin`, `id_jenis`) VALUES
('r1', 'Beban Gaji', 'Gaji pegawai', '1', '2'),
('r2', 'Pendapatan', 'Pendapatan dari penjualan pupuk', '1', '1'),
('r4', 'Kas', 'Kas dari pemasukan penjualan pupuk', '1', '1'),
('r5', 'Modal', 'Modal awal', '1', '2'),
('r6', 'Peralatan', 'Pembelian atau perawatan', '1', '2'),
('r7', 'Persediaan', 'Persediaan', '1', '1');
-- --------------------------------------------------------
--
-- Table structure for table `customer`
--
CREATE TABLE `customer` (
`id_cus` int(11) NOT NULL,
`nama_cus` varchar(40) NOT NULL,
`alamat_cus` text NOT NULL,
`no_hp` varchar(15) NOT NULL,
`email_cus` varchar(35) NOT NULL,
`username` varchar(30) NOT NULL,
`password` varchar(35) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `customer`
--
INSERT INTO `customer` (`id_cus`, `nama_cus`, `alamat_cus`, `no_hp`, `email_cus`, `username`, `password`) VALUES
(1, 'Fahrizal Azi Ferdiansyah', 'Banyuwangi Balak', 'jiwanrizal$gmai', '085678128123', 'jiwan', '12345'),
(5, 'Jiwan Rizal', 'Banyuwangi', '085736586636', 'jiwanrizal5@gmail.com', 'aji', '12345');
-- --------------------------------------------------------
--
-- Table structure for table `dekorasi`
--
CREATE TABLE `dekorasi` (
`id_dekorasi` int(40) NOT NULL,
`nama_dekorasi` varchar(50) NOT NULL,
`harga_dekorasi` int(30) NOT NULL,
`deskripsi_dekorasi` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `dekorasi`
--
INSERT INTO `dekorasi` (`id_dekorasi`, `nama_dekorasi`, `harga_dekorasi`, `deskripsi_dekorasi`) VALUES
(2, 'Minimalis', 750000, 'Dekorasi minimalis dapat di tempatkan di ruangan kecil/sempit dengan harga yang terjangkau'),
(3, 'Sedang', 5000000, 'Dekorasi yang tidak terlalu besar dengan kualitas memuaskan'),
(4, 'Mewah', 10000000, 'Dekorasi yang besar dengan barang-barang yang mewah.');
-- --------------------------------------------------------
--
-- Table structure for table `galeri`
--
CREATE TABLE `galeri` (
`id_galeri` int(11) NOT NULL,
`foto` varchar(30) NOT NULL,
`id_kategori` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `galeri`
--
INSERT INTO `galeri` (`id_galeri`, `foto`, `id_kategori`) VALUES
(1, 'gallery-4.jpg', '5'),
(2, 'gallery-5.jpg', '2'),
(4, '06627c8c-6b87-4f60-b151-00a359', '2'),
(6, 'cople.jpeg', '3'),
(7, 'grup.jpeg', '7'),
(8, 'kids.jpeg', '4'),
(9, 'single.jpeg', '5'),
(10, 'wedding.jpeg', '2'),
(11, 'wisuda.jpeg', '6'),
(12, 'prewedding.jpeg', '8');
-- --------------------------------------------------------
--
-- Table structure for table `jenis_pengeluaran`
--
CREATE TABLE `jenis_pengeluaran` (
`id_jenis_pengeluaran` int(11) NOT NULL,
`jenis_pengeluaran` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `jenis_pengeluaran`
--
INSERT INTO `jenis_pengeluaran` (`id_jenis_pengeluaran`, `jenis_pengeluaran`) VALUES
(1, 'Dekorasi'),
(2, 'Kamera');
-- --------------------------------------------------------
--
-- Table structure for table `jenis_saldo`
--
CREATE TABLE `jenis_saldo` (
`id_jenis` int(11) NOT NULL,
`nama_saldo` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `jenis_saldo`
--
INSERT INTO `jenis_saldo` (`id_jenis`, `nama_saldo`) VALUES
(1, 'Debit'),
(2, 'Kredit');
-- --------------------------------------------------------
--
-- Table structure for table `kategori`
--
CREATE TABLE `kategori` (
`id_kategori` int(35) NOT NULL,
`nama_kategori` varchar(50) NOT NULL,
`harga` int(11) NOT NULL,
`deskripsi` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `kategori`
--
INSERT INTO `kategori` (`id_kategori`, `nama_kategori`, `harga`, `deskripsi`) VALUES
(2, 'Wedding', 100000, 'Baju couple dan serasi'),
(3, 'Couple', 100000, 'uwuw'),
(4, 'Kids', 0, '0'),
(5, 'Single', 50000, 'Dapat Konsumsi'),
(6, 'Wisuda', 0, '0'),
(7, 'Grup', 0, '0'),
(8, 'Prewedding', 20000, 'Bensin Gratis');
-- --------------------------------------------------------
--
-- Table structure for table `kertas`
--
CREATE TABLE `kertas` (
`id_kertas` int(50) NOT NULL,
`nama_kertas` varchar(50) NOT NULL,
`harga` int(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `konfirmasi_pembayaran`
--
CREATE TABLE `konfirmasi_pembayaran` (
`id_konfirmasi` int(50) NOT NULL,
`id_pemesanan` int(50) NOT NULL,
`opsi` varchar(30) NOT NULL,
`dp` int(50) DEFAULT NULL,
`total_bayar` int(50) NOT NULL,
`bukti_transfer` varchar(128) NOT NULL,
`tgl_checkout` varchar(30) NOT NULL,
`jurnal` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `konfirmasi_pembayaran`
--
INSERT INTO `konfirmasi_pembayaran` (`id_konfirmasi`, `id_pemesanan`, `opsi`, `dp`, `total_bayar`, `bukti_transfer`, `tgl_checkout`, `jurnal`) VALUES
(16, 50, 'Lunas', 0, 130000, '0918194620X310.jpg', 'Senin, 3 Agustus 2020', 'Ya'),
(17, 52, 'Lunas', 0, 130000, '0918194620X310.jpg', 'Selasa, 4 Agustus 2020', 'Ya'),
(18, 53, 'DP', 40000, 80000, '0918194620X310.jpg', 'Selasa, 4 Agustus 2020', 'Ya'),
(19, 54, 'Lunas', 0, 130000, '0918194620X310.jpg', 'Selasa, 4 Agustus 2020', 'Ya');
-- --------------------------------------------------------
--
-- Table structure for table `pemesanan`
--
CREATE TABLE `pemesanan` (
`id_pemesanan` int(50) NOT NULL,
`id_kategori` int(11) NOT NULL,
`id_cus` int(50) NOT NULL,
`id_dekorasi` int(50) NOT NULL,
`id_sesi` int(50) NOT NULL,
`jenis` varchar(30) NOT NULL,
`lokasi` text,
`tgl_pemesanan` varchar(128) NOT NULL,
`waktu_pemesanan` varchar(30) NOT NULL,
`waktu_selesai` varchar(30) NOT NULL,
`total_biaya` int(70) NOT NULL,
`status_cus` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `pemesanan`
--
INSERT INTO `pemesanan` (`id_pemesanan`, `id_kategori`, `id_cus`, `id_dekorasi`, `id_sesi`, `jenis`, `lokasi`, `tgl_pemesanan`, `waktu_pemesanan`, `waktu_selesai`, `total_biaya`, `status_cus`) VALUES
(51, 2, 5, 1, 1, 'Studio', '', '03-08-2020', '20:11', '20:17', 130000, 'Belum Checkout'),
(52, 2, 1, 1, 1, 'Studio', '', '04-08-2020', '15:02', '15:08', 130000, 'Pesanan Selesai'),
(53, 5, 1, 1, 1, 'Studio', '', '04-08-2020', '15:06', '15:12', 80000, 'Pesanan Selesai'),
(54, 2, 1, 1, 1, 'Studio', '', '04-08-2020', '15:16', '15:22', 130000, 'Pesanan Selesai');
-- --------------------------------------------------------
--
-- Table structure for table `sesi_pemotretan`
--
CREATE TABLE `sesi_pemotretan` (
`id_sesi` int(30) NOT NULL,
`jumlah_sesi` int(30) NOT NULL,
`harga_sesi` int(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `sesi_pemotretan`
--
INSERT INTO `sesi_pemotretan` (`id_sesi`, `jumlah_sesi`, `harga_sesi`) VALUES
(1, 2, 10000),
(2, 1, 5000);
-- --------------------------------------------------------
--
-- Table structure for table `tbl_pengeluaran`
--
CREATE TABLE `tbl_pengeluaran` (
`id_pengeluaran` int(11) NOT NULL,
`nama_pengeluaran` varchar(30) NOT NULL,
`biaya_pengeluaran` int(11) NOT NULL,
`deskripsi_pengeluaran` text NOT NULL,
`tgl_pengeluaran` varchar(30) NOT NULL,
`id_jenis_pengeluaran` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tbl_pengeluaran`
--
INSERT INTO `tbl_pengeluaran` (`id_pengeluaran`, `nama_pengeluaran`, `biaya_pengeluaran`, `deskripsi_pengeluaran`, `tgl_pengeluaran`, `id_jenis_pengeluaran`) VALUES
(1, 'Menambah Dekorasi', 25000, 'Penambahan model dekorasi', 'Sabtu, 1 Agustus 2020', 1),
(2, 'Membuat Bingkai', 50000, 'Lagi mahal nih kertasnya', 'Minggu, 2 Agustus 2020', 1),
(3, 'Membuat Bingkai', 50000, 'Asa', 'Selasa, 4 Agustus 2020', 1);
-- --------------------------------------------------------
--
-- Table structure for table `transaksi`
--
CREATE TABLE `transaksi` (
`id_transaksi` int(11) NOT NULL,
`id_admin` varchar(5) NOT NULL,
`no_reff` varchar(30) NOT NULL,
`tgl_input` varchar(30) NOT NULL,
`tgl_transaksi` varchar(50) NOT NULL,
`jenis_saldo` int(11) NOT NULL,
`saldo` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `transaksi`
--
INSERT INTO `transaksi` (`id_transaksi`, `id_admin`, `no_reff`, `tgl_input`, `tgl_transaksi`, `jenis_saldo`, `saldo`) VALUES
(34, '1', 'r5', '04-08-2020 05:21:26', '2020-08-04', 2, 1500000),
(35, '', 'r1', '04-08-2020 06:04:15', '2020-08-05', 2, 150000),
(37, '', 'r2', '04-08-2020 07:14:18', '2020-08-06', 1, 150000),
(39, '', 'r2', '04-08-2020 07:15:44', '2020-08-21', 1, 150000),
(40, '', 'r6', '04-08-2020 08:24:16', '2020-08-13', 2, 50000),
(41, '', 'r2', '04-08-2020 08:32:23', '2020-08-05', 1, 135000);
-- --------------------------------------------------------
--
-- Table structure for table `ukuran`
--
CREATE TABLE `ukuran` (
`id_ukuran` int(30) NOT NULL,
`nama_ukuran` varchar(80) NOT NULL,
`harga` int(35) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `admin`
--
ALTER TABLE `admin`
ADD PRIMARY KEY (`id_admin`);
--
-- Indexes for table `akun`
--
ALTER TABLE `akun`
ADD PRIMARY KEY (`no_reff`);
--
-- Indexes for table `customer`
--
ALTER TABLE `customer`
ADD PRIMARY KEY (`id_cus`);
--
-- Indexes for table `dekorasi`
--
ALTER TABLE `dekorasi`
ADD PRIMARY KEY (`id_dekorasi`);
--
-- Indexes for table `galeri`
--
ALTER TABLE `galeri`
ADD PRIMARY KEY (`id_galeri`);
--
-- Indexes for table `jenis_pengeluaran`
--
ALTER TABLE `jenis_pengeluaran`
ADD PRIMARY KEY (`id_jenis_pengeluaran`);
--
-- Indexes for table `jenis_saldo`
--
ALTER TABLE `jenis_saldo`
ADD PRIMARY KEY (`id_jenis`);
--
-- Indexes for table `kategori`
--
ALTER TABLE `kategori`
ADD PRIMARY KEY (`id_kategori`);
--
-- Indexes for table `kertas`
--
ALTER TABLE `kertas`
ADD PRIMARY KEY (`id_kertas`);
--
-- Indexes for table `konfirmasi_pembayaran`
--
ALTER TABLE `konfirmasi_pembayaran`
ADD PRIMARY KEY (`id_konfirmasi`);
--
-- Indexes for table `pemesanan`
--
ALTER TABLE `pemesanan`
ADD PRIMARY KEY (`id_pemesanan`);
--
-- Indexes for table `sesi_pemotretan`
--
ALTER TABLE `sesi_pemotretan`
ADD PRIMARY KEY (`id_sesi`);
--
-- Indexes for table `tbl_pengeluaran`
--
ALTER TABLE `tbl_pengeluaran`
ADD PRIMARY KEY (`id_pengeluaran`);
--
-- Indexes for table `transaksi`
--
ALTER TABLE `transaksi`
ADD PRIMARY KEY (`id_transaksi`);
--
-- Indexes for table `ukuran`
--
ALTER TABLE `ukuran`
ADD PRIMARY KEY (`id_ukuran`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `admin`
--
ALTER TABLE `admin`
MODIFY `id_admin` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `customer`
--
ALTER TABLE `customer`
MODIFY `id_cus` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `dekorasi`
--
ALTER TABLE `dekorasi`
MODIFY `id_dekorasi` int(40) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `galeri`
--
ALTER TABLE `galeri`
MODIFY `id_galeri` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT for table `jenis_pengeluaran`
--
ALTER TABLE `jenis_pengeluaran`
MODIFY `id_jenis_pengeluaran` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `jenis_saldo`
--
ALTER TABLE `jenis_saldo`
MODIFY `id_jenis` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `kategori`
--
ALTER TABLE `kategori`
MODIFY `id_kategori` int(35) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `kertas`
--
ALTER TABLE `kertas`
MODIFY `id_kertas` int(50) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `konfirmasi_pembayaran`
--
ALTER TABLE `konfirmasi_pembayaran`
MODIFY `id_konfirmasi` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
--
-- AUTO_INCREMENT for table `pemesanan`
--
ALTER TABLE `pemesanan`
MODIFY `id_pemesanan` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=55;
--
-- AUTO_INCREMENT for table `tbl_pengeluaran`
--
ALTER TABLE `tbl_pengeluaran`
MODIFY `id_pengeluaran` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `transaksi`
--
ALTER TABLE `transaksi`
MODIFY `id_transaksi` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=42;
--
-- AUTO_INCREMENT for table `ukuran`
--
ALTER TABLE `ukuran`
MODIFY `id_ukuran` int(30) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java | UTF-8 | 6,191 | 2.0625 | 2 | [
"MIT"
] | permissive | /*
* Copyright 2012-2016 Broad Institute, Inc.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.broadinstitute.gatk.engine.traversals;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMRecord;
import org.broadinstitute.gatk.engine.GenomeAnalysisEngine;
import org.testng.Assert;
import org.broadinstitute.gatk.utils.BaseTest;
import org.broadinstitute.gatk.utils.GenomeLocParser;
import org.broadinstitute.gatk.utils.sam.ArtificialSAMUtils;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author aaron
* <p/>
* Class TraverseDuplicatesUnitTest
* <p/>
* test the meat of the traverse dupplicates.
*/
public class TraverseDuplicatesUnitTest extends BaseTest {
private TraverseDuplicates obj = new TraverseDuplicates();
private SAMFileHeader header;
private GenomeLocParser genomeLocParser;
private GenomeAnalysisEngine engine;
private File refFile = new File(validationDataLocation + "Homo_sapiens_assembly17.fasta");
@BeforeMethod
public void doBefore() {
header = ArtificialSAMUtils.createArtificialSamHeader(1, 1, 1000);
genomeLocParser =new GenomeLocParser(header.getSequenceDictionary());
engine = new GenomeAnalysisEngine();
engine.setReferenceDataSource(refFile);
engine.setGenomeLocParser(genomeLocParser);
obj.initialize(engine, null);
}
@Test
public void testAllDuplicatesNoPairs() {
List<SAMRecord> list = new ArrayList<SAMRecord>();
for (int x = 0; x < 10; x++) {
SAMRecord read = ArtificialSAMUtils.createArtificialRead(header, "SWEET_READ" + x, 0, 1, 100);
read.setDuplicateReadFlag(true);
list.add(read);
}
Set<List<SAMRecord>> myPairings = obj.uniqueReadSets(list);
Assert.assertEquals(myPairings.size(), 1);
Assert.assertEquals(myPairings.iterator().next().size(), 10); // dup's
}
@Test
public void testNoDuplicatesNoPairs() {
List<SAMRecord> list = new ArrayList<SAMRecord>();
for (int x = 0; x < 10; x++) {
SAMRecord read = ArtificialSAMUtils.createArtificialRead(header, "SWEET_READ" + x, 0, 1, 100);
read.setDuplicateReadFlag(false);
list.add(read);
}
Set<List<SAMRecord>> myPairing = obj.uniqueReadSets(list);
Assert.assertEquals(myPairing.size(), 10); // unique
}
@Test
public void testFiftyFiftyNoPairs() {
List<SAMRecord> list = new ArrayList<SAMRecord>();
for (int x = 0; x < 5; x++) {
SAMRecord read = ArtificialSAMUtils.createArtificialRead(header, "SWEET_READ" + x, 0, 1, 100);
read.setDuplicateReadFlag(true);
list.add(read);
}
for (int x = 10; x < 15; x++)
list.add(ArtificialSAMUtils.createArtificialRead(header, String.valueOf(x), 0, x, 100));
Set<List<SAMRecord>> myPairing = obj.uniqueReadSets(list);
Assert.assertEquals(myPairing.size(), 6); // unique
}
@Test
public void testAllDuplicatesAllPairs() {
List<SAMRecord> list = new ArrayList<SAMRecord>();
for (int x = 0; x < 10; x++) {
SAMRecord read = ArtificialSAMUtils.createArtificialRead(header, "SWEET_READ"+ x, 0, 1, 100);
read.setDuplicateReadFlag(true);
read.setMateAlignmentStart(100);
read.setMateReferenceIndex(0);
read.setReadPairedFlag(true);
list.add(read);
}
Set<List<SAMRecord>> myPairing = obj.uniqueReadSets(list);
Assert.assertEquals(myPairing.size(), 1); // unique
}
@Test
public void testNoDuplicatesAllPairs() {
List<SAMRecord> list = new ArrayList<SAMRecord>();
for (int x = 0; x < 10; x++) {
SAMRecord read = ArtificialSAMUtils.createArtificialRead(header, "SWEET_READ"+ x, 0, 1, 100);
if (x == 0) read.setDuplicateReadFlag(true); // one is a dup but (next line)
read.setMateAlignmentStart(100); // they all have a shared start and mate start so they're dup's
read.setMateReferenceIndex(0);
read.setReadPairedFlag(true);
list.add(read);
}
Set<List<SAMRecord>> myPairing = obj.uniqueReadSets(list);
Assert.assertEquals(myPairing.size(), 1); // unique
}
@Test
public void testAllDuplicatesAllPairsDifferentPairedEnd() {
List<SAMRecord> list = new ArrayList<SAMRecord>();
for (int x = 0; x < 10; x++) {
SAMRecord read = ArtificialSAMUtils.createArtificialRead(header, "SWEET_READ" + x, 0, 1, 100);
if (x == 0) read.setDuplicateReadFlag(true); // one is a dup
read.setMateAlignmentStart(100 + x);
read.setMateReferenceIndex(0);
read.setReadPairedFlag(true);
list.add(read);
}
Set<List<SAMRecord>> myPairing = obj.uniqueReadSets(list);
Assert.assertEquals(myPairing.size(), 10); // unique
}
}
|
C# | UTF-8 | 6,383 | 2.578125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MB_YGS__LYS_Puan_Hesaplama_Motoru
{
public partial class LysHesapla : Form
{
#region Metodlar
public void texttamamla(Control y)
{
foreach (Control nesne in y.Controls)
{
if (nesne is TextBox)
{
if (string.IsNullOrEmpty(nesne.Text))
{
nesne.Text = "0";
}
}
}
}
public void değeral()
{
t = double.Parse(textBox1.Text);
s = double.Parse(textBox2.Text);
m = double.Parse(textBox3.Text);
f = double.Parse(textBox4.Text);
m2 = double.Parse(textBox6.Text);
g = double.Parse(textBox7.Text);
f2 = double.Parse(textBox8.Text);
k = double.Parse(textBox9.Text);
b = double.Parse(textBox10.Text);
t = double.Parse(textBox11.Text);
e1 = double.Parse(textBox12.Text);
c1 = double.Parse(textBox13.Text);
c2 = double.Parse(textBox14.Text);
f3 = double.Parse(textBox15.Text);
}
public void temizle(Control x)
{
foreach (Control nesne2 in x.Controls)
{
if (nesne2 is TextBox)
{
nesne2.Text = "";
}
}
}
#endregion
#region Değişkenler
double t, s, m, f,m2,g,f2,k,b,c1,c2,f3,mf1,mf2,mf3,mf4,tm1,tm2,tm3,ts1,ts2,d,e1;
#endregion
public LysHesapla()
{
InitializeComponent();
}
private void button6_Click(object sender, EventArgs e)
{
texttamamla(groupBox4);
texttamamla(groupBox5);
değeral();
mf1 = 100 + (t * 1.334) + (m * 1.619) + (s * 0.311) + (f * 0.921) + (m2 * 2.732) + (g * 1.439) + (f2 * 1.059) + (k * 0.391) + (b * 0.311);
mf2 = 99.990 + (t * 1.314) + (m * 1.314) + (s * 0.311) + (f * 1.439) + (m2 * 1.568) + (g * 0.908) + (f2 * 1.469) + (k * 1.253) + (b * 1.253);
mf3 = 100.010 + (t * 1.311) + (m * 1.311) + (s * 0.798) + (f * 1.311) + (m2 * 1.245) + (g * 0.598) + (f2 * 1.348) + (k * 1.447) + (b * 1.557);
mf4 = 99.990 + (t * 1.311) + (m * 1.447) + (s * 0.798) + (f * 0.800) + (m2 * 2.200) + (g * 1.311) + (f2 * 1.348) + (k * 0.800) + (b * 0.400);
tm1 = 100.002 + (t * 1.335) + (m * 1.337) + (s * 0.633) + (f * 0.465) + (m2 * 1.901) + (g * 1.086) + (e1 * 1.582) + (c1 * 1.374);
tm2 = 100.020 + (t * 1.488) + (m * 1.412) + (s * 0.619) + (f * 0.358) + (m2 * 1.880) + (g * 0.450) + (e1 * 1.890) + (c1 * 1.315);
tm3 = 99.982 + (t * 1.651) + (m * 1.035) + (s * 0.974) + (f * 0.382) + (m2 * 1.573) + (g * 0.420) + (e1 * 1.961) + (c1 * 1.553);
ts1 = 101.974 + (c2 * 0.843) + (t * 1.276) + (m * 1.043) + (s * 1.204) + (f * 0.498) + (e1 * 1.534) + (t * 1.534) + (c1 * 0.954) + (f3 * 1.534);
ts2 = 110.526 + (t * 1.809) + (m * 0.378) + (s * 1.033) + (f * 0.469) + (e1 * 1.966) + (c1 * 0.809) + (c2 * 0.809) + (t * 1.479) + (f3 * 1.125);
textBox16.Text = mf1.ToString();
textBox17.Text = mf2.ToString();
textBox18.Text = mf3.ToString();
textBox19.Text = mf4.ToString();
textBox20.Text = tm1.ToString();
textBox21.Text = tm2.ToString();
textBox22.Text = tm3.ToString();
textBox23.Text = ts1.ToString();
textBox24.Text = ts2.ToString();
}
private void button3_Click(object sender, EventArgs e)
{
texttamamla(groupBox4);
texttamamla(groupBox5);
değeral();
d = double.Parse(textBox5.Text);
mf1 = 100 + (t * 1.334) + (m * 1.619) + (s * 0.311) + (f * 0.921) + (m2 * 2.732) + (g * 1.439) + (f2 * 1.059) + (k * 0.391) + (b * 0.311) + (d * 0.6);
mf2 = 99.990 + (t * 1.314) + (m * 1.314) + (s * 0.311) + (f * 1.439) + (m2 * 1.568) + (g * 0.908) + (f2 * 1.469) + (k * 1.253) + (b * 1.253) + (d * 0.6);
mf3 = 100.010 + (t * 1.311) + (m * 1.311) + (s * 0.798) + (f * 1.311) + (m2 * 1.245) + (g * 0.598) + (f2 * 1.348) + (k * 1.447) + (b * 1.557) + (d * 0.6);
mf4 = 99.990 + (t * 1.311) + (m * 1.447) + (s * 0.798) + (f * 0.800) + (m2 * 2.200) + (g * 1.311) + (f2 * 1.348) + (k * 0.800) + (b * 0.400) + (d * 0.6);
tm1 = 100.002 + (t * 1.335) + (m * 1.337) + (s * 0.633) + (f * 0.465) + (m2 * 1.901) + (g * 1.086) + (e1 * 1.582) + (c1 * 1.374) + (d * 0.6);
tm2 = 100.020 + (t * 1.488) + (m * 1.412) + (s * 0.619) + (f * 0.358) + (m2 * 1.880) + (g * 0.450) + (e1 * 1.890) + (c1 * 1.315) + (d * 0.6);
tm3 = 99.982 + (t * 1.651) + (m * 1.035) + (s * 0.974) + (f * 0.382) + (m2 * 1.573) + (g * 0.420) + (e1 * 1.961) + (c1 * 1.553) + (d * 0.6);
ts1 = 101.974 + (c2 * 0.843) + (t * 1.276) + (m * 1.043) + (s * 1.204) + (f * 0.498) + (e1 * 1.534) + (t * 1.534) + (c1 * 0.954) + (f3 * 1.534) + (d * 0.6);
ts2 = 110.526 + (t * 1.809) + (m * 0.378) + (s * 1.033) + (f * 0.469) + (e1 * 1.966) + (c1 * 0.809) + (c2 * 0.809) + (t * 1.479) + (f3 * 1.125) + (d * 0.6);
textBox25.Text = mf1.ToString();
textBox26.Text = mf2.ToString();
textBox27.Text = mf3.ToString();
textBox28.Text = mf4.ToString();
textBox29.Text = tm1.ToString();
textBox30.Text = tm2.ToString();
textBox31.Text = tm3.ToString();
textBox32.Text = ts1.ToString();
textBox33.Text = ts2.ToString();
}
private void button5_Click(object sender, EventArgs e)
{
temizle(groupBox4);
temizle(groupBox5);
temizle(groupBox6);
temizle(groupBox7);
}
private void groupBox5_Enter(object sender, EventArgs e)
{
}
}
}
|
PHP | UTF-8 | 928 | 2.546875 | 3 | [] | no_license | <?php
class Post extends AppModel {
var $name = 'Post';
var $displayField = 'title';
var $validate = array(
'post' => array(
'rule' => array('custom', '/^[a-z0-9 ]*$/i'),
'maxLength' => 610,
'require' => true,
'message' => 'Your post is too long'
)
);
var $belongsTo = array(
'Topic' => array(
'className' => 'Topic',
'foreignKey' => 'topic_id'
),
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
var $hasMany = array(
'Comment' => array (
'className' => 'Comment',
'order' => array (
'Comment.created' => 'DESC',
)
)
);
}
|
JavaScript | UTF-8 | 655 | 3.703125 | 4 | [] | no_license | //new功能
//访问构造函数的属性和构造函数原型的属性
function fakeNew(){
var obj = new Object();
var Constructor = Array.prototype.shift.call(arguments);
obj.__proto__ = Constructor.prototype;
var result = Constructor.apply(obj,arguments);
return typeof result ==='object'? result : obj ;
}
function Person(age,name,sex){
this.age = age;
this.sex = sex;
this.name = name;
}
Person.prototype.home = 'beijing';
Person.prototype.sayHello = function () {
console.log('What is your name?');
};
var XiaoMing = fakeNew(Person,18,'XiaoMing','boy');
XiaoMing.sayHello();
|
Shell | UTF-8 | 242 | 3.0625 | 3 | [] | no_license | #!/bin/bash
importantlines=""
if [ -p /dev/stdin ]; then
while IFS= read -r line; do
if [[ $line =~ .*Verif.* ]]; then
importantlines="|$importantlines$line"
fi
done
fi
curl --request POST --url "$1" --data-raw "$2$importantlines"
|
C# | UTF-8 | 861 | 2.53125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace Haxgo.Core.Sessions
{
public class SessionService
{
public static void InsertObject(string Key, object Obj)
{
if ((Obj != null))
{
if (HttpContext.Current.Session[Key] == null)
{
HttpContext.Current.Session[Key] = Obj;
}
}
}
public static object GetObject(string Key)
{
return HttpContext.Current.Session[Key];
}
public static void RemoveObject(string Key)
{
if ((HttpContext.Current.Session[Key] != null))
{
HttpContext.Current.Session[Key] = null;
}
}
}
}
|
TypeScript | UTF-8 | 3,217 | 2.53125 | 3 | [] | no_license | import Axios, { AxiosRequestConfig } from 'axios';
import { RouteComponentProps } from 'react-router-dom';
import * as config from './app.config';
import { Dto } from './dtos/Dto';
import { ResourceError } from './dtos/Error';
import { SystemLogout } from './components/Login';
const instance = Axios.create({
baseURL: config.apiHostAddres,
timeout: 5000,
headers: {
'Access-Control-Allow-Origin': '*',
}
});
export default instance;
export function Get(url: string, config?: AxiosRequestConfig) {
try {
console.info(`Getting ${url}.`);
const token = localStorage.getItem('token');
const response = instance.get(url, { ...config, headers: { 'Auth-Token': token } });
return response;
} catch (error) {
console.error(error.response);
if (error.response && error.response.status === 401) {
SystemLogout();
} else {
throw error;
}
}
}
export async function Put(url: string, data: any, config?: AxiosRequestConfig) {
try {
console.info(`About to put to ${url} object ${JSON.stringify(data)}`);
const token = localStorage.getItem('token');
return await instance.put(url, data, { ...config, headers: { 'Auth-Token': token } });
} catch (error) {
console.error(error.response);
if (error.response && error.response.status === 401) {
SystemLogout();
} else {
throw error;
}
}
}
export async function Post(url: string, data: any, config?: AxiosRequestConfig) {
try {
console.info(`About to post to ${url} object ${JSON.stringify(data)}`);
const token = localStorage.getItem('token');
return await instance.post(url, data, { ...config, headers: { 'Auth-Token': token } });
} catch (error) {
console.error(error.response);
if (error.response && error.response.status === 401) {
SystemLogout();
} else {
throw error;
}
}
}
export async function Delete(url: string, config?: AxiosRequestConfig) {
try {
console.info(`Deleting ${url}.`);
const token = localStorage.getItem('token');
return await instance.delete(url, { ...config, headers: { 'Auth-Token': token } });
} catch (error) {
console.error(error.response);
if (error.response && error.response.status === 401) {
SystemLogout();
} else {
throw error;
}
}
}
export async function GetAllBy<T extends Dto>(url: string, expectedObject: { new(): T; }) {
try {
const expectedDtoName = (new expectedObject).dtoName;
const response = await Get(url, {});
const resArray: T[] = [];
for (const dto of response.data) {
if (dto.dtoName === expectedDtoName) {
resArray.push(dto);
} else {
throw new ResourceError('Response from server does not match expected DTO.', response);
}
}
return resArray;
} catch (error) {
if (error.response && error.response.status === 401) {
SystemLogout();
}
console.error(error);
}
} |
C# | UTF-8 | 3,642 | 2.546875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectManager
{
public partial class CreateForm : Form
{
public enum createType
{
EMPLOYEE = 1,
PROJECT = 2
}
public createType userDefinedCreate { get; set; }
public object newCreation { get; set; }
public CreateForm(createType createType)
{
InitializeComponent();
this.userDefinedCreate = createType;
loadPropGrid();
}
public CreateForm(createType createType, object objToEdit)
{
InitializeComponent();
this.newCreation = objToEdit;
this.userDefinedCreate = createType;
loadPropGrid(objToEdit);
}
private void loadPropGrid(object objToCreate = null)
{
switch (userDefinedCreate)
{
case createType.EMPLOYEE:
pg_Create.SelectedObject = new XMLDataToObj.Employee()
{
Admin = "false",
AssignedProjects = new List<XMLDataToObj.AssignedProjects>(),
Password = "default",
UserName = "default"
};
if (objToCreate != null)
{
pg_Create.SelectedObject = (XMLDataToObj.Employee)objToCreate;
}
break;
case createType.PROJECT:
XMLDataToObj.Project proj = new XMLDataToObj.Project();
proj.ProjectDescription = new XMLDataToObj.ProjectDescription();
proj.ProjectDescription.Requirements = new List<XMLDataToObj.Requirement>();
proj.ProjectDescription.Risks = new List<XMLDataToObj.Risk>();
pg_Create.SelectedObject = proj;
if (objToCreate != null)
{
pg_Create.SelectedObject = (XMLDataToObj.Project)objToCreate;
}
break;
default:
MessageBox.Show("Unkown type encountered. Currently only creation of new " + Environment.NewLine +
"Employees or Projects is currently supported.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
}
private void b_Save_Click(object sender, EventArgs e)
{
switch (userDefinedCreate)
{
case createType.EMPLOYEE:
newCreation = (XMLDataToObj.Employee)pg_Create.SelectedObject;
break;
case createType.PROJECT:
newCreation = (XMLDataToObj.Project)pg_Create.SelectedObject;
break;
default:
newCreation = null;
MessageBox.Show("Unkown type encountered. Currently only creation of new " + Environment.NewLine +
"Employees or Projects is currently supported.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
private void b_Cancel_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
}
}
}
|
PHP | UTF-8 | 1,210 | 2.75 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: oem
* Date: 24.10.18
* Time: 13:54
*/
namespace Phore\Datalytics\Core\Aggregator;
use InvalidArgumentException;
class AggregatorFactory
{
private $defaultAggregator;
public function __construct(string $defaultAggregator="first")
{
$this->defaultAggregator = $defaultAggregator;
}
public function createAggregator(string $aggregatorName = null) : Aggregator
{
if ($aggregatorName === null) {
$aggregatorName = $this->defaultAggregator;
}
switch ($aggregatorName) {
case "avg":
return new AvgAggregator();
case "count":
return new CountAggregator();
case "first":
return new FirstAggregator();
case "max":
return new MaxAggregator();
case "min":
return new MinAggregator();
case "sum":
return new SumAggregator();
case "last":
return new LastAggregator();
default:
throw new InvalidArgumentException("Unknown aggregator name: $aggregatorName");
}
}
}
|
Go | UTF-8 | 1,092 | 3.03125 | 3 | [] | no_license | package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
func main() {
var (
input string
verbose bool
)
flag.StringVar(&input, "i", "main.go", "set input file")
flag.BoolVar(&verbose, "v", false, "verbose mode")
flag.Parse()
f, err := os.OpenFile(input, os.O_RDONLY, os.ModePerm)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
defer func() {
if err := f.Close(); err != nil {
fmt.Print(err.Error())
os.Exit(1)
}
}()
out := strings.Replace(input, filepath.Ext(input), ".pgo", 1)
buf := bytes.NewBuffer([]byte{})
scan := bufio.NewScanner(f)
for scan.Scan() {
line := scan.Text()
def := strings.TrimSpace(line)
if strings.HasPrefix(def, "//#") {
def = strings.Replace(def, "//", "", 1)
buf.WriteString(def + "\n")
if verbose {
fmt.Println(def)
}
} else {
buf.WriteString(line + "\n")
if verbose {
fmt.Println(line)
}
}
}
fmt.Println(out)
if err := ioutil.WriteFile(out, buf.Bytes(), os.ModePerm); err != nil {
fmt.Print(err.Error())
os.Exit(1)
}
}
|
Java | UTF-8 | 743 | 2.53125 | 3 | [] | no_license | package ovgu.ir;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.tartarus.snowball.ext.PorterStemmer;
public class TextStemmer {
public List<String> getStemmedValue(List<String> termList){
Tokenizer tk = new Tokenizer();
Analyzer az = new StandardAnalyzer();
List<String> resultList = new ArrayList<>();
resultList=tk.tokenizeList(termList, az);
PorterStemmer stemmer = new PorterStemmer();
List<String> ls = new ArrayList<String>();
for (String term : resultList) {
stemmer.setCurrent(term);
stemmer.stem();
String result = stemmer.getCurrent();
ls.add(result);
}
return ls;
}
}
|
PHP | UTF-8 | 2,152 | 2.640625 | 3 | [] | no_license | <?php
/*
Plugin Name: Anti-User
Plugin URI: NONE
Description: Basic WordPress Plugin Header Comment
Version: 20160911
Author: shamelessApathy
Author URI: NONE
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: wporg
Domain Path: /languages
*/
defined('ABSPATH') or die(' No script kiddies please! ');
/* Potentially need Activation Hook Here */
# register_activation_hook( __FILE__, 'pluginprefix_function_to_run');
/* Deactivation Hook */
# register+deactivation_hook( __FILE__, 'pluginprefix_function_to_run');
/* Adding a Top-Level Admin Menu */
class AntiUser {
public function __construct()
{
function first_hook()
{
// This is where we intercept the registration of a new user, if au_register switch is turned ON, we block creation
add_action('register_post', 'prevent_registration', 10, 3 );
function prevent_registration($sanitized_user_login, $user_email, $errors)
{
if (get_option('au_register_switch') === '1')
{
$errors->add('demo_error', "<strong>ERROR</strong>:This site does not accept new users");
}
}
}
add_action('wp_loaded', 'first_hook');
/* Registering the Anti-User menu inside of the admin_menu hook */
add_action('admin_menu', 'anti_user_menu');
/* Here we define everything for the menu */
function anti_user_menu()
{
$page_title = "Anti-User Options";
$menu_title = "Anti-User";
$capability = "administrator";
$menu_slug = "anti-user";
$icon_url = plugin_dir_url(__FILE__) . 'images/hallows.png';
add_menu_page(
$page_title,
$menu_title,
$capability,
$menu_slug,
'anti_user_options_page',
$icon_url,
$position = null
);
}
/* Adding Enable/Disable User creation option Default is 0 = OFF*/
add_option('au_register_switch', 0);
/**
* This function renders the admin options area
* @param none
* @return PHP/HTML Template
*/
function anti_user_options_page()
{
if (isset($_POST['au_register_switch']))
{
update_option('au_register_switch', $_POST['au_register_switch']);
}
$template_url = plugin_dir_url(__FILE__) . "templates";
require_once("templates/au_admin_menu.php");
}
}
}
$anti = new AntiUser();
|
C++ | UTF-8 | 763 | 3.625 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
struct vertex {
float x, y, z;
vertex(float x, float y, float z)
: x(x), y(y),z(z)
{}
vertex(const vertex& vert)
: x(vert.x), y(vert.y), z(vert.z)
{
std::cout << "copied" << std::endl;
}
};
std::ostream& operator<<(std::ostream& stream, const vertex& vertex)
{
stream << vertex.x << "," << vertex.y << "," << vertex.z;
return stream;
}
int main()
{
std::vector<vertex> vert;
vert.reserve(3);
vert.emplace_back( 1,2,3 );
vert.emplace_back( 4,5,6 );
vert.emplace_back( 7,8,9 );
for (int i = 0; i < vert.size(); i++)
std::cout << vert[i] << std::endl;
vert.erase(vert.begin() + 1);
for (const vertex& v : vert)
std::cout << v << std::endl;
vert.clear();
std::cin.get();
} |
Java | UTF-8 | 1,256 | 3.4375 | 3 | [] | no_license | package functionAndArrayPepcoding;
import java.util.Scanner;
public class AnyBaseAddition {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int b = sc.nextInt();
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int d = getSum(b, n1, n2);
System.out.println(d);
sc.close();
}
public static int getSum(int b, int n1, int n2){
// write ur code here
int n1InDecimal = baseToDecimal(n1, b);
int n2InDecimal = baseToDecimal( n2, b);
int sumInDecimal = n1InDecimal + n2InDecimal;
int sumInGivenBase = decimalToAnyBase(sumInDecimal, b);
return sumInGivenBase;
}
public static int baseToDecimal(int n, int b)
{
int num = 0;
int i=0;
while(n>0)
{
int rem = n%10;
num = (rem*(int)Math.pow(b,i)) + num;
n/=10;
i++;
}
return num;
}
public static int decimalToAnyBase(int n, int b)
{
int num = 0;
int i=0;
while(n>0)
{
int rem = n%b;
num = (rem*(int)Math.pow(10,i)) + num;
n/=b;
i++;
}
return num;
}
}
|
SQL | UTF-8 | 23,523 | 3.625 | 4 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 5.1.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jun 14, 2021 at 09:55 AM
-- Server version: 10.4.18-MariaDB
-- PHP Version: 8.0.5
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `visitbosnia`
--
DELIMITER $$
--
-- Procedures
--
CREATE DEFINER=`root`@`localhost` PROCEDURE `ClearAllUserData` () BEGIN
DELETE FROM userratings where 1;
DELETE FROM userfavorites where 1;
DELETE FROM user where 1;
END$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `user_ratings` (`p_oid` INT) BEGIN
UPDATE object SET averagerating = (SELECT AVG(rating) FROM userratings WHERE oid = p_oid) WHERE oid = p_oid;
END$$
--
-- Functions
--
CREATE DEFINER=`root`@`localhost` FUNCTION `GetObjectName` (`p_id` INT) RETURNS VARCHAR(255) CHARSET utf8mb4 BEGIN
declare ret varchar(255);
select name into ret FROM object where oid = p_id;
return ret;
END$$
CREATE DEFINER=`root`@`localhost` FUNCTION `GetUserName` (`p_id` INT) RETURNS VARCHAR(255) CHARSET utf8mb4 BEGIN
declare ret varchar(255);
select concat(name, ' ', surname) into ret FROM user where uid = p_id;
return ret;
END$$
DELIMITER ;
-- --------------------------------------------------------
--
-- Stand-in structure for view `active_users`
-- (See below for the actual view)
--
CREATE TABLE `active_users` (
`uid` int(11)
,`name` varchar(100)
,`surname` varchar(100)
,`username` varchar(30)
,`email` varchar(255)
,`startdate` date
);
-- --------------------------------------------------------
--
-- Table structure for table `city`
--
CREATE TABLE `city` (
`cid` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`Country` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `city`
--
INSERT INTO `city` (`cid`, `name`, `Country`) VALUES
(24, 'Visoko', 1),
(27, 'Sarajevo', 1),
(28, 'Zenica', 1),
(31, 'Travnik', 1),
(32, 'Jajce', 1);
-- --------------------------------------------------------
--
-- Table structure for table `country`
--
CREATE TABLE `country` (
`cid` int(11) NOT NULL,
`name` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `country`
--
INSERT INTO `country` (`cid`, `name`) VALUES
(1, 'Bosnia and Herzegovina');
-- --------------------------------------------------------
--
-- Stand-in structure for view `fav_objects`
-- (See below for the actual view)
--
CREATE TABLE `fav_objects` (
`objectid` int(11)
,`object` varchar(255)
,`favnum` bigint(21)
);
-- --------------------------------------------------------
--
-- Stand-in structure for view `most_active_users`
-- (See below for the actual view)
--
CREATE TABLE `most_active_users` (
`user` int(11)
,`GetUserName(user)` varchar(255)
,`favno` bigint(21)
);
-- --------------------------------------------------------
--
-- Table structure for table `object`
--
CREATE TABLE `object` (
`oid` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`street` varchar(255) NOT NULL,
`phone` varchar(20) DEFAULT NULL,
`opening_hours` time NOT NULL,
`closing_hours` time NOT NULL,
`pricing` int(11) DEFAULT 0,
`webpage` varchar(255) DEFAULT NULL,
`email` varchar(150) DEFAULT NULL,
`start_day` varchar(20) DEFAULT 'Monday',
`close_day` varchar(20) DEFAULT 'Sunday',
`isVegan` tinyint(1) DEFAULT 0,
`description` longtext DEFAULT NULL,
`isGlutenFree` tinyint(1) DEFAULT 0,
`isPetFriendly` tinyint(1) DEFAULT 0,
`city` int(11) NOT NULL,
`isHalal` tinyint(1) DEFAULT 0,
`image` varchar(255) NOT NULL,
`averagerating` double DEFAULT NULL,
`active` bit(1) NOT NULL DEFAULT b'1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `object`
--
INSERT INTO `object` (`oid`, `name`, `street`, `phone`, `opening_hours`, `closing_hours`, `pricing`, `webpage`, `email`, `start_day`, `close_day`, `isVegan`, `description`, `isGlutenFree`, `isPetFriendly`, `city`, `isHalal`, `image`, `averagerating`, `active`) VALUES
(41, 'Chipas', 'Kolodvorska 1', '062/459-199', '07:00:00', '17:00:00', 1, 'www.chipas.com', 'chipas@gmail.com', 'monday', 'sunday', 1, 'A nice and cheap place to eat', 0, 1, 24, 0, 'chipas.jpg', 2, b'1'),
(45, 'Metropolis SCCCCCC', 'Maršala Tita 21', '033 203-315', '07:00:00', '23:00:00', 2, 'www.metropolis.com', 'metropolis@gmail.com', 'monday', 'sunday', 1, 'Nice place to eat.', 1, 1, 27, 1, 'metropolis.png', NULL, b'0'),
(46, '4 sobe gospođe Safije', 'Čekaluša 61', '062/459-199', '07:00:00', '23:00:00', 3, 'www.4sgs.com', '4sgs@gmail.com', 'monday', 'sunday', 0, 'Lorem Ipsum is simply dummy.', 1, 1, 27, 1, 'safija.png', NULL, b'1'),
(57, 'Trebevićka žiÄara', 'Hrvatin bb', '062/459-199', '19:00:00', '09:00:00', 1, 'www.zicara.ba', 'zicara@gmail.com', 'monday', 'saturday', 0, 'fhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghdukfhsfgiugdhgukdhkguhdukghdukghduk', 0, 0, 27, 0, 'zicara.jpg', NULL, b'1'),
(58, 'Rafting na Miljacki', 'Konjicka bb', '062/459-199', '19:00:00', '10:00:00', 2, 'www.raftingnaneretvi.com', 'rafting@gmail.com', 'monday', 'sunday', 0, 'hferiuuhfreuifhreuifherhfiupiupiupuierhphphpiueiufhehphpiehpiuiueiupuieiuerhfuiepfpierhpfieueprhperihepfiuheruifpehperhpiffihhererhfhrfpuiehifieupfepihfp', 0, 0, 27, 0, 'rafting.jpg', NULL, b'1'),
(59, 'Sunnyland', 'Antuna Hangija 23', '062/459-199', '07:00:00', '18:00:00', 2, 'www.sunnyland.com', 'sunnyland@gmail.com', 'monday', 'sunday', 0, 'Sunnyland is a beautiful............................................jklgyskjaehakveshklvjeskjflkeshbhkeshjfkjeshkjfbhesbfkesbkjghsjlfkjesjheslhgjeahjkhakjfjkgdsghsdjskghkshgsrghsrsoggokpsdjgpsjpsro', 0, 0, 27, 0, 'sunnyland.jpg', NULL, b'1'),
(60, 'Vijećnica', 'Obala Kulina Bana', '063/353-755', '08:00:00', '17:00:00', 2, 'www.vijecnica.ba', 'vjsa@gmail.com', 'monday', 'friday', 0, 'Vijecnica, a heart of Sarajevo, rebuilt. Ahdgjabjwkjgjsjkjgjseklgkleklghaeglahgjagoaghoihgoihhaojaogjihoaghoihoesitgjeuigjioujpogjiohesigejojiofhjshfuihaeoifuiotesrjopjarpjzspihrsprijrgijs', 0, 0, 27, 0, 'vijecnica.jpg', NULL, b'1'),
(61, 'Zemaljski muzej', 'Zmaja od Bosne', '061/425-414', '09:00:00', '16:00:00', 1, 'www.zemuzej.com', 'zmuzej@gmail.com', 'monday', 'saturday', 0, 'Zemaljski muzej as one of the oldest museums in Bosnia and Herzegovina. jhgdosjlgjajkjfeeskhrkjfklsrngjneskjjfasfesrhfnhehajfekheskjfeskhghehfbbjsegvfjesghtkjgbjgeshjgesh', 0, 0, 27, 0, 'zemuzej.jpg', NULL, b'1'),
(62, 'Sebilj', 'Bascarsija', '065/942-412', '00:00:00', '00:00:00', 1, 'www.sebilj.ba', 'sebilj@hotmail.com', 'monday', 'sunday', 0, 'Sebilj, sight placed in the heart of Bascarsija.hgeighkjleshngioeshoifhesjkhghksheghkhdjkrgkshkgsrjkhkghskjhjsfkeagjkfhajkgegfhahkjfkjajgakgjahkghaghjakgahgka', 0, 0, 27, 0, 'seb.jpg', NULL, b'1'),
(63, 'Sarajevo tunel', 'Čekaluša 61', '062/847-433', '08:00:00', '16:00:00', 1, 'www.tunel.com', 'tunel@gmail.com', 'monday', 'friday', 0, 'Tunnel..ijsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjrsdodjgugrjgjr', 0, 0, 27, 0, 'tunel.jpg', NULL, b'1'),
(64, 'Gazi-Husrev Begova džamija', 'Hrvatin bb', '061/466-435', '00:00:00', '00:00:00', 1, 'www.ghbdzamija.ba', 'ghb@gmail.com', 'monday', 'sunday', 0, 'ejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjdejtlrjgorjd', 0, 0, 27, 0, 'begdz.jpg', NULL, b'1'),
(65, 'Hotel Hills', 'Čekaluša 61', '062/345-456', '00:00:00', '00:00:00', 3, 'www.hotelhills.com', 'hotelhills@gmail.com', 'monday', 'sunday', 0, 'lrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessiljlrjdijjessilj', 0, 0, 27, 0, 'hotelhills.jpg', 5, b'1'),
(66, 'Hotel Europe', 'Kolodvorska 1', '063/345-457', '00:00:00', '00:00:00', 3, 'www.hoteleurope.com', 'hoteleurope@gmail.com', 'monday', 'sunday', 0, 'kdfigdgiljdxrlgjljdlgjsodgdj', 0, 0, 27, 0, 'hoteleurope.jpg', NULL, b'1'),
(67, 'Hotel Marriot', 'Kolodvorska 1', '063/345-452', '00:00:00', '00:00:00', 3, 'www.marriot.com', 'marriot@gmail.com', 'monday', 'sunday', 0, 'dkjshfehstogiruodiuzesotpogesjojdupusgpjseopjgp', 0, 0, 27, 0, 'marriot.jpg', NULL, b'1'),
(68, 'Swissotel', 'Hrvatin bb', '063/353-752', '00:00:00', '00:00:00', 3, 'www.swissotel.com', 'swissotel@gmail.com', 'monday', 'sunday', 0, 'ldsjgltsjsjdkfkjesbkjfefhkwehtkrhieiowr', 0, 0, 27, 0, 'swissotel.jpg', NULL, b'1'),
(69, 'Hotel Hollywood', 'Kolodvorska 1', '063/353-753', '00:00:00', '00:00:00', 2, 'www.hollywood.com', 'hollywood@gmail.com', 'monday', 'sunday', 0, 'rkgmkleruuhdgrdgkherkihgio', 0, 0, 27, 0, 'hollywood.jpg', NULL, b'1'),
(70, 'Holiday Inn', 'Kolodvorska 1', '063/345-452', '00:00:00', '00:00:00', 3, 'www.holidayinn.com', 'holidayinn@gmail.com', 'monday', 'sunday', 0, 'fkdlerjoej4zojerzlreklter', 0, 0, 27, 0, 'holidayinn.jpg', NULL, b'1'),
(71, 'Regina', 'Kolodvorska 1', '063/345-444', '07:00:00', '23:00:00', 2, 'www.regina.ba', 'regina@gmail.com', 'monday', 'sunday', 0, 'lkdgjlrjtlgjesljgdjgjsdgijidjgdpsoegptse', 0, 1, 27, 0, 'regina.jpg', NULL, b'1'),
(72, 'Superfood', 'Kolodvorska 1', '062/459-122', '08:00:00', '23:00:00', 3, 'www.superfood.ba', 'superfood@gmail.com', 'monday', 'sunday', 0, 'kjjhkhkgukhukhkhhhiuuzglojl', 0, 1, 27, 1, 'superfood.jpg', 4, b'1'),
(73, 'Rafting na Željeznici', 'Kolodvorska 1', '063/345-422', '08:00:00', '17:00:00', 2, 'www.raftingnauni.com', 'raftingnauni@gmail.com', 'monday', 'sunday', 0, 'lksjgdlijdlitgjtlkjdglsjdigljerlkojsdgldjgl', 0, 0, 27, 0, 'raftinguna.jpg', NULL, b'1'),
(74, 'Quad Bjelašnica', 'Bjela bb', '063/345-122', '06:00:00', '16:00:00', 3, 'www.quadbj.com', 'quadbjel@gmail.com', 'friday', 'sunday', 0, 'lksjgdlijdlitgjtlkjdglsjdigljerlkojsdgldjglkgjdsljgejgiejskjglkewkkgjewlhflewhsklhwekljhjewhwfkjewjelgsjkdghjesgfjefegkfgaekfhaegkgae', 0, 0, 27, 0, 'quad.jpg', NULL, b'1'),
(75, 'Fortica Zipline', 'Fortica bb', '061/315-312', '08:00:00', '20:00:00', 3, 'www.fortica.ba', 'fortica@gmail.com', 'thursday', 'sunday', 0, 'iughieoifpoejshhkfhiehsofpoejahgbkjlrjhejlhfiopsegbslfiehjfplijeshjlifhesjfkjeilguflewjfhhgrjsghkfewghiofhesoige', 0, 0, 27, 0, 'fortica.jpg', NULL, b'1'),
(76, 'Intermezzo Ilidža', 'Mala Aleja bb', '061/158-738', '08:00:00', '23:00:00', 1, 'www.intermezzoJe.com', 'intermezzoforver@hotmail.com', 'monday', 'sunday', 0, 'Intermezzo Ilidza, with you since 1999.........rjisehfeuisgjsehifuherawuihgfghegfuegifgaeigfiuafgiawjk', 0, 0, 27, 0, 'int.jfif', NULL, b'1'),
(77, 'Fabrika', 'Ferhadija bb', '061/213-414', '08:00:00', '00:00:00', 2, 'www.fabrikasa.com', 'fabrikasa@hotmail.com', 'monday', 'sunday', 0, 'Fabrika, placed in one of main streets...hgaihfjpawkjhfjaehaiohesjiohjiajgenjsekjbesjfkjjkjfkhkejjfjkesjghsekjgesjkjgoesjijgspjespjko', 0, 0, 27, 0, 'fabrika.jpg', NULL, b'1'),
(78, 'Taverna', 'Kolodvorska 10', '062/418-656', '10:00:00', '23:00:00', 2, 'www.taverna.com', 'tavsa@gmail.com', 'monday', 'saturday', 0, 'fhesfiufhesuhfishzeirhiueszriuehsuirgaueiriuzaeuruuieaoriueaitoheaopihtpoitehtpiaehpirhaeiptijaeouiruioeautioeuaiotuoaehothaeiehioraehtipaehiothaeghtoihaeutheauohtuoaehitoghitaeutioaetihotgo', 0, 0, 27, 0, 'tav.jfif', NULL, b'1');
-- --------------------------------------------------------
--
-- Table structure for table `objecttype`
--
CREATE TABLE `objecttype` (
`oid` int(11) NOT NULL,
`type` int(11) DEFAULT NULL,
`object` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `objecttype`
--
INSERT INTO `objecttype` (`oid`, `type`, `object`) VALUES
(42, 5, 41),
(46, 5, 45),
(48, 5, 46),
(60, 3, 57),
(62, 3, 58),
(63, 3, 59),
(64, 4, 59),
(65, 5, 59),
(66, 6, 59),
(67, 4, 60),
(68, 4, 61),
(69, 4, 62),
(70, 4, 63),
(71, 4, 64),
(72, 2, 65),
(75, 2, 66),
(76, 2, 67),
(77, 2, 68),
(78, 2, 69),
(79, 2, 70),
(81, 5, 71),
(83, 5, 72),
(84, 3, 73),
(85, 3, 74),
(86, 3, 75),
(87, 7, 76),
(88, 8, 77),
(89, 9, 78);
-- --------------------------------------------------------
--
-- Stand-in structure for view `top_10_places`
-- (See below for the actual view)
--
CREATE TABLE `top_10_places` (
`oid` int(11)
,`name` varchar(255)
,`street` varchar(255)
,`start_day` varchar(20)
,`close_day` varchar(20)
,`opening_hours` time
,`closing_hours` time
,`phone` varchar(20)
,`webpage` varchar(255)
,`image` varchar(255)
,`active` bit(1)
);
-- --------------------------------------------------------
--
-- Table structure for table `type`
--
CREATE TABLE `type` (
`tid` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`supertype` int(11) DEFAULT NULL,
`picture` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `type`
--
INSERT INTO `type` (`tid`, `name`, `supertype`, `picture`) VALUES
(1, 'Catering', NULL, 'images/catering'),
(2, 'Accommodation', NULL, 'images/accommodation'),
(3, 'Adventure', NULL, 'images/adventure'),
(4, 'Sights', NULL, 'images/sights'),
(5, 'Restaurants', 1, NULL),
(6, 'Coffee bars', 1, NULL),
(7, 'Desert Shops', 1, NULL),
(8, 'Pubs', 1, NULL),
(9, 'Winery', 1, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`uid` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`surname` varchar(100) NOT NULL,
`email` varchar(255) NOT NULL,
`phone` varchar(20) DEFAULT NULL,
`dob` date NOT NULL,
`image` varchar(255) DEFAULT NULL,
`gender` varchar(6) DEFAULT NULL,
`username` varchar(30) NOT NULL,
`active` bit(1) NOT NULL DEFAULT b'1',
`password` varchar(50) NOT NULL,
`city` int(11) NOT NULL,
`admin` bit(1) NOT NULL DEFAULT b'0',
`startdate` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`uid`, `name`, `surname`, `email`, `phone`, `dob`, `image`, `gender`, `username`, `active`, `password`, `city`, `admin`, `startdate`) VALUES
(32, 'Azra', 'Kurtic', 'azrakurtic@gmail.com', '062561849', '2021-05-31', 'Adriana-Lima.jpg', 'female', 'azrak', b'1', '2450a8e9a4eeebbd95e18852119ea635f71c1c1f', 27, b'1', '2021-06-11'),
(33, 'Adna', 'Salkovic', 'adnas@gmail.com', '062561849', '2021-06-01', '', 'female', 'adnas', b'1', 'da52bd1f555a79073d28149a774ecc39f35f7d55', 27, b'0', '2021-06-11'),
(34, 'Faris', 'Begic', 'fabegic@gmail.com', '062/459-199', '2021-06-01', '', 'male', 'begicfa', b'1', '356a192b7913b04c54574d18c28d46e6395428ab', 24, b'0', '2021-06-13'),
(35, 'Chipas', 'Begic', 'azrak@gmail.com', '062/459-199', '2021-06-09', '', 'male', 'mujohamz', b'1', '6eb140bafa7b836fe8c2399211be75ad61bea5c5', 24, b'0', '2021-06-13');
--
-- Triggers `user`
--
DELIMITER $$
CREATE TRIGGER `date_check` BEFORE INSERT ON `user` FOR EACH ROW BEGIN
DECLARE msg varchar(255);
IF NEW.dob > CURDATE() THEN
SET msg = 'INVALID DATE, Date from future';
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg;
END IF;
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `user_start_date_trg` BEFORE INSERT ON `user` FOR EACH ROW BEGIN
set NEW.startdate = SYSDATE();
END
$$
DELIMITER ;
-- --------------------------------------------------------
--
-- Table structure for table `userfavorites`
--
CREATE TABLE `userfavorites` (
`fid` int(11) NOT NULL,
`user` int(11) DEFAULT NULL,
`object` int(11) DEFAULT NULL,
`date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `userfavorites`
--
INSERT INTO `userfavorites` (`fid`, `user`, `object`, `date`) VALUES
(37, 32, 41, '2021-06-14');
--
-- Triggers `userfavorites`
--
DELIMITER $$
CREATE TRIGGER `user_fav_date_trg` BEFORE INSERT ON `userfavorites` FOR EACH ROW BEGIN
set NEW.date = SYSDATE();
END
$$
DELIMITER ;
-- --------------------------------------------------------
--
-- Table structure for table `userratings`
--
CREATE TABLE `userratings` (
`uid` int(11) NOT NULL,
`user` int(11) DEFAULT NULL,
`object` int(11) DEFAULT NULL,
`rating` double DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `userratings`
--
INSERT INTO `userratings` (`uid`, `user`, `object`, `rating`) VALUES
(51, 32, 65, 5),
(52, 32, 72, 4),
(53, 32, 41, 2);
--
-- Triggers `userratings`
--
DELIMITER $$
CREATE TRIGGER `user_rating_ins_trg` AFTER INSERT ON `userratings` FOR EACH ROW BEGIN
UPDATE object SET averagerating = (SELECT AVG(rating) FROM userratings WHERE oid = object);
END
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER `user_rating_upd_trg` AFTER UPDATE ON `userratings` FOR EACH ROW BEGIN
UPDATE object SET averagerating = (SELECT AVG(rating) FROM userratings WHERE oid = object);
END
$$
DELIMITER ;
-- --------------------------------------------------------
--
-- Structure for view `active_users`
--
DROP TABLE IF EXISTS `active_users`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `active_users` AS SELECT `user`.`uid` AS `uid`, `user`.`name` AS `name`, `user`.`surname` AS `surname`, `user`.`username` AS `username`, `user`.`email` AS `email`, `user`.`startdate` AS `startdate` FROM `user` WHERE `user`.`active` = 1 ;
-- --------------------------------------------------------
--
-- Structure for view `fav_objects`
--
DROP TABLE IF EXISTS `fav_objects`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `fav_objects` AS SELECT `uf`.`object` AS `objectid`, `o`.`name` AS `object`, count(`uf`.`object`) AS `favnum` FROM ((`object` `o` join `user` `u`) join `userfavorites` `uf`) WHERE `o`.`oid` = `uf`.`object` AND `u`.`uid` = `uf`.`user` AND (NULL is null OR cast(`u`.`startdate` as date) >= NULL) AND (NULL is null OR cast(`u`.`startdate` as date) <= NULL) AND `o`.`active` = 1 GROUP BY `uf`.`object` ;
-- --------------------------------------------------------
--
-- Structure for view `most_active_users`
--
DROP TABLE IF EXISTS `most_active_users`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `most_active_users` AS SELECT `userratings`.`user` AS `user`, `GetUserName`(`userratings`.`user`) AS `GetUserName(user)`, count(0) AS `favno` FROM (`userratings` join `user`) WHERE `user`.`uid` = `userratings`.`user` AND `user`.`active` = 1 GROUP BY `GetUserName`(`userratings`.`user`) ORDER BY 2 DESC ;
-- --------------------------------------------------------
--
-- Structure for view `top_10_places`
--
DROP TABLE IF EXISTS `top_10_places`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `top_10_places` AS SELECT `o`.`oid` AS `oid`, `o`.`name` AS `name`, `o`.`street` AS `street`, `o`.`start_day` AS `start_day`, `o`.`close_day` AS `close_day`, `o`.`opening_hours` AS `opening_hours`, `o`.`closing_hours` AS `closing_hours`, `o`.`phone` AS `phone`, `o`.`webpage` AS `webpage`, `o`.`image` AS `image`, `o`.`active` AS `active` FROM (`object` `o` join `city` `c`) WHERE `o`.`city` = `c`.`cid` AND `o`.`active` = 1 ORDER BY `o`.`averagerating` DESC LIMIT 0, 6 ;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `city`
--
ALTER TABLE `city`
ADD PRIMARY KEY (`cid`),
ADD KEY `city_country_cid_fk` (`Country`);
--
-- Indexes for table `country`
--
ALTER TABLE `country`
ADD PRIMARY KEY (`cid`);
--
-- Indexes for table `object`
--
ALTER TABLE `object`
ADD PRIMARY KEY (`oid`),
ADD KEY `City` (`city`),
ADD KEY `obj_name_ind` (`name`),
ADD KEY `obj_pricing_ind` (`pricing`);
--
-- Indexes for table `objecttype`
--
ALTER TABLE `objecttype`
ADD PRIMARY KEY (`oid`),
ADD KEY `Object` (`object`),
ADD KEY `Type` (`type`);
--
-- Indexes for table `type`
--
ALTER TABLE `type`
ADD PRIMARY KEY (`tid`),
ADD KEY `Supertype` (`supertype`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`uid`),
ADD KEY `user_city_cid_fk` (`city`),
ADD KEY `user_name_ind` (`name`),
ADD KEY `user_surname_ind` (`surname`);
--
-- Indexes for table `userfavorites`
--
ALTER TABLE `userfavorites`
ADD PRIMARY KEY (`fid`),
ADD KEY `UserFavorites_object_oid_fk` (`object`),
ADD KEY `UserFavorites_user_uid_fk` (`user`);
--
-- Indexes for table `userratings`
--
ALTER TABLE `userratings`
ADD PRIMARY KEY (`uid`),
ADD UNIQUE KEY `unq_rating` (`user`,`object`),
ADD KEY `UserRatings_object_oid_fk` (`object`),
ADD KEY `UserRatings_user_uid_fk` (`user`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `city`
--
ALTER TABLE `city`
MODIFY `cid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=33;
--
-- AUTO_INCREMENT for table `country`
--
ALTER TABLE `country`
MODIFY `cid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `object`
--
ALTER TABLE `object`
MODIFY `oid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=80;
--
-- AUTO_INCREMENT for table `objecttype`
--
ALTER TABLE `objecttype`
MODIFY `oid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=93;
--
-- AUTO_INCREMENT for table `type`
--
ALTER TABLE `type`
MODIFY `tid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=36;
--
-- AUTO_INCREMENT for table `userfavorites`
--
ALTER TABLE `userfavorites`
MODIFY `fid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=38;
--
-- AUTO_INCREMENT for table `userratings`
--
ALTER TABLE `userratings`
MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=54;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `city`
--
ALTER TABLE `city`
ADD CONSTRAINT `city_country_cid_fk` FOREIGN KEY (`Country`) REFERENCES `country` (`cid`);
--
-- Constraints for table `object`
--
ALTER TABLE `object`
ADD CONSTRAINT `City` FOREIGN KEY (`city`) REFERENCES `city` (`cid`);
--
-- Constraints for table `objecttype`
--
ALTER TABLE `objecttype`
ADD CONSTRAINT `Object` FOREIGN KEY (`object`) REFERENCES `object` (`oid`),
ADD CONSTRAINT `Type` FOREIGN KEY (`type`) REFERENCES `type` (`tid`);
--
-- Constraints for table `type`
--
ALTER TABLE `type`
ADD CONSTRAINT `Supertype` FOREIGN KEY (`supertype`) REFERENCES `type` (`tid`);
--
-- Constraints for table `user`
--
ALTER TABLE `user`
ADD CONSTRAINT `user_city_cid_fk` FOREIGN KEY (`city`) REFERENCES `city` (`cid`);
--
-- Constraints for table `userfavorites`
--
ALTER TABLE `userfavorites`
ADD CONSTRAINT `UserFavorites_object_oid_fk` FOREIGN KEY (`object`) REFERENCES `object` (`oid`),
ADD CONSTRAINT `UserFavorites_user_uid_fk` FOREIGN KEY (`user`) REFERENCES `user` (`uid`);
--
-- Constraints for table `userratings`
--
ALTER TABLE `userratings`
ADD CONSTRAINT `UserRatings_object_oid_fk` FOREIGN KEY (`object`) REFERENCES `object` (`oid`),
ADD CONSTRAINT `UserRatings_user_uid_fk` FOREIGN KEY (`user`) REFERENCES `user` (`uid`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Shell | UTF-8 | 2,317 | 3.078125 | 3 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #!/bin/bash
# Licensed under the Apache License, Version 2.0 or the MIT License.
# SPDX-License-Identifier: Apache-2.0 OR MIT
# Copyright Tock Contributors 2023.
BUILD_DIR="verilator_build/"
# Preemptively cleanup layout (incase this was a test) so that following apps (non-tests) load the correct layout.
rm $TOCK_ROOT_DIRECTORY/target/$TARGET/release/deps/layout.ld
if [[ "${VERILATOR}" == "yes" ]]; then
if [ -d "$BUILD_DIR" ]; then
# Cleanup before we build again
printf "\n[CW-130: Verilator Tests]: Cleaning up verilator_build...\n\n"
rm -R "$BUILD_DIR"/*
else
printf "\n[CW-130: Verilator Tests]: Setting up verilator_build...\n\n"
mkdir "$BUILD_DIR"
fi
# Copy in and covert from cargo test output to binary
${OBJCOPY} ${1} "$BUILD_DIR"/earlgrey-cw310-tests.elf
if [[ "${APP}" != "" ]]; then
# An app was specified, copy it in
printf "[CW-130: Verilator Tests]: Linking APP\n\n"
${OBJCOPY} --update-section .apps=${APP} "$BUILD_DIR"/earlgrey-cw310-tests.elf "$BUILD_DIR"/earlgrey-cw310-tests.elf
fi
${OBJCOPY} --output-target=binary "$BUILD_DIR"/earlgrey-cw310-tests.elf "$BUILD_DIR"/earlgrey-cw310-tests.bin
# Create VMEM file from test binary
srec_cat "$BUILD_DIR"/earlgrey-cw310-tests.bin\
--binary --offset 0 --byte-swap 8 --fill 0xff \
-within "$BUILD_DIR"/earlgrey-cw310-tests.bin\
-binary -range-pad 8 --output "$BUILD_DIR"/binary.64.vmem --vmem 64
${OPENTITAN_TREE}/bazel-bin/hw/build.verilator_real/sim-verilator/Vchip_sim_tb \
--meminit=rom,${OPENTITAN_TREE}/bazel-out/k8-fastbuild-ST-2cc462681f62/bin/sw/device/lib/testing/test_rom/test_rom_sim_verilator.39.scr.vmem \
--meminit=flash0,./"$BUILD_DIR"/binary.64.vmem \
--meminit=otp,${OPENTITAN_TREE}/bazel-out/k8-fastbuild/bin/hw/ip/otp_ctrl/data/img_rma.24.vmem
elif [[ "${OPENTITAN_TREE}" != "" ]]; then
${OBJCOPY} --update-section .apps=${APP} ${1} bundle.elf
${OBJCOPY} --output-target=binary bundle.elf binary
${OPENTITAN_TREE}/bazel-bin/sw/host/opentitantool/opentitantool.runfiles/lowrisc_opentitan/sw/host/opentitantool/opentitantool --interface=cw310 bootstrap binary
else
../../../tools/qemu/build/qemu-system-riscv32 -M opentitan -nographic -serial stdio -monitor none -semihosting -kernel "${1}" -global driver=riscv.lowrisc.ibex.soc,property=resetvec,value=${QEMU_ENTRY_POINT}
fi
|
Java | UTF-8 | 1,160 | 2.0625 | 2 | [] | no_license | package com.service.goods.service;
import com.github.pagehelper.PageInfo;
import com.goods.pojo.Brand;
import java.util.List;
/**
* @Author: huangzhigao
* @Date: 2020/3/29 14:14
*/
public interface BrandService {
/**
* 查询所有品牌
*
* @return
*/
List<Brand> findAllBrand();
/**
* 根据ID查询品牌
*
* @param id
* @return
*/
Brand findBrandById(Integer id);
/**
* 根据品牌查询
*
* @return
*/
List<Brand> findByBrand(Brand brand);
/**
* 分页查询
*
* @param pageNum 当前页
* @param pageSize 每页大小
* @return
*/
PageInfo<Brand> findByPage(Integer pageNum, Integer pageSize);
/**
* 分页+自定义查询
*
* @param brand
* @param pageNum
* @param pageSize
* @return
*/
PageInfo<Brand> findByExamplePage(Brand brand, Integer pageNum, Integer pageSize);
/**
* 增加品牌
*
* @param brand
*/
void addBrand(Brand brand);
/**
* 修改品牌
*
* @param brand
*/
void updateBrand(Brand brand);
}
|
Markdown | UTF-8 | 853 | 3.359375 | 3 | [
"MIT"
] | permissive | ### 序列化和反序列化二叉搜索树 ###
序列化是将数据结构或对象转换为一系列位的过程,以便它可以存储在文件或内存缓冲区中,或通过网络连接链路传输,以便稍后在同一个或另一个计算机环境中重建。
设计一个算法来序列化和反序列化** 二叉搜索树** 。 对序列化/反序列化算法的工作方式没有限制。 您只需确保二叉搜索树可以序列化为字符串,并且可以将该字符串反序列化为最初的二叉搜索树。
**编码的字符串应尽可能紧凑。**
**示例 1:**
```
输入:root = [2,1,3]
输出:[2,1,3]
```
**示例 2:**
```
输入:root = []
输出:[]
```
**提示:**
* 树中节点数范围是 `[0, 104]`
* `0 <= Node.val <= 104`
* 题目数据 **保证** 输入的树是一棵二叉搜索树。
|
Java | UTF-8 | 922 | 2.453125 | 2 | [] | no_license | package com.lv.dao;
import com.lv.model.User;
import java.util.List;
/**
* 定义有关users数据表有关的操作方法
*
* @author lv
*/
public interface UserDao {
/**
* 插入一条数据
*
* @param user
* @return
*/
public int save(User user);
/**
* 根据用户id删除对应的用户数据
*
* @param id
* @return
*/
public int deleteUserById(int id);
/**
* 根据用户id修改对应的用户数据
*
* @param user
* @return
*/
public int updateUserById(User user);
/**
* 根据用户编号获取一条用户数据,封装成User的一个对象
* 不支持事务
*
* @param id
* @return
*/
public User get(int id);
/**
* 获取所有的用户数据
*
* @return
*/
public List<User> getListAll();
/**
* 查询指定用户名的用户有多少条
*
* @param username
* @return
*/
public long getCountByName(String username);
}
|
Java | UTF-8 | 752 | 2.1875 | 2 | [] | no_license | package de.fisgmbh.tgh.applman.odata;
import java.util.HashMap;
import java.util.Map;
public class EdmTypeEntityApplication extends EdmTypeEntityJPAStandard {
private static final String ET_NAME = "Application";
private static Map<String, String> customPropertyNames;
static {
customPropertyNames = new HashMap<>();
customPropertyNames.put("CommentDetails", "Comments");
customPropertyNames.put("DocumentDetails", "Documents");
customPropertyNames.put("PositionDetails", "Positions");
customPropertyNames.put("SourceDetails", "Sources");
}
public EdmTypeEntityApplication() {
super(ET_NAME);
}
@Override
protected Map<String, String> getCustomPropertyNames() {
return customPropertyNames;
}
}
|
JavaScript | UTF-8 | 481 | 4.125 | 4 | [] | no_license | const first = 2;
const second = 2;
if (first == second){
console.log(" first-second variable 'double equal' condition is true");
}
else {
console.log("first-second variable 'double equal' condition is false");
}
///////
const firstExample = 14;
const secondExample = "14";
if (firstExample === secondExample){
console.log("firstExample-secondExample variable condition is true");
}
else {
console.log("firstExample-secondExample variable condition is false")
}
|
Python | UTF-8 | 11,126 | 2.65625 | 3 | [] | no_license | # ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function
from future.builtins import range
import six
from six import BytesIO
import unittest
from tempfile import NamedTemporaryFile, mkdtemp
from os.path import exists, join
from shutil import rmtree
from uuid import uuid4
from skbio.util import (cardinal_to_ordinal, safe_md5, remove_files,
create_dir, find_duplicates, is_casava_v180_or_later)
from skbio.util._misc import (
_handle_error_codes, MiniRegistry, chunk_str, resolve_key)
class TestMiniRegistry(unittest.TestCase):
def setUp(self):
self.registry = MiniRegistry()
def test_decoration(self):
self.assertNotIn("name1", self.registry)
self.assertNotIn("name2", self.registry)
self.n1_called = False
self.n2_called = False
@self.registry("name1")
def some_registration1():
self.n1_called = True
@self.registry("name2")
def some_registration2():
self.n2_called = True
self.assertIn("name1", self.registry)
self.assertEqual(some_registration1, self.registry["name1"])
self.assertIn("name2", self.registry)
self.assertEqual(some_registration2, self.registry["name2"])
self.registry["name1"]()
self.assertTrue(self.n1_called)
self.registry["name2"]()
self.assertTrue(self.n2_called)
def test_copy(self):
@self.registry("name")
def some_registration():
pass
new = self.registry.copy()
self.assertIsNot(new, self.registry)
@new("other")
def other_registration():
pass
self.assertIn("name", self.registry)
self.assertNotIn("other", self.registry)
self.assertIn("other", new)
self.assertIn("name", new)
def test_everything(self):
class SomethingToInterpolate(object):
def interpolate_me():
"""First line
Some description of things, also this:
Other things are happening now.
"""
def dont_interpolate_me():
"""First line
Some description of things, also this:
Other things are happening now.
"""
class Subclass(SomethingToInterpolate):
pass
@self.registry("a")
def a():
"""x"""
@self.registry("b")
def b():
"""y"""
@self.registry("c")
def c():
"""z"""
subclass_registry = self.registry.copy()
@subclass_registry("o")
def o():
"""p"""
self.registry.interpolate(SomethingToInterpolate, "interpolate_me")
subclass_registry.interpolate(Subclass, "interpolate_me")
self.assertEqual(SomethingToInterpolate.interpolate_me.__doc__,
"First line\n\n Some description of th"
"ings, also this:\n\n\t'a'\n\t x\n\t'b'\n\t y\n\t'c"
"'\n\t z\n\n Other things are happeni"
"ng now.\n ")
self.assertEqual(SomethingToInterpolate.dont_interpolate_me.__doc__,
"First line\n\n Some description of th"
"ings, also this:\n\n Other things are"
" happening now.\n ")
self.assertEqual(Subclass.interpolate_me.__doc__,
"First line\n\n Some description of th"
"ings, also this:\n\n\t'a'\n\t x\n\t'b'\n\t y\n\t'c"
"'\n\t z\n\t'o'\n\t p\n\n Other thin"
"gs are happening now.\n ")
self.assertEqual(Subclass.dont_interpolate_me.__doc__,
"First line\n\n Some description of th"
"ings, also this:\n\n Other things are"
" happening now.\n ")
class ResolveKeyTests(unittest.TestCase):
def test_callable(self):
def func(x):
return str(x)
self.assertEqual(resolve_key(1, func), "1")
self.assertEqual(resolve_key(4, func), "4")
def test_index(self):
class MetadataHaver(dict):
metadata = {}
@property
def metadata(self):
return self
obj = MetadataHaver({'foo': 123})
self.assertEqual(resolve_key(obj, 'foo'), 123)
obj = MetadataHaver({'foo': 123, 'bar': 'baz'})
self.assertEqual(resolve_key(obj, 'bar'), 'baz')
def test_wrong_type(self):
with self.assertRaises(TypeError):
resolve_key({'foo': 1}, 'foo')
class ChunkStrTests(unittest.TestCase):
def test_even_split(self):
self.assertEqual(chunk_str('abcdef', 6, ' '), 'abcdef')
self.assertEqual(chunk_str('abcdef', 3, ' '), 'abc def')
self.assertEqual(chunk_str('abcdef', 2, ' '), 'ab cd ef')
self.assertEqual(chunk_str('abcdef', 1, ' '), 'a b c d e f')
self.assertEqual(chunk_str('a', 1, ' '), 'a')
self.assertEqual(chunk_str('abcdef', 2, ''), 'abcdef')
def test_no_split(self):
self.assertEqual(chunk_str('', 2, '\n'), '')
self.assertEqual(chunk_str('a', 100, '\n'), 'a')
self.assertEqual(chunk_str('abcdef', 42, '|'), 'abcdef')
def test_uneven_split(self):
self.assertEqual(chunk_str('abcdef', 5, '|'), 'abcde|f')
self.assertEqual(chunk_str('abcdef', 4, '|'), 'abcd|ef')
self.assertEqual(chunk_str('abcdefg', 3, ' - '), 'abc - def - g')
def test_invalid_n(self):
with six.assertRaisesRegex(self, ValueError, 'n=0'):
chunk_str('abcdef', 0, ' ')
with six.assertRaisesRegex(self, ValueError, 'n=-42'):
chunk_str('abcdef', -42, ' ')
class MiscTests(unittest.TestCase):
def setUp(self):
self.dirs_to_remove = []
def tearDown(self):
for element in self.dirs_to_remove:
rmtree(element)
def test_is_casava_v180_or_later(self):
self.assertFalse(is_casava_v180_or_later(b'@foo'))
id_ = b'@M00176:17:000000000-A0CNA:1:1:15487:1773 1:N:0:0'
self.assertTrue(is_casava_v180_or_later(id_))
with self.assertRaises(ValueError):
is_casava_v180_or_later(b'foo')
def test_safe_md5(self):
exp = 'ab07acbb1e496801937adfa772424bf7'
fd = BytesIO(b'foo bar baz')
obs = safe_md5(fd)
self.assertEqual(obs.hexdigest(), exp)
fd.close()
def test_remove_files(self):
# create list of temp file paths
test_fds = [NamedTemporaryFile(delete=False) for i in range(5)]
test_filepaths = [element.name for element in test_fds]
# should work just fine
remove_files(test_filepaths)
# check that an error is raised on trying to remove the files...
self.assertRaises(OSError, remove_files, test_filepaths)
# touch one of the filepaths so it exists
extra_file = NamedTemporaryFile(delete=False).name
test_filepaths.append(extra_file)
# no error is raised on trying to remove the files
# (although 5 don't exist)...
remove_files(test_filepaths, error_on_missing=False)
# ... and the existing file was removed
self.assertFalse(exists(extra_file))
# try to remove them with remove_files and verify that an IOError is
# raises
self.assertRaises(OSError, remove_files, test_filepaths)
# now get no error when error_on_missing=False
remove_files(test_filepaths, error_on_missing=False)
def test_create_dir(self):
# create a directory
tmp_dir_path = mkdtemp()
# create a random temporary directory name
tmp_dir_path2 = join(mkdtemp(), str(uuid4()))
tmp_dir_path3 = join(mkdtemp(), str(uuid4()))
self.dirs_to_remove += [tmp_dir_path, tmp_dir_path2, tmp_dir_path3]
# create on existing dir raises OSError if fail_on_exist=True
self.assertRaises(OSError, create_dir, tmp_dir_path,
fail_on_exist=True)
self.assertEqual(create_dir(tmp_dir_path, fail_on_exist=True,
handle_errors_externally=True), 1)
# return should be 1 if dir exist and fail_on_exist=False
self.assertEqual(create_dir(tmp_dir_path, fail_on_exist=False), 1)
# if dir not there make it and return always 0
self.assertEqual(create_dir(tmp_dir_path2), 0)
self.assertEqual(create_dir(tmp_dir_path3, fail_on_exist=True), 0)
def test_handle_error_codes_no_error(self):
obs = _handle_error_codes('/foo/bar/baz')
self.assertEqual(obs, 0)
class CardinalToOrdinalTests(unittest.TestCase):
def test_valid_range(self):
# taken and modified from http://stackoverflow.com/a/20007730/3776794
exp = ['0th', '1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th',
'9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th',
'17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th',
'25th', '26th', '27th', '28th', '29th', '30th', '31st', '32nd',
'100th', '101st', '42042nd']
obs = [cardinal_to_ordinal(n) for n in
list(range(0, 33)) + [100, 101, 42042]]
self.assertEqual(obs, exp)
def test_invalid_n(self):
with six.assertRaisesRegex(self, ValueError, '-1'):
cardinal_to_ordinal(-1)
class TestFindDuplicates(unittest.TestCase):
def test_empty_input(self):
def empty_gen():
raise StopIteration()
yield
for empty in [], (), '', set(), {}, empty_gen():
self.assertEqual(find_duplicates(empty), set())
def test_no_duplicates(self):
self.assertEqual(find_duplicates(['a', 'bc', 'def', 'A']), set())
def test_one_duplicate(self):
self.assertEqual(find_duplicates(['a', 'bc', 'def', 'a']), set(['a']))
def test_many_duplicates(self):
self.assertEqual(find_duplicates(['a', 'bc', 'bc', 'def', 'a']),
set(['a', 'bc']))
def test_all_duplicates(self):
self.assertEqual(
find_duplicates(('a', 'bc', 'bc', 'def', 'a', 'def', 'def')),
set(['a', 'bc', 'def']))
def test_mixed_types(self):
def gen():
for e in 'a', 1, 'bc', 2, 'a', 2, 2, 3.0:
yield e
self.assertEqual(find_duplicates(gen()), set(['a', 2]))
if __name__ == '__main__':
unittest.main()
|
C++ | UTF-8 | 1,418 | 2.796875 | 3 | [] | no_license | #pragma once
#include "RT1W\textures\texture.h"
#include "RT1W/ray.h"
#include "RT1W\hittables\hittable.h"
#include "RT1W\textures\solid_color.h"
class material
{
public:
// not pure virtual: non enforced interface
virtual color emitted(double u, double v, const point3& p) const
{
return color(0, 0, 0);
}
virtual bool scatter(const ray& r_in, const hit_record& rec, color& attenuation, ray& scattered) const = 0;
};
class diffuse_light : public material
{
public:
diffuse_light(std::shared_ptr<base_texture> a) : emit(a) {}
diffuse_light(color c) : emit(std::make_shared<solid_color>(c)) {}
virtual bool scatter(
const ray& r_in, const hit_record& rec, color& attenuation, ray& scattered
) const override
{
return false;
}
virtual color emitted(double u, double v, const point3& p) const override
{
return emit->value(u, v, p);
}
public:
std::shared_ptr<base_texture> emit;
};
class isotropic : public material
{
public:
isotropic(color c) : albedo(std::make_shared<solid_color>(c)) {}
isotropic(std::shared_ptr<base_texture> a) : albedo(a) {}
virtual bool scatter(
const ray& r_in, const hit_record& rec, color& attenuation, ray& scattered
) const override
{
scattered = ray(rec.p, UtilityManager::instance().random_in_unit_sphere(), r_in.time());
attenuation = albedo->value(rec.u, rec.v, rec.p);
return true;
}
public:
std::shared_ptr<base_texture> albedo;
}; |
Java | UTF-8 | 1,043 | 2.09375 | 2 | [] | no_license | package com.spaceapi.spaceapi.controller;
import com.spaceapi.spaceapi.dto.CompanyDto;
import com.spaceapi.spaceapi.service.CompaniesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/spaceapi")
public class CompaniesController {
@Autowired
CompaniesService companiesService;
@GetMapping("/companies")
public List<CompanyDto> findAll() {
return companiesService.findAll();
}
@GetMapping("/companies/{id}")
public CompanyDto findById(@PathVariable Long id) {
return companiesService.findById(id);
}
// @GetMapping("/companies/{name}")
// public CompanyDto findByName(@PathVariable String name) {
// return companiesService.findByName(name);
// }
}
|
Ruby | UTF-8 | 524 | 3.859375 | 4 | [] | no_license | # Maximum sum such that no two elements are adjacent
# Find maximum possible stolen value from houses
def get_max_val(arr, n)
if(n == 0)
return arr[0]
end
if(n == 1)
return [arr[0], arr[1]].max
end
prev_prev_val = arr[0]
prev_val = [arr[0], arr[1]].max
i = 2
while(i < n)
val = [(arr[i] + prev_prev_val), prev_val].max
prev_prev_val = prev_val
prev_val = val
i += 1
end
[prev_val, prev_prev_val].max
end
arr = [6, 7, 1, 3, 8, 2, 4]
puts get_max_val(arr, arr.length)
|
Java | UTF-8 | 344 | 2.0625 | 2 | [] | no_license | package com.revature.hobbycon.dao;
import com.revature.hobbycon.data.UserData;
public interface UserDAO {
public UserData getUser(String userName, String userPW);
public void createNewUser(UserData nu);
public UserData getHobbyName(String hobbyName);
public UserData setHobbyName();
public void setNewHobby(UserData nh);
}
|
Python | UTF-8 | 472 | 3.25 | 3 | [] | no_license | #bulletPointerAdder.py - Adds Wikipedia bullet points to the start
#of each line of text on the clipboard.
import pyperclip,re
text = pyperclip.paste()
splitter = re.compile('\d:')
#TODO: seperate lines and add starsself.
#Seperate lines and add stars
lines = re.split(splitter,text)
for i in range(len(lines)): #loop through all indexes in the "lines" list
lines[i] = '# ' + lines[i]#add # to each string in "lines" list
text = ''.join(lines)
pyperclip.copy(text)
|
C | UTF-8 | 1,654 | 2.953125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *next;
int *nextval(int n_len,char *n)
{
next=(int *)malloc(sizeof(int)*(n_len+1));
next[1]=0;
int i,j;
i=1;j=0;
while(i<n_len)
{
if(j == 0|| n[i] == n[j])
{
i++;
j++;
if(n[i] == n[j])
{
next[i]=next[j];
}
else
next[i]=j;
}
else
j=next[j];
}
i=1;
while(i<=n_len)
{
printf("%5d ",next[i++]);
}
printf("\n");
return next;
}
int select_sub(char *s,char *m)
{
int i=1,j=1;
while(i<=strlen(s)&&j<=strlen(m))
{
if(j == 0 || s[i] == m[j])
{
i++;
j++;
}
else
{
j=next[j];
}
}
if(j>strlen(m))
return i-strlen(m);
else return 0;
}
int main(int argc,char *argv[])
{
if(argc<3)
{
printf("usage:kmp file string\n");
return -1;
}
next=nextval(strlen(argv[2]),argv[2]);
FILE *fp;
fp=fopen(argv[1],"r");
fseek(fp,0,SEEK_END);
long length=ftell(fp);
printf("file lengt %d\n",length);
fseek(fp,0,SEEK_SET);
int linenum[length];
char *p=(char *)malloc(strlen(argv[2])+1);
memcpy(p+1,argv[2],strlen(argv[2]));
char *s=(char *)malloc(length+1);
s[0]='\n';
char *s1=s+1;
char tmp[1024];
int line=1;
while(fgets(tmp,1024,fp))
{
printf("%d\n",strlen(tmp));
linenum[line++]=strlen(tmp);
memcpy(s1,tmp,strlen(tmp));
s1=s1+strlen(tmp);
}
printf("line:%d\n",line-1);
s1=s;
printf("pos1:%d\n",select_sub(s1,argv[2]));
while(s1 < (s+length))
{
int pos=select_sub(s1,argv[2]);
printf("pos1:%d\n",pos);
if(pos == 0)
break;
s1=s1+pos+strlen(argv[2]);
int linen=1;
while(pos>linenum[linen]&&linenum[linen]!=0)
{
pos-=linenum[linen++];
}
printf("%d--%d\n",linen-1,pos);
}
}
|
C# | UTF-8 | 12,966 | 3.21875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace ProjectHamiltonService.Game
{
public class Puzzles
{
public enum Type
{
Variables,
Conditionals,
Cycles,
Functions
}
public static List<Puzzles> puzzles = new List<Puzzles>
{
new Puzzles {
id = "vars_a1",
type = Type.Variables,
instructions= "Imprime la variable miTexto.\n<b>Nota: Imprimir esta en la sección de texto.</b>",
defaultWorkspaceFilename="vars_a1.xml",
expectedOutput="Hola mundo"
},
new Puzzles
{
id= "vars_a2",
type= Type.Variables,
instructions= "Has que la variable suma sea igual a 4, e imprímela.",
defaultWorkspaceFilename="vars_a2.xml",
expectedOutput="4"
},
new Puzzles
{
id="vars_b1",
type= Type.Variables,
instructions= "Haz una variable llamada miVariable, haz que tome el valor de 7 e imprímela en pantalla.",
expectedOutput="7",
defaultWorkspaceFilename="vars_b1.xml"
},
new Puzzles
{
id="vars_b2",
type=Type.Variables,
instructions="Haz una variable llamada bienvenida y haz que imprima “Hola <i>mi_nombre</i>”",
expectedOutput="Hola *",
defaultWorkspaceFilename="vars_b2.xml"
},
new Puzzles
{
id="vars_c1",
type=Type.Variables,
instructions="Suma x con y. E imprime el resultado.",
expectedOutput="7",
defaultWorkspaceFilename="vars_c1.xml"
},
new Puzzles
{
id="vars_c2",
type=Type.Variables,
instructions="Obten el cuadrado de entrada e imprimelo. <b>Nota: Puedes obtener el cuadrado multiplicando el valor por si mismo</b>",
expectedOutput="4"
},
new Puzzles
{
id="cond_a1",
type=Type.Conditionals,
instructions="Si entrada es verdadero, entonces imprime “Todo bien”. ",
defaultWorkspaceFilename="cond_a1.xml"
},
new Puzzles
{
id="cond_a2",
type=Type.Conditionals,
instructions="Si num es mayor o igual a 7, escribe aprobado. Num es 7, ver qué haya un if y que haya “aprobado” en pantalla.",
defaultWorkspaceFilename="cond_a2.xml"
},
new Puzzles
{
id="cond_b1",
type=Type.Conditionals,
instructions="Si miVariable es mayor a cero has que imprima “Es positivo”, si no imprime “Es negativo”.",
expectedOutput="Es positivo",
defaultWorkspaceFilename="cond_b1.xml"
},
new Puzzles
{
id="cond_b2",
type=Type.Conditionals,
instructions="¡Si calificacion es mayor o igual a 7, escribe “Pasaste!”",
expectedOutput="Pasaste!",
defaultWorkspaceFilename="cond_b2.xml"
},
new Puzzles
{
id="cond_c1",
type=Type.Conditionals,
instructions="Si x es igual a y, entonces imprimir “Es igual”.",
defaultWorkspaceFilename="cond_c1.xml",
expectedOutput=""
},
new Puzzles
{
id="cond_c2",
type=Type.Conditionals,
instructions="Si es entrada es cero imprime “Esta entrada es cero”, si entrada es positiva imprime “Esta entrada es mayor a cero”, si entrada es negativa imprime “Esta entrada es menor a cero”.",
defaultWorkspaceFilename="cond_c2.xml",
expectedOutput="Esta entrada es menor a cero"
},
new Puzzles
{
id="loop_a1",
type=Type.Cycles,
instructions="Imprime los números del 1 al 10. Revisar que tenga un ciclo.",
expectedOutput="1 2 3 4 5 6 7 8 9 10"
},
new Puzzles
{
id="loop_a2",
type=Type.Cycles,
instructions="Imprime 10 veces “Hola”. Revisar que hola este escrito en 10 líneas.",
expectedOutput="Hola Hola Hola Hola Hola Hola Hola Hola Hola Hola"
},
new Puzzles
{
id="loop_b1",
type=Type.Cycles,
instructions="Realiza un programa que imprima todos los dígitos pares del 1 al 10.",
expectedOutput="2 4 6 8 10"
},
new Puzzles
{
id="loop_b2",
type=Type.Cycles,
instructions="Realiza un programa que imprima la tabla de 4. Del 4 al 10.",
expectedOutput="4 8 12 16 20 24 28 32 36 40"
},
new Puzzles
{
id="loop_c1",
type=Type.Cycles,
instructions="Escribe en pantalla los números primos del 1 al 20. Recuerda que si un número se puede dividir entre sí mismo y entre 1 y ninguno otro más entonces es primo, el uno no se considera número primo.",
expectedOutput="2 3 5 7 11 13 17 19"
},
new Puzzles
{
id="loop_c2",
type=Type.Cycles,
instructions="Obtén el factorial de 4. E imprimelo en pantalla. Nota: Factorial es el producto de todos los números enteros positivos desde el uno hasta n, por ejemplo: 2! seria 1 x 2 = 2",
expectedOutput="24"
},
new Puzzles
{
id="func_a1",
instructions="Haz una función llamada suma que acepte dos números y retorna su suma.Revisar que exista función y revisar que la podamos usar.",
type= Type.Functions,
functionsExpected = new List<string>{"suma"},
functionTests = new List<FunctionTest>
{
new FunctionTest
{
functionName="suma",
functionParameters= new List<object> { 2, 2 },
outputResult="4"
}
}
},
new Puzzles
{
id="func_a2",
instructions="Haz una función que se llame max, y retorna el número más grande. Revisar que exista función y que funcione así.",
type= Type.Functions,
functionsExpected = new List<string>{"max"},
functionTests = new List<FunctionTest>
{
new FunctionTest
{
functionName="max",
functionParameters= new List<object> { 2, 4 },
outputResult="4"
}
}
},
new Puzzles
{
id="func_b1",
instructions="Realiza una función se llame bienvenida que acepte una cadena de texto y retorne “Hola, [entrada]”. ",
type= Type.Functions,
functionsExpected = new List<string>{"bienvenida"},
functionTests = new List<FunctionTest>
{
new FunctionTest
{
functionName="bienvenida",
functionParameters= new List<object> { "mundo" },
outputResult="Hola mundo"
}
}
},
new Puzzles
{
id="func_b1",
instructions="Realiza una función se llame bienvenida que acepte una cadena de texto y retorne “Hola, [entrada]”. ",
type= Type.Functions,
functionsExpected = new List<string>{"bienvenida"},
functionTests = new List<FunctionTest>
{
new FunctionTest
{
functionName="bienvenida",
functionParameters= new List<object> { "mundo" },
outputResult="Hola mundo"
}
}
},
new Puzzles
{
id="func_b2",
instructions="Realizar una función que se llame recortar, que acepte tres valores número, mínimo y máximo. El primero es el número a recortar." +
"<ul>" +
"<li>Si es mayor a máximo, retorna máximo</li>" +
"<li>Si es menor a mínimo, retorna mínimo</li>" +
"<li>Si esta entre menor y máximo, retorna el valor</li>" +
"<ul>",
type= Type.Functions,
functionsExpected = new List<string>{"recortar"},
functionTests = new List<FunctionTest>
{
new FunctionTest
{
functionName="recortar",
functionParameters= new List<object> { 6, 1, 4 },
outputResult="4"
},
new FunctionTest
{
functionName="recortar",
functionParameters= new List<object> { -1, 1, 4 },
outputResult="1"
},
new FunctionTest
{
functionName="recortar",
functionParameters= new List<object> { 2, 1, 4 },
outputResult="2"
}
}
},
new Puzzles
{
id="func_c1",
instructions="Haz una función llamada esPrimo que retorne verdadero si es un numero primo y falso si no. Recuerda que si un número se puede dividir entre sí mismo y entre 1 y ninguno otro más entonces es primo, el uno no se considera número primo.",
type= Type.Functions,
functionsExpected = new List<string>{"esPrimo"},
functionTests = new List<FunctionTest>
{
new FunctionTest
{
functionName="esPrimo",
functionParameters= new List<object> { 6 },
outputResult="false"
},
new FunctionTest
{
functionName="esPrimo",
functionParameters= new List<object> { 7 },
outputResult="true"
}
}
},
new Puzzles
{
id="func_c2",
instructions="• Haz una función que se llame areaRectangulo y acepte el largo y ancho y retorne el área. ",
type= Type.Functions,
functionsExpected = new List<string>{"areaCirculo"},
functionTests = new List<FunctionTest>
{
new FunctionTest
{
functionName="areaCirculo",
functionParameters= new List<object> { 2, 2 },
outputResult="4"
}
}
},
};
public string GetWorkspaceXmlFromFile()
{
if (instructions == null)
{
return "";
}
string currentDirectory = Directory.GetCurrentDirectory();
string filePath = Path.Combine(currentDirectory, "Game", "Assets", "puzzles_workspace", defaultWorkspaceFilename);
string text = File.ReadAllText(filePath);
return text;
}
public string id;
public Type type;
public string defaultWorkspaceFilename;
public string documentation;
public string instructions;
public string expectedOutput;
public List<string> functionsExpected;
public List<FunctionTest> functionTests;
public class FunctionTest
{
public string functionName;
public List<object> functionParameters;
public string outputResult;
}
}
}
|
Shell | UTF-8 | 318 | 2.625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env bash
echo BUILD_SCM_REVISION $(git rev-parse --short HEAD) || $SHORT_SHA
echo BUILD_SCM_VERSION $(git describe --abbrev=7 --always --tags HEAD) || $SHORT_SHA
echo BUILD_GUST_VERSION $(grep version < package.json | head -1 | awk -F: '{ print $2 }' | sed 's/[",]//g' | tr -d '[[:space:]]') || $SHORT_SHA
|
Java | UTF-8 | 3,727 | 1.75 | 2 | [
"Apache-2.0"
] | permissive | package com.google.android.libraries.bind.widget;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.libraries.bind.card.CardGroup;
import com.google.android.libraries.bind.data.BindingViewGroup;
import com.google.android.libraries.bind.data.BindingViewGroup.BlendMode;
import com.google.android.libraries.bind.data.Bound;
import com.google.android.libraries.bind.data.Data;
import com.google.android.libraries.bind.data.DataList;
import com.google.android.libraries.bind.data.DataView;
import com.google.android.libraries.bind.data.DataViewHelper;
import com.google.android.libraries.bind.util.Util;
public final class BindingViewGroupHelper
extends DataViewHelper
{
static final Paint blendPaint = new Paint();
long blendBitmapDurationMs;
long blendBitmapStartTimeMs;
BindingViewGroup.BlendMode blendMode;
Bitmap blendedBitmap;
boolean blendedBitmapDstComputed;
final Rect blendedBitmapDstRect = new Rect();
final Rect blendedBitmapSrcRect = new Rect();
Data boundData;
public boolean capturing;
CardGroup cardGroup;
int cardGroupPosition = -1;
boolean isOwnedByParent;
boolean supportsAnimationCapture;
final ViewGroup viewGroup;
public BindingViewGroupHelper(DataView paramDataView)
{
super(paramDataView);
Util.checkPrecondition(paramDataView instanceof BindingViewGroup);
Util.checkPrecondition(paramDataView instanceof ViewGroup);
this.viewGroup = ((ViewGroup)paramDataView);
}
public static void markDescendantsAsOwned(ViewGroup paramViewGroup)
{
for (int i = -1 + paramViewGroup.getChildCount(); i >= 0; i--)
{
View localView = paramViewGroup.getChildAt(i);
if ((localView instanceof ViewGroup))
{
if ((localView instanceof BindingViewGroup)) {
((BindingViewGroup)localView).setOwnedByParent(true);
}
markDescendantsAsOwned((ViewGroup)localView);
}
}
}
final void clearBlendedBitmap()
{
if (this.blendedBitmap != null)
{
this.blendedBitmap = null;
this.blendMode = null;
this.blendBitmapStartTimeMs = 0L;
this.blendBitmapDurationMs = 0L;
this.blendedBitmapDstComputed = false;
this.viewGroup.setWillNotDraw(true);
}
}
public final Data getData()
{
if (this.dataRow != null) {
return this.dataRow.getData(0);
}
return this.boundData;
}
void sendDataToChildrenWhoWantIt(ViewGroup paramViewGroup, Data paramData)
{
int i = paramViewGroup.getChildCount();
int j = 0;
if (j < i)
{
View localView = paramViewGroup.getChildAt(j);
if ((localView instanceof BindingViewGroup)) {
if (((BindingViewGroup)localView).isOwnedByParent()) {
((BindingViewGroup)localView).onDataUpdated(paramData);
}
}
for (;;)
{
if (((localView instanceof ViewGroup)) && (!(localView instanceof BindingViewGroup))) {
sendDataToChildrenWhoWantIt((ViewGroup)localView, paramData);
}
j++;
break;
if ((localView instanceof Bound)) {
((Bound)localView).updateBoundData(paramData);
}
}
}
}
public final void setDataRow(DataList paramDataList)
{
this.boundData = null;
super.setDataRow(paramDataList);
}
}
/* Location: F:\apktool\apktool\Google_Play_Store6.0.5\classes-dex2jar.jar
* Qualified Name: com.google.android.libraries.bind.widget.BindingViewGroupHelper
* JD-Core Version: 0.7.0.1
*/ |
Python | UTF-8 | 410 | 2.921875 | 3 | [] | no_license | name = raw_input("Enter file name:\n")
if len(name) < 1: name = "mbox-short.txt"
try:
fhand = open(name)
except:
print "File: <", name, "> does not exist"
d_mails = dict()
for line in fhand:
if line.startswith("From") and not line.startswith("From:"):
words = line.split()
# print words
d_mails[words[1]] = d_mails.get(words[1],0) + 1
#
print "Mails from:", d_mails
#
|
JavaScript | UTF-8 | 1,137 | 2.546875 | 3 | [] | no_license | (function(undefined) {
'use strict';
angular
.module('poc')
.controller('SecondController', SecondController);
SecondController.$inject = ['$http','$scope'];
function SecondController($http, $scope) {
var vm = this;
vm.users = [];
vm.orderObj = 'City';
vm.addUser = addUser;
vm.init = init;
$scope.$watch('vm.users', function() {
if (vm.user) {
alert("New user added");
}
}, true);
function addUser() {
var newUser = vm.user;
vm.users.push(newUser);
vm.user = {};
}
function init() {
$http.get("../../../assets/data/users.json")
.success(function (response) {
vm.users = response;
});
// userService.getUsers().then(successGetUsers, errorGetUsers); // commented because no restAPI is available
}
function errorGetUsers() {
alert("error");
}
function successGetUsers() {
alert("success");
}
}
})();
|
Markdown | UTF-8 | 498 | 2.703125 | 3 | [] | no_license | ---
title: 羽绒服
date: 2020-02-15T20:54:12+08:00
draft: false
---
梦里的羽绒服,通常象征温暖,保护等含义。
梦见有人送给自己羽绒服,预示你会在别人的帮助和庇护下,得到提升,顺利发展。
梦见妻子穿着羽绒服,暗示妻子要离开你。
梦见自己穿的羽绒服破了,表示你事业上将遭受挫折。
梦见你特别留意某件羽绒服,提醒你要充满信心,站稳立场,并公开表明你自己的观点。
|
C++ | UTF-8 | 3,097 | 3.4375 | 3 | [] | no_license | //============================================================================
// Name : file2.cpp
// Author : FatemehAbdi
// Version :
// Copyright : Dast Nazan Bache Boro Oonvar :)
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
class file1{
ifstream myfile ;
string name;
string cate;
public:
void input();
void output1(); //number of each object
void output2(); // number of all objects
void output3(string k); // a function for searching in a file by name
void output4(string y); //find out the number of line which user search
};
void file1:: input()
{
myfile.open ("Object-List.txt");
if(! myfile)
{
cerr<<"File cannot be opened"<<endl;
}
}
//*********************************************************************
//number of each object
void file1 ::output1()
{
int drinkCntr=0,foodCntr=0,snackCntr=0,fruitCntr=0,cleaningCntr=0;
while (myfile)
{
string strInput;
getline (myfile,strInput);
istringstream iss(strInput);
string word;
iss>>word;
iss>>word;
if (word=="drink" )
drinkCntr ++;
if (word=="food" )
foodCntr ++;
if (word=="snack" )
snackCntr ++;
if (word=="fruit" )
fruitCntr ++;
if (word=="cleaning" )
cleaningCntr ++ ;
}
cout<<endl<<"drink"<<drinkCntr<<endl;
cout<<"food"<<foodCntr<<endl;
cout<<"cleaning"<<cleaningCntr<<endl;
cout<<"snack"<<snackCntr<<endl;
cout<<"fruit"<<fruitCntr<<endl;
}
//*********************************************************************
// number of all objects
void file1::output2(){
int number_line;
string line;
while (getline (myfile,line))
{
number_line ++;
}
cout<<"number of all objects"<<number_line;
}
// a function for searching in a file by name
//*********************************************************************
void file1:: output3(string k) // k is a name which user searchs
{
string strInput;
while (myfile)
{
getline (myfile,strInput);
istringstream iss(strInput);
string word=k;
string g;
iss>>g;
if( !g.compare(word) )
cout<<strInput;
iss>>g;
if( !g.compare(word) )
cout<<strInput;
}
}
/**
* find out the number of line which user search
* *********************************************************************
*/
void file1:: output4(string y)
{
string strInput;
int number_line=0;
while (myfile)
{
number_line ++ ;
getline (myfile,strInput);
istringstream iss(strInput);
string word=y;
string g;
iss>>g;
if( !g.compare(word) )
cout<<number_line<<endl<<"******"<<endl;
iss>>g;
if( !g.compare(word) )
cout<<number_line<<endl<<"******"<<endl;
}
}
int main() {
file1 f;
string p,k;
f.input();
// f.output2();
f.output1();
// cout<<"write a word for searching in a file ";
// cin>>p;
// f.output3(p);
//
// cout<<"enter name of object which you want that ID";
// cin>>k;
// f.output4(k);
return 0;
}
|
Java | UTF-8 | 733 | 2.125 | 2 | [] | no_license | package com.example.user.endexam;
public class Bill {
int Bill_id;
int Table_id;
public Bill() {
}
int Product_id;
public int getBill_id() {
return Bill_id;
}
public void setBill_id(int bill_id) {
Bill_id = bill_id;
}
public int getTable_id() {
return Table_id;
}
public void setTable_id(int table_id) {
Table_id = table_id;
}
public int getProduct_id() {
return Product_id;
}
public void setProduct_id(int product_id) {
Product_id = product_id;
}
public Bill(int bill_id, int table_id, int product_id) {
Bill_id = bill_id;
Table_id = table_id;
Product_id = product_id;
}
}
|
Python | UTF-8 | 780 | 3.421875 | 3 | [] | no_license | import operator
opdracht = input()
words = opdracht.split()
ops = {'+' : operator.add, '-' : operator.sub, '*' : operator.mul, '/': operator.truediv}
#answer = ops[words[2]](int(words[0]),int(words[1]))
while True:
alreadyfound = False
if len(words) > 1:
for i in range(0,len(words)):
if alreadyfound:
break
for sign in ops:
if words[i] == sign:
words[i] = ops[words[i]](float(words[i-2]),float(words[i-1]))
words.pop(i-2)
words.pop(i-2)
alreadyfound = True
break
else:
continue
else:
break
answer = words[0]
answer = "{0:.3f}".format(answer)
print(answer) |
PHP | UTF-8 | 2,544 | 2.96875 | 3 | [] | no_license | <?
function boolCast($b) {
return $b === true || $b === 'true';
}
abstract class DBConnection {
const TYPE_BOOLEAN = 'boolean';
const TYPE_INTEGER = 'integer';
const TYPE_STRING = 'string';
const TYPE_TIMESTAMP = 'timestamp';
private static $connection = null;
private static $statementCache = array();
public static $inTransaction = 0;
public static $queryCount = 0;
private static $lastRunStatement = null;
public static function UniqueQueryCount() {
return sizeof(self::$statementCache);
}
public static function BeginTransaction() {
self::Connect();
if (self::$inTransaction == 0) {
self::$connection->beginTransaction();
}
self::$inTransaction++;
}
public static function CommitTransaction() {
self::$inTransaction--;
if (self::$inTransaction == 0) {
self::$connection->commit();
}
}
private static function Connect() {
if (!self::$connection) {
try {
self::$connection = new PDO(
'mysql:', null, null, array(
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_READ_DEFAULT_FILE => dirname(__FILE__).'/mysql.cnf',
PDO::MYSQL_ATTR_READ_DEFAULT_GROUP => 'test'
)
);
} catch (PDOException $ex) {
var_dump($ex);
}
}
}
protected static function CreateStatement($sql) {
self::Connect();
$stmtMD5 = md5($sql);
if (isset(self::$statementCache[$stmtMD5]))
return self::$statementCache[$stmtMD5];
$stmt = self::$connection->prepare($sql);
self::$statementCache[$stmtMD5] = $stmt;
return $stmt;
}
protected static function RunStatement($stmt, $params = array(), $errorMessage = null) {
self::$queryCount++;
self::$lastRunStatement = $stmt;
$stmt->execute($params);
if ($stmt->errorCode() != '00000') {
$errorInfo = $stmt->errorInfo();
if (self::$inTransaction > 0) {
self::$connection->rollBack();
}
trigger_error($errorMessage ? $errorMessage : ($errorInfo[2] ? $errorInfo[2] : 'Database error'), E_USER_ERROR);
}
}
protected static function LastInsertId() {
return (int)self::$connection->lastInsertId();
}
protected static function FoundRows() {
$stmt = self::CreateStatement('SELECT FOUND_ROWS() AS count');
self::RunStatement($stmt);
$line = $stmt->fetch();
return $line['count'];
}
static function ColumnNames() {
$stmt = self::$lastRunStatement;
if (!$stmt)
return null;
$names = array();
for ($i = 0, $iCount = $stmt->columnCount(); $i < $iCount; $i++) {
$meta = $stmt->getColumnMeta($i);
$names[] = $meta['name'];
}
return $names;
}
}
|
C++ | UTF-8 | 4,693 | 2.625 | 3 | [
"Unlicense"
] | permissive | // typingPrototype.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
#include "SDL/SDL.h"
#include <iostream>
#include <string>
#include <cassert>
#include <time.h>
#include "wordList.h"
using namespace std;
#define SCREEN_WIDTH 500
#define SCREEN_HEIGHT 500
#define SCREEN_BPP 32
SDL_Surface *screen = NULL;
bool init() {
//Initialize all SDL subsystems
if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 ) {
return false;
}
//Set up the screen
screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
//If there was an error in setting up the screen
if( screen == NULL ) { return false; }
//Set the window caption
SDL_WM_SetCaption( "Event test", NULL );
//If everything initialized fine
return true;
}
#define NUM_SPELLS 1
#define NUM_RANKS 5
string spellList[NUM_SPELLS] =
{
"Fire Ball",
// "Heal"
};
int g_fireBallMaxDmg[] = {
10, 100, 200, 400, 1000
};
int g_selectedSpell;
int g_selectedRank;
string g_activeWord;
int g_activeWordLength;
int g_numMistakes;
enum CURR_MODE
{
SELECT_SPELL = 1,
SELECT_RANK
};
CURR_MODE g_currMode;
string selectWord(int rank)
{
int randVal = rand() % 6;
string word;
switch (rank)
{
case 0:
word = rank0[randVal];
break;
case 1:
word = rank1[randVal];
break;
case 2:
word = rank2[randVal];
break;
case 3:
word = rank3[randVal];
break;
case 4:
word = rank4[randVal];
break;
}
return word;
}
void judge(char letter)
{
if (letter == g_activeWord[0])
g_activeWord = g_activeWord.substr(1, g_activeWord.size() - 1);
else // mistake!
++g_numMistakes;
}
int _tmain(int argc, _TCHAR* argv[])
{
srand(time(NULL));
// TODO: v1
// X Select spell level (rank 1-5)
// X Present the player w/ a sentence/word of that level difficulty
// X Read in user input, parse for accuracy
// X Based on accuracy (no backspace key), calculate damage dealt to NPC
init();
SDL_EnableUNICODE( SDL_ENABLE );
bool quit = false;
bool activeState = false;
bool wordFinished = false;
SDL_Event event;
while (quit == false)
{
while(SDL_PollEvent(&event))
{
if (event.type == SDL_KEYDOWN)
{
if ((event.key.keysym.unicode >= (Uint16)'a' ) &&
(event.key.keysym.unicode <= (Uint16)'z' ) ||
(event.key.keysym.unicode == (Uint16)' ' ))
{
judge((char)event.key.keysym.unicode);
cout << "Type: " << g_activeWord << endl;
if (g_activeWord == "")
wordFinished = true;
}
else if (( event.key.keysym.unicode >= (Uint16)'0' ) &&
( event.key.keysym.unicode <= (Uint16)'9' ) )
{
if (activeState)
{
if (g_currMode == SELECT_SPELL)
{
char myChar = (char)event.key.keysym.unicode;
g_selectedSpell = atoi(&myChar);
g_currMode = SELECT_RANK;
cout << "Select Rank (0-4):" << endl;
}
else if (g_currMode == SELECT_RANK)
{
char myChar = (char)event.key.keysym.unicode;
g_selectedRank = atoi(&myChar);
cout << "Casting " << spellList[g_selectedSpell] << " Rank " << g_selectedRank << "..." << endl;
g_activeWord = selectWord(g_selectedRank);
g_activeWordLength = (int)g_activeWord.size();
cout << "Type: " << g_activeWord << endl;
}
}
}
else if (event.key.keysym.sym == SDLK_F1)
{
// reset
wordFinished = false;
activeState = true;
g_numMistakes = 0;
g_currMode = SELECT_SPELL;
cout << "Select Spell:" << endl;
for (int i = 0; i < NUM_SPELLS; ++i)
cout << i << ": " << spellList[i] << endl;
}
else if (event.key.keysym.sym == SDLK_ESCAPE)
quit = true;
}
if (event.type == SDL_QUIT)
quit = true;
}
// Casting complete.
if (g_activeWord == "" && activeState && wordFinished)
{
float acc = (float)g_activeWordLength / (g_numMistakes + g_activeWordLength);
int maxDmg = g_fireBallMaxDmg[g_selectedRank];
cout << "Mistakes: " << g_numMistakes << endl;
cout << "Accuracy: " << acc << endl;
cout << "Max Dmg: " << maxDmg << endl;
cout << "Actual Dmg: " << acc * maxDmg << endl;
cout << "-------------------" << endl;
activeState = false;
}
}
// TODO: v2
// Add in timer to time how long it takes to cast (from start of typing).
// Display WPS speed
// Add in an NPC that takes damage, does damage to player
// Add a player heal spell
SDL_EnableUNICODE( SDL_DISABLE );
SDL_Quit();
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.