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
|
---|---|---|---|---|---|---|---|
Ruby
|
UTF-8
| 197 | 2.59375 | 3 |
[] |
no_license
|
class ExchangeRate
def self.calculate_rate(date, amount, base_curr, counter_curr)
rate = FxLib::ExchangeRate.at(date, base_curr, counter_curr)
return (rate * amount).round(4)
end
end
|
Markdown
|
UTF-8
| 33,721 | 3.078125 | 3 |
[] |
no_license
|
# 科学网—终极问题:时间和宇宙的生与死 - 徐明昆的博文
# 终极问题:时间和宇宙的生与死
已有 3441 次阅读2015-6-15 18:50|个人分类:[相对论与量子力学](http://blog.sciencenet.cn/home.php?mod=space&uid=537101&do=blog&classid=153381&view=me)|系统分类:[论文交流](http://blog.sciencenet.cn/home.php?mod=space&do=blog&view=all&uid=537101&catid=11)
别人,或者我猜测:
1.时间不是独立的,时间不能脱离物质单独存在,时间是物质(运动)的属性。
2.所有物质物体不运动,那么时间就不再流逝,或者说时间死了。。
3.物质不会全部湮灭,至少物质和能量不会都湮灭,但是热寂后时间仍然会死【1,2】
4.宇宙起源于(黑洞的?)大爆炸,宇宙大爆炸“之前”宇宙是什么样?这个问题不正确,因为大爆炸后才有时间,没有时间就没有“之前”概念【0】
5.宇宙大爆炸“之前是虚无吗?那要看“虚无”的定义,虚无,是不是连时间空间都没有?
6物理学是研究宇宙规律的,宇宙和时间生前死后是什么样的,可能超出传统物理学的范围。
7.会不会热寂-大爆炸--热寂。。或者收缩--膨胀。。或者,黑洞--爆炸--黑洞。。无限循环呢?
彭罗斯说的物质。。能量。。物质。。循环,也有道理。
8.圣经说,上帝造日月星辰,暗示上帝存在于宇宙大爆炸之前
9.上帝存在吗?这是一个无法证明,也无法证否的问题。因为超出了科学甚至逻辑的范畴。
10.对于这类问题,数学物理似乎不太适用。
BTW :
1。这些“怪异”的想法提示,思想不能僵化,几乎所有发明发现,都产生于传统所
蔑视或反对的奇思怪想之中。
2。宇宙的第一推动力来自大爆炸还是上帝?有上帝创造宇宙是唯心论的说法,但第一推动力来自哪里,
不影响现实生活,不应该和现实政治 关联起来。
【0】[http://www.iqiyi.com/jilupian/20130321/2553330ef2f2cdf0.html](http://www.iqiyi.com/jilupian/20130321/2553330ef2f2cdf0.html)
大爆炸前没有时间。
【1】[http://baike.baidu.com/link?url=SWWkUS_Nh-W4LYZsCN_NIlDniWufEcNzVz_i47G75O0LPO-WfhbvBpl7k92T2T99tM7y9mqhw9_-7BEBLk016K](http://baike.baidu.com/link?url=SWWkUS_Nh-W4LYZsCN_NIlDniWufEcNzVz_i47G75O0LPO-WfhbvBpl7k92T2T99tM7y9mqhw9_-7BEBLk016K)
热寂理论起源于十九世纪物理学家对[热力学第一定律](http://baike.baidu.com/view/25098.htm)和[热力学第二定律](http://baike.baidu.com/view/24939.htm)对宇宙进程的影响的研究,特别是威廉·汤姆森在1851年对当时的一个动态热力学理论(theory of heat)实验做出了如下描述:“热量并非一种物质,然而是机械作用的一种动态形式,我们认识到机械[功](http://baike.baidu.com/view/14447.htm)与热量之间必须是相关的,就如同因与果【1】
热寂理论(Heat death)是猜想宇宙终极命运的一种假说。根据[热力学第二定律](http://baike.baidu.com/view/24939.htm),作为一个“孤立”的系统,宇宙的[熵](http://baike.baidu.com/view/936.htm)会随着时间的流逝而增加,由有序向无序,当宇宙的熵达到最大值时,宇宙中的其他有效能量已经全数转化为热能,所有物质温度达到[热平衡](http://baike.baidu.com/view/708782.htm)。这种状态称为热寂。这样的宇宙中再也没有任何可以维持运动或是生命的能量存在。热寂理论最早由[威廉·汤姆森](http://baike.baidu.com/view/2672001.htm)(William Thomson)于1850年根据自然界中机械能损失的热力学原理推导出的。
【2】http://chuansong.me/n/1455080
**撰文** | 乔治·穆瑟(George Musser)
**翻译** | 虞骏
经验告诉我们,没有任何东西会真正终结。我们死后,尸体会腐败,体内物质会回归泥土和空气,让新的生命能够从中诞生。所以不论变成什么,“我们”都将继续存在下去。可是,这种存在会持续到永远吗?会不会到了未来的某个时间点,就再也没有“之后”可言了呢?令人沮丧的是,现代物理学暗示,前一个答案是不会,后一个答案是会。时间本身有可能终结。所有的活动都将停滞,再也不会更新,再也不会恢复。时间的终结将是所有终结的终结。
爱因斯坦在提出广义相对论诠释引力时,恐怕连他自己都不曾预料到,他的理论会预言出这么一个可怕的前景。在广义相对论之前,大多数物理学家和哲学家都认为,时间是一种放之四海而皆准的鼓声,是宇宙要与之同步的一种稳定节律,不会变化,不会摇摆,也不会停止。爱因斯坦则证明,宇宙更像是一场盛大的复合节奏爵士摇滚即兴演奏会。时间可以变慢,可以拉长,可以被“撕成碎片”。我们感受到引力的同时,也在感受着时间节律的即兴演奏;下落的物体被拖到了时间流逝更加缓慢的地方。时间不仅会影响物体的运作,反过来,物体在做什么也会影响到时间,就像鼓手和舞者彼此激发,共同演绎一段变奏热舞一样。不过,事情一旦失去控制,时间也可能灰飞烟灭,就像一位兴奋过头的鼓手突然暴毙一样。
出现这种情况的那些时刻,被称为奇点(singularity)。这个术语实际所指的正是时间的边界,可能是开端,也可能是终点。最著名的奇点当数宇宙大爆炸(big bang),也就是137亿年前我们这个宇宙(以及其中的时间)无中生有并开始膨胀的那一瞬间。如果宇宙有一天停止膨胀,转而开始收缩,最终就会发生某种与大爆炸相反的过程,称为大挤压(big crunch),给时间“压”出一个终点。时间不一定非得在所有地方同步终结。相对论说,时间会在黑洞内部走到尽头,而在黑洞之外,宇宙绝大多数其他地方,时间仍将继续。黑洞的破坏力名不虚传,甚至超过你对它的所有想象。如果你落入一个黑洞,不仅你的身体会被撕成碎片,这些碎片最终还会撞上黑洞中心的一个奇点,你的时间线(timeline)也就此走到了尽头。你的灰烬中再也诞生不出新的生命,你的分子也不会再得到任何回收利用。就像小说中的某个角色走到了这本小说的最后一页,你遭遇到的不仅仅是死亡,还有彻底的“不复存在”。
相对论会预言诸如死后无法“再生”这么令人不安的事情,这一点物理学家花了几十年才逐渐接受。直到今天,他们还是不太确定,这到底是怎么回事。奇点可以说是物理学家追寻物理学大统一理论的主要原因——他们将爱因斯坦独创的广义相对论与量子力学结合,试图创造出一种量子引力理论。在某种程度上,他们希望这一理论能够令人满意地解释奇点。不过对于“希望”二字,你必须慎之又慎。时间终结令人难以想象,但时间没有终点或许同样矛盾重重。
时间的边界物理学家在时间终结这个问题上对二律悖反的纠结丝毫不亚于哲学家。
无论是在哲学还是在现代物理学中,时间有终点也好,没有终点也罢,都会带来一大堆难题。
在爱因斯坦出现之前很久,各个时代的哲学家就已经为时间是否终有一死而争论不休了。康德(Immanuel Kant)认为,这个问题是一个“二律悖反”(antinomy)——这个哲学术语指的是怎么说都有理,让人不知道该如何思考。
亚里士多德提出了一个类似的原则,他主张时间既没有起点,也没有终点。每一个时刻都是前一个阶段的终点,又都是后一个阶段的起点;每一个事件都是某些前因的后果,又都是另一些后果的前因。所以,时间怎么可能会终结?有什么东西能够保证历史上的最后一件事之后不再有其他事件出现?事实上,就连“终结”这个概念本身都隐含着时间存在这样一个先决条件,既然如此,你又如何能够定义时间的终结?“时间有一个终点,这在逻辑上是不可能的,”英国牛津大学的哲学家理查德·斯温伯恩(Richard Swinburne)如此断言。不过,如果时间无法终结,宇宙必然要无限存在下去,这样一来,所有由“无限”这个概念引出的难题就都会接踵而至。哲学家早就认定,“无限”只是一个数学上的理想化概念,除此之外的所有“无限”都是荒谬的。
大爆炸理论的胜出,以及宇宙中黑洞的发现,似乎为这个问题做了一个了断。宇宙中充斥着奇点,宇宙本身也可能遭遇各种令人不安的时间劫难。就算躲过了大挤压,宇宙也可能被大撕裂(big rip)、大冻结(big freeze)或大刹车(big brake)搞定。不过,如果再追问一句,奇点(不论大小)到底是什么,答案就不那么明确了。“奇点的物理本质,现在还没有定论,”美国密歇根大学安阿伯分校的著名物理哲学家劳伦斯·斯克拉(Lawrence Sklar)说道。
恰恰是招惹出奇点这些“怪物”的那个理论,暗示它们无法真正存在。以大爆炸奇点为例:相对论说,我们看到的每一个星系的前身都曾经被压缩到一点——不只是一个细微如针尖般大小的点,而是一个数学意义上大小为零的点。与此类似,不幸落入黑洞之中的宇航员身上的每一个粒子,也都会被压缩到一个无限小的点中。在这两种情况下,计算密度都意味着要用质量除以一个数值为零的体积,得到的结果是无穷大。其他类型的奇点不会遇到无穷大的密度,但总会遇到无穷大的其他物理量。
尽管现代物理学家不像亚里士多德和康德那样讨厌“无限”,但他们仍把“无限”视为一个信号,表明他们把某个理论扩展运用到超出了极限。不妨回顾一下中学课堂上教过的光线折反射理论。这个理论完美地解释了眼镜和哈哈镜的成像原理。不过它也预言,一块凸透镜会把遥远光源发出的平行光线聚焦到一点,产生一个光强无限大的亮点。实际上,光并不会聚焦到一点,而是会形成一个牛眼状图案。它的光强或许很高,但总归是有限的。光线理论的错误之处在于,光实际上不是线,而是波。
基于类似的思路,几乎所有物理学家都推测,宇宙中的奇点实际上拥有一个就算很高但也有限的密度。相对论的错误之处在于,它漏掉了引力或物质的某个重要属性——正是这个属性在奇点附近发挥作用,把密度保持在了可以控制的范围之内。“大多数人会说,它们(指奇点)标志着这个理论在那里崩溃了,”美国加利福尼亚大学圣巴巴拉分校的物理学家詹姆斯·B·哈特尔(James B. Hartle)说道。要想弄清楚到底发生了什么,就必须用到一个更加完善的理论——量子引力论。物理学家还在苦苦钻研这样一个理论,但他们估计,这个理论会包容量子力学的一个重要见解——物质跟光一样,拥有类似于波的性质。这些波动性应该会把假想的奇点“模糊”成小小的一团,而不再是一点,因而也就排除了“除以零”这样的错误。果真如此的话,时间实际上或许就不会终结。
关于这一点,物理学家分成了两派。一些物理学家认为,时间确实会终结。这种观点的问题在于,已知的物理学定律都是在时间中运作的,描述的也都是事物如何随时间移动和演化。时间的终点超出了已知物理学的范畴。负责掌管时间终点的,必定不会是现有物理学体系中的某一条未知定律,而应该是一套全新的物理学定律——它能避开运动和改变之类与时间有关的概念,而是偏向于几何简洁性之类与时间无关的概念。3 年前,借用量子引力论主流候选理论——弦论(string theory)中的一些观点,新加坡国立大学的布雷特·麦金尼斯(Brett McInnes)提出了一个构想。他提出,在宇宙还是最初那一小团的时候,它的形状是一个圆环面;与圆环面有关的那些数学定理,决定了当时的宇宙必定是完美均匀和完美平滑的。然而,在大挤压或者某个黑洞的奇点处,宇宙可能拥有任何形状,同样的数学推理不一定仍然适用;此时的宇宙,大体上可以说是极端的破烂不堪。这样一套几何物理学定律与通常的动力学定律有着本质的不同:它并不是时间对称的。换句话说,终结不会仅仅是开端的反演。
其他量子引力研究者认为,时间会永恒延伸,既没有开端,也没有终点。在他们看来,大爆炸只是宇宙永恒生命中一个戏剧性的转折点。或许大爆炸前的宇宙经历了一场大挤压,在密度变得太高时发生了逆转——这个场景被称为大反弹(big bounce)。大爆炸前这段宇宙历史中的一些遗迹,甚至有可能流传到今天。按照类似的推理,黑洞中心附近的那一小团奇点也可能像一颗微缩版的恒星那样不停地沸腾和翻滚。如果落入一个黑洞,你会在痛苦中死去,但至少你的时间线不会就此到头。你体内的粒子会“扑通”一声落入这一小团,在它上面留下一个独特的印记,有可能在这个黑洞散发出的微弱光芒中被未来某一代人看到。
假定时间能够持续下去——通过这种方式,这一观点的支持者大可不必再为所谓“一套全新的物理学定律”而大费脑筋。不过,他们同样遇到了麻烦。比方说,宇宙随着时间的流逝只会变得越来越凌乱,如果这一过程已经持续了无限久,那为什么今天的宇宙还没有彻底沦为一盘散沙?至于黑洞,携带有你的印记的那些光又该如何才能逃离那个黑洞的引力魔爪?
归根结底,物理学家在时间终结这个问题上对二律悖反的纠结丝毫不亚于哲学家。已故的量子引力先驱约翰·阿奇博尔德·惠勒(John Archibald Wheeler)就曾经写道:“爱因斯坦的方程说‘这就是终点’,物理学家却说‘终点不存在’。”面对这种两难的局面,一些人干脆举手投降,总结说科学永远无法解决时间会不会终结这个问题。在他们看来,时间的边界同样也是推理和经验观察适用范围的边界。不过,其他一些人认为,破解这道难题只需要一些全新的思路。“这并没有超出物理学的范畴,”美国加利福尼亚大学圣巴巴拉分校的物理学家加里·霍罗威茨(Gary Horowitz)说,“量子引力论应该能够提供一个明确的答案。”
时间之死不过是一个复杂体系的崩溃,就像人类生命的消逝一样,没有什么自相矛盾之处。
尽管HAL 9000只是一台电脑,但“他”大概是电影《2001太空漫游》(2001: A Space Odyssey)里最有人味儿的角色——表情丰富、足智多谋,不仅仅是一大堆线缆,更是诸多矛盾的集合体。就连“他”的死亡都让人联想到人类的死亡。死亡不只是一个事件,而且是一个过程。当戴夫(Dave,电影中的一个角色)慢慢地拔出HAL的电路板时,“他”一项接一项地丧失着智力,同时描述了自己的感受。HAL能够清晰地表达出自己变得越来越衰弱的体验,这是人类在死亡时通常无法做到的。人类的生命是复杂机体的一大壮举,是科学领域内已知最复杂的组织,它的出现和消逝穿越了生命和非生命之间的模糊地带。现代医学在这片模糊地带之中点亮了一盏灯笼,因为医生如今能够挽救过去可能无法存活的早产婴儿,能够复活曾经认为已经死去的濒死病人。
就在物理学家和哲学家苦苦思索试图领悟时间如何终结时,许多人看到了它与生命终结之间的相似之处。正如生命是在无生命的分子组织成机体的过程中涌现出来的一样,时间也可能是在无时间的原料自行产生秩序的过程中涌现出来的。存在时间的世界是一个高度组织化的世界。时间告诉我们诸多事件何时发生,持续多久,以及它们发生的先后次序。或许这种结构不是外部强加的,而是内部产生的。能够产生出来的东西,自然也可以被摧毁。当这种结构分崩离析时,时间便终结了。
按照这种思路,时间之死只不过是一个复杂体系的崩溃,并不比其他任何体系的崩溃更难理解,没有任何自相矛盾、左右为难之处。一项接着一项,时间会丧失它的特性,穿越存在和不存在之间的模糊地带。
最先丧失的特性可能是时间的单向性(unidirectionality,也就是由过去指向未来的那个“时间箭头”。物理学家早在19世纪中叶就已经认识到,时间箭头并不是时间本身的属性,而是物质的属性。时间本身是双向的;我们感受到的时间箭头,只是物质从有序过渡到凌乱的一种自然退化,任何家里养着宠物或者小孩的人对此都会深有感触。(整齐、简洁及有序的起源,可能要归功于麦金尼斯推测的那个几何原理。)如果这一趋势持续下去,宇宙最终将达到一种平衡态,又被称为“热寂”(heat death),这是凌乱到不可能比它本身更乱的一种状态。单个粒子仍将持续不断地进行着自我重组,但宇宙作为一个整体将不再会有任何变化,任何幸存下来的“时钟”都将在前后两个方向上左摇右摆,未来将变得跟过去没有任何区别。少数物理学家已经推测,时间箭头可能会反转,以便宇宙自行恢复到整齐简洁的状态。不过,对于我们这些无法永生的生物来说,连我们自身的存在都取决于指向未来的时间箭头,这样的反转无疑像热寂一样,标志着时间的终结。
消失的时间踪迹当所有恒星都熄灭了很久之后,宇宙将变成一锅由黑洞和自由粒子构成的大杂烩;接下来,就连黑洞也将消散,只留下粒子。
“如果时间就是时钟测量的那个东西,而时钟又根本不存在,那么时间也就不存在。”
最近有研究暗示,时间箭头或许并不是时间遭受死亡折磨时可能丧失的唯一特性。另一个会丧失的特性,可能是衡量时间持续长短的“持续时间”(duration)。我们所知的时间可以用秒、天、年来计量。如果不是这样,我们就只能说出事件发生的先后顺序,无法说出它们到底持续了多久。这正是英国牛津大学物理学家罗杰·彭罗斯(RogerPenrose)在他的新书《时间的循环》(Cycles of Time: An Extraordinary New View of the Universe)中提出的场景。彭罗斯的科研生涯,似乎自始至终都在跟时间过不去。他和英国剑桥大学的物理学家斯蒂芬·霍金(Stephen Hawking)在20世纪60年代证明,奇点并不只在某些特殊前提下才会出现,它的产生应该无法避免。他还主张,落入黑洞的物质不会再有“来世”,在一个真正基础的物理学理论中也不会有时间的一席之地。
最近,彭罗斯从极早期宇宙的一个基本观测事实出发,对时间发起了最新一轮攻击。极早期宇宙就像是一盒刚刚被倒在地板上还没有组装的乐高积木,由一大堆夸克、电子和其他基本粒子混合而成。原子、分子、恒星和星系之类的结构,必须从这堆混合物中一步一步自行组装出来。第一步就是要组装出质子和中子,它们每一个都由3个夸克构成,尺度大约是1 飞米(femtometer,10-15米)。质子和中子会在大爆炸(或大反弹,随便它到底是啥)后10微秒左右出现。
在此之前,宇宙中完全不存在结构——没有任何东西是由“零件”组装而成的。因此,宇宙中也没有任何东西能够起到时钟的作用。时钟要想通过摆动来计时,就必须有一个定义明确的参照,例如钟摆的长度、两面镜子之间的距离,或者原子轨道的大小。连这样的参照物当时都还根本不存在。粒子或许会暂时聚集成团,但它们无法告诉你时间,因为它们没有固定的大小。单个夸克和电子也不能当作参照,因为它们都没有大小。无论物理学家把这样一个粒子放到多大,他们看到的永远是一个点。这些粒子拥有的唯一一个跟“大小”沾边的属性,是它们的所谓“康普顿波长”(Compton wavelength)——这一属性设定了粒子量子效应的尺度,与粒子的质量成反比。然而,在大爆炸后的最初10 皮秒(picosecond,10-12秒)内,这些粒子就连这么基本的尺度属性都没有,因为当时赋予它们质量的过程还没有发生。
“没有了类似于时钟的东西,”彭罗斯说,“事物就不知道如何去记录时间。”没有任何东西能够标记出固定的时间间隔,因此不管是经过了1阿秒(attosecond,10-18秒)还是1飞秒,对于极早期宇宙这锅“原汤”中的粒子来说,都没有任何区别。
彭罗斯提出,能够用这一场景来描述的,不只有久远的过去,还包括久远的未来。当所有恒星都熄灭了很久之后,宇宙将变成一锅由黑洞和自由粒子构成的大杂烩;接下来,就连黑洞也将消散,只留下粒子。这些粒子中的绝大多数将是光子之类的无质量粒子,构建时钟再次成为了不可能完成的任务。在另一种末日场景中,宇宙比方说会被大挤压扼杀,时钟的命运也同样不容乐观。
或许你会认为,就算没有任何东西能够测量时间的持续,至少在抽象意义上,这个概念也应该依然存在才对。不过科学家质疑,一个无法被测量的量,在理论上是否真的存在。在他们看来,无法构建时钟就是一个信号,表明时间本身已经被剥夺了一个基本特征。“如果时间就是时钟测量的那个东西,而时钟又根本不存在,那么时间也就不存在,”西班牙格拉纳达大学(University of Granada)的物理哲学家亨里克·津克纳格尔(Henrik Zinkernagel)说,他也对早期宇宙中时间的消失进行过研究。
彭罗斯提出的场景尽管看上去很简洁,但确实存在弱点。在非常久远的未来,并不是所有的粒子都没有质量;至少电子会幸存下来,利用这些电子,你应该能够构建出一个时钟。彭罗斯推测,电子可能会经历某种“减肥”过程,从而抛弃质量,不过他也承认这种说法不太靠谱。他说:“这个理论有很多让我不爽的地方,这只是其中一处。”再说,如果早期宇宙连尺度这个概念都不存在,那它又如何能够膨胀、稀释和冷却呢?不过,如果彭罗斯真的猜中了什么,那便可以得出一个惊人的推论。尽管致密拥挤的早期宇宙和越来越空旷的久远未来看上去像是完全相反的两个极端,但它们同样都被剥夺了时钟及其他度量尺度的“器具”。用彭罗斯的话来说,“大爆炸和久远的未来非常相似。”他大胆地猜测,久远的过去和久远的未来实际上是一个宏大宇宙循环中的同一个阶段。时间终结之时,时针会拨回到起点,开始新一轮的大爆炸。彭罗斯,这位整个学术生涯都在主张奇点标志着时间终点的科学家,或许发现了一种让时间得以延续的方式。这位时间“杀手”,已经变成了时间的救世主。
时间停滞在特定情况下,时间就连如此基本的“排序”功能也可能丧失,变得跟另外一维空间没有什么两样。
时钟可能会越来越慢,最终停止,时间不复存在,而是转化为另外一维空间。
即便时间的持续不再有意义,飞秒和阿秒不再可分,时间也还没有完全死透。它仍然可以标明一系列事件发生的先后次序和因果关联。就这一点而言,时间和空间有很大的不同,空间就很少对物品在其中应该如何排列有所约束。在时间上相邻的两个事件——比如我敲击键盘,字母出现在显示屏上——不可避免会存在关联。但空间中相邻的两个物体——比方说键盘和记事贴——彼此之间可能完全无关。空间关系不像时间关系那样存在必然性。
但在特定情况下,时间就连如此基本的“排序”功能也可能丧失,变得跟另外一维空间没有什么两样。这种观点可以追溯到20世纪80年代,当时霍金和哈特尔试图把大爆炸解释为时间和空间变得可以区分的那一刻。3 年前,西班牙萨拉曼卡大学(University of Salamanca)的马克·马尔斯(Marc Mars)和西班牙巴斯克地区大学(University of the Basque Country)的何塞·M·M·塞诺维利亚(José M. M. Senovilla)及劳尔·贝拉(Raül Vera)再次提出了类似的想法,只不过他们讨论的不是时间的起点,而是它的终点。
他们的灵感来自于弦论以及弦论的一个推论:我们的四维宇宙(三维空间加上一维时间)可能是一张膜,飘荡在一个更高维的空间中,就像风中的一片树叶。我们则被束缚在这张膜上,就像依附在那片树叶上的一条毛毛虫。正常情况下,我们可以在这个四维“囚笼”中随意走动。但是,如果这张膜受到狂风足够猛烈地吹袭,我们唯一能做的就只有拼命抓牢,再也无法移动分毫。确切地说,我们必须快得超过光速才能在这张膜上移动,可惜我们超不过光速。所有过程都涉及某种移动,因此它们全都会陷于停顿。
从外部来看,由我们生命中连续不断的运动构成的时间线并未终结,只是弯曲得太厉害,以至于它们不再穿越时间,而是从空间中穿过。这张膜仍旧是四维的,只不过所有四个维度都成了空间维度。马尔斯说,物体“受到这张膜的推动,移动速度越来越接近光速,直到最终它们的轨迹太过倾斜,以至于实际上它们在做超光速运动,不再存在时间。重点在于,它们或许完全不知道自己身上正在发生什么”。
我们所有的时钟也都会越走越慢,并最终停止,因此我们没办法确定时间正在转化为空间。我们唯一能看到的,只是星系之类的物体似乎正在加速运动。诡异的是,这恰恰是天文学家确确实实观测到的现象,通常被归因于某种未知的“暗能量”。这种加速有可能是时间的绝唱吗?
时间到了尽头作为终有一死的生物,通过对时间的思考,我们能够更好地认清自己在这个宇宙中所处的位置。
弦论的全息原理揭示,时间会在比奇点更大的范围内融化,连仅存的最后一项特征都消失掉。
到了弥留阶段,时间看起来或许已经消散于无形,但还有一个阴影仍然挥之不去。哪怕已经无法定义时间的持续,也弄不清楚因果关联,你仍然可以给各个事件标上发生的时间,把它们摆到一条时间线上。对于如何才能剥夺时间硕果仅存的这最后一项特征,几个弦论学家小组最近取得了一些进展。美国芝加哥大学的埃米尔·J·马丁内茨(Emil J. Martinec) 和萨夫迪普·S·塞西(Savdeep S. Sethi)、德克萨斯农工大学(Texas A&M University)的丹尼尔·罗宾斯(Daniel Robbins)、斯坦福大学的伊娃·西尔弗斯坦(Eva Silverstein)、布兰迪斯大学(Brandeis University)的阿尔比恩·劳伦斯(Albion Lawrence),还有霍罗威茨等人,已经运用弦论中最强大的一个想法——所谓的全息原理(holographic principle),对黑洞奇点处时间将会怎样进行了研究。
全息图(hologram)是一类能够让人感觉到深度的特殊图像。虽然全息图是平面的,但其中的图案看上去就像有一个实心物体飘浮在你面前的三维空间中一样。全息原理认为,我们的整个宇宙就像是一个全息投影。由相互作用量子粒子构成的一个复杂系统也能让人感觉到深度——换句话说,空间维度在最初的这个系统中并不存在。
不过,倒过来讲就不对了。并非所有的图像都是全息图,图案必须符合一定的条件才行。如果在一张全息图上乱涂乱画,立体幻影就会被破坏。同样的道理,并非所有的粒子系统都会产生一个与我们类似的宇宙;这个系统的“图案”也必须符合一定的条件才行。如果这个系统原本缺少必要的条件,后来创造出了这些条件,空间维度就会突然出现。如果这个系统重新回到了混乱状态,空间维度也会消失——从哪里来,就回哪里去。
接着,我们来设想一颗恒星坍缩成一个黑洞。这颗恒星在我们看来是三维的,但实际上只是某个二维粒子系统中某个图案的全息投影。随着恒星引力越来越强,与它对应的平面系统也会摇晃得越来越剧烈。当奇点终于形成时,秩序便彻底崩溃了。这个过程就像是冰块融化:具有规则晶格排列的水分子,化为了一摊杂乱无章的液体。因此,空间的第三维可以说是融化掉了。
随着第三维空间的融化,时间也会融化。如果你不幸落入一个黑洞,你手表上的时间将取决于你到这个黑洞的中心还有多远。这个距离是在这个正在融化的空间维度上定义的。随着这一空间维度的崩溃,你手表上的时针开始不受控制地乱转,指出事件发生在某个确切时刻、物体处在某个确切地点也已经变得不再可能了。用马丁内茨的话来说:“传统的时空几何概念已经终结了。”
这句话实际上是指,空间和时间已经无法再构建这个世界了。如果你试图测量物体的位置,你会发现它们看起来似乎处在不止一个位置上。空间上的间隔对它们来说没有任何意义;它们能从一个地点跳到另一个地点,而不用穿越中间的距离。事实上,正是通过这种方式,不幸落入黑洞的事件视界、从此一去不复返的那位宇航员留下的印记,才有可能逃出黑洞。“如果空间和时间在奇点附近都不存在,事件视界也就不再轮廓分明了。”霍罗威茨说。
换句话说,弦论所起的作用绝不仅仅是抹平假想中的奇点,在保持宇宙其他地方基本不变的前提下,把这些离经叛道的点替换成某种更对科学家胃口的东西。相反,它揭露出时间和空间的概念会在更大的范围内崩溃,其影响要远远超出奇点本身。需要强调的是,弦论仍然要求这个粒子系统中存在某种原始的时间观念。科学家仍在努力发展一种完全不需要时间作为前提假设的动力学观念。在这一目标实现之前,时间仍将顽强地活着。时间如此根深蒂固地渗透到了物理学的骨髓之中,以至于科学家现在还无法设想时间最终的彻底消失。
为了理解不可理解的东西,科学一贯采用的方法就是把它分解,然后去证明,看起来令人气馁的漫漫长路,也不过是一连串跬步的积累。对付时间的终结,也是如此。作为终有一死的生物,通过对时间的思考,我们能够更好地认清自己在这个宇宙中所处的位置。时间将会逐渐丧失的那些特征,是我们得以存在的先决条件。我们需要时间从过去流向未来,这样才能发育和进化;我们需要时间持续和尺度的概念,这样才能形成复杂的结构;我们需要有因果顺序,这样才能把各个过程一步步分解;我们需要有空间间隔,这样我们的身体才能在这个世界中创造出一小块秩序。随着这些特征的消散,我们继续生存下去的能力也将丧失。时间的终结或许可以想象,但没有人能够直接体验到它,就像没有人能够在自己死亡的那一刻保持清醒一样。
随着我们很多很多代之后的子孙越来越靠近时间终点,他们必须在一个越来越恶劣的宇宙中奋力求生。然而,他们的努力只会加速时间不可避免地迈向终结。毕竟,我们并不是时间死亡的被动受害者,而是杀死时间的帮凶。只要我们活着,就会把能量转化为无用的热量,对宇宙的状况恶化有所贡献。只要我们还活着,时间就难逃一死。
(博主则认为,人类死了,时间仍然难逃一死)
转载本文请联系原作者获取授权,同时请注明本文来自徐明昆科学网博客。
链接地址:[http://blog.sciencenet.cn/blog-537101-898229.html](http://blog.sciencenet.cn/blog-537101-898229.html)
上一篇:[高校学生怎样处理好婚恋与学业的关系](blog-537101-893817.html)
下一篇:[父亲节里话《父亲》](blog-537101-899590.html)
|
Java
|
UTF-8
| 208 | 1.867188 | 2 |
[] |
no_license
|
package com.example.demo.services;
import com.example.demo.entities.Project;
public interface ProjectService {
Project createProject(Long userId, Project project);
Project getProject(Long id);
}
|
Python
|
UTF-8
| 1,943 | 4.5625 | 5 |
[
"MIT"
] |
permissive
|
## Part 1 - Lab week 3
## Program to take input of name and print Hello "name"
# 1 name = str(input("Enter you name :"))
# 1 print("Hello {} ".format(name))
## Part 2
## Subtract 1st num from 2nd num and print
# 2 x = int(input("Please Enter first Number :",))
# 2 y = int(input("Please Enter second Number :"))
# 2 answer = x - y
# 2 print(" {} minus {} is {} ".format(x, y, answer))
## Part 3
## Divide 1st num by second num, give result and remainder
# 3 x = int(input("Enter first number: "))
# 3 y = int(input("Enter second number: "))
# 3 div = int(x/y)
# 3 rem = x%y
# 3 print("{} divided by {} is {} with a remainder of {}".format(x, y, div, rem))
## Part 4
## Prints out a random number from 1 - 10
# 4 import random
# 4 a = int(input("Enter 1st value in range "))
# 4 b = int(input("Enter 2nd value in range "))
# 4 num = random.randint(a,b)
# 4 print("Your random number is {}".format(num))
## Part 5
## Normalising a string and printing original and new characters
# 5 rs = (input("Please enter original raw String "))
# 5 normrs = rs.strip().upper()
# 5 lenrs = len(rs)
# 5 lennormrs = len(normrs)
# 5 print("The string you entered shouting is : {}!!!!! ".format(normrs))
# 5 print("We have shortened the number of characters from {} to {} ".format(lenrs, lennormrs))
## Part 6 & 7
## Program to print out a random fruit
# 6 import random
# 6 fruits = 'Apple', 'Orange', 'Pear','Banana', 'Kiwi'
# 6 ranfruit = random.randint(0,len(fruits)-1)
# 6 fruit = fruits[ranfruit]
# 6 print("Your random fruit is: {}".format(fruit))
# 6 print(fruits[-5])
## Part 8
## Dictionaries
## Creating a dictionary object
currentboook = { 'Title' :"A Whirlwind Tour of Python",
'Author' :"Colm Higgins",
'Price' :100 }
#print(currentboook)
#print(currentboook["Author"])
currentboook["ISBN"] = 12534087
print("currentbook has these values: ")
for attri in currentboook.values():
print(" => {}".format(attri))
|
Go
|
UTF-8
| 688 | 2.71875 | 3 |
[] |
no_license
|
package main
import (
"database/sql"
"log"
_ "github.com/mattn/go-sqlite3"
)
var gAskDB *sql.DB
// GetAskDB 获取当前的数据库连接,注意此方法不支持多线程访问,本程序目前也没有类似的需求。
func GetAskDB() *sql.DB {
if gAskDB == nil {
db, err := sql.Open("sqlite3", "./ask.db")
if err != nil {
log.Fatal(err)
}
_, err = db.Exec(`
create table if not exists cards (
id char(50) primary key not null,
title char(50) not null,
question text not null,
answer text,
review_time datetime default current_timestamp,
level integer default 0,
hash char(16)
)`)
if err != nil {
log.Fatal(err)
}
gAskDB = db
}
return gAskDB
}
|
Python
|
UTF-8
| 1,436 | 3.390625 | 3 |
[] |
no_license
|
class Solution:
def alienOrder(self, words):
graph = {}
indegree = {}
for word in words:
for c in word:
if c not in graph:
graph[c] = set()
indegree[c] = 0
prev_word = words[0]
for i in range(1,len(words)):
curr_word = words[i]
for i in range(min(len(prev_word),len(curr_word))):
prev_char = prev_word[i]
curr_char = curr_word[i]
if prev_char != curr_char:
if curr_char not in graph[prev_char]:
graph[prev_char].add(curr_char)
indegree[curr_char] += 1
break
prev_word = curr_word
ret_str = self.topo_sort(indegree,graph)
return "".join(ret_str) if len(indegree) == len(ret_str) else ""
def topo_sort(self,indegree,graph):
q = []
for c in indegree.keys():
if indegree[c] == 0:
q.append(c)
ret = []
while(len(q) > 0):
node = q.pop(0)
ret.append(node)
for go_to_node in graph[node]:
val = indegree[go_to_node] - 1
if val == 0:
q.append(go_to_node)
indegree[go_to_node] = val
return ret
s = Solution()
print(s.alienOrder(["wrt","wrf","er","ett","rftt","te"]))
|
Python
|
UTF-8
| 9,465 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
from keras.layers import Dropout, Dense, Embedding, LSTM, Bidirectional
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from sklearn.metrics import matthews_corrcoef, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.utils import shuffle
import numpy as np
import pickle
import matplotlib.pyplot as plt
import warnings
import logging
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from imblearn.under_sampling import RandomUnderSampler
logging.basicConfig(level=logging.INFO)
TEXT = "Text"
LABEL = "Label"
CV_splits = 5
def prepare_model_input(X_train, X_test,MAX_NB_WORDS=500,MAX_SEQUENCE_LENGTH=50):
np.random.seed(7)
print(X_train.shape)
print(X_train.head())
print(X_test.shape)
print(X_test.head())
text = np.concatenate((X_train, X_test), axis=0)
text = np.array(text)
tokenizer = Tokenizer(num_words=MAX_NB_WORDS)
tokenizer.fit_on_texts(text)
# pickle.dump(tokenizer, open('text_tokenizer.pkl', 'wb'))
# Uncomment above line to save the tokenizer as .pkl file
sequences = tokenizer.texts_to_sequences(text)
word_index = tokenizer.word_index
text = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)
print('Found %s unique tokens.' % len(word_index))
indices = np.arange(text.shape[0])
# np.random.shuffle(indices)
text = text[indices]
print(text.shape)
X_train_Glove = text[0:len(X_train), ]
X_test_Glove = text[len(X_train):, ]
embeddings_dict = {}
f = open("glove.6B.50d.txt", encoding="utf8")
for line in f:
values = line.split()
word = values[0]
try:
coefs = np.asarray(values[1:], dtype='float32')
except:
pass
embeddings_dict[word] = coefs
f.close()
print('Total %s word vectors.' % len(embeddings_dict))
return (X_train_Glove, X_test_Glove, word_index, embeddings_dict)
## Check function
#x_train_sample = ["Lorem Ipsum is simply dummy text of the printing and typesetting industry", "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout"]
#x_test_sample = ["I’m creating a macro and need some text for testing purposes", "I’m designing a document and don’t want to get bogged down in what the text actually says"]
#X_train_Glove_s, X_test_Glove_s, word_index_s, embeddings_dict_s = prepare_model_input(df_train['Text'].values.tolist(),
# df_test['Text'].values.tolist(), 100, 20)
#print("\n X_train_Glove_s \n ", X_train_Glove_s)
#print("\n X_test_Glove_s \n ", X_test_Glove_s)
#print("\n Word index of the word testing is : ", word_index_s["testing"])
#print("\n Embedding for the word want \n \n", embeddings_dict_s["want"])
def build_bilstm(word_index, embeddings_dict, nclasses, MAX_SEQUENCE_LENGTH=50, EMBEDDING_DIM=50, dropout=0.5, hidden_layer = 3, lstm_node = 32):
# Initialize a sequebtial model
model = Sequential()
# Make the embedding matrix using the embedding_dict
embedding_matrix = np.random.random((len(word_index) + 1, EMBEDDING_DIM))
for word, i in word_index.items():
embedding_vector = embeddings_dict.get(word)
if embedding_vector is not None:
# words not found in embedding index will be all-zeros.
if len(embedding_matrix[i]) != len(embedding_vector):
print("could not broadcast input array from shape", str(len(embedding_matrix[i])),
"into shape", str(len(embedding_vector)), " Please make sure your"
" EMBEDDING_DIM is equal to embedding_vector file ,GloVe,")
exit(1)
embedding_matrix[i] = embedding_vector
# Add embedding layer
model.add(Embedding(len(word_index) + 1,
EMBEDDING_DIM,
weights=[embedding_matrix],
input_length=MAX_SEQUENCE_LENGTH,
trainable=True))
# Add hidden layers
for i in range(0,hidden_layer):
# Add a bidirectional lstm layer
model.add(Bidirectional(LSTM(lstm_node, return_sequences=True, recurrent_dropout=0.2)))
# Add a dropout layer after each lstm layer
model.add(Dropout(dropout))
model.add(Bidirectional(LSTM(lstm_node, recurrent_dropout=0.2)))
model.add(Dropout(dropout))
# Add the fully connected layer with 256 nurons and relu activation
model.add(Dense(256, activation='relu'))
# Add the output layer with softmax activation since we have 2 classes
model.add(Dense(nclasses, activation='softmax'))
# Compile the model using sparse_categorical_crossentropy
model.compile(loss='sparse_categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
return model
def get_eval_report(labels, preds):
mcc = matthews_corrcoef(labels, preds)
tn, fp, fn, tp = confusion_matrix(labels, preds).ravel()
precision = (tp)/(tp+fp)
recall = (tp)/(tp+fn)
f1 = (2*(precision*recall))/(precision+recall)
return {
"mcc": mcc,
"true positive": tp,
"true negative": tn,
"false positive": fp,
"false negative": fn,
"pricision" : precision,
"recall" : recall,
"F1" : f1,
"accuracy": (tp+tn)/(tp+tn+fp+fn)
}
def compute_metrics(labels, preds):
assert len(preds) == len(labels)
return get_eval_report(labels, preds)
def plot_graphs(history, string):
plt.plot(history.history[string])
plt.plot(history.history['val_'+string], '')
plt.xlabel("Epochs")
plt.ylabel(string)
plt.legend([string, 'val_'+string])
plt.show()
def filter_dataframe(df, cat):
count = 0
for ind, row in df.iterrows():
if cat != str(row[LABEL]):
count += 1
row[LABEL] = 'Other'
print(f'{cat} filtered {count} rows in training dataset')
def get_sampling_strategy(df_train):
sizes = df_train.groupby(LABEL).size()
indexes = list(sizes.index)
cat_size = sizes[indexes.index(cat)]
other_cat_size = int(cat_size/(len(df_train[LABEL].unique())-2))+1
sampling_stratgy = {}
for c in df_train[LABEL].unique():
if c == cat:
sampling_stratgy[c] = cat_size
elif c == 'General':
sampling_stratgy[c] = 0
else:
sampling_stratgy[c] = min(other_cat_size, sizes[indexes.index(c)])
print('Sampling strategy: ', sampling_stratgy)
return sampling_stratgy
categories = ["Sequential", "Natural Language Processing", "Audio", "Computer Vision", "Graphs", "Reinforcement Learning"]
for i, cat in enumerate(categories):
df_train = pd.read_csv('../../data/readme_train.csv', sep=';')
df_test = pd.read_csv('../../data/readme_test.csv', sep=';')
df_train.drop( df_train[ df_train['Text'] == "" ].index , inplace=True)
df_test.drop( df_test[ df_test['Text'] == "" ].index , inplace=True)
df_train.drop_duplicates(subset=['Text'], inplace=True, keep=False)
df_train.drop_duplicates(subset=['Text'], inplace=True, keep=False)
df_train.drop( df_train[ df_train[TEXT] == "" ].index , inplace=True)
df_train.drop( df_train[ df_train[LABEL] == "General" ].index , inplace=True)
df_test.drop( df_test[ df_test[LABEL] == "General" ].index , inplace=True)
df_test.drop( df_test[ df_test[TEXT] == "" ].index , inplace=True)
ind = i + 1
print(f'Train test split starts for {cat=} category {ind}/{len(categories)}')
df_train = df_train.drop(columns = 'Repo')
x_train = df_train[TEXT]
y_train = df_train[LABEL]
x_test = df_test[TEXT]
y_test = df_test[LABEL]
undersample = RandomUnderSampler(sampling_strategy=get_sampling_strategy(df_train))
x_train, y_train = undersample.fit_resample(x_train.to_frame(TEXT), y_train)
x_train = x_train[TEXT]
y_train = y_train.to_frame(LABEL)
filter_dataframe(y_train, cat)
y_test = y_test.to_frame(LABEL)
filter_dataframe(y_test, cat)
y_train = np.ravel(y_train)
y_test = np.ravel(y_test)
le = LabelEncoder()
y_train = le.fit_transform(y_train)
y_test = le.transform(y_test)
print("Preparing model input ...")
X_train_Glove, X_test_Glove, word_index, embeddings_dict = prepare_model_input(x_train,x_test)
print("Done!")
print("Building Model!")
model = build_bilstm(word_index, embeddings_dict, 2)
model.summary()
history = model.fit(X_train_Glove, y_train,
validation_data=(X_test_Glove,y_test),
epochs=100,
batch_size=2,
verbose=1)
model.save_weights('/home/jenifer/Downloads/new/software_classification/weights')
plot_graphs(history, 'accuracy')
plot_graphs(history, 'loss')
print(f'\n Evaluating Model for cat: {cat}... \n')
predicted = model.predict(X_test_Glove)
print(predicted)
predicted=np.argmax(predicted,axis=1)
print(predicted)
print(metrics.classification_report(y_test, predicted))
print("\n")
logger = logging.getLogger("logger")
result = compute_metrics(y_test, predicted)
for key in (result.keys()):
logger.info(" %s = %s", key, str(result[key]))
|
Java
|
UTF-8
| 785 | 1.664063 | 2 |
[] |
no_license
|
package my.gov.kpn.quiz.core.dao;
import my.gov.kpn.quiz.core.model.QaPrincipal;
import my.gov.kpn.quiz.core.model.QaRoleType;
import my.gov.kpn.quiz.core.model.QaUser;
/**
* @author rafizan.baharum
* @since 11/9/13
*/
public interface QaPrincipalRoleDao {
void grant(QaPrincipal principal, QaRoleType roleType, QaUser user);
void grant(QaPrincipal principal, QaRoleType[] roleTypes, QaUser user);
void revoke(QaPrincipal principal, QaRoleType roleType, QaUser user);
void revoke(QaPrincipal principal, QaRoleType[] roleTypes, QaUser user);
void revokeAll(QaPrincipal principal, QaUser user);
void overwrite(QaPrincipal principal, QaRoleType roleType, QaUser user);
void overwrite(QaPrincipal principal, QaRoleType[] roleTypes, QaUser user);
}
|
C#
|
UTF-8
| 1,309 | 2.53125 | 3 |
[] |
no_license
|
using System;
using System.ComponentModel;
using System.Collections.ObjectModel;
using mywowNet;
namespace mywowNet.Data
{
public class Item : Entry
{
private int modelId;
private E_ITEM_TYPE type;
private string subclassName;
public int ModelId
{
get { return modelId; }
set
{
if (modelId != value)
{
modelId = value;
RaisePropertyChanged("ModelId");
}
}
}
public E_ITEM_TYPE Type
{
get { return type; }
set
{
if (type != value)
{
type = value;
RaisePropertyChanged("Type");
}
}
}
public string SubClassName
{
get { return subclassName; }
set
{
if (subclassName != value)
{
subclassName = value;
RaisePropertyChanged("SubClassName");
}
}
}
}
public class ItemCollection : ObservableCollection<Item>
{
}
}
|
C++
|
UTF-8
| 1,087 | 2.71875 | 3 |
[] |
no_license
|
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <deque>
#include <set>
#include <map>
#include <cmath>
using namespace std;
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
int plist[10000],pcount=0;
int prime(int n){
int i;
if ((n!=2&&!(n%2))||(n!=3&&!(n%3))||(n!=5&&!(n%5))||(n!=7&&!(n%7)))
return 0;
for (i=0;plist[i]*plist[i]<=n;i++)
if (!(n%plist[i]))
return 0;
return n>1;
}
void initprime(){
int i;
for (plist[pcount++]=2,i=3;i<50000;i++)
if (prime(i))
plist[pcount++]=i;
}
int doit(int n) {
int ret = 1;
int end = (int) sqrt(n + 0.0);
FOR(i,0,pcount-1) {
if (plist[i] > end) break;
if (n == 1) break;
int cnt = 0;
while (n % plist[i] == 0) {
++cnt;
n /= plist[i];
}
ret *= (cnt << 1) + 1;
}
if (n != 1) ret *= 3;
return ((ret - 1) >> 1) + 1;
}
void run() {
initprime();
FOR(i,1,1000000) {
int t = doit(i);
if (t > 1000) {
cout << i << " " << t << endl;
break;
}
}
}
int main () {
run();
return 0;
}
|
Markdown
|
UTF-8
| 1,491 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: "[政治] 游錫堃:亡國必先亡史 應加強台灣史教育"
date: 2020-08-03T13:49:55.000Z
author: RTI 中央廣播電臺
from: https://www.rti.org.tw/news/view/id/2074622
tags: [ RTI 中央廣播電臺 ]
categories: [ RTI 中央廣播電臺 ]
---
<!--1596462595000-->
[[政治] 游錫堃:亡國必先亡史 應加強台灣史教育](https://www.rti.org.tw/news/view/id/2074622)
------
<div>
<img src="https://static.rti.org.tw/assets/thumbnails/2020/06/04/4a281057e7334b5fd980bd84795c6234.jpg" width="360" alt="立法院長游錫堃。(劉玉秋 攝)" title="立法院長游錫堃。(劉玉秋 攝)"><br>立法院長游錫堃今天(3日)出席立法院「109年度職員教育訓練—台灣史碩士學分班」時致詞指出,台灣應該要加強台灣史教育,台灣要成為一個正常國家,如果對歷史不瞭解,這樣國不成國。 立法院委託國立政治大學辦理「109年度職員教育訓練—台灣史碩士學分班」,約30名立法院職員報名,游錫堃本身也參加。 這項課程3日晚間起開課並舉行始業式,包括政治大學校長郭明政、政大公共行政及企業管理教育中心主任顏玉明及課程教師政大文學院院長薛化元等人出席。游錫堃致詞時表示,他年過70歲,今天有機會認識這麼多新同學,覺得同學增加了,這是人生...<a target="_blank" href="https://www.rti.org.tw/news/view/id/2074622">...more</a>
</div>
|
Python
|
UTF-8
| 2,457 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
from scrapy.spiders import Spider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.http import Request
import numpy as np
class PageRankSpider(Spider):
name = "pagerank-crawler"
allowed_domains = [
"en.wikipedia.org"
]
start_urls = [
"https://en.wikipedia.org/wiki/Penguin"
]
deny_urls = [
"https://en\.wikipedia\.org/wiki/Wikipedia.*",
"https://en\.wikipedia\.org/wiki/Main_Page",
"https://en\.wikipedia\.org/wiki/Free_Content",
"https://en\.wikipedia\.org/wiki/Talk.*",
"https://en\.wikipedia\.org/wiki/Portal.*",
"https://en\.wikipedia\.org/wiki/Special.*",
"https://en\.wikipedia\.org/wiki/File.*",
".*#.*",
".*Help:.*",
".*Category:.*",
".*(identifier).*",
".*Template:.*"
]
link_extractor = LinkExtractor(allow="https://en\.wikipedia\.org/wiki/.+",
deny = deny_urls)
visited_pages = set(start_urls)
alpha = 0.15
def parse(self, response):
self.visited_pages = self.visited_pages.union({response.url})
source = response.url.split("/")[-1]
# teleport option
if np.random.rand() < self.alpha:
# seeded PageRank always goes back to the starting page
link = self.start_urls[0]
# alternatively, go back to a random,
# previously-visited page by uncommenting the
# line below (global PageRank)
# link = np.random.choice(list(self.visited_pages))
move_type = "teleport"
# walk option: click a random link on the page
else:
# list of all links on the page, subject to the inclusion and exclusion rules defined above
links = self.link_extractor.extract_links(response)
# pick a random one
n = np.random.randint(0, len(links))
link = links[n].url
move_type = "walk"
# yield data for saving
yield {
"source" : source,
"target" : link.split("/")[-1],
"move_type" : move_type
}
# follow new link
yield Request(link, callback = self.parse)
def parse_start_url(self, response):
return self.parse(response)
|
C#
|
UTF-8
| 3,816 | 2.515625 | 3 |
[] |
no_license
|
using IRC.Helpdesk.Core;
using IRC.Helpdesk.Core.POCOs;
using IRC.Helpdesk.Core.Tests;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Tests
{
/// <summary>
/// Tests for <see cref="ExcelAssetReader"/> Class
/// </summary>
public class ExcelAssetsReaderTests
{
/// <summary>
/// Mocking assets source configuration provider.
/// </summary>
public IAssetSourceConfiguration Config;
[SetUp]
public void Setup()
{
Config = new AssetsConfigurationSourceMock { FirstRow = 2, MakeIndex = 3, ModelIndex = 2, InventoryNumberIndex=3, UserIndex=4, LocationIndex=5 };
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
}
/// <summary>
/// Test if <see cref="ExcelAssetReader.ReadAssets"/> works.
/// </summary>
[Test]
public void ReadAssets_GetTickets_GreaterThan0()
{
var assetsReader = new ExcelAssetReader();
assetsReader.Configure(this.Config);
IEnumerable<AssetTicket> tickets = null;
using (Stream assetsFile = new FileStream(Environment.CurrentDirectory + "\\TestFiles\\Computer Info.xlsx", FileMode.Open))
{
assetsReader.SetSource(assetsFile);
tickets = assetsReader.ReadAssets();
}
Assert.IsNotNull(tickets);
Assert.Greater(tickets.Count(), 0);
}
/// <summary>
/// Test if <see cref="AssetsSourceConfiguration"/> is working properly.
/// </summary>
[Test]
public void CreateAssetsSourceConfiguration_Successfull()
{
var configuration = new AssetsSourceConfiguration(Environment.CurrentDirectory + "\\TestFiles\\AssetsConfigFile.json");
Assert.AreEqual(configuration.FirstRow, 2);
Assert.AreEqual(configuration.MakeIndex, 1);
Assert.AreEqual(configuration.ModelIndex, 2);
Assert.AreEqual(configuration.InventoryNumberIndex, 3);
Assert.AreEqual(configuration.UserIndex, 4);
Assert.AreEqual(configuration.LocationIndex, 5);
}
[TestCase("A", ExpectedResult =1)]
[TestCase("AA", ExpectedResult =27)]
[Test]
public int Convert_ExpectedResults(string columnId)
{
//Preparing
var configuration = new AssetsSourceConfiguration(Environment.CurrentDirectory + "\\TestFiles\\AssetsConfigFile.json");
return configuration.Convert(columnId);
}
/// <summary>
/// Test reading assets from excel text copied row.
/// </summary>
/// <param name="input"></param>
[TestCase(@"helpdesk@rescue.org 18-Aug-09 Office Equipment Camera Sony Nil Digital BFUM10302073 46171 518 270.00 OFDA GO238 Erbil Office Ops Store S 5IQ/ERB/AR#0304
")]
[Test]
public void ReadAssets_FromString_CheckValues(string input)
{
var reader = new ExcelAssetReader();
reader.Configure(this.Config);
var result = reader.ReadAssets(input).ToArray();
Assert.AreEqual(result[0].Model, "18-Aug-09");
}
/// <summary>
/// Test reading a string containing multiple assets.
/// </summary>
[Test]
public void ReadAssets_MultipleAssetsText()
{
var data = File.ReadAllText(Environment.CurrentDirectory + "\\TestFiles\\MultilineAssetsTestText.txt");
var reader = new ExcelAssetReader();
reader.Configure(this.Config);
var assets = reader.ReadAssets(data);
Assert.Greater(assets.Count(), 0);
}
}
}
|
JavaScript
|
UTF-8
| 1,578 | 2.890625 | 3 |
[] |
no_license
|
export function sortByOrigin(list){
var new_Array = [];
var groupby = new Map();
list.forEach((item, i) => {
if (!groupby.has(item.origin))
groupby.set(item.origin,[])
groupby.get(item.origin).push(item);
});
for (const [key,value] of groupby.entries()){
value.forEach((item, i) => {
new_Array.push(item);
});
}
return new_Array;
}
export function sortByDate(list){
var new_Array = [];
list.forEach((item, i) => {
new_Array.push(item);
});
new_Array.sort((a,b) => {
if (!a.hasOwnProperty('date')){
return 1;
}
if (!b.hasOwnProperty('date')){
return -1;
}
return (a.date.getTime() - b.date.getTime());
});
return new_Array;
}
export function sortByNormal(list){
var new_Array = [];
const [p_index, f_index] = list.reduce( ([p,f], e) => (e.hasOwnProperty('index') ? [[...p,e],f] : [p,[...f,e]]), [[],[]] );
const [p_date, f_date] = f_index.reduce( ([p,f], e) => (e.hasOwnProperty('date') ? [[...p,e],f] : [p,[...f,e]]), [[],[]] );
p_index.sort((a,b) => (a.index - b.index));
p_date.sort((a,b) => (a.date.getTime() - b.date.getTime()));
f_date.sort((a,b) => (a.name.localeCompare(b.name)));
p_index.forEach((item, i) => {
new_Array.push(item);
});
p_date.forEach((item, i) => {
new_Array.push(item);
});
f_date.forEach((item, i) => {
new_Array.push(item);
});
return new_Array;
}
export function updateIndex(list){
list.forEach((item, i) => {
item.index = i;
});
}
export default {sortByOrigin, sortByDate, sortByNormal, updateIndex};
|
Java
|
UTF-8
| 1,535 | 3.71875 | 4 |
[] |
no_license
|
package builtin.algorithms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortingTest {
public void testMergeSorting() {
Person p1 = new Person("Bob", 1);
Person p2 = new Person("Alice", 2);
Person p3 = new Person("Claire",3);
List<Person> list = new ArrayList<Person>();
list.add(p1);
list.add(p2);
list.add(p3);
Collections.sort(list, new PersonCmp());
for(Person p:list) {
System.out.println(p);
}
}
private void showList(List<Integer> list) {
for(int x:list) {
System.out.print(x+" ");
}
System.out.println();
}
public void testShuffleAndQucikSort() {
int[] input = {10,50,6000,85,3,1,100};
ArrayList<Integer> list = new ArrayList<Integer>();
for(int x:input) {
list.add(x);
}
//no shuffle method in Arrays
Collections.shuffle(list);
showList(list);
Collections.sort(list);
showList(list);
}
private class Person {
String name;
int id;
public Person(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public String toString() {
return "("+name+", "+Integer.toString(id)+")";
}
}
private class PersonCmp implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return p1.name.compareTo(p2.name);
}
}
public static void main(String[] args) {
SortingTest st = new SortingTest();
st.testMergeSorting();
st.testShuffleAndQucikSort();
}
}
|
C++
|
UTF-8
| 1,166 | 2.984375 | 3 |
[] |
no_license
|
//
// Action_Delay.h
// WalaberEngine
//
// Created by Gulliver, Christopher on 5/28/13.
//
//
#ifndef WalaberEngine_Action_Delay_h
#define WalaberEngine_Action_Delay_h
#include <IAction.h>
namespace Walaber
{
/*! An action that waits / delays for a specific amount of time before finishing execution
*/
class Action_Delay : public IAction
{
public:
Action_Delay( float delayTime ) :
mTimeElapsed(0),
mTimeToDelay(delayTime)
{
// Verify that the delay is not negative
assert( mTimeToDelay >= 0.0f ); // Why you trying have negative delay?
}
/*!
Execute until the delay time has expired
@param elapsedTime the time change since the last time execute was called
@return true when the delay time has expired
*/
virtual bool execute(float elapsedTime )
{
mTimeElapsed += elapsedTime;
return mTimeElapsed >= mTimeToDelay;
}
protected:
Action_Delay();
float mTimeElapsed;
float mTimeToDelay;
};
MAKE_SHARED_PTR( Action_Delay );
}
#endif
|
SQL
|
UTF-8
| 12,095 | 3.203125 | 3 |
[] |
no_license
|
/*
Navicat MySQL Data Transfer
Source Server : vm
Source Server Version : 50537
Source Host : localhost:3306
Source Database : Standard
Target Server Type : MYSQL
Target Server Version : 50537
File Encoding : 65001
Date: 2015-03-22 20:12:37
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `persons`
-- ----------------------------
DROP TABLE IF EXISTS `persons`;
CREATE TABLE `persons` (
`person_id` int(11) NOT NULL AUTO_INCREMENT,
`vorname` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`nachname` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`team_id` int(11) NOT NULL,
PRIMARY KEY (`person_id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of persons
-- ----------------------------
INSERT INTO `persons` VALUES ('1', 'Hans', 'Bergmann', '1');
INSERT INTO `persons` VALUES ('2', 'Klaus', 'Müller', '1');
INSERT INTO `persons` VALUES ('3', 'Johannes', 'Herrmann', '1');
INSERT INTO `persons` VALUES ('4', 'Jasmin', 'Freitag', '2');
INSERT INTO `persons` VALUES ('5', 'Martin', 'Hausler', '2');
INSERT INTO `persons` VALUES ('6', 'Stefanie', 'Neuhaus', '2');
INSERT INTO `persons` VALUES ('7', 'Birgit', 'Bauer', '3');
INSERT INTO `persons` VALUES ('8', 'Amy', 'Dam', '3');
INSERT INTO `persons` VALUES ('9', 'Tia', 'Klose', '3');
INSERT INTO `persons` VALUES ('10', 'Sebastian', 'Rusko', '4');
INSERT INTO `persons` VALUES ('11', 'Alexander', 'Breit', '4');
INSERT INTO `persons` VALUES ('12', 'Harald', 'Konig', '4');
INSERT INTO `persons` VALUES ('13', 'Sandro', 'Kant', '5');
INSERT INTO `persons` VALUES ('14', 'Christoph', 'Lauter', '5');
INSERT INTO `persons` VALUES ('15', 'Heinz', 'Ketch', '5');
-- ----------------------------
-- Table structure for `result_simple`
-- ----------------------------
DROP TABLE IF EXISTS `result_simple`;
CREATE TABLE `result_simple` (
`result_id` int(11) NOT NULL AUTO_INCREMENT,
`person_id` int(11) NOT NULL,
`points` int(11) NOT NULL,
PRIMARY KEY (`result_id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of result_simple
-- ----------------------------
INSERT INTO `result_simple` VALUES ('1', '1', '49');
INSERT INTO `result_simple` VALUES ('2', '2', '71');
INSERT INTO `result_simple` VALUES ('3', '3', '44');
INSERT INTO `result_simple` VALUES ('4', '4', '40');
INSERT INTO `result_simple` VALUES ('5', '5', '52');
INSERT INTO `result_simple` VALUES ('6', '6', '48');
INSERT INTO `result_simple` VALUES ('7', '7', '49');
INSERT INTO `result_simple` VALUES ('8', '8', '42');
INSERT INTO `result_simple` VALUES ('9', '9', '54');
INSERT INTO `result_simple` VALUES ('10', '10', '50');
INSERT INTO `result_simple` VALUES ('11', '11', '64');
INSERT INTO `result_simple` VALUES ('12', '12', '51');
INSERT INTO `result_simple` VALUES ('13', '13', '67');
INSERT INTO `result_simple` VALUES ('14', '14', '60');
INSERT INTO `result_simple` VALUES ('15', '15', '38');
-- ----------------------------
-- Table structure for `results`
-- ----------------------------
DROP TABLE IF EXISTS `results`;
CREATE TABLE `results` (
`result_id` int(11) NOT NULL AUTO_INCREMENT,
`round` int(11) NOT NULL,
`person_id` int(11) NOT NULL,
`points` int(11) NOT NULL,
PRIMARY KEY (`result_id`)
) ENGINE=InnoDB AUTO_INCREMENT=151 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of results
-- ----------------------------
INSERT INTO `results` VALUES ('1', '1', '1', '8');
INSERT INTO `results` VALUES ('2', '1', '2', '9');
INSERT INTO `results` VALUES ('3', '1', '3', '3');
INSERT INTO `results` VALUES ('4', '1', '4', '5');
INSERT INTO `results` VALUES ('5', '1', '5', '6');
INSERT INTO `results` VALUES ('6', '1', '6', '5');
INSERT INTO `results` VALUES ('7', '1', '7', '7');
INSERT INTO `results` VALUES ('8', '1', '8', '3');
INSERT INTO `results` VALUES ('9', '1', '9', '1');
INSERT INTO `results` VALUES ('10', '1', '10', '4');
INSERT INTO `results` VALUES ('11', '1', '11', '6');
INSERT INTO `results` VALUES ('12', '1', '12', '2');
INSERT INTO `results` VALUES ('13', '1', '13', '8');
INSERT INTO `results` VALUES ('14', '1', '14', '5');
INSERT INTO `results` VALUES ('15', '1', '15', '1');
INSERT INTO `results` VALUES ('16', '2', '1', '8');
INSERT INTO `results` VALUES ('17', '2', '2', '4');
INSERT INTO `results` VALUES ('18', '2', '3', '2');
INSERT INTO `results` VALUES ('19', '2', '4', '1');
INSERT INTO `results` VALUES ('20', '2', '5', '4');
INSERT INTO `results` VALUES ('21', '2', '6', '1');
INSERT INTO `results` VALUES ('22', '2', '7', '2');
INSERT INTO `results` VALUES ('23', '2', '8', '4');
INSERT INTO `results` VALUES ('24', '2', '9', '6');
INSERT INTO `results` VALUES ('25', '2', '10', '7');
INSERT INTO `results` VALUES ('26', '2', '11', '7');
INSERT INTO `results` VALUES ('27', '2', '12', '5');
INSERT INTO `results` VALUES ('28', '2', '13', '3');
INSERT INTO `results` VALUES ('29', '2', '14', '8');
INSERT INTO `results` VALUES ('30', '2', '15', '2');
INSERT INTO `results` VALUES ('31', '3', '1', '7');
INSERT INTO `results` VALUES ('32', '3', '2', '7');
INSERT INTO `results` VALUES ('33', '3', '3', '7');
INSERT INTO `results` VALUES ('34', '3', '4', '2');
INSERT INTO `results` VALUES ('35', '3', '5', '7');
INSERT INTO `results` VALUES ('36', '3', '6', '3');
INSERT INTO `results` VALUES ('37', '3', '7', '2');
INSERT INTO `results` VALUES ('38', '3', '8', '1');
INSERT INTO `results` VALUES ('39', '3', '9', '7');
INSERT INTO `results` VALUES ('40', '3', '10', '5');
INSERT INTO `results` VALUES ('41', '3', '11', '3');
INSERT INTO `results` VALUES ('42', '3', '12', '8');
INSERT INTO `results` VALUES ('43', '3', '13', '5');
INSERT INTO `results` VALUES ('44', '3', '14', '9');
INSERT INTO `results` VALUES ('45', '3', '15', '1');
INSERT INTO `results` VALUES ('46', '4', '1', '6');
INSERT INTO `results` VALUES ('47', '4', '2', '7');
INSERT INTO `results` VALUES ('48', '4', '3', '1');
INSERT INTO `results` VALUES ('49', '4', '4', '9');
INSERT INTO `results` VALUES ('50', '4', '5', '6');
INSERT INTO `results` VALUES ('51', '4', '6', '9');
INSERT INTO `results` VALUES ('52', '4', '7', '3');
INSERT INTO `results` VALUES ('53', '4', '8', '3');
INSERT INTO `results` VALUES ('54', '4', '9', '5');
INSERT INTO `results` VALUES ('55', '4', '10', '7');
INSERT INTO `results` VALUES ('56', '4', '11', '9');
INSERT INTO `results` VALUES ('57', '4', '12', '7');
INSERT INTO `results` VALUES ('58', '4', '13', '8');
INSERT INTO `results` VALUES ('59', '4', '14', '9');
INSERT INTO `results` VALUES ('60', '4', '15', '4');
INSERT INTO `results` VALUES ('61', '5', '1', '7');
INSERT INTO `results` VALUES ('62', '5', '2', '8');
INSERT INTO `results` VALUES ('63', '5', '3', '8');
INSERT INTO `results` VALUES ('64', '5', '4', '6');
INSERT INTO `results` VALUES ('65', '5', '5', '4');
INSERT INTO `results` VALUES ('66', '5', '6', '3');
INSERT INTO `results` VALUES ('67', '5', '7', '2');
INSERT INTO `results` VALUES ('68', '5', '8', '9');
INSERT INTO `results` VALUES ('69', '5', '9', '3');
INSERT INTO `results` VALUES ('70', '5', '10', '3');
INSERT INTO `results` VALUES ('71', '5', '11', '9');
INSERT INTO `results` VALUES ('72', '5', '12', '7');
INSERT INTO `results` VALUES ('73', '5', '13', '9');
INSERT INTO `results` VALUES ('74', '5', '14', '3');
INSERT INTO `results` VALUES ('75', '5', '15', '8');
INSERT INTO `results` VALUES ('76', '6', '1', '1');
INSERT INTO `results` VALUES ('77', '6', '2', '9');
INSERT INTO `results` VALUES ('78', '6', '3', '7');
INSERT INTO `results` VALUES ('79', '6', '4', '5');
INSERT INTO `results` VALUES ('80', '6', '5', '5');
INSERT INTO `results` VALUES ('81', '6', '6', '8');
INSERT INTO `results` VALUES ('82', '6', '7', '8');
INSERT INTO `results` VALUES ('83', '6', '8', '4');
INSERT INTO `results` VALUES ('84', '6', '9', '8');
INSERT INTO `results` VALUES ('85', '6', '10', '7');
INSERT INTO `results` VALUES ('86', '6', '11', '9');
INSERT INTO `results` VALUES ('87', '6', '12', '9');
INSERT INTO `results` VALUES ('88', '6', '13', '6');
INSERT INTO `results` VALUES ('89', '6', '14', '3');
INSERT INTO `results` VALUES ('90', '6', '15', '7');
INSERT INTO `results` VALUES ('91', '7', '1', '7');
INSERT INTO `results` VALUES ('92', '7', '2', '3');
INSERT INTO `results` VALUES ('93', '7', '3', '5');
INSERT INTO `results` VALUES ('94', '7', '4', '4');
INSERT INTO `results` VALUES ('95', '7', '5', '7');
INSERT INTO `results` VALUES ('96', '7', '6', '4');
INSERT INTO `results` VALUES ('97', '7', '7', '9');
INSERT INTO `results` VALUES ('98', '7', '8', '2');
INSERT INTO `results` VALUES ('99', '7', '9', '2');
INSERT INTO `results` VALUES ('100', '7', '10', '4');
INSERT INTO `results` VALUES ('101', '7', '11', '5');
INSERT INTO `results` VALUES ('102', '7', '12', '1');
INSERT INTO `results` VALUES ('103', '7', '13', '9');
INSERT INTO `results` VALUES ('104', '7', '14', '6');
INSERT INTO `results` VALUES ('105', '7', '15', '2');
INSERT INTO `results` VALUES ('106', '8', '1', '1');
INSERT INTO `results` VALUES ('107', '8', '2', '9');
INSERT INTO `results` VALUES ('108', '8', '3', '4');
INSERT INTO `results` VALUES ('109', '8', '4', '1');
INSERT INTO `results` VALUES ('110', '8', '5', '1');
INSERT INTO `results` VALUES ('111', '8', '6', '2');
INSERT INTO `results` VALUES ('112', '8', '7', '7');
INSERT INTO `results` VALUES ('113', '8', '8', '2');
INSERT INTO `results` VALUES ('114', '8', '9', '7');
INSERT INTO `results` VALUES ('115', '8', '10', '9');
INSERT INTO `results` VALUES ('116', '8', '11', '6');
INSERT INTO `results` VALUES ('117', '8', '12', '3');
INSERT INTO `results` VALUES ('118', '8', '13', '4');
INSERT INTO `results` VALUES ('119', '8', '14', '3');
INSERT INTO `results` VALUES ('120', '8', '15', '9');
INSERT INTO `results` VALUES ('121', '9', '1', '2');
INSERT INTO `results` VALUES ('122', '9', '2', '9');
INSERT INTO `results` VALUES ('123', '9', '3', '1');
INSERT INTO `results` VALUES ('124', '9', '4', '4');
INSERT INTO `results` VALUES ('125', '9', '5', '7');
INSERT INTO `results` VALUES ('126', '9', '6', '7');
INSERT INTO `results` VALUES ('127', '9', '7', '2');
INSERT INTO `results` VALUES ('128', '9', '8', '6');
INSERT INTO `results` VALUES ('129', '9', '9', '6');
INSERT INTO `results` VALUES ('130', '9', '10', '3');
INSERT INTO `results` VALUES ('131', '9', '11', '4');
INSERT INTO `results` VALUES ('132', '9', '12', '2');
INSERT INTO `results` VALUES ('133', '9', '13', '6');
INSERT INTO `results` VALUES ('134', '9', '14', '8');
INSERT INTO `results` VALUES ('135', '9', '15', '2');
INSERT INTO `results` VALUES ('136', '10', '1', '2');
INSERT INTO `results` VALUES ('137', '10', '2', '6');
INSERT INTO `results` VALUES ('138', '10', '3', '6');
INSERT INTO `results` VALUES ('139', '10', '4', '3');
INSERT INTO `results` VALUES ('140', '10', '5', '5');
INSERT INTO `results` VALUES ('141', '10', '6', '6');
INSERT INTO `results` VALUES ('142', '10', '7', '7');
INSERT INTO `results` VALUES ('143', '10', '8', '8');
INSERT INTO `results` VALUES ('144', '10', '9', '9');
INSERT INTO `results` VALUES ('145', '10', '10', '1');
INSERT INTO `results` VALUES ('146', '10', '11', '6');
INSERT INTO `results` VALUES ('147', '10', '12', '7');
INSERT INTO `results` VALUES ('148', '10', '13', '9');
INSERT INTO `results` VALUES ('149', '10', '14', '6');
INSERT INTO `results` VALUES ('150', '10', '15', '2');
-- ----------------------------
-- Table structure for `teams`
-- ----------------------------
DROP TABLE IF EXISTS `teams`;
CREATE TABLE `teams` (
`team_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`team_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of teams
-- ----------------------------
INSERT INTO `teams` VALUES ('1', 'Lumpis');
INSERT INTO `teams` VALUES ('2', 'Luxe');
INSERT INTO `teams` VALUES ('3', 'Zoidinators');
INSERT INTO `teams` VALUES ('4', 'Sloths');
INSERT INTO `teams` VALUES ('5', 'Winnersquad');
|
PHP
|
UTF-8
| 934 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Omnipay\MyPay\Message;
use Omnipay\Common\Message\AbstractResponse;
class RefundResponse extends AbstractResponse
{
/**
* Is the response successful?
*
* @return bool
*/
public function isSuccessful()
{
return $this->getCode() === 'B200';
}
/**
* Response Message.
*
* @return null|string A response message from the payment gateway
*/
public function getMessage()
{
return $this->data['msg'];
}
/**
* Response code.
*
* @return null|string A response code from the payment gateway
*/
public function getCode()
{
return $this->data['code'];
}
/**
* Gateway Reference.
*
* @return null|string A reference provided by the gateway to represent this transaction
*/
public function getTransactionReference()
{
return $this->data['uid'];
}
}
|
Markdown
|
UTF-8
| 830 | 2.875 | 3 |
[] |
no_license
|
# Reflection by Add Your Name Here
## Using a fenced code block, please display the output from running your program
Please add the requested fenced code block.
## What was your strategy for computing the complement of a DNA string? How did you test it?
Please provide a response to this question.
## How did your program use `java.util.Random` to manipulate the DNA strings?
Please provide a response to this question.
## What was the greatest technical challenge that you faced and how did you overcome it?
Please provide a response to this question.
## After completing this assignment, what is a task that you want to practice more? Why?
Please provide a response to this question.
## After completing this assignment, what is one experience for which you are grateful?
Please provide a response to this question.
|
C#
|
UTF-8
| 952 | 2.578125 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameController : MonoBehaviour
{
[SerializeField]
private List<GameObject> upgradeList;
public DropTable DropTable { get; private set; }
private void Start()
{
DropTable = new DropTable();
DropTable.lootList = new List<LootDrop>
{
new LootDrop(upgradeList[0], 4), //shield
new LootDrop(upgradeList[1], 3), //weapon
new LootDrop(upgradeList[2], 2), //laser
};
}
public GameObject DropItem()
{
int randomNumber = Random.Range(0, 101);
//Debug.Log(randomNumber);
int weightSum = 0;
foreach(LootDrop item in DropTable.lootList)
{
weightSum += item.Weight;
if(randomNumber < weightSum)
{
return item.Drop;
}
}
return null;
}
}
|
Python
|
UTF-8
| 5,704 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
import networkx as nx
import re
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
#get edgelist
f = open('cmap_edgelist.txt')
text_edge = f.readlines()
#get vertexids
f = open('cmap_vertexids.txt')
text_node = f.readlines()
dict_node = {}
#define directional graph
G=nx.DiGraph()
#get all nodes
for line in text_node:
line = re.split(r',', line)
nodeID = line[0]
G.add_node(nodeID)
identifier = re.split(r'\n',line[1])[0]
dict_node[identifier] = nodeID
G.number_of_nodes()
lst_graph = []
for line in text_edge:
line = re.split(r'\t+', line)
first = line[0]
second = re.split(r'\n',line[1])[0]
lst_graph.append([first,second])
# adding edges to graph
G.add_edges_from(lst_graph)
n_edges = G.number_of_edges()
print "Number of edges in graph:"
print n_edges
#a= nx.adjacency_matrix(G)
#print(a.todense())
#creating numpy matrix from graph
n = nx.to_numpy_matrix(G)
#(n.transpose() == n).all()
#no. of self loops
n_selfLoops = sum(np.diagonal(n))
print "Number of self loops in graph:"
print n_selfLoops
print "self loops in graph:"
print G.selfloop_edges()
#G.selfloop_edges()
#no.of dangling nodes
n_dangling = 0
for nodeID in G.nodes():
#print nodeID
if G.out_degree(nodeID) == 0 and G.in_degree(nodeID) == 0:
n_dangling += 1
print "Number of Dangling nodes in graph: "
print n_dangling
# concepts not linked to any other concepts
lst_colSum = np.sum(n, axis = 0)
lst_colSum = np.array(lst_colSum).tolist()
len(lst_colSum)
lst_colSum.count(0)
lst_rowSum = np.sum(n, axis = 1)
lst_rowSum = np.array(lst_rowSum).tolist()
lst_rowSum.count(0)
# Read concept dataframe
concept_mapDF = pd.read_csv(open('/Users/ajitbarik/Ilimi/github/Learning-Platform-Analytics/platform-scripts/object2Vec/content2vec/conceptDF.csv','rU'),
sep ='\t', index_col=0, encoding='utf-8', engine='c')
concept_mapDF.is_copy = False
# no of concepts
n_concepts = concept_mapDF.shape
n_concepts = n_concepts[0]
print "Number of Concepts: %d " % n_concepts
# to check if num is NaN
def isNaN(num):
return num != num
import unicodedata
#temp = unicodedata.normalize('NFKD', temp).encode('ascii','ignore')
def checkMisConcept(x):
if isNaN(x):
return 0
x = x.encode('utf-8')
#x = unicodedata.normalize('NFKD', x).encode('ascii','ignore')
if re.search('misconcept', x, re.IGNORECASE):
return 1
else:
return 0
concept_mapDF['Misconception'] = concept_mapDF['tags'].apply(lambda x: checkMisConcept(x))
# no of misconceptions
n_misconceptions = concept_mapDF['Misconception'].sum()
print "Number of Misconception: %d " % n_misconceptions
lst_misconception = []
#concepts identifier which are misconception
for i in range(len(concept_mapDF['Misconception'])):
if concept_mapDF['Misconception'][i] == 1:
lst_misconception.append(concept_mapDF['identifier'][i])
concept_mapDF.head()
concept_mapDF['DescLen'] = concept_mapDF['description'].map(lambda x: 0 if isNaN(x) else len(x.encode('utf-8')))
# no. of concepts without description
n_conceptsWDesc = 0
for i in range(len(concept_mapDF['DescLen'])):
if concept_mapDF.DescLen[i] == 0:
n_conceptsWDesc += 1
print "Number of concepts without description: %d " % n_conceptsWDesc
# adding desc (whether desciption exist or not)
concept_mapDF['desc'] = concept_mapDF['DescLen'].map(lambda x: x if x == 0 else 1)
print concept_mapDF.head()
# # adding in-degree and out-degree column
# concept_mapDF['in_degree'] = 0
# concept_mapDF['out_degree'] = 0
# concept_mapDF['dangling'] = 0
# concept_mapDF['MisConceptDangling'] = 0
# for i in range(len(concept_mapDF['desc'])):
# identifier = concept_mapDF['identifier'][i]
# if dict_node.has_key(identifier):
# nodeID = dict_node[identifier]
# #print identifier
# in_degree = G.in_degree(nodeID)
# out_degree = G.out_degree(nodeID)
# concept_mapDF['in_degree'][i] = in_degree
# concept_mapDF['out_degree'][i] = out_degree
# if in_degree == 0 and out_degree == 0:
# concept_mapDF['dangling'][i] = 1
# # else:
# # concept_mapDF['in_degree'][i] = 'NA'
# # concept_mapDF['out_degree'][i] = 'NA'
# for i in range(len(concept_mapDF['MisConceptDangling'])):
# if concept_mapDF['Misconception'][i] == 1 and concept_mapDF['dangling'][i] == 1:
# concept_mapDF['MisConceptDangling'][i] = 1
# # no of dangling misconception
# sum(concept_mapDF['MisConceptDangling'])
# concept_mapDF.head()
# pd.crosstab(concept_mapDF.Misconception, concept_mapDF.subject)
# pd.crosstab(concept_mapDF.Misconception, concept_mapDF.desc)
# pd.crosstab(concept_mapDF.Misconception, concept_mapDF.in_degree)
# pd.crosstab(concept_mapDF.Misconception, concept_mapDF.out_degree)
# # Misconceptions having child (out degree > 0)
# lst_index = []
# for i in range(len(concept_mapDF['out_degree'])):
# if concept_mapDF['out_degree'][i] > 0 and concept_mapDF['Misconception'][i] == 1:
# identifier = concept_mapDF['identifier'][i]
# lst_index.append(i)
# #print identifier
# if dict_node.has_key(identifier):
# nodeID = dict_node[identifier]
# #print nodeID
# concept_mapDF.iloc[lst_index,]
# concept_mapDF['desc'][lst_index]
# import seaborn as sns
# sns.set(style="darkgrid")
# sns.boxplot(x="subject", y="DescLen", hue="Misconception", data=concept_mapDF, palette="Set1")
# #plt.ylim(0, 400)
# sns.despine(offset=10, trim=True)
# sns.boxplot(x= 'subject', y="DescLen", hue="dangling", data=concept_mapDF, palette="Set2")
# #plt.ylim(0, 300)
# sns.despine(offset=10, trim=True)
|
PHP
|
UTF-8
| 228 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace DevGroup\Multilingual\interfaces;
interface ContentTabHandlerInterface
{
/**
* @param int $contextId
*
* @return array [$key => $data]
*/
public function contextData($contextId);
}
|
Python
|
UTF-8
| 554 | 4.625 | 5 |
[] |
no_license
|
print('Crie um programa que leia o nome completo de uma pessoa e mostre:'
'\n 1- O nome com todas as letras maiúsculas. '
'\n 2- O nome com todas minúsculas.'
'\n 3- Quantas letras ao todo(sem os espaços)'
'\n 4- Quantas letras tem o primeiro nome.')
nome = str(input('Digite seu nome completo: ')).strip()
print('1- {}' .format(nome.upper()))
print('2- {}' .format(nome.lower()))
nomediv = nome.split()
print('3- {}' .format(len(nome) - nome.count(' ')))
print('4- O seu primeiro nome tem {} letras' .format(len(nomediv[0])))
|
Java
|
UTF-8
| 24,917 | 3.234375 | 3 |
[] |
no_license
|
package edu.ucalgary.ensf409;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
/**
* <h1>Program</h1>
* This program implements an application that
* is used to determine the cheapest combination of
* inventory items that can be used to fulfill an order that
* is specified. The application calculates the most cost effective
* way of assembling a certain item using components from other items.
*
* @author Beau McCartney, Apostolos Scondrianis, Quentin Jennings, Jacob Lansang
* @version 2.4
*/
/**
* Class for main, handles input and output using a Graphic User Interface
*/
public class Program {
private static GUIAccessSQL sqlFrame;
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void main(String[] args) {
sqlFrame = new GUIAccessSQL();
EventQueue.invokeLater(() -> {
sqlFrame.setVisible(true);
});
}
}
/**
* GUIAccessSQL is used to create a Graphic User Interface that requests from the
* user their database ID, database Password, and the URL to the database.
*/
class GUIAccessSQL extends JFrame implements ActionListener, MouseListener {
private DatabaseAccess database;
private String username;
private String password;
private String url;
private JLabel generalMessage1;
private JLabel generalMessage2;
private JLabel usernameLabel;
private JLabel passwordLabel;
private JLabel urlLabel;
private JTextField usernameTextField;
private JTextField passwordTextField;
private JTextField urlTextField;
private JButton connectButton;
/**
* Instantiates a new Gui access sql.
*/
public GUIAccessSQL() {
super("Connect to Database.");
setupGUI();
setSize(600,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* Sets gui.
*/
public void setupGUI() {
//Let's set up the JLabels and the JTextFields and the JButton for our GUI.
generalMessage1 = new JLabel("Welcome to the University of Calgary");
generalMessage2 = new JLabel("Supply Chain Management Software v2.4.");
usernameLabel = new JLabel("Username :");
passwordLabel = new JLabel("Password :");
urlLabel = new JLabel("URL :");
usernameTextField = new JTextField("ensf409", 18);
passwordTextField = new JTextField("ensf409", 18);
urlTextField = new JTextField("jdbc:mysql://localhost:3306/inventory", 30);
connectButton = new JButton("Connect");
//add Mouse Listeners to the JTextFields and ActionListener to the JButton
usernameTextField.addMouseListener(this);
passwordTextField.addMouseListener(this);
urlTextField.addMouseListener(this);
connectButton.addActionListener(this);
//Create the JPanels.
JPanel mainContainer = new JPanel();
JPanel headerPanel = new JPanel();
JPanel usernamePanel = new JPanel();
JPanel passwordPanel = new JPanel();
JPanel urlPanel = new JPanel();
JPanel connectPanel = new JPanel();
//Set the Layouts for the JPanels
mainContainer.setLayout(new BoxLayout(mainContainer, BoxLayout.PAGE_AXIS));
headerPanel.setLayout(new FlowLayout());
usernamePanel.setLayout(new FlowLayout());
passwordPanel.setLayout(new FlowLayout());
urlPanel.setLayout(new FlowLayout());
connectPanel.setLayout(new FlowLayout());
//Add Components to the JPanels.
headerPanel.add(generalMessage1);
headerPanel.add(generalMessage2);
usernamePanel.add(usernameLabel);
usernamePanel.add(usernameTextField);
passwordPanel.add(passwordLabel);
passwordPanel.add(passwordTextField);
urlPanel.add(urlLabel);
urlPanel.add(urlTextField);
connectPanel.add(connectButton);
//Add the JPanels to the main JPanel
mainContainer.add(headerPanel);
mainContainer.add(usernamePanel);
mainContainer.add(passwordPanel);
mainContainer.add(urlPanel);
mainContainer.add(connectPanel);
//Add the main panel to the JFrame.
this.add(mainContainer);
}
/**
* actionPerformed function used to handle an action performed on the
* Connect Button.
* @param e ActionEvent passed on the function actionPerformed
*/
public void actionPerformed(ActionEvent e) {
//Pull the data from the JTextFields username, password and url
username = usernameTextField.getText();
password = passwordTextField.getText();
url = urlTextField.getText();
//Attempt to create a databaseAccess object called database using the inputs provided by the user.
if(validAccess(username, password, url)) {
//We had a successfully created a DatabaseAccess object and connected successfully to the database. Let's
//handle business.
//JOptionPane dialog which notifies the user that they successfully connected.
JOptionPane.showMessageDialog(null, "You successfully connected to the database with username : "
+ username + " and password : "+ password+"and url : " + url);
database.retrieveAll();
/*WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);*/
//Create a GUIUserInput frame and let us use EventQueue to "invokeLater" that Frame.
GUIUserInput userInputFrame = new GUIUserInput(database);
//close the currentFrame.
this.setVisible(false);
EventQueue.invokeLater(() -> {
userInputFrame.setVisible(true);
});
//this.dispose();
}
else {
//Unsuccessful connection to the database. Show a dialog to the user to notify them.
JOptionPane.showMessageDialog(null, "There was an error connecting to the database with username : "
+ username + " and password : "+ password+"and url : " + url);
}
}
/**
* Attempts to create a databaseAccess object through info gained from the GUIAccessSQL object
*
* @param username Database username
* @param password Database password
* @param url URL for the database inventory.
* @return boolean Returns the status of the attempted connection
*/
public boolean validAccess(String username, String password, String url) {
database = new DatabaseAccess(username, password, url);
return database.getIsSuccessful();
}
public void mouseEntered(MouseEvent event) {
}
public void mouseClicked(MouseEvent event) {
if(event.getSource().equals(usernameTextField)) {
usernameTextField.setText("");
}
if(event.getSource().equals(passwordTextField)) {
passwordTextField.setText("");
}
if(event.getSource().equals(urlTextField)) {
urlTextField.setText("");
}
}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent e) {
}
}
/**
* Class used to create a JFrame that handles asks the user to input information
* needed to start the process for finding the cheaper combinations of used
* furniture to create another piece of furniture.
*/
class GUIUserInput extends JFrame implements ActionListener {
DatabaseAccess database;
String category;
String type;
int numOfItems;
JLabel gMessage1;
JLabel gMessage2;
JLabel iLabel;
JLabel noiLabel;
JLabel typeLabel;
JTextField typeTextField;
JTextField noiTextField;
final String[] choices = new String[] {"Chair", "Desk", "Lamp", "Filing"};
final JComboBox<String> selectionDropdown = new JComboBox<String>(choices);
/**
* Instantiates a new GUI for user input.
*
* @param database the database
*/
public GUIUserInput(DatabaseAccess database) {
super("Select Category Form.");
this.database = database;
setupGUI();
setSize(600,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* Function used to Setup the Graphic User Interface
*/
public void setupGUI() {
//Instantiate the JLabels
gMessage1 = new JLabel("Welcome to the University of Calgary");
gMessage2 = new JLabel("Supply Chain Management Software v2.5.");
iLabel = new JLabel("Select the furniture category: ");
noiLabel = new JLabel("Number of Items :");
typeLabel = new JLabel("Type of furniture :");
//Instantiate the JTextFields.
noiTextField = new JTextField(18);
typeTextField = new JTextField(18);
//create the Select button and add an action Listener object to it.
JButton selectCategoryButton = new JButton("Select");
selectCategoryButton.addActionListener(this);
//create Panels
JPanel wrapContainer = new JPanel();
JPanel headerPanel = new JPanel();
JPanel selectorPanel = new JPanel();
JPanel typePanel = new JPanel();
JPanel noiPanel = new JPanel();
JPanel buttonPanel = new JPanel();
//Set the Panel Layouts
wrapContainer.setLayout(new BoxLayout(wrapContainer, BoxLayout.PAGE_AXIS));
headerPanel.setLayout(new FlowLayout());
selectorPanel.setLayout(new FlowLayout());
typePanel.setLayout(new FlowLayout());
noiPanel.setLayout(new FlowLayout());
buttonPanel.setLayout(new FlowLayout());
//Add JLabels, JTextFields and JButton to appropriate panels.
headerPanel.add(gMessage1);
headerPanel.add(gMessage2);
selectorPanel.add(iLabel);
selectorPanel.add(selectionDropdown);
typePanel.add(typeLabel);
typePanel.add(typeTextField);
noiPanel.add(noiLabel);
noiPanel.add(noiTextField);
buttonPanel.add(selectCategoryButton);
//Add all the JPanels to the wrapper Panel.
wrapContainer.add(headerPanel);
wrapContainer.add(selectorPanel);
wrapContainer.add(typePanel);
wrapContainer.add(noiPanel);
wrapContainer.add(buttonPanel);
//Add the wrapper JPanel to the JFrame itself.
this.add(wrapContainer);
}
/**
* actionPerformed function used to handle interaction with the User Input GUI.
* @param e Event handler in the case the button is interacted with.
*/
public void actionPerformed(ActionEvent e) {
String noiString;
String[] furnitureTypeArray;
//Get the data provided from the Graphic User Intefrace.
category = selectionDropdown.getSelectedItem().toString();
type = typeTextField.getText();
noiString = noiTextField.getText();
//Let's attempt to parse the number of Items we would like to create.
try {
numOfItems = Integer.parseInt(noiString);
if(numOfItems <= 0) {
//Illegal argument. The number of Items must be positive
JOptionPane.showMessageDialog(null, "You have inserted non-positive Integer for number of items.");
} else {
//check if the words of type are properly capitalized.
furnitureTypeArray = type.split(" ");
boolean capitalizationFlag = false;
for(int i = 0; i < furnitureTypeArray.length; i++) {
if(furnitureTypeArray[i].charAt(0) <= 'Z' && furnitureTypeArray[i].charAt(0) >= 'A') {
capitalizationFlag = true;
} else {
capitalizationFlag = false;
break;
}
}
if(capitalizationFlag == false) {
JOptionPane.showMessageDialog(null, "Your type is in the wrong form, each"+
"word separated by a space must start with a capital letter.");
} else {
//Let us check if the Type of furniture exists in our ArrayLists
boolean typeFound = false;
switch(category) {
case "Chair":
for(int i =0; i < database.getChairList().size(); i++) {
if(database.getChairList().get(i).getType().equals(type)) {
typeFound = true;
break;
}
}
break;
case "Desk":
for(int i =0; i < database.getDeskList().size(); i++) {
if(database.getDeskList().get(i).getType().equals(type)) {
typeFound = true;
break;
}
}
break;
case "Lamp":
for(int i =0; i < database.getLampList().size(); i++) {
if(database.getLampList().get(i).getType().equals(type)) {
typeFound = true;
break;
}
}
break;
case "Filing":
for(int i =0; i < database.getFilingList().size(); i++) {
if(database.getFilingList().get(i).getType().equals(type)) {
typeFound = true;
break;
}
}
break;
}
if(typeFound == true) {
//Show to the user what they have inputted, and prompt them with the result of their selection.
JOptionPane.showMessageDialog(null, "You have selected the following category: " + category +
", type: " + type + ", number of items: " + numOfItems);
//Create a new GUIOrderForm object and then let's attempt to show on the screen the results of the
//user request.
GUIOrderForm processForm = new GUIOrderForm(category, type, numOfItems, database);
//hide the current frame.
this.setVisible(false);
EventQueue.invokeLater(() -> {
processForm.setVisible(true);
});
} else {
JOptionPane.showMessageDialog(null, "You have entered a type for the category : "
+category+" of items that doesn't exist.");
}
}
}
}
catch(Exception ex) {
//We caught an exception when attemption to convert to integer. User has given an invalid input.
JOptionPane.showMessageDialog(null, "You have inserted an invalid input for number of items.");
ex.printStackTrace();
}
}
}
/**
* This class is used to process the user input provided in GUIUserInput
*/
class GUIOrderForm extends JFrame {
private DatabaseAccess database;
private String category;
private OptionCalculation orderCalc;
private JLabel generalMessage1;
private JLabel generalMessage2;
/**
* Instantiates a new Gui order form.
*
* @param category the category
* @param type the type
* @param numberOfItems the number of items
* @param database the database
*/
public GUIOrderForm(String category, String type, int numberOfItems, DatabaseAccess database) {
super("Order Form Process.");
this.database = database;
this.category = category;
//create an OptionCalculation Object used to process the user Order.
orderCalc = new OptionCalculation(type, numberOfItems);
setupGUI();
setSize(600,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* setupGUI function sets up the Graphic User Interface for the OrderForm process.
*/
public void setupGUI() {
boolean calcSuccess = false;
//Setup the top part of the Graphic Interface and the wrapper JPanel
JPanel wrapContainer = new JPanel();
JPanel headerPanel = new JPanel();
//Setup the Layouts for the wrapper JPanel and the header JPanel
wrapContainer.setLayout(new BoxLayout(wrapContainer, BoxLayout.PAGE_AXIS));
headerPanel.setLayout(new FlowLayout());
//instantiate the header JLabels
generalMessage1 = new JLabel("Welcome to the University of Calgary");
generalMessage2 = new JLabel("Supply Chain Management Software v2.5.");
//add the JLabels to the headerPanel
headerPanel.add(generalMessage1);
headerPanel.add(generalMessage2);
//add the header JPanel to the wrapper JPanel
wrapContainer.add(headerPanel);
//Let's attempt to calculate the cheapest price for the creation of the object.
//Assign the status of the calculation to the variable calcSuccess
switch(category){
case "Chair":
calcSuccess = orderCalc.calculateCheapestPrice(database.getChairList());
break;
case "Desk":
calcSuccess = orderCalc.calculateCheapestPrice(database.getDeskList());
break;
case "Lamp":
calcSuccess = orderCalc.calculateCheapestPrice(database.getLampList());
break;
case "Filing":
calcSuccess = orderCalc.calculateCheapestPrice(database.getFilingList());
break;
}
if(calcSuccess) {
//Let's first delete all items on the list.
for(Object id : orderCalc.getLowestPriceIDs()){
database.deleteItem(category, (String)id); //what the fuck java
}
//Create the Order Form in the text file.
generateOrderForm(orderCalc.getLowestPriceIDs(), orderCalc.getTotalLowestPrice(), category,
orderCalc.getType(), orderCalc.getNumOfItems());
//Create the JPanels needed and their layouts
JPanel orderFormPanel = new JPanel();
orderFormPanel.setLayout(new FlowLayout());
//create a Label that shows what is the cheapest option.
JLabel messageLabel = new JLabel(successfulOrderString(orderCalc.getLowestPriceIDs(), orderCalc.getTotalLowestPrice()));
orderFormPanel.add(messageLabel);
wrapContainer.add(orderFormPanel);
} else {
//recommends manufacturers based on the list of producers of the category
String manufacturers;
switch (category) {
case "Chair":
manufacturers = new String("Office Furnishings, Chairs R Us, Furniture Goods," +
" and Fine Office Supplies");
break;
case "Desk":
manufacturers = new String("Academic Desks, Office Furnishings, Furniture Goods," +
" and Fine Office Supplies");
break;
case "Lamp":
case "Filing":
manufacturers = new String("Office Furnishings, Furniture Goods," +
" and Fine Office Supplies");
break;
default:
manufacturers = new String("ERROR");
}
//Create a JPanel to hold the Manufacturer Recommendation information
JPanel manufacturerPanel = new JPanel();
manufacturerPanel.setLayout(new FlowLayout());
//Create the messages for the user.
JLabel manuMessage1 = new JLabel("Your order can't be fulfilled with the current inventory.");
JLabel manuMessage2 = new JLabel("Recommended Manufacturers :");
//Add JLabels to the Panel
manufacturerPanel.add(manuMessage1);
manufacturerPanel.add(manuMessage2);
//Depending on how many manufacturers are to be recommended create the appropriate JLabels
//with their info.
manufacturerPanel.add(new JLabel(manufacturers));
wrapContainer.add(manufacturerPanel);
}
database.closeConnection();
this.add(wrapContainer);
}
/**
* Makes a String that shows the itemIDs of the items that need to be purchased
* and the total price of the items purchased in case of a successful order.
*
* @param itemIDs The IDs of the items that need to be purchased.
* @param price The total price of the items purchased.
* @return A formatted String that consists of the itemIDs of the purchased items and the total price of the purchased items.
*/
public String successfulOrderString(ArrayList<String> itemIDs, int price) {
StringBuilder itemList = new StringBuilder();
itemList.append("Purchase ");
for(int i = 0; i < orderCalc.getLowestPriceIDs().size(); i++) {
if(i == orderCalc.getLowestPriceIDs().size()-1) {
itemList.append((String)orderCalc.getLowestPriceIDs().get(i)+" ");
} else {
itemList.append((String)orderCalc.getLowestPriceIDs().get(i)+", ");
}
}
itemList.append(" for "+ "$"+price+".");
return new String(itemList);
}
/**
* Returns an array List of recommended manufacturers in the case we can't fulfill an order
*
* @param objectList list of manufacturers that sell components of the item that was ordered
* @return the array list
*/
public ArrayList<String> recommendManufacturers(ArrayList<? extends Furniture> objectList) { // method if order CANNOT be fulfilled
ArrayList<String> recommendedManus = new ArrayList<>();
for (int i = 0; i < objectList.size(); i++) {
for (Manufacturer manu : database.getManuList()) {
//if the object's manufacturer ID
if (objectList.get(i).getManuID().equals(manu.getManuID()) && !recommendedManus.contains(manu.getManuID())) {
recommendedManus.add(manu.getName());
break;
}
}
}
//this should get you a list of manufacturer names. now you just need to output it. ^^
return recommendedManus;
}
/**
* Generates an order form in a text file.
*
* @param itemIDs the item IDs
* @param price the price
* @param category the category
* @param type the type
* @param numOfItems the number of items
*/
public void generateOrderForm(ArrayList<String> itemIDs, int price, String category, String type, int numOfItems) { // output if order can be fulfilled
try {
// System.out.println("Purchase " + id + "and " + manuID + "for " + price + "."); // placeholder as need added price of each item.
BufferedWriter orderFormWriter = new BufferedWriter(new FileWriter("orderform.txt"));
StringBuilder orderForm = new StringBuilder();
orderForm.append("Furniture Order Form\n");
orderForm.append("\n");
orderForm.append("Faculty Name: \n");
orderForm.append("Contact: \n");
orderForm.append("Date: \n");
orderForm.append("\n");
orderForm.append("Original Request: " + type + " " + category + ", " + numOfItems + "\n");
orderForm.append("\n");
orderForm.append("Items Ordered\n");
for (int i = 0; i < itemIDs.size(); i++) { // prints out the IDs of the items ordered
orderForm.append("ID: " + itemIDs.get(i) + "\n");
}
//iterate this please
orderForm.append("\n");
orderForm.append("Total Price: $" + price);
String form = orderForm.toString();
orderFormWriter.write(form);
orderFormWriter.close();
} catch (IOException e) {
System.err.println("IO Error when generating order form file.");
e.printStackTrace();
System.exit(1);
}
}
}
|
Java
|
UTF-8
| 339 | 1.96875 | 2 |
[] |
no_license
|
package de.rooftop.radio.band;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BandRepository extends CrudRepository<Band, Long>{
List<Band> findAll(Sort sort);
}
|
Shell
|
UTF-8
| 278 | 3.203125 | 3 |
[] |
no_license
|
port=5000
if [ "$1" != "" ]; then
echo "Positional parameter 1 contains something"
else
echo "Positional parameter 1 is empty"
fi
mkdir -p logs/"$d/latency"
mkdir -p logs/"$d/bandwidth"
for i in {0..10}
do
newport=`expr $port + $i`
./main node $newport "$1" &
done
|
Swift
|
UTF-8
| 3,907 | 2.8125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
//
// HashingManager.swift
// DropBit
//
// Created by Mitchell on 5/31/18.
// Copyright © 2018 Coin Ninja, LLC. All rights reserved.
//
import Foundation
import CommonCrypto
import PhoneNumberKit
struct HashingManager {
func salt() throws -> Data {
guard keyDerivation.salt.isNotEmpty,
let salt = keyDerivation.salt.data(using: .utf8) else {
throw DBTError.Persistence.missingValue(key: "salt as Data")
}
return salt
}
/// This function always requires a GlobalPhoneNumber for hashing. If a parsedNumber is already available, providing
/// it will skip the step of parsing the global number in this function, increasing efficiency. Passing nil for the parsedNumber
/// and relying on parsing inside this function is acceptable and the more common scenario.
func hash(phoneNumber number: GlobalPhoneNumber, salt: Data, parsedNumber: PhoneNumber?) -> String {
let normalizedNumber = normalizeNumber(number, parsedNumber: parsedNumber)
return pbkdf2SHA256(password: normalizedNumber,
salt: salt,
keyByteCount: 32,
rounds: keyDerivation.iterations)
}
private func normalizeNumber(_ number: GlobalPhoneNumber, parsedNumber: PhoneNumber?) -> String {
let transformablePhoneNumber: PhoneNumber? = parsedNumber ?? (try? phoneNumberKit.parse(number.asE164()))
let originalNationalNumber = number.sanitizedNationalNumber()
let trimmedNationalNumber = originalNationalNumber.dropFirstCharacter(ifEquals: "0")
var normalizedNationalNumber = trimmedNationalNumber
// Similar to Signal, we ignore the national prefix for Brazil whose token is "$2", prefix "0"
let token = "$1"
if let number = transformablePhoneNumber,
let regionCode = phoneNumberKit.getRegionCode(of: number),
let transformRule = phoneNumberKit.nationalPrefixTransformRule(forCountry: regionCode),
transformRule.contains(token) {
// The prefix precedes the token in the transform rule
let prefix = transformRule.replacingOccurrences(of: token, with: "")
// Trim leading 0 from transform rule to match Android
let trimmedTransformRule = transformRule.dropFirstCharacter(ifEquals: "0")
if originalNationalNumber.starts(with: prefix) == false {
normalizedNationalNumber = trimmedTransformRule.replacingOccurrences(of: token, with: trimmedNationalNumber)
}
}
let normalizedGlobalNumber = GlobalPhoneNumber(countryCode: number.countryCode, nationalNumber: normalizedNationalNumber)
return normalizedGlobalNumber.sanitizedGlobalNumber()
}
func pbkdf2SHA256(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> String {
if let data = pbkdf2(hash: CCPBKDFAlgorithm(kCCPRFHmacAlgSHA256), password: password, salt: salt, keyByteCount: keyByteCount, rounds: rounds) {
return data.hexString
}
return ""
}
private func pbkdf2(hash: CCPBKDFAlgorithm, password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
guard let passwordData = password.data(using: String.Encoding.utf8) else {
return nil
}
var derivedKeyData = Data(repeating: 0, count: keyByteCount)
var localDerivedKeyData = Data(repeating: 0, count: keyByteCount)
let derivationStatus = localDerivedKeyData.withUnsafeMutableBytes { (outputBytes: UnsafeMutableRawBufferPointer) -> Int32 in
let status = CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
password,
passwordData.count,
String(data: salt, encoding: .utf8),
salt.count,
hash,
UInt32(rounds),
outputBytes.baseAddress?.assumingMemoryBound(to: UInt8.self),
derivedKeyData.count
)
return status
}
if derivationStatus != 0 {
return nil
}
derivedKeyData = localDerivedKeyData
return derivedKeyData
}
}
|
Markdown
|
UTF-8
| 2,016 | 3.078125 | 3 |
[] |
no_license
|
---
title: 事务的四种隔离级别
tags:
- 数据库
- 事务
---
# 事务的四种隔离级别
## 数据库事务的隔离级别有4种
* 由低到高分别为Read uncommitted 、Read committed 、Repeatable read 、Serializable
* 在事务的并发操作中可能会出现脏读,不可重复读,幻读
## Read uncommitted
* 读未提交,顾名思义,就是一个事务可以读取另一个未提交事务的数据
* 事务回滚会导致脏读
## Read committed
* 读提交,顾名思义,就是一个事务要等另一个事务提交后才能读取数据
* 一个事务范围内两个相同的查询却返回了不同数据会导致不可重复读
* 解决脏读问题
## Repeatable read
* 重复读,就是在开始读取数据(事务开启)时,不再允许修改操作
* 幻读问题对应的是插入INSERT操作,而不是UPDATE操作
## Serializable
* 序列化,事务串行化顺序执行
* 避免脏读、不可重复读与幻读
* 效率低下,比较耗数据库性能
# 数据库事务配置
* 大多数数据库默认的事务隔离级别是Read committed
* Mysql的默认隔离级别是Repeatable read
* select语句会自动获取共享锁
* update/insert/delete会自动获取排它锁
* 一个事务中的一行记录的共享锁被拿走,其他事务只能获取该行的共享锁,不能获取排它锁
* 一个事务中的一行记录的排它锁被拿走,其他事务不能获取该行的共享锁和排它锁
# 第一类更新
* 待补充
# 第二类更新
* 待补充
# 最佳实践
* 通常,对于绝大多数的应用程序来说,可以优先考虑将数据库系统的隔离级别设置为读已提交(Read Committed)
* 这能够在避免脏读的同时保证较好的并发性能。尽管这种事务隔离级别会导致不可重复读、幻读和第二类丢失更新等并发问题
* 但较为科学的做法是在可能出现这类问题的个别场合中,由应用程序主动采用悲观锁或乐观锁来进行事务控制
|
Java
|
UTF-8
| 617 | 1.921875 | 2 |
[] |
no_license
|
package com.thomsonreuters.testproject.client;
import java.util.List;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
* The async counterpart of <code>GreetingService</code>.
*/
public interface GreetingServiceAsync {
void greetServer(String[] input, AsyncCallback<String> callback) throws IllegalArgumentException;
void getUser(AsyncCallback<String> callback) throws IllegalArgumentException;
void queryDataByUser(String user, AsyncCallback<List<String[]>> callback) throws IllegalArgumentException;
void getDates(AsyncCallback<String[]> callback) throws IllegalArgumentException;
}
|
C++
|
UTF-8
| 5,417 | 2.765625 | 3 |
[] |
no_license
|
// $Id: file_sys.cpp,v 1.5 2016-01-14 16:16:52-08 - - $
#include <iostream>
#include <stdexcept>
#include <unordered_map>
using namespace std;
#include "debug.h"
#include "file_sys.h"
int inode::next_inode_nr {1};
struct file_type_hash {
size_t operator() (file_type type) const {
return static_cast<size_t> (type);
}
};
ostream& operator<< (ostream& out, file_type type) {
static unordered_map<file_type,string,file_type_hash> hash {
{file_type::PLAIN_TYPE, "PLAIN_TYPE"},
{file_type::DIRECTORY_TYPE, "DIRECTORY_TYPE"},
};
return out << hash[type];
}
inode_state::inode_state() {
DEBUGF ('i', "root = " << root << ", cwd = " << cwd
<< ", prompt = \"" << prompt() << "\"");
root = make_shared<inode>(file_type::DIRECTORY_TYPE);
// inode_ptr root = rootdirect;
cwd = root;
root->getContents()->insertInMap(".", root);
root->getContents()->insertInMap("..", root);
path.push_back("/");
}
const string& inode_state::prompt() { return prompt_; }
void inode_state::setPrompt(const string& newPrompt) {
prompt_ = newPrompt+" ";
}
inode_ptr inode_state::getRoot(){
return root;
}
inode_ptr inode_state::getCwd(){
return cwd;
}
void inode_state::setCwd(inode_ptr newCwd){
cwd = newCwd;
}
inode_ptr inode_state::getPrevCwd(){
return prevCwd;
}
void inode_state::setPrevCwd (inode_ptr newPrevCwd){
prevCwd = newPrevCwd;
}
wordvec inode_state::getPath (){
return path;
}
void inode_state::append (const string& val){
path.push_back(val);
}
void inode_state::pop () {
path.pop_back();
}
ostream& operator<< (ostream& out, const inode_state& state) {
out << "inode_state: root = " << state.root
<< ", cwd = " << state.cwd;
return out;
}
inode::inode(file_type type): inode_nr (next_inode_nr++) {
switch (type) {
case file_type::PLAIN_TYPE:
contents = make_shared<plain_file>();
break;
case file_type::DIRECTORY_TYPE:
contents = make_shared<directory>();
break;
}
DEBUGF ('i', "inode " << inode_nr << ", type = " << type);
}
int inode::get_inode_nr() const {
DEBUGF ('i', "inode = " << inode_nr);
return inode_nr;
}
int inode::size() const {
DEBUGF ('i', "inode = " << inode_nr);
return contents->size();
}
inode_ptr inode::getNodePtr() const {
return node_ptr;
}
base_file_ptr inode::getContents() const {
return contents;
}
file_error::file_error (const string& what):
runtime_error (what) {
}
size_t plain_file::size() const {
/*size_t size = 0;
for (unsigned int i = 2; i != data.size(); ++i){
size += data[i].length();
}*/
size_t size = data.size();
DEBUGF ('i', "size = " << size);
return size;
}
const wordvec& plain_file::readfile() const {
DEBUGF ('i', data);
return data;
}
void plain_file::writefile (const wordvec& words) {
data = words;
DEBUGF ('i', words);
}
void plain_file::remove (const string&) {
throw file_error ("is a plain file");
}
inode_ptr plain_file::mkdir (const string&, const inode_ptr) {
throw file_error ("is a plain file");
}
inode_ptr plain_file::mkfile (const string&, const wordvec&) {
throw file_error ("is a plain file");
}
void plain_file::insertInMap (const string&, const inode_ptr) {
throw file_error ("is a plain file");
}
map<string, inode_ptr> plain_file::returnMap (){
throw file_error ("is a plain file");
}
bool plain_file::findFile (const string&) {
throw file_error ("is a plain file");
}
bool plain_file::isADirectory (){
return false;
}
size_t directory::size() const {
size_t size = dirents.size();
DEBUGF ('i', "size = " << size);
return size;
}
const wordvec& directory::readfile() const {
throw file_error ("is a directory");
}
void directory::writefile (const wordvec&) {
throw file_error ("is a directory");
}
void directory::remove (const string& filename) {
if (dirents.find(filename) != dirents.end() and filename != "." and filename != ".."){
if (dirents.find(filename)->second->getContents()->isADirectory() == true) {
dirents.find(filename)->second->getContents()->returnMap().erase(".");
dirents.find(filename)->second->getContents()->returnMap().erase("..");
}
dirents.erase(filename);
}
DEBUGF ('i', filename);
}
inode_ptr directory::mkdir (const string& dirname, const inode_ptr parent) {
inode_ptr subdirect = make_shared<inode>(file_type::DIRECTORY_TYPE);
// dirents.insert(dirname, subdirect);
insertInMap(dirname, subdirect);
subdirect->getContents()->insertInMap(".", subdirect);
subdirect->getContents()->insertInMap("..", parent);
return subdirect;
}
inode_ptr directory::mkfile (const string& filename, const wordvec& words) {
inode_ptr newfile = make_shared<inode>(file_type::PLAIN_TYPE);
// insert key value pair into dirents
insertInMap(filename, newfile);
// write words to new file
newfile->getContents()->writefile(words);
DEBUGF ('i', filename);
return newfile;
}
void directory::insertInMap (const string& key, const inode_ptr value){
dirents.insert({key, value});
}
map<string, inode_ptr> directory::returnMap (){
return dirents;
}
bool directory::findFile (const string& key){
bool found = false;
if (dirents.find(key) != dirents.end()){
found = true;
}
return found;
}
bool directory::isADirectory (){
return true;
}
|
Python
|
UTF-8
| 12,531 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Copyright (C) 2017-2019 New York University,
# University at Buffalo,
# Illinois Institute of Technology.
#
# 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.
"""A workflow is a sequence of modules. Each module is represented by a module
handle. The handle maintains information about the module command, status, the
module outputs, and the module state (datasets).
"""
from typing import Optional
from datetime import datetime
from vizier.core.timestamp import get_current_time
from vizier.viztrail.module.output import ModuleOutputs
from vizier.viztrail.module.provenance import ModuleProvenance
from vizier.viztrail.module.timestamp import ModuleTimestamp
from vizier.viztrail.command import ModuleCommand, ModuleArguments
"""Constants for possible module states."""
MODULE_PENDING = 0
MODULE_RUNNING = 1
MODULE_CANCELED = 2
MODULE_ERROR = 3
MODULE_SUCCESS = 4
# List of valid module states
MODULE_STATE = [
MODULE_CANCELED,
MODULE_ERROR,
MODULE_PENDING,
MODULE_RUNNING,
MODULE_SUCCESS
]
class ModuleState(object):
"""Object representing the module (and workflow) state. Implements boolean
properties to test the current state.
"""
def __init__(self, state:int):
"""Set the state value. Raises ValueError if given state is not a valid
value (one of PENDING, RUNNING, CANCELED, ERROR, SUCCESS).
Parameters
----------
state: int
Module state value.
"""
# Raise ValueError if state is not valid
if not state in MODULE_STATE:
raise ValueError('invalid module state \'' + str(state) + '\'')
self.state = state
@property
def is_active(self):
"""True if either pending or running.
Returns
-------
bool
"""
return self.is_pending or self.is_running
@property
def is_canceled(self):
"""True, if module is in CANCELED state.
Returns
-------
bool
"""
return self.state == MODULE_CANCELED
@property
def is_error(self):
"""True, if module is in ERROR state.
Returns
-------
bool
"""
return self.state == MODULE_ERROR
@property
def is_pending(self):
"""True, if module is in PENDING state.
Returns
-------
bool
"""
return self.state == MODULE_PENDING
@property
def is_running(self):
"""True, if module is in RUNNING state.
Returns
-------
bool
"""
return self.state == MODULE_RUNNING
@property
def is_stopped(self):
"""True, if either canceled or in error state.
Returns
-------
bool
"""
return self.is_canceled or self.is_error
@property
def is_success(self):
"""True, if module is in SUCCESS state.
Returns
-------
bool
"""
return self.state == MODULE_SUCCESS
class ModuleHandle(ModuleState):
"""Handle for a module in a curation workflow. Each module has a unique
identifier, a specification of the executed command, a module state, a
timestamp, a list of generated outputs to STDOUT and STDERR, a dictionary of
resulting datasets and provenance information about datasets that were read
and written (only for modules that have previously been executed
successfully).
If a module is in PENDING state it may contain datasets, outputs, and
provenance information from a previous run of the module.
Attributes
----------
identifier: string, optional
Unique module identifier
command: vizier.viztrail.command.ModuleCommand
Specification of the module (i.e., package, name, and arguments)
external_form: string
Printable representation of the module command
outputs: vizier.viztrail.module.output.ModuleOutputs
Module output streams STDOUT and STDERR
provenance: vizier.viztrail.module.provenance.ModuleProvenance
Provenance information about datasets that were read and writen by
previous execution of the module.
state: int
Module state (one of PENDING, RUNNING, CANCELED, ERROR, SUCCESS)
timestamp: vizier.viztrail.module.timestamp.ModuleTimestamp
Module timestamp
"""
def __init__(self,
command: ModuleCommand,
external_form: Optional[str],
identifier: Optional[str] = None,
state: int = MODULE_PENDING,
timestamp: ModuleTimestamp = ModuleTimestamp(),
outputs: ModuleOutputs = ModuleOutputs(),
provenance: ModuleProvenance = ModuleProvenance()
):
"""Initialize the module handle. For new modules, datasets and outputs
are initially empty.
Parameters
----------
command : vizier.viztrail.command.ModuleCommand
Specification of the module (i.e., package, name, and arguments)
external_form: string
Printable representation of module command
identifier : string, optional
Unique module identifier
state: int
Module state (one of PENDING, RUNNING, CANCELED, ERROR, SUCCESS)
timestamp: vizier.viztrail.module.timestamp.ModuleTimestamp, optional
Module timestamp
outputs: vizier.viztrail.module.output.ModuleOutputs, optional
Module output streams STDOUT and STDERR
provenance: vizier.viztrail.module.provenance.ModuleProvenance, optional
Provenance information about datasets that were read and writen by
previous execution of the module.
"""
super(ModuleHandle, self).__init__(
state=state if not state is None else MODULE_PENDING
)
self.identifier = identifier
self.command = command
self.external_form = external_form
self.outputs = outputs if not outputs is None else ModuleOutputs()
self.provenance = provenance if not provenance is None else ModuleProvenance()
self.timestamp = timestamp if not timestamp is None else ModuleTimestamp()
@property
def artifacts(self):
if self.provenance is None:
return []
if self.provenance.write is None:
return {}
return [ self.provenance.write[k] for k in self.provenance.write.keys() ]
@property
def state_string(self):
if self.state == MODULE_PENDING:
return "PENDING"
elif self.state == MODULE_RUNNING:
return "RUNNING"
elif self.state == MODULE_CANCELED:
return "CANCELED"
elif self.state == MODULE_ERROR:
return "ERROR"
elif self.state == MODULE_SUCCESS:
return "SUCCESS"
else:
return "UNKNOWN ({})".format(self.state)
def __repr__(self):
return "{}.{} @ {} is {}\n{}\n{}".format(
self.command.package_id,
self.command.command_id,
self.identifier,
self.state_string,
"\n".join(self.command.arguments.to_yaml_lines(" ")),
self.outputs
)+("\n"+str(self.outputs) if self.outputs is not None else "")
def set_canceled(self,
finished_at: datetime = get_current_time(),
outputs: ModuleOutputs = ModuleOutputs()
) -> None:
"""Set status of the module to canceled. The finished_at property of the
timestamp is set to the given value or the current time (if None). The
module outputs are set to the given value. If no outputs are given the
module output streams will be empty.
Parameters
----------
finished_at: datetime.datetime, optional
Timestamp when module started running
outputs: vizier.viztrail.module.output.ModuleOutputs, optional
Output streams for module
"""
# Update state, timestamp and output information. Clear database state.
self.state = MODULE_CANCELED
self.timestamp.finished_at = finished_at
self.outputs = outputs
def set_error(self,
finished_at: datetime = get_current_time(),
outputs: ModuleOutputs = ModuleOutputs()
) -> None:
"""Set status of the module to error. The finished_at property of the
timestamp is set to the given value or the current time (if None). The
module outputs are adjusted to the given value. the output streams are
empty if no value is given for the outputs parameter.
Parameters
----------
finished_at: datetime.datetime, optional
Timestamp when module started running
outputs: vizier.viztrail.module.output.ModuleOutputs, optional
Output streams for module
"""
# Update state, timestamp and output information. Clear database state.
self.state = MODULE_ERROR
self.timestamp.finished_at = finished_at
self.outputs = outputs
def set_running(self,
started_at: datetime = get_current_time(),
external_form: Optional[str] = None
) -> None:
"""Set status of the module to running. The started_at property of the
timestamp is set to the given value or the current time (if None).
Parameters
----------
started_at: datetime.datetime, optional
Timestamp when module started running
external_form: string, optional
Adjusted external representation for the module command.
"""
# Update state and timestamp information. Clear outputs and, database
# state,
if external_form is not None:
self.external_form = external_form
self.state = MODULE_RUNNING
self.timestamp.started_at = started_at
self.outputs = ModuleOutputs()
def set_success(self,
finished_at: datetime = get_current_time(),
outputs: ModuleOutputs = ModuleOutputs(),
provenance: ModuleProvenance = ModuleProvenance(),
updated_arguments: Optional[ModuleArguments] = None
):
"""Set status of the module to success. The finished_at property of the
timestamp is set to the given value or the current time (if None).
If case of a successful module execution the database state and module
provenance information are also adjusted together with the module
output streams.
Parameters
----------
finished_at: datetime.datetime, optional
Timestamp when module started running
outputs: vizier.viztrail.module.output.ModuleOutputs, optional
Output streams for module
provenance: vizier.viztrail.module.provenance.ModuleProvenance, optional
Provenance information about datasets that were read and writen by
previous execution of the module.
"""
# Update state, timestamp, database state, outputs and provenance
# information.
self.state = MODULE_SUCCESS
self.timestamp.finished_at = finished_at
# If the module is set to success straight from pending state the
# started_at timestamp may not have been set.
if self.timestamp.started_at is None:
self.timestamp.started_at = self.timestamp.finished_at
if updated_arguments is not None:
self.command.arguments = updated_arguments
self.outputs = outputs
self.provenance = provenance
def update_property(self,
external_form: Optional[str] = None
) -> None:
"""Update the value for the external command representation
Parameters
----------
external_form: string, optional
Adjusted external representation for the module command.
"""
self.external_form = external_form
|
Java
|
ISO-8859-1
| 611 | 3.234375 | 3 |
[] |
no_license
|
package upacademy.HelloWorld;
public class Fizbuz {
public static void main (String[] args) {
ScannerUtils su = new ScannerUtils () ;
System.out.println ("Digite um nmero entre 1 e 40...");
int userValue = su.getInt(1, 40);
int i = 0;
while (i <= userValue) {
if (i%3 == 0 && i % 5 == 0) {
System.out.println ("FizBuz");
i++;
} else if (i%3==0) {
System.out.println ("Fiz");
i++;
}else if (i%5 == 0) {
System.out.println ("Buz");
i++;
}
else {
System.out.println (i);
i++;
}
}
}
}
|
Java
|
UTF-8
| 2,279 | 3.578125 | 4 |
[] |
no_license
|
package src.Interviews.Servicenow;
import java.util.ArrayList;
import java.util.List;
public class MergeList {
/**
* Given two lists of nodes, merge them, end result :
*
* In given list, nodeId is sorted with duplicates.
*
* return:
* All node has the same values should be sumed together.
* Node Id is unique.
*
* example:
*
* l1
* id : 1 1 1 4 5 7 7
* val : 2 3 4 5 1 1 1
*
* l2
* id : 1 3 4 4 6 7
* val : 1 1 2 2 1 1
*
* res
* id : 1 3 4 5 6 7
* val : 10 1 9 1 1 3
*
*/
/**
* Similar problem
* LE_809_Expressive_Words
* LE_844_Backspace_String_Compare
*/
class Node {
int id;
int val;
public Node(int id, int val) {
this.id = id;
this.val = val;
}
}
private List<Node> isMatch(List<Node> l1, List<Node> l2) {
List<Node> res = new ArrayList<>();
if (l1 == null && l2 == null) return res;
int i = 0, j = 0;
while (i < l1.size() && j < l2.size()) {
if (l1.get(i).id == l2.get(j).id) {
int len1 = getLen(l1, i);
int len2 = getLen(l2, j);
Node cur = l1.get(i);
cur.val = l2.get(j).val;
res.add(cur);
i += len1;
j += len2;
} else if (l1.get(i).id < l2.get(j).id) {
res.add(l1.get(i));
i++;
} else {
res.add(l2.get(j));
j++;
}
}
while (i == l1.size() && j < l2.size()) {
int k = getLen(l1, i);
res.add(l1.get(i));
i += k;
}
while (j == l2.size() && i < l1.size()) {
int x = getLen(l2, j);
res.add(l1.get(j));
j += x;
}
return res;
}
private int getLen(List<Node> l, int start) {
int idx = start;
Node n = l.get(start);
while (idx < l.size() && l.get(start).id == l.get(idx).id) {
if (idx != start) {
n.val += l.get(idx).val;
}
idx++;
}
return idx - start;
}
}
|
TypeScript
|
UTF-8
| 1,406 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
import { html, TemplateResult } from 'lit-html'
/**
* Get the value of an HTML meta tag.
*/
export function meta(name: string): string {
return (document.querySelector(`meta[name="${name}"]`) as HTMLMetaElement)?.content
}
/**
* Add <wbr> into long word.
*/
export function breakWord(text: string): string[] {
const regex = /([a-z0-9])([A-Z]+[a-z])|([a-zA-Z0-9][.,/<>_])/g
const result = []
let start = 0
while (true) {
const match = regex.exec(text)
if (!match) {
break
}
const index = match.index + (match[1] || match[3]).length
result.push(text.slice(start, index))
start = index
}
if (start < text.length) {
result.push(text.slice(start))
}
return result
}
/**
* Add <wbr> into long word.
*/
export function breakWordLit(text: string): TemplateResult {
const result = []
breakWord(text).forEach(word => {
if (result.length > 0) {
result.push(html`<wbr>`)
}
result.push(html`${word}`)
})
return html`${result}`
}
/**
* Check if the url is external.
* @param url The url to check.
* @returns True if the url is external.
*/
export function isExternalHref(url: URL): boolean {
return url.hostname !== window.location.hostname || url.protocol !== window.location.protocol
}
|
Java
|
UTF-8
| 1,397 | 3.515625 | 4 |
[] |
no_license
|
package in.array;
public class MergeTwoSortArray {
public static Integer[] mergeArray(Integer [] sortedArr1,Integer [] sortedArr2)
{
Integer[] mergeArray = null;
if(sortedArr1.length<=0 && sortedArr2.length<=0)
{
System.out.println("Both array are blank");
}
else if(sortedArr1.length<=0)
{
return sortedArr2;
}
else if(sortedArr2.length<=0)
{
return sortedArr1;
}
else
{
int sortedArr1Len = sortedArr1.length;
int sortedArr2len= sortedArr2.length;
mergeArray = new Integer[sortedArr1Len+sortedArr2len];
if((sortedArr1Len > sortedArr2len) || (sortedArr1Len > sortedArr2len))
{
for (int i = 0; i < sortedArr1.length; i++) {
if(i<sortedArr2len && sortedArr1[i]<sortedArr2[i])
{
mergeArray[i]=sortedArr1[i];
}
else if(i<sortedArr2len)
{
mergeArray[i]=sortedArr2[i];
}
}
}
else
{
for (int i = 0; i < sortedArr2.length; i++) {
if(i<sortedArr1Len && sortedArr2[i]<sortedArr1[i])
{
mergeArray[i]=sortedArr2[i];
}
else if(i<=sortedArr1Len)
{
mergeArray[i]=sortedArr1[i];
}
}
}
}
return mergeArray;
}
public static void main(String[] args) {
Integer [] mergerArray = mergeArray(new Integer [] {0,3,4,31}, new Integer [] {4,6,30});
for (int i = 0; i < mergerArray.length; i++) {
System.out.println(mergerArray[i]);
}
}
}
|
C#
|
UTF-8
| 790 | 2.546875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using entity;
namespace DAL
{
public class logindal
{
public bool Authenticate(loginentity le)
{
try
{
TrainingDBEntities db = new TrainingDBEntities();
var data = (from t in db.RegisterShoppings
where t.Id == le.userid && t.passw == le.password
select t).SingleOrDefault();
if (data == null)
throw new Exception("Invalid credentials");
}
catch(Exception ex)
{
throw ex;
}
return true;
}
}
}
|
SQL
|
UTF-8
| 4,924 | 2.984375 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.8.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: May 25, 2020 at 06:08 PM
-- Server version: 10.1.37-MariaDB
-- PHP Version: 5.6.40
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `giftry_sprint2_sw2`
--
-- --------------------------------------------------------
--
-- Table structure for table `cart`
--
CREATE TABLE `cart` (
`id` int(11) NOT NULL,
`username` varchar(100) NOT NULL,
`pc_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `cart`
--
INSERT INTO `cart` (`id`, `username`, `pc_id`) VALUES
(9, 'Mahmoud', 10),
(10, 'Mahmoud', 11),
(11, 'Ali', 9);
-- --------------------------------------------------------
--
-- Table structure for table `product`
--
CREATE TABLE `product` (
`id` int(100) NOT NULL,
`name` varchar(200) NOT NULL,
`price` int(50) NOT NULL,
`product_desc` varchar(100) NOT NULL,
`img` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `product`
--
INSERT INTO `product` (`id`, `name`, `price`, `product_desc`, `img`) VALUES
(9, 'Dell Inspiron G5 5590 Gaming Laptop', 26999, ' Intel Core i7-9750H, 15.6 Inch, 1 TB Plus 512 SSD, 16 GB RAM, NVIDIA GeForce RTX 2070W1', 'item_XL_99997917_62e00e7b657be.jpg'),
(10, 'HP 9EV92EA ABV Pavilion 15-dk0028ne Gaming Laptop', 18999, ' 15.6 Inch FHD IPS, Intel Core i7-9750H, 16 GB RAM, 1 TB SATA and 256 GB PCIe, ', 'item_XL_110270193_ba7990649cd9e.jpg'),
(11, 'Lenovo YOGA 730 ', 40000, ' Core i7-8550U, 15.6 Inch 4K UHD , 16GB, 1TB, nVidia GTX1050 4GB, Win10, English K', 'item_XL_55262628_e20003accee60.jpg');
-- --------------------------------------------------------
--
-- Table structure for table `sw2_feedback`
--
CREATE TABLE `sw2_feedback` (
`id` int(11) NOT NULL,
`username` varchar(100) NOT NULL,
`text` varchar(500) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `sw2_feedback`
--
INSERT INTO `sw2_feedback` (`id`, `username`, `text`) VALUES
(1, 'Ali', ' welcome first comment\r\n\r\n \r\n \r\n \r\n '),
(2, 'Mahmoud', ' \r\n second comment by user mahmoud\r\n \r\n \r\n ');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`id` int(100) NOT NULL,
`username` varchar(200) NOT NULL,
`email` varchar(200) NOT NULL,
`password` varchar(200) NOT NULL,
`address` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`id`, `username`, `email`, `password`, `address`) VALUES
(1, 'Mahmoud', 'mahmoudelwan460@gmail.com', '1478530123M', '407 omer ibn '),
(4, 'Admin', 'admin@gmail.com', '14785', 'admin407'),
(5, 'Ali', 'mahmoudn460@gmail.com', '1478530123A', 'ioj');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `cart`
--
ALTER TABLE `cart`
ADD PRIMARY KEY (`id`),
ADD KEY `pc_id` (`pc_id`);
--
-- Indexes for table `product`
--
ALTER TABLE `product`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `name` (`name`);
--
-- Indexes for table `sw2_feedback`
--
ALTER TABLE `sw2_feedback`
ADD PRIMARY KEY (`id`),
ADD KEY `username` (`username`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `email` (`email`),
ADD UNIQUE KEY `username` (`username`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `cart`
--
ALTER TABLE `cart`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
MODIFY `id` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;
--
-- AUTO_INCREMENT for table `sw2_feedback`
--
ALTER TABLE `sw2_feedback`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `id` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `cart`
--
ALTER TABLE `cart`
ADD CONSTRAINT `cart_ibfk_1` FOREIGN KEY (`pc_id`) REFERENCES `product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `sw2_feedback`
--
ALTER TABLE `sw2_feedback`
ADD CONSTRAINT `sw2_feedback_ibfk_1` FOREIGN KEY (`username`) REFERENCES `user` (`username`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Python
|
UTF-8
| 247 | 2.921875 | 3 |
[] |
no_license
|
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
my_seq = Seq("GATCGATGGGCCTATATAGGATCGAAAATCGC", IUPAC.unambiguous_dna)
print(repr(my_seq))
print(repr(my_seq.complement()))
print(repr(my_seq.reverse_complement()))
print(repr(my_seq[::-1]))
|
Java
|
UTF-8
| 10,516 | 2.046875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2019 Google LLC
*
* 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 com.google.zetasql;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.zetasql.ZetaSQLTypeParameters.NumericTypeParametersProto;
import com.google.zetasql.ZetaSQLTypeParameters.StringTypeParametersProto;
import com.google.zetasql.ZetaSQLTypeParameters.TypeParametersProto;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public final class TypeParametersTest {
@Test
public void createStringTypeParametersWithMaxLiteral() {
StringTypeParametersProto proto =
StringTypeParametersProto.newBuilder().setIsMaxLength(true).build();
TypeParameters typeParameters = new TypeParameters(proto);
assertThat(typeParameters.isStringTypeParameters()).isTrue();
assertThat(typeParameters.getStringTypeParameters().getIsMaxLength()).isTrue();
assertThat(typeParameters.debugString()).isEqualTo("(max_length=MAX)");
}
@Test
public void createStringTypeParametersWithMaxLength() {
StringTypeParametersProto proto =
StringTypeParametersProto.newBuilder().setMaxLength(1000).build();
TypeParameters typeParameters = new TypeParameters(proto);
assertThat(typeParameters.isStringTypeParameters()).isTrue();
assertThat(typeParameters.getStringTypeParameters().getMaxLength()).isEqualTo(1000);
assertThat(typeParameters.debugString()).isEqualTo("(max_length=1000)");
}
@Test
public void createNumericTypeParametersWithMaxLiteral() {
NumericTypeParametersProto proto =
NumericTypeParametersProto.newBuilder().setIsMaxPrecision(true).setScale(20).build();
TypeParameters typeParameters = new TypeParameters(proto);
assertThat(typeParameters.isNumericTypeParameters()).isTrue();
assertThat(typeParameters.debugString()).isEqualTo("(precision=MAX,scale=20)");
}
@Test
public void createNumericTypeParametersWithPrecisonAndScale() {
NumericTypeParametersProto proto =
NumericTypeParametersProto.newBuilder().setPrecision(20).setScale(7).build();
TypeParameters typeParameters = new TypeParameters(proto);
assertThat(typeParameters.isNumericTypeParameters()).isTrue();
assertThat(typeParameters.debugString()).isEqualTo("(precision=20,scale=7)");
}
@Test
public void createNumericTypeParametersWithPrecisionOnly() {
NumericTypeParametersProto proto =
NumericTypeParametersProto.newBuilder().setPrecision(20).build();
TypeParameters typeParameters = new TypeParameters(proto);
assertThat(typeParameters.isNumericTypeParameters()).isTrue();
assertThat(typeParameters.debugString()).isEqualTo("(precision=20,scale=0)");
}
@Test
public void createTypeParametersWithChildList() {
StringTypeParametersProto stringParam =
StringTypeParametersProto.newBuilder().setMaxLength(10).build();
NumericTypeParametersProto numericParam =
NumericTypeParametersProto.newBuilder().setPrecision(10).setScale(5).build();
List<TypeParameters> childList =
Arrays.asList(
new TypeParameters(),
new TypeParameters(stringParam),
new TypeParameters(numericParam));
TypeParameters structParam = new TypeParameters(childList);
assertThat(structParam.getChildCount()).isEqualTo(3);
assertThat(structParam.isStructOrArrayParameters()).isTrue();
assertThat(structParam.isEmpty()).isFalse();
assertThat(structParam.debugString())
.isEqualTo("[null,(max_length=10),(precision=10,scale=5)]");
}
public static void checkSerializeAndDeserialize(TypeParameters typeParameters) {
try {
TypeParameters typeParameters2 = TypeParameters.deserialize(typeParameters.serialize());
assertThat(typeParameters).isEqualTo(typeParameters2);
assertThat(typeParameters2).isEqualTo(typeParameters);
assertThat(typeParameters.hashCode()).isEqualTo(typeParameters2.hashCode());
assertThat(typeParameters.serialize()).isEqualTo(typeParameters2.serialize());
} catch (IllegalArgumentException e) {
fail(e.toString());
}
}
@Test
public void serializeAndDeserializeStringTypeParameters() {
checkSerializeAndDeserialize(
new TypeParameters(StringTypeParametersProto.newBuilder().setIsMaxLength(true).build()));
checkSerializeAndDeserialize(
new TypeParameters(StringTypeParametersProto.newBuilder().setMaxLength(10).build()));
}
@Test
public void serializeAndDeserializeNumericTypeParameters() {
checkSerializeAndDeserialize(
new TypeParameters(
NumericTypeParametersProto.newBuilder().setPrecision(10).setScale(5).build()));
checkSerializeAndDeserialize(
new TypeParameters(
NumericTypeParametersProto.newBuilder().setIsMaxPrecision(true).setScale(20).build()));
}
@Test
public void serializeAndDeserializeTypeParametersWithChildList() {
StringTypeParametersProto stringParam =
StringTypeParametersProto.newBuilder().setMaxLength(50).build();
NumericTypeParametersProto numericParam =
NumericTypeParametersProto.newBuilder().setPrecision(70).setScale(30).build();
List<TypeParameters> childList =
Arrays.asList(new TypeParameters(stringParam), new TypeParameters(numericParam));
TypeParameters structParam = new TypeParameters(childList);
checkSerializeAndDeserialize(structParam);
}
@Test
public void deserializeStringTypeParametersFailed() {
// is_max_length is set to false.
try {
TypeParameters.deserialize(
TypeParametersProto.newBuilder()
.setStringTypeParameters(StringTypeParametersProto.newBuilder().setIsMaxLength(false))
.build());
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected)
.hasMessageThat()
.contains("is_max_length should either be unset or true");
}
// max_length <= 0.
try {
TypeParameters.deserialize(
TypeParametersProto.newBuilder()
.setStringTypeParameters(StringTypeParametersProto.newBuilder().setMaxLength(-100))
.build());
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().contains("max_length must be larger than 0");
}
}
@Test
public void deserializeNumericTypeParametersFailed() {
// is_max_precision is set to false.
try {
TypeParameters.deserialize(
TypeParametersProto.newBuilder()
.setNumericTypeParameters(
NumericTypeParametersProto.newBuilder().setIsMaxPrecision(false))
.build());
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected)
.hasMessageThat()
.contains("is_max_precision should either be unset or true");
}
// precision > 76.
try {
TypeParameters.deserialize(
TypeParametersProto.newBuilder()
.setNumericTypeParameters(
NumericTypeParametersProto.newBuilder().setPrecision(100).setScale(30))
.build());
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected)
.hasMessageThat()
.contains("precision must be within range [1, 76] or MAX");
}
// scale > 38.
try {
TypeParameters.deserialize(
TypeParametersProto.newBuilder()
.setNumericTypeParameters(
NumericTypeParametersProto.newBuilder().setPrecision(50).setScale(40))
.build());
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().contains("scale must be within range [0, 38]");
}
// precision < scale.
try {
TypeParameters.deserialize(
TypeParametersProto.newBuilder()
.setNumericTypeParameters(
NumericTypeParametersProto.newBuilder().setPrecision(30).setScale(35))
.build());
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected)
.hasMessageThat()
.contains("precision must be equal to or larger than scale");
}
}
@Test
public void twoTypeParametersAreEqual() {
TypeParameters numericParam1 =
new TypeParameters(
NumericTypeParametersProto.newBuilder().setIsMaxPrecision(true).setScale(20).build());
TypeParameters numericParam2 =
new TypeParameters(
NumericTypeParametersProto.newBuilder().setIsMaxPrecision(true).setScale(20).build());
TypeParameters numericParam3 =
new TypeParameters(
NumericTypeParametersProto.newBuilder().setPrecision(50).setScale(20).build());
assertThat(numericParam1.equals(numericParam2)).isTrue();
assertThat(numericParam1.equals(numericParam3)).isFalse();
TypeParameters stringParam1 =
new TypeParameters(StringTypeParametersProto.newBuilder().setMaxLength(100).build());
TypeParameters stringParam2 =
new TypeParameters(StringTypeParametersProto.newBuilder().setMaxLength(100).build());
TypeParameters stringParam3 =
new TypeParameters(StringTypeParametersProto.newBuilder().setMaxLength(1000).build());
assertThat(stringParam1.equals(stringParam2)).isTrue();
assertThat(stringParam1.equals(stringParam3)).isFalse();
List<TypeParameters> childList1 =
Arrays.asList(stringParam1, new TypeParameters(), numericParam1);
List<TypeParameters> childList2 =
Arrays.asList(stringParam2, new TypeParameters(), numericParam2);
List<TypeParameters> childList3 = Arrays.asList(stringParam3, numericParam2);
assertThat(new TypeParameters(childList1).equals(new TypeParameters(childList2))).isTrue();
assertThat(new TypeParameters(childList1).equals(new TypeParameters(childList3))).isFalse();
}
}
|
JavaScript
|
UTF-8
| 20,468 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
//
// # Rules for expressions.
//
import { proto } from "~/util"
import { Match, Rule } from "~/parser"
import { AST, SpellParser } from "~/languages/spell"
/** TODOC!!! */
SpellParser.Rule.InfixOperatorSuffix = class infix_operator extends Rule.Sequence {
// set `outputDatatype` to specify explicit datatype in standard `getAST()`
/** If `true`, we'll wrap output expression in parenthesis. */
@proto parenthesize = false
/** Return output operator from `operator` match. Override for more complex logic.
* TODO: this is language-dependent!
*/
getOutputOperator(operator) {
// Default to just use input string
return operator.value
}
/** Return `true` if we should "negate" the output expression based on `operator`.
* TODO: this is language-dependent!
*/
shouldNegateOutput(operator) {
return false
}
/**
* - `lhs` is left-hand side AST
* - `operator` is operator Match
* - `rhs` is right-hand-side AST
* By default does an InfixExpression, override to e.g. do a CoreMethodInvocation()
*/
compileASTExpression(match, { lhs, operator, rhs }) {
return new AST.InfixExpression(match, {
lhs,
operator: this.getOutputOperator(operator),
rhs
})
}
/**
* While running the "shunting yard algorithm" in getAST(), we'll match
* `Infix-` and `PostfixOperatorSuffix` instances with args on left/right side.
* This routine delegates to rule-specific `compileASTExpression()` to actually output
* the particular AST for the rule.
*
* This routine also handles adding parenthesis and negating the output for you automatically.
*
* `lhs` is the left-hand-side Match AST (NOTE: already AST calculated!)
* `operator` is the operator Match
* `rhs` (for InfixOperatorSuffixes only) is the right-hand-side Match AST.
*/
compileAST(match, { operator, rhs, lhs }) {
let expression = this.compileASTExpression(match, { lhs, operator, rhs })
if (this.parenthesize && !(expression instanceof AST.ParenthesizedExpression)) {
expression = new AST.ParenthesizedExpression(match, { expression })
}
if (this.shouldNegateOutput(operator)) expression = new AST.NotExpression(match, { expression })
return expression
}
getAST(match) {
throw new TypeError("This should never be called")
}
}
/** TODOC!!! */
SpellParser.Rule.PostfixOperatorSuffix = class postfix_operator extends SpellParser.Rule.InfixOperatorSuffix {
/**
* - `lhs` is left-hand side match
* - `operator` is raw full input operator string
*/
compileASTExpression(match, { lhs, operator }) {
throw new TypeError("Must implement compileASTExpression()")
}
}
export const expressions = new SpellParser({
module: "expressions",
rules: [
{
name: "parenthesized_expression",
alias: ["expression"],
syntax: "\\( {expression} \\)",
testRule: "\\(",
getAST(match) {
const { expression } = match.groups
return new AST.ParenthesizedExpression(match, {
expression: expression.AST
})
},
tests: [
{
title: "correctly matches parenthesized expressions",
beforeEach(scope) {
scope.variables.add("thing")
},
tests: [
["(thing)", "(thing)"],
["((thing))", "(thing)"],
["(((thing)))", "(thing)"],
["(1 and yes)", "(1 && true)"]
]
},
{
title: "correctly matches multiple parenthesis",
compileAs: "expression",
tests: [
["(1) and (yes)", "((1) && (true))"],
["((1) and (yes))", "((1) && (true))"],
["((1) and ((yes)))", "((1) && (true))"]
]
},
{
title: "doesn't match malformed parenthesized expressions",
tests: [
["(foo", undefined],
["(foo(bar)baz", undefined]
]
}
]
},
{
name: "compound_expression",
alias: "expression",
isLeftRecursive: true,
precedence: 12,
syntax: "{lhs:simple_expression} {rhsChain:expression_suffix}+",
getAST(match) {
function applyOperatorToRule({ match: ruleMatch, operator, rhs, lhs }) {
function compile(thing) {
if (!thing) return undefined
// TODO: we have one case ("is the queen of spades") where `thing` match is an array... :-(
if (Array.isArray(thing)) return thing.map(compile)
if (thing instanceof Match && thing.rule.getAST) return thing.AST
return thing
}
const args = {
operator,
rhs: compile(rhs),
lhs: compile(lhs)
}
const result = ruleMatch.rule.compileAST(ruleMatch, args)
return result
}
// Iterate through the rhs expressions, using a variant of the shunting-yard algorithm
// to deal with operator precedence. Note that we assume:
// - all infix operators are `left-to-right` associative, and
// - all postfix operators are left to right associative.
// See: https://en.wikipedia.org/wiki/Shunting-yard_algorithm
// See: https://www.chris-j.co.uk/parsing.php
const { lhs, rhsChain } = match.groups
const output = [lhs]
const opStack = []
rhsChain.matched.forEach((rhs) => {
// Unary postfix operator, e.g. "<lhs> is empty"
if (rhs.rule instanceof SpellParser.Rule.PostfixOperatorSuffix) {
const args = {
match: rhs,
lhs: output.pop(),
// use explicit operator if there is one, default to entire match
operator: rhs.groups.operator || rhs
}
output.push(applyOperatorToRule(args))
}
// Infix binary operator, e.g. "<lhs> is a <rhs>"
else if (rhs.rule instanceof SpellParser.Rule.InfixOperatorSuffix) {
const { operator, expression } = rhs.groups
// While top operator on stack is higher precedence than this one
while (opStack[opStack.length - 1]?.match.rule.precedence >= rhs.rule.precedence) {
// pop the top operator and compile it with top 2 things on the output stack
const topOp = opStack.pop()
const args = {
...topOp,
rhs: output.pop(), // NOTE: order is vital here!
lhs: output.pop()
}
output.push(applyOperatorToRule(args))
}
// Push the current operator and expression
opStack.push({ match: rhs, operator })
output.push(expression)
} else {
console.warn("Unexpected rule type", rhs.rule.name)
}
})
// At this point, we have only binary operators in the output stack.
// Run through them and apply the operator to them in pairs.
let topOp
while ((topOp = opStack.pop())) {
const args = {
...topOp,
rhs: output.pop(), // NOTE: order is vital here!
lhs: output.pop()
}
output.push(applyOperatorToRule(args))
}
if (output.length !== 1) {
console.warn("Shunting yard ended up with too much output:", output)
}
return output[0]
},
// test multiple infix expressions in a row
tests: [
{
title: "complex math expressions",
compileAs: "expression",
tests: [
["1 + 2 + 3", "((1 + 2) + 3)"],
["(1+1) * (2+2)", "((1 + 1) * (2 + 2))"],
["((1+1) * (2+2))", "((1 + 1) * (2 + 2))"]
]
},
{
title: "complex property/etc expressions",
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("card")
},
tests: [[`the suit of the card is "ace"`, `(card.suit == "ace")`]]
}
]
},
{
name: "and",
alias: "expression_suffix",
syntax: "(operator:and) {expression:simple_expression}",
precedence: 6,
constructor: "InfixOperatorSuffix",
getOutputOperator: () => "&&",
parenthesize: true,
tests: [
{
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("thing")
scope.variables.add("other")
scope.variables.add("yet-another")
},
tests: [
["thing and other", "(thing && other)"],
["thing and other and yet-another", "((thing && other) && yet_another)"],
["thing is 1 and other is 2", "((thing == 1) && (other == 2))"]
]
}
]
},
{
name: "or",
alias: "expression_suffix",
syntax: "(operator:or) {expression:simple_expression}",
precedence: 5,
constructor: "InfixOperatorSuffix",
getOutputOperator: () => "||",
parenthesize: true,
tests: [
{
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("thing")
scope.variables.add("other")
},
tests: [["thing or other", "(thing || other)"]]
}
]
},
{
name: "is",
alias: "expression_suffix",
precedence: 10,
syntax: "(operator:is not?) {expression:simple_expression}",
constructor: "InfixOperatorSuffix",
parenthesize: true,
getOutputOperator: (operator) => (operator.value === "is not" ? "!=" : "=="),
tests: [
{
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("thing")
scope.variables.add("other")
},
tests: [
["thing is other", "(thing == other)"],
["thing is not other", "(thing != other)"]
]
}
]
},
{
name: "is_exactly",
alias: "expression_suffix",
precedence: 10,
syntax: "(operator:is not? exactly) {expression:simple_expression}",
constructor: "InfixOperatorSuffix",
parenthesize: true,
getOutputOperator: (operator) => (operator.value === "is not exactly" ? "!==" : "==="),
tests: [
{
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("thing")
scope.variables.add("other")
},
tests: [
["thing is exactly other", "(thing === other)"],
["thing is not exactly other", "(thing !== other)"]
]
}
]
},
{
name: "is_a",
alias: "expression_suffix",
precedence: 11,
syntax: "(operator:is not? (a|an)) {expression:type}",
constructor: "InfixOperatorSuffix",
shouldNegateOutput: (operator) => operator.value.includes("not"),
compileASTExpression(match, { lhs, rhs }) {
// TODO: QuotedExpression feels wrong here...
return new AST.CoreMethodInvocation(match, {
methodName: "isOfType",
args: [lhs, new AST.QuotedExpression(match, { expression: rhs })]
})
},
tests: [
{
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("thing")
},
tests: [
["thing is a Bee", "spellCore.isOfType(thing, 'Bee')"],
["thing is an Animal", "spellCore.isOfType(thing, 'Animal')"],
["thing is not a Bee", "!spellCore.isOfType(thing, 'Bee')"],
["thing is not an Animal", "!spellCore.isOfType(thing, 'Animal')"]
]
}
]
},
{
name: "is_same_type_as",
alias: "expression_suffix",
precedence: 11,
syntax: "(operator:is not? the same type as) {expression:simple_expression}",
constructor: "InfixOperatorSuffix",
getOutputOperator: (operator) => (operator.value.includes("not") ? "!==" : "==="),
compileASTExpression(match, { lhs, rhs }) {
return new AST.CoreMethodInvocation(match, {
methodName: "matchesType",
args: [lhs, rhs]
})
},
tests: [
{
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("thing")
scope.variables.add("other")
},
tests: [
["thing is the same type as other", "spellCore.matchesType(thing, other)"],
["thing is not the same type as other", "spellCore.matchesType(thing, other)"]
]
}
]
},
{
name: "is_in",
alias: "expression_suffix",
precedence: 11,
syntax:
"(operator:is (not? in|not? one of|either|not either of?|neither)) (expression:{simple_expression}|{identifier_list})",
constructor: "InfixOperatorSuffix",
shouldNegateOutput: ({ value }) => value.includes("not") || value.includes("neither"),
compileASTExpression(match, { lhs, rhs }) {
return new AST.CoreMethodInvocation(match, {
methodName: "includes",
args: [rhs, lhs]
})
},
tests: [
{
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("thing")
scope.variables.add("red")
scope.constants.add("green")
scope.variables.add("theList")
},
tests: [
["thing is in theList", "spellCore.includes(theList, thing)"],
["thing is one of theList", "spellCore.includes(theList, thing)"],
["thing is not in theList", "!spellCore.includes(theList, thing)"],
["thing is not one of theList", "!spellCore.includes(theList, thing)"],
["thing is either red or green", "spellCore.includes([red, 'green'], thing)"],
["thing is not either red or green", "!spellCore.includes([red, 'green'], thing)"],
["thing is not either of red or green", "!spellCore.includes([red, 'green'], thing)"],
["thing is neither red nor green", "!spellCore.includes([red, 'green'], thing)"]
]
}
]
},
{
name: "includes",
alias: "expression_suffix",
precedence: 11,
syntax: "(operator:includes|contains) {expression:simple_expression}",
constructor: "InfixOperatorSuffix",
compileASTExpression(match, { lhs, rhs }) {
return new AST.CoreMethodInvocation(match, {
methodName: "includes",
args: [lhs, rhs]
})
},
tests: [
{
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("theList")
scope.variables.add("thing")
},
tests: [
["theList includes thing", "spellCore.includes(theList, thing)"],
["theList contains thing", "spellCore.includes(theList, thing)"]
]
}
]
},
{
name: "does_not_include",
alias: "expression_suffix",
precedence: 11,
syntax: "(operator:does not (include|contain)) {expression:simple_expression}",
constructor: "InfixOperatorSuffix",
shouldNegateOutput: () => true,
compileASTExpression(match, { lhs, rhs }) {
return new AST.CoreMethodInvocation(match, {
methodName: "includes",
args: [lhs, rhs]
})
},
tests: [
{
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("theList")
scope.variables.add("thing")
},
tests: [
["theList does not include thing", "!spellCore.includes(theList, thing)"],
["theList does not contain thing", "!spellCore.includes(theList, thing)"]
]
}
]
},
{
name: "is_defined",
alias: "expression_suffix",
precedence: 11,
syntax: "is (defined|undefined|not defined)",
constructor: "PostfixOperatorSuffix",
shouldNegateOutput: (operator) => operator.value !== "is defined",
compileASTExpression(match, { lhs }) {
return new AST.CoreMethodInvocation(match, {
methodName: "isDefined",
args: [lhs]
})
},
tests: [
{
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("thing")
},
tests: [
["thing is defined", "spellCore.isDefined(thing)"],
["thing is undefined", "!spellCore.isDefined(thing)"],
["thing is not defined", "!spellCore.isDefined(thing)"]
]
}
]
},
{
name: "exists",
alias: "expression_suffix",
precedence: 11,
syntax: "(exists|does not exist)",
constructor: "PostfixOperatorSuffix",
shouldNegateOutput: (operator) => operator.value !== "exists",
compileASTExpression(match, { lhs }) {
return new AST.CoreMethodInvocation(match, {
methodName: "isDefined",
args: [lhs]
})
},
tests: [
{
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("thing")
},
tests: [
["thing exists", "spellCore.isDefined(thing)"],
["thing does not exist", "!spellCore.isDefined(thing)"]
]
}
]
},
{
name: "there_is_a",
alias: "expression",
precedence: 11,
syntax: "there (operator:is not? (a|an)|is no such) {expression}",
getAST(match) {
const { operator } = match.groups
const expression = new AST.CoreMethodInvocation(match, {
methodName: "isDefined",
args: [match.groups.expression.AST]
})
if (operator.value.includes("no")) return new AST.NotExpression(match, { expression })
return expression
},
tests: [
{
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("thing")
scope.variables.add("animal")
},
tests: [
{ input: "there is a thing", output: "spellCore.isDefined(thing)" },
{ input: "there is an animal", output: "spellCore.isDefined(animal)" },
{ input: "there is not a thing", output: "!spellCore.isDefined(thing)" },
{ input: "there is no such animal", output: "!spellCore.isDefined(animal)" }
]
}
]
},
/** Collection is empty */
{
name: "is_empty",
alias: "expression_suffix",
precedence: 11,
syntax: "(operator:is not? empty)",
constructor: "PostfixOperatorSuffix",
shouldNegateOutput: (operator) => operator.value.includes("not"),
compileASTExpression(match, { lhs }) {
return new AST.CoreMethodInvocation(match, {
methodName: "isEmpty",
args: [lhs]
})
},
tests: [
{
compileAs: "expression",
beforeEach(scope) {
scope.variables.add("thing")
},
tests: [
["thing is empty", "spellCore.isEmpty(thing)"],
["thing is not empty", "!spellCore.isEmpty(thing)"]
]
}
]
},
/** String utilities */
{
name: "as_uppercase",
alias: "expression_suffix",
precedence: 11,
syntax: "as (upper case|uppercase)",
constructor: "PostfixOperatorSuffix",
compileASTExpression(match, { lhs }) {
return new AST.CoreMethodInvocation(match, {
methodName: "upperCase",
args: [lhs]
})
},
tests: [
{
compileAs: "expression",
tests: [
[`"foo" as upper case`, `spellCore.upperCase("foo")`],
[`1 as uppercase`, `spellCore.upperCase(1)`]
]
}
]
},
{
name: "as_lowercase",
alias: "expression_suffix",
precedence: 11,
syntax: "as (lower case|lowercase)",
constructor: "PostfixOperatorSuffix",
compileASTExpression(match, { lhs }) {
return new AST.CoreMethodInvocation(match, {
methodName: "lowerCase",
args: [lhs]
})
},
tests: [
{
compileAs: "expression",
tests: [
[`"foo" as lower case`, `spellCore.lowerCase("foo")`],
[`1 as lowercase`, `spellCore.lowerCase(1)`]
]
}
]
}
]
})
|
C++
|
UTF-8
| 2,161 | 2.953125 | 3 |
[] |
no_license
|
#include "pch.h"
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int count = 0;
struct point {
int x;
int y;
};
int compare_by(struct point p1, struct point p2, char c) {
count++;
//ここを埋める
if (p1.x == p2.x && p1.y == p2.y) {
return 0;
}
else if (c == 'X') {//Xの処理
if (p1.x > p2.x) {
return 1;
}
else if (p1.x < p2.x) {
return -1;
}
else if (p1.y > p2.y) {
return 1;
}
else {
return -1;
}
}
else if (c == 'Y') {//Yの処理
if (p1.y > p2.y) {
return 1;
}
else if (p1.y < p2.y) {
return -1;
}
else if (p1.x > p2.x) {
return 1;
}
else {
return -1;
}
}
else {//Dの処理
int p1xy = p1.x * p1.x + p1.y * p1.y;
int p2xy = p2.x * p2.x + p2.y * p2.y;
if (p1xy > p2xy) {
return 1;
}
else if (p1xy < p2xy) {
return -1;
}
else if (p1.x > p2.x) {
return 1;
}
else if (p1.x < p2.x) {
return -1;
}
else if (p1.y > p2.y) {
return 1;
}
else {
return -1;
}
}
}
int max_index_by(struct point a[], int n, char c) {
int max_i = 0;
struct point max_p;
int result = 0;
max_p = a[0];
for (int i = 1;i < n;++i) {
result = compare_by(a[i], max_p, c);
if (result == 1) {
max_p = a[i];
max_i = i;
}
else if (result == 0) {
max_p = a[i];
max_i = i;
}
}
return max_i;
}
void bubble_sort(struct point a[], int n, char c) {
struct point tmp;
int result;
for (int k = n - 2;k >= 0;k--) {
for (int l = 0;l <= k;l++) {
struct point a_l = a[l];
struct point a_l_plus_one = a[l + 1];
result = compare_by(a[l], a[l + 1], c);
if (result != -1) {
tmp = a[l];
a[l] = a[l + 1];
a[l + 1] = tmp;
}
}
}
}
int main()
{
char c;
char buf[128];
struct point p;
struct point arr[128];
int i = 0;
int n;
scanf("%c ", &c);
while (fgets(buf, sizeof(buf), stdin) != NULL && i < 128) {
sscanf(buf, "%d %d", &p.x, &p.y);
arr[i] = p;
++i;
}
n = i;
bubble_sort(arr, n, c);
printf("%d\n", count);
for (i = 0;i < n;++i) {
printf("%d %d\n", arr[i].x, arr[i].y);
}
return 0;
}
|
Java
|
UTF-8
| 1,577 | 3.671875 | 4 |
[] |
no_license
|
package bankingsix;
// customer classs
class CustomersSix {
// instance variables
String customerName;
String customerID;
// private variable for this class soley
private AccountSix account;
// constructor with parameters.
CustomersSix(String customerName, String customerID, AccountSix account){
this.customerName = customerName;
this.customerID = customerID;
this.account = account;
}
// method for our customer to deposit
public void deposit(float amnt){
// if account inputed is an instanceof our savings class. we will use the credit method from that class
if (account instanceof SavingsSix){
((SavingsSix)account).credit(amnt);
// if account inputed is an instanceof our checking class. we will use the credit method from that class
} else if (account instanceof CheckingSix){
((CheckingSix)account).credit(amnt);
}
}
// method for depositing interest and activating our addIY method.
void depositInterest(){
System.out.println("Depositing interest to account: " + customerID);
if (account instanceof SavingsSix){
((SavingsSix)account).addIY();
}
}
// method for our customer to withdrawl.
public void withdrawl(float amnt){
if (account instanceof SavingsSix ){
((SavingsSix)account).debit(amnt);
} else if (account instanceof CheckingSix){
((CheckingSix)account).debit(amnt);
}
}
public void display(){
System.out.println("Name: "+ customerName);
System.out.println("ID: "+ customerID);
account.display();
System.out.println(account);
}
}
|
Markdown
|
UTF-8
| 3,442 | 2.640625 | 3 |
[
"CC-BY-4.0",
"MIT",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
---
title: Run content moderation jobs in Azure Content Moderator | Microsoft Docs
description: Learn how to run content moderation jobs in the API console.
services: cognitive-services
author: sanjeev3
manager: mikemcca
ms.service: cognitive-services
ms.technology: content-moderator
ms.topic: article
ms.date: 08/03/2017
ms.author: sajagtap
---
# Start a moderation job from the API console
Use the Review API's [job operations](https://westus.dev.cognitive.microsoft.com/docs/services/580519463f9b070e5c591178/operations/580519483f9b0709fc47f9c5) to initiate end-to-end content moderation jobs for image or text content in Azure Content Moderator.
The moderation job scans your content by using the Content Moderator Image Moderation API or Text Moderation API. Then, the moderation job uses the default and custom workflows (defined by using the Review tool) to generate reviews in the Review tool.
After a human moderator reviews the auto-assigned tags and prediction data and submits a final moderation decision, the Review API submits all information to your API endpoint.
## Use the API console
To test-drive the API by using the online console, you need a few values to enter into the console:
- **teamName**: The team name that you created when you set up your Review tool account.
- **ContentId**: This string is passed to the API and returned through the callback. **ContentId** is useful for associating internal identifiers or metadata with the results of a moderation job.
- **Workflowname**: The name of the workflow that you created. For a quick test, you can use the value **Default**.
- **Ocp-Apim-Subscription-Key**: Located on the **Settings** tab. For more information, see [Overview](overview.md).
The simplest way to access a testing console is from the **Credentials** window.
1. In the **Credentials** window, select [API reference](https://westus.dev.cognitive.microsoft.com/docs/services/580519463f9b070e5c591178/operations/580519483f9b0709fc47f9c5).
The **Job - Create** page opens.
2. For **Open API testing console**, select the region that most closely describes your location.

The **Job - Create** API console opens.
3. Enter values for the required query parameters, and your subscription key. In the **Request body** box, specify the location of the information that you want to scan.

4. Select **Send**. A job ID is created. Copy this to use in the next steps.

5. Select **Get**, and then open the API by selecting the button that matches your region.

6. Enter values for **teamName** and **JobID**. Enter your subscription key, and then select **Send**. The results of the scan are returned.

7. On the Content Moderator Dashboard, select **Review** > **Image**. The image that you scanned appears, ready for human review.

## Next steps
Use the REST API in your code or start with the [Jobs .NET quickstart](moderation-jobs-quickstart-dotnet.md) to integrate with your application.
|
TypeScript
|
UTF-8
| 10,166 | 2.53125 | 3 |
[] |
no_license
|
// 关卡控制逻辑
class Level {
public displayName:string;
public map:Map;
public bt:Battle; // 反向引用回所属 battle
public keys:Elem[] = []; // 装着所有的关卡初始钥匙
public levelType; // 关卡种类
private cfg;
private lv;
public Init(bt:Battle, cfg) {
this.displayName = cfg.displayName;
this.bt = bt;
this.cfg = cfg;
this.lv = bt.player.currentTotalStorey();
this.levelType = this.getLevelType();
this.InitMap(cfg.map);
this.InitElems(bt.btType, cfg.elems, cfg.constElems, cfg.randomGroups,
GCfg.mapsize.w * GCfg.mapsize.h + cfg.init_uncovered.w + cfg.init_uncovered.h,
cfg.init_uncovered, cfg.doorUnlock);
if (cfg.levelLogics) {
for (var levelLogic of cfg.levelLogics) {
var ll = LevelLogicFactory.createLevelLogic(levelLogic.type, ...levelLogic.ps);
this.addLevelLogic(ll);
}
}
}
// 创建地图
public InitMap(cfg) {
this.map = new Map();
}
// 创建指定元素,如果未明确指定配置属性,则默认参考本关卡配置
private elemsCfgInLevel;
public getElemCfg(type:string) {
var attrs = GCfg.getElemAttrsOfLevel(type, this.lv);
if (!attrs)
attrs = GCfg.getElemAttrsCfg(type);
while (attrs && attrs.type) {
type = attrs.type;
var tAttrs = GCfg.getElemAttrsOfLevel(type, this.lv);
tAttrs = tAttrs ? tAttrs : GCfg.getElemAttrsCfg(type);
if (tAttrs) {
for (var k in attrs)
if (k != "type")
tAttrs[k] = attrs[k];
attrs = tAttrs;
} else
break;
}
return {type:type, attrs:attrs};
}
public createElem(type:string, attrs = undefined, player:Player = undefined):Elem {
if (!attrs) { // 如果指定配置属性,则不再参考本关卡配置
var r = this.getElemCfg(type);
type = r.type;
attrs = r.attrs;
}
attrs = attrs ? attrs : {};
var e = ElemFactory.create(type, attrs, player);
// 根据难度对怪物的血量进行调整
if (e instanceof Monster && e.isHazard() && e.hp)
e.hp = Math.ceil(e.hp * GCfg.getDifficultyCfg()[this.bt.player.difficulty]["monsterHp"] / 100);
// 处理携带物品
if (attrs.dropItems) {
for (var dpType of attrs.dropItems) {
var dpe = this.createElem(dpType);
e.addDropItem(dpe);
}
}
e = ElemFactory.doDropItemsOnDie(e);
// 部分元素的创建过程受到遗物的影响,此处只能触发同步逻辑点
this.bt.triggerLogicPointSync("onLevelCreateElem", {e:e, type:type})
return e;
}
// 创建初始元素
public InitElems(btType:string, elemsCfg, constElemsCfg, randomGroupsCfg, elemNumLimit, init_uncovered_size, doorUnlock) {
this.elemsCfgInLevel = elemsCfg;
var maxNumLimit = 0; // 做最大可能数量的检查
var elems = [
this.createElem("Door", {cnt:doorUnlock}) // 下一层入口的门
];
// 逃跑出口,继承关卡不需要
if (this.levelType != "awardInherited")
elems.push(this.createElem("EscapePort", {size: init_uncovered_size}))
// 钥匙存在关卡身上,等待统一安排
for(var i = 0; i < doorUnlock; i++){
this.keys.push(this.createElem("Key"));
}
// 添加固定元素
for (var e in constElemsCfg) {
let num = constElemsCfg[e];
for (var i = 0; i < num; i++)
elems.push(this.createElem(e));
}
// 添加职业物品
elems = this.addOccupationInitItems(elems);
// 添加随机元素
if (randomGroupsCfg) {
for (var group of randomGroupsCfg) {
// 累计数量上限检查
maxNumLimit += group.num[1] - 1;
Utils.assert(maxNumLimit <= elemNumLimit, "elem overflow in map: " + this.displayName);
var arr = Utils.randomSelectByWeightWithPlayerFilter(this.bt.player, group.elems, this.bt.srand, group.num[0], group.num[1], false, undefined, (type) => this.getElemCfg(type));
for (var et of arr) {
var elem = this.createElem(et)
if (group.drops) {
for (var dp of group.drops) {
var dpe = this.createElem(dp);
elem.addDropItem(dpe);
}
}
elems.push(elem);
}
}
}
this.bt.triggerLogicPointSync("onLevelInitElems", {bt:this.bt, elems:elems});
// 依次加入地图
var x = 0;
var y = 0;
for (var elem of elems) {
if(!elem.isBig()){
this.map.addElemAt(elem, x, y);
var cnt = 1;
for (var i = 0; i < cnt; i++) {
x++;
if (x >= this.map.size.w) { y++; x = 0; }
}
}
}
for (var elem of elems) {
if(elem.isBig()){
var esize = elem.attrs.size;
var g = BattleUtils.findRandomEmptyGrid(this.bt, false, esize);
this.map.addElemAt(elem, g.pos.x, g.pos.y);
}
}
}
// 根据配置将部分元素放置在固定位置,其余元素随机
public setElemPosByCfg(cfg, covered:boolean = true){
var biggerElems:Elem[] = [];
var normalElems:Elem[] = [];
// 先分开大尺寸元素和普通元素
this.map.travelAll((x, y) => {
var e = this.map.getElemAt(x, y);
if (!e) return;
if (e.type == "PlaceHolder")
return;
else if (e.isBig())
biggerElems.push(e);
else
normalElems.push(e);
this.map.removeElemAt(e.pos.x, e.pos.y);
});
if(cfg){
// 先给大尺寸元素找到指定位置
var posCfg = GCfg.getElemPosCfg(cfg);
Utils.assert(posCfg, "can not find ElemPosCfg for " + this.bt.btType);
for(var e of biggerElems){
if(posCfg[e.type]){
for(var i = 0; i < posCfg[e.type].length; i++){
var pos = posCfg[e.type][i];
if(!this.map.getElemAt(pos.x, pos.y)){
this.map.addElemAt(e, pos.x, pos.y);
biggerElems = Utils.remove(biggerElems, e);
break;
}
}
}
}
// 给普通元素找到指定位置
for(var e of normalElems){
if(posCfg[e.type]){
for(var i = 0; i < posCfg[e.type].length; i++){
var pos = posCfg[e.type][i];
if(!this.map.getElemAt(pos.x, pos.y)){
this.map.addElemAt(e, pos.x, pos.y);
normalElems = Utils.remove(normalElems, e);
break;
}
}
}
}
}
// 其余元素随机放置
// 先给大尺寸元素找到随机位置
for (var e of biggerElems) {
var esize = e.attrs.size;
var g = BattleUtils.findRandomEmptyGrid(this.bt, covered, esize);
Utils.assert(!!g, "can not place big " + e.type + " with size of " + esize);
this.map.addElemAt(e, g.pos.x, g.pos.y);
var hds:Elem[] = e["placeHolders"]();
Utils.assert(hds.length == esize.w * esize.h - 1, "big elem size mismatch the number of it's placeholders");
}
// 再放置普通元素
for (var e of normalElems) {
Utils.assert(e.type != "PlaceHolder", "place holders should be placed already");
var g = BattleUtils.findRandomEmptyGrid(this.bt, covered);
Utils.assert(!!g, "no more place for elem");
this.map.addElemAt(e, g.pos.x, g.pos.y);
}
}
// 添加职业物品
public addOccupationInitItems(items:Elem[]){
// 继承用的关卡不需要添加职业物品
if(this.levelType == "awardInherited")
return items;
var cfg = GCfg.getOccupationCfg(this.bt.player.occupation);
for(var constItem in cfg.constItems){
for(var i = 0; i < cfg.constItems[constItem]; i++){
var e = this.createElem(constItem);
e["occupationInitItem"] = true; // 提供给遗物判断是否是此时添加的职业物品
items.push(e)
}
}
var es = Utils.randomSelectByWeight(cfg.randomItems.elems, this.bt.srand, cfg.randomItems.num[0], cfg.randomItems.num[1], true);
for(var randomItem of es){
var e = this.createElem(randomItem);
e["occupationInitItem"] = true; // 提供给遗物判断是否是此时添加的职业物品
items.push(e);
}
return items;
}
// 关卡逻辑
public levelLogics:LevelLogic[] = []; // 当前层具有的逻辑
public addLevelLogic(levelLogic:LevelLogic){
levelLogic.level = this;
this.levelLogics.push(levelLogic);
}
public removeLevelLogic(type:string){
var n = Utils.indexOf(this.levelLogics, (l:LevelLogic) => l.type == type);
var levelLogic;
if (n >= 0) {
levelLogic = this.levelLogics[n];
this.levelLogics = Utils.removeAt(this.levelLogics, n);
}
}
private getLevelType() {
var index = this.bt.btType.indexOf("_");
var levelType = this.bt.btType.substring(0 , index);
return levelType;
}
}
|
Python
|
UTF-8
| 671 | 3.03125 | 3 |
[] |
no_license
|
nobel_winners = [
{'category': 'Physics',
'name': 'Albert Einstein',
'nationality': 'Swiss',
'sex': 'male',
'year': 1921},
{'category': 'Physics',
'name': 'Paul Dirac',
'nationality': 'British',
'sex': 'male',
'year': 1933},
{'category': 'Chemistry',
'name': 'Marie Curie',
'nationality': 'Polish',
'sex': 'female',
'year': 1911}
]
import json
with open('nobel_winner3.json','w')as f:
json.dump(nobel_winners,f) # 寫入
print(nobel_winners)
print("1間隔間隔間隔間隔間隔間隔")
with open('nobel_winner3.json')as f:
nobel_winners=json.load(f) # 從JSON讀入
print(nobel_winners)
#python 讀入是用dict方式讀入 要看JSON格式還是要直接開檔案看
|
Java
|
UTF-8
| 1,223 | 2.125 | 2 |
[] |
no_license
|
package cn.mldn.vshop.action.back;
import cn.mldn.util.factory.Factory;
import cn.mldn.util.web.ModelAndView;
import cn.mldn.vshop.service.back.IItemServiceBack;
import cn.mldn.vshop.util.action.AbstractBaseAction;
import cn.mldn.vshop.vo.Item;
public class ItemActionBack extends AbstractBaseAction {
public void edit(Item vo) {
if (super.isRoleAndAction("goods", "goods:item")) {
try {
IItemServiceBack itemService = Factory.getServiceInstance("item.service.back") ;
super.print(itemService.edit(vo));
} catch (Exception e) {
e.printStackTrace();
}
} else {
super.print(false);
}
}
public ModelAndView list() {
if (super.isRoleAndAction("goods", "goods:item")) {
ModelAndView mav = new ModelAndView(
super.getUrl("item.list.page"));
try {
IItemServiceBack itemService = Factory.getServiceInstance("item.service.back") ;
mav.add("allItems", itemService.list());
return mav;
} catch (Exception e) {
e.printStackTrace();
}
} else {
super.setUrlAndMsg("index.page", "unaction.msg");
ModelAndView mav = new ModelAndView(
super.getUrl("forward.back.page"));
return mav;
}
return null;
}
}
|
Shell
|
UTF-8
| 619 | 3.484375 | 3 |
[] |
no_license
|
#!/bin/bash
#
# Test custom level2 creation
#
# Usage: ./ead.sh IISH flow home folder
flows_home=$1
if [ ! -d "$flows_home" ] ; then
echo "flows_home folder should point to the iish-flows home directory."
exit -1
fi
global_home=$flows_home/src/main/global
cd $flows_home/src/main/flow1/custom_level2
na=12345
for fileSet in $flows_home/src/test/flow1/$na/*
do
archiveID=$(basename $fileSet)
work=$fileSet/work
if [ ! -d $work ] ; then
mkdir $work
fi
log=$work/log.txt
# There ought to be some images in the test .level1 folder
targetLevel=level2
source ./run.sh
done
|
Markdown
|
UTF-8
| 89,200 | 3.9375 | 4 |
[] |
no_license
|
数据结构
## 线性表
线性表的物理存储结构有两种,顺序存储结构与链式存储结构。
### 顺序存储结构
#### 概念
- 线性表List是由零个或多个数据元素组成的有限序列。也就是说可以为空。而当存在多个元素时,第一个元素无前驱,最后一个元素无后继,其他元素都有且只有一个前驱与后继。元素之间是一对一的关系;
- 数据类型是一组性质相同的值的集合及定义在此集合上的一些操作的总称。如C语言中按照取值的不同,数据类型可以分为两类,原子类型(不可分解,如int、double、char)与结构类型(如整型数组);
- 抽象数据类型 ADT (Abstract Data Type),类似于面向对象中的类,由方法与属性组成, ADT就是将数据类型与相关操作绑定,与其在计算机内部如何表示与实现无关。如位置坐标xyz;
- 线性表的操作如创建与初始化、判断是否为空、清空、查找、删除、插入等。
- 线性表也称为随机存储结构,因为可以通过一次计算得到线性表中任意位置的地址,存储时间性能为O(1)。
- 线性表相当于在数组上加入一个变量存储当前线性表的长度。线性表位置从1开始计数。数组索引从0开始。
- 线性表在存、读数据时,时间复杂度为O(1);在插入、删除时,时间复杂度为O(n)。
#### 实现
使用数组实现。线性表相当于在数组上加入一个变量存储当前线性表的长度。
当插入或删除操作的位置在表尾时,后边没有元素,因此不需要移动,此时时间复杂度为O(1)。
如下为插入与删除的完整代码。
~~~c
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
/*
Status是函数的类型,返回值是函数结构状态代码,如OK等
初始条件:顺序线性表L已存在,1<=i<=ListLength(L)
操作结果:用e返回L中第i个的数据元素的值
*/
Status ListInsert(SqList *L, int i, ElemType e)
{
if ( i >= MAXSIZE ) // 线性表已满
{
return ERROR;
}
if ( i<1 || i>L->length+1) // 当i不在范围内
{
return ERROR;
}
if ( i <= L->length ) // 插入位置不在表尾
{
// 将要插入位置后数据元素向后移动一位
int j;
for ( j=L->length; j>=i; j-- )
{
L->data[j] = L->data[j-1];
}
}
// 插入位置在表尾时,后边没有元素,因此不需要移动
L->data[i-1] = e; // 插入元素
L->length ++;
return OK;
}
/* 操作结果:删除L的第i个元素,并返回其值 */
Status ListDelete(SqList *L, int i, ElemType *e);
{
if ( L->length == 0 ) // 空表
{
return ERROR;
}
if ( i<1 || i>L->length+1 ) // 当i不在范围内
{
return ERROR;
}
*e = L->data[i-1]; // 取出删除元素
if ( i < L->length ) // 删除位置不在表尾
{
// 将要删除位置后数据元素向前移动一位
int j;
for ( j=i; j<L->length; j++ )
{
L->data[j-1] = L->data[j];
}
}
// 删除位置在表尾时,后边没有元素,因此不需要移动
L->length --;
return OK;
}
~~~
#### 优缺点
- 优点:无需为表示表中元素之间的逻辑关系而增加额外的存储空间,可以快速存取;
- 缺点:插入与删除操作需要移动大量元素。容易造成存储空间的“碎片”。
### 链式存储结构
#### 概念
- 用一组任意的存储单元存储线性表的数据元素,同时存储数据元素信息与后继元素的存储地址(指针)。
- 域指地址,数据域与指针域组成的数据元素称为存储影像,即结点(Node)。头指针是链表的必要条件,不为空。
- 单链表中的第一个结点的存储位置叫做头结点,放在第一个元素结点之前,数据域通常不存储信息,可以用来存放链表的长度。头指针指向头结点,头指针不同于头结点,链表可以没有头结点(空链表),但不可以没有头指针(头指针为空时不存在链表,而空链表是链表)。头结点的存在使得空链表与非空链表处理一致,也方便对链表的开始结点的插入或删除操作。最后一个结点指针为空(NULL)。
- 核心思想是指针后移,即遍历。需要注意None结点没有next属性,单链表只能搜索后继结点不能搜索前驱结点。
- 单链表在插入、删除时,时间复杂度为O(n),当该操作频繁时效率优势明显。
- 顺序存储结构需要预分配存储空间,单链表不需要考虑存储空间的大小问题。

#### 单链表实现
- 对于要修改链表的内容的操作,需要传入链表的指针,即指向指针的指针,所以必须是*L;
- 新建链表的方法可以分为头插法与尾插法,其中头插法优点是简洁,缺点是逆序,而尾插法顺序;
- 面向对象使用引用机制间接地实现了指针的某些功能。而在C语言之前,使用数组描述的链表叫做静态链表,这种描述方法叫做游标实现法。
~~~c
typedef int ElemType;
typedef int Status;
typedef struct Node
{
ElemType data; // 数据域
struct Node *next; // 指针域
} Node; // 结点
typedef struct Node *LinkList; // 单链表
// 链表内容有变化时函数传入指针,不变时传入数值
void CreateListHead( LinkList *L, int n );
void CreateListTail( LinkList *L, int n );
void PrintList( LinkList L );
Status GetElem( LinkList L, int i, ElemType *e );
Status InsertList( LinkList *L, int i, ElemType e );
Status DeleteList( LinkList *L, int i, ElemType *e );
Status ClearList( LinkList *L );
int main( int argc, char const *argv[] )
{
LinkList L;
// PrintList(L);
int n = 5;
// CreateListHead(&L, 5); // 5 4 3 2 1
CreateListTail(&L, 5); // 1 2 3 4 5
PrintList(L);
ElemType a;
GetElem(L, 2, &a); // 2
return 0;
}
void CreateListHead( LinkList *L, int n )
{
int i; // 遍历生成链表
LinkList p; // 新结点,作为中介
LinkList q; // 当前结点
// 因为需要修改链表的内容,需要传入链表的指针,即指向指针的指针,所以必须是*L
// 声明与赋值:*L 对应于函数形参 LinkList *L,p 对应于声明中的 LinkList p;
*L = (LinkList)malloc(sizeof(Node)); // 创建带头结点的空单链表
(*L)->next = NULL; // 头结点数据域不存储信息。头结点未指定data,会随机分配值
q = *L; // 指向头结点,不移动
// 头插法,逆序
for ( i=0; i<n; i++ )
{
p = (LinkList)malloc(sizeof(Node));
p->data = i+1;
p->next = q->next;
q->next = p;
}
}
// get指针移动到指定位置,insert与delete指针移动到指定位置的前一位,因此p指针的初始化不同
// 在链表的第i个元素之前插入新的数据元素
Status InsertList( LinkList *L, int i, ElemType e )
{
LinkList p, q;
int j;
j = 1;
p = *L;
// 移动到第i个元素前的那个元素
while ( p && j<i )
{
p = p->next;
++ j;
}
// 第i个元素不存在
if ( !p || j>i ) // 分别满足 j=8、j=0
{
return ERROR;
}
// 第i个元素存在
q = (LinkList)malloc(sizeof(Node)); // 生成空结点
q->data = e;
// 实现插入操作
q->next = p->next;
p->next = q;
return OK;
}
/* 初始条件:顺序线性表L已存在,1<=i<=ListLength(L) */
/* 操作结果:删除L的第i个数据元素,并用e返回其值,L的长度-1 */
Status DeleteList( LinkList *L, int i, ElemType *e )
{
LinkList p, q;
int j;
j = 1;
p = *L;
while ( p->next && j<i )
{
p = p->next;
/*
q = p->next
p = q;
q = q->next;
不满足,如 i=8
*/
++ j;
}
if ( !(p->next) || j>i )
{
return ERROR;
}
q = p->next;
p->next = q->next;
*e = q->data;
free(q);
return OK;
}
~~~
#### 寻找单链表中间结点
设置快慢指针可以用于寻找单链表中间结点,也可以用于单链表中环的检测。
~~~c
Status MidList( LinkList L, ElemType *e )
{
LinkList p, q;
p = q = L;
while ( p->next != NULL )
{
// p的移动速度是q的两倍
if ( p->next->next != NULL ) // 偶数
{
q = q->next;
p = p->next->next;
printf("%d\t", q->data);
}
else // 奇数
{
p = p->next;
q = q->next;
printf("%d\t", q->data);
}
}
*e = q->data;
printf("\nmid = %d\n", *e);
return OK;
}
~~~
#### 循环链表实现
- 单链表的缺点:不可逆,不从头结点出发,就无法访问到全部结点。
- 单循环链表简称循环链表,将终结点的指针端由空指针改为指向头结点,形成首尾相连的环形单链表。
- 循环链表与单链表的主要差异体现在判断空链表的条件(循环遍历的条件):rear == rear->next(只有头结点)。
- 单链表操作中间结点时需要遍历以定位,循环链表操作头结点时,需要遍历找出尾结点。
- 以上都是头指针表示的单循环链表,查找尾结点时需要进行遍历,对此做出改进。
- 不用头指针,而是用指向尾结点的尾指针来表示循环链表,这时查找头结点和尾结点的时间复杂度都是O(1)。如用于线性表的拼接。
- 单向循环链表的插入是在尾部插入。
- 循环链表实现初始化时可以有头结点,也可以没有头结点。
~~~c
void InitCListHead( LinkList *L ) // 链表有头结点
{
int item = 0;
printf("输入结点的值,输入0完成初始化:\n");
while (1)
{
scanf("%d", &item);
fflush(stdin); // 清空
if ( item == 0 ) // 退出
{
return;
}
/*
判断初始化的链表有没有结点
没有结点 先创建头结点 然后插入数据
有结点 将结点用尾插法插入到链表中
最后 尾结点的 指针域 指向头结点 这样形成一个环
*/
if ( !(*L) ) // 空链表
{
LinkList head = (LinkList)malloc(sizeof(Node)); // 头结点
if ( head == NULL ) // 分配失败
{
exit(0); // 错误退出
}
*L = head; // 链表指向头结点,头指针指向头结点 。L 存放 head 的地址
LinkList node = (LinkList)malloc(sizeof(Node)); // 第一个结点
node->data = item;
node->next = head;
head->next = node;
// (*L)->data = item;
// (*L)->next = *L; // 指针域指向它本身
}
else // 从第二个结点开始,尾部插入
{
LinkList cur; // 指向表头
for ( cur = (*L)->next; cur->next != *L; cur = cur->next ); // 移动指针至表尾
LinkList head = cur->next; // 头结点 head = *L
LinkList node;
node = (LinkList)malloc(sizeof(Node)); // 生成一个新的结点
if ( !(node) ) // 生成失败
{
exit(0);
}
node->data = item;
node->next = head;
cur->next = node;
}
}
}
void InitCListNoHead( LinkList *L ) // 链表没有头结点
{
printf("输入结点的值,输入0完成初始化:\n");
int item = 0;
while (1)
{
scanf("%d", &item);
fflush(stdin);
if ( item == 0 )
{
return;
}
LinkList node = NULL; // 新增结点,不需要头结点
if ( !(*L) ) // 空链表
{
node = (LinkList)malloc(sizeof(Node)); // 添加第一个结点
node->data = item;
node->next = node;
*L = node; // *L就是第一个结点
}
else
{
LinkList cur = NULL;
for ( cur = *L; cur->next != *L; cur = cur->next ); // 移动指针至表尾
node = (LinkList)malloc(sizeof(Node));
node->data = item;
node->next = *L;
cur->next = node;
}
}
}
~~~
#### 约瑟夫问题
分两步,先创建循环链表,再逐一删除结点。
~~~c
typedef struct Node
{
int data;
struct Node *next;
} Node;
Node *create( int n );
int main()
{
int n = 41;
int m = 3;
Node *p = create(n);
while ( p != p->next )
{
int i;
for ( i=1; i<(m-1); i++ ) // i<m-1 == i<2
{
p = p->next;
}
printf("%d->", p->next->data);
Node *temp; // 中间作用
temp = p->next;
p->next = temp->next;
free(temp); // 删除结点
p = p->next;
}
printf("%d\n", p->data);
return 0;
}
Node *create( int n )
{
Node *head = NULL; // 为什么是指针?
head = (Node*)malloc(sizeof(Node)); // 创建头结点,头结点不动,头结点后是第一个结点
Node *cur= NULL;
cur = head; // 当前结点,添加结点时会移动
int i;
Node *node;
if ( 0 != n )
{
for ( i=1; i<=n; i++ ) // 尾插法建立链表
{
node = (Node*)malloc(sizeof(Node));
node->data = i;
cur->next = node; // 第一个结点
cur = node;
}
node->next = head->next; // 让最后一个结点指向第一个有数据结点
}
free(head); // 构成环后不再需要头结点
// node是最后一个结点,不保留头结点
return node->next; // 返回第一个结点
}
~~~
#### 判断单链表中是否有环
- 方法1,比较步数,一个一次走一步,一次每次从头走,位置相同步数不同时判断为有环,两个循环;
- 方法2,快慢指针,一个循环。
~~~c
void InitList( LinkList *L )
{
// 链表创建头结点
Node *head = (Node*)malloc(sizeof(Node));
head->next = NULL;
if (!head)
{
exit(0);
}
*L = head;
}
void CreateListTail( LinkList *L, int n )
{
// 创建带头结点的有环链表(尾插法)
Node *head = *L;
Node *cur = head;
Node *node;
int i;
for ( i=1; i<=n; i++ )
{
node = (Node*)malloc(sizeof(Node));
node->data = i;
cur->next = node;
cur = node;
}
node->next = head->next->next->next; // 设置环的位置
}
void CreateListHead( LinkList *L, int n )
{
// 创建带头结点的无环链表(头插法)
Node *head = *L;
head->next = NULL; // 初始化
Node *node;
int i;
for ( i=1; i<=LENGTH; i++ )
{
node = (Node*)malloc(sizeof(Node));
node->data = i;
node->next = head->next;
head->next = node;
}
}
int HasLoop1( LinkList L )
{
Node *head = L;
Node *cur1 = head;
int pos1 = 0;
while (cur1) // 结点存在
{
Node *cur2 = head;
int pos2 = 0;
while (cur2) // cur2 每次从头结点开始移动
{
if ( cur1 == cur2 )
{
if ( pos1 == pos2 )
{
break; // 没有环
} else // 位置相同步数不同时有环
{
printf("环在第%d个结点处\n", pos2);
return 1;
}
}
cur2 = cur2->next;
pos2 ++;
}
cur1 = cur1->next;
pos1 ++;
}
return 0;
}
int HasLoop2( LinkList L )
{
Node *head = L;
Node *p = head;
Node *q = head;
while ( p != NULL && q != NULL && q->next != NULL )
{
p = p->next;
if ( q->next != NULL)
{
q = q->next->next;
}
printf("p: %d, q: %d\n", p->data, q->data);
if ( p == q )
{
return 1;
}
}
return 0;
}
~~~
#### 魔术师发牌问题
循环链表实现。
~~~c
LinkList CreateLinkList()
{
Node *head = (Node*)malloc(sizeof(Node));
head->next = NULL;
LinkList L = head;
Node *cur = head;
Node *node;
int i;
for ( i=0; i<CardNumber; i++ )
{
node = (Node*)malloc(sizeof(Node));
node->data = 0; // 结点初始化
// if ( head == NULL ) // 设置第一个结点为头结点
// {
// head = node;
// } else
// {
// cur->next = node;
// }
cur->next = node;
cur = node;
}
L = head->next;
node->next = L; // 指向第一个结点
return L;
}
void Magician(LinkList *L)
{
Node *cur = *L;
cur->data = 1; // 第一个位置
int i;
int j;
for ( i=2; i<=CardNumber; i++ ) // 从第二个位置开始
{
for ( j=1; j<=i; j++ ) // 将cur移动到第i个结点
{
cur = cur->next;
if ( cur->data != 0 )
{
j--;
}
}
cur->data = i;
}
}
~~~
#### 双向循环链表实现
- 结点结构包括前驱结点prior与后继结点next,注意插入与删除操作的顺序;
- 要求支持反向移动,因此需要双向循环链表。前驱结点用于反向移动,后继结点用于正向移动。
~~~c
typedef struct Node
{
ElemType data;
struct Node *prior; // 前驱结点
struct Node *next; // 后继结点
} Node, *DualLinkList;
DualLinkList Create()
{
DualLinkList L;
Node *head;
Node *cur; // cur与node都是起中间作用
Node *node;
head = (Node*)malloc(sizeof(Node)); // 头结点
if ( !head ) // 分配失败,返回 NULL
{
exit(0);
}
head->prior = NULL; // 初始化
head->next = NULL;
L = head;
cur = head;
int i;
for ( i=0; i<26; i++ ) // 双向链表,没有循环,尾插法实现
{
node = (Node*)malloc(sizeof(Node));
if ( !node )
{
exit(0);
}
node->data = 'A' + i; // ASCII A-Z 65-90
node->prior = cur;
node->next = cur->next; // 为了程序的通用性
cur->next = node;
cur = node;
}
L = head->next; // 不需要头结点
node->next = L; // 循环
L->prior = node;
return L;
}
void Move(DualLinkList *L, int n)
{
Node *head = *L;
Node *cur;
Node *node;
if ( n > 0 ) // 正向,头结点右移
{
int i;
for ( i=0; i<n; i++ )
{
head = head->next;
}
}
if ( n < 0) // 反向,头结点左移
{
int i;
n = (-1) * n;
for ( i=0; i<n; i++ )
{
head = head->prior;
}
}
*L = head;
}
~~~
## 栈与队列
栈与队列规定了进出的入口,因此相对要比顺序表与链表的实现简单。
### 栈
#### 概念
栈,一个后进先出的线性表。
要求只在表尾进行删除和插入操作。表尾称为栈顶,表头称为栈底。栈顶top存储下一个元素。
栈可用于如浏览器的后退,撤销、函数的实现、编译器检测代码中的括号匹配问题、数值的进制转换等。
基于栈结构的特点,在实际应用中,通常只会对栈执行以下两种操作:
- 向栈中添加元素,此过程被称为"进栈"(入栈或压栈);
- 从栈中提取出指定元素,此过程被称为"出栈"(或弹栈)。
如图所示:
#### 顺序栈实现
- 栈也分顺序存储结构与链式存储结构,分别简称顺序栈与链栈。首先实现顺序存储结构,使用居多;
- 栈有初始化容量。当栈满时进行扩容,未满时大小不变。因此栈中元素的个数通常不等于栈的最大容量;
- 通常使用数组实现,int top存放的是当前栈顶位于数组的第几号元素,用于索引数组。当栈为空时,top=-1;
- 建议使用int *top,top是指针,存储int的地址,也就是指向int,栈顶用于存储下一个数据。当栈为空时,top=base。此外,建议使用ElemType,具有通用性;
- **push时,先赋值后移动top。pop时,先移动top后赋值**。
~~~c
void InitStack(sqStack *s) // 有大小的空栈
{
s->base = (ElemType*)malloc( STACK_INIT_SIZE * sizeof(ElemType) ); // 与普通链表不同,栈有初始化容量
if ( !(s->base) )
{
exit(0);
}
s->top = s->base; // 空栈的栈顶与栈底重合
s->stackSize = STACK_INIT_SIZE;
}
void Push(ElemType e, sqStack *s) // 入栈
{
if ( s->top - s->base >= s->stackSize ) // 栈满扩容
{
s->base = (ElemType*)realloc(s->base, (s->stackSize + STACK_INCREMETN) * sizeof(ElemType)); // malloc + copy
if ( !(s->base) )
{
exit(0);
}
s->top = s->base + s->stackSize; // 设置栈顶
s->stackSize += STACK_INCREMETN;
}
*(s->top) = e;
s->top ++; // 移动栈顶
}
void Pop(ElemType *e, sqStack *s) // 出栈
{
if ( s->top == s->base ) // 空栈
{
return;
}
s->top --; // 栈顶用于存储下一个数据,因此需要先下移
*e = *(s->top);
printf("%d\n", *e);
}
void TraverseStack(sqStack s)
{
sqStack *p = &s; // 备份,将地址存入指针
if ( p->top == p->base )
{
printf("栈为空\n");
return;
}
printf("栈内元素包括:\n");
while ( p->top != p->base )
{
p->top --;
printf("%d\t", *(p->top)); // 最后一位也打印了
}
printf("\n");
}
void ClearStack(sqStack *s) // 清空,内存还在
{
s->top = s->base; // 移动指针
}
void DestoryStack(sqStack *s) // 销毁,内存释放
{
int i;
int len;
len = s->stackSize;
for ( i=0; i<len; i++ )
{
free(s->base);
s->base ++;
}
s->base = s->top = NULL;
s->stackSize = 0;
}
int LenStack(sqStack s) // 返回栈中元素的个数,通常不等于栈的最大容量
{
// return (s->top - s->base); // 错误,s是结构体,不是指针
return (s.top - s.base);
}
~~~
#### 进制转换
- 二进制转换为十进制。如二进制1011转换成十进制是11,采用按权展开求和的方法,具体如下:

- 二进制转换为八进制、十六进制。使用两个栈。
~~~c
int main()
{
Stack s; // 存储二级制的栈
InitStack(&s); // 初始化
printf("请输入8位二进制数:\n");
int i;
ElemType e;
for ( i=0; i<STACK_INIT_SIZE; i++ ) // 生成二进制数
{
scanf("%d", &e);
Push(&s, e); // 进栈
}
int j;
Stack t; // 存储8进制的栈
InitStack(&t);
int len = LenStack(s); // LenStack(s)的返回值在变化
for ( i=0; i<len; i+=3 )
{
int n = 0;
int num = 0; // 3位二进制转换成的十进制
for ( j=0; j<3; j++ )
{
if ( s.top == s.base ) // 到栈底了
{
break;
}
Pop(&s, &n); // 出栈
num += n * pow(2, j);
}
// printf("n = %d\n", num);
Push(&t, num); // 入栈
}
// 打印存储八进制的栈
while ( t.top != t.base )
{
t.top --;
printf("%d\t", *(t.top));
}
printf("\n");
return 0;
}
~~~
#### 链栈实现
- 实现单链表实现。
- 因为只是栈顶来做插入和删除操作,所以比较好的方法就是将栈顶放在单链表的头部,栈顶指针和单链表的头指针合二为一。
~~~c
typedef struct Node // 结点
{
ElemType data;
struct Node *next;
} Node;
typedef struct // 链栈
{
Node *top; // 栈顶指向头结点
int count; // 栈元素计数器
} LinkStack;
int main()
{
LinkStack s;
int i;
if ( InitStack(&s) ) // 初始化
{
printf("Stack is empty: %d\n", StackEmpty(s)); // 栈为空
for ( i=0; i<10; i++ )
{
Push(&s, i + 1); // 入栈
}
printf("Stack is empty: %d\n", StackEmpty(s)); // 栈不为空
}
PrintStack(s);
Pop(&s, &i); // 出栈
PrintStack(s); // 可以执行多次
return 0;
}
Status InitStack(LinkStack *s)
{
// LinkStack s = (LinkStack*)malloc(sizeof(LinkStack));
s->top = (Node*)malloc(sizeof(Node));
if ( !(s->top) )
{
return ERROR;
}
s->top = NULL;
s->count = 0;
return OK;
}
Status Push( LinkStack *s, ElemType e ) // 入栈
{
Node *p = (Node*)malloc(sizeof(Node)); // p 存储 Node 的地址
p->data = e;
p->next = s->top; // 头插法,新结点指向现有的第一个结点。top不动
s->top = p;
s->count ++;
}
Status Pop( LinkStack *s, ElemType *e )
{
if ( StackEmpty(*s) )
{
return ERROR;
}
Node *p;
p = s->top;
*e = p->data;
printf("元素 %d 出栈\n", *e);
s->top = p->next;
free(p);
s->count --;
return OK;
}
~~~
#### 逆波兰计算器
核心是去掉括号。借助顺序栈记忆符号的优先级。
- 运算的优先级规则为从左向右,括号优先级最高,先乘除后加减;
- 逆波兰表达式 RPN,不需要括号的后缀表达式,也就是将操作符放在数字的后面;
- **中缀表达式转换为后缀表达式**。从左向右遍历每个元素,是数字直接输出,是符号判断优先级;
- 逆波兰计算器的实现分两步,先将中缀表达式转换为后缀表达式,再根据逆波兰表达式计算结果。
~~~c
/*使用顺序栈实现逆波兰表达式*/
#define STACK_INIT_SIZE 10
#define STACK_INCREMENT 20
#define MAXBUFFER 10
typedef double ElemType;
typedef struct
{
ElemType *top;
ElemType *base;
int size;
} Stack;
void InitStack(Stack *s);
void PushStack(Stack *s, ElemType e);
void PopStack(Stack *s, ElemType *e);
void PrintStack(Stack s);
int main()
{
Stack s;
InitStack(&s); // init
printf("请按逆波兰表达式输入待计算数据,数据与运算符之间用空格隔开,以#作为结束标志: \n");
char c;
scanf("%c", &c);
char str[MAXBUFFER]; // 缓冲区数组,将没有空格的数字合并 123 4
int i = 0; // 数组索引
double a, b; // 支持小数计算
while ( c != '#' )
{
while ( isdigit(c) || c == '.' ) // 用于过滤数字 123 4 + 5
{
str[i++] = c;
// printf("c = %c\n", c);
str[i] = '\0'; // 字符串结尾
if ( i >= 10 )
{
printf("出错:输入的单个数据过大!\n");
return -1; // main
}
scanf("%c", &c);
if ( c == ' ' ) // 输入的数字之间以空格分隔,数字输入结束
{
a = atof(str); // 将字符串转换为浮点数
// printf("%f\n", a);
PushStack(&s, a); // 一个数字入栈 123
i = 0; // 缓冲区数组重置
break;
}
}
switch (c) // 操作符,没有入栈
{
case '+':
PopStack(&s, &a); // 使用指针返回值
PopStack(&s, &b);
PushStack(&s, b+a);
break;
case '-':
PopStack(&s, &a);
PopStack(&s, &b);
PushStack(&s, b-a); // a先出栈
break;
case '*':
PopStack(&s, &a);
PopStack(&s, &b);
PushStack(&s, b*a);
break;
case '/':
PopStack(&s, &a);
PopStack(&s, &b);
if ( a == 0 )
{
return -1;
} else
{
PushStack(&s, b/a);
}
break;
}
scanf("%c", &c);
}
PrintStack(s); // 栈内一个元素
PopStack(&s, &a);
printf("最终的计算结果为:%f\n", a);
// 8 - (8 + 8) + 8 + 9 / 4 --> 8 8 8 + - 8 + 9 4 / + # 2.25
return 0;
}
// 中缀表达式转换为后缀表达式
int main()
{
Stack t; // 存放运算符,不含括号,数字直接打印
Init(&t);
printf("请输入要计算的中缀表达式,中间不需要空格分隔,使用英文运算符,输入以#结尾:\n");
char c;
scanf("%c", &c);
char d; // 从t中出栈
/*总结规则:从左到右遍历中缀表达式的每个数字和符号,若是数字则直接输出,若是符号,则判断其与栈顶符号的优先级,
是右括号或者优先级低于栈顶符号,则栈顶元素依次出栈并输出,直到遇到左括号或栈空才将吃屎的那个符号入栈。
*/
while ( c != '#' )
{
while ( c >= '0' && c <= '9' ) // 输入的是数字(连续输入,不止一位的数字)
{
printf("%c", c);
scanf("%c", &c);
if ( c < '0' || c > '9' ) // 数字输入结束
{
printf(" ");
}
}
// 输入的是符号
if ( ')' == c ) // 符号中括号的优先级最高,优先出栈
{
Pop(&t, &d); // 栈不为空
// 不是(时打印。左括号只弹出并不输出。只有在遇到" ) "的情况下我们才弹出" ( ",其他情况我们都不会弹出" ( "。
while ( '(' != d )
{
printf("%c ", d);
Pop(&t, &d);
}
}
else if ( '-' == c || '+' == c ) // 乘除优先级高于加减,先出栈
{
if ( !(Len(t)) ) // 空栈,符号直接入栈
{
Push(&t, c);
}
else // 非空栈,部分元素可能需要出栈
{
do
{
Pop(&t, &d);
if ( '(' == d ) // 加减在括号内部
{
Push(&t, d);
}
else // +-*/
{
printf("%c ", d);
}
} while ( Len(t) && '(' != d ); // 循环至少执行一次
// do-while == while + 1
Push(&t, c); // 判断后入栈
}
}
else if ( '*' == c || '/' == c || '(' == c)
{
Push(&t, c);
}
else if ( '#' == c ) // 再过滤一次,否则 # 报错
{
break;
}
else // 要求输入英文括号
{
printf("\n出错:输入格式错误!\n");
return -1;
}
scanf("%c", &c);
}
while ( Len(t) )
{
Pop(&t, &d);
printf("%c ", d);
}
return 0;
}
~~~
### 队列
#### 概念
- 与栈不同,队列Queue是只允许在一端进行插入操作,而在另一端进行删除操作的线性表。如输入缓冲区的实现;
- 栈常用顺序表实现,队列常用链表实现。约定队尾插入,队头删除。
#### 链式队列实现
~~~c
void InitQueue( LinkQueue *q )
{
q->front = q->rear = (Node*)malloc(sizeof(Node));
if ( !(q->front) )
{
exit(0);
}
q->front->next = NULL; // rear的next可以不指定
}
void InsertQueue( LinkQueue *q, ElemType e ) // 尾插法
{
Node *p = (Node*)malloc(sizeof(Node));
if ( !p )
{
exit(0);
}
p->data = e;
p->next = NULL;
q->rear->next = p;
q->rear = p;
}
void DeleteQueue( LinkQueue *q, ElemType *e ) // 头删法
{
if ( q->front == q->rear ) // 空队列
{
exit(0);
}
Node *p = q->front->next; // q->front不存储数据
*e = p->data;
q->front->next = p->next;
if ( q->rear == p ) // 队列只有一个元素。删除以后只剩下头结点
{
// q->rear->next = NULL;
q->rear = q->front;
}
free(p);
}
~~~
#### 循环队列实现
- 顺序存储的队列(数组)队尾插入的时间复杂度为O(1),而队头删除的时间复杂度为O(n)。因为队头不动;
- 当队头可移动时,会出现假溢出的风险,即队尾到了数组尾部,同时造成内存浪费。如下图所示,因此提出循环队列;
- 循环队列的容量是固定的,并且它的队头和队尾指针都可以随着元素入出队列而发生改变,这样循环队列逻辑上就好像是一个环形存储空间。队尾指向可入列的位置;
- 让front或rear指针不断加1,即时超出了地址范围,也会自动从头开始。我们可以采取取模运算处理。取模运算的值永远不会大于除数;
- 根据重合无法区分队列为空或是满,因此队列数组的最后一个存储空间不用。如图所示,假设数组的存数空间为7,此时已经存放1,a,5,7,22,90六个元素了,如果在往数组中添加一个元素,则rear=front;此时,队列满与队列空的判断条件front=rear相同,这样的话我们就不能判断队列到底是空还是满了。
解决这个问题有两个办法:一是增加一个参数,用来记录数组中当前元素的个数;第二个办法是,少用一个存储空间,也就是数组的最后一个存数空间不用,当(rear+1)% maxsize=front时,队列满;
- 所有和事件有关的操作都有队列的影子。如可用于缓冲数据。比如,某一时间cpu太忙,收到的数据来不及处理了,这时候就可以把数据先存到循环队列,等cpu不忙了再拿出来处理。

~~~c
typedef struct
{
ElemType *base; // 动态分配内存基地址
int front; // 索引
int rear;
} LoopQueue;
void Init( LoopQueue *q )
{
q->base = (ElemType*)malloc( MAXSIZE * sizeof(ElemType) ); // 动态分配内存基地址
if ( !(q->base) )
{
exit(0);
}
q->front = 0; // 取值范围 0 -- size-1
q->rear = 0;
}
void Insert( LoopQueue *q, ElemType e ) // 尾插法
{
// 根据重合无法区分队列为空或是满,因此队列数组的最后一个存储空间不用
if ( (q->rear+1) % MAXSIZE == q->front ) // 队列满,重合
{
printf("队列已满\n");
// exit(0); // 进程退出
return; // 函数退出
}
q->base[q->rear] = e;
q->rear = (q->rear+1) % MAXSIZE; // 移动到下一位。队尾指向可入列的位置
}
void Delete( LoopQueue *q, ElemType *e )
{
if ( q->rear == q->front ) // 队列空,重合。不存在 (q->rear)%MAXSIZE == q->front
{
printf("队列为空\n");
return;
}
*e = q->base[q->front];
printf("删除元素%d\n", *e);
q->front = (q->front+1) % MAXSIZE;
}
void Traverse( LoopQueue q )
{
// 不满足 rear < front
// int i;
// for ( i = q.front; i < q.rear; i++ )
// {
// printf("%d\t", q.base[i]);
// }
// printf("\n");
LoopQueue *p = &q;
printf("队列内元素依次为:\n");
while ( p->rear != p->front ) // 通过删除结点实现
{
printf("%d\t", p->base[p->front]);
p->front = (p->front+1) % MAXSIZE;
// p->front = p->front + 1; // 死循环
}
printf("\n");
}
~~~
### 递归与分治
- 尽量使用迭代而不是递归。递归内存消耗较大,原因是函数调用时需要入栈出栈,CPU寄存器需要对其进行保存与恢复;
- 将调用自身的函数称作递归函数。递归建立函数副本,消耗时间与内存。递归函数分为调用与回退阶段,顺序相反。
#### 斐波那契数列
- 递归:涉及了大量的重复运算;
- 递归优化:存储重复数据,在时间复杂度上优化,但是需要引入额外的数组,增加了空间复杂度;
- 迭代:使用循环,不仅降低了时间复杂度,并且空间复杂度为常数;
- 调用 time 头文件用于打印程序运行消耗的时间。
~~~c
int main()
{
int N = 45; // 从0开始,第 N+1 个元素
// 递归消耗的时间
clock_t recursion_start_time = clock();
long result_recursion = Fib_recursion_1(N);
clock_t recursion_end_time = clock();
// 输出递归消耗的时间
printf("Result of recursion: %ld \nTime: %f seconds", result_recursion,
(double)(recursion_end_time-recursion_start_time) / CLOCKS_PER_SEC
);
printf("\n-----------------------\n");
int arr[N+1];
int i;
for ( i = 0; i <= N; i++ ) // 数组初始化
{
arr[i] = 0;
}
// 递归优化后消耗的时间
recursion_start_time = clock();
// ERROR variable-sized object may not be initialized
// 在C中,使用变量来定义数组长度时,这个数组可以定义,却不能同时进行初始化赋值,需要在之后赋值。
result_recursion = Fib_recursion_2(N, arr);
recursion_end_time = clock();
// 输出递归优化后消耗的时间
printf("Result of recursion: %ld \nTime: %f seconds", result_recursion,
(double)(recursion_end_time-recursion_start_time) / CLOCKS_PER_SEC
);
printf("\n-----------------------\n");
// 迭代消耗的时间
clock_t iteration_start_time = clock();
long result_iteration = Fib_iteration(N);
clock_t iteration_end_time = clock();
// 输出迭代消耗的时间
printf("Result of iteration: %ld \nTime: %f seconds", result_iteration,
(double)(iteration_end_time-iteration_start_time) / CLOCKS_PER_SEC
);
return 0;
}
int Fib_recursion_1(int N)
{
if ( N < 2 )
// return N == 0 ? 0 : 1;
return N;
return Fib_recursion_1(N-1) + Fib_recursion_1(N-2);
}
int Fib_recursion_2(int N, int arr[])
{
if ( arr[N] == 0 )
{
if ( N < 2 )
{
arr[N] = N;
}
else{
arr[N] = Fib_recursion_2(N-1, arr) + Fib_recursion_2(N-2, arr);
}
}
return arr[N];
}
int Fib_iteration(int N)
{
if ( N < 2 )
{
return N;
}
long m = 0;
long n = 1;
long temp;
int i;
for ( i=2; i<=N; i++ )
{
temp = m;
m = n;
n = temp + n;
}
return n;
}
~~~
#### 字符串逆序
先使用递归实现,再使用栈实现。
~~~c
int main()
{
char c;
printf("请选择实现方式,输入1表示使用递归实现,输入2表示使用栈实现:\n");
scanf("%c", &c);
switch (c)
{
case '1':
printf("请输入字符串,以#结尾:\n");
Print();
break;
case '2':
printf("请输入字符串,以#结尾:\n");
Stack s;
InitStack(&s);
ReverseStack(&s);
break;
}
return 0;
}
void Print()
{
char c;
scanf("%c", &c);
if ( c != '#')
{
Print(); // 递归
}
if ( c != '#' ) // 逆序输出
{
printf("%c", c);
}
}
void ReverseStack(Stack *s)
{
char c;
scanf("%c", &c);
while ( c != '#' )
{
PushStack(s, c);
scanf("%c", &c);
}
do
{
PopStack(s, &c);
printf("%c", c);
} while ( s->size != 0);
printf("\n");
}
~~~
#### 汉诺塔问题
分治思想,各个小模块通常具有与大问题相同的结构,这种特性也使递归技术有了用武之地。
实现汉诺塔算法可以简单分为三个步骤:
- 把n-1个盘子由A 移到 B;
- 把第n个盘子由 A移到 C;
- 把n-1个盘子由B 移到 C。
如图所示是当 n=3 时的移动步骤:

而当 n=4 时,也就是移完发现左边柱子下面又蹦出来一个盘子的情况下,可以把中间的柱子看成目标柱,然后把最大的移到右边, 然后就和搬三个一模一样了。

~~~c
// 将 n 个盘子从 x 借助 y 移动到 z
void move( int n, char x, char y, char z )
{
if ( 1 == n )
{
printf("%c-->%c\n", x, z);
}
else
{
move( n-1, x, z, y ); // 将 n-1 个盘子从 x 借助 z 移到 y 上
printf("%c-->%c\n", x, z); // 将 第 n 个盘子从 x 移到 z 上
move( n-1, y, x, z ); // 将 n-1 个盘子从 y 借助 x 移到 z 上
}
}
~~~
#### 八皇后问题
回溯算法的典型例题,先用递归算法求解。
深度优先。
本算法的思路是按行来规定皇后位置,第一行放置一个皇后,第二行放置一个皇后, 第N行也放置一个皇后… 这样, 可以保证每行都有一个皇后,那么各行的皇后应该放置在那一列呢, 算法通过循环来完成,在循环的过程中, 一旦找到一个合适的列,则该行的皇后位置确定,则继续进行下一行的皇后的位置的确定。由于每一行确定皇后位置的方式相似,所以可以使用递归法。一旦最后一行的皇后位置确定,则可以得到一组解。
找到一组解之后, 之前确定皇后应该放置在哪一列的循环其实才进行了一轮循环的, 算法通过该循环遍历所有的列,以此确定每一行所有可能的列的位置。在从一轮循环进入下一轮循环之前,算法需要清除在上一轮被标记为不可放置皇后的标记,也就是回溯。因为进入下一轮循环之后,同一行的皇后的列的位置会发生了变化,之前被标记为不可放置皇后的列和正反对角线位置都已经失效。
~~~c
int count = 0;
int notDanger( int row, int j, int (*chess)[8] ) // 危险:同行同列、对角线
{
// 同行、下方(左下方、右下方)天然成立,不需要检查
// 同列
int i;
for ( i=0; i<row; i++ ) // i为行,检查当前行之前的行
{
// if ( *(*(chess+i)+j) != 0 )
if ( chess[i][j] != 0 )
{
return 0;
}
}
int k;
for ( i=row, k=j; i>=0 && k>=0; i--, k-- ) // 左上方
{
// if ( *(*(chess+i)+k) != 0 )
if ( chess[i][k] != 0 )
{
return 0;
}
}
for ( i=row, k=j; i>=0 && k<8; i--, k++ ) // 右上方
{
// if ( *(*(chess+i)+k) != 0 )
if ( chess[i][k] != 0 )
{
return 0;
}
}
return 1; // 没有危险
}
// row当前行
// col所有列
// 参数(*chess)[8]: 表示指向棋盘每一行的指针。行为指针,列为数组
void EightQueen( int row, int col, int (*chess)[8] )
{
int temp[8][8];
int i, j;
for ( i=0; i<8; i++ )
{
for ( j=0; j<8; j++ )
{
temp[i][j] = chess[i][j]; // 初始化
}
}
if ( 8 == row ) // row 0-7 一种方法结束,递归的结束条件
{
printf("第 %d 种具体方案如下:\n", count+1); // count从0开始
for ( i=0; i<8; i++ ) // 行
{
for ( j=0; j<8; j++ ) // 列
{
printf("%d ", temp[i][j]); // wrong!?
// printf("%d ", *(*(temp+i)+j));
}
printf("\n");
}
printf("\n");
count ++;
}
else // 开始递归
{
for ( j=0; j<col; j++ ) // 当前行的所有列
{
// 判断是否危险 row行j列 判断该行中的所有列是否危险 (危险返回 0, 安全返回 1)
if ( notDanger(row, j, chess) ) // 没有危险。第一次是chess,之后是temp
{
for ( i=0; i<8; i++ )
{
// *(*(temp+row)+i) = 0;
temp[row][i] = 0;
}
// *(*(temp+row)+j) = 1; // 放置皇后
temp[row][j] = 1;
EightQueen( row+1, col, temp ); // 下一行,因为一行一定只有一个安全的位置
}
}
}
}
int main()
{
int chess[8][8];
int i, j;
for ( i=0; i<8; i++ )
{
for ( j=0; j<8; j++ )
{
chess[i][j] = 0; // 初始化
}
}
EightQueen( 0, 8, chess );
printf("解决方法共 %d 种\n", count);
return 0;
}
~~~
### 字符串
#### 概念
刚开始的计算机都是处理数值工作,后来引入了字符串的概念,计算机开始可以处理非数值的概念了(当然原理还是用数值来模拟非数值,通过ASCII码表)。
标准 ASCII 码使用 7 个二进位对字符进行编码。基本的 ASCII字符集共有 128 个字符,其中有 96 个可打印字符,包括常用的字母、数字、标点符号等,另外还有 32 个控制字符。虽然标准 ASCII 码是 7 位编码,但由于计算机基本处理单位为字节(1byte = 8bit),所以一般仍以一个字节来存放一个 ASCII 字符。每一个字节中多余出来的一位(最高位)在计算机内部通常保持为 0(在数据传输时可用作奇偶校验位)。
常见字符的ASCII码值如下:
- 空格的ASCII码值为32;
- 数字0到9的ASCII码值为48到57;
- 大写字母“A”到“Z”的ASCII码值为65到90;
- 小写字母“a”到“z”的ASCII码值为97到122。即小写字母大于大写字母;
记住很重要的一点,单引号是字符型,双引号是字符串型。
字符串比较大小时比的就是字符串里每个字符的ASCII码大小。主要是通过模式匹配判断是否相等。
通常使用顺序存储结构进行存储。
#### BF算法
属于朴素的模式匹配算法,效率较低。
BF算法在进行模式匹配时,从主串的第一个字符开始,每次失败,模式串向后移动一个字符的位置,继续匹配**(回溯法)**。但是整个算法受测试数据的影响非常大,在解决实际问题时,由于数据量庞大,时间复杂度往往会很高。
具体示例如图所示:

时间复杂度:
- “BF” 算法在最理想的情况下的时间复杂度为O(m)( m 是模式串的长度,也就是第一次匹配就成功的情况)。
- 一般情况下,"BF"算法的时间复杂度为O(n+m)(n是主串的长度,m是模式串的长度)。
- 最坏的情况下的时间复杂度为O(n * m)(例如主串 S 为“000000000001”,模式串 T ”001”,每次匹配时,直到匹配最后一个元素,才得知匹配失败,运行了 n*m 次)。
~~~c
// 返回子串T在主串S中第pos个字符之后的位置
int stringIndex( char S[], char T[], int pos )
{
int i = pos; // 主串下标
int j = 0; // 子串下标,取值从0开始,要从1开始需要手动在结构体中设置(字符串使用了第一个元素表示长度的方式,省去末尾的\n)
int m = strlen(S);
int n = strlen(T);
while ( i < m && j < n ) // i或j其中一个到达尾部即终止搜索
{
if ( S[i] == T[j] ) // 若相等则继续下一个元素匹配
{
printf("S[%d] = %c, T[%d] = %c\n", i, S[i], j, T[j]);
i ++;
j ++;
}
else
{
// i ++; // wrong
i = i - j + 1; // i回溯到上次匹配首位的下一个元素,这是效率低下的关键!如当 i=1, j=0 时更新 i=1-0+1=2
j = 0; // 若失配则j回溯到第一个元素重新匹配
}
}
// 跳出循环有两种可能,i=strlen(S)说明已经遍历完主串;j=strlen(T),说明模式串遍历完成,在主串中成功匹配
if ( j == n ) // j=strlen(T)
{
return i - n;
}
else // i=strlen(S)
{
return 0; // 若不存在,则返回0
}
}
int main()
{
char S[] = "IFFamFishc";
char T[] = "Fish";
int pos = 0;
int n = stringIndex(S, T, pos);
printf("T子串在S主串中的起始匹配位置为:%d\n", n);
return 0;
}
~~~
#### KMP算法
**主串索引不动或者向前移动,不会往回倒着走。**
- 核心是避免重复遍历,即避免不必要的回溯;
- 对子串进行自检,决定回溯的多少。回溯即向左移动。子串(模式串)元素不同时,回溯较少,元素相同(即有重复)时,回溯较多;
- 问题由模式串决定,不是由目标决定。模式匹配串称为T串,不需要考虑被匹配串S串(主串);
- 给模式匹配串添加一个k数组(也就是KMP算法中著名的next数组)。k数组指导着模式匹配串下一步改用第几号元素去进行匹配;
- 关注T串前缀后缀重叠的个数,其中前缀后缀是针对失配位置而言的。第一个元素永远是前缀,失配元素的前一个永远是后缀。前缀与后缀是可以相同的;
- 查找字串在主串中的位置。下标等同于后缀,next等同于前缀。
- 回溯:T[6] != T[4]在4处失配。对于4来说,6就是S串,0-4相当于T串。然后根据4处的next值开始递归,回溯到上一个失配串。
[以图中的例子来说](https://www.zhihu.com/question/21923021),在 i 处失配,那么主字符串和模式字符串的前边6位就是相同的。又因为模式字符串的前6位,它的前4位前缀和后4位后缀是相同的,所以我们推知主字符串i之前的4位和模式字符串开头的4位是相同的。就是图中的灰色部分。那这部分就不用再比较了。

**next数组中值的意义是字符串的前缀集合与后缀集合的交集中最长元素的长度**。其实,求next数组的过程完全可以看成字符串匹配的过程,即以模式字符串为主字符串,以模式字符串的前缀为目标字符串,一旦字符串匹配成功,那么当前的next值就是匹配成功的字符串的长度。具体来说,就是从模式字符串的第一位(注意,不包括第0位)开始对自身进行匹配运算。 在任一位置,能匹配的最长长度就是当前位置的next值。如下图所示。

关于为什么要把pmt向左移动1位变成next,我觉得这样比较好理解 -> pmt记录的是 长字符串的后缀(和短字符串的前缀) 的长度,具体到前缀部分的index的时候要-1。
next数组的计算,我理解是p串错开一位匹配,0起始的p串与1起始的p串,前者是瞄准了p的前缀,后者抛弃了p[0]所以是瞄准p的后缀,双方的公共部分即是公共前后缀。
~~~c
void get_next( char T[], int *next )
{
// 前缀固定,后缀相对
int j = -1; // 前缀
int i = 0; // 后缀
int n = strlen(T);
next[0] = -1;
while ( i < n ) // T[3] == T[1]
{
if ( -1 == j || T[i] == T[j] )
{
i ++;
j ++;
next[i] = j; // next[4] = 2
}
else
{
j = next[j]; // 回溯 2 = next[4]
}
}
for ( i=0; i<n; i++ ) // 打印
{
printf("%d\t", next[i]);
}
printf("\n");
}
int index_kmp( char S[], char T[], int pos )
{
int i = pos; // 主串
int j = 0; // 字串
int next[255]; // next数组
get_next( T, next ); // 只执行一次
int m = strlen(S);
int n = strlen(T);
while ( i < m && j < n )
{
if ( -1 == j || S[i] == T[j] )
{
i ++;
j ++;
}
else
{
j = next[j]; // KMP与BF不同之处
}
}
if ( n == j ) // 找到
{
return i - n;
}
else // 没找到
{
return -1;
}
}
~~~
具体的一个例子如图所示:

## 树与图
### 树
#### 概念
- 树:树可以为空。除了根结点外,每个子结点可以分为多个不相交的子树。有根结点的树就有子树,子树有顺序。
- 度:树的度是树的结点的度的最大值,每个结点都有度,度为0的结点为根结点;
- 层次:根结点的层次为1,其余结点的层次等于该结点的双亲结点的层次加1。树中结点的最大层次称为树的高度;
- 叶子结点:一棵树当中没有子结点(即度为0)的结点称为叶子结点,简称“叶子”。 叶子是度为0的结点,又称为终端结点。
#### 树的存储结构
树中的某个结点的孩子可以有多个,所以仅仅使用简单的顺序结构或者链式结构是不能完全表示一整棵树的。充分利用顺序存储结构和链式存储结构的特点,完全可以实现对树的存储结构的表示。
表示一棵树的方法如:双亲表示法,孩子表示法,孩子兄弟表示法。
- 对于双亲表示法:我们先将双亲结点存入,我们每插入一个结点都是知道双亲结点位置的,数据可以直接插入。使用顺序存储结构更加方便;
- 而对于孩子表示法,我们每次插入一个结点,对其子树的位置存放暂不确定,所有使用链式存储结构占主要。
对孩子表示法优化后的双亲孩子表示法查询双亲与孩子的时间复杂度都是O(1),**结合顺序结构与链式结构**,结构如下图所示。之后是结构体定义代码。

~~~c
typedef char ElemType;
// 孩子结点
typedef struct CTNode
{
int child; // 孩子结点的下标
struct CTNode *next; // 指向下一个孩子结点的指针
} *ChildPtr;
// 表中的每一行(表头结构)
typedef struct
{
ElemType data; // 存放在树的结点中的数据
int parent; // 存放双亲的下标
ChildPtr firstchild; // 指向第一个孩子的指针
} CTBox;
// 树结构
typedef struct
{
CTBox nodes[MAX_TREE_SIZE]; // 结点数组
int r; // 根的位置
int n; // 结点个数
} Tree;
~~~
#### 二叉树的种类与性质
- 二叉树:二叉树是每个结点最多有两个子树的树结构;
- 满二叉树:在一棵二叉树中,如果所有分支结点都存在左子树和右子树,并且所有叶子都在同一层上,这样的二叉树称为满二叉树。叶子只能出现在最下一层。非叶子结点的度一定是2;
- 完全二叉树:一棵二叉树中,只有最下面两层结点的度可以小于2,并且最下层的叶结点集中在靠左的若干位置上,这样的二叉树称为完全二叉树。叶子结点只能出现在最下两层。最下层的叶子一定集中在左部连续位置。倒数第二层,若有叶子结点,一定都在右部连续位置。同样结点树的二叉树,完全二叉树的深度最小。显然,一棵满二叉树必定是一棵完全二叉树,而完全二叉树未必是满二叉树。完全二叉树去掉最后一层就是满二叉树;
- 结点数与叶子数的关系:
#### 二叉树的遍历与实现
- 二叉树的存储结构一般采用链式存储结构。即二叉链表,不是数组,使用指针索引。
- 遍历方式有四种:前序遍历、中序遍历、后序遍历、层序遍历,顺序是对于根结点而言。
- 实现二叉树时,如果使用迭代,必须知道树有所深,因此使用递归实现,前序遍历。
- 使用递归时,需要设置递归终止条件,如所有的叶子结点指向 NULL 。
- 为了把一个递归过程改为非递归过程,就需要自己维护一个辅助栈结构,记录遍历时的回退路径。非递归的快速排序的设计依据也是这个。
~~~c
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild, *rchild; // 左子树、右子树
} BiTNode, *BiTree;
// 生成二叉树
void CreateBiTree( BiTree *T )
{
char c;
scanf("%c", &c);
if ( ' ' == c ) // 递归终止条件
{
*T = NULL; // 所有的叶子结点指向 NULL
}
else // 递归
{
*T = (BiTNode*)malloc(sizeof(BiTNode)); // 创建结点
(*T)->data = c;
CreateBiTree(&((*T)->lchild));
CreateBiTree(&((*T)->rchild));
}
}
// 访问二叉树结点的具体操作,level参数可以不要
void visit( char c, int level )
{
printf("%c 位于第 %d层\n", c, level);
}
// 前序遍历
void PreOrderTraverse( BiTree T, int level )
{
// 若二叉树为空,遍历结束
if ( T ) // 指针不为空。遍历顺序:根左右
{
visit(T->data, level);
PreOrderTraverse(T->lchild, level+1);
PreOrderTraverse(T->rchild, level+1);
}
}
int main()
{
int level;
BiTree T = NULL; // T表示二叉树。树的地址
CreateBiTree(&T); // AB D CE ;
level = 1;
PreOrderTraverse(T, level);
return 0;
}
~~~
#### [线索二叉树](https://blog.csdn.net/u014492609/article/details/40477795)
二叉树叶子结点的空指针浪费空间。对于完全二叉树,中序遍历每隔一个可以存放前驱与后继结点。
因此需要识别存放指针还是存放线索。存线索指的是存放前驱或后继。
**有了线索二叉树后,对它进行遍历时,其实就等于操作一个双向链表结构。**因此,如果所用的二叉树需要经过遍历或查找结点时需要某种遍历序列中的前驱和后继,那么采用线索二叉链表的存储结构就是非常不错的选择。
标记ltag与rtag取值为0或1。为0时表示有孩子。为1时表示是叶子结点,存在空指针。如:
- ltag为0时指向该结点的左孩子,为1时指向该结点的前驱。
- rtag为0时指向该结点的右孩子,为1时指向该结点的后继。
- 借助标记完成二叉树中序遍历的迭代实现。

~~~c
// 线索存储标志位
// Link(0):表示指向左右孩子的指针
// Thread(1):表示指向前驱后继的线索
typedef enum {Link, Thread} PointerTag;
typedef struct BiThrNode
{
char data;
struct BiThrNode *lchild, *rchild;
PointerTag ltag, rtag;
} BiThrNode, *BiThrTree;
// 全局变量,始终指向刚刚访问过的结点
BiThrTree pre;
// 创建一棵二叉树,约定用户遵照前序遍历的方式输入数据
void CreateBiThrTree( BiThrTree *T )
{
char c;
scanf("%c", &c);
if( ' ' == c )
{
*T = NULL;
}
else
{
*T = (BiThrNode *)malloc(sizeof(BiThrNode));
(*T)->data = c;
(*T)->ltag = Link;
(*T)->rtag = Link;
CreateBiThrTree(&(*T)->lchild);
CreateBiThrTree(&(*T)->rchild);
}
}
// 中序遍历线索化
void InThreading(BiThrTree T)
{
if( T )
{
InThreading( T->lchild ); // 递归左孩子线索化
if( !T->lchild ) // 如果该结点没有左孩子,设置ltag为Thread,并把lchild指向刚刚访问的结点。
{
T->ltag = Thread;
T->lchild = pre; // 前驱变量
}
if( !pre->rchild )
{
pre->rtag = Thread;
pre->rchild = T;
}
pre = T;
InThreading( T->rchild ); // 递归右孩子线索化
}
}
// 构造头指针,pre初始化
// 头结点左链lchild指向根结点,头结点右链rchild指向中序遍历的最后一个结点
void InOrderThreading( BiThrTree *p, BiThrTree T )
{
*p = (BiThrTree)malloc(sizeof(BiThrNode));
(*p)->ltag = Link;
(*p)->rtag = Thread; // 线索
(*p)->rchild = *p;
if( !T ) // 空树
{
(*p)->lchild = *p; // 指向本身
}
else
{
(*p)->lchild = T; // 指向二叉树根节点
pre = *p; // 初始化赋值
InThreading(T);
pre->rchild = *p; // pre指向最后一个叶子结点
pre->rtag = Thread;
(*p)->rchild = pre;
}
}
void visit( char c )
{
printf("%c", c);
}
// 中序遍历二叉树,非递归
void InOrderTraverse( BiThrTree T )
{
BiThrTree p;
p = T->lchild;
while( p != T )
{
while( p->ltag == Link )
{
p = p->lchild;
}
visit(p->data);
while( p->rtag == Thread && p->rchild != T )
{
p = p->rchild;
visit(p->data);
}
p = p->rchild;
}
}
int main()
{
BiThrTree P, T = NULL; // 二叉树根节点
CreateBiThrTree( &T );
InOrderThreading( &P, T );
printf("中序遍历输出结果为: ");
InOrderTraverse( P );
printf("\n");
return 0;
}
~~~
#### 赫夫曼树
- 赫夫曼编码:Huffman 是首个实用的数据无损压缩解决方案。赫夫曼编码基于赫夫曼树构成。
- 带权结点:二叉树叶子结点带权,树结点间的连线相关的数叫做权 Weight。也可以理解为长度或重量。
- 路径:在一棵树中,一个结点到另一个结点之间的通路,称为路径。在一条路径中,每经过一个结点,路径长度都要加 1 。
- 树的带权路径长度 WPL:Weighted Path Length 是树中所有叶子结点的带权路径长度之和。WPL的值越小,说明构造出来的二叉树性能越优。**赫夫曼树就是最优二叉树。**
- 定长编码:如ASCII编码。频率高的字符占用大量内存。
- 变长编码:单个编码的长度不一致,可以根据整体出现频率来调节。频率高的字符长度短。
- 前缀码:所谓的前缀码,就是没有任何码字是其他码字的前缀,设计长短不等的编码。前后不会冲突。由哈夫曼树求得的编码为最优前缀码。每个叶子表示的字符的编码,就是从根到叶子的路径上的标号依次相连所形成的编码,显然这就是该字符的最优前缀码。变长编码可能使解码产生二义性,而前缀码的出现很好地解决了这个问题。
如用于解决远距离通信(电报)的数据传输的最优化问题。对于文字内容”ABCDEF”,赫夫曼编码的步骤包括:
1. 原编码二进制串:通过二进制数据表示如下。

2. 构造哈夫曼树:因为每个字母的出现频率是不同的,假设给每个字母分配权值:A:27,B:8,C:15,D:15,E:30,F:5,首先按照它们的权值进行构造哈夫曼树。每次选择权值最小和次小的根结点,作为左右子树合并为一棵新的树。如下所示:

3. 编码:将所有权值左分支改为0,右分支改为1,进行编码。求得每个字符的哈夫曼编码,有了每个字符的哈夫曼编码,我们就可以制作一个该字符集的哈夫曼编码表。

4. 新编码二进制串:得到相应字符的的传输数据。同时,可以根据赫夫曼树实现解码。其过程是:依次读入文件的二进制码,从赫夫曼树的根结点出发,若当前读入0,则走向左孩子,否则走向右孩子。一旦到达某一叶子时便译出相应的字符。然后重新从根出发继续译码,直至文件结束。

### 图
#### 概念
- 线性表中我们把数据元素叫元素,树中叫结点,在图中数据元素我们则称之为顶点(Vertex);
- 线性表中,相邻的数据元素之间具有线性关系,树结构中,相邻两层的结点具有层次关系,而图结构中,任意两个顶点之间都可能有关系,顶点之间的逻辑关系用边来表示,边集可以是空的;
- 图(Graph)是由顶点的有穷非空集合和顶点之间边的集合组成,通常表示为:G{V,E},其中,G表示一个图,V是图G中顶点的集合,E是图G中边的集合;
- 无向边(Edge),用无序偶(Vi,Vj)来表示。有向边称为弧(Arc),用有序偶<Vi,Vj>来表示,Vi称为弧尾,Vj称为弧头。**箭头从弧尾指向弧头**;
- 有些图的边或弧带有与它相关的数字,这种与图的边或弧相关的数叫做权(Weight),带权的图通常称为网(Network);
- 顶点V的度(Degree)是和V相关联的边的数目,记为TD(V);
- 从顶点V1到顶点V2的路径(Path)的长度是路径上的边或弧的数目;
- 在无向图G中,如果从顶点V1到顶点V2有路径,则称V1和V2是连通的,如果对于图中任意两个顶点Vi和Vj都是连通的,则称G是连通图(ConnectedGraph);
- 一个连通图的生成树是一个极小的连通子图,它含有图中全部的n个顶点,但只有足以构成一棵树的n-1条边;
- 如果一个有向图恰有一个顶点入度为0,其余顶点的入度均为1,则是一棵有向树。
#### 图的存储结构--邻接矩阵
- 图的邻接矩阵(Adjacency Matrix)存储方式是用两个数组来表示图。一个一维数组存储图中顶点信息,一个二维数组(称为邻接矩阵)存储图中的边或弧的信息。
- 无向图不分行列,边数组arc[4] [4]为对称矩阵(0表示不存在顶点间的边,1表示顶点间存在边)。
- 有向图分行列,边数组arc[4] [4]是非对称矩阵。
- 每条边上带有权的图就叫网(是无穷值代表没边,其它的话代表权值)。
~~~c
#define MAXVEX 100 // 最大顶点数
#define INFINITY 65535 // 用65535来代表无穷大
typedef char VertexType; // 顶点类型应由用户定义
typedef int EdgeType; // 边上的权值类型应由用户定义
typedef struct Graph
{
VertexType vexs[MAXVEX]; // 顶点表
EdgeType arc[MAXVEX][MAXVEX]; // 邻接矩阵
int numVertexs, numEdges; // 图中当前的顶点数和边数
} Graph;
void CreateGraph(Graph *G)
{
printf("请输入顶点数与边数:\n");
scanf("%d %d", &(G->numVertexs), &(G->numEdges));
int i, j;
// 顶点表赋值
printf("请输入顶点字符:\n");
getchar();
for ( i=0; i<G->numVertexs; i++ )
{
scanf("%c", &(G->vexs[i])); // 输入字符之间无空格
}
// 初始化
for ( i=0; i<G->numVertexs; i++)
{
for ( j=0; j<G->numVertexs; j++ )
{
G->arc[i][j] = INFINITY;
}
}
VertexType startVertex, endVertex;
int startIndex, endIndex;
int weight;
// 邻接矩阵赋值
printf("请输入起始与结束顶点字符以及权重:\n"); // (V1, V2)
getchar();
for ( i=0; i<G->numEdges; i++ )
{
scanf("%c %c %d", &startVertex, &endVertex, &weight);
getchar(); // 输入完按下回车键,回车键\n会影响给下一次scanf()
// 查找顶点所在位置,即邻接矩阵的行与列
for ( j=0; j<G->numVertexs; j++ )
{
if ( startVertex == G->vexs[j] )
{
startIndex = j;
}
if ( endVertex == G->vexs[j] )
{
endIndex = j;
}
}
G->arc[startIndex][endIndex] = weight;
// 如果是无向图,需要双向保存
G->arc[endIndex][startIndex] = weight;
}
}
~~~
#### 图的存储结构--邻接表
- 对于稀疏图(节点多,连边少),寻找一个点能连到的所有点代价非常大,需要把矩阵整个一行都遍历一遍。此外,邻接矩阵的存储需要空间也恒定为点数量的平方,对于稀疏图而言,矩阵中会存在大量0表示两个点之间没有连线,这样会存在非常大的空间浪费。
- 图的邻接表存储方式是将数组与链表结合。一个一维数组存储图中顶点信息,称为**顶点表**,另外,对于顶点数组中,每个数据元素还需要存储指向第一个邻接点的指针,以便于查找该顶点的边信息。
- 用单链表存储顶点的邻接点。由于邻接点的个数不定,所以用单链表存储,无向图称为顶点的**边表**,有向图称为顶点作为弧尾的出边表。缺点是不能沿着边反着找,因此当要求弧头时需要建立逆邻接表。
如图所示是无向网图:

上图中a-c之间也有条边,权重为2。
邻接表中数据的存储图示如下:

~~~c
//邻接表的时间复杂度:n为顶点数,e为边数 O(n + e)
#define MAXVEX 100
typedef char VertexType; // 顶点类型应由用户定义
typedef int EdgeType; // 边上的权值类型应由用户定义
typedef struct EdgeNode // 边表结点
{
int adjvex; // 邻接点域,存储该顶点对应的下标
int weight; // 用于存储权值
struct EdgeNode *next; // 链域,指向下一个邻接点
} EdgeNode;
typedef struct VertexNode // 顶点结点
{
VertexType data; // 存储顶点数据的信息
struct EdgeNode *first; // 边表头指针
} VertexNode, AdjList[MAXVEX];
typedef struct // 图
{
AdjList adjList; // 定义邻接表
int numVertexs; // 当前邻接表的顶点数
int numEdges; // 当前邻接表的边数
} GraphAdjList;
void CreateALGraph( GraphAdjList *G )
{
printf("请输入顶点数与边数:\n");
scanf("%d %d", &(G->numVertexs), &(G->numEdges));
int i;
printf("请输入顶点字符:\n");
getchar();
for ( i=0; i<G->numVertexs; i++ )
{
scanf("%c", &(G->adjList[i].data)); // G->adjList[i]是值,不是地址
G->adjList[i].first = NULL;
}
int j, k, m;
EdgeNode *e;
printf("请输入边(Vi,Vj)上的下标i,下标j以及权重:\n");
getchar();
for ( i=0; i<G->numEdges; i++ )
{
scanf("%d %d %d", &j, &k, &m);
e = (EdgeNode*)malloc(sizeof(EdgeNode));
e->adjvex = k;
e->weight = m;
e->next = G->adjList[j].first; // 单链表头插法
G->adjList[j].first = e;
e = (EdgeNode*)malloc(sizeof(EdgeNode));
e->adjvex = j;
e->weight = m;
e->next = G->adjList[k].first; // 无向图双向保存
G->adjList[k].first = e;
}
}
void PrintALGraph(GraphAdjList G)
{
int i;
for ( i=0; i<G.numVertexs; i++ )
{
EdgeNode *e = G.adjList[i].first;
printf("%c\t", G.adjList[i].data);
while ( e )
{
printf("%d %d\t", e->adjvex, e->weight);
e = e->next;
}
printf("\n");
}
}
~~~
#### 图的存储结构--十字链表
优化有向图的存储结构。十字链表(Orthogonal List)把邻接表和逆邻接表整合在了一起。这样既容易找到以Vi为尾的弧,也容易找到以Vi为头的弧,因而容易求得顶点的出度和入度。
#### 深度优先遍历
图的遍历,按照一定的原则逐一访问,满足不重不漏的原则。
深度优先遍历(DepthFirstSearch),也有称为深度优先搜索,简称为DFS。类似于回溯法,一条路走到黑。
两种实现方式,基于邻接矩阵与基于邻接表。
类似于树的前序遍历。可以借助栈实现。
~~~~c
~~~~
#### 骑士周游问题
国际象棋的棋盘为8*8的方格棋盘,现将“马”放在任意指定的方格中,按照“马”走棋的规则将“马”进行移动。要求每个方格只能进入一次,最终使得“马”走遍棋盘64个方格,用1~64来标注“马”移动的路径。
哈密尔顿路径指的是经过图中每个顶点,且只经过一次的一条轨迹。如果这条轨迹是一条闭合的路径(从起点出发不重复地遍历所有点后仍能回到起始点),那么这条路径称为哈密尔顿回路。
涉及到递归、回溯。
~~~c
~~~
#### 广度优先遍历
广度优先遍历(BreadthFirstSearch),又称为广度优先搜索,简称BFS。采用逐步扩大查找的范围的方式。
类似于树的层序遍历。
广度优先遍历需要借助于另外的数据结构队列。当把图中的顶点放到队列中时,表示这个顶点被遍历了(可以把顶点的值打印出来)。
~~~c
// 实现不使用递归,使用队列
void BFSTraverse( MatrixGraph G )
{
int i, j;
for ( i=0; i<G.numVertexs; i++ )
{
visited[i] = FALSE;
}
Queue Q;
InitQueue(&Q);
i = 0; // 起点
printf("%c\t", G.vexs[i]);
visited[i] = TRUE;
EnQueue(&Q, i);
while ( !QueueEmpty( Q ) ) // 队列非空
{
DeQueue(&Q, &i);
// printf("\ni=%d, %c出队列\n", i, G.vexs[i]);
for ( j=0; j<G.numVertexs; j++ ) // 邻接矩阵的第i行
{
if ( 1 == G.arc[i][j] && !visited[j] )
{
printf("%c\t", G.vexs[j]);
visited[j] = TRUE;
EnQueue(&Q, j);
}
}
}
}
~~~
#### [迪杰斯特拉算法](https://blog.csdn.net/qq_35644234/article/details/60870719)
从图中的某个顶点出发到达另外一个顶点的所经过的边的权重和最小的一条路径,称为最短路径。
逐个顶点计算,贪心算法。
如图所示,要求V0到V8的最短路径时并不是一下子就求出了V0到V8的最短路径,而是一步步求出它们之间顶点的最短路径,过程中都是基于已经求出的最短路径的基础上,求得更远顶点的最短路径,最终得到要的结果。

~~~c
typedef int Patharc[MAXVEX]; // 用于存储最短路径下标的数组
typedef int ShortPathTabel[MAXVEX]; // 用于存储到各点最短路径的权值和
void ShortestPath_Dijkstra( MGraph G, int start, Patharc *P, ShortPathTabel *D )
{
int final[MAXVEX]; // final[w] = 1 表示已经求得顶点V0到Vw的最短路径,0为没有找到
int i, j, k, min;
// 初始化
for ( i=0; i<G.numVertex; i++ )
{
(*D)[i] = G.arc[start][i]; // 将与V0点有连线的顶点加上权值
(*P)[i] = 0; // 初始化路径数组P为0
final[i] = 0; // 全部顶点初始化为未找到最短路径
}
// 起点
final[start] = 1; // V0至V0的路径为0
(*D)[start] = 0; // V0至V0不需要求路径
// 开始主循环,每次求得V0到某个Vv顶点的最短路径
for ( i=0; i<G.numVertex; i++ )
{
min = INFINITY;
// 选择最小权值和的顶点k作为下一个点。贪心算法
for ( j=0; j<G.numVertex; j++ )
{
if ( !final[j] && (*D)[j] < min )
{
min = (*D)[j];
k = j;
}
}
final[k] = 1; // 将目前找到的最近的顶点置1
// 对与k顶点连通的顶点进行松弛处理。修正当前最短路径及距离
for ( j=0; j<G.numVertex; j++ )
{
if ( !final[j] && (min + G.arc[k][j]) < (*D)[j] )
{
(*D)[j] = min + G.arc[k][j]; // 修改当前路径长度。经过判断后不走V0->V2
(*P)[j] = k; // 存放前驱顶点。如V0->V1->V2
}
}
}
// 打印测试
printf("final:\n");
for ( i=0; i<G.numVertex; i++ )
{
printf("%d\t", final[i]);
}
printf("\n");
}
~~~
## 查找与排序
### 查找
#### 散列表(哈希表)查找
1. 概念
- 顺序表与有序表的查找都需要比较。各个记录之间存在逻辑关系;
- 散列表不需要进行比较与迭代。各个记录之间不存在逻辑关系。
散列表是**在记录的存储位置与它的关键字之间建立一个确定的对应关系f(哈希函数)**,使得每一个关键字key对应一个存储位置f(key)。采用散列技术将记录存储在一块连续的存储空间中,这块连续存储空间称为散列表或哈希表(hash table)。**哈希表简单来说就是一张带索引和存储空间的表。**适用于一对一的查找。缺点是key与value都不可以重复。
2. 散列函数的构造
基本原则:计算简单、散列地址分布均匀。
- 直接定址法:取关键字的某个线性函数值作为散列地址,即:f(key) = a * key + b,适用于知道关键字分布同时位数较小;
- 数字分析法:适合处理关键字位数比较大的情况,如抽取手机号的后四位作为真正的用户编号作为散列地址;
- 平方取中法:将关键字平方之后取中间若干位数字作为散列地址,适用于不知道关键字分布,但位数较小;
- 除留余数法:最常用的构造散列函数方法,对于长度为m的散列函数计算公式为:f(key) = key mod p(p<=m)。p的选择是关键,需要解决冲突;
- 随机数法:取关键字的随机函数值作为散列地址,即:f(key) = random(key)。适用于关键字长度不等的情况,如字符串。
3. 处理散列冲突的方法
冲突:当 key1 != key2时,f(key1) == f(key2)。
- 开放地址法:散列表足够大,发生冲突时,寻找下一个空的散列地址。公式:fi(key) = (f(key)+di) mod m (di=1^2, -1^2, 2^2, -2^2…, q^2, -q^2,q<=m/2),设置位移量di的取值方法可以解决堆积问题;
- 再散列函数:公式:fi(key) = RHi(key) (i=1, 2…k),多个散列函数;
- 公共溢出区法:有两张表,基本表与溢出表。
4. 散列表查找实现代码
~~~c
#define HASHSIZE 12
#define NULLKEY -32768
typedef struct
{
int *elem; // 数据元素的基址,动态分配数组
int count; // 当前数据元素的个数
}HashTable;
int InitHashTable(HashTable *H)
{
H->count = HASHSIZE;
H->elem = (int *)malloc(HASHSIZE * sizeof(int));
if( !H->elem ) // 申请空间失败
{
return -1;
}
for( i=0; i < HASHSIZE; i++ ) // 初始化默认值
{
H->elem[i] = NULLKEY;
}
return 0;
}
// 散列函数使用除留余数法
int Hash(int key)
{
return key % HASHSIZE;
}
// 插入关键字到散列表
void InsertHash(HashTable *H, int key)
{
int addr;
addr = Hash(key); // 最简单的偏移地址
while( H->elem[addr] != NULLKEY ) // 如果不为空,则冲突出现
{
addr = (addr + 1) % HASHSIZE; // 开放定址法的线性探测
}
H->elem[addr] = key;
}
// 散列表查找关键字。查到返回0,没查到返回-1
int SearchHash(HashTable H, int key, int *addr)
{
*addr = Hash(key); // 查找效率 O(1)
while( H.elem[*addr] != key ) // 冲突,使用开放定址法线性探测的逆运算
{
*addr = (*addr + 1) % HASHSIZE;
if( H.elem[*addr] == NULLKEY || *addr == Hash(key) ) // 查到最后或者返回原点说明不存在
{
return -1;
}
}
return 0;
}
~~~
#### Python字典实现
对key进行hash的时候,不同的key可能hash出来的结果是一样的,尤其是数据量增多的时候,这个问题叫做哈希冲突。如果解决这种冲突情况呢?通常的做法有两种,一种是链接法,另一种是开放寻址法,Python选择后者。
开放寻址法中,所有的元素都存放在散列表里,当产生哈希冲突时,通过一个**探测函数**计算出下一个候选位置,如果下一个获选位置还是有冲突,那么不断通过探测函数往下找,直到找个一个空槽来存放待插入元素。
字典中的一个key-value键值对元素称为entry(也叫做slots),对应到Python内部是PyDictEntry,PyDictObject就是PyDictEntry的集合。
entry有三种状态,其中Dummy是一种类似的伪删除方式,保证探测链的连续性。
<https://www.cnblogs.com/nelsen-chen/p/9073004.html>
<https://www.hongweipeng.com/index.php/archives/1230/>
<https://blog.csdn.net/qq_33339479/article/details/90446988>
内存布局如图所示:

### 排序
**内部运算包括比较与交换。**
通常将数据元素称为记录。
稳定排序是指相等的数排序完成后,其顺序保持不变。
有两个排序关键字的时候,稳定排序可以让第一个关键字排序的结果服务于第二个关键字排序中数值相等的那些数
如班级同学已经按照学号排好序了。现在要按照身高排序。如果是稳定排序排好之后,身高相同的同学,还是按照学号顺序的。
#### 冒泡排序
- 两两比较相邻记录。每一轮从前往后取出最大值放在末尾,或**从后往前每次将最小值放在头部**;
- 对于原数列顺序的情况可以设置flag进行优化,可以减少比较的次数。
~~~c
void BubbleSort( int list[], int n )
{
int i, j;
int temp;
int count1 = 0, count2 = 0; // 设置计数器
int flag = 1; // 优化2
// int length = sizeof(list) / sizeof(list[0]); // func, 8, 4
// printf("%d, %d\n", sizeof(list), sizeof(list[0])); // main, 20, 4
// int len; // 优化1,从后往前时不需要该变量
// len = n;
for ( i=0; i<n-1 && flag; i++ )
{
flag = 0;
// for ( j=0; j<len-i,; j++)
for ( j=n-1; j>i; j-- ) // 优化1
{
// flag = 0; // 位置错误,如[1,5,3,4]。循环只执行一次
count1++; // 记录比较次数
if ( list[j-1] > list[j] )
{
flag = 1;
count2++; // 记录交换次数
temp = list[j-1];
list[j-1] = list[j];
list[j] = temp;
}
}
}
printf("总共进行了 %d 次比较与 %d 次交换\n", count1, count2);
}
~~~
#### 选择排序
- 冒泡排序交换次数较多。选择排序每一轮只进行最多一次的交换,相应比较次数增多;
- 左边为有序区,右边为无序区。开始时数组第一个元素为有序区,其余为无序区。**每轮选出无序区的最小值**,放入左边的有序区。也就是说**比较发生在无序区**。
- 当**记录本身基本有序**时,选择排序的算法复杂度依然较高。
~~~c
void SelectSort( int list[], int n )
{
int i, j, min, temp, count1 = 0, count2 = 0;
for ( i=0; i<n-1; i++ ) // i之前为有序区,循环终止条件为 j<n-1
{
min = i;
for ( j=i+1; j<n; j++ ) // 循环终止条件为 j<n 而非 j<n-1
{
count1++;
if ( list[j] < list[min] )
{
min = j;
}
}
count1++;
if ( min != i ) // 交换
{
count2++;
temp = list[i];
list[i] = list[min];
list[min] = temp;
}
}
printf("总共进行了 %d 次比较与 %d 次交换\n", count1, count2);
}
~~~
#### 插入排序
插入排序类似于扑克牌的排序。如图所示:

- 左边为有序区,右边为无序区。开始时数组第一个元素为有序区,其余为无序区。**每轮取无序区的第一个元素**,放入有序区的正确位置。也就是说**比较发生在有序区**;
- 每轮操作时并不需要真的进行完整交换,只需把较小的元素暂存起来,再**把有序区的元素从右向左逐一复制**,减少不必要的交换;
- 当**记录本身基本有序或记录数少**时,插入排序的算法复杂度低。插入排序是简单排序算法中性能最好的。
插入排序的整个过程如图所示:

~~~c
void InsertSort( int list[], int n )
{
int i, j, temp;
// for ( i=0; i<n-1; i++ )
// {
// for ( j=i+1; j>0; j-- )
// {
// count1++;
// if ( list[j-1] > list[j] )
// {
// count2++;
// temp = list[j-1];
// list[j-1] = list[j];
// list[j] = temp;
// }
// }
// }
// 优化,较少不必要的交换
for ( i=1; i<n; i++ ) // i之前为有序区,循环 i从1 开始
{
if ( list[i] < list[i-1] )
{
temp = list[i]; // 将较小的数取出,之后将放在正确的位置上
for ( j=i-1; list[j]>temp; j-- ) // 向后移动,不需要交换
{
list[j+1] = list[j];
}
list[j+1] = temp; // j--后空出来的位置
}
}
}
~~~
#### 希尔排序
- **插入排序的升级版,又称分组排序**;
- 希尔排序就是将原始记录分组进行直接插入排序,满足插入排序记录本身基本有序或记录数少的条件时,算法复杂度低。
分组排序的整个过程如图所示:

~~~c
void ShellSort( int list[], int n )
{
int i, j, temp;
int gap;
for ( gap=n/2; gap>0; gap/=2 ) // N * log(N)
{
for ( i=gap; i<n; i++ ) // 下面与插入排序完全相同
{
if ( list[i] < list[i-gap] )
{
temp = list[i]; // 将较小的数取出,放在正确的位置上
for ( j=i-gap; list[j]>temp; j-=gap ) // 向后移动,不需要交换
{
list[j+gap] = list[j];
}
list[j+gap] = temp; // i--后空出来的位置
}
}
}
}
~~~
#### 堆排序
#### 归并排序
归并排序的最好,最坏,平均时间复杂度均为O(nlogn)。
归并排序和擂台赛原理类似,**不同之处在于归并排序要求确定每一个元素的排列位置**。如图所示是擂台赛。

假设集合一共有n个元素,算法将会对集合进行逐层的折半分组。一直到每组只有一个元素为止。当每个小组内部比较出先后顺序以后,小组之间会展开进一步的比较和排序,合并成一个大组;大组之间继续比较和排序,再合并成更大的组......最终,所有元素合并成了一个有序的集合。归并排序的核心是把两个有序的小集合归并成一个有序的大集合。
**归并排序分两步,先分组后合并**,如图所示。

打印程序执行过程:

- 递归实现:先从下往上分组,再从下往上进行比较与合并;
~~~c
#define MAXSIZE 10
// 实现归并,并将最后的结果存放在list1中
// 归并排序的核心是把两个有序的小集合归并成一个有序的大集合。
void merging( int *list1, int list1_size, int *list2, int list2_size )
{
int temp[MAXSIZE];
int i, j, k;
i = j = k = 0;
// 两数组比较
while ( i < list1_size && j < list2_size )
{
if ( list1[i] > list2[j] )
{
temp[k++] = list2[j++];
}
// else if ( list1[i] <= list2[j] ) // 添加等号
else
{
temp[k++] = list1[i++];
}
}
// 两数组比较结束后其中一个末尾有剩余
while ( i < list1_size )
{
temp[k++] = list1[i++];
}
while ( j < list2_size )
{
temp[k++] = list2[j++];
}
// list1数组保存排序后结果
for ( i=0; i<list1_size+list2_size; i++ )
{
list1[i] = temp[i];
}
}
// 归并排序分两步,先分组后合并
void MergeSort( int list[], int n )
{
if ( n > 1 ) // 递归结束条件,每个数组一个元素
{
// 一个数组分成两个小数组
int *list1 = list;
int list1_size = n / 2;
int *list2 = list + n / 2;
int list2_size = n - list1_size; // 个数可能是奇数
MergeSort( list1, list1_size ); // 分组
MergeSort( list2, list2_size ); // 分组
merging( list1, list1_size, list2, list2_size ); // 比较与合并
}
}
~~~
- 迭代实现
#### 快速排序
- 冒泡排序的升级版,都属于交换排序,通过元素之间的比较与交换位置达到排序的目的。快速排序使得元素移动的间距增大,减少比较与移动的次数;
- 不同的是,冒泡排序在每一轮只把一个元素冒泡到数列的一端,而快速排序在每一轮挑选一个基准元素,并让其他比它大的元素移动到数列一边,比它小的元素移动到数列另一边,从而将数列拆解成两个部分。在分治法的思想下,以基准点为中心,原数列在每一轮被拆分为两部分,每一部分在下一轮又被拆分成两部分,直到不可再分为止。
- 核心包括两步:选择基准点、元素的移动。过程如图所示。代码使用递归实现。

~~~c
// 实现交换
void swap( int list[], int low, int high )
{
int temp;
temp = list[low];
list[low] = list[high];
list[high] = temp;
}
// 指针交换法实现元素的移动
int partition( int list[], int low, int high )
{
int pivot = list[low]; // 将第一个元素作为基准点。在该函数内保持不变。希望存储的是中间的值
int startindex = low; // 备份用于每轮最后的移动,将基准点移动到正确的位置
while ( low < high )
{
// 必须要有 low < high
while ( low < high && list[high] >= pivot ) // 过滤掉右边比基准点大的元素
{
high--; // 指针左移
}
// swap( list, low, high); // 交换。属于挖坑法,存在不必要的交换
while ( low < high && list[low] <= pivot ) // 过滤掉左边比基准点小的元素
{
low++; // 指针右移
}
swap( list, low, high); // 交换
// 测试
// int i;
// for ( i=0; i<8; i++ )
// {
// printf("%d ", list[i]);
// }
// printf("\n");
// if ( low < high )
// {
// swap(list, low, high); // 交换
// }
}
swap( list, startindex, low); // 将基准点移动到正确的位置
return low; // 返回新的基准点
}
void QSort( int list[], int low, int high )
{
int pivot = list[low]; // 基准点
if ( low < high ) // 当指针重叠时完成了一轮比较
{
pivot = partition( list, low, high ); // 计算基准点的函数,返回新的基准点
QSort( list, low, pivot-1); // 基准点左边
QSort( list, pivot+1, high); // 基准点右边
}
}
void QuickSort( int list[], int n ) // 为了与其他排序算法保持格式的统一
{
QSort(list, 0, n-1);
}
~~~
#### 快速排序的优化
- 快速排序的优化:基准点的优化选取(三数取中法)、优化不必要的交换(交换变赋值)、优化小数组排序(插入排序)、优化递归操作(尾递归);
- 快速排序适用于大规模数组。插入排序是简单排序算法中性能最好的。临界值为7。
~~~c
int partition( int list[], int low, int high )
{
// 优化1:优选基准点。交换的目的是使high取最大,low取中间值
int mid = low + ( high - low ) / 2;
if ( list[low] > list[high] ) // list[low] < list[high]
{
swap( list, low, high );
}
if ( list[mid] > list[high] ) // list[mid] < list[high]
{
swap( list, mid, high );
}
if ( list[mid] > list[low] ) // list[mid] < list[low]
{
swap( list, mid, low);
}
int pivot = list[low]; // 将第一个元素作为基准点。在该函数内保持不变。希望存储的是中间的值
int startindex = low; // 备份用于每轮最后的移动,将基准点移动到正确的位置
// 优化2:变交换为赋值操作
while ( low < high )
{
// 必须要有 low < high
while ( low < high && list[high] >= pivot ) // 过滤掉右边比基准点大的元素
{
high--; // 指针左移
}
list[low] = list[high]; // 变交换为赋值操作
while ( low < high && list[low] <= pivot ) // 过滤掉左边比基准点小的元素
{
low++; // 指针右移
}
list[high] = list[low];
}
list[low] = pivot;
return low; // 返回新的基准点
}
// 优化3:结合使用快速排序与插入排序
#define MAX_LENGTH_INSERT_SORT 7 // 快速排序与插入排序性能的临界点
// 简单插入排序
void ISort( int list[], int n )
{
int i, j;
int temp = 0;
for ( i=1; i<=n; i++ )
{
if ( list[i-1] > list[i] )
{
temp = list[i];
for ( j=i-1; list[j]>temp; j-- )
{
list[j+1] = list[j];
}
list[j+1] = temp;
}
}
}
void InsertSort( int list[], int low, int high )
{
ISort( list+low, high-low+1 );
}
void QSort( int list[], int low, int high )
{
int pivot = list[low]; // 基准点
if ( ( high - low ) > MAX_LENGTH_INSERT_SORT ) // 当指针重叠时完成了一轮比较
{
pivot = partition( list, low, high ); // 计算基准点的函数,返回新的基准点
QSort( list, low, pivot-1); // 基准点左边
QSort( list, pivot+1, high); // 基准点右边
}
else
{
InsertSort( list, low, high );
}
}
// 优化4:尾递归,将两个递归修改为一个递归,缩减栈空间的使用,提高效率
void QSort( int list[], int low, int high )
{
int pivot = list[low]; // 基准点
if ( ( high - low ) > MAX_LENGTH_INSERT_SORT ) // 当指针重叠时完成了一轮比较
{
while ( low < high )
{
pivot = partition( list, low, high ); // 计算基准点的函数,返回新的基准点
if ( pivot - low < high - pivot ) // 执行左边
{
QSort( list, low, pivot-1); // 基准点左边
low = pivot + 1; // 基准点右边
}
else // 执行右边
{
QSort( list, pivot+1, high); // 基准点左边
high = pivot - 1; // 基准点右边
}
}
}
else
{
InsertSort( list, low, high );
}
}
~~~
|
JavaScript
|
UTF-8
| 1,044 | 3.078125 | 3 |
[] |
no_license
|
nose_x=0;
nose_y=0;
difference=0;
leftwrist_x=0;
rightwrist_x=0;
function setup(){
video=createCapture(VIDEO);
video.size(560,500);
canvas=createCanvas(560,500);
canvas.position(760,170);
video.position(150,150);
poseNet=ml5.poseNet(video,modelLoaded);
poseNet.on('pose',gotResults);
}
function draw(){
background('#00a8e8');
fill("white");
stroke("#003459");
square(nose_x,nose_y,difference);
document.getElementById("square_sides").innerHTML="width and height of square = "+difference;
}
function modelLoaded(){
console.log("model loaded");
}
function gotResults(results){
if(results.length>0){
console.log(results);
nose_x=results[0].pose.nose.x;
nose_y=results[0].pose.nose.y;
console.log("nose x "+nose_x + " nose y "+nose_y);
leftwrist_x=results[0].pose.leftWrist.x;
rightwrist_x=results[0].pose.rightWrist.x;
difference=floor(leftwrist_x-rightwrist_x)
console.log("leftwrist_x = "+leftwrist_x +" rightwrist_x = "+rightwrist_x +" difference = " + difference);
}}
|
C++
|
UTF-8
| 338 | 2.609375 | 3 |
[] |
no_license
|
#pragma once
#include "ExplicitHand.hpp"
class StraightAceLowHand : public ExplicitHand
{
public:
StraightAceLowHand(Player& player);
~StraightAceLowHand() = default;
bool operator<(const ExplicitHand& rhs) const noexcept override;
bool operator>(const ExplicitHand& rhs) const noexcept override;
};
|
Java
|
UTF-8
| 1,822 | 1.671875 | 2 |
[] |
no_license
|
package com.tencent.mm.plugin.appbrand.jsapi.version;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.plugin.appbrand.config.AppBrandInitConfigWC;
import com.tencent.mm.plugin.appbrand.report.AppBrandStatObject;
final class JsApiUpdateApp$SyncRequest
implements Parcelable
{
public static final Parcelable.Creator<SyncRequest> CREATOR;
private AppBrandInitConfigWC hYb;
private AppBrandStatObject hYc;
static
{
AppMethodBeat.i(138133);
CREATOR = new JsApiUpdateApp.SyncRequest.1();
AppMethodBeat.o(138133);
}
protected JsApiUpdateApp$SyncRequest(Parcel paramParcel)
{
AppMethodBeat.i(138132);
this.hYb = ((AppBrandInitConfigWC)paramParcel.readParcelable(AppBrandInitConfigWC.class.getClassLoader()));
this.hYc = ((AppBrandStatObject)paramParcel.readParcelable(AppBrandStatObject.class.getClassLoader()));
AppMethodBeat.o(138132);
}
public JsApiUpdateApp$SyncRequest(AppBrandInitConfigWC paramAppBrandInitConfigWC, AppBrandStatObject paramAppBrandStatObject)
{
this.hYb = paramAppBrandInitConfigWC;
this.hYc = paramAppBrandStatObject;
}
public final int describeContents()
{
return 0;
}
public final void writeToParcel(Parcel paramParcel, int paramInt)
{
AppMethodBeat.i(138131);
paramParcel.writeParcelable(this.hYb, paramInt);
paramParcel.writeParcelable(this.hYc, paramInt);
AppMethodBeat.o(138131);
}
}
/* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes4-dex2jar.jar
* Qualified Name: com.tencent.mm.plugin.appbrand.jsapi.version.JsApiUpdateApp.SyncRequest
* JD-Core Version: 0.6.2
*/
|
Python
|
UTF-8
| 538 | 3.796875 | 4 |
[] |
no_license
|
class ListList:
def __init__(self, value):
self.value = value
self.setofvalues = set(item for sublist in self.value for item in sublist)
#wtf is this lol
def __iter__(self):
print('Using __iter__')
return(item for sublist in self.value for item in sublist)
#again, wtf is this
def __contains__(self,value):
print('Using __contains__')
return value in self.setofvalues
a = ListList( [ [1,1,1], [0,1,1], [1,5,1] ] )
print(10 in a) # false
print( 5 in a) # true
del ListList.__contains__
print( 5 in a) # Still true !!
|
Java
|
UTF-8
| 1,467 | 2.578125 | 3 |
[] |
no_license
|
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import driver.WebDriverManager;
public class SignInPage extends WebDriverManager{
private WebDriver driver;
private By nameField;
private By lastNameField;
private By emailField;
private By passwordField;
private By createAccountButton;
public SignInPage(WebDriver driver) {
this.driver = driver;
nameField = By.name("firstname");
lastNameField = By.name("lastname");
emailField = By.name("email");
passwordField = By.name("PASSWORD");
createAccountButton = By.id("ppaFormSbtBtn");
}
//Este metodo se encarga de enviar los datos de login
public void signIn(String name, String lastName, String email, String password) {
WebDriverWait wait = new WebDriverWait(driver,20);
try {
driver.findElement(By.xpath("//*[@id=\"captcha-box\"]/div/div[2]/div[1]/div[3]/span[1]"));
}
catch(Exception e){
wait.until(ExpectedConditions.presenceOfElementLocated(nameField));
driver.findElement(nameField).sendKeys(name);
driver.findElement(lastNameField).sendKeys(lastName);
driver.findElement(emailField).sendKeys(email);
driver.findElement(passwordField).sendKeys(password);
wait.until(ExpectedConditions.elementToBeClickable(createAccountButton));
driver.findElement(createAccountButton).click();
}
}
}
|
Python
|
UTF-8
| 1,060 | 2.5625 | 3 |
[] |
no_license
|
import sys
input = sys.stdin.readline
N, L = map(int, input().rstrip('\n').split())
base = [list(map(int, input().rstrip('\n').split())) for _ in range(N)]
answer = 0
def check(base, result):
for r in range(N):
if len(set(base[r])) == 1:
result += 1
continue
now = base[r][0]
count = 1
visit = [False] * N
for c in range(N-1):
diff = abs(base[r][c]-base[r][c+1])
if diff > 1: break
elif diff == 0 : continue
else:
if base[r][c]>base[r][c+1] and c<N-L and True not in visit[c+1:c+L+1] and len(set(base[r][c+1:c+L+1]))==1:
visit[c+1:c+L+1] = [True] * L
elif base[r][c]<base[r][c+1] and c+1>=L and True not in visit[c+1-L:c+1] and len(set(base[r][c+1-L:c+1]))==1:
visit[c+1-L:c+1] = [True] * L
else:
break
else:
result += 1
return result
answer += check(base, 0)
answer += check(list(zip(*base)),0)
print(answer)
|
Java
|
UTF-8
| 3,500 | 3.0625 | 3 |
[] |
no_license
|
package adamsdd.calculator.model;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.regex.Matcher;
public class Calculations {
private Map<String, BiFunction<BigDecimal, BigDecimal, BigDecimal>> calculationOperations = new HashMap<>();
private Map<FunctionOperationType, Function<StringBuilder, StringBuilder>> functionsOperations = new HashMap<>();
public Calculations() {
initCalculationOperations();
initFunctionalOperations();
}
private void initCalculationOperations() {
calculationOperations.put(CalculationOperationType.ADD.label, BigDecimal::add);
calculationOperations.put(CalculationOperationType.SUB.label, BigDecimal::subtract);
calculationOperations.put(CalculationOperationType.MUL.label, BigDecimal::multiply);
calculationOperations.put(CalculationOperationType.DIV.label, BigDecimal::divide);
calculationOperations.put(CalculationOperationType.POW.label, (x, y) -> x.pow(y.intValue()));
calculationOperations.put(CalculationOperationType.SQRT.label, (x, y) -> BigDecimal.valueOf(Math.sqrt(y.doubleValue())));
}
private void initFunctionalOperations() {
functionsOperations.put(FunctionOperationType.C, (currentResult) -> {
if (currentResult.length() > 0) {
currentResult.setLength(0);
}
return currentResult;
});
}
public StringBuilder doFunctionOperation(FunctionOperationType functionOperationType, StringBuilder result) {
return functionsOperations.get(functionOperationType).apply(result);
}
public BigDecimal calculateExpression(String expression) {
System.out.println("expression to calculate = " + expression);
try {
for (Map.Entry<Integer, Operation> op : CalculationPattern.operationsPriority.entrySet()) {
System.out.println("Actual op = " + op);
if (expression.contains(op.getValue().symbol)) {
System.out.println("Expression contains = " + op.getValue().symbol);
Matcher matcher = op.getValue().pattern.matcher(expression);
expression = executePattern(expression, matcher, calculationOperations.get(op.getValue().symbol));
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error = " + e);
}
System.out.println("expression to return = " + expression);
return new BigDecimal(expression);
}
private String executePattern(String expression, Matcher matcher, BiFunction operation) {
String result = null;
while (matcher.find()) {
String reg = matcher.group(0);
System.out.println("matcher.group(0) = " + reg);
System.out.println("matcher.group(1) = " + matcher.group(1));
System.out.println("matcher.group(2) = " + matcher.group(2));
BigDecimal x = new BigDecimal(matcher.group(1));
BigDecimal y = new BigDecimal(matcher.group(2));
result = String.valueOf(operation.apply(x, y));
expression = expression.replace(reg, result);
matcher.reset(expression);
}
System.out.println("RESULT = " + result);
System.out.println("Expression = " + expression);
return expression;
}
}
|
JavaScript
|
UTF-8
| 1,145 | 3.84375 | 4 |
[] |
no_license
|
const handlers = {}
/**
* 1. How do we let you add more than 1 handler for the same type?
*/
const trigger = (type, ...args) => {
// iterate and invoke each handler within this key
handlers[type].forEach(handler => handler(...args))
}
const on = (type, handler) => {
// if the key doesn't exist
if(!(type in handlers)) {
// we initialise an array with the incoming handler
handlers[type] = [handler]
} else {
// otherwise we push the new handler to the existing key
handlers[type].push(handler)
}
}
on('foo', () => {
console.log('Do foo');
});
on('foo', () => {
console.log('Do some other foo');
});
/**
* 2. How do we add an off method?
*/
const onFoo = () => {
console.log('Do onFoo');
};
const off = (type, handler) => {
// remove the matching handler within this key
handlers[type] = handlers[type].filter(h => handler !== h)
}
on('foo', onFoo);
off('foo', onFoo);
/**
* 3. How do I allow you to pass arbitrary arguments?
*/
on('foo', (arg1, arg2) => {
console.log('here are my args', arg1, arg2)
})
// Usage
trigger('foo', 1, 2)
// log: Do Foo
// log: Do some other Foo
// log: here are my args 1 2
|
Java
|
UTF-8
| 549 | 1.875 | 2 |
[] |
no_license
|
package com.example.demo.repository;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.example.demo.entity.IndustryNews;
@Repository
public interface IndustryNewsRepository extends JpaRepository<IndustryNews, Long> {
@Transactional
@Modifying
@Query(value = "delete from IndustryNews")
void deleteAllEntities();
}
|
SQL
|
UTF-8
| 562 | 4.28125 | 4 |
[] |
no_license
|
--Listar o nome do cliente e quantidade de produtos diferentes comprados em 2018
--SELECT * FROM Cliente where NomeCliente = 'Allan Silva'
--SELECT* FROM Produto
--SELECT * FROM Venda
--SELECT * FROM VendaItem
SELECT Total.Nome, COUNT(Total.idProduto) AS Total
FROM
(SELECT C.NomeCliente AS Nome, VI.IdProduto AS idProduto
FROM VendaItem AS VI
INNER JOIN Venda As V
ON vi.IdVenda = V.IdVenda
INNER JOIN Cliente AS C
ON V.IdCliente = C.IdCliente
WHERE YEAR(DataVenda) = 2018
GROUP BY C.NomeCliente, VI.IdProduto) AS Total
GROUP BY Total.Nome
|
C
|
GB18030
| 558 | 3.53125 | 4 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void PrintTrangle(int n);
/*
ӡͼ
ӡn-1space
ӡ2i-1*
ӡ1\n
*/
void PrintTrangle(int n)
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=0;j<n-i;j++)
printf(" ");
for(j=0;j<2*i-1;j++)
printf("*");
printf("\n");
}
}
int main()
{
int n;
printf("How many rows of * for trangle\n");
scanf("%d",&n);//εĸ߶n
PrintTrangle(n);
getchar();
return 0;
}
|
Python
|
UTF-8
| 1,624 | 4.25 | 4 |
[] |
no_license
|
'''
Exercise 16 (and Solution)
Write a password generator in Python. Be creative with how you
generate passwords - strong passwords have a mix of lowercase letters,
uppercase letters, numbers, and symbols. The passwords should
be random, generating a new password every time the user asks
for a new password. Include your run-time code in a main method.
Extra:
Ask the user how strong they want their password to be. For weak passwords, pick a word or two from a list.
'''
import random
import string
passwordList = ['blue', 'orange', 'armadillo', 'letter', 'golden']
def genPassword(difficulty):
password = ''
random.seed()
randomNumber = random.randint(0, len(passwordList)-1)
randomNumber2 = random.randint(0, len(passwordList)-1)
if difficulty == 1:
element = passwordList[randomNumber]
element += passwordList[randomNumber2]
print(element)
return
if difficulty == 2:
word = str(random.randint(0,600))
word += passwordList[randomNumber]
word += str(random.randint(0,600))
word += passwordList[randomNumber2]
word += str(random.randint(0, 600))
print(word)
return
if difficulty == 3:
characters = string.ascii_letters + string.digits
word = ''
for i in range(0, 24):
word += random.choice(characters)
print(word)
print('This is for educational purposes, never use'
' this to actually generate a password. Enter '
'a number from 1-3 for complexity')
#No error checking let it burn!
uInput = int(input('>> '))
genPassword(uInput)
|
Java
|
UTF-8
| 606 | 2.890625 | 3 |
[] |
no_license
|
package com.mmall.concurrency.example.singleton;
import com.mmall.concurrency.annotations.NotRecommend;
import com.mmall.concurrency.annotations.ThreadSafe;
import java.util.Vector;
//饿汉式
@ThreadSafe
public class SingletonExample2 {
//构造私有化
private SingletonExample2(){
}
//单例对象
static {
instance = new SingletonExample2();
}
private static SingletonExample2 instance = null;
public static SingletonExample2 getInstance(){
return instance;
}
public static void main(String[] args){
System.out.println(getInstance());
System.out.println(getInstance());
}
}
|
Ruby
|
UTF-8
| 4,019 | 3.75 | 4 |
[] |
no_license
|
require 'csv'
$mod_mode = 0 #change criteria for printing student list
@students = []
@modifier = "" #specifier for printing student list criteria
@mod_list = [] #student list returned after applying mods
def input_students
puts "Please enter the names of the students and their cohorts"
puts "Use this format 'Namey McName,cohort'"
puts "To finish just hit return twice"
loop do
return if populate_student_array == 0
puts @students.count == 1 ? "Now we have 1 student" : "Now we have #{@students.count} students"
end
end
def mod
if $mod_mode == 1 #print all students with name beginning with a certain letter
@students.select{|student| student[:name][0].downcase == @modifier}
elsif $mod_mode == 2 #print all students with a name less than a certain length
@students.select{|student| student[:name].length < @modifier.to_i}
elsif $mod_mode == 3 #print by cohort
@students.select{|student| student[:cohort] == @modifier.to_sym}
else
@students
end
end
def print_header
puts "The students of Villains Academy"
puts "----------------"
end
def print_students_list
@mod_list.each_with_index do |student, index|
puts "#{index + 1}. #{student[:name]} (#{student[:cohort]} cohort)".center(40)
end
end
def print_footer
puts @mod_list.count == 1 ? "Overall, we have 1 great student!" : "Overall, we have #{@mod_list.count} great students"
end
def interactive_menu
try_load_students
loop do
print_menu
process(STDIN.gets.chomp)
end
end
def show_students
mod_select
@mod_list = mod
if !@mod_list.empty?
print_header
print_students_list
print_footer
else
puts "No student data"
end
end
def print_mod_menu
puts "Choose a selection criteria:"
puts "0. No criteria"
puts "1. Sort by name"
puts "2. Sort by length of name"
puts "3. Sort by cohort"
end
def mod_select
print_mod_menu
mod_process(STDIN.gets.chomp)
end
def mod_process(selection)
case selection
when "0"
$mod_mode = 0
when "1"
$mod_mode = 1
puts "Choose a letter to sort by (a - z):"
@modifier = STDIN.gets.chomp.downcase
when "2"
$mod_mode = 2
puts "Choose name length to sort by (as integer):"
@modifier = STDIN.gets.chomp
when "3"
$mod_mode = 3
puts "Choose a cohort:"
@modifier = STDIN.gets.chomp
else
puts "Invalid command"
end
end
def print_menu
puts "Student directory menu:"
puts "1. Input students"
puts "2. Show the students"
puts "3. Save the student list to students.csv"
puts "4. Load the student list from students.csv"
puts "9. Exit"
end
def process(selection)
case selection
when "1"
input_students
when "2"
show_students
when "3"
puts "Choose a file name(hit enter to use default):"
save_students(STDIN.gets.chomp)
when "4"
puts "Choose a file to load:"
try_load_students(STDIN.gets.chomp)
when "9"
exit
else
puts "Invalid command"
end
end
def save_students(filename = "students")
CSV.open("#{filename}.csv", "wb") do |csv|
@students.each do |student|
student_data = [student[:name], student[:cohort]]
csv << student_data.join(",")
end
end
puts "Data saved in file #{filename}.csv"
end
def load_students(filename = "students.csv")
CSV.foreach(filename) do |line|
populate_student_array(line)
end
puts "Data loaded successfully"
end
def try_load_students(filename = ARGV.first)
if filename.nil?
load_students
return
end
if File.exists?(filename)
load_students(filename)
puts "Loaded #{@students.count} from #{filename}"
else
puts "File '#{filename}' doesn't exist"
return
end
end
def populate_student_array(input = STDIN.gets)
name, cohort = input.chomp.split(",")
return 0 if name.nil?
cohort = "unassigned" if cohort.nil?
@students << {name: name, cohort: cohort.downcase.to_sym, hobbies: 'things', birth_country: 'place', height: 0}
end
interactive_menu
|
Markdown
|
UTF-8
| 2,263 | 3.875 | 4 |
[] |
no_license
|
[包围区域](https://leetcode.com/problems/surrounded-regions/description/)
```
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
```
`
I felt that the problem statement was difficult to understand as it and the associated example don’t clearly indicate what surrounded means. An ‘O’ is surrounded if there is NO path from it to the boundary of the matrix (ie. row index 0, column index 0, row index matrix.length-1, column index matrix[0].length-1) when moving in a North, South, East, or West direction :). Hope this helps anyone else who was unclear.
`
```java
class Solution {
public void solve(char[][] board) {
if(board == null || board.length == 0)
return;
int m = board.length;
int n = board[0].length;
//merge O's on left & right boarder
for (int i = 0; i < m; i++) {
if (board[i][0] == 'O') {
merge(board, i, 0);
}
if (board[i][n - 1] == 'O') {
merge(board, i, n - 1);
}
}
//merge O's on top & bottom boarder
for (int j = 0; j < n; j++) {
if (board[0][j] == 'O') {
merge(board, 0, j);
}
if (board[m-1][j] == 'O') {
merge(board, m - 1, j);
}
}
//process the board
for (int i = 0;i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
} else if (board[i][j] == '#') {
board[i][j] = 'O';
}
}
}
}
public void merge(char[][] board, int i, int j){
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != 'O') {
return;
}
board[i][j] = '#';
merge(board, i - 1, j);
merge(board, i + 1, j);
merge(board, i, j - 1);
merge(board, i, j + 1);
}
}
````
|
Java
|
UTF-8
| 13,816 | 1.859375 | 2 |
[] |
no_license
|
package web.app.rest.company;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import web.app.common.AppConstants;
import web.app.common.LockObject;
import web.app.common.SystemServices;
import web.app.common.User;
import web.app.jpamodel.company.SpCompanyNewCheckParams;
import web.app.jpamodel.company.SpCompanyNewCheckResults;
import web.app.jpamodel.company.SpFindCompany;
import web.app.jpamodel.company.TblCompany;
import web.app.jpamodel.company.TblCompanyComments;
import web.app.jpamodel.company.sp.SpCompanyCommentsResults;
import web.app.jpamodel.company.sp.SpCompanyContactActivityResults;
import web.app.jpamodel.company.sp.SpCompanyContactsResults;
import web.app.jpamodel.company.sp.SpCompanyJobsResults;
import web.app.jpamodel.company.sp.SpCompanyMarketingResults;
import web.app.jpamodel.company.sp.SpCompanyParams;
import web.app.jpamodel.company.sp.SpCompanyProjectsResults;
import web.app.jpamodel.company.sp.SpCompanyTableResults;
import web.app.jpamodel.contact.TblContacts;
import web.app.rest.ApplicationServiceBase;
@Path("/company")
public class CompanyService extends ApplicationServiceBase{
@Path("/get({id})")
@GET
@Produces(MediaType.APPLICATION_JSON)
//@RolesAllowed({"1", "2"})
public CompanyEntity getCompanyEntity(@Context SecurityContext securityContext, @PathParam("id") long id, @QueryParam("lock") boolean lock) {
CompanyEntity companyEntity = new CompanyEntity();
List<TblCompanyComments> companyComments = new ArrayList<TblCompanyComments>();
TblCompany tblCompany = null;
List<TblContacts> companyContacts = new ArrayList<TblContacts>();
User user = (User) securityContext.getUserPrincipal();
if (lock == true ){
SystemServices sysService = (SystemServices) servletContext.getAttribute(AppConstants.SYSTEM_SERVICE);
LockObject lockObject = new LockObject();
lockObject.setObjectId(Long.toString(id));
lockObject.setObjectType("COMPANY");
lockObject.setLockedBy(user.getUserName());
if (!sysService.lockObject(lockObject)){
companyEntity.addMessage("Company locked for edit");
return companyEntity;
};
}
EntityManagerFactory emf = (EntityManagerFactory) servletContext.getAttribute(AppConstants.MSSQL_EMF);
EntityManager em = emf.createEntityManager();
tblCompany = em.find(TblCompany.class, id);
if (tblCompany != null){
//Set selected company to entity
companyEntity.setCompany(tblCompany);
//Get company comments
TypedQuery<TblCompanyComments> queryComments = em.createQuery("SELECT comments FROM TblCompanyComments comments WHERE comments.cmcCompanyID = :comID", TblCompanyComments.class);
queryComments.setParameter("comID", String.valueOf(tblCompany.getComID()));
companyComments = queryComments.getResultList();
//Set selected comments to company entity
companyEntity.setComments(companyComments);
//Get Company Contacts
TypedQuery<TblContacts> queryContacts = em.createQuery("SELECT contacts FROM TblContacts contacts WHERE contacts.conCompanyID = :conCompanyID", TblContacts.class);
queryContacts.setParameter("conCompanyID", tblCompany.getComID());
companyContacts = queryContacts.getResultList();
//Set selected contacts to company entity
companyEntity.setContacts(companyContacts);
}
em.close();
return companyEntity;
}
@Path("/create")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@RolesAllowed({"1", "2"})
public CompanyEntity postCompanyEntity(@Context SecurityContext securityContext, CompanyEntity companyEntity) {
EntityManagerFactory emf = (EntityManagerFactory) servletContext.getAttribute(AppConstants.MSSQL_EMF);
EntityManager em = emf.createEntityManager();
User user = (User) securityContext.getUserPrincipal();
companyEntity.getCompany().setComCreatedBy(user.getUserName());
//companyEntity.getCompany().setComDate(new Date());
companyEntity.getCompany().setComRevisedBy(user.getUserName());;
companyEntity.getCompany().setComRevisedDate(new Date());
//Create company always active
companyEntity.getCompany().setComInactive(false);
em.getTransaction().begin();
em.persist(companyEntity.getCompany());
//flush so that newly created id is reflected on entity object
em.flush();
for (TblCompanyComments companyComment : companyEntity.getComments()) {
if ( companyComment != null && !companyComment.getCmcComment().isEmpty()) {
companyComment.setCmcCompanyID(String.valueOf(companyEntity.getCompany().getComID()));
companyComment.setCmcDate(new Date());
companyComment.setCmcUser(user.getUserName());
em.persist(companyComment);
}
}
em.getTransaction().commit();
em.close();
return companyEntity;
}
@Path("/change")
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@RolesAllowed({"1", "2"})
public CompanyEntity putCompanyEntity(@Context SecurityContext securityContext, CompanyEntity companyEntity, @QueryParam("unlock") boolean unLock) {
User user = (User) securityContext.getUserPrincipal();
SystemServices sysService = (SystemServices) servletContext.getAttribute(AppConstants.SYSTEM_SERVICE);
LockObject lockObject = new LockObject();
lockObject.setObjectId(Long.toString(companyEntity.getCompany().getComID()));
lockObject.setObjectType("COMPANY");
lockObject.setLockedBy(user.getUserName());
if (!sysService.lockObject(lockObject)){
companyEntity.addMessage("Company not locked for edit, please try again.");
return companyEntity;
};
EntityManagerFactory emf = (EntityManagerFactory) servletContext.getAttribute(AppConstants.MSSQL_EMF);
EntityManager em = emf.createEntityManager();
companyEntity.getCompany().setComRevisedBy(user.getUserName());
companyEntity.getCompany().setComRevisedDate(new Date());
em.getTransaction().begin();
em.merge(companyEntity.getCompany());
for (TblCompanyComments companyComment : companyEntity.getComments()) {
if ( companyComment != null && !companyComment.getCmcComment().isEmpty()) {
companyComment.setCmcCompanyID(String.valueOf(companyEntity.getCompany().getComID()));
companyComment.setCmcDate(new Date());
companyComment.setCmcUser(user.getUserName());
em.persist(companyComment);
}
}
em.getTransaction().commit();
em.close();
if (unLock == true ){
sysService.unLockObject(lockObject);
}
return companyEntity;
}
@Path("/addcomment")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public TblCompanyComments addComment(@Context SecurityContext securityContext, TblCompanyComments companyComment) {
EntityManagerFactory emf = (EntityManagerFactory) servletContext.getAttribute(AppConstants.MSSQL_EMF);
EntityManager em = emf.createEntityManager();
User user = (User) securityContext.getUserPrincipal();
if ( companyComment != null && !companyComment.getCmcComment().isEmpty()) {
companyComment.setCmcDate(new Date());
companyComment.setCmcUser(user.getUserName());
}
em.getTransaction().begin();
em.persist(companyComment);
em.getTransaction().commit();
em.close();
return companyComment;
}
@Path("/findcompany")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public CompanyEntity findCompany(@Context SecurityContext securityContext, CompanyEntity companyEntity) {
EntityManagerFactory emf = (EntityManagerFactory) servletContext.getAttribute(AppConstants.MSSQL_EMF);
EntityManager em = emf.createEntityManager();
User user = (User)securityContext.getUserPrincipal();
Query query = em.createNamedStoredProcedureQuery("spFindCompany");
query.setParameter("comName", companyEntity.getFindParams().getComName());
query.setParameter("empID", user.getUserName());
query.setParameter("Inactive", companyEntity.getFindParams().getComInactive());
List<SpFindCompany> resultList = (List<SpFindCompany>)query.getResultList();
em.close();
companyEntity.setFindCompanyResults(resultList);
return companyEntity;
}
@Path("/newcheck")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public List<SpCompanyNewCheckResults> spCompanyNewCheck(@Context SecurityContext securityContext, SpCompanyNewCheckParams params) {
EntityManagerFactory emf = (EntityManagerFactory) servletContext.getAttribute(AppConstants.MSSQL_EMF);
EntityManager em = emf.createEntityManager();
Query query = em.createNamedStoredProcedureQuery("spCompanyNewCheck");
query.setParameter("comName", params.getComName());
query.setParameter("theName", params.getTheName());
List<SpCompanyNewCheckResults> resultList = (List<SpCompanyNewCheckResults>)query.getResultList();
em.close();
return resultList;
}
@Path("/details")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public CompanyDetailsEntity companyDetails(@Context SecurityContext securityContext, SpCompanyParams params) {
CompanyDetailsEntity companyDetails = new CompanyDetailsEntity();
SpCompanyTableResults company = null;
List<SpCompanyTableResults> companyList = null;
List<SpCompanyCommentsResults> comments = null;
List<SpCompanyContactsResults> contacts = null;
List<SpCompanyContactActivityResults> contactActivities = null;
List<SpCompanyJobsResults> jobs = null;
List<SpCompanyProjectsResults> projects = null;
List<SpCompanyMarketingResults> marketings = null;
EntityManagerFactory emf = (EntityManagerFactory) servletContext.getAttribute(AppConstants.MSSQL_EMF);
EntityManager em = emf.createEntityManager();
User user = (User)securityContext.getUserPrincipal();
if (params.getEmpID() == null){
params.setEmpID(user.getUserName());
}
// Get Company
if ( params.getGetCompanyDetail() ) {
Query qCompany = em.createNamedStoredProcedureQuery("sp_CompanyTable");
qCompany.setParameter("comID", params.getComID());
qCompany.setParameter("empID", params.getEmpID());
companyList = (List<SpCompanyTableResults>)qCompany.getResultList();
}
// Get Comments
if ( params.getGetComments() ) {
Query qComments = em.createNamedStoredProcedureQuery("spCompanyComments");
qComments.setParameter("comID", params.getComID());
comments = (List<SpCompanyCommentsResults>)qComments.getResultList();
}
// Get Contacts
if ( params.getGetContacts() ) {
Query qContacts = em.createNamedStoredProcedureQuery("spCompanyContacts");
qContacts.setParameter("comID", params.getComID());
qContacts.setParameter("empID", params.getEmpID());
contacts = (List<SpCompanyContactsResults>)qContacts.getResultList();
}
// Get Contact Activities
if ( params.getGetAvtivities() ) {
Query qContactActivities = em.createNamedStoredProcedureQuery("spCompanyContactActivity");
qContactActivities.setParameter("comID", params.getComID());
qContactActivities.setParameter("empID", params.getEmpID());
contactActivities = (List<SpCompanyContactActivityResults>)qContactActivities.getResultList();
}
// Get Jobs
if ( params.getGetJobs() ) {
Query qJobs = em.createNamedStoredProcedureQuery("spCompanyJobs");
qJobs.setParameter("comID", params.getComID());
qJobs.setParameter("empID", params.getEmpID());
jobs = (List<SpCompanyJobsResults>)qJobs.getResultList();
}
// Get Projects
if ( params.getGetProjects() ) {
Query qProjects = em.createNamedStoredProcedureQuery("spCompanyProjects");
qProjects.setParameter("comID", params.getComID());
qProjects.setParameter("empID", params.getEmpID());
projects = (List<SpCompanyProjectsResults>)qProjects.getResultList();
}
// Get marketing
if ( params.getGetMarketing() ) {
Query qMarketings = em.createNamedStoredProcedureQuery("spCompanyMarketing");
qMarketings.setParameter("comID", params.getComID());
marketings = (List<SpCompanyMarketingResults>)qMarketings.getResultList();
}
em.close();
// Create display entity
if (companyList.iterator().hasNext()){
company = companyList.iterator().next();
}
if (company != null ){
companyDetails.setCompany(company);
if (comments != null) {
companyDetails.setComments(comments);
};
if (contacts != null){
companyDetails.setContacts(contacts);
};
if (contactActivities != null){
companyDetails.setContactActivities(contactActivities);
};
if (jobs != null){
companyDetails.setJobs(jobs);
};
if (projects != null){
companyDetails.setProjects(projects);
};
if (marketings != null){
companyDetails.setMarketings(marketings);
};
}
return companyDetails;
}
}
|
C#
|
UTF-8
| 1,065 | 2.703125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OneSnip
{
public class Snip
{
public event EventHandler<SnipEventArgs> SnipCreated;
private Bitmap image;
private Screen screenUsed;
protected virtual void OnSnipCreated()
{
if ((this.SnipCreated != null))
{
SnipEventArgs e = new SnipEventArgs(image, screenUsed);
this.SnipCreated(this, e);
}
}
public void setImage(Bitmap _image, Screen _screenUsed)
{
image = _image;
screenUsed = _screenUsed;
this.OnSnipCreated();
}
}
public class SnipEventArgs : EventArgs
{
public Bitmap image;
public Screen screenUsed;
public SnipEventArgs(Bitmap _image, Screen _screenUsed)
{
image = _image;
screenUsed = _screenUsed;
}
}
}
|
Swift
|
UTF-8
| 1,075 | 2.890625 | 3 |
[] |
no_license
|
//
// FirebaseAuthManager.swift
// DoubleXP
//
// Created by Toussaint Peterson on 10/10/19.
// Copyright © 2019 Peterson, Toussaint. All rights reserved.
//
import FirebaseAuth
import UIKit
class FirebaseAuthManager {
func createUser(email: String, password: String, completionBlock: @escaping (_ success: Bool) -> Void) {
Auth.auth().createUser(withEmail: email, password: password) {(authResult, error) in
if let user = authResult?.user {
print(user)
completionBlock(true)
} else {
completionBlock(false)
}
}
}
func signIn(email: String, pass: String, completionBlock: @escaping (_ error: String, _ success: Bool) -> Void) {
Auth.auth().signIn(withEmail: email, password: pass) { (result, error) in
if let error = error, let _ = AuthErrorCode(rawValue: error._code) {
completionBlock(String(error._code), false)
} else {
completionBlock(error?.localizedDescription ?? "", true)
}
}
}
}
|
C#
|
UTF-8
| 1,456 | 2.78125 | 3 |
[] |
no_license
|
using ELearning.API.Helper;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace ELearning.API.Middlewares
{
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
await HandleExceptionAsync(httpContext, ex);
}
}
private Task HandleExceptionAsync(HttpContext context, Exception ex)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return context.Response.WriteAsync(new ExceptionResponse()
{
Success = false,
StatusCode = context.Response.StatusCode,
Exceptions = new Exceptions()
{
ErrorMessage = ex.Message,
InnerException = ex.InnerException?.Message,
StackTrace = ex.StackTrace,
ErrorPath = context.Request.Path
}
}.ToString());
}
}
}
|
Markdown
|
UTF-8
| 5,775 | 3.734375 | 4 |
[] |
no_license
|
# `(困难)` [5729.finding-mk-average 求出 MK 平均值](https://leetcode-cn.com/problems/finding-mk-average/)
[contest](https://leetcode-cn.com/contest/weekly-contest-236/problems/finding-mk-average/)
### 题目描述
<div class="notranslate"><p>给你两个整数 <code>m</code> 和 <code>k</code> ,以及数据流形式的若干整数。你需要实现一个数据结构,计算这个数据流的 <b>MK 平均值</b> 。</p>
<p><strong>MK 平均值</strong> 按照如下步骤计算:</p>
<ol>
<li>如果数据流中的整数少于 <code>m</code> 个,<strong>MK 平均值</strong> 为 <code>-1</code> ,否则将数据流中最后 <code>m</code> 个元素拷贝到一个独立的容器中。</li>
<li>从这个容器中删除最小的 <code>k</code> 个数和最大的 <code>k</code> 个数。</li>
<li>计算剩余元素的平均值,并 <strong>向下取整到最近的整数</strong> 。</li>
</ol>
<p>请你实现 <code>MKAverage</code> 类:</p>
<ul>
<li><code>MKAverage(int m, int k)</code> 用一个空的数据流和两个整数 <code>m</code> 和 <code>k</code> 初始化 <strong>MKAverage</strong> 对象。</li>
<li><code>void addElement(int num)</code> 往数据流中插入一个新的元素 <code>num</code> 。</li>
<li><code>int calculateMKAverage()</code> 对当前的数据流计算并返回 <strong>MK 平均数</strong> ,结果需 <strong>向下取整到最近的整数</strong> 。</li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong>
["MKAverage", "addElement", "addElement", "calculateMKAverage", "addElement", "calculateMKAverage", "addElement", "addElement", "addElement", "calculateMKAverage"]
[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]
<strong>输出:</strong>
[null, null, null, -1, null, 3, null, null, null, 5]
<strong>解释:</strong>
MKAverage obj = new MKAverage(3, 1);
obj.addElement(3); // 当前元素为 [3]
obj.addElement(1); // 当前元素为 [3,1]
obj.calculateMKAverage(); // 返回 -1 ,因为 m = 3 ,但数据流中只有 2 个元素
obj.addElement(10); // 当前元素为 [3,1,10]
obj.calculateMKAverage(); // 最后 3 个元素为 [3,1,10]
// 删除最小以及最大的 1 个元素后,容器为 <code>[3]
// [3] 的平均值等于 3/1 = 3 ,故返回 3
obj.addElement(5); // 当前元素为 [3,1,10,5]
obj.addElement(5); // 当前元素为 [3,1,10,5,5]
obj.addElement(5); // 当前元素为 [3,1,10,5,5,5]
obj.calculateMKAverage(); // 最后 3 个元素为 [5,5,5]
// </code>删除最小以及最大的 1 个元素后,容器为 <code>[5]<code>
// </code>[5] 的平均值等于 5/1 = 5 ,故返回 5<code>
</code></code></pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>3 <= m <= 10<sup>5</sup></code></li>
<li><code>1 <= k*2 < m</code></li>
<li><code>1 <= num <= 10<sup>5</sup></code></li>
<li><code>addElement</code> 与 <code>calculateMKAverage</code> 总操作次数不超过 <code>10<sup>5</sup></code> 次。</li>
</ul>
</div>
---
### 思路
```
```
### 答题
``` C++
class MKAverage {
public:
MKAverage(int _m, int _k) : m(_m), k(_k) {
}
void addElement(int num) {
que.push(num);
if (!isReady) {
Init(num);
return;
}
add(num);
remove(que.front());
que.pop();
}
int calculateMKAverage() {
if (isReady) {
int ans = sum / (m - 2 * k);
}
return (!isReady) ? -1 : sum / (m - 2 * k);
}
private:
void Init(int num) {
data.push_back(num);
if (data.size() == m) {
sort(data.begin(), data.end());
for (int i = 0; i < data.size(); i++) {
if (i < k) {
set_low.insert(data[i]);
}
else if (i < m - k) {
set_mid.insert(data[i]);
sum += data[i];
}
else {
set_high.insert(data[i]);
}
}
isReady = true;
}
}
void add(int num) {
if (*set_low.rbegin() > num) {
int e = *set_low.rbegin();
moveNum(set_low, e, set_mid);
sum += e;
set_low.insert(num);
}
else if (*set_high.begin() < num) {
int e = *set_high.begin();
moveNum(set_high, e, set_mid);
sum += e;
set_high.insert(num);
}
else {
set_mid.insert(num);
sum += num;
}
}
void remove(int num) {
if (set_mid.find(num) != set_mid.end()) {
set_mid.erase(set_mid.find(num));
sum -= num;
}
else if (set_low.find(num) != set_low.end()) {
set_low.erase(set_low.find(num));
int e = *set_mid.begin();
moveNum(set_mid, e, set_low);
sum -= e;
}
else {
set_high.erase(set_high.find(num));
int e = *set_mid.rbegin();
moveNum(set_mid, e, set_high);
sum -= e;
}
}
void moveNum(multiset<int>& a_set, int a, multiset<int>& b_set) {
b_set.insert(a);
a_set.erase(a_set.find(a));
}
private:
int m;
int k;
bool isReady = false;
queue<int> que;
vector<int> data;
multiset<int> set_low;
multiset<int> set_mid;
multiset<int> set_high;
long long sum = 0;
};
```
|
Java
|
UTF-8
| 2,397 | 2.375 | 2 |
[] |
no_license
|
package com.switchfully.spaceshark.model.parkingLot;
import com.switchfully.spaceshark.model.Price;
import com.switchfully.spaceshark.model.addresses.Address;
import com.switchfully.spaceshark.model.people.ContactPerson;
import javax.persistence.*;
@Entity
@Table (name = "parkinglot")
public class Parkinglot {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private int id;
@Column (name = "name")
private String name;
@Column (name = "category")
@Enumerated(EnumType.STRING)
private Category category;
@Column (name = "max_capacity")
private int maxCapacity;
@Embedded
private Price pricePerHour;
@ManyToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "contact_person_id")
private ContactPerson contactPerson;
@ManyToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "address_id")
private Address address;
public Parkinglot(String name, Category category, int maxCapacity, Price pricePerHour, ContactPerson contactPerson, Address address) {
this.name = name;
this.category = category;
this.maxCapacity = maxCapacity;
this.pricePerHour = pricePerHour;
this.contactPerson = contactPerson;
this.address = address;
}
public Parkinglot(){
}
public Price getPricePerHour() {
return pricePerHour;
}
public void setPricePerHour(Price pricePerHour) {
this.pricePerHour = pricePerHour;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public int getMaxCapacity() {
return maxCapacity;
}
public void setMaxCapacity(int maxCapacity) {
this.maxCapacity = maxCapacity;
}
public ContactPerson getContactPerson() {
return contactPerson;
}
public void setContactPerson(ContactPerson contactPerson) {
this.contactPerson = contactPerson;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
|
JavaScript
|
UTF-8
| 1,015 | 2.640625 | 3 |
[] |
no_license
|
'use strict';
/**
* @type {Symbol}
*/
let singleton = Symbol();
/**
* @type {Symbol}
*/
let singletonEnforcer = Symbol()
/**
* Scene of the Game.
* Created with PhysiJS
*
* @class Scene
*/
class Scene {
constructor(enforcer) {
if(enforcer != singletonEnforcer) throw "Cannot construct singleton Scene";
Physijs.scripts.worker = '/dist/js/physijs_worker.js';
Physijs.scripts.ammo = '/dist/js/ammo.js';
/**
* @type {Physijs.Scene}
* @private
*/
window.scene = this._scene = new Physijs.Scene({ fixedTimeStep: 1 / 120 });
this.scene.setGravity(new THREE.Vector3( 0, -10, 0 ));
}
/**
* @returns {Scene}
*/
static get instance() {
if(!this[singleton]) {
this[singleton] = new Scene(singletonEnforcer);
}
return this[singleton];
}
/**
* @returns {THREE.Scene}
*/
get scene() {
return this._scene;
}
}
export default Scene.instance;
|
C#
|
UTF-8
| 1,244 | 2.53125 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Door : MonoBehaviour {
public bool open = false;
public float doorOpenAngle = -90f;
public float doorClosedAngle = 0f;
public float doorAngleX = -90f;
public float doorAngleZ = 0f;
public float smooth = 2f; //speed of rotation
public bool isLocked = false;
public AudioSource audioSource;
public AudioClip openingSound;
public AudioClip lockedSound;
void Start(){
audioSource = GetComponent<AudioSource> ();
open = false;
}
public void ChangeDoorState(){
if (isLocked != true) {
open = !open;
if (audioSource != null) {
audioSource.PlayOneShot (openingSound);
}
} else {
audioSource.PlayOneShot (lockedSound);
}
}
void Update () {
if (open == true) {
Quaternion targetRotationOpen = Quaternion.Euler (doorAngleX, doorOpenAngle, doorAngleZ);
transform.localRotation = Quaternion.Slerp (transform.localRotation, targetRotationOpen, smooth * Time.deltaTime);
} else {
Quaternion targetRotationClosed = Quaternion.Euler (doorAngleX, doorClosedAngle, doorAngleZ);
transform.localRotation = Quaternion.Slerp (transform.localRotation, targetRotationClosed, smooth * Time.deltaTime);
}
}
}
|
JavaScript
|
UTF-8
| 3,825 | 2.5625 | 3 |
[] |
no_license
|
import React, { Component } from "react";
import Footer from "./Footer";
import { firestore } from "../components/firebase/firebase";
class Contact extends Component {
constructor() {
super();
this.state = {
firstName: "",
lastName: "",
email: "",
subject: "",
message: "",
};
}
firstNameChange = (event) => {
this.setState({ firstName: event.target.value });
};
lastNameChange = (event) => {
this.setState({ lastName: event.target.value });
};
emailChange = (event) => {
this.setState({ email: event.target.value });
};
subjectChange = (event) => {
this.setState({ subject: event.target.value });
};
messageChange = (event) => {
this.setState({ message: event.target.value });
};
reset = () => {
this.setState({
firstName: "",
lastName: "",
email: "",
subject: "",
message: "",
});
};
formSubmitHandler = (event) => {
event.preventDefault();
if (this.state.message.length > 20) {
const snapShot = firestore.doc(
`learnabiContactUs/form:email:${this.state.email}`
);
snapShot.get().then((doc) => {
if (!doc.exists) {
snapShot.set({
first:
this.state.firstName.charAt(0).toUpperCase() +
this.state.firstName.slice(1),
last:
this.state.lastName.charAt(0).toUpperCase() +
this.state.lastName.slice(1),
email: this.state.email,
subject: this.state.subject,
message: this.state.message,
});
alert("The form has been submitted successfully");
this.reset();
} else {
alert(
"Duplicates are not allowed. We respond in two business days. Thank you for your patience"
);
this.reset();
}
});
} else {
alert("Message is too short");
}
};
render() {
return (
<>
<div id="contact-background">
<section>
<div id="contact-title-div">
<h1>Contact Us</h1>
<i className="fas fa-envelope-open-text"></i>
</div>
<div id="form-div">
<form onSubmit={this.formSubmitHandler}>
<input
type="text"
name="firstName"
placeholder="First Name"
value={this.state.firstName}
onChange={this.firstNameChange}
required
></input>
<input
type="text"
name="lastName"
placeholder="Last Name"
value={this.state.lastName}
onChange={this.lastNameChange}
></input>
<input
type="email"
name="email"
placeholder="Email"
value={this.state.email}
onChange={this.emailChange}
required
></input>
<input
type="text"
name="subject"
placeholder="Subject"
value={this.state.subject}
onChange={this.subjectChange}
></input>
<textarea
type="text"
name="message"
placeholder="Enter a maximum of 1000 characters"
maxlength="1000"
value={this.state.message}
onChange={this.messageChange}
></textarea>
<button type="submit">Submit</button>
</form>
</div>
</section>
</div>
<Footer />
</>
);
}
}
export default Contact;
|
Java
|
UTF-8
| 701 | 1.984375 | 2 |
[] |
no_license
|
package com.bcd.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bcd.dao.UserDao;
import com.bcd.entity.User;
import com.bcd.util.PageBean;
@Service
@Transactional(readOnly=false)
public class UserService {
@Resource
private UserDao userDao;
public PageBean<User> findAll(User user,PageBean<User> pageBean){
return userDao.findAll(user,pageBean);
}
public int add(User user){
return userDao.add(user);
}
public int delete(User user){
return userDao.delete(user);
}
public int update(User user){
return userDao.update(user);
}
}
|
JavaScript
|
UTF-8
| 2,622 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
import React, { useState, useEffect, useRef } from 'react';
import Player from '../../components/player/Player';
import Opponent from '../../components/opponent/Opponent';
import css from './Game.sass';
const Game = () => {
// Just hardcode for now
const players = [
'player',
'cpu1',
'cpu2',
'cpu3',
];
// State
const [ selected, setSelected] = useState([]);
const [ handLabel, setHandLabel ] = useState('Pass');
const [ wasm, setWasm ] = useState(null);
const [ game, setGame ] = useState(null);
// Load WASM library
useEffect(() => {
import( /* webpackChunkName: "wasm" */'wasm-pusoy-dos').then(wasm => {
setWasm(wasm);
});
}, []);
// Get Move Label
useEffect(() => {
const move = wasm &&
wasm.get_hand_type(selected) ||
{type: 'Invalid Hand'};
switch (move.type) {
case 'single':
setHandLabel(`${move.cards.card.rank} of ${move.cards.card.suit.name}`);
break;
case 'pair':
case 'prial':
setHandLabel(`${move.type} of ${move.cards[0].card.rank}`);
break;
case 'fivecardtrick':
switch (move.cards.trick_type) {
case 'Flush':
setHandLabel(`${move.cards.cards[0].card.suit.name} flush`);
break;
case 'FullHouse':
setHandLabel(`Full House`);
break;
default:
setHandLabel(move.cards.trick_type);
break;
}
break;
default:
setHandLabel(move.type);
}
}, [selected, wasm]);
// Functions/Callbacks
function onDeal() {
setGame(wasm.create_game(players));
}
function getPlayerCards(player) {
return wasm.get_player(game, player);
}
function getHiddenCards(player) {
return getPlayerCards(player).map((_, index) => index);
}
// HTML
const table = game ? (
<div className={css.game}>
<div className={css.opponents}>
<div id={css.cpu1}>
<Opponent cards={getHiddenCards(players[1])} vertical={true} />
</div>
<div id={css.cpu2}>
<Opponent cards={getHiddenCards(players[2])} />
</div>
<div id={css.cpu3}>
<Opponent cards={getHiddenCards(players[3])} vertical={true} />
</div>
</div>
<div className={css.player}>
<Player cards={getPlayerCards(players[0])} onSelect={setSelected} />
</div>
<div>{handLabel}</div>
</div>
) : (
<button onClick={onDeal}>Deal!</button>
);
return wasm ? (
table
) : (
<h1>Loading</h1>
);
}
export default Game;
|
Java
|
UTF-8
| 2,779 | 2.34375 | 2 |
[
"MIT"
] |
permissive
|
// Generated from D:/Projects/MT/LALR/src/main/java/util/grammar\GrammarParser.g4 by ANTLR 4.7.2
package util.grammar;
import org.antlr.v4.runtime.tree.ParseTreeListener;
/**
* This interface defines a complete listener for a parse tree produced by
* {@link GrammarParserParser}.
*/
public interface GrammarParserListener extends ParseTreeListener {
/**
* Enter a parse tree produced by {@link GrammarParserParser#start}.
* @param ctx the parse tree
*/
void enterStart(GrammarParserParser.StartContext ctx);
/**
* Exit a parse tree produced by {@link GrammarParserParser#start}.
* @param ctx the parse tree
*/
void exitStart(GrammarParserParser.StartContext ctx);
/**
* Enter a parse tree produced by {@link GrammarParserParser#file}.
* @param ctx the parse tree
*/
void enterFile(GrammarParserParser.FileContext ctx);
/**
* Exit a parse tree produced by {@link GrammarParserParser#file}.
* @param ctx the parse tree
*/
void exitFile(GrammarParserParser.FileContext ctx);
/**
* Enter a parse tree produced by {@link GrammarParserParser#terminals}.
* @param ctx the parse tree
*/
void enterTerminals(GrammarParserParser.TerminalsContext ctx);
/**
* Exit a parse tree produced by {@link GrammarParserParser#terminals}.
* @param ctx the parse tree
*/
void exitTerminals(GrammarParserParser.TerminalsContext ctx);
/**
* Enter a parse tree produced by {@link GrammarParserParser#terminal}.
* @param ctx the parse tree
*/
void enterTerminal(GrammarParserParser.TerminalContext ctx);
/**
* Exit a parse tree produced by {@link GrammarParserParser#terminal}.
* @param ctx the parse tree
*/
void exitTerminal(GrammarParserParser.TerminalContext ctx);
/**
* Enter a parse tree produced by {@link GrammarParserParser#nonterminals}.
* @param ctx the parse tree
*/
void enterNonterminals(GrammarParserParser.NonterminalsContext ctx);
/**
* Exit a parse tree produced by {@link GrammarParserParser#nonterminals}.
* @param ctx the parse tree
*/
void exitNonterminals(GrammarParserParser.NonterminalsContext ctx);
/**
* Enter a parse tree produced by {@link GrammarParserParser#first}.
* @param ctx the parse tree
*/
void enterFirst(GrammarParserParser.FirstContext ctx);
/**
* Exit a parse tree produced by {@link GrammarParserParser#first}.
* @param ctx the parse tree
*/
void exitFirst(GrammarParserParser.FirstContext ctx);
/**
* Enter a parse tree produced by {@link GrammarParserParser#nonterminal}.
* @param ctx the parse tree
*/
void enterNonterminal(GrammarParserParser.NonterminalContext ctx);
/**
* Exit a parse tree produced by {@link GrammarParserParser#nonterminal}.
* @param ctx the parse tree
*/
void exitNonterminal(GrammarParserParser.NonterminalContext ctx);
}
|
Java
|
UTF-8
| 5,231 | 2.15625 | 2 |
[] |
no_license
|
package sg.edu.nus.comp.android3dvisualisationtool.app;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.FragmentManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import sg.edu.nus.comp.android3dvisualisationtool.app.UI.NavigationDrawerFragment;
import sg.edu.nus.comp.android3dvisualisationtool.app.UI.SliderFragment;
import sg.edu.nus.comp.android3dvisualisationtool.app.dataReader.DataReader;
import sg.edu.nus.comp.android3dvisualisationtool.app.openGLES20Support.GLES20SurfaceView;
public class MainActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks, SliderFragment.OnFragmentInteractionListener {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private SliderFragment mDialog_fragment = new SliderFragment();
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
// opengles view
private GLES20SurfaceView mGLSurfaceView;
//window size
public static int width, height;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
mDialog_fragment = (SliderFragment)
getFragmentManager().findFragmentById(R.id.drawer_layout);
initialiseOpenGLESView();
calculateWindowSize();
}
private void calculateWindowSize() {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
try {
int id = item.getItemId();
if (id == R.id.action_dialog) {
FragmentManager fm = getFragmentManager();
mDialog_fragment = mDialog_fragment == null ? new SliderFragment() : mDialog_fragment;
mDialog_fragment.show(fm, "fragment_dialog");
}
return super.onOptionsItemSelected(item);
} catch (Exception ex) {
ex.printStackTrace();
return super.onOptionsItemSelected(item);
}
}
// methods for opengles support
private boolean hasGLES20() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
return configurationInfo.reqGlEsVersion >= 0x20000;
}
private void initialiseOpenGLESView() {
if (hasGLES20()) {
mGLSurfaceView = (GLES20SurfaceView) findViewById(R.id.gl_surface_view);
// set the content for dataReader to read the data file later
DataReader.setContext(getApplicationContext());
} else {
System.out.println("This phone does not support OpenGLES 2.0, quiting...");
System.exit(1);
}
}
@Override
protected void onResume() {
super.onResume();
if (mGLSurfaceView != null)
mGLSurfaceView.onResume();
}
@Override
protected void onPause() {
super.onPause();
if (mGLSurfaceView != null)
mGLSurfaceView.onPause();
}
// handle dialog event
@Override
public void onFragmentInteraction(Uri uri) {
}
@Override
public void onNavigationDrawerItemSelected(int position) {
}
}
|
Java
|
UTF-8
| 4,037 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
package jpaoletti.jpm2.core.converter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jpaoletti.jpm2.core.exception.ConfigurationException;
import jpaoletti.jpm2.core.exception.ConverterException;
import jpaoletti.jpm2.core.model.ContextualEntity;
import jpaoletti.jpm2.core.model.Field;
import jpaoletti.jpm2.util.JPMUtils;
/**
* properties is something like "{prop1} ... {prop2}" where each prop is a
* property of the field value.
*
* @author jpaoletti
*/
public class ToStringConverter extends Converter {
public static final Pattern DISPLAY_PATTERN = Pattern.compile("\\{.*?\\}");
private Integer padCount = 0;
private String prefix;
private String suffix;
private Character padChar = ' ';
private PadDirection padDirection = PadDirection.LEFT;
private Integer cutOff;
private String properties;
private String nullValue = "-";
@Override
public Object visualizeValue(ContextualEntity contextualEntity, Field field, Object value, String instanceId) throws ConverterException, ConfigurationException {
return process(value);
}
protected String process(final Object value) {
String res = (value == null) ? getNullValue() : getFinalValue(value, getProperties());
if (getCutOff() != null && res.length() > getCutOff()) {
res = res.substring(0, getCutOff()) + "...";
}
switch (getPadDirection()) {
case LEFT:
res = JPMUtils.padleft(res, getPadCount(), getPadChar());
break;
case RIGHT:
res = JPMUtils.padright(res, getPadCount(), getPadChar());
break;
}
if (getPrefix() != null) {
res = getPrefix() + res;
}
if (getSuffix() != null) {
res = res + getSuffix();
}
return res;
}
public static String getFinalValue(Object value, String properties) {
String finalValue;
if (properties != null) {
final Matcher matcher = DISPLAY_PATTERN.matcher(properties);
finalValue = properties;
while (matcher.find()) {
final String property = matcher.group();
final String _display = property.replaceAll("\\{", "").replaceAll("\\}", "");
try {
finalValue = finalValue.replace(property, String.valueOf(JPMUtils.get(value, _display)));
} catch (ConfigurationException ex) {
finalValue = finalValue.replace("{" + _display + "}", "?");
}
}
} else {
finalValue = String.valueOf(value);
}
return finalValue;
}
public Integer getPadCount() {
return padCount;
}
public void setPadCount(Integer padCount) {
this.padCount = padCount;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String sufix) {
this.suffix = sufix;
}
public Character getPadChar() {
return padChar;
}
public void setPadChar(Character padChar) {
this.padChar = padChar;
}
public PadDirection getPadDirection() {
return padDirection;
}
public void setPadDirection(PadDirection padDirection) {
this.padDirection = padDirection;
}
public Integer getCutOff() {
return cutOff;
}
public void setCutOff(Integer cutOff) {
this.cutOff = cutOff;
}
public String getProperties() {
return properties;
}
public void setProperties(String properties) {
this.properties = properties;
}
public String getNullValue() {
return nullValue;
}
public void setNullValue(String nullValue) {
this.nullValue = nullValue;
}
public static enum PadDirection {
LEFT, RIGHT
}
}
|
C
|
UTF-8
| 6,126 | 2.5625 | 3 |
[] |
no_license
|
#include "include/ft_printf.h"
void compil_testper(int i, int j, int k)
{
j = printf("%d\n>>%%<<\n", i);
fflush(stdout);
k = ft_printf(">>%%<<");
fflush(stdout);
printf(" Diff = %d\n", (j - k - 3));
fflush(stdout);
}
void compil_testper1(int j, int k)
{
j = printf(">>%%<<\n");
fflush(stdout);
k = ft_printf(">>%%<<");
printf(" Diff = %d\n", (j - k - 1));
fflush(stdout);
}
void compil_testper1_1(int j, int k)
{
j = printf(">>%% et %%<<\n");
fflush(stdout);
k = ft_printf(">>%% et %%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper2_0(int j, int k)
{
j = printf(">>%.0%<<\n");
fflush(stdout);
k = ft_printf(">>%.0%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper2_1(int j, int k)
{
j = printf(">>%.5%<<\n");
fflush(stdout);
k = ft_printf(">>%.5%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper2_2(int j, int k)
{
j = printf(">>%.%<<\n");
fflush(stdout);
k = ft_printf(">>%.%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper2_3(int j, int k)
{
j = printf(">>%.34%<<\n");
fflush(stdout);
k = ft_printf(">>%.34%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper2_4(int j, int k)
{
j = printf(">>%.010%<<\n");
fflush(stdout);
k = ft_printf(">>%.010%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper3_0(int j, int k)
{
j = printf(">>%10%<<\n");
fflush(stdout);
k = ft_printf(">>%10%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper3_1(int j, int k)
{
j = printf(">>%0%<<\n");
fflush(stdout);
k = ft_printf(">>%0%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper3_2(int j, int k)
{
j = printf(">>%34%<<\n");
fflush(stdout);
k = ft_printf(">>%34%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper3_3(int j, int k)
{
j = printf(">>%-10%<<\n");
fflush(stdout);
k = ft_printf(">>%-10%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper3_4(int j, int k)
{
j = printf(">>%-30%<<\n");
fflush(stdout);
k = ft_printf(">>%-30%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper3_5(int j, int k)
{
j = printf(">>%20% et %15%<<\n");
fflush(stdout);
k = ft_printf(">>%20% et %15%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper4_0(int j, int k)
{
j = printf(">>%-30.1%<<\n");
fflush(stdout);
k = ft_printf(">>%-30.1%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper4_1(int j, int k)
{
j = printf(">>%-1.30%<<\n");
fflush(stdout);
k = ft_printf(">>%-1.30%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper4_2(int j, int k)
{
j = printf(">>%30.1%<<\n");
fflush(stdout);
k = ft_printf(">>%30.1%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper4_3(int j, int k)
{
j = printf(">>%1.30%<<\n");
fflush(stdout);
k = ft_printf(">>%1.30%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper4_4(int j, int k)
{
j = printf(">>%-%<<\n");
fflush(stdout);
k = ft_printf(">>%-%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper4_5(int j, int k)
{
j = printf(">>%-.30%<<\n");
fflush(stdout);
k = ft_printf(">>%-.30%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper4_6(int j, int k)
{
j = printf(">>%-.5%<<\n");
fflush(stdout);
k = ft_printf(">>%-.5%<<");
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper5_0(int j, int k)
{
j = printf(">>%030%<<\n");
fflush(stdout);
k = ft_printf(">>%030%<<");
fflush(stdout);
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper5_1(int j, int k)
{
j = printf(">>%.05%<<\n");
fflush(stdout);
k = ft_printf(">>%.05%<<");
fflush(stdout);
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper5_2(int j, int k)
{
j = printf(">>%05%<<\n");
fflush(stdout);
k = ft_printf(">>%05%<<");
fflush(stdout);
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper5_3(int j, int k)
{
j = printf(">>%0.30%<<\n");
fflush(stdout);
k = ft_printf(">>%0.30%<<");
fflush(stdout);
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper5_4(int j, int k)
{
j = printf(">>%-05%<<\n");
fflush(stdout);
k = ft_printf(">>%-05%<<");
fflush(stdout);
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper5_5(int j, int k)
{
j = printf("4567 |%-10]5d| plip\n", 12);
fflush(stdout);
k = ft_printf("4567 |%-10]5d| plip", 12);
fflush(stdout);
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void compil_testper5_6(int j, int k)
{
j = printf("4567 |%10]5d| plip\n", 12);
fflush(stdout);
k = ft_printf("4567 |%10]5d| plip", 12);
fflush(stdout);
printf(" Diff = %d\n", j - k - 1);
fflush(stdout);
}
void test_per(void)
{
int i = 1;
while (i < 2)
{
compil_testper(i, 0, 0);
compil_testper1(i, 0);
compil_testper1_1(i, 0);
compil_testper2_0(0, 0);
compil_testper2_1(0, 0);
compil_testper2_2(0, 0);
compil_testper2_3(0, 0);
compil_testper2_4(0, 0);
printf("----------------------------------------------------------\n");
compil_testper3_0(0, 0);
compil_testper3_1(0, 0);
compil_testper3_2(0, 0);
compil_testper3_3(0, 0);
compil_testper3_4(0, 0);
compil_testper3_5(0, 0);
printf("----------------------------------------------------------\n");
compil_testper4_0(0, 0);
compil_testper4_1(0, 0);
compil_testper4_2(0, 0);
compil_testper4_3(0, 0);
compil_testper4_4(0, 0);
compil_testper4_5(0, 0);
compil_testper4_6(0, 0);
printf("----------------------------------------------------------\n");
compil_testper5_0(0, 0);
compil_testper5_1(0, 0);
compil_testper5_2(0, 0);
compil_testper5_3(0, 0);
compil_testper5_4(0, 0);
compil_testper5_5(0, 0);
compil_testper5_6(0, 0);
i++;
}
}
|
Python
|
UTF-8
| 869 | 2.6875 | 3 |
[] |
no_license
|
#when writing Python scripts in which you manipulate an entry in the Workspace, you need to synchronize the Workspace changes with the Project Table before using a Structure entry from the Project Table.
import sys,os
from schrodinger.maestro import maestro
from schrodinger import project
from schrodinger import surface
#get the project table
pt = maestro.project_table_get()
print 'length of all rows in the project table:' , len(pt.all_rows)
#empty lists
all_structures = []
included_structures = []
print 'length of included structures before addition:' , len(included_structures)
for row in pt.all_rows:
row.is_selected = True
included_structures.append(row.getStructure())
print 'length of included structures after addition:' , len(included_structures)
print 'length of selected structures after addition:' , len(pt.selected_rows)
#maestro.redraw()
|
PHP
|
UTF-8
| 4,006 | 2.6875 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
namespace DaPigGuy\PiggyCrates\Tasks;
use DaPigGuy\PiggyCrates\Main;
use DaPigGuy\PiggyCustomEnchants\CustomEnchants\CustomEnchants;
use pocketmine\block\Block;
use pocketmine\command\ConsoleCommandSender;
use pocketmine\item\enchantment\Enchantment;
use pocketmine\item\enchantment\EnchantmentInstance;
use pocketmine\item\Item;
use pocketmine\Player;
use pocketmine\scheduler\Task;
/**
* Class DropsTask
* @package DaPigGuy\PiggyCrates\Tasks
*/
class DropsTask extends Task
{
/** @var Main */
private $plugin;
/** @var Player */
private $player;
/** @var Block */
private $block;
/** @var Item */
private $key;
/** @var string */
private $type;
/** @var bool */
private $startingTitleComplete = false;
/** @var array */
private $drops;
/** @var array */
private $pickedDrops;
/** @var array */
private $items;
/**
* DropsTask constructor.
* @param Main $plugin
* @param Player $player
* @param Block $block
* @param Item $key
* @param string $type
* @param array $drops
* @param array $pickedDrops
*/
public function __construct(Main $plugin, Player $player, Block $block, Item $key, string $type, array $drops, array $pickedDrops)
{
$this->plugin = $plugin;
$this->player = $player;
$this->block = $block;
$this->key = $key;
$this->type = $type;
$this->drops = $drops;
$this->pickedDrops = $pickedDrops;
}
/**
* @param int $currentTick
*/
public function onRun(int $currentTick)
{
$player = $this->player;
$item = $this->key;
if (!$this->startingTitleComplete) {
$player->getInventory()->removeItem($item->setCount(1));
$player->addTitle("You Have Received");
$this->startingTitleComplete = true;
return;
}
$pickedDrop = reset($this->pickedDrops);
$values = $this->drops[$pickedDrop];
$i = Item::get($values["id"], $values["meta"], $values["amount"]);
$i->setCustomName($values["name"]);
if (isset($values["enchantments"])) {
foreach ($values["enchantments"] as $enchantment => $enchantmentinfo) {
$level = $enchantmentinfo["level"];
/** @var \DaPigGuy\PiggyCustomEnchants\Main $ce */
$ce = $this->plugin->getServer()->getPluginManager()->getPlugin("PiggyCustomEnchants");
if (!is_null($ce) && !is_null($enchant = CustomEnchants::getEnchantmentByName($enchantment))) {
$i = $ce->addEnchantment($i, $enchantment, $level);
} else {
if (!is_null($enchant = Enchantment::getEnchantmentByName($enchantment))) {
$i->addEnchantment(new EnchantmentInstance($enchant, $level));
}
}
}
}
if (isset($values["lore"])) {
$i->setLore([$values["lore"]]);
}
if (isset($values["commands"])) {
foreach ($values["commands"] as $command) {
$command = str_replace(["%PLAYER%"], [$player->getName()], $command);
$this->plugin->getServer()->dispatchCommand(new ConsoleCommandSender(), $command);
}
}
$this->items[] = $i;
$player->addTitle("", "");
$player->addTitle("", $values["amount"] . " " . $values["name"]);
$particles = "pocketmine\\level\\particle\\" . ucfirst($this->plugin->getCrateDropParticle($this->type)) . "Particle";
if (class_exists($particles)) {
$this->block->getLevel()->addParticle(new $particles($this->block->add(0, 2)));
}
array_shift($this->pickedDrops);
if (count($this->pickedDrops) <= 0) {
$player->getInventory()->addItem(...$this->items);
$this->plugin->getScheduler()->cancelTask($this->getHandler()->getTaskId());
}
}
}
|
Ruby
|
UTF-8
| 1,212 | 2.609375 | 3 |
[] |
no_license
|
# == Schema Information
#
# Table name: follows
#
# id :integer not null, primary key
# user_id :integer not null
# followable_type :string
# followable_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Follow < ApplicationRecord
validates :followable_id, :followable_type, :user, presence: true
validates :user_id, uniqueness: { scope: [:followable_id, :followable_type] }
validate :user_cannot_follow_own_playlist
validate :user_cannot_follow_self
belongs_to :followable, polymorphic: true
belongs_to :user
def user_cannot_follow_own_playlist
if user_is_playlist_creator
errors.add(:user, "cannot follow own playlist")
end
end
def user_cannot_follow_self
if user_is_self
errors.add(:user, "can't follow themself")
end
end
private
def user_is_playlist_creator
self.followable_type == 'Playlist' && Playlist.find(self.followable_id).creator_id == self.user_id
end
def user_is_self
self.user_id == self.followable_id && self.followable_type == 'User'
end
end
|
Swift
|
UTF-8
| 329 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
//
// StreamMessage.swift
// SampleAgoraBroadcast
//
// Created by Roger Carvalho on 03/08/2020.
// Copyright © 2020 Roger Carvalho. All rights reserved.
//
import Foundation
/**
Holds the dictionary keys for messages sent between host and audience
*/
enum StreamMessage: String {
case MessageType = "type"
case Data = "data"
}
|
Java
|
UTF-8
| 2,373 | 2.390625 | 2 |
[] |
no_license
|
package com.dxc.common_tools.kafka;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class resultsProducer {
private Logger logger;
private String bootstrapServers;
private String topic;
private Properties properties;
private KafkaProducer<String, String> producer;
private ProducerRecord<String,String> record;
public resultsProducer(String bootstrapServers, String topic) {
this.bootstrapServers = bootstrapServers;
this.topic = topic;
logger = LoggerFactory.getLogger(resultsProducer.class);
// TODO Auto-generated method stub
System.out.println("Portal producer");
//create properties
properties = new Properties();
properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers );
properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName() );
properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName() );
}
public void produceToTopic(String message) throws InterruptedException, ExecutionException {
producer = new KafkaProducer<String, String>(properties);
record = new ProducerRecord<String,String>(topic, "id", message);
producer.send(record, new Callback() {
public void onCompletion(RecordMetadata recordMetadata, Exception e) {
if (e== null) {
logger.info("Successfully received the details as: \n" +
"Topic: " + recordMetadata.topic() + "\n" +
"Partition: " + recordMetadata.partition() + "\n" +
"Offset " + recordMetadata.offset() + "\n" +
"Timestamp " + recordMetadata.timestamp());
}
else {
logger.error("Can't produce,getting error",e);
}
}
}).get();
//flush data
producer.flush();
//flush and close
producer.close();
}
}
|
Java
|
GB18030
| 278 | 2.453125 | 2 |
[] |
no_license
|
package com.design.pattern.behavioral.strategy.imooc;
/**
* Created by geely
*/
public class LiJianPromotionStrategy implements PromotionStrategy {
public void doPromotion() {
System.out.println(",γ̵ļ۸ֱӼȥõļ۸");
}
}
|
JavaScript
|
UTF-8
| 1,284 | 3.171875 | 3 |
[] |
no_license
|
function solve(input) {
var start = parseInt(input[0]);
var end = parseInt(input[1]);
console.log("<table>");
console.log("<tr><th>Num</th><th>Square</th><th>Fib</th></tr>")
for (var i = start; i <= end; i++) {
var result = [];
var currentResult = 'no';
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 5:
case 8:
case 13:
case 21:
case 34:
case 55:
case 89:
case 144:
case 233:
case 377:
case 610:
case 987:
case 1597:
case 2584:
case 4181:
case 6765:
case 10946:
case 17711:
case 28657:
case 46368:
case 750258:
case 121393:
case 196418:
case 317811:
case 514229:
case 832040:
case 1346269:
case 2178309:
case 3524578:
case 5702887:
currentResult = "yes";
break;
}
console.log("<tr><td>" + i + "</td>" + "<td>" + (i * i) + "</td>" + "<td>" + currentResult + "</td></tr>");
}
console.log("</table>");
}
solve([ '2', '6', '' ])
|
Java
|
UTF-8
| 476 | 3.421875 | 3 |
[] |
no_license
|
public class SimpleSingletoneClass {
private static SimpleSingletoneClass instance;
private SimpleSingletoneClass(){
}
public static SimpleSingletoneClass getInstance(){
if(instance == null){
System.out.println("Returned new instance");
instance = new SimpleSingletoneClass();
return instance;
}
//the second condition just for checking, we can do it without else
else{
System.out.println("Returned existed instance");
return instance;
}
}
}
|
C++
|
UTF-8
| 536 | 3.09375 | 3 |
[] |
no_license
|
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
int n,k;
string input;
cin >> n >> k;
cin >> input ;
int mid = n/2;
int i;
int flag = 0;
for(i=n-1;i>=1;i--)
{
int si = n - i;
if(input.substr(0,i) == input.substr(si,i))
{
flag = 1;
break;
}
}
string output;
if(flag == 0)
{
for(int i=0;i<k;i++)
output += input;
}
else
{
string temp = input.substr(i);
output = input;
for(int i=1;i<k;i++)
output += temp;
}
cout << output << endl;
}
|
Markdown
|
UTF-8
| 1,673 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
# express-upload-progress
Sample application to demonstrate file uploading with [express.js](http://expressjs.com/). The upload progress is shown in a progress bar, that is styled with [Twitter's Bootstrap](http://twitter.github.com/bootstrap/).
## Demo
[express-upload-progress.herokuapp.com/](http://express-upload-progress.herokuapp.com/)
Uploaded files are automatically deleted after 1 min.
Maximum file size is 2MB.
## Requirements
A `tmp` directory to store the uploaded files.
Works with the following browsers - [http://caniuse.com/#feat=xhr2](http://caniuse.com/#feat=xhr2)
## License
Copyright (C) 2012 [Mirco Zeiss](mailto: mirco.zeiss@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
JavaScript
|
UTF-8
| 875 | 2.609375 | 3 |
[] |
no_license
|
const Discord = require('discord.js');
const commonUtil = require('./utils/common-util.js');
const client = new Discord.Client();
const Token = 'MjUxMjA5NDQxNzA0MjgwMDc3.CzsZjQ.zz8y-OqJtJk6_BeOHSaTyOwuCYE';
client.on('ready', () => {
console.log('Blackwatch is keeping an eye on you...');
})
client.on('message', msg => {
// housekeeping
let prefix = "!";
if (!msg.content.startsWith(prefix)) return;
if (msg.author.bot) return;
// check message starts with !
if (msg.content.startsWith(prefix)) {
// strip message of !
let message = msg.content.replace(/!/g, '').toLowerCase();
// preparer
return commonUtil._prepare(message, client, msg);
}
// tests
if (msg.content.startsWith(prefix + 'ping')) {
msg.channel.sendMessage('pong!');
}
if (msg.content.startsWith(prefix + 'ayyy')) {
msg.channel.sendMessage('lmao');
}
});
client.login(Token);
|
Python
|
UTF-8
| 503 | 3.5 | 4 |
[] |
no_license
|
'''
@Description:
@Author: 陈十一
@Date: 2020-07-23 09:47:50
@LastEditTime: 2020-07-23 10:16:31
@LastEditors: 陈十一
'''
print("请输入m:")
m = int(input())
# 数学推导可得奇数范围,然后生成对应列表
nums = [i for i in range(m * m - m + 1, m * m + m + 1, 2)]
# 平平无奇的字符串拼接
output = str(m) + "*" + str(m) + "*" + str(m) + "\n=" + str(m*m*m) + "\n="
for i in nums:
output = output + str(i) + "+"
# 删除最后多余的加号后输出
print(output[:-1])
|
Java
|
UTF-8
| 1,480 | 2.75 | 3 |
[] |
no_license
|
package test;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Execution {
public static void main(String[] args) {
Student s = new Student("H234");
Student s2 = new Student("H234");
System.out.println(s.equals(s2));
Map<Student, ReportCard> studentReport = new HashMap<>();
studentReport.put(s, new ReportCard());
studentReport.put(s2, new ReportCard());
System.out.println(studentReport.size());
Set<Student> studentSet = new HashSet<>();
for(int i=0; i<100; i++) {
studentSet.add(new Student("H"+i));
}
System.out.println(studentSet.size());
long startTime = System.nanoTime();
System.out.println(studentSet.contains(new Student("H4")));
System.out.println("Elapsed Time:"+(System.nanoTime()-startTime));
Student s3 = new Student("H234");
System.out.println(s.equals(s));
System.out.println(s.equals(s2)+"---"+s2.equals(s));
System.out.println(s.equals(s2)+"---"+s2.equals(s3)+"---"+s.equals(s3));
System.out.println(s.equals(null));
}
}
//Collection<Student> l = new ArrayList<>();
//l.add(s1); l.addAll(l);
// !!!Object[] o = l.toArray();
//l.remove(s1);
//l.removeAll(l);
//l.clear();
//l.retainAll(l);
//boolean bl= l.contains(s1);
//boolean bl2= l.containsAll(l);
//boolean bl3= l.isEmpty();
//l.size();
//Set<Student> s = new TreeSet<>();
//Queue<Student> q = new PriorityQueue<>();
|
Python
|
UTF-8
| 775 | 3.015625 | 3 |
[] |
no_license
|
import cv2
class EyeDetector:
def __init__(self, faceCascadePath, eyeCascadePath):
self.faceCascade = cv2.CascadeClassifier(faceCascadePath)
self.eyeCascade = cv2.CascadeClassifier(eyeCascadePath)
def track(self, image):
faceRect = self.faceCascade.detectMultiScale(image, scaleFactor = 1.1,
minNeighbors = 3, minSize = (30,30), flags = cv2.CASCADE_SCALE_IMAGE)
rects = []
for (x,y,w,h) in faceRect:
faceROI = image[y:y+h, x:x+w]
rects.append((x,y,x+w,y+h))
eyeRects = self.eyeCascade.detectMultiScale(faceROI, scaleFactor=1.1,
minNeighbors=5, minSize=(10,10), flags = cv2.CASCADE_SCALE_IMAGE)
for (eX,eY,eW,eH) in eyeRects:
rects.append((x + eX, y + eY, x + eX + eW, y + eY + eH))
return rects
|
Java
|
UTF-8
| 2,453 | 3.140625 | 3 |
[] |
no_license
|
package main;
import java.math.BigDecimal;
import java.util.Random;
public class K_means_Strategy implements ClusteringStrategy {
private int cluster;
private VectorList vectorList;
private ClusterList clusterList ;
public boolean isEmpty = false;
public K_means_Strategy(int numberOfCluster, VectorList vectorList) {
this.cluster = numberOfCluster;
this.vectorList = vectorList;
this.clusterList = this.createClusterList();
}
private ClusterList createClusterList() {
ClusterList list = new ClusterList();
for(int i=0; i<this.cluster ; i++){
list.setCluster(new Cluster());
}
return list;
}
public ClusterList getClusterList(){
return this.clusterList;
}
public void setCentralPoint(){
for(Cluster cluster : clusterList.getList()){
cluster.setCentralPoint();
}
}
public void firstClustering(long seed) {
Random random = new Random(seed);
for(Vector vector : vectorList.getVectorList()){
int r = random.nextInt(cluster);
clusterList.getList().get(r).setVector(vector);
}
this.setCentralPoint();
}
public void clustering() {
//クラスタの中身を一度空にする
for(Cluster cluster : clusterList.getList()){
cluster.clean();
}
//距離の地番近いものに入れ直す
for(Vector vector : vectorList.getVectorList()){
BigDecimal distance = this.getDistance(vector, clusterList.getList().get(0));
int minimum = 0;
for(int i=1; i<clusterList.getList().size(); i++){
if(distance.equals(distance.min(this.getDistance(vector, clusterList.getList().get(i))))){
distance = this.getDistance(vector, clusterList.getList().get(i));
minimum = i;
}
}
clusterList.getList().get(minimum).setVector(vector);
}
}
private BigDecimal getDistance(Vector vector, Cluster cluster) {
BigDecimal x = cluster.getCentralPoint().get("X").subtract(new BigDecimal(vector.getData().get("X"))).abs();
BigDecimal y = cluster.getCentralPoint().get("Y").subtract(new BigDecimal(vector.getData().get("Y"))).abs();
return x.pow(2).add(y.pow(2));
}
public boolean validateThreshold() {
for(Cluster cluster : clusterList.getList()){
BigDecimal differ = cluster.movedCentralPoint();
if(!(differ == differ.min(new BigDecimal(0.1)))){
return false;
}
}
return false;
}
public boolean isEmpty(){
for(Cluster cluster : clusterList.getList()){
if(cluster.isEmpty()){
return true;
}
continue;
}
return false;
}
}
|
PHP
|
UTF-8
| 589 | 2.515625 | 3 |
[] |
no_license
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Purchase extends Model
{
use HasFactory;
protected $table = 'purchases';
/**
* The database primary key value.
*
* @var string
*/
protected $primaryKey = 'id';
/**
* Attributes that should be mass-assignable.
*
* @var array
*/
protected $hidden = [
'',
'remember_token',
];
protected $fillable = ['receipt', 'uid', 'status','user_uid','app_id','expire_date'];
}
|
JavaScript
|
UTF-8
| 1,365 | 2.625 | 3 |
[] |
no_license
|
import React, { useState, useEffect } from 'react';
import Card from '../../components/Cards/UserCard';
import Loader from '../../components/Loader';
import moment from 'moment';
function Users(){
const [state, setState] = useState([]);
useEffect(() => {
fetch('https://api.jsonbin.io/b/5d3c29c135e3f814032b5d2b')
.then((res) => res.json())
.then(({ data }) => {
let state = []
data.map(({ attributes }) => {
let name = attributes.name;
let email = attributes.email;
let status = attributes.status;
let start = Date.parse(attributes.starts_at) || null
let end = Date.parse(attributes.ends_at);
let startDate = start && moment(start).format("MMM Do, hh:mm");
let endDate = moment(end).format("MMM Do, hh:mm")
return state.push({ name, email, status, startDate, endDate })
})
setState(state)
})
}, []);
return (
<div className="view-container">
<div>
{
state.length > 0 ?
state.map((x,i) => (
<Card
key={i}
name={x.name}
email={x.email}
status={x.status}
startDate={x.startDate}
endDate={x.endDate}
/>
)) :
<Loader />
}
</div>
</div>
);
};
export default Users;
|
Java
|
UTF-8
| 1,628 | 3.828125 | 4 |
[] |
no_license
|
package practicce.rec;
public class MidtermsPractice {
public static int minimumNum(int a, int b, int c) {
return Math.min(Math.min(a, b), c);
}
public static int maximumNum(int x, int y, int z) {
return Math.max(Math.max(x, y), z);
}
public static int average(int a, int b, int c) {
int sum = (a + b + c) / 3;
return sum;
}
public static int countVowels(String str) {
int vowel = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e'
|| str.charAt(i) == 'i' || str.charAt(i) == 'o'
|| str.charAt(i) == 'u') {
vowel++;
}
}
return vowel;
}
public static void meth1(){
int[][] demo = new int[12][12];
int row = 1;
int col = 1;
for (int x = 0; x < demo.length; x++) {
for (int y = 0; y < demo[x].length; y++) {
demo[x][y] = row * col;
col = col + 1;
}
row = row + 1;
col = 1;
}
//for displaying the above code
for (int x = 0; x < demo.length; x++) {
for (int y = 0; y < demo[x].length; y++) {
System.out.print(" " + demo[x][y] + " | ");
}
System.out.println();
}
}
public static void main(String[] args) {
int a = 2;
int b = 2;
int c = 2;
meth1();
}
}
|
Go
|
UTF-8
| 2,809 | 3.015625 | 3 |
[] |
no_license
|
package db
import "fmt"
import "reflect"
import "regexp"
import "github.com/ziutek/mymysql/mysql"
import "time"
import "misc/naming"
var escape_regexp *regexp.Regexp
func init() {
escape_regexp = regexp.MustCompile(`(\'|\"|\.|\*|\/|\-|\\)`)
}
//----------------------------------------------- escape chars
func SQL_escape(v string) string {
return escape_regexp.ReplaceAllString(v, `\${1}`)
}
//----------------------------------------------- dump struct into sql (fields, values) array.
func SQL_dump(tbl interface{}, excludes ...string) (fields []string, values []string) {
v := reflect.ValueOf(tbl).Elem()
key := v.Type()
count := key.NumField()
fields = make([]string, count)
values = make([]string, count)
slice_idx := 0
for i := 0; i < count; i++ {
f := v.Field(i)
if f.CanSet() {
typeok := true
switch f.Type().String() {
case "int", "int8", "int16", "int32", "int64":
values[slice_idx] = fmt.Sprintf("'%d'", f.Interface())
case "uint", "uint8", "uint16", "uint32", "uint64":
values[slice_idx] = fmt.Sprintf("'%d'", f.Interface())
case "float32", "float64":
values[slice_idx] = fmt.Sprintf("'%f'", f.Interface())
case "string":
tmpstr := SQL_escape(f.Interface().(string))
values[slice_idx] = fmt.Sprintf("'%s'", tmpstr)
case "time.Time":
values[slice_idx] = fmt.Sprintf("'%s'", f.Interface().(time.Time).Format("2006-01-02 15:04:05"))
default:
typeok = false
}
if typeok {
// kickout excluded fields
fieldname := naming.UnderScore(key.Field(i).Name)
for ei := range excludes {
if excludes[ei] == fieldname {
goto L
}
}
fields[slice_idx] = fieldname
slice_idx++
}
}
L:
}
fields = fields[:slice_idx]
values = values[:slice_idx]
return
}
//----------------------------------------------- Load query result into the struct.
func SQL_load(tbl interface{}, row *mysql.Row, res mysql.Result) {
v := reflect.ValueOf(tbl).Elem()
for i, field := range res.Fields() {
f := v.FieldByName(naming.CamelCase(field.Name))
if f.IsValid() {
if f.CanSet() {
switch f.Type().String() {
case "int", "int8", "int16", "int32", "int64":
f.SetInt(int64(row.Int(i)))
case "uint", "uint8", "uint16", "uint32", "uint64":
f.SetUint(uint64(row.Uint(i)))
case "float32", "float64":
f.SetFloat(row.Float(i))
case "string":
f.SetString(row.Str(i))
case "time.Time":
t, _ := time.Parse("2006-01-02 15:04:05", row.Str(i))
f.Set(reflect.ValueOf(t))
}
}
}
}
}
//----------------------------------------------- SET xxx=nnn, xx=nn clause
func SQL_set_clause(fields []string, values []string) []string {
changes := make([]string, len(fields))
for i := range fields {
changes[i] = fields[i] + "=" + values[i]
}
return changes
}
|
Python
|
UTF-8
| 1,607 | 3.71875 | 4 |
[] |
no_license
|
# -------------------------------------------------------------------------------------------------------------------
# -------------------------------- Decompose Conditional ------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------------------
# [Problem]: ou have a complex conditional (if-then/else or switch)
# [Solution]: Decompose the complicated parts of the conditional into separate methods: the condition, then and else.
# -------------------------------------------------------------------------------------------------------------------
from datetime import date
SUMMER_START = '12/06/2020'
SUMMER_END = '31/10/2020'
winterRate, summerRate = 0.5, 0.6
quantity = int(input('please enter quantity: '))
winterServiceCharge = float(input('please enter winterServiceCharge: '))
# [Problem]: ou have a complex conditional (if-then/else or switch)
if date.before(SUMMER_START) or date.after(SUMMER_END):
charge = quantity * winterRate + winterServiceCharge
else:
charge = quantity * summerRate
# [Solution]: Decompose the complicated parts of the conditional into separate methods: the condition, then and else.
def is_winter():
return date.before(SUMMER_START) or date.after(SUMMER_END)
def winter_rate():
return quantity * winterRate + winterServiceCharge
def summar_rate():
return quantity * summerRate
if is_winter():
charge = winter_rate()
else:
charge = summar_rate()
# Solution ---- > Extract Methods
|
Java
|
UTF-8
| 663 | 3.09375 | 3 |
[] |
no_license
|
package com.learncode.tree;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class Ex05LevelOrderSpiralTraversalTest {
@Test
void traverse() {
Tree<Integer> tree = new Tree<>();
Node root = tree.addRoot(4);
Node two = tree.addToLeftOf(root, 2);
Node five = tree.addToRightOf(root, 5);
Node one = tree.addToLeftOf(two, 1);
Node three = tree.addToRightOf(two, 3);
Node six = tree.addToLeftOf(five, 6);
Node seven = tree.addToRightOf(five, 7);
assertEquals("4 2 5 7 6 3 1 ", new Ex05LevelOrderSpiralTraversal<Integer>().traverse(tree));
}
}
|
Swift
|
UTF-8
| 2,069 | 2.6875 | 3 |
[] |
no_license
|
//
// MyScrollTextView.swift
// MyScrollBannerView
//
// Created by OOPer in cooperation with shlab.jp, on 2016/3/27.
// Copyright © 2016 OOPer (NAGATA, Atsuyuki). All rights reserved. See LICENSE.txt .
//
import UIKit
class MyScrollTextView: UIScrollView {
var animationPixelsPerSecond: CGFloat = 60
var animationInterval: TimeInterval = 0.016
fileprivate var label: UILabel?
fileprivate var animationTimer: Timer?
deinit {
animationTimer?.invalidate()
}
var text: String? {
get {
return label?.text
}
set {
if( label == nil ) {
label = UILabel(frame: CGRect(origin: CGPoint.zero, size: self.frame.size))
label!.backgroundColor = self.backgroundColor
self.addSubview(label!)
}
guard let label = label else {fatalError()}
label.text = newValue
let fitSize = label.sizeThatFits(CGSize(width: 9999, height: self.frame.height))
label.frame = CGRect(x: 0, y: 0, width: fitSize.width, height: self.frame.height)
self.contentSize = label.frame.size
self.contentOffset = CGPoint(x: 0, y: 0)
self.showsVerticalScrollIndicator = false
self.showsHorizontalScrollIndicator = false
}
}
func startAnimatingLabel() {
animationTimer?.invalidate()
animationTimer = nil
animationTimer = Timer.scheduledTimer(timeInterval: animationInterval, target: self, selector: #selector(moveLabel), userInfo: nil, repeats: true)
}
func stopAnimatingLabel() {
animationTimer?.invalidate()
animationTimer = nil
}
@objc fileprivate func moveLabel(_ timer: Timer) {
var offsetX = self.contentOffset.x
offsetX += animationPixelsPerSecond * CGFloat(animationInterval)
if offsetX > label?.frame.width ?? 0 {
offsetX = -self.frame.width
}
self.contentOffset = CGPoint(x: offsetX, y: 0)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.