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
C++
UTF-8
1,811
3.25
3
[]
no_license
/* * @lc app=leetcode id=93 lang=cpp * * [93] Restore IP Addresses * * https://leetcode.com/problems/restore-ip-addresses/description/ * * algorithms * Medium (32.03%) * Likes: 719 * Dislikes: 297 * Total Accepted: 146.8K * Total Submissions: 458.4K * Testcase Example: '"25525511135"' * * Given a string containing only digits, restore it by returning all possible * valid IP address combinations. * * Example: * * * Input: "25525511135" * Output: ["255.255.11.135", "255.255.111.35"] * * */ class Solution { public: vector<string> restoreIpAddresses(string s) { vector<string> ret; int i = 0, size = s.size(); if (size < 4) { return ret; } int x, y, z; string str = ""; for (x = max(1, size - 9); x <= min(3, size - 3); x++) { if (isValid(s.substr(0, x))) { for (y = max(x + 1, size - 6); y <= min(x + 3, size - 2); y++) { if (isValid(s.substr(x, y - x))) { for (z = max(y + 1, size - 3); z <= min(y + 3, size - 1); z++) { if (size - z > 3) continue; if (isValid(s.substr(y, z - y)) && isValid(s.substr(z, size - z))) { str = s.substr(0, x) + "." + s.substr(x, y - x) + "." + s.substr(y, z - y) + "." + s.substr(z, size - z); ret.push_back(str); str = ""; } } } } } } return ret; } bool isValid(string s) { return s.size() == 1 || (s.size() == 2 && s[0] != '0') || (stoi(s) <= 255 && s[0] != '0'); } };
Markdown
UTF-8
6,274
3.4375
3
[]
no_license
--- title: time模块 date: 2017-10-12 00:08:12 tags: [笔记,python,time] categories: [笔记,python] comments: false --- ![mahua](https://i.loli.net/2017/11/01/59f9890e94a1e.jpg) <!--more--> Python时间模块之Time模块解析 [文章转载来源](http://blog.csdn.net/SeeTheWorld518/article/details/48314501) time模块。 在开始前,先说明几点: * 在Python中,通常有这几种方式表示时间:时间戳、格式化的时间字符串、元组(struct_time 共九种元素)。由于Python的time模块主要是调用C库实现的,所以在不同的平台可能会有所不同。 * 时间戳(timestamp)的方式:时间戳表示是从1970年1月1号 00:00:00开始到现在按秒计算的偏移量。查看一下type(time.time())的返回值类型,可以看出是float类型。返回时间戳的函数主要有time()、clock()等。 * UTC(世界协调时),就是格林威治天文时间,也是世界标准时间。在中国为UTC+8。DST夏令时。 * 元组方式:struct_time元组共有9个元素,返回struct_time的函数主要有gmtime(),localtime(),strptime()。 ## time.localtime()获取当前的时间 ```python import time ls = time.localtime() 获取当前的时间,其生成的ls的数据结构为具有9个元素的元组 time.struct_time(tm_year=2015, tm_mon=8, tm_mday=24, tm_hour=9, tm_min=39, tm_sec=38, tm_wday=0, tm_yday=236, tm_isdst=0) tm_year :年 tm_mon :月(1-12) tm_mday :日(1-31) tm_hour :时(0-23) tm_min :分(0-59) tm_sec :秒(0-59) tm_wday :星期几(0-6,0表示周日) tm_yday :一年中的第几天(1-366) tm_isdst :是否是夏令时(默认为-1) ``` 使用元组索引获取对应项的值,或者是使用成员符号调用。 调用年份的方法: ```python >>> ls[0] 2015 >>> ls.tm_year 2015 time.time():返回当前时间的时间戳 >>> time.time() 1440337405.85 #对时间戳取整 >>> int(time.time()) 1440746424 ``` ## time.mktime(t):将一个struct_time转化为时间戳 time.mktime() 函数执行与gmtime(), localtime()相反的操作, ```python >>> time.mktime(time.localtime()) 1440338541.0 ``` ## time.sleep(secs):线程推迟指定的时间运行 secs表示线程睡眠指定时间,单位为妙。 time.clock() 函数以浮点数计算的秒数返回当前的CPU时间。用来衡量不同程序的耗时,比time.time()更有用。在不同的系统上含义不同。在NUix系统上,它返回的是“进程时间”,它是用妙表示的浮点数(时间戳)。而在Windows中,第一次调用,返回的是进程运行时实际时间。而第二次之后的调用是自第一次调用以后到现在的运行时间。 返回值 该函数有两个功能: (1)在第一次调用的时候,返回的是程序运行的实际时间; (2)第二次之后的调用,返回的是自第一次调用后,到这次调用的时间间隔在win32系统下,这个函数返回的是真实时间(wall time),而在Unix/Linux下返回的是CPU时间。 ## time.asctime( [t] ) 把一个表示时间的元组或者struct_time表示为 ‘Sun Aug 23 14:31:59 2015’ 这种形式。如果没有给参数,会将time.localtime()作为参数传入。 ```python >>> time.asctime(time.gmtime()) 'Sun Aug 23 14:31:59 2015' ``` ## time.ctime([secs]) 把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果为指定参数,将会默认使用time.time()作为参数。它的作用相当于time.asctime(time.localtime(secs)) ```python >>> time.ctime(1440338541.0) 'Sun Aug 23 22:02:21 2015' ``` ## time.strftime( format [, t] ) 返回字符串表示的当地时间。 把一个代表时间的元组或者struct_time(如由time.localtime()和time.gmtime()返回)转化为格式化的时间字符串,格式由参数format决定。如果未指定,将传入time.localtime()。如果元组中任何一个元素越界,就会抛出ValueError的异常。函数返回的是一个可读表示的本地时间的字符串。 参数: format:格式化字符串 t :可选的参数是一个struct_time对象 时间字符串支持的格式符号:(区分大小写) ```python %a 本地星期名称的简写(如星期四为Thu) %A 本地星期名称的全称(如星期四为Thursday) %b 本地月份名称的简写(如八月份为agu) %B 本地月份名称的全称(如八月份为august) %c 本地相应的日期和时间的字符串表示(如:15/08/27 10:20:06) %d 一个月中的第几天(01 - 31) %f 微妙(范围0.999999) %H 一天中的第几个小时(24小时制,00 - 23) %I 第几个小时(12小时制,0 - 11) %j 一年中的第几天(001 - 366) %m 月份(01 - 12) %M 分钟数(00 - 59) %p 本地am或者pm的相应符 %S 秒(00 - 61) %U 一年中的星期数。(00 - 53星期天是一个星期的开始。)第一个星期天之前的所有天数都放在第0周。 %w 一个星期中的第几天(0 - 6,0是星期天) %W 和%U基本相同,不同的是%W以星期一为一个星期的开始。 %x 本地相应日期字符串(如15/08/01) %X 本地相应时间字符串(如08:08:10) %y 去掉世纪的年份(00 - 99)两个数字表示的年份 %Y 完整的年份(4个数字表示年份) %z 与UTC时间的间隔(如果是本地时间,返回空字符串) %Z 时区的名字(如果是本地时间,返回空字符串) %% ‘%’字符 ``` ```python >>> time.strftime("%Y-%m-%d %H:%M:%S", formattime) '2015-08-24 13:01:30' ``` ## time.strptime(string[,format]) 将格式字符串转化成struct_time. 该函数是time.strftime()函数的逆操作。time strptime() 函数根据指定的格式把一个时间字符串解析为时间元组。所以函数返回的是struct_time对象。 参数: string :时间字符串 format:格式化字符串 ```python >>> stime = "2015-08-24 13:01:30" >>> formattime = time.strptime(stime,"%Y-%m-%d %H:%M:%S") >>> print formattime time.struct_time(tm_year=2015, tm_mon=8, tm_mday=24, tm_hour=13, tm_min=1, tm_sec=30, tm_wday=0, tm_yday=236, tm_isdst=-1) ```
Python
UTF-8
6,803
2.9375
3
[ "BSD-2-Clause" ]
permissive
def function_getMontage(montage): ## Small laplacian ## Calculates spatial filter matrix for Laplacian derivations. ## ## Returns a spatial filter matrix used to calculate Laplacian derivations as ## well as indices used to plot in a topographical layout. ## Assuming that the data vector s is of dimension <samples x channels>, the ## Laplacian derivation s_lap can then be calculated by s_lap = s * lap. ## s = signal(channels x time). ## ## Usage: ## [lap, plot_index, n_rows, n_cols] = getMontage(montage) ## ## Input parameters: ## montage , Matrix containing the topographical layout of the channels. The ## content of this matrix can be one of the following formats: ## (1) Channel numbers where channels are located and zeros ## elsewhere <NxM> ## (2) Ones where channels are located and zeros elsewhere <NxM> ## (3) Predefined layout <string>. ## Examples for each format: ## (1) montage = [0 3,0 , ## 4,1 2 , ## ,0 5,0] ## (2) montage = [0,1,0 , ## ,1,1,1 , ## ,0,1,0] ## (3) montage = '16ch' ## ## Output parameters: ## lap , Laplacian filter matrix ## plot_index , Indices for plotting the montage ## n_rows , Number of rows of the montage ## n_cols , Number of columns of the montage ## ## Copyright by Clemens Brunner, Robert Leeb, Alois Schlögl ## Version matlab Toolbox Biosig ## ------------------------------------------------------------------------ ## Version python ## Frank Y. Zapata C., Luisa F. Velasquez M. ## Version 2020 ## ------------------------------------------------------------------------ # import numpy as np # montage = '22ch' if isinstance(montage,str): # Predefined layouts if montage == '16ch': temp = [[0,0,1,0,0], [0,1,1,1,0], [0,1,1,1,0], [1,1,1,1,1], [0,1,1,1,0], [0,0,1,0,0]] if montage == '22ch': # Database BCI competition IV dataset 2a. temp = [[0,0,0,1,0,0,0], [0,1,1,1,1,1,0], [1,1,1,1,1,1,1], [0,1,1,1,1,1,0], [0,0,1,1,1,0,0], [0,0,0,1,0,0,0]] if montage == '24ch': temp = [[0,1,0,0,1,0,0,1,0], [1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1], [0,1,0,0,1,0,0,1,0]] if montage == '28ch': temp = [[0,0,0,1,0,0,0], [0,1,1,1,1,1,0], [1,1,1,1,1,1,1], [0,1,1,1,1,1,0], [0,0,1,1,1,0,0], [0,0,0,1,0,0,0], [1,1,1,0,1,1,1]] if montage == '30ch': temp = [[0,0,0,1,1,1,0,0,0], [1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1]] if montage == '58ch': temp = [[0,0,1,1,1,1,1,0,0], [1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1], [0,0,1,1,1,1,1,0,0], [0,0,0,1,1,1,0,0,0]], if montage == '60ch': temp = [[0,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,1,1,1,0,0,0,0], [0,0,0,1,1,1,1,1,0,0,0], [0,0,1,1,1,1,1,1,1,0,0], [0,1,1,1,1,1,1,1,1,1,0], [1,1,1,1,1,1,1,1,1,1,1], [0,1,1,1,1,1,1,1,1,1,0], [0,0,1,1,1,1,1,1,1,0,0], [0,0,0,1,1,1,1,1,0,0,0], [0,0,0,0,1,1,1,0,0,0,0]] if montage == '64ch': # order of channels of database GIGA_MI_ME temp = [[0,0,0,0,1,33,34,0,0,0,0], [0,0,0,2,3,37,36,35,0,0,0], [0,7,6,5,4,38,39,40,41,42,0], [0,8,9,10,11,47,46,45,44,43,0], [0,15,14,13,12,48,49,50,51,52,0], [0,16,17,18,19,32,56,55,54,53,0], [24,23,22,21,20,31,57,58,59,60,61], [0,0,0,25,26,30,63,62,0,0,0], [0,0,0,0,27,29,64,0,0,0,0], [0,0,0,0,0,28,0,0,0,0,0]] plot_index = np.where(np.asarray(temp).T==1) n_rows = np.size(np.asarray(temp),0) n_cols = np.size(np.asarray(temp),1) else: # User-defined layouts in the form of a matrix temp = montage plot_index = np.where(np.asarray(temp).T==1) n_rows = np.size(np.asarray(temp),0) n_cols = np.size(np.asarray(temp),1) counter = 1 temp = np.asarray(temp).T lap = np.zeros((np.size(temp,0), np.size(temp,1))) # Used electrode positions instead of ones (format (1)) positions = [] if sum(sum(temp)) != (sum(sum(temp>0))): tmp = np.sort(temp[np.where(temp)]) positions = np.argsort(temp[np.where(temp)]) temp = temp > 0 for k1 in range(0,np.size(temp,1)): for k2 in range(0,np.size(temp,0)): if temp[k2,k1] >= 1: lap[k2,k1] = counter counter = counter + 1 neighbors = np.empty((counter -1, 4)) neighbors[:] = np.nan lap_ = np.zeros((lap.size)) a = 0 for k1 in range(0,np.size(temp,1)): for k2 in range(0,np.size(temp,0)): lap_[a] = lap[k2][k1] a += 1 neighbors = [] for col, row in np.ndindex(lap.T.shape): if lap[row][col]: around = np.array([row+1, row-1, col+1, col-1], dtype=object) pair = np.array([col, col, row, row], dtype=object) around[around<0] = None if around[0]>=lap.shape[0]: around[0] = None if around[2]>=lap.shape[1]: around[2] = None around[2:], pair[2:] = pair[2:], around[2:].copy() indexes = filter(lambda c:None not in c,zip(around, pair)) neighbors.append(([lap[ind] for ind in indexes if lap[ind]] + [0]*4)[:4]) neighbors = np.array(neighbors, dtype=object) # neighbors[neighbors==0] = np.nan # colocar los datos en NaN en ceros 0. lap = np.eye(neighbors.shape[0], dtype=float) for k in range(0,neighbors.shape[0]): temp = neighbors[k,neighbors[k,:]!=0].astype(int) # Neighbors of electrode k for aa in range(0,len(temp)): lap[k,temp[aa]-1] = -1/temp.shape[0] if not positions: lap = lap[positions,positions] lap = lap.T return lap,plot_index,n_rows,n_cols
Java
UTF-8
2,053
2.140625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2014 Your Name <Ewa Milewska>. * * 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. */ package pl.altkom.ogoreczek.model; import java.util.Date; /** * * @author Your Name <Ewa Milewska> */ public class Platnosc { private Date data; private double kwota; private Zamowienie Zamowienie; private Waluta waluta; private SposobPlatnosci sposobPlatnosci; private boolean czyPrzeterminowana; public Date getData() { return data; } public double getKwota() { return kwota; } public pl.altkom.ogoreczek.model.Zamowienie getZamowienie() { return Zamowienie; } public Waluta getWaluta() { return waluta; } public SposobPlatnosci getSposobPlatnosci() { return sposobPlatnosci; } public boolean isCzyPrzeterminowana() { return czyPrzeterminowana; } public void setData(Date data) { this.data = data; } public void setKwota(double kwota) { this.kwota = kwota; } public void setZamowienie(Zamowienie Zamowienie) { this.Zamowienie = Zamowienie; } public void setWaluta(Waluta waluta) { this.waluta = waluta; } public void setSposobPlatnosci(SposobPlatnosci sposobPlatnosci) { this.sposobPlatnosci = sposobPlatnosci; } public void setCzyPrzeterminowana(boolean czyPrzeterminowana) { this.czyPrzeterminowana = czyPrzeterminowana; } }
Markdown
UTF-8
514
2.875
3
[ "MIT" ]
permissive
# ML_projects This repository contains four different machine learning projects. 1 . [Breast Cancer Prediction](https://github.com/abhi0444/ML_Projects/tree/main/Breast%20Cancer) <br> 2 . [Car Insurance Prediction](https://github.com/abhi0444/ML_Projects/tree/main/Car%20Insurance)<br> 3 . [Heart Disease Prediction](https://github.com/abhi0444/ML_Projects/tree/main/Heart%20Disease%20Prediction)<br> 4 . [Loan Approval Prediction](https://github.com/abhi0444/ML_Projects/tree/main/Loan%20Approval%20Project)<br>
Java
UTF-8
702
1.796875
2
[]
no_license
package com.godwei.stock.service.manage; import com.godwei.stock.model.manage.Corporation; import com.godwei.stock.model.manage.User; import com.godwei.stock.util.ActionReturnUtil; public interface SecuritiesService { ActionReturnUtil addUser(User user); ActionReturnUtil addCorporation(Corporation corporation); ActionReturnUtil listUser(); ActionReturnUtil listCorporation(); ActionReturnUtil uLossReported(String uName,String uIdcard); ActionReturnUtil cLossReported(String cName, String cIdcard,String cLicense); ActionReturnUtil deleteUser(String uName, String uIdcard); ActionReturnUtil deleteCorporation(String cName, String cIdcard, String cLicense); }
C++
UTF-8
269
2.6875
3
[]
no_license
#include<iostream> using namespace std; int main(void) { int maxV = -1; int sum = 0; for(int sub=1; sub<=4; sub++) { int minus, plus; scanf("%d %d", &minus, &plus); sum = sum - minus + plus; if(sum > maxV) maxV = sum; } printf("%d\n", maxV); return 0; }
Java
UTF-8
534
2.125
2
[]
no_license
package fr.suravenir.karajan.model; public class TransfertObject { private Object transObjs; private boolean collection; private String name; public Object getTransObjs() { return transObjs; } public void setTransObjs(Object transObjs) { this.transObjs = transObjs; } public boolean isCollection() { return collection; } public void setCollection(boolean collection) { this.collection = collection; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Python
UTF-8
1,198
2.578125
3
[]
no_license
import pandas as pd import numpy as np inCSV = '/Users/danielmsheehan/Downloads/nyctrees2015.csv' df = pd.read_csv(inCSV) dropList = ['spc_latin','the_geom','tree_id','created_at','block_id','boroname','st_assem','st_senate','state','cb_num','zip_city','address','latitude','longitude','x_sp','y_sp','uid','nta'] #rem from dropList 'boro_ct', df = df.drop(dropList, axis=1) df['label'] = np.where(df['health']=='Poor', 1, 0) dfx=df[['health']] dfx['count'] = 1 dfg = dfx.groupby('health').sum() print dfg.head(10) dfx=df[['label']] dfx['count'] = 1 dfg = dfx.groupby('label').sum() print dfg.head(10) df = df.drop(['health'], axis=1) #JUST ADDED TO REMOVE HEALTH COLUMN COMPLETELY print df.head(10) msk = np.random.rand(len(df)) < 0.8 #split 80/20, 80% for training, 20% for testing #http://stackoverflow.com/questions/24147278/how-do-i-create-test-and-train-samples-from-one-dataframe-with-pandas train = df[msk] test = df[~msk] print len(df) print len(train) print len(test) test.to_csv('quiz_w_label.csv', index=False) testDropCols = ['label'] #['health','label'] test = test.drop(testDropCols,axis=1) train.to_csv('data.csv',index=False) test.to_csv('quiz.csv', index=False)
C++
UTF-8
2,236
2.71875
3
[]
no_license
/** * @file ParticleEmitter.h * @author Matt Rudder * @date Created May 20, 2006 * * Defines a collection of particle effects and their location in the game world. */ #ifndef _PARTICLESYSTEM_H_ #define _PARTICLESYSTEM_H_ // Engine include #include "BaseResource.h" #include "VertexCache.h" #include "RenderSystem.h" // System includes #include <vector> using std::vector; class CParticleEffect; /** * Defines a collection of particle effects and their location in the game world. * * @author Matt Rudder * @date Created May 20, 2006 * @date Modified May 20, 2006 */ class CParticleSystem : public CBaseResource { friend class CParticleEffectContentHandler; protected: struct SEffectInstance { unsigned int unNumSpawned; unsigned int unNumActive; CParticleEffect* pEffect; }; vector<SEffectInstance> m_vEffects; bool m_bPlaying; float m_fCurrentTime; public: CParticleSystem(void); CParticleSystem(const CParticleSystem& rSys); virtual ~CParticleSystem(void); /** * Called by the Resource Manager when a previously loaded resource is * requested again. Derived classes may override the default behavior for * any special needs cases, where the same object should not be given out * multiple times. * * @date Created Mar 31, 2006 * @return The original object. */ virtual CBaseResource* cloneResource(void); /** * Allows a resource to output information about itself for debugging purposes * * @date Created Apr 01, 2006 * @return Description string */ virtual CString toString(void) const; /** * Loads a particle emitter from XML definition file. * * @date Created May 20, 2006 * @param[in] sFilename The file to load from. * @return The newly created emitter. */ static CBaseResource* createEmitterFromFile(const CString sFilename); /** * update the actor each frame * * @date Created April 23, 2006 */ virtual void update(D3DXMATRIX* mOffset = NULL); void pause(void) { m_bPlaying = false; } void play(void) { m_bPlaying = true; } bool isPlaying(void) { return m_bPlaying; } void removeParticle(CParticleEffect* pEffect); void reset(bool bPlay = false); }; #endif //_PARTICLESYSTEM_H_
Markdown
UTF-8
1,157
2.515625
3
[]
no_license
# Inspection - Team *T18* | Inspection | Details | | ----- | ----- | | Subject | *RequestFind.java* | | Meeting | *11/2/20, 4:30, teams* | | Checklist | *[Link to Checklist](https://github.com/csucs314f20/t18/blob/master/reports/checklist.md)* | ### Roles | Name | Preparation Time | | ---- | ---- | | Korbin Walsh | 15min | | Alec Moran | 10min | | Chase Howard | 20min | | Michael Bauers | 20min | | Jacob Petterle | 10min | ### Problems found | file:line | problem | hi/med/low | who found | github# | | --- | --- | :---: | :---: | --- | | RequestFind.java : 91 | Unused comment | low | krwalsh1 | #369 | | RequestFind.java : 89 / 92 | Same line if / then statements | low | krwalsh1 | #358 | | RequestFind.java : 55-67 | Statements can be moved to a new function to reduce total number of lines in RetrieveFromDatabase() | low | alecmoran7 | # | | RequestFind.java : 27-35 | Constant variables are in camelcase instead of all caps and non-constant variables are in all caps | low | ch85 | #362 | | RequestFind.java : 117 | buildResponse if statement is slightly confusing | low | mbauers | # | | RequestFind.java : 80-99 | Code in betwween try catch | low | petterle | #353 |
C
UTF-8
568
3.953125
4
[]
no_license
#include "lists.h" /** * delete_nodeint_at_index - deletes node at index * @head: pointer to pointer * @index: what to delete * Return: -1 upon failure, 1 upon success **/ int delete_nodeint_at_index(listint_t **head, unsigned int index) { listint_t *ptr; unsigned int i = 0; listint_t *h; h = *head; if (*head == NULL) return (-1); if (index == 0) { *head = h->next; free(h); return (1); } while (i < index - 1) { if (h == NULL) return (-1); h = h->next; i++; } ptr = (h->next)->next; free(h->next); h->next = ptr; return (1); }
Markdown
UTF-8
7,861
2.890625
3
[]
no_license
--- categories: [] date: "2021-12-05T02:15:59Z" description: "" tags: ["docker", "hugo", "scripts"] title: "Docker Saved My Blog" --- I haven't written any blog posts for a while. One reason is that I've been hard at work on [DocSpring](https://docspring.com) for the last few years, and I haven't had a lot of time to work on personal projects. But the main reason is that my blog uses an older version of [Hugo](https://gohugo.io/), which is a "static site generator" [^1]. I switched from Jekyll to Hugo in 2017, and the current version of Hugo at the time was [`0.21`](https://gohugo.io/news/0.21-relnotes/). I found a cool theme called [hugo-sustain](https://github.com/suyundukov/hugo-sustain). Everything was great for a few years. Time passed. One day, I tried to update a post or write a new post (I can't remember which.) I realized that my `build` and `develop` scripts were broken. I was a new computer at that point, and I had updated my macOS version. I installed the latest version of `hugo` and saw a bunch of interesting and confusing error messages when it tried to compile my old themes and layouts. I tried to downgrade `hugo` to version `0.21`, and it crashed with a segfault (it was built for an older version of macOS.) I cloned the `hugo` repository and tried to compile it from source, but my Go version was too new, so it failed to compile. Finally, I downgraded my Go version to an older version that was released around the same time in 2017. I held my breath as I tried to compile `hugo` one last time. Go tried to fetch all of the required dependencies, and crashed with a bunch of 404 errors. Apparently some of the packages had been renamed and moved around, and the older versions had been removed from the Go package index. So I gave up for a while. Instead of generating my blog from the source, I switched to editing the static files directly. Sometimes I would need to correct a typo or adjust some styles, so I'd go into the generated `./public` directory and manually modify the raw HTML and CSS. Time passed. One day, I started to notice some activity on [a blog post that I had written 11 years ago](/2010/05/13/scanning-lots-of-photos-at-once/). This post is about a GIMP plugin called `deskew` that makes it easy to scan old photos in batches on a scanner and automatically rotate them. I had dropped this plugin file in my Google Drive and had pasted a link to the file. The link worked great for 10 years, and people were able to download the file without any issues. But eventually Google changed something and the link was no longer working. I started to receive emails from people who were requesting access to this file. <img class="lightbox thumb" src="/images/posts/2021/12/request-to-access-deskew.jpeg" alt="Request to access the deskew file" /> I manually shared the file a few times. Then I decided to download the file and check it in to the blog repo. I started going into the `./public` directly to update the HTML, but I decided it was time to have another crack at this Hugo problem and fix my blog. Should I switch to Ghost? I've loved using Ghost for the [DocSpring blog](https://docspring.com/blog). It's a really nice blogging platform that I self-host on [Digital Ocean for $5/mo](https://www.digitalocean.com/), and I enjoy the WYSIWYG writing experience a little more than editing plain Markdown files. (Images are a bit annoying.) But I didn't want to migrate all my posts over to [ghost.org](https://ghost.org/) and get locked in, or spend $5/mo for the rest of my life. I just want some static HTML/CSS that I can put on GitHub Pages forever. Should I upgrade to the latest version of Hugo and spend hours fixing up the themes and tweaking all my posts until everything is working again? No thanks. Hugo runs on my local machine and produces static HTML and CSS content. It's a [pure function](https://www.wikiwand.com/en/Pure_function). There are no security vulnerabilities to watch out for. As far as I'm concerned, Hugo version `0.21` is "finished software." It generates my blog, and I'm happy with my blog. I will continue to be happy with my blog for many years to come. I don't need the latest and greatest features. I just want something stable that I can use over the next few decades without the constant grind of updating packages, breaking things, and debugging random issues. Give me Hugo `0.21` from May 2017! I was even tempted to throw everything away and start from scratch with something old and stable. Preferably written in Bash, C, or Perl. There's a lot of cool new languages out there but they often "move fast and break things." The POSIX standard was created 33 years ago in 1988, so I could still run some shell scripts that are over 30 years old. (I asked Hacker News for some examples: [Ask HN: What is the oldest Posix script that I can still run in a modern shell?](https://news.ycombinator.com/item?id=29446380).) I had a sudden burst of inspiration: # Docker! I could run Hugo in a Docker image! If I can get Hugo `0.21` running in a Docker image, then I can save that Docker image into a `*.tar.gz` file and store it right in my git repo. Then I have a static `hugo` binary that comes packaged with everything it needs to run in a consistent environment, and I can run it anywhere (Linux, Mac OS, Windows.) I found a [Dockerfile in this docker-alpine-hugo repo](https://github.com/jonathanbp/docker-alpine-hugo/blob/master/Dockerfile), and I just needed to change `0.55.3` to `0.21`. Everything worked on the first try! [^2] ### How I use Docker Instead of running `hugo`, I run a `./hugo` wrapper script that runs `hugo` inside a Docker container: ```bash #!/bin/bash docker run --rm -v "${PWD}:/src" hugo-alpine hugo "$@" ``` I have a `build_docker` script [^3] that builds the Docker image and saves it to `hugo-alpine.tar.gz`: ```bash #!/bin/bash set -euo pipefail echo "Building Dockerfile..." docker build . -t hugo-alpine echo "Saving image to hugo-alpine.tar.gz" docker save hugo-alpine > hugo-alpine.tar.gz ``` If I'm on a new computer, I can just run `docker load -i hugo-alpine.tar.gz` to load the `hugo-alpine` image into Docker. I have a `dev` script that starts the `hugo` server and makes it available on port `1313`: ```bash #!/bin/bash docker run --rm -v "${PWD}:/src" -p 1313:1313 hugo-alpine hugo --watch serve --bind 0.0.0.0 ``` Finally, I have a `deploy` script that generates the static site into `./public`, then pushes the result to a `gh-pages` branch: ```bash #!/bin/bash set -euo pipefail if [ ! -d public/.git ]; then rm -rf public REMOTE="$(git remote get-url origin)" git clone "${REMOTE}" public (cd public && git checkout gh-pages) fi docker run --rm -v "${PWD}:/src" hugo-alpine hugo cd public git add -A git commit -m "$(date)" echo "Pushing build..." git push cd .. echo "Pushing source..." git push ``` ### You can view the source code for my blog here: https://github.com/ndbroadbent/ndbroadbent.github.io --- I'm very happy with this workaround. Now I'm back in business, and I can update or write new blog posts to my heart's content. This new Docker-based setup should last me for the next few decades, if not longer. I still love how Hugo is super fast and generates my entire blog in about 6 seconds (even version `0.21`!) I'm in no hurry to switch to anything else. [^1]: A [static site generator](https://www.cloudflare.com/learning/performance/static-site-generator/) converts a folder full of Markdown files into a plain HTML/CSS website that you can host for free on [GitHub Pages](https://pages.github.com/) or [Netlify](https://www.netlify.com/). [^2]: I think it's generally much easier to get older Linux packages running, especially when it's a single Go binary with no dependencies. I wish it was this easy on Mac! [^3]: Hopefully I never have to run this again!
Java
UTF-8
323
1.734375
2
[]
no_license
import states.ChefStates; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author dn */ public interface ChefInterface { public void setChefState(ChefStates s); }
C++
UTF-8
443
2.53125
3
[]
no_license
#include "esfera.h" Esfera::Esfera(){} void Esfera::Redimensionar(int n){ float PI=3.1416; float divisiones = (PI/n); float posicion = PI/2; Vertices.clear(); Vertices.resize(n+1); Vertices[0] = _vertex3f(0,1,0); posicion -= divisiones; for(int i=1; i<n; i++){ Vertices[i] = _vertex3f(cos(posicion), sin(posicion), 0); posicion -= divisiones; } Vertices[n] = _vertex3f(0,-1,0); generarBarrido(n,0); }
PHP
UTF-8
2,150
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Backpack\CRUD\app\Models\Traits\CrudTrait; use Spatie\Permission\Traits\HasRoles; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use App\Notifications\ResetPasswordNotification; class User extends Authenticatable { use CrudTrait; use HasRoles; use HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'lastname', 'phone', 'card_token', 'is_new' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime' ]; public function sendPasswordResetNotification($token) { $url = url("/reset-password/$token?email=" . $this->email); $this->notify(new ResetPasswordNotification($url)); } public function cloudSubscriptions() { return $this->hasMany(CloudPaymentsSubscription::class); } public function getFullnameAttribute() { return $this->name . ' ' . $this->lastname; } public function getIsSubscribedAttribute() { return $this->cloudSubscriptions()->active()->first(); //return $this->cloudSubscriptions()->count() && $this->cloudSubscriptions()->max('nextTransactionDate') >= now(); } public function getActiveSubscriptionAttribute() { return $this->cloudSubscriptions()->activeSubscription()->first(); } public function getFailedSubscriptionAttribute() { return $this->cloudSubscriptions()->failedSubscription()->first(); } public function history() { return $this->hasMany(\App\Models\UserHistory::class, 'user_id'); } }
Python
UTF-8
9,061
2.53125
3
[ "MIT" ]
permissive
import unittest from . import TGBot, botapi import json class PluginTestCase(unittest.TestCase): # TODO: deprecated - kept only to minimize impact, remove in near future def fake_bot(self, *args, **kwargs): me = kwargs.pop('me', None) bot = TGBot(*args, **kwargs) return self.prepare_bot(bot=bot, me=me) def prepare_bot(self, bot=None, me=None): if not bot: bot = self.bot if not me: me = botapi.User(9999999, 'Test', 'Bot', 'test_bot') bot.request_args['test_bot'] = bot bot._fake_message_id = 0 bot._fake_replies = [] bot._fake_sends = [] bot._bot_user = me return bot def assertReplied(self, text, bot=None): if not bot: bot = self.bot self.assertEqual(self.last_reply(bot), text) def assertNoReplies(self, bot=None): if not bot: bot = self.bot self.assertEqual(len(bot._fake_sends), 0, msg='There are replies!') def clear_queues(self, bot=None): if not bot: bot = self.bot bot._fake_sends = [] bot._fake_replies = [] def last_reply(self, bot=None): if not bot: bot = self.bot try: message = bot._fake_sends.pop() except IndexError: raise AssertionError('No replies') return message[1]['text'] def pop_reply(self, bot=None): if not bot: bot = self.bot try: message = bot._fake_sends.pop() except IndexError: raise AssertionError('No replies') return message def push_fake_result(self, result, status_code=200, bot=None): if not bot: bot = self.bot bot._fake_replies.append((status_code, result)) def build_message(self, text=None, sender=None, chat=None, reply_to_message=None, bot=None, **extra): """ Send a Message to the test bot. Refer to https://core.telegram.org/bots/api#message for possible **extra values `from` was renamed in this method to `sender` as it is a reserved keyword. The only extra field is `bot` that should point to the bot instance you want to post the update. Defaults to PluginTestCase().bot """ if not bot: bot = self.bot if 'test_bot' not in bot.request_args: raise Exception('Did you forget to apply PluginTestCase.prepare_bot to your bot instance?') if sender is None: sender = extra.pop('from', None) # didn't read the comment? if sender is None: sender = { 'id': 1, 'first_name': 'John', 'last_name': 'Doe', 'username': 'johndoe', } if chat is None: chat = {'type': 'private'} chat.update(sender) if isinstance(reply_to_message, int): reply_to_message = { 'message_id': reply_to_message, 'chat': chat, } bot._fake_message_id += 1 message_id = extra.pop('message_id', bot._fake_message_id) message = { 'message_id': message_id, 'text': text, 'chat': chat, 'from': sender, 'reply_to_message': reply_to_message, } message.update(extra) return { 'update_id': bot._fake_message_id, 'message': message, } def receive_message(self, text=None, sender=None, chat=None, reply_to_message=None, bot=None, **extra): """ Send a Message to the test bot. Refer to https://core.telegram.org/bots/api#message for possible **extra values `from` was renamed in this method to `sender` as it is a reserved keyword. The only extra field is `bot` that should point to the bot instance you want to post the update. Defaults to PluginTestCase().bot """ if not bot: bot = self.bot upd = botapi.Update.from_dict( self.build_message(text, sender, chat, reply_to_message, bot, **extra) ) bot.process_update(upd) return upd def build_inline(self, query=None, sender=None, offset=None, bot=None, **extra): """ Send an InlineQuery to the test bot. Refer to https://core.telegram.org/bots/api#inlinequery for possible **extra values `from` was renamed in this method to `sender` as it is a reserved keyword. The only extra field is `bot` that should point to the bot instance you want to post the update. Defaults to PluginTestCase().bot """ if not bot: bot = self.bot if 'test_bot' not in bot.request_args: raise Exception('Did you forget to apply PluginTestCase.prepare_bot to your bot instance?') if sender is None: sender = extra.pop('from', None) # didn't read the comment? if sender is None: sender = { 'id': 1, 'first_name': 'John', 'last_name': 'Doe', 'username': 'johndoe', } bot._fake_message_id += 1 query_id = extra.pop('id', bot._fake_message_id) inline_query = { 'id': query_id, 'query': query, 'from': sender, 'offset': offset, } inline_query.update(extra) return { 'update_id': bot._fake_message_id, 'inline_query': inline_query, } def receive_inline(self, query=None, sender=None, offset=None, bot=None, **extra): """ Send an InlineQuery to the test bot. Refer to https://core.telegram.org/bots/api#inlinequery for possible **extra values `from` was renamed in this method to `sender` as it is a reserved keyword. The only extra field is `bot` that should point to the bot instance you want to post the update. Defaults to PluginTestCase().bot """ if not bot: bot = self.bot upd = botapi.Update.from_dict( self.build_inline(query, sender, offset, bot, **extra) ) bot.process_update(upd) return upd class FakeTelegramBotRPCRequest(botapi.TelegramBotRPCRequest): def __init__(self, *args, **kwargs): self._test_bot = kwargs.pop('test_bot', None) if not self._test_bot: raise Exception('Did you forget to apply PluginTestCase.prepare_bot to your bot instance?') _original_rpc_request_.__init__(self, *args, **kwargs) # run immediately as run() might not be called (when TGBot().return_* methods are used) self._async_call() def _async_call(self): self.error = None self.response = None # parse JSON where required if self.api_method == 'answerInlineQuery': _r = self.params.pop('results', '[]') self.params['results'] = json.loads(_r) if self.params and 'reply_markup' in self.params: _r = self.params.pop('reply_markup', '{}') self.params['reply_markup'] = json.loads(_r) self._test_bot._fake_sends.append((self.api_method, self.params, self.files)) status_code, result = 200, {} try: status_code, result = self._test_bot._fake_replies.pop() except IndexError: # if there is not pre-defined result, assume Message if self.on_result == botapi.Message.from_result: result = { 'message_id': None, 'from': self._test_bot._bot_user.__dict__ } result.update(self.params) chat_id = result.pop('chat_id') result['chat'] = { 'id': chat_id, 'type': 'private' if chat_id > 0 else 'group' } if status_code == 200: if self.on_result == botapi.Message.from_result and 'message_id' in result: self._test_bot._fake_message_id += 1 result['message_id'] = self._test_bot._fake_message_id if self.on_result is None: self.result = result else: self.result = self.on_result(result) if self.on_success is not None: self.on_success(self.result) else: self.error = botapi.Error(status_code, result) if self.on_error: self.on_error(self.error) # overriding run() to prevent actual async calls to be able to assert async message sending def run(self): # do nothing as _async_call() was called by init return self # same as above def wait(self): if self.error is not None: return self.error return self.result _original_rpc_request_ = botapi.TelegramBotRPCRequest botapi.TelegramBotRPCRequest = FakeTelegramBotRPCRequest
Java
UTF-8
970
3.5625
4
[]
no_license
package com.yt.datastructure.base.list; import com.yt.datastructure.DataStruct; /** * Created by yantong on 2019/2/14. * 类型相同的元素构成一个线性集合,连续占用一整块内存空间 * 由于此数据结构非常基础,且通用,所以大多数语言都会实现它 * 优点: 1、按照索引查询元素速度快 2、按照索引遍历数组方便 缺点: 1、数组的大小固定后就无法扩容了 2、数组只能存储一种类型的数据 3、添加,删除的操作慢,因为要移动其他的元素。 */ public interface Array extends DataStruct { default void demo() { String[] stringArray = new String[8]; String[] stringArray2 = new String[] {"test", "test2"}; for(int i = 0; i< stringArray2.length ; i ++) { System.out.println(stringArray2[i]); } for (String itemValue : stringArray2) { System.out.println(itemValue); } } }
C#
UTF-8
742
2.609375
3
[]
no_license
using System; namespace Test { public abstract class Test { public int Result() { return 1; } public abstract void Process(); public abstract void GetResult(ref int i); public abstract void GetResult1(out int i); public int Queue() { return 0; } } public abstract class AbsTest { } public interface ITest { void Process1(); } public class GenericClass<T> { //public T GetSum(T var1, T var2) //{ // dynamic a1 = var1; // dynamic b = var2; // return a1 + b; //} } public class childClass: AbsTest { } }
C
UTF-8
1,464
3.140625
3
[]
no_license
//-------------------------------------------------------------------------------------- // File: InputStream.h // Author: Andrew Coulthard // // This class essentially implements a FILO stack system for characters. // // Copyright (c) University of Alberta. All rights reserved. //-------------------------------------------------------------------------------------- #define STR_TERMINAL '\n' typedef struct InputStream { char stream[100]; int index; } InputStream; void IS_Insert(char in, InputStream* iStream) { iStream->stream[iStream->index] = in; iStream->index++; } /* Can be uncommented if we need these for something. char IS_Peek(InputStream* iStream) { if(iStream->index = 0) return iStream->stream[iStream->index]; return iStream->stream[iStream->index - 1]; } char IS_Remove(InputStream* iStream) { if(iStream->index = 0) { return iStream->stream[iStream->index]; } else { char out = iStream->stream[iStream->index - 1]; iStream->stream[iStream->index - 1] = 0; iStream->index -= 1; return out; } } */ void IS_Init(InputStream* iStream) { for(int i = 0; i < 100; i++) { iStream->stream[i] = 0; } iStream->index = 0; } void IS_Clear(InputStream* iStream) { IS_Init(iStream); } int IS_ContainsString(char* search, InputStream* iStream) { int i = 0; while( 1 ) { if( search[i] == STR_TERMINAL && iStream->stream[i] == STR_TERMINAL ) return 1; if( search[i] != iStream->stream[i] ) break; i++; } return 0; }
Python
UTF-8
2,669
2.765625
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- #  @Time    : 2021/4/10 23:35 #  @Author  : Ryu #  @Site    : #  @File    : correlation.py.py #  @Software: PyCharm import cv2 as cv import numpy as np import matplotlib.pyplot as plt import copy import math origin = cv.imread("images/origin.jpg") origin = copy.copy(origin) template = cv.imread("images/template.jpg") template = copy.copy(template) origin_gray = cv.cvtColor(origin, cv.COLOR_BGR2GRAY) origin_gray = origin_gray.astype(np.float) / 256 template_gray = cv.cvtColor(template, cv.COLOR_BGR2GRAY) template_gray = template_gray.astype(np.float) / 256 pointx = 0 pointy = 0 max_inf = -1.0 find = np.zeros((origin.shape[0] - template.shape[0] + 1, origin.shape[1] - template.shape[1] + 1), dtype=np.float) # 平方差 # for i in range(find.shape[0]): # for j in range(find.shape[1]): # find[i][j] = np.sum((template_gray - origin_gray[i:i + template.shape[0], j:j + template.shape[1]]) ** 2) # if (find[i][j] < max_inf): # max_inf = find[i][j] # pointx = i # pointy = j # 相关系数匹配 num = template_gray.shape[0] * template_gray.shape[1] template_gray_mean = np.mean(template_gray) template_gray_submean = template_gray - template_gray_mean sigma_template = math.sqrt(1. / (num - 1) * np.sum(template_gray_submean ** 2)) for i in range(find.shape[0]): for j in range(find.shape[1]): origin_patch = origin_gray[i:i + template_gray.shape[0], j:j + template_gray.shape[1]] origin_patch_mean = np.mean(origin_patch) origin_patch_submean = origin_patch - origin_patch_mean cov = 1. / (num - 1) * np.sum(np.multiply(origin_patch_submean, template_gray_submean)) sigma_origin_patch = math.sqrt(1. / (num - 1) * np.sum(origin_patch_submean ** 2)) coefficient = cov / (sigma_origin_patch * sigma_template) find[i][j] = coefficient if (find[i][j] > max_inf): max_inf = find[i][j] pointx = i pointy = j # 相关匹配 # for i in range(find.shape[0]): # for j in range(find.shape[1]): # find[i][j] = np.sum(np.multiply(template_gray, origin_gray[i:i + template_gray.shape[0], j:j + template_gray.shape[1]])) # if (find[i][j] > max_inf): # max_inf = find[i][j] # pointx = i # pointy = j # find = find.astype(np.float) # print(find) cv.circle(find, (pointy, pointx), 10, (255, 255, 255), 3) cv.rectangle(origin, (pointy, pointx), (pointy + template.shape[1], pointx + template.shape[0]), (0, 0, 255), 5) cv.imshow("find", find) cv.imshow('original image', origin) cv.waitKey(0)
Python
UTF-8
4,910
4.5625
5
[]
no_license
# Lawrence McAfee # ~~~~~~~~ import ~~~~~~~~ from modules.node.HierNode import HierNode from modules.node.LeafNode import LeafNode from modules.node.Stage import Stage from modules.node.block.CodeBlock import CodeBlock as cbk from modules.node.block.HierBlock import HierBlock as hbk from modules.node.block.ImageBlock import ImageBlock as ibk from modules.node.block.ListBlock import ListBlock as lbk from modules.node.block.MarkdownBlock import MarkdownBlock as mbk # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ blocks = [ # The Basics of NumPy Arrays # Data manipulation in Python is nearly synonymous with NumPy array manipulation: # even newer tools like Pandas (Chapter 3) are built around the NumPy array. This sec‐ # tion will present several examples using NumPy array manipulation to access data # and subarrays, and to split, reshape, and join the arrays. While the types of operations # shown here may seem a bit dry and pedantic, they comprise the building blocks of # many other examples used throughout the book. Get to know them well! # We’ll cover a few categories of basic array manipulations here: # Attributes of arrays # Determining the size, shape, memory consumption, and data types of arrays # Indexing of arrays # Getting and setting the value of individual array elements # Slicing of arrays # Getting and setting smaller subarrays within a larger array # Reshaping of arrays # Changing the shape of a given array # Joining and splitting of arrays # Combining multiple arrays into one, and splitting one array into many # # NumPy Array Attributes # First let’s discuss some useful array attributes. We’ll start by defining three random # arrays: a one-dimensional, two-dimensional, and three-dimensional array. We’ll use # NumPy’s random number generator, which we will seed with a set value in order to # ensure that the same random arrays are generated each time this code is run: # In[1]: import numpy as np # np.random.seed(0) # seed for reproducibility # # x1 = np.random.randint(10, size=6) # One-dimensional array # x2 = np.random.randint(10, size=(3, 4)) # Two-dimensional array # x3 = np.random.randint(10, size=(3, 4, 5)) # Three-dimensional array # # Each array has attributes ndim (the number of dimensions), shape (the size of each # dimension), and size (the total size of the array): # In[2]: print("x3 ndim: ", x3.ndim) # print("x3 shape:", x3.shape) # print("x3 size: ", x3.size) # x3 ndim: 3 # x3 shape: (3, 4, 5) # x3 size: 60 # # # 42 | Chapter 2: Introduction to NumPy # # Another useful attribute is the dtype, the data type of the array (which we discussed # previously in “Understanding Data Types in Python” on page 34): # In[3]: print("dtype:", x3.dtype) # dtype: int64 # # Other attributes include itemsize, which lists the size (in bytes) of each array ele‐ # ment, and nbytes, which lists the total size (in bytes) of the array: # In[4]: print("itemsize:", x3.itemsize, "bytes") # print("nbytes:", x3.nbytes, "bytes") # itemsize: 8 bytes # nbytes: 480 bytes # # In general, we expect that nbytes is equal to itemsize times size. # # Array Indexing: Accessing Single Elements # If you are familiar with Python’s standard list indexing, indexing in NumPy will feel # quite familiar. In a one-dimensional array, you can access the ith value (counting from # zero) by specifying the desired index in square brackets, just as with Python lists: # In[5]: x1 # Out[5]: array([5, 0, 3, 3, 7, 9]) # In[6]: x1[0] # Out[6]: 5 # In[7]: x1[4] # Out[7]: 7 # To index from the end of the array, you can use negative indices: # In[8]: x1[-1] # Out[8]: 9 # In[9]: x1[-2] # Out[9]: 7 # In a multidimensional array, you access items using a comma-separated tuple of # indices: # In[10]: x2 # Out[10]: array([[3, 5, 2, 4], # [7, 6, 8, 8], # [1, 6, 7, 7]]) # In[11]: x2[0, 0] # Out[11]: 3 # # # # The Basics of NumPy Arrays | 43 # ] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class Content(LeafNode): def __init__(self): super().__init__( "NumPy Array Attributes", # Stage.REMOVE_EXTRANEOUS, # Stage.ORIG_BLOCKS, # Stage.CUSTOM_BLOCKS, # Stage.ORIG_FIGURES, # Stage.CUSTOM_FIGURES, # Stage.CUSTOM_EXERCISES, ) [self.add(a) for a in blocks] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class NumPyArray(HierNode): def __init__(self): super().__init__("NumPy Array Attributes") self.add(Content()) # eof
JavaScript
UTF-8
2,286
3.78125
4
[]
no_license
class Node { constructor(element) { this.element = element this.next = null } } class LinkedList { constructor() { this.head = null this.length = 0 } //尾部追加元素 append(element) { const node = new Node(element) if (!this.head) { this.head = node this.length = 1 return } let current = this.head while(current.next) { current = current.next } current.next = node this.length++ } //删除指定位置的元素 remove(position = this.length - 1) { if (position < 0 || position >= this.length) { console.log('参数越界') return } let current = this.head, previous = null, index = 0 while(index++ < position) { previous = current current = current.next } if (previous) { previous.next = current.next } else { this.head = current.next } this.length-- return current.element } //删除目标元素 removeTarget(element) { let current = this.head, previous = null while(current && current.element !== element) { previous = current current = current.next } if (!current) {return false} if (previous) { previous.next = current.next } else { this.head = current.next } this.length-- return true } //在指定位置后面插入元素 insert(position, element) { if (position < 0 || position >= this.length) { console.log('参数越界') return false } let current = this.head, index = 0 while(index++ < position) { current = current.next } const node = new Node(element) let next = current.next current.next = node node.next = next this.length++ return true } //获取链表指定位置的元素或节点 getElement(position, type = 'element') { if (position < 0 || position >= this.length) {return null} let current = this.head, i = 0 while (i++ !== position) { current = current.next } return type = 'node' ? current : current.element } toString() { let current = this.head, str = '' while(current) { str += ` ${current.element.value || current.element}` current = current.next } return str } }
JavaScript
UTF-8
1,396
3.3125
3
[ "MIT" ]
permissive
// haversine great circle distance export const distance = (pt1, pt2) => { const [lng1, lat1] = pt1; const [lng2, lat2] = pt2; if (lat1 === lat2 && lng1 === lng2) { return 0; } var radlat1 = (Math.PI * lat1) / 180; var radlat2 = (Math.PI * lat2) / 180; var theta = lng1 - lng2; var radtheta = (Math.PI * theta) / 180; var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); if (dist > 1) { dist = 1; } dist = Math.acos(dist); dist = (dist * 180) / Math.PI; return dist * 60 * 1.1515 * 1.609344; }; export const pathCost = path => { return path .slice(0, -1) .map((point, idx) => distance(point, path[idx + 1])) .reduce((a, b) => a + b, 0); }; export const counterClockWise = (p, q, r) => { return (q[0] - p[0]) * (r[1] - q[1]) < (q[1] - p[1]) * (r[0] - q[0]); }; export const intersects = (a, b, c, d) => { return ( counterClockWise(a, c, d) !== counterClockWise(b, c, d) && counterClockWise(a, b, c) !== counterClockWise(a, b, d) ); }; export const setDifference = (setA, setB) => { const ret = new Set(setA); setB.forEach(p => { ret.delete(p); }); return ret; }; export const rotateToStartingPoint = (path, startingPoint) => { const startIdx = path.findIndex(p => p === startingPoint); path.unshift(...path.splice(startIdx, path.length)); };
C#
UTF-8
832
2.71875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lottery { class SweepstakesQueueManager : ISweepstakesManager { Queue<Sweepstakes> sweepstakes; public Contestant winner; public SweepstakesQueueManager() { sweepstakes = new Queue<Sweepstakes>(); } public void InsertSweepstakes(Sweepstakes sweepstakes) { this.sweepstakes.Enqueue(sweepstakes); } public Sweepstakes GetSweepstakes() { Sweepstakes recentSweepstakes = sweepstakes.Dequeue(); winner = recentSweepstakes.PickWinner(); winner.isWinner = true; recentSweepstakes.Notify(); return recentSweepstakes; } } }
C
UTF-8
2,116
3.125
3
[]
no_license
//http://stackoverflow.com/questions/7469139/what-is-equivalent-to-getch-getche-in-linux //http://cboard.cprogramming.com/c-programming/63166-kbhit-linux.html /*if you want To create a static library gcc -c libterm.c -o libterm.o compile static lib ar -cqv libterm.a libterm.o Create static lib gcc simulacion.c portsimulator.c libterm.a -o simulacion Compile app using created library ** if you want to create a standad compile * gcc simulacion.c portsimulator.c libterm.c -o simulacion http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html * http://www.cprogramming.com/tutorial/shared-libraries-linux-gcc.html * http://www.adp-gmbh.ch/cpp/gcc/create_lib.html * */ #include <stdio.h> #include <termios.h> #include <unistd.h> #include <fcntl.h> static struct termios old, new; /* Initialize new terminal i/o settings */ void initTermios(int echo) { tcgetattr(STDIN_FILENO, &old); /* grab old terminal i/o settings */ new = old; /* make new settings same as old settings */ new.c_lflag &= ~ICANON; /* disable buffered i/o */ new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */ tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */ } /* Restore old terminal i/o settings */ void resetTermios(void) { tcsetattr(0, TCSANOW, &old); } /* Read 1 character - echo defines echo mode */ char getch_(int echo) { char ch; initTermios(echo); ch = getchar(); resetTermios(); return ch; } /* Read 1 character without echo */ char getch(void) { return getch_(0); } /* Read 1 character with echo */ char getche(void) { return getch_(1); } int kbhit(void) { struct termios oldt, newt; int ch; int oldf; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); if(ch != EOF) { ungetc(ch, stdin); return 1; } return 0; }
Ruby
UTF-8
3,191
2.75
3
[]
no_license
Then("Left Unit picker value should be {string}") do |value| # find element using xpath datax = find_element(id: "select_unit_spinner").text #datax = find_element(:xpath, "(//android.widget.RelativeLayout[1])[4]").text if datax != value fail("Expected right unit picker value is #{value}, Actual value is #{datax}") else print("Data sesuai") end end Then("Right Unit picker value should be {string}") do |value2| # find element using xpath dataz = find_element(xpath: "(//android.widget.RelativeLayout/android.widget.TextView[1])[2]").text if dataz != value2 fail("Expected right unit picker value is #{value2}, Actual value is #{dataz}") else print("Data sesuai") end end #untuk button disable & enable dalam satu step (get value enable atau disable) Then(/^Show all button should be (enabled|disabled)$/) do |state| button_state = find_element(id: "btn_show_all").enabled? #print(button_state) if state == "enabled" if button_state != true fail("Button not enable") end elsif state == "disabled" if button_state != false fail("button not disable") end end end When(/^i press on clear button$/) do print("clear button is pressed") end When(/^i type "([^"]*)" on application keyboard$/) do |target| #find element di dalam class (hanya untuk 1 kali tap) #find_element(id: "keypad").find_element(xpath: "//android.widget.Button[@text='#{target}']").click #untuk klik numpad keyboard lebih dari sekali menggunakan each do x = target.split("") x.each do |num| find_element(id: "keypad").find_element(xpath: "//android.widget.Button[@text='#{num}']").click end end Then(/^i should see result as "([^"]*)"$/) do |result| x = find_element(id: "target_value").text if x != result fail("Expected value is #{result}, Actual value is #{x}") else print("Data sesuai") end end Then(/^i press on favorite icon$/) do find_element(id: "action_add_favorites").click end Then(/^i press favorite conversions$/) do text("Favorite conversions").click end And(/^i verify "([^"]*)" added to favorite conversions list$/) do |unit_type| text(unit_type) end ##================ START Scenario 5 selector ================## Then(/^i press on search icon$/) do find_element(id: "action_search").click end Then(/^i type "([^"]*)" in search field$/) do |search| find_element(id: "search_src_text").send_keys(search) end And(/^i press return button on soft keyboard$/) do Appium::TouchAction.new.tap(x:1001, y:1718, count: 1).perform end Then(/^i should see "([^"]*)" as a current unit converter$/) do |curren_unit| #cara untuk locate element container find_element(id: "action_bar").find_element(xpath: "//android.widget.TextView[@text='#{curren_unit}']") end Then(/^convertion unit must be "([^"]*)"$/) do |arg| x = find_element(id: "action_bar").find_element(xpath: "//android.widget.TextView").text if x != arg fail("unit converter tidak sesuai, value akhir akan berbeda!!!c") else printf("Unit converter sesuai ") end end Then('i wait for {int} seconds') do |int| sleep(int) end ##================ END Scenario 5 selector ================##
TypeScript
UTF-8
2,838
2.546875
3
[ "MIT" ]
permissive
import { GraphQLFieldResolver } from 'graphql' import { intArg, stringArg } from '../definitions/args' import { NexusObjectTypeDef, objectType } from '../definitions/objectType' import { dynamicOutputMethod } from '../dynamicMethod' const relayConnectionMap = new Map<string, NexusObjectTypeDef<string>>() let pageInfo: NexusObjectTypeDef<string> export const RelayConnectionFieldMethod = dynamicOutputMethod({ name: 'relayConnectionField', typeDefinition: `<FieldName extends string>(fieldName: FieldName, opts: { type: NexusGenObjectNames | NexusGenInterfaceNames | core.NexusObjectTypeDef<any> | core.NexusInterfaceTypeDef<any>, edges: core.SubFieldResolver<TypeName, FieldName, "edges">, pageInfo: core.SubFieldResolver<TypeName, FieldName, "pageInfo">, args?: Record<string, core.NexusArgDef<any>>, nullable?: boolean, description?: string }): void `, factory({ typeDef: t, args: [fieldName, config] }) { /* istanbul ignore next */ if (!config.type) { throw new Error(`Missing required property "type" from relayConnection field ${fieldName}`) } const typeName = typeof config.type === 'string' ? config.type : config.type.name pageInfo = pageInfo || objectType({ name: `ConnectionPageInfo`, definition(p) { p.boolean('hasNextPage') p.boolean('hasPreviousPage') }, }) /* istanbul ignore next */ if (config.list) { throw new Error(`Collection field ${fieldName}.${typeName} cannot be used as a list.`) } if (!relayConnectionMap.has(typeName)) { relayConnectionMap.set( typeName, objectType({ name: `${typeName}RelayConnection`, definition(c) { c.list.field('edges', { type: objectType({ name: `${typeName}Edge`, definition(e) { e.id('cursor') e.field('node', { type: config.type }) }, }), }) c.field('pageInfo', { type: pageInfo }) }, }) ) } t.field(fieldName, { type: relayConnectionMap.get(typeName)!, args: { first: intArg(), after: stringArg(), last: intArg(), before: stringArg(), ...config.args, }, nullable: config.nullable, description: config.description, resolve(root, args, ctx, info) { const edgeResolver: GraphQLFieldResolver<any, any> = (...fArgs) => config.edges(root, args, ctx, fArgs[3]) const pageInfoResolver: GraphQLFieldResolver<any, any> = (...fArgs) => config.pageInfo(root, args, ctx, fArgs[3]) return { edges: edgeResolver, pageInfo: pageInfoResolver, } }, }) }, })
Markdown
UTF-8
1,543
2.8125
3
[]
no_license
--- layout: post title: "How to use semantic-ui in rails" date: 2016-01-03 21:35:00 -0200 categories: semantic rails --- I've been using [semantic-ui](http://semantic-ui.com/) on some rails project and it's a good UI framework to work with because of it's social clean and flex design. But I didn't find any blog post on how to use it in a rails app. When we talk about stylesheet frameworks, the first thing that comes to our mind is Bootstrap or Foundation, with their tons of tutorials and gems on how to use them in a rails project and the problem is that I don't find the same amount of information when we talk about semantic, even it seems so easy to understand. - The first thing we have to do is download [semantic.js](https://raw.githubusercontent.com/Semantic-Org/Semantic-UI-CSS/master/semantic.js) and [semantic.css](https://raw.githubusercontent.com/Semantic-Org/Semantic-UI-CSS/master/semantic.css) - We are going to put `semantic.js` on `vendor/assets/javascripts` and `semantic.css` on `vendor/assets/stylesheets` - Configure your rails app to use semantic files changing `config/initializers/assets.rb` adding: {% highlight ruby %} Rails.application.config.assets.precompile += %w( semantic.css semantic.js ) {% endhighlight %} - Finally, we just have to change `application.js` file adding: {% highlight ruby %} //= require semantic {% endhighlight %} and application.css adding: {% highlight ruby %} *= require semantic {% endhighlight %} and here we are, with all files configurated and ready to be used.
Java
UTF-8
1,189
2.359375
2
[]
no_license
package pl.sdacademy; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; // 20180707 so // checking 2018-10-15 public class DodajServlet extends HttpServlet { @Override public void init() throws ServletException { System.out.println("Servlet " + this.getServletName() + " has started"); } @Override protected void doPost(HttpServletRequest reqest, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); //jesli tego nie będzie href 2 liie niżej nie zadziała i tylko się wyświetli jako text response.getWriter().println((Integer.parseInt(reqest.getParameter("p1"))+Integer.parseInt(reqest.getParameter("p2")))); response.getWriter().println("<p><a href=\"kamienie.html\">Przejdz do kamienie.html (młódź)</a></p>"); // response.sendRedirect("/draft/kamienie.html"); } @Override public void destroy() { System.out.println("Servlet " + this.getServletName() + " has stopped"); } }
Java
UTF-8
4,485
2.203125
2
[ "Apache-2.0" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.redkale.net.sncp; import org.redkale.service.Service; import org.redkale.util.AnyValue; import java.util.*; import java.util.stream.*; import org.redkale.util.*; /** * Service对象的封装类 * * <p> * 详情见: http://www.redkale.org * * @author zhangjx * @param <T> Service的子类 */ public final class ServiceWrapper<T extends Service> implements Comparable<ServiceWrapper> { private static volatile int maxClassNameLength = 0; private static volatile int maxNameLength = 0; private final T service; private final AnyValue conf; private final String sncpGroup; //自身的组节点名 可能为null private final Set<String> groups; //所有的组节点,包含自身 private final String name; private final boolean remote; private final Class[] types; @SuppressWarnings("unchecked") public ServiceWrapper(Class<T> type, T service, String name, String sncpGroup, Set<String> groups, AnyValue conf) { this.service = service; this.conf = conf; this.sncpGroup = sncpGroup; this.groups = groups; this.name = name; this.remote = Sncp.isRemote(service); ResourceType rty = service.getClass().getAnnotation(ResourceType.class); this.types = rty == null ? new Class[]{type == null ? (Class<T>) service.getClass() : type} : rty.value(); maxNameLength = Math.max(maxNameLength, name.length()); StringBuilder s = new StringBuilder(); if (this.types.length == 1) { s.append(types[0].getName()); } else { s.append('['); s.append(Arrays.asList(this.types).stream().map((Class t) -> t.getName()).collect(Collectors.joining(","))); s.append(']'); } maxClassNameLength = Math.max(maxClassNameLength, s.length() + 1); } public String toSimpleString() { StringBuilder sb = new StringBuilder(); sb.append(remote ? "RemoteService" : "LocalService "); int len; if (types.length == 1) { sb.append("(type= ").append(types[0].getName()); len = maxClassNameLength - types[0].getName().length(); } else { StringBuilder s = new StringBuilder(); s.append('['); s.append(Arrays.asList(this.types).stream().map((Class t) -> t.getName()).collect(Collectors.joining(","))); s.append(']'); sb.append("(types=").append(s); len = maxClassNameLength - s.length(); } for (int i = 0; i < len; i++) { sb.append(' '); } sb.append(", name='").append(name).append("'"); for (int i = 0; i < maxNameLength - name.length(); i++) { sb.append(' '); } sb.append(")"); return sb.toString(); } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (!(obj instanceof ServiceWrapper)) return false; ServiceWrapper other = (ServiceWrapper) obj; return (this.types[0].equals(other.types[0]) && this.remote == other.remote && this.name.equals(other.name) && Objects.equals(this.sncpGroup, other.sncpGroup)); } @Override public int hashCode() { int hash = 3; hash = 67 * hash + Objects.hashCode(this.types[0]); hash = 67 * hash + Objects.hashCode(this.sncpGroup); hash = 67 * hash + Objects.hashCode(this.name); hash = 67 * hash + (this.remote ? 1 : 0); return hash; } @Override public int compareTo(ServiceWrapper o) { int rs = this.types[0].getName().compareTo(o.types[0].getName()); if (rs == 0) rs = this.name.compareTo(o.name); return rs; } public Class[] getTypes() { return types; } public Service getService() { return service; } public AnyValue getConf() { return conf; } public String getName() { return name; } public boolean isRemote() { return remote; } public Set<String> getGroups() { return groups; } }
Swift
UTF-8
2,699
2.984375
3
[]
no_license
// // Post.swift // MyOlympia // // Created by Michael Russo on 8/6/17. // Copyright © 2017 ToeMoss. All rights reserved. // import Foundation import Firebase import FirebaseDatabase class Post { private var _username: String! private var _userImg: String! private var _postImg: String! private var _caption: String! private var _likes: Int! private var _postKey: String! private var _postRef: DatabaseReference! private var _date: String! private var _isFeatured: Bool! var username: String { return _username } var userImg: String { return _userImg } var postImg: String { get { return _postImg } set { _postImg = newValue } } var caption: String { return _caption } var likes: Int { return _likes } var postKey: String { return _postKey } var date: String { return _date } var isFeatured: Bool { return _isFeatured } init(imgUrl: String, likes: Int, username: String, userImg: String, caption: String, date: String, isFeatured: Bool) { self._likes = likes self._postImg = imgUrl self._username = username self._userImg = userImg self._caption = caption self._date = date self._isFeatured = isFeatured } init(postKey: String, postData: Dictionary<String, AnyObject>) { _postKey = postKey if let username = postData["username"] as? String { self._username = username } if let userImg = postData["userImg"] as? String { self._userImg = userImg } if let postImage = postData["imageUrl"] as? String { self._postImg = postImage } if let likes = postData["likes"] as? Int { self._likes = likes } if let caption = postData["caption"] as? String { self._caption = caption } if let date = postData["date"] as? String { self._date = date } if let isFeatured = postData["isFeatured"] as? Bool { self._isFeatured = isFeatured } _postRef = Database.database().reference().child("posts").child(_postKey) } //called in PostCell func adjustLikes(addLike: Bool) { if addLike { _likes = _likes + 1 } else { _likes = _likes - 1 } _postRef.child("likes").setValue(_likes) } }
Python
UTF-8
5,670
3.328125
3
[ "MIT" ]
permissive
from .Player_Class import Player class Game(Player): def __init__(self, more_player = False): self.more_player = more_player self.players = [Player()] self.players.append(Player()) if self.more_player else self.players.append(Player(ai = True)) def __players__(self): if self.more_player: for i in range(len(self.players)): print(f"Pseudo du joueur {i+1}:") self.players[i].set_name() else: print(f"Pseudo du joueur 1:") self.players[0].set_name() print() def start(self): print("~~~Drawlice~~~") print("\nBienvenu(e) sur Drawlice") print("Le premier jeu où tu gagnes seulement avec ta chance!") print("Alors il y aura combien de joueur(s)? (1 ou 2)") tmp = input("> ") while tmp not in ["1", "2"]: print("#MAUVAISE ENTRÉ") tmp = input("> ") self.more_player = True if tmp == "2" else False self.__players__() def combat(self): tmp = 0 player1 = self.players[0] player2 = self.players[1] print() for player in self.players: player.set_status() if player.status == "Atk": print(f"{player.name} fait une attaque", end=" ") print("magique" if "magic" in player.dmg else "physique", end=" ") print("de", player.dmg['magic'] if "magic" in player.dmg else player.dmg['physic']) else: print(f"{player.name} fait une défense", end=" ") print("magique" if "magic" in player.dmg else "physique", end=" ") print("de", player.dmg['magic'] if "magic" in player.dmg else player.dmg['physic']) print() if player1.status == "Atk" and player2.status == "Def": if "magic" in player1.dmg and "magic" in player2.dmg: tmp = player1.dmg["magic"]-player2.dmg["magic"] if player1.dmg["magic"]-player2.dmg["magic"] > 0 else 0 player2.pv -= tmp print(f"{player1.name} inflige {tmp} dégats magiques à {player2.name}") elif "physic" in player1.dmg and "physic" in player2.dmg: tmp = player1.dmg["physic"]-player2.dmg["physic"] if player1.dmg["physic"]-player2.dmg["physic"] > 0 else 0 player2.pv -= tmp print(f"{player1.name} inflige {tmp} dégats physiques à {player2.name}") else: tmp = player1.dmg["magic" if "magic" in player1.dmg else "physic"] player2.pv -= tmp print(f"{player1.name} inflige {tmp} dégats", end=" ") print("magique" if "magic" in player1.dmg else "physique", end=" ") print(f"à {player2.name}") elif player2.status == "Atk" and player1.status == "Def": if "magic" in player1.dmg and "magic" in player2.dmg: tmp = player2.dmg["magic"]-player1.dmg["magic"] if player2.dmg["magic"]-player1.dmg["magic"] > 0 else 0 player1.pv -= tmp print(f"{player2.name} inflige {tmp} dégats magiques à {player1.name}") elif "physic" in player1.dmg and "physic" in player2.dmg: tmp = player2.dmg["physic"]-player1.dmg["physic"] if player2.dmg["physic"]-player1.dmg["physic"] > 0 else 0 player1.pv -= tmp print(f"{player2.name} inflige {tmp} dégats physiques à {player1.name}") else: tmp = player2.dmg["magic" if "magic" in player2.dmg else "physic"] player1.pv -= tmp print(f"{player2.name} inflige {tmp} dégats", end=" ") print("magique" if "magic" in player2.dmg else "physique", end=" ") print(f"à {player1.name}") elif player1.status == "Atk" and player2.status == "Atk": if "magic" in player1.dmg: tmp = player1.dmg["magic"] player2.pv -= tmp print(f"{player1.name} inflige {tmp} dégats magiques à {player2.name}") else: tmp = player1.dmg["physic"] player2.pv -= tmp print(f"{player1.name} inflige {tmp} dégats physiques à {player2.name}") if "magic" in player2.dmg: tmp = player2.dmg["magic"] player1.pv -= tmp print(f"{player2.name} inflige {tmp} dégats magiques à {player1.name}") else: tmp = player2.dmg["physic"] player1.pv -= tmp print(f"{player2.name} inflige {tmp} dégats physiques à {player1.name}") elif player1.status == "Def" and player2.status == "Def": print(f"{player1.name} et {player2.name} restent sur la défensive") print() return def loop(self): print("Le combat commence!") print(f"{self.players[0].name} Vs {self.players[1].name}") while True: for player in self.players: print(f"{player.name}: {player.pv}/30") if self.players[0].pv <= 0 and self.players[1].pv <= 0: print("Égalité") return elif self.players[0].pv <= 0: print(f"Joueur {self.players[1].name} gagne!") return elif self.players[1].pv <= 0: print(f"Joueur {self.players[0].name} gagne!") return for i in range(len(self.players)): print(f"\nTour de {self.players[i].name}:") self.players[i].dice.roll() self.combat()
Python
UTF-8
8,111
2.875
3
[]
permissive
""" start_time, end_time, is_only_by_appointment, is_or_by_appointment, is_subject_to_change, start_date, end_date, hours_open_id, id """ import pandas as pd import config from utah_polling_location import PollingLocationTxt import datetime import re class ScheduleTxt(object): """ Inherits from PollingLocationTxt. """ def __init__(self, base_df, early_voting_true='false', drop_box_true='false'): self.base_df = base_df def format_for_schedule(self): sch_base_df = self.base_df # Drop base_df columns. sch_base_df.drop(['index', 'ocd_division', 'county', 'location_name', 'address_1', 'address_2', 'city', 'state', 'zip', 'id'], inplace=True, axis=1) # print self.dedupe(sch_base_df) return self.dedupe(sch_base_df) def format_time(self, hours): arr = hours.split("-") if len(arr[0]) > 7: hours = arr[0] else: hours = "0" + arr[0] if len(arr[1]) > 4: mins = arr[1] else: mins = "0" + arr[1] return hours + "-" + mins def get_sch_time(self, hours, start_date): hours_arr = hours.split("-") time = hours_arr[0].strip() offset = hours_arr[1].strip() if len(time) < 8: time = "0" + time if len(offset) <5: offset = "0" + offset return time + "-" + offset # arr = hours.split("-") # offset = self.utc_offset(county) # print arr[0] + ";00" + offset def convert_from_twelve_hour(self, hours): if not pd.isnull(hours): arr = hours.split(":") hour = int(arr[0]) mins = arr[1] if hour < 12: hour = str(hour + 12) return str(hour) + ":" + str(mins) else: return '' def is_only_by_appointment(self): return '' def is_or_by_appointment(self): return '' def is_subject_to_change(self): # create conditional when/if column is present return '' def get_start_date(self, start_date): string = str(start_date) date = datetime.datetime.strptime(string, '%m/%d/%y').strftime('%Y-%m-%d') return date # return start_date + config.utc_offset def get_end_date(self, end_date): # create conditional when/if column is present string = str(end_date) date = datetime.datetime.strptime(string, '%m/%d/%y').strftime('%Y-%m-%d') return date def get_hours_open_id(self, hours_open_id): """#""" return hours_open_id def create_schedule_id(self, index): """Create id""" # concatenate county name, or part of it (first 3/4 letters) with index # add leading zeros to maintain consistent id length if index <= 9: index_str = '000' + str(index) elif index in range(10, 100): index_str = '00' + str(index) elif index in range(100, 1000): index_str = '0' + str(index) else: index_str = str(index) return 'sch' + str(index_str) def build_schedule_txt(self): """ New columns that match the 'schedule.txt' template are inserted into the DataFrame, apply() is used to run methods that generate the values for each row of the new columns. """ self.base_df['start_time2'] = self.base_df.apply( lambda row: self.get_sch_time(row["start_time"], row["start_date"]), axis=1) self.base_df['end_time2'] = self.base_df.apply( lambda row: self.get_sch_time(row['end_time'], row["start_date"]), axis=1) self.base_df['is_only_by_appointment2'] = self.base_df.apply( lambda row: self.is_only_by_appointment(), axis=1) self.base_df['is_or_by_appointment2'] = self.base_df.apply( lambda row: self.is_or_by_appointment(), axis=1) self.base_df['is_subject_to_change2'] = self.base_df.apply( lambda row: self.is_subject_to_change(), axis=1) self.base_df['start_date2'] = self.base_df.apply( lambda row: self.get_start_date(row['start_date']), axis=1) # # self.base_df['end_date2'] = self.base_df.apply( lambda row: self.get_end_date(row['end_date']), axis=1) # # self.base_df['hours_open_id2'] = self.base_df.apply( lambda row: self.get_hours_open_id(row['hours_open_id']), axis=1) # # self.base_df['id2'] = self.base_df.apply( lambda row: self.create_schedule_id(row['index']), axis=1) return self.base_df # def dedupe(self, dupe): # """#""" # return dupe.drop_duplicates(subset=['address_line', 'hours']) def write_schedule_txt(self): """Drops base DataFrame columns then writes final dataframe to text or csv file""" sch = self.build_schedule_txt() # print sch # # start_time2, end_time2, is_only_by_appointment2, is_or_by_appointment2, is_subject_to_change2, start_date2, end_date2, hours_open_id2, id2 # Drop base_df columns. sch.drop(['entry_name', 'county', 'loc_name', 'address_1', 'address_2', 'address_3', 'city', 'state', 'zip', 'dirs', 'services', 'start_time', 'end_time', 'start_date', 'end_date', 'days_times_open', 'state_id', 'index', 'name', 'address_line', 'directions', 'hours', 'photo_uri', 'hours_open_id', 'is_drop_box', 'is_early_voting', 'lat', 'long', 'latlng', 'poll_id'], inplace=True, axis=1) # hours,photo_uri,hours_open_id,is_drop_box,is_early_voting,latitude,longitude,latlng_source,id, # Drop base_df columns. # sch.drop(['address_line', 'directions', 'hours', 'photo_uri', 'is_drop_box', 'is_early_voting', # 'latitude', 'longitude', 'latlng_source', 'id'], inplace=True, axis=1) # sch = self.dedupe(sch) # 'address_line' and 'hours are used to identfy/remove duplicates # print sch # sch.drop(['address_line', 'hours'], inplace=True, axis=1) # print sch sch.rename(columns={'start_time2': 'start_time', 'end_time2': 'end_time', 'is_only_by_appointment2': 'is_only_by_appointment', 'is_or_by_appointment2': 'is_or_by_appointment', 'is_subject_to_change2': 'is_subject_to_change', 'start_date2': 'start_date', 'end_date2': 'end_date', 'hours_open_id2': 'hours_open_id', 'id2': 'id'}, inplace=True) print sch sch.to_csv(config.output + 'schedule.txt', index=False, encoding='utf-8') # send to txt file sch.to_csv(config.output + 'schedule.csv', index=False, encoding='utf-8') # send to csv file if __name__ == '__main__': s = 'ocd_division county location_name address_1 address_2 city state zip_code start_time end_time start_date end_date index address_line directions hours photo_uri hours_open_id is_drop_box is_early_voting latitude longitude latlng_source id'.split(' ') print s intermediate_doc = 'intermediate_doc.csv' colnames = ['entry_name', 'county', 'loc_name', 'address_1', 'address_2', 'address_3', 'city', 'state', 'zip', 'dirs', 'services', 'start_time', 'end_time', 'start_date', 'end_date', 'days_times_open', 'state_id', 'index', 'name', 'address_line', 'directions', 'hours', 'photo_uri', 'hours_open_id', 'is_drop_box', 'is_early_voting', 'lat', 'long', 'latlng', 'poll_id'] early_voting_df = pd.read_csv(config.output + intermediate_doc, names=colnames, encoding='ISO-8859-1', skiprows=1, delimiter=',') early_voting_df['index'] = early_voting_df.index +1 # offsets zero based index so it starts at 1 for ids #print early_voting_df #print early_voting_df.hours_open_id ScheduleTxt(early_voting_df).write_schedule_txt() #ScheduleTxt(early_voting_df).format_for_schedule()
Java
UTF-8
1,504
2.453125
2
[]
no_license
package com.bfong.notepadbf; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class NoteAdapter extends RecyclerView.Adapter<NoteViewHolder> { private static final String TAG = "NoteAdapter"; private List<Note> noteList; private MainActivity mainAct; NoteAdapter(List<Note> list, MainActivity ma) { this.noteList = list; this.mainAct = ma; } @NonNull @Override public NoteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_list_row, parent, false); itemView.setOnClickListener(mainAct); itemView.setOnLongClickListener(mainAct); return new NoteViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull NoteViewHolder holder, int position) { Note note = noteList.get(position); holder.title.setText(note.getTitle()); holder.date.setText(DateFormat.format("E MMM dd, hh:mm aa", note.getDate())); String n = note.getText(); if (n.length() <= 80) holder.text.setText(n); else holder.text.setText(n.substring(0, 80) + "..."); } @Override public int getItemCount() { return noteList.size(); } }
Java
UTF-8
1,465
2.4375
2
[]
no_license
package com.example.jstalin.servicios; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; public class ServiciosHiloSecundario01Activity extends AppCompatActivity { Intent servicio; boolean serviceRun = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_servicios_hilo_secundario01); servicio = new Intent(this,MiServicioAsynTask.class); } public void accionIniciar(View v) { boolean isServiceRun = MiServicioAsynTask.isRunService; Log.d("ERROR", isServiceRun+"---------------"); if(isServiceRun){ Toast.makeText(getBaseContext(), "No se puede inicar servicio, servicio ya iniciado", Toast.LENGTH_SHORT); }else{ startService(servicio); MiServicioAsynTask.isRunService = true; } } public void accionParar(View v) { boolean isServiceRun = MiServicioAsynTask.isRunService; Log.d("ERROR", isServiceRun+"---------------"); if(isServiceRun){ stopService(servicio); MiServicioAsynTask.isRunService = false; }else{ Toast.makeText(getBaseContext(), "No se puede parar servicio, no hay servicio iniciado", Toast.LENGTH_SHORT); } } }
Java
UTF-8
300
2.34375
2
[]
no_license
package ru.timofeeva.box; import ru.timofeeva.sweets.Sweet; public interface Box { void add(Sweet sweet); double getBoxWeight(); double getBoxPrice(); void delete(int index); void optimizeWeight(double maxWeight); void optimizePrice(double maxPrice); void printBox(); }
TypeScript
UTF-8
39,085
3
3
[ "Apache-2.0" ]
permissive
/// <reference types="angular" /> declare namespace ArrayHelpers { /** * Removes elements in the target array based on the new collection, returns true if * any changes were made */ function removeElements(collection: Array<any>, newCollection: Array<any>, index?: string): boolean; /** * Changes the existing collection to match the new collection to avoid re-assigning * the array pointer, returns true if the array size has changed */ function sync(collection: Array<any>, newCollection: Array<any>, index?: string): boolean; } declare namespace StringHelpers { function isDate(str: any): boolean; /** * Convert a string into a bunch of '*' of the same length * @param str * @returns {string} */ function obfusicate(str: String): String; /** * Simple toString that obscures any field called 'password' * @param obj * @returns {string} */ function toString(obj: any): string; } declare namespace UrlHelpers { /** * Returns the URL without the starting '#' if it's there * @param url * @returns {string} */ function noHash(url: string): string; function extractPath(url: string): string; /** * Returns whether or not the context is in the supplied URL. If the search string starts/ends with '/' then the entire URL is checked. If the search string doesn't start with '/' then the search string is compared against the end of the URL. If the search string starts with '/' but doesn't end with '/' then the start of the URL is checked, excluding any '#' * @param url * @param thingICareAbout * @returns {boolean} */ function contextActive(url: string, thingICareAbout: string): boolean; /** * Joins the supplied strings together using '/', stripping any leading/ending '/' * from the supplied strings if needed, except the first and last string * @returns {string} */ function join(...paths: string[]): string; function parseQueryString(text?: string): any; /** * Apply a proxy to the supplied URL if the jolokiaUrl is using the proxy, or if the URL is for a a different host/port * @param jolokiaUrl * @param url * @returns {*} */ function maybeProxy(jolokiaUrl: string, url: string): string; /** * Escape any colons in the URL for ng-resource, mostly useful for handling proxified URLs * @param url * @returns {*} */ function escapeColons(url: string): string; } declare namespace Core { /** * Private method to support testing. * * @private */ function _resetUrlPrefix(): void; /** * Prefixes absolute URLs with current window.location.pathname * * @param path * @returns {string} */ function url(path: string): string; /** * Returns location of the global window * * @returns {string} */ function windowLocation(): Location; function unescapeHTML(str: any): string; /** * Private method to support testing. * * @private */ function _resetJolokiaUrls(): Array<String>; /** * Trims the leading prefix from a string if its present * @method trimLeading * @for Core * @static * @param {String} text * @param {String} prefix * @return {String} */ function trimLeading(text: string, prefix: string): string; /** * Trims the trailing postfix from a string if its present * @method trimTrailing * @for Core * @static * @param {String} trim * @param {String} postfix * @return {String} */ function trimTrailing(text: string, postfix: string): string; /** * Ensure our main app container takes up at least the viewport * height */ function adjustHeight(): void; function isChromeApp(): boolean; /** * Adds the specified CSS file to the document's head, handy * for external plugins that might bring along their own CSS * * @param path */ function addCSS(path: any): void; /** * Wrapper to get the window local storage object * * @returns {WindowLocalStorage} */ function getLocalStorage(): WindowLocalStorage; /** * If the value is not an array then wrap it in one * * @method asArray * @for Core * @static * @param {any} value * @return {Array} */ function asArray(value: any): any[]; /** * Ensure whatever value is passed in is converted to a boolean * * In the branding module for now as it's needed before bootstrap * * @method parseBooleanValue * @for Core * @param {any} value * @param {Boolean} defaultValue default value to use if value is not defined * @return {Boolean} */ function parseBooleanValue(value: any, defaultValue?: boolean): boolean; function toString(value: any): string; /** * Converts boolean value to string "true" or "false" * * @param value * @returns {string} */ function booleanToString(value: boolean): string; /** * object to integer converter * * @param value * @param description * @returns {*} */ function parseIntValue(value: any, description?: string): number; /** * Formats numbers as Strings. * * @param value * @returns {string} */ function numberToString(value: number): string; /** * object to integer converter * * @param value * @param description * @returns {*} */ function parseFloatValue(value: any, description?: string): number; /** * Navigates the given set of paths in turn on the source object * and returns the last most value of the path or null if it could not be found. * * @method pathGet * @for Core * @static * @param {Object} object the start object to start navigating from * @param {Array} paths an array of path names to navigate or a string of dot separated paths to navigate * @return {*} the last step on the path which is updated */ function pathGet(object: any, paths: any): any; /** * Navigates the given set of paths in turn on the source object * and updates the last path value to the given newValue * * @method pathSet * @for Core * @static * @param {Object} object the start object to start navigating from * @param {Array} paths an array of path names to navigate or a string of dot separated paths to navigate * @param {Object} newValue the value to update * @return {*} the last step on the path which is updated */ function pathSet(object: any, paths: any, newValue: any): any; /** * Performs a $scope.$apply() if not in a digest right now otherwise it will fire a digest later * * @method $applyNowOrLater * @for Core * @static * @param {*} $scope */ function $applyNowOrLater($scope: ng.IScope): void; /** * Performs a $scope.$apply() after the given timeout period * * @method $applyLater * @for Core * @static * @param {*} $scope * @param {Integer} timeout */ function $applyLater($scope: any, timeout?: number): void; /** * Performs a $scope.$apply() if not in a digest or apply phase on the given scope * * @method $apply * @for Core * @static * @param {*} $scope */ function $apply($scope: ng.IScope): void; /** * Performs a $scope.$digest() if not in a digest or apply phase on the given scope * * @method $apply * @for Core * @static * @param {*} $scope */ function $digest($scope: ng.IScope): void; /** * Look up a list of child element names or lazily create them. * * Useful for example to get the <tbody> <tr> element from a <table> lazily creating one * if not present. * * Usage: var trElement = getOrCreateElements(tableElement, ["tbody", "tr"]) * @method getOrCreateElements * @for Core * @static * @param {Object} domElement * @param {Array} arrayOfElementNames * @return {Object} */ function getOrCreateElements(domElement: any, arrayOfElementNames: string[]): any; /** * static unescapeHtml * * @param str * @returns {any} */ function unescapeHtml(str: any): any; /** * static escapeHtml method * * @param str * @returns {*} */ function escapeHtml(str: any): any; /** * Returns true if the string is either null or empty * * @method isBlank * @for Core * @static * @param {String} str * @return {Boolean} */ function isBlank(str: string): boolean; /** * removes all quotes/apostrophes from beginning and end of string * * @param text * @returns {string} */ function trimQuotes(text: string): string; /** * Converts camel-case and dash-separated strings into Human readable forms * * @param value * @returns {*} */ function humanizeValue(value: any): string; } declare namespace HawtioCompile { var _module: angular.IModule; } declare namespace ControllerHelpers { function createClassSelector(config: any): (selection: any, model: any) => string; function createValueClassSelector(config: any): (model: any) => string; /** * Binds a $location.search() property to a model on a scope; so that its initialised correctly on startup * and its then watched so as the model changes, the $location.search() is updated to reflect its new value * @method bindModelToSearchParam * @for Core * @static * @param {*} $scope * @param {ng.ILocationService} $location * @param {String} modelName * @param {String} paramName * @param {Object} initialValue */ function bindModelToSearchParam($scope: any, $location: any, modelName: string, paramName: string, initialValue?: any, to?: (value: any) => any, from?: (value: any) => any): void; /** * For controllers where reloading is disabled via "reloadOnSearch: false" on the registration; lets pick which * query parameters need to change to force the reload. We default to the JMX selection parameter 'nid' * @method reloadWhenParametersChange * @for Core * @static * @param {Object} $route * @param {*} $scope * @param {ng.ILocationService} $location * @param {Array[String]} parameters */ function reloadWhenParametersChange($route: any, $scope: any, $location: any, parameters?: string[]): void; } declare namespace Core { const lazyLoaders: {}; const numberTypeNames: { 'byte': boolean; 'short': boolean; 'int': boolean; 'long': boolean; 'float': boolean; 'double': boolean; 'java.lang.byte': boolean; 'java.lang.short': boolean; 'java.lang.integer': boolean; 'java.lang.long': boolean; 'java.lang.float': boolean; 'java.lang.double': boolean; }; /** * Returns the number of lines in the given text * * @method lineCount * @static * @param {String} value * @return {Number} * */ function lineCount(value: any): number; function safeNull(value: any): string; function safeNullAsString(value: any, type: string): string; /** * Converts the given value to an array of query arguments. * * If the value is null an empty array is returned. * If the value is a non empty string then the string is split by commas * * @method toSearchArgumentArray * @static * @param {*} value * @return {String[]} * */ function toSearchArgumentArray(value: any): string[]; function folderMatchesPatterns(node: any, patterns: any): any; function scopeStoreJolokiaHandle($scope: any, jolokia: any, jolokiaHandle: any): void; function closeHandle($scope: any, jolokia: any): void; /** * Pass in null for the success function to switch to sync mode * * @method onSuccess * @static * @param {Function} Success callback function * @param {Object} Options object to pass on to Jolokia request * @return {Object} initialized options object */ function onSuccess(fn: (response: Jolokia.IResponse) => void | ((response: Jolokia.IResponse) => void)[], options?: Jolokia.IParams): any; /** * The default error handler which logs errors either using debug or log level logging based on the silent setting * @param response the response from a jolokia request */ function defaultJolokiaErrorHandler(response: Jolokia.IErrorResponse, options?: Jolokia.IParams): void; /** * Logs any failed operation and stack traces */ function logJolokiaStackTrace(response: Jolokia.IErrorResponse): void; function supportsLocalStorage(): boolean; function isNumberTypeName(typeName: any): boolean; /** * Escapes the mbean for Jolokia GET requests. * See: http://www.jolokia.org/reference/html/protocol.html#escape-rules * * @param {string} mbean the mbean * @returns {string} */ function escapeMBean(mbean: string): string; /** * Escapes the mbean as a path for Jolokia POST "list" requests. * See: https://jolokia.org/reference/html/protocol.html#list * * @param {string} mbean the mbean * @returns {string} */ function escapeMBeanPath(mbean: string): string; function escapeDots(text: string): string; /** * Escapes all dots and 'span' text in the css style names to avoid clashing with bootstrap stuff * * @method escapeTreeCssStyles * @static * @param {String} text * @return {String} */ function escapeTreeCssStyles(text: string): string; function showLogPanel(): void; /** * Returns the CSS class for a log level based on if its info, warn, error etc. * * @method logLevelClass * @static * @param {String} level * @return {String} */ function logLevelClass(level: string): "error" | "" | "warning" | "info"; function toPath(hashUrl: string): string; function parseMBean(mbean: any): any; /** * Creates a link by appending the current $location.search() hash to the given href link, * removing any required parameters from the link * @method createHref * @for Core * @static * @param {ng.ILocationService} $location * @param {String} href the link to have any $location.search() hash parameters appended * @param {Array} removeParams any parameters to be removed from the $location.search() * @return {Object} the link with any $location.search() parameters added */ function createHref($location: any, href: any, removeParams?: any): any; /** * Turns the given search hash into a URI style query string * @method hashToString * @for Core * @static * @param {Object} hash * @return {String} */ function hashToString(hash: any): string; /** * Parses the given string of x=y&bar=foo into a hash * @method stringToHash * @for Core * @static * @param {String} hashAsString * @return {Object} */ function stringToHash(hashAsString: string): {}; /** * Register a JMX operation to poll for changes, only * calls back when a change occurs * * @param jolokia * @param scope * @param arguments * @param callback * @param options * @returns Object */ function registerForChanges(jolokia: any, $scope: any, arguments: any, callback: (response: any) => void, options?: any): () => void; interface IResponseHistory { [name: string]: any; } function getOrInitObjectFromLocalStorage(key: string): any; function getResponseHistory(): any; const MAX_RESPONSE_CACHE_SIZE = 20; /** * Register a JMX operation to poll for changes * @method register * @for Core * @static * @return {Function} a zero argument function for unregistering this registration * @param {*} jolokia * @param {*} scope * @param {Object} arguments * @param {Function} callback */ function register(jolokia: Jolokia.IJolokia, scope: any, arguments: any, callback: any): () => void; /** * Register a JMX operation to poll for changes using a jolokia search using the given mbean pattern * @method registerSearch * @for Core * @static * @paran {*} jolokia * @param {*} scope * @param {String} mbeanPattern * @param {Function} callback */ function unregister(jolokia: Jolokia.IJolokia, scope: any): void; /** * Converts the given XML node to a string representation of the XML * @method xmlNodeToString * @for Core * @static * @param {Object} xmlNode * @return {Object} */ function xmlNodeToString(xmlNode: any): any; /** * Returns true if the given DOM node is a text node * @method isTextNode * @for Core * @static * @param {Object} node * @return {Boolean} */ function isTextNode(node: any): boolean; /** * Returns the lowercase file extension of the given file name or returns the empty * string if the file does not have an extension * @method fileExtension * @for Core * @static * @param {String} name * @param {String} defaultValue * @return {String} */ function fileExtension(name: string, defaultValue?: string): string; function getUUID(): string; /** * Parses some text of the form "xxxx2.3.4xxxx" * to extract the version numbers as an array of numbers then returns an array of 2 or 3 numbers. * * Characters before the first digit are ignored as are characters after the last digit. * @method parseVersionNumbers * @for Core * @static * @param {String} text a maven like string containing a dash then numbers separated by dots * @return {Array} */ function parseVersionNumbers(text: string): number[]; /** * Converts a version string with numbers and dots of the form "123.456.790" into a string * which is sortable as a string, by left padding each string between the dots to at least 4 characters * so things just sort as a string. * * @param text * @return {string} the sortable version string */ function versionToSortableString(version: string, maxDigitsBetweenDots?: number): string; function time(message: string, fn: any): any; /** * Compares the 2 version arrays and returns -1 if v1 is less than v2 or 0 if they are equal or 1 if v1 is greater than v2 * @method compareVersionNumberArrays * @for Core * @static * @param {Array} v1 an array of version numbers with the most significant version first (major, minor, patch). * @param {Array} v2 * @return {Number} */ function compareVersionNumberArrays(v1: number[], v2: number[]): 1 | -1 | 0; /** * Helper function which converts objects into tables of key/value properties and * lists into a <ul> for each value. * @method valueToHtml * @for Core * @static * @param {any} value * @return {String} */ function valueToHtml(value: any): any; /** * If the string starts and ends with [] {} then try parse as JSON and return the parsed content or return null * if it does not appear to be JSON * @method tryParseJson * @for Core * @static * @param {String} text * @return {Object} */ function tryParseJson(text: string): any; /** * Given values (n, "person") will return either "1 person" or "2 people" depending on if a plural * is required using the String.pluralize() function from sugarjs * @method maybePlural * @for Core * @static * @param {Number} count * @param {String} word * @return {String} */ function maybePlural(count: Number, word: string): string; /** * given a JMX ObjectName of the form <code>domain:key=value,another=something</code> then return the object * <code>{key: "value", another: "something"}</code> * @method objectNameProperties * @for Core * @static * @param {String} name * @return {Object} */ function objectNameProperties(objectName: string): {}; /** * Removes dodgy characters from a value such as '/' or '.' so that it can be used as a DOM ID value * and used in jQuery / CSS selectors * @method toSafeDomID * @for Core * @static * @param {String} text * @return {String} */ function toSafeDomID(text: string): string; /** * Invokes the given function on each leaf node in the array of folders * @method forEachLeafFolder * @for Core * @static * @param {Array[Folder]} folders * @param {Function} fn */ function forEachLeafFolder(folders: any, fn: any): void; function extractHashURL(url: string): string; /** * Breaks a URL up into a nice object * @method parseUrl * @for Core * @static * @param url * @returns object */ function parseUrl(url: string): any; function getDocHeight(): number; /** * If a URL is external to the current web application, then * replace the URL with the proxy servlet URL * @method useProxyIfExternal * @for Core * @static * @param {String} connectUrl * @return {String} */ function useProxyIfExternal(connectUrl: any): any; /** * Extracts the url of the target, eg usually http://localhost:port, but if we use fabric to proxy to another host, * then we return the url that we proxied too (eg the real target) * * @param {ng.ILocationService} $location * @param {String} scheme to force use a specific scheme, otherwise the scheme from location is used * @param {Number} port to force use a specific port number, otherwise the port from location is used */ function extractTargetUrl($location: any, scheme: any, port: any): string; /** * Returns true if the $location is from the hawtio proxy */ function isProxyUrl($location: ng.ILocationService): boolean; /** * handy do nothing converter for the below function **/ function doNothing(value: any): any; const bindModelToSearchParam: typeof ControllerHelpers.bindModelToSearchParam; const reloadWhenParametersChange: typeof ControllerHelpers.reloadWhenParametersChange; /** * Returns a new function which ensures that the delegate function is only invoked at most once * within the given number of millseconds * @method throttled * @for Core * @static * @param {Function} fn the function to be invoked at most once within the given number of millis * @param {Number} millis the time window during which this function should only be called at most once * @return {Object} */ function throttled(fn: any, millis: number): () => any; /** * Attempts to parse the given JSON text and returns the JSON object structure or null. *Bad JSON is logged at info level. * * @param text a JSON formatted string * @param message description of the thing being parsed logged if its invalid */ function parseJsonText(text: string, message?: string): any; /** * Returns the humanized markup of the given value */ function humanizeValueHtml(value: any): string; /** * Gets a query value from the given url * * @param url url * @param parameterName the uri parameter value to get * @returns {*} */ function getQueryParameterValue(url: any, parameterName: any): string; /** * Takes a value in ms and returns a human readable * duration * @param value */ function humanizeMilliseconds(value: number): String; function getRegexs(): any; function removeRegex(name: any): void; function writeRegexs(regexs: any): void; function maskPassword(value: any): any; /** * Match the given filter against the text, ignoring any case. * <p/> * This operation will regard as a match if either filter or text is null/undefined. * As its used for filtering out, unmatched. * <p/> * * @param text the text * @param filter the filter * @return true if matched, false if not. */ function matchFilterIgnoreCase(text: any, filter: any): any; } declare var humanizeDuration: any; declare var humandate: any; declare namespace CoreFilters { } declare namespace FileUpload { interface IFileItem { url: string; alias?: string; headers: any; formData: Array<any>; method: string; withCredentials: boolean; removeAfterUpload: boolean; index: number; progress: number; isReady: boolean; isUploading: boolean; isUploaded: boolean; isSuccess: boolean; isCancel: boolean; isError: boolean; uploader: FileUploader; json?: string; remove: () => void; upload: () => void; cancel: () => void; onBeforeUpload: () => void; onProgress: (progress: number) => void; onSuccess: (response: any, status: number, headers: any) => void; onError: (response: any, status: number, headers: any) => void; onCancel: (response: any, status: number, headers: any) => void; onComplete: (response: any, status: number, headers: any) => void; } interface IFilter { name: String; fn: (item: IFileItem) => boolean; } interface IOptions { url: String; alias?: String; headers?: any; queue?: Array<IFileItem>; progress?: number; autoUpload?: boolean; removeAfterUpload?: boolean; method?: String; filters?: Array<IFilter>; formData?: Array<any>; queueLimit?: number; withCredentials?: boolean; } interface FileUploader { url: String; alias?: String; headers?: any; queue?: Array<any>; progress?: number; autoUpload?: boolean; removeAfterUpload?: boolean; method?: String; filters?: Array<IFilter>; formData?: Array<any>; queueLimit?: number; withCredentials?: boolean; addToQueue: (files: FileList, options: any, filters: String) => void; removeFromQueue: (item: IFileItem) => void; clearQueue: () => void; uploadItem: (item: any) => void; cancelItem: (item: any) => void; uploadAll: () => void; cancelAll: () => void; destroy: () => void; isFile: (value: any) => boolean; isFileLikeObject: (value: any) => boolean; getIndexOfItem: (item: IFileItem) => number; getReadyItems: () => Array<IFileItem>; getNotUploadedItems: () => Array<IFileItem>; onAfterAddingFile: (item: IFileItem) => void; onWhenAddingFileFailed: (item: IFileItem, filter: IFilter, options: any) => void; onAfterAddingAll: (addedItems: Array<IFileItem>) => void; onBeforeUploadItem: (item: IFileItem) => void; onProgressItem: (item: IFileItem, progress: number) => void; onSuccessItem: (item: IFileItem, response: any, status: number, headers: any) => void; onErrorItem: (item: IFileItem, response: any, status: number, headers: any) => void; onCancelItem: (item: IFileItem, response: any, status: number, headers: any) => void; onCompleteItem: (item: IFileItem, response: any, status: number, headers: any) => void; onProgressAll: (progress: number) => void; onCompleteAll: () => void; } interface RequestParameters { type: String; mbean: String; operation: String; arguments: Array<any>; } function useJolokiaTransport($scope: ng.IScope, uploader: FileUploader, jolokia: any, onLoad: (json: string) => RequestParameters): void; } declare namespace FilterHelpers { var log: Logging.Logger; function search(object: any, filter: string, maxDepth?: number, and?: boolean): boolean; /** * Tests if an object contains the text in "filter". The function * only checks the values in an object and ignores keys altogether, * can also work with strings/numbers/arrays * @param object * @param filter * @returns {boolean} */ function searchObject(object: any, filter: string, maxDepth?: number, depth?: number): boolean; } declare namespace Core { /** * a NodeSelection interface so we can expose things like the objectName and the MBean's entries * * @class NodeSelection */ interface NodeSelection { /** * @property title * @type string */ title: string; /** * @property key * @type string * @optional */ key?: string; /** * @property typeName * @type string * @optional */ typeName?: string; /** * @property objectName * @type string * @optional */ objectName?: string; /** * @property domain * @type string * @optional */ domain?: string; /** * @property entries * @type any * @optional */ entries?: any; /** * @property folderNames * @type array * @optional */ folderNames?: string[]; /** * @property children * @type NodeSelection * @optional */ children?: Array<NodeSelection>; /** * @property parent * @type NodeSelection * @optional */ parent?: NodeSelection; /** * @method isFolder * @return {boolean} */ isFolder?: () => boolean; /** * @property version * @type string * @optional */ version?: string; /** * @method get * @param {String} key * @return {NodeSelection} */ get(key: string): NodeSelection; /** * @method ancestorHasType * @param {String} typeName * @return {Boolean} */ ancestorHasType(typeName: string): boolean; /** * @method ancestorHasEntry * @param key * @param value * @return {Boolean} */ ancestorHasEntry(key: string, value: any): boolean; /** * @method findDescendant * @param {Function} filter * @return {NodeSelection} */ findDescendant(filter: any): NodeSelection; /** * @method findAncestor * @param {Function} filter * @return {NodeSelection} */ findAncestor(filter: any): NodeSelection; } /** * @class Folder * @uses NodeSelection */ class Folder implements NodeSelection { title: string; constructor(title: string); id: string; key: string; typeName: string; items: NodeSelection[]; children: Array<NodeSelection>; folderNames: string[]; domain: string; objectName: string; map: {}; entries: {}; addClass: string; parent: Folder; isLazy: boolean; icon: string; tooltip: string; entity: any; version: string; mbean: JMXMBean; expand: boolean; get(key: string): NodeSelection; isFolder(): boolean; /** * Navigates the given paths and returns the value there or null if no value could be found * @method navigate * @for Folder * @param {Array} paths * @return {NodeSelection} */ navigate(...paths: string[]): NodeSelection; hasEntry(key: string, value: any): boolean; parentHasEntry(key: string, value: any): boolean; ancestorHasEntry(key: string, value: any): boolean; ancestorHasType(typeName: string): boolean; getOrElse(key: string, defaultValue?: NodeSelection): Folder; sortChildren(recursive: boolean): void; moveChild(child: Folder): void; insertBefore(child: Folder, referenceFolder: Folder): void; insertAfter(child: Folder, referenceFolder: Folder): void; /** * Removes this node from my parent if I have one * @method detach * @for Folder */ detach(): void; /** * Searches this folder and all its descendants for the first folder to match the filter * @method findDescendant * @for Folder * @param {Function} filter * @return {Folder} */ findDescendant(filter: any): any; /** * Searches this folder and all its ancestors for the first folder to match the filter * @method findDescendant * @for Folder * @param {Function} filter * @return {Folder} */ findAncestor(filter: any): any; } } interface NodeSelection extends Core.NodeSelection { } declare class Folder extends Core.Folder { } declare namespace Core { /** * Operation arguments are stored in a map of argument name -> type */ interface JMXOperationArgument { name: string; desc: string; type: string; } /** * Schema for a JMX operation object */ interface JMXOperation { args: Array<JMXOperationArgument>; desc: string; ret: string; canInvoke?: boolean; } /** * JMX operation object that's a map of the operation name to the operation schema */ interface JMXOperations { [methodName: string]: JMXOperation; } /** * JMX attribute object that contains the type, description and if it's read/write or not */ interface JMXAttribute { desc: string; rw: boolean; type: string; canInvoke?: boolean; } /** * JMX mbean attributes, attribute name is the key */ interface JMXAttributes { [attributeName: string]: JMXAttribute; } /** * JMX mbean object that contains the operations/attributes */ interface JMXMBean { op: JMXOperations; attr: JMXAttributes; desc: string; canInvoke?: boolean; } /** * Individual JMX domain, mbean names are stored as keys */ interface JMXDomain { [mbeanName: string]: JMXMBean; } /** * The top level object returned from a 'list' operation */ interface JMXDomains { [domainName: string]: JMXDomain; } function operationToString(name: string, args: Array<JMXOperationArgument>): string; } declare namespace Log { function formatStackTrace(exception: any): string; function formatStackLine(line: string): string; } /** * Module that provides functions related to working with javascript objects */ declare namespace ObjectHelpers { /** * Convert an array of 'things' to an object, using 'index' as the attribute name for that value * @param arr * @param index * @param decorator */ function toMap(arr: Array<any>, index: string, decorator?: (any) => void): any; } declare namespace PluginHelpers { interface PluginModule { pluginName: string; log: Logging.Logger; _module: ng.IModule; controller?: (name: string, inlineAnnotatedConstructor: any[]) => any; } function createControllerFunction(_module: ng.IModule, pluginName: string): (name: string, inlineAnnotatedConstructor: any[]) => angular.IModule; function createRoutingFunction(templateUrl: string): (templateName: string, reloadOnSearch?: boolean) => { templateUrl: string; reloadOnSearch: boolean; }; } declare namespace PollHelpers { function setupPolling($scope: any, updateFunction: (next: () => void) => void, period?: number, $timeout?: ng.ITimeoutService, jolokia?: Jolokia.IJolokia): () => void; } declare namespace Core { /** * Parsers the given value as JSON if it is define */ function parsePreferencesJson(value: any, key: any): any; function initPreferenceScope($scope: any, localStorage: any, defaults: any): void; /** * Returns true if there is no validFn defined or if its defined * then the function returns true. * * @method isValidFunction * @for Perspective * @param {Core.Workspace} workspace * @param {Function} validFn * @param {string} perspectiveId * @return {Boolean} */ function isValidFunction(workspace: any, validFn: any, perspectiveId: any): any; } declare namespace SelectionHelpers { function selectNone(group: any[]): void; function selectAll(group: any[], filter?: (any) => boolean): void; function toggleSelection(item: any): void; function selectOne(group: any[], item: any): void; function sync(selections: Array<any>, group: Array<any>, index: string): Array<any>; function select(group: any[], item: any, $event: any): void; function isSelected(item: any, yes?: string, no?: string): any; function clearGroup(group: any): void; function toggleSelectionFromGroup(group: any[], item: any, search?: (item: any) => boolean): void; function isInGroup(group: any[], item: any, yes?: string, no?: string, search?: (item: any) => boolean): any; function filterByGroup(group: any, item: any, yes?: string, no?: string, search?: (item: any) => boolean): any; function syncGroupSelection(group: any, collection: any, attribute?: string): void; function decorate($scope: any): void; } declare namespace StorageHelpers { interface BindModelToLocalStorageOptions { $scope: any; $location: ng.ILocationService; localStorage: WindowLocalStorage; modelName: string; paramName: string; initialValue?: any; to?: (value: any) => any; from?: (value: any) => any; onChange?: (value: any) => void; } function bindModelToLocalStorage(options: BindModelToLocalStorageOptions): void; } declare namespace UI { var scrollBarWidth: number; function findParentWith($scope: any, attribute: any): any; function getIfSet(attribute: any, $attr: any, def: any): any; function observe($scope: any, $attrs: any, key: any, defValue: any, callbackFunc?: any): void; function getScrollbarWidth(): number; }
C++
UTF-8
1,622
2.53125
3
[]
no_license
#pragma once /** \file SDLMusic.h */ /** TODO: Specialization of IMusic interface for SDL */ #include <SDL/SDL_mixer.h> #include ".\IMusic.h" //! \namespace yang Contains all Yangine code namespace yang { /** \class SDLMusic */ /** SDL Music resource */ class SDLMusic : public IMusic { public: // --------------------------------------------------------------------- // // Public Member Variables // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // // Public Member Functions // --------------------------------------------------------------------- // /// Constructor /// \param pResource - raw data that contains music data /// \param pMusic - Loaded SDL music resource SDLMusic(IResource* pResource, Mix_Music* pMusic); /** Default Destructor */ ~SDLMusic(); /// Get Mix_Music* resource /// \return pointer to a Mix_Music virtual void* GetNativeMusic() override final; private: // --------------------------------------------------------------------- // // Private Member Variables // --------------------------------------------------------------------- // Mix_Music* m_pMusic; ///< Actual SDL music resource // --------------------------------------------------------------------- // // Private Member Functions // --------------------------------------------------------------------- // public: // --------------------------------------------------------------------- // // Accessors & Mutators // --------------------------------------------------------------------- // }; }
Java
UTF-8
320
1.8125
2
[]
no_license
package controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public interface Controller { // request�� ó���� �� �̵��� URL�� ��ȯ public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception; }
PHP
UTF-8
814
2.578125
3
[]
no_license
<?php require_once "app/admin.php"; $admin = new admin(); if (isset($_POST['tsimpan'])) { $admin = new admin(); $admin->input(); } ?> <h2>INPUT DATA ADMIN</h2> <table> <form action="" method="POST"> <tr> <th>NAMA</th> <td><input type="text" name="nama"></td> </tr> <tr> <th>ALAMAT</th> <td><textarea name="alamat"></textarea></td> </tr> <tr> <th>EMAIL</th> <td><input type="text" name="email"></td> </tr> <tr> <th>HP</th> <td><input type="text" name="hp"></td> </tr> <tr> <th>USERNAME</th> <td><input type="text" name="username"></td> </tr> <tr> <th>PASSWORD</th> <td><input type="password" name="password"></td> </tr> <tr> <th></th> <td><input class="tambah" type="submit" name="tsimpan" value="TAMBAH"></td> </tr> </table> </form>
Markdown
UTF-8
351
2.5625
3
[]
no_license
# Fiddling with react Basically running through the [React tutorial][1]. I added some additional functionality by .e.g using [FireBase][2] and added some simple UI elements like a delete &#x2717; and edit &#x270E; icon. The edit function doesn't work though. [1]: http://facebook.github.io/react/docs/tutorial.html [2]: https://www.firebase.com/
Markdown
UTF-8
5,218
2.75
3
[ "Apache-2.0" ]
permissive
--- layout: base title: 'Old Church Slavonic UD' udver: '2' --- # UD for Old Church Slavonic <span class="flagspan"><img class="flag" src="../../flags/svg/MORAVA.svg" /></span> ## Tokenization and Word Segmentation * In general, words are delimited by whitespace characters. * Punctuation such as commas and periods is not included in the data. Occasionally a punctuation symbol (typically a hyphen) is part of a word, as in _вꙑ-инѫ_. * There are no multi-word tokens. * There are no words with spaces. ## Morphology ### Tags * Old Church Slavonic uses 14 universal POS categories. There are no particles, punctuation and other symbols in the data. * The only auxiliary verb ([AUX]()) in Old Church Slavonic is _бꙑти_ “to be”. It is used as copula (_съ ними <b>естъ</b> женихъ_ “the bridegroom is with them”). * There are five main (de)verbal forms, distinguished by the value of the [VerbForm]() feature: * Infinitive `Inf`, tagged [VERB]() or [AUX](). * Finite verb `Fin`, tagged [VERB]() or [AUX](). * Participle `Part`, tagged [VERB]() or [AUX](). * Resultative participle `PartRes`, tagged [VERB]() or [AUX](). * Supine `Sup`, tagged [VERB]() or [AUX](). ### Nominal Features * Nominal words ([NOUN](), [PROPN]() and [PRON]()) have an inherent [Gender]() feature with one of three values: `Masc`, `Fem` or `Neut`. * The following parts of speech inflect for `Gender` because they must agree with nouns: [ADJ](), [DET](), [NUM](), [VERB](), [AUX](). For verbs (including auxiliaries), only participles can inflect for gender. Finite verbs don't. * The three values of the [Number]() feature are `Sing`, `Dual`, and `Plur`. The following parts of speech inflect for number: [NOUN](), [PROPN](), [PRON](), [ADJ](), [DET](), [NUM](), [VERB](), [AUX]() (finite and participles). * [Case]() has 7 possible values: `Nom`, `Gen`, `Dat`, `Acc`, `Ins`, `Loc`, `Voc`. It occurs with the nominal words, i.e., [NOUN](), [PROPN](), [PRON](), [ADJ](), [DET](), [NUM](). For verbs ([VERB]()) and auxiliaries ([AUX]()) it occurs with participles (`VerbForm=Part`). ### Degree and Polarity * [Degree]() applies to adjectives ([ADJ]()) and adverbs ([ADV]()) and has one of two possible values: `Pos`, `Cmp`. * [Polarity]() is used to mark the negative adverbs _не, ни, нѣ,_ and the negative forms of the auxiliary _нѣстъ, нѣсмъ, нѣсте, нѣси, нѣсмь, нѣсть,_ i.e., only the `Neg` value is used. ### Verbal Features * Finite verbs always have one of three values of [Mood](): `Ind`, `Imp` or `Sub`. * Indicative verbs always have one of three values of [Tense](): `Past`, `Pres`, `Fut`. The future tense is only annotated on the future forms of the auxiliary verb. * There are two values of [Aspect](): `Imp`, `Perf`. * There are two values of [Voice](): `Act`, `Pass`. ### Pronouns, Determiners, Quantifiers * [PronType]() is used with pronouns ([PRON]()) and adverbs ([ADV]()): `Prs`, `Rcp`, `Int`, `Rel`. * The [Poss]() feature marks possessive personal adjectives (e.g. _мои_ “my”). * The [Reflex]() feature is always used together with `PronType=Prs` and it marks reflexive pronouns _(сѧ)_ and reflexive possessive adjectives _(свои)_. * [Person]() is a lexical feature of personal pronouns ([PRON]()) and has three values, `1`, `2` and `3`. With personal possessive adjectives ([ADJ]()), the feature actually encodes the person of the possessor. Person is not marked on other types of pronouns and on nouns, although they can be almost always interpreted as the 3rd person. * As a cross-reference to subject, person is also marked on finite verbs ([VERB](), [AUX]()). ### Other Features * There is one language-specific feature: * [Variant]() with one value, `Short`, is used with adjectives and participles to mark the short or _nominal_ forms (as opposed to the long or _pronominal_ forms). For example, masculine singular nominative short _золъ_ “bad”; long _зълꙑ_ “bad”. ## Syntax ### Core Arguments, Oblique Arguments and Adjuncts * Nominal subject ([nsubj]()) is a noun phrase in the nominative case, without preposition. * A subordinate clause may serve as the subject and is labeled `csubj`. * Nominal direct object ([obj]()) is a noun phrase in the accusative case, without preposition. * Nominal indirect object ([iobj]()) is a noun phrase in the dative case, without preposition. * Other nominal dependents of a predicate are labeled as oblique ([obl]()). * In passive clauses, the subject is labeled with [nsubj:pass]() or [csubj:pass](), respectively. * If the demoted agent is present, its relation is labeled [obl:agent](). ### Relations Overview * The following relation subtypes are used in Old Church Slavonic: * [nsubj:pass]() for nominal subjects of passive verbs * [csubj:pass]() for clausal subjects of passive verbs * [obl:agent]() for agents of passive verbs * [aux:pass]() for the passive auxiliary * [flat:name]() for parts of a personal name * [advcl:cmp]() for adverbial clauses of comparison ## Treebanks There is 1 Old Church Slavonic UD treebank: * [Old Church Slavonic-PROIEL](../treebanks/cu_proiel/index.html)
Python
UTF-8
2,180
2.609375
3
[]
no_license
#!/usr/bin/python # coding=utf-8 import pycurl, json, os, sys, time from StringIO import StringIO #setup InstaPush variables # set this to Application ID from Instapush appID = "5826bf64a4c48ad384b54902" # set this to the Application Secret from Instapush appSecret = "ad55eaf6f79ccea20aa10e331a5ec343" # leave this set to DoorAlert unless you named your event something different in Instapush pushEvent = "sendIP" #=====================loop begin============================ count = 10 time.sleep(30) while True: p = os.popen("ping -c 1 www.baidu.com | awk \'/packet loss/{print $6}\'",'r') POCKET_LOSS = p.read() # print "count: ", count, ", pocket loss: ", POCKET_LOSS count = count - 1 if count == 0: # print "Error! Can't connect Internet, program exit\n" sys.exit(0) if POCKET_LOSS == "0%\n": p = os.popen("ifconfig eth0 | sed -n \"2,2p\" | awk \'{print substr($2,1)}\'",'r') ETH0_IP_ADDR = p.read() pushMessage = "Raspberry Pi, eth0 IP " + ETH0_IP_ADDR break time.sleep(10) #============================================================= # use StringIO to capture the response from our push API call buffer = StringIO() # use Curl to post to the Instapush API c = pycurl.Curl() # set Instapush API URL c.setopt(c.URL, 'https://api.instapush.im/v1/post') # setup custom headers for authentication variables and content type c.setopt(c.HTTPHEADER, ['x-instapush-appid: ' + appID, 'x-instapush-appsecret: ' + appSecret, 'Content-Type: application/json']) # create a dictionary structure for the JSON data to post to Instapush json_fields = {} # setup JSON values json_fields['event']=pushEvent json_fields['trackers'] = {} json_fields['trackers']['message']=pushMessage postfields = json.dumps(json_fields) # make sure to send the JSON with post c.setopt(c.POSTFIELDS, postfields) # set this so we can capture the resposne in our buffer c.setopt(c.WRITEFUNCTION, buffer.write) # uncomment to see the post that is sent #c.setopt(c.VERBOSE, True) c.perform() # capture the response from the server body= buffer.getvalue() # print the response #print(body) # reset the buffer buffer.truncate(0) buffer.seek(0) # cleanup c.close()
Java
UTF-8
7,037
1.835938
2
[]
no_license
package demo.wang.com.cosplay.thirdlogintest; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.tencent.connect.UserInfo; import com.tencent.connect.auth.QQAuth; import com.tencent.connect.auth.QQToken; import com.tencent.connect.common.Constants; import com.tencent.connect.share.QQShare; import com.tencent.connect.share.QzoneShare; import com.tencent.tauth.IUiListener; import com.tencent.tauth.Tencent; import com.tencent.tauth.UiError; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import demo.wang.com.cosplay.thirdlogintest.control.BaseUiListener; import demo.wang.com.cosplay.thirdlogintest.model.QQLogin; public class MainActivity extends Activity { TextView login_in_tv, show_tv, login_out_tv, login_info_tv ,share_info; Tencent mTencent; String TAG = "TAG"; public static String APPID = "1105475673"; public static String SCOPE = "all"; String openid, token; String expires_in; QQAuth mQQAuth; BaseUiListener listener; QQLogin mQQLogin = new QQLogin(); Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); String msg2 = msg.toString(); JSONObject response = (JSONObject) msg.obj; show_tv.setText(msg2); try { openid = response.getString("openid"); token = response.getString("access_token"); expires_in = response.getString("expires_in"); mQQLogin.setOpenid(response.getString("openid")); mQQLogin.setAccess_token(response.getString("access_token")); //设置身份的token mTencent.setAccessToken(token, expires_in); mTencent.setOpenId(openid); } catch (Exception e) { } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); login_in_tv = (TextView) findViewById(R.id.click_login); login_out_tv = (TextView) findViewById(R.id.click_login_out); show_tv = (TextView) findViewById(R.id.click_login_show); login_info_tv = (TextView) findViewById(R.id.click_login_info); share_info = (TextView) findViewById(R.id.click_share_show); listener = new BaseUiListener(handler, MainActivity.this); login_in_tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { mTencent = Tencent.createInstance(APPID, getApplicationContext()); mTencent.login(MainActivity.this, SCOPE, listener); } }).start(); } }); login_out_tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mTencent = Tencent.createInstance(APPID, getApplicationContext()); mTencent.logout(MainActivity.this); Toast.makeText(getApplicationContext(), "登出QQ", Toast.LENGTH_SHORT).show(); } }); login_info_tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { QQToken qqToken = mTencent.getQQToken(); mQQAuth = QQAuth.createInstance(APPID, MainActivity.this); UserInfo info = new UserInfo(getApplicationContext(), mTencent.getQQToken()); info.getUserInfo(new IUiListener() { @Override public void onComplete(Object o) { Message msguser = new Message(); msguser.obj = o; msguser.what = 0; handler.sendMessage(msguser); } @Override public void onError(UiError uiError) { } @Override public void onCancel() { } }); } }).start(); } }); share_info.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { //onClickShare(); shareToQzone (); } }).start(); } }); } /** * 分享到qq */ private void onClickShare() { Bundle params = new Bundle(); params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT); params.putString(QQShare.SHARE_TO_QQ_TITLE, "要分享的标题"); params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "要分享的摘要"); params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, "http://www.qq.com/news/1.html"); params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,"http://imgcache.qq.com/qzone/space_item/pre/0/66768.gif"); params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "测试应用222222"); mTencent.shareToQQ(MainActivity.this, params, listener); } /** * 分享到qqzore */ private void shareToQzone() { final Bundle params = new Bundle(); params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);//(图文) params.putString(QzoneShare.SHARE_TO_QQ_TITLE, "标题");//必填 params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, "摘要");//选填 params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, "http://www.qq.com/news/1.html");//必填 params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, new ArrayList<String>());//wiki上写着选填,但不填会出错 mTencent.shareToQzone(MainActivity.this, params, listener); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Tencent.onActivityResultData(requestCode, resultCode, data, listener); if (requestCode == Constants.REQUEST_API) { if (resultCode == Constants.REQUEST_LOGIN) { Tencent.handleResultData(data, listener); } } } }
Markdown
UTF-8
16,898
2.59375
3
[]
no_license
# openstack之keystone部署 **前言**   openstack更新频率是挺快的,每六个月更新一次(命名是是以A-Z的方式,Austin*,Bexar...Newton*)。博主建议大家先可一种版本研究,等某一版本研究透彻了,在去研究新的版本。其实更新来说,也就是无非对于软件来说的一些优化。对于用户角度并没有多大的改变。切记不要追着新版本走,那样只会是丢了西瓜拣芝麻!   看一下官网的图   ![img](assets/1092539-20170120102018406-40875988.png)   我们按照Newton这个版本来部署。大家也可以上官网看下官方文档,写的也挺详细。 **废话不多说,直接部署** openstack基于centos7 、redhat7 或者Ubuntu来部署的 **系统信息:** ``` 1 [root@bodbayLi ~]# cat /etc/redhat-release 2 CentOS Linux release 7.2.1511 (Core)     #操作系统信息 3 [root@bodbayLi ~]# uname -r 4 3.10.0-327.22.2.el7.x86_64        #内核的版本信息 ``` **First Step:准备阶段** 安装官方yum源。之前在部署这个openstack的时候还要考虑各种的安装包。后来官方直接出了自己的yum源。 yum安装(下载软件包到本地--->安装--->删除) 修改yum.conf ![img](assets/1092539-20170120104110187-1661661279.png) 修改keepcache=1 修改cachedir=/newton  #方便管理。并且所有的软件包都下载到本地,可以自己制作yum源 ``` `yum ``-``y install centos``-``release``-``openstack``-``newton ``#安装官方的yum源``yum ``-``y upgrade ``#更新``yum ``-``y install python``-``openstackclient ``#安装工具``yum ``-``y install openstack``-``selinux ``#安装openstack-selinux包自动管理openstack组件的安全策略` ``` 安装完上面的部分,接下来部署数据库 **Second Step**   因为keystone是一个认证服务也属于一个web app,既然是认证服务就要在后端安装一个数据库。用来存放用户的相关数据 ``` `yum ``-``y install mariadb mariadb``-``server python2``-``PyMySQL   <br>  ``#前面两个是属于centos7版本mysql数据库的名称,后面那个是一个Python模块。(在python当中操作mysql)` ```  安装好后在/etc/my.cnf.d/目录下创建一个openstack.cnf文件。(什么名字都行但是要以.cnf结尾) ``` 1 [mysqld] 2 bind-address = 182.92.84.106 #本机管理网络ip 3 4 default-storage-engine = innodb 5 innodb_file_per_table 6 max_connections = 4096 7 collation-server = utf8_general_ci 8 character-set-server = utf8 ``` 保存退出,启动mariadb systemctl start mariadb.service #启动mariadb并设为开机启动。在centos6版本中启动管理服务由之前的init.d systemctl enable mariadb.service #在centos7中则是systemctl来管理启动服务,千万要记住 查看mariadb.service运行状态 ![img](assets/1092539-20170120144457031-944210935.png) 上面就是mariadb部署过程 **Third Step**   部署keystone keystone关于数据库的操作: ``` 1 mysql -u root -p #登入数据库 2 CREATE DATABASE keystone; #新建库keystone 3 GRANT ALL PRIVILEGES ON keystone.* TO 'keystone'@'localhost' \ 4 IDENTIFIED BY '123'; #新建本地访问keystone库的账号 5 GRANT ALL PRIVILEGES ON keystone.* TO 'keystone'@'%' \ 6 IDENTIFIED BY '123'; #新建远程访问keystone库的账号 ``` keystone为什么要创建一个自己的数据库?   应为keystone程序要访问数据库,首先自己要有一个数据库,就来访问自己的数据库 **注意:以后每部署一个组件都要有一个自己的数据库,在数据库中。比如nova也要访问数据库,那么数据库中就存放一个nova的库,里面存放一些nova相关的信息 ,catalog等** 安装软件包 ``` 1 #keystone软件包名openstack-keystone 2 #安装httpd和mod_wsgi的原因是,社区主推apache+keystone 3 #openstack-keystone本质就是一款基于wsgi协议的web app,而httpd本质就是一个兼容wsgi协议的web server,所以我们需要为httpd安装mod_wsgi模块 4 yum -y install openstack-keystone httpd mod_wsgi ``` 修改keyston配置文件:/etc/keystone/keystone.conf ``` 1 #让openstack-keystone能够知道如何连接到后端的数据库keystone 2 #mysql+pymysql:pymysql是一个python库,使用python可以操作mysql原生sql 3 [database] 4 connection = mysql+pymysql://keystone:123@182.92.84.106/keystone  #mysql+pmysql是由上面的Python-mysql                   #用户名:密码@mysql地址/哪个库        那个模块安装的,用pymysql来操作mysql 5 [token]    #令牌 6 provider = fernet #fernet为生成token的方式(还有pki) ``` 注意在mysql数据库中创建密码的时候加上了引号“123”而在配置文件中不要加上引号,不然会保错 保存退出,并初始化数据库 ``` `su ``-``s ``/``bin``/``sh ``-``c ``"keystone-manage db_sync"` `keystone` ``` 之所以要初始化,是因为python的orm对象关系映射,需要初始化来生成数据库表结构。什么是orm(Object Relation Mapping)的缩写叫对象关系映射。 可能有的时候大家在部署的时候会遇到报错,怎么办,虽然我没有遇到,但是如果各位遇到了不要慌 ``` `tail ``-``f ``-``n ``20` `/``var``/``log``/``keystone``/``keystone.log` ``` 看看是哪一步骤出现问题解决就好。 接下来初始化Fernet key库(生成token) ``` `keystone``-``manage fernet_setup ``-``-``keystone``-``user keystone ``-``-``keystone``-``group keystone``keystone``-``manage credential_setup ``-``-``keystone``-``user keystone ``-``-``keystone``-``group keystone` ``` 上面的两个步骤是keystone对自己授权的一个过程,创建了一个keystone用户与一个keystone组。并对这个用户和组授权。因为keystone是对其他组件认证的服务,那么它自己就合格么?所以它先要对自己进行一下认证  **Fourth Step** **配置web server整合keystone**   修改主机名,方便操作 ``` `hostnamectl ``set``-``hostname controller` ``` 配置hosts ``` `182.92``.``84.106` `controller` ``` 配置http.conf/ServerName ``` `ServerName controller` ``` 为mod_wsgi模块添加配置文件 \#直接拷贝模块文件或者做软连接都可以 ln -s /usr/share/keystone/wsgi-keystone.conf /etc/httpd/conf.d/ wsgi:apache关于mod_wsgi模块的配置文件 keystone:用来连接keystone 查看wsgi-keystone.conf文件 ![img](assets/1092539-20170120154537718-357101770.png) ![img](assets/1092539-20170120154453187-859092505.png) ![img](assets/1092539-20170120154624218-781925562.png) 1.上面两个端口说明keystone要开放这两个端口,apache才能把请求交给keystone 2.Port 5000:Wsgi守护进程,进程5个,每个进程下面一个线程,用户keystone,组keystone。进程组/usr/bin/keystone-wsgi-public 用来产生5000端口(内部用户与外部用户使用) 3.Port 35357:跟上面一样。进程组/usr/bin/keystone-wsgi-admin 用来产生35357端口(管理员使用) **Fifth Step** 启动服务 ``` systemctl start httpd.service #启动httpd服务 systemctl enable httpd.service #设置成开机自启 ``` 查看服务状态 ![img](assets/1092539-20170120155923296-2025563661.png) 到这里keystone就部署完了,接下来就是如何要操作它了 **如何操作keystone** **一.创建keystone的catalog**   配置/etc/keystone/keystone.conf ``` `[DEFAULT]``admin_token ``=` `123``  ``#keystone自己对自己授予令牌为。虽然是可以但是这样是危险的,后面会去解决它` ```   设置环境变量 ``` export OS_TOKEN=123 export OS_URL=http://182.92.84.106:35357/v3 export OS_IDENTITY_API_VERSION=3 ``` 1.第一步的值等于keystone.conf中admin_token的值。并且只要在当前终端执行命令,当前终端就是管理员用户 2.因为现在keystone没有提供Endpoint,所以自己手动指定一个Endpoint,以后的请求就往这个url提交。v3代表用的keystone版本为3 3.认证版本为3   为keystone创建catalog ``` `openstack service create \`` ``-``-``name keystone ``-``-``description ``"OpenStack Identity"` `identity` ``` 基于前两步给的权限,创建认证服务实体 ![img](assets/1092539-20170120161951750-204394665.png) 基于建立的服务实体,创建访问该实体的三个api端点 ``` openstack endpoint create --region RegionOne \ identity public http://182.92.84.106:5000/v3 openstack endpoint create --region RegionOne \ identity internal http://182.92.84.106:5000/v3  #前两个为5000端口,专门处理内部和外部的访问                               #用keystone-wsgi-public openstack endpoint create --region RegionOne \ identity admin http://182.92.84.106:35357/v3  #35357端口,专门处理admin#用keystone-wsgi-admin ``` ![img](assets/1092539-20170206141551932-1586685689.png) ![img](assets/1092539-20170206141625791-1612926845.png) ![img](assets/1092539-20170206141651229-827559804.png) 可以看见上面三个的service_id一样说明他们属于一个服务的Endpoint 白色箭头是访问路径 登录数据库查看keystone库中的表 ![img](assets/1092539-20170206141852776-1385249838.png) 上面的步骤操作成功后,这样keystone就可以工作了。   **二.创建域,项目(租户),用户,角色,并把四个元素关联在一起**   在openstack中最大的资源集合就是域--->项目(租户)--->用户--->角色   1.创建域    1 openstack domain create --description "Default Domain" default #创建一个默认的域“default” ![img](assets/1092539-20170206142023401-1709597937.png)   2.创建管理员  ``` #创建admin项目 在“default”域中 openstack project create --domain default \ --description "Admin Project" admin #创建admin用户 在“default”域中 openstack user create --domain default \ --password-prompt admin        #输入密码 #创建admin角色 openstack role create admin #创建上述三者的关联 openstack role add --project admin --user admin admin     #不关联用户无法使用 ```   第一步与第二步的作用就是keystone能够被使用初始化的操作  **大家觉得上面的两大部分才完成一个功能有些麻烦,别急 官方最新给出了一个框架叫做Bootsrap,能够直接完成第一步和第二步的操作**   如何操作的呢 请看     **三** ``` #本质就是在为keystone创建catalog keystone-manage bootstrap --bootstrap-password 123 \ --bootstrap-admin-url http://182.92.84.106:35357/v3/ \ --bootstrap-internal-url http://182.92.84.106:35357/v3/ \ --bootstrap-public-url http://182.92.84.106:5000/v3/ \ --bootstrap-region-id RegionOne #这个123就是上面你输入的部分的那个密码 #只不过用这步操作的话不用修改配置文件,不用写admin_token,第一步与第二步的操作一点都不要去做直接就第三步 ```   设置环境变量   ``` export OS_USERNAME=admin    #用户名 export OS_PASSWORD=123    #就是keystone-manage中设定的--bootstrap-password export OS_PROJECT_NAME=admin  #项目名    project <-- 用户 <--角色 若想让用户获取权限必须要指定用户所在的项目是哪个 export OS_USER_DOMAIN_NAME=Default  #默认域 export OS_PROJECT_DOMAIN_NAME=Default export OS_AUTH_URL=http://182.92.84.106:35357/v3  #认证url export OS_IDENTITY_API_VERSION=3  #指定版本信息 ``` 验证关联 ![img](assets/1092539-20170120172317921-1333222131.png) 对比它们的ID发现是否一样 这些ID都可以在mysql数据库中查到 ![img](assets/1092539-20170120172504375-137128829.png) **四.使用第三种方法步骤**   删除mysql keystone数据库   重新初始化keystone数据库   退出环境变量   修改/etc/keystone/keystone.conf/ 下的[DEFAULT] 将admin_token=123删掉   直接操作第三步   结束后查看assignment(openstack assignment list)看是否有结果 **五.测试**  创建用于后期测试用的项目,用户,租户,建立关联  ``` openstack project create --domain default \ --description "Demo Project" demo #创建项目名为demo openstack user create --domain default \ --password-prompt demo #创建普通用户为demo 设置密码 openstack role create user        #创建普通用户的角色即user openstack role add --project demo --user demo user    #建立关联 ``` 每一个创建的过程都是这几个步骤。但是会少了一步创建角色的过程。因为用户就两个,一个是admin,另一个就是user(一个项目里可以有很多admin角色和user角色)注意.角色一定是在项目中。 **六。为后续的服务创建统一的项目叫service**     因为keystone是一个独立的授权组件,后面每搭建一个新的服务都需要在keystone中执行四种操作:1.建项目 2.建用户 3.建角色 4.做关联 并且创建catalog ``` #后面所有的服务(nova。glace等等)公用一个项目service,都是管理员角色admin (组件之间的通信都角色都是admin) #所以实际上后续的服务安装关于keysotne的操作只剩2,4 openstack project create --domain default \ --description "Service Project" service ```   每一个组件,都要有一个访问用户。(比如访问glance要有一个glance用户,还有一个一个角色,还要有一个关联)以后要部署glance,要在keystone中创建一个glance的catalog(service名/Endpoint)。还要有一个访问catalog的用户信息,这样的话还要 创建一个域。但是现在已经有了一个默认的域 所以不需要再创建,域有了还要创建一个项目,但是现在项目也已经有了。service项目,所以不用创建了。就需要创建一个叫glance的用户就行了(一般组件叫什么名,用户就叫什么名)。还要创建一个角色。但是也不用创建,之前就有一个admin角色。最后就只要做一个关联就行。以后每个组件都要这么做。就是说学会了keystone的部署,后面的组件也就部署好了 ![img](assets/1092539-20170120175954484-1963301093.png) 查看project ![img](assets/1092539-20170120180024015-1331286638.png) **七.验证** 1.准备 出于安全考虑,关闭临时令牌认证机制(配置文件中的admin_token和keystone-manage的--bootstrap-password都是基于该机制) 2.取消一切环境变量(退出xshell/puppy远程连接软件,重新连接) 3.验证操作方法   管理员用户admin申请token ``` openstack --os-auth-url http://controller:35357/v3 \ --os-identity-api-version 3 \ --os-project-domain-name default \ --os-user-domain-name default \ --os-project-name admin \ --os-username admin \ token issue ``` ![img](assets/1092539-20170213105039550-1480458595.png) 注意:一定要加上--os-identity-api-version 3 为普通用户申请token ``` openstack --os-auth-url http://controller:5000/v3 \ --os-identity-api-version 3 \ --os-project-domain-name default \ --os-user-domain-name default \ --os-project-name demo \ --os-username demo \ token issue ``` ![img](assets/1092539-20170213105338191-1303351423.png) 为了以后不写一长串的用户信息,我们可以把它定义成为一个脚本 admin ``` export OS_PROJECT_DOMAIN_NAME=Default export OS_USER_DOMAIN_NAME=Default export OS_PROJECT_NAME=admin export OS_USERNAME=admin export OS_PASSWORD=123 export OS_AUTH_URL=http://182.92.84.106:35357/v3 export OS_IDENTITY_API_VERSION=3 export OS_IMAGE_API_VERSION=2 ``` user ``` export OS_PROJECT_DOMAIN_NAME=Default export OS_USER_DOMAIN_NAME=Default export OS_PROJECT_NAME=demo export OS_USERNAME=demo export OS_PASSWORD=123 export OS_AUTH_URL=http://182.92.84.106:35357/v3 export OS_IDENTITY_API_VERSION=3 export OS_IMAGE_API_VERSION=2 ``` 针对不同的业务应该有不同的用户信息,也都应该定义成脚本形式,方便管理 最后申请token的操作为 ``` source admin openstack token issue ```
C++
UTF-8
824
3.34375
3
[]
no_license
#include <iostream> using namespace std; class Movie { int prs[3],mtype[4],sum; public: Movie() { prs[0]=50; prs[1]=70; prs[2]=90; mtype[0]=50; mtype[1]=70; mtype[2]=90; mtype[3]=110; } int prize(int n1,int n2,int n3) //n1 for sitting type and n2 is for movie type //n3 is for number of tickets { sum=prs[n1-1]+mtype[n2-1]; sum=sum*n3; return sum; } }; int main(int argc, char const *argv[]) { Movie m; int n1,n2,n3; cout<<"1. 2D Hindi\n"; cout<<"2. 3D Hindi\n"; cout<<"3. 2D English\n"; cout<<"4. 3D English\n"; cout<<"select movie type:\n"; cin>>n1; cout<<"1. silver\n"; cout<<"2. gold\n"; cout<<"3. platinum\n"; cout<<"select setting type:\n"; cin>>n2; cout<<"enter number of tickets:"; cin>>n3; cout<<"prize:"<<m.prize(n1,n2,n3)<<endl; return 0; }
Go
UTF-8
563
2.703125
3
[ "MIT" ]
permissive
package model import "time" // UserTableSQL is the SQL statement for createing a table corresponding to the User model var UserTableSQL = `CREATE TABLE IF NOT EXISTS user ( user_id CHARACTER(36) PRIMARY KEY, account_id CHARACTER(36), is_active INTEGER, created_at DATETIME, updated_at DATETIME );` // User represents a row in the "user" table type User struct { UserID string `db:"user_id"` AccountID string `db:"account_id"` IsActive bool `db:"is_active"` CreatedAt time.Time `db:"created_at"` UpdatedAt time.Time `db:"updated_at"` }
Java
UTF-8
1,319
3.09375
3
[]
no_license
package com.example.kpadmin.encryptionapp; /** * ObjectListNode Class * @author Kunal Purohit * @version 1.0 - November 11,2015 */ public class ObjectListNode { private Object info1; private Object info2; private ObjectListNode next; // Default ctor public ObjectListNode() { info1 = null; info2 = null; next = null; } // One-arg ctor public ObjectListNode(Object o, Object r) { info1 = o; info2 = r; next = null; } public ObjectListNode(Object o) { info1 = o; info2 = null; next = null; } // Two-arg ctor public ObjectListNode(Object o, Object r, ObjectListNode p) { info1 = o; info2 = r; next = p; } // Sets info field public void setInfo1(Object o) { info1 = o; } // Returns object in info field public Object getInfo1() { return info1; } // Sets info field public void setInfo2(Object o) { info2 = o; } // Returns object in info field public Object getInfo2() { return info2; } // Sets next field public void setNext(ObjectListNode p) { next = p; } // Returns object in info field public ObjectListNode getNext() { return next; } }
C++
UTF-8
735
3.15625
3
[]
no_license
#include <iostream> #include <functional> #include <utility> using std::bind; using std::function; using std::cout; using std::endl; using std::placeholders::_1; using std::placeholders::_2; void f (int x, int y, int z) { cout << x << " " << y << " " << z << endl; } void fb (int n1, int n2, int n3, const int& n4, int n5) { cout << n1 << ' ' << n2 << ' ' << n3 << ' ' << n4 << ' ' << n5 << endl; } int main () { function<void()> f_call = bind (f, 1, 2, 3); f_call (); //Equivalent to f (1, 2, 3) function<void(int)> f_call_reord = bind (f, 1, _1, 3); f_call_reord (2); // f (1, 2, 3) int n = 7; auto f1 = bind (fb, _2, _1, 42, std::cref(n), n); n = 10; f1(1, 2, 1001); }
Java
UTF-8
607
2.78125
3
[]
no_license
import com.codingame.gameengine.runner.MultiplayerGameRunner; public class Main { public static void main(String[] args) { MultiplayerGameRunner gameRunner = new MultiplayerGameRunner(); gameRunner.addAgent(Player1.class); gameRunner.addAgent(Player2.class); // gameRunner.addAgent("python3 /home/user/player.py"); // The first league is classic tic-tac-toe gameRunner.setLeagueLevel(1); // The second league is ultimate tic-tac-toe // gameRunner.setLeagueLevel(2); gameRunner.start(); } }
Markdown
UTF-8
5,179
3.59375
4
[]
no_license
# 模式-代理模式(Proxy) ## 代理模式(Proxy) 代理模式是一种结构型的模式。结构型模式的特定是影响对象之间的连接方式,确保系统的变化不需要改变对象间的连接。 代理模式引入一个新的对象,来实现对真实对象的操作,或将新的对象作为真实对象的一个替身,即代理对象。 代理模式的一些作用使用情况: 1. 远程代理:为一个位于不同地址空间的对象提供一个本地的代理对象。 2. 虚拟代理:根据需要创建开销很大的对象,当需要创建一个资源消耗很大的对象时,先创建一个消耗相对较小的对象来表示,真实对象只有在需要时才会被真正创建。 3. 保护代理:控制对原始对象的访问。保护代理用于对象应该有不同的访问权限时。 4. 智能代理:取代了简单的指针,在访问对象时执行一些附加操作。 5. Copy-on-Write 代理:虚拟代理的一种,把复制(克隆)操作延迟到只有客户端真正需要时才执行。对象的深度克隆是一个开销较大的操作。 ## 代理模式的组成 1. 代理角色(Proxy) 1. 保存一个引用使得代理可以访问实体。若RealSubject和Subject接口相同,Proxy会引用Subject。 2. 提供一个与Subject相同的接口,这样代理就可以用来代替实体。 3. 控制实体的存取,创建和删除。 4. 依赖于代理的类型 1. 远程代理负责对请求及参数进行编码,并向不同地址空间中的实体发送已编码的请求 2. 虚拟代理可以缓存实体的附加信息,以便延迟对它的访问 3. 保护代理检查调用者是否具有实现一个请求所需要的访问权限。 2. 抽象主题角色(Subject) 定义代理(Proxy)和真实主题角色(realSubject)共有的接口。 3. 真是主题角色(RealSubject) 定义了代理角色(Proxy)所代表的具体对象 ## 例子 ### 虚拟代理例子 ``` cpp class Subject{ public: virtual ~Subject(){}; virtual void Request() = 0; protected: Subject(){}; }; class RealSubject : public Subject{ public: RealSubject(){}; ~RealSubject(){}; virtual void Request(){}; }; class Proxy : public Subject{ private: RealSubject* m_subject; public: Proxy(){}; ~Porxy(){ if(m_subject != NULL) delete m_subject;}; void Request(){ if(m_subject == NULL) m_subject = new RealSubject(); m_subject->Request(); }; } // 调用 void main(){ Subject* subject = new Proxy(); subject->Request(); delete subject; return 0; } ``` ### 智能代理例子 ``` cpp template<class T> class auto_ptr { public: explicit auto_ptr(T *p = 0): pointee(p) {} auto_ptr(auto_ptr<T>& rhs): pointee(rhs.release()) {} ~auto_ptr() { delete pointee; } auto_ptr<T>& operator=(auto_ptr<T>& rhs) { if (this != &rhs) reset(rhs.release()); return *this; } T& operator*() const { return *pointee; } T* operator->() const { return pointee; } T* get() const { return pointee; } T* release() { T *oldPointee = pointee; pointee = 0; return oldPointee; } void reset(T *p = 0) { if (pointee != p) { delete pointee; pointee = p; } } private: T *pointee; }; ``` 智能指针 ``` cpp template <typename T> class smart_ptr { public: smart_ptr(T *p = 0): pointee(p), count(new size_t(1)) { } //初始的计数值为1 smart_ptr(const smart_ptr &rhs): pointee(rhs.pointee), count(rhs.count) { ++*count; } //拷贝构造函数,计数加1 ~smart_ptr() { decr_count(); } //析构,计数减1,减到0时进行垃圾回收,即释放空间 smart_ptr& operator= (const smart_ptr& rhs) //重载赋值操作符 { //给自身赋值也对,因为如果自身赋值,计数器先减1,再加1,并未发生改变 ++*count; decr_count(); pointee = rhs.pointee; count = rhs.count; return *this; } //重载箭头操作符和解引用操作符,未提供指针的检查 T *operator->() { return pointee; } const T *operator->() const { return pointee; } T &operator*() { return *pointee; } const T &operator*() const { return *pointee; } size_t get_refcount() { return *count; } //获得引用计数器值 private: T *pointee; //实际指针,被代理 size_t *count; //引用计数器 void decr_count() //计数器减1 { if(--*count == 0) { delete pointee; delete count; } } }; ``` ## 本文参考: 1. [http://blog.csdn.net/hguisu/article/details/7542143](http://blog.csdn.net/hguisu/article/details/7542143) 2. [http://blog.csdn.net/wuzhekai1985/article/details/6669219](http://blog.csdn.net/wuzhekai1985/article/details/6669219)
Java
UTF-8
492
2.84375
3
[]
no_license
package utility_classes; public class Reservation_Time { public int Minute; public int Hour; public Reservation_Time(){ this.Minute = 0; this.Hour=0; } public Reservation_Time(int Minute,int Hour){ this.Minute = Minute; this.Hour=Hour; } public void Set_Reservation_Time(int Minute,int Hour){ this.Minute = Minute; this.Hour=Hour; } public String Get_Reservation_Time(){ return String.format(" %d : %d ",this.Hour,this.Minute); } }
Java
UTF-8
3,918
2.921875
3
[]
no_license
package pokemonstuff; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; public class MainSwingScreen extends JPanel implements ActionListener { private PokePlayer player; private JButton walkGrassB; private JButton checkPartyB; private JButton healPokeB; private JButton quitGameB; private JScrollPane scrollPane; public static JTextArea textArea; private static JSplitPane splitPane; private static JPanel topPanel; private static JPanel bottomPanel; public MainSwingScreen(PokePlayer player) { this.player = player; walkGrassB = new JButton("Walk in Grass"); checkPartyB = new JButton("Check Party"); healPokeB = new JButton("Heal pokemon"); quitGameB = new JButton("Quit Game"); textArea = new JTextArea(15, 30); scrollPane = new JScrollPane(textArea); textArea.setEditable(false); topPanel = new JPanel(); bottomPanel = new JPanel(); splitPane = new JSplitPane(0, topPanel, bottomPanel); textArea.append("You chose " + ((Pokemon)player.getParty().get(0)).getPokeName() + "!"); textArea.append("\nYou also gain a PIDGEY pokemon!"); add(splitPane); topPanel.add(walkGrassB); topPanel.add(checkPartyB); topPanel.add(healPokeB); topPanel.add(quitGameB); topPanel.add(scrollPane); bottomPanel.add(scrollPane); topPanel.setLayout(new GridLayout(2, 2)); walkGrassB.setActionCommand("Walk in Grass"); walkGrassB.addActionListener(this); checkPartyB.setActionCommand("Check Party"); checkPartyB.addActionListener(this); healPokeB.setActionCommand("Heal pokemon"); healPokeB.addActionListener(this); quitGameB.setActionCommand("Quit Game"); quitGameB.addActionListener(this); } public static void createAndShowGUI(PokePlayer player) { JFrame frame = new JFrame("Choose an Action"); frame.setDefaultCloseOperation(3); MainSwingScreen newContentPane = new MainSwingScreen(player); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.pack(); frame.setSize(StartingPokeSwing.WIDTH, StartingPokeSwing.HEIGHT); frame.setVisible(true); } public void actionPerformed(ActionEvent ae) { Pokemon currentPoke = null; Pokemon wildPoke = null; int chance = (int)(Math.random() * 100.0D); for (int i = 0; i < player.getParty().size(); i++) { if (((Pokemon)player.getParty().get(i)).getHp() > 0) { currentPoke = (Pokemon)player.getParty().get(i); break; } } if (ae.getActionCommand().equals("Walk in Grass")) { textArea.append("\nYou walk in Grass"); if (chance <= 75) { if (chance <= 25) { wildPoke = new Pokemon(PokeName.PIDGEY); } else if ((chance > 25) && (chance <= 50)) { wildPoke = new Pokemon(PokeName.RATTATA); } else if (chance > 50) { wildPoke = new Pokemon(PokeName.BIDOOF); } BattleSwingScreen.createAndShowGUI(player, currentPoke, wildPoke); } else { textArea.append("\nYou find no Pokemon in the grass"); } } else if (ae.getActionCommand().equals("Check Party")) { CheckPokeSwing.createAndShowGUI(player, currentPoke); } else if (ae.getActionCommand().equals("Heal pokemon")) { for (int j = 0; j < player.getParty().size(); j++) { ((Pokemon)player.getParty().get(j)).setHp(((Pokemon)player.getParty().get(j)).getMaxHp()); } textArea.append("\nYou heal your Pokemon at the pokemon center"); } else if (ae.getActionCommand().equals("Quit Game")) { System.exit(0); } } }
Markdown
UTF-8
9,710
2.6875
3
[ "Apache-2.0" ]
permissive
grunt-nunjucks-render ===================== [![Build Status](https://travis-ci.org/piwi/grunt-nunjucks-render.svg?branch=master)](https://travis-ci.org/piwi/grunt-nunjucks-render) [![Code Climate](https://codeclimate.com/github/piwi/grunt-nunjucks-render/badges/gpa.svg)](https://codeclimate.com/github/piwi/grunt-nunjucks-render) This is a [grunt](http://gruntjs.com/) plugin to render [nunjucks](http://mozilla.github.io/nunjucks/) templates and strings. It takes data in `JSON` or `YAML` format and allows to configure *nunjucks* in *Grunt* tasks. Getting Started --------------- This plugin requires Grunt `~0.4.1` and Node `~0.10.0`. Please first have a look at the [Getting Started](http://gruntjs.com/getting-started) guide of Grunt. You may install this plugin with this command: ```shell npm install grunt-nunjucks-render --save-dev ``` Once the plugin is installed, it may be enabled inside your `Gruntfile.js` with this line of JavaScript: ```js grunt.loadNpmTasks('grunt-nunjucks-render'); ``` The "nunjucks_render" task -------------------------- ### Overview In your project's Gruntfile, add a section named `nunjucks_render` to the data object passed into `grunt.initConfig()`: ```js grunt.initConfig({ nunjucks_render: { options: { // task global options go here }, your_target: { options: { // target specific options go here }, files: [ { data: // path to JSON or YAML file(s) src: // path to template file(s) dest: // path to output destination file(s) str: // direct string(s) to parse (before templates by default) str_prepend: // direct string(s) to parse and concat before templates str_append: // direct string(s) to parse and concat after templates } ] } } }); ``` See the [dedicated page](http://gruntjs.com/configuring-tasks#files-array-format) to learn how to build your `files` objects. Note that some properties are added here: - `data` to define a list of files to get the parsing data, - `str`, `str_prepend` and `str_append` to define some raw strings to parse and concatenate to the final rendering. ### Environment A special [*nunjucks* environment loader](http://mozilla.github.io/nunjucks/api.html#loader) is designed by the plugin to use a full set of options when searching templates (original and included ones). The loader is defined in `lib/loader.js`. The `template_path` environment variable will always contain the path of the current parsed template (the current file), even for inclusions. The `template_date` environment variable will always contain the date of the current parsing, even for inclusions. The plugin embeds the [date-filter](https://www.npmjs.com/package/nunjucks-date-filter) natively to let you write formated dates: {{ my_date | date() }} // with default format {{ my_date | date('YYY') }} // with custom format ### Options Options can be defined globally for the `nunjucks_render` task or for each target. The target options will always overload global settings. A "*template*" here is a raw template, defined as the `src` item of a target files, or a *nunjucks* included template. - **searchPaths** - Type: `String`, `Array` - Default value: `"."` (i.e. relative to your `Gruntfile.js`) - One or more paths to be scanned by the template loader while searching *nunjucks* templates. By default, the loader will search in **all** directories of the root directory. If `baseDir` is defined and the template is found in it, this file will be used. - **baseDir** - Type: `String` - Default value: `"."` (i.e. relative to your `Gruntfile.js`) - Path to the directory in which *nunjucks* will first search templates. This directory name is striped from templates files `name` entry. - **extensions** - Type: `String`, `Array` - Default value: `".j2"` (for *jinja2*) - One or more file extensions to use by the template loader while searching *nunjucks* templates. This allows you to write `{% include my-partial %}` instead of `{% include my-partial.j2 %}`. - **autoescape** - Type: `Boolean` - Default value: `false` - Force data escaping by *nunjucks* (see <http://mozilla.github.io/nunjucks/api.html#configure>). - **watch** - Type: `Boolean` - Default value: `true` - Force *nunjucks* to watch template files updates (see <http://mozilla.github.io/nunjucks/api.html#configure>). - **data** - Type: `Object`, `String` (filename), `Array` (array of filenames) - Default value: `null` - Can be used to fill in a default `data` value for a whole task or a target. This will be merged with "per-file" data (which have precedence). - **processData** - Type: `Function` - Default: `null` - Define a function to transform data as a pre-compilation process (before to send them to *nunjucks*). - **name** - Type: `RegExp`, `Function` - Default value: `/.*/` - A regular expression or function to build final template name. Default is the filename. - **asFunction** - Type: `Boolean` - Default value: `false` - Use this to return the raw *precompiled* version of the *nunjucks* content instead of its final rendering. - **env** - Type: `nunjucks.Environment` - Default value: `null` - A custom *nunjucks* environment to use for compilation (see <http://mozilla.github.io/nunjucks/api.html#environment>). - **strAdd** - Type: `String` in "*prepend*" or "*append*" - Default value: `"prepend"` - The default process to execute on the `str` files entry. By default, strings will be parsed and *prepended* to final rendering (i.e. displayed before templates contents). Note that when this argument is `prepend`, the `str` items will be added AFTER any `str_prepend` other items while if it is `append`, the `str` items will be added BEFORE any other `str_append` items. - **strSeparator** - Type: `String` - Default value: `"\n"` - A string used to separate parsed strings between them and from templates contents. #### Examples You can have a look at the `Gruntfile.js` of the plugin for various usage examples. Define a base path for all parsed files: ```js options: { baseDir: 'templates/to/read/' }, files: { 'file/to/output-1.html': 'file-1.j2', 'file/to/output-2.html': 'file-2.j2', 'file/to/output-3.html': 'file-3.j2' } ``` Define a global `data` table for all parsed files: ```js options: { data: { name: "my name", desc: "my description" } }, files: { 'file/to/output.html': 'template/to/read.j2' } ``` Define a global JSON data file for all parsed files: ```js options: { data: 'commons.json' }, files: { 'file/to/output-1.html': 'template/to/read-1.j2', 'file/to/output-2.html': 'template/to/read-2.j2', 'file/to/output-3.html': 'template/to/read-3.j2' } ``` Define a global `data` table for all targets, over-written by a "per-target" data: ```js options: { data: { name: "my name", desc: "my description" } }, my_target: { files: { data: { desc: "my desc which will over-write global one" }, src: 'template/to/read.j2', dest: 'file/to/output.html' } } ``` Define a full set of [grunt files](http://gruntjs.com/configuring-tasks#files-array-format): ```js files: [ { expand: true, src: 'template/to/read-*.j2', data: 'common-data.json', dest: 'dest/directory/' } ] ``` Usage of the `str` argument: ```js files: { data: { desc: "my desc which will over-write global one" }, src: 'template/to/read.j2', dest: 'file/to/output.html', str: "My nunjucks string with var: {{ username }}" } ``` ```js files: { data: { desc: "my desc which will over-write global one" }, src: 'template/to/read.j2', dest: 'file/to/output.html', str: [ "My first nunjucks string with var: {{ username }}", "My second nunjucks string with var: {{ username }}" ] } ``` Use the module in your tasks ---------------------------- As this module defines "non-tasked" functions, you can use the followings in your own tasks or modules. ### `NunjucksRenderFile` var NunjucksRenderFile = require('grunt-nunjucks-render/lib/render-file'); var content = NunjucksRenderFile( filepath , data[ , options ][ , nunjucks.Environment ]); ### `NunjucksRenderString` var NunjucksRenderString = require('grunt-nunjucks-render/lib/render-string'); var content = NunjucksRenderString( str , data[ , options ][ , nunjucks.Environment ]); Related third-parties links --------------------------- - [Grunt](http://gruntjs.com/), a task runner - [Nunjucks](http://mozilla.github.io/nunjucks/), a templating engine for JavaScript - [Jinja2](http://jinja.pocoo.org/), the first inspiration of *Nunjucks* - [JSON](http://json.org/), the *JavaScript Object Notation* - [YAML](http://yaml.org/), a human friendly data serialization - [moment.js](http://momentjs.com/), a date/time manager - [nunjucks-date-filter](https://www.npmjs.com/package/nunjucks-date-filter), an implementation of *momentjs* for *nunjucks* Contributing ------------ In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).
Java
UTF-8
1,911
3.515625
4
[]
no_license
package dataStructuresAndAbstractionsGennemgang; public class Noter { /** * Noter: While the roots of most plants are firmly in the ground, the root * of an ADT tree is at the tree’s top; it is the origin of a hierarchical * organization. Each node can have children. A node with children is a * parent; a node without children is a leaf. The root is the only node that * has no parent; all other nodes have one parent each * * * In general, each node in a tree can have an arbitrary number of children. * We sometimes call such a tree a general tree. If each node has no more * than n children, the tree is called an n-ary tree. Realize that not every * general tree is an n-ary tree. If each node has at most two children, the * tree is called a binary tree. * * All leaves in a full binary tree are on the same level and every nonleaf * has exactly two children. A complete binary tree is full to its * next-to-last level, and its leaves on the last level are filled from left * to right. Binary trees are used extensively, and these special trees will * be important to our later discussions. * * brug til matematik: Now, if n is the number of nodes in a full tree, we * have the following results: n = 2h - 1 2h = n + 1 h = log2 (n + 1) That * is, the height of a full tree that has n nodes is log2 (n + 1). Der er * mere om dette ovre i Test klassen. * * Traversals: Note: Traversals of a binary tree A preorder traversal visits * the root of a binary tree before visiting the nodes in its two subtrees. * An inorder traversal visits the root between visiting the nodes in its * two subtrees. A postorder traversal visits the root after visiting the * nodes in its two subtrees. A level-order traversal visits nodes from left * to right within each level of the tree, beginning with the root. */ }
C#
UTF-8
5,785
2.890625
3
[]
no_license
using System; using System.Collections.Immutable; using System.Linq; namespace NNLib.Csv { /// <summary> /// Used to choose input, target and ignored attributes of training data from csv file. /// </summary> public class SupervisedSetVariableIndexes { private readonly ImmutableArray<int> _ignored; private readonly ImmutableArray<int> _inputVarIndexes; private readonly ImmutableArray<int> _targetVarIndexes; public ImmutableArray<int> Ignored => Error == null ? _ignored : throw new ArgumentException(Error); public ImmutableArray<int> InputVarIndexes => Error == null ? _inputVarIndexes : throw new ArgumentException(Error); public ImmutableArray<int> TargetVarIndexes => Error == null ? _targetVarIndexes : throw new ArgumentException(Error); public SupervisedSetVariableIndexes(int[] inputVarIndexes, int[] targetVarIndexes, int[] ingored) : this(inputVarIndexes, targetVarIndexes) { _ignored = ingored.ToImmutableArray(); } private SupervisedSetVariableIndexes(ImmutableArray<int> inputVarIndexes, ImmutableArray<int> targetVarIndexes, ImmutableArray<int> ignored) => (_inputVarIndexes, _targetVarIndexes, _ignored) = (inputVarIndexes, targetVarIndexes, ignored); public SupervisedSetVariableIndexes(int[] inputVarIndexes, int[] targetVarIndexes) { if (inputVarIndexes.Intersect(targetVarIndexes).Any()) { Error = "inputVarIndexes and targetVarIndexes contains the same elements"; } if (inputVarIndexes.Length <= 0) { Error = "Input variable(s) must be set"; } if (targetVarIndexes.Length <= 0) { Error = "Target variable(s) must be set"; } Array.Sort(inputVarIndexes); Array.Sort(targetVarIndexes); if (_ignored.IsDefault) { _ignored = ImmutableArray<int>.Empty; } _inputVarIndexes = inputVarIndexes.ToImmutableArray(); _targetVarIndexes = targetVarIndexes.ToImmutableArray(); } public string? Error { get; private set; } public SupervisedSetVariableIndexes ChangeVariableUse(int index, VariableUses variableUse) { if (variableUse == VariableUses.Ignore) { return IgnoreVariable(index); } ImmutableArray<int> newInputVars; ImmutableArray<int> newTargetVars; ImmutableArray<int> new_ignored = _ignored; if (variableUse == VariableUses.Target && _inputVarIndexes.Contains(index)) { newInputVars = _inputVarIndexes.Remove(index); newTargetVars = _targetVarIndexes.Add(index); } else if (variableUse == VariableUses.Input && _targetVarIndexes.Contains(index)) { newInputVars = _inputVarIndexes.Add(index); newTargetVars = _targetVarIndexes.Remove(index); } else if (_ignored.Contains(index)) { new_ignored = new_ignored.Remove(index); if (variableUse == VariableUses.Input) { newInputVars = _inputVarIndexes.Add(index); newTargetVars = _targetVarIndexes; } else { newInputVars = _inputVarIndexes; newTargetVars = _targetVarIndexes.Add(index); } } else if ((variableUse == VariableUses.Input && _inputVarIndexes.Contains(index)) || (variableUse == VariableUses.Target && _targetVarIndexes.Contains(index))) { newInputVars = _inputVarIndexes; newTargetVars = _targetVarIndexes; } else { throw new Exception(); } return new SupervisedSetVariableIndexes(newInputVars.ToArray(), newTargetVars.ToArray(), new_ignored.ToArray()); } private SupervisedSetVariableIndexes IgnoreVariable(int index) { ImmutableArray<int> newInputVars; ImmutableArray<int> newTargetVars; ImmutableArray<int> new_ignored = _ignored; if (_inputVarIndexes.Contains(index)) { if (_inputVarIndexes.Length == 1) { Error = "Input variables must be set"; } newInputVars = _inputVarIndexes.Remove(index); newTargetVars = _targetVarIndexes; } else if (_targetVarIndexes.Contains(index)) { if (_targetVarIndexes.Length == 1) { Error = "Target variables must be set"; } newInputVars = _inputVarIndexes; newTargetVars = _targetVarIndexes.Remove(index); } else if (_ignored.Contains(index)) { return new SupervisedSetVariableIndexes(_inputVarIndexes.ToArray(), _targetVarIndexes.ToArray(), _ignored.ToArray()); } else { throw new Exception($"_ignored array doesn't contain {index} index"); } new_ignored = new_ignored.Add(index); return new SupervisedSetVariableIndexes(newInputVars.ToArray(), newTargetVars.ToArray(), new_ignored.ToArray()); } public SupervisedSetVariableIndexes Clone() => new SupervisedSetVariableIndexes(_inputVarIndexes, _targetVarIndexes, _ignored); } }
Java
UTF-8
822
1.601563
2
[]
no_license
package com.netty.battery.maintenance.service; import com.netty.battery.maintenance.config.ServerResponse; import com.netty.battery.maintenance.pojo.BasChaPilPojo; import com.github.pagehelper.PageInfo; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** * *************************************************** * * @Auther: zianY * @Descipion: TODO * @CreateDate: 2019-11-15 * **************************************************** */ public interface ChargingService { /** * 测试 * @return */ ServerResponse getUserInfo(); ServerResponse startService() throws Exception; Integer stopService(String chaIp,String chaNum); // 根据桩id 查询桩ip及端口号等信息 List<BasChaPilPojo> selChaIp(String chaId,String chaNum); }
C++
UTF-8
732
2.59375
3
[]
no_license
#pragma once #include "GraphicObject.h" struct WeaponInfo { int bullets_id; short xw, yw; float deley; char *particle; char *sprite; }; class Weapon: public GraphicObject { Weapon(); public: Weapon(hgeVector pos, short layer); virtual ~Weapon(); void Initiate(WeaponInfo &info); void RotateTo(const hgeVector &taget); void RotateTo(float x, float y); virtual void Render(); virtual void Fire(float x, float y); virtual void Update(); virtual void UpdateGraphic(); void SetDir(hgeVector dir) { this->dir = dir; } protected: hgeVector dir; int bullets_id; hgeParticleSystem *particle; hgeSprite *sprite; float deley; float timer; bool firing; };
C#
UTF-8
7,843
3.03125
3
[]
no_license
using System; using System.Drawing; using System.Linq; using Vkm.Api.Basic; using Vkm.Api.Options; namespace Vkm.Common { public static class DefaultDrawingAlgs { public static void DrawIconAndText(BitmapEx bitmap, FontFamily iconFontFamily, string iconSymbol, FontFamily textFontFamily, string text, string textExample, Color color) { var textHeight = (text != null)?FontEstimation.EstimateFontSize(bitmap, textFontFamily, textExample):0; var imageHeight = (int) (bitmap.Height * 0.9 - textHeight); using (var graphics = bitmap.CreateGraphics()) using (var whiteBrush = new SolidBrush(color)) using (Font textFont = (textHeight > 0)?new Font(textFontFamily, textHeight, GraphicsUnit.Pixel): null) using (Font imageFont = new Font(iconFontFamily, imageHeight, GraphicsUnit.Pixel)) { var size = graphics.MeasureString(text, textFont); graphics.DrawString(text, textFont, whiteBrush, bitmap.Width - size.Width, bitmap.Height - size.Height); graphics.DrawString(iconSymbol, imageFont, whiteBrush, 0, 0); } } public static void DrawCaptionedIcon(BitmapEx bitmap, FontFamily iconFontFamily, string iconSymbol, FontFamily textFontFamily, string text, string textExample, Color color) { DrawElements(bitmap, new TextDrawElement(iconFontFamily, iconSymbol, color, 70, StringAlignment.Center), new TextDrawElement(textFontFamily, text, color, 30, StringAlignment.Center)); } internal static void DrawElements(BitmapEx bitmap, params TextDrawElement[] elements) { using (var graphics = bitmap.CreateGraphics()) { int yPosition = 0; for (var index = 0; index < elements.Length; index++) { TextDrawElement element = elements[index]; var maxHeight = bitmap.Height * element.Percentage / 100; var textHeight = (element.Text != null)?FontEstimation.EstimateFontSize(bitmap, element.FontFamily, element.Text, alterHeight:maxHeight):0; using (var brush = new SolidBrush(element.Color)) using (Font textFont = (textHeight > 0)?new Font(element.FontFamily, textHeight, GraphicsUnit.Pixel): null) { var size = graphics.MeasureString(element.Text, textFont); float x = 0; if (element.Alignment == StringAlignment.Center) x = (bitmap.Width - size.Width) / 2; else if (element.Alignment == StringAlignment.Far) x = (bitmap.Width - size.Width); graphics.DrawString(element.Text, textFont, brush, x, yPosition + (maxHeight - size.Height) / 2); } yPosition += maxHeight; } } } public static void DrawTexts(BitmapEx bitmap, FontFamily fontFamily, string l1, string l2, string textExample, Color color) { var textHeight = FontEstimation.EstimateFontSize(bitmap, fontFamily, textExample); using (var graphics = bitmap.CreateGraphics()) using (var whiteBrush = new SolidBrush(color)) using (var textFont = new Font(fontFamily, textHeight, GraphicsUnit.Pixel)) { var size = graphics.MeasureString(l1, textFont); graphics.DrawString(l1, textFont, whiteBrush, bitmap.Width - size.Width, 0); size = graphics.MeasureString(l2, textFont); graphics.DrawString(l2, textFont, whiteBrush, bitmap.Width - size.Width, bitmap.Height / 2); } } public static void DrawText(BitmapEx bitmap, FontFamily fontFamily, string text, Color color) { var height = FontEstimation.EstimateFontSize(bitmap, fontFamily, text); using (var graphics = bitmap.CreateGraphics()) using (var whiteBrush = new SolidBrush(color)) using (var font = new Font(fontFamily, height, GraphicsUnit.Pixel)) { var size = graphics.MeasureString(text, font); if (size.Width / size.Height > 5) { var splittedText = SplitText(text); if (splittedText != text) { DrawText(bitmap, fontFamily, splittedText, color); return; } } graphics.DrawString(text, font, whiteBrush, (bitmap.Width - size.Width) / 2, (bitmap.Height - size.Height) / 2); } } public static void DrawPlot(BitmapEx bitmap, Color color, int[] values, int fromY, int toY, int startIndex = 0, double? minValue = null, double? maxValue = null) { DrawPlot(bitmap, color, values.Select(v=>(double)v).ToArray(), fromY, toY, startIndex, minValue, maxValue); } public static void DrawPlot(BitmapEx bitmap, Color color, double[] values, int fromY, int toY, int startIndex = 0, double? minValue = null, double? maxValue = null) { var min = double.MaxValue; var max = double.MinValue; if (minValue == null || maxValue == null) { for (int i = startIndex; i < values.Length; i++) { if (min > values[i]) min = values[i]; if (max < values[i]) max = values[i]; } } min = minValue ?? min; max = maxValue ?? max; var coef = (max != min) ? ((toY - fromY) / ((max - min))) : 0; var midY = (toY + fromY) / 2; var midValue = (max + min) / 2.0; Point[] points = new Point[values.Length - startIndex]; for (int i = startIndex; i < values.Length; i++) { points[i-startIndex] = new Point(i-startIndex, (int)(midY - (values[i]-midValue)*coef)); } using (var graphics = bitmap.CreateGraphics()) using (var pen = new Pen(color)) { graphics.DrawCurve(pen, points); } } private static string SplitText(string text) { int pos = 0; for (int i = 0; i < Math.Min(text.Length, text.Length-pos); i++) { if (text[i] == ' ') pos = i; } if (pos > 0) { text = text.Substring(0, pos) + "\n" + text.Substring(pos + 1); } return text; } public static void SelectElement(BitmapEx bitmap, ThemeOptions themeOptions) { using (var graphics = bitmap.CreateGraphics()) using (var pen = new Pen(themeOptions.ForegroundColor, 3)) { graphics.DrawRectangle(pen, 0, 0, bitmap.Width, bitmap.Height); } } } internal struct TextDrawElement { public readonly string Text; public readonly FontFamily FontFamily; public readonly Color Color; public readonly byte Percentage; public readonly StringAlignment Alignment; public TextDrawElement(FontFamily fontFamily, string text, Color color, byte percentage, StringAlignment alignment) { Text = text; FontFamily = fontFamily; Color = color; Percentage = percentage; Alignment = alignment; } } }
Python
UTF-8
149
3.046875
3
[]
no_license
from random import randint import sys n = int(sys.argv[1]) a = [] for i in range(n): a.append(randint(1,6)) b = sum(a)/n print(a) print(b)
Java
UTF-8
3,523
2.375
2
[]
no_license
/* * 广州丰石科技公司有限公司拥有本软件版权2017并保留所有权利。 * Copyright 2017, Guangzhou Rich Stone Data Technologies Company Limited, * All rights reserved. * */ package com.richstonedt.road.query.engine.cs.common; import com.richstonedt.road.query.engine.model.common.RoadQueryEngineException; import com.richstonedt.road.query.engine.model.excel.ExcelFile; import com.richstonedt.road.query.engine.model.excel.ExcelSheet; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * <b><code>CityRoadsInfoReader</code></b> * <p> * class_comment * </p> * <b>Create Time:</b> 2017/1/23 17:02 * * @author Hetian Zhu * @version 0.1.0 * @since road-query-engine-cs 0.1.0 */ public class CityRoadsInfoReader { private final static Logger LOG = LoggerFactory.getLogger(CityRoadsInfoReader.class); /** * getRoadExcelInfo * * @return java.util.List<com.richstonedt.road.query.engine.model.excel.ExcelFile> * @see List<ExcelFile> * @since road-query-engine-cs 0.1.0 */ public static List<ExcelFile> getRoadExcelInfo(){ /* Read city roads info from cityRoadInfo.json */ String jsonString = readExcelFileInfoFromJson(); JSONObject jsonObject = JSONObject.fromObject(jsonString); JSONArray files = jsonObject.getJSONArray("files"); List<ExcelFile> result = new ArrayList<>(); /* Generate ExcelFile from JSON Object */ for (int i = 0; i < files.size(); i++) { JSONObject object = files.getJSONObject(i); ExcelFile excel = new ExcelFile(); excel.setFilePath(object.getString("filePath")); excel.setCityCode(object.getString("cityCode")); List<ExcelSheet> sheets = new ArrayList<>(); JSONArray jsonSheets = object.getJSONArray("sheetNameList"); for (int j = 0; j < jsonSheets.size(); j++) { JSONObject jsonSheet = jsonSheets.getJSONObject(j); ExcelSheet sheet = new ExcelSheet(); sheet.setName(jsonSheet.getString("name")); sheet.setStartRow(jsonSheet.getInt("startRow")); sheet.setEndRow(jsonSheet.getInt("endRow")); sheet.setStartCol(jsonSheet.getInt("startCol")); sheet.setEndCol(jsonSheet.getInt("endCol")); sheets.add(sheet); } excel.setSheets(sheets); result.add(excel); } return result; } /** * readExcelFileInfoFromJson * * @return java.lang.String * @see String * @since road-query-engine-cs 0.1.0 */ private static String readExcelFileInfoFromJson(){ InputStream is = CityRoadsInfoReader.class.getResourceAsStream("/cityRoadInfo.json"); StringBuilder stringBuilder = new StringBuilder(); Scanner scanner = null; try{ scanner = new Scanner(is); while (scanner.hasNextLine()){ stringBuilder.append(scanner.nextLine()); } return stringBuilder.toString(); }catch(Exception e){ LOG.error("Fail to read cityRoadInfo.json"); throw new RoadQueryEngineException(e); }finally { if (scanner!=null){ scanner.close(); } } } }
Markdown
UTF-8
2,619
2.546875
3
[]
no_license
# Resume * * * ## Work Experience - **RuleMeister Inc. | Software Application/ Full-stack Developer Nov 2018 - PRESENT | Alhambra, CA** - Maintained and built a healthcare management system. Including authorization, claim submission, process and reporting. This suite also includes patient/healthcare provider/vendor management. - Designed and developed document repository service. This service provides file operations across different management systems. - Researched and integrated third party API with web application system. - Conducted front-end unit testing with Jasmine/Karma for the angular application, and back-end testing for back-end service built in C# with NUnit. - Monitored, tested and maintained existing weekly/monthly SSRS reports. Worked with clients to design and build ad-hoc reports or automatically reporting processes. - **Titanium Plus Auto Parts Inc. | Software Engineer Aug 2017 - Nov 2018 | City of Industry, CA** - Developed and directed software system validation and testing methods. - Worked closely with clients and cross-functional departments to communicate project statuses and proposals. - Developed, refined functions to company built, existing WMS (warehouse management system) with C# (WinForm) and MS SQL. - Third party API integration with WMS to make order fulfillment automatically, accurately and efficiently. Responsible for developing, maintaining Amazon MWS, eBay, Walmart, Magento API functionalities. - **California State Polytechnic University, Pomona Digital Service & Technology Department | Student Programmer Feb 2016 - June 2017 | Pomona, CA** - Built a system for school graduate thesis format checking using Java. - The system is able to detect format errors correctly and efficiently: for a 100 pages document, the system takes less than 10 seconds to finish the process, and can detect about 90\% formatting errors. - **California State Polytechnic University, Pomona Department of Computer Science | Grader Feb 2016 - June 2017 | Pomona, CA** - CS 331 (Design and Analysis of Algorithms) - CS 431 (Operating System) - CS 537 (Scheduling algorithm) ## Skills - C# - Angular - Python - Jasmine/Karma - Java - SQL(MS SQL) - SSRS - HTML/CSS - TFS/Git - Familar: C#, Angular, SQL ## Education - California State Polytechnic University, Pomona | 09/2015-06/2017 Master's degree in Computer Science - National Taiwan Normal University | 09/2011-06/2015 Bachelor's degree in Computer Science and Information Engineering ## Resume in PDF format [PDF](misc/resume2021.pdf)
Shell
UTF-8
1,913
2.6875
3
[ "MIT" ]
permissive
#!/bin/bash # Place the CUDA_VISIBLE_DEVICES="xxxx" required before the python call # e.g. to specify the first two GPUs in your system: CUDA_VISIBLE_DEVICES="0,1" python ... # SEGAN with no pre-emph and no bias in conv layers (just filters to downconv + deconv) #CUDA_VISIBLE_DEVICES="2,3" python main.py --init_noise_std 0. --save_path segan_vanilla \ # --init_l1_weight 100. --batch_size 100 --g_nl prelu \ # --save_freq 50 --epoch 50 # SEGAN with pre-emphasis to try to discriminate more high freq (better disc of high freqs) #CUDA_VISIBLE_DEVICES="1,2,3" python main.py --init_noise_std 0. --save_path segan_preemph \ # --init_l1_weight 100. --batch_size 100 --g_nl prelu \ # --save_freq 50 --preemph 0.95 --epoch 86 # Apply pre-emphasis AND apply biases to all conv layers (best SEGAN atm) BATCH_SIZE=256 TYPE=4 DATA_PATH=/scratch4/sniu/data/multi_segan_n5.tfrecords SAVE_PATH=/scratch4/sniu/segan declare -A types types=([1]="I" [2]="II" [3]="III" [4]="IV" [5]="V") CUDA_VISIBLE_DEVICES="0,1" python main.py --init_noise_std 0. \ --init_l1_weight 100. --batch_size ${BATCH_SIZE} --g_nl prelu \ --save_path ${SAVE_PATH}/type_v${TYPE}_b${BATCH_SIZE} \ --synthesis_path ${SAVE_PATH}/dwavegan_samples \ --e2e_dataset ${DATA_PATH} \ --save_clean_path ${SAVE_PATH}/test_clean_results_v${TYPE}_b${BATCH_SIZE} \ --save_freq 200 --preemph 0.95 --epoch 86 --bias_deconv True \ --bias_downconv True --bias_D_conv True --decoder_type ${types[${TYPE}]} \
PHP
UTF-8
434
3.40625
3
[]
no_license
<?php /** * Class AddressManager * 使用拦截器 __call() */ class Person{ function __call($method, $args){ $i = 1; $args_str = ''; foreach($args as $v){ $args_str .= "arg ".$i." is (".$v.")"; $i ++; } exit("you called an unexist funciton {$method}, and {$args_str}"); } } $person = new Person(); $person -> hello('arg1','arg2','xxxxx','asdfasdfa');
C#
UTF-8
254
3.09375
3
[]
no_license
using System; namespace pattern_Bridge { class DrawingAPI2 : DrawingAPI { public void drawCircle(double x, double y, double radius) { Console.WriteLine($"API2.circle at {x}:{y} radius {radius}\n"); } } }
Python
UTF-8
444
2.953125
3
[]
no_license
import socket import sys HOST='127.0.0.1' PORT=50007 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((HOST,PORT)) except Exception as e: print('Server not found or not open') sys.exit() while True: c=input('Input the content you want to send:') s.sendall(c.encode()) data=s.recv(1024) data=data.decode() print('Received:',data) if c.lower()=='bye': break s.close()
Java
UTF-8
826
3.0625
3
[]
no_license
package com.polopoly.ps.pcmd.parser; import java.io.File; import java.io.IOException; public class ExistingFileParser implements Parser<File> { public String getHelp() { return "a file name (relative or absolute)"; } public File parse(String fileName) throws ParseException { File file = new File(fileName); validate(file); if (!file.exists()) { throw new ParseException(this, fileName, "The file " + file.getAbsolutePath() + " did not exist."); } try { file = file.getCanonicalFile(); } catch (IOException e) { System.err.println("Could not turn " + file.getAbsolutePath() + " into a canonical path."); } return file; } protected void validate(File file) throws ParseException { } }
C#
UTF-8
1,122
2.703125
3
[]
no_license
using Movies.Core.Entities; using Movies.Core.Interfaces; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Movies.Infrastructure.DataAccess.Repositories { public class MovieSampleRepository : IMovieRepository { public Task<Movie> AddMovieAsync(Movie entity) { throw new NotImplementedException(); } public Task<Movie> DeleteMovieAsync(int id) { throw new NotImplementedException(); } public Task<Movie> GetMovieAsync(int id) { throw new NotImplementedException(); } public async Task<IEnumerable<Movie>> GetMoviesAsync(Movie entity) { var movies = new List<Movie>() { new Movie() { Id = 1, Title = "Titanic", Year = 1997 }, new Movie() { Id = 2, Title = "Space Jam", Year = 1995 } }; return movies; } public Task<Movie> UpdateMovieAsync(Movie entity) { throw new NotImplementedException(); } } }
Java
UTF-8
1,087
4.125
4
[]
no_license
package project4; /** * Point class * Creates variables and methods for a point object * @author Carole-Anne */ public class Point { private int x; private int y; /** * Point constructor * Instantiates coordinates of a point object * @param a - x coordinate * @param b - y coordinate */ public Point(int a, int b) { x = a; y = b; } /** * Equals method * Checks if two points are equal * @param otherPoint - point to be compared * @return true if equal, false if not */ public boolean equals(Point otherPoint) { if ((otherPoint.x == this.x) && (otherPoint.y == this.y)) return true; else return false; } /** * get X * Gets the x coordinate of a point * @return int x. */ public int getX() { return this.x; } /** * get Y * Gets the y coordinate of a point * @return int y. */ public int getY() { return this.y; } /** * toString * Returns the state of a point object * @return String- a message with the state of the point */ public String toString() { return "Point: " + x +"," + y; } }
PHP
UTF-8
34,658
2.578125
3
[]
no_license
<?php require_once("includes/validate_credentials.php"); ?> <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang=""> <!--<![endif]--> <head> <?php require_once("includes/head.php"); ?> </head> <body> <?php $id=$Hash->decrypt($_GET['id']); $stmt = $database->query("SELECT * FROM institution_details WHERE id = '$id'"); $row = $database->fetch_array($stmt); ?> <?php // save new car $user= $_SESSION['username']; if(isset($_POST['savec'])){ $_POST = array_map( 'stripslashes', $_POST ); //collect form data extract($_POST); if(!isset($error)){ try { $owner = $row['id']; //insert into database $stmtca = $database->query("INSERT INTO cars (plate_nber,model,insurance_camp,owner,status) VALUES ('$plate_nber', '$model', '$insurance_camp', '$owner', 'active')") ; //redirect to index page $values['id']=$row['id']; header('Location: display.php?id='. $Hash->encrypt($values['id']).''); exit; } catch(PDOException $e) { echo $e->getMessage(); } } } // save new house if(isset($_POST['saveh'])){ $_POST = array_map( 'stripslashes', $_POST ); //collect form data extract($_POST); if(!isset($error)){ try { $owner = $row['id']; $stmtca = $database->query("INSERT INTO location (province,district,sector,cell,plot_nber,country,status) VALUES ('$province', '$district', '$sector', '$cell',' $plot_nber', '$country', 'active')") ; $id_location= $database->inset_id(); //insert into database $stmtca = $database->query("INSERT INTO houses (type,owner,id_location, status) VALUES ('$type', '$owner', '$id_location', 'active')"); //redirect to index page $values['id']=$row['id']; header('Location: display.php?id='. $Hash->encrypt($values['id']).''); exit; } catch(PDOException $e) { echo $e->getMessage(); } } } // add a comment if(isset($_POST['send'])){ $_POST = array_map( 'stripslashes', $_POST ); //collect form data extract($_POST); if(!isset($error)){ try { $owner = $row['id']; $id_institution= $row['id_institution']; $stmtcat = $database->query("SELECT * FROM institution WHERE id = '$id_institution'"); $rowtype = $database->fetch_array($stmtcat); $type= $rowtype['Name']; $time= date('Y-m-d H:i:s'); //insert into database $stmtca = $database->query("INSERT INTO comments (user,comment,type,owner,time,status) VALUES ('$user', '$comment', '$type', '$owner', '$time', 'active')") ; //redirect to index page $valuered['id']=$row['id']; header('Location: display.php?id='.$Hash->encrypt($valuered['id']).''); exit; } catch(PDOException $e) { echo $e->getMessage(); } } } //check for any errors if(isset($error)){ foreach($error as $error){ echo '<p class="error">'.$error.'</p>'; } } ?> <!-- Left Panel --> <?php require_once 'includes/left_nav.php'; ?> <!-- Left Panel --> <!-- Right Panel --> <div id="right-panel" class="right-panel"> <!-- Header--> <?php require_once 'includes/top_nav.php'; ?> <!-- Header--> <div class="breadcrumbs"> <div class="col-sm-4"> <div class="page-header float-left"> <div class="page-title"> <h1>Dashboard</h1> </div> </div> </div> <div class="col-sm-8"> <div class="page-header float-right"> <div class="page-title"> <ol class="breadcrumb text-right"> <li class="active">Dashboard</li> </ol> </div> </div> </div> </div> <div class="content mt-3"> <!-- displaying institution basic info --> <div class="col-lg-12"> <div class="card"> <div class="card-header"> <h4>Institution Details</h4> </div> <div class="card-body"> <div class="default-tab"> <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-item nav-link active" id="basic-info-tab" data-toggle="tab" href="#basic-info" role="tab" aria-controls="basic-info" aria-selected="true">Basic Information</a> <a class="nav-item nav-link" id="cars-tab" data-toggle="tab" href="#cars" role="tab" aria-controls="cars" aria-selected="false">Cars</a> <a class="nav-item nav-link" id="houses-tab" data-toggle="tab" href="#houses" role="tab" aria-controls="houses" aria-selected="false">Houses</a> </div> </nav> <div class="tab-content pl-3 pt-2" id="nav-tabContent"> <!-- basic info tab --> <div class="tab-pane fade show active" id="basic-info" role="tabpanel" aria-labelledby="basic-info-tab"> <ul class="list-group list-group-flush"> <?php $pid= $row['id_institution']; $stmt = $database->query("SELECT * FROM institution WHERE Id = '$pid' "); $rowin = $database->fetch_array($stmt); $cnid= $row['country']; $stmtcntry = $database->query("SELECT * FROM countries WHERE id= '$cnid'"); $rowcntry = $database->fetch_array($stmtcntry); $cnloc= $row['country_loc']; $stmtloc = $database->query("SELECT * FROM countries WHERE id= '$cnloc'"); $rowloc = $database->fetch_array($stmtloc); $value['id']= $row['id']; if ($rowin['Name']== "O N G") { echo ' <li class="list-group-item"><b>Name:</b> '.$row['name'].'</li> <li class="list-group-item"><b>Type:</b> '.$rowin['Name'].'</li> <li class="list-group-item"><b>Email:</b> '.$row['email'].'</li> <li class="list-group-item"><b>Telephone:</b> '.$row['telephone'].'</li> <li class="list-group-item"><b>Contact Person:</b> '.$row['contact_person'].'</li> <li class="list-group-item"><b>Contact phone:</b> '.$row['contact_phone'].'</li> <li class="list-group-item"><b>Country:</b> '.$rowcntry['nicename'].'</li> <li class="list-group-item"><b>Location:</b> '.$row['location'].'</li> <li class="list-group-item"><b>Benefits:</b> '.$row['benefits'].'</li> <li class="list-group-item"><b>Meeting:</b> '.$row['meeting'].'</li> <li class="list-group-item"><b>Animal contribution:</b> '.$row['animal_contribution'].'</li> <li class="list-group-item"><b>Responsible Ministry:</b> '.$row['responsible_ministry'].'</li> <li class="list-group-item"><b>Attachment:</b> <a href="'.$row['attachment'].'" download>'.$row['attachment'].'</a></li> <li class="list-group-item"><b>Payment date:</b> '.$row['payment_date'].'</li> <li class="list-group-item"><b>Start Date:</b> '.$row['start_date'].'</li> <li class="list-group-item"><b>End Date:</b> '.$row['end_date'].'</li> <li class="list-group-item"><a href="editong.php?id='.$Hash->encrypt($value['id']).'" style="font_size:30px;" > <button type="button" class="btn btn-secondary">Edit</button></a></li> '; } elseif ($rowin['Name']== "Rwandan Embassies") { echo ' <li class="list-group-item"><b>Name:</b> '.$row['name'].'</li> <li class="list-group-item"><b>Type:</b> '.$rowin['Name'].'</li> <li class="list-group-item"><b>Email:</b> '.$row['email'].'</li> <li class="list-group-item"><b>Telephone:</b> '.$row['telephone'].'</li> <li class="list-group-item"><b>Contact Person:</b> '.$row['contact_person'].'</li> <li class="list-group-item"><b>Contact phone:</b> '.$row['contact_phone'].'</li> <li class="list-group-item"><b>Country:</b> '.$rowcntry['nicename'].'</li> <li class="list-group-item"><b>Location:</b> '.$row['location'].'</li> <li class="list-group-item"><b>Start Date:</b> '.$row['start_date'].'</li> <li class="list-group-item"><b>End Date:</b> '.$row['end_date'].'</li> <li class="list-group-item"><a href="editrwem.php?id='.$Hash->encrypt($value['id']).'" style="font_size:30px;" > <button type="button" class="btn btn-secondary">Edit</button></a></li> '; } elseif ($rowin['Name']== "Foreign Embassies") { echo ' <li class="list-group-item"><b>Name:</b> '.$row['name'].'</li> <li class="list-group-item"><b>Type:</b> '.$rowin['Name'].'</li> <li class="list-group-item"><b>Email:</b> '.$row['email'].'</li> <li class="list-group-item"><b>Telephone:</b> '.$row['telephone'].'</li> <li class="list-group-item"><b>Contact Person:</b> '.$row['contact_person'].'</li> <li class="list-group-item"><b>Contact phone:</b> '.$row['contact_phone'].'</li> <li class="list-group-item"><b>Country:</b> '.$rowcntry['nicename'].'</li> <li class="list-group-item"><b>Country Represented:</b> '.$rowloc['nicename'].'</li> <li class="list-group-item"><b>Location:</b> '.$row['location'].'</li> <li class="list-group-item"><b>Start Date:</b> '.$row['start_date'].'</li> <li class="list-group-item"><b>End Date:</b> '.$row['end_date'].'</li> <li class="list-group-item"><a href="editforem.php?id='.$Hash->encrypt($value['id']).'" style="font_size:30px;" > <button type="button" class="btn btn-secondary">Edit</button></a></li> '; } elseif ($rowin['Name']== "MOFA") { echo ' <li class="list-group-item"><b>Name:</b> '.$row['name'].'</li> <li class="list-group-item"><b>Type:</b> '.$rowin['Name'].'</li> <li class="list-group-item"><b>Email:</b> '.$row['email'].'</li> <li class="list-group-item"><b>Telephone:</b> '.$row['telephone'].'</li> <li class="list-group-item"><b>Contact Person:</b> '.$row['contact_person'].'</li> <li class="list-group-item"><b>Contact phone:</b> '.$row['contact_phone'].'</li> <li class="list-group-item"><b>Country:</b> '.$rowcntry['nicename'].'</li> <li class="list-group-item"><b>Location:</b> '.$row['location'].'</li> <li class="list-group-item"><a href="editin.php?id='.$Hash->encrypt($value['id']).'" style="font_size:30px;" > <button type="button" class="btn btn-secondary">Edit</button></a></li> '; } ?> </ul> </div> <!-- add car tab --> <div class="tab-pane fade" id="cars" role="tabpanel" aria-labelledby="cars-tab"> <ul class="list-group list-group-flush"> <li class="list-group-item"> <button type="button" class="btn btn-success mb-1" data-toggle="modal" data-target="#addcar"> Add Car </button> </li> <?php $car_id= $Hash->decrypt($_GET['id']); $stmtc = $database->query("SELECT * FROM cars WHERE owner = '$car_id' AND status!='deleted' "); $num=$database->num_rows($stmtc); if ($num != 0) { $c=1; while ($rowi = $database->fetch_array($stmtc)) { $value['id']=$rowi['id']; echo ' <li class="list-group-item"> <a href="cars.php?id='.$Hash->encrypt($value['id']).'"> <b>Car'.$c.' Plate Number:</b> '.$rowi['plate_nber'].' </a> </li> '; $c=$c+1; } } else{ echo "<b>No cars</b>"; } ?> </ul> </div> <!-- add house tab --> <div class="tab-pane fade" id="houses" role="tabpanel" aria-labelledby="houses-tab"> <ul class="list-group list-group-flush"> <li class="list-group-item"> <button type="button" class="btn btn-success mb-1" data-toggle="modal" data-target="#addhouse"> Add House </button> </li> <?php $house_id= $Hash->decrypt($_GET['id']); $stmth = $database->query("SELECT * FROM houses WHERE owner = '$house_id' AND status!='deleted' "); $numh=$database->num_rows($stmth); if ($numh != 0) { $n=1; while ($rowh = $database->fetch_array($stmth)) { $idh=$rowh['id_location']; $stmtl = $database->query("SELECT * FROM Location WHERE id = '$idh' AND status!='deleted' "); $rowl = $database->fetch_array($stmtl); $valueho['id']=$rowh['id']; echo ' <li class="list-group-item"> <a href="houses.php?id='.$Hash->encrypt($valueho['id']).'"> <div> <b>Type of House number '.$n.':</b> '.$rowh['type'].'<br/> <b>Province:</b> '.$rowl['province'].' </div> </a> </li> '; $n=$n+1; } } else{ echo "<b>No houses</b>"; } ?> </ul> </div> </div> </div> </div> </div> </div> <!-- Comments section --> <div class="col-lg-12"> <div class="card"> <div class="card-header"> <h4>Comments</h4> </div> <div class="card-body"> <form action='' method='post' name="form"> <div class="form-line"> <div class="form-group"> <label >Comment</label> <textarea class="form-control" name='comment' cols='10' rows='5'><?php if(isset($error)){ echo $_POST['comment'];}?></textarea> </div> </div> <input type='submit' name='send' value='Send' class="btn btn-primary "> </form> <!-- displaying comments --> <ul class="list-group list-group-flush card-body"> <?php $cmnt_id= $Hash->decrypt($_GET['id']); $typein=$rowin['Name']; $stmtc = $database->query("SELECT * FROM comments WHERE owner = '$cmnt_id' AND status!='deleted' AND type = '$typein' "); $nums=$database->num_rows($stmtc); if ($nums != 0) { while ($rowcmnt = $database->fetch_array($stmtc)) { $valuecmnt['id']=$rowcmnt['id']; $usernm= $rowcmnt['user']; echo ' <li class="list-group-item"><b>User:</b> '.$rowcmnt['user'].'<br/> <b>Comment:</b> '.$rowcmnt['comment'].'<br/> '; if ($user==$usernm) { echo ' <a href="editcomment.php?id='.$Hash->encrypt($valuecmnt['id']).'">Edit</a>'; } echo ' </li>'; } } else{ echo "<b>No Comments</b>"; } ?> </ul> </div> </div> </div> </div> <!-- .content --> <!-- inserting modals --> <!-- add car --> <div class="modal fade" id="addcar" tabindex="-1" role="dialog" aria-labelledby="mediumModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="mediumModalLabel">Add Car</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action='' method='post' name="form"> <label >Plate Number</label> <div class="form-group"> <div class="form-line"> <input type="text" id="plot_nber" class="form-control" name="plate_nber" value='<?php if(isset($error)){ echo $_POST['plate_nber'];}?>' required> </div> <div class="form-line"> <label >Model</label> <input type="text" id="model" class="form-control" name="model" value='<?php if(isset($error)){ echo $_POST['model'];}?>' required> </div> <div class="form-line"> <label >Insurance</label> <input type="text" id="insurance_camp" class="form-control" name="insurance_camp" value='<?php if(isset($error)){ echo $_POST['insurance_camp'];}?>' required> </div> </div> <input type='submit' name='savec' value='Save' class="btn btn-primary "> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> </div> </div> </div> </div> <!-- add house --> <div class="modal fade" id="addhouse" tabindex="-1" role="dialog" aria-labelledby="mediumModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="mediumModalLabel">Add House</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action='' method='post' name="form"> <label >Type of House</label> <div class="form-group"> <div class="form-line"> <input type="text" id="type" class="form-control" name="type" value='<?php if(isset($error)){ echo $_POST['type'];}?>' required> </div> <div class="form-line"> <label >Province</label> <input type="text" id="province" class="form-control" name="province" value='<?php if(isset($error)){ echo $_POST['province'];}?>' required> </div> <div class="form-line"> <label >District</label> <input type="text" id="district" class="form-control" name="district" value='<?php if(isset($error)){ echo $_POST['district'];}?>' required> </div> <div class="form-line"> <label >Sector</label> <input type="text" id="sector" class="form-control" name="sector" value='<?php if(isset($error)){ echo $_POST['sector'];}?>' required> </div> <div class="form-line"> <label >Cell</label> <input type="text" id="cell" class="form-control" name="cell" value='<?php if(isset($error)){ echo $_POST['cell'];}?>' required> </div> <div class="form-line"> <label >Plot Number</label> <input type="text" id="plot_nber" class="form-control" name="plot_nber" value='<?php if(isset($error)){ echo $_POST['plot_nber'];}?>' required> </div> <label for="Name">Country</label> <div class="form-line"> <select name="country"> <?php $stmtcntry = $database->query("SELECT * FROM countries"); while ($rowcntry = $database->fetch_array($stmtcntry)) { echo ' <option value='.$rowcntry['id'].'>'.$rowcntry['nicename'].'</option>'; } ?> </select> </div> </div> <input type='submit' name='saveh' value='Save' class="btn btn-primary "> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> </div> </div> </div> </div> </div><!-- /#right-panel --> <!-- Right Panel --> <script src="assets/js/vendor/jquery-2.1.4.min.js"></script> <script src="assets/js/popper.min.js"></script> <script src="assets/js/plugins.js"></script> <script src="assets/js/main.js"></script> <script src="assets/js/lib/chart-js/Chart.bundle.js"></script> <script src="assets/js/dashboard.js"></script> <script src="assets/js/widgets.js"></script> <script src="assets/js/lib/vector-map/jquery.vmap.js"></script> <script src="assets/js/lib/vector-map/jquery.vmap.min.js"></script> <script src="assets/js/lib/vector-map/jquery.vmap.sampledata.js"></script> <script src="assets/js/lib/vector-map/country/jquery.vmap.world.js"></script> </body> </html>
Markdown
UTF-8
12,941
3.21875
3
[ "MIT", "Apache-2.0" ]
permissive
+++ author = ["Alexander Neumann"] title = "Splitting Data with Content-Defined Chunking" date = 2018-12-01T00:00:00Z series = ["Advent 2018"] +++ In this post you'll learn what Content-Defined Chunking (CDC) is and how you can use it to split large data into smaller blocks in a deterministic way. These blocks can be found again in other data later, even if the location of the block is different than the first time. I wrote a small Go package to do the splitting, which performs really well. Why is splitting data an interesting problem? ============================================= In my spare time, I'm working on a fast backup program called [restic](https://restic.net), which is written in Go. When a (possible large) file is read, the program needs to save the data somewhere so that it can be restored later. I think it is a good idea to split files into smaller parts, which are more manageable for a program. It also allows detecting and efficiently handling small changes in big files, like virtual machine images. Once such a part of a file is saved, it can be referenced when the same data is contained in different files, so restic de-duplicates the data it reads. The parts are identified based on the SHA-256 hash of the contents, so a list of these hashes can describe the content of a file. There are different strategies for splitting files, the most obvious one would be to just use static boundaries, and e.g. split after every megabyte of data. This gives us manageable chunks, but if the data in the file is shifted, for example by inserting a byte at the start of the file, all chunks will be different and need to be saved anew. We can do better than that. Rabin fingerprints ================== During the research I did before starting to implement what would later become restic, I discovered a publication titled ["Fingerprinting by Random Polynomials"](http://www.xmailserver.org/rabin.pdf) by [Michael O. Rabin](https://en.wikipedia.org/wiki/Michael_O._Rabin) published in 1981. It describes a way to efficiently compute a ["Rabin fingerprint"](https://en.wikipedia.org/wiki/Rabin_fingerprint) (or "hash", in modern terms) for a number of bytes. It has the great property that it can be computed as a [rolling hash](https://en.wikipedia.org/wiki/Rolling_hash): the Rabin fingerprint of a window of bytes can be efficiently calculated while the window moves through a very large file. The idea is that when a new byte is to be processed, the oldest byte is first removed from the calculation, and the new byte is factored in. How can we use that to find chunk boundaries? Restic uses a window of 64 bytes, so while reading a file, it computes the fingerprint of all such windows: byte 0 to byte 63, byte 1 to byte 64 and so on. It then checks every fingerprint if the least significant bits are all zero. If this is the case, then we found a chunk boundary! For random input bytes, the calculated fingerprints are roughly random as well, so by varying the number of bits that are checked we can (roughly) configure how large the resulting chunks will be. Since the cut points for individual chunks only depend on the 64 bytes preceding them, this method of splitting data is called "Content-Defined Chunking" (CDC). Early on I recognized that the algorithm and implementation has the potential to be very helpful to other projects as well, so I published it as a [separate package](https://github.com/restic/chunker) for other people to import ([API on godoc.org](https://godoc.org/github.com/restic/chunker)) with a very liberal BSD 2-clause license. Enough theory, let's dive into the code! Splitting data ============== The type which does all the hard work of computing the fingerprints over the sliding window is contained in the `Chunker` type. The Rabin fingerprint needs a so-called "irreducible polynomial" to work, which is encoded as an `uint64`. The `chunker` package exports the function `RandomPolynomial()` which creates a new polynomial for you to use. Our first program will generate a random polynomial and create a new `Chunker` which reads data from `os.Stdin`: ```go p, err := chunker.RandomPolynomial() if err != nil { panic(err) } fmt.Printf("using polynomial %v for splitting data\n", p) chk := chunker.New(os.Stdin, p) ``` The `Next()` method on the `Chunker` reads data out the reader (`os.Stdin` in this example) into a byte slice buffer. The methods returns a next `Chunk` and an error. We call it repeatedly until `io.EOF` is returned, which tells us that all data has been read: ```go buf := make([]byte, 16*1024*1024) // 16 MiB for { chunk, err := chk.Next(buf) if err == io.EOF { break } if err != nil { panic(err) } fmt.Printf("%d\t%d\t%016x\n", chunk.Start, chunk.Length, chunk.Cut) } ``` Let's get some random data to test: ``` $ dd if=/dev/urandom bs=1M count=100 of=data 100+0 records in 100+0 records out 104857600 bytes (105 MB, 100 MiB) copied, 0,548253 s, 191 MB/s ``` Now if we feed the data in this file to the program we've just written ([code](https://gist.github.com/fd0/a74e42a7a4f51c4ccaa6c11a09c14619)), it prints the start offset, length, and fingerprint for the chunk it found: ``` $ cat data | go run main.go using polynomial 0x3dea92648f6e83 for splitting data 0 2908784 000c31839a100000 2908784 2088949 001e8b4104900000 4997733 1404824 000a18d1f0200000 6402557 617070 001bc6ac84300000 7019627 1278326 001734984b000000 8297953 589913 0004cf802b600000 8887866 554526 001eb5a362900000 9442392 1307416 000ef1e549c00000 [...] 102769045 864607 00181b67df300000 103633652 592134 0000a0c8b4200000 104225786 631814 001d5ba20d38998b ``` On a second run, it'll generate a new polynomial and the chunks will be different, so if you depend on your program computing the same boundaries, you'll need to pass in the same polynomial. Let's fix the polynomial (`0x3dea92648f6e83`) for the next runs and change the program like this ([code](https://gist.github.com/bf984e1c40b56eaeff310d07a0d71128)): ```go chk := chunker.New(os.Stdin, 0x3dea92648f6e83) ``` After replacing the randomly generated polynomial with a constant, every new run will give us the same chunks: ``` $ cat data | go run main.go 0 2908784 000c31839a100000 2908784 2088949 001e8b4104900000 4997733 1404824 000a18d1f0200000 [...] 102769045 864607 00181b67df300000 103633652 592134 0000a0c8b4200000 104225786 631814 001d5ba20d38998b ``` Now we can experiment with the data. For example, what happens when we insert bytes at the beginning? Let's test that by inserting the bytes `foo` using the shell: ``` $ (echo -n foo; cat data) | go run main.go 0 2908787 000c31839a100000 2908787 2088949 001e8b4104900000 4997736 1404824 000a18d1f0200000 6402560 617070 001bc6ac84300000 [...] ``` We can see that the first chunk is different: it's three bytes longer (2908787 versus 2908784), but the fingerprint at the end of the chunk is the same. All other chunks following the first one are also the same! Let's add a hash to identify the contents of the individual chunks ([code](https://gist.github.com/1e06773ef15cac6e16efe0c291c8f4b4)): ```go for { chunk, err := chk.Next(buf) if err == io.EOF { break } if err != nil { panic(err) } hash := sha256.Sum256(chunk.Data) fmt.Printf("%d\t%d\t%016x\t%032x\n", chunk.Start, chunk.Length, chunk.Cut, hash) } ``` These are the chunks for the raw, unmodified file: ``` $ cat data | go run main.go 0 2908784 000c31839a100000 8d17f5f7326a2fd7[...] 2908784 2088949 001e8b4104900000 ba7c71226609c0de[...] 4997733 1404824 000a18d1f0200000 9c4db21626a27d4b[...] 6402557 617070 001bc6ac84300000 4c249c3b88500c23[...] 7019627 1278326 001734984b000000 5bec562b7ad37b8b[...] [...] ``` Now we can see that adding bytes at the start only changes the first chunk: ``` $ (echo -n foo; cat data) | go run main.go 0 2908787 000c31839a100000 f41084d25bc273f2[...] 2908787 2088949 001e8b4104900000 ba7c71226609c0de[...] 4997736 1404824 000a18d1f0200000 9c4db21626a27d4b[...] 6402560 617070 001bc6ac84300000 4c249c3b88500c23[...] 7019630 1278326 001734984b000000 5bec562b7ad37b8b[...] ``` The SHA-256 hash for the first chunk changed from `8d17f5f7326a2fd7[...]` to `f41084d25bc273f2[...]`, but the rest are still the same. That's pretty cool. Let's see how many different chunks we have in our data file by counting the different hashes: ``` $ cat data | go run main.go | cut -f4 | sort | uniq | wc -l 69 ``` What happens when we feed the program our data twice, how many chunks does it detect? Let's find out: ``` $ (cat data; cat data) | go run main.go | cut -f4 | sort | uniq | wc -l 70 ``` Huh, so we only got a single additional chunk. The cause is that for the first round, it'll find the same chunks as before (it's the same data after all) right until the last chunk. In the previous run, the end of the last chunk was determined by the end of the file. Now there's additional data, so the chunk continues. The next cut point will in the second run of the data, it'll be the same as the first cut point, just with some additional data at the beginning of the chunk, so the SHA-256 hash is different. Afterwards, the same chunks follow in the same order. Changing a few consecutive bytes of data somewhere in most cases also only affects a single chunk, let's write the output to a file, change the data a bit using `sed`, and write another file: ``` $ cat data | go run main.go > orig.log $ cat data | sed 's/EZE8HX/xxxxxx/' | go run main.go > mod.log ``` The string `EZE8HX` was present in my randomly generated file `data` only once and the `sed` command above changed it to the string `xxxxxx`. When we now compare the two log files using `diff`, we can see that for exactly one chunk the SHA-256 hash has changed, but the other chunks and the chunk boundaries stayed the same: ```diff $ diff -au orig.log mod.log --- orig.log 2018-11-24 13:14:45.265329525 +0100 +++ mod.log 2018-11-24 13:19:32.344681407 +0100 @@ -55,7 +55,7 @@ 83545247 547876 00198b8839f00000 2cbeea803ba79d54[...] 84093123 889631 0007ddacabc00000 a2b6e8651ae1ab69[...] 84982754 2561935 000c53712f500000 bca589959b019a80[...] -87544689 2744485 0000a49118b00000 02b125104f06ed85[...] +87544689 2744485 0000a49118b00000 ce2e43496ae6e7c3[...] 90289174 1167308 00034d6cce700000 ad25a331993d9db7[...] 91456482 1719951 001d2fea8ae00000 ba5153845c5b5228[...] 93176433 1362655 0003009fc1600000 8e7a35e340c10d61[...] ``` This technique can be used for many other things besides a backup program. For example, the program `rsync` uses content-defined chunking to efficiently transfer files by detecting which parts of the files are already present on the receiving side (with a different rolling hash). The [Low Bandwidth Network File System (LBFS)](https://pdos.csail.mit.edu/papers/lbfs:sosp01/lbfs.pdf) uses CDC with Rabin fingerprints to only transfer chunks that are needed over the network. Another application of a rolling hash is finding strings in text, for example in the [Rabin-Karp algorithm](https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm). If you're interested in how the `chunker` package is used in restic, there's a [post over at the restic blog](https://restic.net/blog/2015-09-12/restic-foundation1-cdc) which explains this in a bit more detail. Performance =========== Performance is crucial for backup programs. If creating backups is too slow people tend to stop using it. The `chunker` package is written in plain Go. It doesn't have any fancy low-level assembler, but the code is already pretty fast, thanks to some optimized calculations. The package has some benchmarks: ``` $ go test -run xxx -bench 'BenchmarkChunker$' goos: linux goarch: amd64 pkg: github.com/restic/chunker BenchmarkChunker-4 20 70342669 ns/op 477.01 MB/s --- BENCH: BenchmarkChunker-4 chunker_test.go:325: 23 chunks, average chunk size: 1458888 bytes chunker_test.go:325: 23 chunks, average chunk size: 1458888 bytes PASS ok github.com/restic/chunker 1.655s ``` Running on an older machine with an Intel i5 CPU `chunker` processes at about 477 MB per second on a single core. Conclusion ========== Content-Defined Chunking can be used to split data into smaller chunks in a deterministic way so that the chunks can be rediscovered if the data has slightly changed, even when new data has been inserted or data was removed. The [`chunker` package](https://github.com/restic/chunker) provides a fast implementation in pure Go with a liberal license and a simple API. If you use the `chunker` package for something cool, please let us know by [opening an issue](https://github.com/restic/chunker/issues/new) in the repo over at GitHub!
C++
UTF-8
652
3.125
3
[]
no_license
class Solution { public: Node* connect(Node* root) { if(!root) return NULL; queue<Node*> bfs; bfs.push(root); while(!bfs.empty()){ int size = bfs.size(); while(size--){ Node* curr = bfs.front(); bfs.pop(); if(!bfs.empty() && size){ curr->next = bfs.front(); } if(curr->left) bfs.push(curr->left); if(curr->right) bfs.push(curr->right); } } return root; } };
JavaScript
UTF-8
293
3.03125
3
[]
no_license
'use strict'; const filterByDistrict = (stations,query) => { //console.log(stations) const valor = query.toLowerCase(); const district=stations.filter((e)=>{ return e.district.toLowerCase().indexOf(valor)!=-1; }) console.log(district); return district; };
Python
UTF-8
1,219
3.6875
4
[]
no_license
# 3. Написать программу, которая обходит не взвешенный ориентированный граф без петель, # в котором все вершины связаны, по алгоритму поиска в глубину (Depth-First Search). # # # Примечания: # a. граф должен храниться в виде списка смежности; # b. генерация графа выполняется в отдельной функции, которая принимает на вход число вершин. import random def generation_graph(n): g = [] for i in range(n): p = [j for j in range(i)] + [_ for _ in range(i + 1, n)] li = sorted(random.sample(p, random.randint(1, n - 1))) g.append(set(li)) return g def dfs(graph, start, visited=None): if visited is None: visited = set() visited.add(start) print(start) for next in graph[start] - visited: dfs(graph, next, visited) return visited n = int(input('Сколько вершин в графе: ')) start = int(input('От какой вершины идти: ')) g = generation_graph(n) print(g) dfs(g, start)
Ruby
UTF-8
398
2.96875
3
[ "MIT" ]
permissive
class Episode attr_reader :attributes def initialize filename @filename = filename @attributes = nil process end def process if @filename =~ /^(.*)s(\d{2})e(\d{2})[^\d]+/i @attributes = { season: $2, episode: $3 } @attributes[:name] = $1.gsub(/(1080|720)p?/,'').gsub(/20\d{2}/,'').gsub('.',' ').rstrip @attributes[:filename] = @filename end end end
Python
UTF-8
620
3.15625
3
[]
no_license
class Solution: def strStr(self, source, target): # write your code here self.source=source self.target=target if target=="": return 0 if source=="" or source==None or target==None: return -1 length = len(target)-1 for i in range(0,len(source)): if i+length>=len(source): break s='' for c in range(i,i+length+1): s=s+source[c] if s==target: return 1 return -1 source=None target='a' So=Solution() print(So.strStr(source,target))
Java
UTF-8
17,565
2.875
3
[]
no_license
package com.mkyong.IO; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.StringTokenizer; import junit.framework.TestCase; public class IODemo extends TestCase { /** * @param args */ public static void main(String[] args) { try { File file = new File("d:\\test3.txt"); if (file.createNewFile()) { System.out.println("File is created!"); } else { System.out.println("File already exists."); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void FilePathExample() { try { String filename = "testing.txt"; String finalfile = ""; String workingDir = System.getProperty("user.dir"); String your_os = System.getProperty("os.name").toLowerCase(); if (your_os.indexOf("win") >= 0) { finalfile = workingDir + "\\" + filename; } else if (your_os.indexOf("nix") >= 0 || your_os.indexOf("nux") >= 0) { finalfile = workingDir + "/" + filename; } else { finalfile = workingDir + "{others}" + filename; } System.out.println("Final filepath:" + finalfile); File file = new File(finalfile); if (file.createNewFile()) { System.out.println("Done"); } else { System.out.println("File already exists!"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void FilePermissionExample() { try { File file = new File("/mkyong/shellscript.sh"); if (file.exists()) { System.out.println("Is Execute allow : " + file.canExecute()); System.out.println("Is Write allow : " + file.canWrite()); System.out.println("Is Read allow : " + file.canRead()); } file.setExecutable(false); file.setReadable(false); file.setWritable(false); System.out.println("Is Execute allow : " + file.canExecute()); System.out.println("Is Write allow : " + file.canWrite()); System.out.println("Is Read allow : " + file.canRead()); if (file.createNewFile()) { System.out.println("File is created!"); } else { System.out.println("File already exists."); } } catch (IOException e) { e.printStackTrace(); } } public void BufferedInputStreamExample() { File file = new File("D:\\testing.txt"); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); while (dis.available() != 0) { System.out.println(dis.readLine()); } } catch (IOException e) { e.printStackTrace(); } finally { try { fis.close(); bis.close(); dis.close(); } catch (IOException ex) { ex.printStackTrace(); } } } public void BufferedReaderExample() { BufferedReader br = null; try { String sCurrentLine; br = new BufferedReader(new FileReader("C:\\testing.txt")); while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } public void WriteFileExample() { FileOutputStream fop = null; File file; String content = "This is the text content"; try { file = new File("c:/newfile.txt"); fop = new FileOutputStream(file); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } // get the content in bytes byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fop != null) { fop.close(); } } catch (IOException e) { e.printStackTrace(); } } } public void WriteFileExample1() { /*File file = new File("c:/newfile.txt"); String content = "This is the text content"; try (FileOutputStream fop = new FileOutputStream(file)) { // if file doesn't exists, then create it if (!file.exists()) { file.createNewFile(); } // get the content in bytes byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); }*/ } public void WriteToFileExample() { try { String content = "This is the content to write into file"; File file = new File("/users/mkyong/filename.txt"); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } } public void AppendToFileExample() { try { String data = " This content will append to the end of the file"; File file = new File("javaio-appendfile.txt"); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } // true = append file FileWriter fileWritter = new FileWriter(file.getName(), true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); bufferWritter.write(data); bufferWritter.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } } public void DeleteFileExample() { try { File file = new File("c:\\logfile20100131.log"); if (file.delete()) { System.out.println(file.getName() + " is deleted!"); } else { System.out.println("Delete operation is failed."); } } catch (Exception e) { e.printStackTrace(); } } public void RenameFileExample() { File oldfile = new File("oldfile.txt"); File newfile = new File("newfile.txt"); if (oldfile.renameTo(newfile)) { System.out.println("Rename succesful"); } else { System.out.println("Rename failed"); } } private static final String FILE_DIR = "c:\\folder"; private static final String FILE_TEXT_EXT = ".txt"; public void deleteFile(String folder, String ext) { GenericExtFilter filter = new GenericExtFilter(ext); File dir = new File(folder); // list out all the file name with .txt extension String[] list = dir.list(filter); if (list.length == 0) return; File fileDelete; for (String file : list) { String temp = new StringBuffer(FILE_DIR).append(File.separator) .append(file).toString(); fileDelete = new File(temp); boolean isdeleted = fileDelete.delete(); System.out.println("file : " + temp + " is deleted : " + isdeleted); } } // inner class, generic extension filter public class GenericExtFilter implements FilenameFilter { private String ext; public GenericExtFilter(String ext) { this.ext = ext; } public boolean accept(File dir, String name) { return (name.endsWith(ext)); } } public void listFile(String folder, String ext) { GenericExtFilter filter = new GenericExtFilter(ext); File dir = new File(folder); if(dir.isDirectory()==false){ System.out.println("Directory does not exists : " + FILE_DIR); return; } // list out all the file name and filter by the extension String[] list = dir.list(filter); if (list.length == 0) { System.out.println("no files end with : " + ext); return; } for (String file : list) { String temp = new StringBuffer(FILE_DIR).append(File.separator) .append(file).toString(); System.out.println("file : " + temp); } } public void CopyFileExample(){ InputStream inStream = null; OutputStream outStream = null; try{ File afile =new File("Afile.txt"); File bfile =new File("Bfile.txt"); inStream = new FileInputStream(afile); outStream = new FileOutputStream(bfile); byte[] buffer = new byte[1024]; int length; //copy the file content in bytes while ((length = inStream.read(buffer)) > 0){ outStream.write(buffer, 0, length); } inStream.close(); outStream.close(); System.out.println("File is copied successful!"); }catch(IOException e){ e.printStackTrace(); } } public void MoveFileExample(){ InputStream inStream = null; OutputStream outStream = null; try{ File afile =new File("C:\\folderA\\Afile.txt"); File bfile =new File("C:\\folderB\\Afile.txt"); inStream = new FileInputStream(afile); outStream = new FileOutputStream(bfile); byte[] buffer = new byte[1024]; int length; //copy the file content in bytes while ((length = inStream.read(buffer)) > 0){ outStream.write(buffer, 0, length); } inStream.close(); outStream.close(); //delete the original file afile.delete(); System.out.println("File is copied successful!"); }catch(IOException e){ e.printStackTrace(); } } public void GetFileCreationDateExample(){ try{ Process proc = Runtime.getRuntime().exec("cmd /c dir c:\\logfile.log /tc"); BufferedReader br = new BufferedReader( new InputStreamReader(proc.getInputStream())); String data =""; //it's quite stupid but work for(int i=0; i<6; i++){ data = br.readLine(); } System.out.println("Extracted value : " + data); //split by space StringTokenizer st = new StringTokenizer(data); String date = st.nextToken();//Get date String time = st.nextToken();//Get time System.out.println("Creation Date : " + date); System.out.println("Creation Time : " + time); }catch(IOException e){ e.printStackTrace(); } } public void GetFileLastModifiedExample(){ File file = new File("c:\\logfile.log"); System.out.println("Before Format : " + file.lastModified()); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); System.out.println("After Format : " + sdf.format(file.lastModified())); } public void ChangeFileLastModifiedExample(){ try{ File file = new File("C:\\logfile.log"); //print the original last modified date SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); System.out.println("Original Last Modified Date : " + sdf.format(file.lastModified())); //set this date String newLastModified = "01/31/1998"; //need convert the above date to milliseconds in long value Date newDate = sdf.parse(newLastModified); file.setLastModified(newDate.getTime()); //print the latest last modified date System.out.println("Lastest Last Modified Date : " + sdf.format(file.lastModified())); }catch(ParseException e){ e.printStackTrace(); } } public void FileReadAttribute(){ File file = new File("c:/file.txt"); //mark this file as read only, since jdk 1.2 file.setReadOnly(); if(file.canWrite()){ System.out.println("This file is writable"); }else{ System.out.println("This file is read only"); } //revert the operation, mark this file as writable, since jdk 1.6 file.setWritable(true); if(file.canWrite()){ System.out.println("This file is writable"); }else{ System.out.println("This file is read only"); } } public void FileSizeExample(){ File file =new File("c:\\java_xml_logo.jpg"); if(file.exists()){ double bytes = file.length(); double kilobytes = (bytes / 1024); double megabytes = (kilobytes / 1024); double gigabytes = (megabytes / 1024); double terabytes = (gigabytes / 1024); double petabytes = (terabytes / 1024); double exabytes = (petabytes / 1024); double zettabytes = (exabytes / 1024); double yottabytes = (zettabytes / 1024); System.out.println("bytes : " + bytes); System.out.println("kilobytes : " + kilobytes); System.out.println("megabytes : " + megabytes); System.out.println("gigabytes : " + gigabytes); System.out.println("terabytes : " + terabytes); System.out.println("petabytes : " + petabytes); System.out.println("exabytes : " + exabytes); System.out.println("zettabytes : " + zettabytes); System.out.println("yottabytes : " + yottabytes); }else{ System.out.println("File does not exists!"); } } public void AbsoluteFilePathExample(){ try{ File temp = File.createTempFile("i-am-a-temp-file", ".tmp" ); String absolutePath = temp.getAbsolutePath(); System.out.println("File path : " + absolutePath); String filePath = absolutePath. substring(0,absolutePath.lastIndexOf(File.separator)); System.out.println("File path : " + filePath); }catch(IOException e){ e.printStackTrace(); } } public void LineNumberReaderExample(){ try{ File file =new File("c:\\ihave10lines.txt"); if(file.exists()){ FileReader fr = new FileReader(file); LineNumberReader lnr = new LineNumberReader(fr); int linenumber = 0; while (lnr.readLine() != null){ linenumber++; } System.out.println("Total number of lines : " + linenumber); lnr.close(); }else{ System.out.println("File does not exists!"); } }catch(IOException e){ e.printStackTrace(); } } public void FileChecker(){ File f = new File("c:\\mkyong.txt"); if(f.exists()){ System.out.println("File existed"); }else{ System.out.println("File not found!"); } } public void FileHidden(){ File file = new File("c:/hidden-file.txt"); if(file.isHidden()){ System.out.println("This file is hidden"); }else{ System.out.println("This file is not hidden"); } } public void test1UTF(){ try { File fileDir = new File("c:\\temp\\test.txt"); BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream(fileDir), "UTF8")); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } catch (UnsupportedEncodingException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } } public void test2UTF(){ try { File fileDir = new File("c:\\temp\\test.txt"); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(fileDir), "UTF8")); out.append("Website UTF-8").append("\r\n"); out.append("?? UTF-8").append("\r\n"); out.append("??????? UTF-8").append("\r\n"); out.flush(); out.close(); } catch (UnsupportedEncodingException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } } public void Assign_File_Content(){ try{ DataInputStream dis = new DataInputStream ( new FileInputStream ("c:\\logging.log")); byte[] datainBytes = new byte[dis.available()]; dis.readFully(datainBytes); dis.close(); String content = new String(datainBytes, 0, datainBytes.length); System.out.println(content); }catch(Exception ex){ ex.printStackTrace(); } } }
Java
UTF-8
434
1.695313
2
[]
no_license
package com.procrastinators.malayalammemes.malayalammemes; import android.support.v7.app.AppCompatActivity; import android.widget.LinearLayout; /** * Created by Jazeem on 03/09/15. */ public abstract class RefreshableFragmentActivity extends AppCompatActivity{ public abstract void refreshFavourites(); public abstract LinearLayout getICULinearLayout(); public abstract LinearLayout getTrollMalayalamLinearLayout(); }
C++
UTF-8
1,203
2.59375
3
[]
no_license
/************************************************* ** Tad Ultrasonic Sensor: Reads the distance between the sensor and objects ** Enginyers: Ignasi Ballarà Franco, Joaquim Porte Jimenez, Arnau Tienda Tejedo ** Date: 02/05/2017 *************************************************/ const int PIN_Trig = 2; const int PIN_Echo = 3; int state_US = 0; unsigned long US_millisant = 0; int start_Ultrasound = 0; String info_ultrasound; int distance = 0; const String distance_string = "\tDistance: \t"; /************************************************* Private functions *************************************************/ int readUltrasound(){ int x = 0; int distanceCm = 0; digitalWrite(PIN_Trig, LOW); delayMicroseconds(2); digitalWrite(PIN_Trig, HIGH); delayMicroseconds(10); digitalWrite(PIN_Trig, LOW); x = pulseIn(PIN_Echo, HIGH); distanceCm = x / 29.1 / 2 ; if (distanceCm < 20){ return 1; }else{ return 0; } return distanceCm; } /************************************************* Public functions *************************************************/ void init_TUltrasonicSensor(){ pinMode(PIN_Trig, OUTPUT); pinMode(PIN_Echo, INPUT); digitalWrite(PIN_Trig, LOW); state_US = 0; }
Java
UTF-8
1,164
2.375
2
[]
no_license
package TrackBuddy.plugin.trackmate.features.BCellobject; import java.util.Iterator; import tracking.BCellobject; import net.imagej.ImgPlus; import net.imglib2.type.numeric.RealType; public abstract class IndependentBCellobjectFeatureAnalyzer< T extends RealType< T >> implements BCellobjectAnalyzer< T > { protected final ImgPlus< T > img; protected final Iterator< BCellobject > BCellobjects; protected String errorMessage; private long processingTime; public IndependentBCellobjectFeatureAnalyzer( final ImgPlus< T > img, final Iterator< BCellobject > BCellobjects ) { this.img = img; this.BCellobjects = BCellobjects; } public abstract void process( final BCellobject BCellobject ); @Override public boolean checkInput() { return true; } @Override public boolean process() { final long start = System.currentTimeMillis(); while ( BCellobjects.hasNext() ) { process( BCellobjects.next() ); } processingTime = System.currentTimeMillis() - start; return true; } @Override public String getErrorMessage() { return errorMessage; } @Override public long getProcessingTime() { return processingTime; } }
Python
UTF-8
3,200
3.109375
3
[ "MIT" ]
permissive
#!/usr/bin/env python # https://github.com/PySimpleGUI/PySimpleGUI/blob/master/DemoPrograms/Demo_Script_Launcher.py import PySimpleGUI as sg import glob import ntpath import subprocess LOCATION_OF_YOUR_SCRIPTS = '' TRANSPARENCY = .6 # how transparent the window looks. 0 = invisible, 1 = normal window # Execute the command. Will not see the output from the command until it completes. def open_file_vscode(command, *args): expanded_args = [] for a in args: expanded_args.append(a) # expanded_args += a try: sp = subprocess.Popen(['code', command, expanded_args], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = sp.communicate() if out: print(out.decode("utf-8")) if err: print(err.decode("utf-8")) except: out = '' return out def execute_command_blocking(command, *args): expanded_args = [] for a in args: expanded_args.append(a) # expanded_args += a try: sp = subprocess.Popen(['python', command, expanded_args], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = sp.communicate() if out: print(out.decode("utf-8")) if err: print(err.decode("utf-8")) except: out = '' return out # Executes command and immediately returns. Will not see anything the script outputs def execute_command_nonblocking(command, *args): expanded_args = [] for a in args: expanded_args += a try: sp = subprocess.Popen(["python",command, expanded_args], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except: pass def Launcher2(): sg.theme('GreenTan') filelist = glob.glob(LOCATION_OF_YOUR_SCRIPTS+'*.py') namesonly = [] for file in filelist: namesonly.append(ntpath.basename(file)) layout = [ [sg.Listbox(values=namesonly, size=(30, 19), select_mode=sg.SELECT_MODE_EXTENDED, key='demolist'), sg.Output(size=(88, 20), font='Courier 10')], [sg.Button('Run'), sg.Button('Open code'), sg.Button('EXIT')], ] window = sg.Window('Python Script launcher', layout, alpha_channel=TRANSPARENCY,) # ---===--- Loop taking in user input --- # while True: event, values = window.read() if event in ('EXIT', None): break # exit button clicked if event == 'Open code': for index, file in enumerate(values['demolist']): print('Open %s by VS Code' % file) window.refresh() # make the print appear immediately open_file_vscode(LOCATION_OF_YOUR_SCRIPTS + file) elif event == 'Run': for index, file in enumerate(values['demolist']): print('Launching %s' % file) window.refresh() # make the print appear immediately execute_command_blocking(LOCATION_OF_YOUR_SCRIPTS + file) window.close() if __name__ == '__main__': Launcher2()
Java
UTF-8
2,569
2.21875
2
[]
no_license
package com.shareshow.airpc.activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.shareshow.airpc.ftpserver.FTPServerService; import com.shareshow.airpc.util.DebugLog; import com.shareshow.airpc.util.NetworkUtils; /** * Created by TEST on 2017/10/19. */ public class BaseShareActivity extends AppCompatActivity { private NetReceiver netReceiver; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initRegisterNet(); } private void initRegisterNet(){ netReceiver = new NetReceiver(); IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"); intentFilter.addAction("android.net.wifi.WIFI_AP_STATE_CHANGED"); registerReceiver(netReceiver, intentFilter); } private class NetReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent){ String action = intent.getAction(); if (action!=null&&(ConnectivityManager.CONNECTIVITY_ACTION.equals(action)||action.equals("android.net.wifi.WIFI_AP_STATE_CHANGED"))){ boolean isConnected = NetworkUtils.isNetworkConnected(); DebugLog.showLog(this,"isConnected:"+isConnected); if (isConnected){ startFTPService(); }else{ stopFTPService(); } } } } public void unRegisterReceiver(){ if(netReceiver!=null){ unregisterReceiver(netReceiver); } } //关闭FTP服务; public void stopFTPService(){ Intent intent2 = new Intent(getApplicationContext(), FTPServerService.class); if (FTPServerService.isRunning()){ this.stopService(intent2); } } //开启FTP服务 public void startFTPService(){ Intent intent2 = new Intent(getApplicationContext(), FTPServerService.class); if (!FTPServerService.isRunning()){ this.startService(intent2); } } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); stopFTPService(); unRegisterReceiver(); } }
JavaScript
UTF-8
1,085
2.9375
3
[]
no_license
import React, { Component } from 'react' class Game extends Component { render () { return ( // So i've gotten the math of the scores and the basic framework of the assignment looking // like how i wanted it to. But i still need the function to randomize images and display // them as buttons to run the incScore function and the resetScore & newGame functions if // they accidentally click on an already-clicked image. // // The theme was going to be anime images, and i had the idea // of adding the image URLs to an array, then randomly push them into a new array until // the original was 'empty'. Once the new array was filled, clicking an image pushes it into // a third 'clicked' array, once there, the game continues so long as the image clicked // is not contained in the 'clicked' array and the scores will continue to increment. // Once an image is clicked twice, the resetScore & newGame functions are run to reset // the score and re-randomize the images. ) } } export default Game
Python
UTF-8
3,953
2.71875
3
[]
no_license
from rest_framework import serializers, renderers, parsers import re import os import csv import logging LOG = logging.getLogger('impaqd') class ResponseStatusRenderer(renderers.JSONRenderer): """ Default renderer. Should be used on ALL views. All views should implement this renderer OR if it implements another renderer, this `ResponseStatusRenderer.render(ResponseStatusRenderer(), data, *args, **kwargs)` should be added as the first line in the render function. """ def render(self, data, *args, **kwargs): # default values (Should never be used) #code = 0 #title = 'Error' #text = 'We apologize, but something went wrong' #http_status_code = args[1].get('response').status_code #response_mappings = [] #if hasattr(args[1].get('view'), 'status_mappings'): # view_status_mappings = args[1].get('view').status_mappings # response_mappings = [m for m in view_status_mappings if m[0] == http_status_code] #if len(response_mappings) > 0: # # First try and get responsestatus from mapping # try: # code = response_mappings[0][1] # status_obj = ResponseStatus.objects.get(code=code) # title = status_obj.title # text = status_obj.text # except Exception, e: # code = 0 # import traceback # print traceback.format_exc() # LOG.error(traceback.format_exc()) #if code == 0: # # Otherwise fall back on default (three digit) codes # try: # code = http_status_code # status_obj = ResponseStatus.objects.get(code=code) # title = status_obj.title # text = status_obj.text # except Exception, e: # code = 0 # import traceback # print traceback.format_exc() # LOG.error(traceback.format_exc()) #status = {'status': {'code' : code, 'title': title, 'text' : text}} #data.update(status) return super(ResponseStatusRenderer, self).render(data, *args, **kwargs) ##### # Underscore to CamelCase renderer # Adapted from https://gist.github.com/johtso/5881137 # recursive_key_map(camelcase_to_underscore, dict) to convert back to underscore #### class CamelCaseJSONRenderer(renderers.JSONRenderer): def render(self, data, *args, **kwargs): # Always use ResponseStatusRenderer on all custom renderes ResponseStatusRenderer.render(ResponseStatusRenderer(), data, *args, **kwargs) if data: data = recursive_key_map(underscore_to_camelcase, data) return super(CamelCaseJSONRenderer, self).render(data, *args, **kwargs) class CamelCaseToJSONParser(parsers.JSONParser): def parse(self, *args, **kwargs): obj = super(CamelCaseToJSONParser, self).parse(*args, **kwargs) return recursive_key_map(camelcase_to_underscore, obj) def underscore_to_camelcase(word, lower_first=True): result = ''.join(char.capitalize() for char in word.split('_')) if lower_first: return result[0].lower() + result[1:] else: return result _first_cap_re = re.compile('(.)([A-Z][a-z]+)') _all_cap_re = re.compile('([a-z0-9])([A-Z])') # http://stackoverflow.com/a/1176023 def camelcase_to_underscore(word): s1 = _first_cap_re.sub(r'\1_\2', word) return _all_cap_re.sub(r'\1_\2', s1).lower() def recursive_key_map(function, obj): if isinstance(obj, dict): new_dict = {} for key, value in obj.iteritems(): if isinstance(key, basestring): key = function(key) new_dict[key] = recursive_key_map(function, value) return new_dict if hasattr(obj, '__iter__'): return [recursive_key_map(function, value) for value in obj] else: return obj
Ruby
UTF-8
1,980
3.65625
4
[]
no_license
class Sudoku def initialize(board_string) @cloned_string = board_string @cloned_string.gsub!(/-/, '0') @array_of_characters = @cloned_string.chars @board = [] 0.upto(8) do |i| @board << @array_of_characters.slice(i * 9, 9).map{|x| x.to_i} end p @board end def valid_row?(index_of_row) @board[index_of_row].reject {|i| i == 0 }.uniq == @board[index_of_row].reject {|i| i == 0 } end def valid_column?(index_of_column) @board.transpose[index_of_column].reject {|i| i == 0 }.uniq == @board.transpose[index_of_column].reject {|i| i == 0 } end def block_cord(x, y) return [x / 3, y / 3] end def valid_block?(x,y) block_array = [] @board.each_with_index do |row, row_index| row.each_with_index do |cell, col_index| if block_cord(x, y) == block_cord(row_index, col_index) block_array << cell end end end block_array.count(@board[x][y]) <= 1 end def solve(board = @board) if board_completed?(board) return true end 0.upto(8) do |x| 0.upto(8) do |y| if board[x][y] == 0 1.upto(9) do |n| board[x][y] = n if valid_row?(x) && valid_column?(y) if valid_block?(x, y) if solve(board) return true end end end end board[x][y] = 0 return false end end end end def board return @board end def board_completed?(board) result = true board.each_with_index do |row, row_index| row.each_with_index do |cell, col_index| result = result && valid_row?(row_index) && valid_column?(col_index) && cell != 0 && valid_block?(row_index, col_index) end end return result end def to_s print_string = "" @board.each do |row| print_string += row.join("") + "\n" end print_string end end
Python
UTF-8
664
2.59375
3
[]
no_license
import gtk class QTTable(gtk.TreeView): def __init__(self, colinfo, model): gtk.TreeView.__init__(self) self.set_model(model) self.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH) self.set_headers_visible(True) self._colinfo = colinfo index = 0 for colname, options in colinfo: renderer = gtk.CellRendererText() for item in ('size', 'scale'): if item in options: renderer.set_property(item, options[item]) column = gtk.TreeViewColumn(colname, renderer, text=index) self.append_column(column) index += 1
Java
UTF-8
297
1.9375
2
[]
no_license
package pe.edu.upeu.gth.interfaz; import java.util.ArrayList; import java.util.Map; public interface CRUDOperations { public ArrayList<Map<String, Object>> listar(); public boolean add(Object o); public boolean edit(Object o); public boolean delete(Object o); }
C#
UTF-8
1,387
2.765625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoMapper; using MediatR; namespace MovieData.Models { public class GetAllMoviesRequest :IRequest<GetAllMoviesResponse> { public int Id { get; set; } [Required(ErrorMessage = "Enter Movie Title")] public string Title { get; set; } [Required(ErrorMessage = "Enter Movie Genre")] public string Genre { get; set; } [Range(1990, 2060)] public string ReleseDate { get; set; } } public class GetAllMoviesResponse { public List<MvcMovieContext> Success { get; set; } } internal class GetAllMoviesHandler : IRequestHandler<GetAllMoviesRequest, GetAllMoviesResponse> { IMovieDataAccess _movieDataAccess; private readonly IMapper _mapper; public GetAllMoviesHandler(IMovieDataAccess movieDataAccess,IMapper mapper) { _movieDataAccess = movieDataAccess; _mapper = mapper; } public async Task<GetAllMoviesResponse> Handle(GetAllMoviesRequest request, CancellationToken cancellationToken) { return new GetAllMoviesResponse() { Success = _movieDataAccess.GetAllMovies() }; } } }
Python
UTF-8
398
3.359375
3
[]
no_license
class Solution: # @param {integer} n # @return {string} def convertToTitle(self, n): times = 0 res = [] while n >= 27: res.append(n % 27) n %= 27 times += 1 if times == 10000: break res.append(n) return res test = Solution() for i in range(24,30): print(test.convertToTitle(i))
Java
UTF-8
1,599
2.546875
3
[]
no_license
package nc.ccas.gasel.services.doc; import static java.util.regex.Pattern.compile; import java.util.Arrays; import java.util.Collection; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; public class XmlDocChecker implements DocumentChecker { public static final XmlDocChecker INSTANCE = new XmlDocChecker(); static final Pattern VAR_PATTERN = compile("\\$\\{([a-zA-Z0-9_ ]+)\\}"); public DocumentCheckResult checkDocument(String documentData, String... allowedVariables) { return checkDocument(documentData, Arrays.asList(allowedVariables)); } public DocumentCheckResult checkDocument(String documentData, Collection<String> allowedVariables) { return _checkDocument(documentData, // new TreeSet<String>(allowedVariables)); } private DocumentCheckResult _checkDocument(String documentData, Set<String> allowedVariables) { DocumentCheckResult checkResult = new DocumentCheckResult(); if (!documentData.startsWith("<?xml")) { checkResult.error("Format du document invalide"); return checkResult; } Matcher matcher = VAR_PATTERN.matcher(documentData); while (matcher.find()) { String var = matcher.group(1).trim().toLowerCase(); checkResult.variable(var); if (!allowedVariables.contains(var)) checkResult.error("Variable invalide : " + var); } Set<String> variables = checkResult.variables(); for (String var : allowedVariables) { if (variables.contains(var)) continue; checkResult.warning("Variable inutilisée : " + var); } return checkResult; } }
JavaScript
UTF-8
960
2.5625
3
[]
no_license
/* Funciones Javascript para flotas_editar.php */ $(function(){ // Boton atrás: $("a#botvolver").click(function(){ $("form#detflota").submit(); }); // Boton cancelar: $("a#botreset").click(function(){ $("form#formflota")[0].reset() }); // Validar formulario $("form#formflota").submit(function(e){ var valido = true; var error = ''; var flota = $('input#flota').val(); var acronimo = $('input#acronimo').val(); if (flota.length < 6){ error = $('input#errflotalong').val(); valido = false; $('input#flota').focus(); } else{ if (acronimo.length < 6){ error = $('input#erracrolong').val(); valido = false; $('input#acronimo').focus(); } } if(!valido) { alert(error); e.preventDefault(); } }); });
TypeScript
UTF-8
2,259
2.640625
3
[]
no_license
import { ethers } from "hardhat"; import { assert, expect } from "chai"; import { Contract } from "@ethersproject/contracts"; describe("Bishop", function () { let bishop: Contract; before(async function () { const KnightMove = await ethers.getContractFactory("Bishop"); bishop = await KnightMove.deploy(); }); it('Bishop at (4, 4)', async function () { let moves = await bishop.functions.validMovesFor({X: 4, Y: 4}); expect(moves[0].includes([8, 8]), "[8, 8] Must be a valid move."); expect(moves[0].includes([1, 7]), "[1, 7] Must be a valid move."); expect(moves[0].includes([7, 1]), "[7, 1] Must be a valid move."); expect(moves[0].includes([1, 1]), "[1, 1] Must be a valid move."); expect(moves[0].includes([3, 3]), "[3, 3] Must be a valid move."); expect(moves[0].includes([5, 5]), "[5, 5] Must be a valid move."); expect(!moves[0].includes([9, 9]), "[9, 9] Shouldn't be a valid move."); expect(!moves[0].includes([0, 8]), "[0, 8] Shouldn't be a valid move."); expect(!moves[0].includes([8, 0]), "[9, 9] Shouldn't be a valid move."); expect(!moves[0].includes([0, 0]), "[0, 0] Shouldn't be a valid move."); }); it('Bishop at (1, 1)', async function () { let moves = await bishop.functions.validMovesFor({X: 1, Y: 1}); expect(moves[0].includes([2, 2]), "[2, 2] Must be a valid move."); expect(moves[0].includes([3, 3]), "[3, 3] Must be a valid move."); expect(moves[0].includes([4, 4]), "[4, 4] Must be a valid move."); expect(moves[0].includes([5, 5]), "[5, 5] Must be a valid move."); expect(moves[0].includes([6, 6]), "[6, 6] Must be a valid move."); expect(moves[0].includes([7, 7]), "[7, 7] Must be a valid move."); expect(moves[0].includes([8, 8]), "[8, 8] Must be a valid move."); expect(moves[0].length, "Moves must only be chess diagonal").be.eq(7); }); it('Bishop at (1, 2)', async function () { let moves = await bishop.functions.validMovesFor({X: 1, Y: 2}); expect(!moves.includes([4, 4]), "[4, 4] Shouldn't be a valid move."); expect(moves[0].length, "Moves must only be chess diagonal").be.eq(7); }); });
Python
UTF-8
2,252
3.5625
4
[]
no_license
from math import gcd from random import randint, choice task = """6. Реализовать алгоритм построения ПСП методом Фиббоначи с запаздываниями. Обосновать выбор коэффициентов алгоритма. Для начального заполнения использовать стандартную линейную конгруэнтную ПСП с выбранным периодом. Реализовать возможность для пользователя вводить коэффициенты заранее.""" def factor(n): result = [] d = 2 while d * d <= n: if n % d == 0: result.append(d) n //= d else: d += 1 if n > 1: result.append(n) return result def get_coeff(period): c = randint(0, period) while gcd(c, period) != 1: c += 1 b = 2 a = None factor_result = factor(period) while b <= period: if all([b % p == 0 for p in factor_result]): if period % 4 == 0: if b % 4 == 0: a = b + 1 break else: a = b + 1 break b += 1 return a, c, randint(2, period) def gen_linear_congruential(period): coeff_a, coeff_c, x0 = get_coeff(period) result = [x0] for i in range(1, period): result.append((coeff_a * result[i - 1] + coeff_c) % period) return result def LFG(init, lst, m, count): result = init.copy() for i in range(len(init), count): result.append(sum([result[len(result) - j] for j in lst]) % (2 ** m)) return result delays = input("Параметры запаздывания: ") if not delays: # y = x^k + x^j + 1 must be primitive delays = choice([[7, 10], [5, 17], [24, 55], [65, 71], [128, 159]]) k = delays[1] + 10 m = 8 print(f"delays = {delays}, k = {k}, m = {m}") else: delays = [int(item) for item in delays.split()] k = int(input("Длина начального заполнения: ")) m = int(input("Модуль: ")) initial_filling = gen_linear_congruential(k) print(LFG(initial_filling, delays, m, 1000))
Java
UTF-8
157
2.046875
2
[]
no_license
package com.smartglossa.calculator; public class Sample { public static void main(String[] args) { System.out.println("Hari is Best"); } }
Java
UTF-8
4,793
1.804688
2
[]
no_license
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2010.04.10 at 10:15:41 PM EDT // package net.edmacdonald.fantasyGrounds.character.fourthEdition.jpg; import net.edmacdonald.fantasyGrounds.character.fourthEdition.jpg.Action; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{}action"/> * &lt;element ref="{}keywords" minOccurs="0"/> * &lt;element ref="{}link"/> * &lt;element ref="{}name"/> * &lt;element ref="{}recharge"/> * &lt;element ref="{}shortdescription" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "action", "keywords", "link", "name", "recharge", "shortdescription" }) @XmlRootElement(name = "id-001") public class Id001 { @XmlElement(required = true) protected Action action; protected Keywords keywords; @XmlElement(required = true) protected Link link; @XmlElement(required = true) protected Name name; @XmlElement(required = true) protected Recharge recharge; protected Shortdescription shortdescription; /** * Gets the value of the action property. * * @return * possible object is * {@link Action } * */ public Action getAction() { return action; } /** * Sets the value of the action property. * * @param value * allowed object is * {@link Action } * */ public void setAction(Action value) { this.action = value; } /** * Gets the value of the keywords property. * * @return * possible object is * {@link Keywords } * */ public Keywords getKeywords() { return keywords; } /** * Sets the value of the keywords property. * * @param value * allowed object is * {@link Keywords } * */ public void setKeywords(Keywords value) { this.keywords = value; } /** * Gets the value of the link property. * * @return * possible object is * {@link Link } * */ public Link getLink() { return link; } /** * Sets the value of the link property. * * @param value * allowed object is * {@link Link } * */ public void setLink(Link value) { this.link = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link Name } * */ public Name getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link Name } * */ public void setName(Name value) { this.name = value; } /** * Gets the value of the recharge property. * * @return * possible object is * {@link Recharge } * */ public Recharge getRecharge() { return recharge; } /** * Sets the value of the recharge property. * * @param value * allowed object is * {@link Recharge } * */ public void setRecharge(Recharge value) { this.recharge = value; } /** * Gets the value of the shortdescription property. * * @return * possible object is * {@link Shortdescription } * */ public Shortdescription getShortdescription() { return shortdescription; } /** * Sets the value of the shortdescription property. * * @param value * allowed object is * {@link Shortdescription } * */ public void setShortdescription(Shortdescription value) { this.shortdescription = value; } }
PHP
UTF-8
173
2.5625
3
[ "MIT" ]
permissive
<?php namespace Swiftcore\Utility; interface ErrorBag { public function getErrors(); public function hasErrors(); public function addErrors(array $errors); }
C++
UTF-8
1,461
2.640625
3
[ "MIT" ]
permissive
/** * @defgroup Examples Examples of how to use OMiSCID. * */ /** * @file Examples/Accumulator.h * @ingroup Examples * @brief Demonstration of an accumulator server. Header file. * * @author Dominique Vaufreydaz */ #ifndef __ACCUMULATOR_WITH_STRUCTURED_MESSAGE_H__ #define __ACCUMULATOR_WITH_STRUCTURED_MESSAGE_H__ // Standard includes #include <ServiceControl/UserFriendlyAPI.h> #include "AccumulatorStructuredMessage.h" namespace Omiscid { /** * @class Accumulator * @ingroup Examples * @brief this class is used to managed an accumulator service. Is is also used * to monitor incomming activity from intput connector of the service */ class AccumulatorWithStructuredMessage : public ConnectorListener { public: /* @brief constructor */ AccumulatorWithStructuredMessage(); /* @brief destructor */ virtual ~AccumulatorWithStructuredMessage(); /* @brief callback function to receive data */ virtual void MessageReceived(Service& TheService, const SimpleString LocalConnectorName, const Message& Msg); private: Service * MyAssociatedService; /*!< my omiscid self */ // To work as an accumulator Mutex Locker; /*!< Lock access to my variable */ float Accu; /*!< my accumulator */ }; #ifdef OMISCID_RUNING_TEST // Call test in a separate function extern int DoAccumulatorWithStructuredMessageTest(int argc, char*argv[] ); #endif // OMISCID_RUNING_TEST } // namespace Omiscid #endif // __ACCUMULATOR_WITH_STRUCTURED_MESSAGE_H__
Markdown
UTF-8
1,034
2.515625
3
[]
no_license
## 0x15 JAVASCRIPT - Web JQuery ![JQUERY](https://s3.amazonaws.com/intranet-projects-files/holbertonschool-higher-level_programming+/305/4724718.jpg) #### AUTHOR Spencer Cheng: [github account](https://github.com/spencerhcheng), [twitter](https://twitter.com/spencerhcheng) #### SETUP All files are interpreted on Chrome (`version 57.0`). Code is style checked using `semistandard` with the flag `--global $:semistandard *.js --global $`. jQuery version 3.x is being used. ### OBJECTIVES Learning points: * How to select HTML elements in Javascript * How to select HTML elements with jQuery * What are differences between ID, class and tag name selectors * How to modify an HTML element style * How to get and update an HTML element content * How to modify the DOM * How to make a GET request with jQuery Ajax * How to make a POST request with jQuery Ajax * How to listen/bind to DOM events * How to listen/bind to user events Import jQuery ``` <head> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> </head> ```
C++
UTF-8
608
2.921875
3
[]
no_license
#include <Asset.h> TEST_CASE("Assets & Resources", "[CPU Memory Ops][Core]") { SECTION("Assets") { Asset<std::string> test; test.Set("Hello World"); REQUIRE(test.Get() == "Hello World"); Asset<int> iTest; iTest.Set(42); REQUIRE(iTest.Get() == 42); } SECTION("Resources") { Channel res; res.SetName("Resource Name"); REQUIRE(res.GetName() == "Resource Name"); res.SetType("image"); REQUIRE(res.GetType() == "image"); res.SetUri("uri//uri"); REQUIRE(res.GetUri() == "uri//uri"); } }