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
Java
UTF-8
315
2.21875
2
[]
no_license
package part05.async.svc; import part05.async.domain.Currency; import part05.async.svc.impl.ExchangeRateServiceSimulator; public interface ExchangeRateService { static ExchangeRateService instance() { return new ExchangeRateServiceSimulator(); } double getRate(Currency from, Currency to); }
Java
UTF-8
1,528
2.40625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2012 Dominik Schürmann <dominik@dominikschuermann.de> * * 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.hctrom.romcontrol.fastergps.rootcommands; import com.hctrom.romcontrol.fastergps.rootcommands.util.Log; public class RootCommands { public static boolean DEBUG = false; public static int DEFAULT_TIMEOUT = 50000; public static final String TAG = "RootCommands"; /** * General method to check if user has su binary and accepts root access for this program! * * @return true if everything worked */ public static boolean rootAccessGiven() { boolean rootAccess = false; try { Shell rootShell = Shell.startRootShell(); Toolbox tb = new Toolbox(rootShell); if (tb.isRootAccessGiven()) { rootAccess = true; } rootShell.close(); } catch (Exception e) { Log.e(TAG, "Problem while checking for root access!", e); } return rootAccess; } }
Python
UTF-8
1,486
2.8125
3
[]
no_license
import os import string import operator spam_path = "hw5_spam_dist/dist/spam/" ham_path = "hw5_spam_dist/dist/ham/" spam_emails = [] ham_emails = [] print("asdf") for spam_email in os.listdir(spam_path): print(spam_email) f = open(spam_path + spam_email, 'r', errors='ignore') spam_emails.append(f.read()) for ham_email in os.listdir(ham_path): print(ham_email) f = open(ham_path + ham_email, 'r', errors='ignore') ham_emails.append(f.read()) for x in range(len(spam_emails)): print(x) spam_emails[x] = spam_emails[x].split() for x in range(len(ham_emails)): print(x) ham_emails[x] = ham_emails[x].split() spam_words = {} ham_words = {} for x in spam_emails: for y in x: if y in spam_words: spam_words[y] += 1 else: spam_words[y] = 1 for x in ham_emails: for y in x: if y in ham_words: ham_words[y] += 1 else: ham_words[y] = 1 difference = {} divide = {} both = set(spam_words.keys()) & set(ham_words.keys()) spam = set(spam_words.keys()) - set(ham_words.keys()) ham = set(ham_words.keys()) - set(spam_words.keys()) for z in both: difference[z] = spam_words[z] - ham_words[z] divide[z] = (spam_words[z] / ham_words[z], spam_words[z] - ham_words[z]) sorted_differences = sorted(difference.items(), key=operator.itemgetter(1)) sorted_divide = sorted(divide.items(), key=operator.itemgetter(1)) print([x for x in sorted_divide if x[1][1] < -5000])
PHP
UTF-8
525
3.03125
3
[]
no_license
<?php echo "Merhaba Dünya!"; # buradan sonrası açıklama satırıdır $tarih="01.05.2010"; // satırın sadece bu kısmı açıklama satırıdır # bu satırın tamamı açıklama satırıdır // bu satırın da tamamı açıklama satırıdır /* Bu kısımda ise birden fazla satır açıklama satırı olarak tanımlanmıştır */ echo "<br><b>Tarih</b>: "; /* bu araya açıklama ekledik */ echo $tarih; // echo $sonuc; <- kodun çalışmasını istemediğimiz için açıklama satırı yaptık. ?>
Java
UTF-8
1,257
3.703125
4
[]
no_license
package com.example.suanfa.tree; /** * @author: luozijian * @date: 2022/6/3 * @description: 计算节点数 */ public class CountNode { /** * 普通计算树节点的方法 * @param root * @return */ public int countNodes(TreeNode root){ if(root == null) { return 0; } return 1 + countNodes(root.left) + countNodes(root.right); } /** * 满二叉树计算节点的方法 * @param root * @return */ public int countPerfectTreeNodes(TreeNode root){ int h = 0; while(root != null) { root = root.left; h++; } return (int)Math.pow(2, h) - 1; } /** * 计算完全二叉树节点的方法 * @param root * @return */ public int countCompleteTreeNodes(TreeNode root) { if(root == null) { return 0; } int hr = 0, hl = 0; TreeNode l = root, r = root; while (l != null){ l = l.left; hl++; } while (r != null){ r = r.right; hr++; } if(hr == hl){ return countPerfectTreeNodes(root); } return countNodes(root); } }
Java
UTF-8
3,750
2.84375
3
[]
no_license
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.stage.Stage; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Meluleki */ public class Driver extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("Accuracy chart"); // Title for the window opening /*Next thing you need to do is define the x and y exis setting them nto number axis*/ final NumberAxis xAxis = new NumberAxis(); final NumberAxis yAxis = new NumberAxis(); /*Setting the name of the two axis*/ xAxis.setLabel("Chunk Size as number of charecters in each chunk"); yAxis.setLabel("Accuracy as a %"); /*defining linechar and setting the title for the graph*/ final LineChart<Number, Number> lChart = new LineChart<>(xAxis, yAxis); lChart.setTitle("Accuracy vs Chunk size"); /*Defining the series for the XYChart now*/ XYChart.Series series[] = new XYChart.Series[5]; for (int i = 0; i < 5; i++) { series[i] = new XYChart.Series(); } /*series to be used for the different model sizes*/ /*Defining experiment*/ for (int i = 100000; i < 500000; i += 100000) { populateWithData(series[(i / 100000) - 1], i); } Scene scene = new Scene(lChart, 800, 600); for (int i = 0; i < 5; i++) { lChart.getData().add(series[i]); } primaryStage.setScene(scene); primaryStage.show(); } private void populateWithData(XYChart.Series series, int modelSize) { float accuracy = 0; File f = new File(Values.DEFAULT_DIREC); File result = new File("result/general"); if (!result.getParentFile().exists()) { result.getParentFile().mkdir(); } if (!result.exists()) { try { result.createNewFile(); } catch (IOException ex) { Logger.getLogger(Experiment.class.getName()).log(Level.SEVERE, null, ex); } } series.setName("Model size: " + modelSize); try { try (BufferedWriter bw = new BufferedWriter(new FileWriter(result, true))) { bw.write("Model size is: " + modelSize + "\n\n"); File files[] = f.listFiles(); for (int i = 0; i < 1000; i += 50) { Experiment e = null; accuracy = 0; for (File tempF : files) { e = new Experiment(tempF.getName(), 50 + i, modelSize); float a = (float) e.performTesting(); accuracy += a; bw.write(Float.toString(a) + " "); } bw.write(" " + Float.toString(accuracy / 9)); bw.newLine(); series.getData().add(new XYChart.Data<>(e.size, (accuracy / 9))); } bw.flush(); } } catch (IOException e) { System.out.println(e.toString()); } } public static void main(String[] args) { launch(args); } }
C#
UTF-8
2,949
2.625
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. namespace System.Formats.Cbor { public partial class CborReader { /// <summary>Reads the next data item as the start of an array (major type 4).</summary> /// <returns>The length of the definite-length array, or <see langword="null" /> if the array is indefinite-length.</returns> /// <exception cref="InvalidOperationException">The next data item does not have the correct major type.</exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para> /// <para>-or-</para> /// <para>The next value uses a CBOR encoding that is not valid under the current conformance mode.</para></exception> public int? ReadStartArray() { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.Array); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { if (_isConformanceModeCheckEnabled && CborConformanceModeHelpers.RequiresDefiniteLengthItems(ConformanceMode)) { throw new CborContentException(SR.Format(SR.Cbor_ConformanceMode_IndefiniteLengthItemsNotSupported, ConformanceMode)); } AdvanceBuffer(1); PushDataItem(CborMajorType.Array, null); return null; } else { ReadOnlySpan<byte> buffer = GetRemainingBytes(); int arrayLength = DecodeDefiniteLength(header, buffer, out int bytesRead); AdvanceBuffer(bytesRead); PushDataItem(CborMajorType.Array, arrayLength); return arrayLength; } } /// <summary>Reads the end of an array (major type 4).</summary> /// <exception cref="InvalidOperationException"><para>The current context is not an array.</para> /// <para>-or-</para> /// <para>The reader is not at the end of the array.</para></exception> /// <exception cref="CborContentException"><para>The next value has an invalid CBOR encoding.</para> /// <para>-or-</para> /// <para>There was an unexpected end of CBOR encoding data.</para></exception> public void ReadEndArray() { if (_definiteLength is null) { ValidateNextByteIsBreakByte(); PopDataItem(expectedType: CborMajorType.Array); AdvanceDataItemCounters(); AdvanceBuffer(1); } else { PopDataItem(expectedType: CborMajorType.Array); AdvanceDataItemCounters(); } } } }
PHP
UTF-8
78
2.90625
3
[]
no_license
<?php $texte= two("salut"); function two($a){ return $a; } echo $texte; ?>
Markdown
UTF-8
3,011
2.59375
3
[]
no_license
# webpack基础用法 ## entry 用来指定打包的入口 - 参考模块依赖图 * 单入口:entry 是一个字符串 * 多入口:entry 是一个对象 ```js entry: './src/index.js' entry: { index: './src/index.js', search: './src/search.js' } ``` ## output 用来指定打包的输出 - 告诉 webpack 如何将编译后的文件输出到磁盘 ```js output: { filename: '[name].js', // 通过占位符确保文件名称的唯一 path: __dirname + '/dist' } ``` ## loaders - 解决 webpack 不能识别的文件 webpack 开箱即用只支持 js 和 json 两种文件类型,通过 loaders 去支持其它文件类型并且把它们转化成有效的模块,并且可以添加到依赖图中。 本身是一个函数,接受源文件作为参数,返回转换的结果 ### 常见的 loaders 有哪些? * babel-loader 转换 ES6、ES7 等 js 新特性语法 * css-loader 支持 .css 文件的加载和解析 * less-loader 将 less 文件转换成 css * ts-loader 将 TS 转换成 js * file-loader 进行图片、字体等的打包 * raw-loader 将文件以字符串的形式导入 * thread-loader 多进程打包 js 和 css loaders 的用法 ```js module: { rules: [ { test: /\.txt$/, // test 自定匹配规则 use: 'raw-loader' // use 指定使用的 loader 名称 } ] } ``` ## plugins 插件用于 bundle 文件的优化,资源管理和环境变量注入,作用于整个构建流程 ### 常见的 plugins 有哪些? * CommonChunkPlugin 将 chunks 相同的模块代码提取成公共 js * CleanWebpackPlugin 清理构建目录 * ExtractTextWebpackPlugin 将 css 从 bundle 文件里提取成一个独立的 css 文件 * CopyWebpackPlugin 将文件或者文件夹拷贝到构建的输出目录 * HtmlWebpackPlugin 创建 html 文件去承载输出的 bundle * UglifyjsWebpackPlugin 压缩 js * ZipWebpackPlugin 将打包出的资源生成一个 zip 包 ```js // 放到 plugins 数组中 plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ] ``` ## mode -- webpack 4 中提出的概念 指定当前的构建环境是:production、development 还是 none 设置 mode 可以使用 webpack 内置的函数,默认值为 production ### mode 的内置函数功能 * development * 设置 process.env.NODE_ENV 的值为 development * 开启 NamedChunksPlugin 和 NamedModulesPlugin * production * 设置 process.env.NODE_ENV 的值为 production * 开启 FlagDependencyUsagePlugin, FlagIncludedChunksPlugin, ModuleConcatenationPlugin, NoEmitOnErrorsPlugin, OccurrenceOrderPlugin, SideEffectsFlagPlugin 和 TerserPlugin * none * 不开启任何优化选项 ## 资源解析 ### 解析 ES6 使用 babel-loader,babel 的配置文件是 .babelrc ```js rules: [ { test: /\.js$/, use: 'babel-loader' } ] ``` .babelrc ```js // preset 是多个 plugin 的集合 { "presets": [ "@babel/preset-env" // ES6 的 babel preset ], "plugins": [ "@babel/proposal-class-properties" ] } ```
Python
UTF-8
985
3.40625
3
[]
no_license
''' Chinese Communist Party -- Jack Lu, Vincent Lin SoftDev2 pd8 K #19: Ready, Set, Math! 2019-04-16 ''' def union(a, b): ''' only one occurance of each element in result''' lst = [] lst = [x for x in a if x not in lst] [lst.append(x) for x in b if x not in lst] return lst def intersection(a, b): ''' element is in intersection if in both a and b''' return [x for x in a if x in b] def difference(u, a): ''' element is in u but not in a''' return [x for x in u if x not in a] def sym_diff(a, b): ''' elements exclusive to one set''' return union(difference(a,b),difference(b,a)) def cart_product(a, b): ''' all possible combinations of elements in a and b ''' return [(x, y) for x in a for y in b] #cs = cart_product({1,2}, {'red', 'white'}) #print(cs) #u = union({1,2,3}, {2,3,4}) #print(u) #i = intersection({1,2,3}, {2,3,4}) #print(i) #sd = sym_diff({2,3,4}, {1,2,3,}) #print(sd) #d = difference({2,3,4}, {1,2,3,}) #print(d)
Markdown
UTF-8
1,475
2.734375
3
[ "MIT" ]
permissive
# SliceMap.jl [![Build Status](https://github.com/mcabbott/SliceMap.jl/workflows/CI/badge.svg)](https://github.com/mcabbott/SliceMap.jl/actions?query=workflow%3ACI) This package provides some `mapslices`-like functions, with gradients defined for [Tracker](https://github.com/FluxML/Tracker.jl) and [Zygote](https://github.com/FluxML/Zygote.jl): ```julia mapcols(f, M) ≈ mapreduce(f, hcat, eachcol(M)) MapCols{d}(f, M) # where d=size(M,1), for SVector slices ThreadMapCols{d}(f, M) # using Threads.@threads maprows(f, M) ≈ mapslices(f, M, dims=2) slicemap(f, A; dims) ≈ mapslices(f, A, dims=dims) # only Zygote ``` The capitalised functions differ both in using [StaticArrays](https://github.com/JuliaArrays/StaticArrays.jl) slices, and using [ForwardDiff](https://github.com/JuliaDiff/ForwardDiff.jl) for the gradient of each slice, instead of the same reverse-mode Tracker/Zygote. For small slices, this will often be much faster, with or without gradients. The package also defines Zygote gradients for the Slice/Align functions in [JuliennedArrays](https://github.com/bramtayl/JuliennedArrays.jl), which is a good way to roll-your-own `mapslices`-like thing (and is exactly how `slicemap(f, A; dims)` works). Similar gradients are also available in [TensorCast](https://github.com/mcabbott/TensorCast.jl), and in [LazyStack](https://github.com/mcabbott/LazyStack.jl). There are more details & examples at [docs/intro.md](docs/intro.md).
Python
UTF-8
2,206
2.625
3
[]
no_license
import unittest from pisak import switcher_app from gi.repository import GObject, Clutter class SwitcherAppTest(unittest.TestCase): def test_context(self): """ Context for a dummy application. """ class DummyApp(object): pass app = DummyApp() switcher_app.Context(app) def test_switcher(self): """ Create switcher and add a dummy cycle to it. """ class DummyCycle(object): def __init__(self): self.exposed = False self.interval = 1000 def expose_next(self): self.exposed = True switcher = switcher_app.Switcher(object()) cycle = DummyCycle() switcher.push_cycle(cycle) self.assertTrue(cycle.exposed) def test_key_switcher_input(self): """ Test keyboard input with switcher. """ class DummyStage(GObject.GObject): __gsignals__ = { "key-release-event": (GObject.SIGNAL_RUN_FIRST, None, (object,)) } def __init__(self): super().__init__() def trigger_key(self): event = Clutter.KeyEvent() event.keyval = 0x20 self.emit("key-release-event", event) triggered = False def response(source): nonlocal triggered triggered = True stage = DummyStage() switcher_input = switcher_app.KeyboardSwitcherInput(stage) switcher_input.connect("switcher-select", response) stage.trigger_key() self.assertTrue(triggered) def test_switcher_add_input(self): """ Test adding an input to a switcher. """ class DummyInput(switcher_app.SwitcherInput): def trigger(self): self.emit("switcher-select") switcher = switcher_app.Switcher(object()) input_1 = DummyInput() input_2 = DummyInput() switcher.add_input(input_1) switcher.add_input(input_2) switcher.remove_input(input_1) switcher.remove_input(input_2) if __name__ == '__main__': unittest.main()
Markdown
UTF-8
3,771
3.28125
3
[]
no_license
# 클래스타입 구성파일 * xml 파일 형식의 구성파일(ApplicationContex.txml) 과 동일한 역할을 하는 자바 클래스 파일 * 클래스에 @Configuration 어노테이션 추가하여 Spring 이 해당 클래스를 구성파일로 인식하도록 설정 ### bean 등록 * 객체 생성자 메서드 정의(메서드 명 = bean id) 후 @Bean 어노테이션 추가 * 의존성 주입 : 객체 생성자 메서드 내에서 생성자나 setter로 협력객체(bean 등록 메서드 호출) 주입 ```java //applicationContext.xml <bean id="foo" class="com.naver.Foo"/> <bean id="bar" class="com.naver.Bar"> <property name="foo" ref="foo"/> </bean> //applicationContext.java @Configuration public class ApplicationContext { @Bean public Foo foo { return new Foo(); } @Bean public Bar bar { Bar bar = new Bar(); bar.setFoo(foo()); return bar; } } ``` * xml 구성파일 <bean> 태그의 대부분의 어트리뷰트들을 클래스 구성파일에서도 어노테이션을 통해 사용 가능 | xml | class | |:---:|:------:| |lazy-init="true"|@Lazy| |scope="prototype"|@Scope(value="prototype")| |depends-on="bar"|@DependsOn(value="bar")| ```java //applicationContext.xml <bean id="foo" class="com.naver.Foo" lazy-init="true"/> <bean id="bar" class="com.naver.Bar" scope="request" depends-on="foo"/> //applicationContext.java @Configuration public class ApplicationContext { @Bean @Lazy public Foo foo() { return new Foo(); } @Bean @Scope(value="request") @DependsOn(value="foo") public Bar bar() { return new Bar(); } } ``` ### Component-Scan * 구성클래스에 @ComponentScan(basePackages={"path.to.bean.package"}) 어노테이션 추가 * xml 타입 구성파일의 <context:component-scan> 태그와 동일한 기능 수행 ```java @Configuration @ComponentScan(basePackages={"com.naver"}) public class ApplicationContext { } ``` ### 구성클래스 중첩 * xml 타입 구성파일에서 다른 xml 타입 구성파일을 import 하여 하나의 구성파일 처럼 사용하는것과 동일한 기능 ``` //applicationContext.xml //foo, bar 두개 bean 모두 등록됨 <bean id="foo" class="com.naver.Foo"/> <import resource="applicationContext-security.xml"/> //applicationContext-security.xml <bean id="bar" class="com.naver.Bar"/> ``` * 구성클래스에 @Import(다른구성클래스.class) 어노테이션 추가 ```java //ApplicationContextSecurity.java @Configuration public class ApplicationContextSecurity { @Bean public Bar bar() {return new Bar();} } @Configuration @Import(ApplicationContextSecurity.class) public class ApplicationContext { @Bean public Foo foo() {return new Foo(); } } ``` <br> # 혼합구성 * xml 타입 구성파일과 클래스타입 구성파일을 함께 사용하는것 * xml, 클래스 구성파일에 정의되어있는 spring 설정, bean 들 모두 사용 가능 ### 클래스 구성파일에 xml 구성파일 추가 * 클래스 구성파일에 @ImportResource(value="classpath:applicationContext.xml") 어노테이션 추가 ```java //applicationContext.xml <bean id="bar" class="com.naver.Bar"> //AppConfig.java @Configuration @ImportResource(value="classpath:applicationContext.xml") //foo, bar 빈 모두 등록됨 public class AppConfig() { @Bean public Foo foo() { return new Foo(); } } ``` ### xml 구성파일에 클래스 구성파일 추가 * xml 구성파일에 클래스 구성파일을 익명 bean 으로 등록 * 클래스 구성파일에 정의되어있는 spring 설정, bean 사용 가능 ```java //applicationContext.xml <bean id="bar" class="com.naver.Bar"/> <bean class="com.naver.AppConfig"/> //AppConfig.java @Configuration public class AppConfig() { @Bean public Foo foo() { return new Foo(); } } ```
Java
UTF-8
314
1.789063
2
[]
no_license
package com.fzy.admin.fp.member.sem.repository; import com.fzy.admin.fp.common.spring.base.BaseRepository; import com.fzy.admin.fp.member.sem.domain.StoredAliSwitch; public interface StoredAliSwitchRepository extends BaseRepository<StoredAliSwitch>{ StoredAliSwitch findByMerchantId(String merchantId); }
Python
UTF-8
127
3.28125
3
[]
no_license
class Test: def __init__(self): print('constructor') def m1(self,x): print('The value of x:',x) t=Test() t.m1(10)
Java
UTF-8
587
2.140625
2
[]
no_license
package sen.com.openglcamera.offscreen; import android.opengl.GLES20; import android.opengl.GLSurfaceView.Renderer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; public class OffScreenRenderer implements Renderer{ @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { GLES20.glClearColor(1.0f, 0, 0, 1); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT|GLES20.GL_DEPTH_BUFFER_BIT); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { } @Override public void onDrawFrame(GL10 gl) { } }
PHP
UTF-8
2,786
2.53125
3
[ "MIT" ]
permissive
<?php namespace Database\Seeders; use App\Models\User; use Illuminate\Database\Seeder; use Spatie\Permission\Models\Permission; class RolePermissionSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $supperAdminRole = User::createRole('Supper Admin'); $memberRole = User::createRole('Member'); // Permissions Group Wise $permissionGroups = [ 'dashboard' => [ 'dashboard.view', 'dashboard.member_statistice' ], 'user' => [ 'user.list', 'user.create', 'user.edit', 'user.show', 'user.delete' ], 'member' => [ 'member.list', 'member.create', 'member.edit', 'member.show', 'member.delete' ], 'monthly_installment' => [ 'monthly_installment.list', 'monthly_installment.create', 'monthly_installment.edit', 'monthly_installment.show', 'monthly_installment.delete' ], 'fixed_installment' => [ 'fixed_installment.list', 'fixed_installment.create', 'fixed_installment.edit', 'fixed_installment.show', 'fixed_installment.delete' ], 'collection' => [ 'collection.list', 'collection.create', 'collection.edit', 'collection.show', 'collection.delete' ], 'report' => [ 'report.monthly_Collection', 'report.fixed_collection' ], ]; $memberPermissions = [ 'dashboard.view', 'profile.edit', 'collection.view' ]; // Insert the permission and assign it to a role foreach($permissionGroups as $permissionGroupKey => $permissions){ foreach($permissions as $permissionName){ $permission = Permission::create([ // 'guard_name' => 'sunctum', 'group_name' => $permissionGroupKey, 'name' => $permissionName ]); $supperAdminRole-> givePermissionTo($permission); $permission->assignRole($supperAdminRole); if(in_array($permissionName, $memberPermissions)){ $memberRole-> givePermissionTo($permission); $permission->assignRole($memberRole); } } } } }
Java
UTF-8
526
2.09375
2
[]
no_license
package com.travely.travely.domain; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) public class StoreImg { private Long storeIdx; private Long storeImgIdx; private String storeImgUrl; @Builder public StoreImg(Long storeIdx, Long storeImgIdx, String storeImgUrl) { this.storeIdx = storeIdx; this.storeImgIdx = storeImgIdx; this.storeImgUrl = storeImgUrl; } }
Markdown
UTF-8
5,550
2.875
3
[]
no_license
五十七 第 十 章 六月六日断肠时 另一名会中弟子,用手一推老瞎婆炊火杖所着树之另一面,轰地一声,应手而倒,一棵树如斧削般去了半边。 两个人所施为的,系当分之世已绝传的无上神功,怎会不令内园各接待的一流高手,瞠目结舌,半响才轰起一阵彩声。 驼子瞠目大喝:“瞎婆子!你取巧,并没照我这办法做。” “驼鬼!你能隔水除蛟,我自当以真气腐物,你如不能,我亦不屑。” 两人在争执中,青娘子田媚却与活骷髅在低声暗语,大家全注视着二人,谁也没听到说什么。 六指魔婆看了碧涛神鳌一眼说: “老怪物!你恐怕没能为争取第一把交椅,但你那高傲神态,似又不甘人下,今宵如何?” 碧涛神鳌怒视魔婆一眼,冷然说:“老乞婆既然看不惯我这傲态,莫非是想要较量高低?” “莫非依样葫芦?” “我不屑!” “那你出个题目。” “何必惊动众人,咱们就原坐不动,一试高低。” “怎么试法?” “当然是拳脚并用!” 老乞婆沙哑的说:“新奇,你就动手吧!” 两人面对面而坐,相距不到三尺,碧涛神鳌倏地一震臂,一缕指风,已到面门,老乞婆倏地双掌齐翻,左足一扬。 啪的一声,两人坐在那儿全是一晃荡。 碧涛神鳌冷然的说:“老乞婆你输了!” “蛤蟆打呵欠好大口气!” “老婆子,你眉心一点绿,已中我碧涛阴煞,不服输,三天后替你运葬!” 老乞婆倏地一震臂,飞身而起,龙头拐呼的一声,向魔头腹部捣去。 碧涛神鳌一抖乾坤网,正待还手,陡觉一股子强劲气流,在面前掠过,全身不由己的暴退五尺。 这班边荒鬼怪,全部被这突然现身之人神动所慑,怔呵呵的注视来人,神色连变却不言不动。 来人中等身材,高不到七尺,一袭灰暗长衫,足登快履,灰发披拂下垂,直盖到胸前脖后。 别人看不见面色,简直没丝毫隙缝,就如织就的丝罩,罩在头上,永不会让人看到庐山真面目。 众人无语,他也不吭,就这么干耗着…… 百毒鬼婆也看到了,厉喝:“什么人?来此生事!” 披发客嘿嘿一阵干笑,并没答复。 碧涛神鳌向前一迈步,拱手说:“在下请教阁下大名。” “嗯!你比较客气,但我答复不出。” “为什么?” “练功夫练的忘记了一切。” 百毒鬼婆轻蔑的道:“你没忘记自己?” “这个倒被你毒婆子猜中了。” “你自己是什么东西说给我婆子听听?” 披发人又是嘿嘿嘿一阵干笑。 百毒鬼婆炊火筒猛一砸地,轰的一声,火花四射:“别装模作样,老婆子已经活了几十年,还……” “那是说你吃了不少饭。” “也有更多的见识,杖下不死无名鬼,敢报个名……” “我是五绝帮主!” 百毒鬼婆一声冷笑:“你没照照镜子,凭你也……” “我早照过啦!凭我这副怪样,正是五绝帮主!” “谁尊你的?” “自加封号,普天之下,绝没人敢说一声不字!” “我老婆子就不服。” “那你试一下!” 百毒鬼婆陡地一顺炊火筒,就要动手。 “慢着!” “你怕了我老婆子?” “我是说不服的不止是你,你们五个一齐上如何?” 这披发怪客指着鬼婆、驼子、碧涛神鳌、活骷髅、六指魔婆。 这句话不打紧,气疯了这五个鬼怪,也壮了五个人的胆。以为你再高能为,也禁受不了五人合攻。 驼子火眼一转说:“这是你自愿,别……” “死了不怨别人,但这遭动手,我有条件!” “说出来驼子听听。” “我赢了,尔等五人终身服膺五绝帮令,不得二心!” “但你要输了呢? “让五绝帮主位于尔五人中一个,我终身服从。” 驼子一笑说:“得!这办法公平,就这么办。” “你一个人答应不算。” 活骷髅、六指魔婆、碧涛神鳌齐颔首表示同意。 披发怪客面对百毒鬼婆说:“老婆子!你有点反复无常,本帮主最信你不过,怎么成了锯口葫芦。” 百毒鬼望一皱眉说:“我也同意!” “是君子之言?” “绝非小人之语!” “要知一言出口……” “你就别烦了,老婆子一言出口,至死靡他!” 争执之语,声闻远近,余再添远居红楼,仍然能听出个眉目,环顾问:“老前辈!这披发人……” “孩子!这真骇人听闻,红楼居高临下,可见全场,老夫数十年江湖,就没见披发人怎么来的。 “此人行若鬼魅,功力无敌,五个蛮荒丑怪,绝非其敌! “蛇谷主人出谷之意,是奉神尼佛旨,对抗那鬼东西,披发人未现身前,我还弄不清她意向,如今完了。” “老前辈!你说什么完了?” “被发人主要的是收服她,一字一字咬得很紧,蛇谷主人百分之百的败定了,她说过的话,安能更改,必然取膺五绝帮,与中原武林敌对!披发人必许以五绝帮中极高位置,博其欢心,……哎!这惨劫……”
Markdown
UTF-8
2,181
3.03125
3
[]
no_license
<h1 align="center">Job Search App</h1> <p align="center">Job marketplace for University students, convenient and easy to use.</p> <p align="center"><img src="public/img/readme/job-search-demo-admin-panel.gif" alt="job search admin panel gif"></p> ## Table of Contents - [Basic Overview](#basic-overview) - [Getting Started](#getting-started) - [Possible additions in future](#possible-additions-in-future) - [Contribute](#contribute) ## Basic Overview Job Search App is a [Laravel](https://laravel.com) based PHP web application that acts as a new kind of job marketplace for University students. It’s a nimble and responsive weapon in student's job search arsenal, bringing various positions posted by Professors and allowing them to easily apply to posted jobs. The app provides platform for University Professors to post jobs and keep check on number of applications received. ## Getting Started To clone and run this application, you'll need [Git](https://git-scm.com/downloads), [Composer](https://getcomposer.org/download) and [Node.js](https://nodejs.org/en/download/) (which comes with [npm](http://npmjs.com)) installed on your computer. For more information regarding running Laravel project locally, you can visit laravel [documentation](https://laravel.com/docs/5.4/#installation). From your command line: ```bash # Clone this repository $ git clone https://github.com/harry-ghuman/job_search_laravel_imp.git # Install dependencies $ composer install $ npm install # Update the .env file and migrate $ php artisan migrate ``` ## Possible additions in future - Improving Panel Dashboard by adding relevant information regarding jobs posted and more - Use of [Bootstrap Dialog](https://nakupanda.github.io/bootstrap3-dialog/) for showing alert messages - Email notifications to users ## Contribute Contribution are always welcome! Please ensure your pull request adhress to the following guidelines: - Search previous suggestions before making a new one, as yours may be a duplicate. - Make an individual pull request for each suggestion. - Keep descriptions short and simple, but descriptive. - Check your spelling and grammar. Thank you for your suggestions!
Java
UTF-8
17,115
2.265625
2
[ "BSD-3-Clause" ]
permissive
/** * Processor of TSQL2 on a Relational Database System * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE. * It is also available through the world-wide-web at this URL: * http://www.opensource.org/licenses/bsd-license.php * * @copyright Copyright (c) 2008-2009 Jiri Tomek <katulus@volny.cz> * @copyright Copyright (c) 2016- Marek Rychly <marek.rychly@gmail.com> * @license http://www.opensource.org/licenses/bsd-license.php New BSD License */ package cz.vutbr.fit.tsql2lib; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.HashMap; /** * Metadata for TSQL2ResultSet * * @author Jiri Tomek <katulus@volny.cz> * @copyright Copyright (c) 2008-2009 Jiri Tomek <katulus@volny.cz> */ public class TSQL2ResultSetMetaData implements ResultSetMetaData, Constants { /** * Original relational result set metadata */ private ResultSetMetaData _originalMetadata; /** * Mapping array from old column indexes to new column indexes */ private ArrayList<Integer> _indexMap; /** * Number of columns visible to user */ private int _columnCount = 0; /** * Labels of columns visible to user */ private ArrayList<String> _columnLabels; /** * Names of columns visible to user */ private ArrayList<String> _columnNames; /** * Types of columns visible to user */ private ArrayList<Integer> _columnTypes; /** * Inner TSQL types of columns visible to user. */ private ArrayList<TSQL2Types> _columnTSQLTypes; /** * Scales of columns visible to user. */ private ArrayList<DateTimeScale> _columnScales; /** * Map for translating label to column index */ private HashMap<String, Integer> _labelToIndexMap; /** * Create temporal result set metadata from relational result set metadata * * @param originalMetaData Relational result set metadata * @throws java.sql.SQLException */ public TSQL2ResultSetMetaData(ResultSetMetaData originalMetaData) throws SQLException { _originalMetadata = originalMetaData; // get number of columns of original results to process all of them int originalColumnCount = _originalMetadata.getColumnCount(); TSQL2DatabaseMetaData dbMetadata = TSQL2DatabaseMetaData.getInstance(); _indexMap = new ArrayList<>(originalColumnCount); _columnLabels = new ArrayList<>(originalColumnCount); _columnNames = new ArrayList<>(originalColumnCount); _columnTypes = new ArrayList<>(originalColumnCount); _columnTSQLTypes = new ArrayList<>(originalColumnCount); _columnScales = new ArrayList<>(originalColumnCount); _labelToIndexMap = new HashMap<>(originalColumnCount); // for all columns for (int i = 1; i <= originalColumnCount; i++) { String columnLabel = _originalMetadata.getColumnLabel(i); String ucLabel = columnLabel.toUpperCase(); String columnName = _originalMetadata.getColumnName(i); int columnType = _originalMetadata.getColumnType(i); String resultColumnLabel = columnLabel; String resultColumnName = columnName; int resultColumnType = columnType; TSQL2Types resultTSQLType = TSQL2Types.SQLTYPE; DateTimeScale resultScale = DateTimeScale.SECOND; int skip = 0; if (columnLabel.startsWith(IMPLICIT_VTS)) { /* * If there is implicit VTS column, following column contains source table. */ String tableName = Utils.unquoteString(_originalMetadata.getColumnLabel(i + 1)); String alias = Utils.unquoteString(_originalMetadata.getColumnLabel(i + 2)); // cut alias from beginning of table name - it is here for uniqueness of column name // fixed: columns without aliases have a special empty-alias name if (!Settings.EmptyColumnAlias.equals(alias)) { tableName = tableName.substring(alias.length()); } // implicit valid-time column resultColumnLabel = "VALID"; resultColumnName = "VALID"; resultColumnType = Types.OTHER; resultTSQLType = TSQL2Types.EVENT; resultScale = dbMetadata.getMetaData(tableName).getValidTimeScale(); // skip next columns skip = 2; } else if (columnLabel.startsWith(IMPLICIT_VTE)) { // change previous column type from EVENT to PERIOD because this is end time of that period _columnTSQLTypes.set(_columnTSQLTypes.size() - 1, TSQL2Types.PERIOD); continue; } else if (columnLabel.startsWith(EXPLICIT_VTS)) { /* * If there is explicit VTS column, following column contains source table and second * following column contains alias for this column. */ String tableName = Utils.unquoteString(_originalMetadata.getColumnLabel(i + 1)); String alias = Utils.unquoteString(_originalMetadata.getColumnLabel(i + 2)); // cut alias from beginning of table name - it is here for uniqueness of column name // fixed: columns without aliases have a special empty-alias name if (!Settings.EmptyColumnAlias.equals(alias)) { tableName = tableName.substring(alias.length()); } else { alias = ""; } if (alias.length() != 0) { resultColumnLabel = alias; } else { resultColumnLabel = "VALID(" + tableName + ")"; } resultColumnName = resultColumnLabel; resultColumnType = Types.OTHER; resultTSQLType = TSQL2Types.EVENT; resultScale = dbMetadata.getMetaData(tableName).getValidTimeScale(); // skip next two columns skip = 2; } else if (columnLabel.startsWith(EXPLICIT_VTE)) { // change previous column type from EVENT to PERIOD because this is end time of that period _columnTSQLTypes.set(_columnTSQLTypes.size() - 1, TSQL2Types.PERIOD); continue; } else if (columnLabel.startsWith(EXPLICIT_TTS)) { /* * If there is explicit VTS column, following column contains source table and second * following column contains alias for this column. */ String tableName = Utils.unquoteString(_originalMetadata.getColumnLabel(i + 1)); String alias = Utils.unquoteString(_originalMetadata.getColumnLabel(i + 2)); // cut alias from beginning of table name - it is here for uniqueness of column name // fixed: columns without aliases have a special empty-alias name if (!Settings.EmptyColumnAlias.equals(alias)) { tableName = tableName.substring(alias.length()); } else { alias = ""; } if (alias.length() != 0) { resultColumnLabel = alias; } else { resultColumnLabel = "TRANSACTION(" + tableName + ")"; } resultColumnName = resultColumnLabel; resultColumnType = Types.OTHER; resultTSQLType = TSQL2Types.PERIOD; // skip next two columns skip = 2; } else if (columnLabel.startsWith(EXPLICIT_TTE)) { // skip end column to make just one column from start and end continue; } else if (columnLabel.startsWith(INTERSECT_BEGINNING)) { // intersection beginning String alias = Utils.unquoteString(_originalMetadata.getColumnLabel(i + 2)); if ((alias != null) && (alias.length() != 0)) { resultColumnLabel = alias; } else { resultColumnLabel = "INTERSECTION"; } resultColumnName = resultColumnLabel; resultColumnType = Types.OTHER; resultTSQLType = TSQL2Types.PERIOD; // skip next two columns skip = 2; } else if (columnLabel.startsWith(INTERSECT_END)) { continue; } else if ((ucLabel.equals(Settings.ValidTimeStartColumnNameRaw.toUpperCase())) || (ucLabel.equals(Settings.ValidTimeEndColumnNameRaw.toUpperCase())) || (ucLabel.equals(Settings.TransactionTimeStartColumnNameRaw.toUpperCase())) || (ucLabel.equals(Settings.TransactionTimeEndColumnNameRaw.toUpperCase()))) { // skip system columns continue; } // create mapping record to map new index to old index _indexMap.add(i); _columnCount++; // create mapping record to map label to new index _labelToIndexMap.put(resultColumnLabel.toUpperCase(), _columnCount); _columnNames.add(resultColumnName); _columnLabels.add(resultColumnLabel); _columnTypes.add(resultColumnType); _columnTSQLTypes.add(resultTSQLType); _columnScales.add(resultScale); // skip some columns if required i += skip; } } /** * Get original index value from new index value * * @param newIndex New index value. This is value after result * pre-processing. * @return Original index value to point into original result set * @throws SQLException */ public int getOriginalIndex(int newIndex) throws SQLException { try { return _indexMap.get(newIndex - 1); // column index is one based } catch (IndexOutOfBoundsException e) { throw new SQLException("Column index is out of bounds."); } } /** * Get original index value from column label * * @param columnLabel Label of column * @return Original index value to point into original result set * @throws SQLException */ public int getOriginalIndex(String columnLabel) throws SQLException { try { return getOriginalIndex(_labelToIndexMap.get(columnLabel.toUpperCase())); } catch (NullPointerException e) { throw new SQLException("Unknown column '" + columnLabel + "'."); } } /** * Get inner TSQL type of column. If column is period, current and next * column in original result set are beginning and end of that period. * * @param column Index of column * @return TSQL type of column * @throws SQLException */ public TSQL2Types getColumnTSQLType(int column) throws SQLException { try { return _columnTSQLTypes.get(column - 1); // arrayList is zero based, columns are one based } catch (IndexOutOfBoundsException e) { throw new SQLException("Column index is out of bounds."); } } /** * Get inner TSQL type of column. If column is period, current and next * column in original result set are beginning and end of that period. * * @param columnLabel Label of column * @return TSQL type of column * @throws SQLException */ public TSQL2Types getColumnTSQLType(String columnLabel) throws SQLException { Integer index = _labelToIndexMap.get(columnLabel.toUpperCase()); if (index == null) { throw new SQLException("Column label doesn't exist."); } try { return _columnTSQLTypes.get(index - 1); // arrayList is zero based, columns are one based } catch (IndexOutOfBoundsException e) { throw new SQLException("Column index is out of bounds."); } } /** * Get time scale of column. * * @param column Index of column * @return Date scale * @throws SQLException */ public DateTimeScale getColumnScale(int column) throws SQLException { try { return _columnScales.get(column - 1); // arrayList is zero based, columns are one based } catch (IndexOutOfBoundsException e) { throw new SQLException("Column index is out of bounds."); } } /** * Get time scale of column. * * @param columnLabel Label of column * @return Date scale * @throws SQLException */ public DateTimeScale getColumnScale(String columnLabel) throws SQLException { Integer index = _labelToIndexMap.get(columnLabel.toUpperCase()); if (index == null) { throw new SQLException("Column label doesn't exist."); } try { return _columnScales.get(index - 1); // arrayList is zero based, columns are one based } catch (IndexOutOfBoundsException e) { throw new SQLException("Column index is out of bounds."); } } @Override public String getCatalogName(int column) throws SQLException { return _originalMetadata.getCatalogName(column); } @Override public String getColumnClassName(int column) throws SQLException { return _originalMetadata.getColumnClassName(column); } @Override public int getColumnCount() throws SQLException { return _columnCount; } @Override public int getColumnDisplaySize(int column) throws SQLException { return _originalMetadata.getColumnDisplaySize(column); } @Override public String getColumnLabel(int column) throws SQLException { try { return _columnLabels.get(column - 1); // arrayList is zero based, columns are one based } catch (IndexOutOfBoundsException e) { throw new SQLException("Column index is out of bounds."); } } @Override public String getColumnName(int column) throws SQLException { try { return _columnNames.get(column - 1); // arrayList is zero based, columns are one based } catch (IndexOutOfBoundsException e) { throw new SQLException("Column index is out of bounds."); } } @Override public int getColumnType(int column) throws SQLException { try { return _columnTypes.get(column - 1); // arrayList is zero based, columns are one based } catch (IndexOutOfBoundsException e) { throw new SQLException("Column index is out of bounds."); } } @Override public String getColumnTypeName(int column) throws SQLException { return _originalMetadata.getColumnTypeName(column); } @Override public int getPrecision(int column) throws SQLException { return _originalMetadata.getPrecision(column); } @Override public int getScale(int column) throws SQLException { return _originalMetadata.getScale(column); } @Override public String getSchemaName(int column) throws SQLException { return _originalMetadata.getSchemaName(column); } @Override public String getTableName(int column) throws SQLException { return _originalMetadata.getTableName(column); } @Override public boolean isAutoIncrement(int column) throws SQLException { return _originalMetadata.isAutoIncrement(column); } @Override public boolean isCaseSensitive(int column) throws SQLException { return _originalMetadata.isCaseSensitive(column); } @Override public boolean isCurrency(int column) throws SQLException { return _originalMetadata.isCurrency(column); } @Override public boolean isDefinitelyWritable(int column) throws SQLException { return _originalMetadata.isDefinitelyWritable(column); } @Override public int isNullable(int column) throws SQLException { return _originalMetadata.isNullable(column); } @Override public boolean isReadOnly(int column) throws SQLException { return _originalMetadata.isReadOnly(column); } @Override public boolean isSearchable(int column) throws SQLException { return _originalMetadata.isSearchable(column); } @Override public boolean isSigned(int column) throws SQLException { return _originalMetadata.isSigned(column); } @Override public boolean isWritable(int column) throws SQLException { return _originalMetadata.isWritable(column); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return _originalMetadata.isWrapperFor(iface); } @Override public <T> T unwrap(Class<T> iface) throws SQLException { return _originalMetadata.unwrap(iface); } }
Shell
UTF-8
455
3.296875
3
[]
no_license
#!/bin/bash source ./CONFIG.sh OUT="out/classes" rm -rf "$OUT" mkdir -p $OUT if [ "$(expr substr $(uname -s) 1 10)" == "MINGW64_NT" ]; then CP="$LIB" elif [ "$(expr substr $(uname -s) 1 10)" == "Linux" ]; then CP="$LIB" fi find . -name "*.java" | xargs javac -cp "$CP" -d $OUT -sourcepath $SRC mkdir -p "out/lib/" cp $CP "out/lib/" cp -r $RES "out/classes/" cd out cd classes JAR="../Main.jar" CLASSES_JAR="./" jar -cfe "$JAR" "$MAIN" $CLASSES_JAR
TypeScript
UTF-8
107
2.78125
3
[ "MIT" ]
permissive
export interface IValueObject<T> extends Readonly<{ type: string; value: T; }> { toString(): string; }
Java
UTF-8
3,231
2.578125
3
[]
no_license
package com.epam.newsmanagement.common.entity; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * Testing entity {@link NewsInfo} */ public class NewsInfoTest { /** * testing methods for variable news */ @Test public void testNews(){ NewsInfo newsInfo = new NewsInfo(); Assert.assertTrue(newsInfo.getNews() == null); News news1 = new News(); news1.setIdNews(new Long(1)); newsInfo.setNews(news1); Assert.assertEquals(news1, newsInfo.getNews()); } /** * testing methods for variable author */ @Test public void testAuthor(){ NewsInfo newsInfo = new NewsInfo(); Assert.assertTrue(newsInfo.getAuthor() == null); Author author = new Author(); author.setIdAuthor(new Long(1)); newsInfo.setAuthor(author); Assert.assertEquals(author, newsInfo.getAuthor()); } /** * testing methods for variable tags */ @Test public void testTags(){ NewsInfo newsInfo = new NewsInfo(); Assert.assertTrue(newsInfo.getTags() == null); Tag tag1 = new Tag(); tag1.setIdTag(new Long(1)); Tag tag2 = new Tag(); tag2.setIdTag(new Long(2)); List<Tag> tagList = new ArrayList<>(); tagList.add(tag1); tagList.add(tag2); newsInfo.setTags(tagList); Assert.assertEquals(tagList, newsInfo.getTags()); } /** * testing methods for variable comments */ @Test public void testComments(){ NewsInfo newsInfo = new NewsInfo(); Assert.assertTrue(newsInfo.getComments() == null); Comment comment1 = new Comment(); comment1.setIdComment(new Long(1)); Comment comment2 = new Comment(); comment2.setIdComment(new Long(2)); List<Comment> commentList = new ArrayList<>(); commentList.add(comment1); commentList.add(comment2); newsInfo.setComments(commentList); Assert.assertEquals(commentList, newsInfo.getComments()); } /** * testing overriding methods equals() */ @Test public void testEquals(){ NewsInfo newsInfo1 = new NewsInfo(); NewsInfo newsInfo2 = new NewsInfo(); Assert.assertEquals(newsInfo1, newsInfo2); Author author1 = new Author(); Author author2 = new Author(); author1.setIdAuthor(new Long(1)); author2.setIdAuthor(new Long(1)); newsInfo1.setAuthor(author1); newsInfo2.setAuthor(author2); Assert.assertEquals(newsInfo1, newsInfo2); } /** * testing overriding methods hashCode() */ @Test public void testHashCode(){ NewsInfo newsInfo1 = new NewsInfo(); NewsInfo newsInfo2 = new NewsInfo(); Assert.assertEquals(newsInfo1.hashCode(), newsInfo2.hashCode()); Author author1 = new Author(); Author author2 = new Author(); author1.setIdAuthor(new Long(1)); author2.setIdAuthor(new Long(1)); newsInfo1.setAuthor(author1); newsInfo2.setAuthor(author2); Assert.assertEquals(newsInfo1.hashCode(), newsInfo2.hashCode()); } }
JavaScript
UTF-8
1,130
2.71875
3
[]
no_license
var PriorityTypes = require('./priority-types'); var moment = require('moment'); var _ = require('lodash'); function Task(name, dueDate, priority, status, percentComplete, id) { var self = this; self.TITLE = name; self.DUE_DATE = dueDate; self.PRIORITY = priority; self.STATUS = status || 'Not Started'; self.PERCENT_COMPLETE = percentComplete; self.COMPLETED = false; self.PUBLICLY_VISIBLE = true; self.OWNER_USER_ID = process.env.USER_ID; self.RESPONSIBLE_USER_ID = process.env.USER_ID; self.ID = id; return self; } Task.prototype.format = function() { var response = this.TITLE; if(this.DUE_DATE) { response +='<break time="500ms"/> due '+ moment(this.DUE_DATE).format('MMMM Do YYYY'); } if(this.PRIORITY && _.findKey(PriorityTypes, this.PRIORITY)) { response +='<break time="500ms"/> with a '+ _.findKey(PriorityTypes, this.PRIORITY) +' priority'; } if(this.PERCENT_COMPLETE) { response +='<break time="500ms"/> '+this.PERCENT_COMPLETE +' percent complete'; } if(this.STATUS) { response +='<break time="500ms"/> with '+this.STATUS +' status'; } return response; }; module.exports = Task;
Java
UTF-8
606
2.453125
2
[]
no_license
package modelo; import java.util.ArrayList; import java.util.List; public class RegistroCompra { private List<Factura> facturalist; public RegistroCompra() { this.facturalist= new ArrayList<Factura>(); // TODO Auto-generated constructor stub } public void guardarCompra(Factura f) { this.facturalist.add(f); } public List<Factura> getFacturalist() { return facturalist; } public void setFacturalist(List<Factura> facturalist) { this.facturalist = facturalist; } @Override public String toString() { return "RegistroCompra [facturalist=" + facturalist + "]"; } }
JavaScript
UTF-8
2,272
2.578125
3
[]
no_license
import React, { useState } from "react"; import UserTable from "./tables/UserTable"; import AddUserForm from "./forms/AddUserForm"; import EditUserForm from "./forms/EditUserForm"; const App = () => { const usersData = [ { id: 1, race: "10km", fname: "Tania", lname: "Harding", gender: "Female", age: "33", code: "504", idnum: "" }, { id: 2, race: "10km", fname: "Paul", lname: "Scott", gender: "Male", age: "45", code: "1554", idnum: "7212295403087" }, { id: 3, race: "5km", fname: "Mark", lname: "Turner", gender: "Male", age: "40", code: "8632", idnum: ""} ]; const [users, setUsers] = useState(usersData); const [editing, setEditing] = useState(false); const initialFormState = { id: null, race: "", fname: "", lname: "", gender: "", age: "", code: "", idnum: "" }; const [currentUser, setCurrentUser] = useState(initialFormState); const addUser = user => { user.id = users.length + 1; setUsers([...users, user]); }; const deleteUser = id => { setEditing(false); setUsers(users.filter(user => user.id !== id)); }; const editRow = user => { setEditing(true); setCurrentUser({ id: user.id, race: user.race, fname: user.fname, lname: user.lname, gender: user.gender, age: user.age, code: user.code, idnum: user.idnum }); }; const updateUser = (id, updatedUser) => { setEditing(false); setUsers(users.map(user => (user.id === id ? updatedUser : user))); }; return ( <div className="container"> <h2>Participant Details</h2> <div className="flex-row"> <div className="flex-large"> {editing ? ( <div> <h2>Edit participant</h2> <EditUserForm editing={editing} setEditing={setEditing} currentUser={currentUser} updateUser={updateUser} /> </div> ) : ( <div> <h3>Add participant</h3> <AddUserForm addUser={addUser} /> </div> )} </div> <div className="flex-large"> <h3>Details</h3> <UserTable users={users} editRow={editRow} deleteUser={deleteUser} /> </div> </div> </div> ); }; export default App;
Python
UTF-8
1,601
2.53125
3
[]
no_license
import os import pyodbc import pandas as pd import numpy as np from dotenv import load_dotenv load_dotenv() # Database configuration # server = os.getenv('SERVER') # database = os.getenv('DB_NAME') # username = os.getenv('DB_USERNAME') # password = os.getenv('DB_PASSWORD') #connect to the Database # connection = pyodbc.connect( # 'DRIVER={ODBC Driver 17 for SQL Server};\ # SERVER='+server+';\ # DATABASE='+database+';\ # UID='+username+';\ # PWD='+ password # ) # cursor = connection.cursor() # print(cursor) # df = pd.read_sql_query('SELECT * FROM [DB_114226_vsdsandbox].[dbo].[bank_statement_activity]', connection) # print(df) server = os.getenv('SERVER') # database = os.getenv('DB_NAME') username = os.getenv('DB_USERNAME') password = os.getenv('DB_PASSWORD') def create_db_connection(server,username, password): connection = None try: connection = pyodbc.connect( 'DRIVER={ODBC Driver 17 for SQL Server};\ SERVER='+server+';\ UID='+username+';\ PWD='+ password ) print("Database connection successful") except Error as err: print(f"Error: '{err}'") return connection conn = create_db_connection(server,username,password) print(conn) df = pd.read_sql_query( 'SELECT * FROM [DB_114226_vsdsandbox].[dbo].[Bank_Ledger_Transactions]', conn) print(df) def read_db_table(dbname, **kwargs): pass def all_table_matches(): pass def at_least_three_matching_values(): pass def not_at_least_three_matching_values(): pass
Java
UTF-8
134
1.960938
2
[]
no_license
package it.polimi.ingsw.client.network; /** * Enum to return the network choice */ public enum NetworkTypeEnum { RMI, SOCKET }
Swift
UTF-8
2,595
3.046875
3
[]
no_license
// // Movie.swift // UpcomingMovies // // Created by Rodolfo Roca on 6/27/19. // Copyright © 2019 Rodolfo Roca. All rights reserved. // import Foundation struct Movie: Decodable { var id: Int var title: String var popularity: Double? var releaseDate: Date? var runtime: Int? var userScore: Double var posterPath: String? var backdropPath: String? var genres: [Genre] = [Genre]() var overview: String? enum CodingKeys: String, CodingKey { case id case title case popularity case releaseDate = "release_date" case runtime case userScore = "vote_average" case posterPath = "poster_path" case backdropPath = "backdrop_path" case genres case genreIDs = "genre_ids" case overview } init(from decoder: Decoder) throws { let valueContainer = try decoder.container(keyedBy: CodingKeys.self) self.id = try valueContainer.decode(Int.self, forKey: CodingKeys.id) self.title = try valueContainer.decode(String.self, forKey: CodingKeys.title) self.popularity = try? valueContainer.decode(Double.self, forKey: CodingKeys.popularity) let dateString = try? valueContainer.decode(String.self, forKey: CodingKeys.releaseDate) let dateFormatter = DateFormatter.init() dateFormatter.dateFormat = "yyyy-MM-dd" dateFormatter.isLenient = true if let dateString = dateString, dateString != "" { self.releaseDate = dateFormatter.date(from: dateString)! } self.runtime = try? valueContainer.decode(Int.self, forKey: CodingKeys.runtime) self.userScore = try valueContainer.decode(Double.self, forKey: CodingKeys.userScore) self.posterPath = try? valueContainer.decode(String.self, forKey: CodingKeys.posterPath) self.backdropPath = try? valueContainer.decode(String.self, forKey: CodingKeys.backdropPath) if let genreIDs = try? valueContainer.decode([Int].self, forKey: CodingKeys.genreIDs) { for id in genreIDs { for genre in AppDelegate.allGenres { if id == genre.id { self.genres.append(genre) break } } } } else { self.genres = try valueContainer.decode([Genre].self, forKey: CodingKeys.genres) } self.overview = try? valueContainer.decode(String.self, forKey: CodingKeys.overview) } }
Java
UTF-8
2,027
2.390625
2
[]
no_license
package com.mycompany.webapp.dao; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.mycompany.webapp.dto.Review; @Mapper public interface ReviewDao { public static List<Review> selectAll() { // TODO Auto-generated method stub return null; } public static int insert(Review review) { // TODO Auto-generated method stub return 0; } public Review selectByREVIEW_ID(int REVIEW_ID); public static int update(Review review) { // TODO Auto-generated method stub return 0; } public static int deleteByREVIEW_ID(int REVIEW_ID) { // TODO Auto-generated method stub return 0; } public int count(); } //mybatis에서 제공해주는 annotation -> 이거 사용하려면 pom.xml에 이와 관련한 것이 있어야 함. //mybatis에서 mapper라는 annotation으로 자동적으로 인터페이스를 구현한 객체를 만들어줌, //Mapper가 해석될려면 추가적으로 설정해줄 것이 있음. /* @Repository public class BoardsDao{ @Autowired private SqlSessionTemplate sst; public List<Board> selectAll(){ List<Board> list = sst.selectList("boards.selectAll"); return list; } public List<Board> selectByPage(Pager pager) { List<Board> list = sst.selectList("boards.selectByPage", pager); return list; } public int insert(Board board) { int rows = sst.insert("boards.insert", board); return rows; } public Board selectByBno(int bno) { Board board = sst.selectOne("boards.selectByBno", bno); return board; } public int update(Board board) { int rows = sst.update("boards.update", board); return rows; } public int deleteByBno(int bno) { int rows = sst.delete("boards.deleteByBno", bno); return rows; } public int updateBhitcount(int bno) { int rows = sst.update("boards.updateBhitcount", bno); return rows; } public int count() { int rows = sst.selectOne("boards.count"); return rows; } } */
JavaScript
UTF-8
791
3.03125
3
[]
no_license
var isValidBST = function(root) { if (!root) return true if (!root.left && !root.right) return true if (root.left == null) { return root.right.val > root.val && isValidBST(root.right) } else if (root.right == null) { return root.left.val < root.val && isValidBST(root.left) } return ( root.right.val > root.val && root.left.val < root.val && isValidBST(root.right) && isValidBST(root.left) ) } var isValidBST = function(root) { if (!root.left && !root.right) { return true } else if ( (root.left && root.left.val > root.val) || (root.right && root.right.val < root.val) ) { return false } else { return isValidBST(root.left) && isValidBST(root.left) } }
JavaScript
UTF-8
957
2.6875
3
[]
no_license
//将数据库中的图片上传到七牛云服务器中 //引入上传方法 const unload = require('./unload'); //引入nanoid获取唯一key值 const nanoid = require('nanoid') module.exports = async (key,dataWay)=>{ //1.获取数据库图片链接 const movies = await dataWay.find({$or:[ {[key]:''}, {[key]:null}, {[key]:{$exists:false}} ]}); for (let i = 0; i < movies.length; i++) { let movie = movies[i]; //获取每个文档对象 let url = movie.src;//获取每个图片链接 let fileName = '.jpg'; if(key === 'coverKey'){ url = movie.cover; }else if (key === 'videoKey'){ url = movie.link; fileName = '.mp4'; } let key2 = `${nanoid(21)}${fileName}`;//对key值进行唯一值获取 console.log(movie,url,key2); //2.将链接上传到七牛 await unload(url,key2); //3.保存key值到数据库中 movie[key] = key2 ; await movie.save(); } }
Java
UTF-8
3,392
2.65625
3
[]
no_license
package ru.job4j.quartz; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; import java.io.InputStream; import java.sql.*; import java.time.LocalDateTime; import java.util.Properties; import static org.quartz.JobBuilder.*; import static org.quartz.TriggerBuilder.*; import static org.quartz.SimpleScheduleBuilder.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AlertRabbit { private static final Logger LOG = LoggerFactory.getLogger(AlertRabbit.class.getName()); public static void init() { try (InputStream inputStream = AlertRabbit.class.getClassLoader().getResourceAsStream("rabbit.properties")) { Properties settings = new Properties(); settings.load(inputStream); Class.forName(settings.getProperty("driver-class-name")); try (Connection connection = DriverManager.getConnection( settings.getProperty("url"), settings.getProperty("username"), settings.getProperty("password") )) { try { Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.start(); JobDataMap data = new JobDataMap(); data.put("store", connection); JobDetail job = newJob(Rabbit.class) .usingJobData(data) .build(); SimpleScheduleBuilder times = simpleSchedule() .withIntervalInSeconds(Integer.parseInt(settings.getProperty("rabbit.interval"))) .repeatForever(); Trigger trigger = newTrigger() .startNow() .withSchedule(times) .build(); scheduler.scheduleJob(job, trigger); Thread.sleep(10000); scheduler.shutdown(); } catch (Exception se) { LOG.error("Error run Scheduler", se); } } catch (Exception ec) { LOG.error("DriverManager.getConnection", ec); } } catch (Exception e) { LOG.error("Error opening file rabbit.properties", e); } } public static void add(Connection cn) { try (PreparedStatement statement = cn.prepareStatement("insert into rabbit(create_date) values(?)")) { statement.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now())); statement.execute(); } catch (Exception e) { LOG.error("Error add date for tables SQL", e); } } public static void main(String[] args) { init(); } public static class Rabbit implements Job { public Rabbit() { LOG.info("Print now hashCode: {}", hashCode()); } @Override public void execute(JobExecutionContext context) { Connection cn = (Connection) context.getJobDetail().getJobDataMap().get("store"); try { LOG.info("connection.getMetaData().getMaxTablesInSelect() {}", cn.getMetaData().getMaxTablesInSelect()); } catch (SQLException e) { LOG.error("Error getMetaData()", e); } add(cn); } } }
JavaScript
UTF-8
2,178
3.140625
3
[]
no_license
import React, { Component } from "react"; import socketIOClient from "socket.io-client"; const endpoint = "http://192.168.1.50:4001" //change IP address to local machine's IP const socket = socketIOClient(endpoint); class App extends Component { constructor() { super(); this.state = { people: [], name: '', age: '' }; } componentDidMount () { socket.on('person', (person) => { this.setState({ people: [...this.state.people, person] }) }) } handleChange = event => { this.setState({ name: event.target.value }) } handleChanges = event => { this.setState({ age: event.target.value }) } handleSubmit = event => { event.preventDefault(); let name = this.state.name; let age = this.state.age; let id = socket.id.slice(8); let person = { id, name, age } this.setState({ people: [...this.state.people, person], name: '', age: '' }) socket.emit('person', name, age, id) } render() { const person = this.state.people.sort((obj1, obj2) => obj2.age - obj1.age).map((person, index) => { return <tr key={index}> <td>{person.id}</td> <td>{person.name}</td> <td>{person.age}</td> </tr> }) return ( <div> <h1>HELLO</h1> <p>Please enter the following:</p> <form onSubmit={this.handleSubmit}> <input type="text" placeholder="name" value={this.state.name}onChange={this.handleChange} /><br/><br/> <input type="text" placeholder="age" value={this.state.age} onChange={this.handleChanges} /> <br/><br/> <button className="btn btn-primary">Enter</button> </form> <table className="table table-dark"> <thead> <tr> <th scope="col">ID</th> <th scope="col">First</th> <th scope="col">Age</th> </tr> </thead> <tbody> {person} </tbody> </table> </div> ); } } export default App;
Python
UTF-8
245
3.59375
4
[]
no_license
def pattern(): print("Height of the pyramid : ", end = "") h = int(input()) print() while(h): for i in range(h): print('*', end = " ") print() h -= 1 if __name__ == '__main__': pattern()
TypeScript
UTF-8
2,056
2.546875
3
[ "MIT" ]
permissive
import { ResourceType } from "@models/Resource"; import { initialResourceState, resourceReducer, resourceSaga, ResourceStoreState } from "@store/resource"; import { connectRouter, routerMiddleware } from "connected-react-router"; import { createBrowserHistory } from "history"; import { merge, throttle } from "lodash"; import { applyMiddleware, createStore, Store } from "redux"; import createSagaMiddleware from "redux-saga"; import { loadState, saveState } from "./utils"; export const history = createBrowserHistory(); export interface StoreState { resources: ResourceStoreState; } export function getInitialState(): StoreState { // Load state from disk const storageState = loadState(); const memoryState: StoreState = { resources: { [ResourceType.LaunchItems]: initialResourceState(), [ResourceType.LaunchDetails]: initialResourceState(), [ResourceType.LaunchStatus]: initialResourceState() } }; // Merge memory state with storage state // Storage state will override memory state return merge(memoryState, storageState); } export function rootReducer(state: StoreState, action: any) { return { resources: resourceReducer(state.resources, action) }; } export function initStore(): Store<StoreState> { const STORE_SAVE_INTERVAL = 500; // in milliseconds const sagaMiddleware = createSagaMiddleware(); const middlewares = [ sagaMiddleware, routerMiddleware(history) ]; const initialState = getInitialState(); const store = createStore<StoreState>( connectRouter(history)(rootReducer), initialState, applyMiddleware(...middlewares), ); store.subscribe( throttle(() => { saveState({ // TODO: Add your stores which requires disk saving here // Sample // session: store.getState().session }); }, STORE_SAVE_INTERVAL) ); sagaMiddleware.run(resourceSaga); return store; }
Java
UTF-8
567
2
2
[ "Apache-2.0" ]
permissive
package gank.sin.me.gk.dagger.module; import android.content.Context; import javax.inject.Named; import dagger.Module; import dagger.Provides; import gank.sin.me.gk.dagger.ApplicationContext; import gank.sin.me.gk.db.GankDB; /** * Created by sin on 2016/8/19. */ @Module public class DBModule { @Provides @Named("context") public Context provideContext(@ApplicationContext Context context){ return context; } @Provides public GankDB provideGankDB(@Named("context") Context context){ return new GankDB(context); } }
Java
UTF-8
2,343
1.578125
2
[]
no_license
package com.rbcodebase.app; import android.app.Application; import com.crashlytics.android.Crashlytics; import com.facebook.react.ReactApplication; import com.oblador.vectoricons.VectorIconsPackage; import com.facebook.reactnative.androidsdk.FBSDKPackage; import com.microsoft.codepush.react.CodePush; import com.github.xinthink.rnmk.ReactMaterialKitPackage; import com.mapbox.reactnativemapboxgl.ReactNativeMapboxGLPackage; import com.babisoft.ReactNativeLocalization.ReactNativeLocalizationPackage; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import io.fabric.sdk.android.Fabric; import java.util.Arrays; import java.util.List; import com.facebook.CallbackManager; import com.facebook.FacebookSdk; import com.rbcodebase.app.modules.google.GoogleSignInPackage; public class MainApplication extends Application implements ReactApplication { private static CallbackManager mCallbackManager = CallbackManager.Factory.create(); protected static CallbackManager getCallbackManager() { return mCallbackManager; } private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override protected String getJSBundleFile() { return CodePush.getJSBundleFile(); } @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new VectorIconsPackage(), new GoogleSignInPackage(), new ReactMaterialKitPackage(), new ReactNativeMapboxGLPackage(), new ReactNativeLocalizationPackage(), new FBSDKPackage(mCallbackManager), new CodePush(getResources().getString(R.string.reactNativeCodePush_androidDeploymentKey), getApplicationContext(), BuildConfig.DEBUG) ); } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); Fabric.with(this, new Crashlytics()); SoLoader.init(this, /* native exopackage */ false); FacebookSdk.sdkInitialize(getApplicationContext()); } }
JavaScript
UTF-8
813
2.875
3
[]
no_license
// Generated by CoffeeScript 1.3.3 (function() { define(function() { var Vector; return Vector = { dotProduct: function(v1, v2) { return v1[0] * v2[0] + v1[1] * v2[1]; }, scale: function(s, v) { return [v[0] * s, v[1] * s]; }, length: function(v) { return Math.pow(v[0] * v[0] + v[1] * v[1], 0.5); }, add: function(v1, v2) { return [v1[0] + v2[0], v1[1] + v2[1]]; }, subtract: function(v1, v2) { return [v1[0] - v2[0], v1[1] - v2[1]]; }, normalize: function(v) { var l; l = this.length(v); return [v[0] / l, v[1] / l]; }, reflect: function(v, n) { return this.subtract(v, this.scale(2 * this.dotProduct(v, n), n)); } }; }); }).call(this);
Java
UTF-8
16,862
2.390625
2
[]
no_license
package database; import exceptions.AccessDeniedException; import exceptions.WrongFileException; import message.builder.IMessageBuilder; import message.builder.JSONMessageBuilder; import net.UserType; import structures.Password; import structures.ResultInfo; import java.io.*; import java.sql.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DatabaseManager { private static DatabaseManager instance; private Connection connection; private CallableStatement studentList; private CallableStatement resultList; private CallableStatement studentResultList; private CallableStatement groupList; private CallableStatement resultListWithParam; private CallableStatement resultUpdate; private CallableStatement passwordStatement; private Pattern loginPattern = Pattern.compile("[a-zA-Z0-9.]{1,20}"); private Pattern typePattern = Pattern.compile("[a-zA-Z_]+"); private Pattern datePattern = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}"); private Pattern filePattern = Pattern.compile("C:\\\\uni-results\\\\[a-zA-Z0-9]+.sql"); private String user, password; private IMessageBuilder builder = new JSONMessageBuilder(); private DatabaseManager() {} public static DatabaseManager getInstance() { if (instance == null) { synchronized (DatabaseManager.class) { if (instance == null) { instance = new DatabaseManager(); } } } return instance; } public void init(String address, String dbName, String user, String password, String backupUser, String backupPassword) throws SQLException { this.user = backupUser; this.password = backupPassword; connection = DriverManager.getConnection("jdbc:mysql://" + address + "/" + dbName + "?" + "user=" + user + "&password=" + password + "&noAccessToProcedureBodies=true"); studentList = connection.prepareCall("{call student_list(?, ?)}"); resultList = connection.prepareCall("{call result_list(?, ?)}"); studentResultList = connection.prepareCall("{call student_result_list(?, ?)}"); groupList = connection.prepareCall("{call group_list(?)}"); resultListWithParam = connection.prepareCall("{call result_list_param(?, ?, ?, ?)}"); resultUpdate = connection.prepareCall("{call activity_update(?, ?, ?, ?, ?)}"); passwordStatement = connection.prepareCall("SELECT pass, salt FROM Users WHERE login = ?"); } public String getStudentList(int groupID, String lecturerLogin) throws NullPointerException, AccessDeniedException { synchronized (this) { try { studentList.setInt(1, groupID); studentList.setString(2, lecturerLogin); ResultSet rs = studentList.executeQuery(); if (rs == null) throw new NullPointerException("Result set is null"); if (hasColumn(rs, "Access denied")) throw new AccessDeniedException("Access denied"); ArrayList<String> parts = new ArrayList<>(); while (rs.next()) { parts.add(builder .put("login", rs.getString("login")) .put("name_str", rs.getString("name_str")) .put("last_name", rs.getString("last_name")) .get() ); } builder.put("size", parts.size()); for (int i = 0; i < parts.size(); i++) builder.put("part" + i, parts.get(i)); return builder.get(); } catch (SQLException e) { System.err.println("SQL Exception in getStudentList"); throw new NullPointerException("Unable to retrieve data"); } } } public String getResultList(int groupID, String lecturerLogin) throws NullPointerException, AccessDeniedException { synchronized (this) { try { resultList.setInt(1, groupID); resultList.setString(2, lecturerLogin); ResultSet rs = resultList.executeQuery(); if (rs == null) throw new NullPointerException("Result set is null"); if (hasColumn(rs, "Access denied")) throw new AccessDeniedException("Access denied"); ArrayList<String> parts = new ArrayList<>(); while (rs.next()) { parts.add(builder .put("ID", rs.getInt("ID")) .put("login", rs.getString("login")) .put("name_str", rs.getString("name_str")) .put("last_name", rs.getString("last_name")) .put("when_given", rs.getString("when_given")) .put("res_value", rs.getInt("res_value")) .put("res_type", rs.getString("res_type")) .get() ); } builder.put("size", parts.size()); for (int i = 0; i < parts.size(); i++) builder.put("part" + i, parts.get(i)); return builder.get(); } catch (SQLException e) { System.err.println("SQL Exception in getStudentList"); throw new NullPointerException("Unable to retrieve data"); } } } public String getResultList(int groupID, String lecturerLogin, String input, boolean isLogin, boolean isLecturer) throws NullPointerException, AccessDeniedException { synchronized (this) { try { Matcher match = loginPattern.matcher(input); if (!(match.matches() && isLecturer)) throw new AccessDeniedException("Access denied"); resultListWithParam.setInt(1, groupID); resultListWithParam.setString(2, lecturerLogin); resultListWithParam.setString(3, (isLogin) ? input : ""); resultListWithParam.setString(4, (isLogin) ? "" : input); ResultSet rs = resultListWithParam.executeQuery(); if (rs == null) throw new NullPointerException("Result set is null"); if (hasColumn(rs, "Access denied")) throw new AccessDeniedException("Access denied"); ArrayList<String> parts = new ArrayList<>(); while (rs.next()) { parts.add(builder .put("ID", rs.getInt("ID")) .put("login", rs.getString("login")) .put("name_str", rs.getString("name_str")) .put("last_name", rs.getString("last_name")) .put("when_given", rs.getString("when_given")) .put("res_value", rs.getDouble("res_value")) .put("res_type", rs.getString("res_type")) .get() ); } builder.put("size", parts.size()); for (int i = 0; i < parts.size(); i++) builder.put("part" + i, parts.get(i)); return builder.get(); } catch (SQLException e) { System.err.println("SQL Exception in getStudentList"); throw new AccessDeniedException("Unable to retrieve data"); } } } public String getStudentResultList(int groupID, String studentLogin) throws NullPointerException, AccessDeniedException { synchronized (this) { try { studentResultList.setInt(1, groupID); studentResultList.setString(2, studentLogin); ResultSet rs = studentResultList.executeQuery(); if (rs == null) throw new NullPointerException("Result set is null"); if (hasColumn(rs, "Access denied")) throw new AccessDeniedException("Access denied"); ArrayList<String> parts = new ArrayList<>(); while (rs.next()) { String msg = builder .put("when_given", rs.getString("when_given")) .put("res_value", rs.getDouble("res_value")) .put("res_type", rs.getString("res_type")) .get(); parts.add( msg ); } builder.put("size", parts.size()); for (int i = 0; i < parts.size(); i++) builder.put("part" + i, parts.get(i)); return builder.get(); } catch (SQLException e) { System.err.println("SQL Exception in getStudentList"); throw new NullPointerException("Unable to retrieve data"); } } } public String getGroupList(String userLogin, boolean isLecturer) throws NullPointerException, AccessDeniedException { synchronized (this) { try { groupList.setString(1, userLogin); ResultSet rs = groupList.executeQuery(); if (rs == null) throw new NullPointerException("Result set is null"); if (hasColumn(rs, "Access denied")) throw new AccessDeniedException("Access denied"); ArrayList<String> parts = new ArrayList<>(); while (rs.next()) { if (isLecturer) { parts.add(builder .put("ID", rs.getInt("ID")) .put("group_name", rs.getString("group_name")) .put("start_time", rs.getString("start_time")) .put("week_patt", rs.getString("week_patt")) .put("week_day", rs.getInt("week_day")) .get() ); } else { parts.add(builder .put("ID", rs.getInt("ID")) .put("group_name", rs.getString("group_name")) .put("last_name", rs.getString("last_name")) .put("degree", rs.getString("degree")) .put("start_time", rs.getString("start_time")) .put("week_patt", rs.getString("week_patt")) .put("week_day", rs.getInt("week_day")) .get() ); } } builder.put("size", parts.size()); for (int i = 0; i < parts.size(); i++) builder.put("part" + i, parts.get(i)); return builder.get(); } catch (SQLException e) { System.err.println("SQL Exception in getStudentList"); throw new NullPointerException("Unable to retrieve data"); } } } public void updateResultRows(ResultInfo[] results, boolean doAddition, boolean isLecturer) throws NullPointerException, AccessDeniedException { synchronized (this) { if (!isLecturer) throw new AccessDeniedException("Access denied"); if (results.length == 0) return; String date = results[0].getDate(); if (!checkDateFormat(date)) { throw new AccessDeniedException("Invalid date"); } try { connection.setAutoCommit(false); for (ResultInfo res : results) { resultUpdate.setString(1, res.getLogin()); resultUpdate.setInt(2, res.getGroupID()); resultUpdate.setString(3, date); resultUpdate.setDouble(4, res.getValue()); resultUpdate.setBoolean(5, doAddition); resultUpdate.executeUpdate(); } connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException ignored) { } System.err.println("SQL Exception in updateResultRows"); throw new NullPointerException("Unable to retrieve data"); } finally { try { connection.setAutoCommit(true); } catch (SQLException e) { System.err.println("SQL Exception in updateResultRows"); throw new NullPointerException("Unable to update data"); } } } } public void insertResultRows(ResultInfo[] results, boolean isLecturer) throws NullPointerException, AccessDeniedException { synchronized (this) { if (!isLecturer) throw new AccessDeniedException("Access denied"); if (results.length == 0) return; String date = results[0].getDate(); if (!checkDateFormat(date)) { throw new AccessDeniedException("Invalid date"); } try { connection.setAutoCommit(false); PreparedStatement stmt; stmt = connection.prepareStatement("INSERT INTO Results VALUES(NULL, ?, ?, ?, ?, ?)"); for (ResultInfo res : results) { Matcher matchLogin = loginPattern.matcher(res.getLogin()); Matcher matchType = typePattern.matcher(res.getType()); Matcher matchDate = datePattern.matcher(res.getDate()); boolean loginMatcher = matchLogin.matches(); boolean typeMatcher = matchType.matches(); boolean dateMatcher = matchDate.matches(); if (!(loginMatcher && typeMatcher && dateMatcher)) throw new AccessDeniedException("Invalid data pattern"); stmt.setString(1, res.getLogin()); stmt.setInt(2, res.getGroupID()); stmt.setString(3, res.getType()); stmt.setString(4, date); stmt.setDouble(5, res.getValue()); stmt.executeUpdate(); } connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException ignored) { } System.err.println("SQL Exception in updateResultRows"); throw new NullPointerException("Unable to retrieve data"); } finally { try { connection.setAutoCommit(true); } catch (SQLException e) { System.err.println("SQL Exception in updateResultRows"); throw new NullPointerException("Unable to update data"); } } } } public void deleteResultRow(ResultInfo[] results, boolean isLecturer) throws NullPointerException, AccessDeniedException { synchronized (this) { if (!isLecturer) throw new AccessDeniedException("Access denied"); try { connection.setAutoCommit(false); PreparedStatement stmt; stmt = connection.prepareStatement("DELETE FROM Results WHERE ID = ?"); for (ResultInfo res : results) { stmt.setInt(1, res.getResultID()); stmt.executeUpdate(); } connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException ignored) {} System.err.println("SQL Exception in updateResultRows"); throw new NullPointerException("Unable to retrieve data"); } finally { try { connection.setAutoCommit(true); } catch (SQLException e) { System.err.println("SQL Exception in updateResultRows"); throw new NullPointerException("Unable to update data"); } } } } public Password getPassword(String login, UserType type) throws AccessDeniedException { synchronized (this) { try { Matcher match = loginPattern.matcher(login); if (!match.matches()) throw new AccessDeniedException("Access denied"); int count = 0; ResultSet rs; if (type == UserType.ADMIN) { if (login.equals("admin")) count++; } else if (type == UserType.LECTURER) { rs = passwordStatement.executeQuery("SELECT login FROM Lecturers WHERE login = \'" + login + "\'"); while (rs.next()) count++; } if (type == UserType.STUDENT) { rs = passwordStatement.executeQuery("SELECT login FROM Students WHERE login = \'" + login + "\'"); while (rs.next()) count++; } if (count == 0) throw new AccessDeniedException("Access denied"); rs = passwordStatement.executeQuery("SELECT pass, salt FROM Users WHERE login = \'" + login + "\'"); if (rs == null) throw new NullPointerException("Result set is null"); if (hasColumn(rs, "Access denied")) throw new AccessDeniedException("Access denied"); if (rs.next()) return new Password(rs.getString("pass"), rs.getString("salt")); else throw new AccessDeniedException("Access denied"); } catch (SQLException e) { System.err.println("SQL Exception in updateResultRows"); throw new NullPointerException("Unable to retrieve data"); } } } public void doBackup(String file) throws AccessDeniedException, WrongFileException { synchronized (this) { System.out.println("Performing a backup to " + file); if (!filePattern.matcher(file).matches()) throw new WrongFileException("File name has to be of this format: [a-zA-Z0-9]+.sql"); File workDir = new File("C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin"); String[] command = { "cmd.exe", "/c", "mysqldump.exe " + "--opt --quote-names --routines --triggers --user=" + user + " --password=" + password + " " + "uni_results > \"" + file + "\"" }; performDump(workDir, command); } } public void doRestore(String file) throws AccessDeniedException, WrongFileException { synchronized (this) { System.out.println("Performing a restore from " + file); if (!filePattern.matcher(file).matches()) throw new WrongFileException("File name has to be of this format: [a-zA-Z0-9]+.sql"); File workDir = new File("C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin"); String[] command = { "cmd.exe", "/c", "mysql.exe " + "--user=" + user + " --password=" + password + " --default-character-set=utf8 " + "--database=uni_results < \"" + file + "\"" }; performDump(workDir, command); } } private void performDump(File workDir, String[] command) throws WrongFileException { try { Process dump = Runtime.getRuntime().exec(command, null, workDir); String line; InputStream is = dump.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while ( (line = br.readLine()) != null) System.out.println(line); is = dump.getErrorStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); while ( (line = br.readLine()) != null) System.err.println(line); } catch (IOException e) { throw new WrongFileException(); } } private boolean hasColumn(ResultSet rs, String name) throws SQLException { ResultSetMetaData meta = rs.getMetaData(); int columns = meta.getColumnCount(); for (int i = 1; i <= columns; i++) { if (name.equals(meta.getColumnName(i))) return true; } return false; } private boolean checkDateFormat(String date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sdf.setLenient(false); try { sdf.parse(date); } catch (ParseException e) { return false; } return true; } }
Python
UTF-8
5,834
2.875
3
[]
no_license
# Python version import sys print('Python: {}'.format(sys.version)) # scipy import scipy print('scipy: {}'.format(scipy.__version__)) # numpy import numpy print('numpy: {}'.format(numpy.__version__)) # matplotlib import matplotlib print('matplotlib: {}'.format(matplotlib.__version__)) # pandas import pandas print('pandas: {}'.format(pandas.__version__)) # scikit-learn import sklearn print('sklearn: {}'.format(sklearn.__version__)) # Load libraries from pandas import read_csv from pandas.plotting import scatter_matrix from matplotlib import pyplot from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.model_selection import StratifiedKFold from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC import os,sys from scipy import stats import pandas as pd import numpy as np dataset = pd.read_csv('trainData.csv') dataset.replace('?', np.nan, inplace=True) #print(dataset["A14"].value_counts()) #replace missing values with high frequency values dataset = dataset.fillna({"A1": "b"}) dataset = dataset.fillna({"A2": "24.5"}) dataset = dataset.fillna({"A3": "u"}) dataset = dataset.fillna({"A4": "g"}) dataset = dataset.fillna({"A6": "c"}) dataset = dataset.fillna({"A9": "v"}) dataset = dataset.fillna({"A15": "g"}) dataset = dataset.fillna({"A8": "False"}) dataset = dataset.fillna({"A11": "True"}) dataset = dataset.fillna({"A13": "False"}) dataset = dataset.fillna({"A14": "0"}) #convert objects & bool values to int from sklearn.preprocessing import LabelEncoder lb_make = LabelEncoder() dataset["A1"] = lb_make.fit_transform(dataset["A1"]) dataset["A2"] = lb_make.fit_transform(dataset["A2"]) dataset["A3"] = lb_make.fit_transform(dataset["A3"]) dataset["A4"] = lb_make.fit_transform(dataset["A4"]) dataset["A6"] = lb_make.fit_transform(dataset["A6"]) dataset["A8"] = lb_make.fit_transform(dataset["A8"]) dataset["A9"] = lb_make.fit_transform(dataset["A9"]) dataset["A11"] = lb_make.fit_transform(dataset["A11"]) dataset["A13"] = lb_make.fit_transform(dataset["A13"]) dataset["A14"] = lb_make.fit_transform(dataset["A14"]) dataset["A15"] = lb_make.fit_transform(dataset["A15"]) dataset["A16"] = lb_make.fit_transform(dataset["A16"]) #replace missing values of integers & floats using mean value of each column df_mean_imputed = dataset.fillna(dataset.mean()) df_median_imputed = dataset.fillna(dataset.median()) # print(df_mean_imputed) array = dataset.values X = array[:,0:15] y = array[:,15] #split the data set X_train, X_validation, Y_train, Y_validation = train_test_split(X, y, test_size=0.20, random_state=1) #Feature scaling sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_validation = sc_X.transform(X_validation) # Make predictions on validation dataset model = LogisticRegression(solver='liblinear', multi_class='ovr') model.fit(X_train, Y_train) predictions = model.predict(X_validation) # Evaluate predictions print('Accuracy: ',accuracy_score(Y_validation, predictions)) print('confusion_matrix: ') print(confusion_matrix(Y_validation, predictions)) print('classification_report: ') print(classification_report(Y_validation, predictions)) ######################################################################## #for test data set dataset = pd.read_csv('testdata.csv') dataset.replace('?', np.nan, inplace=True) #print(dataset["A14"].value_counts()) #replace missing values with high frequency values dataset = dataset.fillna({"A1": "b"}) dataset = dataset.fillna({"A2": "24.5"}) dataset = dataset.fillna({"A3": "u"}) dataset = dataset.fillna({"A4": "g"}) dataset = dataset.fillna({"A6": "c"}) dataset = dataset.fillna({"A9": "v"}) dataset = dataset.fillna({"A15": "g"}) dataset = dataset.fillna({"A8": "False"}) dataset = dataset.fillna({"A11": "True"}) dataset = dataset.fillna({"A13": "False"}) dataset = dataset.fillna({"A14": "0"}) #convert objects & bool values to int from sklearn.preprocessing import LabelEncoder lb_make = LabelEncoder() dataset["A1"] = lb_make.fit_transform(dataset["A1"]) dataset["A2"] = lb_make.fit_transform(dataset["A2"]) dataset["A3"] = lb_make.fit_transform(dataset["A3"]) dataset["A4"] = lb_make.fit_transform(dataset["A4"]) dataset["A6"] = lb_make.fit_transform(dataset["A6"]) dataset["A8"] = lb_make.fit_transform(dataset["A8"]) dataset["A9"] = lb_make.fit_transform(dataset["A9"]) dataset["A11"] = lb_make.fit_transform(dataset["A11"]) dataset["A13"] = lb_make.fit_transform(dataset["A13"]) dataset["A14"] = lb_make.fit_transform(dataset["A14"]) dataset["A15"] = lb_make.fit_transform(dataset["A15"]) # dataset["A16"] = lb_make.fit_transform(dataset["A16"]) #replace missing values of integers & floats using mean value of each column df_mean_imputed = dataset.fillna(dataset.mean()) df_median_imputed = dataset.fillna(dataset.median()) # print(df_mean_imputed) array = dataset.values X = array[:,0:15] y = array[:,14] X = sc_X.transform(X) predictions = model.predict(X) # Evaluate predictions print("Predictions (1-> success & 0-> Failure):") print( predictions)
Markdown
UTF-8
3,383
2.984375
3
[]
no_license
<!DOCTYPE html> <html> <body> <h1>这是一个标题</h1> <h2>这是一个标题</h2> <h3>这是一个标题</h3> <h1>Test</h1> <hr style="height:5px;border:none;border-top:50px solid #2894ff;" /> <hr style=" height:2px;border:none;border-top:2px dotted #185598;" /> <h3>Test 1</h3> <?php // echo "<div style='background:#ff0000; width:300px; height:300px;'>"; // echo 'Test 1'; // echo '<br>'; $x = "World!"; echo $x; echo '<br>'; $s = 'Hello'; echo $s; echo '<br>'; echo $s.' '.$x; echo '<br>'; echo strlen('hello word!'); echo '<br>'; echo strpos("hello word!","o"); echo '<br>'; ?> <hr style=" height:2px;border:none;border-top:2px dotted #185598;" /> <h3>Test 2</h3> <?php // echo 'Test 2'; // echo '<br>'; $s = 9.6e6; echo $s; echo '<br>'; var_dump($s); echo '<br>'; echo '<br>'; $im = imagecreatetruecolor(300,1000); $red = imagecolorallocate($im,255,0,0); imageline($im,30,30,240,140,$red); imagepng($im); imagedestroy($im); ?> <hr style=" height:2px;border:none;border-top:2px dotted #185598;" /> <h3>Test 3</h3> <?php // echo 'Test 3'; // echo '<br>'; $x=5; $y=3; echo 'x='.$x; echo '<br>'; echo 'y='.$y; echo '<br>'; echo '<br>'; print 'z1='.$z=$x+$y; echo '<br>'; echo 'z1='.$x+=$y; echo '<br>'; echo '<br>'; echo '-(z1)='.$z=-$x; echo '<br>'; echo '<br>'; print 'z2='.$z=$x*$y; echo '<br>'; echo 'z2='.$x*=$y; echo '<br>'; print 'z3='.$z=$x/$y; echo '<br>'; echo 'z3='.$x/=$y; echo '<br>'; print 'z4='.$z=$x%$y; echo '<br>'; echo 'z4='.$x%=$y; echo '<br>'; echo '<br>'; $x=7; echo ++$x." //"."($x=7,echo ++$x)"; echo '<br>'; $y=10; echo $y++."//"."(y=10,echo y++)"; echo '<br>'; echo $y."//"."(echo y)"; echo '<br>'; echo '<br>'; echo '<br>'; ?> <hr style=" height:2px;border:none;border-top:2px dotted #185598;" /> <h3>Test 4</h3> <?php // echo 'Test 4'; // echo '<br>'; class Car { var $color; function __construct($color="green") { $this->color = $color; } function what_color(){ return $this->color; } } function print_vars($obj) { foreach (get_object_vars($obj) as $prop => $val) { echo "\t$prop = $val\n"; } } $herbie = new Car("white"); echo "\therbie: Properties\n"; print_vars($herbie); echo '<br>'; echo '<br>'; $x="Hello world!"; $x=null; var_dump($x); echo '<br>'; echo '<br>'; ?> <hr style=" height:2px;border:none;border-top:2px dotted #185598;" /> <h3>Test 5</h3> <?php // echo 'Test 5'; // echo '<br>'; // define("GREETING", "欢迎访问 Runoob.com"); define("greeting", "欢迎访问 runoob.COM",true); echo GREETING; echo '<br>'; echo greeting; echo '<br>'; ?> <hr style=" height:2px;border:none;border-top:2px dotted #185598;" /> <h3>Test 6</h3> <?php // echo 'Test 6'; // echo '<br>'; for ($i=1; $i<=10; $i++) { if ($i % 2 == 1) { echo "<ins>" . $i . "</ins>".","; } elseif($i<10 ) { echo $i.','; } else { echo $i."。"; } } ?> <hr style=" height:2px;border:none;border-top:2px dotted #185598;" /> <h3>Test 7</h3> <?php // echo 'Test 7'; $x=7; $y=10; echo 'x='.$x; echo '<br>'; echo 'y='.$y; echo '<br>'; var_dump($x>10 and $y>5); echo '<br>'; var_dump($x!=$y); echo '<br>'; var_dump($x||$y); echo '<br>'; echo '<br>'; $x=array("a"=>"red","b"=>"green","c"=>"white"); $y=array("d"=>"blue","e"=>"yellow","f"=>"black"); $z=$x+$y; var_dump($z); ?> <hr style=" height:2px;border:none;border-top:2px dotted #185598;" /> </body> </html>
Java
UTF-8
614
2.296875
2
[]
no_license
package finalproject.service; import java.util.List; import javax.inject.Inject; import org.springframework.stereotype.Service; import finalproject.data.entities.Customer; import finalproject.data.repository.CustomerRepository; @Service public class CustomerService { @Inject CustomerRepository customerRepository; public Customer findByName(String name) { return this.customerRepository.findByName(name); } public List<Customer> findAll(){ return this.customerRepository.findAll(); } public Customer save(Customer customer) { return this.save(customer); } }
Java
UTF-8
932
2.40625
2
[]
no_license
package com.tom.example1.config; import org.slf4j.MDC; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Callable; import java.util.concurrent.Future; /** * MyThreadPoolTaskExecutor 将父线程的trackId传递下去给子线程即可 * * @author TomLuo * @date 2023年03月06日 21:55 */ public final class MyThreadPoolTaskExecutor extends ThreadPoolTaskExecutor { public MyThreadPoolTaskExecutor() { super(); } @Override public void execute(Runnable task) { super.execute(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap())); } @Override public <T> Future<T> submit(Callable<T> task) { return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap())); } @Override public Future<?> submit(Runnable task) { return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap())); } }
Markdown
UTF-8
355
3.265625
3
[]
no_license
# Description Create a function that will return `true` if the input is in the following date time format `01-09-2016 01:20` and `false` if it is not. This Kata has been inspired by the Regular Expressions chapter from the book Eloquent JavaScript. --- ## Solution ```js const dateChecker = (date) => /\d{2}-\d{2}-\d{4}\s\d{2}:\d{2}/.test(date); ```
Markdown
UTF-8
1,038
2.90625
3
[ "MIT" ]
permissive
# General | Security | File Uploads <br> ### Only allow authorised users to upload files. todo: complement description <br> ### Always disallow upload of executable files. TODO: Add description <br> ### Always validate uploaded files against a list of allowed extensions allow. TODO: Add description <br> ### Avoid accepting compressed files such as ZIP files. It is not recommended allowing applications to accept compressed files. Compressed files such as ZIP archives can contain any type of files. This makes it possible for multiple attack methods to be used to harm the system. TODO: complement description <br> ### Always restrict the maximum allowed size for uploaded files. The application should enforce size restrictions for the upload mechanism. This will allow the system to protect the file storage capacity. In case the file storage process require decompression of files, the allowed size should consider the extra-space required for the files to be decompressed. TODO: complement description <br>
Markdown
UTF-8
1,537
3.125
3
[]
no_license
Problems with Divine Justice ============================ Christianity claims that God is just. Setting universalism (i.e. the theory that all are ultimately saved, that none go to hell) and annihilationism (i.e. the theory that those who do not go to heaven do not go to hell either, but rather are annihilated) aside, Christianity also claims that at the end of one’s life one either enjoys an eternity in heaven or suffers an eternity in hell. These claims, it is often argued, conflict. How can a just God treat human beings in this way? The argument is most naturally cast as a problem relating to vagueness. Just rewards and just punishments are proportional to whatever it is that is being rewarded or punished. The just punishment for murder is greater than the just punishment for slander because murder is a greater crime that slander. Whatever it is that determines whether one is rewarded in heaven or punished in hell - be it faith, works, or a combination of the two - is something that comes in degrees. One can have more faith or less faith, more good works or less good works. In order for the rewards and punishments for faith or works to just, then, these rewards and punishments must admit of degrees. One with greater faith or greater works deserves better than one with lesser faith or lesser works. Heaven and hell, though, are both all or nothing affairs; they do not admit of degrees. God’s policy of sending some to heaven and some to hell, then, seems to be inconsistent with his treating us justly.
C#
UTF-8
4,841
2.625
3
[ "Apache-2.0" ]
permissive
// This file constitutes a part of the SharpMedia project, (c) 2007 by the SharpMedia team // and is licensed for your use under the conditions of the NDA or other legally binding contract // that you or a legal entity you represent has signed with the SharpMedia team. // In an event that you have received or obtained this file without such legally binding contract // in place, you MUST destroy all files and other content to which this lincese applies and // contact the SharpMedia team for further instructions at the internet mail address: // // legal@sharpmedia.com // using System; using System.Collections.Generic; using System.Text; using System.Collections.ObjectModel; using SharpMedia.AspectOriented; namespace SharpMedia.Input.Mappings { /// <summary> /// A triggered action delegate. /// </summary> public delegate void TrigerredAction(float triggerData); /// <summary> /// An action. /// </summary> /// <remarks>Should add possibilities for "merging" triggers in one frame.</remarks> [Serializable] public sealed class Action : IActionTriggerable { #region Private Members ActionMapping mapping; List<IActionTrigger> triggers = new List<IActionTrigger>(); string name; TrigerredAction events = null; string desc = string.Empty; #endregion #region Protected Methods internal void Initialize(EventProcessor processor, bool bind) { foreach (IActionTrigger trigger in triggers) { trigger.Initialize(processor, bind); } } #endregion #region Constructors /// <summary> /// Creates an action /// </summary> /// <param name="name"></param> internal Action([NotNull] ActionMapping mapping, string name) { this.mapping = mapping; this.name = name; } #endregion #region Methods /// <summary> /// Adds a trigger to action. /// </summary> /// <param name="trigger"></param> public void AddTrigger(IActionTrigger trigger) { lock (triggers) { triggers.Add(trigger); trigger.BindTo(this); trigger.Initialize(mapping.InputProvider, true); } } /// <summary> /// Removes trigger from action. /// </summary> /// <param name="trigger"></param> public void RemoveTrigger(IActionTrigger trigger) { lock (triggers) { if (triggers.Remove(trigger)) { trigger.Initialize(mapping.InputProvider, false); trigger.BindTo(null); } } } /// <summary> /// Triggers the action, usually through triggers (but can use manual trigger here). /// </summary> /// <param name="stateData">Usually used by axis triggers to </param> public void Trigger(float stateData) { TrigerredAction ev = events; if (ev != null) { ev(stateData); } } #endregion #region Properties /// <summary> /// The mapping this action belongs to. /// </summary> public ActionMapping Mapping { get { return mapping; } } /// <summary> /// All action triggers. /// </summary> public ReadOnlyCollection<IActionTrigger> ActionTriggers { get { return new ReadOnlyCollection<IActionTrigger>(triggers); } } /// <summary> /// The name of action. /// </summary> public string Name { get { return name; } } /// <summary> /// Description of action. /// </summary> public string Description { get { return desc; } set { desc = value; } } /// <summary> /// Event trigger, including the a /// </summary> public event TrigerredAction Event { add { lock (triggers) { events += value; } } remove { lock (triggers) { events -= value; } } } #endregion #region IActionTriggerable Members void IActionTriggerable.Trigger(IActionTrigger trigger, float stateData) { Trigger(stateData); } #endregion } }
Markdown
UTF-8
6,925
3.359375
3
[ "MIT" ]
permissive
--- layout: post title: Outfit Suggestion --- In this quarter, KeFan Ping and I completed an Outfit Recommendation application that can recommend daily wear for users. Please refer to this [repo link](https://github.com/KefanPing/Outfit_Recommendation_Project) for details. This blog is a reflection on this outfit recommended app. This blog is written by us (KeFan Ping and me) together. ## Inspiration Do you sometimes (definitely not during the final exams week) stand in front of your closet and think deeply about "what should I wear today?!", "how do I pair up clothes today to make me more fashionable?!". Everyone defines fashion personally, but there are always some methods and ways that are fashionable for most people. What a person wears can also clearly show how that person's character and taste are. For people who don't have time to think about this, they may need to use an app to improve their sense of fashion, such as an outfit recommendation app. ## Overall, what did you achieve in your project? - Overall, we have implemented a local app which can store photo of clothes owned by users and recommend what to wear (top, bottom, and shoes) daily. Our user interface is designed with PyQt5, and our recognition model is trained with TensorFlow. Our recommendation system is based on the rationality of the style and the degree of color combination. - At the beginning of the project, we continuously tried many different data sets and recognition ideas to increase the rationality of recognition and recommendation. In the end, we chose a data set from kaggle and decided to use four models to reduce the recognition error rate by slightly modifying the huge data set. - When we designed our recommendation system, we wrote a lot of complex functions on the front-end and back-end models to identify, classify, record information, display information, and recommend combinations of users’ photos. In addition, we also provide buttons to delete and edit information. This reminds us of how we learned OOP before. ## What are aspects of your project that you are especially proud of? Kefan: The thing I am most proud of is that our app did help me sort out clothes and recommended me clothes combinations that I think are very fashionable. Kefan: I use various apps on my computer and mobile phones every day, but this is the first time I have implemented an app by myself, and I think it is very useful. Chengwei: Our subcategory identify model has 99% accuracy and other three models has average around 80% accuracy. I'm so proud of our images indentify models' accuracy. Chengwei: I also proud of our app's functionality and UI design, our APP allow user insert the image, delet the cloth, edit the cloth feature before the generate the outfit combinations. And our UI has good looking and simple, as a user I feel so comfortable to use this APP. ## What are two things you would suggest doing to further improve your project? (You are not responsible for doing those things.) - Our design idea is actually more suitable for users to use on mobile phones. We have two ways to improve: The first method: Turn this local app into a web app so that users can use it not only on the computer, but also on the mobile phone. The second method: Make this app a mobile application (you can download it from the App store or Google store), but we need to learn a new programming language - We also hope to continue to build a record system that can store the user's historical wear, not only to record fashion, but also to record the user's life. Our plan is to create a txt file to store the paths of clothes recommended in history. When the user wants to query the previous outfits, our program will extract the path from the txt and display them. ## How does what you achieved compare to what you set out to do in your proposal? (if you didn't complete everything in your proposal, that's fine!) Looking at it now, our proposal is too ambitious. There are several things we mentioned in the proposal but they were not completed: - We originally planned to involve some NLP content, such as analyzing what style of clothes people like to wear nowadays, what color combination is the most popular, etc. through news and social media. - We originally planned that our app can save the user's clothes information, but our current work requires the user to re-upload all clothes every time the app is opened. ## What are three things you learned from the experience of completing your project? Data analysis techniques? Python packages? Git + GitHub? Etc? - We build our UI with PyQt5 package, it is a very convenient package to design the appearance of an UI. We learned how to connect an event to a button, display images in UI, get the imformation from user. - We build our mechine learning model with TensworFlow package. We learned the technique to build and trian a machine learning model by TensworFlow. We also found a very powerful resnet50 layer on the Keras website to help us improve the accuracy of the models. - We didn’t use GitHub much before. Through this project, we witnessed GitHub’s ability to edit files and manage files, and also saw the convenience of GitHub as a programmer community. ## How will your experience completing this project will help you in your future studies or career? Please be as specific as possible. Kefan: As a person who regards data science as a career plan, the computer vision model training and interactive app development carried out in this project gave me some initial experience in this field. As I said above, this is my first time writing a program, and this has brought me the experience of putting ideas into practice. In the process, I learned how to adjust our plan reasonably to improve the app. Since our project requires some knowledge beyond the class, this process also exercised my self-study ability, Through the study of PyQt5, I have more ideas for designing my own software in the future. In addition to the technical level, I also witnessed the strength of the team. During these two months, Chengwei and I have united our thoughts and acted together in the process of completing the project. A lot of our work is done together. In this process, everyone reminds and supplements each other, which greatly improves work efficiency. Communication in all work is the most important, and the information is processed in a timely, effective and clear manner. Chengwei: We build and train some mechine learning models to help us to identify the images of cloth. We learned a lot of knowlegeds about how to built a mechine learning model such as: data collection and cleaning, prepare trainning,testing,validation dataset. Construct a machine learning model and train it, imporve machine learning model. This is a very valueable experience for my future career related to data sicence and machine learning.
PHP
UTF-8
1,476
2.65625
3
[]
no_license
<?php use Illuminate\Database\Seeder; class PositionTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $poses = [ 'deps' => [ 'Директор', 'Заместитель директора', ], 'funct' => [ 'Руководитель группы', 'Главный менеджер', 'Главный менеджер 1 уровня', 'Главный менеджер 2 уровня', 'Главный менеджер 3 уровня', 'Менеджер', 'Менеджер 1 уровня', 'Менеджер 2 уровня', 'Менеджер 3 уровня', 'Начальник управления', 'Начальник отдела', 'Руководитель', 'Главный специалист', 'Эксперт', ], ]; foreach ($poses['deps'] as $pos) { $position = new \App\Position(); $position->name = $pos; $position->save(); } foreach ($poses['funct'] as $post) { $position = new \App\Position(); $position->name = $post; $position->save(); } } }
Java
UTF-8
73,449
1.585938
2
[]
no_license
/* Elijah Gonzales 725000232 Josiah Hamid-Khani 725003646 Joseph Hernandez 825002632 CSCE 313-505 October 10, 2018 parserGrammarParser.java */ // Generated from H:/Java\parserGrammar.g4 by ANTLR 4.7 import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.*; import org.antlr.v4.runtime.tree.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class parserGrammarParser extends Parser { static { RuntimeMetaData.checkVersion("4.7", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int T__0=1, T__1=2, T__2=3, T__3=4, T__4=5, T__5=6, T__6=7, T__7=8, T__8=9, T__9=10, T__10=11, T__11=12, T__12=13, T__13=14, T__14=15, T__15=16, T__16=17, T__17=18, T__18=19, T__19=20, T__20=21, T__21=22, T__22=23, T__23=24, T__24=25, T__25=26, T__26=27, T__27=28, T__28=29, T__29=30, T__30=31, T__31=32, T__32=33, T__33=34, T__34=35, T__35=36, T__36=37, Identifier=38, Alpha=39, Digit=40, WS=41; public static final int RULE_program = 0, RULE_query = 1, RULE_relationName = 2, RULE_expr = 3, RULE_atomicExpr = 4, RULE_selection = 5, RULE_condition = 6, RULE_conjunction = 7, RULE_comparison = 8, RULE_op = 9, RULE_operand = 10, RULE_attributeName = 11, RULE_projection = 12, RULE_attributeList = 13, RULE_renaming = 14, RULE_union = 15, RULE_difference = 16, RULE_product = 17, RULE_command = 18, RULE_closeCmd = 19, RULE_writeCmd = 20, RULE_openCmd = 21, RULE_exitCmd = 22, RULE_showCmd = 23, RULE_createCmd = 24, RULE_updateCmd = 25, RULE_insertCmd = 26, RULE_deleteCmd = 27, RULE_typedAttributeList = 28, RULE_type = 29, RULE_integer = 30, RULE_literal = 31; public static final String[] ruleNames = { "program", "query", "relationName", "expr", "atomicExpr", "selection", "condition", "conjunction", "comparison", "op", "operand", "attributeName", "projection", "attributeList", "renaming", "union", "difference", "product", "command", "closeCmd", "writeCmd", "openCmd", "exitCmd", "showCmd", "createCmd", "updateCmd", "insertCmd", "deleteCmd", "typedAttributeList", "type", "integer", "literal" }; private static final String[] _LITERAL_NAMES = { null, "'<-'", "';'", "'('", "')'", "'select'", "'||'", "'&&'", "'=='", "'!='", "'<'", "'>'", "'<='", "'>='", "'project'", "','", "'rename'", "'+'", "'-'", "'*'", "'CLOSE'", "'WRITE'", "'OPEN'", "'EXIT'", "'SHOW'", "'CREATE TABLE'", "'PRIMARY KEY'", "'UPDATE'", "'SET'", "'='", "'WHERE'", "'INSERT INTO'", "'VALUES FROM'", "'VALUES FROM RELATION'", "'DELETE FROM'", "'VARCHAR'", "'INTEGER'", "'\"'" }; private static final String[] _SYMBOLIC_NAMES = { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, "Identifier", "Alpha", "Digit", "WS" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } @Override public String getGrammarFileName() { return "parserGrammar.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public parserGrammarParser(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class ProgramContext extends ParserRuleContext { public List<QueryContext> query() { return getRuleContexts(QueryContext.class); } public QueryContext query(int i) { return getRuleContext(QueryContext.class,i); } public List<CommandContext> command() { return getRuleContexts(CommandContext.class); } public CommandContext command(int i) { return getRuleContext(CommandContext.class,i); } public ProgramContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_program; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterProgram(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitProgram(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitProgram(this); else return visitor.visitChildren(this); } } public final ProgramContext program() throws RecognitionException { ProgramContext _localctx = new ProgramContext(_ctx, getState()); enterRule(_localctx, 0, RULE_program); int _la; try { enterOuterAlt(_localctx, 1); { setState(68); _errHandler.sync(this); _la = _input.LA(1); while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__19) | (1L << T__20) | (1L << T__21) | (1L << T__22) | (1L << T__23) | (1L << T__24) | (1L << T__26) | (1L << T__30) | (1L << T__33) | (1L << Identifier))) != 0)) { { setState(66); _errHandler.sync(this); switch (_input.LA(1)) { case Identifier: { setState(64); query(); } break; case T__19: case T__20: case T__21: case T__22: case T__23: case T__24: case T__26: case T__30: case T__33: { setState(65); command(); } break; default: throw new NoViableAltException(this); } } setState(70); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class QueryContext extends ParserRuleContext { public RelationNameContext relationName() { return getRuleContext(RelationNameContext.class,0); } public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public QueryContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_query; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterQuery(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitQuery(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitQuery(this); else return visitor.visitChildren(this); } } public final QueryContext query() throws RecognitionException { QueryContext _localctx = new QueryContext(_ctx, getState()); enterRule(_localctx, 2, RULE_query); try { enterOuterAlt(_localctx, 1); { setState(71); relationName(); setState(72); match(T__0); setState(73); expr(); setState(74); match(T__1); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class RelationNameContext extends ParserRuleContext { public TerminalNode Identifier() { return getToken(parserGrammarParser.Identifier, 0); } public RelationNameContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_relationName; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterRelationName(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitRelationName(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitRelationName(this); else return visitor.visitChildren(this); } } public final RelationNameContext relationName() throws RecognitionException { RelationNameContext _localctx = new RelationNameContext(_ctx, getState()); enterRule(_localctx, 4, RULE_relationName); try { enterOuterAlt(_localctx, 1); { setState(76); match(Identifier); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ExprContext extends ParserRuleContext { public AtomicExprContext atomicExpr() { return getRuleContext(AtomicExprContext.class,0); } public SelectionContext selection() { return getRuleContext(SelectionContext.class,0); } public ProjectionContext projection() { return getRuleContext(ProjectionContext.class,0); } public RenamingContext renaming() { return getRuleContext(RenamingContext.class,0); } public UnionContext union() { return getRuleContext(UnionContext.class,0); } public DifferenceContext difference() { return getRuleContext(DifferenceContext.class,0); } public ProductContext product() { return getRuleContext(ProductContext.class,0); } public ExprContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_expr; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterExpr(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitExpr(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitExpr(this); else return visitor.visitChildren(this); } } public final ExprContext expr() throws RecognitionException { ExprContext _localctx = new ExprContext(_ctx, getState()); enterRule(_localctx, 6, RULE_expr); try { setState(85); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,2,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(78); atomicExpr(); } break; case 2: enterOuterAlt(_localctx, 2); { setState(79); selection(); } break; case 3: enterOuterAlt(_localctx, 3); { setState(80); projection(); } break; case 4: enterOuterAlt(_localctx, 4); { setState(81); renaming(); } break; case 5: enterOuterAlt(_localctx, 5); { setState(82); union(); } break; case 6: enterOuterAlt(_localctx, 6); { setState(83); difference(); } break; case 7: enterOuterAlt(_localctx, 7); { setState(84); product(); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class AtomicExprContext extends ParserRuleContext { public RelationNameContext relationName() { return getRuleContext(RelationNameContext.class,0); } public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public AtomicExprContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_atomicExpr; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterAtomicExpr(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitAtomicExpr(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitAtomicExpr(this); else return visitor.visitChildren(this); } } public final AtomicExprContext atomicExpr() throws RecognitionException { AtomicExprContext _localctx = new AtomicExprContext(_ctx, getState()); enterRule(_localctx, 8, RULE_atomicExpr); try { setState(92); _errHandler.sync(this); switch (_input.LA(1)) { case Identifier: enterOuterAlt(_localctx, 1); { setState(87); relationName(); } break; case T__2: enterOuterAlt(_localctx, 2); { setState(88); match(T__2); setState(89); expr(); setState(90); match(T__3); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class SelectionContext extends ParserRuleContext { public ConditionContext condition() { return getRuleContext(ConditionContext.class,0); } public AtomicExprContext atomicExpr() { return getRuleContext(AtomicExprContext.class,0); } public SelectionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_selection; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterSelection(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitSelection(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitSelection(this); else return visitor.visitChildren(this); } } public final SelectionContext selection() throws RecognitionException { SelectionContext _localctx = new SelectionContext(_ctx, getState()); enterRule(_localctx, 10, RULE_selection); try { enterOuterAlt(_localctx, 1); { setState(94); match(T__4); setState(95); match(T__2); setState(96); condition(); setState(97); match(T__3); setState(98); atomicExpr(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ConditionContext extends ParserRuleContext { public List<ConjunctionContext> conjunction() { return getRuleContexts(ConjunctionContext.class); } public ConjunctionContext conjunction(int i) { return getRuleContext(ConjunctionContext.class,i); } public ConditionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_condition; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterCondition(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitCondition(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitCondition(this); else return visitor.visitChildren(this); } } public final ConditionContext condition() throws RecognitionException { ConditionContext _localctx = new ConditionContext(_ctx, getState()); enterRule(_localctx, 12, RULE_condition); int _la; try { enterOuterAlt(_localctx, 1); { setState(100); conjunction(); setState(105); _errHandler.sync(this); _la = _input.LA(1); while (_la==T__5) { { { setState(101); match(T__5); setState(102); conjunction(); } } setState(107); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ConjunctionContext extends ParserRuleContext { public List<ComparisonContext> comparison() { return getRuleContexts(ComparisonContext.class); } public ComparisonContext comparison(int i) { return getRuleContext(ComparisonContext.class,i); } public ConjunctionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_conjunction; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterConjunction(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitConjunction(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitConjunction(this); else return visitor.visitChildren(this); } } public final ConjunctionContext conjunction() throws RecognitionException { ConjunctionContext _localctx = new ConjunctionContext(_ctx, getState()); enterRule(_localctx, 14, RULE_conjunction); int _la; try { enterOuterAlt(_localctx, 1); { setState(108); comparison(); setState(113); _errHandler.sync(this); _la = _input.LA(1); while (_la==T__6) { { { setState(109); match(T__6); setState(110); comparison(); } } setState(115); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ComparisonContext extends ParserRuleContext { public List<OperandContext> operand() { return getRuleContexts(OperandContext.class); } public OperandContext operand(int i) { return getRuleContext(OperandContext.class,i); } public OpContext op() { return getRuleContext(OpContext.class,0); } public ConditionContext condition() { return getRuleContext(ConditionContext.class,0); } public ComparisonContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_comparison; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterComparison(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitComparison(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitComparison(this); else return visitor.visitChildren(this); } } public final ComparisonContext comparison() throws RecognitionException { ComparisonContext _localctx = new ComparisonContext(_ctx, getState()); enterRule(_localctx, 16, RULE_comparison); try { setState(124); _errHandler.sync(this); switch (_input.LA(1)) { case T__36: case Identifier: case Alpha: case Digit: enterOuterAlt(_localctx, 1); { setState(116); operand(); setState(117); op(); setState(118); operand(); } break; case T__2: enterOuterAlt(_localctx, 2); { setState(120); match(T__2); setState(121); condition(); setState(122); match(T__3); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class OpContext extends ParserRuleContext { public OpContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_op; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterOp(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitOp(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitOp(this); else return visitor.visitChildren(this); } } public final OpContext op() throws RecognitionException { OpContext _localctx = new OpContext(_ctx, getState()); enterRule(_localctx, 18, RULE_op); int _la; try { enterOuterAlt(_localctx, 1); { setState(126); _la = _input.LA(1); if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__7) | (1L << T__8) | (1L << T__9) | (1L << T__10) | (1L << T__11) | (1L << T__12))) != 0)) ) { _errHandler.recoverInline(this); } else { if ( _input.LA(1)==Token.EOF ) matchedEOF = true; _errHandler.reportMatch(this); consume(); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class OperandContext extends ParserRuleContext { public AttributeNameContext attributeName() { return getRuleContext(AttributeNameContext.class,0); } public LiteralContext literal() { return getRuleContext(LiteralContext.class,0); } public OperandContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_operand; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterOperand(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitOperand(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitOperand(this); else return visitor.visitChildren(this); } } public final OperandContext operand() throws RecognitionException { OperandContext _localctx = new OperandContext(_ctx, getState()); enterRule(_localctx, 20, RULE_operand); try { setState(130); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,7,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(128); attributeName(); } break; case 2: enterOuterAlt(_localctx, 2); { setState(129); literal(); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class AttributeNameContext extends ParserRuleContext { public TerminalNode Identifier() { return getToken(parserGrammarParser.Identifier, 0); } public AttributeNameContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_attributeName; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterAttributeName(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitAttributeName(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitAttributeName(this); else return visitor.visitChildren(this); } } public final AttributeNameContext attributeName() throws RecognitionException { AttributeNameContext _localctx = new AttributeNameContext(_ctx, getState()); enterRule(_localctx, 22, RULE_attributeName); try { enterOuterAlt(_localctx, 1); { setState(132); match(Identifier); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ProjectionContext extends ParserRuleContext { public AttributeListContext attributeList() { return getRuleContext(AttributeListContext.class,0); } public AtomicExprContext atomicExpr() { return getRuleContext(AtomicExprContext.class,0); } public ProjectionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_projection; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterProjection(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitProjection(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitProjection(this); else return visitor.visitChildren(this); } } public final ProjectionContext projection() throws RecognitionException { ProjectionContext _localctx = new ProjectionContext(_ctx, getState()); enterRule(_localctx, 24, RULE_projection); try { enterOuterAlt(_localctx, 1); { setState(134); match(T__13); setState(135); match(T__2); setState(136); attributeList(); setState(137); match(T__3); setState(138); atomicExpr(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class AttributeListContext extends ParserRuleContext { public List<AttributeNameContext> attributeName() { return getRuleContexts(AttributeNameContext.class); } public AttributeNameContext attributeName(int i) { return getRuleContext(AttributeNameContext.class,i); } public AttributeListContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_attributeList; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterAttributeList(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitAttributeList(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitAttributeList(this); else return visitor.visitChildren(this); } } public final AttributeListContext attributeList() throws RecognitionException { AttributeListContext _localctx = new AttributeListContext(_ctx, getState()); enterRule(_localctx, 26, RULE_attributeList); int _la; try { enterOuterAlt(_localctx, 1); { setState(140); attributeName(); setState(145); _errHandler.sync(this); _la = _input.LA(1); while (_la==T__14) { { { setState(141); match(T__14); setState(142); attributeName(); } } setState(147); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class RenamingContext extends ParserRuleContext { public AttributeListContext attributeList() { return getRuleContext(AttributeListContext.class,0); } public AtomicExprContext atomicExpr() { return getRuleContext(AtomicExprContext.class,0); } public RenamingContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_renaming; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterRenaming(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitRenaming(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitRenaming(this); else return visitor.visitChildren(this); } } public final RenamingContext renaming() throws RecognitionException { RenamingContext _localctx = new RenamingContext(_ctx, getState()); enterRule(_localctx, 28, RULE_renaming); try { enterOuterAlt(_localctx, 1); { setState(148); match(T__15); setState(149); match(T__2); setState(150); attributeList(); setState(151); match(T__3); setState(152); atomicExpr(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class UnionContext extends ParserRuleContext { public List<AtomicExprContext> atomicExpr() { return getRuleContexts(AtomicExprContext.class); } public AtomicExprContext atomicExpr(int i) { return getRuleContext(AtomicExprContext.class,i); } public UnionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_union; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterUnion(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitUnion(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitUnion(this); else return visitor.visitChildren(this); } } public final UnionContext union() throws RecognitionException { UnionContext _localctx = new UnionContext(_ctx, getState()); enterRule(_localctx, 30, RULE_union); try { enterOuterAlt(_localctx, 1); { setState(154); atomicExpr(); setState(155); match(T__16); setState(156); atomicExpr(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class DifferenceContext extends ParserRuleContext { public List<AtomicExprContext> atomicExpr() { return getRuleContexts(AtomicExprContext.class); } public AtomicExprContext atomicExpr(int i) { return getRuleContext(AtomicExprContext.class,i); } public DifferenceContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_difference; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterDifference(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitDifference(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitDifference(this); else return visitor.visitChildren(this); } } public final DifferenceContext difference() throws RecognitionException { DifferenceContext _localctx = new DifferenceContext(_ctx, getState()); enterRule(_localctx, 32, RULE_difference); try { enterOuterAlt(_localctx, 1); { setState(158); atomicExpr(); setState(159); match(T__17); setState(160); atomicExpr(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ProductContext extends ParserRuleContext { public List<AtomicExprContext> atomicExpr() { return getRuleContexts(AtomicExprContext.class); } public AtomicExprContext atomicExpr(int i) { return getRuleContext(AtomicExprContext.class,i); } public ProductContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_product; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterProduct(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitProduct(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitProduct(this); else return visitor.visitChildren(this); } } public final ProductContext product() throws RecognitionException { ProductContext _localctx = new ProductContext(_ctx, getState()); enterRule(_localctx, 34, RULE_product); try { enterOuterAlt(_localctx, 1); { setState(162); atomicExpr(); setState(163); match(T__18); setState(164); atomicExpr(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class CommandContext extends ParserRuleContext { public OpenCmdContext openCmd() { return getRuleContext(OpenCmdContext.class,0); } public CloseCmdContext closeCmd() { return getRuleContext(CloseCmdContext.class,0); } public WriteCmdContext writeCmd() { return getRuleContext(WriteCmdContext.class,0); } public ExitCmdContext exitCmd() { return getRuleContext(ExitCmdContext.class,0); } public ShowCmdContext showCmd() { return getRuleContext(ShowCmdContext.class,0); } public CreateCmdContext createCmd() { return getRuleContext(CreateCmdContext.class,0); } public UpdateCmdContext updateCmd() { return getRuleContext(UpdateCmdContext.class,0); } public InsertCmdContext insertCmd() { return getRuleContext(InsertCmdContext.class,0); } public DeleteCmdContext deleteCmd() { return getRuleContext(DeleteCmdContext.class,0); } public CommandContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_command; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterCommand(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitCommand(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitCommand(this); else return visitor.visitChildren(this); } } public final CommandContext command() throws RecognitionException { CommandContext _localctx = new CommandContext(_ctx, getState()); enterRule(_localctx, 36, RULE_command); try { enterOuterAlt(_localctx, 1); { setState(175); _errHandler.sync(this); switch (_input.LA(1)) { case T__21: { setState(166); openCmd(); } break; case T__19: { setState(167); closeCmd(); } break; case T__20: { setState(168); writeCmd(); } break; case T__22: { setState(169); exitCmd(); } break; case T__23: { setState(170); showCmd(); } break; case T__24: { setState(171); createCmd(); } break; case T__26: { setState(172); updateCmd(); } break; case T__30: { setState(173); insertCmd(); } break; case T__33: { setState(174); deleteCmd(); } break; default: throw new NoViableAltException(this); } setState(177); match(T__1); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class CloseCmdContext extends ParserRuleContext { public RelationNameContext relationName() { return getRuleContext(RelationNameContext.class,0); } public CloseCmdContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_closeCmd; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterCloseCmd(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitCloseCmd(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitCloseCmd(this); else return visitor.visitChildren(this); } } public final CloseCmdContext closeCmd() throws RecognitionException { CloseCmdContext _localctx = new CloseCmdContext(_ctx, getState()); enterRule(_localctx, 38, RULE_closeCmd); try { enterOuterAlt(_localctx, 1); { setState(179); match(T__19); setState(180); relationName(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class WriteCmdContext extends ParserRuleContext { public RelationNameContext relationName() { return getRuleContext(RelationNameContext.class,0); } public WriteCmdContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_writeCmd; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterWriteCmd(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitWriteCmd(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitWriteCmd(this); else return visitor.visitChildren(this); } } public final WriteCmdContext writeCmd() throws RecognitionException { WriteCmdContext _localctx = new WriteCmdContext(_ctx, getState()); enterRule(_localctx, 40, RULE_writeCmd); try { enterOuterAlt(_localctx, 1); { setState(182); match(T__20); setState(183); relationName(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class OpenCmdContext extends ParserRuleContext { public RelationNameContext relationName() { return getRuleContext(RelationNameContext.class,0); } public OpenCmdContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_openCmd; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterOpenCmd(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitOpenCmd(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitOpenCmd(this); else return visitor.visitChildren(this); } } public final OpenCmdContext openCmd() throws RecognitionException { OpenCmdContext _localctx = new OpenCmdContext(_ctx, getState()); enterRule(_localctx, 42, RULE_openCmd); try { enterOuterAlt(_localctx, 1); { setState(185); match(T__21); setState(186); relationName(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ExitCmdContext extends ParserRuleContext { public ExitCmdContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_exitCmd; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterExitCmd(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitExitCmd(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitExitCmd(this); else return visitor.visitChildren(this); } } public final ExitCmdContext exitCmd() throws RecognitionException { ExitCmdContext _localctx = new ExitCmdContext(_ctx, getState()); enterRule(_localctx, 44, RULE_exitCmd); try { enterOuterAlt(_localctx, 1); { setState(188); match(T__22); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ShowCmdContext extends ParserRuleContext { public AtomicExprContext atomicExpr() { return getRuleContext(AtomicExprContext.class,0); } public ShowCmdContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_showCmd; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterShowCmd(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitShowCmd(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitShowCmd(this); else return visitor.visitChildren(this); } } public final ShowCmdContext showCmd() throws RecognitionException { ShowCmdContext _localctx = new ShowCmdContext(_ctx, getState()); enterRule(_localctx, 46, RULE_showCmd); try { enterOuterAlt(_localctx, 1); { setState(190); match(T__23); setState(191); atomicExpr(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class CreateCmdContext extends ParserRuleContext { public RelationNameContext relationName() { return getRuleContext(RelationNameContext.class,0); } public TypedAttributeListContext typedAttributeList() { return getRuleContext(TypedAttributeListContext.class,0); } public AttributeListContext attributeList() { return getRuleContext(AttributeListContext.class,0); } public CreateCmdContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_createCmd; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterCreateCmd(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitCreateCmd(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitCreateCmd(this); else return visitor.visitChildren(this); } } public final CreateCmdContext createCmd() throws RecognitionException { CreateCmdContext _localctx = new CreateCmdContext(_ctx, getState()); enterRule(_localctx, 48, RULE_createCmd); try { enterOuterAlt(_localctx, 1); { setState(193); match(T__24); setState(194); relationName(); setState(195); match(T__2); setState(196); typedAttributeList(); setState(197); match(T__3); setState(198); match(T__25); setState(199); match(T__2); setState(200); attributeList(); setState(201); match(T__3); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class UpdateCmdContext extends ParserRuleContext { public RelationNameContext relationName() { return getRuleContext(RelationNameContext.class,0); } public List<AttributeNameContext> attributeName() { return getRuleContexts(AttributeNameContext.class); } public AttributeNameContext attributeName(int i) { return getRuleContext(AttributeNameContext.class,i); } public List<LiteralContext> literal() { return getRuleContexts(LiteralContext.class); } public LiteralContext literal(int i) { return getRuleContext(LiteralContext.class,i); } public ConditionContext condition() { return getRuleContext(ConditionContext.class,0); } public UpdateCmdContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_updateCmd; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterUpdateCmd(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitUpdateCmd(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitUpdateCmd(this); else return visitor.visitChildren(this); } } public final UpdateCmdContext updateCmd() throws RecognitionException { UpdateCmdContext _localctx = new UpdateCmdContext(_ctx, getState()); enterRule(_localctx, 50, RULE_updateCmd); int _la; try { enterOuterAlt(_localctx, 1); { setState(203); match(T__26); setState(204); relationName(); setState(205); match(T__27); setState(206); attributeName(); setState(207); match(T__28); setState(208); literal(); setState(216); _errHandler.sync(this); _la = _input.LA(1); while (_la==T__14) { { { setState(209); match(T__14); setState(210); attributeName(); setState(211); match(T__28); setState(212); literal(); } } setState(218); _errHandler.sync(this); _la = _input.LA(1); } setState(219); match(T__29); setState(220); condition(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class InsertCmdContext extends ParserRuleContext { public RelationNameContext relationName() { return getRuleContext(RelationNameContext.class,0); } public List<LiteralContext> literal() { return getRuleContexts(LiteralContext.class); } public LiteralContext literal(int i) { return getRuleContext(LiteralContext.class,i); } public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public InsertCmdContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_insertCmd; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterInsertCmd(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitInsertCmd(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitInsertCmd(this); else return visitor.visitChildren(this); } } public final InsertCmdContext insertCmd() throws RecognitionException { InsertCmdContext _localctx = new InsertCmdContext(_ctx, getState()); enterRule(_localctx, 52, RULE_insertCmd); int _la; try { setState(241); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,12,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(222); match(T__30); setState(223); relationName(); setState(224); match(T__31); setState(225); match(T__2); setState(226); literal(); setState(231); _errHandler.sync(this); _la = _input.LA(1); while (_la==T__14) { { { setState(227); match(T__14); setState(228); literal(); } } setState(233); _errHandler.sync(this); _la = _input.LA(1); } setState(234); match(T__3); } break; case 2: enterOuterAlt(_localctx, 2); { setState(236); match(T__30); setState(237); relationName(); setState(238); match(T__32); setState(239); expr(); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class DeleteCmdContext extends ParserRuleContext { public RelationNameContext relationName() { return getRuleContext(RelationNameContext.class,0); } public ConditionContext condition() { return getRuleContext(ConditionContext.class,0); } public DeleteCmdContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_deleteCmd; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterDeleteCmd(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitDeleteCmd(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitDeleteCmd(this); else return visitor.visitChildren(this); } } public final DeleteCmdContext deleteCmd() throws RecognitionException { DeleteCmdContext _localctx = new DeleteCmdContext(_ctx, getState()); enterRule(_localctx, 54, RULE_deleteCmd); try { enterOuterAlt(_localctx, 1); { setState(243); match(T__33); setState(244); relationName(); setState(245); match(T__29); setState(246); condition(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class TypedAttributeListContext extends ParserRuleContext { public List<AttributeNameContext> attributeName() { return getRuleContexts(AttributeNameContext.class); } public AttributeNameContext attributeName(int i) { return getRuleContext(AttributeNameContext.class,i); } public List<TypeContext> type() { return getRuleContexts(TypeContext.class); } public TypeContext type(int i) { return getRuleContext(TypeContext.class,i); } public TypedAttributeListContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_typedAttributeList; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterTypedAttributeList(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitTypedAttributeList(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitTypedAttributeList(this); else return visitor.visitChildren(this); } } public final TypedAttributeListContext typedAttributeList() throws RecognitionException { TypedAttributeListContext _localctx = new TypedAttributeListContext(_ctx, getState()); enterRule(_localctx, 56, RULE_typedAttributeList); int _la; try { enterOuterAlt(_localctx, 1); { setState(248); attributeName(); setState(249); type(); setState(256); _errHandler.sync(this); _la = _input.LA(1); while (_la==T__14) { { { setState(250); match(T__14); setState(251); attributeName(); setState(252); type(); } } setState(258); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class TypeContext extends ParserRuleContext { public IntegerContext integer() { return getRuleContext(IntegerContext.class,0); } public TypeContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_type; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterType(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitType(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitType(this); else return visitor.visitChildren(this); } } public final TypeContext type() throws RecognitionException { TypeContext _localctx = new TypeContext(_ctx, getState()); enterRule(_localctx, 58, RULE_type); try { setState(265); _errHandler.sync(this); switch (_input.LA(1)) { case T__34: enterOuterAlt(_localctx, 1); { setState(259); match(T__34); setState(260); match(T__2); setState(261); integer(); setState(262); match(T__3); } break; case T__35: enterOuterAlt(_localctx, 2); { setState(264); match(T__35); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class IntegerContext extends ParserRuleContext { public List<TerminalNode> Digit() { return getTokens(parserGrammarParser.Digit); } public TerminalNode Digit(int i) { return getToken(parserGrammarParser.Digit, i); } public IntegerContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_integer; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterInteger(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitInteger(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitInteger(this); else return visitor.visitChildren(this); } } public final IntegerContext integer() throws RecognitionException { IntegerContext _localctx = new IntegerContext(_ctx, getState()); enterRule(_localctx, 60, RULE_integer); int _la; try { enterOuterAlt(_localctx, 1); { setState(267); match(Digit); setState(271); _errHandler.sync(this); _la = _input.LA(1); while (_la==Digit) { { { setState(268); match(Digit); } } setState(273); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class LiteralContext extends ParserRuleContext { public List<TerminalNode> Alpha() { return getTokens(parserGrammarParser.Alpha); } public TerminalNode Alpha(int i) { return getToken(parserGrammarParser.Alpha, i); } public List<TerminalNode> Digit() { return getTokens(parserGrammarParser.Digit); } public TerminalNode Digit(int i) { return getToken(parserGrammarParser.Digit, i); } public TerminalNode Identifier() { return getToken(parserGrammarParser.Identifier, 0); } public LiteralContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_literal; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).enterLiteral(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof parserGrammarListener ) ((parserGrammarListener)listener).exitLiteral(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof parserGrammarVisitor ) return ((parserGrammarVisitor<? extends T>)visitor).visitLiteral(this); else return visitor.visitChildren(this); } } public final LiteralContext literal() throws RecognitionException { LiteralContext _localctx = new LiteralContext(_ctx, getState()); enterRule(_localctx, 62, RULE_literal); int _la; try { setState(286); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,17,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(274); _la = _input.LA(1); if ( !(_la==Alpha || _la==Digit) ) { _errHandler.recoverInline(this); } else { if ( _input.LA(1)==Token.EOF ) matchedEOF = true; _errHandler.reportMatch(this); consume(); } } break; case 2: enterOuterAlt(_localctx, 2); { setState(275); _la = _input.LA(1); if ( !(_la==Alpha || _la==Digit) ) { _errHandler.recoverInline(this); } else { if ( _input.LA(1)==Token.EOF ) matchedEOF = true; _errHandler.reportMatch(this); consume(); } setState(279); _errHandler.sync(this); _la = _input.LA(1); while (_la==Alpha || _la==Digit) { { { setState(276); _la = _input.LA(1); if ( !(_la==Alpha || _la==Digit) ) { _errHandler.recoverInline(this); } else { if ( _input.LA(1)==Token.EOF ) matchedEOF = true; _errHandler.reportMatch(this); consume(); } } } setState(281); _errHandler.sync(this); _la = _input.LA(1); } } break; case 3: enterOuterAlt(_localctx, 3); { setState(282); match(T__36); setState(283); match(Identifier); setState(284); match(T__36); } break; case 4: enterOuterAlt(_localctx, 4); { setState(285); match(Identifier); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3+\u0123\4\2\t\2\4"+ "\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t"+ "\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22"+ "\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31\t\31"+ "\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36\4\37\t\37\4 \t \4!"+ "\t!\3\2\3\2\7\2E\n\2\f\2\16\2H\13\2\3\3\3\3\3\3\3\3\3\3\3\4\3\4\3\5\3"+ "\5\3\5\3\5\3\5\3\5\3\5\5\5X\n\5\3\6\3\6\3\6\3\6\3\6\5\6_\n\6\3\7\3\7\3"+ "\7\3\7\3\7\3\7\3\b\3\b\3\b\7\bj\n\b\f\b\16\bm\13\b\3\t\3\t\3\t\7\tr\n"+ "\t\f\t\16\tu\13\t\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\5\n\177\n\n\3\13\3\13"+ "\3\f\3\f\5\f\u0085\n\f\3\r\3\r\3\16\3\16\3\16\3\16\3\16\3\16\3\17\3\17"+ "\3\17\7\17\u0092\n\17\f\17\16\17\u0095\13\17\3\20\3\20\3\20\3\20\3\20"+ "\3\20\3\21\3\21\3\21\3\21\3\22\3\22\3\22\3\22\3\23\3\23\3\23\3\23\3\24"+ "\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3\24\5\24\u00b2\n\24\3\24\3\24\3\25"+ "\3\25\3\25\3\26\3\26\3\26\3\27\3\27\3\27\3\30\3\30\3\31\3\31\3\31\3\32"+ "\3\32\3\32\3\32\3\32\3\32\3\32\3\32\3\32\3\32\3\33\3\33\3\33\3\33\3\33"+ "\3\33\3\33\3\33\3\33\3\33\3\33\7\33\u00d9\n\33\f\33\16\33\u00dc\13\33"+ "\3\33\3\33\3\33\3\34\3\34\3\34\3\34\3\34\3\34\3\34\7\34\u00e8\n\34\f\34"+ "\16\34\u00eb\13\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\5\34\u00f4\n\34"+ "\3\35\3\35\3\35\3\35\3\35\3\36\3\36\3\36\3\36\3\36\3\36\7\36\u0101\n\36"+ "\f\36\16\36\u0104\13\36\3\37\3\37\3\37\3\37\3\37\3\37\5\37\u010c\n\37"+ "\3 \3 \7 \u0110\n \f \16 \u0113\13 \3!\3!\3!\7!\u0118\n!\f!\16!\u011b"+ "\13!\3!\3!\3!\3!\5!\u0121\n!\3!\2\2\"\2\4\6\b\n\f\16\20\22\24\26\30\32"+ "\34\36 \"$&(*,.\60\62\64\668:<>@\2\4\3\2\n\17\3\2)*\2\u0122\2F\3\2\2\2"+ "\4I\3\2\2\2\6N\3\2\2\2\bW\3\2\2\2\n^\3\2\2\2\f`\3\2\2\2\16f\3\2\2\2\20"+ "n\3\2\2\2\22~\3\2\2\2\24\u0080\3\2\2\2\26\u0084\3\2\2\2\30\u0086\3\2\2"+ "\2\32\u0088\3\2\2\2\34\u008e\3\2\2\2\36\u0096\3\2\2\2 \u009c\3\2\2\2\""+ "\u00a0\3\2\2\2$\u00a4\3\2\2\2&\u00b1\3\2\2\2(\u00b5\3\2\2\2*\u00b8\3\2"+ "\2\2,\u00bb\3\2\2\2.\u00be\3\2\2\2\60\u00c0\3\2\2\2\62\u00c3\3\2\2\2\64"+ "\u00cd\3\2\2\2\66\u00f3\3\2\2\28\u00f5\3\2\2\2:\u00fa\3\2\2\2<\u010b\3"+ "\2\2\2>\u010d\3\2\2\2@\u0120\3\2\2\2BE\5\4\3\2CE\5&\24\2DB\3\2\2\2DC\3"+ "\2\2\2EH\3\2\2\2FD\3\2\2\2FG\3\2\2\2G\3\3\2\2\2HF\3\2\2\2IJ\5\6\4\2JK"+ "\7\3\2\2KL\5\b\5\2LM\7\4\2\2M\5\3\2\2\2NO\7(\2\2O\7\3\2\2\2PX\5\n\6\2"+ "QX\5\f\7\2RX\5\32\16\2SX\5\36\20\2TX\5 \21\2UX\5\"\22\2VX\5$\23\2WP\3"+ "\2\2\2WQ\3\2\2\2WR\3\2\2\2WS\3\2\2\2WT\3\2\2\2WU\3\2\2\2WV\3\2\2\2X\t"+ "\3\2\2\2Y_\5\6\4\2Z[\7\5\2\2[\\\5\b\5\2\\]\7\6\2\2]_\3\2\2\2^Y\3\2\2\2"+ "^Z\3\2\2\2_\13\3\2\2\2`a\7\7\2\2ab\7\5\2\2bc\5\16\b\2cd\7\6\2\2de\5\n"+ "\6\2e\r\3\2\2\2fk\5\20\t\2gh\7\b\2\2hj\5\20\t\2ig\3\2\2\2jm\3\2\2\2ki"+ "\3\2\2\2kl\3\2\2\2l\17\3\2\2\2mk\3\2\2\2ns\5\22\n\2op\7\t\2\2pr\5\22\n"+ "\2qo\3\2\2\2ru\3\2\2\2sq\3\2\2\2st\3\2\2\2t\21\3\2\2\2us\3\2\2\2vw\5\26"+ "\f\2wx\5\24\13\2xy\5\26\f\2y\177\3\2\2\2z{\7\5\2\2{|\5\16\b\2|}\7\6\2"+ "\2}\177\3\2\2\2~v\3\2\2\2~z\3\2\2\2\177\23\3\2\2\2\u0080\u0081\t\2\2\2"+ "\u0081\25\3\2\2\2\u0082\u0085\5\30\r\2\u0083\u0085\5@!\2\u0084\u0082\3"+ "\2\2\2\u0084\u0083\3\2\2\2\u0085\27\3\2\2\2\u0086\u0087\7(\2\2\u0087\31"+ "\3\2\2\2\u0088\u0089\7\20\2\2\u0089\u008a\7\5\2\2\u008a\u008b\5\34\17"+ "\2\u008b\u008c\7\6\2\2\u008c\u008d\5\n\6\2\u008d\33\3\2\2\2\u008e\u0093"+ "\5\30\r\2\u008f\u0090\7\21\2\2\u0090\u0092\5\30\r\2\u0091\u008f\3\2\2"+ "\2\u0092\u0095\3\2\2\2\u0093\u0091\3\2\2\2\u0093\u0094\3\2\2\2\u0094\35"+ "\3\2\2\2\u0095\u0093\3\2\2\2\u0096\u0097\7\22\2\2\u0097\u0098\7\5\2\2"+ "\u0098\u0099\5\34\17\2\u0099\u009a\7\6\2\2\u009a\u009b\5\n\6\2\u009b\37"+ "\3\2\2\2\u009c\u009d\5\n\6\2\u009d\u009e\7\23\2\2\u009e\u009f\5\n\6\2"+ "\u009f!\3\2\2\2\u00a0\u00a1\5\n\6\2\u00a1\u00a2\7\24\2\2\u00a2\u00a3\5"+ "\n\6\2\u00a3#\3\2\2\2\u00a4\u00a5\5\n\6\2\u00a5\u00a6\7\25\2\2\u00a6\u00a7"+ "\5\n\6\2\u00a7%\3\2\2\2\u00a8\u00b2\5,\27\2\u00a9\u00b2\5(\25\2\u00aa"+ "\u00b2\5*\26\2\u00ab\u00b2\5.\30\2\u00ac\u00b2\5\60\31\2\u00ad\u00b2\5"+ "\62\32\2\u00ae\u00b2\5\64\33\2\u00af\u00b2\5\66\34\2\u00b0\u00b2\58\35"+ "\2\u00b1\u00a8\3\2\2\2\u00b1\u00a9\3\2\2\2\u00b1\u00aa\3\2\2\2\u00b1\u00ab"+ "\3\2\2\2\u00b1\u00ac\3\2\2\2\u00b1\u00ad\3\2\2\2\u00b1\u00ae\3\2\2\2\u00b1"+ "\u00af\3\2\2\2\u00b1\u00b0\3\2\2\2\u00b2\u00b3\3\2\2\2\u00b3\u00b4\7\4"+ "\2\2\u00b4\'\3\2\2\2\u00b5\u00b6\7\26\2\2\u00b6\u00b7\5\6\4\2\u00b7)\3"+ "\2\2\2\u00b8\u00b9\7\27\2\2\u00b9\u00ba\5\6\4\2\u00ba+\3\2\2\2\u00bb\u00bc"+ "\7\30\2\2\u00bc\u00bd\5\6\4\2\u00bd-\3\2\2\2\u00be\u00bf\7\31\2\2\u00bf"+ "/\3\2\2\2\u00c0\u00c1\7\32\2\2\u00c1\u00c2\5\n\6\2\u00c2\61\3\2\2\2\u00c3"+ "\u00c4\7\33\2\2\u00c4\u00c5\5\6\4\2\u00c5\u00c6\7\5\2\2\u00c6\u00c7\5"+ ":\36\2\u00c7\u00c8\7\6\2\2\u00c8\u00c9\7\34\2\2\u00c9\u00ca\7\5\2\2\u00ca"+ "\u00cb\5\34\17\2\u00cb\u00cc\7\6\2\2\u00cc\63\3\2\2\2\u00cd\u00ce\7\35"+ "\2\2\u00ce\u00cf\5\6\4\2\u00cf\u00d0\7\36\2\2\u00d0\u00d1\5\30\r\2\u00d1"+ "\u00d2\7\37\2\2\u00d2\u00da\5@!\2\u00d3\u00d4\7\21\2\2\u00d4\u00d5\5\30"+ "\r\2\u00d5\u00d6\7\37\2\2\u00d6\u00d7\5@!\2\u00d7\u00d9\3\2\2\2\u00d8"+ "\u00d3\3\2\2\2\u00d9\u00dc\3\2\2\2\u00da\u00d8\3\2\2\2\u00da\u00db\3\2"+ "\2\2\u00db\u00dd\3\2\2\2\u00dc\u00da\3\2\2\2\u00dd\u00de\7 \2\2\u00de"+ "\u00df\5\16\b\2\u00df\65\3\2\2\2\u00e0\u00e1\7!\2\2\u00e1\u00e2\5\6\4"+ "\2\u00e2\u00e3\7\"\2\2\u00e3\u00e4\7\5\2\2\u00e4\u00e9\5@!\2\u00e5\u00e6"+ "\7\21\2\2\u00e6\u00e8\5@!\2\u00e7\u00e5\3\2\2\2\u00e8\u00eb\3\2\2\2\u00e9"+ "\u00e7\3\2\2\2\u00e9\u00ea\3\2\2\2\u00ea\u00ec\3\2\2\2\u00eb\u00e9\3\2"+ "\2\2\u00ec\u00ed\7\6\2\2\u00ed\u00f4\3\2\2\2\u00ee\u00ef\7!\2\2\u00ef"+ "\u00f0\5\6\4\2\u00f0\u00f1\7#\2\2\u00f1\u00f2\5\b\5\2\u00f2\u00f4\3\2"+ "\2\2\u00f3\u00e0\3\2\2\2\u00f3\u00ee\3\2\2\2\u00f4\67\3\2\2\2\u00f5\u00f6"+ "\7$\2\2\u00f6\u00f7\5\6\4\2\u00f7\u00f8\7 \2\2\u00f8\u00f9\5\16\b\2\u00f9"+ "9\3\2\2\2\u00fa\u00fb\5\30\r\2\u00fb\u0102\5<\37\2\u00fc\u00fd\7\21\2"+ "\2\u00fd\u00fe\5\30\r\2\u00fe\u00ff\5<\37\2\u00ff\u0101\3\2\2\2\u0100"+ "\u00fc\3\2\2\2\u0101\u0104\3\2\2\2\u0102\u0100\3\2\2\2\u0102\u0103\3\2"+ "\2\2\u0103;\3\2\2\2\u0104\u0102\3\2\2\2\u0105\u0106\7%\2\2\u0106\u0107"+ "\7\5\2\2\u0107\u0108\5> \2\u0108\u0109\7\6\2\2\u0109\u010c\3\2\2\2\u010a"+ "\u010c\7&\2\2\u010b\u0105\3\2\2\2\u010b\u010a\3\2\2\2\u010c=\3\2\2\2\u010d"+ "\u0111\7*\2\2\u010e\u0110\7*\2\2\u010f\u010e\3\2\2\2\u0110\u0113\3\2\2"+ "\2\u0111\u010f\3\2\2\2\u0111\u0112\3\2\2\2\u0112?\3\2\2\2\u0113\u0111"+ "\3\2\2\2\u0114\u0121\t\3\2\2\u0115\u0119\t\3\2\2\u0116\u0118\t\3\2\2\u0117"+ "\u0116\3\2\2\2\u0118\u011b\3\2\2\2\u0119\u0117\3\2\2\2\u0119\u011a\3\2"+ "\2\2\u011a\u0121\3\2\2\2\u011b\u0119\3\2\2\2\u011c\u011d\7\'\2\2\u011d"+ "\u011e\7(\2\2\u011e\u0121\7\'\2\2\u011f\u0121\7(\2\2\u0120\u0114\3\2\2"+ "\2\u0120\u0115\3\2\2\2\u0120\u011c\3\2\2\2\u0120\u011f\3\2\2\2\u0121A"+ "\3\2\2\2\24DFW^ks~\u0084\u0093\u00b1\u00da\u00e9\u00f3\u0102\u010b\u0111"+ "\u0119\u0120"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
Ruby
UTF-8
2,860
4.40625
4
[]
no_license
# PSEUDOCODE # write a method that takes a string as a parameter and creates # a fake name by swapping the first and last name # changing all the vowels to the next vowel # and changes each consonant to the next consonant in the alphabet # create method called name_generator # add parameter called (name) def name_generator(name) # use .downcase to make sure all letters are lowercase # reverse the name so last name appears first, join them back # together after they've been reversed name.downcase.split(' ').reverse.join(' ') end # p name_generator("Felicia Torres") def next_vowel(string) # create a vowels variable containing letters "aeiou" vowels = "aeiou" # create a hash with vowels and their next counterpart conversions = {"a" => "e", "e" => "i", "i" => "o", "o" => "u", "u" => "a"} # create a letter variable and set to string.SPLIT letters = string.split('') # create a new vowel variable and set it to an empty string new_vowel = "" # loop through the array of letters letters.each do |letter| # if the letter is a vowel, replace it with the next vowel # in the sequence if vowels.include?(letter) new_vowel += conversions[letter] else # if it's not a vowel, put it in the letter variable new_vowel += letter end end new_vowel end # puts next_vowel("abcdefiou") def next_consonant(string) consonants = "bcdfghjklmnpqrstvwxyz" consonant_conversions = { "b" => "c", "c" => "d", "d" => "f", "f" => "g", "g" => "h", "h" => "j", "j" => "k", "k" => "l", "l" => "m", "m" => "n", "n" => "p", "p" => "q", "q" => "r", "r" => "s", "s" => "t", "t" => "v", "v" => "w", "w" => "x", "x" => "y", "y" => "z", "z" => "b" } letters_cons = string.split('') new_consonant = "" letters_cons.each do |convert| if consonants.include?(convert) new_consonant += consonant_conversions[convert] else new_consonant += convert end end new_consonant end # puts next_consonant("bcdfghijz") def alias_creator(agent_name) # reverse the names so the last name appears first reversed_name = name_generator(agent_name) # make sure the vowels are concentrated and shifted to the next vowel vowel_switcher = next_vowel(reversed_name) # same with consonants using method above cons_switcher = next_consonant(vowel_switcher) # combine everything cons_switcher.split(' ').map { |name| name.capitalize }.join(' ') end p alias_creator("Felicia Torres") # USER INTERFACE fake_names = {} loop do puts "Welcome to the alias generator" puts "Please enter a name, type 'quit' when you are finished." spy_name = gets.chomp if spy_name == "quit" break end puts alias_creator(spy_name) fake_names[spy_name] = alias_creator(spy_name) end puts "Here are all of the spies and their names:" fake_names.each do |key, value| puts "#{key} => #{value}" end
Java
UTF-8
202
1.632813
2
[]
no_license
package com.nyd.application.api.call; import com.nyd.application.model.mongo.AddressBook; public interface AddressBookService { public void save(AddressBook addressBook) throws Exception; }
Python
UTF-8
10,668
2.640625
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 4 11:49:47 2019 @author: kenneth """ from __future__ import absolute_import import numpy as np from Utils.utils import EvalC from Utils.Loss import loss from Utils.kernels import Kernels class KLR(EvalC, loss, Kernels): def __init__(self, kernel = None, lamda = None): ''' Kernel Logistic Regression via Gradient Descent. [Solution 1] --------------------------------------------------------------------- :param: kernel: kernel for computing Gram matrix :param: lamda: regularization parameter Reference: http://dept.stat.lsa.umich.edu/~jizhu/pubs/Zhu-JCGS05.pdf ''' super().__init__() if not kernel: kernel = 'rbf' #default self.kernel = kernel else: self.kernel = kernel if not lamda: lamda = 1e-5 self.lamda = lamda else: self.lamda = lamda return def activation(self): ''' return binary array ''' return 1/(1+ np.exp(-self.knl.dot(self.alpha))) def kernelize(self, x1, x2): ''' :params: X: NxD ''' if self.kernel == 'linear': return Kernels.linear(x1, x2) elif self.kernel == 'rbf': return Kernels.rbf(x1, x2) elif self.kernel == 'sigmoid': return Kernels.sigmoid(x1, x2) elif self.kernel == 'polynomial': return Kernels.polynomial(x1, x2) elif self.kernel == 'cosine': return Kernels.cosine(x1, x2) elif self.kernel == 'correlation': return Kernels.correlation(x1, x2) elif self.kernel == 'linrbf': return Kernels.linrbf(x1, x2) elif self.kernel == 'rbfpoly': return Kernels.rbfpoly(x1, x2) elif self.kernel == 'rbfcosine': return Kernels.rbfpoly(x1, x2) elif self.kernel == 'etakernel': return Kernels.etakernel(x1, x2) elif self.kernel == 'alignment': return Kernels.alignment(x1, x2) elif self.kernel == 'laplace': return Kernels.laplacian(x1, x2) elif self.kernel == 'locguass': return Kernels.locguass(x1, x2) elif self.kernel == 'chi': return Kernels.chi(x1) def y_i(self, y): ''' :param: y: Nx1 ''' return np.outer(y, y) def alpha_y_i_kernel(self, X, y): ''' :params: X: NxD feature space :params: y: Dx1 dimension ''' alpha = np.random.randn(X.shape[0]) self.alph_s = np.outer(alpha, alpha) #alpha_i's alpha_j's self.y_i_s = self.y_i(y) #y_i's y_j's self.k = self.kernelize(X, X) return (alpha, self.alph_s, self.y_i_s, self.k) def cost(self): ''' return: cost loss as seen in paper 1/len(self.Y)*np.ones(self.X.shape[0]).T.dot(1 + np.exp(-self.knl.dot(self.Y))) ''' # return 1/len(self.Y)*np.ones(self.X.shape[0]).T.dot(1 + np.exp(-self.knl.dot(self.Y))) return self.Y.T.dot(np.dot(self.knl, self.alpha)) - np.sum(np.log(1 + np.exp(np.dot(self.knl, self.alpha)))) -\ .5*self.lamda*np.dot(self.alpha.T, np.dot(self.knl, self.alpha)) def fit(self, X, y, lr:float = None, iterations:int = None): ''' :param: X: NxD :param: y: Nx1 :return type: vector Nx1 ''' self.X = X self.Y = y if not lr: lr = 1e-2 self.lr = lr else: self.lr = lr if not iterations: iterations = 3 self.iterations = iterations else: self.iterations = iterations self.cost_rec = np.zeros(self.iterations) self.alpha, self.alpha_i_s, self.y_i_s, self.knl = self.alpha_y_i_kernel(X, y) for ii in range(self.iterations): self.cost_rec[ii] = self.cost() print(f"Cost of computation: {self.cost_rec[ii]}") #compute the gradient self.alpha = self.alpha - (self.knl.dot(self.Y)*(np.ones(self.X.shape[0]) - self.activation()) + self.lamda * np.dot(self.knl, self.alpha)) # self.alpha = self.alpha - self.knl.dot(self.Y - self.activation() - self.lamda*self.alpha) return self def predict(self, X): y_pred = np.array(np.sign(1/(1 + np.exp(-np.dot(self.Y * self.alpha, self.kernelize(self.X, X)))))) for enum, ii in enumerate(y_pred): if y_pred[enum] > 0: y_pred[enum] = 0 else: y_pred[enum] = 1 return y_pred class KLR_IRLS(EvalC, loss, Kernels): def __init__(self, kernel = None, lamda = None, epsilon = None): ''' Kernel Logistic Regression via Gradient Descent. [Solution 1] --------------------------------------------------------------------- :param: kernel: kernel for computing Gram matrix :param: lamda: regularization parameter Reference: http://dept.stat.lsa.umich.edu/~jizhu/pubs/Zhu-JCGS05.pdf ''' super().__init__() if not epsilon: epsilon = 0.001 self.epsilon = epsilon else: self.epsilon = epsilon if not kernel: kernel = 'rbf' #default self.kernel = kernel else: self.kernel = kernel if not lamda: lamda = 1e-5 self.lamda = lamda else: self.lamda = lamda return def activation(self): ''' :p(\alpha) return: probabilities ''' return 1/(1+ np.exp(-self.knl.dot(self.alpha))) def kernelize(self, x1, x2): ''' :params: X: NxD ''' if self.kernel == 'linear': return Kernels.linear(x1, x2) elif self.kernel == 'rbf': return Kernels.rbf(x1, x2) elif self.kernel == 'sigmoid': return Kernels.sigmoid(x1, x2) elif self.kernel == 'polynomial': return Kernels.polynomial(x1, x2) elif self.kernel == 'cosine': return Kernels.cosine(x1, x2) elif self.kernel == 'correlation': return Kernels.correlation(x1, x2) elif self.kernel == 'linrbf': return Kernels.linrbf(x1, x2) elif self.kernel == 'rbfpoly': return Kernels.rbfpoly(x1, x2) elif self.kernel == 'rbfcosine': return Kernels.rbfpoly(x1, x2) elif self.kernel == 'etakernel': return Kernels.etakernel(x1, x2) elif self.kernel == 'alignment': return Kernels.alignment(x1, x2) elif self.kernel == 'laplace': return Kernels.laplacian(x1, x2) elif self.kernel == 'locguass': return Kernels.locguass(x1, x2) elif self.kernel == 'chi': return Kernels.chi(x1) def y_i(self, y): ''' :param: y: Nx1 ''' return np.outer(y, y) def alpha_y_i_kernel(self, X, y): ''' :params: X: NxD feature space :params: y: Dx1 dimension ''' alpha = np.random.randn(X.shape[0]) self.alph_s = np.outer(alpha, alpha) #alpha_i's alpha_j's self.y_i_s = self.y_i(y) #y_i's y_j's self.k = self.kernelize(X, X) return (alpha, self.alph_s, self.y_i_s, self.k) def cost(self): ''' return: cost loss as seen in paper 1/len(self.Y)*np.ones(self.X.shape[0]).T.dot(1 + np.exp(-self.knl.dot(self.Y))) ''' # return 1/len(self.Y)*np.ones(self.X.shape[0]).T.dot(1 + np.exp(-self.knl.dot(self.Y))) return self.Y.T.dot(np.dot(self.knl, self.alpha)) - np.sum(np.log(1 + np.exp(np.dot(self.knl, self.alpha)))) -\ .5*self.lamda*np.dot(self.alpha.T, np.dot(self.knl, self.alpha)) def fit(self, X, y, lr:float = None, iterations:int = None): ''' :param: X: NxD :param: y: Nx1 :return type: vector Nx1 ''' self.X = X self.Y = y if not lr: lr = 1e-2 self.lr = lr else: self.lr = lr if not iterations: iterations = 5 self.iterations = iterations else: self.iterations = iterations self.cost_rec = np.zeros(self.iterations) self.alpha, self.alpha_i_s, self.y_i_s, self.knl = self.alpha_y_i_kernel(X, y) for ii in range(self.iterations): self.cost_rec[ii] = self.cost() if np.absolute(self.cost_rec[ii] - self.cost_rec[ii-1])/np.absolute(self.cost_rec[ii]) < self.epsilon: break else: # while np.absolute((self.cost_rec[ii] - self.cost_rec[ii - 1])/self.cost_rec[ii]) <= self.epsilon: print(f"Cost of computation: {self.cost_rec[ii]}") #compute using IRLS # self.W = np.outer(self.activation(), (1 - self.activation())) self.W = (self.activation()*(1 - self.activation()))*np.eye(X.shape[0]) self.z = self.knl.dot(self.alpha) + np.diagonal(np.linalg.pinv(self.W))*(self.Y - self.activation()) self.alpha = np.linalg.inv(self.knl.T.dot(self.knl.dot(self.W)) + self.lamda*self.knl).dot(self.knl.T.dot(self.W.dot(self.z))) return self def predict(self, X): y_pred = np.array(np.sign(1/(1 + np.exp(-np.dot(self.Y * self.alpha, self.kernelize(self.X, X)))))) for enum, ii in enumerate(y_pred): if y_pred[enum] > 0: y_pred[enum] = 1 else: y_pred[enum] = 0 return y_pred #%% Test import matplotlib.pyplot as plt from sklearn.datasets import make_blobs, make_moons from sklearn.model_selection import train_test_split X, y = make_moons(1000, noise = .03) X, y = make_blobs(n_samples=1000, centers=2, n_features=2) X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size = 0.3) klrmodel = KLR(kernel='rbf').fit(X_train, Y_train) klrmodel.predict(X_test) klrmodel.summary(Y_test, klrmodel.predict(X_test), klrmodel.alpha) plt.scatter(X_test[:, 0], X_test[:, 1], c = klrmodel.predict(X_test)) #%% klrmodel_irls = KLR_IRLS(kernel='rbf').fit(X_train, Y_train) klrmodel_irls.predict(X_test) klrmodel_irls.summary(Y_test, klrmodel_irls.predict(X_test), klrmodel_irls.alpha) plt.scatter(X_test[:, 0], X_test[:, 1], c = klrmodel_irls.predict(X_test))
PHP
UTF-8
8,726
2.78125
3
[]
no_license
<?php include 'connection.php'; //sender's id $id = $_GET['id']; //This query fetches the account number, name and balance of sender using their id $senderquery = " select account_number,name,balance from customers where id='$id' "; $query2 = mysqli_query($con,$senderquery); $res2 = mysqli_fetch_array($query2); $sender_accNo = $res2['account_number']; $sender_name=$res2['name']; $sender_amount = $res2['balance']; //Fetching all customers data(receivers name) and displaying it in drop down list except the sender's name $fetchquery = "SELECT * FROM customers where id!='$id'"; $query_run = mysqli_query($con,$fetchquery); if(isset($_POST['submit'])){ //Fetches the receiver name and amount from the form $receiver_name = $_POST['receiver']; $amount = $_POST['amount']; //This query fetches the account number and balance of receiver using their name $recievequery = " select account_number,balance from customers where name='$receiver_name' "; $query = mysqli_query($con,$recievequery); $res = mysqli_fetch_array($query); $receiver_accNo=$res['account_number']; $receiver_amount=$res['balance']; //Checking if the sender has sufficient balance to transfer money if((int)$amount > $sender_amount){ ?> <script> alert("You have insufficient balance"); </script> <?php } else{ //Add the amount to receiver balance $receiver_amount = $receiver_amount + (int)$amount; //Subtract the amount from sender's balance $sender_amount = $sender_amount - (int)$amount; //Update sender's and receiver's data with new balance $update_rece_query="UPDATE customers SET balance='$receiver_amount' WHERE account_number='$receiver_accNo'"; $update_send_query="UPDATE customers SET balance='$sender_amount' WHERE account_number='$sender_accNo'"; $run_query=mysqli_query($con,$update_rece_query); $run_query2=mysqli_query($con,$update_send_query); $amount_transfer = (int)$amount; //insert the transaction data to transaction table $INSERT = "INSERT INTO transaction(senderaccNo,senderName,receiveraccNo,receiverName,amount) VALUES('$sender_accNo','$sender_name','$receiver_accNo','$receiver_name','$amount_transfer')"; $check=mysqli_query($con,$INSERT); if($check){ ?> <script> alert("Transaction successful"); </script> <?php }else{ ?> <script> alert("Transaction failed"); </script> <?php } } } ?> <!DOCTYPE html> <html lang="en"> <head> <!-- Bootstrap and font awesome links --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <link rel="stylesheet" href="css/transferMoney_page.css" type="text/css"> </head> <body> <!-- Navbar --> <nav class="w3-bar"> <a class="navbar-brand" href="#" style="color:white">Banking System</a> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav" style="float:right; font-size:16px"> <li class="nav-item active" style="padding-right:6em"> <a class="nav-link" href="index.php" style="color: white">Home<span class="sr-only">(current)</span></a> </li> <li class="nav-item" style="padding-right:6em"> <a class="nav-link" href="view_customers.php" style="color:white">View all customers</a> </li> <li class="nav-item" style="padding-right:6em"> <a class="nav-link" href="transactionHistory.php" style="color:white">Transaction History</a> </li> </ul> </div> </nav> <div class="container"> <h1>Transfer money</h1> <div class="row"> <?php //Connect to a database and fetch particular customer data include 'connection.php'; $selectquery = " select * from customers where id='$id' "; $query = mysqli_query($con,$selectquery); $check_customer = mysqli_num_rows($query) > 0; if($check_customer){ while($row = mysqli_fetch_array($query)) { ?> <!-- Display the particular customer data in a card view --> <div class="col"> <div class="card"> <div class="card-body"> <p class="card-title">Sender's details</p> <img src="css/images/avatar.png"> <h5 id="name" name="name" class="card-title"><?php echo $row['name']; ?></h4> <h6 class="card-subtitle mb-2 text-muted">ID: <?php echo $row['id']; ?></h6> <h6 class="card-text">Account number: <?php echo $row['account_number']; ?></h6> <p class="card-text">Email id: <?php echo $row['email']; ?></p> <p class="card-text">Balance: <?php echo $row['balance']; ?></p> </div> </div> <?php } } else{ echo "No customer found"; } ?> </div> </div> <div class="form"> <!-- Form for taking receiver's name and amount to transfer as input --> <form method="POST"> <h2>Transfer Amount to</h2> <select name="receiver" id="receiver"> <option>Select Receiver...</option> <?php while($row=mysqli_fetch_array($query_run)){ $name=$row["name"]; echo "<option>$name</option>"; } ?> </select> <input type="text" id="amount" name="amount" placeholder="Amount"> <input type="submit" id="submit" name="submit" text="Submit" value="submit"> </form> </div> </div> <!-- Displaying the transaction details of particular customer --> <div class="main-div"> <h1>Your Transaction details</h1> <div class="table-wrapper"> <div class="fl-table"> <table> <thead> <tr> <th style="font-size: 20px">Transaction ID</th> <th style="font-size: 20px">Receiver Account Number</th> <th style="font-size: 20px">Receiver Name</th> <th style="font-size: 20px">Amount</th> </tr> </thead> <tbody> <?php include 'connection.php'; $transactionquery = "select * from transaction where senderaccNo='$sender_accNo' "; $run_query = mysqli_query($con,$transactionquery); while($row = mysqli_fetch_array($run_query)) { ?> <tr> <td class="id" style="font-size: 17px"><?php echo $row['id']; ?> </td> <td style="font-size: 17px"><?php echo $row['receiveraccNo']; ?> </td> <td style="font-size: 17px"><?php echo $row['receiverName']; ?> </td> <td style="font-size: 17px"><?php echo $row['amount']; ?> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </body> </html>
C#
UTF-8
939
2.8125
3
[]
no_license
// Serialization of an object - BLOB (Binary Large Object). The object should be // streamed to a text file. Show also the retrieval of the object from that file and // conversion back to its original form. using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Test; namespace BlobToSerialize { class Program { FileStream fs = File.Open(BlobToSerialize.img, FileMode.CreateNew, FileAccess.Write); } { static void Main(string[] args) { using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8)); } } } using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Test; namespace BlobToDeserialize { class Program { static void Main(string[] args) { using (StreamReader sr = new StreamReader(fs, System.Encoding.img)); } } }
Java
UTF-8
258
1.625
2
[]
no_license
package com.fossil.wearables.fsl.shared; public class PinType { public static final int TYPE_PIN_ADD = 1; public static final int TYPE_PIN_DELETE = 3; public static final int TYPE_PIN_EDIT = 2; public static final int TYPE_PIN_SYNCED = 0; }
Python
UTF-8
1,183
3.3125
3
[]
no_license
class Solution: def swimInWater(self, grid): """ :type grid: List[List[int]] :rtype: int """ def dfs_visit(x, y, visit, depth): if not (0 <= x < n) or not (0 <= y < n): return False if (x, y) in visit: return False if grid[x][y] > depth: return False if x == n-1 and y == n-1: return True visit.add((x, y)) for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)): if dfs_visit(x+dx, y+dy, visit, depth): return True return False def has_route(depth): return dfs_visit(0, 0, set(), depth) n = len(grid) lo, hi = 0, n*n-1 while lo < hi: mid = lo + (hi-lo)//2 if not has_route(mid): lo = mid+1 else: hi = mid return lo def test(grid, ans): r = Solution().swimInWater(grid) print(r == ans, r, ans) grid = [[0,2],[1,3]] test(grid, 3) grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]] test(grid, 16)
Python
UTF-8
1,832
2.515625
3
[ "MIT" ]
permissive
#!/usr/bin/env python import jinja2 import json import yaml import argparse import copy import os hostAction = False parser = argparse.ArgumentParser( description='Ansible inventory from jinja2 template') parser.add_argument('--list', dest='listAction', action='store_true', help='list all host groups') parser.add_argument('--host', dest='hostAction', action='store', help='list a particular host') args = parser.parse_args() templateLoader = jinja2.FileSystemLoader( searchpath=os.path.dirname(os.path.realpath(__file__))) templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "inventory_template.ini" template = templateEnv.get_template(TEMPLATE_FILE) # render template outputText = template.render(env=os.environ) # parse JSON inventoryData = yaml.load(outputText) listData = copy.deepcopy(inventoryData) hostData = {} for group in listData: # the JSON for --list is a shallower copy of the full # inventory JSON listData[group]['hosts'] = inventoryData[group]['hosts'].keys() # the _meta hostvars (which is also the basis for --host output) # is a concatenation of assigned hostvars for host in inventoryData[group]['hosts']: if host not in hostData: hostData[host] = {} for k in inventoryData[group]['hosts'][host]: hostData[host][k] = inventoryData[group]['hosts'][host][k] listData['_meta'] = {} listData['_meta']['hostvars'] = copy.deepcopy(hostData) if args.hostAction: print json.dumps(hostData[args.hostAction], sort_keys=True, indent=4, separators=(',', ': ')) else: print json.dumps(listData, sort_keys=True, indent=4, separators=(',', ': '))
Python
UTF-8
2,041
2.703125
3
[]
no_license
import json import csv import cv2 from rdkit.Chem import Draw from rdkit import Chem from tqdm import tqdm from utils import * from pqdm.processes import pqdm def write_smiles_and_imgs(smiles_dict_train, smiles_dict_val, smiles, idx): smiles_dict = None if idx >= 1980000: mode = 'val' idx -= 1980000 smiles_dict = smiles_dict_val else: mode = 'train' smiles_dict = smiles_dict_train smiles_dict[str(idx)] = smiles #print(f'smiles_dict_{mode} has {len(smiles_dict.keys())} terms.') img_path = base_path + f'/oscar_images/{mode}/{idx}.png' if not os.path.exists(img_path): mol = Chem.MolFromSmiles(smiles) Draw.MolToFile(mol, img_path) originalImage = cv2.imread(img_path) grayImage = cv2.cvtColor(originalImage, cv2.COLOR_BGR2GRAY) (thresh, blackAndWhiteImage) = cv2.threshold(grayImage, 127, 255, cv2.THRESH_BINARY) cv2.imwrite(img_path, blackAndWhiteImage) def write_imgs(img_name, smiles, mode): img_path = base_path + f'/oscar_images/{mode}/{img_name}' if not os.path.exists(img_path): mol = Chem.MolFromSmiles(smiles) Draw.MolToFile(mol, img_path) originalImage = cv2.imread(img_path) grayImage = cv2.cvtColor(originalImage, cv2.COLOR_BGR2GRAY) (thresh, blackAndWhiteImage) = cv2.threshold(grayImage, 127, 255, cv2.THRESH_BINARY) cv2.imwrite(img_path, blackAndWhiteImage) if __name__ == '__main__': base_path = '/ocean/projects/tra190016p/ylix/dacon' with open("smiles_json_30000.json", 'r') as fr: #cr = csv.reader(fr) #next(cr) #smiles_json_train, smiles_json_val = {}, {} smiles_dict = json.load(fr) params = [ [k, smiles_dict[k], 'test' ] for k in smiles_dict.keys()] pqdm(params, write_imgs, n_jobs=128, argument_type='args', desc=f'{color.BLUE}Creating SMILES and images for OSCAR.')
Markdown
UTF-8
602
2.53125
3
[]
no_license
# JS_30_challenge Based upon wesbo's [30-day JS challenge](https://javascript30.com/). His [repo](https://github.com/wesbos/JavaScript30) I downloaded his entire repo, removed all the solutions, then redid the directories to no longer have spaces. Removing solutions: ```shell rm */'index-FINISHED.html' ``` [Renaming stuff:](https://unix.stackexchange.com/questions/223182/how-to-replace-spaces-in-all-file-names-with-underscore-in-linux-using-shell-scr) ```shell find -name "* *" -print0 | sort -rz | \ while read -d $'\0' f; do mv -v "$f" "$(dirname "$f")/$(basename "${f// /_}")"; done ```
JavaScript
UTF-8
1,444
3.59375
4
[]
no_license
/** * Helper functions to deal with Date and time */ /** * @typedef {Object} TimeAgoResult * @property {number} type * @property {number} value */ /** * interval types */ export const interval = { Now: 0, Second: 1, Minute: 2, Hour: 3, Day: 4, Month: 5, Year: 6 }; /** * Returns interval type and value given two dates * * @param {Date} from - Date in the past * @param {Date} [to=new Date()] - Optional date in the future. Defaults to current date/time * @returns {TimeAgoResult} */ export function timeAgo(from, to = new Date()) { let timeDiff = Math.floor((to.getTime() - from.getTime()) / 1000); if (timeDiff === 0) { return { type: interval.Now, value: 0 }; } // seconds if (timeDiff < 60) { return { type: interval.Second, value: timeDiff }; } // minutes timeDiff = Math.floor(timeDiff / 60); if (timeDiff < 60) { return { type: interval.Minute, value: timeDiff }; } // hours timeDiff = Math.floor(timeDiff / 60); if (timeDiff < 24) { return { type: interval.Hour, value: timeDiff }; } // days timeDiff = Math.floor(timeDiff / 24); if (timeDiff < 30) { return { type: interval.Day, value: timeDiff }; } // months timeDiff = Math.floor(timeDiff / 30); if (timeDiff < 12) { return { type: interval.Month, value: timeDiff }; } // years timeDiff = Math.floor(timeDiff / 12); return { type: interval.Year, value: timeDiff }; }
Python
UTF-8
6,857
2.65625
3
[]
no_license
##################################################################### # Example : load, display and cycle the ** left or right only ** image from a # for a set of rectified stereo images from a directory structure # of left-images / right-images with filesname DATE_TIME_STAMP_{L|R}.png # optionally load available IMU/GPS ground truth data # basic illustrative python script for use with provided dataset # Author : Toby Breckon, toby.breckon@durham.ac.uk # Copyright (c) 2017 Department of Computer Science, # Durham University, UK # License : LGPL - http://www.gnu.org/licenses/lgpl.html ##################################################################### import cv2 import os import numpy as np import csv import gyro # local file gyro.py ##################################################################### # where is the data ? - set this to where you have it master_path_to_dataset = os.path.join(os.curdir, "TTBB-durham-02-10-17-sub5") directory_to_cycle = "left-images"; # edit this for left or right image set ##################################################################### # full camera parameters - from camera calibration # supplied images are stereo rectified camera_focal_length_px = 399.9745178222656; # focal length in pixels (fx, fy) camera_focal_length_m = 4.8 / 1000; # focal length in metres (4.8 mm, f) stereo_camera_baseline_m = 0.2090607502; # camera baseline in metres (B) camera_height_above_wheelbase_m = (1608.0 + 31.75 + 90) / 1000; # in mm optical_image_centre_h = 262.0; # from calibration - cy optical_image_centre_w = 474.5; # from calibration - cx image_height = 544; image_width = 1024; ##################################################################### # set this to a file timestamp to start from (empty is first example - outside lab) # e.g. set to 1506943191.487683 for the end of the Bailey, just as the vehicle turns skip_forward_file_pattern = ""; # set to timestamp to skip forward to pause_playback = False; # pause until key press after each image ##################################################################### # resolve full directory location of data set for images full_path_directory = os.path.join(master_path_to_dataset, directory_to_cycle); # open ground truth GPS / IMU data files if available gps_file_name = os.path.join(master_path_to_dataset, "GPS.csv"); imu_file_name = os.path.join(master_path_to_dataset, "IMU.csv"); gps_data = []; imu_data = []; if (os.path.isfile(gps_file_name)): with open(gps_file_name, newline='') as csvfileGPS: gps_data = list(csv.DictReader(csvfileGPS)); print("-- using GPS data file: " + gps_file_name); else: print("-- GPS data file not found: " + gps_file_name); if (os.path.isfile(imu_file_name)): with open(imu_file_name, newline='') as csvfileIMU: imu_data = list(csv.DictReader(csvfileIMU)); print("-- using IMU data file: " + imu_file_name); else: print("-- IMU data file not found: " + imu_file_name); # get a list of the files, sort them (by timestamp in filename) and iterate for index, filename in enumerate(sorted(os.listdir(full_path_directory))): # skip forward to start a file we specify by timestamp (if this is set) if ((len(skip_forward_file_pattern) > 0) and not(skip_forward_file_pattern in filename)): continue; elif ((len(skip_forward_file_pattern) > 0) and (skip_forward_file_pattern in filename)): skip_forward_file_pattern = ""; # from image filename get the correspondoning full path full_path_filename = os.path.join(full_path_directory, filename); # for sanity print out these filenames print(full_path_filename); # check the file is a PNG file (left) and check a correspondoning right image # actually exists if ('.png' in filename) and (os.path.isfile(full_path_filename)) : # read left and right images and display in windows # N.B. despite one being grayscale both are in fact stored as 3-channel # RGB images so load both as such img = cv2.imread(full_path_filename, cv2.IMREAD_COLOR) print("-- file loaded successfully"); print("\n"); ##################################################################### # *** do any processing here *** ##################################################################### # for now diplay GPS/IMU data on image if we have it if (len(gps_data) >= index): text = "GPS: lat.=%2f long.=%2f alt.=%2f"\ %(float(gps_data[index]['latitude']), float(gps_data[index]['longitude']), float(gps_data[index]['altitude'])); cv2.putText(img, text, (20,40), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,255), 1, 12) if (len(imu_data) >= index): roll, pitch, heading = gyro.gyro_to_angles( float(imu_data[index]['orientation_x']), float(imu_data[index]['orientation_y']), float(imu_data[index]['orientation_z']), float(imu_data[index]['orientation_w'])); text = "IMU: roll/pitch/heading. (%2f, %2f, %2f) "\ %(roll, pitch, heading); cv2.putText(img, text, (20,60), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,255), 1, 12) text = "IMU: angular velocity (%2f, %2f, %2f)"\ %(float(imu_data[index]['angular_velocity_x']), float(imu_data[index]['angular_velocity_y']), float(imu_data[index]['angular_velocity_z'])); cv2.putText(img, text, (20,80), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,255), 1, 12) text = "IMU: accel. (%2f, %2f, %2f)"\ %(float(imu_data[index]['linear_acceleration_x']), float(imu_data[index]['linear_acceleration_y']), float(imu_data[index]['linear_acceleration_z'])); cv2.putText(img, text, (20,100), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,255), 1, 12) # display the image cv2.imshow('input image',img); # keyboard input for exit (as standard), save disparity and cropping # exit - x # save - s # pause - space key = cv2.waitKey(100 * (not(pause_playback))) & 0xFF; # wait 40ms (i.e. 1000ms / 25 fps = 40 ms) if (key == ord('x')): # exit break; # exit elif (key == ord('s')): # save cv2.imwrite("input.png", img); elif (key == ord(' ')): # pause (on next frame) pause_playback = not(pause_playback); else: print("-- files skipped (perhaps one is missing or not PNG)"); print("\n"); # close all windows cv2.destroyAllWindows() #####################################################################
Python
UTF-8
254
2.84375
3
[]
no_license
from csv import reader,DictReader # with open("employee.csv")as f: # data_reader=reader(f) # for row in data_reader: # print(row) with open("employee.csv")as f: data_reader=DictReader(f) for row in data_reader: print(row)
Markdown
UTF-8
384
2.796875
3
[]
no_license
# Arduino-Digital-Hourglass Simple hourglass using tilt switch and Arduino. This project represent a digital hourglass that turns on an LED every ten minute. In the circuit is used tilt switch which helps the arduino to restart the hourglass **Arduino circuit of the project:** ![alt tag](https://github.com/KSamardzhiev/Arduino-Digital-Hourglass/blob/master/DigitalHourglass.png)
JavaScript
UTF-8
2,090
2.734375
3
[]
no_license
export const filterFun = (toFilter, property, query) => { if (query == "") return toFilter; return toFilter.filter((element) => { if (element.hasOwnProperty(property)) { if (Array.isArray(element[property])) return element[property].includes(query); return element[property] == query; } return true; }); }; export const onlyUnique = (value, index, self) => self.indexOf(value) === index; export function debounce(fn, delay) { var timeoutID = null; return function() { clearTimeout(timeoutID); var args = arguments; var that = this; timeoutID = setTimeout(function() { fn.apply(that, args); }, delay); }; } export const checkEmail = (email) => /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/.test( email ); export const checkName = (name) => /^[a-zA-ZÀ-ÿ\u00f1\u00d1]+(\s*[a-zA-ZÀ-ÿ\u00f1\u00d1]*)*[a-zA-ZÀ-ÿ\u00f1\u00d1]+$/.test( name ); export const cloudinaryImage = (url="",options=[]) =>{ if(!url) return ""; let[ partOne,parTwo] = url.split('upload/') let transformations = options.reduce((prev, act, index, array) => { let isLastElement = index == array.length - 1; let symbol = isLastElement ? "/":","; return prev + `${act}${symbol}`; },''); return `${partOne}upload/${transformations}${parTwo}`; } export const cloudinarySrcSet = (url) =>{ let sizes = [256,300,400,512,768,1024,1280,1600,1920]; let srcSet = sizes.reduce((prev, act) => { return prev + cloudinaryImage(url,['f_auto',`w_${act}`]) + ` ${act}w,`; },'') return srcSet; }
PHP
UTF-8
6,486
2.609375
3
[]
no_license
<?php error_reporting(0); session_start(); /*For Server --------------*/ $db_host = "localhost"; $db_user = "root"; $db_password = ""; $db = "lottery"; date_default_timezone_set('Asia/Manila'); $current_date = date('Y-m-d H:i:s'); $admin_url="http://localhost/JustGrab"; $client_url=""; $image_url="http://74.208.111.147/Lottery_UAT/uploads/"; $connect = mysql_connect($db_host,$db_user,$db_password) or die(mysql_error()); $GOOGLE_API_KEY="AIzaSyCSK4grIYFHXG-oTZnoRKOWnbBjTXhb5S0"; mysql_select_db($db,$connect) or die(mysql_error()); function secure($field,$type) { switch($type) { case 'get': $output = strip_tags(mysql_real_escape_string(filter_input(INPUT_GET, $field, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES))); break; case 'post': $output = strip_tags(mysql_real_escape_string(filter_input(INPUT_POST, $field, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES))); break; default: break; } return $output; } function UniqueRandomNumbersWithinRange_payment($min, $max, $quantity) { $numbers = range($min, $max); shuffle($numbers); return array_slice($numbers, 0, $quantity); } function randomstring() { $string=str_split('abcdefghijklmnopqrstuvwxyz'.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.'0123456789'); shuffle($string); $rand =''; foreach(array_rand($string,12) as $k) { $rand .=$string[$k]; } return $rand; } /** * Replace Space to "-" from String * */ function rpcspace($str) { $str=strtolower(str_replace(" ","-",$str)); return $str; } /** * Replace all special Character in string * */ function removespecialch($string) { $string = strtolower(str_replace(' ', '-', $string)); // Replaces all spaces with hyphens. $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars. return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one. } $key = "&/ASD%g/..&FWSF2csvsq2we!%%"; function my_number_decrypt($data, $key, $base64_safe=true, $expand=true) { if ($base64_safe) $data = base64_decode($data.'=='); $data = @mcrypt_encrypt(MCRYPT_ARCFOUR, $key, $data, MCRYPT_MODE_STREAM); if ($expand) $data = base_convert($data, 36, 10); return $data; } $a=""; function get_rambol6($number, $combinations = array( )) { if (empty($number)) { $GLOBALS['a'].=join('', $combinations) . ","; // echo join('', $combinations) . ","; //echo implode(',',$combinations); } else { // echo "<pre>"; // print_r($number); for ($i = count($number) - 1; $i >= 0; --$i) { $new_number = $number; $new_combinations = $combinations; list($foo) = array_splice($new_number, $i, 1); array_unshift($new_combinations, $foo); get_rambol6($new_number, $new_combinations); } } return rtrim($GLOBALS['a'],","); } function get_rambol3($number, $no_digit, $all_combination = array()) { if (empty($all_combination)) { $all_combination = $number; } if ($no_digit == 1) { return $all_combination; } $new_combinations = array(); foreach ($all_combination as $combination) { foreach ($number as $digit) { if( $number[0].$number[1].$number[2]==$combination.$digit || $number[0].$number[2].$number[1]==$combination.$digit || $number[1].$number[2].$number[0]==$combination.$digit || $number[1].$number[0].$number[2]==$combination.$digit || $number[2].$number[1].$number[0]==$combination.$digit || $number[2].$number[0].$number[1]==$combination.$digit || $number[0].$number[0].$number[0]==$combination.$digit || $number[1].$number[1].$number[1]==$combination.$digit || $number[2].$number[2].$number[2]==$combination.$digit ) { } else { } if(in_array($combination . $digit,$new_combinations)){} else { if ( $number[0].$number[1].$number[2]==$combination.$digit || $number[0].$number[2].$number[1]==$combination.$digit || $number[1].$number[2].$number[0]==$combination.$digit || $number[1].$number[0].$number[2]==$combination.$digit || $number[2].$number[1].$number[0]==$combination.$digit || $number[2].$number[0].$number[1]==$combination.$digit || $number[0].$number[0].$number[0]==$combination.$digit || $number[1].$number[1].$number[1]==$combination.$digit || $number[2].$number[2].$number[2]==$combination.$digit ){} else{ $new_combinations[] = $combination . $digit; } } } } return get_rambol3($number, $no_digit - 1, $new_combinations); } function CreateBet_Notification($registation_idsj,$message4) { //Google cloud messaging GCM-API url global $GOOGLE_API_KEY; $registation_ids = array(); $Notification_type=1; array_push($registation_ids,$registation_idsj); $respJson = '{"greetMsg":"'.$message4.'","Notification_type":"'.$Notification_type.'"}'; $message = array("m" => $respJson); $url = 'https://android.googleapis.com/gcm/send'; $fields = array( 'registration_ids' => $registation_ids, 'data' => $message, ); // Update your Google Cloud Messaging API Key if (!defined('GOOGLE_API_KEY')) { define("GOOGLE_API_KEY", $GOOGLE_API_KEY); } $headers = array( 'Authorization: key='.$GOOGLE_API_KEY, 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); $result = curl_exec($ch); //echo "--".$result; if ($result === FALSE) { // die('Curl failed: ' . curl_error($ch)); } curl_close($ch); // return $result; } //so anytime i need to sanitize something i simply type for example: //$username = secure("username", "post"); ?>
C#
UTF-8
980
2.953125
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AskTheCode.PathExploration.Heuristics { public sealed class FixedIntervalSmtHeuristic : SimpleSmtHeuristic { private readonly int interval; public FixedIntervalSmtHeuristic(int interval) { this.interval = interval; } public override bool DoSolve(ExplorationState state) { return state.Path.Depth % this.interval == 0; } } public class FixedIntervalSmtHeuristicFactory : IHeuristicFactory<FixedIntervalSmtHeuristic> { private readonly int interval; public FixedIntervalSmtHeuristicFactory(int interval) { this.interval = interval; } public FixedIntervalSmtHeuristic CreateHeuristic(Explorer explorer) { return new FixedIntervalSmtHeuristic(this.interval); } } }
Markdown
UTF-8
5,094
2.625
3
[]
no_license
[![Documentation Status](https://readthedocs.org/projects/tiva-ssd1306-driver/badge/?version=latest)](https://tiva-ssd1306-driver.readthedocs.io/en/latest/?badge=latest) # tiva_SSD1306_Driver Driver for the SSD1306 OLED controller for the TivaC. ## Features - Flexible font types(any font that has ttf convertible by website listed in the Font instruction) - Multiple simultaneuos fonts - Variable image size - Auxillary features like adjusting constrast, clear display, etc ## Design This a pretty simple driver, communication with the ssd1306 is detailed in the datasheet and most functions simply follow that. The font creator script was designed to be easy to use and require almost no work to integrate the result. ## Docs [Doxygen Docs for the Driver](https://tiva-ssd1306-driver.readthedocs.io/en/latest/) ## Directory Structure - src/: the src directory containing the driver source files - oled_font.h: files containing font struct definition that all created bitmaps will follow - ssd1306_info.h: containing configs, register maps and information about the ssd1306 - ssd1360_utils: header and source files for utilities functions used by the driver, mainly I2C functions for writing list/single item - ssd1306: the main driver containing function that user will directly uses - main.c: containing a small program serving as example or quick test of the display - create_new_font.py: scripts used for automating creation of new c array struct for a font type, need the file path of the raw c font file as first argument and font name as second command line argument, output two files in src/oled_font_font_name.h and src/oled_font_font_name.c - docs/: contain doxygen docs ## External Dependencies This project is a ccs project, setting up ccs is outside the scope of this README so consult TI documentation for that This driver uses the Tivaware support package from TI for the low level works so to run this you need to have this in the compile PATH ## Display Icon and Images Icon and Images are recommended to have black background and be mainly black and white, icons like this have a better chance of working well: ![Black Background Icons](image/2018-11-03-19-18-36.png) Credits: Icons made by Google from https://www.flaticon.com/ (a very good site to get black background icons) Making the dimension symmetric like 16x16 gives good results, this driver does support drawing partial image but it's recommended to pre-crop before inserting the bit map into the firmware ### How to print picture on screen Resize your picture if you need to, then go to this [site](http://javl.github.io/image2cpp/), depending on your picture, pick Horizontal or Vertical in the Output section(just do trial and error if you are not sure), copy the images in to a bitmap array and use it like this: ```c // in your c file static uint8_t testIcon[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // arrays obtained from the site above ssd1306PrintPic(testIcon, 0, 127, 0, 0); // print icons onscreen with given coordinate ``` ## Using Custom Fonts This driver comes with a python script called create_new_font.py that allows converting a c array bitmap to a struct that is used by the firmware The python script will take a raw c bitmap file and converts to struct used by firmware, the struct you will be interested in will be in the form of font_name_set, where font_name is supplied as the second argument of the python script and is declared in src/oled_font_font_name.h By default, the raw c font file has incosistent whitespace in them, the script will remove those whitespace as well as put the raw array into source files ready to be integrated into the firmware This repo comes with an example font called source_pro. Steps: 1. Get a ttf file from site like [this](https://fonts.google.com/) 2. Go [here](https://littlevgl.com/ttf-font-to-c-array) and convert the file to a c array file, set bpp to 1, other settings are up to you but monospace font tends to look better 3. With the downloaded c array file, launch the python script: ```python python3 create_new_font.py /home/your_name/Downloads/source_code_pro_oled.c font_name # provide raw bit map fiile path and font name ``` 4. The steps above will create two files, oled_font_font_name.h and oled_font_font_name.c, you need the struct named font_name_set(declared in oled_font_font_name.h) to use the write string function: ```c // main.c #include "oled_font_font_name.h" ssd1306PrintString("ABCDE14321L", 0, 0, font_name_set); ``` ## Credits And Reources Huge thanks to [Adafruit SSD1306 library](https://github.com/adafruit/Adafruit_SSD1306) for providing the detailed steps needed for initializing the ssd1306 as well as for the macro definitions [Image to C Array Converter](http://javl.github.io/image2cpp/) [Google Font](https://fonts.google.com/) [TTF to C Array Converter](https://littlevgl.com/ttf-font-to-c-array)
JavaScript
UTF-8
1,102
2.65625
3
[]
no_license
// const db = require('./models') const {db , Vegetable, Gardener, Plot} = require('./models') db.sync({force: true}) .then(() => { console.log('Database synced!') Vegetable.create({name : 'Carrot', color: 'Orange', planted_on: new Date(Date.now())}) Vegetable.create({name : 'Lettuce', color: 'Green', planted_on: new Date(Date.now())}) Vegetable.create({name : 'Broccoli', color: 'Green', planted_on: new Date(Date.now())}) Vegetable.create({name : 'Cauliflower', color: 'White', planted_on: new Date(Date.now())}) Vegetable.create({name : 'Corn', color: 'Yellow', planted_on: new Date(Date.now())}) .then ((vegetable) => { return Gardener.create({name : 'Dingo', age : 39, favoriteVegetableId : vegetable.id}) }) // db.close() // only if using a version of node without `finally` }) .catch(err => { console.log('Disaster! Something went wrong! ') console.log(err) // db.close() // only if using a version of node without `finally` }) // .finally(() => { // only if using a version of node WITH `finally` // db.close() // })
Python
UTF-8
164
4.15625
4
[]
no_license
def main(): n = int(input("Digite o número: ")) if n % 2 == 0: print("O número é par!") else: print("O número é ímpar!") main()
TypeScript
UTF-8
1,141
2.578125
3
[]
no_license
import { Injectable, Logger } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { IUser } from '../interfaces/user.interface'; import { User } from '../models/user.model'; @Injectable() export class UserRepository { private logger: Logger = new Logger('UserRepository'); constructor(@InjectModel('User') private userModel: Model<User>) {} async create(user: IUser): Promise<User> { try { const createdUser = new this.userModel(user); return await createdUser.save(); } catch (error) { this.logger.error(`Failed to create user ${error.message}`); throw error; } } async findByEmail(email: string): Promise<User> { try { return await this.userModel.findOne({ email }); } catch (error) { this.logger.error(`Failed to find user ${error.message}`); throw error; } } async findById(id: string): Promise<Partial<User>> { try { return await this.userModel.findOne({ id }); } catch (error) { this.logger.error(`Failed to find user ${error.message}`); throw error; } } }
PHP
UTF-8
1,027
3.015625
3
[ "MIT" ]
permissive
<?php namespace cwreden\requestLimiter; class Configuration { /** * @var int */ private $limit; /** * @var int */ private $limitAuthenticated; /** * @var int */ private $resetInterval; /** * Configuration constructor. * @param int $limit * @param int $limitAuthenticated * @param int $resetInterval */ public function __construct( $limit, $limitAuthenticated, $resetInterval ) { $this->limit = $limit; $this->limitAuthenticated = $limitAuthenticated; $this->resetInterval = $resetInterval; } /** * @return int */ public function getLimit(): int { return $this->limit; } /** * @return int */ public function getLimitAuthenticated(): int { return $this->limitAuthenticated; } /** * @return int */ public function getResetInterval(): int { return $this->resetInterval; } }
Markdown
UTF-8
2,233
2.625
3
[]
no_license
--- book: author: Annemarie Selinko cover_image_url: https://images-na.ssl-images-amazon.com/images/I/81FRzK3pj6L.jpg goodreads: '84049' isbn10: '8493388335' isbn13: '9788493388331' publication_year: '1951' spine_color: '#cf785d' tags: - german - historical-fiction title: Désirée plan: date_added: '2015-04-09' related_books: - book: stefan-zweig/joseph-fouche text: A literary, but less fictional biography of the big grey eminence of the time. - book: robert-graves/i-claudius text: Another old classic of historical fantasy, following a protagonist who, at least for the book's duration, is commentating big history from the sidelines. - book: alexandre-dumas/the-count-of-monte-cristo text: Another fictional account of Napoleon's France. review: date_read: - 2008-08-01 rating: 4 --- Désirée got me started on serious historical fiction – this, or [Klaus Kordon](/klaus-kordon/die-roten-matrosen/), but it's a close race. Désirée is the true tale of Désirée Clary, told in the form of her fictional diary. Why her? Because her life touches on larger-than-life history in many ways: Born as a wealthy silk merchant's daughter in Marseille in 1777 (not the best time for wealthy merchants in France), she got first-hand experience of the late days of the French revolution. Her sister and niece married into the Bonaparte family, while Désirée, who was engaged to you-know-who himself for a while, married Jean Baptiste Bernadotte, a general and Marshal of the Empire. Her husband, after handling boring everyday life matters like managing cities and contributing significantly to the victory at Austerlitz, was adopted by the Swedish king, and elected as his heir. He aligned Sweden with Napoleon's enemies, and planned and executed major parts of the decisive victory over Napoleon at Leipzig. He reigned as King of Sweden for twenty-six prosperous years. Désirée tells this convoluted story in a nuanced, well-researched collection of diary entries. If, at times, it seems like it gives in to name-dropping important historical figures, I can't complain because this vivid parade of people invoved in the fate of France taught me more (or at least more permanently) than my history teachers ever managed.
Java
UTF-8
1,032
2.265625
2
[]
no_license
package ru.workout.domainlayer.service; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import io.reactivex.Single; import io.reactivex.schedulers.Schedulers; import ru.workout.domainlayer.model.pojosforapi.ApiCar; import ru.workout.domainlayer.repository.ICarsRepository; public class CarsServiceImpl implements ICarsService { @Inject @Named(ICarsRepository.REMOTE) ICarsRepository mServerRepository; @Inject @Named(ICarsRepository.LOCAL) ICarsRepository mDbRepository; @Inject public CarsServiceImpl() { } @Override public Single<List<ApiCar>> getCars() { return mServerRepository.getCars().subscribeOn(Schedulers.io()) .doOnSuccess(response -> { mDbRepository.insertCars(response); }) .onErrorReturn(throwable -> mDbRepository.getCars().blockingGet()); } @Override public void insertCars(List<ApiCar> cars) { mDbRepository.insertCars(cars); } }
Python
UTF-8
3,031
3.5
4
[]
no_license
import time hg_score = 0 words = {'class' : '설계도' , 'instance' : 'A a = new A()', 'overriding' : '메소드 OOOOO'} def hangmanGame(): global life, unknown, user_input, checked_letter, hg_score message= ' JAVA 용어 맞추기 게임 ' print('='*((100-len(message))//2) + message + '='*((100-len(message))//2)) time.sleep(1.5) print('목숨이 사라지기 전에 무슨 단어인지 맞춰주세요!') time.sleep(1.5) print('알파벳 한 글자씩 추측해보세요. 답을 눈치챘다면 정답 바로 입력!') time.sleep(1.5) round = 0 for word in words: life = (len(word) // 2) + 1 unknown = ['_' for i in range(len(word))] checked_letter = [] # 성공 혹은 실패할때까지 글자추측 반복 while unknown.count('_') > 0 and life > 0: print('\n남은 목숨:', '♥ '*life) print(unknown, ' 힌트:', words[word]) user_input = input('>> ') validCheck(word) letterCheck(word) # 성공/실패 여부 확인 successCheck(word) round += 1 if success == True: hg_score += 10 else: break if round < len(words): print('다음 단계로 넘어갑니다.') time.sleep(1) print('게임이 끝났습니다:)\n( java 용어 맞추기 게임 총점수:',hg_score,')') time.sleep(2) def validCheck(word): global user_input, unknown, checked_letter if user_input.isalpha() and len(user_input) == 1 : if user_input in checked_letter: print('이미 입력한 글자입니다.') time.sleep(1) user_input = input('>> ') validCheck(word) else: if user_input != word: print('알파벳 소문자 1글자로 다시 입력해주세요^_^') time.sleep(1) user_input = input('>> ') validCheck(word) checked_letter.append(user_input) def letterCheck(word): global life, unknown, user_input if word == user_input: unknown = [] # 바로 성공 else: check = 0 for i in range(len(word)): if word[i] == user_input: unknown[i] = user_input check += 1 if check == 0: life -= 1 def successCheck(word): global success, life, unknown if unknown.count('_') == 0: print('정답입니다!') time.sleep(1.5) success = True elif life == 0: print('실패! 남은 목숨이 없습니다ㅠㅠ') time.sleep(1.5) print('정답은',word,'입니다.') time.sleep(2) success = False
Markdown
UTF-8
402
3.03125
3
[]
no_license
# eoslog Simple log formatter with standard (non-go) log levels ## Usage ```go import ( log "github.com/MeowWolf/eoslog" ) log.Trace.Printf("...") log.Debug.Printf("...") log.Info.Printf("...") log.Warn.Printf("...") log.Error.Printf("...") log.Critical.Printf("...") ``` The individual levels are just `Logger`s underneath so all the normal methods work, e.g. `Print`, `Printf`, `Println`, etc.
Go
UTF-8
1,910
2.765625
3
[]
no_license
package main import ( "bytes" "crypto/sha256" "encoding/gob" "encoding/hex" "fmt" "log" ) const subsidy = 10 // Transaction represents a transaction type Transaction struct { ID []byte Vin []TXInput Vout []TXOutput } // IsCoinbase checks whether the transaction is coinbase func (tx *Transaction) IsCoinbase() bool { return (len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].OutIndex == -1) } // SetHash sets the ID fields of the transaction func (tx *Transaction) SetHash() { var result bytes.Buffer var hash [32]byte encoder := gob.NewEncoder(&result) err := encoder.Encode(tx) if err != nil { log.Panicln(err) } hash = sha256.Sum256(result.Bytes()) tx.ID = hash[:] } // NewCoinbaseTX creates a new coinbase transaction func NewCoinbaseTX(to, msg string) *Transaction { if msg == "" { msg = fmt.Sprintf("Reward to '%s'", to) } //TODO: why not set to nil txin := TXInput{[]byte{}, -1, nil, []byte(msg)} txout := NewTXOutput(subsidy, to) tx := Transaction{nil, []TXInput{txin}, []TXOutput{*txout}} tx.SetHash() return &tx } // NewTransaction creates a new transaction func NewTransaction(from, to string, amt int, bc *Blockchain) *Transaction { var inputs []TXInput var outputs []TXOutput wallets := GetWallets() wallet := wallets.GetWallet(from) pubKeyHash := HashPubKey(wallet.PubKey) total, validOutputs := bc.FindSpendableOutputs(pubKeyHash, amt) if total < amt { log.Panicln("not enough balance") } for id, outs := range validOutputs { txID, err := hex.DecodeString(id) if err != nil { log.Panicln(err) } for _, idx := range outs { input := TXInput{txID, idx, nil, wallet.PubKey} inputs = append(inputs, input) } } outputs = append(outputs, *NewTXOutput(amt, to)) if total > amt { outputs = append(outputs, *NewTXOutput(total-amt, from)) } tx := Transaction{nil, inputs, outputs} tx.SetHash() return &tx }
Markdown
UTF-8
8,105
3.359375
3
[]
no_license
# Project 2-Stock Tutorial ## Team: [Shahid Hussain](https://github.com/shahidlashari), [Norberto Mantohac](https://github.com/NMantohac), [Narayan Poudel](https://github.com/naryan), [Ujwal Kashyap](https://github.com/usualketchup) ## URL Links 1) GitHub: https://github.com/shahidlashari/project_2_stockTutorial 2) Heroku: https://boiling-mesa-48982.herokuapp.com/ 3) Overall Function (Heroku): https://drive.google.com/file/d/1zHej-dCa_UZEOLRB9GcCynfTVeOVNj9I/view ## Description * The Stock Tutorial application provides the user a basic interactive and educational experience of the stock market trade through analyzing a variety of real-time stock data and emulating a stock portfolio. The app utilizes Alpha Vantage API to obtain specific data, such as stock time series, currency & foreign exchange rates, cryptoratings, and digital currencies traded on a specific market. The trending page provides these results in a form of either a chart or a simple text. In addition, there is error handling, so there will be no data returned if the user leaves the input form empty or inputs incorrect values. * For the Dashboard page, an alert will pop up if the user hasn't created an account (fake account) through the sign-up form. In the Sign-Up page, the user is able to create an account after providing a valid username, password, and email. Otherwise, there will be errors for each scenario (invalid username, invalid password and email, invalid username and email, etc.). Once the user is successful in creating an accouont, the app will then direct the user straight into the Dashboard page where the user can now save/buy/sell stocks. The stock search input returns the best-matching symbols and market information based on keywords, and from there the user can view stock prices and save them into the stock watchlist. In the stock watchlist, the user can buy (opening price) and sell (closing price) the saved stock, which would then reflect on the user's balance from the initial $10,000 budget. The user is free to logout from their account after pressing the logout button, but a new account must be created again in order to access the Dashboard page. * The Stock Tutorial application is done through React with React-Bootstrap Framework for the front-end, whereas Node.js and Express (server) with a MySQL database is done for the back-end. In addition, the general file structure follows the MVC paradigm to allow others an easy access of the work-flow of the files/folders. In the front-end, the use of functional and class components (containers) were used to render the pages, which also included states and vanilla JavaScript functions. Overall, the index.js Javascript files contain variables (const/let), async & await and callback functions, try/catch blocks, arrays/objects, import/exports, if-else statements, for-in loops, destructuring variables, local storage and queries. The necessary data in the local MySQL database are in the seed.sql file, which are for running initial queries. For npm packages, **axios** was used to make API calls to the Alpha Vantage API, and **Recharts** was used to display the data as a line chart with multiple lines (open, high, low, close) average prices of each month for the past year. In addition, **dotenv** was used to hide all the API keys and **mysql2** was to return all queries as promises. For dev dependencies, **ESLint** was to enforce a cleaner and better coding style, and **concurrently** was to run the localhost of the front and back-end at the same time. One last note, the entire app is mobile responsive and there are css with media queries, so the website looks good in smaller screens. ## User Story * The user wants to learn more details about stocks, but does not know where to start. The Stock Tutorial app gives the user a demonstration on how to buy and sell stocks based on their opening and closing prices for the day. * User needs to create an account first in order to access Dashboard, which their data will be stored in our database and local storage. * User can search for stock of their choice, but if the user doesn't know the symbol of the stock, the search bar has functionality to show the best matches stocks even if the user enters just one letter. * User can view the price of desired stock and save it. This particular stock will apear in the stock watchlist and will also be stored in our database, so the user can buy if they want to. * User is allocated $10,000.00 to start with and appears in the user's budget model. * User can sell stock by just clicking on the sell button and the budget will be updated accordingly. * User can logout after pressing logout button and will be redirected to home page. The user must create an account again in the sign-up form in order to access Dashboard again. * User can view trending page, which returns data (chart/text) of stock time series (monthly), currency exchange rate, foreign exchange rate (monthly), cryptorating, and digital currency in the physical market (monthly). ## Technologies * Visual Studio Code * React * React-Bootstrap Framework * Node.js * Express (Server) * MySQL Database (MySQL Workbench) * API - Alpha Vantage * npm - axios, if-env, dotenv, mysql2, and recharts * npm (Dev) - ESLint & concurrently * Travis CI/ESLint * GitHub * Heroku & JawsDB add-on ## Challenges * This project was definitely a lot tougher than we expected, and we experienced and learned many things, but in the end we were able to accomplish a lot of stuff for this project alone! The team is incredibly proud of how this project turned out because in the beginning it felt like a strange and relatively overwhelming idea, but over time we were able to solve each problem using our knowledge, resources, and help from each other and from the TAs/Instructor. This is an invaluable experience to us as junior web developers, and a solid testament of how much we've learned and are able to apply in code! * The main challenge early on was working with React since we didn't spend much time on it, so we had to refer back to the todo boilerplate and react class activities a lot in order to get a good picture of what we wanted to do. Using React definitely created a lot of early confusion with class/functional components and how they connected with states & props. Another challenge was dealing with our local MySQL database and using the correct queries that involved our API calls and the database itself. In the trending page, the early issue was deciding on a react chart (npm package) to display the data, and we had to go through 2 different ones (Canvas.js/chart and react-charts) before we decided on **Recharts**. Once this was decided, the main issue was actually displaying that data because it needed to be in a specific object format, so the information received from the API call had to be essentially converted into the chart format. A last minute issue was about React-Bootstrap and deploying it to Heroku, and it was regarding the replacement of href tags as Links from 'react-router-dom' and passing the to prop as well. * The members in the team learned a lot of different things, but it varies to each person in regards to what they worked on, what they learned and how they were able to solve each problem (either through trial & error, online resources, class videos, or help from each other and form the TAs/Instructor). * We were all able to solve each problem through continuous effort, good communication, everyday meetings, patience, time management, online resources, and help from the TAs/Instructor! ## Screenshot(s) * Stock Tutorial - Home Page: ![Stock Tutorial - Home Page:](https://puu.sh/FJOXn/10b37c3c6d.jpg) * Stock Tutorial - Trending Page (67% Zoomed Out): ![Stock Tutorial - Trending Page (67% Zoomed Out):](https://puu.sh/FJOYl/57ab0db046.png) * Stock Tutorial - Dashboard Page: ![Stock Tutorial - Dashboard Page:](https://puu.sh/FJP46/55c9964afe.png) * Stock Tutorial - Sign-Up Page: ![Stock Tutorial - Sign-Up Page:](https://puu.sh/FJP2D/e139f0790a.png)
Markdown
UTF-8
203
2.796875
3
[]
no_license
Write a program to find count of the most frequent item of an array. Assume that input is array of integers. Ex.: input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3] ouptut: key -1 occurs 5 times
Java
UTF-8
788
3.734375
4
[]
no_license
import java.util.Vector; public class FamilyTree { //using vectors so number of children can change String name; //Vector of family trees Vector<FamilyTree> children; FamilyTree parent; //constructor public FamilyTree(String name) { this.name = name; this.children = new Vector(); this.parent = null; } public FamilyTree addChild(FamilyTree child) { children.add(child); child.parent = this; return child; } public FamilyTree addChild(String name) { FamilyTree kid = new FamilyTree(name); return addChild(kid); } public void print(int level){ int spaces = level * 10; for (int ix = 0; ix < spaces; ix++){ System.out.print(" "); } System.out.println(this.name); for (FamilyTree kid : this.children){ kid.print(level + 1); } } }
Markdown
UTF-8
3,931
2.578125
3
[]
no_license
print("this website will give you informatio about a country of your choice") print("choose your country") print("make sure the country starts with a capital letter") input=input() if input=="Afghanistan": print("continent:asia capital:Kabul language:Dari population:31.11 million size:647,000 sq km main religion:islam") elif input=="Argentina": print("continent:South America capital:Argentina langauge:Spanish population:42.61 million size:2,740,000 sq km main religion:Christianity") elif input=="Australia": print("continent:Australia capital:Canberra langauge:english population:22.26 million size:7,750,000 sq km main religion:Christianity") elif input=="Belgium": print("continent:Europe capital:Brussels langauge:French population:10.47 million size:30,000 sq km main religion:Christianity") elif input=="Brazil": print("continent:South America capital:Brasilia langauge:portugese population:208.35 million size: 8,515,000 sq km main religion:christianity") elif input=="China": print("continent:Asia capital: Beijing langauge:Chinese population:1.4 billion size:9,596,000 sq km main religion:Chinese folk religion") elif input=="Denmark": print("continent:Europe capital:Copenhagen langauge:Danish population:5.74 million size:42,000 sq km main religion:Church of Denmark") elif input=="England": print("continent:Europe capital:London langauge:English population:55.26 million size:130,000 sq km main religion:Church of England") elif input=="France": print("continent:Europe capital:Paris langauge:French population:67.2 million size:640,000 sq km main religion:Christianity") elif input=="Greece": print("continent:Greece capital:Athens langauge:Greek population:11.18 million size:131,000 sq km main religion: Eastern Orthodoxy") elif input=="Germany": print("continent:Europe capital:Berlin langauge:German population: 82.34 million size: 357,000 sq km main religion:Christianity") elif input=="Italy": print("continent:Europe capital:Rome langauge:Italien population: 60.56 million size:301,000 sq km main religion:Christianity") elif input=="India": print("continent:Asia capital:New Delhi langauge:English population:1.34 billion size:3,287,000 sq km main religion:Hinduism") elif input=="Ireland": print("continent:Europe capital:Dublin langauge:English population:4.7 million size:70,000 sq km main religion:Christianity") elif input=="Japan": print("continent:Asia capital:Tokyo langauge:Japanese population:126.67 million size: 377,000 sq km main religion:Shinto") elif input=="South Korea": print("continent:Asia capital:Seoul langauge:Korean population:51.46 million size:100,000 sq km main religion:Christianity") elif input=="Mexico": print("continent:North America capital:Mexico city langauge:Spanish population: 123.67 million size:1,972,000 sq km main religion:Christianity") elif input=="Norway": print("continent:Europe capital:Oslo langauge:Norwegian population:5.26 million size:323,000 sq km main religion:") elif input=="": print("continent: capital: langauge: population: size: main religion:") elif input=="": print("continent: capital: langauge: population: size: main religion:") elif input=="": print("continent: capital: langauge: population: size: main religion:") elif input=="": print("continent: capital: langauge: population: size: main religion:")
Shell
UTF-8
838
3.390625
3
[]
no_license
#!/bin/bash -x declare -A Test count=0 valid=true read -p "enter the value for a" a read -p "enter the value for b" b read -p "enter the value for c" c Test[1]=$(( ($a + $b) * $c )) Test[2]=$(( ($a * $b) + $c )) Test[3]=$(( $c + ($a / $b) )) Test[4]=$(( ($a % $b) + $c )) while [ $valid ] do if [ $count -le 4 ] then Cases[((count++))]=${Test[$count]} else { break } fi done echo ${Cases[@]} echo "element in accending order are :" for (( i = 0; i < 4; i++ )) do for (( j=i; j < 4-i-1; i++ )) do echo $j echo ${Cases[$((j+1))]} if [ ${Cases[j]} -gt ${Cases[$((j+1))]} ] then temp=${Cases[$j]} Cases[$j]=${Cases[$((j+1))]} Cases[$((j+1))]=$temp fi done done echo ${Test[*]} echo "element in deccending order are :" for (( i = 4; i > 0; i-- )) do { echo ${Test[$i]} } done
C
UTF-8
662
3.03125
3
[]
no_license
#include <stdlib.h> #include <stdio.h> int comp(const void*a, const void*b) { return *(int*)a - *(int*)b; } int main() { int N, M; int coins[100000]; scanf("%d%d", &N, &M); for(int i=0; i<N; i++){ scanf("%d", &coins[i]); } qsort(coins, N, sizeof(int), comp); int i, j; for(i = 0, j=N-1; i < j; ){ int sum = coins[i] + coins[j]; if(sum == M){ printf("%d %d", coins[i], coins[j]); break; } else if(sum > M){ j--; } else{ i++; } } if(i >= j){ printf("No Solution"); } system("pause"); }
Python
UTF-8
82
3.8125
4
[]
no_license
num = int(input('Enter Numbers:- ')) for i in range(num): print(i, end=" ")
Java
UTF-8
3,731
2.09375
2
[]
no_license
package com.peeplotech.studygroup.lecturer; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.widget.TextView; import com.makeramen.roundedimageview.RoundedImageView; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; import com.peeplotech.studygroup.Profile; import com.peeplotech.studygroup.R; import com.peeplotech.studygroup.adapters.CourseAdapter; import com.peeplotech.studygroup.databases.Database; import com.peeplotech.studygroup.models.Course; import com.peeplotech.studygroup.models.User; import com.peeplotech.studygroup.util.Common; import io.paperdb.Paper; public class LecturerDashboard extends AppCompatActivity { //widgets private TextView greetUser, userId; private RoundedImageView userAvatar; private RecyclerView courseRecycler; private CardView addCourse; //data private CourseAdapter adapter; private List<Course> courseList = new ArrayList<>(); //values private User currentUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lecturer_dashboard); //value currentUser = Paper.book().read(Common.CURRENT_USER); //widgets greetUser = findViewById(R.id.greetUser); userId = findViewById(R.id.userId); userAvatar = findViewById(R.id.userAvatar); courseRecycler = findViewById(R.id.courseRecycler); addCourse = findViewById(R.id.addCourse); //init initialize(); } private void initialize() { //user profile initUserProfile(); //load courses loadCourses(); //add course addCourse.setOnClickListener(v -> { startActivity(new Intent(this, AddCourse.class)); overridePendingTransition(R.anim.slide_left, R.anim.slide_out_left); }); } private void initUserProfile() { //set data greetUser.setText("Welcome " + currentUser.getFirst_name()); userId.setText("@" + currentUser.getUser_id()); if (!TextUtils.isEmpty(currentUser.getUser_avatar())){ Picasso.get() .load(Uri.parse(currentUser.getUser_avatar())) .config(Bitmap.Config.RGB_565) .fit().centerCrop() .into(userAvatar); } //click greetUser.setOnClickListener(v -> openProfile()); userAvatar.setOnClickListener(v -> openProfile()); } private void openProfile(){ startActivity(new Intent(this, Profile.class)); overridePendingTransition(R.anim.slide_left, R.anim.slide_out_left); } @Override protected void onResume() { super.onResume(); currentUser = Paper.book().read(Common.CURRENT_USER); initUserProfile(); loadCourses(); } private void loadCourses() { //clear list courseList.clear(); //init recycler courseRecycler.setHasFixedSize(true); courseRecycler.setLayoutManager(new LinearLayoutManager(this)); //init list courseList = new Database(this).getAllCreatedCourses(currentUser.getUser_id()); //adapter adapter = new CourseAdapter(this, this, courseList); courseRecycler.setAdapter(adapter); adapter.notifyDataSetChanged(); } }
Java
UTF-8
9,007
2.4375
2
[]
no_license
/* * Copyright 2014 EUROPEAN DYNAMICS SA <info@eurodyn.com> * * Licensed under the EUPL, Version 1.1 only (the "License"). * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. */ package com.eurodyn.qlack2.fuse.cm.api; import com.eurodyn.qlack2.fuse.cm.api.dto.*; import com.eurodyn.qlack2.fuse.cm.api.exception.QFileNotFoundException; import com.eurodyn.qlack2.fuse.cm.api.exception.QNodeLockException; import java.util.List; import java.util.Map; public interface DocumentService { // ********************** // Folder functionalities // ********************** /** * Creates a new folder under a specific parent folder * * * @param folder * The FolderDTO of the folder to be created. * @param userId * The ID of the logged in user who is creating the folder. * @param lockToken * A lock token id, which will used to examine whether the user * is allowed to create a folder under the specific hierarchy * (check for locked ascendant). * @return The id of the newly created folder conflict * @throws QNodeLockException * If the folder/node cannot be created under the specific * hierarchy since an ascendant is already locked * */ String createFolder(FolderDTO folder, String userId, String lockToken) throws QNodeLockException; /** * Deletes a folder * * * @param folderID * The ID of the folder to be deleted. * @param lockToken * A lock token id, which will used to examine whether the user * is allowed to delete the folder under the specific hierarchy. * It checks for locked ascendant or if the folder has been locked by other user. * @throws QNodeLockException * If the folder/node cannot be deleted under the specific * hierarchy since an ascendant or the folder itself is already locked * @throws QFileNotFoundException * If the node to be deleted does not exist. */ void deleteFolder(String folderID, String lockToken) throws QNodeLockException, QFileNotFoundException; void renameFolder(String folderID, String newName, String userId, String lockToken) throws QNodeLockException, QFileNotFoundException; /** * Finds an return a folder with the specific ID along with is children * (optionally) * * * @param folderID * The ID of the folder to be retrieved. * @param lazyRelatives * When true it will not compute the relatives * (ancestors/descendats) of the required folder. * @param findPath * When true the directory path until the required folder will be * computed. * @return The FolderDTO which contains all the information about the folder. */ FolderDTO getFolderByID(String folderID, boolean lazyRelatives, boolean findPath); /** * Gets the content of a folder node in a zip file. This method retrieves * the binary contents of all files included in the folder node specified as * well as their attributes if the includeAttributes argument is true. The * contents of files included in other folders contained by the folder * specified are also retrieved in case the isDeep argument is true. * * @param folderID * The ID of the folder the content of which is to be retrieved * @param includeProperties * If true then a separate properties file will be created inside * the final zip file for each node included in the result, * containing the nodes' properties in the form: propertyName = * propertyValue * @param isDeep * If true then the whole tree commencing by the specified folder * will be traversed in order to be included in the final result. * Otherwise only the file nodes which are direct children of the * specified folder will be included in the result. * @return The binary content (and properties if applicable) of the * specified folder as a byte array representing a zip file. */ byte[] getFolderAsZip(String folderID, boolean includeProperties, boolean isDeep); // ********************** // File functionalities // ********************** String createFile(FileDTO file, String userID, String lockToken) throws QNodeLockException; /** * Deletes a file * * * @param fileID * The ID of the file to be deleted. * @param lockToken * A lock token id, which will used to examine whether the user * is allowed to delete the file, under the specific hierarchy. * It checks for locked ascendant or if the file itself has been locked by other user. * @throws QNodeLockException * If the node cannot be deleted under the specific * hierarchy since an ascendant or the folder itself is already locked * @throws QFileNotFoundException * If the node to be deleted does not exist. */ void deleteFile(String fileID, String lockToken) throws QNodeLockException, QFileNotFoundException; void renameFile(String fileID, String newName, String userID, String lockToken) throws QNodeLockException, QFileNotFoundException; /** * Finds an return a file with the specific ID along with its versions * (optionally) * * * @param fileID * The ID of the folder to be retrieved. * @param findPath * When true the directory path until the required folder will be * computed. * @return The FileDTO which contains all the information about the required file */ FileDTO getFileByID(String fileID, boolean includeVersions, boolean findPath); // ********************** // Common functionalities // ********************** NodeDTO getNodeByID(String nodeID); FolderDTO getParent(String nodeID, boolean lazyRelatives); List<FolderDTO> getAncestors(String nodeID); String createAttribute(String nodeId, String attributeName, String attributeValue, String userId, String lockToken) throws QNodeLockException, QFileNotFoundException; void updateAttribute(String nodeID, String attributeName, String attributeValue, String userID, String lockToken) throws QNodeLockException, QFileNotFoundException; void updateAttributes(String nodeID, Map<String, String> attributes, String userID, String lockToken) throws QNodeLockException; void deleteAttribute(String nodeID, String attributeName, String userID, String lockToken) throws QNodeLockException, QFileNotFoundException; String copy(String nodeID, String newParentID, String userID, String lockToken); void move(String nodeID, String newParentID, String userID, String lockToken); /** * Checks whether a file or folder with the same name, already exists in a * specified directory * * @param name * The name of the new file which should be checked to find out * if a duplicate name exists * @param parentNodeID * The ID of the folder within which a file is a specified name * is searched * * @return true if the specified file name is unique in the folder. */ boolean isFileNameUnique(String name, String parentNodeID); /** * Checks whether the folder or file names are unique in the specified * directory and returns a lists on the duplicate * * @param fileNames * The file names which will be checked id it is unique in a * provided directory. * @param parentId * The id of the parent folder within which duplicate file and * folder names are searched. * * @return a lists on the duplicates. */ List<String> duplicateFileNamesInDirectory(List<String> fileNames, String parentId); /** * Creates a new file as well as a new version for the specific file * * @param cmFile * The FileDTO which contain all the new file information * @param cmVersion * The new version. * @param content * The binary content of the new version. It is optional, so null can be used instead. * @param userID * The user ID of the creator. * @param lockToken * The lock token to be used so as to avoid lock conflicts. * * @return CreateFileAndVersionStatusDTO which contains the ids of the newly * created file and version. */ CreateFileAndVersionStatusDTO createFileAndVersion(FileDTO cmFile, VersionDTO cmVersion, byte[] content, String userID, String lockToken); }
Java
UTF-8
4,411
2.359375
2
[]
no_license
package com.twotowerstudios.virtualnotebookdesign.PageActivityMain; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.support.v7.widget.Toolbar; import android.text.method.ScrollingMovementMethod; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.EditText; import com.twotowerstudios.virtualnotebookdesign.Objects.Page; import com.twotowerstudios.virtualnotebookdesign.R; import org.parceler.Parcels; public class NewPageChildFragment extends DialogFragment { private OnFragmentInteractionListener mListener; char type; Page page; public NewPageChildFragment() { // Required empty public constructor } public static NewPageChildFragment newInstance(char type, Page page) { NewPageChildFragment fragment = new NewPageChildFragment(); Bundle args = new Bundle(); args.putChar("type", type); args.putParcelable("page", Parcels.wrap(page)); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { type = getArguments().getChar("type"); page = Parcels.unwrap(getArguments().getParcelable("page")); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment if(type == 't'){ return inflater.inflate(R.layout.fragment_new_page_child_text, container, false); }/*else if(type == 'i'){ return inflater.inflate(R.layout.fragment_new_page_child_image, container, false); }else if(type == 'd'){ return inflater.inflate(R.layout.fragment_new_page_child_drive, container, false); }*/else{return inflater.inflate(R.layout.fragment_new_page_child_text, container, false);} } @Override public void onViewCreated(View v, @Nullable Bundle savedInstanceState) { if (type=='t') { Toolbar tbNewpagechild = (Toolbar) v.findViewById(R.id.tbNewpagechild); final EditText etTitlePageChild = (EditText) v.findViewById(R.id.etTitlePageChild); final EditText etBodyPageChild = (EditText) v.findViewById(R.id.etBodyPageChild); etTitlePageChild.setMovementMethod(new ScrollingMovementMethod()); tbNewpagechild.inflateMenu(R.menu.newpage); tbNewpagechild.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.action_newpage: mListener.returnTextChildInfo(etTitlePageChild.getText().toString(), etBodyPageChild.getText().toString()); dismiss(); break; }return false; } }); }else{ } } @Override public void onResume() { super.onResume(); DisplayMetrics displaymetrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int height = displaymetrics.heightPixels; int width = displaymetrics.widthPixels; WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(getDialog().getWindow().getAttributes()); lp.width = (int)(width*0.9); lp.height = WindowManager.LayoutParams.WRAP_CONTENT; getDialog().getWindow().setAttributes(lp); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragmentInteractionListener { void returnTextChildInfo(String title, String text); } }
Python
UTF-8
1,705
3.09375
3
[]
no_license
""" Simple shakedown of grammar.py features, one by one. """ import nose import logging logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.WARNING) log = logging.getLogger(__name__) ## Ridiculous path hack so that this can work both within and ## outside of nosetests, locally and from the main project folder. ## import sys import os sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from makogram import grammar ## With Mako templates only def test_string_template(): """One rhs consisting only of a string""" pattern = "this is a test" g = grammar.Grammar() g.prod("S", pattern) result = g.gen("S") assert result == pattern def test_mako_sub(): g = grammar.Grammar() g.prod("S", "testing ${p2()} testing") g.prod("p2", "passing") result = g.gen("S") assert result == "testing passing testing" return result def test_mako_choice(): g = grammar.Grammar() g.prod("S", "testing ${p2()}") g.prod("p2", "A") g.prod("p2", "B") g.prod("p2", "C") result = g.gen("S") assert result in ["testing A", "testing B", "testing C"] ## With procedures def foo(): return "FOO" def test_mixed_choice(): g = grammar.Grammar() g.prod("S", foo) g.prod("S", "bar") has_foo = False has_bar = False for _ in range( 1000 ): s = g.gen("S") assert s=="FOO" or s=="bar" if s == "FOO": has_foo = True if s == "bar": has_bar = True if has_foo and has_bar: return assert False, "Didn't try both choices" if __name__ == "__main__": print(test_mako_sub()) #nose.runmodule()
Python
UTF-8
29,921
3.453125
3
[]
no_license
from random import randint from time import sleep print "Choose your Pokemon:" print "Grass Type:" print "1. Bulbasaur 2. Chikorita 3. Victreebel" print "Flying Type:" print "4. Spearow 5. Butterfree 6. Pidgeotto" print "Ground Type:" print "7. Onix 8. Sandshrew 9. Geodude" print "Ghost Type:" print "10. Haunter 11. Dusknoir 12. Sableye" print "Nomral Type:" print "13. Rattata 14. Eevee 15. Snorlax" print "Fire Type:" print "16. Charmander 17. Arcanine 18. Torchic" print "Water Type:" print "19. Squirtle 20. Poliwag 21. Goldeen" choice = input("Enter the number associated with the Pokemon you like to choose... ") choice2 = randint(1,21) def switch_human(choice): switcher = { 1: "You chose Bulbasaur", 2: "You chose Chikorita", 3: "You chose Victreebel", 4: "You chose Spearow", 5: "You chose Butterfree", 6: "You chose Pidgeotto", 7: "You chose Onix", 8: "You chose Sandshrew", 9: "You chose Geodude", 10: "You chose Haunter", 11: "You chose Dusknoir", 12: "You chose Sableye", 13: "You chose Rattata", 14: "You chose Eevee", 15: "You chose Snorlax", 16: "You chose Charmander", 17: "You chose Arcanine", 18: "You chose Torchic", 19: "You chose Squirtle", 20: "You chose Poliwag", 21: "You chose Goldeen", } return switcher.get(choice) def switch_computer(choice2): switcher = { 1: "AI chose Bulbasaur", 2: "AI chose Chikorita", 3: "AI chose Victreebel", 4: "AI chose Spearow", 5: "AI chose Butterfree", 6: "AI chose Pidgeotto", 7: "AI chose Onix", 8: "AI chose Sandshrew", 9: "AI chose Geodude", 10: "AI chose haunter", 11: "AI chose Dusknoir", 12: "AI chose Sableye", 13: "AI chose Rattata", 14: "AI chose Eevee", 15: "AI chose Snorlax", 16: "AI chose Charmander", 17: "AI chose Arcanine", 18: "AI chose Torchic", 19: "AI chose Squirtle", 20: "AI chose Poliwag", 21: "AI chose Goldeen" } return switcher.get(choice2) print switch_human(choice) print switch_computer(choice2) Player_HP = 1200 Opponent_HP = 1200 Pmove1 = 10 Pmove2 = 5 Pmove3 = 2 Omove1 = 10 Omove2 = 5 Omove3 = 2 def grass_moves_human(choice2,move1,move2,move3,HP): print "1. Leaf Blade", move1 print "2. Bullet Seed", move2 print "3. Frenzy Plant", move3 move_number = input("Enter move number... ") if move1 == 0: if move_number == 1: print "Leaf Blade Unavailable" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "Bullet Seed Unavailable" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "Frenzy Plant Unavailable" return move1,move2,move3,HP if choice2 in range(7,10) or choice2 in range(19,22): if move_number == 1: print "You used Leaf Blade" move1 -= 1 HP -= randint(0, 250) elif move_number == 2: print "You used Bullet Seed" move2 -= 1 HP -= randint(0, 500) elif move_number == 3: print "You used Frenzy Plant" move3 -= 1 HP -= randint(0, 550) elif choice2 in range(4,7) or choice2 in range(16,19) or choice2 in range(1,4): if move_number == 1: print "You used Leaf Blade" move1 -= 1 HP -= randint(0, 50) elif move_number == 2: print "You used Bullet Seed" move2 -= 1 HP -= randint(0, 50) elif move_number == 3: print "You used Frenzy Plant" move3 -= 1 HP -= randint(0, 50) else: if move_number == 1: print "You used Leaf Blade" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "You used Bullet Seed" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "You used Frenzy Plant" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def flying_moves_human(choice2,move1,move2,move3,HP): print "1. Air Cutter", move1 print "2. Aeroblast", move2 print "3. Dragon Ascent", move3 move_number = input("Enter move number... ") if move1 == 0: if move_number == 1: print "Air Cutter Unavailable" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "Aeroblast Unavailable" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "Dragon Ascent Unavailable" return move1,move2,move3,HP if choice2 in range(1,4): if move_number == 1: print "You used Air Cutter" move1 -= 1 HP -= randint(0, 250) elif move_number == 2: print "You used Aeroblast" move2 -= 1 HP -= randint(0, 500) elif move_number == 3: print "You used Dragon Ascent" move3 -= 1 HP -= randint(0, 550) else: if move_number == 1: print "You used Air Cutter" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "You used Aeroblast" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "You used Dragon Ascent" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def ground_moves_human(choice2,move1,move2,move3,HP): print "1. Bone Rush", move1 print "2. Drill Run", move2 print "3. Precipice Blades", move3 move_number = input("Enter move number... ") if move1 == 0: if move_number == 1: print "Bone Rush Unavailable" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "Drill Run Unavailable" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "Precipice Blades Unavailable" return move1,move2,move3,HP if choice2 in range(16,19): if move_number == 1: print "You used Bone Rush" move1 -= 1 HP -= randint(0, 250) elif move_number == 2: print "You used Drill Run" move2 -= 1 HP -= randint(0, 500) elif move_number == 3: print "You used Precipice Blades" move3 -= 1 HP -= randint(0, 550) elif choice2 in range(1,7): if move_number == 1: print "You used Bone Rush" move1 -= 1 HP -= randint(0, 50) elif move_number == 2: print "You used Drill Run" move2 -= 1 HP -= randint(0, 50) elif move_number == 3: print "You used Precipice Blades" move3 -= 1 HP -= randint(0, 50) else: if move_number == 1: print "You used Bone Rush" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "You used Drill Run" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "You used Precipice Blades" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def ghost_moves_human(choice2,move1,move2,move3,HP): print "1. Astonish", move1 print "2. Ominous Wind", move2 print "3. Shadow Force", move3 move_number = input("Enter move number... ") if move1 == 0: if move_number == 1: print "Astonish Unavailable" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "Ominous Wind Unavailable" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "Shadow Force Unavailable" return move1,move2,move3,HP if choice2 in range(10,13): if move_number == 1: print "You used Astonish" move1 -= 1 HP -= randint(0, 250) elif move_number == 2: print "You used Ominous Wind" move2 -= 1 HP -= randint(0, 500) elif move_number == 3: print "You used Shadow Force" move3 -= 1 HP -= randint(0, 550) elif choice2 in range(13,16): if move_number == 1: print "You used Astonish" move1 -= 1 HP -= randint(0, 50) elif move_number == 2: print "You used Ominous Wind" move2 -= 1 HP -= randint(0, 50) elif move_number == 3: print "You used Shadow Force" move3 -= 1 HP -= randint(0, 50) else: if move_number == 1: print "You used Astonish" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "You used Ominous Wind" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "You used Shadow Force" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def normal_moves_human(choice2,move1,move2,move3,HP): print "1. Double Hit", move1 print "2. Crush Claw", move2 print "3. Boomburst", move3 move_number = input("Enter move number... ") if move1 == 0: if move_number == 1: print "Double Hit Unavailable" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "Crush Claw Unavailable" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "Boomburst Unavailable" return move1,move2,move3,HP if choice2 in range(10,14): if move_number == 1: print "You used Double Hit" move1 -= 1 HP -= randint(0, 50) elif move_number == 2: print "You used Crush Claw" move2 -= 1 HP -= randint(0, 50) elif move_number == 3: print "You used Boomburst" move3 -= 1 HP -= randint(0, 50) else: if move_number == 1: print "You used Double Hit" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "You used Crush Claw" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "You used Boomburst" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def fire_moves_human(choice2,move1,move2,move3,HP): print "1. Ember", move1 print "2. Fire Pledge", move2 print "3. Flare Blitz", move3 move_number = input("Enter move number... ") if move1 == 0: if move_number == 1: print "Ember Unavailable" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "Fire Pledge Unavailable" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "Flare Blitz Unavailable" return move1,move2,move3,HP if choice2 in range(10,13): if move_number == 1: print "You used Ember" move1 -= 1 HP -= randint(0, 250) elif move_number == 2: print "You used Fire Pledge" move2 -= 1 HP -= randint(0, 500) elif move_number == 3: print "You used Flare Blitz" move3 -= 1 HP -= randint(0, 550) elif choice2 in range(13,16): if move_number == 1: print "You used Ember" move1 -= 1 HP -= randint(0, 50) elif move_number == 2: print "You used Fire Pledge" move2 -= 1 HP -= randint(0, 50) elif move_number == 3: print "You used Flare Blitz" move3 -= 1 HP -= randint(0, 50) else: if move_number == 1: print "You used Ember" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "You used Fire Pledge" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "You used Flare Blitz" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def water_moves_human(choice2,move1,move2,move3,HP): print "1. Aqua Jet", move1 print "2. Bubble Beam", move2 print "3. Hydro Cannon", move3 move_number = input("Enter move number... ") if move1 == 0: if move_number == 1: print "Aqua Jet Unavailable" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "Bubble Beam Unavailable" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "Hydro Cannon Unavailable" return move1,move2,move3,HP if choice2 in range(7,10) or choice2 in range(16,19): if move_number == 1: print "You used Aqua Jet" move1 -= 1 HP -= randint(0, 250) elif move_number == 2: print "You used Bubble Beam" move2 -= 1 HP -= randint(0, 500) elif move_number == 3: print "You used Hydro Cannon" move3 -= 1 HP -= randint(0, 550) elif choice2 in range(13,16): if move_number == 1: print "You used Aqua Jet" move1 -= 1 HP -= randint(0, 50) elif move_number == 2: print "You used Bubble Beam" move2 -= 1 HP -= randint(0, 50) elif move_number == 3: print "You used Hydro Cannon" move3 -= 1 HP -= randint(0, 50) else: if move_number == 1: print "You used Aqua Jet" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "You used Bubble Beam" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "You used Hydro Cannon" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def grass_moves_ai(choice2, move1, move2, move3, HP): print "1. Leaf Blade", move1 print "2. Bullet Seed", move2 print "3. Frenzy Plant", move3 move_number = randint(1,3) if move1 == 0: if move_number == 1: print "AI Missed!" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "AI Missed!" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "AI Missed!" return move1,move2,move3,HP if choice2 in range(7, 10) or choice2 in range(19, 22): if move_number == 1: print "AI used Leaf Blade" move1 -= 1 HP -= randint(0, 250) elif move_number == 2: print "AI used Bullet Seed" move2 -= 1 HP -= randint(0, 500) elif move_number == 3: print "AI used Frenzy Plant" move3 -= 1 HP -= randint(0, 550) elif choice2 in range(4, 7) or choice2 in range(16, 19) or choice2 in range(1, 4): if move_number == 1: print "AI used Leaf Blade" move1 -= 1 HP -= randint(0, 50) elif move_number == 2: print "AI used Bullet Seed" move2 -= 1 HP -= randint(0, 50) elif move_number == 3: print "AI used Frenzy Plant" move3 -= 1 HP -= randint(0, 50) else: if move_number == 1: print "AI used Leaf Blade" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "AI used Bullet Seed" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "AI used Frenzy Plant" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def flying_moves_ai(choice2, move1, move2, move3, HP): print "1. Air Cutter", move1 print "2. Aeroblast", move2 print "3. Dragon Ascent", move3 move_number = randint(1,3) if move1 == 0: if move_number == 1: print "AI Missed!" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "AI Missed!" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "AI Missed!" return move1,move2,move3,HP if choice2 in range(1, 4): if move_number == 1: print "AI used Air Cutter" move1 -= 1 HP -= randint(0, 250) elif move_number == 2: print "AI used Aeroblast" move2 -= 1 HP -= randint(0, 500) elif move_number == 3: print "AI used Dragon Ascent" move3 -= 1 HP -= randint(0, 550) else: if move_number == 1: print "AI used Air Cutter" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "AI used Aeroblast" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "AI used Dragon Ascent" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def ground_moves_ai(choice2, move1, move2, move3, HP): print "1. Bone Rush", move1 print "2. Drill Run", move2 print "3. Precipice Blades", move3 move_number = randint(1,3) if move1 == 0: if move_number == 1: print "AI Missed!" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "AI Missed!" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "AI Missed!" return move1,move2,move3,HP if choice2 in range(16, 19): if move_number == 1: print "AI used Bone Rush" move1 -= 1 HP -= randint(0, 250) elif move_number == 2: print "AI used Drill Run" move2 -= 1 HP -= randint(0, 500) elif move_number == 3: print "AI used Precipice Blades" move3 -= 1 HP -= randint(0, 550) elif choice2 in range(1, 7): if move_number == 1: print "AI used Bone Rush" move1 -= 1 HP -= randint(0, 50) elif move_number == 2: print "AI used Drill Run" move2 -= 1 HP -= randint(0, 50) elif move_number == 3: print "AI used Precipice Blades" move3 -= 1 HP -= randint(0, 50) else: if move_number == 1: print "AI used Bone Rush" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "AI used Drill Run" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "AI used Precipice Blades" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def ghost_moves_ai(choice2, move1, move2, move3, HP): print "1. Astonish", move1 print "2. Ominous Wind", move2 print "3. Shadow Force", move3 move_number = randint(1,3) if move1 == 0: if move_number == 1: print "AI Missed!" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "AI Missed!" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "AI Missed!" return move1,move2,move3,HP if choice2 in range(10, 13): if move_number == 1: print "AI used Astonish" move1 -= 1 HP -= randint(0, 250) elif move_number == 2: print "AI used Ominous Wind" move2 -= 1 HP -= randint(0, 500) elif move_number == 3: print "AI used Shadow Force" move3 -= 1 HP -= randint(0, 550) elif choice2 in range(13, 16): if move_number == 1: print "AI used Astonish" move1 -= 1 HP -= randint(0, 50) elif move_number == 2: print "AI used Ominous Wind" move2 -= 1 HP -= randint(0, 50) elif move_number == 3: print "AI used Shadow Force" move3 -= 1 HP -= randint(0, 50) else: if move_number == 1: print "AI used Astonish" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "AI used Ominous Wind" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "AI used Shadow Force" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def normal_moves_ai(choice2, move1, move2, move3, HP): print "1. Double Hit", move1 print "2. Crush Claw", move2 print "3. Boomburst", move3 move_number = randint(1,3) if move1 == 0: if move_number == 1: print "AI Missed!" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "AI Missed!" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "AI Missed!" return move1,move2,move3,HP if choice2 in range(10, 14): if move_number == 1: print "AI used Double Hit" move1 -= 1 HP -= randint(0, 50) elif move_number == 2: print "AI used Crush Claw" move2 -= 1 HP -= randint(0, 50) elif move_number == 3: print "AI used Boomburst" move3 -= 1 HP -= randint(0, 50) else: if move_number == 1: print "AI used Double Hit" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "AI used Crush Claw" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "AI used Boomburst" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def fire_moves_ai(choice2, move1, move2, move3, HP): print "1. Ember", move1 print "2. Fire Pledge", move2 print "3. Flare Blitz", move3 move_number = randint(1,3) if move1 == 0: if move_number == 1: print "AI Missed!" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "AI Missed!" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "AI Missed!" return move1,move2,move3,HP if choice2 in range(10, 13): if move_number == 1: print "AI used Ember" move1 -= 1 HP -= randint(0, 250) elif move_number == 2: print "AI used Fire Pledge" move2 -= 1 HP -= randint(0, 500) elif move_number == 3: print "AI used Flare Blitz" move3 -= 1 HP -= randint(0, 550) elif choice2 in range(13, 16): if move_number == 1: print "AI used Ember" move1 -= 1 HP -= randint(0, 50) elif move_number == 2: print "AI used Fire Pledge" move2 -= 1 HP -= randint(0, 50) elif move_number == 3: print "AI used Flare Blitz" move3 -= 1 HP -= randint(0, 50) else: if move_number == 1: print "AI used Ember" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "AI used Fire Pledge" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "AI used Flare Blitz" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def water_moves_ai(choice2, move1, move2, move3, HP): print "1. Aqua Jet", move1 print "2. Bubble Beam", move2 print "3. Hydro Cannon", move3 move_number = randint(1,3) if move1 == 0: if move_number == 1: print "AI Missed!" return move1,move2,move3,HP if move2 == 0: if move_number == 2: print "AI Missed!" return move1,move2,move3,HP if move3 == 0: if move_number == 3: print "AI Missed!" return move1,move2,move3,HP if choice2 in range(7, 10) or choice2 in range(16, 19): if move_number == 1: print "AI used Aqua Jet" move1 -= 1 HP -= randint(0, 250) elif move_number == 2: print "AI used Bubble Beam" move2 -= 1 HP -= randint(0, 500) elif move_number == 3: print "AI used Hydro Cannon" move3 -= 1 HP -= randint(0, 550) elif choice2 in range(13, 16): if move_number == 1: print "AI used Aqua Jet" move1 -= 1 HP -= randint(0, 50) elif move_number == 2: print "AI used Bubble Beam" move2 -= 1 HP -= randint(0, 50) elif move_number == 3: print "AI used Hydro Cannon" move3 -= 1 HP -= randint(0, 50) else: if move_number == 1: print "AI used Aqua Jet" move1 -= 1 HP -= randint(0, 150) elif move_number == 2: print "AI used Bubble Beam" move2 -= 1 HP -= randint(0, 200) elif move_number == 3: print "AI used Hydro Cannon" move3 -= 1 HP -= randint(0, 250) return move1,move2,move3,HP def the_game(php,ohp,pmove1,pmove2,pmove3,omove1,omove2,omove3,choice,choice2): if pmove1+pmove2+pmove3 == 0 and omove1+omove2+omove3 == 0: print "Nobody has moves left! Match draw!" return elif pmove1+pmove2+pmove3 == 0: print "No moves left. Opponent's turn!" elif php <= 0: print "You lose!" return else: if choice in range(1,4): pmove1,pmove2,pmove3,ohp = grass_moves_human(choice2,pmove1,pmove2,pmove3,ohp) if choice in range(4, 7): pmove1,pmove2,pmove3,ohp = flying_moves_human(choice2, pmove1, pmove2, pmove3, ohp) if choice in range(7,10): pmove1,pmove2,pmove3,ohp = ground_moves_human(choice2,pmove1,pmove2,pmove3,ohp) if choice in range(10,13): pmove1,pmove2,pmove3,ohp = ghost_moves_human(choice2,pmove1,pmove2,pmove3,ohp) if choice in range(13,16): pmove1,pmove2,pmove3,ohp = normal_moves_human(choice2,pmove1,pmove2,pmove3,ohp) if choice in range(16,19): pmove1,pmove2,pmove3,ohp = fire_moves_human(choice2,pmove1,pmove2,pmove3,ohp) if choice in range(19,22): pmove1,pmove2,pmove3,ohp = water_moves_human(choice2,pmove1,pmove2,pmove3,ohp) print "Player HP is {} and Opponent HP is {}".format(php,ohp) if omove1+omove2+omove3 == 0: print "Opponent has no moves left. Your turn!" elif ohp <= 0: print "You win!" return else: print "Opponent is attacking..." sleep(2) if choice2 in range(1,4): omove1,omove2,omove3,php = grass_moves_ai(choice2,omove1,omove2,omove3,php) if choice2 in range(4, 7): omove1,omove2,omove3,php = flying_moves_ai(choice2, omove1, omove2, omove3, php) if choice2 in range(7,10): omove1,omove2,omove3,php = ground_moves_ai(choice2,omove1,omove2,omove3,php) if choice2 in range(10,13): omove1,omove2,omove3,php = ghost_moves_ai(choice2,omove1,omove2,omove3,php) if choice2 in range(13,16): omove1,omove2,omove3,php = normal_moves_ai(choice2,omove1,omove2,omove3,php) if choice2 in range(16,19): omove1,omove2,omove3,php = fire_moves_ai(choice2,omove1,omove2,omove3,php) if choice2 in range(19,22): omove1,omove2,omove3,php = water_moves_ai(choice2,omove1,omove2,omove3,php) print "Player HP is {} and Opponent HP is {}".format(php, ohp) return the_game(php,ohp,pmove1,pmove2,pmove3,omove1,omove2,omove3,choice,choice2) the_game(Player_HP,Opponent_HP,Pmove1,Pmove2,Pmove3,Omove1,Omove2,Omove3,choice,choice2)
Java
UTF-8
2,520
2.546875
3
[]
no_license
package org.servlets.garits.Accounts; import java.util.ArrayList; public class Customer { public Customer(String email, String name, String address, String tel, String post_code, String fax) { this.email = email; this.name = name; this.address = address; this.tel = tel; this.post_code = post_code; this.fax = fax; } private String email; private String name; private String address; private String tel; private String post_code; private String fax; private ArrayList<Vehicle> vehicles = new ArrayList<Vehicle>(); public ArrayList<Vehicle> getVehicles() { return vehicles; } public void setVehicles(ArrayList<Vehicle> vehicles) { this.vehicles = vehicles; } public Customer() { } @Override public String toString() { return "Customer{" + "email=" + email + ", name=" + name + ", address=" + address + ", tel=" + tel + ", post_code=" + post_code + ", fax=" + fax + ", vehicles=" + vehicles + '}'; } public void makeRepairBooking() { // TODO - implement Customer.makeRepairBooking } public void makeMoTBooking() { // TODO - implement Customer.makeMoTBooking } public void confirmService() { // TODO - implement Customer.confirmService } public String getEmail() { return this.email; } /** * * @param email */ public void setEmail(String email) { this.email = email; } public String getName() { return this.name; } /** * * @param name */ public void setName(String name) { this.name = name; } public String getAddress() { return this.address; } /** * * @param address */ public void setAddress(String address) { this.address = address; } public String getTel() { return this.tel; } /** * * @param tel */ public void setTel(String tel) { this.tel = tel; } public String getPostCode() { return this.post_code; } /** * * @param postCode */ public void setPostCode(String postCode) { this.post_code = postCode; } public String getFax() { return this.fax; } /** * * @param fax */ public void setFax(String fax) { this.fax = fax; } public void AddVehicle(Vehicle v) { this.vehicles.add(v); } public Vehicle GetVehicle(String regNo){ for(Vehicle v: vehicles){ if(v.getRegNo().equals(regNo)){ return v; } } return null; } /** * * @param name * @param ID */ }
JavaScript
UTF-8
1,872
2.703125
3
[]
no_license
const app = require('./app'); const http = require('http'); // let env = process.env.NODE_ENV || 'development'; // console.log(`Server is running in ${env} mode`); //This portion of code is required only for SSL/HTTPs requests to handle const port = normalizePort(app.get("port") || '3000'); app.set('port', port); const server = http.createServer(app).listen(app.get("port"), function () { console.log('http server is running at http://localhost:' + app.get("port")); }); function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } function onError(error) { if (error.syscall !== "listen") { throw error; } var bind = typeof app.get("port") === "string" ? "Pipe " + app.get("port") : "Port " + app.get("port"); // handle specific listen errors with friendly messages switch (error.code) { case "ENOENT": console.error(bind + "directory not found"); // process.exit(1); process.exit(error.code); break; case "ECONNREFUSED": console.error(bind + "connection refused by target"); process.exit(error.code); break; case "EACCES": console.error(bind + " requires elevated privileges"); process.exit(error.code); break; case "EADDRINUSE": console.error(bind + " is already in use"); process.exit(error.code); break; case "ETIMEDOUT": console.error(bind + "is taking so much time to response"); process.exit(error.code); default: console.log("fired error") throw error; } } module.exports = server;
Java
UTF-8
4,866
1.734375
2
[ "Apache-2.0" ]
permissive
/* * (c) Copyright 2019 Palantir Technologies Inc. All rights reserved. * * 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.palantir.conjure.java.services.dialogue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.palantir.conjure.java.services.Auth; import com.palantir.conjure.java.types.TypeMapper; import com.palantir.conjure.java.visitor.DefaultTypeVisitor; import com.palantir.conjure.spec.ArgumentDefinition; import com.palantir.conjure.spec.BodyParameterType; import com.palantir.conjure.spec.EndpointDefinition; import com.palantir.conjure.spec.HeaderParameterType; import com.palantir.conjure.spec.ListType; import com.palantir.conjure.spec.MapType; import com.palantir.conjure.spec.OptionalType; import com.palantir.conjure.spec.ParameterType; import com.palantir.conjure.spec.PathParameterType; import com.palantir.conjure.spec.QueryParameterType; import com.palantir.conjure.spec.SetType; import com.palantir.conjure.spec.Type; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.TypeName; import java.util.Comparator; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class ParameterTypeMapper { private static final Logger log = LoggerFactory.getLogger(ParameterTypeMapper.class); private final TypeMapper parameterTypes; public ParameterTypeMapper(TypeMapper parameterTypes) { this.parameterTypes = parameterTypes; } public TypeName baseType(Type type) { return parameterTypes.getClassName(type); } public List<ParameterSpec> methodParams(EndpointDefinition endpointDef) { ImmutableList.Builder<ParameterSpec> paramSpecBuilder = ImmutableList.builder(); endpointDef.getAuth().ifPresent(auth -> paramSpecBuilder.add(Auth.authParam(auth))); endpointDef.getArgs().stream() .sorted(Comparator.comparing(o -> o.getParamType().accept(PARAM_SORT_VISITOR) + o.getType().accept(TYPE_SORT_VISITOR))) .forEach(def -> paramSpecBuilder.add(param(def))); return paramSpecBuilder.build(); } private ParameterSpec param(ArgumentDefinition def) { ParameterSpec.Builder param = ParameterSpec.builder( parameterTypes.getClassName(def.getType()), def.getArgName().get()); param.addAnnotations(markers(def.getMarkers())); return param.build(); } private Set<AnnotationSpec> markers(List<Type> markers) { if (!markers.isEmpty()) { log.debug("conjure-dialogue does not support markers. In particular, it ignores @Safe annotations"); } return ImmutableSet.of(); } /** Produces an ordering for ParamaterType of Header, Path, Query, Body. */ private static final ParameterType.Visitor<Integer> PARAM_SORT_VISITOR = new ParameterType.Visitor<Integer>() { @Override public Integer visitHeader(HeaderParameterType value) { return 0; } @Override public Integer visitPath(PathParameterType value) { return 10; } @Override public Integer visitQuery(QueryParameterType value) { return 20; } @Override public Integer visitBody(BodyParameterType value) { return 30; } @Override public Integer visitUnknown(String unknownType) { return -1; } }; /** * Produces a type sort ordering for use with {@link #PARAM_SORT_VISITOR} such that types with known defaults come * after types without known defaults. */ private static final Type.Visitor<Integer> TYPE_SORT_VISITOR = new DefaultTypeVisitor<Integer>() { @Override public Integer visitOptional(OptionalType value) { return 1; } @Override public Integer visitList(ListType value) { return 1; } @Override public Integer visitSet(SetType value) { return 1; } @Override public Integer visitMap(MapType value) { return 1; } @Override public Integer visitDefault() { return 0; } }; }
Ruby
UTF-8
679
2.65625
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
require 'socket' describe 'IPSocket#getaddress' do describe 'when given a hostname' do it 'returns the IP address of the hostname' do addr = IPSocket.getaddress('localhost') %w{127.0.0.1 ::1}.include?(addr).should == true end end describe 'when given an IP address' do it 'returns the IP address itself' do IPSocket.getaddress('127.0.0.1').should == '127.0.0.1' IPSocket.getaddress('::1').should == '::1' end end describe 'when given a non existing hostname' do it 'raises SocketError' do block = proc { IPSocket.getaddress('cats.are.awesome.local') } block.should raise_error(SocketError) end end end
Java
UTF-8
1,310
2.875
3
[]
no_license
package homework_one; public class Entity { private String name; private String surname; private Integer age; private String mail; private String password; private Role role; public Entity(Role role) { this.role = role; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "Entity{" + "name='" + name + '\'' + ", surname='" + surname + '\'' + ", age=" + age + ", mail='" + mail + '\'' + ", password='" + password + '\'' + ", role=" + role + '}'; } }
PHP
UTF-8
3,102
2.515625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php final class DiffusionInlineCommentController extends PhabricatorInlineCommentController { protected function newInlineCommentQuery() { return new DiffusionDiffInlineCommentQuery(); } protected function newContainerObject() { return $this->loadCommit(); } private function getCommitPHID() { return $this->getRequest()->getURIData('phid'); } private function loadCommit() { $viewer = $this->getViewer(); $commit_phid = $this->getCommitPHID(); $commit = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withPHIDs(array($commit_phid)) ->executeOne(); if (!$commit) { throw new Exception(pht('Invalid commit PHID "%s"!', $commit_phid)); } return $commit; } protected function createComment() { $commit = $this->loadCommit(); // TODO: Write a real PathQuery object? $path_id = $this->getChangesetID(); $path = queryfx_one( id(new PhabricatorRepository())->establishConnection('r'), 'SELECT path FROM %T WHERE id = %d', PhabricatorRepository::TABLE_PATH, $path_id); if (!$path) { throw new Exception(pht('Invalid path ID!')); } return id(new PhabricatorAuditInlineComment()) ->setCommitPHID($commit->getPHID()) ->setPathID($path_id); } protected function loadCommentForDone($id) { $viewer = $this->getViewer(); $inline = $this->loadCommentByID($id); if (!$inline) { throw new Exception(pht('Failed to load comment "%d".', $id)); } $commit = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withPHIDs(array($inline->getCommitPHID())) ->executeOne(); if (!$commit) { throw new Exception(pht('Failed to load commit.')); } $owner_phid = $commit->getAuthorPHID(); $viewer_phid = $viewer->getPHID(); $viewer_is_owner = ($owner_phid && ($owner_phid == $viewer_phid)); $viewer_is_author = ($viewer_phid == $inline->getAuthorPHID()); $is_draft = $inline->isDraft(); if ($viewer_is_owner) { // You can mark inlines on your own commits as "Done". } else if ($viewer_is_author && $is_draft) { // You can mark your own unsubmitted inlines as "Done". } else { throw new Exception( pht( 'You can not mark this comment as complete: you did not author '. 'the commit and the comment is not a draft you wrote.')); } return $inline; } protected function canEditInlineComment( PhabricatorUser $viewer, PhabricatorAuditInlineComment $inline) { // Only the author may edit a comment. if ($inline->getAuthorPHID() != $viewer->getPHID()) { return false; } // Saved comments may not be edited. if ($inline->getTransactionPHID()) { return false; } // Inline must be attached to the active revision. if ($inline->getCommitPHID() != $this->getCommitPHID()) { return false; } return true; } protected function loadObjectOwnerPHID( PhabricatorInlineComment $inline) { return $this->loadCommit()->getAuthorPHID(); } }
Java
UTF-8
2,825
3.40625
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; //private static ArrayList<Integer>[] list;  class Pairs{ int screen = 0; int clipboard = 0; int count = 0; public Pairs(int screen, int clipboard, int count){ this.clipboard = clipboard; this.screen = screen; this.count = count; } } public class BOJ14226 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //StringTokenizer st = new StringTokenizer(br.readLine()); int S = 0; S = Integer.parseInt(br.readLine());//S개의 이모티콘을 만들기 위한 시간의 최솟값 boolean[][] check = new boolean[10001][10001];//화면 이모티콘, 클립보드 이모티콘 방문체크 //bfs인데 정해진 좌표에서 동서남북방향으로 움직이는 방식과는 조금 다르다 //움직이는 조건은 //1. 복사 : 화면, 클립보드 = 화면, 초+1 //2. 붙여넣기 : 화면 + 클립보드, 클립보드, 초+1 //3. 삭제 : 화면-1, 클립보드, 초+1 Queue<Pairs> queue = new LinkedList<Pairs>(); queue.add(new Pairs(1,0,0));//처음시작은 화면에 하나가 있는 상태 check[1][0] = true; while(!queue.isEmpty()){ Pairs pairs = queue.poll(); int nowScreen = pairs.screen; int nowClipboard = pairs.clipboard; int nowCount = pairs.count; if(nowScreen == S){//내가 원하는 갯수가 되면 break System.out.println(nowCount); break; } //복사(조건 필요없다...?) //nowClipboard = nowScreen; queue.add(new Pairs(nowScreen, nowScreen, nowCount+1)); //붙여넣기(단, 클립보드가 0개면 안되고, 내가 원하는 갯수S를 넘으면 안되고 들린적있으면 안됨) if(!check[nowScreen + nowClipboard][nowClipboard] && nowClipboard > 0 && nowScreen+nowClipboard <= S){ queue.add(new Pairs(nowScreen + nowClipboard, nowClipboard, nowCount+1)); check[nowScreen + nowClipboard][nowClipboard] = true; } //삭제(단, 이동하려는 곳이 방문한적이 없어야하고, 스크린에 아무것도 없으면 안됨) if(nowScreen >= 1 && !check[nowScreen-1][nowClipboard]){ queue.add(new Pairs(nowScreen-1, nowClipboard, nowCount+1)); check[nowScreen-1][nowClipboard] = true; } } } }
JavaScript
UTF-8
2,585
2.65625
3
[]
no_license
import React from 'react' import Aux from '../../hoc/Auxy' import Burger from '../../components/Burger/Burger' import BuildControls from '../../components/Burger/BuildControls/BuildControls' import Modal from '../../components/Burger/UI/Modal/Modal' import OrderSummary from '../../components/Burger/OrderSummary/OrderSummary' const ING_PRICES={ salad:0.6, bacon:0.8, meat:1.1, cheese:0.3 } export default class BurgerBuilder extends React.Component{ state={ ingredients: { salad:0, cheese:0, bacon:0, meat:0 }, purchasable:false, totalPrice:4, purchasing:false } addIngredientsHandler=(type)=>{ let currentCount=this.state.ingredients[type]; let newCount=currentCount+1; let newIngredients={ ...this.state.ingredients} newIngredients[type]=newCount; let currentPrice=this.state.totalPrice; let newPrice=currentPrice+ING_PRICES[type]; this.setState({ingredients:newIngredients, totalPrice:newPrice}) this.updatePurchasable(newIngredients) } subtractIngredientHandler=(type)=> { let currentCount=this.state.ingredients[type]; let newCount=currentCount-1; newCount=Math.max(0,newCount); let newIngredients={ ...this.state.ingredients} newIngredients[type]=newCount; let currentPrice=this.state.totalPrice; let newPrice=currentPrice-ING_PRICES[type]; if(currentCount>0) this.setState({ingredients:newIngredients, totalPrice:newPrice}) else this.setState({ingredients:newIngredients, totalPrice:currentPrice}) this.updatePurchasable(newIngredients) } updatePurchasable(ingredients) { let sum=Object.keys(ingredients).map( (key)=> { return ingredients[key]}).reduce( (sum, ele)=> { return sum+ele} , 0) this.setState({purchasable:sum>0}) } purchaseHandler=()=> { this.setState({purchasing:true}) } purchaseCancelledHandle=()=>{ this.setState({purchasing:false}) } purchaseContinuedHandler=()=>{ alert("You have bought the burger : " + this.state.totalPrice.toFixed(2)) } render() { return( <Aux> <Modal modalClosed={this.purchaseCancelledHandle.bind(this)} show={this.state.purchasing}> <OrderSummary continue={this.purchaseContinuedHandler.bind(this)} cancel={this.purchaseCancelledHandle.bind(this)} ingredients={this.state.ingredients}></OrderSummary></Modal> <Burger ingredients={this.state.ingredients}></Burger> <BuildControls price={this.state.totalPrice} adding={this.addIngredientsHandler.bind(this)} subtracting={this.subtractIngredientHandler.bind(this)} purchasable={this.state.purchasable} ordering={this.purchaseHandler.bind(this)} ></BuildControls> </Aux> ) } }
JavaScript
UTF-8
2,380
2.796875
3
[]
no_license
import React, {useState, useContext} from 'react'; import { GlobalContext } from "../Context/GlobalState"; export const SumarTransaccion = () => { const [descripcion, setDescripcion] = useState(""); const [categoria, setCategoria] = useState(""); const [monto, setMonto] = useState(""); const [fechaCreacion, setFechaCreacion] = useState(""); const { sumarTransaccion } = useContext(GlobalContext); const onSubmit = e =>{ e.preventDefault(); const nuevaTransaccion = { id: "t"+Math.floor(Math.random()*10000000), descripcion, categoria, monto: +monto, fechaCreacion } sumarTransaccion(nuevaTransaccion); } return ( <> <h3>Añade una nueva transacción</h3> {/* Form para introducir datos */} <form onSubmit={onSubmit} className="formularios"> {/* DESCRIPCIÓN */} <div > <label htmlFor="text">Descripción:</label> {/* Este input tendrá el valor de text y con un evento se pondra el valor que tipeemos */} <input type="text" value={descripcion} onChange={(e) => setDescripcion(e.target.value)} placeholder="Describe la transacción..." /> </div> {/* CATEGORIA */} <div > <label htmlFor="text">Categoria:</label> {/* Este input tendrá el valor de text y con un evento se pondra el valor que tipeemos */} <input type="text" value={categoria} onChange={(e) => setCategoria(e.target.value)} placeholder="¿Qué categoría es?" /> </div> {/* MONTO */} <div > <label htmlFor="amount" >Monto: <br /> Positivo si es ingreso, negativo si es egreso</label> <input type="number" value={monto} onChange={(e) => setMonto(e.target.value)} placeholder="Introduce el monto..." /> </div> {/* FECHA */} <div > <label htmlFor="date" >Fecha de operación: </label> <br /> <input type="date" value={fechaCreacion} onChange={(e) => setFechaCreacion(e.target.value)} placeholder="Introduce fecha de operación" /> </div> {/* BOTON DE SUBMIT */} <button className="btn">Enviar transacción </button> </form> </> ) }