branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>'use strict'; const test = require('supertape'); const vim = require('./vim'); test('vim: no operations', (t) => { const result = vim('hello', {}); t.notOk(result); t.end(); }); <file_sep>'use strict'; module.exports = { 'F2 - Rename file': async ({DOM}) => { await DOM.renameCurrent(); }, 'D - Build Dev': async ({CloudCmd}) => { await CloudCmd.TerminalRun.show({ command: 'npm run build:client:dev', autoClose: false, closeMessage: 'Press any button to close Terminal', }); CloudCmd.refresh(); }, 'P - Build Prod': async ({CloudCmd}) => { await CloudCmd.TerminalRun.show({ command: 'npm run build:client', autoClose: true, }); CloudCmd.refresh(); }, };
42b51f3e13c647c24ad4a0ad90111e786f38d5bf
[ "JavaScript" ]
2
JavaScript
rberrelleza/cloudcmd
16a1eade2a993903296dc0cc010fd57e387bb9b5
36bd7adcd67251229cfb5dd93a1496d2e26051b1
refs/heads/main
<file_sep>import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import TfidfTransformer from sklearn.svm import SVC import tensorflow as tf from tensorflow import keras from tensorflow.keras.datasets import mnist from tensorflow.keras.utils import to_categorical from tensorflow.keras import layers from keras.models import Sequential from keras.utils import to_categorical import kerastuner as kt activation_functions = ['relu', 'elu'] output_activation_functions = ['sigmoid', 'softmax'] optimizers = {'adam': tf.keras.optimizers.Adam, 'RMSProp': tf.keras.optimizers.RMSprop, 'SGD': tf.keras.optimizers.SGD} learning_rates = [1e-2, 1e-3, 1e-4] def print_scores(model, scores): print("\n") for i in range(len(scores)): print(model.metrics_names[i], " = ", scores[i]) def model_builder(hp): first_layer = hp.Int('first_layer_hp', min_value=50, max_value=150, step=25) second_layer = hp.Int('second_layer_hp', min_value=50, max_value=150, step=25) third_layer = hp.Int('third_layer_hp', min_value=50, max_value=150, step=25) hidden_layer_activation = hp.Choice('hidden_layer_activation', values=activation_functions) output_layer_activation = hp.Choice('output_layer_activation', values=output_activation_functions) optimizer = hp.Choice('optimizer', values=['adam', 'RMSProp', 'SGD']) learning_rate = hp.Choice('lr', values=learning_rates) model = keras.Sequential() #model.add(layers.Flatten()) model.add(layers.Dense(first_layer, activation=hidden_layer_activation)) model.add(layers.Dense(second_layer, activation=hidden_layer_activation)) model.add(layers.Dense(third_layer, activation=hidden_layer_activation)) model.add(layers.Dense(2, activation=output_layer_activation)) lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(learning_rate, decay_steps=100000, decay_rate=0.96, staircase=True) model.compile(optimizer=optimizers[optimizer](learning_rate=lr_schedule), loss='categorical_crossentropy', metrics=['accuracy', 'categorical_crossentropy', ]) return model def tune_nn_model(x_train, y_train): y_train = to_categorical(y_train) tuner = kt.BayesianOptimization(model_builder, objective='val_accuracy', max_trials=4) stop_early = keras.callbacks.EarlyStopping(monitor='val_loss', patience=5) tuner.search(x_train, y_train, epochs=50, validation_split=0.3, callbacks=[stop_early]) best_hps = tuner.get_best_hyperparameters(num_trials=1)[0] print("Best Hyperparams:", best_hps) # Calculate best epochs model = tuner.hypermodel.build(best_hps) history = model.fit(x_train, y_train, epochs=50, validation_split=0.3) val_acc_per_epoch = history.history['val_accuracy'] best_epoch = val_acc_per_epoch.index(max(val_acc_per_epoch)) + 1 # Train for said epochs model = tuner.hypermodel.build(best_hps) model.fit(x_train, y_train, epochs=best_epoch, validation_split=0.3) #Save model model.save("simpleNNBestModel.h5") def test_simple_fc_nn(x_test, y_test): y_test = to_categorical(y_test) best_simple_NN_model = keras.models.load_model('simpleNNBestModel.h5') # best_simple_NN_model = create_simple_NN(activation_fn = best_simple_NN_config[1], output_activation_fn = best_simple_NN_config[2], # optimizer = best_simple_NN_config[3], learning_rate = best_simple_NN_config[4]) # best_simple_NN_model.fit(x_train, y_train, epochs=20, verbose=1) scores = best_simple_NN_model.evaluate(x_test, y_test, verbose=1) print("\n\nBest Model Scores on Test Data: ") print_scores(best_simple_NN_model, scores) prediction = best_simple_NN_model.predict(x_test) n_values = 2; prediction = np.eye(n_values, dtype=int)[np.argmax(prediction, axis=1)] class_report = classification_report(y_test, prediction) print("Report: \n", class_report) conf_matrix = confusion_matrix(y_test.argmax(axis=1), prediction.argmax(axis=1)) print("\nConfusion Matrix:\n", conf_matrix) f1 = f1_score(y_test.argmax(axis=1), prediction.argmax(axis=1)) print("\nF1-Score: ", f1) <file_sep>import pandas as pd import numpy as np import nltk from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import TfidfTransformer from sklearn.svm import SVC from sklearn.preprocessing import FunctionTransformer from nltk.stem import PorterStemmer from nltk.stem.lancaster import LancasterStemmer from nltk.stem.snowball import SnowballStemmer from nltk.stem import WordNetLemmatizer from trainAndTestNN import test_simple_fc_nn # function from https://towardsdatascience.com/setting-up-text-preprocessing-pipeline-using-scikit-learn-and-spacy-e09b9b76758f def pipelinize(function, active=True): def list_comprehend_a_function(list_or_series, active=True): if active: return [function(i) for i in list_or_series] else: # if it's not active, just pass it right back return list_or_series return FunctionTransformer(list_comprehend_a_function, validate=False, kw_args={'active':active}) def stemmer(text): stemmer = LancasterStemmer() return stemmer.stem(text) def lemmatizer(text): lemmatizer = WordNetLemmatizer() return lemmatizer.lemmatize(text) def split_and_countvectorize(df_headline:pd.DataFrame, label:pd.DataFrame): label = df['clickbait'] df_headline = df.drop(columns=['clickbait']) #print(df_headline) x_train, x_test, y_train, y_test = train_test_split(df_headline, label, test_size=0.3, random_state = 123) # nltk.download('wordnet') preprocessing = Pipeline([('stemmer', pipelinize(stemmer)), ('vectorizer', CountVectorizer(lowercase=True)), ('term_frequency', TfidfTransformer(use_idf=False))]) # preprocessing = Pipeline([('lemmatizer', pipelinize(lemmatizer)), ('vectorizer', CountVectorizer(lowercase=True)), # ('term_frequency', TfidfTransformer(use_idf=False))]) x_train = preprocessing.fit_transform(x_train['headline']) x_test = preprocessing.transform(x_test['headline']) return x_train, x_test, y_train, y_test def test_multinomial_nb(x_train, x_test, y_train, y_test): model = MultinomialNB(alpha = 0.2).fit(x_train, y_train) # model = SVC().fit(x_train, y_train) prediction = model.predict(x_test) class_report = classification_report(y_test, prediction) print("Report: \n", class_report) conf_matrix = confusion_matrix(y_test, prediction) print("\nConfusion Matrix:\n", conf_matrix) f1 = f1_score(y_test, prediction) print("\nF1-Score: ", f1) df = pd.read_csv('./train1.csv') label = df['clickbait'] df_headline = df.drop(columns=['clickbait']) print(df_headline) x_train, x_test, y_train, y_test = split_and_countvectorize(df_headline, label) print(x_train) print(x_test) print("Multinomial Naive Bayes Test:") test_multinomial_nb(x_train, x_test, y_train, y_test) print("Simple NN:") test_simple_fc_nn(x_test=x_test.todense(), y_test=y_test.to_numpy()) # NB with previous setup: F1-Score: 0.9732808616404309 # NB with lancaster stemming: F1-Score: 0.9732863946986954 # Simple NN: F1-Score: 0.9734832414085702 <file_sep># DataMiningFinalProject ## Problem Statement In the digital age, countless websites and articles are fighting for our attention in order to gain traction for their websites. This has manifested itself in the presentation of news headlines, where the titles go from intriguing to inaccurate. Clickbait, as it is commonly known, has become increasingly common. Whether the article's headline is a half-truth or a full lie, the reader is typically left disappointed by the unkept promises of the title. The author, on the other hand, has succeeded nonetheless in getting people to look at their webpage and in turn, their advertisements. Clickbait doesn't just affect those unfortunate enough to be tricked into reading the articles. Their mere presence dilutes the actual news for anyone scrolling through a news feed. Even if you can recognize all clickbait, it still ends up wasting your time because you have to sift through it all to get to the news you actually want to read. Clickbait titles can also make readers suspicious of legitimate news with impressive titles, making real news harder to digest. Given the headache of clickbait, can a machine learning model determine whether or not a headline is clickbait? How well can clickbait be separated from honest headlines? This project aims to create a machine learning model capable of delineating between clickbait and honest headlines. ## Dataset The dataset used is the "News Clickbait Dataset" which is [available here](https://www.kaggle.com/vikassingh1996/news-clickbait-dataset). The data contains two subsets. We chose to start with only the first because the second subset was unbalanced. The first subset contained a balanced 32,000 samples so we were confident that it would be sufficient for a competent agent. The data is formatted in a very simple fashion. It contains only two fields: a headline given as a string and a clickbait status given as a 0 or 1. As a result, the model only uses the title of the article to make its decision. Other information such as the contents of the article, the author, the website of publication, and associated images are not considered. ## Applied Techniques The machine learning techniques we evaluated are: - Naive Bayes - Vector Machines - MLP Neural Networks Our goal with our different model types was to encompass a range of varying complexity to allow us to use the simplest sufficient model. The data pre-processing techniques we evaluated are: - lowercasing text - removing punctuation - tokenization - term counting - normalizing - term frequency representation - stop list - stemming - lemmatization The data pre-processing techniques were chosen in alignment with the most common Natural Language Processing Techniques. ## Evaluation Measures The data evaluation measures we employed are: - F1-Score - Confusion Matrix - Accuracy - Precision - Recall Of these evaluation measures, we valued F1-Score and confusion matrices the most. F1-Scores gave us a robust representation of how well a particular model was doing overall. Confusion matrices helped us to diagnose if a model was incorrectly classifying too many articles as clickbait or vice versa. The other metrics were also useful statistics but didn't drive our process as much as F1-Score or confusion matrices. ## Results Some of our most notable results for how our model performed on unseen test data are as follows: - Naive Bayes F-1 Score: 0.97328 - SVM F-1 Score: 0.97024 - Neural Network F-1 Score: 0.97348 - NN With Preprocessing F1-Score: 0.96846 ## Conclusion Ultimately, we found that effective clickbait classifiers can be created solely based on the article's title. Another key takeaway from this project is that even a simple model such as Naive Bayes can perform extremely well. While near-perfect accuracy is still just out of reach, increased model complexity and more features would likely be enough to break past the 0.97 F1-Score barrier. We feel that our models perform exceptionally well and would function properly in a production environment. That being said, if we wanted to strive for near-perfect accuracy, there are some improvements that we could still make. First, incorporating the second subset of data into the data we used could help make the model more robust. Second, we feel that collecting more features in the dataset would also create a way to understand more challenging examples. A feature like the author of the article could help rule out any articles written by established journalists. The images used alongside the article could also provide some insight, with clickbait articles perhaps leaning towards more shocking images. Other changes that may help make improvements would involve our pre-processing pipeline. Various other techniques are possible although we feel that these changes alone are unlikely to bring about near-perfect accuracy. Having already tried a variety of methods and different approaches to many pre-processing techniques, it seems as though we have attempted many of the changes that would bring about the most positive impact. That being several incremental improvements could still help the model perform even better.
46b9204dd4ed5f3b73e008bd9c6e09ab90cb59a1
[ "Markdown", "Python" ]
3
Python
MadKingAaron/DataMiningFinalProject
5e40fb06747dbedf17e4e1ad78123eae014ee777
bb015c3cda7c49c34f5db2aa6adc5903f9e047fa
refs/heads/devel
<repo_name>nim-lang-cn/Nim<file_sep>/build_all.sh #! /bin/sh # build development version of the compiler; can be rerun safely set -u # error on undefined variables set -e # exit on first error echo_run(){ printf "\n$*\n" "$@" } [ -d csources ] || echo_run git clone --depth 1 https://github.com/nim-lang/csources.git nim_csources=bin/nim_csources build_nim_csources(){ ## avoid changing dir in case of failure ( echo_run cd csources echo_run sh build.sh $@ ) # keep $nim_csources in case needed to investigate bootstrap issues # without having to rebuild from csources echo_run cp bin/nim $nim_csources } [ -f $nim_csources ] || echo_run build_nim_csources $@ # Note: if fails, may need to `cd csources && git pull` echo_run bin/nim c --skipUserCfg --skipParentCfg koch echo_run ./koch boot -d:release echo_run ./koch tools # Compile Nimble and other tools. <file_sep>/doc/tut2.rst ====================== Nim教程 (II) ====================== :Author: <NAME> :Version: |nimversion| .. contents:: 引言 ============ "重复让荒谬合理。" -- <NAME> 本文档是 *Nim* 编程语言的高级构造部分。 **注意本文档有些过时** 因为 `manual <manual.html>`_ **包含更多高级语言特性的样例** 。 编译指示(Pragmas) ======= 编译指示是Nim中不用引用大量新关键字,给编译器附加信息、命令的方法。编译指示用特殊的 ``{.`` 和 ``.}`` 花括号括起来。本教程不讲pragmas。 可用编译指示的描述见 `manual <manual.html#pragmas>`_ 或 `user guide <nimc.html#additional-features>`_ . 面向对象编程 =========================== 虽然Nim对面向对象编程(OOP)的支持很简单,但可以使用强大的OOP技术。OOP看作 *一种* 程序设计方式,不是 *唯一* 方式。通常过程的解决方法有更简单和高效的代码。 特别是,首选组合是比继承更好的设计。 继承 ----------- 继承在Nim中是完全可选的。对象需要用运行时类型信息使用继承 要使用运行时类型信息启用继承,对象需要从 ``RootObj`` 继承。 这可以直接完成,也可以通过从继承自 ``RootObj`` 的对象继承来间接完成。 通常,具有继承的类型也被标记为“ref”类型,即使这不是严格执行的。要在运行时检查某个对象是否属于某种类型,可以使用 ``of`` 运算符。 .. code-block:: nim :test: "nim c $1" type Person = ref object of RootObj name*: string # *表示 `name`可以从其它模块访问 age: int # 没有*表示字段对其它模块隐藏 Student = ref object of Person # Student从Person继承 id: int # 有一个id字段 var student: Student person: Person assert(student of Student) # is true # 对象构造: student = Student(name: "Anton", age: 5, id: 2) echo student[] 继承是使用 ``object of`` 语法完成的。目前不支持多重继承。如果一个对象类型没有合适的祖先, ``RootObj`` 可以用作它的祖先,但这只是一个约定。 没有祖先的对象是隐式的“final”。你可以使用 ``inheritable`` 编译指示来引入除 ``system.RootObj`` 之外的新对象根。 (例如,GTK封装使用了这种方法。) 只要使用继承,就应该使用Ref对象。它不是必须的,但是对于非ref对象赋值,例如 ``let person:Person = Student(id:123)`` 将截断子类字段。 **注意** :对于简单的代码重用,组合(*has-a* 关系)通常优于继承(*is-a* 关系)。由于对象是Nim中的值类型,因此组合与继承一样有效。 相互递归类型 ------------------------ 对象、元组和引用可以模拟相互依赖的非常复杂的数据结构; 它们是 *相互递归的* 。在Nim中,这些类型只能在单个类型部分中声明。(即任何其他因为需要任意符号先行减慢编译速度的类型。) 示例: .. code-block:: nim :test: "nim c $1" type Node = ref object # 对具有以下字段的对象的引用: le, ri: Node # 左右子树 sym: ref Sym # 叶节点包含Sym的引用 Sym = object # 符号 name: string # 符号名 line: int # 符号声明的行 code: Node # 符号的抽象语法树 类型转换 ---------------- Nim区分 `type casts`:idx: 和 `type conversions`:idx: 。使用 ``cast`` 运算符完成转换,并强制编译器将位模式解释为另一种类型。 类型转换是将类型转换为另一种类型的更友好的方式:它们保留抽象 *值* ,不一定是 *位模式* 。如果无法进行类型转换,则编译器会引发异常。 类型转换语法 ``destination_type(expression_to_convert)`` (像平时的调用): .. code-block:: nim proc getID(x: Person): int = Student(x).id 如果 ``x`` 不是 ``Student`` ,则引发 ``InvalidObjectConversionError`` 异常。 对象变体 --------------- 在需要简单变体类型的某些情况下,对象层次结构通常是过度的。 一个示例: .. code-block:: nim :test: "nim c $1" # 这是一个如何在Nim中建模抽象语法树的示例 type NodeKind = enum # 不同节点类型 nkInt, # 整型值叶节点 nkFloat, # 浮点型叶节点 nkString, # 字符串叶节点 nkAdd, # 加法 nkSub, # 减法 nkIf # if语句 Node = ref object case kind: NodeKind # ``kind`` 字段是鉴别字段 of nkInt: intVal: int of nkFloat: floatVal: float of nkString: strVal: string of nkAdd, nkSub: leftOp, rightOp: Node of nkIf: condition, thenPart, elsePart: Node var n = Node(kind: nkFloat, floatVal: 1.0) # 以下语句引发了一个`FieldError`异常,因为 n.kind的值不匹配: n.strVal = "" 从该示例可以看出,对象层次结构的优点是不需要在不同对象类型之间进行转换。但是,访问无效对象字段会引发异常。 方法调用语法 ------------------ 调用例程有一个语法糖:语法 ``obj.method(args)`` 可以用来代替 ``method(obj,args)`` 。如果没有剩余的参数,则可以省略括号: ``obj.len`` (而不是 ``len(obj)`` )。 此方法调用语法不限于对象,它可以用于任何类型: .. code-block:: nim :test: "nim c $1" import strutils echo "abc".len # is the same as echo len("abc") echo "abc".toUpperAscii() echo({'a', 'b', 'c'}.card) stdout.writeLine("Hallo") # the same as writeLine(stdout, "Hallo") (查看方法调用语法的另一种方法是它提供了缺少的后缀表示法。) 所以“纯面向对象”代码很容易编写: .. code-block:: nim :test: "nim c $1" import strutils, sequtils stdout.writeLine("Give a list of numbers (separated by spaces): ") stdout.write(stdin.readLine.splitWhitespace.map(parseInt).max.`$`) stdout.writeLine(" is the maximum!") 属性 ---------- 如上例所示,Nim不需要 *get-properties* :使用 *方法调用语法* 调用的普通get-procedures实现相同。但设定值是不同的;为此需要一个特殊的setter语法: .. code-block:: nim :test: "nim c $1" type Socket* = ref object of RootObj h: int # 由于缺少星号,无法从模块外部访问 proc `host=`*(s: var Socket, value: int) {.inline.} = ## setter of host address s.h = value proc host*(s: Socket): int {.inline.} = ## getter of host address s.h var s: Socket new s s.host = 34 # same as `host=`(s, 34) (该示例还显示了 ``inline`` 程序。) 可以重载 ``[]`` 数组访问运算符来提供 `数组属性`:idx: : .. code-block:: nim :test: "nim c $1" type Vector* = object x, y, z: float proc `[]=`* (v: var Vector, i: int, value: float) = # setter case i of 0: v.x = value of 1: v.y = value of 2: v.z = value else: assert(false) proc `[]`* (v: Vector, i: int): float = # getter case i of 0: result = v.x of 1: result = v.y of 2: result = v.z else: assert(false) 这个例子可以更好的用元组展示,元组提供 ``v[]`` 访问。 动态分发 ---------------- 程序总是使用静态调度。对于动态调度,用 ``method`` 替换 ``proc`` 关键字: .. code-block:: nim :test: "nim c $1" type Expression = ref object of RootObj ## abstract base class for an expression Literal = ref object of Expression x: int PlusExpr = ref object of Expression a, b: Expression # 注意:'eval'依赖于动态绑定 method eval(e: Expression): int {.base.} = # 重写基方法 quit "to override!" method eval(e: Literal): int = e.x method eval(e: PlusExpr): int = eval(e.a) + eval(e.b) proc newLit(x: int): Literal = Literal(x: x) proc newPlus(a, b: Expression): PlusExpr = PlusExpr(a: a, b: b) echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4))) 请注意,在示例中,构造函数 ``newLit`` 和 ``newPlus`` 是procs,因为它们使用静态绑定更有意义,但 ``eval`` 是一种方法,因为它需要动态绑定。 **注意:** 从Nim 0.20开始,要使用多方法,必须在编译时明确传递 ``--multimethods:on`` 。 在多方法中,所有具有对象类型的参数都用于分发: .. code-block:: nim :test: "nim c --multiMethods:on $1" type Thing = ref object of RootObj Unit = ref object of Thing x: int method collide(a, b: Thing) {.inline.} = quit "to override!" method collide(a: Thing, b: Unit) {.inline.} = echo "1" method collide(a: Unit, b: Thing) {.inline.} = echo "2" var a, b: Unit new a new b collide(a, b) # output: 2 如示例所示,多方法的调用不能有歧义:collide2比collide1更受欢迎,因为解析是从左到右的。因此 ``Unit,Thing`` 比 ``Thing,Unit`` 更准确。 **性能说明**: Nim不会生成虚函数表,但会生成调度树。这避免了方法调用的昂贵间接分支并启用内联。但是,其他优化(如编译时评估或死代码消除)不适用于方法。 异常 ========== 在Nim中,异常是对象。按照惯例,异常类型后缀为“Error”。 `system <system.html>`_ 模块定义了异常层次结构。异常来自 ``system.Exception`` ,它提供了通用接口。 必须在堆上分配异常,因为它们的生命周期是未知的。编译器将阻止您引发在栈上创建的异常。所有引发的异常应该至少指定在 ``msg`` 字段中引发的原因。 一个约定是只在异常情况下应该引发异常:例如,如果无法打开文件,不应引发异常,这很常见(文件可能不存在)。 Raise语句 --------------- 发起一个异常用 ``raise`` 语句: .. code-block:: nim :test: "nim c $1" var e: ref OSError new(e) e.msg = "the request to the OS failed" raise e 如果 ``raise`` 关键字后面没有表达式,则最后一个异常是 *re-raised* 。为了避免重复这种常见的代码模式,可以使用 ``system`` 模块中的模板 ``newException`` : .. code-block:: nim raise newException(OSError, "the request to the OS failed") Try语句 ------------- ``try`` 语句处理异常: .. code-block:: nim :test: "nim c $1" from strutils import parseInt # 读取应包含数字的文本文件的前两行并尝试添加 var f: File if open(f, "numbers.txt"): try: let a = readLine(f) let b = readLine(f) echo "sum: ", parseInt(a) + parseInt(b) except OverflowError: echo "overflow!" except ValueError: echo "could not convert string to integer" except IOError: echo "IO error!" except: echo "Unknown exception!" # reraise the unknown exception: raise finally: close(f) 除非引发异常,否则执行 ``try`` 之后的语句。然后执行适当的 ``except`` 部分。 如果存在未明确列出的异常,则执行空的 ``except`` 部分。它类似于 ``if`` 语句中的 ``else`` 部分。 如果有一个 ``finally`` 部分,它总是在异常处理程序之后执行。 在 ``except`` 部分中 *消耗* 异常。如果未处理异常,则通过调用堆栈传播该异常。这意味着程序的其余部分 - 不在 ``finally`` 子句中 - 通常不会被执行(如果发生异常)。 如果你需要*访问 ``except`` 分支中的实际异常对象或消息,你可以使用来自 `system <system.html>`_ 模块的 `getCurrentException()<system.html#getCurrentException>`_ 和 `getCurrentExceptionMsg()<system.html#getCurrentExceptionMsg>`_ 的过程。例: .. code-block:: nim try: doSomethingHere() except: let e = getCurrentException() msg = getCurrentExceptionMsg() echo "Got exception ", repr(e), " with message ", msg 引发异常的procs注释 --------------------------------------- 通过使用可选的 ``{.raises.}`` pragma,你可以指定过程是为了引发一组特定的异常,或者根本没有异常。如果使用 ``{.raises.}`` 编译指示,编译器将验证这是否为真。例如,如果指定过程引发 ``IOError`` ,并且在某些时候它(或它调用的一个过程)开始引发一个新的异常,编译器将阻止该过程进行编译。用法示例: .. code-block:: nim proc complexProc() {.raises: [IOError, ArithmeticError].} = ... proc simpleProc() {.raises: [].} = ... 一旦你有这样的代码,如果引发的异常列表发生了变化,编译器就会停止,并指出过程停止验证编译指示的行,没有捕获的异常和它的行数以及文件。 正在引发未捕获的异常,这可能有助于您找到已更改的有问题的代码。 如果你想将 ``{.raises.}`` 编译指示添加到现有代码中,编译器也可以帮助你。你可以在你的过程中添加 ``{.effects.}`` 编译指示语句, 编译器将输出所有推断的效果直到那一点(异常跟踪是Nim效果系统的一部分)。 查找proc引发的异常列表的另一种更迂回的方法是使用Nim ``doc2`` 命令,该命令为整个模块生成文档,并使用引发的异常列表来装饰所有过程。 您可以在手册中阅读有关Nim的 `效果系统和相关编译指示的更多信息<manual.html#effect-system>`_ 。 泛型 ======== 泛型是Nim用 `类型化参数`:idx: 参数化过程,迭代器或类型的方法。它们对于高效型安全容器很有用: .. code-block:: nim :test: "nim c $1" type BinaryTree*[T] = ref object # 二叉树是左右子树用泛型参数 ``T`` 可能nil的泛型 le, ri: BinaryTree[T] data: T # 数据存储在节点 proc newNode*[T](data: T): BinaryTree[T] = # 节点构造 new(result) result.data = data proc add*[T](root: var BinaryTree[T], n: BinaryTree[T]) = # 插入节点 if root == nil: root = n else: var it = root while it != nil: # 比较数据; 使用对任何有 ``==`` and ``<`` 操作符的类型有用的泛型 ``cmp`` 过程 var c = cmp(it.data, n.data) if c < 0: if it.le == nil: it.le = n return it = it.le else: if it.ri == nil: it.ri = n return it = it.ri proc add*[T](root: var BinaryTree[T], data: T) = # 方便过程: add(root, newNode(data)) iterator preorder*[T](root: BinaryTree[T]): T = # 二叉树前序遍历。 # 因为递归迭代器没有实现,用显式的堆栈(更高效): var stack: seq[BinaryTree[T]] = @[root] while stack.len > 0: var n = stack.pop() while n != nil: yield n.data add(stack, n.ri) # 右子树push到堆栈 n = n.le # 跟随左指针 var root: BinaryTree[string] # 用 ``string`` 实例化一个二叉树 add(root, newNode("hello")) # 实例化 ``newNode`` 和 ``add`` add(root, "world") # 实例化第二个 ``add`` 过程 for str in preorder(root): stdout.writeLine(str) 该示例显示了通用二叉树。根据上下文,括号用于引入类型参数或实例化通用过程、迭代器或类型。如示例所示,泛型使用重载:使用“add”的最佳匹配。 序列的内置 ``add`` 过程没有隐藏,而是在 ``preorder`` 迭代器中使用。 模板 ========= 模板是一种简单的替换机制,可以在Nim的抽象语法树上运行。模板在编译器的语义传递中处理。它们与语言的其余部分很好地集成,并且没有C的预处理器宏缺陷。 要 *调用* 模板,将其作为过程。 Example: .. code-block:: nim template `!=` (a, b: untyped): untyped = # 此定义存在于system模块中 not (a == b) assert(5 != 6) # 编译器将其重写为:assert(not(5 == 6)) ``!=``, ``>``, ``>=``, ``in``, ``notin``, ``isnot`` 操作符实际是模板:这对重载自动可用的 ``==`` , ``!=`` 操作符有好处。 (除了IEEE浮点数 - NaN打破了基本的布尔逻辑。) ``a > b`` 变换成 ``b < a`` 。 ``a in b`` 变换成 ``contains(b, a)`` 。 ``notin`` 和 ``isnot`` 顾名思义。 模板对于延迟计算特别有用。看一个简单的日志记录过程: .. code-block:: nim :test: "nim c $1" const debug = true proc log(msg: string) {.inline.} = if debug: stdout.writeLine(msg) var x = 4 log("x has the value: " & $x) 这段代码有一个缺点:如果 ``debug`` 有一天设置为false,那么仍然会执行 ``$`` 和 ``&`` 操作! (程序的参数求值是 *急切* )。 将 ``log`` 过程转换为模板解决了这个问题: .. code-block:: nim :test: "nim c $1" const debug = true template log(msg: string) = if debug: stdout.writeLine(msg) var x = 4 log("x has the value: " & $x) 参数的类型可以是普通类型,也可以是元类型 ``untyped`` , ``typed`` 或 ``type`` 。 ``type`` 表示只有一个类型符号可以作为参数给出, ``untyped`` 表示符号查找,并且在表达式传递给模板之前不执行类型解析。 如果模板没有显式返回类型,则使用 ``void`` 与过程和方法保持一致。 要将一个语句块传递给模板,请使用 ``untyped`` 作为最后一个参数: .. code-block:: nim :test: "nim c $1" template withFile(f: untyped, filename: string, mode: FileMode, body: untyped) = let fn = filename var f: File if open(f, fn, mode): try: body finally: close(f) else: quit("cannot open: " & fn) withFile(txt, "ttempl3.txt", fmWrite): txt.writeLine("line 1") txt.writeLine("line 2") 在示例中,两个 ``writeLine`` 语句绑定到 ``body`` 参数。 ``withFile`` 模板包含样板代码,有助于避免忘记关闭文件的常见错误。 注意 ``let fn = filename`` 语句如何确保 ``filename`` 只被求值一次。 示例: 提升过程 ---------------------- .. code-block:: nim :test: "nim c $1" import math template liftScalarProc(fname) = ## 使用一个标量参数提升一个proc并返回一个 ## 标量值(例如 ``proc sssss[T](x: T): float``), ## 来提供模板过程可以处理单个seq[T]形参或嵌套seq[seq[]]或同样的类型 ## ## .. code-block:: Nim ## liftScalarProc(abs) ## 现在 abs(@[@[1,-2], @[-2,-3]]) == @[@[1,2], @[2,3]] proc fname[T](x: openarray[T]): auto = var temp: T type outType = type(fname(temp)) result = newSeq[outType](x.len) for i in 0..<x.len: result[i] = fname(x[i]) liftScalarProc(sqrt) # 让sqrt()可以用于序列 echo sqrt(@[4.0, 16.0, 25.0, 36.0]) # => @[2.0, 4.0, 5.0, 6.0] 编译成Javascript ========================= Nim代码可以编译成JavaScript。为了写JavaScript兼容的代码你要记住以下几个方面: - ``addr`` 和 ``ptr`` 在JavaScript中有略微不同的语义。你不确定它们是怎样编译成JavaScript,建议避免使用。 - 在JavaScript中的 ``cast[T](x)`` 被转换为 ``(x)`` ,除了在有符号/无符号整数之间进行转换,在这种情况下,它在C语言中表现为静态强制转换。 - ``cstring`` 在JavaScript中表示JavaScript字符串。 只有在语义上合适时才使用 ``cstring`` 是一个好习惯。例如。不要使用 ``cstring`` 作为二进制数据缓冲区。 Part 3 ====== 下一部分将是完全关于使用宏的元编程: `Part III <tut3.html>`_ <file_sep>/.github/ISSUE_TEMPLATE/bug_report.md --- name: Bug report about: Have you found an unexpected behavior? Use this template. title: Think about the title, twice labels: '' assignees: '' --- Function `echo` outputs the wrong string. ### Example ```nim echo "Hello World!" ``` ### Current Output ``` Hola mundo! ``` ### Expected Output ``` Hello World! ``` ### Possible Solution * In file xyz there is a call that might be the cause of it. ### Additional Information * It was working in version a.b.c * Issue #abc is related, but different because of ... * This issue is blocking my project xyz ``` $ nim -v Nim Compiler Version 0.1.2 ``` <file_sep>/changelogs/changelog_X_XX_X.md # vx.xx.x - yyyy-mm-dd ## Changes affecting backwards compatibility - Example item: `Foo` changed to `Bar`. ### Breaking changes in the standard library ### Breaking changes in the compiler ## Library additions - `set[T].len` is now an alias for `set[T].card` (cardinality) ## Library changes ## Language additions ## Language changes ### Tool changes ### Compiler changes ## Bugfixes <file_sep>/tinyc/config.h /* Modified to not rely on a configure script: */ #define CONFIG_SYSROOT "" #define TCC_VERSION "0.9.27" #if defined(WIN32) || defined(_WIN32) # define TCC_TARGET_PE 1 # define TCC_TARGET_I386 # define CONFIG_TCCDIR "." #elif defined(__i386__) # define CONFIG_USE_LIBGCC # define TCC_TARGET_I386 # define CONFIG_TCCDIR "/usr/local/lib/tcc" # define GCC_MAJOR 4 # define HOST_I386 1 #else # define CONFIG_USE_LIBGCC # define TCC_TARGET_X86_64 # define CONFIG_TCCDIR "/usr/local/lib/tcc" # define GCC_MAJOR 4 # define HOST_X86_64 1 #endif <file_sep>/doc/destructors.rst ================================== Nim析构函数与移动语义 ================================== :Authors: <NAME> :Version: |nimversion| .. contents:: 关于本文档 =================== 本文档描述了即将推出的Nim运行时,它不再使用经典的GC算法,而是基于析构函数和移动语义。 新运行时的优点是Nim程序无法访问所涉及的堆大小,并且程序更易于编写以有效使用多核机器。 作为一个很好的奖励,文件和套接字等不再需要手动“关闭”调用。 本文档旨在成为关于Nim中移动语义和析构函数如何工作的精确规范。 起因示例 ================== 使用此处描述的语言机制,自定义seq可以写为: .. code-block:: nim type myseq*[T] = object len, cap: int data: ptr UncheckedArray[T] proc `=destroy`*[T](x: var myseq[T]) = if x.data != nil: for i in 0..<x.len: `=destroy`(x[i]) dealloc(x.data) x.data = nil proc `=`*[T](a: var myseq[T]; b: myseq[T]) = # 自赋值不做任何事: if a.data == b.data: return `=destroy`(a) a.len = b.len a.cap = b.cap if b.data != nil: a.data = cast[type(a.data)](alloc(a.cap * sizeof(T))) for i in 0..<a.len: a.data[i] = b.data[i] proc `=sink`*[T](a: var myseq[T]; b: myseq[T]) = # 移动赋值 `=destroy`(a) a.len = b.len a.cap = b.cap a.data = b.data proc add*[T](x: var myseq[T]; y: sink T) = if x.len >= x.cap: resize(x) x.data[x.len] = y inc x.len proc `[]`*[T](x: myseq[T]; i: Natural): lent T = assert i < x.len x.data[i] proc `[]=`*[T](x: var myseq[T]; i: Natural; y: sink T) = assert i < x.len x.data[i] = y proc createSeq*[T](elems: varargs[T]): myseq[T] = result.cap = elems.len result.len = elems.len result.data = cast[type(result.data)](alloc(result.cap * sizeof(T))) for i in 0..<result.len: result.data[i] = elems[i] proc len*[T](x: myseq[T]): int {.inline.} = x.len 生命周期跟踪钩子 ======================= Nim的标准 ``string`` 和 ``seq`` 类型以及其他标准集合的内存管理是通过所谓的 ``生命周期跟踪钩子`` 或 ``类型绑定运算符`` 执行的。 每个(通用或具体)对象类型有3个不同的钩子 ``T``( ``T`` 也可以是 ``distinct`` 类型),由编译器隐式调用。 (注意:这里的“钩子”一词并不表示任何类型的动态绑定或运行时间接,隐式调用是静态绑定的,可能是内联的。) (Note: The word "hook" here does not imply any kind of dynamic binding or runtime indirections, the implicit calls are statically bound and potentially inlined.) `=destroy` 钩子 --------------- `=destroy` 钩子释放对象的相关内存并释放其他相关资源。当变量超出范围或者声明它们的例程即将返回时,变量会通过此钩子被销毁。 这个类型 ``T`` 的钩子的原型需要是: .. code-block:: nim proc `=destroy`(x: var T) ``=destroy`` 中的一般形式如下: .. code-block:: nim proc `=destroy`(x: var T) = # first check if 'x' was moved to somewhere else: if x.field != nil: freeResource(x.field) x.field = nil `=sink` 钩子 ------------ `=sink` 钩子移动一个对象,资源从源头被移动并传递到目的地。 通过将对象设置为其默认值(对象状态开始的值),确保源的析构函数不会释放资源。 将对象``x``设置回其默认值写为``wasMoved(x)``。 这个类型``T``的钩子的原型需要是: .. code-block:: nim proc `=sink`(dest: var T; source: T) ``=sink`` 的一般形式如下: .. code-block:: nim proc `=sink`(dest: var T; source: T) = `=destroy`(dest) dest.field = source.field **注意**: ``=sink`` 不需要检查自赋值。 如何处理自赋值将在本文档后面解释。 `=` (复制) 钩子 --------------- Nim中的普通赋值是概念上地复制值。 对于无法转换为 ``=sink`` 操作的赋值,调用 ``=`` hook。 这个类型 ``T`` 的钩子的原型需要是: .. code-block:: nim proc `=`(dest: var T; source: T) ``=``的一般形式如下: .. code-block:: nim proc `=`(dest: var T; source: T) = # 阻止自赋值: if dest.field != source.field: `=destroy`(dest) dest.field = duplicateResource(source.field) ``=`` proc 可以用 ``{.error.}`` 标记。 然后,在编译时阻止任何可能导致副本的任务。 移动语义 ============== “移动”可以被视为优化的复制操作。 如果之后未使用复制操作的源,则可以通过移动替换副本。 本文档使用符号 ``lastReadOf(x)`` 来描述之后不使用 ``x` `。 此属性由静态流程控制分析计算,但也可以通过显式使用 ``system.move`` 来强制执行。 交换 ==== 需要检查自赋值以及是否需要销毁 ``=`` 和 ``= sink`` 中的先前对象,这是将 ``system.swap`` 视为内置原语的强大指标。只需通过 ``copyMem`` 或类似机制交换涉及对象中的每个字段。 换句话说, ``swap(a, b)`` is **不是** 实现为 ``let tmp = move(a); b = move(a); a = move(tmp)`` 。 这还有其他后果: * Nim的模型不支持包含指向同一对象的指针的对象。否则,交换的对象最终会处于不一致状态。 * Seqs可以在实现中使用 ``realloc`` 。 Sink形参 =============== 要将变量移动到集合中,通常会涉及 ``sink`` 形参。 之后不应使用传递给 ``sink`` 形参的位置。 这通过控制流图的静态分析来确保。 如果无法证明它是该位置的最后一次使用,则会执行复制,然后将此副本传递给接收器参数。 sink形参 *may* be consumed once in the proc's body but doesn't have to be consumed at all. The reason for this is that signatures like ``proc put(t: var Table; k: sink Key, v: sink Value)`` should be possible without any further overloads and ``put`` might not take owership of ``k`` if ``k`` already exists in the table. Sink parameters enable an affine type system, not a linear type system. The employed static analysis is limited and only concerned with local variables; however object and tuple fields are treated as separate entities: .. code-block:: nim proc consume(x: sink Obj) = discard "no implementation" proc main = let tup = (Obj(), Obj()) consume tup[0] # ok, only tup[0] was consumed, tup[1] is still alive: echo tup[1] Sometimes it is required to explicitly ``move`` a value into its final position: .. code-block:: nim proc main = var dest, src: array[10, string] # ... for i in 0..high(dest): dest[i] = move(src[i]) An implementation is allowed, but not required to implement even more move optimizations (and the current implementation does not). 重写规则 ============= **注意**: 允许两种不同的实施策略: 1. 生成的 ``finally`` 部分可以是一个环绕整个过程体的单个部分。 2. The produced ``finally`` section is wrapped around the enclosing scope. The current implementation follows strategy (1). This means that resources are not destroyed at the scope exit, but at the proc exit. :: var x: T; stmts --------------- (destroy-var) var x: T; try stmts finally: `=destroy`(x) g(f(...)) ------------------------ (nested-function-call) g(let tmp; bitwiseCopy tmp, f(...); tmp) finally: `=destroy`(tmp) x = f(...) ------------------------ (function-sink) `=sink`(x, f(...)) x = lastReadOf z ------------------ (move-optimization) `=sink`(x, z) wasMoved(z) v = v ------------------ (self-assignment-removal) discard "nop" x = y ------------------ (copy) `=`(x, y) f_sink(g()) ----------------------- (call-to-sink) f_sink(g()) f_sink(notLastReadOf y) -------------------------- (copy-to-sink) (let tmp; `=`(tmp, y); f_sink(tmp)) f_sink(lastReadOf y) ----------------------- (move-to-sink) f_sink(y) wasMoved(y) Object and array construction ============================= Object and array construction is treated as a function call where the function has ``sink`` parameters. Destructor removal ================== ``wasMoved(x);`` followed by a `=destroy(x)` operation cancel each other out. An implementation is encouraged to exploit this in order to improve efficiency and code sizes. Self assignments ================ ``=sink`` in combination with ``wasMoved`` can handle self-assignments but it's subtle. The simple case of ``x = x`` cannot be turned into ``=sink(x, x); wasMoved(x)`` because that would lose ``x``'s value. The solution is that simple self-assignments are simply transformed into an empty statement that does nothing. The complex case looks like a variant of ``x = f(x)``, we consider ``x = select(rand() < 0.5, x, y)`` here: .. code-block:: nim proc select(cond: bool; a, b: sink string): string = if cond: result = a # moves a into result else: result = b # moves b into result proc main = var x = "abc" var y = "xyz" # possible self-assignment: x = select(true, x, y) Is transformed into: .. code-block:: nim proc select(cond: bool; a, b: sink string): string = try: if cond: `=sink`(result, a) wasMoved(a) else: `=sink`(result, b) wasMoved(b) finally: `=destroy`(b) `=destroy`(a) proc main = var x: string y: string try: `=sink`(x, "abc") `=sink`(y, "xyz") `=sink`(x, select(true, let blitTmp = x wasMoved(x) blitTmp, let blitTmp = y wasMoved(y) blitTmp)) echo [x] finally: `=destroy`(y) `=destroy`(x) As can be manually verified, this transformation is correct for self-assignments. Lent type ========= ``proc p(x: sink T)`` means that the proc ``p`` takes ownership of ``x``. To eliminate even more creation/copy <-> destruction pairs, a proc's return type can be annotated as ``lent T``. This is useful for "getter" accessors that seek to allow an immutable view into a container. The ``sink`` and ``lent`` annotations allow us to remove most (if not all) superfluous copies and destructions. ``lent T`` is like ``var T`` a hidden pointer. It is proven by the compiler that the pointer does not outlive its origin. No destructor call is injected for expressions of type ``lent T`` or of type ``var T``. .. code-block:: nim type Tree = object kids: seq[Tree] proc construct(kids: sink seq[Tree]): Tree = result = Tree(kids: kids) # converted into: `=sink`(result.kids, kids); wasMoved(kids) proc `[]`*(x: Tree; i: int): lent Tree = result = x.kids[i] # borrows from 'x', this is transformed into: result = addr x.kids[i] # This means 'lent' is like 'var T' a hidden pointer. # Unlike 'var' this hidden pointer cannot be used to mutate the object. iterator children*(t: Tree): lent Tree = for x in t.kids: yield x proc main = # everything turned into moves: let t = construct(@[construct(@[]), construct(@[])]) echo t[0] # accessor does not copy the element! Owned refs ========== Let ``W`` be an ``owned ref`` type. Conceptually its hooks look like: .. code-block:: nim proc `=destroy`(x: var W) = if x != nil: assert x.refcount == 0, "dangling unowned pointers exist!" `=destroy`(x[]) x = nil proc `=`(x: var W; y: W) {.error: "owned refs can only be moved".} proc `=sink`(x: var W; y: W) = `=destroy`(x) bitwiseCopy x, y # raw pointer copy Let ``U`` be an unowned ``ref`` type. Conceptually its hooks look like: .. code-block:: nim proc `=destroy`(x: var U) = if x != nil: dec x.refcount proc `=`(x: var U; y: U) = # Note: No need to check for self-assignments here. if y != nil: inc y.refcount if x != nil: dec x.refcount bitwiseCopy x, y # raw pointer copy proc `=sink`(x: var U, y: U) {.error.} # Note: Moves are not available. Hook lifting ============ The hooks of a tuple type ``(A, B, ...)`` are generated by lifting the hooks of the involved types ``A``, ``B``, ... to the tuple type. In other words, a copy ``x = y`` is implemented as ``x[0] = y[0]; x[1] = y[1]; ...``, likewise for ``=sink`` and ``=destroy``. Other value-based compound types like ``object`` and ``array`` are handled correspondingly. For ``object`` however, the compiler generated hooks can be overridden. This can also be important to use an alternative traversal of the involved datastructure that is more efficient or in order to avoid deep recursions. Hook generation =============== The ability to override a hook leads to a phase ordering problem: .. code-block:: nim type Foo[T] = object proc main = var f: Foo[int] # error: destructor for 'f' called here before # it was seen in this module. proc `=destroy`[T](f: var Foo[T]) = discard The solution is to define ``proc `=destroy`[T](f: var Foo[T])`` before it is used. The compiler generates implicit hooks for all types in *strategic places* so that an explicitly provided hook that comes too "late" can be detected reliably. These *strategic places* have been derived from the rewrite rules and are as follows: - In the construct ``let/var x = ...`` (var/let binding) hooks are generated for ``typeof(x)``. - In ``x = ...`` (assignment) hooks are generated for ``typeof(x)``. - In ``f(...)`` (function call) hooks are generated for ``typeof(f(...))``. - For every sink parameter ``x: sink T`` the hooks are generated for ``typeof(x)``. nodestroy pragma ================ The experimental `nodestroy`:idx: pragma inhibits hook injections. This can be used to specialize the object traversal in order to avoid deep recursions: .. code-block:: nim type Node = ref object x, y: int32 left, right: owned Node type Tree = object root: owned Node proc `=destroy`(t: var Tree) {.nodestroy.} = # use an explicit stack so that we do not get stack overflows: var s: seq[owned Node] = @[t.root] while s.len > 0: let x = s.pop if x.left != nil: s.add(x.left) if x.right != nil: s.add(x.right) # free the memory explicit: dispose(x) # notice how even the destructor for 's' is not called implicitly # anymore thanks to .nodestroy, so we have to call it on our own: `=destroy`(s) As can be seen from the example, this solution is hardly sufficient and should eventually be replaced by a better solution. <file_sep>/doc/gc.rst ========================== Nim's Garbage Collector ========================== :Author: <NAME> :Version: |nimversion| .. "The road to hell is paved with good intentions." Introduction ============ This document describes how the GC works and how to tune it for (soft) `realtime systems`:idx:. The basic algorithm is *Deferred Reference Counting* with cycle detection. References on the stack are not counted for better performance (and easier C code generation). Cycle detection is currently done by a simple mark&sweep GC that has to scan the full (thread local heap). ``--gc:v2`` replaces this with an incremental mark and sweep. That it is not production ready yet, however. The GC is only triggered in a memory allocation operation. It is not triggered by some timer and does not run in a background thread. To force a full collection call ``GC_fullCollect``. Note that it is generally better to let the GC do its work and not enforce a full collection. Cycle collector =============== The cycle collector can be en-/disabled independently from the other parts of the GC with ``GC_enableMarkAndSweep`` and ``GC_disableMarkAndSweep``. Realtime support ================ To enable realtime support, the symbol `useRealtimeGC`:idx: needs to be defined via ``--define:useRealtimeGC`` (you can put this into your config file as well). With this switch the GC supports the following operations: .. code-block:: nim proc GC_setMaxPause*(maxPauseInUs: int) proc GC_step*(us: int, strongAdvice = false, stackSize = -1) The unit of the parameters ``maxPauseInUs`` and ``us`` is microseconds. These two procs are the two modus operandi of the realtime GC: (1) GC_SetMaxPause Mode You can call ``GC_SetMaxPause`` at program startup and then each triggered GC run tries to not take longer than ``maxPause`` time. However, it is possible (and common) that the work is nevertheless not evenly distributed as each call to ``new`` can trigger the GC and thus take ``maxPause`` time. (2) GC_step Mode This allows the GC to perform some work for up to ``us`` time. This is useful to call in a main loop to ensure the GC can do its work. To bind all GC activity to a ``GC_step`` call, deactivate the GC with ``GC_disable`` at program startup. If ``strongAdvice`` is set to ``true``, GC will be forced to perform collection cycle. Otherwise, GC may decide not to do anything, if there is not much garbage to collect. You may also specify the current stack size via ``stackSize`` parameter. It can improve performance, when you know that there are no unique Nim references below certain point on the stack. Make sure the size you specify is greater than the potential worst case size. These procs provide a "best effort" realtime guarantee; in particular the cycle collector is not aware of deadlines yet. Deactivate it to get more predictable realtime behaviour. Tests show that a 2ms max pause time will be met in almost all cases on modern CPUs (with the cycle collector disabled). Time measurement ---------------- The GC's way of measuring time uses (see ``lib/system/timers.nim`` for the implementation): 1) ``QueryPerformanceCounter`` and ``QueryPerformanceFrequency`` on Windows. 2) ``mach_absolute_time`` on Mac OS X. 3) ``gettimeofday`` on Posix systems. As such it supports a resolution of nanoseconds internally; however the API uses microseconds for convenience. Define the symbol ``reportMissedDeadlines`` to make the GC output whenever it missed a deadline. The reporting will be enhanced and supported by the API in later versions of the collector. Tweaking the GC --------------- The collector checks whether there is still time left for its work after every ``workPackage``'th iteration. This is currently set to 100 which means that up to 100 objects are traversed and freed before it checks again. Thus ``workPackage`` affects the timing granularity and may need to be tweaked in highly specialized environments or for older hardware. Keeping track of memory ----------------------- If you need to pass around memory allocated by Nim to C, you can use the procs ``GC_ref`` and ``GC_unref`` to mark objects as referenced to avoid them being freed by the GC. Other useful procs from `system <system.html>`_ you can use to keep track of memory are: * ``getTotalMem()`` Returns the amount of total memory managed by the GC. * ``getOccupiedMem()`` Bytes reserved by the GC and used by objects. * ``getFreeMem()`` Bytes reserved by the GC and not in use. These numbers are usually only for the running thread, not for the whole heap, with the exception of ``--gc:boehm`` and ``--gc:go``. In addition to ``GC_ref`` and ``GC_unref`` you can avoid the GC by manually allocating memory with procs like ``alloc``, ``allocShared``, or ``allocCStringArray``. The GC won't try to free them, you need to call their respective *dealloc* pairs when you are done with them or they will leak. Heap dump ========= The heap dump feature is still in its infancy, but it already proved useful for us, so it might be useful for you. To get a heap dump, compile with ``-d:nimTypeNames`` and call ``dumpNumberOfInstances`` at a strategic place in your program. This produces a list of used types in your program and for every type the total amount of object instances for this type as well as the total amount of bytes these instances take up. This list is currently unsorted! You need to use external shell script hacking to sort it. The numbers count the number of objects in all GC heaps, they refer to all running threads, not only to the current thread. (The current thread would be the thread that calls ``dumpNumberOfInstances``.) This might change in later versions. Garbage collector options ------------------------- You can choose which garbage collector to use when compiling source code, you can pass ``--gc:`` on the compile command with the choosed garbage collector. - ``--gc:refc`` Deferred `reference counting <https://en.wikipedia.org/wiki/Reference_counting>`_ with cycle detection, `thread local heap <https://en.wikipedia.org/wiki/Heap_(programming)>`_, default. - ``--gc:markAndSweep`` `Mark-And-Sweep <https://en.wikipedia.org/wiki/Tracing_garbage_collection#Copying_vs._mark-and-sweep_vs._mark-and-don't-sweep>`_ based garbage collector, `thread local heap <https://en.wikipedia.org/wiki/Heap_(programming)>`_. - ``--gc:boehm`` `Boehm <https://en.wikipedia.org/wiki/Boehm_garbage_collector>`_ based garbage collector, `stop-the-world <https://en.wikipedia.org/wiki/Tracing_garbage_collection#Stop-the-world_vs._incremental_vs._concurrent>`_, `shared heap <https://en.wikipedia.org/wiki/Heap_(programming)>`_. - ``--gc:go`` Go lang like garbage collector, `stop-the-world <https://en.wikipedia.org/wiki/Tracing_garbage_collection#Stop-the-world_vs._incremental_vs._concurrent>`_, `shared heap <https://en.wikipedia.org/wiki/Heap_(programming)>`_. - ``--gc:regions`` `Stack <https://en.wikipedia.org/wiki/Memory_management#Stack_allocation>`_ based garbage collector. - ``--gc:none`` No garbage collector. The same Nim code can be compiled to use any of the garbage collectors; the Nim syntax generally will not change from one garbage collector to another. No garbage collector is used for `JavaScript and NodeJS <backends.html#backends-the-javascript-target>`_ compilation targets. `NimScript <nims.html>`_ target uses Nim VM garbage collector. If you are new to Nim and just starting, the default garbage collector is balanced to fit most common use cases. <file_sep>/doc/manual.rst ========== Nim手册 ========== :Authors: <NAME>, <NAME> :Version: |nimversion| .. contents:: "复杂度"很像"能量": 你可以将它从最终用户转移到一个或多个其他玩家,但总量对于给定的任务保持不变。-- Ran 关于本文 =================== **注意** : 这份文件是草案,Nim的一些功能可能需要更精确的措辞。本手册不断发展为合适的规范。 **注意** : Nim的实验特性在 `这里 <manual_experimental.html>`_ 。 本文描述Nim语言的词汇、语法,和语义。 学习如何编译Nim程序和生成文档见 `Compiler User Guide <nimc.html>`_ 和 `DocGen Tools Guide <docgen.html>`_ 。 语言构造用扩展巴科斯范式(BNF)解释,其中 ``(a)*`` 表示 0 或者更多 ``a``, ``a+`` 表示1或更多 ``a``, 以及 ``(a)?`` 表示可选 *a* 。小括号用来对元素进行分组。 ``&`` 是先行操作符; ``&a`` 表示需要 ``a`` 但不被消耗。它将在下列规则中消耗。 ``|``, ``/`` 符号用于标记可选并且优先级最低。 ``/`` 是要求解析器尝试给定顺序的可选项的有序选择。 ``/`` 常用于确保语法没有歧义。 非终端符以小写字母开始,抽象终端符用大写。 逐字终端符(包括关键字)用 ``'`` 引用。示例:: ifStmt = 'if' expr ':' stmts ('elif' expr ':' stmts)* ('else' stmts)? 二元操作符 ``^*`` 用于由第二个实参分隔的0或多次出现的简写;不像 ``^+`` 表示1或多个出现: ``a ^+ b`` 是 ``a (b a)*`` 的简写 ``a ^* b`` 是 ``(a (b a)*)?`` 的简写。示例:: arrayConstructor = '[' expr ^* ',' ']' Nim的其他部分,如作用域规则或运行时语义,都是非正式描述的。 定义 =========== Nim代码指定一个计算,该计算作用于由称为 `位置`:idx: 的组件组成的内存。 变量基本上是位置的名称。每个变量和位置都是某种 `类型`:idx: 。 变量类型叫做 `静态类型`:idx: ,位置的类型叫做 `动态类型`:idx: 。 如果静态类型和动态类型不一样,它是动态类型的一个超类型或子类型。 `标识符`:idx: 是声明为变量,类型,过程等的名称的符号。 声明适用的程序区域叫做 `作用域`:idx: 。作用域可以嵌套。 标识符的含义由声明标识符的最小封闭范围确定,除非重载解析规则另有说明。 表达式指定生成值或位置的计算。产生位置的表达式叫 `左值`:idx: 。左值可以表示位置或位置包含的值,具体取决于上下文。 Nim `程序`:idx: 由一个或多个包含Nim代码的文本 `源文件`:idx: 构成。 它由Nim `编译器`:idx: 处理成一个 `可执行文件`:idx: 。 可执行文件的类型取决于编译器实现; 例如它可以是原生二进制或JavaScript源代码。 在典型的Nim程序中,多数代码编译成可执行文件。 但是,某些代码可以在 `编译期`:idx: 执行 。 这可以包括宏定义使用的常量表达式,宏定义,和Nim过程。 编译期支持大部分Nim语言,但有一些限制 -- 详见 `Restrictions on Compile-Time Execution <#restrictions-on-compileminustime-execution>`_ 。 我们用术语 `进行时`:idx: 来涵盖可执行文件中的编译时执行和代码执行。 编译器把Nim源代码解析为称为 `抽象语法树`:idx: (`AST`:idx:) 的内部数据结构 。 然后,在执行代码或编译成可执行文件前,通过 `语义分析`:idx: 变换AST。 这会添加语义信息,诸如表达式类型、标识符含义,以及某些情况下的表达式值。 语义分析期间的错误叫做 `静态错误`:idx: 。 未另行指定时,本手册中描述的错误是静态错误。 `运行时检查错误`:idx: 是实现在运行时检查并报告的错误。 报错此类错误的方法是通过 *引发异常* 或 *以致命错误退出* 。 但是,该实现提供了禁用这些 `运行时检查`:idx: 的方法 . 有关详细信息,请参阅 pragmas_ 部分。 检查的运行时错误是导致异常还是致命错误取决于实现。 因此以下程序无效;即使代码声称从越界数组访问中捕获 `IndexError` ,编译器也可以选择允许程序退出致命错误。 .. code-block:: nim var a: array[0..1, char] let i = 5 try: a[i] = 'N' except IndexError: echo "invalid index" `未经检查的运行时错误`:idx: 是一个不能保证被检测到的错误,并且可能导致任意的计算后续行为。 如果仅使用 `safe`:idx: 语言功能并且未禁用运行时检查,则不会发生未经检查的运行时错误。 `常量表达式`:idx: 是一个表达式,其值可以在出现的代码的语义分析期间计算。 它不是左值也没有副作用。 常量表达式不仅限于语义分析的功能,例如常量折叠;他们可以使用编译时执行所支持的所有Nim语言功能。 由于常量表达式可以用作语义分析的输入(例如用于定义数组边界),因此这种灵活性要求编译器交错语义分析和编译时代码执行。 在源代码中从上到下和从左到右进行图像语义分析是非常准确的,在必要时交错编译时代码执行以计算后续语义分析所需的值。 我们将在本文档后面看到,宏调用不仅需要这种交错,而且还会产生语义分析不能完全从上到下,从左到右进行的情况。 词法分析 ================ 编码 -------- 所有Nim源文件都采用UTF-8编码(或其ASCII子集)。 其他编码不受支持。 可以使用任何标准平台行终端序列 - Unix使用ASCII LF(换行),Windows使用ASCII序列CR LF的(返回后跟换行),老的Macintosh使用ASCII CR(返回)字符。 无论什么平台,使用这些形式的效果是一样的。 缩进 ----------- Nim的标准语法描述了一个 `缩进敏感`:idx: 语言。 这意味着所有控制结构都可以通过缩进识别。 缩进仅由空格组成;制表符是不允许的。 缩进处理按如下方式实现:词法分析器使用前面的空格数注释以下标记;缩进不是一个单独的标记。 这个技巧允许只用1个先行标记解析Nim。 解析器使用由整数个空格组成的缩进堆栈级别。 缩进信息在解析器重要的位置上查询,否则被忽略:伪终端 ``IND{>}`` 表示由比在堆栈顶部更多的空格构成; ``IND{=}`` 缩进具有相同数量的空格。 ``DED`` 是描述从堆栈弹出一个值的运作的伪代码, ``IND{>}`` 意味着推到栈上。 使用这种表示法,我们现在可以轻松定义语法的核心:一个语句块(简化示例):: ifStmt = 'if' expr ':' stmt (IND{=} 'elif' expr ':' stmt)* (IND{=} 'else' ':' stmt)? simpleStmt = ifStmt / ... stmt = IND{>} stmt ^+ IND{=} DED # list of statements / simpleStmt # or a simple statement 注释 -------- 注释从字符串或字符字面值外的任何地方开始,并带有哈希字符 ``#`` 。 注释包含 `注释片段`:idx: 的连接。 评论文章以 `#` 开头,​​一直运行到行尾。 行尾字符属于该片段。 如果下一行只包含一个注释片段,而它与前一个片段之间没有其他符号,则它不会启动新注释: .. code-block:: nim i = 0 # 这是跨行的单个注释。 # 扫描器合并这个块。 # 注释从这里继续。 `文档注释`:idx: 由两个开始 ``##`` 。 文档注释是符号;它们仅允许出现在输入文件的某个地方,因为它们属于语法树。 多行注释 ------------------ 从版本0.13.0开始,Nim支持多行注释。 .. code-block:: nim #[注释这里. 多行 不是问题。]# 多行注释支持嵌套: .. code-block:: nim #[ #[ 在已经注释代码中的多行注释]# proc p[T](x: T) = discard ]# 多行文档注释并支持嵌套: .. code-block:: nim proc foo = ##[长文档注释。 ]## 标识符 & 关键字 ---------------------- Nim中的标识符可以是任何以字母开头的数字、字母 和下划线。但有以下限制: * 必须以字母开头 * 不能以下划线 ``_`` 结尾 * 不允许两个连续的下划线 ``_`` :: letter ::= 'A'..'Z' | 'a'..'z' | '\x80'..'\xff' digit ::= '0'..'9' IDENTIFIER ::= letter ( ['_'] (letter | digit) )* 目前,序数值> 127(非ASCII)的任何Unicode字符都被归类为 ``字母`` ,因此可能是标识符的一部分,但该语言的后续版本可能会指定某些Unicode字符来代替运算符字符。 下面预留的关键字不能用作标识符: .. code-block:: nim addr and as asm bind block break case cast concept const continue converter defer discard distinct div do elif else end enum except export finally for from func if import in include interface is isnot iterator let macro method mixin mod nil not notin object of or out proc ptr raise ref return shl shr static template try tuple type using var when while xor yield 有些关键字未使用;它们是为语言的未来发展而保留的。 标识符相等性 ------------------- 两个标识符被认为是相等的如果下列算法返回真: .. code-block:: nim proc sameIdentifier(a, b: string): bool = a[0] == b[0] and a.replace("_", "").toLowerAscii == b.replace("_", "").toLowerAscii 这意味着只有首字母大小写敏感。 其他字母在ASCII范围内不区分大小写,并且忽略下划线。 这种相当不正统的标识符比较方法称为 `部分不区分大小写`:idx: 并且具有优于传统区分大小写的一些优点: 它允许程序员大多使用他们自己喜欢的拼写样式,无论是humpStyle还是snake_style,不同程序员编写的库不能使用不兼容的约定。 Nim感知编辑器或IDE可以将标识符显示为首选。 另一个优点是它使程序员不必记住标识符的确切拼写。关于第一个字母的例外允许明确地解析像 ``var foo:Foo`` 这样的公共代码。 请注意,此规则也适用于关键字,这意味着 ``notin`` 和 ``notIn`` 以及 ``not_in`` 是相同的, (全小写版本 (``notin``, ``isnot``) 是写关键字的首选方式)。 从历史上看,Nim是一种完全 `风格不敏感`:idx: 语言。 这意味着它不区分大小写并且忽略了下划线,并且 ``foo`` 和 ``Foo`` 之间甚至没有区别。 字符串字面值 --------------- 语法中的终端符号: ``STR_LIT`` 。 字符串字面值可以通过匹配双引号来分隔,并且可以包含以下 `转义序列`:idx: : ================== =================================================== 转义序列 含义 ================== =================================================== ``\p`` 平台特定的换行: CRLF on Windows, LF on Unix ``\r``, ``\c`` `回车`:idx: ``\n``, ``\l`` `换行`:idx: (通常叫做 `新行`:idx:) ``\f`` `换页`:idx: ``\t`` `制表符`:idx: ``\v`` `垂直制表符`:idx: ``\\`` `反斜线`:idx: ``\"`` `双引号`:idx: ``\'`` `单引号`:idx: ``\`` '0'..'9'+ `十进制值的字符d`:idx:; 后跟的所有十进制数字都用于该字符 ``\a`` `告警`:idx: ``\b`` `退格`:idx: ``\e`` `退出`:idx: `[ESC]`:idx: ``\x`` HH `带十六进制值的字符HH`:idx:; 只允许两位十六进制数字 ``\u`` HHHH `具有十六进制值的unicode代码点HHHH`:idx: ; 只允许四位十六进制数字 ``\u`` {H+} `unicode代码点`:idx:; 用 ``{}`` 括起来的所有十六进制数字都用于代码点 ================== =================================================== Nim中的字符串可以包含任何8位值,甚至是嵌入的零。 但是,某些操作可能会将第一个二进制零解释为终止符。 三引用字符串字面值 ----------------------------- 语法中的终端符号: ``TRIPLESTR_LIT``. 字符串字面值也可以用三个双引号分隔 ``"""`` ... ``"""`` 。 这种形式的字面值可能会持续几行,可能包含 ``"`` 并且不解释任何转义序列。 为方便起见,当开头的 ``"""`` 后面跟一个换行符 (开头 ``"""`` 和换行符之间可能有空格)时,换行符(和前面的空格)不包含在字符串。 字符串字面值的结尾由模式定义 ``"""[^"]``, 所以: .. code-block:: nim """"long string within quotes"""" 生成:: "long string within quotes" 原始字符串字面值 ------------------- 语法中的终端符号: ``RSTR_LIT``. 还有原始字符串字面值,前面带有字母 ``r`` (or ``R``) 并通过匹配双引号(就像普通的字符串字面值一样)分隔并且不解释转义序列。 这对于正则表达式或Windows路径特别方便: .. code-block:: nim var f = openFile(r"C:\texts\text.txt") # 原始字符串, 所以 ``\t`` 不是制表符。 为了在原始字符串中生成一个单独的 ``"`` , 必须使用两个: .. code-block:: nim r"a""b" Produces:: a"b ``r""""`` 这个符号是不可能的,因为三个引号引用了三引号字符串字面值。 ``r"""`` 与 ``"""`` 相同,因为三重引用的字符串字面值也不解释转义序列。 广义原始字符串字面值 ------------------------------- 语法中的终端符号: ``GENERALIZED_STR_LIT``, ``GENERALIZED_TRIPLESTR_LIT`` 。 ``标识符"字符串字面值"`` 这种构造(标识符和开始引号之间没有空格)是广义原始字符串。 这是 ``identifier(r"string literal")`` 的缩写, 所以它表示一个过程调用原始字符串字面值作为唯一的参数。 广义原始字符串字面值特别便于将小型语言直接嵌入到Nim中(例如正则表达式)。 ``标识符"""字符串字面值"""`` 也存在。它是 ``标识符("""字符串字面值""")`` 的缩写。 字符字面值 ------------------ 字符字面值用单引号 ``''`` 括起来,并且可以包含与字符串相同的转义序列 - 有一个例外:平台依赖的 `newline`:idx: (``\p``) 是不允许的,因为它可能比一个字符宽(通常是CR / LF对)。 以下是对字符字面值有效的 `转义序列`:idx: : ================== =================================================== 转义序列 含义 ================== =================================================== ``\r``, ``\c`` `回车`:idx: ``\n``, ``\l`` `换行`:idx: ``\f`` `换页`:idx: ``\t`` `制表符`:idx: ``\v`` `垂直制表符`:idx: ``\\`` `反斜杠`:idx: ``\"`` `双引号`:idx: ``\'`` `单引号`:idx: ``\`` '0'..'9'+ `十进制值的字符d`:idx:; 后跟的所有十进制数字都用于该字符 ``\a`` `告警`:idx: ``\b`` `退格`:idx: ``\e`` `退出`:idx: `[ESC]`:idx: ``\x`` HH `十六进制字符HH`:idx:; 只允许两位数字 ================== =================================================== 字符不是Unicode字符,而是单个字节。 这样做的原因是效率:对于绝大多数用例,由于UTF-8是专门为此设计的,所得到的程序仍然可以正确处理UTF-8。 另一个原因是Nim因此可以依靠这个特性像其它算法一样有效地支持 ``array[char, int]`` 或 ``set[char]`` 。 `Rune` 类型用于Unicode字符,它可以表示任何Unicode字符。 ``Rune`` 在 `unicode module <unicode.html>`_ 声明。 数值常量 ------------------- 数值常量是单一类型,并具有以下形式:: hexdigit = digit | 'A'..'F' | 'a'..'f' octdigit = '0'..'7' bindigit = '0'..'1' HEX_LIT = '0' ('x' | 'X' ) hexdigit ( ['_'] hexdigit )* DEC_LIT = digit ( ['_'] digit )* OCT_LIT = '0' 'o' octdigit ( ['_'] octdigit )* BIN_LIT = '0' ('b' | 'B' ) bindigit ( ['_'] bindigit )* INT_LIT = HEX_LIT | DEC_LIT | OCT_LIT | BIN_LIT INT8_LIT = INT_LIT ['\''] ('i' | 'I') '8' INT16_LIT = INT_LIT ['\''] ('i' | 'I') '16' INT32_LIT = INT_LIT ['\''] ('i' | 'I') '32' INT64_LIT = INT_LIT ['\''] ('i' | 'I') '64' UINT_LIT = INT_LIT ['\''] ('u' | 'U') UINT8_LIT = INT_LIT ['\''] ('u' | 'U') '8' UINT16_LIT = INT_LIT ['\''] ('u' | 'U') '16' UINT32_LIT = INT_LIT ['\''] ('u' | 'U') '32' UINT64_LIT = INT_LIT ['\''] ('u' | 'U') '64' exponent = ('e' | 'E' ) ['+' | '-'] digit ( ['_'] digit )* FLOAT_LIT = digit (['_'] digit)* (('.' digit (['_'] digit)* [exponent]) |exponent) FLOAT32_SUFFIX = ('f' | 'F') ['32'] FLOAT32_LIT = HEX_LIT '\'' FLOAT32_SUFFIX | (FLOAT_LIT | DEC_LIT | OCT_LIT | BIN_LIT) ['\''] FLOAT32_SUFFIX FLOAT64_SUFFIX = ( ('f' | 'F') '64' ) | 'd' | 'D' FLOAT64_LIT = HEX_LIT '\'' FLOAT64_SUFFIX | (FLOAT_LIT | DEC_LIT | OCT_LIT | BIN_LIT) ['\''] FLOAT64_SUFFIX 从结果中可以看出,数值常数可以包含下划线以便于阅读。 整数和浮点字面值可以用十进制(无前缀),二进制(前缀 ``0b`` ),八进制(前缀 ``0o`` )和十六进制(前缀 ``0x`` )表示法给出。 每个定义的数字类型都有一个字面值。 以一撇开始的后缀 ('\'') 叫 `类型后缀`:idx: 。 没有类型后缀的字面值是整数类型,除非字面值包含点或 ``E|e`` ,在这种情况下它是 ``浮点`` 类型。 整数类型是 ``int`` 如果字面值在 ``low(i32)..high(i32)`` 范围,否则是 ``int64`` 。 为了符号方便,类型后缀的撇号是可选的,如果它没有歧义(只有具有类型后缀的十六进制浮点字面值可能是不明确的)。 类型后缀是: ================= ========================= 类型后缀 字面值类型 ================= ========================= ``'i8`` int8 ``'i16`` int16 ``'i32`` int32 ``'i64`` int64 ``'u`` uint ``'u8`` uint8 ``'u16`` uint16 ``'u32`` uint32 ``'u64`` uint64 ``'f`` float32 ``'d`` float64 ``'f32`` float32 ``'f64`` float64 ================= ========================= 浮点字面值也可以是二进制,八进制或十六进制表示法: 根据IEEE浮点标准, ``0B0_10001110100_0000101001000111101011101111111011000101001101001001'f64`` 约为 1.72826e35。 对字面值进行边界检查,以使它们适合数据类型。 非基数10字面值主要用于标志和位模式表示,因此边界检查是在位宽而非值范围上完成的。 如果字面值符合数据类型的位宽,则接受它。 因此:0b10000000'u8 == 0x80'u8 == 128,但是,0b10000000'i8 == 0x80'i8 == -1而不是导致溢出错误。 操作符 --------- Nim允许用户定义的运算符。运算符是以下字符的任意组合 = + - * / < > @ $ ~ & % | ! ? ^ . : \ 这些关键字也是操作符: ``and or not xor shl shr div mod in notin is isnot of``. `.`:tok: `=`:tok:, `:`:tok:, `::`:tok: 不作为一般操作符;它们用于其他符号用途。 ``*:`` 是一个特殊情况,被看作是 `*`:tok: 和 `:`:tok: 两个标记(为了支持 ``var v*: T``)。 ``not`` 关键字是一元操作符, ``a not b`` 解析成 ``a(not b)``, 不是 ``(a) not (b)`` 。 其它标记 ------------ 以下字符串表示其他标记:: ` ( ) { } [ ] , ; [. .] {. .} (. .) [: `切片`:idx: 运算符 `..`:tok: 优先于包含点的其它标记: `{..}`:tok: 是三个标记 `{`:tok:, `..`:tok:, `}`:tok: 而不是两个标记 `{.`:tok:, `.}`:tok: 。 句法 ====== 本节列出了Nim的标准语法。解析器如何处理缩进已在 `词法分析`_ 部分中描述。 Nim允许用户可定义的运算符。二元运算符具有11个不同的优先级。 结合律 ------------- 第一个字符是 ``^`` 的二元运算符是右结合,所有其他二元运算符都是左结合。 .. code-block:: nim proc `^/`(x, y: float): float = # 右关联除法运算符 result = x / y echo 12 ^/ 4 ^/ 8 # 24.0 (4 / 8 = 0.5, then 12 / 0.5 = 24.0) echo 12 / 4 / 8 # 0.375 (12 / 4 = 3.0, then 3 / 8 = 0.375) ---------- 一元运算符总是比任何二元运算符优先: ``$a + b`` is ``($a) + b`` 而不是 ``$(a + b)`` 。 如果一元运算符的第一个字符是 ``@`` 它是 `符印样`:idx: 运算符,比 ``主后缀`` 优先: ``@x.abc`` 解析成 ``(@x).abc`` 而 ``$x.abc`` 解析成 ``$(x.abc)`` 。 对于非关键字的二元运算符,优先级由以下规则确定: 以 ``->``, ``~>`` or ``=>`` 结尾的运算符称为 `箭头形`:idx:, 优先级最低。 如果操作符以 ``=`` 结尾,并且它的第一个字符不是 ``<``, ``>``, ``!``, ``=``, ``~``, ``?``, 它是一个 *赋值运算符* 具有第二低的优先级。 否则优先级由第一个字符决定。 ================ =============================================== ================== =============== 优先级 运算符 首字符 终端符号 ================ =============================================== ================== =============== 10 (highest) ``$ ^`` OP10 9 ``* / div mod shl shr %`` ``* % \ /`` OP9 8 ``+ -`` ``+ - ~ |`` OP8 7 ``&`` ``&`` OP7 6 ``..`` ``.`` OP6 5 ``== <= < >= > != in notin is isnot not of`` ``= < > !`` OP5 4 ``and`` OP4 3 ``or xor`` OP3 2 ``@ : ?`` OP2 1 *赋值运算符* (like ``+=``, ``*=``) OP1 0 (lowest) *箭头形操作符* (like ``->``, ``=>``) OP0 ================ =============================================== ================== =============== 运算符是否使用前缀运算符也受前面的空格影响(此版本的修改随版本0.13.0引入): .. code-block:: nim echo $foo # 解析成 echo($foo) 间距还决定了 ``(a, b)`` 是否被解析为调用的参数列表,或者它是否被解析为元组构造函数: .. code-block:: nim echo(1, 2) # 传1和2给echo .. code-block:: nim echo (1, 2) # 传元组(1, 2)给echo 语法 ------- 语法的起始符号是 ``module``. .. include:: grammar.txt :literal: 求值顺序 =================== 求值顺序是从左到右、从内到外,和大多数其他典型的命令式编程语言一样: .. code-block:: nim :test: "nim c $1" var s = "" proc p(arg: int): int = s.add $arg result = arg discard p(p(1) + p(2)) doAssert s == "123" 赋值也不例外,左侧表达式在右侧之前进行求值: .. code-block:: nim :test: "nim c $1" var v = 0 proc getI(): int = result = v inc v var a, b: array[0..2, int] proc someCopy(a: var int; b: int) = a = b a[getI()] = getI() doAssert a == [1, 0, 0] v = 0 someCopy(b[getI()], getI()) doAssert b == [1, 0, 0] 基本原理:与重载赋值或赋值类操作的一致性 ``a = b`` 可以读作 ``performSomeCopy(a, b)``. 常量和常量表达式 ================================== `常量`:idx: 是一个与常量表达式值绑定的符号。 常量表达式仅限于依赖于以下类别的值和操作,因为它们要么构建在语言中,要么在对常量表达式进行语义分析之前进行声明和求值: * 字面值 * 内置运算符 * 之前声明的常量和编译时变量 * 之前声明过的宏和模板 * 之前声明的过程除了可能修改编译时变量之外没有任何副作用 常量表达式可以包含可以在内部使用编译时支持的所有Nim功能的代码块(详见下一节)。 在这样的代码块中,可以声明变量然后稍后读取和更新它们,或者声明变量并将它们传递给修改它们的过程。 但是,此类块中的代码仍必须遵循上面列出的用于引用块外部的值和操作的限制。 访问和修改编译时变量的能力增加了常量表达式的灵活性。 例如,下面的代码在 **编译时** 打印Fibonacci数列的开头。 (这是对定义常量的灵活性的证明,而不是解决此问题的推荐样式。) .. code-block:: nim :test: "nim c $1" import strformat var fib_n {.compileTime.}: int var fib_prev {.compileTime.}: int var fib_prev_prev {.compileTime.}: int proc next_fib(): int = result = if fib_n < 2: fib_n else: fib_prev_prev + fib_prev inc(fib_n) fib_prev_prev = fib_prev fib_prev = result const f0 = next_fib() const f1 = next_fib() const display_fib = block: const f2 = next_fib() var result = fmt"Fibonacci sequence: {f0}, {f1}, {f2}" for i in 3..12: add(result, fmt", {next_fib()}") result static: echo display_fib 编译期执行限制 ====================================== 将在编译时执行的Nim代码不能使用以下语言功能: * 方法 * 闭包迭代器 * ``cast`` 运算符 * 引用(指针)类型 * 外部函数接口(FFI) 随着时间的推移,部分或全部这些限制可能会被取消。 类型 ===== 所有表达式都具有在语义分析期间已知的类型。 Nim是静态类型的。可以声明新类型,这实际上定义了可用于表示此自定义类型的标识符。 这些是主要的类型: * 序数类型(由整数,bool,字符,枚举(及其子范围)类型组成) * 浮点类型 * 字符串类型 * 结构化类型 * 引用 (指针)类型 * 过程类型 * 泛型类型 序数类型 ------------- 序数类型有以下特征: - 序数类型是可数和有序的。该属性允许定义函数的操作 ``inc``, ``ord``, ``dec`` 。 - 序数值具有最小可能值。尝试进一步向下计数低于最小值会产生已检查的运行时或静态错误。 - 序数值具有最大可能值。尝试计数超过最大值会产生已检查的运行时或静态错误。 整数,bool,字符和枚举类型(以及这些类型的子范围)属于序数类型。 出于简化实现的原因,类型 ``uint`` 和 ``uint64`` 不是序数类型。 (这将在该语言的更高版本中更改。) 如果基类型是序数类型,则不同类型是序数类型。 预定义整数类型 ------------------------- 这些整数类型是预定义的: ``int`` 通用有符号整数类型;它的大小取决于平台,并且与指针大小相同。 一般应该使用这种类型。 没有类型后缀的整数字面值是这种类型,如果它在 ``low(int32)... high(int32)`` 范围内,否则字面值的类型是 ``int64`` 。 intXX 附加的有符号整数类型的XX位使用此命名方案(例如:int16是16位宽整数)。 当前的实现支持 ``int8``, ``int16``, ``int32``, ``int64`` 。 这些类型的字面值后缀为'iXX。 ``uint`` 通用的 `无符号整型`:idx: ; 它的大小取决于平台,并且与指针大小相同。 类型后缀为 ``'u`` 的整数字面值就是这种类型。 uintXX 附加的无符号整数类型的XX位使用此命名方案(例如:uint16是16位宽的无符号整数)。 当前的实现支持 ``uint8``, ``uint16``, ``uint32``, ``uint64`` 。 这些类型的字面值具有后缀 'uXX 。 无符号操作被全面封装; 不会导致上溢或下溢。 除了有符号和无符号整数的常用算术运算符 (``+ - *`` etc.) 之外,还有一些运算符正式处理 *整型* 整数但将它们的参数视为 *无符号*: 它们主要用于向后与缺少无符号整数类型的旧版本语言的兼容性。 有符号整数的这些无符号运算使用 ``%`` 后缀作为约定: ====================== ====================================================== 操作符 含义 ====================== ====================================================== ``a +% b`` 无符号整型加法 ``a -% b`` 无符号整型减法 ``a *% b`` 无符号整型乘法 ``a /% b`` 无符号整型除法 ``a %% b`` 无符号整型取模 ``a <% b`` 无符号比较 ``a`` 和 ``b`` ``a <=% b`` 无符号比较 ``a`` 和 ``b`` ``ze(a)`` 用零填充 ``a`` 的位,直到它具有 ``int`` 类型的宽度 ``toU8(a)`` 8位无符号转换 ``a`` (仍然是 ``int8`` 类型) ``toU16(a)`` 16位无符号转换 ``a`` (仍然是 ``int16`` 类型) ``toU32(a)`` 32位无符号转换 ``a`` (仍然是 ``int32`` 类型) ====================== ====================================================== `自动类型转换`:idx: 在使用不同类型的整数类型的表达式中执行:较小的类型转换为较大的类型。 `缩小类型转换`:idx: 将较大的类型转换为较小的类型(例如 ``int32 - > int16`` 。 `扩展类型转换`:idx: 将较小的类型转换为较大的类型(例如 ``int16 - > int32`` )。 Nim中只有扩展类型转型是 *隐式的*: .. code-block:: nim var myInt16 = 5i16 var myInt: int myInt16 + 34 # of type ``int16`` myInt16 + myInt # of type ``int`` myInt16 + 2i32 # of type ``int32`` 但是,如果字面值适合这个较小的类型并且这样的转换比其他隐式转换便宜,则 ``int`` 字面值可以隐式转换为较小的整数类型,因此 ``myInt16 + 34`` 产生 ``int16`` 结果。 有关详细信息,请参阅 `可转换关系 <#type-relations-convertible-relation>`_ 。 子范围类型 -------------- 子范围类型是序数或浮点类型(基本类型)的值范围。 要定义子范围类型,必须指定其限制值 - 类型的最低值和最高值。例如: .. code-block:: nim type Subrange = range[0..5] PositiveFloat = range[0.0..Inf] ``Subrange`` 是整数的子范围,只能保存0到5的值。 ``PositiveFloat`` 定义所有正浮点值的子范围。 NaN不属于任何浮点类型的子范围。 将任何其他值分配给类型为 ``Subrange`` 的变量是检查的运行时错误(如果可以在语义分析期间确定,则为静态错误)。 允许从基本类型到其子类型之一(反之亦然)的分配。 子范围类型与其基类型具有相同的大小(子范围示例中的 ``int`` )。 预定义浮点类型 -------------------------------- 以下浮点类型是预定义的: ``float`` 通用浮点类型;它的大小曾经是平台相关的,但现在它总是映射到 ``float64`` 。一般应该使用这种类型。 floatXX 实现可以使用此命名方案定义XX位的其他浮点类型(例如:float64是64位宽的浮点数)。 当前的实现支持 ``float32`` 和 ``float64`` 。 这些类型的字面值具有后缀 'fXX 。 执行具有不同类型浮点类型的表达式中的自动类型转换:有关更多详细信息,请参阅 `可转换关系` 。 在浮点类型上执行的算术遵循IEEE标准。 整数类型不会自动转换为浮点类型,反之亦然。 IEEE标准定义了五种类型的浮点异常: * 无效: 使用数学上无效的操作数的操作, 例如 0.0/0.0, sqrt(-1.0), 和log(-37.8). * 除以零:除数为零,且除数是有限的非零数,例如1.0 / 0.0。 * 溢出:操作产生的结果超出指数范围,例如MAXDOUBLE + 0.0000000000001e308。 * 下溢:操作产生的结果太小而无法表示为正常数字,例如,MINDOUBLE * MINDOUBLE。 * 不精确:操作产生的结果无法用无限精度表示,例如,输入中的2.0 / 3.0,log(1.1)和0.1。 IEEE异常在执行期间被忽略或映射到Nim异常: `FloatInvalidOpError`:idx:, `FloatDivByZeroError`:idx:, `FloatOverflowError`:idx:, `FloatUnderflowError`:idx:, 和 `FloatInexactError`:idx: 。 这些异常继承自 `FloatingPointError`:idx: 基类。 Nim提供了编译指示 `nanChecks`:idx: 和 `infChecks`:idx: 控制是否忽略IEEE异常或捕获Nim异常: .. code-block:: nim {.nanChecks: on, infChecks: on.} var a = 1.0 var b = 0.0 echo b / b # raises FloatInvalidOpError echo a / b # raises FloatOverflowError 在当前的实现中, ``FloatDivByZeroError`` 和 ``FloatInexactError`` 永远不会被引发。 ``FloatOverflowError`` 取代了 ``FloatDivByZeroError`` 。 还有一个 `floatChecks`:idx: 编译指示用作 ``nanChecks`` 和 ``infChecks`` 的快捷方式。 ``floatChecks`` 默认关闭。 受 ``floatChecks`` 编译指示影响的唯一操作是浮点类型的 ``+`` , ``-`` , ``*`` , ``/`` 运算符。 在语义分析期间,实现应始终使用最大精度来评估浮点指针值; 这表示在常量展开期间,表达式 ``0.09'f32 + 0.01'f32 == 0.09'f64 + 0.01'f64`` 求值为真。 布尔类型 ------------ 布尔类型在Nim中命名为 `bool`:idx: 并且可以是两个预定义值之一 ``true`` 和 ``false`` 。 ``while``, ``if``, ``elif``, ``when`` 中的语句需要是 ``bool`` 类型。 这种情况成立:: ord(false) == 0 and ord(true) == 1 布尔类型定义了运算符 ``not, and, or, xor, <, <=, >, >=, !=, ==`` 。 ``and`` 和 ``or`` 运算符执行短路求值。示例: .. code-block:: nim while p != nil and p.name != "xyz": # 如果 p == nil, p.name不被求值。 p = p.next bool类型的大小是一个字节。 字符类型 -------------- 字符类型在Nim中被命名为 ``char`` 。它的大小是一字节。 因此,它不能代表UTF-8字符,而是它的一部分。 这样做是出于效率:对于绝大多数用例,由于UTF-8是专门为此设计的,所得到的程序仍然可以正确处理UTF-8。 另一个原因是Nim可以有效地支持 ``array[char,int]`` 或 ``set[char]`` ,因为许多算法依赖于这个特性。 `Rune` 类型用于Unicode字符,它可以表示任何Unicode字符。 ``Rune`` 在 `unicode module <unicode.html>`_ 中声明。 枚举类型 ----------------- 枚举类型定义一个新类型,其值由指定的值组成。这些值是有序的。例: .. code-block:: nim type Direction = enum north, east, south, west 现在以下内容成立:: ord(north) == 0 ord(east) == 1 ord(south) == 2 ord(west) == 3 # 也允许: ord(Direction.west) == 3 因此, north < east < south < west 。 比较运算符可以与枚举类型一起使用。 枚举值也可以使用它所在的枚举类型 ``Direction.nort`` 来限定,而不是 ``north`` 等。 为了更好地与其他编程语言连接,可以为枚举类型的字段分配显式序数值。 但是,序数值必须按升序排列。 未明确给出序数值的字段被赋予前一个字段+ 1的值。 显式有序枚举可以有 *洞* : .. code-block:: nim type TokenType = enum a = 2, b = 4, c = 89 # 洞是合法的 但是,它不再是序数,因此不可能将这些枚举用作数组的索引类型。 过程 ``inc``, ``dec``, ``succ`` 和 ``pred`` 对于它们不可用。 编译器支持枚举的内置字符串化运算符 ``$`` 。 字符串化的结果可以通过显式给出要使用的字符串值来控制: .. code-block:: nim type MyEnum = enum valueA = (0, "my value A"), valueB = "value B", valueC = 2, valueD = (3, "abc") 从示例中可以看出,可以通过使用元组指定字段的序数值及其字符串值。 也可以只指定其中一个。 枚举可以使用 ``pure`` 编译指示进行标记,以便将其字段添加到特定模块特定的隐藏作用域,该作用域仅作为最后一次尝试进行查询。 只有没有歧义的符号才会添加到此范围。 但总是可以通过写为 ``MyEnum.value`` 的类型限定来访问: .. code-block:: nim type MyEnum {.pure.} = enum valueA, valueB, valueC, valueD, amb OtherEnum {.pure.} = enum valueX, valueY, valueZ, amb echo valueA # MyEnum.valueA echo amb # 错误:不清楚它是MyEnum.amb还是OtherEnum.amb echo MyEnum.amb # OK. 要使用枚举实现位字段,请参阅 `Bit fields <#set-type-bit-fields>`_ 字符串类型 ----------- 所有字符串字面值都是 ``string`` 类型。 Nim中的字符串与字符序列非常相似。 但是,Nim中的字符串都是以零结尾的并且具有长度字段。 可以用内置的 ``len`` 过程检索长度;长度永远不会计算终止零。 除非首先将字符串转换为 ``cstring`` 类型,否则无法访问终止零。 终止零确保可以在O(1)中完成此转换,无需任何分配。 字符串的赋值运算符始终复制字符串。 ``&`` 运算符拼接字符串。 大多数原生Nim类型支持使用特殊的 ``$`` proc转换为字符串。 例如,当调用 ``echo`` proc时,会调用参数的内置字符串化操作: .. code-block:: nim echo 3 # 为 `int` 调用 `$` 每当用户创建一个专门的对象时,该过程的实现提供了 ``string`` 表示。 .. code-block:: nim type Person = object name: string age: int proc `$`(p: Person): string = # `$` 始终返回字符串 result = p.name & " is " & $p.age & # we *need* the `$` in front of p.age which # is natively an integer to convert it to # a string " years old." 虽然也可以使用 ``$ p.name`` ,但字符串上的 ``$`` 操作什么都不做。 请注意,我们不能依赖于从 ``int`` 到 ``string`` 的自动转换,就像 ``echo`` 过程一样。 字符串按字典顺序进行比较。 所有比较运算符都可用。 字符串可以像数组一样索引(下限为0)。 与数组不同,它们可用于case语句: .. code-block:: nim case paramStr(i) of "-v": incl(options, optVerbose) of "-h", "-?": incl(options, optHelp) else: write(stdout, "invalid command line option!\n") 按照惯例,所有字符串都是UTF-8字符串,但不强制执行。 例如,从二进制文件读取字符串时,它们只是一个字节序列。 索引操作 ``s[i]`` 表示 ``s`` 的第i个 *char* ,而不是第i个 *unichar* 。 来自 `unicode module <unicode.html>`_ 的迭代器 ``runes`` 可用于迭代所有Unicode字符。 cstring类型 ------------ ``cstring`` 类型意味着 `compatible string` 是编译后端的字符串的原生表示。 对于C后端,``cstring`` 类型表示一个指向零终止char数组的指针,该数组与Ansi C中的 ``char*`` 类型兼容。 其主要目的在于与C轻松互通。 索引操作 ``s [i]`` 表示 ``s`` 的第i个 *char*;但是没有执行检查 ``cstring`` 的边界,使索引操作不安全。 为方便起见,Nim中的 ``string`` 可以隐式转换为 ``cstring`` 。 如果将Nim字符串传递给C风格的可变参数proc,它也会隐式转换为 ``cstring`` : .. code-block:: nim proc printf(formatstr: cstring) {.importc: "printf", varargs, header: "<stdio.h>".} printf("This works %s", "as expected") 即使转换是隐式的,它也不是 *安全的* :垃圾收集器不认为 ``cstring`` 是根,并且可能收集底层内存。 然而在实践中,这几乎从未发生过,因为GC保守地估计堆栈根。 可以使用内置过程 ``GC_ref`` 和 ``GC_unref`` 来保持字符串数据在少数情况下保持活动状态。 为返回字符串的cstrings定义了 `$` proc。因此,从cstring获取一个nim字符串: .. code-block:: nim var str: string = "Hello!" var cstr: cstring = str var newstr: string = $cstr 结构化类型 ---------------- 结构化类型的变量可以同时保存多个值。 结构化类型可以嵌套到无限级别。 数组、序列、元组、对象和集合属于结构化类型。 数组和序列类型 ------------------------ 数组是同类型的,这意味着数组中的每个元素都具有相同的类型。 数组总是具有指定为常量表达式的固定长度(开放数组除外)。 它们可以按任何序数类型索引。 参数 ``A`` 可以是 *开放数组* ,在这种情况下,它由0到 ``len(A)- 1`` 的整数索引。 数组表达式可以由数组构造函数 ``[]`` 构造。 数组表达式的元素类型是从第一个元素的类型推断出来的。 所有其他元素都需要隐式转换为此类型。 序列类似于数组,但动态长度可能在运行时期间发生变化(如字符串)。 序列实现为可增长的数组,在添加项目时分配内存块。 序列 ``S`` 始终用从0到 ``len(S)-1`` 的整数索引,并检查其边界。 序列可以由数组构造函数 ``[]`` 和数组一起构造,以序列运算符 ``@`` 。 为序列分配空间的另一种方法是调用内置的 ``newSeq`` 过程。 序列可以传递给 *开放数组* 类型的参数。 示例: .. code-block:: nim type IntArray = array[0..5, int] # an array that is indexed with 0..5 IntSeq = seq[int] # a sequence of integers var x: IntArray y: IntSeq x = [1, 2, 3, 4, 5, 6] # [] is the array constructor y = @[1, 2, 3, 4, 5, 6] # the @ turns the array into a sequence let z = [1.0, 2, 3, 4] # the type of z is array[0..3, float] 数组或序列的下限可以由内置的proc ``low()`` 接收,上限由 ``high()`` 接收。 长度可以由 ``len()`` 接收。序列或开放数组的 ``low()`` 总是返回0,因为这是第一个有效索引。 可以使用 ``add()`` proc或 ``&`` 运算符将元素追加到序列中,并使用 ``pop()`` proc删除(并获取)序列的最后一个元素。 符号 ``x [i]`` 可用于访问 ``x`` 的第i个元素。 数组始终是边界检查(静态或运行时)。可以通过编译指示禁用这些检查,或使用 ``--boundChecks:off`` 命令行开关调用编译器。 数组构造函数可以具有可读的显式索引: .. code-block:: nim type Values = enum valA, valB, valC const lookupTable = [ valA: "A", valB: "B", valC: "C" ] 如果省略索引,则使用 ``succ(lastIndex)`` 作为索引值: .. code-block:: nim type Values = enum valA, valB, valC, valD, valE const lookupTable = [ valA: "A", "B", valC: "C", "D", "e" ] 开放数组(openarray) ----------- 通常,固定大小的数组太不灵活了;程序应该能够处理不同大小的数组。 `开放数组`:idx: 类型只能用于参数。 开放数组总是从位置0开始用 ``int`` 索引。 ``len`` , ``low`` 和 ``high`` 操作也可用于开放数组。 具有兼容基类型的任何数组都可以传递给开放数组形参,无关索引类型。 除了数组序列之外,还可以将序列传递给开放数组参数。 开放数组类型不能嵌套: 不支持多维开放数组,因为这种需求很少并且不能有效地完成。 .. code-block:: nim proc testOpenArray(x: openArray[int]) = echo repr(x) testOpenArray([1,2,3]) # array[] testOpenArray(@[1,2,3]) # seq[] 可变参数 ------- ``varargs`` 参数是一个开放数组参数,它还允许将可变数量的参数传递给过程。 编译器隐式地将参数列表转换为数组: .. code-block:: nim proc myWriteln(f: File, a: varargs[string]) = for s in items(a): write(f, s) write(f, "\n") myWriteln(stdout, "abc", "def", "xyz") # 转换成: myWriteln(stdout, ["abc", "def", "xyz"]) 仅当varargs参数是过程头中的最后一个参数时,才会执行此转换。 也可以在此上下文中执行类型转换: .. code-block:: nim proc myWriteln(f: File, a: varargs[string, `$`]) = for s in items(a): write(f, s) write(f, "\n") myWriteln(stdout, 123, "abc", 4.0) # 转换成: myWriteln(stdout, [$123, $"def", $4.0]) 在这个例子中, ``$`` 应用于传递给参数 ``a`` 的任何参数。 (注意 ``$`` 对字符串是一个空操作。) 请注意,传递给 ``varargs`` 形参的显式数组构造函数不会隐式地构造另一个隐式数组: .. code-block:: nim proc takeV[T](a: varargs[T]) = discard takeV([123, 2, 1]) # takeV的T是"int", 不是"int数组" ``varargs[typed]`` 被特别对待:它匹配任意类型的参数的变量列表,但 *始终* 构造一个隐式数组。 这是必需的,以便内置的 ``echo`` proc执行预期的操作: .. code-block:: nim proc echo*(x: varargs[typed, `$`]) {...} echo @[1, 2, 3] # 打印 "@[1, 2, 3]" 而不是 "123" 未检查数组 ---------------- ``UncheckedArray[T]`` 类型是一种特殊的 ``数组`` ,编译器不检查它的边界。 这对于实现定制灵活大小的数组通常很有用。 另外,未检查数组转换为不确定大小的C数组: .. code-block:: nim type MySeq = object len, cap: int data: UncheckedArray[int] 大致生成C代码: .. code-block:: C typedef struct { NI len; NI cap; NI data[]; } MySeq; 未检查数组的基本类型可能不包含任何GC内存,但目前尚未检查。 **未来方向**: 应该在未经检查的数组中允许GC内存,并且应该有一个关于GC如何确定数组的运行时大小的显式注释。 元组和对象类型 ----------------------- 元组或对象类型的变量是异构存储容器。 元组或对象定义类型的各种命名 *字段* 。 元组还定义了字段的 *顺序* 。 元组用于异构存储类型,没有开销和很少的抽象可能性。 构造函数 ``()`` 可用于构造元组。 构造函数中字段的顺序必须与元组定义的顺序相匹配。 如果它们以相同的顺序指定相同类型的相同字段,则不同的元组类型 *等效* 。字段的 *名称* 也必须相同。 元组的赋值运算符会对每个组件进行复制。 对象的默认赋值运算符也会复制每一个组件。 在 `这里 <manual_experimental.html#type-bound-operations>`_ 描述了赋值运算符的重载。 .. code-block:: nim type Person = tuple[name: string, age: int] # 代表人的类型:人由名字和年龄组成 var person: Person person = (name: "Peter", age: 30) # 一样,但不太可读: person = ("Peter", 30) 可以使用括号和尾随逗号构造具有一个未命名字段的元组: .. code-block:: nim proc echoUnaryTuple(a: (int,)) = echo a[0] echoUnaryTuple (1,) 事实上,每个元组结构都允许使用尾随逗号。 实现将字段对齐以获得最佳访问性能。 对齐与C编译器的方式兼容。 为了与 ``object`` 声明保持一致, ``type`` 部分中的元组也可以用缩进而不是 ``[]`` 来定义: .. code-block:: nim type Person = tuple # 代表人的类型 name: string # 人由名字 age: natural # 和年龄组成 对象提供了元组不具备的许多功能。 对象提供继承和信息隐藏。 对象在运行时可以访问它们的类型,因此 ``of`` 运算符可用于确定对象的类型。 ``of`` 运算符类似于Java中的 ``instanceof`` 运算符。 .. code-block:: nim type Person = object of RootObj name*: string # *表示可以从其他模块访问`name` age: int # 没有*表示该字段已隐藏 Student = ref object of Person # 学生是人 id: int # 有个id字段 var student: Student person: Person assert(student of Student) # is true assert(student of Person) # also true 应该从定义模块外部可见的对象字段必须用 ``*`` 标记。 与元组相反,不同的对象类型永远不会 *等价* 。 没有祖先的对象是隐式的 ``final`` ,因此没有隐藏的类型字段。 可以使用 ``inheritable`` pragma来引入除 ``system.RootObj`` 之外的新根对象。 对象构造 ------------------- 对象也可以使用 `对象构造表达式`:idx: 创建, 具有语法 ``T(fieldA:valueA,fieldB:valueB,...)`` 其中 ``T`` 是 ``object`` 类型或 ``ref object`` 类型: .. code-block:: nim var student = Student(name: "Anton", age: 5, id: 3) 请注意,与元组不同,对象需要字段名称及其值。 对于 ``ref object`` 类型, ``system.new`` 是隐式调用的。 对象变体 --------------- 在需要简单变体类型的某些情况下,对象层次结构通常有点过了。 对象变体是通过用于运行时类型灵活性的枚举类型区分的标记联合,对照如在其他语言中找到的 *sum类型* 和 *代数数据类型(ADT)* 的概念。 一个示例: .. code-block:: nim # 这是一个如何在Nim中建模抽象语法树的示例 type NodeKind = enum # 不同的节点类型 nkInt, # 带有整数值的叶节点 nkFloat, # 带有浮点值的叶节点 nkString, # 带有字符串值的叶节点 nkAdd, # 加法 nkSub, # 减法 nkIf # if语句 Node = ref NodeObj NodeObj = object case kind: NodeKind # ``kind`` 字段是鉴别字段 of nkInt: intVal: int of nkFloat: floatVal: float of nkString: strVal: string of nkAdd, nkSub: leftOp, rightOp: Node of nkIf: condition, thenPart, elsePart: Node # 创建一个新case对象: var n = Node(kind: nkIf, condition: nil) # 访问n.thenPart是有效的,因为 ``nkIf`` 分支是活动的 n.thenPart = Node(kind: nkFloat, floatVal: 2.0) # 以下语句引发了一个 `FieldError` 异常,因为n.kind的值不合适且 ``nkString`` 分支未激活: n.strVal = "" # 无效:会更改活动对象分支: n.kind = nkInt var x = Node(kind: nkAdd, leftOp: Node(kind: nkInt, intVal: 4), rightOp: Node(kind: nkInt, intVal: 2)) # valid:不更改活动对象分支: x.kind = nkSub 从示例中可以看出,对象层次结构的优点是不需要在不同对象类型之间进行转换。 但是,访问无效对象字段会引发异常。 对象声明中 ``case`` 的语法紧跟着 ``case`` 语句的语法: ``case`` 部分中的分支也可以缩进。 在示例中, ``kind`` 字段称为 `鉴别字段`:idx: : 为安全起见,不能对其进行地址限制,并且对其赋值受到限制:新值不得导致活动对象分支发生变化。 此外,在对象构造期间指定特定分支的字段时,必须将相应的鉴别字段值指定为常量表达式。 而不是更改活动对象分支,将内存中的旧对象完全替换为新对象: .. code-block:: nim var x = Node(kind: nkAdd, leftOp: Node(kind: nkInt, intVal: 4), rightOp: Node(kind: nkInt, intVal: 2)) # 更改节点的内容: x[] = NodeObj(kind: nkString, strVal: "abc") 从版本0.20开始 ``system.reset`` 不能再用于支持对象分支的更改,因为这从来就不是完全内存安全的。 作为一项特殊规则,鉴别字段类型也可以使用 ``case`` 语句来限制。 如果 ``case`` 语句分支中的鉴别字段变量的可能值是所选对象分支的鉴别字段值的子集,则初始化被认为是有效的。 此分析仅适用于序数类型的不可变判别符,并忽略 ``elif`` 分支。 A small 示例: .. code-block:: nim let unknownKind = nkSub # 无效:不安全的初始化,因为类型字段不是静态已知的: var y = Node(kind: unknownKind, strVal: "y") var z = Node() case unknownKind of nkAdd, nkSub: # valid:此分支的可能值是nkAdd / nkSub对象分支的子集: z = Node(kind: unknownKind, leftOp: Node(), rightOp: Node()) else: echo "ignoring: ", unknownKind 集合类型 -------- .. include:: sets_fragment.txt 引用和指针类型 --------------------------- 引用(类似于其他编程语言中的指针)是引入多对一关系的一种方式。 这意味着不同的引用可以指向并修改内存中的相同位置(也称为 `别名`:idx: )。 Nim区分 `追踪`:idx:和 `未追踪`:idx: 引用。 未追踪引用也叫 *指针* 。 追踪引用指向垃圾回收堆中的对象,未追踪引用指向手动分配对象或内存中其它位置的对象。 因此,未追踪引用是 *不安全* 的。 然而对于某些访问硬件的低级操作,未追踪引用是不可避免的。 使用 **ref** 关键字声明追踪引用,使用 **ptr** 关键字声明未追踪引用。 通常, `ptr T` 可以隐式转换为 `pointer` 类型。 空的下标 ``[]`` 表示法可以用来取代引用, ``addr`` 程序返回一个对象的地址。 地址始终是未经过引用的参考。 因此, ``addr`` 的使用是 *不安全的* 功能。 ``.`` (访问元组和对象字段运算符)和 ``[]`` (数组/字符串/序列索引运算符)运算符对引用类型执行隐式解引用操作: .. code-block:: nim type Node = ref NodeObj NodeObj = object le, ri: Node data: int var n: Node new(n) n.data = 9 # 不必写n[].data; 实际上 n[].data是不鼓励的。 还对过程调用的第一个参数执行自动解引用。 但是目前这个功能只能通过 ``{.experimental:"implicitDeref".}`` 来启用: .. code-block:: nim {.experimental: "implicitDeref".} proc depth(x: NodeObj): int = ... var n: Node new(n) echo n.depth # 也不必写n[].depth 为了简化结构类型检查,递归元组无效: .. code-block:: nim # 无效递归 type MyTuple = tuple[a: ref MyTuple] 同样, ``T = ref T`` 是无效类型。 作为语法扩展 ``object`` 类型,如果在类型部分中通过 ``ref object`` 或 ``ptr object`` 符号声明,则可以是匿名的。 如果对象只应获取引用语义,则此功能非常有用: .. code-block:: nim type Node = ref object le, ri: Node data: int 要分配新的追踪对象,必须使用内置过程 ``new`` 。 为了处理未追踪的内存,可以使用过程 ``alloc`` , ``dealloc`` 和 ``realloc`` 。 系统模块的文档包含更多信息。 Nil --- 如果引用指向 *nothing* ,则它具有值 ``nil`` 。 ``nil`` 也是所有 ``ref`` 和 ``ptr`` 类型的默认值。 解除引用 ``nil`` 是一个不可恢复的致命运行时错误。 解除引用操作 ``p []`` 意味着 ``p`` 不是nil。 这可以通过实现来利用,以优化代码,如: .. code-block:: nim p[].field = 3 if p != nil: # 如果p为nil,``p []`` 会导致崩溃, # 所以我们知道 ``p`` 总不是nil。 action() Into: .. code-block:: nim p[].field = 3 action() *注意* :这与用于解引用NULL指针的C的“未定义行为”不具有可比性。 将GC内存和 ``ptr`` 混用 -------------------------------- 如果未追踪对象包含追踪对象(如追踪引用,字符串或序列),则需要特别小心:为了正确释放所有内容,必须在手动释放未追踪内存之前调用内置过程 ``GCunref`` : .. code-block:: nim type Data = tuple[x, y: int, s: string] # 为堆上的Data分配内存: var d = cast[ptr Data](alloc0(sizeof(Data))) # 在垃圾收集堆上创建一个新字符串: d.s = "abc" # 告诉GC不再需要该字符串: GCunref(d.s) # 释放内存: dealloc(d) 没有 ``GCunref`` 调用,为 ``d.s`` 字符串分配的内存永远不会被释放。 该示例还演示了低级编程的两个重要特性: ``sizeof`` proc以字节为单位返回类型或值的大小。 ``cast`` 运算符可以绕过类型系统:编译器被强制处理 ``alloc0`` 调用的结果(返回一个无类型的指针),就好像它是 ``ptr Data`` 类型。 只有在不可避免的情况下才能进行强转:它会破坏类型安全性并且错误可能导致隐蔽的崩溃。 **注意**: 该示例仅起作用,因为内存初始化为零( ``alloc0`` 而不是 ``alloc`` 执行此操作): ``d.s`` 因此初始化为二进制零,字符串赋值可以处理。 在将垃圾收集数据与非托管内存混合时,需要知道这样的低级细节。 .. XXX finalizers for traced objects Not nil注解 ------------------ ``nil`` 是有效值的所有类型都可以注释为使用 ``not nil`` 注释将 ``nil`` 排除: .. code-block:: nim type PObject = ref TObj not nil TProc = (proc (x, y: int)) not nil proc p(x: PObject) = echo "not nil" # 编译器捕获: p(nil) # 和这个: var x: PObject p(x) 编译器确保每个代码路径初始化包含非空指针的变量。此分析的细节仍在此处指定。 过程类型 --------------- 过程类型在内部是指向过程的指针。 ``nil`` 是过程类型变量的允许值。 Nim使用过程类型来实现 `函数式`:idx: 编程技术。 Examples: .. code-block:: nim proc printItem(x: int) = ... proc forEach(c: proc (x: int) {.cdecl.}) = ... forEach(printItem) # 无法编译,因为调用约定不同 .. code-block:: nim type OnMouseMove = proc (x, y: int) {.closure.} proc onMouseMove(mouseX, mouseY: int) = # 有默认的调用约定 echo "x: ", mouseX, " y: ", mouseY proc setOnMouseMove(mouseMoveEvent: OnMouseMove) = discard # 可以, 'onMouseMove'有默认的调用约定,它是兼容的 # 到 'closure': setOnMouseMove(onMouseMove) 过程类型的一个微妙问题是过程的调用约定会影响类型兼容性:过程类型只有在具有相同的调用约定时才是兼容的。 作为一个特殊的扩展,调用约定 ``nimcall`` 的过程可以传递给一个参数,该参数需要调用约定 ``closure`` 的proc。 Nim支持这些 `调用约定`:idx:\: `nimcall`:idx: 是用于Nim **proc** 的默认约定。它与 ``fastcall`` 相同,但仅适用于支持 ``fastcall`` 的C编译器。 `closure`:idx: 是缺少任何pragma注释的 **过程类型** 的默认调用约定。 它表示该过程具有隐藏的隐式形参(*环境*)。 具有调用约定 ``closure`` 的过程变量占用两个机器字:一个用于proc指针,另一个用于指向隐式传递环境的指针。 `stdcall`:idx: 这是微软指定的stdcall约定。生成的C过程使用 ``__stdcall`` 关键字声明。 `cdecl`:idx: cdecl约定意味着过程应使用与C编译器相同的约定。 在Windows下,生成的C过程使用 ``__cdecl`` 关键字声明。 `safecall`:idx: 这是微软指定的safecall约定。 生成的C过程使用 ``__safecall`` 关键字声明。 *安全* 一词指的是所有硬件寄存器都应被推送到硬件堆栈。 `inline`:idx: 内联约定意味着调用者不应该调用该过程,而是直接内联其代码。 请注意,Nim不是内联的,而是将其留给C编译器;它生成 ``__inline`` 程序。 这只是编译器的一个提示:编译器可能完全忽略它,它可能内联没有标记为 ``inline`` 的过程。 `fastcall`:idx: Fastcall对不同的C编译器意味着不同的东西,不论C的 ``__fastcall`` 意义是什么。 `syscall`:idx: 系统调用约定与C中的 ``__syscall`` 相同,用于中断。 `noconv`:idx: 生成的C代码将没有任何显式调用约定,因此使用C编译器的默认调用约定。 这是必需的,因为Nim对程序的默认调用约定是 ``fastcall`` 来提高速度。 大多数调用约定仅适用于Windows 32位平台。 默认调用约定是 ``nimcall`` ,除非它是内部proc(proc中的proc)。 对于内部过程,无论是否访问其环境,都会执行分析。 如果它这样做,它有调用约定 ``closure`` ,否则它有调用约定 ``nimcall`` 。 Distinct类型 ------------- ``distinct`` 类型是从 `基类型`:idx: 派生的新类型与它的基类型不兼容。 特别是,它是一种不同类型的基本属性,它 *并不* 意味着它和基本类型之间的子类型关系。 允许从不同类型到其基本类型的显式类型转换,反之亦然。另请参阅 ``distinctBase`` 以获得逆操作。 如果基类型是序数类型,则不同类型是序数类型。 模拟货币 ~~~~~~~~~~~~~~~~~~~~ 可以使用不同的类型来模拟不同的物理 `单位`:idx: 比如具有数字基类型。 以下示例模拟货币。 货币计算中不应混合不同的货币。 不同类型是模拟不同货币的完美工具: .. code-block:: nim type Dollar = distinct int Euro = distinct int var d: Dollar e: Euro echo d + 12 # 错误:无法添加没有单位的数字和 ``美元`` ``d + 12.Dollar`` 也不允许,因为 ``+`` 为 ``int`` (在其它类型之中)定义, 而没有为 ``Dollar`` 定义。 因此需要定义美元的 ``+`` : .. code-block:: proc `+` (x, y: Dollar): Dollar = result = Dollar(int(x) + int(y)) 将一美元乘以一美元是没有意义的,但可以不带单位相乘;对除法同样成立: .. code-block:: proc `*` (x: Dollar, y: int): Dollar = result = Dollar(int(x) * y) proc `*` (x: int, y: Dollar): Dollar = result = Dollar(x * int(y)) proc `div` ... 这很快变得乏味。 实现是琐碎的,编译器不应该生成所有这些代码只是为了以后优化它 - 毕竟美元 ``+`` 应该生成与整型 ``+`` 相同的二进制代码。 编译指示 `borrow`:idx: 旨在解决这个问题;原则上它会生成以上的琐碎实现: .. code-block:: nim proc `*` (x: Dollar, y: int): Dollar {.borrow.} proc `*` (x: int, y: Dollar): Dollar {.borrow.} proc `div` (x: Dollar, y: int): Dollar {.borrow.} ``borrow`` 编译指示使编译器使用与处理distinct类型的基类型的proc相同的实现,因此不会生成任何代码。 但似乎所有这些样板代码都需要为 ``欧元`` 货币重复。这可以通过 模板_ 解决。 .. code-block:: nim :test: "nim c $1" template additive(typ: typedesc) = proc `+` *(x, y: typ): typ {.borrow.} proc `-` *(x, y: typ): typ {.borrow.} # 一元运算符: proc `+` *(x: typ): typ {.borrow.} proc `-` *(x: typ): typ {.borrow.} template multiplicative(typ, base: typedesc) = proc `*` *(x: typ, y: base): typ {.borrow.} proc `*` *(x: base, y: typ): typ {.borrow.} proc `div` *(x: typ, y: base): typ {.borrow.} proc `mod` *(x: typ, y: base): typ {.borrow.} template comparable(typ: typedesc) = proc `<` * (x, y: typ): bool {.borrow.} proc `<=` * (x, y: typ): bool {.borrow.} proc `==` * (x, y: typ): bool {.borrow.} template defineCurrency(typ, base: untyped) = type typ* = distinct base additive(typ) multiplicative(typ, base) comparable(typ) defineCurrency(Dollar, int) defineCurrency(Euro, int) 借用编译指示还可用于注释不同类型以允许某些内置操作被提升: .. code-block:: nim type Foo = object a, b: int s: string Bar {.borrow: `.`.} = distinct Foo var bb: ref Bar new bb # 字段访问有效 bb.a = 90 bb.s = "abc" 目前只有点访问符可以用这种方式借用。 避免SQL注入攻击 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 从Nim传递到SQL数据库的SQL语句可能被模拟为字符串。 但是,使用字符串模板并填充值很容易受到 `SQL注入攻击`:idx:\: .. code-block:: nim import strutils proc query(db: DbHandle, statement: string) = ... var username: string db.query("SELECT FROM users WHERE name = '$1'" % username) # 可怕的安全漏洞,但编译没有问题 通过将包含SQL的字符串与不包含SQL的字符串区分开来可以避免这种情况。 不同类型提供了一种引入与 ``string`` 不兼容的新字符串类型 ``SQL`` 的方法: .. code-block:: nim type SQL = distinct string proc query(db: DbHandle, statement: SQL) = ... var username: string db.query("SELECT FROM users WHERE name = '$1'" % username) # 静态错误:`query` 需要一个SQL字符串。 它是抽象类型的基本属性,它们 *并不* 意味着抽象类型与其基类型之间的子类型关系。 允许从 ``string`` 到 ``SQL`` 的显式类型转换: .. code-block:: nim import strutils, sequtils proc properQuote(s: string): SQL = # 为SQL语句正确引用字符串 return SQL(s) proc `%` (frmt: SQL, values: openarray[string]): SQL = # 引用每个论点: let v = values.mapIt(SQL, properQuote(it)) # we need a temporary type for the type conversion :-( type StrSeq = seq[string] # 调用 strutils.`%`: result = SQL(string(frmt) % StrSeq(v)) db.query("SELECT FROM users WHERE name = '$1'".SQL % [username]) 现在我们针对SQL注入攻击有了编译时的检查。 因为 ``"".SQL`` 转换为 ``SQL("")`` 这种漂亮的 ``SQL`` 字符串并不需要新的语法。 我们所说的 ``SQL`` 类型实际上存在于库中, 作为像 `db_sqlite <db_sqlite.html>`_ 这类模块的 `SqlQuery type <db_common.html#SqlQuery>`_ 。 自动类型 --------- ``auto`` 类型只能用于返回类型和参数。 对于返回类型,它会使编译器从过程体中推断出类型: .. code-block:: nim proc returnsInt(): auto = 1984 对于形参,它现在是创建隐式的泛型例程: .. code-block:: nim proc foo(a, b: auto) = discard 同: .. code-block:: nim proc foo[T1, T2](a: T1, b: T2) = discard 然而,该语言的更高版本可能会将其更改为从方法体 ``推断形参类型`` 。 然后上面的 ``foo`` 将被拒绝,因为形参的类型不能从空的 ``discard`` 语句中推断出来。 类型关系 ============== 以下部分定义了描述编译器类型检查所需类型的几个关系。 类型相等性 ------------- Nim对大多数类型使用结构类型等价。 仅对于对象,枚举和不同类型使用名称等价。 *伪代码中* 的以下算法确定类型相等: .. code-block:: nim proc typeEqualsAux(a, b: PType, s: var HashSet[(PType, PType)]): bool = if (a,b) in s: return true incl(s, (a,b)) if a.kind == b.kind: case a.kind of int, intXX, float, floatXX, char, string, cstring, pointer, bool, nil, void: # 叶类型: 类型等价; 不做更多检查 result = true of ref, ptr, var, set, seq, openarray: result = typeEqualsAux(a.baseType, b.baseType, s) of range: result = typeEqualsAux(a.baseType, b.baseType, s) and (a.rangeA == b.rangeA) and (a.rangeB == b.rangeB) of array: result = typeEqualsAux(a.baseType, b.baseType, s) and typeEqualsAux(a.indexType, b.indexType, s) of tuple: if a.tupleLen == b.tupleLen: for i in 0..a.tupleLen-1: if not typeEqualsAux(a[i], b[i], s): return false result = true of object, enum, distinct: result = a == b of proc: result = typeEqualsAux(a.parameterTuple, b.parameterTuple, s) and typeEqualsAux(a.resultType, b.resultType, s) and a.callingConvention == b.callingConvention proc typeEquals(a, b: PType): bool = var s: HashSet[(PType, PType)] = {} result = typeEqualsAux(a, b, s) 由于类型可以是有环图,因此上述算法需要辅助集合 ``s`` 来检测这种情况 类型相等与类型区分 ------------------------------------- 以下算法(伪代码)确定两种类型是否相等而不是 ``不同`` 类型。 为简洁起见,省略了辅助集 ``s`` 的循环检查: .. code-block:: nim proc typeEqualsOrDistinct(a, b: PType): bool = if a.kind == b.kind: case a.kind of int, intXX, float, floatXX, char, string, cstring, pointer, bool, nil, void: # leaf type: kinds identical; nothing more to check result = true of ref, ptr, var, set, seq, openarray: result = typeEqualsOrDistinct(a.baseType, b.baseType) of range: result = typeEqualsOrDistinct(a.baseType, b.baseType) and (a.rangeA == b.rangeA) and (a.rangeB == b.rangeB) of array: result = typeEqualsOrDistinct(a.baseType, b.baseType) and typeEqualsOrDistinct(a.indexType, b.indexType) of tuple: if a.tupleLen == b.tupleLen: for i in 0..a.tupleLen-1: if not typeEqualsOrDistinct(a[i], b[i]): return false result = true of distinct: result = typeEqualsOrDistinct(a.baseType, b.baseType) of object, enum: result = a == b of proc: result = typeEqualsOrDistinct(a.parameterTuple, b.parameterTuple) and typeEqualsOrDistinct(a.resultType, b.resultType) and a.callingConvention == b.callingConvention elif a.kind == distinct: result = typeEqualsOrDistinct(a.baseType, b) elif b.kind == distinct: result = typeEqualsOrDistinct(a, b.baseType) 子类型关系 ---------------- 如果对象 ``a`` 继承自 ``b``, ``a`` 是 ``b`` 的类型。 这种了类型关系扩展到 ``var``, ``ref``, ``ptr`` : .. code-block:: nim proc isSubtype(a, b: PType): bool = if a.kind == b.kind: case a.kind of object: var aa = a.baseType while aa != nil and aa != b: aa = aa.baseType result = aa == b of var, ref, ptr: result = isSubtype(a.baseType, b.baseType) .. XXX nil is a special value! 可转换关系 -------------------- 类型 ``a`` 可 **隐式** 转换到类型 ``b`` 如果下列算法返回真: .. code-block:: nim proc isImplicitlyConvertible(a, b: PType): bool = if isSubtype(a, b) or isCovariant(a, b): return true case a.kind of int: result = b in {int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float, float32, float64} of int8: result = b in {int16, int32, int64, int} of int16: result = b in {int32, int64, int} of int32: result = b in {int64, int} of uint: result = b in {uint32, uint64} of uint8: result = b in {uint16, uint32, uint64} of uint16: result = b in {uint32, uint64} of uint32: result = b in {uint64} of float: result = b in {float32, float64} of float32: result = b in {float64, float} of float64: result = b in {float32, float} of seq: result = b == openArray and typeEquals(a.baseType, b.baseType) of array: result = b == openArray and typeEquals(a.baseType, b.baseType) if a.baseType == char and a.indexType.rangeA == 0: result = b == cstring of cstring, ptr: result = b == pointer of string: result = b == cstring Nim为 ``范围`` 类型构造函数执行了隐式转换。 设 ``a0``, ``b0`` 为类型 ``T``. 设 ``A = range[a0..b0]`` 为实参类型, ``F`` 正式的形参类型。 从 ``A`` 到 ``F`` 存在隐式转换,如果 ``a0 >= low(F) 且 b0 <= high(F)`` 且 ``T`` 各 ``F`` 是有符号或无符号整型。 如果以下算法返回true,则类型 ``a`` 可 **显式** 转换为类型 ``b`` : .. code-block:: nim proc isIntegralType(t: PType): bool = result = isOrdinal(t) or t.kind in {float, float32, float64} proc isExplicitlyConvertible(a, b: PType): bool = result = false if isImplicitlyConvertible(a, b): return true if typeEqualsOrDistinct(a, b): return true if isIntegralType(a) and isIntegralType(b): return true if isSubtype(a, b) or isSubtype(b, a): return true 可转换关系可以通过用户定义的类型 `converter`:idx: 来放宽。 .. code-block:: nim converter toInt(x: char): int = result = ord(x) var x: int chr: char = 'a' # 隐式转换发生在这里 x = chr echo x # => 97 # 你也可以使用显式转换 x = chr.toInt echo x # => 97 如果 ``a`` 是左值并且 ``typeEqualsOrDistinct(T, type(a))`` 成立, 类型转换 ``T(a)`` 也是左值。 赋值兼容性 ------------------------ 表达式 ``b`` 可以赋给表达式 ``a`` 如果 ``a`` 是 `左值` 并且 ``isImplicitlyConvertible(b.typ, a.typ)`` 成立。 重载解析 ====================== 在调用 ``p(args)`` 中选择匹配最佳的例程 ``p`` 。 如果多个例程同样匹配,则在语义分析期间报告歧义。 args中的每个arg都需要匹配。参数可以匹配的方式有多种不同的类别。 设 ``f`` 是形式参数的类型, ``a`` 是参数的类型。 1. 准确匹配: ``a`` 和 ``f`` 是相同类型。 2. 字面匹配: ``a`` 是值为 ``v`` 的整型字面值, ``f`` 是有符号或无符号整型 ``v`` 在 ``f`` 的范围里. 或: ``a`` 是值为 ``v``的浮点字面值, ``f`` 是浮点类型 ``v`` 在 ``f`` 的范围里。 3. 泛型匹配: ``f`` 是泛型类型且 ``a`` 匹配, 例如 ``a`` 是 ``int`` 且 ``f`` 是泛型限制 (受限) 形参类型 (像 ``[T]`` 或 ``[T: int|char]``. 4. 子范围或子类型匹配: ``a`` is a ``range[T]`` and ``T`` matches ``f`` exactly. Or: ``a`` is a subtype of ``f``. 5. 整数转换匹配: ``a`` 可转换为 ``f`` 且 ``f`` 和 ``a`` 是同样的整数或浮点类型。 6. 转换匹配: ``a`` 可能通过用户定义的转换器转换为 ``f`` 。 这些匹配类别具有优先级:完全匹配优于字面值匹配,并且优于通用匹配等。 在下面的 ``count(p, m)`` 计算 ``m`` 匹配过程 ``p`` 的匹配数。 如果下列算法返回真,例程 ``p`` 比 ``q`` 更匹配: for each matching category m in ["exact match", "literal match", "generic match", "subtype match", "integral match", "conversion match"]: if count(p, m) > count(q, m): return true elif count(p, m) == count(q, m): discard "continue with next category m" else: return false return "ambiguous" 一些示例: .. code-block:: nim proc takesInt(x: int) = echo "int" proc takesInt[T](x: T) = echo "T" proc takesInt(x: int16) = echo "int16" takesInt(4) # "int" var x: int32 takesInt(x) # "T" var y: int16 takesInt(y) # "int16" var z: range[0..4] = 0 takesInt(z) # "T" 如果算法返回 "歧义" 则执行进一步消歧: 如果参数 ``a`` 通过子类型关系匹配 ``p`` 的参数类型 ``f`` 和 ``q`` 的 ``g`` ,则考虑继承深度: .. code-block:: nim type A = object of RootObj B = object of A C = object of B proc p(obj: A) = echo "A" proc p(obj: B) = echo "B" var c = C() # not ambiguous, calls 'B', not 'A' since B is a subtype of A # but not vice versa: p(c) proc pp(obj: A, obj2: B) = echo "A B" proc pp(obj: B, obj2: A) = echo "B A" # but this is ambiguous: pp(c, c) 同样,对于通用匹配,匹配的结果中首选最特化的泛型类型: .. code-block:: nim proc gen[T](x: ref ref T) = echo "ref ref T" proc gen[T](x: ref T) = echo "ref T" proc gen[T](x: T) = echo "T" var ri: ref int gen(ri) # "ref T" 基于 'var T' 的重载 ---------------------------- 如果形式参数 ``f`` 是除了普通类型检查外的 ``var T`` 类型, 则检查实参是否 `左值`:idx: 。 ``var T`` 比 ``T`` 更好地匹配。 .. code-block:: nim proc sayHi(x: int): string = # 匹配非var整型 result = $x proc sayHi(x: var int): string = # 匹配var整型 result = $(x + 10) proc sayHello(x: int) = var m = x # 可改变的x echo sayHi(x) # 匹配sayHi的非var版本 echo sayHi(m) # 匹配sayHi的var版本 sayHello(3) # 3 # 13 无类型的延迟类型解析 -------------------------------- **注意**: `未解析`:idx: 表达式是为没有执行符号查找和类型检查的表达式。 由于未声明为 ``立即`` 的模板和宏参与重载分析,因此必须有一种方法将未解析的表达式传递给模板或宏。 .. code-block:: nim template rem(x: untyped) = discard rem unresolvedExpression(undeclaredIdentifier) ``untyped`` 类型的参数总是匹配任何参数(只要有任何参数传递给它)。 但是必须注意,因为其他重载可能触发参数的解析: .. code-block:: nim template rem(x: untyped) = discard proc rem[T](x: T) = discard # 未声明的标识符:'unresolvedExpression' rem unresolvedExpression(undeclaredIdentifier) ``untyped`` 和 ``varargs [untyped]`` 是这种意义上唯一的惰性元类型,其他元类型 ``typed`` 和 ``typedesc`` 并不是惰性的。 可变参数匹配 ---------------- 见 `Varargs <#types-varargs>`_. 语句和表达式 ========================== Nim使用通用语句/表达式范例:与表达式相比,语句不会产生值。 但是,有些表达式是语句。 语句分为 `简单语句`:idx: 和 `复杂语句`:idx: 。 简单语句是不能包含像赋值,调用或者 ``return`` 的语句; 复杂语句可以包含其它语句。 为了避免 `dangling else问题`:idx:, 复杂语句必须缩进。 细节可以在语法中找到。 语句列表表达式 ------------------------- 语句也可以出现在类似于 ``(stmt1; stmt2; ...; ex)`` 的表达式上下文中。 语句也可以出现在表达式上下文中。 这叫做语句列表表达式或 ``(;)`` 。 ``(stmt1; stmt2; ...; ex)`` 的类型是 ``ex`` 的类型。 所有其他语句必须是 ``void`` 类型。 (可以用 ``discard`` 生成 ``void`` 类型。) ``(;)`` 不引入新作用域。 Discard表达式 ----------------- 示例: .. code-block:: nim proc p(x, y: int): int = result = x + y discard p(3, 4) # 丢弃 `p` 的返回值 ``discard`` 语句评估其副作用的表达式,并丢弃表达式的结果。 在不使用discard语句的情况下忽略过程的返回值是一个静态错误。 如果使用 `discardable`:idx: 编译指示声明了被调用的proc或iterator,则可以隐式忽略返回值: .. code-block:: nim proc p(x, y: int): int {.discardable.} = result = x + y p(3, 4) # now valid 空 ``discard`` 语句通常用作null语句: .. code-block:: nim proc classify(s: string) = case s[0] of SymChars, '_': echo "an identifier" of '0'..'9': echo "a number" else: discard Void上下文 ------------ 在语句列表中,除最后一个表达式之外的每个表达式都需要具有类型 ``void`` 。 除了这个规则之外,对内置 ``result`` 符号的赋值也会触发后续表达式的强制 ``void`` 上下文: .. code-block:: nim proc invalid*(): string = result = "foo" "invalid" # 错误: 'string' 类型值必须丢弃 .. code-block:: nim proc valid*(): string = let x = 317 "valid" Var语句 ------------- Var语句声明新的局部变量和全局变量并初始化它们。 逗号分隔的变量列表可用于指定相同类型的变量: .. code-block:: nim var a: int = 0 x, y, z: int 如果给出初始值设定项,则可以省略该类型:该变量的类型与初始化表达式的类型相同。 如果没有初始化表达式,变量总是使用默认值初始化。 默认值取决于类型,并且在二进制中始终为零。 ============================ ============================================== 类型 默认值 ============================ ============================================== any integer type 0 any float 0.0 char '\\0' bool false ref or pointer type nil procedural type nil sequence ``@[]`` string ``""`` tuple[x: A, y: B, ...] (default(A), default(B), ...) (analogous for objects) array[0..., T] [default(T), ...] range[T] default(T); this may be out of the valid range T = enum cast[T]\(0); this may be an invalid value ============================ ============================================== 出于优化原因,可以使用 `noinit`:idx: 编译指示来避免隐式初始化: .. code-block:: nim var a {.noInit.}: array[0..1023, char] 如果一个proc用 ``noinit`` 编译指示注释,则指的是它隐含的 ``result`` 变量: .. code-block:: nim proc returnUndefinedValue: int {.noinit.} = discard 隐式初始化可以用 `requiresInit`:idx: 类型编译指示阻止。 编译器需要对对象及其所有字段进行显式初始化。 然而它执行 `控制流分析`:idx: 证明变量已经初始化并且不依赖于语法属性: .. code-block:: nim type MyObject = object {.requiresInit.} proc p() = # 以下内容有效: var x: MyObject if someCondition(): x = a() else: x = a() # use x Let语句 ------------- ``let`` 语句声明了新的本地和全局 `单次赋值`:idx: 变量并绑定值。 语法与 ``var`` 语句的语法相同,只是关键字 ``var`` 被替换为关键字 ``let`` 。 Let变量不是左值因此不能传递给 ``var`` 参数,也不能采用它们的地址。他们无法分配新值。 对于let变量,可以使用与普通变量相同的编译指示。 元组解包 --------------- 在 ``var`` 或 ``let`` 语句中可以执行元组解包。 特殊标识符 ``_`` 可以用来忽略元组的某些部分: .. code-block:: nim proc returnsTuple(): (int, int, int) = (4, 2, 3) let (x, _, z) = returnsTuple() 常量段 ------------- const部分声明其值为常量表达式的常量: .. code-block:: import strutils const roundPi = 3.1415 constEval = contains("abc", 'b') # computed at compile time! 声明后,常量符号可用作常量表达式。 详见 `Constants and Constant Expressions <#constants-and-constant-expressions>`_ 。 静态语句和表达式 --------------------------- 静态语句/表达式显式需要编译时执行。 甚至一些具有副作用的代码也允许在静态块中: .. code-block:: static: echo "echo at compile time" 在编译时可以执行哪些Nim代码存在限制; 详见 `Restrictions on Compile-Time Execution <#restrictions-on-compileminustime-execution>`_ 。 如果编译器无法在编译时执行块,那么这是一个静态错误。 If语句 ------------ 示例: .. code-block:: nim var name = readLine(stdin) if name == "Andreas": echo "What a nice name!" elif name == "": echo "Don't you have a name?" else: echo "Boring name..." ``if`` 语句是在控制流中创建分支的简单方法:计算关键字 ``if`` 之后的表达式,如果为真,则执行 ``:`` 之后的相应语句。 这一直持续到最后一个 ``elif`` 。 如果所有条件都失败,则执行 ``else`` 部分。 如果没有 ``else`` 部分,则继续执行下一个语句。 在 ``if`` 语句中,新的作用域在 ``if`` 或 ``elif`` 或 ``else`` 关键字之后立即开始,并在相应的 *then* 块之后结束。 出于可视化目的,作用域已包含在 ``{| |}`` 在以下示例中 示例: .. code-block:: nim if {| (let m = input =~ re"(\w+)=\w+"; m.isMatch): echo "key ", m[0], " value ", m[1] |} elif {| (let m = input =~ re""; m.isMatch): echo "new m in this scope" |} else: {| echo "m not declared here" |} Case语句 -------------- 示例: .. code-block:: nim case readline(stdin) of "delete-everything", "restart-computer": echo "permission denied" of "go-for-a-walk": echo "please yourself" else: echo "unknown command" # 允许分支缩进; 冒号也是可选的 # 在选择表达式后: case readline(stdin): of "delete-everything", "restart-computer": echo "permission denied" of "go-for-a-walk": echo "please yourself" else: echo "unknown command" ``case`` 语句类似于if语句,但它表示多分支选择。 评估关键字 ``case`` 之后的表达式,如果它的值在 *slicelist* 中,则执行在 ``of`` 关键字之后的相应语句。 如果该值不在任何给定的 *slicelist* 中,则执行 ``else`` 部分。 如果没有 ``else`` 部分而且 ``expr`` 可以保持在 ``slicelist`` 中的所有可能值,则会发生静态错误。 这仅适用于序数类型的表达式。 ``expr`` 的“所有可能的值”由 ``expr`` 的类型决定。 为了阻止静态错误,应该使用带有空 ``discard`` 语句的 ``else`` 部分。 对于非序数类型,不可能列出每个可能的值,因此这些值总是需要 ``else`` 部分。 因为在语义分析期间检查case语句的详尽性,所以每个 ``of`` 分支中的值必须是常量表达式。 此限制还允许编译器生成更高性能的代码。 作为一种特殊的语义扩展,case语句的 ``of`` 分支中的表达式可以计算为集合或数组构造函数;然后将集合或数组扩展为其元素列表: .. code-block:: nim const SymChars: set[char] = {'a'..'z', 'A'..'Z', '\x80'..'\xFF'} proc classify(s: string) = case s[0] of SymChars, '_': echo "an identifier" of '0'..'9': echo "a number" else: echo "other" # is equivalent to: proc classify(s: string) = case s[0] of 'a'..'z', 'A'..'Z', '\x80'..'\xFF', '_': echo "an identifier" of '0'..'9': echo "a number" else: echo "other" When语句 -------------- 示例: .. code-block:: nim when sizeof(int) == 2: echo "running on a 16 bit system!" elif sizeof(int) == 4: echo "running on a 32 bit system!" elif sizeof(int) == 8: echo "running on a 64 bit system!" else: echo "cannot happen!" ``when`` 语句几乎与 ``if`` 语句完全相同,但有一些例外: * 每个条件 (``expr``) 必须是一个类型为 ``bool`` 的常量表达式。 * 语句不打开新作用域。 * 属于计算结果为true的表达式的语句由编译器翻译,其他语句不检查语义。 ``when`` 语句启用条件编译技术。 作为一种特殊的语法扩展, ``when`` 结构也可以在 ``object`` 定义中使用。 When nimvm语句 -------------------- ``nimvm`` 是一个特殊的符号,可以用作 ``when nimvm`` 语句的表达式来区分编译时和可执行文件之间的执行路径。 示例: .. code-block:: nim proc someProcThatMayRunInCompileTime(): bool = when nimvm: # 编译时采用这个分支。 result = true else: # 可执行文件中采用这个分支 result = false const ctValue = someProcThatMayRunInCompileTime() let rtValue = someProcThatMayRunInCompileTime() assert(ctValue == true) assert(rtValue == false) ``when nimvm`` 语句必须满足以下要求: * 它的表达式必须是 ``nimvm`` 。不允许更多的复杂表达式。 * 它必须不含有 ``elif`` 分支。 * 必须含有 ``else`` 分支。 * 分支中的代码不得影响 ``when nimvm`` 语句后面的代码的语义。例如它不能定义后续代码中使用的符号。 Return语句 ---------------- 示例: .. code-block:: nim return 40+2 ``return`` 语句结束当前过程的执行。 它只允许在程序中使用。如果有一个 ``expr`` ,这是一个语法糖: .. code-block:: nim result = expr return result 如果proc有返回类型,没有表达式的 ``return`` 是 ``return result`` 的简短表示法。 `result`:idx: 变量始终是过程的返回值。 它由编译器自动声明。 作为所有变量, ``result`` 被初始化为(二进制)零: .. code-block:: nim proc returnZero(): int = # 隐式返回0 Yield语句 --------------- 示例: .. code-block:: nim yield (1, 2, 3) 在迭代器中使用 ``yield`` 语句而不是 ``return`` 语句。 它仅在迭代器中有效。执行返回到调用迭代器的for循环体。 Yield不会结束迭代过程,但是如果下一次迭代开始,则执行会返回到迭代器。 有关更多信息,请参阅有关迭代器 (`迭代器和for语句`_) 的部分。 Block语句 --------------- 示例: .. code-block:: nim var found = false block myblock: for i in 0..3: for j in 0..3: if a[j][i] == 7: found = true break myblock # 跳出两个for循环块 echo found 块语句是一种将语句分组到(命名) ``block`` 的方法。 在块内,允许 ``break`` 语句立即跳出块。 ``break`` 语句可以包含周围块的名称,以指定要跳出的块。 Break语句 --------------- 示例: .. code-block:: nim break ``break`` 语句用于立即跳出块。 如果给出 ``symbol`` ,则它是要跳出的封闭块的名称。 如果不存在,则跳出最里面的块。 While语句 --------------- 示例: .. code-block:: nim echo "Please tell me your password:" var pw = readLine(stdin) while pw != "12345": echo "Wrong password! Next try:" pw = readLine(stdin) 执行 ``while`` 语句直到 ``expr`` 计算结果为false。 无尽的循环没有错误。 ``while`` 语句打开一个 '隐式块',这样它们就可以用 ``break`` 语句跳出。 Continue语句 ------------------ 一个 ``continue`` 语句导致周围循环结构的下一次迭代。 它只允许在一个循环中。 continue语句是嵌套块的语法糖: .. code-block:: nim while expr1: stmt1 continue stmt2 Is equivalent to: .. code-block:: nim while expr1: block myBlockName: stmt1 break myBlockName stmt2 汇编语句 ------------------- 不安全的 ``asm`` 语句支持将汇编程序代码直接嵌入到Nim代码中。 汇编程序代码中引用Nim标识符的标识符应包含在特殊字符中,该字符可在语句的编译指示中指定。默认的特殊字符是 ``'`'`` : .. code-block:: nim {.push stackTrace:off.} proc addInt(a, b: int): int = # a in eax, and b in edx asm """ mov eax, `a` add eax, `b` jno theEnd call `raiseOverflow` theEnd: """ {.pop.} 如果使用GNU汇编器,则会自动插入引号和换行符: .. code-block:: nim proc addInt(a, b: int): int = asm """ addl %%ecx, %%eax jno 1 call `raiseOverflow` 1: :"=a"(`result`) :"a"(`a`), "c"(`b`) """ 替代: .. code-block:: nim proc addInt(a, b: int): int = asm """ "addl %%ecx, %%eax\n" "jno 1\n" "call `raiseOverflow`\n" "1: \n" :"=a"(`result`) :"a"(`a`), "c"(`b`) """ Using语句 --------------- using语句在模块中反复使用相同的参数名称和类型提供了语法上的便利。 Instead of: .. code-block:: nim proc foo(c: Context; n: Node) = ... proc bar(c: Context; n: Node, counter: int) = ... proc baz(c: Context; n: Node) = ... 可以告诉编译器关于名称 ``c`` 的参数应默认键入 ``Context`` , ``n`` 应该默认为 ``Node`` 等的约定: .. code-block:: nim using c: Context n: Node counter: int proc foo(c, n) = ... proc bar(c, n, counter) = ... proc baz(c, n) = ... proc mixedMode(c, n; x, y: int) = # 'c' 被推断为 'Context' 类型 # 'n' 被推断为 'Node' 类型 # 'x' and 'y' 是 'int' 类型。 ``using`` 部分使用相同的基于缩进的分组语法作为 ``var`` 或 ``let`` 部分。 请注意, ``using`` 不适用于 ``template`` ,因为无类型模板参数默认为类型 ``system.untyped`` 。 应该使用 ``using`` 声明和明确键入的参数混合参数,它们之间需要分号。 If表达式 ------------- `if表达式` 几乎就像一个if语句,但它是一个表达式。 示例: .. code-block:: nim var y = if x > 8: 9 else: 10 if表达式总是会产生一个值,所以 ``else`` 部分是必需的。 ``Elif`` 部分也是允许的。 When表达式 --------------- 就像 `if表达式` ,但对应于when语句。 Case表达式 --------------- `case表达式` 与case语句非常相似: .. code-block:: nim var favoriteFood = case animal of "dog": "bones" of "cat": "mice" elif animal.endsWith"whale": "plankton" else: echo "I'm not sure what to serve, but everybody loves ice cream" "ice cream" 如上例所示,case表达式也可以引入副作用。 当为分支给出多个语句时,Nim将使用最后一个表达式作为结果值。 Block表达式 ---------------- `block表达式` 几乎就像一个块语句,但它是一个表达式,它使用块下的最后一个表达式作为值。 它类似于语句列表表达式,但语句列表表达式不会打开新的块作用域。 .. code-block:: nim let a = block: var fib = @[0, 1] for i in 0..10: fib.add fib[^1] + fib[^2] fib Table构造函数 ----------------- 表构造函数是数组构造函数的语法糖: .. code-block:: nim {"key1": "value1", "key2", "key3": "value2"} # is the same as: [("key1", "value1"), ("key2", "value2"), ("key3", "value2")] 空表可以写成 ``{:}`` (与 ``{}`` 的空集相反,这是另一种写为空数组构造函数 ``[]`` 的方法。 这种略微不同寻常的支持表的方式有很多优点: * 保留了(键,值)对的顺序,因此很容易支持有序的字典,例如 ``{key:val}.newOrderedTable`` 。 * 表字面值可以放入 ``const`` 部分,编译器可以很容易地将它放入可执行文件的数据部分,就像数组一样,生成的数据部分需要最少的内存。 * 每个表实现在语法上都是一样的。 * 除了最小的语法糖之外,语言核心不需要了解表。 类型转换 ---------------- 语法上, `类型转换` 类似于过程调用,但类型名称替换过程名称。 类型转换总是安全的,因为将类型转换为另一个类型失败会导致异常(如果无法静态确定)。 普通的procs通常比Nim中的类型转换更受欢迎:例如, ``$`` 是 ``toString`` 运算符,而 ``toFloat`` 和 ``toInt`` 可用于从浮点转换为整数,反之亦然。 类型转换也可用于消除重载例程的歧义: .. code-block:: nim proc p(x: int) = echo "int" proc p(x: string) = echo "string" let procVar = (proc(x: string))(p) procVar("a") 类型强转 ---------- 示例: .. code-block:: nim cast[int](x) 类型强转是一种粗暴的机制,用于解释表达式的位模式,就好像它将是另一种类型一样。 类型强转仅用于低级编程,并且本质上是不安全的。 addr操作符 ----------------- ``addr`` 运算符返回左值的地址。 如果位置的类型是 ``T`` ,则 `addr` 运算符结果的类型为 ``ptr T`` 。 地址是未追踪引用。 获取驻留在堆栈上的对象的地址是 *不安全的* ,因为指针可能比堆栈中的对象存在更久,因此可以引用不存在的对象。 可以获取变量的地址,但是不能在通过 ``let`` 语句声明的变量上使用它: .. code-block:: nim let t1 = "Hello" var t2 = t1 t3 : pointer = addr(t2) echo repr(addr(t2)) # --> ref 0x7fff6b71b670 --> 0x10bb81050"Hello" echo cast[ptr string](t3)[] # --> Hello # 下面的行不能编译: echo repr(addr(t1)) # 错误: 表达式没有地址 unsafeAddr操作符 ----------------------- 为了更容易与其他编译语言(如C)的互操作性,检索 ``let`` 变量的地址,参数或 ``for`` 循环变量,可以使用 ``unsafeAddr`` 操作: .. code-block:: nim let myArray = [1, 2, 3] foreignProcThatTakesAnAddr(unsafeAddr myArray) 过程 ========== 大多数编程语言称之为 `方法`:idx: 或 `函数`:idx: 在Nim中称为 `过程`:idx: 。 过程声明由标识符,零个或多个形式参数,返回值类型和代码块组成。 正式参数声明为由逗号或分号分隔的标识符列表。 形参由 ``: 类型名称`` 给出一个类型。 该类型适用于紧接其之前的所有参数,直到达到参数列表的开头,分号分隔符或已经键入的参数。 分号可用于使类型和后续标识符的分隔更加清晰。 .. code-block:: nim # 只使用逗号 proc foo(a, b: int, c, d: bool): int # 使用分号进行视觉区分 proc foo(a, b: int; c, d: bool): int # 会失败:a是无类型的,因为 ';' 停止类型传播。 proc foo(a; b: int; c, d: bool): int 可以使用默认值声明参数,如果调用者没有为参数提供值,则使用该默认值。 .. code-block:: nim # b is optional with 47 as its default value proc foo(a: int, b: int = 47): int 参数可以声明为可变的,因此允许proc通过使用类型修饰符 `var` 来修改这些参数。 .. code-block:: nim # 通过第二个参数 ``返回`` 一个值给调用者 # 请注意,该函数根本不使用实际返回值(即void) proc foo(inp: int, outp: var int) = outp = inp + 47 如果proc声明没有正文,则它是一个 `前向`:idx: 声明。 如果proc返回一个值,那么过程体可以访问一个名为 `result` 的隐式声明的变量。 过程可能会重载。 重载解析算法确定哪个proc是参数的最佳匹配。 示例: .. code-block:: nim proc toLower(c: char): char = # toLower for characters if c in {'A'..'Z'}: result = chr(ord(c) + (ord('a') - ord('A'))) else: result = c proc toLower(s: string): string = # 字符串toLower result = newString(len(s)) for i in 0..len(s) - 1: result[i] = toLower(s[i]) # calls toLower for characters; no recursion! 调用过程可以通过多种方式完成: .. code-block:: nim proc callme(x, y: int, s: string = "", c: char, b: bool = false) = ... # call with positional arguments # parameter bindings: callme(0, 1, "abc", '\t', true) # (x=0, y=1, s="abc", c='\t', b=true) # call with named and positional arguments: callme(y=1, x=0, "abd", '\t') # (x=0, y=1, s="abd", c='\t', b=false) # call with named arguments (order is not relevant): callme(c='\t', y=1, x=0) # (x=0, y=1, s="", c='\t', b=false) # call as a command statement: no () needed: callme 0, 1, "abc", '\t' # (x=0, y=1, s="abc", c='\t', b=false) 过程可以递归地调用自身。 `运算符`:idx: 是具有特殊运算符符号作为标识符的过程: .. code-block:: nim proc `$` (x: int): string = # 将整数转换为字符串;这是一个前缀运算符。 result = intToStr(x) 具有一个参数的运算符是前缀运算符,具有两个参数的运算符是中缀运算符。 (但是,解析器将这些与运算符在表达式中的位置区分开来。) 没有办法声明后缀运算符:所有后缀运算符都是内置的,并由语法显式处理。 任何运算符都可以像普通的proc一样用 '`opr`' 表示法调用。(因此运算符可以有两个以上的参数): .. code-block:: nim proc `*+` (a, b, c: int): int = # Multiply and add result = a * b + c assert `*+`(3, 4, 6) == `+`(`*`(a, b), c) 导出标记 ------------- 如果声明的符号标有 `asterisk`:idx: 它从当前模块导出: .. code-block:: nim proc exportedEcho*(s: string) = echo s proc `*`*(a: string; b: int): string = result = newStringOfCap(a.len * b) for i in 1..b: result.add a var exportedVar*: int const exportedConst* = 78 type ExportedType* = object exportedField*: int 方法调用语法 ------------------ 对于面向对象的编程,可以使用语法 ``obj.method(args)`` 而不是 ``method(obj, args)`` 。 如果没有剩余的参数,则可以省略括号: ``obj.len`` (而不是 ``len(obj)`` )。 此方法调用语法不限于对象,它可用于为过程提供任何类型的第一个参数: .. code-block:: nim echo "abc".len # 与echo len"abc"相同 echo "abc".toUpper() echo {'a', 'b', 'c'}.card stdout.writeLine("Hallo") # 与相同writeLine(stdout,"Hallo") 查看方法调用语法的另一种方法是它提供了缺少的后缀表示法。 方法调用语法与显式泛型实例化冲突: ``p[T](x)`` 不能写为 ``x.p[T]`` 因为 ``x.p[T]`` 总是被解析为 ``(x.p)[T]`` 。 见: `Limitations of the method call syntax <#templates-limitations-of-the-method-call-syntax>`_ 。 ``[:]`` 符号旨在缓解这个问题: ``xp[:T]`` 由解析器重写为 ``p[T](x)`` , ``xp[:T](y)`` 被重写为 ``p[T](x,y)`` 。 注意 ``[:]`` 没有AST表示,重写直接在解析步骤中执行。 属性 ---------- Nim不需要 *get-properties* :使用 *方法调用语法* 调用的普通get-procedure达到相同目的。 但设定值是不同的;为此需要一个特殊的setter语法: .. code-block:: nim # 模块asocket type Socket* = ref object of RootObj host: int # 无法从模块外部访问 proc `host=`*(s: var Socket, value: int) {.inline.} = ## hostAddr的setter. ##它访问'host'字段并且不是对 ``host =`` 的递归调用,如果内置的点访问方法可用,则首选点访问: s.host = value proc host*(s: Socket): int {.inline.} = ## hostAddr的getter ##它访问'host'字段并且不是对 ``host`` 的递归调用,如果内置的点访问方法可用,则首选点访问: s.host .. code-block:: nim # 模块 B import asocket var s: Socket new s s.host = 34 # 同`host=`(s, 34) 定义为 ``f=`` 的proc(尾随 ``=`` )被称为 `setter`:idx: 。 可以通过常见的反引号表示法显式调用setter: .. code-block:: nim proc `f=`(x: MyObject; value: string) = discard `f=`(myObject, "value") ``f=`` 可以在模式 ``xf = value`` 中隐式调用,当且仅当 ``x`` 的类型没有名为 ``f`` 的字段或者 ``f`` 时在当前模块中不可见。 这些规则确保对象字段和访问者可以具有相同的名称。 在模块 ``x.f`` 中总是被解释为字段访问,在模块外部它被解释为访问器proc调用。 命令调用语法 ------------------------- 如果调用在语法上是一个语句,则可以在没有 ``()`` 的情况下调用例程。 这种限制意味着 ``echo f 1, f 2`` 被解析为 ``echo(f(1), f(2))`` 而不是 ``echo(f(1, f(2)))`` 。 在这种情况下,方法调用语法可用于提供一个或多个参数: .. code-block:: nim proc optarg(x: int, y: int = 0): int = x + y proc singlearg(x: int): int = 20*x echo optarg 1, " ", singlearg 2 # 打印 "1 40" let fail = optarg 1, optarg 8 # 错误。命令调用的参数太多 let x = optarg(1, optarg 8) # 传统过程调用2个参数 let y = 1.optarg optarg 8 # 与上面相同,没有括号 assert x == y 命令调用语法也不能将复杂表达式作为参数。 例如: (`anonymous procs <#procedures-anonymous-procs>`_), ``if``, ``case`` 或 ``try`` 。 调用没有参数的函数仍需要 () 来区分调用和作为第一类值的函数本身。 闭包 -------- 过程可以出现在模块的顶层以及其他范围内,在这种情况下,它们称为嵌套过程。 嵌套的proc可以从其封闭的范围访问局部变量,如果它这样做,它就变成了一个闭包。 任何捕获的变量都存储在闭包(它的环境)的隐藏附加参数中,并且它们通过闭包及其封闭范围的引用来访问(即,对它们进行的任何修改在两个地方都是可见的)。 如果编译器确定这是安全的,则可以在堆上或堆栈上分配闭包环境。 在循环中创建闭包 ~~~~~~~~~~~~~~~~~~~~~~~~~~ 由于闭包通过引用来捕获局部变量,因此通常我们不希望在循环体中这么用。 想了解如何修改这种操作的详细说明,请参阅 `closureScope <system.html#closureScope.t,untyped>`_ 。 匿名过程 --------------- 未命名的过程可以作为 lambda 表达式传递到其他过程中: .. code-block:: nim var cities = @["Frankfurt", "Tokyo", "New York", "Kyiv"] cities.sort(proc (x,y: string): int = cmp(x.len, y.len)) Procs as表达式既可以作为嵌套的 Proc 出现,也可以作为顶级可执行代码出现。 `sugar<sugar.html>` 模块包含 `=>` 宏, 该宏可以为类似 lambdas 的匿名过程提供更简洁的语法, 就像你在 JavaScript 、 C# 等语言中那样使用。 函数 ---- The ``func`` 关键字为 `noSideEffect`:idx: 的过程引入了一个快捷方式。 .. code-block:: nim func binarySearch[T](a: openArray[T]; elem: T): int 是它的简写: .. code-block:: nim proc binarySearch[T](a: openArray[T]; elem: T): int {.noSideEffect.} 不可重载的内置 ------------------------ 由于实现简单,它们不能重载以下内置过程(它们需要专门的语义检查): declared, defined, definedInScope, compiles, sizeof, is, shallowCopy, getAst, astToStr, spawn, procCall 因此,它们更像关键词而非普通标识符;然而,与关键字不同,重新定义可能是 `shadow`:idx: ``system`` 模块中的定义。 从这个列表中不应该用点符号 ``x.f`` 写,因为 ``x`` 在传递给 ``f`` 之前不能进行类型检查: declared, defined, definedInScope, compiles, getAst, astToStr Var形参 -------------- 参数的类型可以使用 ``var`` 关键字作为前缀: .. code-block:: nim proc divmod(a, b: int; res, remainder: var int) = res = a div b remainder = a mod b var x, y: int divmod(8, 5, x, y) # modifies x and y assert x == 1 assert y == 3 在示例中, ``res`` 和 ``remainder`` 是 `var parameters` 。 可以通过过程修改Var参数,并且调用者可以看到更改。 传递给var参数的参数必须是左值。 Var参数实现为隐藏指针。 上面的例子相当于: .. code-block:: nim proc divmod(a, b: int; res, remainder: ptr int) = res[] = a div b remainder[] = a mod b var x, y: int divmod(8, 5, addr(x), addr(y)) assert x == 1 assert y == 3 在示例中,var参数或指针用于提供两个返回值。 这可以通过返回元组以更干净的方式完成: .. code-block:: nim proc divmod(a, b: int): tuple[res, remainder: int] = (a div b, a mod b) var t = divmod(8, 5) assert t.res == 1 assert t.remainder == 3 可以使用 `元组解包`:idx: 来访问元组的字段: .. code-block:: nim var (x, y) = divmod(8, 5) # 元组解包 assert x == 1 assert y == 3 **注意**: ``var`` 参数对于有效的参数传递永远不是必需的。 由于无法修改非var参数,因此如果编译器认为可以加快执行速度,则编译器始终可以通过引用自由传递参数。 Var返回类型 --------------- proc,转换器或迭代器可能返回一个 ``var`` 类型,这意味着返回的值是一个左值,并且可以由调用者修改: .. code-block:: nim var g = 0 proc writeAccessToG(): var int = result = g writeAccessToG() = 6 assert g == 6 如果隐式引入的指针可用于访问超出其生命周期的位置,则这是一个静态错误: .. code-block:: nim proc writeAccessToG(): var int = var g = 0 result = g # 错误! For iterators, a component of a tuple return type can have a ``var`` type too: .. code-block:: nim iterator mpairs(a: var seq[string]): tuple[key: int, val: var string] = for i in 0..a.high: yield (i, a[i]) 在标准库中,返回 ``var`` 类型的例程的每个名称都以每个约定的前缀 ``m`` 开头。 .. include:: manual/var_t_return.rst 未来的方向 ~~~~~~~~~~~~~~~~~ Nim的更高版本可以使用如下语法更准确地了解借用规则: .. code-block:: nim proc foo(other: Y; container: var X): var T from container 这里 ``var T from container`` 明确地暴露了该位置不同于第二个形参(在本例中称为'container')。 语法 ``var T from p`` 指定一个类型 ``varTy [T,2]`` ,它与 ``varTy [T,1]`` 不兼容。 下标操作符重载 ------------------------------------- 数组/开放数组/序列的 ``[]`` 下标运算符可以重载。 多方法 ============= **注意:** 从Nim 0.20开始,要使用多方法,必须在编译时明确传递 ``--multimethods:on`` 。 程序总是使用静态调度。多方法使用动态调度。 要使动态分派处理对象,它应该是引用类型。 .. code-block:: nim type Expression = ref object of RootObj ## abstract base class for an expression Literal = ref object of Expression x: int PlusExpr = ref object of Expression a, b: Expression method eval(e: Expression): int {.base.} = # 重写 base 方法 raise newException(CatchableError, "Method without implementation override") method eval(e: Literal): int = return e.x method eval(e: PlusExpr): int = # 当心: 依赖动态绑定 result = eval(e.a) + eval(e.b) proc newLit(x: int): Literal = new(result) result.x = x proc newPlus(a, b: Expression): PlusExpr = new(result) result.a = a result.b = b echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4))) 在示例中,构造函数 ``newLit`` 和 ``newPlus`` 是procs因为它们应该使用静态绑定,但 ``eval`` 是一种方法,因为它需要动态绑定。 从示例中可以看出,基本方法必须使用 `base`:idx: 编译指示进行注释。 ``base`` 编译指示还可以提醒程序员使用基本方法 ``m`` 作为基础来确定调用 ``m`` 可能导致的所有效果。 **注意**: 编译期执行不支持方法。 **注意**: 从Nim 0.20开始,不推荐使用泛型方法。 通过procCall禁止动态方法解析 ----------------------------------------------- 可以通过内置的 `system.procCall`:idx: 来禁止动态方法解析。 这有点类似于传统OOP语言提供的 `super`:idx: 关键字。 .. code-block:: nim :test: "nim c $1" type Thing = ref object of RootObj Unit = ref object of Thing x: int method m(a: Thing) {.base.} = echo "base" method m(a: Unit) = # Call the base method: procCall m(Thing(a)) echo "1" 迭代器和for语句 =============================== `for`:idx: 语句是一种迭代容器元素的抽象机制。 它依赖于 `iterator`:idx:这样做。就像 ``while`` 语句一样, ``for`` 语句打开一个 `隐式块`:idx:,这样它们就可以留下一个 ``break`` 语句。 ``for`` 循环声明迭代变量 - 它们的范围一直到循环体的末尾。 迭代变量的类型由迭代器的返回类型推断。 迭代器类似于一个过程,除了它可以在 ``for`` 循环的上下文中调用。 迭代器提供了一种指定抽象类型迭代的方法。 执行 ``for`` 循环的关键作用是在被调用的迭代器中播放 ``yield`` 语句。 每当达到 ``yield`` 语句时,数据就会被绑定到 ``for`` 循环变量,并且控制在 ``for`` 循环的主体中继续。 迭代器的局部变量和执行状态在调用之间自动保存。 示例: .. code-block:: nim # 该定义存在于系统模块中 iterator items*(a: string): char {.inline.} = var i = 0 while i < len(a): yield a[i] inc(i) for ch in items("hello world"): # `ch` is an iteration variable echo ch 编译器生成代码就像程序员编写的那样: .. code-block:: nim var i = 0 while i < len(a): var ch = a[i] echo ch inc(i) 如果迭代器产生一个元组,那么迭代变量可以与元组中的组件一样多。 第i个迭代变量的类型是第i个组件的类型。 换句话说,支持for循环上下文中的隐式元组解包。 隐式items和pairs调用 ------------------------------- 如果for循环表达式 ``e`` 不表示迭代器而for循环正好有1个变量,则for循环表达式被重写为 ``items(e)`` ;即隐式调用 ``items`` 迭代器: .. code-block:: nim for x in [1,2,3]: echo x 如果for循环恰好有2个变量,则隐式调用 ``pairs`` 迭代器。 在重写步骤之后执行标识符 ``items`` 或 ``pairs`` 的符号查找,以便考虑所有 ``items`` 或 ``pairs`` 的重载。 第一类迭代器 --------------------- Nim中有两种迭代器: *inline* 和 *closure* 迭代器。 一个 `内联迭代器`:idx: 是一个迭代器,总是由编译器内联,导致抽象的开销为零,但可能导致代码大小的大量增加。 注意:内联迭代器上的for循环体被内联到迭代器代码中出现的每个 ``yield`` 语句中,因此理想情况下,代码应该被重构为包含单个yield,以避免代码膨胀。 内联迭代器是二等公民; 它们只能作为参数传递给其他内联代码工具,如模板、宏和其他内联迭代器。 与此相反, `闭包迭代器`:idx: 可以更自由地传递: .. code-block:: nim iterator count0(): int {.closure.} = yield 0 iterator count2(): int {.closure.} = var x = 1 yield x inc x yield x proc invoke(iter: iterator(): int {.closure.}) = for x in iter(): echo x invoke(count0) invoke(count2) 闭包迭代器和内联迭代器有一些限制: 1. 目前,闭包迭代器无法在编译时执行。 2. 在闭包迭代器中允许 ``return`` 但在内联迭代器中不允许(但很少有用)并结束迭代。 3. 内联和闭包迭代器都不能递归。 4. 内联和闭包迭代器都没有特殊的 ``result`` 变量。 5. js后端不支持闭包迭代器。 迭代器既没有标记为 ``{.closure.}`` 也不是 ``{.inline.}`` 则显式默认内联,但这可能会在未来版本的实现中发生变化。 ``iterator`` 类型总是隐式调用约定 ``closure`` ;以下示例显示如何使用迭代器实现 `协作任务`:idx: 系统: .. code-block:: nim # 简单任务: type Task = iterator (ticker: int) iterator a1(ticker: int) {.closure.} = echo "a1: A" yield echo "a1: B" yield echo "a1: C" yield echo "a1: D" iterator a2(ticker: int) {.closure.} = echo "a2: A" yield echo "a2: B" yield echo "a2: C" proc runTasks(t: varargs[Task]) = var ticker = 0 while true: let x = t[ticker mod t.len] if finished(x): break x(ticker) inc ticker runTasks(a1, a2) 内置的 ``system.finished`` 可用于确定迭代器是否已完成其操作;尝试调用已完成其工作的迭代器时不会引发异常。 注意使用 ``system.finished`` 容易出错,因为它只在迭代器完成下一次迭代返回 ``true`` : .. code-block:: nim iterator mycount(a, b: int): int {.closure.} = var x = a while x <= b: yield x inc x var c = mycount # 实例化迭代器 while not finished(c): echo c(1, 3) # 生成 1 2 3 0 而是必须使用此代码: .. code-block:: nim var c = mycount # 实例化迭代器 while true: let value = c(1, 3) if finished(c): break # 并且丢弃 'value'。 echo value 它用于迭代器返回一对 ``(value,done)`` 和 ``finished`` 用于访问隐藏的 ``done`` 字段。 闭包迭代器是 *可恢复函数* ,因此必须为每个调用提供参数。 为了解决这个限制,可以捕获外部工厂proc的参数: .. code-block:: nim proc mycount(a, b: int): iterator (): int = result = iterator (): int = var x = a while x <= b: yield x inc x let foo = mycount(1, 4) for f in foo(): echo f 转换器 ========== 转换器就像普通的过程,除了它增强了 ``隐式可转换`` 类型关系(参见 `可转换关系`_ ): .. code-block:: nim # 不好的风格:Nim不是C。 converter toBool(x: int): bool = x != 0 if 4: echo "compiles" 还可以显式调用转换器以提高可读性。 请注意,不支持隐式转换器链接:如果存在从类型A到类型B的转换器以及从类型B到类型C的转换器,则不提供从A到C的隐式转换。 Type段 ============= 示例: .. code-block:: nim type # 演示相互递归类型的示例 Node = ref object # 垃圾收集器管理的对象(r​​ef) le, ri: Node # 左右子树 sym: ref Sym # 叶节点含有Sym的引用 Sym = object # 一个符号 name: string # 符号名 line: int # 声明符号的行 code: Node # 符号的抽象语法树 类型部分以 ``type`` 关键字开头。 它包含多个类型定义。 类型定义将类型绑定到名称。 类型定义可以是递归的,甚至可以是相互递归的。 相互递归类型只能在单个 ``type`` 部分中使用。 像 ``objects`` 或 ``enums`` 这样的标称类型只能在 ``type`` 部分中定义。 异常处理 ================== Try语句 ------------- 示例: .. code-block:: nim # 读取应包含数字的文本文件的前两行并尝试添加 var f: File if open(f, "numbers.txt"): try: var a = readLine(f) var b = readLine(f) echo "sum: " & $(parseInt(a) + parseInt(b)) except OverflowError: echo "overflow!" except ValueError: echo "could not convert string to integer" except IOError: echo "IO error!" except: echo "Unknown exception!" finally: close(f) ``try`` 之后的语句按顺序执行,除非引发异常 ``e`` 。 如果 ``e`` 的异常类型匹配 ``except`` 子句中列出的任何类型,则执行相应的语句。 ``except`` 子句后面的语句称为 `异常处理程序`:idx: 。 如果存在未列出的异常,则执行空的 `except`:idx: 子句。 它类似于 ``if`` 语句中的 ``else`` 子句。 如果有一个 `finally`:idx: 子句,它总是在异常处理程序之后执行。 异常处理程序中的 *consume* 异常。 但是,异常处理程序可能会引发另一个异常。 如果未处理异常,则通过调用堆栈传播该异常。 这意味着程序不在 ``finally`` 子句中的其余部分通常不会被执行(如果发生异常)。 Try表达式 -------------- 尝试也可以用作表达式;然后 ``try`` 分支的类型需要适合 ``except`` 分支的类型,但 ``finally`` 分支的类型总是必须是 ``void`` : .. code-block:: nim let x = try: parseInt("133a") except: -1 finally: echo "hi" 为了防止令人困惑的代码,有一个解析限制,如果 ``try`` 跟在一个 ``(`` 它必须写成一行: .. code-block:: nim let x = (try: parseInt("133a") except: -1) 排除从句 -------------- 在 ``except`` 子句中,可以使用以下语法访问当前异常: .. code-block:: nim try: # ... except IOError as e: # Now use "e" echo "I/O error: " & e.msg 或者,可以使用 ``getCurrentException`` 来检索已经引发的异常: .. code-block:: nim try: # ... except IOError: let e = getCurrentException() # 现在使用"e" 注意 ``getCurrentException`` 总是返回一个 ``ref Exception`` 类型。 如果需要一个正确类型的变量(在上面的例子中,``IOError`` ),必须明确地转换它: .. code-block:: nim try: # ... except IOError: let e = (ref IOError)(getCurrentException()) # "e"现在是合适的类型 但是,这很少需要。 最常见的情况是从 ``e`` 中提取错误消息,对于这种情况,使用 ``getCurrentExceptionMsg`` 就足够了: .. code-block:: nim try: # ... except: echo getCurrentExceptionMsg() Defer语句 --------------- 可以使用 ``defer`` 语句而不是 ``try finally`` 语句。 当前块中 ``defer`` 之后的任何语句都将被视为隐式try块: .. code-block:: nim :test: "nim c $1" proc main = var f = open("numbers.txt") defer: close(f) f.write "abc" f.write "def" 被重写为: .. code-block:: nim :test: "nim c $1" proc main = var f = open("numbers.txt") try: f.write "abc" f.write "def" finally: close(f) 不支持顶级 ``defer`` 语句,因为不清楚这样的语句应该引用什么。 Raise语句 --------------- 示例: .. code-block:: nim raise newEOS("operating system failed") 除了数组索引,内存分配等内置操作之外,``raise`` 语句是引发异常的唯一方法。 .. XXX document this better! 如果没有给出异常名称,则当前异常会 `re-raised`:idx: 。 如果没有异常重新加注,则引发 `ReraiseError`:idx:异常。 因此, ``raise`` 语句 *总是* 引发异常。 异常层级 ------------------- 异常树在 `system <system.html>`_ 模块中定义。 每个异常都继承自 ``system.Exception`` 。 表示编程错误的异常继承自``system.Defect``(它是``Exception``的子类型)并严格地说是不可捕获的,因为它们也可以映射到终止整个过程的操作。 表示可以捕获的任何其他运行时错误的异常继承自 ``system.CatchableError``(这是 ``Exception`` 的子类型)。 导入的异常 ------------------- 可以引发和捕获导入的C++异常。 使用 `importcpp` 导入的类型可以被引发或捕获。例外是通过值引发并通过引用捕获。 示例: .. code-block:: nim type std_exception {.importcpp: "std::exception", header: "<exception>".} = object proc what(s: std_exception): cstring {.importcpp: "((char *)#.what())".} try: raise std_exception() except std_exception as ex: echo ex.what() 效应系统 ============= 异常跟踪 ------------------ Nim支持异常跟踪。 `raises`:idx: 编译器可用于显式定义允许proc/iterator/method/converter引发的异常。编译器验证这个: .. code-block:: nim :test: "nim c $1" proc p(what: bool) {.raises: [IOError, OSError].} = if what: raise newException(IOError, "IO") else: raise newException(OSError, "OS") 一个空的 ``raises`` 列表( ``raises:[]`` )意味着不会引发任何异常: .. code-block:: nim proc p(): bool {.raises: [].} = try: unsafeCall() result = true except: result = false ``raises`` 列表也可以附加到proc类型。这会影响类型兼容性: .. code-block:: nim :test: "nim c $1" :status: 1 type Callback = proc (s: string) {.raises: [IOError].} var c: Callback proc p(x: string) = raise newException(OSError, "OS") c = p # 类型错误 对于例程 ``p`` ,编译器使用推理规则来确定可能引发的异常集;算法在 ``p`` 的调用图上运行: 1.通过某些proc类型 ``T`` 的每个间接调用都被假定为引发 ``system.Exception`` (异常层次结构的基本类型),因此除非 ``T`` 有明确的 ``raises`` 列表。 但是如果调用的形式是 ``f(...)`` 其中 ``f`` 是当前分析的例程的参数,则忽略它。 乐观地认为该呼叫没有效果。规则2补偿了这种情况。 2.假定在一个不是调用本身(而不是nil)的调用中的某些proc类型的每个表达式都以某种方式间接调用,因此它的引发列表被添加到 ``p`` 的引发列表中。 3.对前向声明或 ``importc`` 编译指示的未知proc ``q`` 的每次调用,假定会引发 ``system.Exception`` ,除非 ``q`` 有一个明确的 ``raises`` 列表。 4.每次对方法 ``m`` 的调用都会被假定为引发 ``system.Exception`` ,除非 ``m`` 有一个明确的 ``raises`` 列表。 5.对于每个其他调用,分析可以确定一个确切的 ``raises`` 列表。 6.为了确定 ``raises`` 列表,考虑 ``p`` 的 ``raise`` 和 ``try`` 语句。 规则1-2确保下面的代码正常工作: .. code-block:: nim proc noRaise(x: proc()) {.raises: [].} = # 可能引发任何异常的未知调用, 但这是合法的: x() proc doRaise() {.raises: [IOError].} = raise newException(IOError, "IO") proc use() {.raises: [].} = # 不能编译, 可能引发IOError。 noRaise(doRaise) 因此,在许多情况下,回调不会导致编译器在其效果分析中过于保守。 Tag跟踪 ------------ 异常跟踪是Nim `效应系统`:idx: 的一部分。 引发异常是 *效应* 。 其他效应也可以定义。 用户定义的效应是 *标记* 例程并对此标记执行检查的方法: .. code-block:: nim :test: "nim c $1" :status: 1 type IO = object ## input/output effect proc readLine(): string {.tags: [IO].} = discard proc no_IO_please() {.tags: [].} = # the compiler prevents this: let x = readLine() 标签必须是类型名称。一个 ``tags`` 列表 - 就像一个 ``raises`` 列表 - 也可以附加到一个proc类型。 这会影响类型兼容性。 标签跟踪的推断类似于异常跟踪的推断。 Effects编译指示 -------------- ``effects`` 编译指示旨在帮助程序员进行效果分析。 这是一个声明,使编译器将所有推断的效果输出到 ``effects`` 的位置: .. code-block:: nim proc p(what: bool) = if what: raise newException(IOError, "IO") {.effects.} else: raise newException(OSError, "OS") 编译器生成一条提示消息,可以引发 ``IOError`` 。 未列出 ``OSError`` ,因为它不能在分支中引发 ``effects`` 编译指示。 泛型 ======== 泛型是Nim用 `类型形参`:idx: 参数化过程、迭代器或类型的方法 。 根据上下文,括号用于引入类型形参或实例化泛型过程、迭代器或类型。 以下示例显示了可以建模的通用二叉树: .. code-block:: nim :test: "nim c $1" type BinaryTree*[T] = ref object # 二叉树是左右子树带有泛型形参 ``T`` 的泛型类型,其值可能为nil le, ri: BinaryTree[T] data: T # 数据存储在节点中。 proc newNode*[T](data: T): BinaryTree[T] = # 构造一个节点 result = BinaryTree[T](le: nil, ri: nil, data: data) proc add*[T](root: var BinaryTree[T], n: BinaryTree[T]) = # 把节点插入到一颗树 if root == nil: root = n else: var it = root while it != nil: # 比较数据项;使用泛型 ``cmp`` proc,适用于任何具有``==``和````运算符的类型 var c = cmp(it.data, n.data) if c < 0: if it.le == nil: it.le = n return it = it.le else: if it.ri == nil: it.ri = n return it = it.ri proc add*[T](root: var BinaryTree[T], data: T) = # 便利过程: add(root, newNode(data)) iterator preorder*[T](root: BinaryTree[T]): T = # 前序遍历二叉树 # 由于递归迭代器尚未实现,因此它使用显式堆栈(因为更高效): var stack: seq[BinaryTree[T]] = @[root] while stack.len > 0: var n = stack.pop() while n != nil: yield n.data add(stack, n.ri) # 将右子树推入堆栈 n = n.le # 跟着左指针 var root: BinaryTree[string] # 使用 ``string`` 实例化二叉树 add(root, newNode("hello")) # 实例化 ``newNode`` 和 ``add`` add(root, "world") # 实例化第二个 ``add`` proc for str in preorder(root): stdout.writeLine(str) ``T`` 被称为 `泛型类型形参`:idx: 或 `类型变量`:idx: 。 Is操作符 ----------- 在语义分析期间评估 ``is`` 运算符以检查类型等价。 因此,它对于泛型代码中的类型特化非常有用: .. code-block:: nim type Table[Key, Value] = object keys: seq[Key] values: seq[Value] when not (Key is string): # 用于优化的字符串的空值 deletedKeys: seq[bool] 类型类别 ------------ 类型类是一种特殊的伪类型,可用于匹配重载决策或 ``is`` 运算符中的类型。 Nim支持以下内置类型类: ================== =================================================== 类型 匹配 ================== =================================================== ``object`` 任意对象类型 ``tuple`` 任意元组类型 ``enum`` 任意枚举 ``proc`` 任意过程类型 ``ref`` 任意 ``ref`` 类型 ``ptr`` 任意 ``ptr`` 类型 ``var`` 任意 ``var`` 类型 ``distinct`` 任意distinct类型 ``array`` 任意数组array类型 ``set`` 任意set类型 ``seq`` 任意seq类型 ``auto`` 任意类型 ``any`` distinct auto (见下方) ================== =================================================== 此外,每个泛型类型都会自动创建一个与通用类型的任何实例化相匹配的相同名称的类型类。 可以使用标准布尔运算符组合类型类,以形成更复杂的类型类: .. code-block:: nim # 创建一个匹配所有元组和对象类型的类型类 type RecordType = tuple or object proc printFields(rec: RecordType) = for key, value in fieldPairs(rec): echo key, " = ", value 以这种方式使用类型类的过程被认为是 `隐式通用的`:idx: 。 对于程序中使用的每个唯一的param类型组合,它们将被实例化一次。 虽然类型类的语法看起来类似于ML的语言中的ADT /代数数据类型,但应该理解类型类是类型实例化时强制执行的静态约束。 类型类不是真正的类型,而是一个提供通用“检查”的系统,最终将 *解析* 为某种单一类型。 与对象变体或方法不同,类型类不允许运行时类型动态。 例如,以下内容无法编译: .. code-block:: nim type TypeClass = int | string var foo: TypeClass = 2 # foo的类型在这里解析为int foo = "this will fail" # 错误在这里,因为foo是一个int Nim允许将类型类和常规类型指定为 `类型限制`:idx: 泛型类型参数: .. code-block:: nim proc onlyIntOrString[T: int|string](x, y: T) = discard onlyIntOrString(450, 616) # 合法 onlyIntOrString(5.0, 0.0) # 类型不匹配 onlyIntOrString("xy", 50) # 不合法因为 'T' 不能同时是两种类型 默认情况下,在重载解析期间,每个命名类型类将仅绑定到一个具体类型。 我们称这样的类类为 `绑定一次`:idx: 类型。 以下是直接从系统模块中抽取的用于展示的示例: .. code-block:: nim proc `==`*(x, y: tuple): bool = ## 要求 `x` and `y` 是同样的元组类型 ## 从 `x` 和 `y` 部分中提升的元组泛型 ``==`` 操作符。 result = true for a, b in fields(x, y): if a != b: result = false 或者,可以将 ``distinct`` 类型修饰符应用于类型类,以允许与类型类匹配的每个参数绑定到不同的类型。 这种类型类称为 `绑定多次`:idx: 类型 使用隐式通用样式编写的过程通常需要引用匹配泛型类型的类型参数。 可以使用点语法轻松访问它们: .. code-block:: nim type Matrix[T, Rows, Columns] = object ... proc `[]`(m: Matrix, row, col: int): Matrix.T = m.data[col * high(Matrix.Columns) + row] 或者,当使用匿名或不同类型类时,可以在proc参数上使用 `type` 运算符以获得类似的效果。 当使用类型类而不是具体类型实例化泛型类型时,这会产生另一个更具体的类型类: .. code-block:: nim seq[ref object] # 存储任意对象类型引用的序列 type T1 = auto proc foo(s: seq[T1], e: T1) # seq[T1]与 `seq` 相同,但T1允许当签名匹配时绑定到单个类型 Matrix[Ordinal] # 任何使用整数值的矩阵实例化 如前面的例子所示,在这样的实例化中,没有必要提供泛型类型的所有类型参数,因为任何缺失的参数都将被推断为具有 `any` 类型的等价物,因此它们将匹配任何类型而不受歧视。 泛型推导限制 ------------------------------ 类型 ``var T`` 和 ``typedesc [T]`` 不能在泛型实例中推断出来。以下是不允许的: .. code-block:: nim :test: "nim c $1" :status: 1 proc g[T](f: proc(x: T); x: T) = f(x) proc c(y: int) = echo y proc v(y: var int) = y += 100 var i: int # 允许:推断 'T' 为 'int' 类型 g(c, 42) # 无效:'T'不推断为'var int'类型 g(v, i) # 也不允许:通过'var int'进行显式实例化 g[var int](v, i) 泛型符号查找 ------------------------- 开放和封闭的符号 ~~~~~~~~~~~~~~~~~~~~~~~ 泛型中的符号绑定规则比较微妙:有“开放”和“封闭”符号。 “封闭”符号不能在实例化上下文中重新绑定,“开放”符号可以。 默认重载符号是打开的,每个其他符号都是关闭的。 在两个不同的上下文中查找开放符号:定义上下文和实例化时的上下文都被考虑: .. code-block:: nim :test: "nim c $1" type Index = distinct int proc `==` (a, b: Index): bool {.borrow.} var a = (0, 0.Index) var b = (0, 0.Index) echo a == b # 可以了 在示例中,元组的通用 ``==`` (在系统模块中定义)使用元组组件的 ``==`` 运算符。 但是, ``Index`` 类型的 ``==`` 是在元组的 ``==`` *之后* 定义的;然而,该示例编译为实例化也将当前定义的符号考虑在内。 Mixin语句 --------------- 可以通过 `mixin`:idx: 强制打开符号声明: .. code-block:: nim :test: "nim c $1" proc create*[T](): ref T = # 这里没有重载'init',所以我们需要明确说明它是一个开放的符号: mixin init new result init result ``mixin`` 语句只在模板和泛型中有意义。 Bind语句 -------------- ``bind`` 语句是 ``mixin`` 语句的对应语句。 它可以用于显式声明应该提前绑定的标识符(即标识符应该在模板/泛型定义的范围内查找): .. code-block:: nim # 模块A var lastId = 0 template genId*: untyped = bind lastId inc(lastId) lastId .. code-block:: nim # 模块B import A echo genId() 但是 ``bind`` 很少有用,因为符号绑定默认来自定义的作用域。 ``bind`` 语句只在模板和泛型中有意义。 模板 ========= 模板是宏的一种简单形式:它是一种简单的替换机制,可以在Nim的抽象语法树上运行。 它在编译器的语义传递中处理。 *调用* 模板的语法与调用过程相同。 示例: .. code-block:: nim template `!=` (a, b: untyped): untyped = # 此定义存在于系统模块中 not (a == b) assert(5 != 6) # 编译器将其重写为:: assert(not (5 == 6)) ``!=``, ``>``, ``>=``, ``in``, ``notin``, ``isnot`` 运算符实际上是模板: | ``a > b`` 变换成 ``b < a``. | ``a in b`` 变换成 ``contains(b, a)``. | ``notin`` 和 ``isnot`` 见名知意。 模板的“类型”可以是符号 ``untyped`` , ``typed`` 或 ``typedesc`` 。 这些是“元类型”,它们只能在某些上下文中使用。 也可以使用常规类型;这意味着需要 ``typed`` 表达式。 类型化和无类型形参 --------------------------- ``无类型`` 参数表示在将表达式传递给模板之前不执行符号查找和类型解析。 这意味着例如 *未声明* 标识符可以传递给模板: .. code-block:: nim :test: "nim c $1" template declareInt(x: untyped) = var x: int declareInt(x) # 有效 x = 3 .. code-block:: nim :test: "nim c $1" :status: 1 template declareInt(x: typed) = var x: int declareInt(x) # 无效,因为x尚未声明,因此没有类型 每个参数都是 ``无类型`` 的模板称为 `立即`:idx: 模板。 由于历史原因模板可以使用 ``立即`` 编译指示进行显式注释,然后这些模板不会参与重载分辨率,编译器会 *忽略* 参数的类型。 现在不推荐使用显式立即模板。 **注意**: 由于历史原因 ``stmt`` 是类型化 ``typed`` 的别名, ``expr`` 是无类型 ``untyped`` 的别名, 但他们被移除了。 向模板传代码块 ---------------------------------- 您可以在特殊的 ``:`` 语法之后将一个语句块作为最后一个参数传递给模板: .. code-block:: nim :test: "nim c $1" template withFile(f, fn, mode, actions: untyped): untyped = var f: File if open(f, fn, mode): try: actions finally: close(f) else: quit("cannot open: " & fn) withFile(txt, "ttempl3.txt", fmWrite): # 特殊冒号 txt.writeLine("line 1") txt.writeLine("line 2") 在这个例子中,两个 ``writeLine`` 语句绑定到 ``actions`` 参数。 通常将一块代码传递给模板,接受块的参数需要是“untyped”类型。 因为符号查找会延迟到模板实例化时间: .. code-block:: nim :test: "nim c $1" :status: 1 template t(body: typed) = block: body t: var i = 1 echo i t: var i = 2 # '尝试重新声明i'失败 echo i 上面的代码因已经声明了 ``i`` 的错误信息失败。 原因是 ``var i = ...`` 需要在传递给 ``body`` 参数之前进行类型检查,而Nim中的类型检查意味着符号查找。 为了使符号查找成功,需要将 ``i`` 添加到当前(即外部)范围。 在类型检查之后,这些对符号表的添加不会回滚(无论好坏)。 同样的代码可以用 ``untyped`` ,因为传递的主体不需要进行类型检查: .. code-block:: nim :test: "nim c $1" template t(body: untyped) = block: body t: var i = 1 echo i t: var i = 2 # 编译 echo i 无类型可变参数 ------------------ 除了 ``untyped`` 元类型防止类型检查之外, ``varargs[untyped]`` 甚至连参数的数量都可以不确定: .. code-block:: nim :test: "nim c $1" template hideIdentifiers(x: varargs[untyped]) = discard hideIdentifiers(undeclared1, undeclared2) 但是,由于模板无法通过varargs进行迭代,因此该功能通常对宏非常有用。 模板符号绑定 --------------------------- 模板是 `卫生`:idx: 宏,它打开了一个新的作用域。大多数符号都是从模板的定义作用域绑定的: .. code-block:: nim # 模块A var lastId = 0 template genId*: untyped = inc(lastId) lastId .. code-block:: nim # 模块B import A echo genId() # 'lastId'已被'genId'的定义作用域所约束 在泛型中,``mixin`` 或 ``bind`` 语句可以影响符号绑定。 标识符构造 ----------------------- 在模板中,可以使用反引号表示法构造标识符: .. code-block:: nim :test: "nim c $1" template typedef(name: untyped, typ: typedesc) = type `T name`* {.inject.} = typ `P name`* {.inject.} = ref `T name` typedef(myint, int) var x: PMyInt 示例中 ``name`` 用 ``myint`` 实例化,所以 \`T name\` 变为 ``Tmyint`` 。 模板形参查询规则 ------------------------------------ 模板中的参数 ``p`` 甚至在表达式 ``x.p`` 中被替换。 因此,模板参数可以用作字段名称,也可以使用相同的参数名称对限定的全局符号进行隐藏: .. code-block:: nim # 模块'm' type Lev = enum levA, levB var abclev = levB template tstLev(abclev: Lev) = echo abclev, " ", m.abclev tstLev(levA) # 生成: 'levA levA' 但是可以通过 ``bind`` 语句正确捕获全局符号: .. code-block:: nim # 模块'm' type Lev = enum levA, levB var abclev = levB template tstLev(abclev: Lev) = bind m.abclev echo abclev, " ", m.abclev tstLev(levA) # 生成: 'levA levB' 模板卫生 -------------------- 每个默认模板是 `卫生的`:idx:\: 无法在实例化上下文中访问模板中声明的本地标识符: .. code-block:: nim :test: "nim c $1" template newException*(exceptn: typedesc, message: string): untyped = var e: ref exceptn # e是隐式符号生成 new(e) e.msg = message e # 所以这是可以的: let e = "message" raise newException(IoError, e) 是否在模板中声明的符号是否暴露给实例化范围由 `inject`:idx: 和 `gensym`:idx: 编译指示控制,gensym的符号不会暴露而是注入。 ``type``, ``var``, ``let`` 和 ``const`` 的实体符号默认是 ``gensym`` ,``proc``, ``iterator``, ``converter``, ``template``, ``macro`` 是 ``inject``. 但是,如果实体的名称作为模板参数传递,则它是一个注入符号: .. code-block:: nim template withFile(f, fn, mode: untyped, actions: untyped): untyped = block: var f: File # 因为'f'是模板形参,它被隐式注入 ... withFile(txt, "ttempl3.txt", fmWrite): txt.writeLine("line 1") txt.writeLine("line 2") ``inject`` 和 ``gensym`` 编译指示是二等注释;它们在模板定义之外没有语义,不能被抽象: .. code-block:: nim {.pragma myInject: inject.} template t() = var x {.myInject.}: int # 不行 为了摆脱模板中的卫生,可以为模板使用 `dirty`:idx: 编译指示。 ``inject`` 和 ``gensym`` 在 ``dirty`` 模板中没有意义。 方法调用语法限制 ------------------------------------- ``x.f`` 中的表达式 ``x`` 需要进行语义检查(即符号查找和类型检查),然后才能确定需要将其重写为 ``f(x)`` 。 因此,当用于调用模板/宏时,点语法有一些限制: .. code-block:: nim :test: "nim c $1" :status: 1 template declareVar(name: untyped) = const name {.inject.} = 45 # 不能编译: unknownIdentifier.declareVar 另一个常见的例子是: .. code-block:: nim :test: "nim c $1" :status: 1 from sequtils import toSeq iterator something: string = yield "Hello" yield "World" var info = something().toSeq 这里的问题是编译器已经决定 ``something()`` 作为迭代器在 ``toSeq`` 将其转换为序列之前不可调用。 It is also not possible to use fully qualified identifiers with module symbol in method call syntax. The order in which the dot operator binds to symbols prohibits this. .. code-block:: nim :test: "nim c $1" :status: 1 import sequtils var myItems = @[1,3,3,7] let N1 = count(myItems, 3) # OK let N2 = sequtils.count(myItems, 3) # fully qualified, OK let N3 = myItems.count(3) # OK let N4 = myItems.sequtils.count(3) # illegal, `myItems.sequtils` can't be resolved This means that when for some reason a procedure needs a disambiguation through the module name, the call needs to be written in function call syntax. 宏 ====== 宏是在编译时执行的特殊函数。 通常,宏的输入是传递给它的代码的抽象语法树(AST)。 然后,宏可以对其进行转换并返回转换后的AST。 这可用于添加自定义语言功能并实现 `领域特定语言(DSL)`:idx: 。 宏调用是一种语义分析 *不* 会完全从上到下,从左到右进行的情况。相反,语义分析至少发生两次: * 语义分析识别并解析宏调用。 * 编译器执行宏体(可以调用其他触发器)。 * 它将宏调用的AST替换为宏返回的AST。 * 它重复了代码区域的语义分析。 * 如果宏返回的AST包含其他宏调用,则此过程将进行迭代。 虽然宏启用了高级编译时代码转换,但它们无法更改Nim的语法。 但是,这并不是真正的限制因为Nim的语法无论如何都足够灵活。 Debug示例 ------------- 以下示例实现了一个强大的 ``debug`` 命令,该命令接受可变数量的参数: .. code-block:: nim :test: "nim c $1" # 使用Nim语法树,我们需要一个在``macros``模块中定义的API: import macros macro debug(args: varargs[untyped]): untyped = # `args` 是 `NimNode` 值的集合,每个值都包含宏的参数的AST。 # 宏总是必须返回一个 `NimNode` 。 # 类型为 `nnkStmtList` 的节点适用于此用例。 result = nnkStmtList.newTree() # 迭代传递给此宏的任何参数: for n in args: # 添加对写入表达式的语句列表的调用; # `toStrLit` 将AST转换为其字符串表示形式: result.add newCall("write", newIdentNode("stdout"), newLit(n.repr)) # 添加对写入“:”的语句列表的调用 result.add newCall("write", newIdentNode("stdout"), newLit(": ")) # 添加对写入表达式值的语句列表的调用: result.add newCall("writeLine", newIdentNode("stdout"), n) var a: array[0..10, int] x = "some string" a[0] = 42 a[1] = 45 debug(a[0], a[1], x) 宏调用扩展成: .. code-block:: nim write(stdout, "a[0]") write(stdout, ": ") writeLine(stdout, a[0]) write(stdout, "a[1]") write(stdout, ": ") writeLine(stdout, a[1]) write(stdout, "x") write(stdout, ": ") writeLine(stdout, x) 传递给 ``varargs`` 参数的参数包含在数组构造函数表达式中。 这就是为什么 ``debug`` 遍历所有 ``n`` 的子节点。 BindSym ------- 上面的 ``debug`` 宏依赖于 ``write`` , ``writeLine`` 和 ``stdout`` 在系统模块中声明的事实,因此在实例化的上下文中可见。 有一种方法可以使用绑定标识符(又名 `符号`:idx:)而不是使用未绑定的标识符。 内置的 ``bindSym`` 可以用于: .. code-block:: nim :test: "nim c $1" import macros macro debug(n: varargs[typed]): untyped = result = newNimNode(nnkStmtList, n) for x in n: # 我们可以在作用域中通过'bindSym'绑定符号: add(result, newCall(bindSym"write", bindSym"stdout", toStrLit(x))) add(result, newCall(bindSym"write", bindSym"stdout", newStrLitNode(": "))) add(result, newCall(bindSym"writeLine", bindSym"stdout", x)) var a: array[0..10, int] x = "some string" a[0] = 42 a[1] = 45 debug(a[0], a[1], x) 宏调用扩展为: .. code-block:: nim write(stdout, "a[0]") write(stdout, ": ") writeLine(stdout, a[0]) write(stdout, "a[1]") write(stdout, ": ") writeLine(stdout, a[1]) write(stdout, "x") write(stdout, ": ") writeLine(stdout, x) 但是,符号 ``write`` , ``writeLine`` 和 ``stdout`` 已经绑定,不再被查找。如示例所示, ``bindSym`` 可以隐式地处理重载符号。 Case-Of宏 ------------- 在Nim中,可以使用具有 *case-of* 表达式的语法的宏,区别在于所有分支都传递给宏实现并由宏实现处理。 然后是宏实现将 *of-branches* 转换为有效的Nim语句。 以下示例应显示如何将此功能用于词法分析器。 .. code-block:: nim import macros macro case_token(args: varargs[untyped]): untyped = echo args.treeRepr # 从正则表达式创建词法分析器 # ... (实现留给读者作为练习 ;-) discard case_token: # 这个冒号告诉解析器它是一个宏语句 of r"[A-Za-z_]+[A-Za-z_0-9]*": return tkIdentifier of r"0-9+": return tkInteger of r"[\+\-\*\?]+": return tkOperator else: return tkUnknown **风格注释** :为了代码可读性,最好使用功能最少但仍然足够的编程结构。所以“检查清单”是: (1) 如果可能,请使用普通的proc和iterator。 (2) 否则:如果可能,使用泛型的proc和iterator。 (3) 否则:如果可能,请使用模板。 (4) 否则:使用宏。 Macros用作编译指示 ----------------- 整个例程(procs,iterators等)也可以通过编译指示表示法传递给模板或宏: .. code-block:: nim template m(s: untyped) = discard proc p() {.m.} = discard 这是一个简单的语法转换: .. code-block:: nim template m(s: untyped) = discard m: proc p() = discard For循环宏 -------------- 一个宏作为唯一的输入参数,特殊类型 ``system.ForLoopStmt`` 的表达式可以重写整个 ``for`` 循环: .. code-block:: nim :test: "nim c $1" import macros {.experimental: "forLoopMacros".} macro enumerate(x: ForLoopStmt): untyped = expectKind x, nnkForStmt # 我们剥离第一个for循环变量并将其用作整数计数器: result = newStmtList() result.add newVarStmt(x[0], newLit(0)) var body = x[^1] if body.kind != nnkStmtList: body = newTree(nnkStmtList, body) body.add newCall(bindSym"inc", x[0]) var newFor = newTree(nnkForStmt) for i in 1..x.len-3: newFor.add x[i] # 将枚举(X)转换为'X' newFor.add x[^2][1] newFor.add body result.add newFor # 现在将整个宏包装在一个块中以创建一个新的作用域 result = quote do: block: `result` for a, b in enumerate(items([1, 2, 3])): echo a, " ", b # 没有将宏包装在一个块中,我们需要在这里为 `a` 和 `b` 选择不同的名称以避免重定义错误 for a, b in enumerate([1, 2, 3, 5]): echo a, " ", b 目前,必须通过 ``{.experimental: "forLoopMacros".}`` 显式启用循环宏。 特殊类型 ============= static[T] --------- 顾名思义,静态参数必须是常量表达式: .. code-block:: nim proc precompiledRegex(pattern: static string): RegEx = var res {.global.} = re(pattern) return res precompiledRegex("/d+") # 用预编译的正则表达式替换调用,存储在全局变量中 precompiledRegex(paramStr(1)) # 错误,命令行选项不是常量表达式 出于代码生成的目的,所有静态参数都被视为通用参数 - proc将针对每个唯一提供的值(或值的组合)单独编译。 静态参数也可以出现在泛型类型的签名中: .. code-block:: nim type Matrix[M,N: static int; T: Number] = array[0..(M*N - 1), T] # 注意 `Number` 在这里只是一个类型约束,而 `static int` 要求我们提供一个int值 AffineTransform2D[T] = Matrix[3, 3, T] AffineTransform3D[T] = Matrix[4, 4, T] var m1: AffineTransform3D[float] # 正确 var m2: AffineTransform2D[string] # 错误 `string`不是`Number` 请注意,``static T`` 只是底层泛型类型 ``static[T]`` 的语法方便。 可以省略类型参数以获取所有常量表达式的类型类。 可以通过使用另一个类型类实例化 ``static`` 来创建更具体的类型类。 您可以通过将表达式强制转换为相应的 ``static`` 类型来强制将表达式在编译时作为常量表达式进行求值: .. code-block:: nim import math echo static(fac(5)), " ", static[bool](16.isPowerOfTwo) 编译器将报告任何未能评估表达式或可能的类型不匹配错误。 typedesc[T] ----------- 在许多情况下,Nim允许您将类型的名称视为常规值。 这些值仅在编译阶段存在,但由于所有值必须具有类型,因此 ``typedesc`` 被视为其特殊类型。 ``typedesc`` 就像一个通用类型。例如,符号 ``int`` 的类型是 ``typedesc [int]`` 。 就像常规泛型类型一样,当泛型参数被省略时, ``typedesc`` 表示所有类型的类型类。 作为一种语法方便,您还可以使用 ``typedesc`` 作为修饰符。 具有 ``typedesc`` 参数的过程被认为是隐式通用的。 它们将针对提供的类型的每个唯一组合进行实例化,并且在proc的主体内,每个参数的名称将引用绑定的具体类型: .. code-block:: nim proc new(T: typedesc): ref T = echo "allocating ", T.name new(result) var n = Node.new var tree = new(BinaryTree[int]) 当存在多种类型的参数时,它们将自由地绑定到不同类型。 要强制绑定一次行为,可以使用显式通用参数: .. code-block:: nim proc acceptOnlyTypePairs[T, U](A, B: typedesc[T]; C, D: typedesc[U]) 绑定后,类型参数可以出现在proc签名的其余部分中: .. code-block:: nim :test: "nim c $1" template declareVariableWithType(T: typedesc, value: T) = var x: T = value declareVariableWithType int, 42 通过约束与类型参数匹配的类型集,可以进一步影响重载解析。 这在实践中通过模板将属性附加到类型。 约束可以是具体类型或类型类。 .. code-block:: nim :test: "nim c $1" template maxval(T: typedesc[int]): int = high(int) template maxval(T: typedesc[float]): float = Inf var i = int.maxval var f = float.maxval when false: var s = string.maxval # 错误,没有为字符串实现maxval template isNumber(t: typedesc[object]): string = "Don't think so." template isNumber(t: typedesc[SomeInteger]): string = "Yes!" template isNumber(t: typedesc[SomeFloat]): string = "Maybe, could be NaN." echo "is int a number? ", isNumber(int) echo "is float a number? ", isNumber(float) echo "is RootObj a number? ", isNumber(RootObj) 传递 ``typedesc`` 几乎完全相同,只是因为宏没有一般地实例化。 类型表达式简单地作为 ``NimNode`` 传递给宏,就像其他所有东西一样。 .. code-block:: nim import macros macro forwardType(arg: typedesc): typedesc = # ``arg`` 是 ``NimNode`` 类型 let tmp: NimNode = arg result = tmp var tmp: forwardType(int) typeof操作符 --------------- **注意**: ``typeof(x)`` 由于历史原因也可以写成 ``type(x)`` ,但不鼓励。 您可以通过从中构造一个 ``typeof`` 值来获取给定表达式的类型(在许多其他语言中,这被称为 `typeof`:idx: 操作符): .. code-block:: nim var x = 0 var y: typeof(x) # y has type int 如果 ``typeof`` 用于确定proc/iterator/converter ``c(X)`` 调用的结果类型(其中``X``代表可能为空的参数列表),首选将 ``c`` 解释为迭代器,这种可以通过将 ``typeOfProc`` 作为第二个参数传递给 ``typeof`` 来改变: .. code-block:: nim :test: "nim c $1" iterator split(s: string): string = discard proc split(s: string): seq[string] = discard # 因为迭代器是首选解释,`y` 的类型为 ``string`` : assert typeof("a b c".split) is string assert typeof("a b c".split, typeOfProc) is seq[string] 模块 ======= Nim支持通过模块概念将程序拆分为多个部分。 每个模块都需要在自己的文件中,并且有自己的 `命名空间`:idx: 。 模块启用 `信息隐藏`:idx: and `分开编译`:idx: 。 模块可以通过 `import`:idx: 语句访问另一个模块的符号。 `递归模块依赖`:idx: 是允许的,但有点微妙。 仅导出标有星号(``*``)的顶级符号。 有效的模块名称只能是有效的Nim标识符(因此其文件名为 ``标识符.nim`` )。 编译模块的算法是: - 像往常一样编译整个模块,递归地执行import语句 - 如果有一个只导入已解析的(即导出的)符号的环;如果出现未知标识符则中止 这可以通过一个例子来说明: .. code-block:: nim # 模块A type T1* = int # 模块A导出类型 ``T1`` import B # 编译器开始解析B proc main() = var i = p(3) # 因为B在这里被完全解析了 main() .. code-block:: nim # 模块 B import A # 这里没有解析A,仅导入已知的A符号。 proc p*(x: A.T1): A.T1 = # 这是有效的,因为编译器已经将T1添加到A的接口符号表中 result = x + 1 Import语句 ~~~~~~~~~~~~~~~~ 在 ``import`` 语句之后,可以跟随模块名称列表或单个模块名称后跟 ``except`` 列表以防止导入某些符号: .. code-block:: nim :test: "nim c $1" :status: 1 import strutils except `%`, toUpperAscii # 行不通: echo "$1" % "abc".toUpperAscii 没有检查 ``except`` 列表是否真的从模块中导出。 此功能允许针对不导出这些标识符的旧版本模块进行编译。 Include语句 ~~~~~~~~~~~~~~~~~ ``include`` 语句与导入模块有着根本的不同:​​它只包含文件的内容。 ``include`` 语句对于将大模块拆分为多个文件很有用: .. code-block:: nim include fileA, fileB, fileC 导入的模块名 ~~~~~~~~~~~~~~~~~~~~~~~ 可以通过 ``as`` 关键字引入模块别名: .. code-block:: nim import strutils as su, sequtils as qu echo su.format("$1", "lalelu") 然后无法访问原始模块名称。 符号 ``path/to/module`` 或 ``"path/to/module"`` 可用于引用子目录中的模块: .. code-block:: nim import lib/pure/os, "lib/pure/times" 请注意,模块名称仍然是 ``strutils`` 而不是 ``lib/pure/strutils`` 因此 **无法** 做: .. code-block:: nim import lib/pure/strutils echo lib/pure/strutils.toUpperAscii("abc") 同样,以下内容没有意义,因为名称已经是 ``strutils`` : .. code-block:: nim import lib/pure/strutils as strutils 从目录中集体导入 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 语法 ``import dir / [moduleA, moduleB]`` 可用于从同一目录导入多个模块。 路径名在语法上是Nim标识符或字符串文字。如果路径名不是有效的Nim标识符,则它必须是字符串文字: .. code-block:: nim import "gfx/3d/somemodule" # 在引号中因为'3d'不是有效的Nim标识符 伪import/include目录 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 目录也可以是所谓的“伪目录”。当存在多个具有相同路径的模块时,它们可用于避免歧义。 有两个伪目录: 1. ``std``: ``std`` 伪目录是Nim标准库的抽象位置。 例如,语法 ``import std / strutils`` 用于明确地引用标准库的 ``strutils`` 模块。 2. ``pkg``: ``pkg`` 伪目录用于明确引用Nimble包。 但是,对于超出本文档范围的技术细节,其语义为:*使用搜索路径查找模块名称但忽略标准库位置* 。 换句话说,它与 ``std`` 相反。 From import语句 ~~~~~~~~~~~~~~~~~~~~~ 在 ``from`` 语句之后,一个模块名称后面跟着一个 ``import`` 来列出一个人喜欢使用的符号而没有明确的完全限定: .. code-block:: nim :test: "nim c $1" from strutils import `%` echo "$1" % "abc" # 可能:完全限定: echo strutils.replace("abc", "a", "z") 如果想要导入模块但是想要对 ``module`` 中的每个符号进行完全限定访问,也可以使用 ``from module import nil`` 。 Export语句 ~~~~~~~~~~~~~~~~ ``export`` 语句可用于符号转发,因此客户端模块不需要导入模块的依赖项: .. code-block:: nim # 模块B type MyObject* = object .. code-block:: nim # 模块A import B export B.MyObject proc `$`*(x: MyObject): string = "my object" .. code-block:: nim # 模块C import A # B.MyObject这里已经被隐式导入: var x: MyObject echo $x 当导出的符号是另一个模块时,将转发其所有定义。您可以使用 ``except`` 列表来排除某些符号。 请注意,导出时,只需指定模块名称: .. code-block:: nim import foo/bar/baz export baz 作用域规则 ----------- 标识符从其声明点开始有效,直到声明发生的块结束。 标识符已知的范围是标识符的范围。 标识符的确切范围取决于它的声明方式。 块作用域 ~~~~~~~~~~~ 在块的声明部分中声明的变量的 *作用域* 从声明点到块结束有效。 如果块包含第二个块,其中标识符被重新声明,则在该块内,第二个声明将是有效的。 跳出内部区块后,第一个声明再次有效。 除非对过程或迭代器重载有效,否则不能在同一个块中重新定义标识符。 元组或对象作用域 ~~~~~~~~~~~~~~~~~~~~~ 元组或对象定义中的字段标识符在以下位置有效: * 到元组/对象定义的结尾。 * 给定元组/对象类型的变量的字段指示符。 * 在对象类型的所有后代类型中。 模块作用域 ~~~~~~~~~~~~ 模块的所有标识符从声明点到模块结束都是有效的。 来自间接依赖模块的标识符 *不* 可用。 The `system`:idx: 模块自动导入每个模块。 如果模块通过两个不同的模块导入标识符,则必须限定每次出现的标识符,除非它是重载过程或迭代器,在这种情况下会发生重载解析: .. code-block:: nim # 模块A var x*: string .. code-block:: nim # 模块B var x*: int .. code-block:: nim # 模块C import A, B write(stdout, x) # 错误: x有歧义 write(stdout, A.x) # 没有错误: 使用限定符 var x = 4 write(stdout, x) # 没有歧义: 使用模块C的x 代码重排 ~~~~~~~~~~~~~~~ **注意** :代码重新排序是实验性的,必须通过 ``{.experimental.}`` 启用。 代码重新排序功能可以在顶级范围内隐式重新排列过程,模板和宏定义以及变量声明和初始化,这样在很大程度上,程序员不必担心正确排序定义或被迫使用转发声明前缀模块内的定义。 .. 注意:以下是代码重新排序前体的文档,即 {.noForward.} 。 在此模式下,过程定义可能不按顺序出现,编译器将推迟其语义分析和编译,直到它实际需要使用定义生成代码。 在这方面,此模式类似于动态脚本语言的操作方式,其中函数调用在代码执行之前不会被解析。 以下是编译器采用的详细算法: 1. 次遇到可调用符号时,编译器将只记录符号可调用名称,并将其添加到当前作用域中的相应重载集。 在此步骤中,它不会尝试解析符号签名中使用的任何类型表达式(因此它们可以引用其他尚未定义的符号)。 2. 当遇到顶级调用时(通常在模块的最末端),编译器将尝试确定匹配的重载集中所有符号的实际类型。 这是一个潜在的递归过程,因为符号的签名可能包含其他调用表达式,其类型也将在此时解析。 3. 最后,在选择最佳重载之后,编译器将启动编译各自符号的正文。这反过来将导致编译器发现需要解决的更多调用表达式和步骤必要时将重复图2和3。 请注意,如果在此方案中从未使用过可调用符号,则为身体永远不会编译。这是导致最佳的默认行为编译时间,但如果所有定义都是详尽的汇编必需的,使用 ``nim check`` 也提供此选项。 示例: .. code-block:: nim {.experimental: "codeReordering".} proc foo(x: int) = bar(x) proc bar(x: int) = echo(x) foo(10) 变量也可以重新排序。 *初始化* 的变量(即将声明和赋值组合在一个语句中的变量)可以重新排序其整个初始化语句。 小心顶级执行代码: .. code-block:: nim {.experimental: "codeReordering".} proc a() = echo(foo) var foo = 5 a() # 输出: "5" .. TODO: 让我们现在把它列成表格。这是一个*实验性特征* 因此 ``declared`` 与它一起操作的具体方式可以在最终的情况下决定,因为现在它工作的有点奇怪。 涉及 ``declared`` 表达式的值是在代码重新排序过程 *之前* 而不是之后确定的。 例如,此代码的输出与禁用代码重新排序时的输出相同。 .. code-block:: nim {.experimental: "codeReordering".} proc x() = echo(declared(foo)) var foo = 4 x() # "false" 重要的是要注意,重新排序 *仅* 适用于顶级范围的符号。因此,以下将 *编译失败* : .. code-block:: nim {.experimental: "codeReordering".} proc a() = b() proc b() = echo("Hello!") a() 编译器消息 ================= Nim编译器发出不同类型的消息: `hint`:idx:, `warning`:idx:, and `error`:idx: 消息。 如果编译器遇到任何静态错误,则会发出 *error* 消息。 编译指示 ======= Pragma是Nim的方法,可以在不引入大量新关键字的情况下为编译器提供额外的信息/命令。 在语义检查期间,语境处理是即时处理的。 Pragma包含在特殊的 ``{.`` 和 ``.}`` 花括号中。 在访问该功能的更好的语法变得可用之前,编译指示通常也被用作第一个使用语言功能的实现。 deprecated编译指示 ----------------- deprecated编译指示用于将符号标记为已弃用: .. code-block:: nim proc p() {.deprecated.} var x {.deprecated.}: char 该编译指示还可以接受一个可选的警告字符串以转发给开发人员。 .. code-block:: nim proc thing(x: bool) {.deprecated: "use thong instead".} noSideEffect编译指示 ------------------- ``noSideEffect`` 编译指示用于标记proc / iterator没有副作用。 这意味着proc / iterator仅更改可从其参数访问的位置,并且返回值仅取决于参数。 如果它的参数都没有类型``var T``或``ref T``或``ptr T``,这意味着没有修改位置。 如果编译器无法验证,则将proc / iterator标记为无副作用是一个静态错误。 作为一种特殊的语义规则,内置的 `<system.html#debugEcho,varargs[typed,]>`_ 假装没有副作用, 这样它就可以用来调试标记为 ``noSideEffect`` 的例程了。 ``func`` 是没有副作用的proc语法糖。 .. code-block:: nim func `+` (x, y: int): int 要覆盖编译器的副作用分析,可以使用 ``{.noSideEffect.}`` 编译指示块: .. code-block:: nim func f() = {.noSideEffect.}: echo "test" compileTime编译指示 ------------------ ``compileTime`` pragma用于标记仅在编译时执行期间使用的proc或变量。 不会为它生成代码。 编译时触发器可用作宏的帮助器。 从该语言的0.12.0版开始,在其参数类型中使用 ``system.NimNode`` 的proc被隐式声明为 ``compileTime`` : .. code-block:: nim proc astHelper(n: NimNode): NimNode = result = n 同: .. code-block:: nim proc astHelper(n: NimNode): NimNode {.compileTime.} = result = n noReturn编译指示 --------------- ``noreturn`` 编译指示用于标记不返回的过程。 acyclic编译指示 -------------- ``acyclic`` 编译指示用于类型声明。弃用并忽略。 final编译指示 ------------ ``final`` 编译指示可以用于对象类型,以指定它不能从中继承。 请注意,继承仅适用于从现有对象继承的对象(通过 ``超类型对象`` 语法)或已标记为 ``可继承`` 的对象。 shallow编译指示 -------------- ``shallow`` 编译指示会影响类型的语义:允许编译器生成浅拷贝。 这可能会导致严重的语义问题并破坏内存安全。 但是,它可以大大加快赋值,因为Nim的语义需要深拷贝序列和字符串。 这可能很昂贵,特别是如果用序列构建树结构: .. code-block:: nim type NodeKind = enum nkLeaf, nkInner Node {.shallow.} = object case kind: NodeKind of nkLeaf: strVal: string of nkInner: children: seq[Node] pure编译指示 ----------- 可以使用 ``pure`` 编译指示标记对象类型,以便省略用于运行时类型标识的类型字段。 这曾经是与其他编译语言二进制兼容所必需的。 枚举类型可以标记为 ``纯`` 。然后访问其字段始终需要完全限定。 asmNoStackFrame编译指示 ---------------------- proc可以使用 ``asmNoStackFrame`` 编译指示标记,告诉编译器它不应该为过程生成堆栈帧。 也有像 ``return result;`` 生成的没有出口的语句,生成的C函数声明为 ``__declspec(naked)`` 或 ``__attribute__((naked))`` (取决于使用的C编译器)。 **注意** :此pragma只应由仅包含汇编语句的过程使用。 error编译指示 ------------ ``error`` 编译指示用于使编译器输出具有给定内容的错误消息。但是,编译错误后不一定会中止。 ``error`` 编译指示也可用于注释符号(如迭代器或proc)。 然后,符号的 *使用* 会触发静态错误。 这对于排除由于重载和类型转换而导致某些操作有效特别有用: .. code-block:: nim ## 检查是否比较了基础int值而不是指针: proc `==`(x, y: ptr int): bool {.error.} fatal编译指示 ------------ ``fatal`` 编译指示用于使编译器输出具有给定内容的错误消息。 与 ``error`` 编译指示相反,编译保证会被此编译指示中止。 示例: .. code-block:: nim when not defined(objc): {.fatal: "Compile this program with the objc command!".} warning编译指示 -------------- ``warning`` 编译指示用于使编译器输出具有给定内容的警告消息,警告后继续编译。 hint编译指示 ----------- ``hint`` 编译指示用于使编译器输出具有给定内容的提示消息,提示后继续编译。 line编译指示 ----------- ``line`` pragma可用于影响带注释语句的行信息,如堆栈回溯中所示: .. code-block:: nim template myassert*(cond: untyped, msg = "") = if not cond: # 更改'raise'语句的运行时行信息: {.line: instantiationInfo().}: raise newException(EAssertionFailed, msg) 如果 ``line`` 编译指示与参数一起使用,则参数需要是 ``tuple[filename: string, line: int]`` 。 如果在没有参数的情况下使用它,则使用 ``system.InstantiationInfo()`` 。 linearScanEnd 编译指示 -------------------- ``linearScanEnd`` 编译指示可以用来告诉编译器如何编译Nim `case`:idx: 语句。 从语法上讲,它必须用作语句: .. code-block:: nim case myInt of 0: echo "most common case" of 1: {.linearScanEnd.} echo "second most common case" of 2: echo "unlikely: use branch table" else: echo "unlikely too: use branch table for ", myInt 在这个例子中,case分支 ``0`` 和 ``1`` 比其他情况更常见。 因此,生成的汇编程序代码应首先测试这些值,以便CPU的分支预测器有很好的成功机会(避免昂贵的CPU管道停顿)。 其他情况可能会被放入O(1)开销的跳转表中,但代价是(很可能)管道停顿。 应该将 ``linearScanEnd`` 编译指示放入应通过线性扫描进行测试的最后一个分支。 如果放入整个 ``case`` 语句的最后一个分支,整个 ``case`` 语句使用线性扫描。 computedGoto编译指示 ------------------- ``calculateGoto`` 编译指示可用于告诉编译器如何编译在 ``while true`` 语句中中的Nim `case`:idx: 语句。 从语法上讲,它必须在循环中用作语句: .. code-block:: nim type MyEnum = enum enumA, enumB, enumC, enumD, enumE proc vm() = var instructions: array[0..100, MyEnum] instructions[2] = enumC instructions[3] = enumD instructions[4] = enumA instructions[5] = enumD instructions[6] = enumC instructions[7] = enumA instructions[8] = enumB instructions[12] = enumE var pc = 0 while true: {.computedGoto.} let instr = instructions[pc] case instr of enumA: echo "yeah A" of enumC, enumD: echo "yeah CD" of enumB: echo "yeah B" of enumE: break inc(pc) vm() 如示例所示, ``computedGoto`` 对解释器最有用。 如果底层后端(C编译器)不支持计算的goto扩展,则简单地忽略编译指示。 unroll编译指示 ------------- ``unroll`` 编译指示可用于告诉编译器它应该为执行效率展开 `for`:idx: 或 `while`:idx: 循环: .. code-block:: nim proc searchChar(s: string, c: char): int = for i in 0 .. s.high: {.unroll: 4.} if s[i] == c: return i result = -1 在上面的例子中,搜索循环按因子4展开。展开因子也可以省略;然后编译器选择适当的展开因子。 **注意** :目前编译器会识别但忽略此编译指示。 immediate编译指示 ---------------- 编译指示 immediate 已被弃用。 参阅 `指定类型和无类型参数 <#templates-typed-vs-untyped-parameters>`_. 编译选项编译指示 -------------------------- 此处列出的编译指示可用于覆盖proc/method/converter的代码生成选项。 该实现目前提供以下可能的选项(稍后可以添加各种其他选项)。 =============== =============== ============================================ pragma allowed values description =============== =============== ============================================ checks on|off 打开或关闭所有运行时检查的代码生成。 boundChecks on|off 打开或关闭数组绑定检查的代码生成。 overflowChecks on|off 打开或关闭上溢或下溢检查的代码生成。 nilChecks on|off 打开或关闭nil指针检查的代码生成。 assertions on|off 打开或关闭断言的代码生成。 warnings on|off 打开或关闭编译器的警告消息。 hints on|off 打开或关闭编译器的提示消息。 optimization none|speed|size 优化代码的速度或大小,或禁用优化。 patterns on|off 打开或关闭术语重写模板/宏。 callconv cdecl|... 指定后面的所有过程(和过程类型)的默认调用约定。 =============== =============== ============================================ 示例: .. code-block:: nim {.checks: off, optimization: speed.} # 编译时没有运行时检查并优化速度 push和pop编译指示 -------------------- `push/pop`:idx: 编译指示与option指令非常相似,但用于暂时覆盖设置。 示例: .. code-block:: nim {.push checks: off.} # 编译本节而不进行运行时检查,因为它对速度至关重要 # ... some code ... {.pop.} # 恢复堆栈 `push/pop`:idx: can switch on/off some standard library pragmas, example: .. code-block:: nim {.push inline.} proc thisIsInlined(): int = 42 func willBeInlined(): float = 42.0 {.pop.} proc notInlined(): int = 9 {.push discardable, boundChecks: off, compileTime, noSideEffect, experimental.} template example(): string = "https://nim-lang.org" {.pop.} {.push deprecated, hint[LineTooLong]: off, used, stackTrace: off.} proc sample(): bool = true {.pop.} For third party pragmas it depends on its implementation, but uses the same syntax. register编译指示 --------------- ``register`` 编译指示仅用于变量。 它将变量声明为 ``register`` ,给编译器一个提示,即应该将变量放在硬件寄存器中以便更快地访问。 C编译器通常会忽略这一点,但有充分的理由:无论如何,他们通常会做得更好。 在高度特定的情况下(例如,字节码解释器的调度循环),它可能提供好处。 global编译指示 ------------- ``global`` 编译指示可以应用于proc中的变量,以指示编译器将其存储在全局位置并在程序启动时初始化它。 .. code-block:: nim proc isHexNumber(s: string): bool = var pattern {.global.} = re"[0-9a-fA-F]+" result = s.match(pattern) 在泛型proc中使用时,将为proc的每个实例创建一个单独的唯一全局变量。 未定义模块中创建的全局变量的初始化顺序,但所有这些变量的顺序将在其原始模块中的任何顶级变量之后以及导入模块中的任何变量之前初始化。 pragma编译指示 ------------- ``pragma`` 编译指示可用于声明用户定义的编译指示。 这很有用,因为Nim的模板和宏不会影响编译指示。 用户定义的编译指示与所有其他符号在不同的模块范围内。 它们无法从模块导入。 示例: .. code-block:: nim when appType == "lib": {.pragma: rtl, exportc, dynlib, cdecl.} else: {.pragma: rtl, importc, dynlib: "client.dll", cdecl.} proc p*(a, b: int): int {.rtl.} = result = a+b 在该示例中,引入了名为 ``rtl`` 的新编译指示,该编译指示从动态库导入符号或导出用于动态库生成的符号。 禁用某些消息 -------------------------- Nim会产生一些可能会惹恼用户的警告和提示(“行太长”)。 提供了一种禁用某些消息的机制:每个提示和警告消息都在括号中包含一个符号。 这是可用于启用或禁用它的消息标识符: .. code-block:: Nim {.hint[LineTooLong]: off.} # 关掉行太长的提示 这通常比一次禁用所有警告更好。 used编译指示 ----------- Nim会对未导出但未使用的符号生成警告。 ``used`` 编译指示可以附加到符号以抑制此警告。 当符号由宏生成时,这尤其有用: .. code-block:: nim template implementArithOps(T) = proc echoAdd(a, b: T) {.used.} = echo a + b proc echoSub(a, b: T) {.used.} = echo a - b # 没有为未使用的'echoSub'发出警告 implementArithOps(int) echoAdd 3, 5 experimental编译指示 ------------------- ``experimental`` 编译指示实现了实验语言功能。 根据具体特征,这意味着该特征被认为对于其他稳定版本而言太不稳定,或者该特征的未来不确定(可能随时删除)。 示例: .. code-block:: nim import threadpool {.experimental: "parallel".} proc threadedEcho(s: string, i: int) = echo(s, " ", $i) proc useParallel() = parallel: for i in 0..4: spawn threadedEcho("echo in parallel", i) useParallel() 作为顶级语句,实验编译指示为其启用的模块的其余部分启用了一项功能。 这对于跨越模块范围的宏和通用实例化是有问题的。 目前这些用法必须放在 ``.push/pop`` 环境中: .. code-block:: nim # client.nim proc useParallel*[T](unused: T) = # use a generic T here to show the problem. {.push experimental: "parallel".} parallel: for i in 0..4: echo "echo in parallel" {.pop.} .. code-block:: nim import client useParallel(1) 特定实现的编译指示 =============================== 本节描述了当前Nim实现支持的其他编译指示,但不应将其视为语言规范的一部分。 Bitsize 编译指示 -------------- ``bitsize`` 编译指示用于对象字段成员。它将该字段声明为C/C++中的位字段。 .. code-block:: Nim type mybitfield = object flag {.bitsize:1.}: cuint 生成: .. code-block:: C struct mybitfield { unsigned int flag:1; }; Volatile编译指示 --------------- ``volatile`` 编译指示仅用于变量。 它将变量声明为 ``volatile`` ,无论C/C++中的含义是什么(它的语义在C/C++中没有很好地定义)。 **注意** :LLVM后端不存在此编译指示。 NoDecl编译指示 ------------- ``noDecl`` 编译指示几乎可以应用于任何符号(变量,proc,类型等),有时与C的互操作性有用: 它告诉Nim它不应该在C代码中为符号生成声明。 例如: .. code-block:: Nim var EACCES {.importc, noDecl.}: cint # EACCES是一个变量,因为Nim不知道它的价值 但是,``header`` 编译指示通常是更好的选择。 **注意** :这不适用于LLVM后端。 Header编译指示 ------------- ``header`` 编译指示与 ``noDecl`` 编译指示非常相似:它几乎可以应用于任何符号并指定不应该声明它,而生成的代码应该包含一个 ``#include`` : .. code-block:: Nim type PFile {.importc: "FILE*", header: "<stdio.h>".} = distinct pointer # 导入C的FILE *类型; Nim会将其视为新的指针类型 ``header`` 编译指示始终期望字符串不变。 字符串包含头文件:与C一样,系统头文件包含在尖括号中: ``<>`` 。 如果没有给出尖括号,Nim将生成的C代码中的头文件包含在 ``""`` 中。 **注意** :这不适用于LLVM后端。 IncompleteStruct编译指示 ----------------------- ``incompleteStruct`` 编译指示告诉编译器不要在 ``sizeof`` 表达式中使用底层的C ``struct`` : .. code-block:: Nim type DIR* {.importc: "DIR", header: "<dirent.h>", pure, incompleteStruct.} = object Compile编译指示 -------------- ``compile`` 编译指示可用于编译和链接项目的C/C++源文件: .. code-block:: Nim {.compile: "myfile.cpp".} **注意** :Nim计算SHA1校验和,只有在文件发生变化时才重新编译。 您可以使用 ``-f`` 命令行选项强制重新编译该文件。 Link编译指示 ----------- ``link`` 编译指示可用于将附加文件与项目链接: .. code-block:: Nim {.link: "myfile.o".} PassC编译指示 ------------ 可以使用 ``passC`` 编译指示将其他参数传递给C编译器,就像使用命令行开关 ``--passC`` 一样: .. code-block:: Nim {.passC: "-Wall -Werror".} 请注意,您可以使用 `system module <system.html>`_ 中的 ``gorge`` 来嵌入将在语义分析期间执行的外部命令的参数: .. code-block:: Nim {.passC: gorge("pkg-config --cflags sdl").} PassL编译指示 ------------ ``passL`` 编译指示可用于将其他参数传递给链接器,就像使用命令行开关 ``--passL`` 一样: .. code-block:: Nim {.passL: "-lSDLmain -lSDL".} 请注意,您可以使用 `system module <system.html>`_ 中的 ``gorge`` 来嵌入将在语义分析期间执行的外部命令的参数: .. code-block:: Nim {.passL: gorge("pkg-config --libs sdl").} Emit编译指示 ----------- ``emit`` 编译指示可用于直接影响编译器代码生成器的输出。 因此,它使您的代码无法移植到其他代码生成器/后端。 它的使用非常不鼓励的。但是,它对于与 `C++`:idx: 或 `Objective C`:idx: 代码非常有用。 示例: .. code-block:: Nim {.emit: """ static int cvariable = 420; """.} {.push stackTrace:off.} proc embedsC() = var nimVar = 89 # 访问字符串文字之外的发送部分中的Nim符号: {.emit: ["""fprintf(stdout, "%d\n", cvariable + (int)""", nimVar, ");"].} {.pop.} embedsC() ``nimbase.h`` 定义了 ``NIM_EXTERNC`` C宏,它可以用于 ``extern "C"``代码,用于 ``nim c`` 和 ``nim cpp`` ,例如: .. code-block:: Nim proc foobar() {.importc:"$1".} {.emit: """ #include <stdio.h> NIM_EXTERNC void fun(){} """.} 为了向后兼容,如果``emit``语句的参数是单个字符串文字,则可以通过反引号引用Nim符号。 但是不推荐使用此用法。 对于顶级emit语句, 生成的C/C++文件中应该发出代码的部分可以通过前缀 ``/*TYPESECTION*/`` 或 ``/*VARSECTION*/`` 或 ``/*INCLUDESECTION*/`` 来影响: .. code-block:: Nim {.emit: """/*TYPESECTION*/ struct Vector3 { public: Vector3(): x(5) {} Vector3(float x_): x(x_) {} float x; }; """.} type Vector3 {.importcpp: "Vector3", nodecl} = object x: cfloat proc constructVector3(a: cfloat): Vector3 {.importcpp: "Vector3(@)", nodecl} ImportCpp编译指示 ---------------- **注意**: `c2nim <https://github.com/nim-lang/c2nim/blob/master/doc/c2nim.rst>`_ 可以解析C++子集并且知道 ``importcpp`` 编译指示模式语言。 没有必要知道这里描述的所有细节。 和 `importc pragma for C <#foreign-function-interface-importc-pragma>`_ 类似, ``importcpp`` 编译指示一般可以用于引入 `C++`:idx: 方法或C++符号。 生成的代码会使用C++方法调用的语法: ``obj->method(arg)`` 。 结合 ``header`` 和 ``emit`` 编译指示,这允许与C++库的接口: .. code-block:: Nim # 和C++引擎对接的反例... ;-) {.link: "/usr/lib/libIrrlicht.so".} {.emit: """ using namespace irr; using namespace core; using namespace scene; using namespace video; using namespace io; using namespace gui; """.} const irr = "<irrlicht/irrlicht.h>" type IrrlichtDeviceObj {.header: irr, importcpp: "IrrlichtDevice".} = object IrrlichtDevice = ptr IrrlichtDeviceObj proc createDevice(): IrrlichtDevice {. header: irr, importcpp: "createDevice(@)".} proc run(device: IrrlichtDevice): bool {. header: irr, importcpp: "#.run(@)".} 需要告诉编译器生成C++(命令 ``cpp`` )才能使其工作。 当编译器发射C++代码时,会定义条件符号 ``cpp`` 。 命名空间 ~~~~~~~~~~ *接口* 示例使用 ``.emit`` 来生成 ``using namespace`` 声明。 通过 ``命名空间::标识符`` 符号来引用导入的名称通常要好得多: .. code-block:: nim type IrrlichtDeviceObj {.header: irr, importcpp: "irr::IrrlichtDevice".} = object 枚举Importcpp ~~~~~~~~~~~~~~~~~~~ 当 ``importcpp`` 应用于枚举类型时,数字枚举值用C++枚举类型注释, 像这个示例: ``((TheCppEnum)(3))`` 。 (事实证明这是实现它的最简单方法。) 过程Importcpp ~~~~~~~~~~~~~~~~~~~ 请注意,procs的 ``importcpp`` 变体使用了一种有点神秘的模式语言,以获得最大的灵活性: - 哈希 ``#`` 符号被第一个或下一个参数替换。 哈希 ``#.`` 后面的一个点表示该调用应使用C++的点或箭头表示法。 - 符号 ``@`` 被剩下的参数替换,用逗号分隔。 示例: .. code-block:: nim proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "#.CppMethod(@)".} var x: ptr CppObj cppMethod(x[], 1, 2, 3) 生成: .. code-block:: C x->CppMethod(1, 2, 3) 作为一个特殊的规则来保持与旧版本的 ``importcpp`` 编译指示的向后兼容性,如果没有特殊的模式字符(任何一个 ``#'@`` ),那么认为是C++的点或箭头符号,所以上面的例子也可以写成: .. code-block:: nim proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "CppMethod".} 请注意,模式语言自然也涵盖了C++的运算符重载功能: .. code-block:: nim proc vectorAddition(a, b: Vec3): Vec3 {.importcpp: "# + #".} proc dictLookup(a: Dict, k: Key): Value {.importcpp: "#[#]".} - 上标点 ``'`` 后跟0..9范围的整数 ``i`` 被第i个形参类型替换。 第0位是结果类型。这可以用于将类型传递给C++函数模板。 在 ``'`` 和数字之间可以使用星号来获得该类型的基类型。 (所以它从类型中“拿走了一颗星”; ``T *`` 变为 ``T`` 。) 可以使用两颗星来获取元素类型的元素类型等。 示例: .. code-block:: nim type Input {.importcpp: "System::Input".} = object proc getSubsystem*[T](): ptr T {.importcpp: "SystemManager::getSubsystem<'*0>()", nodecl.} let x: ptr Input = getSubsystem[Input]() 生成: .. code-block:: C x = SystemManager::getSubsystem<System::Input>() - ``#@`` 是一个支持 ``cnew`` 操作的特例。 这是必需的,以便直接内联调用表达式,而无需通过临时位置。 这只是为了规避当前代码生成器的限制。 例如,C++的 ``new`` 运算符可以像这样“导入”: .. code-block:: nim proc cnew*[T](x: T): ptr T {.importcpp: "(new '*0#@)", nodecl.} # 'Foo'构造函数: proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)".} let x = cnew constructFoo(3, 4) 生成: .. code-block:: C x = new Foo(3, 4) 但是,根据用例, ``new Foo`` 也可以这样包装: .. code-block:: nim proc newFoo(a, b: cint): ptr Foo {.importcpp: "new Foo(@)".} let x = newFoo(3, 4) 封装构造函数 ~~~~~~~~~~~~~~~~~~~~~ 有时候C++类有一个私有的复制构造函数,因此不能生成像 ``Class c = Class(1,2);`` 这样的代码,而是 ``Class c(1,2);`` 。 为此,包含C ++构造函数的Nim proc需要使用 `构造函数`:idx: 编译器。 这个编译指示也有助于生成更快的C++代码,因为构造然后不会调用复制构造函数: .. code-block:: nim # 更好的'Foo'构建函数: proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)", constructor.} 封装析构函数 ~~~~~~~~~~~~~~~~~~~~ 封装destruct由于Nim直接生成C++,所以任何析构函数都由C++编译器在作用域出口处隐式调用。 这意味着通常人们可以完全没有封装析构函数。 但是当需要显式调用它时,需要将其封装起来。 模式语言提供了所需的一切: .. code-block:: nim proc destroyFoo(this: var Foo) {.importcpp: "#.~Foo()".} 对象的Importcpp ~~~~~~~~~~~~~~~~~~~~~ 泛型 ``importcpp`` 的对象映射成C++模板。这意味着您可以轻松导入C++的模板,而无需对象类型的模式语言: .. code-block:: nim type StdMap {.importcpp: "std::map", header: "<map>".} [K, V] = object proc `[]=`[K, V](this: var StdMap[K, V]; key: K; val: V) {. importcpp: "#[#] = #", header: "<map>".} var x: StdMap[cint, cdouble] x[6] = 91.4 生成: .. code-block:: C std::map<int, double> x; x[6] = 91.4; - 如果需要更精确的控制, 上标点 ``'`` 可以用在提供的模式里标志泛型类型的具体类型参数。 更多细节,见过程模式中的上标点操作符。 .. code-block:: nim type VectorIterator {.importcpp: "std::vector<'0>::iterator".} [T] = object var x: VectorIterator[cint] Produces: .. code-block:: C std::vector<int>::iterator x; ImportObjC编译指示 ----------------- 和 `importc pragma for C <#foreign-function-interface-importc-pragma>`_ 类似, ``importobjc`` 编译指示可用于导入 `Objective C`:idx: 方法。 生成的代码使用Objective C 方法调用语法: ``[obj method param1: arg]``. 除了 ``header`` 和 ``emit`` 编译指示之外,这允许与Objective C中编写的库的对接: .. code-block:: Nim # 和GNUStep对接的反例 ... {.passL: "-lobjc".} {.emit: """ #include <objc/Object.h> @interface Greeter:Object { } - (void)greet:(long)x y:(long)dummy; @end #include <stdio.h> @implementation Greeter - (void)greet:(long)x y:(long)dummy { printf("Hello, World!\n"); } @end #include <stdlib.h> """.} type Id {.importc: "id", header: "<objc/Object.h>", final.} = distinct int proc newGreeter: Id {.importobjc: "Greeter new", nodecl.} proc greet(self: Id, x, y: int) {.importobjc: "greet", nodecl.} proc free(self: Id) {.importobjc: "free", nodecl.} var g = newGreeter() g.greet(12, 34) g.free() 需要告诉编译器生成Objective C(命令 ``objc`` )以使其工作。当编译器发出Objective C代码时,定义条件符号 ``objc`` 。 CodegenDecl编译指示 ------------------ ``codegenDecl`` 编译指示可用于直接影响Nim的代码生成器。 它接收一个格式字符串,用于确定如何在生成的代码中声明变量或proc。 对于变量,格式字符串中的$1表示变量的类型,$2是变量的名称。 以下Nim哇到处: .. code-block:: nim var a {.codegenDecl: "$# progmem $#".}: int 会生成这个C代码: .. code-block:: c int progmem a 对于过程,$1是过程的返回类型,$2是过程的名称,$3是参数列表。 下列nim代码: .. code-block:: nim proc myinterrupt() {.codegenDecl: "__interrupt $# $#$#".} = echo "realistic interrupt handler" 会生成这个代码: .. code-block:: c __interrupt void myinterrupt() InjectStmt编译指示 ----------------- ``injectStmt`` 编译指示可用于在当前模块中的每个其他语句之前注入语句。 它只应该用于调试: .. code-block:: nim {.injectStmt: gcInvariants().} # ... 这里的复杂代码会导致崩溃 ... 编译期定义的编译指示 --------------------------- 此处列出的编译指示可用于在编译时选择接受-d /--define选项中的值。 该实现目前提供以下可能的选项(稍后可以添加各种其他选项)。 ================= ============================================ pragma description ================= ============================================ `intdefine`:idx: 读取构建时定义为整数 `strdefine`:idx: 读取构建时定义为字符串 `booldefine`:idx: 读取构建时定义为bool ================= ============================================ .. code-block:: nim const FooBar {.intdefine.}: int = 5 echo FooBar :: nim c -d:FooBar=42 foobar.nim 在上面的例子中,提供-d标志会导致符号 ``FooBar`` 在编译时被覆盖,打印出42。 如果省略 ``-d:FooBar = 42`` ,则使用默认值5。要查看是否提供了值,可以使用 `defined(FooBar)` 。 语法 `-d:flag` 实际上只是 `-d:flag = true` 的快捷方式。 自定义标注 ------------------ 可以定义自定义类型的编译指示。 自定义编译指示不会直接影响代码生成,但可以通过宏检测它们的存在。 使用带有编译指示“pragma”的注释模板定义自定义编译指示: .. code-block:: nim template dbTable(name: string, table_space: string = "") {.pragma.} template dbKey(name: string = "", primary_key: bool = false) {.pragma.} template dbForeignKey(t: typedesc) {.pragma.} template dbIgnore {.pragma.} 考虑风格化的对象关系映射(ORM)实现示例: .. code-block:: nim const tblspace {.strdefine.} = "dev" # dev, test和prod环境的开关 type User {.dbTable("users", tblspace).} = object id {.dbKey(primary_key = true).}: int name {.dbKey"full_name".}: string is_cached {.dbIgnore.}: bool age: int UserProfile {.dbTable("profiles", tblspace).} = object id {.dbKey(primary_key = true).}: int user_id {.dbForeignKey: User.}: int read_access: bool write_access: bool admin_acess: bool 在此示例中,自定义编译指示用于描述Nim对象如何映射到关系数据库的模式。 自定义编译指示可以包含零个或多个参数。 为了传递多个参数,请使用模板调用语法之一。 键入所有参数并遵循模板的标准重载决策规则。 因此,可以为参数,按名称传递,varargs等提供默认值。 可以在可以指定普通编译指示的所有位置使用自定义编译指示。 可以注释过程,模板,类型和变量定义,语句等。 宏模块包括帮助程序,可用于简化自定义编译器访问 `hasCustomPragma` , `getCustomPragmaVal` 。 有关详细信息,请参阅宏模块文档。 这些宏没有魔法,它们不会通过遍历AST对象表示做任何你不能做的事情。 自定义编译指示的更多示例: - 更好的序列化/反序列化控制: .. code-block:: nim type MyObj = object a {.dontSerialize.}: int b {.defaultDeserialize: 5.}: int c {.serializationKey: "_c".}: string - 在游戏引擎中采用gui检查的类型: .. code-block:: nim type MyComponent = object position {.editable, animatable.}: Vector3 alpha {.editRange: [0.0..1.0], animatable.}: float32 外部函数接口 ========================== Nim的 `FFI`:idx: (外部函数接口) 非常广泛,这里只记载扩展到其它未来后端的部分 (如 LLVM/JavaScript后端)。 Importc编译指示 -------------- ``importc`` 编译指示提供了一种从C导入proc或变量的方法。 可选参数是包含C标识符的字符串。 如果缺少参数,则C名称与Nim标识符 *拼写完全相同* : .. code-block:: proc printf(formatstr: cstring) {.header: "<stdio.h>", importc: "printf", varargs.} 请注意,此编译指示有点用词不当:其他后端确实在同一名称下提供相同的功能。 * `importcpp <manual.html#implementation-specific-pragmas-importcpp-pragma>`_ * `importobjc <manual.html#implementation-specific-pragmas-importobjc-pragma>`_ * `importjs <manual.html#implementation-specific-pragmas-importjs-pragma>`_ .. code-block:: Nim proc p(s: cstring) {.importc: "prefix$1".} 在示例中, ``p`` 的外部名称设置为 ``prefixp`` 。 只有 ``$1`` 可用,文字美元符号必须写成 ``$$`` 。 Exportc编译指示 -------------- ``exportc`` 编译指示提供了一种将类型,变量或过程导出到C的方法。 枚举和常量无法导出。 可选参数是包含C标识符的字符串。 如果缺少参数,则C名称是Nim标识符 *与拼写完全相同* : .. code-block:: Nim proc callme(formatstr: cstring) {.exportc: "callMe", varargs.} 请注意,此编译指示有点用词不当:其他后端确实在同一名称下提供相同的功能。 传递给 ``exportc`` 的字符串文字可以是格式字符串: .. code-block:: Nim proc p(s: string) {.exportc: "prefix$1".} = echo s 在示例中, ``p`` 的外部名称设置为 ``prefixp`` 。 只有 ``$1`` 可用,文字美元符号必须写成 ``$$`` 。 Extern编译指示 ------------- 就像 ``exportc`` 或 ``importc`` 一样, ``extern`` 编译指示会影响名称修改。传递给 ``extern`` 的字符串文字可以是格式字符串: .. code-block:: Nim proc p(s: string) {.extern: "prefix$1".} = echo s 在示例中, ``p`` 的外部名称设置为 ``prefixp`` 。只有 ``$1`` 可用,文字美元符号必须写成 ``$$`` 。 Bycopy编译指示 ------------- ``bycopy`` 编译指示可以应用于对象或元组类型,并指示编译器按类型将类型传递给过程: .. code-block:: nim type Vector {.bycopy.} = object x, y, z: float Byref编译指示 ------------ ``byref`` 编译指示可以应用于对象或元组类型,并指示编译器通过引用(隐藏指针)将类型传递给过程。 Varargs编译指示 -------------- ``varargs`` 编译指示只适用于过程 (和过程类型)。 它告诉Nim proc可以在最后指定的参数获取可变数量的参数。 Nim字符串值将自动转换为C字符串: .. code-block:: Nim proc printf(formatstr: cstring) {.nodecl, varargs.} printf("hallo %s", "world") # "world"将作为C字符串传递 Union编译指示 ------------ ``union`` 编译指示适用于任何 ``对象`` 类型。 这意味着所有对象的字段在内存中是重叠的。 这会在生成的C / C ++代码中生成一个 ``union`` 而不是 ``struct`` 。 然后,对象声明不能使用继承或任何GC的内存,但目前尚不做检查。 **未来方向**: 应该允许在联合中使用GC内存并且GC应当保守地扫描联合。 Packed编译指示 ------------- ``packed`` 编译指示适用于任何 ``对象`` 类型。 它确保对象的字段打包在连续的内存中。 将数据包或消息存储到网络或硬件驱动程序以及与C的互操作性非常有用。 没有定义packed编译指示的继承用法,且不应该与GC的内存(ref)一起使用。 **未来方向**: 在packed pragma中使用GC内存将导致静态错误。应该定义和记录继承的用法。 用于导入的Dynlib编译指示 ------------------------ 使用 ``dynlib`` 编译指示,可以从动态库(Windows的 ``.dll`` 文件,UNIX的 ``lib*.so`` 文件)导入过程或变量。 .. code-block:: Nim proc gtk_image_new(): PGtkWidget {.cdecl, dynlib: "libgtk-x11-2.0.so", importc.} 通常,导入动态库不需要任何特殊的链接器选项或链接到导入库。 这也意味着不需要安装 *开发* 包。 ``dynlib`` 导入机制支持版本控制方案: .. code-block:: nim proc Tcl_Eval(interp: pTcl_Interp, script: cstring): int {.cdecl, importc, dynlib: "libtcl(|8.5|8.4|8.3).so.(1|0)".} 在运行时,搜索动态库(按此顺序) libtcl.so.1 libtcl.so.0 libtcl8.5.so.1 libtcl8.5.so.0 libtcl8.4.so.1 libtcl8.4.so.0 libtcl8.3.so.1 libtcl8.3.so.0 ``dynlib`` 编译指示不仅支持常量字符串作为参数,还支持字符串表达式: .. code-block:: nim import os proc getDllName: string = result = "mylib.dll" if existsFile(result): return result = "mylib2.dll" if existsFile(result): return quit("could not load dynamic library") proc myImport(s: cstring) {.cdecl, importc, dynlib: getDllName().} **注意**: 形如 ``libtcl(|8.5|8.4).so`` 只支持常量字符串,因为它们需要预编译。 **注意**: 传变量给 ``dynlib`` 编译指示在进行时会失败,因为初始化问题的顺序。 **注意**: ``dynlib`` 导入可以用 ``--dynlibOverride:name`` 命令行选项重写。 编译器用户指南包括更多信息。 用于导出的Dynlib编译指示 ------------------------ 过程可以用 ``dynlib`` 编译指示导出到一个动态库。 编译指示没有实参而且必须和 ``exportc`` 拼接在一起: .. code-block:: Nim proc exportme(): int {.cdecl, exportc, dynlib.} 这只有当程序通过 ``--app:lib`` 命令行选项编译为动态库时有用。 此编译指示仅对Windows目标上的代码生成有影响,因此当忘写并且仅在Mac和/或Linux上测试动态库时,不会出现错误。 在Windows上,这个编译指示在函数声明中添加了 ``__declspec(dllexport)`` 。 线程 ======= 要启用线程支持,需要使用 ``--threads:on`` 命令行开关。 然后 ``system`` 模块包含几个线程原语。 请参阅低级线程API `threads <threads.html>`_ 和 `channels <channels.html>`_ 模块。 还有高级并行结构可用。见 `spawn <manual_experimental.html#parallel-amp-spawn>`_ 更多细节。 Nim的线程内存模型与其他常见编程语言(C,Pascal,Java)完全不同:每个线程都有自己的(垃圾收集)堆,内存共享仅限于全局变量。 这有助于防止竞争条件。 GC效率得到了很大提高,因为GC永远不必停止其他线程并看到它们引用的内容。 Thread编译指示 ------------- 作为新执行线程执行的proc应该由 ``thread`` 编译指示标记,以便于阅读。 编译器检查是否存在 `无堆共享限制`:dx:\: 的违规。此限制意味着构造一个由不同(线程本地)堆分配的内存组成的数据结构是无效的。 线程proc被传递给 ``createThread`` 或 ``spawn`` 并间接调用;所以 ``thread`` 编译指示暗示 ``procvar`` 。 GC安全 --------- 当过程不通过调用GC不安全的过程直接或间接访问任何含有GC内存的全局变量(``string``, ``seq``, ``ref`` 或闭包)时,我们称过程 ``p`` `GC安全`:idx: 。 `gcsafe`:idx: 可用于将proc标记为gcsafe,否则此属性由编译器推断。 请注意, ``noSideEffect`` 意味着 ``gcsafe`` 。创建线程的唯一方法是通过 ``spawn`` 或 ``createThread`` 。 被调用的proc不能使用 ``var`` 参数,也不能使用任何参数包含 ``ref`` 或 ``closure`` 类型。 这会强制执行 *无堆共享限制* 。 从C导入的例程总是被假定为 ``gcsafe`` 。 要禁用GC安全检查,可以使用 ``--threadAnalysis:off`` 命令行开关。 这是一种临时解决方法,可以简化从旧代码到新线程模型的移植工作。 要覆盖编译器的gcsafety分析,可以使用 ``{.gcsafe.}`` 编译指示: .. code-block:: nim var someGlobal: string = "some string here" perThread {.threadvar.}: string proc setPerThread() = {.gcsafe.}: deepCopy(perThread, someGlobal) 未来的方向: - 可能会提供一个共享的GC堆内存。 Threadvar编译指示 ---------------- 变量可以用 ``threadvar`` 编译指示标记,使它成为 `thread-local`:idx: 变量; 另外,这意味着 ``global`` 编译指示的所有效果。 .. code-block:: nim var checkpoints* {.threadvar.}: seq[string] 由于实现限制,无法在 ``var`` 部分中初始化线程局部变量。 (在创建线程时需要复制每个线程局部变量。) 线程和异常 ---------------------- 线程和异常之间的交互很简单:一个线程中的 *处理过的* 异常不会影响任何其他线程。但是,一个线程中的 *未处理的* 异常终止整个 *进程* 。 <file_sep>/changelog.md # x.x - xxxx-xx-xx ## Changes affecting backwards compatibility ### Breaking changes in the standard library - `base64.encode` no longer supports `lineLen` and `newLine`. Use `base64.encodeMIME` instead. - `os.splitPath()` behavior synchronized with `os.splitFile()` to return "/" as the dir component of "/root_sub_dir" instead of the empty string. - `sequtils.zip` now returns a sequence of anonymous tuples i.e. those tuples now do not have fields named "a" and "b". - `strutils.formatFloat` with `precision = 0` has the same behavior in all backends, and it is compatible with Python's behavior, e.g. `formatFloat(3.14159, precision = 0)` is now `3`, not `3.`. ### Breaking changes in the compiler - Implicit conversions for `const` behave correctly now, meaning that code like `const SOMECONST = 0.int; procThatTakesInt32(SOMECONST)` will be illegal now. Simply write `const SOMECONST = 0` instead. ## Library additions - `macros.newLit` now works for ref object types. - `system.writeFile` has been overloaded to also support `openarray[byte]`. - Added overloaded `strformat.fmt` macro that use specified characters as delimiter instead of '{' and '}'. ## Library changes - `asyncdispatch.drain` now properly takes into account `selector.hasPendingOperations` and only returns once all pending async operations are guaranteed to have completed. - `asyncdispatch.drain` now consistently uses the passed timeout value for all iterations of the event loop, and not just the first iteration. This is more consistent with the other asyncdispatch apis, and allows `asyncdispatch.drain` to be more efficient. - `base64.encode` and `base64.decode` was made faster by about 50%. - `htmlgen` adds [MathML](https://wikipedia.org/wiki/MathML) support (ISO 40314). ## Language additions ## Language changes - Unsigned integer operators have been fixed to allow promotion of the first operand. ### Tool changes ### Compiler changes - JS target indent is all spaces, instead of mixed spaces and tabs, for generated JavaScript. ## Bugfixes - The `FD` variant of `selector.unregister` for `ioselector_epoll` and `ioselector_select` now properly handle the `Event.User` select event type. <file_sep>/doc/tut1.rst ===================== Nim教程 (I) ===================== :Author: <NAME> :Version: |nimversion| .. contents:: 引言 ============ .. raw:: html <blockquote><p> "人是一种视觉动物 -- 我渴望美好事物。" </p></blockquote> 本文是编程语言Nim的教程。该教程认为你熟悉基本的编程概念如变量、类型和语句但非常基础。 `manual <manual.html>`_ 包含更多的高级特性示例。本教程的代码示例和其它的Nim文档遵守 `Nim style guide <nep1.html>`_ 。 第一个程序 ================= 我们从一个调整过的"hello world"程序开始: .. code-block:: Nim :test: "nim c $1" # 这是注释 echo "What's your name? " var name: string = readLine(stdin) echo "Hi, ", name, "!" 保存到文件"greetings.nim",编译运行: nim compile --run greetings.nim 用 ``--run`` `switch <nimc.html#compiler-usage-command-line-switches>`_ Nim在编译之后自动执行文件。你可以在文件名后给程序追加命令行参数nim compile --run greetings.nim arg1 arg2 经常使用的命令和开关有缩写,所以你可以用:: nim c -r greetings.nim 编译发布版使用:: nim c -d:release greetings.nim Nim编译器默认生成大量运行时检查,旨在方便调试。用 ``-d:release`` `关闭一些检查并且打开优化<nimc.html#compiler-usage-compile-time-symbols>`_ 。 (译者注,-d:release的功能在最近的版本已经发生变化,现在会打开运行时检查,使用-d:danger来替代,以生成更好性能的代码) 程序的作用显而易见,需要解释下语法:没有缩进的语句会在程序开始时执行。缩进是Nim语句进行分组的方式。缩进仅允许空格,不允许制表符。 字符串用双引号括起来。 ``var`` 语句声明了一个名为 ``name`` 的新变量, 它的类型为 ``string`` ,值由 `readLine <io.html#readLine,File>`_ 过程返回。 因为编译器明确知道 `readLine <io.html#readLine,File>`_ 返回的是一个字符串, 所以你可以省略声明中的类型(这叫作 `局部类型推导`:idx: )。所以也可以这样用: .. code-block:: Nim :test: "nim c $1" var name = readLine(stdin) 请注意,这基本上是Nim中存在的唯一类型推导形式:兼顾了简洁与可读性。 "hello world" 程序包含了一些编译器已知的标识符: ``echo`` 、 `readLine <io.html#readLine,File>`_ 等。 这些内置项被声明在了在由任何其他模块隐式导入的 system_ 模块中。 词法元素 ================ 让我们看看Nim词法元素的更多细节:像其它编程语言一样,Nim由(字符串)字面值、标识符、关键字、注释、操作符、和其它标点符号构成。 字符串和字符字面值 ----------------------------- 字符串字面值通过双引号括起来;字符字面值用单引号。特殊字符通过 ``\`` 转义: ``\n`` 表示换行, ``\t`` 表示制表符等,还有 *原始* 字符串字面值: .. code-block:: Nim r"C:\program files\nim" 在原始字面值中反斜杠不是转义字符。 第三种也是最后一种写字符串字面值的方法是 *长字符串字面值* 。用三引号 ``"""..."""`` 写,他们可以跨行并且 ``\`` 也不是转义字符。例如它们对嵌入HTML代码模板很有用。 注释 -------- 注释在任何字符串或字符字面值之外,以哈希字符 ``#`` 开始,文档以 ``##`` 开始: .. code-block:: nim :test: "nim c $1" # 注释。 var myVariable: int ## 文档注释 文档注释是令牌;它们只允许在输入文件中的某些位置,因为它们属于语法树!这个功能可实现更简单的文档生成器。 多行注释以 ``#[`` 开始,以 ``]#`` 结束。多行注释也可以嵌套。 .. code-block:: nim :test: "nim c $1" #[ You can have any Nim code text commented out inside this with no indentation restrictions. yes("May I ask a pointless question?") #[ Note: these can be nested!! ]# ]# 数字 ------- 数字字面值与其它大多数语言一样。作为一个特别的地方,为了更好的可读性,允许使用下划线: ``1_000_000`` (一百万)。 包含点(或者'e'或'E')的数字是浮点字面值: ``1.0e9`` (十亿)。十六进制字面值前缀是 ``0x`` ,二进制字面值用 ``0b`` ,八进制用 ``0o`` 。 单独一个前导零不产生八进制。 var语句 ================= var语句声明一个本地或全局变量: .. code-block:: var x, y: int # 声明x和y拥有类型 ``int`` 缩进可以用在 ``var`` 关键字后来列一个变量段。 .. code-block:: :test: "nim c $1" var x, y: int # 可以有注释 a, b, c: string 赋值语句 ======================== 赋值语句为一个变量赋予新值或者更一般地,赋值到一个存储地址: .. code-block:: var x = "abc" # 引入一个新变量`x`并且赋值给它 x = "xyz" # 赋新值给 `x` ``=`` 是 *赋值操作符* 。赋值操作符可以重载。你可以用一个赋值语句声明多个变量并且所有的变量具有相同的类型: .. code-block:: :test: "nim c $1" var x, y = 3 # 给变量`x`和`y`赋值3 echo "x ", x # 输出 "x 3" echo "y ", y # 输出 "y 3" x = 42 # 改变`x`为42而不改变`y` echo "x ", x # 输出"x 42" echo "y ", y # 输出"y 3" 注意,使用过程对声明的多个变量进行赋值时可能会产生意外结果:编译器会 *展开* 赋值并多次调用该过程。 如果程序的结果取决于副作用,变量可能最终会有不同的值。为了安全起见,多赋值时使用没有副作用的过程。 常量 ========= 常量是绑定在一个值上的符号。常量值不能改变。编译器必须能够在编译期对常量声明进行求值: .. code-block:: nim :test: "nim c $1" const x = "abc" # 常量x包含字符串"abc" 可以在 ``const`` 关键字之后使用缩进来列出整个常量部分: .. code-block:: :test: "nim c $1" const x = 1 # 这也可以有注释 y = 2 z = y + 5 # 计算是可能的 let语句 ================= ``let`` 语句像 ``var`` 语句一样但声明的符号是 *单赋值* 变量:初始化后它们的值将不能改变。 .. code-block:: let x = "abc" # 引入一个新变量`x`并绑定一个值 x = "xyz" # 非法: 给`x`赋值 ``let`` 和 ``const`` 的区别在于: ``let`` 引入一个变量不能重新赋值。 ``const`` 表示"强制编译期求值并放入数据段": .. code-block:: const input = readLine(stdin) # 错误: 需要常量表达式 .. code-block:: :test: "nim c $1" let input = readLine(stdin) # 可以 流程控制语句 ======================= greetings程序由三个顺序执行的语句构成。只有最原始的程序可以不需要分支和循环。 If语句 ------------ if语句是分支流程控制的一种方法: .. code-block:: nim :test: "nim c $1" let name = readLine(stdin) if name == "": echo "Poor soul, you lost your name?" elif name == "name": echo "Very funny, your name is name." else: echo "Hi, ", name, "!" 可以没有或多个 ``elif`` ,并且 ``else`` 是可选的, ``elif`` 关键字是 ``else if`` 的简写,并且避免过度缩进。( ``""`` 是空字符串,不包含字符。) Case语句 -------------- 另一个分支的方法是case语句。case语句是多分支: .. code-block:: nim :test: "nim c $1" let name = readLine(stdin) case name of "": echo "Poor soul, you lost your name?" of "name": echo "Very funny, your name is name." of "Dave", "Frank": echo "Cool name!" else: echo "Hi, ", name, "!" 可以看出,对于分支允许使用逗号分隔的值列表。 case语句可以处理整型、其它序数类型和字符串。(序数类型后面会讲到) 对整型或序数类型值,也可以用范围: .. code-block:: nim # 这段语句将会在后面解释: from strutils import parseInt echo "A number please: " let n = parseInt(readLine(stdin)) case n of 0..2, 4..7: echo "The number is in the set: {0, 1, 2, 4, 5, 6, 7}" of 3, 8: echo "The number is 3 or 8" 上面的代码不能编译: 原因是你必须覆盖每个 ``n`` 可能包含的值,但代码里只处理了 ``0..8`` 。 因为列出来每个可能的值不现实(尽管范围可以实现),我们通过告诉编译器不处理其它值来修复: .. code-block:: nim ... case n of 0..2, 4..7: echo "The number is in the set: {0, 1, 2, 4, 5, 6, 7}" of 3, 8: echo "The number is 3 or 8" else: discard 空 `discard 语句 <#procedures-discard-statement>`_ 是一个 *什么都不做* 的语句。 编译器知道带有 else 部分的 case 语句不会失败,因此错误消失。 请注意,不可能覆盖所有可能的字符串值:这就是字符串情况总是需要 else 分支的原因。 通常情况下,case语句用于枚举的子范围类型,其中编译器对检查您是否覆盖了任何可能的值有很大帮助。 While语句 --------------- while语句是一个简单的循环结构: .. code-block:: nim :test: "nim c $1" echo "What's your name? " var name = readLine(stdin) while name == "": echo "Please tell me your name: " name = readLine(stdin) # 没有 ``var`` , 因为我们没有声明一个新变量 示例使用while循环来不断的询问用户的名字,只要用户什么都没有输入(只按回车)。 For语句 ------------- ``for`` 语句是一个用于循环遍历 *迭代器* 提供的所有元素的构造。 这个例子中使用了内置的 `<system.html#countup.i,T,T,Positive>`_ 迭代器: .. code-block:: nim :test: "nim c $1" echo "Counting to ten: " for i in countup(1, 10): echo i # --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines 变量 ``i`` 通过 ``for`` 循环隐式地声明,因为是由 `countup <system.html#countup.i,T,T,Positive>`_ 返回的,所以是 ``int`` 类型。 ``i`` 遍历出了 1, 2, .., 10,然后每个值都被 ``echo`` 。 你也可以像下面这样写: .. code-block:: nim echo "Counting to 10: " var i = 1 while i <= 10: echo i inc(i) # increment i by 1 # --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines 倒数可以轻松实现 (但不常需要): .. code-block:: nim echo "Counting down from 10 to 1: " for i in countdown(10, 1): echo i # --> Outputs 10 9 8 7 6 5 4 3 2 1 on different lines 因为计数在程序中经常出现,所以 Nim 还有一个 `..<system.html#...i,S,T>`_ 迭代器用来实现这个功能: .. code-block:: nim for i in 1..10: ... 零索引计数有两个简写 ``..<`` 和 ``..^`` ,为了简化计数到较高索引的前一位。 .. code-block:: nim for i in 0..<10: ... # 0..9 or .. code-block:: nim var s = "some string" for i in 0..<s.len: ... 其它有用的迭代器(如数组和序列)是 * ``items`` 和 ``mitems`` ,提供不可改变和可改变元素, * ``pairs`` 和 ``mpairs`` 提供元素和索引数字。 .. code-block:: nim :test: "nim c $1" for index, item in ["a","b"].pairs: echo item, " at index ", index # => a at index 0 # => b at index 1 作用域和块语句 ------------------------------ 控制流语句有一个还没有讲的特性: 它们有自己的作用域。这意味着在下面的示例中, ``x`` 在作用域外是不可访问的: .. code-block:: nim :test: "nim c $1" :status: 1 while false: var x = "hi" echo x # 不行 一个while(for)语句引入一个隐式块。标识符是只在它们声明的块内部可见。 ``block`` 语句可以用来显式地打开一个新块: .. code-block:: nim :test: "nim c $1" :status: 1 block myblock: var x = "hi" echo x # 不行 块的 *label* (本例中的 ``myblock`` ) 是可选的。 Break语句 --------------- 块可以用一个 ``break`` 语句跳出。break语句可以跳出一个 ``while``, ``for``, 或 ``block`` 语句. 它跳出最内层的结构, 除非给定一个块标签: .. code-block:: nim :test: "nim c $1" block myblock: echo "entering block" while true: echo "looping" break # 跳出循环,但不跳出块 echo "still in block" block myblock2: echo "entering block" while true: echo "looping" break myblock2 # 跳出块 (和循环) echo "still in block" Continue语句 ------------------ 像其它编程语言一样, ``continue`` 语句立刻开始下一次迭代: .. code-block:: nim :test: "nim c $1" while true: let x = readLine(stdin) if x == "": continue echo x When语句 -------------- 示例: .. code-block:: nim :test: "nim c $1" when system.hostOS == "windows": echo "running on Windows!" elif system.hostOS == "linux": echo "running on Linux!" elif system.hostOS == "macosx": echo "running on Mac OS X!" else: echo "unknown operating system" ``when`` 语句几乎等价于 ``if`` 语句, 但有以下区别: * 每个条件必须是常量表达式,因为它被编译器求值。 * 分支内的语句不打开新作用域。 * 编译器检查语义并 *仅* 为属于第一个求值为true的条件生成代码。 ``when`` 语句在写平台特定代码时有用,类似于C语言中的 ``#ifdef`` 结构。 语句和缩进 ========================== 既然我们覆盖了基本的控制流语句, 让我们回到Nim缩进规则。 在Nim中 *简单语句* 和 *复杂语句* 有区别。 *简单语句* 不能包含其它语句:属于简单语句的赋值, 过程调用或 ``return`` 语句。 *复杂语句* 像 ``if`` 、 ``when`` 、 ``for`` 、 ``while`` 可以包含其它语句。 为了避免歧义,复杂语句必须缩进, 但单个简单语句不必: .. code-block:: nim # 单个赋值语句不需要缩进: if x: x = false # 嵌套if语句需要缩进: if x: if y: y = false else: y = true # 需要缩进, 因为条件后有两个语句: if x: x = false y = false *表达式* 是语句通常有一个值的部分。 例如,一个if语句中的条件是表达式。表达式为了更好的可读性可以在某些地方缩进: .. code-block:: nim if thisIsaLongCondition() and thisIsAnotherLongCondition(1, 2, 3, 4): x = true 根据经验,表达式中的缩进允许在操作符、开放的小括号和逗号后。 用小括号和分号 ``(;)`` 可以在只允许表达式的地方使用语句: .. code-block:: nim :test: "nim c $1" # 编译期计算fac(4) : const fac4 = (var x = 1; for i in 1..4: x *= i; x) Procedure(过程) ========== 为了在示例中定义像 `echo <system.html#echo,varargs[typed,]>`_ 和 `readLine <io.html#readLine,File>`_ 这样的新命令, 需要 `procedure` (过程)的概念。(一些语言叫 *methods (方法)* 或 *functions (函数)* 。) 在Nim中用 ``proc`` 关键字来定义一个过程: .. code-block:: nim :test: "nim c $1" proc yes(question: string): bool = echo question, " (y/n)" while true: case readLine(stdin) of "y", "Y", "yes", "Yes": return true of "n", "N", "no", "No": return false else: echo "Please be clear: yes or no" if yes("Should I delete all your important files?"): echo "I'm sorry Dave, I'm afraid I can't do that." else: echo "I think you know what the problem is just as well as I do." 这个示例展示了一个名叫 ``yes`` 的过程,它问用户一个 ``question`` 并返回true如果他们回答"yes"(或类似的回答),返回false当他们回答"no"(或类似的回答)。一个 ``return`` 语句立即跳出过程。 ``(question: string): bool`` 语法描述过程需要一个名为 ``question`` ,类型为 ``string`` 的变量,并且返回一个 ``bool`` 值。 ``bool`` 类型是内置的:合法的值只有 ``true`` 和 ``false`` 。if或while语句中的条件必须是 ``bool`` 类型。 一些术语: 示例中 ``question`` 叫做一个(形) *参*, ``"Should I..."`` 叫做 *实参* 传递给这个参数。 Result变量 --------------- 一个返回值的过程有一个隐式 ``result`` 变量声明代表返回值。一个没有表达式的 ``return`` 语句是 ``return result`` 的简写。 ``result`` 总在过程的结尾自动返回如果退出时没有 ``return`` 语句. .. code-block:: nim :test: "nim c $1" proc sumTillNegative(x: varargs[int]): int = for i in x: if i < 0: return result = result + i echo sumTillNegative() # echos 0 echo sumTillNegative(3, 4, 5) # echos 12 echo sumTillNegative(3, 4 , -1 , 6) # echos 7 ``result`` 变量已经隐式地声明在函数的开头,那么比如再次用'var result'声明, 将用一个相同名字的普通变量遮蔽它。result变量也已经用返回类型的默认值初始化过。 注意引用数据类型将是 ``nil`` 在过程的开头,因此可能需要手动初始化。 形参 ---------- 形参在过程体中不可改变。默认地,它们的值不能被改变,这允许编译器以最高效的方式实现参数传递。如果在一个过程内需要可以改变的变量,它必须在过程体中用 ``var`` 声明。 遮蔽形参名是可能的,实际上是一个习语: .. code-block:: nim :test: "nim c $1" proc printSeq(s: seq, nprinted: int = -1) = var nprinted = if nprinted == -1: s.len else: min(nprinted, s.len) for i in 0 .. <nprinted: echo s[i] 如果过程需要为调用者修改实参,可以用 ``var`` 参数: .. code-block:: nim :test: "nim c $1" proc divmod(a, b: int; res, remainder: var int) = res = a div b # 整除 remainder = a mod b # 整数取模操作 var x, y: int divmod(8, 5, x, y) # 修改x和y echo x echo y 示例中, ``res`` 和 ``remainder`` 是 `var parameters` 。Var参数可以被过程修改,改变对调用者可见。注意上面的示例用一个元组作为返回类型而不是var参数会更好。 Discard语句 ----------------- 调用仅为其副作用返回值并忽略返回值的过程, **必须** 用 ``discard`` 语句。Nim不允许静默地扔掉一个返回值: .. code-block:: nim discard yes("May I ask a pointless question?") 返回类型可以被隐式地忽略如果调用的方法、迭代器已经用 ``discardable`` pragma声明过。 .. code-block:: nim :test: "nim c $1" proc p(x, y: int): int {.discardable.} = return x + y p(3, 4) # now valid 在 `Comments`_ 段中描述 ``discard`` 语句也可以用于创建块注释。 命名参数 --------------- 通常一个过程有许多参数而且参数的顺序不清晰。这在构造一个复杂数据类型时尤为突出。因此可以对传递给过程的实参命名,以便于看清哪个实参属于哪个形参: .. code-block:: nim proc createWindow(x, y, width, height: int; title: string; show: bool): Window = ... var w = createWindow(show = true, title = "My Application", x = 0, y = 0, height = 600, width = 800) 既然我们使用命名实参来调用 ``createWindow`` 实参的顺序不再重要。有序实参和命名实参混合起来用也没有问题,但不是很好读: .. code-block:: nim var w = createWindow(0, 0, title = "My Application", height = 600, width = 800, true) 编译器检查每个形参只接收一个实参。 默认值 -------------- 为了使 ``createWindow`` 方法更易于使用,它应当提供 `默认值` ;这些值在调用者没有指定时用作实参: .. code-block:: nim proc createWindow(x = 0, y = 0, width = 500, height = 700, title = "unknown", show = true): Window = ... var w = createWindow(title = "My Application", height = 600, width = 800) 现在调用 ``createWindow`` 只需要设置不同于默认值的值。 现在形参可以由默认值进行类型推导;例如,没有必要写 ``title: string = "unknown"`` 。 重载过程 --------------------- Nim提供类似C++的过程重载能力: .. code-block:: nim proc toString(x: int): string = ... proc toString(x: bool): string = if x: result = "true" else: result = "false" echo toString(13) # calls the toString(x: int) proc echo toString(true) # calls the toString(x: bool) proc (注意 ``toString`` 通常是 Nim 中的 `$ <dollars.html>`_ 操作符。) 编译器会为 ``toString`` 的调用选择最合适的过程。 这里不讨论这个重载解析算法是如何精确工作的(会在手册中具体说明)。 不管怎么说,它并不会导致什么意外,并是基于一个非常简单的统一算法。 有歧义的调用会报错。 操作符 --------- Nim库重度使用重载,一个原因是每个像 ``+`` 的操作符就是一个重载过程。解析器让你在 `中缀标记` (``a + b``)或 `前缀标记` (``+ a``)中使用操作符。 一个中缀操作符总是有两个实参,一个前缀操作符总是一个。(后缀操作符是不可能的,因为这有歧义: ``a @ @ b`` 表示 ``(a) @ (@b)`` 还是 ``(a@) @ (b)`` ?它总是表示 ``(a) @ (@b)`` , 因为Nim中没有后缀操作符。 除了几个内置的关键字操作符如 ``and`` 、 ``or`` 、 ``not`` ,操作符总是由以下符号构成: ``+ - * \ / < > = @ $ ~ & % ! ? ^ . |`` 允许用户定义的操作符。没有什么阻止你定义自己的 ``@!?+~`` 操作符,但这么做降低了可读性。 操作符优先级由第一个字符决定。细节可以在手册中找到。 用反引号"``"括起来定义一个新操作符: .. code-block:: nim proc `$` (x: myDataType): string = ... # 现在$操作符对myDataType生效,重载解析确保$对内置类型像之前一样工作。 "``"标记也可以来用调用一个像任何其它过程的操作符: .. code-block:: nim :test: "nim c $1" if `==`( `+`(3, 4), 7): echo "True" 前向声明 -------------------- 每个变量、过程等,需要使用前向声明。前向声明不能互相递归: .. code-block:: nim # 前向声明: proc even(n: int): bool .. code-block:: nim proc odd(n: int): bool = assert(n >= 0) # 确保我们没有遇到负递归 if n == 0: false else: n == 1 or even(n-1) proc even(n: int): bool = assert(n >= 0) # 确保我们没有遇到负递归 if n == 1: false else: n == 0 or odd(n-1) 这里 ``odd`` 取决于 ``even`` 反之亦然。因此 ``even`` 需要在完全定义前引入到编译器。前向声明的语法很简单:直接忽略 ``=`` 和过程体。 ``assert`` 只添加边界条件,将在 `模块`_ 段中讲到。 语言的后续版本将弱化前向声明的要求。 示例也展示了一个过程体可以由一个表达式构成,其值之后被隐式返回。 迭代器 ========= 让我们回到简单的计数示例: .. code-block:: nim :test: "nim c $1" echo "Counting to ten: " for i in countup(1, 10): echo i 写一个 `countup <system.html#countup.i,T,T,Positive>`_ 过程可以实现这个循环吗?让我们试试: .. code-block:: nim proc countup(a, b: int): int = var res = a while res <= b: return res inc(res) 这不行,问题在于过程不应当只 ``return`` ,但是迭代器后的return和 **continue** 已经完成。这 *return and continue* 叫做 `yield` 语句。现在只剩下用 ``iterator`` 替换 ``proc`` 关键字, 它来了——我们的第一个迭代器: .. code-block:: nim :test: "nim c $1" iterator countup(a, b: int): int = var res = a while res <= b: yield res inc(res) 迭代器看起来像过程,但有几点重要的差异: * 迭代器只能从循环中调用。 * 迭代器不能包含 ``return`` 语句(过程不能包含 ``yield`` 语句)。 * 迭代器没有隐式 ``result`` 变量。 * 迭代器不支持递归。 * 迭代器不能前向声明,因为编译器必须能够内联迭代器。(这个限制将在编译器的未来版本中消失。) 你也可以用 ``closure`` 迭代器得到一个不同的限制集合。详见 `一等迭代器<manual.html#iterators-and-the-for-statement-first-class-iterators>`_ 。 迭代器可以和过程有同样的名字和形参,因为它们有自己的命名空间。 因此,通常的做法是将迭代器包装在同名的proc中,这些迭代器会累积结果并将其作为序列返回, 像 `strutils模块<strutils.html>`_ 中的 ``split`` 。 基本类型 =========== 本章处理基本内置类型和它们的操作细节。 布尔值 -------- Nim的布尔类型叫做 ``bool`` ,由两个预先定义好的值 ``true`` 和 ``false`` 构成。while、if、elif和when语句中的条件必须是布尔类型。 为布尔类型定义操作符 ``not, and, or, xor, <, <=, >, >=, !=, ==`` 。 ``and`` 和 ``or`` 操作符执行短路求值。例如: .. code-block:: nim while p != nil and p.name != "xyz": # 如果p == nil,p.name不被求值 p = p.next 字符 ---------- 字符类型叫做 ``char`` 。大小总是一字节,所以不能表示大多数UTF-8字符;但可以表示组成多字节UTF-8字符的一个字节。原因是为了效率:对于绝大多数用例,程序依然可以正确处理UTF-8因为UTF-8是专为此设计的。 字符字面值用单引号括起来。 字符可以用 ``==``, ``<``, ``<=``, ``>``, ``>=`` 操作符比较。 ``$`` 操作符将一个 ``char`` 转换成一个 ``string`` 。字符不能和整型混合;用 ``ord`` 过程得到一个 ``char`` 的序数值。 从整型到 ``char`` 转换使用 ``chr`` 过程。 字符串 ------- 字符串变量是 **可以改变的** , 字符串可以追加,而且非常高效。Nim中的字符串有长度字段,以零结尾。一个字符串长度可以用内置 ``len`` 过程获取;长度不计结尾的零。访问结尾零是一个错误,它只为Nim字符串无拷贝转换为 ``cstring`` 存在。 字符串赋值会产生拷贝。你可以用 ``&`` 操作符拼接字符串和 ``add`` 追加到一个字符串。 字符串用字典序比较,支持所有比较操作符。通过转换,所有字符串是UTF-8编码过的,但不是强制。例如,当从进制文件读取字符串时,他们只是一串字节序列。索引操作符 ``s[i]`` 表示 ``s`` 的第i个 *字符* , 不是第i个 *unichar* 。 一个字符串变量用空字符串初始化 ``""`` 。 整型 -------- Nim有以下内置整型: ``int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64`` 。 默认整型是 ``int`` 。整型字面值可以用 *类型前缀* 来指定一个非默认整数类型: .. code-block:: nim :test: "nim c $1" let x = 0 # x是 ``int`` y = 0'i8 # y是 ``int8`` z = 0'i64 # z是 ``int64`` u = 0'u # u是 ``uint`` 多数常用整数用来计数内存中的对象,所以 ``int`` 和指针具有相同的大小。 整数支持通用操作符 ``+ - * div mod < <= == != > >=`` 。 也支持 ``and or xor not`` 操作符,并提供 *按位* 操作。 左移用 ``shl`` ,右移用 ``shr`` 。位移操作符实参总是被当作 *无符号整型* 。 普通乘法或除法可以做 `算术位移`:idx: 。 无符号操作不会引起上溢和下溢。 无损 `自动类型转换`:idx: 在表达式中使用不同类型的整数时执行。如果失真,会抛出 `EOutOfRange`:idx: 异常(如果错误没能在编译时检查出来)。 浮点 ------ Nim有这些内置浮点类型: ``float float32 float64`` 。 默认浮点类型是 ``float`` 。在当前的实现, ``float`` 是64位。 浮点字面值可以有 *类型前缀* 来指定非默认浮点类型: .. code-block:: nim :test: "nim c $1" var x = 0.0 # x是 ``float`` y = 0.0'f32 # y是 ``float32`` z = 0.0'f64 # z是 ``float64`` 浮点类型支持通用操作符 ``+ - * / < <= == != > >=`` 并遵循IEEE-754标准。 在具有不同浮点类型的表达式中执行自动类型转换:短类型被转换为了长类型。 整数类型 **不** 会自动转换为浮点类型,反之亦然。 需要使用 `toInt <system.html#toInt,float>`_ 和 `toFloat <system.html#toFloat,int>`_ 过程来转换。 类型转换 --------------- 数字类型转换通过使用类型来执行: .. code-block:: nim :test: "nim c $1" var x: int32 = 1.int32 # 与调用int32(1)相同 y: int8 = int8('a') # 'a' == 97'i8 z: float = 2.5 # int(2.5)向下取整为2 sum: int = int(x) + int(y) + int(z) # sum == 100 内部类型表示 ============================ 之前提到过,内置的 `$ <dollars.html>`_ (字符串化)操作符将基本类型转换成了字符串, 所以你才可以用 ``echo`` 过程将内容打印到控制台上。 但是高级类型和你自定义的类型,需要为他们定义了 ``$`` 操作符才能使用。 有时你可能只想调试复杂类型的当前值,而不想再去编写它的 ``$`` 运算符。 那么你可以用 `repr <system.html#repr,T>`_ 过程,它可以用于任何类型甚至复杂的循环数据图。 下面的示例表明,即使对于基本类型,``$`` 和 ``repr`` 的输出之间也存在差异: .. code-block:: nim :test: "nim c $1" var myBool = true myCharacter = 'n' myString = "nim" myInteger = 42 myFloat = 3.14 echo myBool, ":", repr(myBool) # --> true:true echo myCharacter, ":", repr(myCharacter) # --> n:'n' echo myString, ":", repr(myString) # --> nim:0x10fa8c050"nim" echo myInteger, ":", repr(myInteger) # --> 42:42 echo myFloat, ":", repr(myFloat) # --> 3.1400000000000001e+00:3.1400000000000001e+00 高级类型 ============== 在Nim中新类型可以在 ``type`` 语句里定义: .. code-block:: nim :test: "nim c $1" type biggestInt = int64 # 可用的最大整数类型 biggestFloat = float64 # 可用的最大浮点类型 枚举和对象类型只能定义在 ``type`` 语句中。 枚举 ------------ 枚举类型的变量只能赋值为枚举指定的值。这些值是有序符号的集合。每个符号映射到内部的一个整数类型。第一个符号用运行时的0表示,第二个用1,以此类推。例如: .. code-block:: nim :test: "nim c $1" type Direction = enum north, east, south, west var x = south # `x`是`Direction`; 值是`south` echo x # 向标准输出写"south" 所有对比操作符可以用枚举类型。 枚举符号 枚举的符号可以被限定以避免歧义: ``Direction.south`` 。 ``$`` 操作符可以将任何枚举值转换为它的名字, ``ord`` 过程可以转换为它底层的整数类型。 为了更好的对接其它编程语言,枚举类型可以赋一个显式的序数值,序数值必须是升序。 序数类型 ------------- 枚举、整型、 ``char`` 、 ``bool`` (和子范围)叫做序数类型。序数类型有一些特殊操作: ----------------- -------------------------------------------------------- Operation Comment ----------------- -------------------------------------------------------- ``ord(x)`` 返回表示 `x` 的整数值 ``inc(x)`` `x` 递增1 ``inc(x, n)`` `x` 递增 `n`; `n` 是整数 ``dec(x)`` `x` 递减1 ``dec(x, n)`` `x` 递减 `n`; `n` 是整数 ``succ(x)`` 返回 `x` 的下一个值 ``succ(x, n)`` 返回 `x` 后的第n个值 ``pred(x)`` 返回 `x` 的前一个值 ``pred(x, n)`` 返回 `x` 前的第n个值 ----------------- -------------------------------------------------------- `inc <system.html#inc,T,int>`_、 `dec <system.html#dec,T,int>`_、 `succ <system.html#succ,T,int>`_ 和 `pred <system.html#pred,T,int>`_ 操作符可能会失败并抛出一个 `EOutOfRange` 或 `EOverflow` 异常。 (如果代码编译时打开了运行时检查。) 子范围 --------- 一个子范围是一个整型或枚举类型值(基本类型)的范围。例如: .. code-block:: nim :test: "nim c $1" type MySubrange = range[0..5] ``MySubrange`` 是只包含0到5的 ``int`` 范围。赋任何其它值给 ``MySubrange`` 类型的变量是编译期或运行时错误。允许给子范围赋值它的基类型,反之亦然。 ``system`` 模块定义了重要的 `Natural(自然数) <system.html#Natural>`_ 类型, 作为 ``range[0..high(int)]``的类型 (`high <system.html#high,typedesc[T]>`_ 返回最大值)。 其它编程语言可能建议对自然数的情况使用无符号整数。这通常是 **不明智的** : 你不希望因为数字不能为负而使用无符号算术。 Nim的 ``Natural`` 类型有助于避免这个常见的编程错误。 集合类型 ---- 集合模拟了数学集合的概念。 集合的基类型只能是固定大小的序数类型,它们是: * ``int8``-``int16`` * ``uint8``/``byte``-``uint16`` * ``char`` * ``enum`` 或等价类型。对有符号整数集合的基类型被定义为在 ``0 .. MaxSetElements-1`` 的范围内, 其中 ``MaxSetElements`` 目前是2^16。 原因是集合被实现为高性能位向量。尝试声明具有更大类型的集将导致错误: .. code-block:: nim var s: set[int64] # 错误: 集合太大 集合可以通过集合构造器来构造: ``{}`` 是空集合。 空集合与其它具体的集合类型兼容。构造器也可以用来包含元素(和元素范围): .. code-block:: nim type CharSet = set[char] var x: CharSet x = {'a'..'z', '0'..'9'} # 构造一个包含'a'到'z'和'0'到'9'的集合 集合支持的操作符: ================== ======================================================== 操作符 含义 ================== ======================================================== ``A + B`` 并集 ``A * B`` 交集 ``A - B`` 差集 ``A == B`` 相等 ``A <= B`` 子集 ``A < B`` 真子集 ``e in A`` 元素 ``e notin A`` A不包含元素e ``contains(A, e)`` 包含元素e ``card(A)`` A的基 (集合A中的元素数量) ``incl(A, elem)`` 同 ``A = A + {elem}`` ``excl(A, elem)`` 同 ``A = A - {elem}`` ================== ======================================================== 位字段 ~~~~~~~~~~ 集合经常用来定义过程的 *标示* 。这比定义必须或在一起的整数常量清晰并且类型安全。 枚举、集合和强转可以一起用: .. code-block:: nim type MyFlag* {.size: sizeof(cint).} = enum A B C D MyFlags = set[MyFlag] proc toNum(f: MyFlags): int = cast[cint](f) proc toFlags(v: int): MyFlags = cast[MyFlags](v) assert toNum({}) == 0 assert toNum({A}) == 1 assert toNum({D}) == 8 assert toNum({A, C}) == 5 assert toFlags(0) == {} assert toFlags(7) == {A, B, C} 注意集合如何把枚举变成2的指数。 如果和C一起使用枚举和集合,使用distinct cint。 为了和C互通见 `bitsize pragma <#implementation-specific-pragmas-bitsize-pragma>`_ 。 数组 ------ 数组是固定长度的容器。数组中的元素具有相同的类型。数组索引类型可以是任意序数类型。 数组可以用 ``[]`` 来构造: .. code-block:: nim :test: "nim c $1" type IntArray = array[0..5, int] # 一个索引为0..5的数​组 var x: IntArray x = [1, 2, 3, 4, 5, 6] for i in low(x)..high(x): echo x[i] ``x[i]`` 标记用来访问 ``x`` 的第i个元素。数组访问总是有边界检查的 (编译期或运行时)。这些检查可以通过pragmas或调用编译器的命令行开关 ``--bound_checks:off`` 来关闭。 数组是值类型,和任何其它Nim类型一样。赋值操作符拷贝整个数组内容。 内置的 `len <system.html#len,TOpenArray>`_ 过程返回数组的长度。 `low(a) <system.html#low,openArray[T]>`_ 返回数组 ``a`` 的最小索引, `high(a) <system.html#high,openArray[T]>`_ 则返回最大索引。 .. code-block:: nim :test: "nim c $1" type Direction = enum north, east, south, west BlinkLights = enum off, on, slowBlink, mediumBlink, fastBlink LevelSetting = array[north..west, BlinkLights] var level: LevelSetting level[north] = on level[south] = slowBlink level[east] = fastBlink echo repr(level) # --> [on, fastBlink, slowBlink, off] echo low(level) # --> north echo len(level) # --> 4 echo high(level) # --> west 嵌套数组的语法,即其它语言中的多维数组,实际上是追加更多中括号因为通常每个维度限制为和其它一样的索引类型。 在Nim中你可以在不同的维度有不同索引类型,所以嵌套语法稍有不同。 基于上面的例子,其中层数定义为枚举的数组被另一个枚举索引,我们可以添加下面的行来添加一个在层数上进行再分割的灯塔类型: .. code-block:: nim type LightTower = array[1..10, LevelSetting] var tower: LightTower tower[1][north] = slowBlink tower[1][east] = mediumBlink echo len(tower) # --> 10 echo len(tower[1]) # --> 4 echo repr(tower) # --> [[slowBlink, mediumBlink, ...more output.. # 下面的行不能编译因为类型不匹配 #tower[north][east] = on #tower[0][1] = on 注意内置 ``len`` 过程如何只返回数组的第一维长度。另一个定义 ``LightTower`` 的方法来更好的说明它的嵌套本质是忽略上面定义的 ``LevelSetting`` 类型,取而代之是直接将它以第一维类型嵌入。 .. code-block:: nim type LightTower = array[1..10, array[north..west, BlinkLights]] 从零开始对数组很普遍,有从零到指定索引减1的范围简写语法: .. code-block:: nim :test: "nim c $1" type IntArray = array[0..5, int] # 一个索引为0..5的数​组 QuickArray = array[6, int] # 一个索引为0..5的数​组 var x: IntArray y: QuickArray x = [1, 2, 3, 4, 5, 6] y = x for i in low(x)..high(x): echo x[i], y[i] 序列 --------- 序列类似数组但是动态长度,可以在运行时改变(像字符串)。因为序列是大小可变的它们总是分配在堆上,被垃圾回收。 序列的索引总是从零开始递增的 ``int`` 类型。 `len <system.html#len,seq[T]>`_ , `low <system.html#low,openArray[T]>`_ 和 `<system.html#high,openArray[T]>`_ 操作符也可用于序列。 ``x[i]`` 标记可以用于访问 ``x`` 的第 i 个元素。 序列可以用数组构造器 ``[]`` 数组到序列操作符 ``@`` 构成。另一个为序列分配空间的方法是调用内置 `newSeq <system.html#newSeq>`_ 过程。 序列可以传递给一个开放数组形参。 Example: .. code-block:: nim :test: "nim c $1" var x: seq[int] # 整数序列引用 x = @[1, 2, 3, 4, 5, 6] # @ 把数组转成分配在堆上的序列 序列变量用 ``@[]`` 初始化。 ``for`` 语句可以用一到两个变量当和序列一起使用。当你使用一个变量的形式,变量持有序列提供的值。 ``for`` 语句是在 `system <system.html>`_ 模块中的 `items() <system.html#items.i,seq[T]>`_ 迭代器结果上迭代。 但如果你使用两个变量形式,第一个变量将持有索引位置,第二个变量持有值。这里 ``for`` 语句是在 `system <system.html>`_ 模块中的 `pairs() <system.html#pairs.i,seq[T]>`_ 迭代器结果上迭代。例如: .. code-block:: nim :test: "nim c $1" for value in @[3, 4, 5]: echo value # --> 3 # --> 4 # --> 5 for i, value in @[3, 4, 5]: echo "index: ", $i, ", value:", $value # --> index: 0, value:3 # --> index: 1, value:4 # --> index: 2, value:5 开放数组 ----------- **注意**: 开放数组只用于形参。 固定大小的数组往往过于死板;而过程也应当能够处理不同大小的数组。 `开放数组`:idx: 类型为我们带来了可能。开放数组的索引总是以0开始的 ``int`` 。 `len <system.html#len,TOpenArray>`_, `low <system.html#low,openArray[T]>`_ 和 `high <system.html#high,openArray[T]>`_ 操作符也可以在开放数组使用。 所有兼容基类型的数组都可以代入开放数组参数,索引类型无关紧要。 .. code-block:: nim :test: "nim c $1" var fruits: seq[string] # 字符串序列用 '@[]' 初始化 capitals: array[3, string] # 固定大小的字符串数组 capitals = ["New York", "London", "Berlin"] # 数组 'capitals' 允许只有三个元素的赋值 fruits.add("Banana") # 序列 'fruits' 在运行时动态扩展 fruits.add("Mango") proc openArraySize(oa: openArray[string]): int = oa.len assert openArraySize(fruits) == 2 # 过程接受一个序列作为形参 assert openArraySize(capitals) == 3 # 也可以是一个数组 开放数组类型无法嵌套:多维开放数组不支持,因为这个需求很少见且不能有效的实现。 可变参数 ------- ``varargs`` 参数像开放数组形参。 它也表示实现传递数量可变的实参给过程。 编译器将实参列表自动转换为数组: .. code-block:: nim :test: "nim c $1" proc myWriteln(f: File, a: varargs[string]) = for s in items(a): write(f, s) write(f, "\n") myWriteln(stdout, "abc", "def", "xyz") # 编译器转为: myWriteln(stdout, ["abc", "def", "xyz"]) 转换只在可变形参是过程头部的最后一个形参时完成。它也可以在这个情景执行类型转换: .. code-block:: nim :test: "nim c $1" proc myWriteln(f: File, a: varargs[string, `$`]) = for s in items(a): write(f, s) write(f, "\n") myWriteln(stdout, 123, "abc", 4.0) # 编译器转为: myWriteln(stdout, [$123, $"abc", $4.0]) 在示例中 `$ <dollars.html>`_ 适用于任何传递给形参 ``a`` 的实参。 注意 `$ <dollars.html>`_ 适用于空字符串指令。 Note that `$ <dollars.html>`_ applied to strings is a nop. 切片 ------ 切片语法看起来像子范围但用于不同的场景。切片只是一个包含两个边界 `a` and `b` 的切片类型对象。 它自己不是很有用,但是其它收集类型定义接受切片对象来定义范围的操作符。 .. code-block:: nim :test: "nim c $1" var a = "Nim is a progamming language" b = "Slices are useless." echo a[7..12] # --> 'a prog' b[11..^2] = "useful" echo b # --> 'Slices are useful.' 在上面的例子中切片用于修改字符串的一部分。切片边界可以持有任何它们的类型支持的值,但它是使用切片对象的过程,它定义了接受的值。 为了理解指定字符串、数组、序列等索引的不同方法, 必须记住Nim使用基于零的索引。 所以字符串 ``b`` 长度是19, 两个不同的指定索引的方法是 .. code-block:: nim "Slices are useless." | | | 0 11 17 使用索引 ^19 ^8 ^2 使用^ 其中 ``b[0..^1]`` 等价于 ``b[0..b.len-1]`` 和 ``b[0..<b.len]`` ,它可以看作 ``^1`` 提供一个指定 ``b.len-1`` 的简写。 在上面的例子中,因为字符串在句号中结束,来获取字符串中"useless"的部分并替换为"useful"。 ``b[11..^2]`` 是"useless"的部分, ``b[11..^2] = "useful"`` 用"useful"替换"useless",得到结果"Slices are useful." 注意: 可选方法是 ``b[^8..^2] = "useful"`` 或 ``b[11..b.len-2] = "useful"`` 或 as ``b[11..<b.len-1] = "useful"`` 。 对象 ------- 在具有名称的单个结构中将不同值打包在一起的默认类型是对象类型。对象是值类型,意味关当对象赋值给一个新变量时它所有的组成部分也一起拷贝。 每个对象类型 ``Foo`` 有一个构造函数 ``Foo(field: value, ...)`` 其中它的所有字段可以被初始化。没有指定的字段将获得它们的默认值。 .. code-block:: nim type Person = object name: string age: int var person1 = Person(name: "Peter", age: 30) echo person1.name # "Peter" echo person1.age # 30 var person2 = person1 # 复制person 1 person2.age += 14 echo person1.age # 30 echo person2.age # 44 # 顺序可以改变 let person3 = Person(age: 12, name: "Quentin") # 不需要指定每个成员 let person4 = Person(age: 3) # 未指定的成员将用默认值初始化。本例中它是一个空字符串。 doAssert person4.name == "" 在定义的模块外可见的对象字段需要加上 ``*`` 。 .. code-block:: nim :test: "nim c $1" type Person* = object # 其它模块可见 name*: string # 这个类型的字段在其它模块可见 age*: int 元组 ------ 元组和你目前见到的对象很像。它们是赋值时拷贝每个组成部分的值类型。与对象类型不同的是,元组类型是结构化类型,这意味着不同的元组类型是 *等价的* 如果它们以相同的顺序指定相同类型和相同名称的字段。 构造函数 ``()`` 可以用来构造元组。构造函数中字段的顺序必须与元组定义中的顺序匹配。但与对象不同,此处可能不使用元组类型的名称。 如对象类型, ``t.field`` 用来访问一个元组的字段。 另一个对象不可用的标记法是 ``t[i]`` 访问第 ``i``' 个字段。这里 ``i`` 必须是一个常整数。 .. code-block:: nim :test: "nim c $1" type # 类型表示一个人: # 一个人有名字和年龄。 Person = tuple name: string age: int # 等价类型的语法。 PersonX = tuple[name: string, age: int] # 匿名字段语法 PersonY = (string, int) var person: Person personX: PersonX personY: PersonY person = (name: "Peter", age: 30) # Person和PersonX等价 personX = person # 用匿名字段创建一个元组: personY = ("Peter", 30) # 有匿名字段元组兼容有字段名元组。 person = personY personY = person # 通常用于短元组初始化语法 person = ("Peter", 30) echo person.name # "Peter" echo person.age # 30 echo person[0] # "Peter" echo person[1] # 30 # 你不需要在一个独立类型段中声明元组。 var building: tuple[street: string, number: int] building = ("Rue del Percebe", 13) echo building.street # 下面的行不能编译,它们是不同的元组。 #person = building # --> Error: type mismatch: got (tuple[street: string, number: int]) # but expected 'Person' 即使你不需要为元组声明类型就可以使用,不同字段名创建的元组将认为是不同的对象,尽管有相同的字段类型。 元组在且只在变量赋值期间被 *解包* 。 这可以方便地将元组的字段直接赋值给一个个命名的变量。 `os module <os.html>`_ 模块中的 `splitFile <os.html#splitFile,string>`_ 过程就是一个例子, 它同时返回一个路径的目录、名称和扩展名。 元组解包必须使用小括号括住你想赋值的解包变量,否则所有的变量都会赋上相同的值! 例如: .. code-block:: nim :test: "nim c $1" import os let path = "usr/local/nimc.html" (dir, name, ext) = splitFile(path) baddir, badname, badext = splitFile(path) echo dir # 输出 `usr/local` echo name # 输出 `nimc` echo ext # 输出 `.html` # 下面输出同样的行: # `(dir: usr/local, name: nimc, ext: .html)` echo baddir echo badname echo badext 元组字段总是公有的,你不必像对象类型字段显式的标记来导出。 引用和指针类型 --------------------------- 引用(类似其它编程语言中的指针)是引入多对一关系的方式。这表示不同的引用可以指向和修改相同的内存位置。 Nim区分 `被追踪`:idx: 和 `未追踪`:idx: 引用。未追踪引用也被称为 *指针* 。追踪的引用指向垃圾回收堆里的对象,未追踪引用指向手动分配对象或内存中其它地方的对象。因此未追踪引用是 *不安全的* 。 为了某些低级的操作(例如,访问硬件),未追踪的引用是必须的。 追踪的引用用 **ref** 关键字声明;未追踪引用用 **ptr** 关键字声明。 空 ``[]`` 下标标记可以用来 *解引用* 一个引用,表示获取引用指向的内容。 ``.`` (访问一个元组/对象字段操作符)和 ``[]`` (数组/字符串/序列索引操作符)操作符为引用类型执行隐式解引用操作: .. code-block:: nim :test: "nim c $1" type Node = ref object le, ri: Node data: int var n: Node new(n) n.data = 9 # 不必写n[].data; 实际上n[].data是不提倡的! 为了分配一个新追踪的对象,必须使用内置过程 ``new`` 。 为了处理未追踪内存, 可以用 ``alloc``, ``dealloc`` 和 ``realloc`` 。 `system <system.html>`_ 模块文档包含更多细节。 如果一个引用指向 *nothing*, 它的值是 ``nil`` 。 过程类型 --------------- 过程类型是指向过程的指针。 ``nil`` 是过程类型变量允许的值。Nim使用过程类型达到 `函数式`:idx: 编程技术。 Example: .. code-block:: nim :test: "nim c $1" proc echoItem(x: int) = echo x proc forEach(action: proc (x: int)) = const data = [2, 3, 5, 7, 11] for d in items(data): action(d) forEach(echoItem) 过程类型的一个小问题是调用规约影响类型兼容性:过程类型只兼容如果他们有相同的调用规约。不同的调用规约列在 `manual <manual.html#types-procedural-type>`_ 。 Distinct类型 ------------- 一个Distinct类型允许用于创建“非基本类型的子类型”。你必须 **显式** 定义distinct类型的所有行为。 为了帮助这点,distinct类型和它的基类型可以相互强转。 示例提供在 `manual <manual.html#types-distinct-type>`_ 。 模块 ======= Nim支持用模块的概念把一个程序拆分成片段。每个模块在它自己的文件里。模块实现了 `信息隐藏`:idx: 和 `编译隔离`:idx: 。一个模块可以通过 `import`:idx: 语句访问另一个模块符号。 只有标记了星号(``*``)的顶级符号被导出: .. code-block:: nim # Module A var x*, y: int proc `*` *(a, b: seq[int]): seq[int] = # 分配新序列: newSeq(result, len(a)) # 两个序列相乘: for i in 0..len(a)-1: result[i] = a[i] * b[i] when isMainModule: # 测试序列乘 ``*`` : assert(@[1, 2, 3] * @[1, 2, 3] == @[1, 4, 9]) 上面的模块导出 ``x`` 和 ``*``, 但没有 ``y`` 。 一个模块的顶级语句在程序开始时执行,比如这可以用来初始化复杂数据结构。 每个模块有特殊的魔法常量 ``isMainModule`` 在作为主文件编译时为真。 如上面所示,这对模块内的嵌入测试非常有用。 一个模块的符号 *可以* 用 ``module.symbol`` 语法 *限定* 。如果一个符号有歧义,它 *必须* 被限定。一个符号有歧义如果定义在两个或多个不同的模块并且被第三个模块导入: .. code-block:: nim # Module A var x*: string .. code-block:: nim # Module B var x*: int .. code-block:: nim # Module C import A, B write(stdout, x) # error: x 有歧义 write(stdout, A.x) # okay: 用了限定 var x = 4 write(stdout, x) # 没有歧义: 使用模块C的x 但这个规则不适用于过程或迭代器。重载规则适用于: .. code-block:: nim # Module A proc x*(a: int): string = $a .. code-block:: nim # Module B proc x*(a: string): string = $a .. code-block:: nim # Module C import A, B write(stdout, x(3)) # no error: A.x is called write(stdout, x("")) # no error: B.x is called proc x*(a: int): string = discard write(stdout, x(3)) # 歧义: 调用哪个 `x` ? 排除符号 ----------------- 普通的 ``import`` 语句将带来所有导出的符号。这可以用 ``except`` 标识符点名限制哪个符号应当被排除。 .. code-block:: nim import mymodule except y From语句 -------------- 我们已经看到简单的 ``import`` 语句导入所有导出的符号。一个只导入列出来的符号的可选方法是使用 ``from import`` 语句: .. code-block:: nim from mymodule import x, y, z ``from`` 语句也可以强制限定符号的命名空间,因此可以使符号可用,但需要限定。 .. code-block:: nim from mymodule import x, y, z x() # 没有任何限定使用x .. code-block:: nim from mymodule import nil mymodule.x() # 必须用模块名前缀限定x x() # 没有限定使用x是编译错误 因为模块普遍比较长方便描述,你也可以在限定符号时使用短的别名。 .. code-block:: nim from mymodule as m import nil m.x() # m是mymodule别名 Include语句 ----------------- ``include`` 语句和导入一个模块做不同的基础工作:它只包含一个文件的内容。 ``include`` 语句在把一个大模块拆分为几个文件时有用: .. code-block:: nim include fileA, fileB, fileC Part 2 ====== 那么, 既然我们完成了基本的,让我们看看Nim除了为过程编程提供漂亮的语法外还有哪些: `Part II <tut2.html>`_ .. _strutils: strutils.html .. _system: system.html <file_sep>/doc/tut3.rst ======================= Nim教程 (III) ======================= :Author: <NAME> :Version: |nimversion| .. contents:: 引言 ============ "能力越大,责任越大。" -- 蜘蛛侠的叔叔 本文档是关于Nim宏系统的教程。宏是编译期执行的函数,把Nim语法树变换成不同的树。 用宏可以实现的功能示例: * 一个断言宏,如果断言失败打印比较运算符两边的数, ``myAssert(a == b)`` 转换成 ``if a != b: quit($a " != " $b)`` * 一个调试宏,打印符号的值和名字。 ``myDebugEcho(a)`` 转换成 ``echo "a: ", a`` * 表达式的象征性区别。 ``diff(a*pow(x,3) + b*pow(x,2) + c*x + d, x)`` 转换成 ``3*a*pow(x,2) + 2*b*x + c`` (译者注:ax^3+bx^2+cx+d 微分的结果是 3ax^2+2bx+c) 宏实参 --------------- 宏的实参有两面性。一面用来重载解析,另一面在宏体内使用。例如,如果 ``macro foo(arg: int)`` 在表达式 ``foo(x)`` 中调用, ``x`` 必须是与整型兼容的类型, 但在宏体 *内* ``arg`` 的类型是 ``NimNode`` , 而不是 ``int`` !这么做的原因会在我们见到具体的示例时明白。 有两种给宏传递实参的方式,实参必须是 ``typed`` 或 ``untyped`` 中的一种。 无类型(untyped)实参 ----------------- 无类型宏实参在语义检查前传递给宏。这表示传给宏的语法树Nim尚不需要理解,唯一的限制是它必须是可以解析的。通常宏不检查实参但在变换结果中使用。编译器会检查宏展开的结果,所以除了 一些错误消息没有其它坏事情发生。 ``untyped`` 实参的缺点是对重载解析不利。 无类型实参的优点是语法树可以预知,也比 ``typed`` 简单。 类型化(typed)实参 --------------- 对于类型化实参,语义检查器在它传给宏之前对其进行检查并进行变换。这里标识符节点解析成符号, 树中的隐式类型转换被看作调用,模板被展开,最重要的是节点有类型信息。类型化实参的实参列表可以有 ``typed`` 类型。 但是其它所有类型,例如 ``int``, ``float`` 或 ``MyObjectType`` 也是类型化实参,它们作为一个语法树传递给宏。 静态实参 ---------------- 静态实参是向宏传递值而不是语法树的方法。例如对于 ``macro foo(arg: static[int])`` 来说, ``foo(x)`` 表达式中的 ``x`` 需要是整型常量, 但在宏体中 ``arg`` 只是一个普通的 ``int`` 类型。 .. code-block:: nim import macros macro myMacro(arg: static[int]): untyped = echo arg # 只是int (7), 不是 ``NimNode`` myMacro(1 + 2 * 3) 代码块实参 ------------------------ 可以在具有缩进的单独代码块中传递调用表达式的最后一个参数。 例如下面的代码示例是合法的(不推荐的)调用 ``echo`` 的方法: .. code-block:: nim echo "Hello ": let a = "Wor" let b = "ld!" a & b 对于宏来说这样的调用很有用;任意复杂度的语法树可以用这种标记传给宏。 语法树 --------------- 为了构建Nim语法树,我们需要知道如何用语法树表示Nim源码, 能被Nim编译器理解的树看起来是什么样子的。 Nim语法树节点记载在 `macros <macros.html>`_ 模块。 一个更加互动性的学习Nim语法树的方法是用 ``macros.treeRepr`` ,它把语法树转换成一个多行字符串打印到控制台。 它也可以用来探索实参表达式如何用树的形式表示, 以及生成的语法树的调试打印。 ``dumpTree`` 是一个预定义的宏,以树的形式打印它的实参。树表示的示例: .. code-block:: nim dumpTree: var mt: MyType = MyType(a:123.456, b:"abcdef") # 输出: # StmtList # VarSection # IdentDefs # Ident "mt" # Ident "MyType" # ObjConstr # Ident "MyType" # ExprColonExpr # Ident "a" # FloatLit 123.456 # ExprColonExpr # Ident "b" # StrLit "abcdef" 自定义语义检查 ----------------------- 宏对实参做的第一件事是检查实参是否是正确的形式。不是每种类型的错误输入都需要在这里捕获,但是应该捕获在宏求值期间可能导致崩溃的任何内容并创建一个很好的错误消息。 ``macros.expectKind`` 和 ``macros.expectLen`` 是一个好的开始。如果检查需要更加复杂,任意错误消息可以用 ``macros.error`` 过程创建。 .. code-block:: nim macro myAssert(arg: untyped): untyped = arg.expectKind nnkInfix 生成代码 --------------- 生成代码有两种方式。通过用含有多个 ``newTree`` 和 ``newLit`` 调用的表达式创建语法树,或者用 ``quote do:`` 表达式。 第一种为语法树生成提供最好的底层控制,第二种简短很多。如果你选择用 ``newTree`` 和 ``newLit`` 创建语法树, ``marcos.dumpAstGen`` 宏可以帮你很多。 ``quote do:`` 允许你直接写希望生成的代码,反引号用来插入来自 ``NimNode`` 符号的代码到生成的表达式中。 这表示你无法在 ``quote do:`` 使用反引号做除了注入符号之外的事情。确保只注入 ``NimNode`` 类型的符号到生成的语法树中。 你可以使用 ``newLit`` 把任意值转换成 ``NimNode`` 表达式树类型, 以便安全地注入到树中。 .. code-block:: nim :test: "nim c $1" import macros type MyType = object a: float b: string macro myMacro(arg: untyped): untyped = var mt: MyType = MyType(a:123.456, b:"abcdef") # ... let mtLit = newLit(mt) result = quote do: echo `arg` echo `mtLit` myMacro("Hallo") 调用``myMacro``将生成下面的代码: .. code-block:: nim echo "Hallo" echo MyType(a: 123.456'f64, b: "abcdef") 构建你的第一个宏 ------------------------- 为了给写宏一个开始,我们展示如何实现之前提到的 ``myDebug`` 宏。 首先要构建一个宏使用的示例,接着打印实参。这可以看出一个正确的实参是什么样子。 .. code-block:: nim :test: "nim c $1" import macros macro myAssert(arg: untyped): untyped = echo arg.treeRepr let a = 1 let b = 2 myAssert(a != b) .. code-block:: Infix Ident "!=" Ident "a" Ident "b" 从输出可以看出实参信息是一个中缀操作符(节点类型是"Infix"), 两个操作数在索引1和2的位置。用这个信息可以写真正的宏。 .. code-block:: nim :test: "nim c $1" import macros macro myAssert(arg: untyped): untyped = # 所有节点类型标识符用前缀 "nnk" arg.expectKind nnkInfix arg.expectLen 3 # 操作符作字符串字面值 let op = newLit(" " & arg[0].repr & " ") let lhs = arg[1] let rhs = arg[2] result = quote do: if not `arg`: raise newException(AssertionError,$`lhs` & `op` & $`rhs`) let a = 1 let b = 2 myAssert(a != b) myAssert(a == b) 这是即将生成的代码。 调试生成的宏可以在宏最后一行用 ``echo result.repr`` 语句。它也是用于获取此输出的语句。 .. code-block:: nim if not (a != b): raise newException(AssertionError, $a & " != " & $b) 能力与责任 ------------------------------- 宏非常强大。 宏可以改变表达式的语义,让不知道宏做什么的人难以理解。 可以使用模板或泛型实现的相同逻辑,最好不要使用宏。 当宏用于某种用途时,应当有一个优秀的文档。 说自己写的代码一目了然的人实现宏时,需要足够的文档。 限制 ----------- 因为宏由Nim虚拟机的编译器求值,它有Nim虚拟机的所有限制。 必须用纯Nim代码实现,宏可以在shell打开外部进程,不能调用除了编译器内置外的C函数。 更多示例 ============= 本教程讲解了宏系统的基础。对于宏能够做的事情,有些宏可以给你灵感。 Strformat --------- 在Nim标准库中, ``strformat`` 库提供了一个在编译时解析字符串字面值的宏。通常不建议像这样在宏中解析字符串。 解析的AST不能具有类型信息,并且在VM上实现的解析通常不是非常快。在AST节点上操作几乎总是推荐的方式。 但 ``strformat`` 仍然是宏实际应用的一个很好的例子,它比 ``assert`` 宏稍微复杂一些。 `Strformat <https://github.com/nim-lang/Nim/blob/5845716df8c96157a047c2bd6bcdd795a7a2b9b1/lib/pure/strformat.nim#L280>`_ 抽象语法树模式匹配(Ast Pattern Matching) -------------------- Ast Pattern Matching是一个宏库,可以帮助编写复杂的宏。这可以看作是如何使用新语义重新利用Nim语法树的一个很好的例子。 `Ast Pattern Matching <https://github.com/krux02/ast-pattern-matching>`_ OpenGL沙盒 -------------- 这个项目有一个完全用宏编写的Nim到GLSL编译器。它通过递归扫描所有使用的函数符号来编译它们,以便可以在GPU上执行交叉库函数。 `OpenGL Sandbox <https://github.com/krux02/opengl-sandbox>`_
b74de3f6e4f620bc6454d5750d38d6dabc510679
[ "Markdown", "C", "reStructuredText", "Shell" ]
11
Shell
nim-lang-cn/Nim
281adaff630fb8ad29fe3e98a3711fce8e8d27f7
9b1be59e11fb5bec47a28e89352b1d9621acae59
refs/heads/master
<file_sep>#include"FT.h" #include<iostream> using namespace std; //dgemm with FT /** * m: number of row of A (N-i-B) * n: number of row of B (B) * k: number of col of A / col of B (i) */ void dgemmFT( magma_trans_t transA, magma_trans_t transB, int m, int n, int k, double alpha, double * A, int lda, double * B, int ldb, double beta, double * C, int ldc, ABFTEnv * abftEnv, double * col_chkA, int col_chkA_ld, double * row_chkA, int row_chkA_ld, double * col_chkB, int col_chkB_ld, double * row_chkB, int row_chkB_ld, double * col_chkC, int col_chkC_ld, double * row_chkC, int row_chkC_ld, bool FT, bool DEBUG, bool CHECK_BEFORE, bool CHECK_AFTER, bool INJECT, magma_queue_t * stream) { // if (true) { // cout << "dgemm" << endl; // } int mem_row = 0; // number of row and col of B stored in memory(no trans operation) int mem_col = 0; if (FT && CHECK_BEFORE) { // number of row and col of A stored in memory(no trans operation) if (transA == MagmaNoTrans) { mem_row = m; mem_col = k; at_col_chk_recal(abftEnv, A, lda, mem_row, mem_col); cudaStreamSynchronize(stream[1]); cudaStreamSynchronize(stream[4]); // col_detect_correct(A, lda, abftEnv->chk_nb, mem_row, mem_col, // col_chkA, col_chkA_ld, // abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, // abftEnv->stream[1]); if (DEBUG) { cout<<"[DGEMM-BEFORE] matrix A:"<<endl; printMatrix_gpu(A, lda, mem_row, mem_col, 4, 4); cout<<"[DGEMM-BEFORE] recalculated column checksum of A:"<<endl; printMatrix_gpu(abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, (mem_row / abftEnv->chk_nb) * 2, mem_col, 2, 4); cout<<"[DGEMM-BEFORE] updated column checksum of A:"<<endl; printMatrix_gpu(col_chkA, col_chkA_ld, (mem_row / abftEnv->chk_nb) * 2, mem_col, 2, 4); } } else if (transA == MagmaTrans) { mem_row = k; mem_col = m; at_row_chk_recal(abftEnv, A, lda, mem_row, mem_col); cudaStreamSynchronize(stream[1]); cudaStreamSynchronize(stream[4]); // row_detect_correct(A, lda, abftEnv->chk_nb, mem_row, mem_col, // row_chkA, row_chkA_ld, // abftEnv->vrt_recal_chk, abftEnv->vrt_recal_chk_ld, // abftEnv->stream[1]); if (DEBUG) { cout<<"[DGEMM-BEFORE] matrix A:"<<endl; printMatrix_gpu(A, lda, mem_row, mem_col, 4, 4); cout<<"[DGEMM-BEFORE] recalculated row checksum of A:"<<endl; printMatrix_gpu(abftEnv->vrt_recal_chk, abftEnv->vrt_recal_chk_ld, mem_row , (mem_col / abftEnv->chk_nb) * 2, 4, 2); cout<<"[DGEMM-BEFORE] updated row checksum of A:"<<endl; printMatrix_gpu(row_chkA, row_chkA_ld, mem_row, (mem_col / abftEnv->chk_nb) * 2, 4, 2); } } //verify B before use if (transB == MagmaNoTrans) { mem_row = k; mem_col = n; at_row_chk_recal(abftEnv, B, ldb, mem_row, mem_col); cudaStreamSynchronize(stream[1]); cudaStreamSynchronize(stream[4]); // row_detect_correct(B, ldb, abftEnv->chk_nb, mem_row, mem_col, // row_chkB, row_chkB_ld, // abftEnv->vrt_recal_chk, abftEnv->vrt_recal_chk_ld, // abftEnv->stream[1]); if (DEBUG) { cout<<"[DGEMM-BEFORE] matrix B:"<<endl; printMatrix_gpu(B, ldb, mem_row, mem_col, 4, 4); cout<<"[DGEMM-BEFORE] recalculated row checksum of B:"<<endl; printMatrix_gpu(abftEnv->vrt_recal_chk, abftEnv->vrt_recal_chk_ld, mem_row, (mem_col / abftEnv->chk_nb) * 2, 4, 2); cout<<"[DGEMM-BEFORE] updated row checksum of B:"<<endl; printMatrix_gpu(row_chkB, row_chkB_ld, mem_row, (mem_col / abftEnv->chk_nb) * 2, 4, 2); } } else if (transB == MagmaTrans) { mem_row = n; mem_col = k; at_col_chk_recal(abftEnv, B, ldb, mem_row, mem_col); cudaStreamSynchronize(stream[1]); cudaStreamSynchronize(stream[4]); // col_detect_correct(B, ldb, abftEnv->chk_nb, mem_row, mem_col, // col_chkB, col_chkB_ld, // abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, // abftEnv->stream[1]); if (DEBUG) { cout<<"[DGEMM-BEFORE] matrix B:"<<endl; printMatrix_gpu(B, ldb, mem_row, mem_col, 4, 4); cout<<"[DGEMM-BEFORE] recalculated column checksum of B:"<<endl; printMatrix_gpu(abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, (mem_row / abftEnv->chk_nb) * 2, mem_col, 2, 4); cout<<"[DGEMM-BEFORE] updated column checksum of B:"<<endl; printMatrix_gpu(row_chkB, row_chkB_ld, (mem_row / abftEnv->chk_nb) * 2, mem_col, 2, 4); } } mem_row = m; mem_col = n; at_col_chk_recal(abftEnv, C, ldc, mem_row, mem_col); cudaStreamSynchronize(stream[1]); cudaStreamSynchronize(stream[4]); // col_detect_correct(C, ldc, abftEnv->chk_nb, mem_row, mem_col, // col_chkC, col_chkC_ld, // abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, // abftEnv->stream[1]); at_row_chk_recal(abftEnv, C, ldc, mem_row, mem_col); cudaStreamSynchronize(stream[1]); cudaStreamSynchronize(stream[4]); // row_detect_correct(C, ldc, abftEnv->chk_nb, mem_row, mem_col, // row_chkC, row_chkC_ld, // abftEnv->vrt_recal_chk, abftEnv->vrt_recal_chk_ld, // abftEnv->stream[1]); if (DEBUG) { cout<<"[DGEMM-BEFORE] matrix C:"<<endl; printMatrix_gpu(C, ldc, mem_row, mem_col, 4, 4); cout<<"[DGEMM-BEFORE] recalculated column checksum of C:"<<endl; printMatrix_gpu(abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, (mem_row / abftEnv->chk_nb) * 2, mem_col, 2, 4); cout<<"[DGEMM-BEFORE] updated column checksum of C:"<<endl; printMatrix_gpu(col_chkC, col_chkC_ld, (mem_row / abftEnv->chk_nb) * 2, mem_col, 2, 4); cout<<"[DGEMM-BEFORE] recalculated row checksum of C:"<<endl; printMatrix_gpu(abftEnv->vrt_recal_chk, abftEnv->vrt_recal_chk_ld, mem_row, (mem_col / abftEnv->chk_nb) * 2, 4, 2); cout<<"[DGEMM-BEFORE] updated row checksum of C:"<<endl; printMatrix_gpu(row_chkC, row_chkC_ld, mem_row, (mem_col / abftEnv->chk_nb) * 2, 4, 2); } } magmablasSetKernelStream(stream[1]); //[Cholesky] MagmaNoTrans, MagmaTrans, MAGMA_D_ONE * (-1), MAGMA_D_ONE magma_dgemm(transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc ); if (INJECT) { magma_dscal( 1, 10000000000, C, 1); } if(FT){ magmablasSetKernelStream(stream[4]); //magmablasSetKernelStream(stream[1]); if (transA == MagmaNoTrans) { magma_dgemm(transA, transB, (m / abftEnv->chk_nb) * 2, n, k, alpha, col_chkA, col_chkA_ld, B, ldb, beta, col_chkC, col_chkC_ld ); } else { magma_dgemm(transA, transB, (m / abftEnv->chk_nb) * 2, n, k, alpha, row_chkA, row_chkA_ld, B, ldb, beta, col_chkC, col_chkC_ld ); } if (transB == MagmaNoTrans) { //we can further work on this to support trans A. magma_dgemm(transA, transB, m , (n / abftEnv->chk_nb) * 2, k, alpha, A, lda, row_chkB, row_chkB_ld, beta, row_chkC, row_chkC_ld ); } else { //we can further work on this to support trans A. magma_dgemm(transA, transB, m , (n / abftEnv->chk_nb) * 2, k, alpha, A, lda, col_chkB, col_chkB_ld, beta, row_chkC, row_chkC_ld ); } } if (FT && CHECK_AFTER) { mem_row = m; mem_col = n; at_col_chk_recal(abftEnv, C, ldc, mem_row, mem_col); cudaStreamSynchronize(stream[1]); cudaStreamSynchronize(stream[4]); // col_detect_correct(C, ldc, abftEnv->chk_nb, mem_row, mem_col, // col_chkC, col_chkC_ld, // abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, // abftEnv->stream[1]); at_row_chk_recal(abftEnv, C, ldc, mem_row, mem_col); cudaStreamSynchronize(stream[1]); cudaStreamSynchronize(stream[4]); // row_detect_correct(C, ldc, abftEnv->chk_nb, mem_row, mem_col, // row_chkC, row_chkC_ld, // abftEnv->vrt_recal_chk, abftEnv->vrt_recal_chk_ld, // abftEnv->stream[1]); if (DEBUG) { cout<<"[DGEMM-AFTER] matrix C:"<<endl; printMatrix_gpu(C, ldc, mem_row, mem_col, 4, 4); cout<<"[DGEMM-AFTER] recalculated column checksum of C:"<<endl; printMatrix_gpu(abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, (mem_row / abftEnv->chk_nb) * 2, mem_col, 2, 4); cout<<"[DGEMM-AFTER] updated column checksum of C:"<<endl; printMatrix_gpu(col_chkC, col_chkC_ld, (mem_row / abftEnv->chk_nb) * 2, mem_col, 2, 4); cout<<"[DGEMM-AFTER] recalculated row checksum of C:"<<endl; printMatrix_gpu(abftEnv->vrt_recal_chk, abftEnv->vrt_recal_chk_ld, mem_row, (mem_col / abftEnv->chk_nb) * 2, 4, 2); cout<<"[DGEMM-AFTER] updated row checksum of C:"<<endl; printMatrix_gpu(row_chkC, row_chkC_ld, mem_row, (mem_col / abftEnv->chk_nb) * 2, 4, 2); } } }<file_sep>#include"FT.h" #include<iostream> using namespace std; //dsyrk with FT /** * n: number of row of A * m: number of col of A */ void dsyrkFT(magma_uplo_t uplo, magma_trans_t trans, int n, int m, double alpha, double * A, int lda, double beta, double * C, int ldc, ABFTEnv * abftEnv, double * col_chkA, int col_chkA_ld, double * col_chkC, int col_chkC_ld, bool FT, bool DEBUG, bool CHECK_BEFORE, bool CHECK_AFTER, magma_queue_t * stream){ /* m n * ****************** ********* * * A * =>* C * n * * * * * * ****************** ********* */ // // if (true) { // cout << "syrk" << endl; // } if (FT && CHECK_BEFORE) { //verify A before use //reclaculate checksums of A on GPU at_col_chk_recal(abftEnv, A, lda, n, m); cudaStreamSynchronize(stream[1]); cudaStreamSynchronize(stream[4]); //handle error // col_detect_correct(A, lda, // abftEnv->chk_nb, n, m, // col_chkA, col_chkA_ld, // abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, // stream[1]); if (DEBUG) { cudaStreamSynchronize(stream[1]); cout<<"[DSYRK-BEFORE]matrix A:"<<endl; printMatrix_gpu(abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, 2, m, -1, -1); cout<<"[DSYRK-BEFORE]updated checksum of A:"<<endl; printMatrix_gpu(col_chkA, col_chkA_ld, 2, m, -1, -1); } //verify C before use //reclaculate checksums of C on GPU at_col_chk_recal(abftEnv, C, ldc, n, n); cudaStreamSynchronize(stream[1]); cudaStreamSynchronize(stream[4]); //handle error // col_detect_correct(C, ldc, // abftEnv->chk_nb, n, m, // col_chkC, col_chkC_ld, // abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, // stream[1]); if (DEBUG) { cudaStreamSynchronize(stream[1]); cout<<"[DSYRK-BEFORE]matrix C:"<<endl; printMatrix_gpu(abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, 2, n, -1, -1); cout<<"[DSYRK-BEFORE]updated checksum of C:"<<endl; printMatrix_gpu(col_chkA, col_chkA_ld, 2, n, -1, -1); } } //if (FT) { magmablasSetKernelStream(stream[1]); // magma_dgemm( // MagmaNoTrans, MagmaTrans, // n, n, m, // MAGMA_D_ONE * (-1), // A, lda, A, lda, // MAGMA_D_ONE, // C, ldc ); // } else { magma_dsyrk(uplo, trans, n, m, alpha, A, lda, beta, C, ldc); // } if(FT){ //update checksums on GPU //magmablasSetKernelStream(stream[1]); magmablasSetKernelStream(stream[4]); magma_dgemm( MagmaNoTrans, MagmaTrans, 2, n, m, MAGMA_D_ONE * (-1), col_chkA, col_chkA_ld, A, lda, MAGMA_D_ONE, col_chkC, col_chkC_ld ); } if (FT && CHECK_AFTER) { //verify C after use //reclaculate checksums of C on GPU at_col_chk_recal(abftEnv, C, ldc, n, n); cudaStreamSynchronize(stream[1]); cudaStreamSynchronize(stream[4]); //handle error // col_detect_correct(C, ldc, // abftEnv->chk_nb, n, m, // col_chkC, col_chkC_ld, // abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, // stream[1]); if (DEBUG) { cudaStreamSynchronize(stream[1]); cout<<"[DSYRK-AFTER]matrix C:"<<endl; printMatrix_gpu(abftEnv->hrz_recal_chk, abftEnv->hrz_recal_chk_ld, 2, n, -1, -1); cout<<"[DSYRK-AFTER]updated checksum of C:"<<endl; printMatrix_gpu(col_chkC, col_chkC_ld, 2, n, -1, -1); } } }
b0e4a61ae76e34bb8a932060e1d3f73faf1fa86b
[ "C++" ]
2
C++
FTFFTW/FT-MAGMA
cd3d77ac873531ba6eef51ef5460e2c59a561657
450f1fa0dfa09490e186343463c318c9f1fb9191
refs/heads/main
<file_sep>#include <stdio.h> typedef struct student{ char name[20]; float marks; }student; int c=0; void writetofile(student std){ char l[0]; l[0]=c==0?'w':'a',c++; FILE *fptr; fptr=fopen("bruh.bin",l); fprintf(fptr, "\nname: %s", std.name); fprintf(fptr, "\tMarks: %f", std.marks); fclose(fptr); } void input(student std){ printf("\nEnter name: "); gets(std.name); printf("\nEnter mks: "); scanf("%f%*c", &std.marks); writetofile(std); } void print(){ FILE *fptr; fptr=fopen("bruh.bin", "r"); char c; c=fgetc(fptr); while(c != EOF){ printf("%c", c); c=fgetc(fptr); } fclose(fptr); } void main(){ student std[20]; int n; printf("\nEnter num of stds: "); scanf("%d%*c", &n); for(int i=0; i<n; i++){ input(std[i]); } print(); }
71cc522d70d3573426ccfa1eae0b4970b3acf246
[ "C" ]
1
C
chatiaro/pps
fc1d1f87823c27da67e4df8f4f6bc2112fb2c861
025fff0835cc9ac339ccccb4955d9b161a9b0082
refs/heads/master
<repo_name>mzgg/AkilliAsistan<file_sep>/src/com/mehmetzahit/bean/TopicContentBean.java package com.mehmetzahit.bean; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.bean.SessionScoped; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import org.hibernate.Query; import org.hibernate.Session; import com.mehmetzahit.dao.TopicContentDAO; import com.mehmetzahit.entities.TopicContent; import com.mehmetzahit.util.HibernateUtil; import javax.faces.application.FacesMessage; @ManagedBean @SessionScoped public class TopicContentBean implements Serializable { private static final long serialVersionUID = 1L; private int topicID; // parametre olarak değer geçirildi. private String topicName; // parametre olarak değer geçirildi. private int memberID; // parametre olarak değer geçirildi. // ----------------------------------------- private int contentID; private String contentTitle; private String content; private String keywords; private int rating; //------------------- private String secili; private String search; private String searchText; // ------------------------------ private List<TopicContent> contentList = new ArrayList<TopicContent>(); private List<TopicContent> topiccontent = new ArrayList<TopicContent>(); public List<TopicContent> getTopiccontent() { return topiccontent; } public void setTopiccontent(List<TopicContent> topiccontent) { this.topiccontent = topiccontent; } public String getSearch() { return search; } public void setSearch(String search) { this.search = search; } public int getTopicID() { return topicID; } public void setTopicID(int topicID) { this.topicID = topicID; } public String getTopicName() { return topicName; } public void setTopicName(String topicName) { this.topicName = topicName; } public int getMemberID() { return memberID; } public void setMemberID(int memberID) { this.memberID = memberID; } public int getContentID() { return contentID; } public void setContentID(int contentID) { this.contentID = contentID; } public String getContentTitle() { return contentTitle; } public void setContentTitle(String contentTitle) { this.contentTitle = contentTitle; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public int getRating() { return rating; } public void setRating(int rating) { this.rating = rating; } public List<TopicContent> getContentList() { return contentList; } public void setContentList(List<TopicContent> contentList) { this.contentList = contentList; } public String calis() { TopicContent topicContent = new TopicContent(); topicContent.setContentID(contentID); topicContent.setContentTitle(contentTitle); topicContent.setContent(content); topicContent.setKeywords(keywords); topicContent.setRating(rating); topicContent.setMemberID(memberID); topicContent.setTopicID(topicID); try { Session session = HibernateUtil.getSessionfactory().openSession(); session.beginTransaction(); session.save(topicContent); session.getTransaction().commit(); FacesContext context = FacesContext.getCurrentInstance(); context.addMessage(null, new FacesMessage("Tebrikler!", "Kategori Başarıyla Oluşturuldu")); return "TopicContent"; } catch (Exception e) { System.out.println("hata burda"); return "TopicContent"; } } public String content() { Session session = HibernateUtil.getSessionfactory().openSession(); Query query = session.createQuery("FROM TopicContent WHERE memberID=:parametre1 and topicID=:parametre2"); System.out.println("bak bahim"+ memberID +"bidaha bhabahim"+ getMemberID()); query.setParameter("parametre1",memberID); query.setParameter("parametre2",topicID); contentList.clear(); topiccontent = query.list(); for(TopicContent topic:topiccontent){ contentList.add(new TopicContent( topic.getContentID(), topic.getContentTitle(), topic.getContent(), topic.getKeywords(), topic.getRating(), topic.getMemberID(), topic.getTopicID() )); } return "TopicContent"; } public String SearchContent() { Session session = HibernateUtil.getSessionfactory().openSession(); Query query=session.createQuery("FROM TopicContent WHERE memberID=:parametre1 and topicID=:parametre2 and keywords like :parametre3"); System.out.println(search+"bilocan gelmişmi"); System.out.println("bak bahim"+ memberID +"bidaha bhabahim"+ getMemberID()); query.setParameter("parametre1",memberID); query.setParameter("parametre2",topicID); query.setParameter("parametre3",search+"%"); topiccontent = query.list(); contentList.clear(); for(TopicContent topic:topiccontent){ contentList.add(new TopicContent( topic.getContentID(), topic.getContentTitle(), topic.getContent(), topic.getKeywords(), topic.getRating(), topic.getMemberID(), topic.getTopicID() )); } return "TopicContent?faces-redirect=true"; } public List<String> search(){ Session session=HibernateUtil.getSessionfactory().openSession(); Query query=session.createQuery("FROM TopicContent WHERE memberID=:parametre1 and topicID=:parametre2 and keywords like :parametre3"); query.setParameter("parametre1",memberID); query.setParameter("parametre2",topicID); query.setParameter("parametre3",getSearch()+"%"); System.out.println(search); List<TopicContent> list=query.list(); List<String> results = new ArrayList<String>(); for(TopicContent top:list){ int i=0; while(i<top.getKeywords().split(",").length){ results.add(top.getKeywords().split(",")[i]); i++; } } return results; } public String getSecili() { return secili; } public void setSecili(String secili) { this.secili = secili; } public String getSearchText() { return searchText; } public void setSearchText(String searchText) { this.searchText = searchText; } } <file_sep>/src/com/mehmetzahit/entities/CreateTopic.java package com.mehmetzahit.entities; public class CreateTopic { private int topicID; private String topicName; private String topicType; private int memberID; public int getMemberID() { return memberID; } public void setMemberID(int memberID) { this.memberID = memberID; } public int getTopicID() { return topicID; } public void setTopicID(int topicID) { this.topicID = topicID; } public String getTopicName() { return topicName; } public void setTopicName(String topicName) { this.topicName = topicName; } public String getTopicType() { return topicType; } public void setTopicType(String topicType) { this.topicType = topicType; } } <file_sep>/src/com/mehmetzahit/dao/TopicCodeContentDAO.java package com.mehmetzahit.dao; import org.hibernate.Session; import com.mehmetzahit.entities.TopicCodeContent; import com.mehmetzahit.util.HibernateUtil; public class TopicCodeContentDAO { public static String SaveCode(String codeTitle, String codeContent, int contentID, int topicID, int memberID) { TopicCodeContent tcc = new TopicCodeContent(); tcc.setCodeTitle(codeTitle); tcc.setCodeContent(codeContent); tcc.setContentID(contentID); tcc.setTopicID(topicID); tcc.setMemberID(memberID); try { Session session = HibernateUtil.getSessionfactory().openSession(); session.beginTransaction(); session.save(tcc); session.getTransaction().commit(); } catch (Exception e) { System.out.println("Kayıt Ekleme hatası"); } System.out.println("1:" + contentID + "2:" + memberID + "3:" + topicID); return "TopicContent?faces-redirec=true"; } } <file_sep>/README.md # AkilliAsistan JSF+Hibernate+PrimeFaces ile Akilli Kisisel Asistan <file_sep>/src/com/mehmetzahit/bean/TopicCodeContentBean.java package com.mehmetzahit.bean; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import org.hibernate.Session; import com.mehmetzahit.dao.TopicCodeContentDAO; import com.mehmetzahit.entities.TopicCodeContent; import com.mehmetzahit.entities.TopicContent; import com.mehmetzahit.util.HibernateUtil; @ManagedBean @SessionScoped public class TopicCodeContentBean implements Serializable { private static final long serialVersionUID = 1L; private int contentID; //setPropertyActionListener ile değer atanması private int memberID; //setPropertyActionListener ile değer atanması private int topicID; //setPropertyActionListener ile değer atanması private int codeID; private String codeContent; private String codeTitle; public int getContentID() { return contentID; } public void setContentID(int contentID) { this.contentID = contentID; } public int getMemberID() { return memberID; } public void setMemberID(int memberID) { this.memberID = memberID; } public int getTopicID() { return topicID; } public void setTopicID(int topicID) { this.topicID = topicID; } public int getCodeID() { return codeID; } public void setCodeID(int codeID) { this.codeID = codeID; } public String getCodeContent() { return codeContent; } public void setCodeContent(String codeContent) { this.codeContent = codeContent; } public String getCodeTitle() { return codeTitle; } public void setCodeTitle(String codeTitle) { this.codeTitle = codeTitle; } public String addCode() { return TopicCodeContentDAO.SaveCode(codeTitle, codeContent, contentID, topicID, memberID); } } <file_sep>/src/com/mehmetzahit/bean/MembersBean.java package com.mehmetzahit.bean; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.servlet.http.HttpSession; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.mehmetzahit.dao.LoginDAO; import com.mehmetzahit.entities.Members; import com.mehmetzahit.entities.Topics; import com.mehmetzahit.util.HibernateUtil; @ManagedBean @SessionScoped public class MembersBean { private List<Members> memberList; private List<Topics> topics=new ArrayList<Topics>(); public List<Topics> getTopics() { return topics; } public void setTopics(List<Topics> topics) { this.topics = topics; } public List<Members> getMemberList() { return memberList; } public void setMemberList(List<Members> memberList) { this.memberList = memberList; } private String email; private String password; private int memberID; private ArrayList<String> asd = new ArrayList<String>(); private ArrayList<Integer> topicID = new ArrayList<Integer>(); private HashMap<Integer, String>ogrno=new HashMap<Integer,String>(); public HashMap<Integer, String> getOgrno() { return ogrno; } public void setOgrno(HashMap<Integer, String> ogrno) { this.ogrno = ogrno; } public ArrayList<Integer> getTopicID() { return topicID; } public void setTopicID(ArrayList<Integer> topicID) { this.topicID = topicID; } public int getMemberID() { return memberID; } public void setMemberID(int memberID) { this.memberID = memberID; } public ArrayList<String> getAsd() { return asd; } public void setAsd(ArrayList<String> asd) { this.asd = asd; } // ----------------------------------------------- public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String validateUsernamePassword() { boolean valid = LoginDAO.validate(getEmail(), getPassword()); if (valid) { HttpSession session = SessionBean.getSession(); session.setAttribute("username", getEmail()); bilgi(); callTopic(); return "admin?faces-redirect=true"; } else { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Incorrect Username and Passowrd", "Please enter correct username and Password")); return "login?faces-redirect=true"; } } public void bilgi() { SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory(); Session session = sessionfactory.openSession(); session.beginTransaction(); Query query = session.createQuery("from Members WHERE email=:parametre"); query.setParameter("parametre", getEmail()); memberList = query.list(); for (Members member : memberList) { setMemberID(member.getMemberID()); } } public void callTopic() { // Session session =HibernateUtil.getSessionfactory().openSession(); SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory(); Session session = sessionfactory.openSession(); session.beginTransaction(); Query query = session.createQuery("FROM Topics WHERE memberID=:parametre"); query.setParameter("parametre", getMemberID()); List<Topics> list = query.list(); for (Topics topik : list) { topics.add(new Topics(topik.getTopicID(),topik.getTopicName())); ogrno.put(53,"rize"); //ogrno.put(topik.getTopicID(),topics.getTopicName()); } System.out.println(ogrno.keySet()); } public String logout() { HttpSession session = SessionBean.getSession(); session.invalidate(); return "login?faces-redirect=true"; } } <file_sep>/src/com/mehmetzahit/bean/CreateTopicBean.java package com.mehmetzahit.bean; import java.io.Serializable; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import org.hibernate.Session; import com.mehmetzahit.entities.CreateTopic; import com.mehmetzahit.util.HibernateUtil; @ManagedBean @SessionScoped public class CreateTopicBean implements Serializable{ private static final long serialVersionUID = 1L; private int topicID; private String topicName; private String topicType; private int memberID; private String parametre; public String getParametre() { return parametre; } public void setParametre(String parametre) { this.parametre = parametre; } //--------------------------------------------------- public int getMemberID() { return memberID; } public void setMemberID(int memberID) { this.memberID = memberID; } public int getTopicID() { return topicID; } public void setTopicID(int topicID) { this.topicID = topicID; } public String getTopicName() { return topicName; } public void setTopicName(String topicName) { this.topicName = topicName; } public String getTopicType() { return topicType; } public void setTopicType(String topicType) { this.topicType = topicType; } public void saveDB(){ CreateTopic createtopic=new CreateTopic(); createtopic.setTopicName(topicName); createtopic.setMemberID(Integer.parseInt(parametre)); System.out.println(Integer.parseInt(parametre)+"bu parameter"); try { Session session=HibernateUtil.getSessionfactory().openSession(); session.beginTransaction(); session.save(createtopic); session.getTransaction().commit(); } catch (Exception e) { System.out.println("Hata var bah bahalým nedir"); } } } <file_sep>/src/com/mehmetzahit/dao/LoginDAO.java package com.mehmetzahit.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class LoginDAO { public static boolean validate(String user, String password) { SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory(); Session session = sessionfactory.openSession(); Query query = session.createQuery(" From Members where Email=:parametre and Password=:<PASSWORD>"); query.setParameter("parametre", user); query.setParameter("parametre2", password); List<?> list = query.list(); if (list.size() > 0) return true; else return false; } }
58296b8d776c7d6a7665fa3ca08267594ceefebe
[ "Markdown", "Java" ]
8
Java
mzgg/AkilliAsistan
6ffd40153ea59a349fe84f91625fa1bb0be9dc8f
beb421b0230fccaeb8e038341675a904d759d5cb
refs/heads/master
<repo_name>uxmoon/wp-quiz<file_sep>/inc/tweaks.php <?php // contact form 7 disable default CSS add_filter( 'wpcf7_load_css', '__return_false' ); // Preventing Duplicate Submissions from CF7 function is_already_submitted($formName, $fieldName, $fieldValue){ require_once(ABSPATH . 'wp-content/plugins/contact-form-7-to-database-extension/CFDBFormIterator.php'); $exp = new CFDBFormIterator(); $atts = array(); $atts['show'] = $fieldName; $atts['filter'] = "$fieldName=$fieldValue"; $exp->export($formName, $atts); $found = false; while ($row = $exp->nextRow()) { $found = true; } return $found; } function my_validate_email($result, $tag) { $formName = 'datos_premios'; // Name of the form containing this field $fieldName = 'user_email'; // Set to your form's unique field name $name = $tag['name']; if($name == $fieldName){ $valueToValidate = $_POST[$name]; if (is_already_submitted($formName, $fieldName, $valueToValidate)) { $result->invalidate($name, 'Este mail se encuentra participando.'); // error message } } return $result; } add_filter('wpcf7_validate_email*', 'my_validate_email', 10, 2); // disable emojis remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action( 'wp_print_styles', 'print_emoji_styles' ); remove_action( 'admin_print_styles', 'print_emoji_styles' ); // post and commetns // Disable comments globally - https://www.dfactory.eu/turn-off-disable-comments/ // - - - - - - - - - - - - - - - - - - - - - - - - - function df_disable_comments_post_types_support() { $post_types = get_post_types(); foreach ($post_types as $post_type) { if(post_type_supports($post_type, 'comments')) { remove_post_type_support($post_type, 'comments'); remove_post_type_support($post_type, 'trackbacks'); } } } add_action('admin_init', 'df_disable_comments_post_types_support'); // Close comments on the front-end // - - - - - - - - - - - - - - - - - - - - - - - - - function df_disable_comments_status() { return false; } add_filter('comments_open', 'df_disable_comments_status', 20, 2); add_filter('pings_open', 'df_disable_comments_status', 20, 2); // Hide existing comments // - - - - - - - - - - - - - - - - - - - - - - - - - function df_disable_comments_hide_existing_comments($comments) { $comments = array(); return $comments; } add_filter('comments_array', 'df_disable_comments_hide_existing_comments', 10, 2); // Redirect any user trying to access comments page // - - - - - - - - - - - - - - - - - - - - - - - - - function df_disable_comments_admin_menu_redirect() { global $pagenow; if ($pagenow === 'edit-comments.php') { wp_redirect(admin_url()); exit; } } add_action('admin_init', 'df_disable_comments_admin_menu_redirect'); // Remove comments metabox from dashboard // - - - - - - - - - - - - - - - - - - - - - - - - - function df_disable_comments_dashboard() { remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal'); } add_action('admin_init', 'df_disable_comments_dashboard'); // Remove comments links from admin bar // - - - - - - - - - - - - - - - - - - - - - - - - - function df_disable_comments_admin_bar() { if (is_admin_bar_showing()) { remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60); } } add_action('init', 'df_disable_comments_admin_bar'); // Remove sidebar links // - - - - - - - - - - - - - - - - - - - - - - - - - function remove_menus(){ // remove_menu_page( 'index.php' ); //Dashboard remove_menu_page( 'edit.php' ); //Posts remove_menu_page( 'upload.php' ); //Media // remove_menu_page( 'edit.php?post_type=page' ); //Pages remove_menu_page( 'edit-comments.php' ); //Comments // remove_menu_page( 'themes.php' ); //Appearance // remove_menu_page( 'plugins.php' ); //Plugins // remove_menu_page( 'users.php' ); //Users // remove_menu_page( 'tools.php' ); //Tools // remove_menu_page( 'options-general.php' ); //Settings } add_action( 'admin_menu', 'remove_menus' ); // remove junk from head remove_action('wp_head', 'rsd_link'); remove_action('wp_head', 'wp_generator'); //removes WP Version # for security remove_action('wp_head', 'feed_links', 2); remove_action('wp_head', 'index_rel_link'); remove_action('wp_head', 'wlwmanifest_link'); remove_action('wp_head', 'feed_links_extra', 3); remove_action('wp_head', 'start_post_rel_link', 10, 0); remove_action('wp_head', 'parent_post_rel_link', 10, 0); remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0); remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 ); remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 ); // remove wp version param from any enqueued scripts function vc_remove_wp_ver_css_js( $src ) { if ( strpos( $src, 'ver=' . get_bloginfo( 'version' ) ) ) $src = remove_query_arg( 'ver', $src ); return $src; } add_filter( 'style_loader_src', 'vc_remove_wp_ver_css_js', 9999 ); add_filter( 'script_loader_src', 'vc_remove_wp_ver_css_js', 9999 );<file_sep>/README.md Overview ======== A multiple step form to gather customer information and a multiple choice contest for local pharmaceutical companies. WordPress theme for a quiz contest ---------------------------------- - Theme created based on underscores starter theme [link](http://underscores.me/) - Styles created using postCSS [link](https://github.com/postcss/postcss) WordPress Plugins ----------------- - Akismet - Contact Form 7 - Contact Form 7 Multi-Step Forms - Contact Form DB<file_sep>/footer.php </div> <footer id="colophon" class="site-footer" role="contentinfo"> <ul class="site-logos"> <li> <img src="<?php echo get_stylesheet_directory_uri(); ?>/images/logos/zarator-atorvastatin.png" alt="Zarator Atorvastatin"> </li> <li> <img src="<?php echo get_stylesheet_directory_uri(); ?>/images/logos/anemidox-ferrum.png" alt="Anemidox Ferrum"> </li> <li> <img src="<?php echo get_stylesheet_directory_uri(); ?>/images/logos/principia-pregabalina.png" alt="Principia Pregabalina"> </li> <li> <img src="<?php echo get_stylesheet_directory_uri(); ?>/images/logos/cronopen-azitromicina.png" alt="Cronopen Azitromicina"> </li> <li> <img src="<?php echo get_stylesheet_directory_uri(); ?>/images/logos/femorel-ibandronato-sodico.png" alt="Femorel Ibandronato sódico"> </li> </ul> <div class="site-info"> <a href="<?php echo esc_url( home_url( '/' ) ); ?>bases-y-condiciones/" class="link-copy">Bases y Condiciones</a> <a href="http://www.elea.com/" class="link-elea"><span class="hide-text">ELEA. Hace bien.</span></a> </div> </footer> </div> <?php wp_footer(); ?> </body> </html> <file_sep>/js/app.js (function($) { $(function() { $('.wpcf7-form').on('keydown', '.vof_dni, .vof_pharmacy_phone', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13,110,190])||/65|67|86|88/.test(e.keyCode)&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()}); }); // skin input radio blue $( '.wpcf7-list-item.first input[type="radio"]' ).iCheck({ checkboxClass: 'icheckbox_flat-green', radioClass: 'iradio_flat-green' }); // skin input radio red $( '.wpcf7-list-item.last input[type="radio"]' ).iCheck({ checkboxClass: 'icheckbox_flat-red', radioClass: 'iradio_flat-red' }); })( jQuery );
47d643e13e7408c8c32fd6e3ca3addf97c884af8
[ "Markdown", "JavaScript", "PHP" ]
4
PHP
uxmoon/wp-quiz
d8947c4b356f23b3e3d7f5917d1b4cc04aefd08a
27055d300e66f7ea89744ea070b0441069ed79b5
refs/heads/master
<repo_name>aristides1000/Proyecto<file_sep>/vistas/404.php <?php header($_SERVER['SERVER_PROTOCOL'] . '404 Not Found', true, 404); include_once 'app/config.inc.php'; include_once 'app/Conexion.inc.php'; include_once 'app/RepositorioUsuario.inc.php'; include_once 'app/ValidadorLogin.inc.php'; include_once 'app/ControlSesion.inc.php'; include_once 'app/Redireccion.inc.php'; $título = 'Error 404'; /* establece la cabecera de nuestro código del index.php para que sea usado por todos */ include_once 'plantillas/documento-declaracion.inc.php'; /* el .inc es de include */ /* aquí enlazamos con la barra de navegación */ include_once 'plantillas/navbar.inc.php'; ?> <div class="container cuatro-cero-cuatro"> <div class="row"> <br> <div class="col-md-4"> <img src="img/404.gif" class="img-rounded img-responsive"> <br> </div> <div class="col-md-5"> <h1>Error 404</h1> <h3>La página que has intentado localizar no se encuentra en nuestro servidor</h3> <button class="btn btn-primary btn-sm"> <a href="<?php echo SERVIDOR; ?>" id="cuatro-cero-cuatro"> <p> <span class="glyphicon glyphicon-home" aria-hidden="true"></span> &nbsp Volver a la página principal &nbsp </p> </a> </button> </div> </div> </div> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <?php include_once 'plantillas/documento-cierre.inc.php'; ?><file_sep>/nbproject/project.properties file.reference.www-Proyecto=. files.encoding=UTF-8 site.root.folder=${file.reference.www-Proyecto} <file_sep>/plantillas/panel_control_declaracion.inc.php <div class="container"> <div class="row"> <div class="col-sm-3 col-md-2 sidebar"> <ul class="nav nav-sidebar"> <li> <a href="<?php echo RUTA_GESTOR_ENTRADAS; ?>"><i class="fas fa-door-open"></i> &nbsp;Entradas</a> <a href="<?php echo RUTA_GESTOR_COMENTARIOS; ?>"><span class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></span> &nbsp;Mi Carrito</a> <a href="<?php echo RUTA_GESTOR_FAVORITOS; ?>"><span class="glyphicon glyphicon-grain" aria-hidden="true"></span> &nbsp;Favoritos</a> </li> </ul> </div> <div class="col-sm-9 col-md-10 main"><file_sep>/plantillas/form_entrada_recuperada_validada.inc.php <input type="hidden" id="id-entrada" name="id-entrada" value="<?php echo $id_entrada; ?>"> <div class="form-group"> <label for="titulo">Título</label> <input type="text" class="form-control" id="titulo" name="titulo" placeholder="Colócale el título" value="<?php echo $validador -> obtener_titulo(); ?>"> <input type="hidden" id="titulo-original" name="titulo-original" value="<?php echo $entrada_recuperada -> obtener_titulo(); ?>"> <?php $validador -> mostrar_error_titulo(); ?> </div> <div class="form-group"> <label for="url">URL</label> <input type="text" class="form-control" id="url" name="url" placeholder="Dirección única sin espacios para la entrada" value="<?php echo $validador -> obtener_url(); ?>"> <input type="hidden" id="url-original" name="url-original" value="<?php echo $entrada_recuperada -> obtener_url(); ?>"> <?php $validador -> mostrar_error_url(); ?> </div> <div class="form-group"> <label for="contenido">Contenido</label> <textarea class="form-control" rows="4" id="texto" name="texto" placeholder="Escribe Aquí tu artículo"><?php echo $validador -> obtener_texto(); ?></textarea> <input type="hidden" id="texto-original" name="texto-original" value="<?php echo $entrada_recuperada -> obtener_texto(); ?>"> <?php $validador -> mostrar_error_texto(); ?> </div> <div class="checkbox"> <label> <input type="checkbox" name="publicar" value="si" <?php if ($validador -> obtener_checkbox()) echo 'checked'; ?>>Deseas publicarlo de inmediato <input type="hidden" id="publicar-original" name="publicar-original" value="<?php echo $entrada_recuperada -> esta_activa(); ?>"> </label> </div> <br> <div class="text-right"> <button class="btn btn-default" type="submit" id="btn" name="guardar_cambios_entrada" >Guardar Cambios</button> </div><file_sep>/vistas/buscar.php <?php include_once 'app/EscritorEntradas.inc.php'; $busqueda = null; $resultados = null; //$resultados_multiples = null; $buscar_titulo = false; $buscar_contenido = false; $buscar_tags = false; $buscar_autor = false; if (isset($_POST['buscar']) && isset($_POST['termino-buscar']) && !empty($_POST['termino-buscar'])) { $busqueda = $_POST['termino-buscar']; //esto se debe validar correctamente //$resultados_multiples = false; Conexion::abrir_conexion(); $resultados = RepositorioEntrada::buscar_entradas_todos_los_campos(Conexion::obtener_conexion(), $busqueda); Conexion::cerrar_conexion(); } if (isset($_POST['busqueda-avanzada']) && isset($_POST['campos'])) { if (in_array("titulo", $_POST['campos'])) { $buscar_titulo = true; } if (in_array("contenido", $_POST['campos'])) { $buscar_contenido = true; } if (in_array("tags", $_POST['campos'])) { $buscar_tags = true; } if (in_array("autor", $_POST['campos'])) { $buscar_autor = true; } if ($_POST['fecha'] == "recientes") { $orden = "DESC"; } if ($_POST['fecha'] == "antiguas") { $orden = "ASC"; } if (isset($_POST['termino-buscar']) && !empty($_POST['termino-buscar'])) { $busqueda = $_POST['termino-buscar']; //esto se debe validar correctamente //$resultados_multiples = true; Conexion :: abrir_conexion(); if ($buscar_titulo) { $entradas_por_titulo = RepositorioEntrada :: buscar_entradas_por_titulo(Conexion::obtener_conexion(), $busqueda, $orden); } if ($buscar_contenido) { $entradas_por_contenido = RepositorioEntrada :: buscar_entradas_por_contenido(Conexion::obtener_conexion(), $busqueda, $orden); } if ($buscar_tags) { //añadir tagas cuando existan } if ($buscar_autor) { $entradas_por_autor = RepositorioEntrada :: buscar_entradas_por_autor(Conexion::obtener_conexion(), $busqueda, $orden); } } } $titulo = "Buscar en el Sistema"; include_once 'plantillas/documento-declaracion.inc.php'; include_once 'plantillas/navbar.inc.php'; ?> <div class="container-fluid"> <div class="row"> <div class="jumbotron"> <h1 class="text-center">Buscar en SupplyHome</h1> <br> <div class="row"> <div class="col-md-2"> </div> <div class="col-md-8 text-center"> <form role="form" method="post" action="<?php echo RUTA_BUSCAR; ?>"> <div class="form-group"> <input type="search" name="termino-buscar" class="form-control" placeholder="¿Qué buscas?" required <?php echo "value='" . $busqueda . "'" ?>> </div> <button type="submit" name="buscar" class="btn btn-primary btn-sm"> <p> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> &nbsp Buscar </p> </button> </form> </div> </div> </div> </div> </div> <!--Esta parte me da error--> <!--<div class="container"> <div class="row"> <div class="panel-group"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" href="#avanzada">Busqueda Avanzada</a> </h4> </div> <div id="avanzada" class="collapse panel-collapse"> <div class="panel-body"> <form role="form" method="post" action="<?php echo RUTA_BUSCAR; ?>"> <div class="form-group"> <input type="search" name="termino-buscar" class="form-control" placeholder="¿Qué buscas?" required <?php echo "value='" . $busqueda . "'" ?>> </div> <p>buscar en los siguientes campos:</p> <label class="checkbox-inline"> <input type="checkbox" value="titulo" name="campos[]" <?php if (isset($_POST['busqueda-avanzada'])) { if ($buscar_titulo) { echo "checked"; } } else { echo "checked"; } ?> >Título </label> <label class="checkbox-inline"> <input type="checkbox" value="contenido" name="campos[]" <?php if (isset($_POST['busqueda-avanzada'])) { if ($buscar_contenido) { echo "checked"; } } else { echo "checked"; } ?> >Contenido </label> <label class="checkbox-inline"> <input type="checkbox" value="tags" name="campos[]" <?php if (isset($_POST['busqueda-avanzada'])) { if ($buscar_tags) { echo "checked"; } } else { echo "checked"; } ?> >Tags </label> <label class="checkbox-inline"> <input type="checkbox" value="autor" name="campos[]" <?php if (isset($_POST['busqueda-avanzada'])) { if ($buscar_autor) { echo "checked"; } } ?> >Autor </label> <hr> <p>Ordenar por:</p> <label class="radio-inline"> <input type="radio" name="fecha" value="recientes" <?php if (isset($_POST['busqueda-avanzada']) && isset($orden) && $orden == 'DESC') { echo "checked"; } if (!isset($_POST['busqueda_avanzada'])) { echo "checked"; } ?> >Entradas más recientes </label> <label class="radio-inline"> <input type="radio" name="fecha" value="antiguas" <?php if (isset($_POST['busqueda-avanzada']) && isset($orden) && $orden == 'ASC') { echo "checked"; } ?> >Entradas más Antiguas </label> <hr> <button type="submit" name="busqueda-avanzada" class="btn btn-primary btn-sm"> <p> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> &nbsp Busqueda Avanzada </p> </button> </form> </div> </div> </div> </div> </div> </div>--> <div class="container" id="resultados"> <div class="row"> <div class="col-md-12"> <div class="page-header"> <h1> Resultados <?php if (isset($_POST['buscar']) && count($resultados)) { echo " "; ?> <small><?php echo count($resultados); ?></small> <?php } //COMPROBAR RESULTADOS EN BUSQUEDA MÚLTIPLE ?> </h1> </div> </div> </div> <?php if (isset($_POST['buscar'])) { if (count($resultados)) { EscritorEntradas::mostrar_entradas_busqueda($resultados); } else { ?> <h3>sin coincidencias</h3> <br> <?php } } else if (isset($_POST['busqueda_avanzada'])) { if (count($entradas_por_titulo) || count($entradas_por_contenido) || count($entradas_por_autor)) { $parametros = count($_POST['campos']); $ancho_columnas = 12 / $parametros; ?> <div class="row"> <?php for ($i = 0; $i < $parametros; $i++) { ?> <div class="<?php echo 'col-md-' . $ancho_columnas; ?> text-center"></div> <h4><?php echo 'Coincidencias en ' . $_POST['campos'][$i]; ?></h4> <br> <?php switch ($_POST['campos'][$i]) { case "titulo": EscritorEntradas::mostrar_entradas_busqueda_multiple($entradas_por_titulo); break; case "contenido": EscritorEntradas::mostrar_entradas_busqueda_multiple($entradas_por_contenido); break; case "tags": break; case "autor": EscritorEntradas::mostrar_entradas_busqueda_multiple($entradas_por_autor); break; } ?> </div> <?php } ?> </div> <?php } else { ?> <h3>Sin coincidencias</h3> <br> <?php } } ?> </div> <?php include_once 'plantillas/documento-cierre.inc.php'; ?><file_sep>/scripts/generar-url-secreta.php <?php include_once 'app/config.inc.php'; include_once 'app/Conexion.inc.php'; include_once 'app/Usuario.inc.php'; include_once 'app/RecuperacionClave.inc.php'; include_once 'app/RepositorioUsuario.inc.php'; include_once 'app/RepositorioRecuperacionClave.inc.php'; include_once 'app/Redireccion.inc.php'; function sa($longitud) { $caracteres = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $numero_caracteres = strlen($caracteres); $string_aleatorio = ''; for ($i = 0; $i < $longitud; $i++) { $string_aleatorio .= $caracteres[rand(0, $numero_caracteres - 1)]; } return $string_aleatorio; } if (isset($_POST['enviar_email'])) { $email = $_POST['email']; Conexion::abrir_conexion(); if (!RepositorioUsuario :: email_existe(Conexion :: obtener_conexion(), $email)) { return; } $usuario = RepositorioUsuario :: obtener_usuario_por_email(Conexion :: obtener_conexion(), $email); $nombre_usuario = $usuario -> obtener_nombre(); $string_aleatorio = sa(10); $url_secreta = hash('sha256', $string_aleatorio . $nombre_usuario); //va a generar una cadena de 64 caractéres $peticion_generada = RepositorioRecuperacionClave :: generar_peticion(Conexion :: obtener_conexion(), $usuario -> obtener_id(), $url_secreta); Conexion :: cerrar_conexion(); //si la petición es correcta, notificar instrucciones if ($peticion_generada) { Redireccion :: redirigir(SERVIDOR); } } //si la petición ha fallado, notificar error ?><file_sep>/scripts/script-relleno.php <?php include_once 'app/config.inc.php'; include_once 'app/Conexion.inc.php'; include_once 'app/Usuario.inc.php'; include_once 'app/Entrada.inc.php'; include_once 'app/Comentario.inc.php'; include_once 'app/RepositorioUsuario.inc.php'; include_once 'app/RepositorioEntrada.inc.php'; include_once 'app/RepositorioComentario.inc.php'; Conexion::abrir_conexion(); for ($usuarios = 0; $usuarios < 100; $usuarios++){ $nombre = sa(10); $email = sa(5).'@'.sa(3); $password = password_hash('<PASSWORD>', PASSWORD_DEFAULT); $usuario = new Usuario('', $nombre, $email, $password, '', ''); RepositorioUsuario::insertar_usuario(Conexion::obtener_conexion(), $usuario); } for ($entradas = 0; $entradas < 100; $entradas++){ $titulo = sa(10); $url = $titulo; $texto = lorem(); $autor = rand(1, 100); $entrada = new Entrada('', $autor, $url, $titulo, $texto, '', ''); RepositorioEntrada::insertar_entrada(Conexion::obtener_conexion(), $entrada); } for ($comentarios = 0; $comentarios < 100; $comentarios++){ $titulo = sa(10); $texto = lorem(); $autor = rand(1, 100); $entrada =rand(1, 100); $comentario = new Comentario('', $autor, $entrada, $titulo, $texto, ''); RepositorioComentario::insertar_comentario(Conexion::obtener_conexion(), $comentario); } function sa($longitud) { $caracteres = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $numero_caracteres = strlen($caracteres); $string_aleatorio = ''; for ($i = 0; $i < $longitud; $i++) { $string_aleatorio .= $caracteres[rand(0, $numero_caracteres - 1)]; } return $string_aleatorio; } function lorem(){ $lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vel lacus accumsan, gravida lorem ac, volutpat turpis. Vestibulum fermentum tincidunt nisl quis cursus. Morbi in dolor eu erat luctus porttitor in vitae velit. Etiam quis ante cursus, fringilla sapien efficitur, accumsan ex. Duis imperdiet elementum nisi, eget tristique nibh dignissim vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In molestie tristique fringilla. Nunc pellentesque leo sapien, et faucibus mauris interdum sed. Cras posuere ut justo sed bibendum. Vivamus id urna eu diam mattis finibus. Ut id pharetra orci, in tincidunt risus. Pellentesque et volutpat turpis. Nulla commodo odio ultricies, dignissim enim eget, sollicitudin felis. Donec in vulputate ex, nec varius dui. Fusce posuere nisi a posuere porta. Proin quam magna, lobortis vel molestie id, fringilla sit amet odio. Etiam pellentesque justo tincidunt sem rutrum ultricies. Praesent dolor lectus, feugiat eu metus varius, suscipit placerat augue. Nullam fringilla vel nisi eget fermentum. Aenean posuere lorem non dolor feugiat, sit amet aliquet elit vestibulum. Mauris quis velit eget nunc pretium tincidunt. Curabitur quis tincidunt massa. Maecenas in mollis mi. Nullam vitae arcu elementum augue posuere tincidunt at cursus orci. Nulla nec ex sed dolor mollis placerat sit amet ac diam. Nulla id orci elit. Pellentesque semper pulvinar tortor, quis sollicitudin velit elementum id. Aenean feugiat enim lorem, non commodo enim porttitor eu. Sed tortor metus, faucibus eu varius at, facilisis non justo. Curabitur mollis dapibus sem, non pulvinar ligula accumsan eu. Etiam fringilla vel lorem at ullamcorper. Mauris malesuada, enim a ornare gravida, sapien tellus rutrum nisi, eu luctus quam lacus ut erat. Aliquam vitae nulla est. Integer ut varius orci. Cras a nulla sed lacus varius volutpat ut nec enim. Cras a accumsan dolor. Ut condimentum, ex et tempor convallis, nunc magna luctus dolor, at semper nisl nibh pretium massa. Donec mollis dictum felis, sodales tincidunt ligula ultrices id. Donec eu quam accumsan velit venenatis lacinia. Duis sed nibh pharetra elit congue euismod. Sed euismod pharetra tincidunt. Donec et pulvinar urna, ut semper leo. Donec mi tellus, pulvinar ut porttitor iaculis, vestibulum at arcu. Etiam rutrum lacinia urna ac sagittis. Sed semper dui in blandit hendrerit. Proin vitae augue non massa tempor vehicula sed non leo. Vivamus tempor ipsum a semper convallis. Vivamus dignissim lobortis pulvinar. Aliquam sit amet eleifend nunc. Aliquam erat volutpat. Donec iaculis ligula at quam tempor mollis. Nulla eu aliquet lorem. Ut rhoncus mollis magna, et pulvinar est lacinia eu. Nullam ut risus eu tortor efficitur porta. Fusce tempor bibendum nulla, sed lacinia augue dapibus nec. Nullam pulvinar orci est, vel sodales risus feugiat sed. Donec massa libero, elementum non interdum in, condimentum ut velit. Ut fermentum mauris nec nisl sodales rutrum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque non condimentum purus. Fusce pulvinar odio quis erat mattis, quis eleifend ex tincidunt. Maecenas volutpat consectetur ornare. Cras interdum congue commodo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam consectetur urna quis porta vehicula. Etiam iaculis porttitor dui quis mattis. Duis eros tortor, ullamcorper non ante ut, sollicitudin consequat nulla. Donec eget volutpat mauris. Integer nunc velit, mattis at imperdiet at, tincidunt ac quam. Curabitur ut aliquet lorem.'; return $lorem; } ?> <file_sep>/plantillas/navbar.inc.php <?php include_once 'app/ControlSesion.inc.php'; include_once 'app/config.inc.php'; Conexion :: abrir_conexion(); $total_usuarios = RepositorioUsuario :: obtener_numero_usuarios(Conexion::obtener_conexion()); ?> <nav class="navbar navbar-default navbar-static-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Este botón despliega la barra de Navegación</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?php echo SERVIDOR ?>"> &nbsp SupplyHome </a> </div> <div id="navbar" class="navbar-collapse collapse"> <?php // if (!ControlSesion::sesion_iniciada()){ ?> <ul class="nav navbar-nav"> <li><a href="<?php echo RUTA_NOSOTROS ?>"><i class="fas fa-building"></i> &nbsp;Nosotros</a></li> <li><a href="<?php echo RUTA_PRODUCTOS ?>"><span class="glyphicon glyphicon-apple" aria-hidden="true"></span> &nbsp;Nuestros Productos</a></li> <li><a href="<?php echo RUTA_AUTORES ?>"><span class="glyphicon glyphicon-grain" aria-hidden="true"></span> &nbsp;Provedores</a></li> </ul> <?php // } ?> <!--Barra de sesión--> <ul class="nav navbar-nav navbar-right"> <?php if (ControlSesion::sesion_iniciada()) { ?> <li> <a href="<?php echo RUTA_PERFIL; ?>"> <span class="glyphicon glyphicon-user" aria-hidden="true"></span> &nbsp; <?php echo ' ' . $_SESSION['nombre_usuario']; ?> </a> </li> <li> <a href="<?php echo RUTA_GESTOR; ?>"> <span class="glyphicon glyphicon-dashboard" aria-hidden="true"></span> &nbsp; Gestor de Compra </a> </li> <li> <a href="<?php echo RUTA_LOGOUT; ?>"> <span class="glyphicon glyphicon-log-out" aria-hidden="true"></span> &nbsp; Cerrar Sesión </a> </li> <?php } else { ?> <li> <a href="#"> <span class="glyphicon glyphicon-user" aria-hidden="true"></span> &nbsp; <?php echo $total_usuarios; ?> </a> </li> <li> <a href="<?php echo RUTA_LOGIN ?>"><span class="glyphicon glyphicon-log-in" aria-hidden="true"></span> &nbsp; Iniciar sesión </a> </li> <li> <a href="<?php echo RUTA_REGISTRO ?>"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> &nbsp; Registro </a> </li> <?php } ?> </ul> </div> </div> </nav><file_sep>/app/RepositorioComentario.inc.php <?php include_once 'app/config.inc.php'; include_once 'app/Conexion.inc.php'; include_once 'app/Comentario.inc.php'; class RepositorioComentario { public static function insertar_comentario($conexion, $comentario) { $comentario_insertado = false; if (isset($conexion)) { try { $sql = "INSERT INTO comentarios(autor_id, entrada_id, titulo, texto, fecha) VALUES(:autor_id, :entrada_id, :titulo, :texto, NOW())"; /* Esta sección de código da error por la Actualización de PHP 7 */ /* $sentencia = $conexion->prepare($sql); $sentencia->bindParam(':autor_id', $comentario -> obtener_autor_id(), PDO::PARAM_STR); $sentencia->bindParam(':entrada_id', $comentario -> obtener_entrada_id(), PDO::PARAM_STR); $sentencia->bindParam(':titulo', $comentario -> obtener_titulo(), PDO::PARAM_STR); $sentencia->bindParam(':texto', $comentario -> obtener_texto(), PDO::PARAM_STR); */ /* inicio versión de código que pasa variables en lugar de funciones que evita errores en PHP */ $autor_idtemp = $comentario->obtener_autor_id(); $entrada_idtemp = $comentario->obtener_entrada_id(); $titulotemp = $comentario->obtener_titulo(); $textotemp = $comentario->obtener_texto(); $sentencia = $conexion->prepare($sql); $sentencia->bindParam(':autor_id', $autor_idtemp, PDO::PARAM_STR); $sentencia->bindParam(':entrada_id', $entrada_idtemp, PDO::PARAM_STR); $sentencia->bindParam(':titulo', $titulotemp, PDO::PARAM_STR); $sentencia->bindParam(':texto', $textotemp, PDO::PARAM_STR); /* fin de código de la nueva versión */ $comentario_insertado = $sentencia->execute(); } catch (PDOException $ex) { print 'ERROR' . $ex->getMessage(); } } return $comentario_insertado; } public static function obtener_comentarios($conexion, $entrada_id) { $comentarios = array(); if (isset($conexion)) { try { include_once 'Comentario.inc.php'; $sql = "SELECT * FROM comentarios WHERE entrada_id = :entrada_id"; /* Esta sección de código da error por la Actualización de PHP 7 */ $sentencia = $conexion -> prepare($sql); $sentencia -> bindParam(':entrada_id', $entrada_id, PDO::PARAM_STR); /* inicio versión de código que pasa variables en lugar de funciones que evita errores en PHP */ /* $entrada_idtemp = $comentario->obtener_entrada_id(); $sentencia = $conexion->prepare($sql); $sentencia->bindParam(':entrada_id', $entrada_idtemp, PDO::PARAM_STR); */ /* fin de código de la nueva versión */ $sentencia->execute(); $resultado = $sentencia -> fetchAll(); if (count($resultado)) { foreach ($resultado as $fila) { $comentarios[] = new Comentario($fila['id'], $fila['autor_id'], $fila['entrada_id'], $fila['titulo'], $fila['texto'], $fila['fecha']); } } } catch (PDOException $ex) { print "ERROR" . $ex -> getMessage(); } } return $comentarios; } public static function contar_comentarios_usuario($conexion, $id_usuario) { $total_comentarios = '0'; if (isset($conexion)) { try { $sql = "SELECT COUNT(*) as total_comentarios FROM comentarios WHERE autor_id = :autor_id"; /* Pendiente que aquí comienza el error */ /* Esta sección de código da error por la Actualización de PHP 7 */ $sentencia = $conexion->prepare($sql); $sentencia->bindParam(':autor_id', $id_usuario, PDO::PARAM_STR); $sentencia->execute(); $resultado = $sentencia->fetch(); if (!empty($resultado)) { $total_comentarios = $resultado['total_comentarios']; } } catch (PDOException $ex) { print 'ERROR ' . $ex->getMessage(); } } return $total_comentarios; } } ?><file_sep>/vistas/home.php <?php include_once 'app/Conexion.inc.php'; include_once 'app/RepositorioUsuario.inc.php'; include_once 'app/EscritorEntradas.inc.php'; $titulo = 'SupplyHome'; /* establece la cabecera de nuestro código del index.php para que sea usado por todos */ include_once 'plantillas/documento-declaracion.inc.php'; /* el .inc es de include */ /* aquí enlazamos con la barra de navegación */ include_once 'plantillas/navbar.inc.php'; ?> <div class="container-fluid"> <div class="jumbotron"> <h1>Bienvenido a SupplyHome</h1> <p> Disfruta la experiencia de comprar en nuestros supermercados</p> </div> </div> <div class="container-fluid"> <div class="row"> <div class="col-md-4"> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <p> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> &nbsp Búsqueda </p> </div> <div class="panel-body text-center"> <form role="form" method="post" action="<?php echo RUTA_BUSCAR; ?>"> <div class="form-group"> <input type="search" name="termino-buscar" class="form-control" placeholder="¿Qué buscas?" required> </div> <button type="submit" name="buscar" class="btn btn-primary btn-sm"> <p> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> &nbsp Buscar </p> </button> </form> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <p> <span class="glyphicon glyphicon-filter" aria-hidden="true"></span> &nbsp Filtros </p> </div> <div class="panel-body"></div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <p> <span class="glyphicon glyphicon-calendar" aria-hidden="true"></span> &nbsp Archivo </p> </div> <div class="panel-body"></div> </div> </div> </div> </div> <div class="col-md-8"> <?php EscritorEntradas::escribir_entradas(); ?> </div> </div> </div> <?php include_once 'plantillas/documento-cierre.inc.php'; ?><file_sep>/app/config.inc.php <?php //info de la base de datos define('NOMBRE_SERVIDOR', 'localhost'); define('NOMBRE_USUARIO', 'root'); define('PASSWORD', ''); define('NOMBRE_BD', 'blog'); //rutas de la web //importante incluir las nuevas rutas aquí, esto incluye las nuevas de carrito de compra //ESTAS SON LAS RUTAS DE MI PÁGINA //PARA ACTIVARLAS EN LOS VINCULOS DEBO ESCRIBIR "href="<?php echo RUTA_ENTRADAS(aqui va el cierre de la etiqueta de llamado a php)"" define("SERVIDOR", "http://localhost/Proyecto");/*mi ruta a la carpeta proyecto, tengo que estar muy pilas con esto al momento de montar mi carpeta en otra compu OJO OJO OJO OJO OJO OJO OJO sobre todo con el puerto de localhost que por defecto es 80, eso me va generar un error si no estoy pilas OJO*/ define("RUTA_REGISTRO", SERVIDOR."/registro"); define("RUTA_REGISTRO_CORRECTO", SERVIDOR."/registro-correcto"); define("RUTA_LOGIN", SERVIDOR."/login"); define("RUTA_LOGOUT", SERVIDOR."/logout"); define("RUTA_ENTRADA", SERVIDOR."/entrada"); define("RUTA_GESTOR", SERVIDOR."/gestor"); define("RUTA_GESTOR_ENTRADAS", RUTA_GESTOR."/entradas"); define("RUTA_GESTOR_COMENTARIOS", RUTA_GESTOR."/comentarios"); define("RUTA_GESTOR_FAVORITOS", RUTA_GESTOR."/favoritos"); define("RUTA_NUEVA_ENTRADA", SERVIDOR."/nueva-entrada"); define("RUTA_BORRAR_ENTRADA", SERVIDOR."/borrar-entrada"); define("RUTA_EDITAR_ENTRADA", SERVIDOR."/editar-entrada"); define("RUTA_RECUPERAR_CLAVE", SERVIDOR."/recuperar-clave"); define("RUTA_GENERAR_URL_SECRETA", SERVIDOR."/generar-url-secreta"); define("RUTA_PRUEBA_MAIL", SERVIDOR."/mail"); define("RUTA_RECUPERACION_CLAVE", SERVIDOR."/recuperacion-clave"); define("RUTA_BUSCAR", SERVIDOR."/buscar"); define("RUTA_PERFIL", SERVIDOR."/perfil"); define("RUTA_NOSOTROS", SERVIDOR."/nosotros"); define("RUTA_PRODUCTOS", SERVIDOR."/productos"); define("RUTA_AUTORES", SERVIDOR."/#"); //recursos define("RUTA_CSS", SERVIDOR . "/css/"); define("RUTA_JS", SERVIDOR . "/js/"); define("DIRECTORIO_RAIZ", realpath(__DIR__."/..")); ?><file_sep>/app/ValidadorRegistro.inc.php <?php include_once 'RepositorioUsuario.inc.php'; class ValidadorRegistro { private $aviso_inicio; private $aviso_cierre; private $nombre; private $email; private $clave; private $error_nombre; private $error_email; private $error_clave1; private $error_clave2; public function __construct($nombre, $email, $clave1, $clave2, $conexion) { $this->aviso_inicio = "<br><div class='alert alert-danger' role='alert'>"; $this->aviso_cierre = "</div>"; $this->nombre = ""; $this->email = ""; $this->clave = ""; $this->error_nombre = $this->validar_nombre($conexion, $nombre); $this->error_email = $this->validar_email($conexion, $email); $this->error_clave1 = $this->validar_clave1($clave1); $this->error_clave2 = $this->validar_clave2($clave1, $clave2); if ($this->error_clave1 === "" && $this->error_clave2 === "") { $this->clave = $clave1; } } private function variable_iniciada($variable) { if (isset($variable) && !empty($variable)) { return true; } else { return false; } } private function validar_nombre($conexion, $nombre) { if (!$this->variable_iniciada($nombre)) { return "Debes escribir un nombre de usuario."; } else { $this->nombre = $nombre; } if (strlen($nombre) < 6) { return "El nombre debe ser más largo de 6 caracteres."; } if (strlen($nombre) > 24) { return "El nombre no debe ser más largo de 24 caracteres."; } if (RepositorioUsuario :: nombre_existe($conexion, $nombre)) { return "Este nombre de usuario ya está en uso, por favor, prueba otro nombre."; } return ""; } private function validar_email($conexion, $email) { if (!$this->variable_iniciada($email)) { return "Debes escribir un email."; } else { $this->email = $email; } if (RepositorioUsuario :: email_existe($conexion, $email)) { return "Este email ya está en uso, por favor, pruebe otro email o <a href='#'>Intente recuperar su contraseña</a>"; } return ""; } private function validar_clave1($clave1) { if (!$this->variable_iniciada($clave1)) { return "Debes escribir una contraseña."; } return ""; } private function validar_clave2($clave1, $clave2) { if (!$this->variable_iniciada($clave1)) { return "Primero debes rellenar la contraseña"; } if (!$this->variable_iniciada($clave2)) { return "Debes confirmar tu contraseña."; } if ($clave1 !== $clave2) { return "Las contraseñas no coinciden, vuelve a escribirlas con detenimiento."; } return ""; } public function obtener_nombre() { return $this->nombre; } public function obtener_email() { return $this->email; } public function obtener_clave() { return $this->clave; } public function obtener_error_nombre() { return $this->error_nombre; } public function obtener_error_email() { return $this->error_email; } public function obtener_error_clave1() { return $this->error_clave1; } public function obtener_error_clave2() { return $this->error_clave2; } public function mostrar_nombre() { if ($this->nombre !== "") { echo 'value"' . $this->nombre . '"'; } } public function mostrar_error_nombre() { if ($this->error_nombre !== "") { echo $this->aviso_inicio . $this->error_nombre . $this->aviso_cierre; } } public function mostrar_email() { if ($this->email !== "") { echo 'value"' . $this->email . '"'; } } public function mostrar_error_email() { if ($this->error_email !== "") { echo $this->aviso_inicio . $this->error_email . $this->aviso_cierre; } } public function mostrar_error_clave1() { if ($this->error_clave1 !== "") { echo $this->aviso_inicio . $this->error_clave1 . $this->aviso_cierre; } } public function mostrar_error_clave2() { if ($this->error_clave2 !== "") { echo $this->aviso_inicio . $this->error_clave2 . $this->aviso_cierre; } } public function registro_valido() { if ($this->error_nombre === "" && $this->error_email === "" && $this->error_clave1 === "" && $this->error_clave2 === "") { return true; } else { return false; } } } ?><file_sep>/vistas/productos.php <?php include_once 'app/config.inc.php'; include_once 'app/Conexion.inc.php'; include_once 'app/RepositorioUsuario.inc.php'; include_once 'app/ValidadorLogin.inc.php'; include_once 'app/ControlSesion.inc.php'; include_once 'app/Redireccion.inc.php'; $título = 'Nosotros'; include_once 'plantillas/documento-declaracion.inc.php'; include_once 'plantillas/navbar.inc.php'; ?> <div class="container"> <div class="row"> <?php // Conexion::abrir_conexion(); // $re=mysql_query("SELECT * FROM productos")or die(mysql_error()); // while ($f=mysql_fetch_array($re)) { ?> <div class="col-md-4"> <center> <img src="../producto/cebolla.jpg" class="img-responsive img-rounded"><br> <span>Cebolla</span><br> <a href="#">ver</a> </center> </div> <div class="col-md-4"> <center> <img src="../producto/detergente.jpg" class="img-responsive img-rounded" width="150px"><br> <span>detergente</span><br> <a href="#">ver</a> </center> </div> <?php // Conexion::cerrar_conexion(); // } ?> </div> </div> <?php include_once 'plantillas/documento-cierre.inc.php'; ?><file_sep>/plantillas/entradas_al_azar.inc.php <?php include_once 'app/EscritorEntradas.inc.php'; ?> <div class="row"> <div class="col-md-12"> <hr> <h3>Otras entradas interesantes</h3> </div> <?php for ($i = 0; $i < count($entradas_azar); $i++) { $entrada_actual = $entradas_azar[$i]; ?> <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-heading"> <?php echo $entrada_actual->obtener_titulo(); ?> </div> <div class="panel-body"> <p> <?php echo EscritorEntradas::resumir_texto(nl2br($entrada_actual->obtener_texto())); ?> </p> </div> </div> </div> <?php } ?> <div class="col-md-12"> <hr> </div> </div><file_sep>/index.php <?php include_once 'app/config.inc.php'; include_once 'app/Conexion.inc.php'; include_once 'app/Usuario.inc.php'; include_once 'app/Entrada.inc.php'; include_once 'app/Comentario.inc.php'; include_once 'app/RepositorioUsuario.inc.php'; include_once 'app/RepositorioEntrada.inc.php'; include_once 'app/RepositorioComentario.inc.php'; $componentes_url = parse_url($_SERVER['REQUEST_URI']); $ruta = $componentes_url['path']; $partes_ruta = explode('/', $ruta); $partes_ruta = array_filter($partes_ruta); $partes_ruta = array_slice($partes_ruta, 0); $ruta_elegida = 'vistas/404.php'; if ($partes_ruta[0] == 'Proyecto') { /*Estar pendiente con el archivo 'app/config.inc.php' estar pendiente para no equivocarnos con la conexion y el puerto de los servidores virtuales, en el caso de mi casa el puerto del localhost es 8080*/ if(count($partes_ruta) == 1) { $ruta_elegida = 'vistas/home.php'; }else if (count($partes_ruta) == 2) { switch ($partes_ruta[1]) { /*Aquí van las urls con 2 divisores o separadores osea, estos '/' si no entiendes lo que digo ve el video de urls amigables de java dev one*/ case 'login': $ruta_elegida = 'vistas/login.php'; break; case 'logout': $ruta_elegida = 'vistas/logout.php'; break; case 'registro': $ruta_elegida = 'vistas/registro.php'; break; case 'gestor': $ruta_elegida = 'vistas/gestor.php'; $gestor_actual = ''; break; case 'relleno-dev': $ruta_elegida = 'scripts/script-relleno.php'; break; case 'nueva-entrada': $ruta_elegida = 'vistas/nueva-entrada.php'; break; case 'borrar-entrada': $ruta_elegida = 'scripts/borrar-entrada.php'; break; case 'editar-entrada': $ruta_elegida = 'vistas/editar-entrada.php'; break; case 'recuperar-clave': $ruta_elegida = 'vistas/recuperar-clave.php'; break; case 'generar-url-secreta': $ruta_elegida = 'scripts/generar-url-secreta.php'; break; case 'mail': $ruta_elegida = 'vistas/prueba-mail.php'; break; case 'buscar': $ruta_elegida = 'vistas/buscar.php'; break; case 'perfil': $ruta_elegida = 'vistas/perfil.php'; break; case 'nosotros': $ruta_elegida = 'vistas/nosotros.php'; break; case 'productos': $ruta_elegida = 'vistas/productos.php'; break; } }else if (count($partes_ruta) == 3) { /*Aquí van las urls con 3 divisores o separadores osea, estos '/' si no entiendes lo que digo ve el video de urls amigables de java dev one*/ if ($partes_ruta[1] == 'registro-correcto') { $nombre = $partes_ruta[2]; $ruta_elegida = 'vistas/registro-correcto.php'; } if ($partes_ruta[1] == 'entrada') { $url = $partes_ruta[2]; Conexion::abrir_conexion(); $entrada = RepositorioEntrada :: obtener_entrada_por_url(Conexion::obtener_conexion(), $url); if ($entrada != null){ $autor = RepositorioUsuario::obtener_usuario_por_id(Conexion::obtener_conexion(), $entrada -> obtener_autor_id()); $comentarios = RepositorioComentario::obtener_comentarios(Conexion::obtener_conexion(), $entrada -> obtener_id()); $entradas_azar = RepositorioEntrada::obtener_entradas_al_azar(Conexion::obtener_conexion(), 3); $ruta_elegida = 'vistas/entrada.php'; } } if ($partes_ruta[1] == 'gestor') { switch ($partes_ruta[2]) { case 'entradas': $gestor_actual = 'entradas'; $ruta_elegida = 'vistas/gestor.php'; break; case 'comentarios': $gestor_actual = 'comentarios'; $ruta_elegida = 'vistas/gestor.php'; break; case 'favoritos': $gestor_actual = 'favoritos'; $ruta_elegida = 'vistas/gestor.php'; break; } } if ($partes_ruta[1] == 'recuperacion-clave'){ $url_personal = $partes_ruta[2]; $ruta_elegida = 'vistas/recuperacion-clave.php'; } } } include_once $ruta_elegida; /* if ($partes_ruta[2] == 'registro') { include_once 'vistas/registro.php';*//*todas las demás páginas llevan el pámetro $partes_ruta[2], si no comprendes ve el video de java dev one número 38 de url amigables*//* } else if ($partes_ruta[2] == 'login') { include_once 'vistas/login.php'; } else if ($partes_ruta[1] == 'Proyecto') { include_once 'vistas/home.php';/*dejar el home siempre de último escribir las demás páginas siempre arriba de home que es nuestro nuevo index que es nuestra página principal*//* } else { echo '404'; } */ ?><file_sep>/vistas/recuperar-clave.php <?php $título = 'Recuperación de Contraseña'; /* establece la cabecera de nuestro código del index.php para que sea usado por todos */ include_once 'plantillas/documento-declaracion.inc.php'; /* el .inc es de include */ /* aquí enlazamos con la barra de navegación */ include_once 'plantillas/navbar.inc.php'; ?> <div class="container"> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading text-center"> <p> <span class="glyphicon glyphicon-user" aria-hidden="true"></span> &nbsp Recuperación de Contraseña </p> </div> <div class="panel-body"> <form role="form" method="post" action="<?php echo RUTA_GENERAR_URL_SECRETA; ?>"> <h2>Introduce tu email</h2> <br> <p> Escribe la dirección de correo electrónico con la que te registraste y te enviaremos un email con el que podras restablecer tu contraseña. </p> <br> <label for="email" class="sr-only">Email</label> <input type="email" class="form-control" name="email" id="email" placeholder="Email" required autofocus> <br> <button class="btn btn-lg btn-primary btn-block" type="submit" name="enviar_email"> <p> <span class="glyphicon glyphicon-send" aria-hidden="true"></span> &nbsp Enviar </p> </button> </form> </div> </div> </div> </div> </div> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <?php include_once 'plantillas/documento-cierre.inc.php'; ?> <file_sep>/plantillas/form_nueva_entrada_validado.inc.php <div class="form-group"> <label for="titulo">Título</label> <input type="text" class="form-control" id="titulo" name="titulo" placeholder="Colócale el título" <?php $validador -> mostrar_titulo(); ?> > <?php $validador -> mostrar_error_titulo(); ?> </div> <div class="form-group"> <label for="url">URL</label> <input type="text" class="form-control" id="url" name="url" placeholder="Dirección única sin espacios para la entrada" <?php $validador -> mostrar_url(); ?> > <?php $validador -> mostrar_error_url(); ?> </div> <div class="form-group"> <label for="contenido">Contenido</label> <textarea class="form-control" rows="4" id="contenido" name="texto" placeholder="Escribe Aquí tu artículo" ><?php $validador -> mostrar_texto(); ?></textarea> <?php $validador -> mostrar_error_texto(); ?> </div> <div class="checkbox"> <label> <input type="checkbox" name="publicar" value="si" <?php if ($entrada_publica) echo 'checked'; ?> >Deseas publicarlo de inmediato</label> </div> <br> <div class="text-right"> <button class="btn btn-default" type="submit" id="btn" name="guardar" >Guardar Entrada</button> </div><file_sep>/app/Validador.inc.php <?php abstract class Validador { protected $aviso_inicio; protected $aviso_cierre; protected $titulo; protected $url; protected $texto; protected $error_titulo; protected $error_url; protected $error_texto; function __construct() { } protected function variable_iniciada($variable) { if (isset($variable) && !empty($variable)) { return true; } else { return false; } } protected function validar_titulo($conexion, $titulo) { if (!$this->variable_iniciada($titulo)) { return "Debes escribir un título"; } else { $this->titulo = $titulo; } if (strlen($titulo) > 255) { return "El título no puede ser mayor a 255 caracteres"; } if (RepositorioEntrada :: titulo_existe($conexion, $titulo)) { return "Ya existe una entrada con ese título, por favor escoge uno diferente."; } } protected function validar_url($conexion, $url) { if (!$this->variable_iniciada($url)) { return "Debes insertar una url"; } else { $this->url = $url; } $url_tratada = str_replace(' ', '', $url); $url_tratada = preg_replace('/\s+/', '', $url_tratada); if (strlen($url) != strlen($url_tratada)) { return "La URL no puede contener espaciados"; } if (RepositorioEntrada :: url_existe($conexion, $url)) { return "Ya existe otro articulo con la misma URL, elige una diferente."; } } protected function validar_texto($conexion, $texto) { if (!$this->variable_iniciada($texto)) { return "El texto no puede estar vacío"; } else { $this->texto = $texto; } } public function obtener_titulo() { return $this->titulo; } public function obtener_url() { return $this->url; } public function obtener_texto() { return $this->texto; } public function mostrar_titulo() { if($this -> titulo != ""){ echo 'value = "' . $this -> titulo . '"'; } } public function mostrar_url() { if($this -> url != ""){ echo 'value = "' . $this -> url . '"'; } } public function mostrar_texto() { if ($this -> texto != "" && strlen(trim($this -> texto)) > 0) { echo $this -> texto; } } public function mostrar_error_titulo() { if ($this -> error_titulo != "") { echo $this -> aviso_inicio . $this -> error_titulo . $this -> aviso_cierre; } } public function mostrar_error_url() { if ($this -> error_url != "") { echo $this -> aviso_inicio . $this -> error_url . $this -> aviso_cierre; } } public function mostrar_error_texto() { if ($this -> error_texto != "") { echo $this -> aviso_inicio . $this -> error_texto . $this -> aviso_cierre; } } public function entrada_valida() { if ($this -> error_titulo == "" && $this -> error_url == "" && $this -> error_texto == ""){ return true; } else { return false; } } } ?> <file_sep>/app/ValidadorEntrada.inc.php <?php include_once 'RepositorioEntrada.inc.php'; include_once 'Validador.inc.php'; class ValidadorEntrada extends Validador { public function __construct($titulo, $url, $texto, $conexion) { $this->aviso_inicio = "<br><div class='alert alert-danger' role='alert'>"; $this->aviso_cierre = "</div>"; $this->titulo = ""; $this->url = ""; $this->texto = ""; $this->error_titulo = $this->validar_titulo($conexion, $titulo); $this->error_url = $this->validar_url($conexion, $url); $this->error_texto = $this->validar_texto($conexion, $texto); } } ?><file_sep>/sql/blog.sql CREATE DATABASE blog DEFAULT CHARACTER SET utf8; USE blog; CREATE TABLE usuarios ( id INT NOT NULL UNIQUE AUTO_INCREMENT, nombre VARCHAR(25) NOT NULL UNIQUE, email VARCHAR(255) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, fecha_registro DATETIME NOT NULL, activo TINYINT NOT NULL, PRIMARY KEY(id) ); CREATE TABLE entradas ( id INT NOT NULL UNIQUE AUTO_INCREMENT, autor_id INT NOT NULL, url VARCHAR(255) NOT NULL UNIQUE, titulo VARCHAR(255) NOT NULL UNIQUE, texto TEXT CHARACTER SET utf8 NOT NULL, fecha DATETIME NOT NULL, activa TINYINT NOT NULL, PRIMARY KEY(id), FOREIGN KEY(autor_id) REFERENCES usuarios(id) ON UPDATE CASCADE ON DELETE RESTRICT ); CREATE TABLE comentarios ( id INT NOT NULL UNIQUE AUTO_INCREMENT, autor_id INT NOT NULL, entrada_id INT NOT NULL, titulo VARCHAR(255) NOT NULL, texto TEXT CHARACTER SET utf8 NOT NULL, fecha DATETIME NOT NULL, PRIMARY KEY(id), FOREIGN KEY(autor_id) REFERENCES usuarios(id) ON UPDATE CASCADE ON DELETE RESTRICT, FOREIGN KEY(entrada_id) REFERENCES entradas(id) ON UPDATE CASCADE ON DELETE RESTRICT ); CREATE TABLE recuperacion_clave ( id INT NOT NULL UNIQUE AUTO_INCREMENT, usuario_id INT NOT NULL, url_secreta VARCHAR(255) NOT NULL, fecha DATETIME NOT NULL, PRIMARY KEY(id), FOREIGN KEY(usuario_id) REFERENCES usuarios(id) ON UPDATE CASCADE ON DELETE RESTRICT );<file_sep>/vistas/registro.php <?php include_once 'app/config.inc.php'; include_once 'app/Conexion.inc.php'; include_once 'app/Usuario.inc.php'; include_once 'app/RepositorioUsuario.inc.php'; include_once 'app/ValidadorRegistro.inc.php'; include_once 'app/Redireccion.inc.php'; if (isset($_POST['enviar'])) { Conexion :: abrir_conexion(); $validador = new ValidadorRegistro($_POST['nombre'], $_POST['email'], $_POST['clave1'], $_POST['clave2'], Conexion :: obtener_conexion()); if ($validador->registro_valido()) { $usuario = new Usuario('', $validador->obtener_nombre(), $validador->obtener_email(), password_hash($validador->obtener_clave(), PASSWORD_DEFAULT), '', ''); $usuario_insertado = RepositorioUsuario :: insertar_usuario(Conexion :: obtener_conexion(), $usuario); if ($usuario_insertado) { Redireccion::redirigir(RUTA_REGISTRO_CORRECTO . '/' . $usuario->obtener_nombre()); } } Conexion :: cerrar_conexion(); } $titulo = 'Registro'; /* establece la cabecera de nuestro código del index.php para que sea usado por todos */ include_once 'plantillas/documento-declaracion.inc.php'; /* el .inc es de include */ /* aquí enlazamos con la barra de navegación */ include_once 'plantillas/navbar.inc.php'; ?> <div class="container-fluid"> <div class="jumbotron"> <h1 class="text-center">Formulario de Registro</h1> </div> </div> <div class="container-fluid"> <div class="row"> <div class="col-md-6 text-center"> <div class="panel panel-deafult"> <div class="panel-heading"> <p> <span class="glyphicon glyphicon-apple" aria-hidden="true"></span> &nbsp Instrucciones </p> </div> <div class="panel-body"> <br> <p class="text-justify"> Para unirte, hacer compras y darnos tu experiencia en nuestros supermercados llena el siguiente formulario, recuerda que tu email te ayudará a gestionar tu cuenta de usuario </p> <br> <a href="#">¿Ya tienes cuenta?</a> <br> <a href="#">¿Olvidaste tu contrañesa?</a> <br> <br> </div> </div> </div> <div class="col-md-6 text-center"> <div class="panel panel-deafult"> <div class="panel-heading"> <p> <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> &nbsp Introduce tus datos </p> </div> <div class="panel-body"> <form role="form" method="post" action="<?php echo RUTA_REGISTRO ?>"> <?php if (isset($_POST['enviar'])) { include_once 'plantillas/registro_validado.inc.php'; } else { include_once 'plantillas/registro_vacio.inc.php'; } ?> </form> </div> </div> </div> </div> </div> <?php include_once 'plantillas/documento-cierre.inc.php'; ?><file_sep>/plantillas/registro_validado.inc.php <div class="form-group"> <label>Nombre de Usuario</label> <input type="text" class="form-control" name="nombre" placeholder="Escribe aquí tu nombre" <?php $validador -> mostrar_nombre() ?>> <?php $validador -> mostrar_error_nombre(); ?> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" name="email" placeholder="Escribe aquí tu email" <?php $validador -> mostrar_email() ?>> <?php $validador -> mostrar_error_email(); ?> </div> <div class="form-group"> <label>Contraseña</label> <input type="<PASSWORD>" class="form-control" name="clave1" placeholder="Escribe aquí tu Contraseña"> <?php $validador -> mostrar_error_clave1(); ?> </div> <div class="form-group"> <label>Confirma tu Contraseña</label> <input type="<PASSWORD>" class="form-control" name="clave2" placeholder="<PASSWORD>"> <?php $validador -> mostrar_error_clave2(); ?> </div> <button type="submit" class="btn btn-primary btn-lg" name="enviar"> <p> <span class="glyphicon glyphicon-send" aria-hidden="true"></span> &nbsp Enviar mis datos </p> </button><file_sep>/plantillas/documento-cierre.inc.php <?php Conexion :: cerrar_conexion(); ?> <script src="<?php echo RUTA_JS ?>jquery.min.js"></script> <script src="<?php echo RUTA_JS ?>bootstrap.min.js"></script> <script src="<?php echo RUTA_JS ?>all.js"></script> </body> </html><file_sep>/vistas/entrada.php <?php include_once 'app/config.inc.php'; include_once 'app/Conexion.inc.php'; include_once 'app/Usuario.inc.php'; include_once 'app/Entrada.inc.php'; include_once 'app/Comentario.inc.php'; include_once 'app/RepositorioUsuario.inc.php'; include_once 'app/RepositorioEntrada.inc.php'; include_once 'app/RepositorioComentario.inc.php'; $titulo = $entrada->obtener_titulo(); /* establece la cabecera de nuestro código del index.php para que sea usado por todos */ include_once 'plantillas/documento-declaracion.inc.php'; /* el .inc es de include */ /* aquí enlazamos con la barra de navegación */ include_once 'plantillas/navbar.inc.php'; ?> <div class="container contenido-articulo"> <div class="row"> <div class="col-md-12"> <h1> <?php echo $entrada->obtener_titulo(); ?> </h1> </div> </div> <br> <div class="row"> <div class="col-md-12"> <p> Por <a href="#"> <span class="glyphicon glyphicon-user" aria-hidden="true"></span> &nbsp <?php echo $autor -> obtener_nombre(); ?> </a> el &nbsp <span class="glyphicon glyphicon-calendar" aria-hidden="true"></span> &nbsp <?php echo $entrada -> obtener_fecha(); ?> </p> </div> </div> <br> <div class="row"> <div class="col-md-12"> <article class="text-justify"> <?php echo nl2br($entrada -> obtener_texto()); ?> </article> </div> </div> <?php include_once 'plantillas/entradas_al_azar.inc.php'; ?> <br> <?php if (count($comentarios) > 0) { include_once 'plantillas/comentarios_entrada.inc.php'; } else { echo '<p>¡Todavía no hay comentarios!</p>'; } ?> </div> <?php include_once 'plantillas/documento-cierre.inc.php'; ?><file_sep>/vistas/nosotros.php <?php include_once 'app/config.inc.php'; include_once 'app/Conexion.inc.php'; include_once 'app/RepositorioUsuario.inc.php'; include_once 'app/ValidadorLogin.inc.php'; include_once 'app/ControlSesion.inc.php'; include_once 'app/Redireccion.inc.php'; $título = 'Nosotros'; include_once 'plantillas/documento-declaracion.inc.php'; include_once 'plantillas/navbar.inc.php'; ?> <div class="container cuatro-cero-cuatro"> <div class="row"> <br> <div class="col-md-4"> <img src="img/nosotros.jpg" class="img-rounded img-responsive"> <br> </div> <div class="col-md-5"> <h1>Una empresa con mucha historia</h1> </div> </div> <div class="row"> <div class="col-md-12"> <p>Somos una cadena de supermercados especializados en darle lo mejor a nuestros clientes, siempre comprometidos con un mañana mejor</p> <h3>Misión</h3> <p>Brindar permanentemente calidad en la atención y el servicio para satisfacer las necesidades y requerimientos de nuestros clientes a través de la mejora continua en cada uno de nuestros procesos, con base en un espíritu noble de responsabilidad social.</p> <h3>Visión</h3> <p>Ser la cadena de Supermercados líder a nivel nacional, en servicio al cliente, variedad de productos, precios accesibles y proyección comunitaria.</p> <h3>Nuestros Valores</h3> <ul> <li>Responsabilidad</li> <li>Honestidad</li> <li>Integridad</li> <li>Confianza</li> <li>Aprendizaje</li> <li>Respeto y Tolerancia</li> <li>Disciplina</li> </ul> </div> </div> </div> <?php include_once 'plantillas/documento-cierre.inc.php'; ?>
4aa17cbff48c5f4e1d109a63da368c4726f657df
[ "SQL", "PHP", "INI" ]
25
PHP
aristides1000/Proyecto
00cdb93527caa4461bd3826e1ec58c4badce4719
647a2cf52a68ae66f38d7d5559967442eaab92dd
refs/heads/master
<file_sep> <?php include ("header.php") ?> <?php include ("index2.php"); ?> <table border ="1"> <?php for ($i = 0; $i <= 3; $i++) { ?> <tr> <?php for ($j = 1; $j <= 4; $j++) { ?> <td> <?php echo $spectacle[$i][$j]; ?> </td > <?php } ?> </tr> <?php } ?> <?php include ("footer.php") ?><file_sep><?php /*heure*/ $spectacle[0][1]='heure'; /*titre spectacle*/ $spectacle[0][2]='titre spectacle'; /*Artiste*/ $spectacle[0][3]='Artiste'; /*PICTURE*/ $spectacle[0][4]='PICTURE'; /*heure*/ $spectacle[1][1]='18h'; /*titre spectacle*/ $spectacle[1][2]='Le lac des cygnes'; /*Artiste*/ $spectacle[1][3]='Le cygne'; /*PICTURE*/ $spectacle[1][4]='<img width=90px src="https://upload.wikimedia.org/wikipedia/fr/7/71/Quebec_citadelles_200x200.png">'; /*heure*/ $spectacle[2][1]='15h'; /*titre spectacle*/ $spectacle[2][2]='Asterix le gaulois'; /*Artiste*/ $spectacle[2][3]='Asterix'; /*PICTURE*/ $spectacle[2][4]='<img width=90px src="https://upload.wikimedia.org/wikipedia/fr/7/71/Quebec_citadelles_200x200.png">'; /*heure*/ $spectacle[3][1]='19h'; /*titre spectacle*/ $spectacle[3][2]='Popeye'; /*Artiste*/ $spectacle[3][3]='Popeye'; /*PICTURE*/ $spectacle[3][4]='<img width=90px src="https://upload.wikimedia.org/wikipedia/fr/7/71/Quebec_citadelles_200x200.png">'; ?>
a5b7c3fc79e38bb6bb3391b0e94b57dc19c205bb
[ "PHP" ]
2
PHP
Ludovicmoreau/php
933ef487cc1ecf73746b30d78450869e8e0be3cd
16daed9993aba7e7f1660706e3a22cb2e9dc59ba
refs/heads/master
<repo_name>mtanjung/sample-code<file_sep>/js/rest api/app/services/anagramService.js class anagramService { constructor(log, mongoose, errs) { this.log = log; this.mongoose = mongoose; this.errs = errs; } async getAnagrams(word, limit) { const Dictionary = this.mongoose.model('Dictionary'); const wordLength = word.length; const useLimit = !!(limit); limit = parseInt(limit); const words = await Dictionary.find( { word: { $nin: [word] }, $where: `this.word.length == ${wordLength}` }, { word: 1, _id: 0 }, ); if (words.length === 0) { this.log.info(`Anagram(s) not found for '${word}'`); return []; } // Loop words returned from db and find anagram const matches = []; let matchesCounter = 0; for (const i in words) { // console.log(words[i].word); const target = words[i].word; const isAnagram = this.isAnagram(word, target); if (isAnagram) { matches.push(target); matchesCounter++; if (useLimit && matchesCounter >= limit) { break; } } } this.log.info(`Anagram(s) found for '${word}' => '${matches}'`); return matches; } /* * Compare source and target string to see if they are anagrams */ isAnagram(source, target) { if (source.length !== target.length) { return false; } const sourceCharCount = this.arrayCountValues(source); const targetCharCount = this.arrayCountValues(target); for (let i = 0; i < source.length; i++) { if (sourceCharCount[source[i]] !== targetCharCount[source[i]]) { return false; } } return true; } /* * Missed php function array_count_values :( * Count the number of occurrences of every character in a string. * e.g given 'words', return [ w: 1, o: 1, r: 1, s: 1, d: 1 ] */ arrayCountValues(word) { const counts = []; for (let i = 0; i < word.length; i++) { const key = word[i]; counts[key] = (counts[key]) ? counts[key] + 1 : 1; } return counts; } } module.exports = anagramService; <file_sep>/php/Animals/src/Animal.php <?php namespace MTCodeAssignment\src; /** * This class generates animal object with several functionality * * @author <NAME> */ class Animal { /** * Name of the animal * * @var string|null */ private $name = null; /** * Age of the animal * * @var integer|null */ private $age = null; /** * Favorite food of the animal * * @var string|null */ private $favoriteFood = null; /** * Store an array of animal names * * @var array */ private $names = []; /** * Speak counter * * @var integer */ private $speakCounter = 0; /** * Stores the average length of names * * @var integer */ private $averageNameLength = 0; /** * Constructor * * @param string $name */ public function __construct($name = '') { // Set inital age to a random number between 5 and 10 $this->age = rand(5, 10); // If $name provided, update several properties if ($name !== '') { $this->name = $name; // Push name to names array $this->names[] = $name; // Update the average name length $this->averageNameLength = strlen($name); } } /** * Get name of the animal * * @return string */ public function getName() { return $this->name; } /** * Get age of the animal * * @return integer */ public function getAge() { return $this->age; } /** * Get favorite food of the animal * * @return string */ public function getFavoriteFood() { return $this->favoriteFood; } /** * Get Names array for the animal * * @return array */ public function getNames() { return $this->names; } /** * Get average name length for the animal * * @return integer */ public function getAverageNameLength() { return $this->averageNameLength; } /** * Set name of the animal, also push the new name into $names and * calculate the average name length of the animal, so when we are pulling the value * we don't have to calculate it, just simple return the property. * * @param string $newName * @return void */ public function setName($newName) { $this->name = $newName; $this->names[] = $newName; $pastNameCount = count($this->names); $countCharactersInNames = strlen(implode('', $this->names)); $this->averageNameLength = round($countCharactersInNames / $pastNameCount); } /** * Set age of the animal * * @param integer $newAge * @return void */ public function setAge($newAge) { return $this->age = $newAge; } /** * set favorite food of the animal * * @param string $newFavoriteFood * @return void */ public function setFavoriteFood($newFavoriteFood) { return $this->favoriteFood = $newFavoriteFood; } /** * Print out $sound. This function will also increase the speak counter * and age on every 5 speak increment. * * @param string $sound * @return void */ public function speak($sound = '') { echo $sound . PHP_EOL; $this->speakCounter++; if ($this->speakCounter !== 0 && $this->speakCounter % 5 === 0) { $this->age++; } } } <file_sep>/js/rest api/app/validators/deleteWordValidator.js const joi = require('joi'); module.exports = joi.object().keys({ // word must have .json extension word: joi.string().min(1).max(100).trim() .regex(/([a-zA-Z])+(.json)$/) .required(), }).required(); <file_sep>/php/Animals/tests/AnimalTest.php <?php declare (strict_types = 1); namespace MTCodeAssignment\tests; use PHPUnit\Framework\TestCase; use MTCodeAssignment\src\Animal; final class AnimalTest extends TestCase { public function testNewAnimalAgeMustBeRandomBetween5To10(): void { $animal = new Animal(); $animalAge = $animal->getAge(); $this->assertTrue( ($animalAge >= 5) && ($animalAge <= 10), "Age must be between 5 and 10" ); } public function testLoopNewAnimalAgeMustBeRandomBetween5To10(): void { $numberOfLoops = 10000; for ($i = 1; $i <= $numberOfLoops; $i++) { $this->testNewAnimalAgeMustBeRandomBetween5To10(); } } public function testSpeakWithoutValue(): void { $animal = new Animal(); $this->expectOutputString(PHP_EOL); $animal->speak(); } public function testSpeakWithValue(): void { $animal = new Animal(); $sound = 'Annniimmmaaalll'; $this->expectOutputString($sound.PHP_EOL); $animal->speak($sound); } /** * Test age increment of 1 for every 5 speaks */ public function testSpeakUpdateAge(): void { $animal = new Animal(); $speakCounter = 0; $animalInitialAge = $animal->getAge(); for ($i=1; $i<=1000; $i++) { // Prevent echo from populating the terminal with ob_ ob_start(); $animal->speak(); ob_end_clean(); $speakCounter++; $animalAge = $animal->getAge(); if ($speakCounter !== 0 && $speakCounter % 5 === 0) { $animalInitialAge++; } //echo 'Speak counter: ' . $speakCounter . ' - '; //echo 'Animal age: ' . $animalAge . ' - '; //echo 'Target age: ' . $animalInitialAge; $this->assertEquals($animalAge, $animalInitialAge); } } /** * Test average name length calculation */ public function testAverageNameLength(): void { $animal = new Animal(); $animalNames = []; for ($i=1; $i<=100; $i++) { $testName = str_repeat('test name', $i * rand(1, 10)); $animal->setName($testName); $currentAverageNameLength = $animal->getAverageNameLength(); $animalNames[] = $testName; $targetAverageNameLength = round(strlen(implode('', $animalNames)) / $i); //echo 'Animal avg length: ' . $currentAverageNameLength. ' vs target: ' . $targetAverageNameLength . PHP_EOL; $this->assertEquals($currentAverageNameLength, $targetAverageNameLength); } } } <file_sep>/docker/apache/Dockerfile FROM httpd:2.4.33-alpine RUN apk update; \ apk upgrade; # Copy apache vhost file to proxy php requests to php-fpm container COPY proto.apache.conf /usr/local/apache2/conf/proto.apache.conf RUN echo "Include /usr/local/apache2/conf/proto.apache.conf" \ >> /usr/local/apache2/conf/httpd.conf COPY server.crt /usr/local/apache2/conf/server.crt COPY server.key /usr/local/apache2/conf/server.key #RUN sed -i \ # -e 's/^#\(Include .*httpd-ssl.conf\)/\1/' \ # -e 's/^#\(LoadModule .*mod_ssl.so\)/\1/' \ # -e 's/^#\(LoadModule .*mod_socache_shmcb.so\)/\1/' \ # /usr/local/apache2/conf/httpd.conf # #conf/httpd.conf # Run #RUN chmod 777 /var/www/proto/portal/cache/ /var/www/proto/portal/log/<file_sep>/php/Animals/src/Main.php <?php namespace MTCodeAssignment\src; require __DIR__ . '/../vendor/autoload.php'; use MTCodeAssignment\src\Cat; use MTCodeAssignment\src\Dog; use MTCodeAssignment\src\Data; $cat1 = new Cat(); echo 'Name is currently ' . $cat1->getName() . PHP_EOL; $cat1->setName('Garfield'); echo 'Name has been changed to ' . $cat1->getName() . PHP_EOL; $data = new Data('database'); $data->insert('Cat', $cat1); // Additional functionality, folowing the pattern above. $cat1InitialName = $cat1->getName(); $cat1InitialAge = $cat1->getAge(); echo $cat1InitialName . ' current age is ' . $cat1InitialAge . PHP_EOL; $cat1->setAge(10); echo $cat1InitialName. ' age has been changed from '. $cat1InitialAge .' to ' . $cat1->getAge() . PHP_EOL; $cat1->setName('Tigger'); echo $cat1InitialName . ' new name is ' . $cat1->getName() . PHP_EOL; if ($cat1->getFavoriteFood() === null) { echo $cat1->getName() . ' does not have favorite food yet ' . PHP_EOL; } $cat1->setFavoriteFood('Fish'); echo $cat1->getName() . ' favorite food is ' . $cat1->getFavoriteFood() . PHP_EOL; try { $data->beginTransaction(); // @todo Need to use prepared statements and parameterized queries // to avoid SQL injection // $this->connection->prepare('pet_shop_inventory', $animal); $data->insert('pet_shop_inventory', $cat1); $data->commit(); //throw new \PDOException("Whoops this is just a dummy connection"); echo 'Yay ' . $cat1->getName() . ' is now in our database :)' . PHP_EOL; } catch (\PDOException $e) { $data->rollbacks(); echo 'Something went wrong ' . $cat1->getName() . ' did not get saved into our database :(' . PHP_EOL; } $cat2 = new Cat('Miumiu'); echo 'New Cat arrived! her name is ' . $cat2->getName() . PHP_EOL; echo 'Her age is ' . $cat2->getAge() . PHP_EOL; $numberOfSpeak = 5; for ($i=1; $i<=$numberOfSpeak; $i++) { $cat2->speak(); } echo $cat2->getName(). ' speaks! Exactly ' . $numberOfSpeak . ' times!' . PHP_EOL; echo 'Everytime she speaks 5 times, she will get older by 1. She is now ' . $cat2->getAge() . PHP_EOL; $cat2PreviousName = $cat2->getName(); $cat2->setName('Princess'); echo $cat2PreviousName . ' changed her name to ' . $cat2->getName() . '!' . PHP_EOL; $cat2PreviousName = $cat2->getName(); $namesToTry = ['Lion', 'Sharky', 'Kitty', 'Coco Chanel Divalicious', '<NAME>']; foreach ($namesToTry as $name) { $cat2->setName($name); } echo $cat2PreviousName . ' changed her name ' . count($namesToTry). ' times more!' . PHP_EOL; echo 'Names she tried: '. implode(', ', $namesToTry) . PHP_EOL; echo 'Finally settled with "' . $cat2->getName() . '"'. PHP_EOL; echo 'In total she changed her name ' . count($cat2->getNames()) . ' times!'. PHP_EOL; echo 'Those names are ' . implode(', ', $cat2->getNames()) . PHP_EOL; echo 'Averange length of those names is ' . $cat2->getAverageNameLength() . ' (rounded, spaces included)' . PHP_EOL; <file_sep>/php/Animals/src/Data.php <?php namespace MTCodeAssignment\src; class Data { public function __construct($database) { echo 'Connecting to database' . PHP_EOL; } public function beginTransaction() { echo 'Beginning a transaction' . PHP_EOL; } public function commit() { echo 'Committing transaction' . PHP_EOL; } public function rollbacks() { echo 'Rolling back transaction' . PHP_EOL; } public function insert($table, $object) { echo 'Inserting ' . $object->getName() . ' into table ' . $table . PHP_EOL; } public function prepare($table, $object) { echo 'Preparing ' . $object->getName() . ' for save insert into table ' . $table . PHP_EOL; } } <file_sep>/leetcode/longest-substring-without-repeating-characters.php <?php /* https://leetcode.com/problems/longest-substring-without-repeating-characters/ Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. */ class Solution { /** * @param String $s * @return Integer */ public function lengthOfLongestSubstring($s) { $pastChars = []; $sLen = strlen($s); $prevChar = null; $currChar = null; $longest = 0; $currentLongest = 0; for ($i = 0; $i < $sLen; $i++) { $currChar = $s[$i]; if ($currChar == $prevChar) { $currentLongest = 1; $pastChars = []; } elseif (in_array($s[$i], $pastChars)) { // Find array key of the duplicate $dupKey = array_search($s[$i], $pastChars); // Remove all elements from index 0 up to index of the dup value $pastChars = array_slice($pastChars, $dupKey + 1); $currentLongest = count($pastChars) + 1; } else { $currentLongest++; } if ($currentLongest > $longest) { $longest = $currentLongest; } $prevChar = $currChar; $pastChars[] = $currChar; } return $longest; } } <file_sep>/php/Animals/tests/DogTest.php <?php declare (strict_types = 1); namespace MTCodeAssignment\tests; use PHPUnit\Framework\TestCase; use MTCodeAssignment\src\Dog; final class DogTest extends TestCase { public function testSpeakWithoutValue(): void { $cat = new Dog(); $this->expectOutputString('woof'.PHP_EOL); $cat->speak(); } public function testSpeakWithValue(): void { $cat = new Dog(); $sound = 'woofwoof'; $this->expectOutputString($sound.PHP_EOL); $cat->speak($sound); } } <file_sep>/leetcode/longest-palindromic-substring.php <?php /* https://leetcode.com/problems/longest-palindromic-substring/ Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb"s */ class Solution { /** * @param String $s * @return String */ public $result = ''; public $str = ''; public function longestPalindrome($s) { $this->str = $s; $n = strlen($s); if ($n < 1) {return '';} for ($i = 0; $i < $n; $i++) { $this->isPolindrome($i, $i); $this->isPolindrome($i, $i + 1); } return $this->result; } private function isPolindrome($l, $r) { $s = $this->str; echo '$l = ' . $l . PHP_EOL; while ($l >= 0 && $r < strlen($s) && $s[$l] === $s[$r]) { $polindrome = substr($s, $l, $r - $l + 1); $n = strlen($polindrome); if ($n > 0 && $n > strlen($this->result)) { $this->result = $polindrome; } $l--; $r++; echo 'counter' . PHP_EOL; } } } <file_sep>/php/Animals/src/Cat.php <?php namespace MTCodeAssignment\src; use MTCodeAssignment\src\Animal; /** * This class generates Cat object extends from animal * * @author <NAME> */ class Cat extends Animal { /** * Print out $sound. If $sound not provided, the sound will be 'meow' * * @param string $sound * @return void */ public function speak($sound = 'meow') { parent::speak($sound); } } <file_sep>/js/rest api/app/controllers/anagramController.js class anagramController { constructor(log, AnagramService, httpStatus) { this.log = log; this.AnagramService = AnagramService; this.httpStatus = httpStatus; } async getAnagrams(req, res) { try { const { limit } = req.query; const { word } = req.params; // Remove .json from the word const sanitizedWord = word.replace(/(.json)$/, ''); const result = await this.AnagramService.getAnagrams(sanitizedWord, limit); res.send(result); } catch (err) { this.log.error(err.message); res.send(err); } } } module.exports = anagramController; <file_sep>/php/Animals/src/Dog.php <?php namespace MTCodeAssignment\src; use MTCodeAssignment\src\Animal; /** * This class generates Dog object extends from animal * * @author <NAME> */ class Dog extends Animal { /** * Print out $sound. If $sound not provided, the sound will be 'woof' * * @param string $sound * @return void */ public function speak($sound = 'woof') { parent::speak($sound); } } <file_sep>/php/Animals/sqls/homework.sql CREATE TABLE `animals` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, `age` tinyint unsigned DEFAULT NULL, `favorite_food` varchar(255) DEFAULT NULL, `past_names` varchar(255) DEFAULT NULL, `speak_counter` int unsigned DEFAULT NULL, `type` varchar(255) DEFAULT NULL, `created_at` datetime DEFAULT CURRENT_TIMESTAMP, `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `animals` (`name`,`age`,`favorite_food`,`past_names`,`speak_counter`,`type`) VALUES ('Garfield',5,'fish','[\"garlan\",\"sharky\",\"tigger\"]',4,'cat'), ('Woffie',7,'bone','[\"enzo\",\"fire\"]',3,'dog'), ('Sophia',9,'bully sticks','[\"princess\",\"queen\"]',6,'dog'), ('Tigger',10,'crackers','[\"cracker\",\"garfield\"]',2,'cat');<file_sep>/php/Animals/tests/CatTest.php <?php declare (strict_types = 1); namespace MTCodeAssignment\tests; use PHPUnit\Framework\TestCase; use MTCodeAssignment\src\Cat; final class CatTest extends TestCase { public function testSpeakWithoutValue(): void { $cat = new Cat(); $this->expectOutputString('meow'.PHP_EOL); $cat->speak(); } public function testSpeakWithValue(): void { $cat = new Cat(); $sound = 'roaaarrrrrr'; $this->expectOutputString($sound.PHP_EOL); $cat->speak($sound); } } <file_sep>/js/rest api/app/configs/dependencyInjection.js const serviceLocator = require('../lib/serviceLocator'); const config = require('./configs')(); serviceLocator.register('logger', () => require('../lib/logger').create(config.application_logging)); serviceLocator.register('httpStatus', () => require('http-status')); serviceLocator.register('mongoose', () => require('mongoose')); serviceLocator.register('errs', () => require('restify-errors')); serviceLocator.register('WordService', (serviceLocator) => { const log = serviceLocator.get('logger'); const mongoose = serviceLocator.get('mongoose'); const errs = serviceLocator.get('errs'); const WordService = require('../services/wordService'); return new WordService(log, mongoose, errs); }); serviceLocator.register('AnagramService', (serviceLocator) => { const log = serviceLocator.get('logger'); const mongoose = serviceLocator.get('mongoose'); const errs = serviceLocator.get('errs'); const AnagramService = require('../services/AnagramService'); return new AnagramService(log, mongoose, errs); }); serviceLocator.register('wordController', (serviceLocator) => { const log = serviceLocator.get('logger'); const httpStatus = serviceLocator.get('httpStatus'); const WordService = serviceLocator.get('WordService'); const wordController = require('../controllers/wordController'); return new wordController(log, WordService, httpStatus); }); serviceLocator.register('anagramController', (serviceLocator) => { const log = serviceLocator.get('logger'); const httpStatus = serviceLocator.get('httpStatus'); const AnagramService = serviceLocator.get('AnagramService'); const anagramController = require('../controllers/anagramController'); return new anagramController(log, AnagramService, httpStatus); }); module.exports = serviceLocator; <file_sep>/js/rest api/app/services/wordService.js class wordService { constructor(log, mongoose, errs) { this.log = log; this.mongoose = mongoose; this.errs = errs; } async createWords(words) { const Dictionary = this.mongoose.model('Dictionary'); const wordsExist = await Dictionary.find({ word: { $in: words } }, { word: 1, _id: 0 }); // Check for existing words, if already exist do not insert // Dictionary should be unique, if words already exist do not insert if (wordsExist.length !== 0) { const existingWords = []; for (const i in wordsExist) { existingWords.push(wordsExist[i].word); } // ES7 specific! words = words.filter(x => !existingWords.includes(x)); } words = words.map(t => ({ word: t })); const wordsAdded = await Dictionary.insertMany(words); this.log.info('Words created successfully'); return wordsAdded; } async deleteWord(word) { const Dictionary = this.mongoose.model('Dictionary'); // Remove .json from the word const SanitizedWord = word.replace(/(.json)$/, ''); const exists = await Dictionary.find({ word: SanitizedWord }, { word: 1, _id: 0 }); if (exists.length === 0) { this.log.info(`Word '${SanitizedWord}' does not exit`); return; } const deleteWord = await Dictionary.deleteOne({ word: SanitizedWord }); this.log.info(`Word '${SanitizedWord}' deleted successfully`); return deleteWord; } async deleteAll() { const Dictionary = this.mongoose.model('Dictionary'); const DeleteAll = await Dictionary.deleteMany({}); this.log.info('All words in the dictionary deleted successfully!'); return DeleteAll; } async getStats() { const Dictionary = this.mongoose.model('Dictionary'); const stats = await Dictionary.aggregate([ { $project: { word: 1, length: { $strLenCP: '$word' }, }, }, { $sort: { length: 1 } }, { $group: { _id: '$_id.word', longestWord: { $last: '$word' }, shortestWord: { $first: '$word' }, totalRecords: { $sum: 1 }, avgWordLength: { $avg: '$length' }, }, }, { $project: { _id: 0, totalRecords: '$totalRecords', longestWord: '$longestWord', shortestWord: '$shortestWord', avgWordLengthRounded: { $ceil: '$avgWordLength' }, }, }, ]); this.log.info(stats); return stats; } } module.exports = wordService; <file_sep>/leetcode/add-two-numbers.php <?php /* https://leetcode.com/problems/add-two-numbers/ You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. */ class ListNode { public $val = 0; public $next = null; public function __construct($val) { $this->val = $val; } } class Solution { /** * @param ListNode $l1 * @param ListNode $l2 * @return ListNode */ public function addTwoNumbers($l1, $l2) { $result = new ListNode(0); $current = $result; $carry = 0; while (!is_null($l1) || !is_null($l2)) { $sum = $l1->val + $l2->val + $carry; $carry = floor($sum / 10); $current->next = new ListNode($sum % 10); $current = $current->next; $l1 = $l1->next; $l2 = $l2->next; } if ($carry > 0) { $current->next = new ListNode($carry); } return $result->next; } } <file_sep>/php/Animals/src/PetShop.php <?php namespace MTCodeAssignment\src; require __DIR__ . '/../vendor/autoload.php'; use MTCodeAssignment\src\Cat; use MTCodeAssignment\src\Data; class PetShop { public function __construct() { $this->connection = new Data('database'); } public function saveTest() { $cat = new Cat('Kitty'); $this->insertToPetShopInventory($cat); $dog = new Cat('Doggy'); $this->insertToPetShopInventory($dog); } /** * Create three nameless cats and dogs insert them to the database. * Make the objects persist, so they can be access outside this function * * @return void */ public function savePetShop() { for ($i=1; $i<=3; $i++) { $newCat = 'newCat'.$i; $this->$newCat = new Cat(); $this->insertToPetShopInventory($this->$newCat); $newDog = 'newDog'.$i; $this->$newDog = new Dog(); $this->insertToPetShopInventory($this->$newDog); } } public function logStats($message) { echo $message . PHP_EOL; } private function insertToPetShopInventory($animal) { try { $this->connection->beginTransaction(); // @todo Need to use prepared statements and parameterized queries // to avoid SQL injection // $this->connection->prepare('pet_shop_inventory', $animal); $this->connection->insert('pet_shop_inventory', $animal); $this->connection->commit(); // throw new \PDOException("Whoops this is just a dummy connection"); $this->logStats('Success! '.$animal->getName() . ' inserted to our db'); } catch (\PDOException $e) { $this->connection->rollbacks(); $this->logStats('Error' . $e->getMessage()); } } } $newPetShop = new PetShop(); $newPetShop->saveTest(); $newPetShop->savePetShop(); $newPetShop->logStats('Test logStats'); $newPetShop->newCat1->speak('test'); for ($i=1; $i<=3; $i++) { $newCat = 'newCat'.$i; echo 'Nameless ' . substr(strrchr(get_class($newPetShop->$newCat), '\\'), 1) . ' Say '; $newPetShop->$newCat->speak('Meow-'.$i); } for ($i=1; $i<=3; $i++) { $newDog = 'newDog'.$i; echo 'Nameless ' . substr(strrchr(get_class($newPetShop->$newDog), '\\'), 1) . ' Say '; $newPetShop->$newDog->speak('Woof-'.$i); } <file_sep>/php/Animals/README.md # MT code assessment This project is prepared by <NAME> on February 3rd 2019 as a code assignment for X company to demonstrate PHP OOP best practices. # Notes - Echo(s) will have PHP_EOL appended so it look nice on the terminal. Unit tests updated accordingly. - Documentation on the class(es), most of them are not needed (properties, setters and getters for example). The code is self explanatory, so there is no need really to add documentation on every single methods. I just added it for this excercise. - Always use triple equals (===) equality comparison operator where possible. # Requirements - PHP 7.2+, since 7.1 is now supported for critical security issues only per http://php.net/supported-versions.php - PHPUnit 8 (requires PHP 7.2+) - Composer (optional). I have included the vendor folder just in case # Coding standard - Coding style guide: PSR-2 - StudlyCaps for class name - camelCase() for methods - camelCase for properties and variables - Filename must match class name where applicable # Things to improve on - Use prepared statements and parameterized queries to avoid SQL injection - Add more test cases to AnimalTest # Folder structure ``` project ├── README.md ├── composer.json ├── composer.lock ├── sqls │   └── homework.sql ├── src │   ├── Animal.php > base class for cat and dog │   ├── Cat.php > subclass of animal │   ├── Data.php > database class │   ├── Dog.php > subclass of animal │   ├── Main.php > executes variety of functions utilizing cat and dog objects │   └── PetShop.php > Pet shop class, resposible for managing inventory of animals ├── tests │   ├── AnimalTest.php │   ├── CatTest.php │   └── DogTest.php └── vendor => generated by composer (composer require --dev phpunit/phpunit ^8) ``` # Tests ## Running tests individually > vendor/bin/phpunit --bootstrap vendor/autoload.php tests/CatTest.php > vendor/bin/phpunit --bootstrap vendor/autoload.php tests/DogTest.php > vendor/bin/phpunit --bootstrap vendor/autoload.php tests/AnimalTest.php ## Running all tests > vendor/bin/phpunit --bootstrap vendor/autoload.php tests ## Test Main and PetShop > php src/Main.php > php src/PetShop.php<file_sep>/js/rest api/app/controllers/wordController.js class wordController { constructor(log, WordService, httpStatus) { this.log = log; this.WordService = WordService; this.httpStatus = httpStatus; } async create(req, res) { try { const { words } = req.body; await this.WordService.createWords(words); res.status(201); res.send(); } catch (err) { this.log.error(err.message); res.send(err); } } async deleteWord(req, res) { try { const { word } = req.params; const sanitizedWord = word.replace(/(.json)$/, ''); await this.WordService.deleteWord(sanitizedWord); res.status(204); res.send(); } catch (err) { this.log.error(err.message); res.send(err); } } async deleteAll(req, res) { try { await this.WordService.deleteAll(); res.status(204); res.send(); } catch (err) { this.log.error(err.message); res.send(err); } } async getStats(req, res) { try { const results = await this.WordService.getStats(); res.send(results); } catch (err) { this.log.error(err.message); res.send(err); } } } module.exports = wordController; <file_sep>/js/rest api/README.md # Introduction This project is prepared for company X as part of interview process. The project is to build RESTful API that provides anagrams. # Design Overview I utilized MVC and dependency injection architecture for this project. Most of modern frameworks are doing this making them lightweight. # Directory Structure ``` . ├── .env > config parameters ├── README.md ├── app │   ├── configs > configuration classes, includes list of services for the dependency injection. │   ├── controllers > controller classes │   ├── lib > helper classes │   ├── models > database schema definition │   ├── routes > router class │   ├── services > business logic │   └── validators > validators for API requests ├── logs > logs every requests to a file ├── node_modules > installed after running npm install ├── data > mongodb directory / updated dictionary.txt (with header type) ├── package-lock.json ├── package.json ├── server.js > run 'node server' to start! └── tests > test files in ruby ``` # Coding Standard Airbnb JavaScript Style Guide (https://github.com/airbnb/javascript) # Requirements (listed versions I have on my local machine) - node (10.8.0) - npm (6.2.0) - ruby (2.3.3) - mongodb (4.0.6) # Getting Started install dependencies > npm install start mongodb by executing below command in the project root folder > mongod --dbpath data/db load dictionary to the database > mongoimport -d MT -c dictionaries --type csv --file data/dictionary.txt --columnsHaveTypes --headerline Start node server, please make sure nothing is running on port 3000. To change port please update .env file > node server # API Routes ## Get Get anagrams for aerst > http://localhost:3000/anagrams/aerst.json Get statistics (longest, shortest word, etc) > http://localhost:3000/words/stats.json ## Post Add words to the database > http://localhost:3000/words.json ## Delete Delete bear from the database > http://localhost:3000/words/bear.json Delete all words > http://localhost:3000/words.json # Things I learned while working on this project ## mongoDB I probably should not have used mongoDB, I spent too much time on it! :( but hey I learned a lot! ### Lesson learned running import from txt file could add NaN and Infinity data types to the database. 'infinity' string actually gets added as infinity data type. So, I had to change the import to account for this infinity data type gets added using this command > mongoimport -d MT -c dictionaries --type csv --file data/dictionary.txt -f word with this no infinity yay! > mongoimport -d MT -c dictionaries --type csv --file data/dictionary.txt --columnsHaveTypes --headerline ## Javascript - use async/await is much better than callbacks and promises # Things to improve on - Improve query speed on mongoDB - Add standard sanitization on the request body/params/query # Tests Ruby test has been added to package.json, to run execute: > npm test to test via curl (e.g.) > curl -i -X POST -d '{"words":["read", "dear", "dare"]}' http://localhost:3000/words.json -H "Content-Type: application/json"s <file_sep>/docker/docker-compose.yml version: "3.4" services: php: build: context: './php/' args: PHP_VERSION: ${PHP_VERSION} networks: - backend volumes: - ${PROJECT_ROOT}/:/var/www/proto/ container_name: php #command: php /var/www/proto/portal/symfony keywordobjects:bootstrap-config #tty: true environment: DOCKER_HOST: host.docker.internal extra_hosts: - "aud.proto.ko.int:172.18.0.4" - "ppc.proto.ko.int:172.18.0.4" - "seo.proto.ko.int:172.18.0.4" - "syn.proto.ko.int:172.18.0.4" - "da.proto.ko.int:172.18.0.4" - "dash.proto.ko.int:172.18.0.4" - "admin.proto.ko.int:172.18.0.4" apache: build: context: './apache/' args: APACHE_VERSION: ${APACHE_VERSION} depends_on: - php - mysql networks: - frontend - backend ports: - "80:80" - "443:443" volumes: - ${PROJECT_ROOT}/:/var/www/proto/ container_name: apache environment: DOCKER_HOST: host.docker.internal #extra_hosts: # - "aud.proto.ko.int:172.17.0.1" mysql: image: mysql:${MYSQL_VERSION:-latest} command: mysqld --sql_mode="" --local_infile=1 restart: always ports: - "3306:3306" volumes: - ${DATABASE_DIR}/:/var/lib/mysql - ${PROJECT_ROOT}/:/var/www/proto/ networks: - backend environment: MYSQL_ROOT_PASSWORD: "${<PASSWORD>}" #MYSQL_DATABASE: "${DB_NAME}" MYSQL_USER: "${DB_USERNAME}" MYSQL_PASSWORD: "${<PASSWORD>}" container_name: mysql command: mysqld --innodb-buffer-pool-size=256M --sql_mode="" networks: frontend: backend:<file_sep>/docker/README.md # Introduction Docker setup for local environment # Installation ## Step 1: Download and install docker desktop Mac: - https://docs.docker.com/docker-for-mac/ Windows: - https://docs.docker.com/docker-for-windows/ ## Step 2: Update hosts on your local machine on mac: /etc/hosts on windows: c:\windows\system32\drivers\etc\hosts ``` ## Docker: Keyword Objects # Portal 127.0.0.1 proto.ko.ext 127.0.0.1 proto.ko.int # Dash 127.0.0.1 dash.proto.ko.ext 127.0.0.1 dash.proto.ko.int # PPC 127.0.0.1 ppc.proto.ko.ext 127.0.0.1 ppc.proto.ko.int # SEO 127.0.0.1 seo.proto.ko.ext 127.0.0.1 seo.proto.ko.int # Admin 127.0.0.1 admin.proto.ko.ext 127.0.0.1 admin.proto.ko.int # DA 127.0.0.1 da.proto.ko.ext 127.0.0.1 da.proto.ko.int # Syn 127.0.0.1 syn.proto.ko.ext 127.0.0.1 syn.proto.ko.int # Aud 127.0.0.1 aud.proto.ko.ext 127.0.0.1 aud.proto.ko.int ``` Note: will need to flush DNS windows: ipconfig /flushdns mac: sudo killall -HUP mDNSResponder ## Step 3: Kill any processes using port 80/443 ### ON Mac - sudo killall httpd ### On Windows 10 find PID: netstat -ano | findstr :80|443 kill PID: taskkill /PID (PIDherewithoutparentheses) /F ## Step 4: Git submodules Go to ko-docker folder and execute the following git commands: - git submodule init - git submodule update --init --recursive - git submodule foreach --recursive git checkout master ## Step 5: Set up DB Download data.zip, unzip to ko-docker folder. ## Step 6: Run docker - docker-compose build - docker-compose up Note: cannot create container for service x: b'drive has not been shared' open docker setting, shared drives check apply Note: Error: A firewall is blocking file sharing between Windows and the containers https://success.docker.com/article/error-a-firewall-is-blocking-file-sharing-between-windows-and-the-containers if does not work ! try: https://addshore.com/2019/01/a-firewall-is-blocking-sharing-between-windows-and-the-containers-docker/ https://stackoverflow.com/questions/42203488/settings-to-windows-firewall-to-allow-docker-for-windows-to-share-drive/43904051#43904051 ## Step 7: login to PHP container, execute bootstrap run on ko-docker: - docker exec -it php /bin/sh once logged in to container, execute the following commands: - php /var/www/proto/portal/symfony keywordobjects:bootstrap-config; - php /var/www/proto/ppc/symfony keywordobjects:bootstrap-config; - php /var/www/proto/seo/symfony keywordobjects:bootstrap-config; - php /var/www/proto/admin/symfony keywordobjects:bootstrap-config; - php /var/www/proto/syn/symfony keywordobjects:bootstrap-config; - php /var/www/proto/aud/bootstrap.php; - php /var/www/proto/da/bootstrap.php; - php /var/www/proto/dash/bootstrap.php; - cd /var/www/proto/aud; php app/console assets:install --symlink --relative; - cd /var/www/proto/da; php app/console assets:install --symlink --relative; - cd /var/www/proto/dash; php app/console assets:install --symlink --relative; ## Step 8: Disable php_value on apps/portal/web/.htaccess apps/dash/web/.htaccess apps/admin/web/.htaccess apps/aud/web/.htaccess apps/da/web/.htaccess php_value max_input_vars 10000 => #php_value max_input_vars 10000 Note: Do not commit these changes ## Step 9: Verify the app is working Open your favorite browser and go to: https://proto.ko.ext/index.php/login <file_sep>/docker/php/Dockerfile #FROM php:7.2.7-fpm-alpine3.7 FROM php:7.0-fpm-alpine3.7 COPY www.conf /usr/local/etc/php-fpm.d/www.conf RUN apk update; \ apk upgrade; RUN docker-php-ext-install mysqli pdo pdo_mysql # Run KO bootstrap #CMD ["php", "/var/www/proto/portal/symfony", "keywordobjects:bootstrap-config"] #CMD php /var/www/proto/portal/symfony keywordobjects:bootstrap-config #CMD php /var/www/proto/ppc/symfony keywordobjects:bootstrap-config #CMD php /var/www/proto/seo/symfony keywordobjects:bootstrap-config #CMD php /var/www/proto/admin/symfony keywordobjects:bootstrap-config #CMD php /var/www/proto/aud/bootstrap.php #CMD php /var/www/proto/da/bootstrap.php #CMD php /var/www/proto/dash/bootstrap.php # Run KO Stuff! need to be at the app directory! at least for DA #RUN php /var/www/proto/aud/app/console assets:install --symlink --relative #RUN php /var/www/proto/da/app/console assets:install --symlink --relative #RUN php /var/www/proto/dash/app/console assets:install --symlink --relative #CMD ["php", "/var/www/proto/da/app/console assets:install --symlink --relative"] #CMD ["php", "/var/www/proto/aud/app/console assets:install --symlink --relative"] #CMD ["php", "/var/www/proto/dash/app/console assets:install --symlink --relative"]<file_sep>/leetcode/rotate-image.php <?php /* https://leetcode.com/problems/rotate-image/ You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Note: You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example 1: Given input matrix = [ [1,2,3], [4,5,6], [7,8,9] ], rotate the input matrix in-place such that it becomes: [ [7,4,1], [8,5,2], [9,6,3] ] Example 2: Given input matrix = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ], rotate the input matrix in-place such that it becomes: [ [15,13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7,10,11] ] */ class Solution { /** * @param Integer[][] $matrix * @return NULL */ public function rotate(&$matrix) { $n = count($matrix); $this->transpose($matrix); for ($i = 0; $i < $n; $i++) { $matrix[$i] = array_reverse($matrix[$i]); } } public function transpose(&$matrix) { $row = count($matrix); $col = $row; $done = []; for ($i = 0; $i < $row; $i++) { for ($j = 0; $j < $col; $j++) { if ($i === $j) { continue; } if (in_array([$i, $j], $done) || in_array([$j, $i], $done)) { continue; } [$matrix[$i][$j], $matrix[$j][$i]] = [$matrix[$j][$i], $matrix[$i][$j]]; //$temp = $matrix[$i][$j]; //$matrix[$i][$j] = $matrix[$j][$i]; //$matrix[$j][$i] = $temp; $done[] = [$i, $j]; $done[] = [$j, $i]; } } //print_r($matrix); } }
f73bdfa6f292ac23b5cd138f92734959974f1bbd
[ "SQL", "YAML", "JavaScript", "Markdown", "PHP", "Dockerfile" ]
26
JavaScript
mtanjung/sample-code
e6a6d49da67f3112b6c2023d240e43a29f7b713a
009262a7da17b291fbc25bd0f83f4ef1470736fe
refs/heads/master
<repo_name>andre-artus/NPEG<file_sep>/NPEG/GrammarInterpreter/NpegOptions.cs using System; namespace NPEG.GrammarInterpreter { [Flags] public enum NpegOptions { Optimize=0x2, Cached = 0x1, None = 0x0 } }
bc6fed359b7f37970e43bb16c2136385ac04a314
[ "C#" ]
1
C#
andre-artus/NPEG
8a7533474161b1468786abb17890f80f79cf0a45
5cf8385b0688f1fd9542441109b76ad0b4198c3b
refs/heads/main
<repo_name>shaiqsdmn/WebTechLab<file_sep>/week3lab/index.php <!DOCTYPE HTML> <html> <head> </head> <body> <?php // define variables and set to empty values $firstname = $lastname = $email = $gender = $comment = $website = ""; $firstnameError=""; $lastnameError=""; $emailError=""; $websiteError=""; $commentError=""; $genderError=""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $firstname = test_input($_POST["firstname"]); $lastname = test_input($_POST["lastname"]); $email = test_input($_POST["email"]); $website = test_input($_POST["website"]); $comment = test_input($_POST["comment"]); $gender = test_input($_POST["gender"]); if(empty($firstname) || $firstname =="" || !preg_match("/[a-zA-Z-]*$/",$firstname)) { $firstnameError = "Please enter first name!"; } if(empty($lastname) || $lastname =="" || !preg_match("/[a-zA-Z-]*$/",$lastname)) { $lastnameError = "Please enter last name!"; } if(empty($email) || $email =="") { $emailError = "Please enter email!"; } if(empty($website) || $website =="") { $websiteError = "Please enter website!"; } if(empty($comment) || $comment =="") { $commentError = "Please enter comment!"; } if(empty($gender) || $gender =="") { $genderError = "Please enter gender!"; } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <fieldset> <fieldset> <legend align="center"><h1>Registration</h1></legend> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> First Name: <tr> <td><input type="text" id="firstname" placeholder = "<NAME>" required></td> </tr> <?php echo $firstnameError; ?> <br><br> Last Name: <tr> <td><input type="text" id="lastname" placeholder = "<NAME>" required></td> </tr> <?php echo $lastnameError; ?> <br><br> E-mail: <input type="text" name="email"> <?php echo $emailError; ?> <br><br> Website: <input type="text" name="website"> <?php echo $websiteError; ?> <br><br> Comment: <textarea name="comment" rows="5" cols="40"></textarea> <?php echo $commentError; ?> <br><br> Gender: <input type="radio" name="gender" value="female" checked>Female <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="other">Other <br><br> <input type="submit" name="submit" value="Submit"> <?php echo $genderError; ?> <br><br> </form> </fieldset> </fieldset> <?php echo "<h2>Your Input:</h2>"; echo $firstname; echo "<br>"; echo $lastname; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html><file_sep>/week2lab/MyCircle.php <?php /*$odd="Odd Numbers Are : "; echo $odd; echo "<br>"; for ($i=11; $i<=99; $i+=2) { echo $i." , "."<br>" ; } ?>*/ /*class Fruit { public $name; public $color; function __construct ($name) { $this -> name = =$name; } function get_name() { return $this -> name; } } $apple = new Fruit("Apple"); echo $apple -> get_name(); ?> */ <?php class MyCircle { public $radius; function __construct($name){ $this->name = $name; } function getRadious() { return $this->radius; } function setRadius($radius){ return $this->radius=radius; } function getArea(){ return "area is = ".$this->radius*2*3.14; } $radius = new myCycle("Apple"); echo $radius->getarea(); ?> <file_sep>/week2lab/myaction.php <!DOCTYPLE html> <html> <head> <title>Practice on Makeup</title> <body> <div> <?php if(isset($_POST['create'])) echo 'its working!' ?> </div> <form action="myaction.php" method="post" > <label for="name">Name</label> <input type="text" id ="name" name="name"> <br> <label for ="password">Password</label> <input type="<PASSWORD>" id="password" name="password"> <button>Submit</button> </form> </body> </head> </html>
e02447094ed5aee830eb8068389838961b5777bb
[ "PHP" ]
3
PHP
shaiqsdmn/WebTechLab
7466591b17a5b14e184ab6b1cdee76a1e589f70d
a62fc8d2593597cee290f5697b7359e5784eddd3
refs/heads/master
<file_sep>from check50 import * class Frequency(Checks): @check() def exists(self): """frequency.c exists""" self.require("frequency.c") @check("exists") def compiles(self): """frequency.c compiles""" self.spawn("clang -o frequency frequency.c -lcs50 -lm").exit(0) @check("compiles") def test_base_case(self): """does the program provide the expected output from the example given?""" self.spawn("./frequency").stdin("2").stdin("THE QUICK BROWN FOX").stdin("JUMPED OVER THE LAZY DOG").stdout("A *").stdout("B *").stdout("C *").stdout("D **").stdout("E ****").stdout("F *").stdout("G *").stdout("H **").stdout("I *").stdout("J *").stdout("K *").stdout("L *").stdout("M *").stdout("N *").stdout("O ****").stdout("P *").stdout("Q *").stdout("R **").stdout("T **").stdout("U **").stdout("V *").stdout("W *").stdout("X *").stdout("Y *").stdout("Z *").exit(0)<file_sep>from check50 import * class PartnerUp(Checks): @check() def exists(self): """partnerup.c exists""" self.require("partnerup.c") @check("exists") def compiles(self): """partnerup.c compiles""" self.spawn("clang -o partnerup partnerup.c -lcs50 -lm").exit(0) @check("compiles") def test_odd_number(self): """odd number of students rejected (could everyone have a unique partner?)""" self.spawn("./partnerup").stdin("13").stdin("<NAME> <NAME> <NAME>").stdin("<NAME> <NAME>").stdout("bad").exit(0) @check("compiles") def test_simple_reverse(self): """given list of students is simply reversed in second line""" self.spawn("./partnerup").stdin("6").stdin("<NAME> <NAME>").stdin("<NAME>").stdout("good").exit(0) @check("compiles") def test_smallest_case(self): """smallest number of students""" self.spawn("./partnerup").stdin("2").stdin("<NAME>").stdin("<NAME>").stdout("good").exit(0) @check("compiles") def test_largest_case(self): """test the largest number of students""" self.spawn("./partnerup").stdin("30").stdin("<NAME> <NAME>").stdin("<NAME> T<NAME>").stdout("good").exit(0) @check("compiles") def test_split_list(self): """partners are consistent with something other than a simple reversal of first list order""" self.spawn("./partnerup").stdin("4").stdin("<NAME>").stdin("<NAME>").stdout("good").exit(0) @check("compiles") def test_all_assigned_self(self): """partners all assigned to self""" self.spawn("./partnerup").stdin("6").stdin("<NAME> <NAME>").stdin("<NAME>").stdout("bad").exit(0) @check("compiles") def test_double_self_assignment(self): """two partners assigned to self""" self.spawn("./partnerup").stdin("6").stdin("<NAME> <NAME>").stdin("<NAME> <NAME>").stdout("bad").exit(0) @check("compiles") def test_four_wrong(self): """four partners inconsistent""" self.spawn("./partnerup").stdin("6").stdin("<NAME>").stdin("<NAME>").stdout("bad").exit(0)
1e5d76fc549498569607495124570beb929e1e0b
[ "Python" ]
2
Python
lcs-rgordon/checks
387a0e31975b8ab5445de12ae1fd03bd59b9478d
a816dbaa9a1fc0ccbd43a20fcbb9beca33a0a449
refs/heads/master
<repo_name>BusinessDuck/xdsioszxcvaqerfdadafsdf<file_sep>/GameLogic/DatabaseInspector.swift // // DatabaseCreator.swift // GameLogic // // Created by Admin on 10.12.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit import SQLite class DatabaseInspector { class func getDatabase() -> Database{ let documentPath = NSSearchPathForDirectoriesInDomains( .DocumentDirectory, .UserDomainMask, true ).first as String let language = NSBundle.mainBundle().preferredLocalizations.first as NSString var databasePath:NSString switch language { case "ru": databasePath = documentPath.stringByAppendingString("/ru.sqlite3") break default: databasePath = documentPath.stringByAppendingString("/db.sqlite3") break } let db = Database(databasePath) return self.checkDatabase(db, databasePath: databasePath) } class func resetDatabase(hard: Bool) -> Database{ let language = NSBundle.mainBundle().preferredLocalizations.first as NSString let documentPath = NSSearchPathForDirectoriesInDomains( .DocumentDirectory, .UserDomainMask, true ).first as String var databasePath:NSString var bundle:NSString switch language { case "ru": bundle = NSBundle.mainBundle().pathForResource("ru", ofType: "sqlite3")! databasePath = documentPath.stringByAppendingString("/ru.sqlite3") break default: bundle = NSBundle.mainBundle().pathForResource("db", ofType: "sqlite3")! databasePath = documentPath.stringByAppendingString("/db.sqlite3") break } if(hard){ let fileManager = NSFileManager.defaultManager() fileManager.removeItemAtPath(databasePath, error:nil) fileManager.copyItemAtPath(bundle, toPath: databasePath, error:nil) return resetDatabase(false) } let db = Database(databasePath) let idExp = Expression<Int>("id") let firstExp = Expression<Bool>("first") let levelIdExp = Expression<Int>("levelId") let scoreExp = Expression<Int>("score") let hintedExp = Expression<Bool>("hinted") let completeExp = Expression<Bool>("complete") let levels = db["levels"] levels.update(completeExp <- false, hintedExp <- false)? let gameStmt = db["statement"] gameStmt.filter(idExp == 1).update(scoreExp <- 0, firstExp <- true, levelIdExp <- 1)? return db } class func checkDatabase(db: Database, databasePath: String) -> Database { let fileManager = NSFileManager.defaultManager() if !fileManager.fileExistsAtPath(databasePath) { return self.resetDatabase(true) } let versionExp = Expression<Int>("version") let stmt = db.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?") let levels:Int = stmt.scalar("levels") as Int let settings:Int = stmt.scalar("settings") as Int let statement:Int = stmt.scalar("statement") as Int if (levels + settings + statement) < 3 { return self.resetDatabase(true) } let countV = db["settings"].total(versionExp) //@todo upgrade check db if(countV < 2.0){ return self.resetDatabase(true) } return db } } <file_sep>/GameLogic/LevelProviderProtocol.swift // // LevelProviderProtocol.swift // GameLogic // // Created by Admin on 27.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import Foundation protocol LevelProviderProtocol { func setLevelComplete(id: Int) func setLevelHinted(id: Int) func updateLevel(level: Level) func getLevels() -> Array<Level> func getLevelById(id: Int) -> Level func setRepository(source: AnyObject) func getRepository() -> AnyObject init(repository: AnyObject) }<file_sep>/GameLogic/AudioPlayer.swift // // AudioPlayer.swift // GameLogic // // Created by Admin on 26.01.15. // Copyright (c) 2015 Admin. All rights reserved. // import UIKit import AVFoundation class AudioController { required init(){ } private var _player:AVAudioPlayer? private func _playFile(name:String, loops:Int, allowPlay: Bool, volume:Float = 1.0){ var soundPath = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(name, ofType: "mp3")!) // Removed deprecated use of AVAudioSessionDelegate protocol AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil) AVAudioSession.sharedInstance().setActive(true, error: nil) var error:NSError? self._player = AVAudioPlayer(contentsOfURL: soundPath, error: &error) if(!allowPlay){ self._player?.volume = 0 } else { self._player?.volume = volume } self._player?.prepareToPlay() self._player?.numberOfLoops = loops self._player?.play() } func mainTheme(volume:Float) { self._playFile("main_theme", loops: 4, allowPlay: settingsProvider!.getMusic(), volume: volume) } func gameTheme(volume:Float){ self._playFile("game_theme", loops: 4, allowPlay: settingsProvider!.getMusic(), volume: volume) } func click() { self._playFile("click", loops: 0, allowPlay: settingsProvider!.getSound()) } func completeLevel() { self._playFile("complete_level", loops: 0, allowPlay: settingsProvider!.getSound(), volume: 0.3) } func cancel() { self._playFile("cancel_answer", loops: 0, allowPlay: settingsProvider!.getSound()) } func getPlayerInstance() -> AVAudioPlayer?{ return self._player } func setPlayerInstance(instance: AVAudioPlayer?) -> AudioController{ self._player = instance return self } } <file_sep>/GameLogic/Settings.swift // // Statement.swift // GameLogic // // Created by Admin on 28.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import Foundation class GameSettings{ private var _music: Bool private var _sound: Bool init(id: Int, music: Bool, sound: Bool){ self._music = music self._sound = sound } init(){ self._sound = true self._music = true } func setMusic(music: Bool) { self._music = music } func setSound(sound: Bool){ self._sound = sound } func getMusic() -> Bool{ return self._music } func getSound() -> Bool{ return self._sound } }<file_sep>/GameLogic/GameController.swift // // ViewController.swift // GameLogic // // Created by Admin on 13.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit import AVFoundation import GameKit let levelProvider = LocalLevelProvider.sharedInstance class GameController: UIViewController{ @IBOutlet var mainView: GameScreenView! @IBOutlet weak var buttonNext: UIButton! @IBOutlet weak var buttonPrev: UIButton! @IBOutlet weak var prevLevelLabel: UILabel! @IBOutlet weak var nextLevelLabel: UILabel! @IBOutlet weak var currentLevelLabel: UILabel! @IBOutlet weak var emojiLabelOne: EmojiLabel! @IBOutlet weak var scoreSmall: UITextView! @IBOutlet weak var iAdView: UIView! @IBOutlet weak var hintCount: UILabel! @IBOutlet weak var questSwipe: UIImageView! @IBOutlet weak var answerSwipe: UIImageView! var audioPlayer:AudioController? = AudioController() required init(coder: NSCoder){ super.init(coder: coder) } override init(nibName: String!, bundle: NSBundle!){ var subview = UIView() super.init(nibName: nil, bundle: nil) } convenience override init(){ self.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() var answer:String = levelProvider.getLevelById(stmtProvider!.getCurrentLevelId()).answer if(countElements(answer) > 27){ self.answerSwipe.hidden = false self.questSwipe.hidden = false } else { self.answerSwipe.hidden = true self.questSwipe.hidden = true } self.audioPlayer?.setPlayerInstance(AVAudioPlayer()); NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("removeSelf"), name: "removeLevel", object: nil) let id: Int = stmtProvider!.getCurrentLevelId() self.currentLevelLabel.text = String(id) self.nextLevelLabel.text = String(1 + id) self.prevLevelLabel.text = String(id - 1) self.scoreSmall.text = "\(stmtProvider!.getCurrentScore())" self.hintCount.text = "\(stmtProvider!.getHintCount())" self.checkLevelVisible() } override func viewDidAppear(animated: Bool) { self.audioPlayer?.gameTheme(0.10) } func removeSelf(){ self.dismissViewControllerAnimated(true, completion: nil) let subviews:Array<AnyObject> = self.view.subviews for view in subviews{ view.removeFromSuperview() } self.removeFromParentViewController() self.view.removeFromSuperview() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func goToLevel(sender: AnyObject) { if stmtProvider!.getCurrentLevelId() == self.currentLevelLabel.text!.toInt(){ return } NSNotificationCenter.defaultCenter().postNotificationName("removeLevel", object: nil) let level = levelProvider.getLevelById(self.currentLevelLabel.text!.toInt()!) stmtProvider!.setCurrentLevel(level.id) let mainSrotyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) var viewController = mainSrotyboard.instantiateViewControllerWithIdentifier("gameViewController") as GameController UIApplication.sharedApplication().keyWindow?.rootViewController = viewController } @IBAction func nextLevel(sender: UIButton) { if self.nextLevelLabel.text!.toInt()! <= levelProvider.getLevels().count { self.prevLevelLabel.text = self.currentLevelLabel.text let current = self.currentLevelLabel.text!.toInt()! + 1 let next = current + 1 self.currentLevelLabel.text = String(current) self.nextLevelLabel.text = String(next) self.checkLevelVisible() } } @IBAction func prevLevel(sender: UIButton){ if self.currentLevelLabel.text!.toInt()! > 1 { self.nextLevelLabel.text = self.currentLevelLabel.text let current = self.currentLevelLabel.text!.toInt()! - 1 let prev = current - 1 self.currentLevelLabel.text = String(current) self.prevLevelLabel.text = String(prev) self.currentLevelLabel.reloadInputViews() self.checkLevelVisible() } } func checkLevelVisible(){ self.nextLevelLabel.hidden = false self.prevLevelLabel.hidden = false if self.prevLevelLabel.text?.toInt() <= 0{ self.prevLevelLabel.hidden = true } else { if levelProvider.getLevelById(self.prevLevelLabel.text!.toInt()!).complete { self.prevLevelLabel.textColor = GradientAssistance.green() } else { self.prevLevelLabel.textColor = GradientAssistance.red() } } if self.nextLevelLabel.text!.toInt() > levelProvider.getLevels().count { self.nextLevelLabel.hidden = true } else { if levelProvider.getLevelById(self.nextLevelLabel.text!.toInt()!).complete { self.nextLevelLabel.textColor = GradientAssistance.green() } else { self.nextLevelLabel.textColor = GradientAssistance.red() } } } } <file_sep>/GameLogic/ButtonClass.swift // // ButtonClass.swift // GameLogic // // Created by Admin on 17.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit class ButtonClass: UIButton { var id: NSNumber? var srcId: NSNumber? let normalState = UIImage(named: "button_normal.png") let emptyState = UIImage(named: "button_empty.png") let normalTextColor = UIColor(red: (51/255), green: (51/255), blue: (51/255), alpha: 1) override func didAddSubview(subview: UIView) { } func setNormalState(){ self.setTitleColor(self.normalTextColor, forState: UIControlState.Normal) self.setBackgroundImage(self.normalState, forState: UIControlState.Normal) } func setEmptyState(){ self.setTitleColor(self.normalTextColor, forState: UIControlState.Normal) self.setBackgroundImage(self.emptyState, forState: UIControlState.Normal) } } <file_sep>/GameLogic/GameStatement.swift // // Statement.swift // GameLogic // // Created by Admin on 28.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import Foundation class GameStatement{ private var _levelId: Int! private var _score: Int! private var _firstRun: Bool! private var _hintCount: Int! init(levelId: Int, score: Int, first: Bool, count: Int){ self._levelId = levelId self._score = score self._firstRun = first self._hintCount = count } init(){ self._firstRun = true self._levelId = 1 self._score = 0 self._hintCount = 0; } func setCurrentLevel(id: Int) { self._levelId = id } func setCurrentScore(score: Int) { self._score = score } func setFirst(first: Bool) { self._firstRun = first } func setHintCount(count: Int!){ self._hintCount = count; } func getCurrentLevelId() -> Int! { return self._levelId! } func getCurrentScore() -> Int! { return self._score! } func getFirst() -> Bool{ return self._firstRun! } func getHintCount() -> Int! { return self._hintCount! } }<file_sep>/GameLogic/EmojiViewController.swift // // EmojiViewController.swift // GameLogic // // Created by Admin on 28.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit class EmojiViewController: UIViewController { @IBOutlet weak var emojiLabel1: EmojiLabel! @IBOutlet weak var emojiLabel2: EmojiLabel! @IBOutlet weak var emojiLabel3: EmojiLabel! @IBOutlet weak var emojiLabel4: EmojiLabel! @IBOutlet weak var emojiLabel5: EmojiLabel! @IBOutlet weak var emojiLabel6: EmojiLabel! @IBOutlet weak var paper1: UIImageView! @IBOutlet weak var paper2: UIImageView! @IBOutlet weak var paper3: UIImageView! @IBOutlet weak var paper4: UIImageView! @IBOutlet weak var paper5: UIImageView! @IBOutlet weak var paper6: UIImageView! override func drawLayer(layer: CALayer!, inContext ctx: CGContext!) { } override func viewDidLoad(){ let level = levelProvider.getLevelById(stmtProvider!.getCurrentLevelId()) //@TODO refactor that & business logic is temporary var Labels: Array<EmojiLabel!> = [] let random = arc4random_uniform(10) + 1 switch level.quest.count { case 1: if random > 5 { Labels.append(self.emojiLabel3) self.emojiLabel4.hidden = true self.paper4.hidden = true } else { Labels.append(self.emojiLabel4) self.emojiLabel3.hidden = true self.paper3.hidden = true } self.emojiLabel1.hidden = true self.emojiLabel2.hidden = true self.emojiLabel5.hidden = true self.emojiLabel6.hidden = true self.paper1.hidden = true self.paper2.hidden = true self.paper5.hidden = true self.paper6.hidden = true case 2: Labels.append(self.emojiLabel2) if random > 5 { Labels.append(self.emojiLabel5) self.emojiLabel4.hidden = true self.paper4.hidden = true } else { Labels.append(self.emojiLabel4) self.emojiLabel5.hidden = true self.paper5.hidden = true } self.emojiLabel1.hidden = true self.emojiLabel3.hidden = true self.emojiLabel6.hidden = true self.paper1.hidden = true self.paper3.hidden = true self.paper6.hidden = true case 3: if random > 5 { Labels.append(self.emojiLabel2) Labels.append(self.emojiLabel4) Labels.append(self.emojiLabel6) self.emojiLabel1.hidden = true self.emojiLabel3.hidden = true self.emojiLabel5.hidden = true self.paper1.hidden = true self.paper3.hidden = true self.paper5.hidden = true } else { Labels.append(self.emojiLabel1) Labels.append(self.emojiLabel3) Labels.append(self.emojiLabel5) self.emojiLabel2.hidden = true self.emojiLabel4.hidden = true self.emojiLabel6.hidden = true self.paper2.hidden = true self.paper4.hidden = true self.paper6.hidden = true } case 4: Labels.append(self.emojiLabel2) Labels.append(self.emojiLabel3) Labels.append(self.emojiLabel4) Labels.append(self.emojiLabel5) self.emojiLabel1.hidden = true self.paper1.hidden = true self.emojiLabel6.hidden = true self.paper6.hidden = true case 5: Labels.append(self.emojiLabel1) Labels.append(self.emojiLabel2) Labels.append(self.emojiLabel3) Labels.append(self.emojiLabel4) Labels.append(self.emojiLabel5) self.emojiLabel6.hidden = true self.paper6.hidden = true default: Labels.append(self.emojiLabel1) Labels.append(self.emojiLabel2) Labels.append(self.emojiLabel3) Labels.append(self.emojiLabel4) Labels.append(self.emojiLabel5) Labels.append(self.emojiLabel6) } for (index, emoji) in enumerate(level.quest) { Labels[index]?.setEmoji(emoji) } super.viewDidLoad() } override func didReceiveMemoryWarning() { } } <file_sep>/GameLogic/EmojiLabel.swift // // EmojiLabel.swift // GameLogic // // Created by Admin on 25.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit class EmojiLabel: UILabel { var emoji = "\u{1F6AB}" override func drawTextInRect(rect: CGRect) { self.font = UIFont.systemFontOfSize(36) self.textAlignment = NSTextAlignment.Center self.text = self.emoji super.drawTextInRect(rect) } func setEmoji(emoji: String){ let hex:String = emoji.stringByReplacingOccurrencesOfString("U+", withString: "0x") var start = NSScanner(string: hex) var result: UInt32 = 0 if start.scanHexInt(&result){ self.emoji = String(UnicodeScalar(result)) } } } <file_sep>/GameLogic/LevelProvider.swift // // LevelProvider.swift // GameLogic // // Created by Admin on 27.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import Foundation import SQLite private let _LevelProviderSharedInstance = LocalLevelProvider(repository: DatabaseInspector.getDatabase()) class LocalLevelProvider: LevelProviderProtocol { class var sharedInstance :LocalLevelProvider{ return _LevelProviderSharedInstance } let idExp = Expression<Int>("id") let answerExp = Expression<String>("answer") let questExp = Expression<String>("quest") let hintExp = Expression<String>("hint") let hintedExp = Expression<Bool>("hinted") let scoreExp = Expression<Int>("score") let completeExp = Expression<Bool>("complete") private var _repository: Database required init(source: AnyObject){ self._repository = source as Database } private var list: Array<Level> = [] required init(repository: AnyObject){ self._repository = repository as Database for row in self._repository["levels"]{ //TODO: levels as string reference to settings self.list.append( Level( id: row.get(self.idExp) as Int, answer: row.get(self.answerExp).uppercaseString as String, score: row.get(self.scoreExp) as Int, hint: row.get(self.hintExp) as String, hinted: row.get(self.hintedExp) as Bool, complete: row.get(self.completeExp) as Bool, quest: split(row.get(self.questExp), { $0 == ";"}) ) ) } } func getLevelById(id: Int) -> Level{ var filtered = list.filter({ m in m.id == id }) var lvl: Level = filtered.first! return lvl } func getLevels() -> Array<Level>{ return self.list } func setLevelComplete(id: Int){ self.list[id - 1].complete = true self._repository["levels"].filter(self.idExp == id).update(self.completeExp <- true)? } func setLevelHinted(id: Int){ self.list[id - 1].hinted = true self._repository["levels"].filter(self.idExp == id).update(self.hintedExp <- true)? } func updateLevel(level: Level){ self.list[level.id - 1] = level self._repository["levels"].filter(self.idExp == level.id).update( self.answerExp <- level.answer, self.questExp <- join(";", level.quest), self.scoreExp <- level.score, self.completeExp <- level.complete, self.hintExp <- level.hint )? } func levelExist(id: Int) -> Bool{ var filtered = list.filter({ m in m.id == id }) if(filtered.count != 0){ return true } return false } func getFirstIncomplete() -> Int{ var filtered = list.filter({ m in m.complete == false }) if(filtered.count == 0) { return -1 } else { return filtered.first!.id } } func setRepository(source: AnyObject){ self._repository = source as Database } func getRepository() -> AnyObject{ return self._repository } } <file_sep>/GameLogic/Gradients.swift // // Gradients.swift // GameLogic // // Created by Admin on 24.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit class GradientAssistance { var colorFrom:UIColor = UIColor.whiteColor() var colorTo:UIColor = UIColor.whiteColor() func cyanBlue() ->CAGradientLayer { self.colorTo = UIColor(red: (77/255), green: (178/255), blue: (182/255), alpha: 1) self.colorFrom = UIColor(red: (168/255), green: (227/255), blue: (240/255), alpha: 1) return self.getLayer() } func transparent()->CAGradientLayer{ self.colorTo = UIColor(red: 1, green: 1, blue: 1, alpha: 0) self.colorFrom = UIColor(red: 1, green: 1, blue: 1, alpha: 0) return self.getLayer() } class func green()-> UIColor{ return UIColor(red: (51/255), green: (153/255), blue: (0/255), alpha: 1) } class func red()-> UIColor{ return UIColor(red: (204/255), green: (51/255), blue: (0/255), alpha: 1) } class func alpha()-> UIColor{ return UIColor(red: (0/255), green: (0/255), blue: (0/255), alpha: 0) } func getLayer() -> CAGradientLayer{ var colors:Array <AnyObject> = [self.colorFrom.CGColor, self.colorTo.CGColor] var gradientLayer: CAGradientLayer = CAGradientLayer() gradientLayer.colors = colors return gradientLayer } }<file_sep>/GameLogic/AboutController.swift // // hintController.swift // GameLogic // // Created by Admin on 04.12.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit class aboutController: UIViewController { @IBOutlet weak var textLabel: UITextView! @IBOutlet weak var area: UILabel! @IBOutlet weak var aboutTitle: UILabel! override func viewDidLoad() { super.viewDidLoad() self.view.layer.shadowOpacity = 0.8 self.view.layer.shadowRadius = 3.0 self.view.layer.shadowColor = UIColor.blackColor().CGColor; self.view.layer.shadowOffset = CGSizeMake(0, 0); area.layer.cornerRadius = 2; area.clipsToBounds = true self.aboutTitle.text = NSLocalizedString("ABOUT_TITLE", comment: "") self.textLabel.text = NSLocalizedString("ABOUT_TEXT", comment: "") } override func didReceiveMemoryWarning() { } @IBAction func close(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } } <file_sep>/GameLogic/StatementProvider.swift // // StatementProvider.swift // GameLogic // // Created by Admin on 28.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import Foundation import SQLite class LocalStatementProvider: StatementProviderProtocol { struct Static { static var instance: LocalStatementProvider? } class func sharedInstance(db: Database) -> LocalStatementProvider { if(Static.instance == nil){ Static.instance = LocalStatementProvider(repository: db) } return Static.instance! } private var _repository: Database private let _statement: GameStatement private let idExp = Expression<Int>("id") private let currentlevelIdExp = Expression<Int>("levelId") private let currentScore = Expression<Int>("score") private let firstRunExp = Expression<Bool>("first") private let countExp = Expression<Int>("hint") required init(repository: AnyObject) { self._repository = repository as Database self._statement = GameStatement() for row in self._repository["statement"]{ self._statement.setCurrentLevel(row.get(self.currentlevelIdExp)) self._statement.setCurrentScore(row.get(self.currentScore)) self._statement.setFirst(row.get(self.firstRunExp)) self._statement.setHintCount(row.get(self.countExp)) } } func getGameStatement() -> GameStatement { return self._statement } func apply() -> Bool { if let insert = self._repository["statement"].filter(self.idExp == 1).update( self.currentlevelIdExp <- self._statement.getCurrentLevelId() , self.currentScore <- self._statement.getCurrentScore(), self.firstRunExp <- self._statement.getFirst(), self.countExp <- self._statement.getHintCount() ){ return true } return false } func setCurrentLevel(id: Int) { self.getGameStatement().setCurrentLevel(id) } func setCurrentScore(score: Int) { self.getGameStatement().setCurrentScore(score) } func setFirst(first: Bool) { self.getGameStatement().setFirst(first) } func setHintCount(count: Int){ self.getGameStatement().setHintCount(count) } func getCurrentLevelId() -> Int { return self.getGameStatement().getCurrentLevelId() } func getCurrentScore() -> Int { return self.getGameStatement().getCurrentScore() } func getFirst() -> Bool { return self.getGameStatement().getFirst() } func getHintCount() -> Int { return self.getGameStatement().getHintCount() } func setRepository(repository: AnyObject) { self._repository = repository as Database } func getRepository() -> AnyObject { return self._repository } }<file_sep>/GameLogic/CompleteController.swift import UIKit import AVFoundation import GameKit var countWH: Int = 0; class CompleteController: UIViewController { @IBOutlet weak var textLabel: UITextView! @IBOutlet weak var area: UILabel! @IBOutlet weak var scoreLabel: UITextView! @IBOutlet weak var completeButton: UIButton! var endGame = false var audioPlayer:AudioController? = AudioController() func roundToTens(x : Double) -> Int { return 10 * Int(round(x / 10.0)) } func submitScore() { var leaderboardID = "hangmovie" var sScore = GKScore(leaderboardIdentifier: leaderboardID) sScore.value = Int64(stmtProvider!.getCurrentScore()) let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer() GKScore.reportScores([sScore], withCompletionHandler: { (error: NSError!) -> Void in if error != nil { println(error.localizedDescription) } else { println("Score submitted") } }) } override func viewDidLoad() { super.viewDidLoad() self.audioPlayer?.setPlayerInstance(AVAudioPlayer()) self.view.layer.shadowOpacity = 0.8 self.view.layer.shadowRadius = 3.0 self.view.layer.shadowColor = UIColor.blackColor().CGColor; self.view.layer.shadowOffset = CGSizeMake(0, 0); area.layer.cornerRadius = 2; area.clipsToBounds = true let array = [ NSLocalizedString("GOOD_1", comment: "") , NSLocalizedString("GOOD_2", comment: "") , NSLocalizedString("GOOD_3", comment: "") , NSLocalizedString("GOOD_4", comment: "") ] self.completeButton.setTitle(NSLocalizedString("CONTINUE_BUTTON", comment: ""), forState: .Normal) let randomIndex = Int(arc4random_uniform(UInt32(array.count))) self.textLabel.text = array[randomIndex] self.scoreLabel.text = "0" // area.backgroundColor = GradientAssistance.alpha() } override func viewDidAppear(animated: Bool) { self.audioPlayer?.completeLevel() let levelId = stmtProvider!.getCurrentLevelId() let level = levelProvider.getLevelById(levelId) stmtProvider!.setFirst(false) //Logic run next or first uncomplete stmtProvider!.getGameStatement() if(!level.complete){ levelProvider.setLevelComplete(levelId) var calculatedScore: Int = 0 if(level.hinted) { calculatedScore = self.roundToTens(Double(level.score/2)) } else { calculatedScore = level.score } stmtProvider!.setCurrentScore(calculatedScore + stmtProvider!.getCurrentScore()) self.addScore(calculatedScore) self.submitScore() /* events */ if(level.id == 1 && !level.complete){ GKAchivementsHelper.getAchivement("hm_1st") } if(level.id == 10 && !level.complete){ GKAchivementsHelper.getAchivement("hm_10st") } if(level.id == 20 && !level.complete){ GKAchivementsHelper.getAchivement("hm_20lvl") } if(level.id == 30 && !level.complete){ GKAchivementsHelper.getAchivement("hm_30lvl") } if(level.id == 40 && !level.complete){ GKAchivementsHelper.getAchivement("hm_40lvl") } if(level.id == 50 && !level.complete){ GKAchivementsHelper.getAchivement("hm_50lvl") } if(level.id == 60 && !level.complete){ GKAchivementsHelper.getAchivement("hm_60lvl") } if(level.id == 70 && !level.complete){ GKAchivementsHelper.getAchivement("hm_70lvl") } if(level.id == 80 && !level.complete){ GKAchivementsHelper.getAchivement("hm_80lvl") } if(level.id == 90 && !level.complete){ GKAchivementsHelper.getAchivement("hm_90lvl") } if(level.id == 100 && !level.complete){ GKAchivementsHelper.getAchivement("hm_100lvl") GKAchivementsHelper.getAchivement("hm_flvl") } if(!level.hinted){ countWH++ } else { countWH = 0 } if(countWH == 3){ GKAchivementsHelper.getAchivement("hm_3lvl_wh") } if(countWH == 5){ GKAchivementsHelper.getAchivement("hm_5lvl_wh") } if(countWH == 10){ GKAchivementsHelper.getAchivement("hm_10lvl_wh") } if(countWH == 50){ GKAchivementsHelper.getAchivement("hm_50lvl_wh") } if(countWH == 100){ GKAchivementsHelper.getAchivement("hm_100lvl_wh") } } if(levelProvider.levelExist(levelId + 1) && !levelProvider.getLevelById(levelId + 1).complete){ stmtProvider!.setCurrentLevel(levelId + 1) } else { let last = levelProvider.getFirstIncomplete() if(last >= 0){ stmtProvider!.setCurrentLevel(last) } else { self.endGame = true stmtProvider!.setFirst(true) } } stmtProvider!.apply() } func addScore(score:Int){ dispatch.async.bg { var index = 0; while(index < score){ dispatch.sync.main { index = index + 1 self.scoreLabel.text = "\(index)" } } } } @IBAction func hideModalDialogue(sender: AnyObject) { if(self.endGame){ let vc = self.storyboard!.instantiateViewControllerWithIdentifier("completeGameController") as UIViewController self.showViewController(vc, sender: vc) } else { NSNotificationCenter.defaultCenter().postNotificationName("removeLevel", object: nil) let level = levelProvider.getLevelById(stmtProvider!.getCurrentLevelId()) let mainSrotyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) var viewController = mainSrotyboard.instantiateViewControllerWithIdentifier("gameViewController") as GameController UIApplication.sharedApplication().keyWindow?.rootViewController = viewController } } override func didReceiveMemoryWarning() { } @IBAction func toNext(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func inMenu(sender: AnyObject){ } }<file_sep>/GameLogic/Array.swift // // Array.swift // GameLogic // // Created by Admin on 28.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import Foundation extension Array { mutating func { for (idx, element) in enumerate(self){ if(includeElement(element)){ return idx } } return nil } }<file_sep>/GameLogic/SettingsController.swift // // NewGameController.swift // GameLogic // // Created by Admin on 26.01.15. // Copyright (c) 2015 Admin. All rights reserved. // import UIKit import GameKit class SettingsController: UIViewController, GKGameCenterControllerDelegate { @IBOutlet weak var area: UILabel! @IBOutlet weak var musicLabel: UILabel! @IBOutlet weak var soundLabel: UILabel! @IBOutlet weak var musicSwitch: UISwitch! @IBOutlet weak var soundSwitch: UISwitch! @IBOutlet weak var leadersTableButton: UIButton! @IBOutlet weak var backToMainButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.view.layer.shadowOpacity = 0.8 self.view.layer.shadowRadius = 3.0 self.view.layer.shadowColor = UIColor.blackColor().CGColor self.view.layer.shadowOffset = CGSizeMake(0, 0) area.layer.cornerRadius = 2 area.clipsToBounds = true self.musicLabel.text = NSLocalizedString("GAME_SETTINGS_MUSIC", comment: "") self.soundLabel.text = NSLocalizedString("GAME_SETTINGS_SOUND", comment: "") self.leadersTableButton.setTitle(NSLocalizedString("GAME_SETTINGS_TABLE", comment: ""), forState: .Normal) self.backToMainButton.setTitle(NSLocalizedString("GAME_SETTINGS_MAIN", comment: ""), forState: .Normal) self.musicSwitch.on = settingsProvider!.getMusic() as Bool self.soundSwitch.on = settingsProvider!.getSound() as Bool } override func viewDidAppear(animated: Bool) { } @IBAction func changeMusic(sender: UISwitch) { settingsProvider!.setMusic(sender.on) var rootVC = self.view.window!.rootViewController as? GameController if(!sender.on){ rootVC?.audioPlayer?.getPlayerInstance()?.stop() return; } rootVC?.audioPlayer?.getPlayerInstance()?.volume = 0.15 rootVC?.audioPlayer?.getPlayerInstance()?.play() } @IBAction func changeSound(sender: UISwitch) { settingsProvider!.setSound(sender.on) } @IBAction func Close(sender: UIButton) { self.dismissViewControllerAnimated(true, completion: nil) } func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!) { gameCenterViewController.dismissViewControllerAnimated(true, completion: nil) } @IBAction func showGameCenterTable(sender: AnyObject) { var gcVC: GKGameCenterViewController = GKGameCenterViewController() gcVC.gameCenterDelegate = self gcVC.viewState = GKGameCenterViewControllerState.Leaderboards gcVC.leaderboardIdentifier = "hangmovie" self.presentViewController(gcVC, animated: true, completion: nil) } @IBAction func backToMenu(sender: AnyObject) { var rootVC = self.view.window!.rootViewController as? GameController rootVC?.audioPlayer?.getPlayerInstance()?.stop() } }<file_sep>/GameLogic/SettingsProvider.swift // // SettingsProvider.swift // HangMovie // // Created by Admin on 05.02.15. // Copyright (c) 2015 Admin. All rights reserved. // import Foundation import SQLite class LocalSettingsProvider: SettingsProviderProtocol { private var _repository: Database private var _settings: GameSettings //Exp private var _idExp = Expression<Int>("id") private var _musicExp = Expression<Bool>("music") private var _soundExp = Expression<Bool>("sound") required init(repository: AnyObject) { self._repository = repository as Database self._settings = GameSettings() for row in self._repository["settings"]{ self._settings.setMusic(row.get(self._musicExp)) self._settings.setSound(row.get(self._soundExp)) } } func apply() -> Bool { if let insert = self._repository["settings"].filter(self._idExp == 1).update( self._musicExp <- self._settings.getMusic(), self._soundExp <- self._settings.getSound() ){ return true } return false; } func setRepository(repository: AnyObject) { self._repository = repository as Database } func setMusic(music: Bool){ self._settings.setMusic(music) } func setSound(sound: Bool){ self._settings.setSound(sound) } func getMusic() -> Bool { return self._settings.getMusic() } func getSound() -> Bool { return self._settings.getSound() } func getRepository() -> AnyObject { return self._repository } func getGameSettings() -> GameSettings { return self._settings } }<file_sep>/GameLogic/MainMenuController.swift // // MainMenuController.swift // GameLogic // // Created by Admin on 21.01.15. // Copyright (c) 2015 Admin. All rights reserved. // import UIKit import AVFoundation import GameKit var stmtProvider: LocalStatementProvider? = LocalStatementProvider.sharedInstance(DatabaseInspector.getDatabase()) var settingsProvider: LocalSettingsProvider? = LocalSettingsProvider(repository: DatabaseInspector.getDatabase()) class MainMenuController: UIViewController, GKGameCenterControllerDelegate { private let ANIMATION_DURATION = 0.5 @IBOutlet weak var continueButton: UIButton! @IBOutlet weak var newGame: UIButton! @IBOutlet weak var aboutGame: UIButton! @IBOutlet weak var soundButton: UIButton! @IBOutlet weak var musicButton: UIButton! @IBOutlet weak var cloud1: UIImageView! @IBOutlet weak var cloud2: UIImageView! @IBOutlet weak var cloud3: UIImageView! @IBOutlet weak var cloud4: UIImageView! @IBOutlet weak var cloud5: UIImageView! @IBOutlet weak var tree1: UIImageView! @IBOutlet weak var tree2: UIImageView! @IBOutlet weak var tree3: UIImageView! var audioPlayer:AudioController? = AudioController() var cloud1Animated:Bool = false var gcEnabled = Bool() // Stores if the user has Game Center enabled var gcDefaultLeaderBoard = String() // Stores the default leaderboardID /** Game center */ func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!) { gameCenterViewController.dismissViewControllerAnimated(true, completion: nil) } func authenticateLocalPlayer() { let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer() localPlayer.authenticateHandler = {(ViewController, error) -> Void in if((ViewController) != nil) { // 1 Show login if player is not logged in self.presentViewController(ViewController, animated: true, completion: nil) } else if (localPlayer.authenticated) { // 2 Player is already euthenticated & logged in, load game center self.gcEnabled = true // Get the default leaderboard ID localPlayer.loadDefaultLeaderboardIdentifierWithCompletionHandler({ (leaderboardIdentifer: String!, error: NSError!) -> Void in if error != nil { println(error) } else { self.gcDefaultLeaderBoard = leaderboardIdentifer } }) } else { // 3 Game center is not enabled on the users device self.gcEnabled = false println(error) } } } override func viewDidLoad() { super.viewDidLoad() self.authenticateLocalPlayer() self.audioPlayer?.setPlayerInstance(AVAudioPlayer()); if(stmtProvider!.getFirst()){ self.continueButton.hidden = true; } if(!settingsProvider!.getSound()){ self.soundButton.selected = true } if(!settingsProvider!.getMusic()){ self.musicButton.selected = true } //Localizable self.continueButton.setTitle(NSLocalizedString("CONTINUE_GAME", comment: ""), forState: .Normal) self.newGame.setTitle(NSLocalizedString("NEW_GAME", comment: ""), forState: .Normal) self.aboutGame.setTitle(NSLocalizedString("ABOUT_GAME", comment: ""), forState: .Normal) } override func viewDidAppear(animated: Bool) { self.audioPlayer!.mainTheme(1.0) UIView.animateWithDuration( 4, delay: 0.5, options: UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse, animations: { self.cloud1.center.x -= 10 self.cloud1.center.y -= 10 }, completion: { finished in }) UIView.animateWithDuration( 8, delay: 0.85, options: UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse, animations: { self.cloud2.center.x -= 20 self.cloud2.center.y += 10 }, completion: { finished in }) UIView.animateWithDuration( 6, delay: 0.5, options: UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse, animations: { self.cloud3.center.x += 30 }, completion: { finished in }) UIView.animateWithDuration( 6, delay: 0.5, options: UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse, animations: { self.cloud5.center.x -= 25 }, completion: { finished in }) UIView.animateWithDuration( 6, delay: 0.5, options: UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse, animations: { self.cloud4.center.x -= 15 }, completion: { finished in }) UIView.animateWithDuration( 2, delay: 0.4, options: UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse, animations: { self.tree2.center.x -= 5 }, completion: { finished in }) UIView.animateWithDuration( 1, delay: 0.2, options: UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse, animations: { self.tree3.center.x -= 3 }, completion: { finished in }) } @IBAction func continueGame(sender: UIButton) { self.audioPlayer?.getPlayerInstance()?.stop() self.audioPlayer?.cancel() self.play(false) } @IBAction func createNewGame(sender: UIButton) { if(!stmtProvider!.getFirst()){ let mainSrotyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let viewController:UIViewController = mainSrotyboard.instantiateViewControllerWithIdentifier("newGameModalController") as UIViewController self.presentViewController(viewController, animated: true, completion: nil) return } self.audioPlayer?.getPlayerInstance()?.stop() self.audioPlayer?.cancel() self.play(true) } func play(reset: Bool){ if(reset){ var db = DatabaseInspector.resetDatabase(false) //stmtProvider!.setSharedInstance() stmtProvider = LocalStatementProvider(repository: db); } let mainSrotyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) var viewController = mainSrotyboard.instantiateViewControllerWithIdentifier("gameViewController") as GameController UIApplication.sharedApplication().keyWindow?.rootViewController = viewController } @IBAction func musicChange(sender: UIButton) { settingsProvider!.setMusic(!settingsProvider!.getMusic()) if(settingsProvider!.apply()){ self.musicButton.selected = !settingsProvider!.getMusic() if(!settingsProvider!.getMusic()){ self.audioPlayer?.getPlayerInstance()?.stop() } else { self.audioPlayer?.getPlayerInstance()?.play() } } } @IBAction func soundChange(sender: UIButton) { settingsProvider!.setSound(!settingsProvider!.getSound()) if(settingsProvider!.apply()){ self.soundButton.selected = !settingsProvider!.getSound() } } } <file_sep>/GameLogic/ModalShadow.swift // // ModalShadow.swift // GameLogic // // Created by Admin on 05.12.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit class ModalShadow: UIView { @IBOutlet weak var subView: UIView! override func drawRect(rect: CGRect) { super.drawRect(rect) self.layer.shadowColor = UIColor.blackColor().CGColor self.layer.shadowOffset = CGSizeMake(5, 5) self.layer.shadowRadius = 5 } } <file_sep>/GameLogic/AnswerView.swift /// // AnswerView.swift // GameLogic // // Created by Admin on 14.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit import AVFoundation class AnswerView: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { var answerUsr:String = "" var button: UIButton? var level: Level! var device: String! @IBOutlet weak var answerCollection: UICollectionView! let reuseIdentifier = "answerCell" var srcIndex: Int = 0 var audioPlayer:AudioController? override func viewDidLoad() { super.viewDidLoad() self.level = levelProvider.getLevelById(stmtProvider!.getCurrentLevelId()) for character in enumerate(self.level.answer!){ self.answerUsr = self.answerUsr + " " } self.device = UIDevice.currentDevice().modelName self.answerCollection.layer.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0).CGColor self.audioPlayer = AudioController() NSNotificationCenter.defaultCenter().addObserver(self, selector:"update:", name: "changeAnswer", object: self.button) } override func viewDidDisappear(animated: Bool){ NSNotificationCenter.defaultCenter().removeObserver("changeAnswer") } func update(note: NSNotification){ let tmpButton = (note.object as UIButton) let buttonText = tmpButton.titleLabel?.text if var value:String? = buttonText { var insertResult = self.answerUsr.insertInSpace(value!, srcText: self.level!.answer) self.answerUsr = insertResult.string self.srcIndex = tmpButton.valueForKey("id") as Int self.answerCollection.reloadItemsAtIndexPaths([NSIndexPath(forRow: insertResult.index, inSection: 0)]) } if(self.answerUsr.lowercaseString == self.level.answer.lowercaseString){ self.completeThisLevel() } } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return countElements(self.level.answer) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { switch(self.device){ case "iPhone 6 Plus": return CGSizeMake(46, 59) case "iPhone 6": return CGSizeMake(36, 46) case "iPhone 5": return CGSizeMake(32, 41) case "iPhone 5s": return CGSizeMake(32, 41) case "iPhone 5c": return CGSizeMake(32, 41) default: return CGSizeMake(26, 33) } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as AnswerViewCell var letter:String = " " if (indexPath.row < countElements(self.answerUsr)) { letter = toString(self.answerUsr[indexPath.row]) } if (self.answerUsr[indexPath.row] == " "){ cell.answerButton.setEmptyState() } else { cell.answerButton.setNormalState() } if self.level.answer[indexPath.row] == " " { cell.layer.hidden = true return cell } cell.answerButton.setValue(self.srcIndex, forKey: "srcId") cell.answerButton.setValue(indexPath.row, forKey: "id") cell.answerButton.setTitle(letter, forState: UIControlState.Normal) return cell } @IBAction func toQuest(sender: UIButton) { if(sender.titleLabel?.text == " ") { return } self.audioPlayer!.cancel() let keyID:NSString = "id" let id: Int = sender.valueForKey(keyID) as Int let letter = self.answerUsr[Int(id)] NSNotificationCenter.defaultCenter().postNotificationName("changeQuest", object: sender) let start = self.answerUsr.substringToIndex(id) let end = self.answerUsr.substringFromIndex(id + 1) self.answerUsr = start + " " + end self.answerCollection.reloadItemsAtIndexPaths([NSIndexPath(forRow: id, inSection: 0)]) } func completeThisLevel(){ let vc = self.storyboard!.instantiateViewControllerWithIdentifier("completeModalController") as UIViewController self.showViewController(vc, sender: vc) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>/GameLogic/QuestViewCell.swift // // QuestViewCell.swift // GameLogic // // Created by Admin on 14.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit class QuestViewCell: UICollectionViewCell { @IBOutlet weak var questButton: ButtonClass! } <file_sep>/GameLogic/NewGameController.swift // // NewGameController.swift // GameLogic // // Created by Admin on 26.01.15. // Copyright (c) 2015 Admin. All rights reserved. // import UIKit class NewGameController: UIViewController { @IBOutlet weak var area: UILabel! @IBOutlet weak var sureText: UITextView! @IBOutlet weak var sureButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.sureText.text = NSLocalizedString("NEW_GAME_SURE", comment: "") self.sureButton.setTitle(NSLocalizedString("NEW_GAME_SURE_BUTTON", comment: ""), forState: .Normal) self.view.layer.shadowOpacity = 0.8 self.view.layer.shadowRadius = 3.0 self.view.layer.shadowColor = UIColor.blackColor().CGColor; self.view.layer.shadowOffset = CGSizeMake(0, 0); area.layer.cornerRadius = 2; area.clipsToBounds = true } @IBAction func Close(sender: UIButton) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func startNewGame(sender: UIButton) { MainMenuController().play(true) } } <file_sep>/GameLogic/GameScreenView.swift // // GameScreenView.swift // GameLogic // // Created by Admin on 24.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit class GameScreenView: UIView { override func drawRect(rect: CGRect) { var gradientLayer:CAGradientLayer = GradientAssistance().cyanBlue() gradientLayer.endPoint = CGPointMake(0, 1) gradientLayer.frame = self.bounds self.layer.insertSublayer(gradientLayer, atIndex: 0) } }<file_sep>/GameLogic/StatementProviderProtocol.swift // // StatementProviderProtocol.swift // GameLogic // // Created by Admin on 28.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import Foundation protocol StatementProviderProtocol { init(repository: AnyObject) func getGameStatement() -> GameStatement func apply() -> Bool func setRepository(repository: AnyObject) func getRepository() -> AnyObject }<file_sep>/GameLogic/SettingsProviderProtocol.swift // // SettingsProviderProtocol.swift // GameLogic // // Created by Admin on 27.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import Foundation protocol SettingsProviderProtocol { init(repository: AnyObject) func getGameSettings() -> GameSettings func apply() -> Bool func setRepository(repository: AnyObject) func getRepository() -> AnyObject }<file_sep>/GameLogic/LevelController.swift // // LevelController.swift // GameLogic // // Created by Admin on 01.12.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit class LevelController: UIViewController { @IBOutlet weak var mainView: UIView! @IBOutlet weak var nextLevel: UIButton! @IBOutlet weak var prevLevel: UIButton! @IBAction func goBack(sender: UIButton) { self.dismissViewControllerAnimated(true, completion: nil) } } <file_sep>/GameLogic/String.swift // // String.swift // GameLogic // // Created by Admin on 26.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit struct inserterComplete{ var index: Int var string: String } extension String{ func substringToIndex(Index:Int) -> String { return self.substringToIndex(advance(self.startIndex, Index)) } func substringFromIndex(Index:Int) -> String { return self.substringFromIndex(advance(self.startIndex, Index)) } func insertInSpace(char: String, srcText: String) -> inserterComplete{ var result = inserterComplete(index: countElements(self), string: self) for (index, character) in enumerate(self){ let start = advance(startIndex,index) let end = advance(startIndex, index + 1) let range = start..<end if(character == " " && (srcText[index] != " ")){ result.string = self.stringByReplacingCharactersInRange(range, withString: char) result.index = index return result } } result.string = self + char return result } subscript(integerIndex: Int) -> Character{ let index = advance(startIndex, integerIndex) return self[index] } subscript(integerRange: Range<Int>) -> String{ let start = advance(startIndex,integerRange.startIndex) let end = advance(startIndex, integerRange.endIndex) let range = start..<end return self[range] } mutating func shuffle() -> String{ var array = Array(self).map({String($0)}) for _ in 0..<10{ array.sort{ (_,_) in arc4random() < arc4random() } } return "".join(array) } } <file_sep>/GameLogic/QuestView.swift // // QuestView.swift // GameLogic // // Created by Admin on 14.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit import AVFoundation class QuestView: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{ var audioPlayer:AudioController? let reuseIdentifier = "questCell" var button: UIButton? var shuffled = levelProvider.getLevelById(stmtProvider!.getCurrentLevelId()).answer.shuffle().stringByReplacingOccurrencesOfString(" ", withString: "") var device: String! @IBOutlet weak var questCollection: UICollectionView! override func viewDidLoad() { self.audioPlayer = AudioController() super.viewDidLoad() self.device = UIDevice.currentDevice().modelName self.questCollection.layer.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0).CGColor NSNotificationCenter.defaultCenter().addObserver(self, selector:"update:", name: "changeQuest", object: self.button) } override func viewDidDisappear(animated: Bool){ NSNotificationCenter.defaultCenter().removeObserver("changeQuest") } func update(note: NSNotification){ let tmpButton = (note.object as UIButton) let buttonText = tmpButton.titleLabel?.text let srcId:Int = tmpButton.valueForKey("srcId") as Int if var value:String? = buttonText { let start = advance(self.shuffled.startIndex, srcId) let end = advance(self.shuffled.startIndex, srcId + 1) let range = start..<end self.shuffled = self.shuffled.stringByReplacingCharactersInRange(range, withString: value!) } self.questCollection.reloadItemsAtIndexPaths([NSIndexPath(forRow: srcId, inSection: 0)]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return countElements(self.shuffled) } //set value to collection func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { switch(self.device){ case "iPhone 6 Plus": return CGSizeMake(46, 59) case "iPhone 6": return CGSizeMake(36, 46) case "iPhone 5": return CGSizeMake(32, 41) case "iPhone 5s": return CGSizeMake(32, 41) case "iPhone 5c": return CGSizeMake(32, 41) default: return CGSizeMake(26, 33) } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as QuestViewCell var letter = toString(self.shuffled[indexPath.row]); if (letter == " "){ cell.questButton.setEmptyState() } else { cell.questButton.setNormalState() } cell.questButton.setTitle(letter, forState: UIControlState.Normal) cell.questButton.setValue(indexPath.row, forKey: "id") return cell } @IBAction func toAnswer(sender: UIButton) { if(sender.titleLabel?.text == " ") { return } self.audioPlayer!.click() let keyID:NSString = "id" let id: Int = sender.valueForKey(keyID) as Int let letter = self.shuffled[Int(id)] NSNotificationCenter.defaultCenter().postNotificationName("changeAnswer", object: sender) let start = self.shuffled.substringToIndex(id) let end = self.shuffled.substringFromIndex(id + 1) self.shuffled = start + " " + end self.questCollection.reloadItemsAtIndexPaths([NSIndexPath(forRow: id, inSection: 0)]) } } <file_sep>/GameLogic/Level.swift // // Level.swift // GameLogic // // Created by Admin on 26.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import Foundation class Level { var id: Int var answer: String! var score: Int var hint: String var hinted: Bool var complete: Bool var quest: Array<String> init(id: Int, answer: String, score: Int, hint: String, hinted: Bool, complete: Bool, quest: Array<String>){ self.id = id self.answer = answer self.score = score self.hint = hint self.hinted = hinted self.complete = complete self.quest = quest } } <file_sep>/GameLogic/CompleteGameController.swift // // NewGameController.swift // GameLogic // // Created by Admin on 26.01.15. // Copyright (c) 2015 Admin. All rights reserved. // import UIKit import Foundation class CompleteGameController: UIViewController { @IBOutlet weak var area: UILabel! @IBOutlet weak var completeButton: UIButton! @IBOutlet weak var completeText: UITextView! override func viewDidLoad() { super.viewDidLoad() self.completeText.text = NSLocalizedString("COMPLETE_GAME_TEXT", comment: "") self.completeButton.setTitle(NSLocalizedString("COMPLETE_GAME_BUTTON", comment: ""), forState: .Normal) self.view.layer.shadowOpacity = 0.8 self.view.layer.shadowRadius = 3.0 self.view.layer.shadowColor = UIColor.blackColor().CGColor; self.view.layer.shadowOffset = CGSizeMake(0, 0); area.layer.cornerRadius = 2; area.clipsToBounds = true } @IBAction func Close(sender: UIButton) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func rateUs(sender: AnyObject) { UIApplication.sharedApplication().openURL(NSURL(string: "http://itunes.com/apps/hangmovie")!) } @IBAction func exit(sender: AnyObject) { exit(0) } } <file_sep>/GameLogic/HintController.swift // // hintController.swift // GameLogic // // Created by Admin on 04.12.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit import StoreKit class hintController: UIViewController, SKPaymentTransactionObserver, SKProductsRequestDelegate { @IBOutlet weak var textLabel: UITextView! @IBOutlet weak var area: UILabel! @IBOutlet weak var image: UIImageView! /* payments */ @IBOutlet weak var Alert: UILabel! @IBOutlet weak var productTitle: UILabel! @IBOutlet weak var productDescription: UITextView! @IBOutlet weak var buyButton: UIButton! var product: SKProduct? var productID = "hamgmovie_p" ///end override func viewDidLoad() { super.viewDidLoad() self.Alert.hidden = true self.productTitle.hidden = true self.buyButton.hidden = true self.productDescription.hidden = true self.image.hidden = true self.textLabel.hidden = true self.productDescription.text = "" self.productTitle.text = NSLocalizedString("PRODUCT_LOADING",comment: "") self.Alert.text = NSLocalizedString("PRODUCT_ALERT",comment: "") self.buyButton.setTitle(NSLocalizedString("PRODUCT_BUY",comment: ""), forState: .Normal) self.view.layer.shadowOpacity = 0.8 self.view.layer.shadowRadius = 3.0 self.view.layer.shadowColor = UIColor.blackColor().CGColor; self.view.layer.shadowOffset = CGSizeMake(0, 0); area.layer.cornerRadius = 2; area.clipsToBounds = true let count = stmtProvider!.getHintCount() let level: Level = levelProvider.getLevelById(stmtProvider!.getCurrentLevelId()) if(count == 0 && !level.hinted){ self.Alert.hidden = false self.productTitle.hidden = false self.buyButton.hidden = false self.buyButton.enabled = false self.productDescription.hidden = false /** Payments */ SKPaymentQueue.defaultQueue().addTransactionObserver(self) getProductInfo() } else { if(!level.hinted){ stmtProvider!.setHintCount(count - 1) } self.textLabel.text = level.hint self.textLabel.hidden = false self.image.hidden = false self.textLabel.hidden = false self.image.hidden = false; levelProvider.setLevelHinted(level.id) } } func productsRequest(request: SKProductsRequest!, didReceiveResponse response: SKProductsResponse!) { var products = response.products if (products.count != 0) { product = products[0] as? SKProduct buyButton.enabled = true productTitle.text = product!.localizedTitle productDescription.text = product!.localizedDescription } else { productTitle.text = "Product not found" productDescription.hidden = true } products = response.invalidProductIdentifiers for product in products { println("Product not found: \(product)") } } override func didReceiveMemoryWarning() { } @IBAction func close(sender: AnyObject) { var gc = self.view.window?.rootViewController as GameController gc.hintCount.text = ("\(stmtProvider!.getHintCount())") self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func buyProduct(sender: AnyObject) { let payment = SKPayment(product: product) SKPaymentQueue.defaultQueue().addPayment(payment) } func getProductInfo(){ if SKPaymentQueue.canMakePayments() { let request = SKProductsRequest(productIdentifiers: NSSet(objects: self.productID)) request.delegate = self request.start() } else { productDescription.text = "Please enable In App Purchase in Settings" } } func unlockFeature() { stmtProvider!.setHintCount(5) stmtProvider!.apply() } func paymentQueue(queue: SKPaymentQueue!, updatedTransactions transactions: [AnyObject]!) { for transaction in transactions as [SKPaymentTransaction] { switch transaction.transactionState { case SKPaymentTransactionState.Purchased: self.unlockFeature() SKPaymentQueue.defaultQueue().finishTransaction(transaction) case SKPaymentTransactionState.Failed: SKPaymentQueue.defaultQueue().finishTransaction(transaction) default: break } } } } <file_sep>/GameLogic/DispatchAsync.swift // // DispatchAsync.swift // GameLogic // // Created by Admin on 08.12.14. // Copyright (c) 2014 Admin. All rights reserved. // import Foundation class dispatch { class async { class func bg(block: dispatch_block_t) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block) } class func main(block: dispatch_block_t) { dispatch_async(dispatch_get_main_queue(), block) } } class sync { class func bg(block: dispatch_block_t) { dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block) } class func main(block: dispatch_block_t) { if NSThread.isMainThread() { block() } else { dispatch_sync(dispatch_get_main_queue(), block) } } } } <file_sep>/GameLogic/BannerController.swift // // BannerController.swift // HangMovie // // Created by Admin on 31.03.15. // Copyright (c) 2015 Admin. All rights reserved. // import Foundation import iAd import UIKit class BannerController: ADBannerView, ADBannerViewDelegate{ var rootVS:GameController? /* * Banner */ func bannerViewWillLoadAd(banner: ADBannerView!) { self.rootVS = self.window?.rootViewController as GameController? self.delegate = self self.rootVS?.view.hidden = true //hide until ad loaded } func bannerViewDidLoadAd(banner: ADBannerView!) { // NSLog("bannerViewDidLoadAd") self.rootVS?.view.hidden = false //now show banner as ad is loaded } func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) { NSLog("banner failed to recieve ad with error:%@", error); } }<file_sep>/GameLogic/AnswerViewCell.swift // // AnswerViewCell.swift // GameLogic // // Created by Admin on 13.11.14. // Copyright (c) 2014 Admin. All rights reserved. // import UIKit class AnswerViewCell: UICollectionViewCell { @IBOutlet weak var answerButton: ButtonClass! }
1a74e3d8238dba92843e8cbb53a60da9894fb7d2
[ "Swift" ]
34
Swift
BusinessDuck/xdsioszxcvaqerfdadafsdf
bee5ed14ded83eb5b4652c0bccebba7f8978fc22
8c16723a3e1b045df4938eca4b1e22718d5fd481
refs/heads/master
<repo_name>k-21d/spring-cloud-demo<file_sep>/spring-cloud-config-server/src/main/resources/application.properties spring.application.name=config.server server.port=12345 spring.cloud.config.server.git.uri=<file_sep>/spring-cloud-client-application/src/main/java/com/k21d/springcloud/client/controller/SpringEventController.java package com.k21d.springcloud.client.controller; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.context.PayloadApplicationEvent; import org.springframework.context.event.EventListener; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class SpringEventController implements ApplicationEventPublisherAware { private ApplicationEventPublisher applicationEventPublisher; @GetMapping("/send/event") public String sendEvent(@RequestParam String message){ applicationEventPublisher.publishEvent(message); return System.currentTimeMillis()+"."; } @EventListener public void onMessage(PayloadApplicationEvent event){ System.out.println(event.getPayload()); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } } <file_sep>/spring-cloud-client-application/src/main/java/com/k21d/springcloud/client/annotation/RequestMappingMethodInvocationHandler.java package com.k21d.springcloud.client.annotation; import org.springframework.beans.factory.BeanFactory; import org.springframework.core.DefaultParameterNameDiscoverer; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.client.RestTemplate; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; public class RequestMappingMethodInvocationHandler implements InvocationHandler { private final String serviceName; private final DefaultParameterNameDiscoverer defaultParameterNameDiscoverer = new DefaultParameterNameDiscoverer(); private final BeanFactory beanFactory; public RequestMappingMethodInvocationHandler(String serviceName, BeanFactory beanFactory) { this.serviceName = serviceName; this.beanFactory = beanFactory; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { GetMapping getMapping = findAnnotation(method, GetMapping.class); if (getMapping != null){ String[] uri = getMapping.value(); StringBuilder urlBuilder = new StringBuilder("http://") .append(serviceName).append("/") .append(uri[0]); int count = method.getParameterCount(); String[] paramNames = defaultParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); Annotation[][] annotations = method.getParameterAnnotations(); StringBuilder queryString = new StringBuilder(); //方法注解集合 for (int i=0;i<count;i++){ Annotation[] paramAnnotation = annotations[i]; Class<?> paramType = parameterTypes[i]; RequestParam requestParam = (RequestParam) paramAnnotation[0]; if (requestParam!=null){ String paramName = paramNames[i]; String requestParamName = StringUtils.hasText(requestParam.value())?requestParam.value():paramName; String requestParamValue = String.class.equals(paramType) ?(String)args[i]:String.valueOf(args[i]); queryString.append("&") .append(requestParamName).append("=").append(requestParamValue); } if (StringUtils.hasText(queryString)){ urlBuilder.append("?").append(queryString); } String url = urlBuilder.toString(); //RestTemplate "loadBalanceTemplate" //获得BeanFactory RestTemplate loadBalanceTemplate = beanFactory.getBean("loadBalanceTemplate",RestTemplate.class); return loadBalanceTemplate.getForObject(url,method.getReturnType()); } } return null; } } <file_sep>/spring-cloud-server-application/src/main/java/com/k21d/springcloud/server/controller/RemoteApplicationEventReceiverController.java package com.k21d.springcloud.server.controller; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.context.PayloadApplicationEvent; import org.springframework.context.event.EventListener; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController public class RemoteApplicationEventReceiverController implements ApplicationEventPublisherAware { private ApplicationEventPublisher applicationEventPublisher; @PostMapping("/reveive/remote/event") public String receive(@RequestBody Map<String,Object> data){ //事件的发送者 String sender = (String) data.get("sender"); //事件的数据内容 String value = (String) data.get("value"); //事件类型 String type = (String) data.get("type"); //接收到对方内容,同样也要发送事件到本地做处理 applicationEventPublisher.publishEvent(value); return "revceived"; } public static class SenderRemoteAppEvent extends ApplicationEvent{ private final String sender; public SenderRemoteAppEvent(String sender,Object object) { super(object); this.sender = sender; } public String getSender() { return sender; } } @EventListener public void onEvent(SenderRemoteAppEvent event){ System.out.println(event.getSender()+":"+event); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } } <file_sep>/spring-cloud-auth-server/src/main/java/com/k21/springcloud/security/config/SecurityConfigurtation.java package com.k21.springcloud.security.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity //@EnableGlobalMethodSecurity public class SecurityConfigurtation extends WebSecurityConfigurerAdapter { @Bean public AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } @Override protected void configure(HttpSecurity http) throws Exception { } @Bean PasswordEncoder encoder(){ return new BCryptPasswordEncoder(); } @Bean public UserDetailsService userDetailsService(){ InMemoryUserDetailsManager memoryUserDetailsManager = new InMemoryUserDetailsManager(); memoryUserDetailsManager.createUser( User.builder().passwordEncoder(encoder()::encode) .username("admin") .password("123") .roles("ADMIN") .build()); return memoryUserDetailsManager; } } <file_sep>/spring-cloud-discovery/zk-client/src/main/resources/application.properties server.port=0 spring.application.name=zk-discovery-client<file_sep>/spring-cloud-server-application/src/main/resources/application.properties spring.application.name=spring-cloud-server-application server.port=0 spring.cloud.stream.rabbit.bindings.k21d.destination=kkk123<file_sep>/spring-cloud-client-application/src/main/java/com/k21d/springcloud/client/controller/MessageController.java package com.k21d.springcloud.client.controller; import com.k21d.springcloud.client.stream.SimpleMessageService; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.support.GenericMessage; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController public class MessageController { @Autowired private RabbitTemplate rabbitTemplate; @Autowired private SimpleMessageService simpleMessageService; @GetMapping public String send(@RequestParam String message){ rabbitTemplate.convertAndSend(message); return "ok"; } @GetMapping("/stream/send") public boolean streamSend(@RequestParam String message){ MessageChannel messageChannel = simpleMessageService.k21d(); Map<String,Object> headers = new HashMap<>(); headers.put("charset-encoding","UTF-8"); GenericMessage<String> msg = new GenericMessage<>(message,headers); return messageChannel.send(msg); } } <file_sep>/spring-cloud-servlet-gateway/src/main/resources/application.properties spring.application.name=spring-cloud-servlet-gateway server.port=7123
cde0af602f07c0a8735329ec0f4c526f9140530e
[ "Java", "INI" ]
9
INI
k-21d/spring-cloud-demo
430009e448943fdef65835cc2ae0d1d33160cf11
72e44dee27aa509a1f8e06339f1df0e099427946
refs/heads/master
<repo_name>rodrigomf24/mise<file_sep>/app/models/product.server.model.js 'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Product Schema */ var ProductSchema = new Schema({ name: { type: String, default: '', required: 'Please fill Product name', trim: true }, quantity: { type: Number, default: 0, required: 'Please fill Product quantity', trim: true }, upc: { type: String, default: '', required: 'Please fill Product upc(unique product code)', trim: true }, price: { type: Number, default: 0.0, required: 'Please fill Product price', trim: true }, cost: { type: Number, default: 0.0, required: 'Please fill Product cost', trim: true }, shipping: { type: Boolean, default: false, trim: true }, imageThumb: { type: String, default: '', required: 'Please select Product thumbnail image', trim: true }, image: { type: String, default: '', required: 'Please select Product image', trim: true }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Product', ProductSchema);
663ad84c6a01b7a5287bc89af43b89ca28ddc4af
[ "JavaScript" ]
1
JavaScript
rodrigomf24/mise
10bfa58acc0217da8bf085eeef9a2352a4f99b91
415d7f0bfb76badf1abdcb6dc161b0ca7dc5cfd8
refs/heads/master
<repo_name>andrew-inzer/repo<file_sep>/google-api-project/src/main/java/inzer/google/api/controllers/CloudStorageController.java package inzer.google.api.controllers; import com.google.api.services.storage.model.Bucket; import com.google.api.services.storage.model.StorageObject; import inzer.google.api.services.ICloudStorageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping(value = "/cloud-storage") public class CloudStorageController { @Autowired private ICloudStorageService service; @RequestMapping(value = "/get-buckets-list", method = RequestMethod.GET) public List<Bucket> getBucketsList() throws Exception { return service.getBucketsList(); } @RequestMapping(value = "/create-bucket", method = RequestMethod.GET) public void createBucket(@RequestParam(value = "bucketName", required = true) String bucketName) throws Exception { service.createBucket(bucketName); } @RequestMapping(value = "/delete-bucket", method = RequestMethod.GET) public void deleteBucket(@RequestParam(value = "bucketName", required = true) String bucketName) throws Exception { service.deleteBucket(bucketName); } @RequestMapping(value = "/get-bucket", method = RequestMethod.GET) public Bucket getBucket(@RequestParam(value = "bucketName", required = true) String bucketName) throws Exception { return service.getBucket(bucketName); } @RequestMapping(value = "/get-files-list", method = RequestMethod.GET) public List<StorageObject> getFilesList(@RequestParam(value = "bucketName", required = true) String bucketName) throws Exception { return service.getFilesList(bucketName); } @RequestMapping(value = "/upload-file", method = RequestMethod.GET) public void uploadFile( @RequestParam(value = "bucketName", required = true) String bucketName, @RequestParam(value = "filePath", required = true) String filePath ) throws Exception { service.uploadFile(bucketName, filePath); } @RequestMapping(value = "/delete-file", method = RequestMethod.GET) public void deleteFile( @RequestParam(value = "bucketName", required = true) String bucketName, @RequestParam(value = "fileName", required = true) String fileName ) throws Exception { service.deleteFile(bucketName, fileName); } @RequestMapping(value = "/download-file", method = RequestMethod.GET) public void downloadFile( @RequestParam(value = "bucketName", required = true) String bucketName, @RequestParam(value = "fileName", required = true) String fileName, @RequestParam(value = "destinationDirectory", required = true) String destinationDirectory ) throws Exception { service.downloadFile(bucketName, fileName, destinationDirectory); } } <file_sep>/google-api-project/src/main/resources/cloud-storage-secrets.properties project.id= account.id= private.key.path=<file_sep>/google-api-project/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>inzer.google.api</groupId> <artifactId>google-api-project</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>google-api-project Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <war.name>google-api-project</war.name> <org.springframework.version>4.1.2.RELEASE</org.springframework.version> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-storage</artifactId> <version>v1-rev18-1.19.0</version> </dependency> <dependency> <groupId>com.google.http-client</groupId> <artifactId>google-http-client-jackson2</artifactId> <version>1.17.0-rc</version> </dependency> <dependency> <groupId>com.google.oauth-client</groupId> <artifactId>google-oauth-client-jetty</artifactId> <version>1.17.0-rc</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.10.8</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>${war.name}</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.2</version> <configuration> <warName>${war.name}</warName> <packagingExcludes>**/classes/WEB-INF/,**/lib/</packagingExcludes> <failOnMissingWebXml>false</failOnMissingWebXml> <archive> <addMavenDescriptor>false</addMavenDescriptor> </archive> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.0</version> <configuration> <username>manager</username> <password><PASSWORD>> <url>http://localhost:8080/manager/text</url> <path>/${war.name}</path> <warFile>${basedir}/target/${war.name}.war</warFile> <update>true</update> <ignorePackaging>true</ignorePackaging> </configuration> <executions> <execution> <id>tomcat-deploy</id> <phase>install</phase> <goals> <goal>deploy</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
adf92dc8e31adef4ae00a930de7414a4b2d43fbc
[ "Java", "Maven POM", "INI" ]
3
Java
andrew-inzer/repo
587a3ca7499b07e4a79e6d4a1029fecdf621aa47
34f8cb7096063ea5018abaadb9dbae93ff620ea6
refs/heads/master
<file_sep>Content Discussed : How to Connect MySQL DB from Node.js, Execute MySQL Query From Node.js, Use of MySQL Store Procedure in Node.js. Before Running this Project Install npm packages using 'npm install' command. Configure MySQL DB Configuration as per yours. <file_sep>Content Discussed : How to Connect MySQL DB from Node.js Execute MySQL Query From Node.js Use of MySQL Store Procedure in Node.js. Before Running this Project Install npm packages using 'npm install' command. Configure MySQL DB Configuration as per yours.
e2b31fc137144ecd4eedfdab8cadac845f4469ef
[ "Markdown", "JavaScript" ]
2
Markdown
Ggoings/MySQL
8d0712772a5c175cdd0ae1571b8e1da0bb2fe631
f66d12ab59b228abcdf6abc5106fd75e51e15f59
refs/heads/master
<repo_name>dalepotter/auto-tickspot-templater<file_sep>/autoTimeAdder.php <?php // Show errors ini_set('display_errors',1); ini_set('display_startup_errors',1); error_reporting(-1); // Include the configuration file require 'config.php'; // Set available projects/tasks $taskIDs = array( 5664072 => "IATI/Tools and Utilities (Registry, Datastore, websites, publishing tools, etc.)", 6894543 => "DIPR Internal meetings", 7186258 => "DIPR general HR (incl 121s, appraisal, pdp's and objective setting)", ); // Set template for tasks done during the week $weeklyTasks = array( array( 'day' => 'Monday', 'task' => "IATI/Tools and Utilities (Registry, Datastore, websites, publishing tools, etc.)", 'hours' => 6 ), array( 'day' => 'Monday', 'task' => "DIPR general HR (incl 121s, appraisal, pdp's and objective setting)", 'hours' => 1, 'notes' => "Dale/Joni 1-to-1" ), array( 'day' => 'Tuesday', 'task' => "IATI/Tools and Utilities (Registry, Datastore, websites, publishing tools, etc.)", 'hours' => 7 ), array( 'day' => 'Wednesday', 'task' => "IATI/Tools and Utilities (Registry, Datastore, websites, publishing tools, etc.)", 'hours' => 7 ), array( 'day' => 'Thursday', 'task' => "IATI/Tools and Utilities (Registry, Datastore, websites, publishing tools, etc.)", 'hours' => 7 ), array( 'day' => 'Friday', 'task' => "IATI/Tools and Utilities (Registry, Datastore, websites, publishing tools, etc.)", 'hours' => 7 ), ); // Set the date for the week beginning $weekBeginning = "Monday this week"; //$weekBeginning = "2015-04-20"; // Enables a specific week start date to be set // Loop over each element in $weeklyTasks to append the task ID foreach($weeklyTasks as $key => $task){ // Find the relevant task ID and append to the array $weeklyTasks[$key]['taskId'] = array_search($task['task'], $taskIDs); // Set notes to an empty string if not set if ( !isset($weeklyTasks[$key]['notes']) ){ $weeklyTasks[$key]['notes'] = ""; } } // Add each task to tickspot for this week // Get the timestamp for the week that the entries are to be added on $timestampWeekStart = strtotime($weekBeginning); // Set extra details for the tickspot API call $apiEndpoint = "https://www.tickspot.com/26859/api/v2/entries.json"; $apiUserAgent = "AutoTimeAdder (" . userEmail . ")"; // Loop over each $weeklyTask and send an API request (via POST) to add foreach($weeklyTasks as $task){ // Build the data array $data = array( 'date' => date( 'Y-m-d', strtotime($task['day'], $timestampWeekStart) ), 'hours' => $task['hours'], 'notes' => $task['notes'], 'task_id' => $task['taskId'], 'user_id' => tickspotUserId, ); // Encode data to a JSON format string $dataJson = json_encode($data); // Set the headers for the request $headers = array( "Content-Type: application/json", "Authorization: Token token=" . tickspotApiKey, "User-Agent: " . $apiUserAgent ); // Set-up a cURL object $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $apiEndpoint); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, $dataJson); curl_setopt($curl, CURLOPT_VERBOSE, true); // Execute the request and print result to the browser $result = curl_exec($curl); echo "Entered:" . $result . "<br/>"; // End: foreach($weeklyTasks as $task) } ?><file_sep>/config.php <?php // Set the email that you use for your Tickspot account // This will likely be an alphanumeric code define("userEmail", "YOUR-EMAIL-ADDRESS"); // Set Tickspot API key - Instructions on obtaining your API key here: https://github.com/tick/tick-api/blob/master/sections/roles.md define("tickspotApiKey", "YOUR-TICKSPOT-API-KEY"); // Set Tickspot user ID - Instructions on obtaining your user ID here: https://github.com/tick/tick-api/blob/master/sections/roles.md // This will likely be a large integer define("tickspotUserId", "YOUR-USER-ID"); ?><file_sep>/README.md # auto-tickspot-templater Script to automatically add a 'template' of activities to your Tickspot account using their API
8f02b9b40b187a21175c19bd690c44238f0e23c4
[ "Markdown", "PHP" ]
3
PHP
dalepotter/auto-tickspot-templater
97fb85950b785100d1309860b2b8decad2d65da5
048b3cb6026383a9761cb03770655a4f86474c0f
refs/heads/main
<repo_name>YR2368044/shop_mall<file_sep>/src/store/actions.js export default { addCart(context, payload){ return new Promise((resolve, reject) => { // payload 为新添加的商品。购物车中不能添加重复的商品, // 如果重复的话只是将数量 +1 即可,所以要进行判断 // 法一:for...of 循环 // let oldProduct = null // for (let item of state.cartList) { // if (item.iid === payload.iid) { // oldProduct = item // } // } // if (oldProduct) { // oldProduct.count += 1 // }else{ // payload.count = 1 // state.cartList.push(payload) // } // 法二:find方法 // 1.查找之前数组中是否有该商品 let oldProduct = context.state.cartList.find(item => item.iid === payload.iid) // 2.判断 if (oldProduct) { // 不要在 actions 中直接修改 state,通过 mutations 修改 // oldProduct.count += 1 //任务一:添加数量 context.commit("addCounter", oldProduct) resolve("当前的商品数量+1") }else{ payload.count = 1 // 不要在 actions 中直接修改 state,通过 mutations 修改 // context.state.cartList.push(payload) //任务二:添加商品 context.commit("addToCart", payload) resolve("添加购物车成功") } }) } }<file_sep>/src/store/mutations.js export default { // mutations 唯一的目的就是修改 state,其中每个方法的任务尽可能要单一 // 异步操作 和 复杂判断逻辑 都放在 actions 中 addCounter(state, payload){ //可以在开发工具中跟踪 payload.count++ }, addToCart(state, payload){ // 记录 购物车的商品是否被选中 应该在商品的对象中添加属性来记录, // checked 属性表示是否被选中,默认为选中 payload.checked = true state.cartList.push(payload) } }
92ee2d8d201185a01dffe2906e2b3ae18b6d4076
[ "JavaScript" ]
2
JavaScript
YR2368044/shop_mall
a4fb190de2b05c7a13f62736ab80b473663e2812
2ffef9471531e22db9e6a74a00a6de8395f502fe
refs/heads/master
<file_sep>(function() { 'use strict'; var module = angular.module('app.admin', ['app.admin.news', 'app.admin.files' ,'app.admin.contacts']); angular.module('app').config(configure); /* @ngInject */ function configure($routeProvider) { } })(); <file_sep>(function () { 'use strict'; var module = angular.module('app.admin.news', []); angular.module('app').config(configure); /* @ngInject */ function configure($routeProvider) { $routeProvider.when('/admin/news/news-vew', { templateUrl: 'app/admin/news/news-vew.html', controller: 'NewsAdminViewController' }); $routeProvider.when('/admin/news/news-create', { templateUrl: 'app/admin/news/news-create.html', controller: 'NewsAdminCreateController' }); $routeProvider.when('/admin/news/news-edit/:id', { templateUrl: 'app/admin/news/news-edit.html', controller: 'NewsAdminEditController' }); } })(); <file_sep>package com.chieftain.agency.dao.accesstoken; import com.chieftain.agency.dao.Dao; import com.chieftain.agency.entity.AccessToken; public interface AccessTokenDao extends Dao<AccessToken, Long> { AccessToken findByToken(String accessTokenString); } <file_sep>package com.chieftain.agency.dao.userinquiries; import com.chieftain.agency.dao.JpaDao; import com.chieftain.agency.entity.UserInquiries; public class JpaUserInquiriesDao extends JpaDao<UserInquiries, Long> implements UserInquiriesDao { public JpaUserInquiriesDao() { super(UserInquiries.class); } } <file_sep>(function () { 'use strict'; angular.module('app.contacts').factory('ContactsService', ContactsService); /* @ngInject */ function ContactsService($resource) { return $resource('rest/contacts'); } })();<file_sep>(function () { 'use strict'; angular.module('app.admin.news').controller('FilesAdminViewController', FilesAdminViewController); /* @ngInject */ function FilesAdminViewController($scope, $location, FilesAdminService) { $scope.people = FilesAdminService.query(); $scope.curentRow = null; $scope.updateDisabled = true; $scope.columns = [{ text: 'name', datafield: 'name', width: 200, cellsalign: 'left', align: 'left' }, { text: 'url', datafield: 'url', width: 400, cellsalign: 'left', align: 'left' }, { text: 'effectiveDate', datafield: 'effectiveDate', width: 400, cellsalign: 'left', align: 'left' }]; $scope.settings = { width: "100%", height: "100%", altrows: true, sortable: true, selectionmode: "singlerow", pageable: true, pagesize: 20, columnsresize: true, showtoolbar: false, enablebrowserselection: true, source: $scope.people, columns: $scope.columns }; $scope.refresh = function () { $scope.people = FilesAdminService.query(); $scope.settings.source = $scope.people; }; $scope.create = function () { $location.path('/admin/files/files-create'); }; $scope.delete = function () { // $scope.curentRow.$remove(function() { // $scope.refresh(); // }); }; } })();<file_sep><!--<ol class="breadcrumb">--> <!--<li class="breadcrumb-item active">{{ 'INDEX_ABOUT_MENU_ITEM' |--> <!--translate }}</li>--> <!--</ol>--> <p class="">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p class="">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p class="">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p class="">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p class="">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><file_sep>(function() { 'use strict'; var module = angular.module('app.admin.files', []); angular.module('app').config(configure); /* @ngInject */ function configure($routeProvider) { $routeProvider.when('/admin/files/files-vew', { templateUrl : 'app/admin/files/files-vew.html', controller : 'FilesAdminViewController' }); $routeProvider.when('/admin/files/files-create', { templateUrl : 'app/admin/files/files-create.html', controller : 'FilesAdminCreateController' }); } })(); <file_sep>(function() { 'use strict'; var module = angular.module('app.about', []); angular.module('app').config(configure); /* @ngInject */ function configure($routeProvider) { $routeProvider.when('/about', { templateUrl : 'app/about/about.html' }); } })(); <file_sep>(function () { 'use strict'; angular.module('app.admin.news').controller('NewsAdminViewController', NewsAdminViewController); /* @ngInject */ function NewsAdminViewController($scope, $location, NewsAdminService) { $scope.people = NewsAdminService.query(); $scope.curentRow = null; $scope.updateDisabled = true; $scope.columns = [{ text: 'language', datafield: 'language', width: 200, cellsalign: 'left', align: 'left' }, { text: 'publishDate', datafield: 'publishDate', cellsformat: 'd', width: 200, cellsalign: 'left', align: 'left' }, { text: 'title', datafield: 'title', width: 200, cellsalign: 'left', align: 'left' }, { text: 'published', datafield: 'published', width: 200, cellsalign: 'left', align: 'left' }, { text: 'author', datafield: 'author', width: 200, cellsalign: 'left', align: 'left' }, { text: 'shortContent', datafield: 'shortContent', width: 350, cellsalign: 'left', align: 'left' }]; $scope.settings = { width: "100%", height: "100%", altrows: true, sortable: true, selectionmode: "singlerow", pageable: true, pagesize: 20, columnsresize: true, showtoolbar: false, source: $scope.people, rowselect: function (event) { $scope.updateDisabled = false; $scope.curentRow = NewsAdminService.get({ id: event.args.row.id }); }, columns: $scope.columns }; $scope.refresh = function () { $scope.people = NewsAdminService.query(); $scope.settings.source = $scope.people; }; $scope.create = function () { $location.path('/admin/news/news-create'); }; $scope.edit = function () { $location.path('/admin/news/news-edit/' + $scope.curentRow.id); }; $scope.delete = function () { $scope.curentRow.$remove(function () { $scope.refresh(); }); }; } })();<file_sep>package com.chieftain.agency.dao.subscriptions; import com.chieftain.agency.dao.JpaDao; import com.chieftain.agency.entity.Subscriptions; public class JpaSubscriptionsDao extends JpaDao<Subscriptions, Long> implements SubscriptionsDao { public JpaSubscriptionsDao() { super(Subscriptions.class); } } <file_sep>(function() { 'use strict'; angular.module('app.news').factory('NewsTopItemService', NewsTopItemService); /* @ngInject */ function NewsTopItemService($rootScope, $resource) { return $resource('rest/news/top/:lang'); } })();<file_sep>(function() { 'use strict'; angular.module('app.icolist').controller('IcoListListController', IcoListListController); /* @ngInject */ function IcoListListController($rootScope, $scope, IcoListService) { $scope.items = IcoListService.query(); } })();<file_sep>(function() { 'use strict'; var module = angular.module('app.news', []); angular.module('app').config(configure); /* @ngInject */ function configure($routeProvider) { $routeProvider.when('/news', { templateUrl : 'app/news/news-list.html', controller : 'NewsListController' }); $routeProvider.when('/news_view/:id', { templateUrl : 'app/news/news-view.html', controller : 'NewsViewController' }); } })(); <file_sep>package com.chieftain.agency.rest.resources; import com.chieftain.agency.dao.news.NewsDao; import com.chieftain.agency.entity.News; import com.chieftain.agency.transfer.NewsDto; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; @Component @Path("/admin/news") public class NewsAdminResource { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private NewsDao newsDao; @Autowired private ModelMapper modelMapper; @GET @Produces(MediaType.APPLICATION_JSON) public List<NewsDto> list() throws IOException { this.logger.info("list()"); List<News> allEntries = this.newsDao.findAll(); return allEntries.stream().map(allEntry -> convertToDto(allEntry)).collect(Collectors.toList()); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("{id}") public NewsDto read(@PathParam("id") Long id) { this.logger.info("read(id)"); News item = this.newsDao.find(id); if (item == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return convertToDto(item); } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public NewsDto create(NewsDto icoItem) { this.logger.info("create(): " + icoItem); News item = null; item = this.newsDao.save(convertFromDto(icoItem)); return convertToDto(item); } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("{id}") public NewsDto update(@PathParam("id") Long id, NewsDto icoItem) { this.logger.info("update(): " + icoItem); News item = this.newsDao.save(convertFromDto(icoItem)); return convertToDto(item); } @DELETE @Produces(MediaType.APPLICATION_JSON) @Path("{id}") public void delete(@PathParam("id") Long id) { this.logger.info("delete(id)"); this.newsDao.delete(id); } private NewsDto convertToDto(News news) { NewsDto icoListDto = modelMapper.map(news, NewsDto.class); return icoListDto; } private News convertFromDto(NewsDto newstDto) { News news = modelMapper.map(newstDto, News.class); return news; } } <file_sep># rating-agency Project created to support all around crypto rating agency activities. Has initial integration, and newsletter support. To install Client run: npm install To run project: mnv resources:resources jetty:run To run liquibase: mnv resources:resources liquibase:update To package: mvn clean package Default url: http://localhost:8080/ admin UI: http://localhost:8080/login user: admin password: <PASSWORD> To run mysql in docker container use docker run --detach --name=test-mysql --env="MYSQL_ROOT_PASSWORD=<PASSWORD>" -p 3308:3306 mysql <file_sep>(function() { 'use strict'; angular.module('app.admin.news').factory('NewsAdminService', NewsAdminService); /* @ngInject */ function NewsAdminService($resource) { return $resource('rest/admin/news/:id', { id : '@id' }); } })();<file_sep>(function() { 'use strict'; angular.module('app.currencies').controller('CurrenciesListController', CurrenciesListController); /* @ngInject */ function CurrenciesListController($rootScope, $scope, CurrenciesService) { $scope.items = CurrenciesService.query(); } })();<file_sep>(function () { 'use strict'; angular.module('app.main').controller('MainController', MainController); /* @ngInject */ function MainController($scope, $rootScope, MainPageService) { $scope.newsItems = MainPageService.query({url: "news", lang: $rootScope.lang}); $scope.currencyItems = MainPageService.query({url: "currencies"}); $scope.icoListItems = MainPageService.query({url: "icos"}); $rootScope.$on('$translateChangeSuccess', function (event, data) { $scope.newsItems = MainPageService.query({url: "news", lang: $rootScope.lang}); $scope.currencyItems = MainPageService.query({url: "currencies"}); $scope.icoListItems = MainPageService.query({url: "icos"}); }); } })();<file_sep>(function () { 'use strict'; angular.module('app.contacts').controller('ContactsCreateController', ContactsCreateController); /* @ngInject */ function ContactsCreateController($scope, $route, ContactsService) { $scope.newsItem = new ContactsService(); $scope.newsItem.name = null; $scope.newsItem.email = null; $scope.newsItem.comment = null; $scope.ok = function () { $scope.newsItem.$save(function () { $route.reload(); }); }; } })();<file_sep>package com.chieftain.agency.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.sql.Timestamp; @JsonIgnoreProperties(ignoreUnknown = true) public class IcoWatchEntity { @JsonProperty("name") private String name; @JsonProperty("image") private String image; @JsonProperty("description") private String description; @JsonProperty("website_link") private String websiteLink; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonProperty("start_time") private Timestamp startTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonProperty("end_time") private Timestamp endTime; @JsonProperty("timezone") private String timezone; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getWebsiteLink() { return websiteLink; } public void setWebsiteLink(String websiteLink) { this.websiteLink = websiteLink; } public Timestamp getStartTime() { return startTime; } public void setStartTime(Timestamp startTime) { this.startTime = startTime; } public Timestamp getEndTime() { return endTime; } public void setEndTime(Timestamp endTime) { this.endTime = endTime; } public String getTimezone() { return timezone; } public void setTimezone(String timezone) { this.timezone = timezone; } } <file_sep>(function() { 'use strict'; var module = angular.module('app.translation', []); angular.module('app').config(configure); /* @ngInject */ function configure($routeProvider, $translateProvider) { $translateProvider.useStaticFilesLoader({ prefix : 'app/translations/', suffix : '.json' }).preferredLanguage('en').useLocalStorage(); } angular.module('app').run(run); /* @ngInject */ function run($rootScope, $location, $cookieStore, UserService, matchmedia) { $rootScope.lang = 'en'; $rootScope.default_float = 'left'; $rootScope.opposite_float = 'right'; $rootScope.default_direction = 'ltr'; $rootScope.opposite_direction = 'rtl'; } })(); <file_sep>db.username=agnc_user db.password=<PASSWORD> db.driver=com.mysql.jdbc.Driver db.url=jdbc:mysql://127.0.0.1:3308/agnc?characterEncoding=UTF-8&useUnicode=true db.removeAbandoned=true db.initialSize=1 db.maxActive=5 app.secret=fgfdhgfgfadsfdss5erbfd spring.freemarker.cache=false multipart.maxFileSize=-1 multipart.maxRequestSize=1024Mb cloud.aws.credentials.accessKey= cloud.aws.credentials.secretKey= cloud.aws.region= cloud.aws.s3.bucket=<file_sep>CREATE USER 'agnc'@'localhost' IDENTIFIED BY 'g4sGfdTbT23'; CREATE USER 'agnc'@'%' IDENTIFIED BY 'g4sGfdTbT23'; CREATE DATABASE agnc CHARACTER SET utf8 COLLATE utf8_general_ci; GRANT ALL PRIVILEGES ON agnc.* TO 'agnc'@'localhost'; GRANT ALL PRIVILEGES ON agnc.* TO 'agnc'@'%'; CREATE USER 'agnc_user'@'localhost' IDENTIFIED BY 'tmuL4svR76d'; CREATE USER 'agnc_user'@'%' IDENTIFIED BY 'tmuL4svR76d'; GRANT DELETE ON agnc.* TO 'agnc_user'@'localhost'; GRANT DELETE ON agnc.* TO 'agnc_user'@'%'; GRANT INSERT ON agnc.* TO 'agnc_user'@'localhost'; GRANT INSERT ON agnc.* TO 'agnc_user'@'%'; GRANT SELECT ON agnc.* TO 'agnc_user'@'localhost'; GRANT SELECT ON agnc.* TO 'agnc_user'@'%'; GRANT UPDATE ON agnc.* TO 'agnc_user'@'localhost'; GRANT UPDATE ON agnc.* TO 'agnc_user'@'%';<file_sep>(function () { 'use strict'; var app = angular.module('app'); var appConfig = { useAccessTokenHeader: true, debug: true }; app.value('appConfig', appConfig); app.config(configure); app.filter("trust", ['$sce', function ($sce) { return function (htmlCode) { return $sce.trustAsHtml(htmlCode); } }]); /* @ngInject */ function configure($locationProvider, $httpProvider) { $locationProvider.hashPrefix('!'); $httpProvider.interceptors.push(function ($q, $rootScope, $location) { return { 'responseError': function (rejection) { var status = rejection.status; var config = rejection.config; var statusText = rejection.statusText; // var method = config.method; // var url = config.url; if ($rootScope.firstCall !== true) { if (status == 401) { $location.path("/login"); } else { // $rootScope.error = method + " on " + url // + " failed with status " + status; $rootScope.error = statusText; } } else { $rootScope.firstCall = false; } return $q.reject(rejection); } }; }); $httpProvider.interceptors .push(function ($q, $rootScope, $location) { return { 'request': function (config) { var isRestCall = config.url.indexOf('rest') == 0; if (isRestCall && angular .isDefined($rootScope.accessToken)) { var accessToken = $rootScope.accessToken; if (appConfig.useAccessTokenHeader) { config.headers['X-Access-Token'] = accessToken; } else { config.url = config.url + "?token=" + accessToken; } } return config || $q.when(config); } }; }); // $.jqx.theme = 'darkblue'; $.jqx.theme = 'orange'; } app.run(run); /* @ngInject */ function run($rootScope, $location, $cookieStore, UserService, matchmedia) { $rootScope.$on('$viewContentLoaded', function () { delete $rootScope.error; }); $rootScope.hasRole = function (role) { if ($rootScope.user === undefined) { return false; } if ($rootScope.user.roles[role] === undefined) { return false; } return $rootScope.user.roles[role]; }; $rootScope.logout = function () { delete $rootScope.user; delete $rootScope.accessToken; $cookieStore.remove('accessToken'); $location.path("/login"); }; var originalPath = $location.path(); var accessToken = $cookieStore.get('accessToken'); if (accessToken !== undefined) { $rootScope.accessToken = accessToken; $rootScope.firstCall = true; UserService.get(function (user) { $rootScope.user = user; $location.path(originalPath); $rootScope.firstCall = false; }); } $rootScope.initialized = true; $rootScope.phone = matchmedia.isPhone(); } app.directive('elSize', ['$parse', function ($parse) { return function (scope, elem, attrs) { var fn = $parse(attrs.elSize); scope.$watch(function () { // console.log(($(".footer").height() + elem.height() + 60)); // console.log($(window).height()); if (($(".footer").height() + elem.height() + 60) >= $(window).height()) { $(".footer").removeClass("footer-fixed"); $(".footer").addClass("footer-relative"); } else { $(".footer").addClass("footer-fixed"); $(".footer").removeClass("footer-relative"); } if ($(window).width() < 992) { $("#main-menu").attr("data-toggle", "collapse"); $("#main-menu").attr("data-target", "#navbar-collapse"); } return {width: elem.width(), height: elem.height()}; }, function (size) { fn.assign(scope, size); }, true); } }]); }) (); <file_sep>(function() { 'use strict'; var module = angular.module('app.contacts', []); angular.module('app').config(configure); /* @ngInject */ function configure($routeProvider) { $routeProvider.when('/contacts', { templateUrl : 'app/contacts/contacts.html', controller : 'ContactsCreateController' }); } })(); <file_sep>(function () { 'use strict'; angular.module('app.admin.news').controller('NewsAdminCreateController', NewsAdminCreateController); /* @ngInject */ function NewsAdminCreateController($scope, $location, NewsAdminService) { var countries = [{ value: "ru", label: "Russian" }, { value: "en", label: "English" }]; $scope.comboBoxSettings = { created: function (args) { args.instance.focus(); }, source: countries, width: 230, height: 25, displayMember: "language", valueMember: "language" }; $scope.newsItem = new NewsAdminService(); $scope.newsItem.language = null; $scope.newsItem.imageUrl = null; $scope.newsItem.title = null; $scope.newsItem.shortContent = null; $scope.newsItem.content = null; $scope.newsItem.publishDate = null; $scope.newsItem.published = null; $scope.newsItem.author = null; $scope.editorSettingsContent = { width: 1020, height: 300 }; $scope.editorSettingsShContent = { width: 1020, height: 130 }; $scope.ok = function () { $scope.newsItem.$save(function () { $location.path('/admin/news/news-vew'); }); }; $scope.cancel = function () { $location.path('/admin/news/news-vew'); }; } })();<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.chieftain</groupId> <artifactId>rating-agency</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>crypto-fund Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <version.org.springframework.security>4.2.3.RELEASE</version.org.springframework.security> <version.org.springframework>4.3.9.RELEASE</version.org.springframework> <version.com.sun.jersey.json>1.19.4</version.com.sun.jersey.json> <version.org.glassfish.jersey>2.26-b07</version.org.glassfish.jersey> <version.org.hibernate>5.2.10.Final</version.org.hibernate> <version.org.apache.logging.log4j>2.8.2</version.org.apache.logging.log4j> <version.javax.servlet-api>3.1.0</version.javax.servlet-api> <version.org.hsqldb>2.4.0</version.org.hsqldb> <mysql.connector.java.version>5.1.24</mysql.connector.java.version> <version.maven-compiler-plugin>3.6.1</version.maven-compiler-plugin> <version.org.eclipse.jetty.jetty-maven-plugin>9.4.6.v20170531</version.org.eclipse.jetty.jetty-maven-plugin> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${version.org.springframework}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${version.org.springframework}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${version.org.springframework}</version> </dependency> <dependency> <groupId>org.glassfish.jersey.ext</groupId> <artifactId>jersey-spring4</artifactId> <version>${version.org.glassfish.jersey}</version> </dependency> <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson</artifactId> <version>${version.org.glassfish.jersey}</version> </dependency> <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-multipart</artifactId> <version>${version.org.glassfish.jersey}</version> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>${version.org.hsqldb}</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${version.org.hibernate}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${version.org.hibernate}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${version.org.apache.logging.log4j}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${version.org.apache.logging.log4j}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${version.org.springframework.security}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${version.org.springframework.security}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${version.javax.servlet-api}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${version.org.springframework}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.xmlgraphics</groupId> <artifactId>fop</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.7.5</version> </dependency> <dependency> <groupId>org.modelmapper</groupId> <artifactId>modelmapper</artifactId> <version>0.7.4</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>eclipselink</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <version>3.5.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.java.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-aws-context</artifactId> <version>1.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.knowm.xchange</groupId> <artifactId>xchange-core</artifactId> <version>4.3.2</version> </dependency> <dependency> <groupId>org.knowm.xchange</groupId> <artifactId>xchange-poloniex</artifactId> <version>4.3.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <profiles> <profile> <id>home</id> <properties> <build.profile.id>home</build.profile.id> </properties> </profile> <profile> <id>prod</id> <properties> <build.profile.id>prod</build.profile.id> </properties> </profile> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <build.profile.id>dev</build.profile.id> </properties> </profile> </profiles> <build> <finalName>rating-agency</finalName> <resources> <resource> <filtering>true</filtering> <directory>src/main/resources</directory> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${version.maven-compiler-plugin}</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.liquibase</groupId> <artifactId>liquibase-plugin</artifactId> <version>1.9.5.0</version> <configuration> <propertyFileWillOverride>false</propertyFileWillOverride> <promptOnNonLocalDatabase>false</promptOnNonLocalDatabase> <propertyFile>src/main/resources/profiles/${build.profile.id}/liquibase.properties</propertyFile> </configuration> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>${version.org.eclipse.jetty.jetty-maven-plugin}</version> <configuration> <webApp> <contextPath>/</contextPath> <webInfIncludeJarPattern>.*/^(asm-all-repackaged)[^/]*\.jar$</webInfIncludeJarPattern> </webApp> </configuration> </plugin> <!--<plugin>--> <!--<artifactId>maven-war-plugin</artifactId>--> <!--<version>2.4</version>--> <!--<configuration>--> <!--<packagingExcludes>WEB-INF/lib/*.jar</packagingExcludes>--> <!--<archive>--> <!--<manifest>--> <!--<addClasspath>true</addClasspath>--> <!--<classpathPrefix>lib/</classpathPrefix>--> <!--</manifest>--> <!--</archive>--> <!--</configuration>--> <!--</plugin>--> </plugins> </build> </project> <file_sep>(function() { 'use strict'; angular.module('app.news').factory('SubscribeService', SubscribeService); /* @ngInject */ function SubscribeService($rootScope, $resource) { return $resource('rest/subscriptions/'); } })();<file_sep>(function() { 'use strict'; angular.module('app.admin.contacts').controller('ContactsAdminViewController', ContactsAdminViewController); /* @ngInject */ function ContactsAdminViewController($scope, $location, ContactsAdminService) { $scope.people = ContactsAdminService.query(); $scope.curentRow = null; $scope.updateDisabled = true; $scope.columns = [ { text : 'effectiveDate', datafield : 'effectiveDate', cellsformat: 'd', width : 200, cellsalign : 'left', align : 'left' }, { text : 'name', datafield : 'name', width : 200, cellsalign : 'left', align : 'left' }, { text : 'email', datafield : 'email', width : 200, cellsalign : 'left', align : 'left' }, { text : 'comment', datafield : 'comment', width : 800, cellsalign : 'left', align : 'left' }]; $scope.settings = { width : "100%", height : "100%", altrows : true, sortable : true, selectionmode : "singlerow", pageable : true, pagesize : 20, columnsresize : true, showtoolbar : false, enablebrowserselection: true, source : $scope.people, columns : $scope.columns }; $scope.refresh = function() { $scope.people = ContactsAdminService.query(); $scope.settings.source = $scope.people; }; } })();<file_sep>(function() { 'use strict'; var module = angular.module('app.icolist', []); angular.module('app').config(configure); /* @ngInject */ function configure($routeProvider) { $routeProvider.when('/ico-list', { templateUrl : 'app/ico-list/ico-list-list.html', controller : 'IcoListListController' }); $routeProvider.when('/ico-list/view/:id', { templateUrl : 'app/ico-list/ico-list-view.html', controller : 'IcoListViewController' }); } })(); <file_sep>(function() { 'use strict'; angular.module('app.news').factory('NewsItemService', NewsItemService); /* @ngInject */ function NewsItemService($rootScope, $resource) { return $resource('rest/news/:lang/:id'); } })();<file_sep>(function () { 'use strict'; angular.module('app.news').controller('NewsViewController', NewsViewController); /* @ngInject */ function NewsViewController($scope, $routeParams, $rootScope, NewsItemService, NewsTopItemService) { NewsItemService.get({lang : $rootScope.lang, id: $routeParams.id }).$promise.then( function (value) { var options = { weekday: "long", year: "numeric", month: "long", day: "numeric" }; var d = new Date(value.displayDate); value.displayDate = d.toLocaleDateString($rootScope.lang, options); $scope.newsItem = value; }, function (error) {/*Do something with error*/ } ); $scope.newsItems = NewsTopItemService.query({lang : $rootScope.lang }) } })();<file_sep>(function() { 'use strict'; angular.module('app.icolist').controller('IcoListViewController', IcoListViewController); /* @ngInject */ function IcoListViewController($rootScope, $routeParams, $scope, IcoListService) { $scope.item = IcoListService.get({ id : $routeParams.id }); } })();<file_sep><footer class="footer navbar-inverse" ng-show="initialized"> <div class="container"> <div class="row"> <div class="col-sm-3"> <h1>LOGO</h1> </div> <div class="col-sm-2"> <h4 class="navbar-link">{{ 'FOOTER_GET_STARTED' | translate }}</h4> <a href="#" class="navbar-link text-left">{{ 'INDEX_MAIN_MENU_ITEM' | translate }}</a> </div> <div class="col-sm-3"> <h4 class="navbar-link">{{ 'FOOTER_ABOUT_US' | translate }}</h4> <a href="#!/about" class="navbar-link text-left">{{ 'INDEX_ABOUT_MENU_ITEM' | translate }}</a> </div> <div class="col-sm-2"> <h4 class="navbar-link">{{ 'FOOTER_PRODUCTS' | translate }}</h4> <a href="#!/ico-list" class="navbar-link text-left">{{ 'INDEX_ICO_LIST_MENU_ITEM' | translate }}</a> <br> <a href="#!/currencies" class="navbar-link text-left">{{ 'INDEX_CURRENCIES_MENU_ITEM' | translate }}</a> </div> <div class="col-sm-2 text-right"> <a href="" class="telegram navbar-link" style="font-size: 30px !important;"><i class="fa fa-telegram"></i></a> <a href="" class="vk navbar-link" style="font-size: 30px !important;"><i class="fa fa-vk"></i></a> <a href="" class="facebook navbar-link" style="font-size: 30px !important;"><i class="fa fa-facebook"></i></a> <button type="button" class="btn btn-danger" onclick="window.location.href='#!/contacts'">{{'CONTACT_US_BUTTON' | translate}} </button> </div> </div> <div class="row"> <div class="navbar-link" ng-show="initialized"> <p>© {{ 'INDEX_COPYRIGHT_FOOTER_ITEM' | translate }}</p> </div> </div> </div> </footer><file_sep>(function() { 'use strict'; angular.module('app.admin.news').controller('NewsAdminEditController', NewsAdminEditController); /* @ngInject */ function NewsAdminEditController($scope, $routeParams, $location, NewsAdminService) { var countries = [ { value : "ru", label : "Russian" }, { value : "en", label : "English" } ]; $scope.comboBoxSettings = { created : function(args) { args.instance.focus(); }, source : countries, width : 230, height : 25 }; $scope.newsItem = NewsAdminService.get({ id : $routeParams.id }); $scope.editorSettingsContent = { width : 1020, height : 300 }; $scope.editorSettingsShContent = { width : 1020, height : 130 }; $scope.ok = function() { $scope.newsItem.$save(function() { $location.path('/admin/news/news-vew/'); }); }; $scope.cancel = function() { $location.path('/admin/news/news-vew'); }; } })();<file_sep>(function() { 'use strict'; var module = angular.module('app.login', []); angular.module('app').config(configure); /* @ngInject */ function configure($routeProvider) { $routeProvider.when('/login', { templateUrl : 'app/login/login.html', controller : 'LoginController' }); } })(); <file_sep>package com.chieftain.agency.rest.resources; import com.chieftain.agency.dao.currencyrating.CurrencyRatingDao; import com.chieftain.agency.entity.CurrencyRating; import com.chieftain.agency.transfer.CurrencyRatingDto; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; @Component @Path("/currencies") public class CurrencyRatingResource { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private CurrencyRatingDao currencyRatingDao; @Autowired private ModelMapper modelMapper; @GET @Produces(MediaType.APPLICATION_JSON) public List<CurrencyRatingDto> list() throws IOException { this.logger.info("list()"); List<CurrencyRating> allEntries = this.currencyRatingDao.findAll(); return allEntries.stream() .map(allEntry -> convertToDto(allEntry)) .collect(Collectors.toList()); } private CurrencyRatingDto convertToDto(CurrencyRating currencyRating) { CurrencyRatingDto currencyRatingDto = modelMapper.map(currencyRating, CurrencyRatingDto.class); return currencyRatingDto; } } <file_sep>package com.chieftain.agency.transfer; import java.sql.Timestamp; public class IcoListDto { private Long id; private String name; private String image; private String description; private String websiteLink; private Timestamp startTime; private Timestamp endTime; private String timezone; private String status; public IcoListDto() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getWebsiteLink() { return websiteLink; } public void setWebsiteLink(String websiteLink) { this.websiteLink = websiteLink; } public Timestamp getStartTime() { return startTime; } public void setStartTime(Timestamp startTime) { this.startTime = startTime; } public Timestamp getEndTime() { return endTime; } public void setEndTime(Timestamp endTime) { this.endTime = endTime; } public String getTimezone() { return timezone; } public void setTimezone(String timezone) { this.timezone = timezone; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } } <file_sep>package com.chieftain.agency.rest.resources; import com.chieftain.agency.aws.S3Wrapper; import com.chieftain.agency.dao.files.FilesDao; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.File; import java.io.IOException; import java.nio.file.Files; @Component @Path("/files") public class FilesResource { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private FilesDao filesDao; @Autowired private ModelMapper modelMapper; @Autowired private S3Wrapper s3Wrapper; @Value("${use.amazon.aws}") private boolean useAWS; @GET @Path("/download/{id}") public Response downloadFile(@PathParam("id") Long id) { com.chieftain.agency.entity.Files itemDb = this.filesDao.find(id); if (useAWS) { try { ResponseEntity<byte[]> items = s3Wrapper.download(id.toString()); return Response.ok(items.getBody(), MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition", "attachment; filename = " + itemDb.getName()).build(); } catch (IOException e) { e.printStackTrace(); return null; } } else { try { return Response.ok(Files.readAllBytes(new File(System.getProperty("java.io.tmpdir") + itemDb.getId().toString()).toPath()), MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition", "attachment; filename = " + itemDb.getName()).build(); } catch (IOException e) { e.printStackTrace(); return null; } } } } <file_sep>(function() { 'use strict'; var module = angular.module('app.admin.contacts', []); angular.module('app').config(configure); /* @ngInject */ function configure($routeProvider) { $routeProvider.when('/admin/contacts/contacts-vew', { templateUrl : 'app/admin/inquiries/inquiries-vew.html', controller : 'ContactsAdminViewController' }); } })(); <file_sep>(function() { 'use strict'; var app = angular.module('app', [ 'ngRoute', 'ngSanitize', 'ngCookies', 'ngResource', 'jqwidgets', 'jqwidgets-amd', 'matchmedia-ng', 'pascalprecht.translate', /* * App modules */ 'app.translation', 'app.login', 'app.main', 'app.news', 'app.about', 'app.contacts', 'app.admin', 'app.ratings', 'app.icolist', 'app.currencies' ]); })(); <file_sep>(function() { 'use strict'; angular.module('app.admin.news').controller('FilesAdminCreateController', FilesAdminCreateController); /* @ngInject */ function FilesAdminCreateController($scope, $location, FilesAdminService) { // $scope.newsItem = new FilesService(); $scope.fileUploadSettings = { width : 300, uploadUrl : 'rest/admin/files/upload', fileInputName : 'content', multipleFilesUpload: false }; $scope.ok = function() { $location.path('/admin/files/files-vew'); }; $scope.cancel = function() { $location.path('/admin/files/files-vew'); }; } })();<file_sep>DROP USER 'agnc'@'localhost'; DROP USER 'agnc'@'%'; DROP DATABASE crpt; DROP USER 'agnc_user'@'localhost'; DROP USER 'agnc_user'@'%'; DROP TABLE `agnc`.`access_token`; DROP TABLE `agnc`.`currency_rating`; DROP TABLE `agnc`.`DATABASECHANGELOG`; DROP TABLE `agnc`.`DATABASECHANGELOGLOCK`; DROP TABLE `agnc`.`files`; DROP TABLE `agnc`.`ico_list`; DROP TABLE `agnc`.`news`; DROP TABLE `agnc`.`User_roles`; DROP TABLE `agnc`.`user`; DROP TABLE `agnc`.`user_inquiries`; DROP TABLE `agnc`.`subscriptions`; DROP TABLE `agnc`.`ticker_data`;<file_sep>(function() { 'use strict'; angular.module('app.login').controller('LoginController', LoginController); /* @ngInject */ function LoginController($scope, $rootScope, $location, $cookieStore, UserService) { $scope.rememberMe = false; $scope.login = function() { UserService.authenticate($.param({ username : $scope.username, password : $<PASSWORD> }), function(authenticationResult) { var accessToken = authenticationResult.token; $rootScope.accessToken = accessToken; if ($scope.rememberMe) { $cookieStore.put('accessToken', accessToken); } UserService.get(function(user) { $rootScope.user = user; $location.path("/"); }); }); }; } })();<file_sep><!--<ol class="breadcrumb">--> <!--<li class="breadcrumb-item active">{{ 'INDEX_CONTACTS_MENU_ITEM' |--> <!--translate }}</li>--> <!--</ol>--> <table class="table"> <thead class="thead-inverse"> <tr> <th>#</th> <th>{{'CURRENCIES_TABLE_NAME'|translate}}</th> <th>{{'CURRENCIES_TABLE_SYMBOL'|translate}}</th> <th>{{'CURRENCIES_TABLE_PRICE'|translate}}</th> <th>{{'CURRENCIES_TABLE_D_VOLUME'|translate}}</th> <th>{{'CURRENCIES_TABLE_MARKET_CAP'|translate}}</th> </tr> </thead> <tbody> <tr ng-repeat="item in items"> <th scope="row">{{$index + 1}}</th> <td>{{item.name}}</td> <td>{{item.symbol}}</td> <td>${{item.priceUsd | number:2}}</td> <td>${{item.volumeUsd24h | number:2}}</td> <td>${{item.marketCapUsd | number:2}}</td> </tr> </tbody> </table> <file_sep>package com.chieftain.agency.rest.resources; import com.amazonaws.services.s3.model.PutObjectResult; import com.chieftain.agency.aws.S3Wrapper; import com.chieftain.agency.dao.files.FilesDao; import com.chieftain.agency.entity.Files; import com.chieftain.agency.transfer.FilesDto; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import java.util.stream.Collectors; @Component @Path("/admin/files") public class FilesAdminResource { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private FilesDao filesDao; @Autowired private S3Wrapper s3Wrapper; @Autowired private ModelMapper modelMapper; @Value("${use.amazon.aws}") private boolean useAWS; @GET @Produces(MediaType.APPLICATION_JSON) public List<FilesDto> list() throws IOException { this.logger.info("list()"); List<Files> allEntries = this.filesDao.findAll(); return allEntries.stream().map(allEntry -> convertToDto(allEntry)).collect(Collectors.toList()); } @POST @Path("/upload") @Consumes({MediaType.MULTIPART_FORM_DATA}) public Response uploadFile(@FormDataParam("content") InputStream fileInputStream, @FormDataParam("content") FormDataContentDisposition fileMetaData) throws Exception { Files item = new Files(); item.setName(fileMetaData.getFileName()); item = this.filesDao.save(item); item.setUrl(); this.filesDao.save(item); if (useAWS) { PutObjectResult putObjectResult = s3Wrapper.upload(fileInputStream, item.getId().toString()); } else { OutputStream os = new FileOutputStream(System.getProperty("java.io.tmpdir")+item.getId().toString()); byte[] buffer = new byte[1024]; int bytesRead; while((bytesRead = fileInputStream.read(buffer)) !=-1){ os.write(buffer, 0, bytesRead); } os.flush(); os.close(); } return Response.ok("Data uploaded successfully !!").build(); } private FilesDto convertToDto(Files files) { FilesDto filesDto = modelMapper.map(files, FilesDto.class); return filesDto; } private Files convertFromDto(FilesDto filesDto) { Files files = modelMapper.map(filesDto, Files.class); return files; } } <file_sep>package com.chieftain.agency.dao.currencyrating; import com.chieftain.agency.dao.JpaDao; import com.chieftain.agency.entity.CurrencyRating; import org.springframework.transaction.annotation.Transactional; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import java.util.List; public class JpaCurrencyRatingDao extends JpaDao<CurrencyRating, Long> implements CurrencyRatingDao { public JpaCurrencyRatingDao() { super(CurrencyRating.class); } @Override @Transactional(readOnly = true) public List<CurrencyRating> findAll() { final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder(); final CriteriaQuery<CurrencyRating> criteriaQuery = builder.createQuery(CurrencyRating.class); Root<CurrencyRating> root = criteriaQuery.from(CurrencyRating.class); TypedQuery<CurrencyRating> typedQuery = this.getEntityManager().createQuery(criteriaQuery); typedQuery.setMaxResults(25); return typedQuery.getResultList(); } @Override public List<CurrencyRating> findFirstRows() { final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder(); final CriteriaQuery<CurrencyRating> criteriaQuery = builder.createQuery(CurrencyRating.class); Root<CurrencyRating> root = criteriaQuery.from(CurrencyRating.class); criteriaQuery.orderBy(builder.desc(root.get("marketCapUsd"))); TypedQuery<CurrencyRating> typedQuery = this.getEntityManager().createQuery(criteriaQuery); typedQuery.setMaxResults(5); return typedQuery.getResultList(); } } <file_sep>package com.chieftain.agency.transfer; import com.fasterxml.jackson.annotation.JsonFormat; import java.sql.Timestamp; public class NewsDto { private Long id; private String language; private String imageUrl; private String title; private String shortContent; private String content; @JsonFormat(pattern = "dd/MM/yyyy") private Timestamp effectiveDate; @JsonFormat(pattern = "dd/MM/yyyy") private Timestamp publishDate; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss") private Timestamp displayDate; private boolean published; private String author; public NewsDto() { displayDate = publishDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getShortContent() { return shortContent; } public void setShortContent(String shortContent) { this.shortContent = shortContent; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Timestamp getEffectiveDate() { return effectiveDate; } public void setEffectiveDate(Timestamp effectiveDate) { this.effectiveDate = effectiveDate; } public Timestamp getPublishDate() { return publishDate; } public void setPublishDate(Timestamp publishDate) { this.publishDate = publishDate; } public boolean getPublished() { return published; } public void setPublished(boolean published) { this.published = published; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Timestamp getDisplayDate() { return publishDate; } } <file_sep>contexts: local, non-sandbox changeLogFile: src/main/database/app.changelog.xml driver: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3308/agnc?characterEncoding=UTF-8&useUnicode=true username: agnc password: <PASSWORD> verbose: true <file_sep>(function() { 'use strict'; var module = angular.module('app.ratings', []); angular.module('app').config(configure); /* @ngInject */ function configure($routeProvider) { $routeProvider.when('/ratings', { templateUrl : 'app/ratings/ratings.html' }); } })(); <file_sep>db.username=agnc_user db.password=<PASSWORD> db.driver=com.mysql.jdbc.Driver db.url=jdbc:mysql://192.168.1.140:3308/agnc?characterEncoding=UTF-8&useUnicode=true db.removeAbandoned=true db.initialSize=1 db.maxActive=5 app.secret=fgfdhgfgfadsfdss5erbfd spring.freemarker.cache=false use.amazon.aws=false multipart.maxFileSize=-1 multipart.maxRequestSize=1024Mb cloud.aws.credentials.accessKey= cloud.aws.credentials.secretKey= cloud.aws.region= cloud.aws.s3.bucket=<file_sep>package com.chieftain.agency.rest.resources; import com.chieftain.agency.dao.subscriptions.SubscriptionsDao; import com.chieftain.agency.entity.Subscriptions; import com.chieftain.agency.transfer.SubscriptionsDto; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Component @Path("/subscriptions") public class SubscriptionsResource { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private ModelMapper modelMapper; @Autowired private SubscriptionsDao subscriptionsDao; @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public SubscriptionsDto create(SubscriptionsDto icoItem) { this.logger.info("create(): " + icoItem); Subscriptions item = this.subscriptionsDao.save(convertFromDto(icoItem)); return convertToDto(item); } private Subscriptions convertFromDto(SubscriptionsDto subscriptionsDto) { Subscriptions subscriptions = modelMapper.map(subscriptionsDto, Subscriptions.class); return subscriptions; } private SubscriptionsDto convertToDto(Subscriptions subscriptions) { SubscriptionsDto subscriptionsDto = modelMapper.map(subscriptions, SubscriptionsDto.class); return subscriptionsDto; } }
9f87b8b83925ba7ead52a05e3775b387e7b8183f
[ "SQL", "HTML", "JavaScript", "Markdown", "Maven POM", "INI", "Java" ]
53
JavaScript
TheFatTony/rating-agency
4a930a00ab029dbfeb4f617689355472f06a9197
3523fafb440b62efac97338aa888327b0fd17e9f
refs/heads/main
<file_sep>import React from 'react'; import { Link, NavLink, Router } from 'react-router-dom'; const NavBar= () => { return ( <nav className="navbar navbar-expand-lg navbar-light bg-dark"> <div className="container-fluid"> <Link to="/" className="navbar-brand" style={{color: "white"}}>Studio Ghibli</Link> <ul className="navbar-nav"> <li className="nav-item"> <NavLink to="/films" className="nav-link active" style={{color: "white"}}>Films</NavLink></li> <li className="nav-item"> <NavLink to="/people" className="nav-link active" style={{color: "white"}}>People</NavLink></li> </ul> </div> </nav> ); } export default NavBar;<file_sep>import React, {useState, useEffect} from 'react'; import {Link} from 'react-router-dom'; const People = () =>{ const [people, setPeople]=useState([]) const [mapPeople, setMapPeople] = useState([]); const styleCardsFilm={ width: "100%", height: "20em", marginTop: "7rem", marginRight: "-10rem" } const cardStyleStyle={ width: "24rem", marginLeft: "2rem", marginRight: "2rem", marginTop: "2rem" } useEffect(()=>{ fetch("https://ghibliapi.herokuapp.com/people").then(response => { return response.json() }).then(filmys => { setPeople(filmys) }) }, []) useEffect(() =>{setMapPeople(people.map((m) => { const linkto=`/people/${m.id}` return ( <div className="card mb-3 border-success" style={cardStyleStyle} key={m.id}> <div className="card-body"> <h5 className="card-title">{m.name}</h5> <Link className="btn btn-success" to={linkto}>More info</Link> </div> </div> )}))}, [people]) return ( <div className="d-flex flex-wrap justify-content-start" style={styleCardsFilm}> {mapPeople} </div> ); } export default People; <file_sep>import React from 'react'; import { useParams } from 'react-router-dom'; const UnknownPage= props => { const { pageName }= useParams(); return( <main className="container"> <h1 className="text-center">404</h1> <p className="text-center">The {props.pageType} {pageName} was not found</p> </main> ); } export default UnknownPage;<file_sep>import React, { useEffect, useState } from 'react'; import {useParams} from 'react-router-dom'; import UnknownPage from './UnknownPage'; const Film = () =>{ const [film, setFilm]=useState(null); const { pageName }=useParams(); const [requestSuccess, setRequestSuccess]=useState(true) const cardStyleStyle={ width: "96rem", height: "36rem", marginLeft: "2rem", marginRight: "2rem", marginTop: "8rem" } useEffect(()=>{ console.log('hi') fetch(`https://ghibliapi.herokuapp.com/films/${pageName}`).then(response => { setRequestSuccess(response.ok) return response.json() }).then(filmy=> { setFilm(filmy) }) }, []) return requestSuccess ? ( <main className="container d-flex justify-content-center align-items-center"> <div className="card border-primary rounded-0" style={cardStyleStyle}> <h2 className="card-title">{film?.title}</h2> <ul className="list-group list-group-flush"> <li className="list-group-item">Film Rating: <span style={{color: (film?.rt_score>=70) ? "green" : "red"}}>{film?.rt_score}</span></li> <li className="list-group-item">Directed by: {film?.director}</li> <li className="list-group-item">Produced by: {film?.producer}</li> <li className="list-group-item">Released in: {film?.release_date}</li> </ul> <div className="card-body"> <p className="card-text">{film?.description}</p> </div> </div> </main> ) : ( <UnknownPage pageType="film with id" /> ); } export default Film;<file_sep>import React, {useState, useEffect} from 'react'; import { BrowserRouter, Switch, Route } from 'react-router-dom'; import studioGhibili from "./studioGhibili.svg" import Films from "./pages/Films" import Film from "./pages/Film"; import NavBar from './components/NavBar'; import People from "./pages/People" import Person from './pages/Person'; import UnknownPage from './pages/UnknownPage'; const App = () => { const imageyStyle={ display: "absolute", marginTop: "-7em", marginLeft: "0", marginRight: "0" } return ( <div> <BrowserRouter> <NavBar /> <Switch> <Route exact path="/"> {()=> <main className="container"> <div className="d-flex justify-content-center"> <img style={imageyStyle} className="" src={studioGhibili} height="800" width="800" /> </div> </main> } </Route> <Route exact path="/films"> {()=> <Films /> } </Route> <Route exact path="/films/:pageName"> {()=><Film />} </Route> <Route exact path="/people"> {()=> <People /> } </Route> <Route exact path="/people/:pageName"> {()=><Person />} </Route> <Route exact path="/:pageName"> {()=><UnknownPage pageType="subpage" />} </Route> </Switch> </BrowserRouter> </div> ) } export default App;<file_sep>import React, { useEffect, useState } from 'react'; import {useParams} from 'react-router-dom'; import UnknownPage from './UnknownPage'; const Person = () =>{ const [person, setPerson]=useState(null); const { pageName }=useParams(); const [requestSuccess, setRequestSuccess]=useState(true) const cardStyleStyle={ width: "96rem", height: "15.5rem", marginLeft: "2rem", marginRight: "2rem", marginTop: "8rem" } useEffect(()=>{ console.log('hi') fetch(`https://ghibliapi.herokuapp.com/people/${pageName}`).then(response => { setRequestSuccess(response.ok) return response.json() }).then(persony=> { setPerson(persony) }) }, []) return requestSuccess ? ( <main className="container d-flex justify-content-center align-items-center"> <div className="card rounded-0 border-primary" style={cardStyleStyle}> <h2 className="card-title">{person?.name}</h2> <ul className="list-group list-group-flush"> <li className="list-group-item">Gender: {person?.gender}</li> <li className="list-group-item">Age: {person?.age}</li> <li className="list-group-item">Hair color: <span style={{color: person?.hair_color}}>{person?.hair_color}</span></li> <li className="list-group-item">Eye color: <span style={{color: (person?.eye_color=="White") ? "beige" : person?.eye_color}}>{person?.eye_color}</span></li> </ul> </div> </main> ) : ( <UnknownPage pageType="person with id" /> ); } export default Person;
5320d0d5cf4956356fac3c531fb93d177ce5f823
[ "JavaScript" ]
6
JavaScript
BucketofJava/Studio-Ghibli-With-React-Routing
7614faa761b612b1b738cb9444bd262b90040fee
15e37b786f936f68c17425c1fa271f71a7cfb20b
refs/heads/master
<file_sep>from django.contrib import admin from facebook.models import Article from facebook.models import Comment #추가한 comment 부르기 # Register your models here. admin.site.register(Article) admin.site.register(Comment) <file_sep>"""main URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from facebook.views import play from facebook.views import play2 from facebook.views import profile from facebook.views import challenge from facebook.views import newsfeed from facebook.views import detail_feed from facebook.views import neww_feed from facebook.views import edit_feed,remove_feed # urlpatterns = [path() , path() , path()] # urlpatterns = [첫번째 주소, 두번째 주소, 세번째 주소] urlpatterns = [ path('admin/', admin.site.urls), path('play/', play), path('play2/', play2), path("LeeJaeHa/profile/", profile), path("challenge/", challenge), path("", newsfeed) , # 첫페이지 path("feed/<pk>/", detail_feed) , # 자세히보기 페이지 보여줘 path("feed/<pk>/edit/", edit_feed) , # 자세히보기 페이지 보여줘 path("feed/<pk>/remove/", remove_feed) , # 자세히보기 페이지 보여줘 path("new/", neww_feed), #path("new/", 글쓰기페이지 띄워줘) ] <file_sep>from django.shortcuts import render , redirect from facebook.models import Article,Comment # Create your views here. cnt = 0 def play(request): return render(request, "play.html") count =0 def play2(request): name = '<NAME>' global count diary = list() count = count + 1 age = 25 if age > 20: status = '성인입니다' else: status = '청소년입니다.' diary = ['날씨가 좋았다 - 월', '흐렸다 - 화','배고팠다 - 수'] return render(request, "play2.html", {'name': name, 'cnt': count, 'status': status, 'diary': diary}) def profile(request): return render(request, "profile.html") def challenge(request): global cnt cnt = cnt + 1 age = 25 name = "이재하" if age >= 20: status = "(성인)입니다" else: status = "(청소년)입니다" if cnt == 7: result = "당첨!입니다." else: result = "꽝입니다." return render(request, "challenge.html", {'age': age, 'cnt': cnt, 'name': name, 'result': result, 'status': status}) def newsfeed(request): articles = Article.objects.all() return render(request, "newsfeed.html", {'articles': articles}) def detail_feed(request , pk): # urls.py 에서 pk 때문 article = Article.objects.get(pk=pk) #코멘트 추가 요청이 들어오면 DB에 등록하기 if request.method == 'POST': #코멘트 등록하기 Comment.objects.create( article= article, author= request.POST['nickname'], text = request.POST['reply'], password = "pw", ) return render(request, "detail_feed.html", {'feed': article}) def neww_feed(request): temp = "-추신 : 감사합니다." #Django가 여기서 글을 등록해라 # 1) 입력한 내용을 받아오기 1번 if request.method == 'POST': #requset 는 받아오는 feed = Article.objects.create( author=request.POST['author'], title=request.POST['title'], text=request.POST['content']+temp, password=request.POST['password'], ) # return redirect(f'/feed/{feed.pk}') return redirect('/feed/'+str(feed.pk)) # 2) 받은 글을 등록하기 return render(request, 'neww_feed.html') def edit_feed(request , pk): # 1) 수정한 글의 정보를 불러오기 feed = Article.objects.get(pk=pk) if request.method == 'POST': feed.title = request.POST ['title'] feed.author = request.POST['author'] feed.text = request.POST['content'] feed.save() #feed.pk #글번호 #return redirect(f'/feed/{feed.pk}/')높은 버전 return redirect('/feed/' +str(feed.pk)) return render(request,"edit_feed.html", {'feed': feed}) def remove_feed(request , pk):#pk를 널은 이유는 페이지의 번호를 알고싶을때 feed = Article.objects.get(pk=pk) if request.method == 'POST': #삭제해주세요 if request.POST['pw']==feed.password: feed.delete() return redirect("/") else: print("비밀번호가 틀렸습니다") return render(request,"remove_feed.html")
79c4e233e3f5fd33aa35dfd72578061eec54f84e
[ "Python" ]
3
Python
LEE-JAEHA/django_facebook
ed5dd8d3e8e48e863f7f343532644426594dd0c1
60543deb9955c78e43091c9692ea3a35f30481f7
refs/heads/master
<repo_name>fantomtom599/Allinone<file_sep>/main/java/com/example/tpkotlin2/SoundBoard.kt package com.example.tpkotlin2 import android.content.Intent import android.media.MediaPlayer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.MotionEvent import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.activity_sound_board.* class SoundBoard : AppCompatActivity() { private var mediaPlayer: MediaPlayer? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sound_board) mediaPlayer = MediaPlayer.create(this, R.raw.death) mediaPlayer?.setOnPreparedListener{ println("READY TO GO") } btnSound.setOnTouchListener{_, event -> handleTouch(event) true } } private fun handleTouch(event: MotionEvent) { when (event.action) { MotionEvent.ACTION_DOWN -> { println("down") mediaPlayer?.start() } MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> { println("up or cancel") mediaPlayer?.pause() mediaPlayer?.seekTo(0) } else -> { print("other") } } } } <file_sep>/main/java/com/example/tpkotlin2/MainActivity.kt package com.example.tpkotlin2 import android.content.Intent import android.media.MediaPlayer import android.os.Bundle import android.view.MotionEvent //import android.support.v7.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private var mediaPlayer: MediaPlayer? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mediaPlayer = MediaPlayer.create(this, R.raw.pnj) mediaPlayer?.setOnPreparedListener{ println("READY TO GO") } btnSoundBoard.setOnClickListener { val intent = Intent(this, SoundBoard::class.java) startActivity(intent) } buttonPlay.setOnClickListener { val intent = Intent(this, Game::class.java) startActivity(intent) } } }
97ff48a2553f208360f61a6d506607b1d0844559
[ "Kotlin" ]
2
Kotlin
fantomtom599/Allinone
b9b2e92f97f073bd845ab94d45621c8db9f17d8d
19fe9c974c086223e548d439286f2706b42decae
refs/heads/master
<file_sep>import React from 'react'; import {AppRegistry} from 'react-native'; import App from './app/'; const HelloRN = () => ( <App /> ); AppRegistry.registerComponent('HelloRN', () => HelloRN); <file_sep>import { Text, View, Image } from 'react-native'; import React, {Component} from 'react'; import styles from './styles'; import image from '../../config/image'; import HeaderText from '../../components/HeaderText'; class Home extends Component { render() { return ( <View style={styles.container}> <HeaderText title='Welcome to React Native'/> <Image source={image.LOGO} style={styles.logo} /> <Text style={styles.paragraphText}> It is recommended to init a new project using react native cli rather than starting by cloning this repo. </Text> <Text style={styles.paragraphText}> But you can take reference to project folder structure for code re-usability. </Text> </View> ); } } export default Home; <file_sep>/** * API paths that will be used throughout this application. */ const BASE_URL = 'http://10.10.9.114:8848'; const uri = { SAMPLE: BASE_URL + '/api/sample' }; export default uri; <file_sep>/** * Configurations that will be used throughout application. */ export const colors = { primary: '#F44336', darkPrimary: '#D32F2F', backgroundColor: '#F5FCFF', primaryTextColor: '#333333', primaryDarkColor: '#212121' }; <file_sep># react-native-project-structure Project structure for building android and ios app using React Native. Since react-native cli does not provide project structure for js code, so it might be daunting for new developers to orgranize project. The goal of this structure is: * Cross Platform * Maximum code reuse * Minimize component state * Keep configuration out of the code <file_sep>import * as httpUtils from './httpUtils'; export { httpUtils }; <file_sep>/* Manage application routes. */
f17945b1a7255811543dcb1051456a5eaa3625f6
[ "JavaScript", "Markdown" ]
7
JavaScript
lf-achyutpkl/react-native-starter
5ac78dfdd49f4dbefff2aa37c00736f2a77891e9
987072f972171d043a9668f47e1fab6a8d097430
refs/heads/master
<file_sep>import sys import os import time import logging import socket sys.path.extend([os.path.join(os.path.abspath(os.path.dirname(__file__)),'..')]) from opencluster.worker import Worker from opencluster.configuration import Conf logger = logging.getLogger(__name__) class HelloWorker(Worker) : def __init__(self): super(HelloWorker,self).__init__(workerType="helloWorker") def doTask(self, task_data): logger.debug("begin...HelloWorker.... :" + task_data) time.sleep(1) return socket.gethostname() + " say: hello " + task_data if __name__ == "__main__" : wk = HelloWorker() if len(sys.argv) != 2 : print "Usage: python helloWorker.py localIP" sys.exit(1) wk.waitWorking(sys.argv[1]) <file_sep>import logging import threading import cPickle import traceback from opencluster.util import compress, decompress from opencluster.errors import ServiceError logger = logging.getLogger(__name__) class WorkerService(object): def __init__(self, worker): self.worker = worker self.condition = threading.Condition() def setWorker(self, worker): worker.host = self.worker.host worker.port = self.worker.port worker.workerType = self.worker.workerType self.worker = worker def doTask(self, v_task): try : task = cPickle.loads(decompress(v_task)) return compress(cPickle.dumps(self.worker.doTask(task.data),-1)) except Exception, e: print '>>> traceback <<<' traceback.print_exc() print '>>> end of traceback <<<' logger.error(e) raise ServiceError(e) def stopTask(self): #to-do, need condition self.worker.interrupted(True) def receiveMaterials(self, v_task): return self.worker.receiveMaterials(cPickle.loads(decompress(v_task))) <file_sep>#!/bin/sh extractHostName() { # extract first part of string (before any whitespace characters) SLAVE=$1 # Remove types and possible comments if [[ "$SLAVE" =~ ^([0-9a-zA-Z/.-]+).*$ ]]; then SLAVE=${BASH_REMATCH[1]} fi # Extract the hostname from the network hierarchy if [[ "$SLAVE" =~ ^.*/([0-9a-zA-Z.-]+)$ ]]; then SLAVE=${BASH_REMATCH[1]} fi echo $SLAVE } bin=`dirname "$0"` bin=`cd "$bin"; pwd` HOSTLIST="${bin}/nodes" if [ ! -f "$HOSTLIST" ]; then echo $HOSTLIST is not a valid nodes list exit 1 fi python ${bin}/startfactory.py > /dev/null 2>&1 & python ${bin}/startfactoryweb.py > /dev/null 2>&1 & sleep 1 GOON=true while $GOON do read line || GOON=false if [ -n "$line" ]; then HOST=$line echo "----------Starting Node on $HOST----------" ssh -n $HOST "$bin/startnode.sh $HOST &" fi done < "$HOSTLIST" echo "start the factory and all nodes....finished." exit 0 <file_sep>OpenCluster -- Python Distributed Computing API =========== ### 1,Install git clone https://github.com/astroitlab/opencluster.git ${OPENCLUSTER_HOME} ### 2,Configuration: mkdir -p /work/opencluster/logs cp ${OPENCLUSTER_HOME}/opencluster/config.ini ${OPENCLUSTER_HOME}/opencluster/logging.conf /work/opencluster ### 3,Start Cluster modify config.ini and sbin/nodes according to your cluster, then run: sbin/start-all.sh ### 4,Run tests cd ${OPENCLUSTER_HOME} python example/helloManager.py -h<file_sep>from servicecontext import ServiceContext class DftpLocal(object) : def __init__(self, url):#dftp:// self.url = url self.node = ServiceContext.getService("",33,"") def readByte(self, f, b, t) : pass def readByteAsyn(self, f, b, t, locked=False) : pass def writeByte(self, f, b, t, bs) : pass def writeByteAsyn(self, f, b, t, bs, locked=False) : pass def writeByteLocked(self, f, b, t, bs) : pass def getFileMeta(self, f) : pass def getChildFileMeta(self, f) : return [] def getListRoots(self) : return [] def getHost(self) : return "" def create(self, f, i=False) : pass def delete(self, f) : return False def copy(self, f, e, t) : return False def copyAsyn(self,f, e, t): pass def rename(self, f, newName) : return False <file_sep>import os import logging from opencluster.configuration import Conf logger = logging.getLogger(__name__) class WorkerProcess(object) : def __init__(self,host,workerType,workerScript): self.workerType = workerType self.workerScript = workerScript self.host = host def start(self): cmd = os.path.join(Conf.getNodeWorkerDir(),"worker.sh") + " " + self.workerScript + " start " + self.host return os.system(cmd) def stop(self,port): filenames = self.workerScript.split("/") filename = filenames[-1] cmd = os.path.join(Conf.getNodeWorkerDir(),"worker.sh") + " " + filename + " stop " + str(port) return os.system(cmd) def stopAll(self): filenames = self.workerScript.split("/") filename = filenames[-1] cmd = os.path.join(Conf.getNodeWorkerDir(),"worker.sh") + " " + filename + " stopAll"; return os.system(cmd) class ServiceProcess(object) : def __init__(self,host,serviceName,serviceScript): self.serviceName = serviceName self.serviceScript = serviceScript self.host = host def start(self): cmd = os.path.join(Conf.getNodeServiceDir(),"service.sh") + " " + self.serviceScript + " start " + self.host return os.system(cmd) def stop(self,port): logger.info("stop") filenames = self.serviceScript.split("/") filename = filenames[-1] cmd = os.path.join(Conf.getNodeServiceDir(),"service.sh") + " " + filename + " stop " + str(port) logger.info(cmd) return os.system(cmd) def stopAll(self): filenames = self.serviceScript.split("/") filename = filenames[-1] cmd = os.path.join(Conf.getNodeServiceDir(),"service.sh") + " " + filename + " stopAll"; logger.info(cmd) return os.system(cmd)<file_sep>import os from dftplocal import DftpLocal class DftpAdapter(object) : def __init__(self, rootUrl): self.rootUrl = rootUrl self.local = DftpLocal(self.rootUrl) def listDir(self,retDir): absDir = os.path.join(self.rootDir,retDir) if os.path.exists(absDir) : raise Exception("dir does not exists") if os.path.isdir(absDir) : raise Exception("it is not dir") return os.listdir(absDir) <file_sep>import logging import Queue from item import * from factory import FactoryContext from asyncexector import AsyncExector logger = logging.getLogger(__name__) class FactoryPatternExector(object): factory = None queue = Queue.Queue() rpl = None @classmethod def getFactory(cls): if not cls.factory : cls.factory = FactoryContext.getDefaultFactory() return cls.factory @classmethod def getWorkerTypeList(cls, workType=None): if workType is None: return cls.getFactory().getNodes() return cls.getFactory().getNodes("_worker_" + workType) @classmethod def getServiceNameList(cls, serviceName): return cls.getFactory().getNodes("_service_" + serviceName) @classmethod def getNodeList(cls): return cls.getFactory().getNodes("_node_") @classmethod def getManagerList(cls): return cls.getFactory().getNodes("_manager_") @classmethod def getServiceList(cls,host=None): return cls.getFactory().getNodes("_service_") @classmethod def createWorkerTypeNode(cls, workerType, nodeValue): return cls.getFactory().createDomainNode("_worker_" + workerType, str(time.time()).replace(".", ""), nodeValue,True) @classmethod def createPhysicalNode(cls, node): return cls.getFactory().createDomainNode("_node_", "".join(node.host.split(".")), node,True) @classmethod def updatePhysicalNode(cls, node): return cls.getFactory().createDomainNode("_node_", "".join(node.host.split(".")), node,False) @classmethod def createServiceNode(cls, host, port, serviceName): return cls.getFactory().createDomainNode("_service_" + serviceName, "".join(host.split("."))+str(port), host+":"+str(port),False) @classmethod def createManager(cls, manager): return cls.getFactory().createDomainNode("_manager_", manager.name, manager,False,manager.timeout) @classmethod def updateManager(cls, manager): return cls.getFactory().update("_manager_", manager.name, manager,False) @classmethod def getLastestObjectBean(cls, ob): keys= FactoryObjValue.getDomainNode(ob.getName()) while True : curOb = cls.getFactory().getLatest(keys[0], int(keys[2]), ob) if curOb : return curOb @classmethod def updateObjectBean(cls,ob, wh): keys= FactoryObjValue.getDomainNode(ob.getName()) return cls.getFactory().update(keys[0], keys[1], wh) @classmethod def append(cls, ppb): try: ob = cls.getFactory().update(ppb.domain, ppb.node, ppb.inHouse) ppb.thisVersion = ob cls.queue.put(ppb) def task(): try: curPpb = cls.queue.get() curVersion = cls.getFactory().getLatest() if not curVersion : curPpb.thisVersion = curVersion curPpb.rx.setRecall(False) curPpb.outhouse.putAll(curVersion) curPpb.outhouse.setReady(ITEM_READY) else: cls.queue.put(curPpb) except Exception,e1 : logger.error(e1) if cls.rpl is None : cls.rpl = AsyncExector(task , ()) cls.rpl.run() except Exception,e : logger.error(e) #end <file_sep>#!/bin/sh processID=`ps aux | grep python | grep startfactory.py | awk '{print $2}'` if [ "$processID"x = ""x ]; then echo "not found factory" else echo "about to kill factory....." `kill -9 $processID` fi processID=`ps aux | grep python | grep startfactoryweb.py | awk '{print $2}'` if [ "$processID"x = ""x ]; then echo "not found factory web" else echo "about to kill factory web....." `kill -9 $processID` fi <file_sep>import web apiUrls = [ "/api/hello", "Hello", "/api/health", "Health" ] def operator_status(func): '''''get operatoration status ''' def gen_status(*args, **kwargs): error, result = None, None try: result = func(*args, **kwargs) except Exception as e: error = str(e) return {'result': result, 'error': error} return gen_status web.config.debug = True class Hello(object): def GET(self): return "hello " def PUT(self): return "hello " class Health(object): def GET(self): return "ok" def PUT(self): return "ok" <file_sep>import sys import os import logging import optparse import Queue import datetime import time import cPickle import MySQLdb logger = logging.getLogger(__name__) from opencluster.factory import FactoryContext from opencluster.factorypatternexector import FactoryPatternExector from opencluster.configuration import Conf, setLogger from opencluster.schedule import LocalScheduler, MultiProcessScheduler, StandaloneScheduler, FactoryScheduler, \ MesosScheduler from opencluster.util import random_time_str from opencluster.item import ManagerOption, CompletionEvent, Success, OtherFailure parser = optparse.OptionParser(usage="Usage: python %prog [options]") def add_default_options(): parser.disable_interspersed_args() parser.add_option("-m", "--mode", type="string", default="local", help="local, process, standalone, mesos, factory") parser.add_option("-n", "--name", type="string", default="", help="job name") parser.add_option("-W", "--workertype", type="string", default="", help="valid worker type registered in factory(specify when mode is standalone)") parser.add_option("-w", "--warehouse", type="string", default="", help="warehouse location in factory(specify when mode is factory)") parser.add_option("-p", "--parallel", type="int", default=0, help="number of processes") parser.add_option("-r", "--retry", type="int", default=0, help="retry times when failed (default: 0)") parser.add_option("-c", "--cpus", type="float", default=1.0, help="cpus used per task") parser.add_option("-G", "--gpus", type="float", default=0, help="gpus used per task") parser.add_option("-M", "--mem", type="float", help="memory used per task") parser.add_option("-g", "--group", type="string", default="", help="which group of machines") parser.add_option("-e", "--config", type="string", default="/work/opencluster/config.ini", help="path for configuration file") parser.add_option("-q", "--quiet", action="store_true", help="be quiet", ) parser.add_option("-v", "--verbose", action="store_true", help="show more useful log", ) add_default_options() def parse_options(): (options, args) = parser.parse_args() if not options: parser.print_help() sys.exit(2) if options.mem is None: options.mem = Conf.MEM_PER_TASK options.logLevel = (options.quiet and logging.ERROR or options.verbose and logging.DEBUG or logging.INFO) setLogger(__name__, options.name, options.logLevel) if options.config: if os.path.exists(options.config) and os.path.isfile(options.config): Conf.setConfigFile(options.config) else: logger.error("configuration file is not found. (%s)" %(options.config,)) sys.exit(2) return options class ManagerStatus(object): def __init__(self, name): self.name = name self.mode = "" self.timeout = 3600 * 24 * 10 # 10 days self.totalNum = 0 self.finished_count = 0 self.fail_count = 0 self.stopped = False self.started = False self.startTime = datetime.datetime.now() self.endTime = None class Manager(object): def __init__(self, mode=None, name=None): self.mode = mode self.manager = None self.options = ManagerOption() self.name = name def initialize(self): if not self.name: self.name = "oc" + random_time_str() self.status = ManagerStatus(self.name) self.status.mode = self.mode if self.mode == 'standalone' and not self.options.workertype: logger.error("when --mode is standalone, --workertype must be specified") sys.exit(2) if self.mode == 'factory' and not self.options.warehouse: logger.error("when --mode is factory, --warehouse must be specified") sys.exit(2) if self.mode == 'local': self.scheduler = LocalScheduler(self) self.isLocal = True elif self.mode == 'process': self.scheduler = MultiProcessScheduler(self, self.options.parallel) self.isLocal = False elif self.mode == 'standalone': self.scheduler = StandaloneScheduler(self, self.options.workertype) self.isLocal = False elif self.mode == 'factory': self.scheduler = FactoryScheduler(self, Conf.getWareHouseAddr(), self.options.warehouse) self.isLocal = False elif self.mode == 'mesos': master = Conf.getMesosMaster() self.scheduler = MesosScheduler(self, master, self.options) self.isLocal = False else: logger.error("error mode, --mode should be one of [local, process, standalone, factory, mesos]") sys.exit(1) if self.options.parallel: self.defaultParallelism = self.options.parallel else: self.defaultParallelism = self.scheduler.defaultParallelism() self.initialized = True def init_cmd_option(self): self.options = parse_options() self.mode = self.mode or self.options.mode self.name = self.name or self.options.name self.initialize() def setOption(self, option): self.options = option def toNext(self, manager): self.manager = manager return manager def schedule(self, tasks): logger.debug(FactoryPatternExector.createManager(self.status)) return self.giveTask(tasks) def statusUpdate(self): self.status.totalNum = self.scheduler.taskNum self.status.finished_count = self.scheduler.finished_count self.status.fail_count = self.scheduler.fail_count self.status.stopped = self.scheduler.stopped self.status.started = self.scheduler.started self.status.endTime = datetime.datetime.now() FactoryPatternExector.updateManager(self.status) def giveTask(self, tasks): return self.scheduler.submitTasks(tasks) def terminated(self): return self.scheduler.terminated() def shutdown(self): self.scheduler.shutdown() self.status.stopped = True self.status.endTime = datetime.datetime.now() FactoryPatternExector.updateManager(self.status) def completionEvents(self): if self.mode != "factory": while True: try: yield self.scheduler.completionEvents.get_nowait() self.scheduler.completionEvents.task_done() except Queue.Empty: if self.status.totalNum == self.status.finished_count + self.status.fail_count: break if self.mode == "factory": raise Exception("please consume results from warehouse [%s,%s]!"%(Conf.getWareHouseAddr(),self.options.warehouse)) def getWaitingWorkers(self, workerType, asynchronous=False, worker=None): logger.info("getWaitingWorkers:%s" % workerType) wslist = self.getWorkerList(workerType) wklist = [] for wsinfo in wslist: wklist.append(FactoryContext.getWorker(wsinfo[0], int(wsinfo[1]), wsinfo[2], asynchronous)) return wklist def getWaitingServices(self, serviceName, asynchronous=False, worker=None): logger.info("getService:%s" % serviceName) wslist = self.getServiceList(serviceName) wklist = [] for wsinfo in wslist: wklist.append(FactoryContext.getWorker(wsinfo[0], int(wsinfo[1]), wsinfo[2], asynchronous)) return wklist def getWorkerList(self, workerType, host=None, port=None): obList = FactoryPatternExector.getWorkerTypeList(workerType); wsList = [] if not obList is None: for obj in obList: hostPort = str(obj.obj).split(":") if hostPort[0] != host or int(hostPort[1]) != port: wsList.append([hostPort[0], hostPort[1], workerType]) return wsList def getServiceList(self, serviceName, host=None, port=None): obList = FactoryPatternExector.getServiceNameList(serviceName); wsList = [] if not obList is None: for obj in obList: hostPort = str(obj.obj).split(":") if hostPort[0] != host or int(hostPort[1]) != port: wsList.append([hostPort[0], hostPort[1], serviceName]) return wsList <file_sep>""" opencluster - Python Distibuted Computing API. Copyright by www.cnlab.net """ import logging import Pyro4 from opencluster.configuration import Conf, setLogger from opencluster.servicecontext import ServiceContext from opencluster.factoryservice import FactoryService from opencluster.factorylocal import FactoryLocal from opencluster.workerlocal import WorkerLocal from opencluster.workerservice import WorkerService Pyro4.config.SERIALIZER = "pickle" Pyro4.config.SERIALIZERS_ACCEPTED = set(['pickle']) Pyro4.config.COMPRESSION = True Pyro4.config.POLLTIMEOUT = 5 Pyro4.config.SERVERTYPE = "multiplex" # multiplex or thread Pyro4.config.SOCK_REUSE = True logger = logging.getLogger(__name__) pyroLoopCondition = True def checkPyroLoopCondition() : global pyroLoopCondition return pyroLoopCondition class FactoryContext(ServiceContext): def __init__(self): super(FactoryContext,self).__init__() @staticmethod def setConfigFile(filePath): Conf.setConfigFile(filePath) @classmethod def startDefaultFactory(cls): servers = Conf.getFactoryServers() servs = servers.split(",") server = servs[0].split(":") cls.startFactory(server[0], int(server[1]), servs, Conf.getFactoryServiceName()) @classmethod def startSlaveFactory(cls): servers = Conf.getFactoryServers() servs = servers.split(",") server = servs[1].split(":") cls.startFactory(server[0], int(server[1]), servs, Conf.getFactoryServiceName()) @classmethod def startFactory(cls, host, port, servers, serviceName): global pyroLoopCondition setLogger(serviceName, port) try: d = Pyro4.Daemon(host=host, port=port) factory = FactoryService(host, port, servers, serviceName) d.register(factory, serviceName) factory.wantBeMaster() d.requestLoop(checkPyroLoopCondition) except KeyboardInterrupt, e: pyroLoopCondition = False logger.warning('stopped by KeyboardInterrupt') @classmethod def startWorker(cls, worker,workerType, host, port, workerOrService="_worker_"): global pyroLoopCondition try: d = Pyro4.Daemon(host=host, port=port) d.register(WorkerService(worker), workerType) cls.getDefaultFactory().createDomainNode(workerOrService + workerType, "".join(host.split("."))+str(port), host+":"+str(port),True) d.requestLoop(checkPyroLoopCondition) except KeyboardInterrupt ,e : pyroLoopCondition = False print "Interrupt by KeyboardInterrupt" @classmethod def getFactory(cls, host, port, servers, serviceName): return FactoryLocal(host, port, serviceName, servers) @classmethod def getDefaultFactory(cls): servers = Conf.getFactoryServers() servs = servers.split(",") server = servs[0].split(":") return cls.getFactory(server[0], int(server[1]), servs, Conf.getFactoryServiceName()) @classmethod def getWorker(cls, host, port, workerType,synchronous=False): return WorkerLocal(host, port, workerType,synchronous) @classmethod def getNodeDaemon(cls, node): return cls.getService(node.host, node.port, node.name) @classmethod def startInetServer(cls): pass if __name__ == "__main__" : FactoryContext.startDefaultFactory() <file_sep>import binascii import node from errors import * from hbdaemon import * from item import * from factoryleader import FactoryLeader logger = logging.getLogger(__name__) class FactoryService(object): def __init__(self, host, port, servers, serviceName): self.factoryLeader = FactoryLeader(host, port, serviceName, servers) self.factoryInfo = FactoryObjValue() self.hbInfo = ObjValue() self.condition = threading.Condition() def wantBeMaster(self): self.factoryLeader.wantBeMaster(self) def checkSessionId(self, sessionId): if sessionId : return sessionId else : return "se%s%s" % (str(time.time()).replace(".", ""),id(self)) def updateDomainVersion(self, domain=None): if not domain : return self.getObjectVersion(str(time.time()).replace(".", "")) domainversion = self.factoryInfo[meta.getMetaVersion(domain)] nodeversions = self.factoryInfo.getWidely(meta.getMetaVersion(domain+"\\..+")); crcstr = "".join(v for k, v in nodeversions.items()) crcversion = self.getObjectVersion(crcstr) if crcversion == domainversion : return domainversion else : return crcversion def getObjectVersion(self, crcstr): return binascii.crc32(crcstr) def getSessionId(self): return self.checkSessionId(None) def create(self, domain, node, obj, sessionId, isHeartBeat, timeout=None): ClosetoOverError.checkMemCapacity() objv = None if domain and node : #lock if self.condition.acquire() : try : domainNodeKey = FactoryObjValue.getDomainNodekey(domain, node) if not self.factoryInfo.has_key(domainNodeKey) : if not self.factoryInfo.has_key(domain) : self.factoryInfo.setObj(domain, 0l) self.factoryInfo.setObj(meta.getMetaVersion(domain), 0l) self.factoryInfo.setObj(meta.getMetaCreater(domain), sessionId) self.factoryInfo.setObj(meta.getMetaCreaterIP(domain), "") self.factoryInfo.setObj(meta.getMetaCreateTime(domain), time.time()) self.factoryInfo.setObj(meta.getMetaUpdateTime(domain), time.time()) self.factoryInfo.setObj(meta.getMetaVersion(domain), self.updateDomainVersion()) self.factoryInfo.setObj(domainNodeKey, obj) self.factoryInfo.setObj(meta.getMetaVersion(domainNodeKey), self.getObjectVersion(str(obj))) self.factoryInfo.setObj(meta.getMetaCreater(domainNodeKey), node) self.factoryInfo.setObj(meta.getMetaCreaterIP(domainNodeKey), "") self.factoryInfo.setObj(meta.getMetaCreateTime(domainNodeKey), time.time()) #self-defined timeout if timeout is not None: self.factoryInfo.setObj(meta.getMetaTimeout(domainNodeKey), timeout) nodeNum = self.factoryInfo.getObj(domain) self.factoryInfo.setObj(domain, nodeNum+1); if isHeartBeat : self.factoryInfo.setObj(meta.getMeta(domainNodeKey), meta.HEARTBEAT) self.factoryLeader.runCopyTask(domainNodeKey, self) # print self.factoryInfo objv = self.get(domain, node, sessionId) else : logger.info("%s is exist,updating!" %(domainNodeKey)) self.update(domain,node,obj,sessionId) except Exception,e: logger.error("factoryservice.create:"+e) finally : #unlock self.condition.release() return objv def update(self, domain, node, obj, sessionId): ClosetoOverError.checkMemCapacity() objv = None if domain and node : if self.condition.acquire() : try : domainNodeKey = FactoryObjValue.getDomainNodekey(domain, node) #if canWrite if self.factoryInfo.has_key(domainNodeKey) : self.factoryInfo.setObj(domainNodeKey, obj) theversion = self.getObjectVersion(str(obj)); if theversion != self.factoryInfo[meta.getMetaVersion(domainNodeKey)] : self.factoryInfo.setObj(meta.getMetaVersion(domainNodeKey), theversion) self.factoryInfo.setObj(meta.getMetaVersion(domain), self.updateDomainVersion()) self.factoryInfo.setObj(meta.getMetaUpdater(domainNodeKey), sessionId) self.factoryInfo.setObj(meta.getMetaUpdaterIP(domainNodeKey), "") self.factoryInfo.setObj(meta.getMetaUpdateTime(domainNodeKey), time.time()) #logger.info(self.factoryInfo) self.factoryLeader.runCopyTask(domainNodeKey, self) objv = self.get(domain, node, sessionId) else : logger.info("%s is not exist!" %(domainNodeKey)) except Exception,e: logger.error("factoryservice.update:"+e) finally : #unlock self.condition.release() return objv def delete(self, domain, node, sessionId=None): objv = None if domain : if not node : ClosetoOverError.checkMemCapacity() if self.condition.acquire() : try : domainNodeKey = FactoryObjValue.getDomainNodekey(domain, node) objv = self.factoryInfo.removeNode(domain, node) if len(objv.items()) > 0 : nodeNum = self.factoryInfo.getObj(domain) if nodeNum : if nodeNum==1 : self.factoryInfo.removeDomain(domain) else : self.factoryInfo.setObj(domain,nodeNum-1) self.factoryLeader.runCopyTask(domainNodeKey,self) else : objv = None logger.info(domainNodeKey + " cant be deleted or not exist!") except Exception,e: logger.error(e) finally : #unlock self.condition.release() return objv def get(self, domain, node, sessionId) : ov = None if domain : if node is None : ClosetoOverError.checkMemCapacity() if self.condition.acquire() : try : # logger.info("get:%s"%FactoryObjValue.getDomainNodekey(domain,node)) ov = self.factoryInfo.getNode(domain, node) if ov.isEmpty() : ov = None finally : self.condition.release() #unlock return ov def getNodesByPrefix(self,prefix): ov = None ClosetoOverError.checkMemCapacity() if self.condition.acquire() : try : # logger.info("get:%s"%FactoryObjValue.getDomainNodekey(domain,node)) ov = self.factoryInfo.getNodeByPrefix(prefix) if ov.isEmpty() : ov = None finally : self.condition.release() #unlock return ov def getLatest(self, domain, node, sessionId,version) : ov = None if self.condition.acquire() : try : nodeVersion = self.factoryInfo.getObj(meta.getMetaVersion(FactoryObjValue.getDomainNodekey(domain,node))) if nodeVersion and nodeVersion!=version : self.get(domain,node,sessionId) logger.info("getLastest:%s,%s" % (nodeVersion,version)) finally : self.condition.release() return ov def getTheFactoryInfo(self): if self.condition.acquire() : try : ov = self.factoryInfo.getFactoryInfo() finally : self.condition.release() return ov def getFactoryInfo(self): # logger.info("getFactoryinfo from %s" % (self.getClientHost())) return self.getTheFactoryInfo() def setFactoryInfo(self, objValue):#need write lock if self.condition.acquire() : try : self.factoryInfo = objValue finally : self.condition.release() return True def askMaster(self): logger.info("receive askMaster................") return self.factoryLeader.getMaster() def askLeader(self): logger.info("receive askLeader................") sv = [] if self.factoryLeader.checkMasterFactory(sv, self) : return True else : return False def heartbeat(self, domainNodeKeys, sessionId): retValue = False if domainNodeKeys : self.hbInfo.setObj(domainNodeKeys, time.time()) domainNodes = domainNodeKeys.split(HbDaemon.vs) if self.get(domainNodes[0],domainNodes[1],sessionId): retValue = True HbDaemon.runGetTask(self.hbInfo, self) return retValue def getClientHost(self): return "" def buildServices(self,node): pass #end <file_sep>import sys import os sys.path.extend([os.path.join(os.path.abspath(os.path.dirname(__file__)),'..')]) from opencluster.factory import FactoryContext FactoryContext.startDefaultFactory() <file_sep>#!/usr/bin/env python import os import sys import time import datetime import socket import random from optparse import OptionParser import threading import logging import signal import marshal import cPickle import MySQLdb import Pyro4 from opencluster.configuration import Conf, setLogger from opencluster.env import env from opencluster.item import TaskStateName from opencluster.util import getuser, safe, decompress, spawn,compress,mkdir_p from mesos.native import MesosExecutorDriver, MesosSchedulerDriver from mesos.interface import Executor, Scheduler, mesos_pb2 from kafka import KafkaConsumer, KafkaClient, SimpleProducer logger = logging.getLogger(__name__) EXECUTOR_MEMORY = 64 # cache MAX_WAITING_TASK = 1000 MAX_EMPTY_TASK_PERIOD = 1 pyroLoopCondition = True def checkPyroLoopCondition() : global pyroLoopCondition return pyroLoopCondition class FactoryMesos(object): def __init__(self, options, command,implicitAcknowledgements): self.framework_id = None self.executor = None self.implicitAcknowledgements = implicitAcknowledgements self.framework = mesos_pb2.FrameworkInfo() self.framework.user = getuser() # if self.framework.user == 'root': # raise Exception("drun is not allowed to run as 'root'") name = 'OpenCluster-Factory' if len(name) > 256: name = name[:256] + '...' self.framework.name = name self.framework.hostname = socket.gethostname() self.options = options self.command = command self.tasks_waiting = {} self.task_launched = {} self.slaveTasks = {} self.stopped = False self.status = 0 self.last_offer_time = time.time() self.lock = threading.RLock() self.priority_size = 4 self.warehouse_addrs = self.options.warehouse_addr.split(",") self.outputdb = None self.kafka_client = None self.producer = None if len(self.warehouse_addrs) > 2: mysqlIpAndPort = self.warehouse_addrs[0].split(":") self.outputdb = MySQLdb.connect(host=mysqlIpAndPort[0], port = int(mysqlIpAndPort[1]), db =self.warehouse_addrs[1],user=self.warehouse_addrs[2],passwd=self.warehouse_addrs[3]) else: self.kafka_client = KafkaClient(self.options.warehouse_addr) self.producer = SimpleProducer(self.kafka_client) for i in range(1,self.priority_size+1): self.tasks_waiting[i] = [] def getExecutorInfo(self): execInfo = mesos_pb2.ExecutorInfo() execInfo.executor_id.value = "default" execInfo.command.value = '%s %s' % ( sys.executable, # .../python.exe os.path.abspath(os.path.join(os.path.dirname(__file__), 'simpleexecutor.py')) ) v = execInfo.command.environment.variables.add() v.name = 'UID' v.value = str(os.getuid()) v = execInfo.command.environment.variables.add() v.name = 'GID' v.value = str(os.getgid()) if hasattr(execInfo, 'framework_id'): execInfo.framework_id.value = str(self.framework_id) if self.options.image and hasattr(execInfo, 'container'): logger.debug("container will be run in Docker") execInfo.container.type = mesos_pb2.ContainerInfo.DOCKER execInfo.container.docker.image = self.options.image execInfo.command.value = '%s %s' % ( sys.executable, # /usr/bin/python.exe or .../python os.path.abspath(os.path.join(os.path.dirname(__file__), 'simpleexecutor.py')) ) for path in ['/etc/passwd', '/etc/group']: v = execInfo.container.volumes.add() v.host_path = v.container_path = path v.mode = mesos_pb2.Volume.RO if self.options.volumes: for volume in self.options.volumes.split(','): fields = volume.split(':') if len(fields) == 3: host_path, container_path, mode = fields mode = mesos_pb2.Volume.RO if mode.lower() == 'ro' else mesos_pb2.Volume.RW elif len(fields) == 2: host_path, container_path = fields mode = mesos_pb2.Volume.RW elif len(fields) == 1: container_path, = fields host_path = '' mode = mesos_pb2.Volume.RW else: raise Exception("cannot parse volume %s", volume) mkdir_p(host_path) v = execInfo.container.volumes.add() v.container_path = container_path v.mode = mode if host_path: v.host_path = host_path Script = os.path.realpath(sys.argv[0]) if hasattr(execInfo, 'name'): execInfo.name = Script execInfo.data = marshal.dumps((Script, os.getcwd(), sys.path, dict(os.environ), self.options.task_per_node, env.environ)) return execInfo def registered(self, driver, fid, masterInfo): logger.debug("Registered with Mesos, FID = %s" % fid.value) self.framework_id = fid.value self.executor = self.getExecutorInfo() def getResources(self, offer): gpus,cpus, mem = 0, 0, 0 for r in offer.resources: if r.name == 'gpus': gpus += float(r.scalar.value) elif r.name == 'cpus': cpus += float(r.scalar.value) elif r.name == 'mem': mem += float(r.scalar.value) return cpus, mem, gpus def getAttributes(self, offer): attrs = {} for a in offer.attributes: attrs[a.name] = a.scalar.value return attrs @safe def append_task(self,t): self.tasks_waiting[t.priority].append(t) @safe def tasks_len(self,priority): return len(self.tasks_waiting[priority]) @safe def tasks_total_len(self): return sum(len(v) for (k,v) in self.tasks_waiting.items()) @safe def get_task_of_waiting_by_id(self,tid): for (k,v) in self.tasks_waiting.items(): for t in v: if t.id == tid: return t return None @safe def pop_task(self,priority): return self.tasks_waiting[priority].pop() @safe def remove_task(self,t): return self.tasks_waiting[t.priority].remove(t) @safe def waiting_tasks(self,priority): return self.tasks_waiting[priority] @safe def resourceOffers(self, driver, offers): rf = mesos_pb2.Filters() rf.refuse_seconds = 60 if self.tasks_total_len()==0: for o in offers: driver.launchTasks(o.id, [], rf) return random.shuffle(offers) self.last_offer_time = time.time() for offer in offers: attrs = self.getAttributes(offer) if self.options.group and attrs.get('group', 'None') not in self.options.group: driver.launchTasks(offer.id, [], rf) continue cpus, mem, gpus = self.getResources(offer) logger.debug("got resource offer %s: cpus:%s, mem:%s, gpus:%s at %s", offer.id.value, cpus, mem, gpus, offer.hostname) sid = offer.slave_id.value tasks = [] for priority in range(1,self.priority_size+1): for t in self.waiting_tasks(priority): if priority > 1 and cpus <=1 : break if cpus>=t.resources.get("cpus",1) and mem>= t.resources.get("mem",100) and (t.resources.get("gpus",0)==0 or attrs.get('gpus', None) is not None) : self.remove_task(t) t.state = mesos_pb2.TASK_STARTING t.state_time = time.time() task = self.create_task(offer, t) tasks.append(task) self.task_launched[t.id] = t self.slaveTasks.setdefault(sid, set()).add(t.id) cpus -= t.resources.get("cpus",1) mem -= t.resources.get("mem",100) operation = mesos_pb2.Offer.Operation() operation.type = mesos_pb2.Offer.Operation.LAUNCH operation.launch.task_infos.extend(tasks) driver.acceptOffers([offer.id], [operation]) if len(tasks) > 0: logger.debug("dispatch %d tasks to slave %s", len(tasks), offer.hostname) def create_task(self, offer, t): task = mesos_pb2.TaskInfo() task.task_id.value = str(t.id) task.slave_id.value = offer.slave_id.value task.name = "%s-%s" % (t.id, t.tried) task.executor.MergeFrom(self.executor) task.data = compress(cPickle.dumps((t, t.tried), -1)) cpu = task.resources.add() cpu.name = "cpus" cpu.type = 0 # mesos_pb2.Value.SCALAR cpu.scalar.value = t.resources.get("cpus",1) mem = task.resources.add() mem.name = "mem" mem.type = 0 # mesos_pb2.Value.SCALAR mem.scalar.value = t.resources.get("mem",100) # gpu = task.resources.add() # gpu.name = "gpus" # gpu.type = 0 # mesos_pb2.Value.SCALAR # gpu.scalar.value = t.resources.get("gpus",1) return task def statusUpdate(self, driver, update): logger.debug("Task %s in state [%s]" % (update.task_id.value, mesos_pb2.TaskState.Name(update.state))) tid = update.task_id.value if tid not in self.task_launched: t = self.get_task_of_waiting_by_id(tid) if t: self.task_launched[tid] = t self.remove_task(t) else: logger.debug("Task %s is finished, ignore it", tid) return t = self.task_launched[tid] t.state = update.state t.state_time = time.time() if update.state == mesos_pb2.TASK_RUNNING: #self.task_update(t,update.state,'') pass elif update.state in (mesos_pb2.TASK_FINISHED, mesos_pb2.TASK_FAILED, mesos_pb2.TASK_LOST): t = self.task_launched.pop(tid) slave = None for s in self.slaveTasks: if tid in self.slaveTasks[s]: slave = s self.slaveTasks[s].remove(tid) break if update.state == mesos_pb2.TASK_FINISHED: self.task_update(t,update.state,update.data) if update.state >= mesos_pb2.TASK_FAILED: if t.tried < self.options.retry: t.tried += 1 logger.warning("task %s failed with %s, retry %s", t.id, TaskStateName[int(update.state)], t.tried) self.append_task(t) # try again else: logger.error("task %s failed with %s on %s", t.id, update.state, slave) self.task_update(t,update.state,str(update.data)) # Explicitly acknowledge the update if implicit acknowledgements # are not being used. if not self.implicitAcknowledgements: driver.acknowledgeStatusUpdate(update) def task_update(self,t,status,result): if status!=mesos_pb2.TASK_FINISHED: t.result = Exception(str(result)) else: t.result = cPickle.loads(decompress(result)) if len(self.warehouse_addrs) > 2: cur = self.outputdb.cursor() value=[status,result,t.id] cur.execute("update t_task set status=%s,result=%s,task_end_time=now() where task_id=%s",value) self.outputdb.commit() cur.close() else: try : self.producer.send_messages("%sResult"%(t.warehouse), cPickle.dumps(t)) except Exception,e: logger.error(e) @safe def check(self, driver): now = time.time() #logger.debug("tasks_waiting:%d,task_launched:%d"%(len(self.tasks_waiting),len(self.task_launched.items()))) for tid, t in self.task_launched.items(): if t.state == mesos_pb2.TASK_STARTING and t.state_time + 60*60 < now: logger.warning("task %s lauched failed, assign again", tid) t.tried += 1 self.task_launched.pop(tid) if t.tried <= self.options.retry : t.state = -1 self.append_task(t) else: self.task_update(t,mesos_pb2.TASK_FAILED,"run timeout") # TODO: check run time if self.tasks_total_len()>0: driver.reviveOffers() # request more offers again def offerRescinded(self, driver, offer): logger.debug("resource rescinded: %s", offer) # task will retry by checking def slaveLost(self, driver, slave): logger.warning("slave %s lost", slave.value) @safe def error(self,driver,code): logger.error("Error from Mesos: %s" % (code)) @safe def stop(self, status): if self.stopped: return self.stopped = True self.status = status if self.outputdb: self.outputdb.close() if self.kafka_client : self.kafka_client.close() logger.debug("scheduler stopped") def start_factory_mesos(): global pyroLoopCondition parser = OptionParser(usage="Usage: python factorymesos.py [options] <command>") parser.allow_interspersed_args=False parser.add_option("-s", "--master", type="string", default="", help="url of master (mesos://172.31.252.180:5050)") parser.add_option("-f", "--factory", type="string", default="", help="host:port of master (172.31.252.180:6666)") parser.add_option("-w", "--warehouse_addr", type="string", default="", help="kafka-172.31.252.182:9092|mysql-172.31.254.25:3306,db,username,password") parser.add_option("-p", "--task_per_node", type="int", default=0, help="max number of tasks on one node (default: 0)") parser.add_option("-I", "--image", type="string", help="image name for Docker") parser.add_option("-V", "--volumes", type="string", help="volumes to mount into Docker") parser.add_option("-r","--retry", type="int", default=0, help="retry times when failed (default: 0)") parser.add_option("-e", "--config", type="string", default="/work/opencluster/config.ini", help="absolute path of configuration file(default:/work/opencluster/config.ini)") parser.add_option("-g","--group", type="string", default='', help="which group to run (default: ''") parser.add_option("-q", "--quiet", action="store_true", help="be quiet", ) parser.add_option("-v", "--verbose", action="store_true", help="show more useful log", ) (options, command) = parser.parse_args() if not options: parser.print_help() sys.exit(2) if options.config: Conf.setConfigFile(options.config) options.master = options.master or Conf.getMesosMaster() options.warehouse_addr = options.warehouse_addr or Conf.getWareHouseAddr() servers = options.factory or Conf.getFactoryServers() servs = servers.split(",") server = servs[0].split(":") options.logLevel = (options.quiet and logging.ERROR or options.verbose and logging.DEBUG or logging.INFO) setLogger(Conf.getFactoryServiceName(), "MESOS",options.logLevel) implicitAcknowledgements = 1 if os.getenv("MESOS_EXPLICIT_ACKNOWLEDGEMENTS"): implicitAcknowledgements = 0 sched = FactoryMesos(options, command, implicitAcknowledgements) driver = MesosSchedulerDriver(sched, sched.framework, options.master,implicitAcknowledgements) driver.start() logger.debug("Mesos Scheudler driver started") warehouse_addrs = options.warehouse_addr.split(",") def fetchTasksFromMySQL(): global pyroLoopCondition mysqlIpAndPort = warehouse_addrs[0].split(":") last_data_time = time.time() while pyroLoopCondition: db = MySQLdb.connect(host=mysqlIpAndPort[0], port = int(mysqlIpAndPort[1]), db =warehouse_addrs[1],user=warehouse_addrs[2],passwd=warehouse_addrs[3]) try : cur = db.cursor() curUpt = db.cursor() dataResults = cur.execute("select task_id,task_desc,task_start_time,status from t_task where status=0 order by priority asc limit 200") results = cur.fetchmany(dataResults) for r in results : sched.append_task(cPickle.loads(r[1])) curUpt.execute("update t_task set task_start_time=now(),status=1 where task_id='" + r[0] + "'") if len(results) > 0: db.commit() last_data_time = time.time() driver.reviveOffers() if sched.tasks_total_len() > MAX_WAITING_TASK : time.sleep(2) if time.time() - last_data_time > MAX_EMPTY_TASK_PERIOD: time.sleep(10) if cur: cur.close() if curUpt: curUpt.close() finally: db.close() def fetchTasksFromKafka(priority): global pyroLoopCondition consumer = KafkaConsumer('OpenCluster%s'%priority, bootstrap_servers=[options.warehouse_addr], group_id="cnlab", auto_commit_enable=True, auto_commit_interval_ms=30 * 1000, auto_offset_reset='smallest') last_data_time = time.time() while pyroLoopCondition: for message in consumer.fetch_messages(): logger.error("%s:%s:%s: key=%s " % (message.topic, message.partition, message.offset, message.key)) sched.append_task(cPickle.loads(message.value)) consumer.task_done(message) last_data_time = time.time() if sched.tasks_len(priority) > MAX_WAITING_TASK : time.sleep(2) if time.time() - last_data_time > MAX_EMPTY_TASK_PERIOD: time.sleep(10) if len(warehouse_addrs) > 2: spawn(fetchTasksFromMySQL) else: for i in range(1,sched.priority_size+1): spawn(fetchTasksFromKafka, i) def handler(signm, frame): logger.warning("got signal %d, exit now", signm) sched.stop(3) signal.signal(signal.SIGTERM, handler) signal.signal(signal.SIGABRT, handler) try: while not sched.stopped: time.sleep(0.5) sched.check(driver) now = time.time() if now > sched.last_offer_time + 60 + random.randint(0,5): logger.warning("too long to get offer, reviving...") sched.last_offer_time = now driver.reviveOffers() except KeyboardInterrupt: logger.warning('stopped by KeyboardInterrupt. The Program is exiting gracefully! Please wait...') sched.stop(4) #terminate pyrothread pyroLoopCondition = False time.sleep(5) driver.stop(False) sys.exit(sched.status) if __name__ == "__main__": start_factory_mesos()<file_sep>import logging import Queue import hbdaemon import Pyro4 import time import traceback from opencluster.errors import LeaderError from opencluster.configuration import Conf from opencluster.servicecontext import ServiceContext logger = logging.getLogger(__name__) class FactoryLeader(object): def __init__(self, host, port, serviceName, servers = None): self.master = False self.alwaysTry = Conf.getAlwaysTryLeader() self.serviceName = serviceName self.thisServer = "%s:%s" % (host, port) self.groupServers = servers self.queue = Queue.Queue() self.rpl = None def getThisServer(self): return self.thisServer def wantBeMaster(self, factoryservice): logger.info("wantBeMaster.............................") sv = [] othermaster = self.getOtherMasterFactory(sv) if not othermaster : logger.info("get one of other factorys for init factoryInfo.........") pks = self.getOtherFactory() if len(pks) > 0 : self.setInitFactoryInfo(pks[0], factoryservice) self.setMaster(True, factoryservice) else : logger.info("but master is %s:%s" % (sv[0], sv[1])) def getLeaderFactory(self): index = self.getLeaderIndex(self.thisServer) return self.electionLeader(-1, index) def getNextLeader(self): logger.info("getNextLeader........") index = self.getLeaderIndex(self.thisServer) return self.electionLeader(index, index+1) def electionLeader(self, begin, index): theOk = False if index >= len(self.groupServers) : index = 0 server = self.groupServers[index].split(":") factoryService = None try : factoryService = ServiceContext.getService(server[0], int(server[1]), self.serviceName) logger.debug(factoryService) if factoryService and factoryService.askLeader(): theOk = True except Exception , e : logger.error("electionLeader2 %s:%s----%s" % (server[0], server[1], e)) theOk = False if begin != index : if not self.alwaysTry and begin < 0: begin = index time.sleep(3) factoryService = self.electionLeader(begin, index + 1) if theOk : self.thisServer = self.groupServers[index] logger.info("leader server is %s:%s" % (server[0], server[1])) return factoryService def electionFixedLeader(self, index): theOk = True if index >= len(self.groupServers) : index = 0 server = self.groupServers[index].split(":") factoryService = None try : factoryService = ServiceContext.getService(server[0], int(server[1]), self.serviceName) if factoryService : factoryService.askLeader() except LeaderError , le : logger.error("electionLeader %s:%s----:%s" % (server[0], server[1], le)) theOk = False leaderIndex = self.getLeaderIndex(le.getLeaderServer()) factoryService = self.electionLeader(leaderIndex) except Exception , e : logger.error("electionLeader %s:%s----:%s" % (server[0], server[1], e)) theOk = False factoryService = self.electionLeader(index + 1) if theOk : self.thisServer = self.groupServers[index] logger.info("leader server is %s:%s" % (server[0], server[1])) return factoryService def getLeaderIndex(self, sa): i = 0; for server in self.groupServers : if sa == server : break i += 1 return i def setMaster(self, isMaster, factory): self.master = isMaster if isMaster : logger.info("leader server is %s" % self.thisServer) if self.master : hbdaemon.HbDaemon.runClearTask(factory) def getMaster(self): try : if self.master : return self.thisServer.split(":") except Exception,e : logger.error(e) def getOtherFactory(self): factorys = [] for str in self.groupServers : if str != self.thisServer : server = str.split(":") try : pk = ServiceContext.getService(server[0], int(server[1]), self.serviceName) clientHost = pk.getClientHost()#check alive state,if not connected,raise CommunicationError factorys.append(pk) except Exception,e : if isinstance(e,Pyro4.errors.CommunicationError) : logger.error("%s maybe is shutdown,can't connected." % str) return factorys def checkMasterFactory(self, sv, factory): if self.master or not self.getOtherMasterFactory(sv) : sv = self.thisServer.split(":") self.setMaster(True, factory) return True else : return False def getOtherMasterFactory(self, sv): pkMaster = None try : for pk in self.getOtherFactory() : ask = pk.askMaster() if ask : pkMaster = pk sv.append(ask[0]) sv.append(ask[1]) except Exception, e : logger.error("getOtherMasterFactory...Error:%s" % e) return pkMaster def setInitFactoryInfo(self, fromFactory, toFactory): try : toFactory.setFactoryInfo(fromFactory.getFactoryInfo()) except Exception, e : logger.error("setInitFactoryInfo...Error:%s" % e) def runCopyTask(self, domainNodeKey, factory): logger.info("runCopyTask:"+domainNodeKey+"............................") # def task(vfactory, queue): # curKey = queue.get() # if queue.empty() : # self.copyFactoryInfo(vfactory.getFactoryInfo()) # self.queue.put(domainNodeKey) # self.rpl = AsyncExector(task , (factory, self.queue)) # self.rpl.run() try: obj = factory.getFactoryInfo() for pk in self.getOtherFactory() : pk.setFactoryInfo(obj) except Exception,e: logger.error("runCopyTask error:%s"%e) def copyFactoryInfo(self, obj): sendlist = [] for factory in self.getOtherFactory() : sendlist.append(factory.setFactoryInfo(obj)) return sendlist #end <file_sep>import sys import os sys.path.extend([os.path.join(os.path.abspath(os.path.dirname(__file__)),'..')]) from opencluster.factorymesos import start_factory_mesos start_factory_mesos() <file_sep>import sys import os import time import datetime import random import cPickle sys.path.extend([os.path.join(os.path.abspath(os.path.dirname(__file__)),'..')]) from opencluster.util import decompress from opencluster.item import Task,Success from opencluster.manager import Manager from opencluster.configuration import Conf loopCondition = True class HelloManager(Manager) : def __init__(self): super(HelloManager,self).__init__() if __name__ == "__main__" : def check_kafka_events(): global loopCondition from kafka import KafkaConsumer, KafkaClient, SimpleProducer warehouse_addr = Conf.getWareHouseAddr() consumer = KafkaConsumer("%sResult"%wk.options.warehouse, bootstrap_servers=[warehouse_addr], group_id="cnlab", auto_commit_enable=True, auto_commit_interval_ms=30 * 1000, auto_offset_reset='smallest') while loopCondition: for message in consumer.fetch_messages(): print "topic=%s, partition=%s, offset=%s, key=%s " % (message.topic, message.partition, message.offset, message.key) task = cPickle.loads(message.value) if task.state == Task.TASK_FINISHED: print "taskId:%s,success!!!:%s"%(task.id,task.result) else: print "taskId:%s,failed!!!"%task.id consumer.task_done(message) last_data_time = time.time() if not loopCondition: break wk = HelloManager() wk.init_cmd_option() try : #update 2016-10-10 tasks = [] start = time.time() for i in range(0,5) : j = str(random.randint(0, 9000000)).ljust(7,'0') taskId = "%s%s" % (datetime.datetime.now().strftime("%Y%m%d%H%M%S%f"),j) task = Task(taskId,workerClass="helloWorker.HelloWorker",workDir = os.path.dirname(os.path.abspath(__file__))) task.data = taskId + " world" # task.priority = 1 # task.resources = {"cpus":1,"mem":100,"gpus":0} # task.warehouse = wk.options.warehouse bt = time.time() tasks.append(task) tasksLen = len(tasks) wk.schedule(tasks) i = 1 if wk.mode=="factory": check_kafka_events() else: for e in wk.completionEvents() : if isinstance(e.reason,Success) : print i,e.task.id,cPickle.loads(decompress(e.result)) else: print i,"Failed:" + str(e.reason.message) i += 1 print "%d tasks finished in %.1f seconds" % (tasksLen, time.time() - start) time.sleep(1) wk.shutdown() except KeyboardInterrupt: print "stopped by KeyboardInterrupt" loopCondition = False sys.exit(1) <file_sep>Pyro4 pyzmq psutil web.py<file_sep>import web t_globals = dict( datestr=web.datestr, ) render = web.template.render('templates/', cache=False, globals=t_globals) render._keywords['globals']['render'] = render def listing(**k): return render.listing()<file_sep>__all__ = ['main','view'] <file_sep>import sys import os import socket sys.path.extend([os.path.join(os.path.abspath(os.path.dirname(__file__)),'..')]) from opencluster.nodedaemon import NodeDademon from opencluster.configuration import Conf if __name__ == "__main__" : if len(sys.argv) != 2 : print "Usage : %s LocalIP" % sys.argv[0] sys.exit(1) NodeDademon(sys.argv[1],Conf.getNodeDefaultPort(),"".join(sys.argv[1].split(".")))<file_sep># -*- coding: UTF-8 -*- import os,time import MySQLdb import pika import urlparse def on_message(channel, method_frame, header_frame, body): channel.queue_declare(queue=body, auto_delete=True) if body.startswith("queue:"): queue = body.replace("queue:", "") key = body + "_key" print("Declaring queue %s bound with key %s" %(queue, key)) channel.queue_declare(queue=queue, auto_delete=True) channel.queue_bind(queue=queue, exchange="test_exchange", routing_key=key) else: print("Message body", body) channel.basic_ack(delivery_tag=method_frame.delivery_tag) if __name__ == "__main__" : db = MySQLdb.connect(db="pcims", user="root",passwd="wsl",host="localhost",port=3306,charset="utf8") cur = db.cursor() list_dirs = os.walk("J:\\pcims") values = [] for root, dirs, files in list_dirs: # files = files.map(lambda f: f.split("\\")[-1]) for f in files: f = f.split("\\")[-1] strs = f.split("+") if len(strs) == 6: values.append((strs[2].decode('gbk').encode("utf-8"),str(strs[0]),strs[3]+"*"+strs[4],str(strs[5]).split(".")[0].decode('gbk').encode("utf-8"),strs[1].decode('gbk').encode("utf-8"),"/uploads/overview/"+f.decode('gbk').encode("utf-8"),"00","1")) else: print(strs) try : cur = db.cursor() n = cur.executemany("insert into t_work (title,work_no,work_size,work_type,author_name,overview,create_time,status,create_user) values(%s,%s,%s,%s,%s,%s,now(),%s,%s)",values) db.commit() except Exception,e : print("insert t_work error:%s"%e) <file_sep>import sys import signal import socket import Pyro4 import zmq from opencluster.configuration import Conf, setLogger from opencluster.node import * from opencluster.factorypatternexector import FactoryPatternExector from opencluster.errors import * from opencluster.service import * from opencluster.process import ServiceProcess, WorkerProcess from opencluster.util import spawn Pyro4.config.SERIALIZER = "pickle" Pyro4.config.SERIALIZERS_ACCEPTED = set(['pickle']) Pyro4.config.COMPRESSION = True Pyro4.config.SERVERTYPE = "multiplex" # multiplex or thread logger = logging.getLogger(__name__) pyroLoopCondition = True pyroUri = None def checkPyroLoopCondition() : global pyroLoopCondition return pyroLoopCondition class NodeService(object) : def __init__(self,node): self.node = node self.nodeFile = NodeFile(self.node.diskPath) def startNewWorker(self,workerType): logger.info("start new worker instance of " + workerType) if workerType not in self.node.availWorkers : return ServiceError( workerType + " is not supported in this node.") workerPro = self.node.availWorkers[workerType] return workerPro.start() def getNode(self): return self.node def stopWorker(self,workerType,port): logger.info("kill worker instance of %s:%s"%(workerType,port)) workerType = workerType[8:] #workertype like "_worker_workerUVFITS" if workerType not in self.node.availWorkers : logger.info(workerType + " is not supported in this node.") return ServiceError( workerType + " is not supported in this node.") workerPro = self.node.availWorkers[workerType] return workerPro.stop(port) def stopAllWorker(self,workerType): logger.info("kill worker instance of %s"%(workerType)) if workerType not in self.node.availWorkers : logger.info(workerType + " is not supported in this node.") return ServiceError( workerType + " is not supported in this node.") workerPro = self.node.availWorkers[workerType] return workerPro.stopAll() def startNewService(self,serviceName): logger.info("start new service instance of " + serviceName) if serviceName not in self.node.availServices : return ServiceError( serviceName + " is not supported in this node.") servicePro = self.node.availServices[serviceName] return servicePro.start() def stopService(self,serviceName,port): logger.info("kill service instance of %s:%s"%(serviceName,port)) serviceName = serviceName[9:] #serviceName like "_service_XXXX" if serviceName not in self.node.availServices : return ServiceError( serviceName + " is not supported in this node.") servicePro = self.node.availServices[serviceName] return servicePro.stop(port) def stopAllService(self,serviceName): logger.info("kill all service instance of %s"%(serviceName)) if serviceName not in self.node.availServices : return ServiceError(serviceName + " is not supported in this node.") servicePro = self.node.availServices[serviceName] return servicePro.stopAll() ''' file operation--------------------------------------------------------------------------- ''' def listFiles(self,relFilePath): return self.nodeFile.listDir(relFilePath) def fReadByte(self,fileName,begin,length): return self.nodeFile.readByte(fileName,begin,length) def fReadFile(self,fileName): return self.nodeFile.readWholeFile(fileName) def fWriteByte(self,fileName,begin,length): pass def fWriteFile(self,fileName,fileByte): return self.nodeFile.writeFile(fileName,fileByte) def fcreate(self,fileName): pass def fCreateDir(self,curDir,dirName): self.nodeFile.createDir(curDir,dirName) def fDelete(self,fileName): return self.nodeFile.remove(fileName) def fcopy(self,fileName): pass def fRename(self,fileName,newName): return self.nodeFile.rename(fileName,newName) class NodeDademon(object): def __init__(self,host, port, name): global pyroLoopCondition global pyroUri setLogger("Node-%s"%host,port) self.node = Node(host, port, "Node" + name) for workerStr in Conf.getNodeAvailWorkers().split(",") : worker = workerStr.split("|") self.node.availWorkers[worker[0]] = WorkerProcess(host,worker[0],worker[1]) for serviceStr in Conf.getNodeAvailServices().split(",") : service = serviceStr.split("|") self.node.availServices[service[0]] = ServiceProcess(host,service[0],service[1]) self.node = self.node.calRes() def runNodeService(): global pyroUri,pyroLoopCondition d = Pyro4.Daemon(host=host, port=port) pyroUri = d.register(NodeService(self.node), self.node.name) d.requestLoop(checkPyroLoopCondition) spawn(runNodeService) time.sleep(1) logger.info("Node:%s started...uri:%s" % (self.node.name,pyroUri)) try : FactoryPatternExector.createPhysicalNode(self.node.calRes()) self.start() except KeyboardInterrupt: pyroLoopCondition = False logger.warning('stopped by KeyboardInterrupt') sys.exit(1) def start(self): context = zmq.Context(1) backend = context.socket(zmq.ROUTER) # ROUTER backend.bind("tcp://*:%s" % Conf.getNodePortForService()) # For services poll_services = zmq.Poller() poll_services.register(backend, zmq.POLLIN) heartbeat_at = time.time() + Conf.getExpiration() while checkPyroLoopCondition(): socks = dict(poll_services.poll((Conf.getExpiration()-1) * 1000)) # Handle service activity on backend if socks.get(backend) == zmq.POLLIN: # Use service address for LRU routing frames = backend.recv_multipart() if not frames: break addressList = str(frames[0]).split(":") address = addressList[0] port = int(addressList[1]) serviceName = addressList[2] self.node.services.pop("%s:%s:%s"%(address,port,serviceName),None) self.node.services["%s:%s:%s"%(address,port,serviceName)] = Service(address,port,serviceName) ov = FactoryPatternExector.createServiceNode(address,port,serviceName) msg = frames[1:] if len(msg) == 1: if msg[0] not in (Conf.PPP_READY, Conf.PPP_HEARTBEAT): logger.error("Invalid message from service: %s" % msg) if time.time() >= heartbeat_at: for service in self.node.services: msg = [service, Conf.PPP_HEARTBEAT] backend.send_multipart(msg) heartbeat_at = time.time() + Conf.HEARTBEAT_INTERVAL expired = [] t = time.time() for address,service in self.node.services.iteritems(): if t > service.expiry: # Worker expired expired.append(address) for address in expired: logger.info("Service expired: %s" % address) self.node.services.pop(address, None) #update node of factory FactoryPatternExector.updatePhysicalNode(self.node.calRes()) #end while true #end def start() #end class NodeDademon if __name__ == "__main__" : def handler(signm, frame): global pyroLoopCondition pyroLoopCondition = False logger.warning("got signal %d, exit now", signm) sys.exit(1) signal.signal(signal.SIGTERM, handler) signal.signal(signal.SIGABRT, handler) NodeDademon("localhost",Conf.getNodeDefaultPort(),socket.gethostname()) <file_sep>from distutils.core import setup setup( name='opencluster', version='1.0', packages=['opencluster'], package_dir={'opencluster': 'opencluster'}, url='', license='', author='<NAME>', author_email='<EMAIL>', requires=['psutil','Pyro4','web.py'], description='' ) <file_sep>[factory] service = FactoryService servers = localhost:6666,localhost:6667,localhost:6668 mesos = zk://172.31.252.180:2181/mesos warehouse= 172.31.254.24:9092 #warehouse= 172.31.254.25:3306,muser,muser,muser safeMemoryPerNode = 100 heartbeat = 5 maxdelay = 2 alwaysTryLeader = true #hour expiration = 10 clearPeriod = 8 alwaysTryLeader = True startWebapp = True [worker] timeout = 2 [webapp] servers = 0.0.0.0:31528 users = admin:admin,guest:123456,test:test static_full_path = /astrodata/opencluster/opencluster/ui/res templates_path = /templates/ [node] defaultPort = 29999 portForService = 30000 diskPath = /astrodata workerDir = /astrodata/opencluster/sbin serviceDir = /astrodata/opencluster/sbin availWorkers = helloWorker|../examples/helloWorker.py,realTimeWorker|../ocscripts/realTimeWorker.py,fitsWorker|../ocscripts/fitsWorker.py,gcleanWorker|../ocscripts/gcleanWorker.py availServices = antennaService|../ocscripts/antennaService.py,calibrationService|../ocscripts/calibrationService.py,weatherService|../ocscripts/weatherService.py<file_sep>import os, sys import socket import logging import marshal import datetime import cPickle import threading, Queue import time import random import multiprocessing from Pyro4.errors import CommunicationError import MySQLdb import traceback logger = logging.getLogger(__name__) from opencluster.util import compress, decompress, mkdir_p, getuser, safe,int2ip,parse_mem,spawn from opencluster.env import env from opencluster.item import Task,Success,OtherFailure,TaskStateName,CompletionEvent try : from mesos.native import MesosExecutorDriver, MesosSchedulerDriver from mesos.interface import mesos_pb2 except : print "warning no module named mesos.native or mesos.interface." pass MAX_FAILED = 3 EXECUTOR_MEMORY = 64 # cache POLL_TIMEOUT = 0.1 RESUBMIT_TIMEOUT = 60 MAX_IDLE_TIME = 30 SHUTDOWN_TIMEOUT = 3 # in seconds def run_task(task, aid): logger.debug("Running task %s", task.id) try: result = task.run(aid) # find Worker instance by workerType return (task.id, Success(), compress(cPickle.dumps(result,-1))) except Exception, e: logger.error("error in task %s", task) import traceback traceback.print_exc() return (task.id, OtherFailure("exception:" + str(e)), None) class Scheduler(object): def __init__(self, manager): self.completionEvents = Queue.Queue() self.shuttingdown = False self.stopped = False self.finished_count = 0 self.fail_count = 0 self.taskNum = 0 self.started = False self.manager = manager def shutdown(self): self.shuttingdown = True def terminated(self): return self.stopped def submitTasks(self, tasks): if self.started: logger.error("Scheduler was started,submitting new tasks is not allowd") return def taskEnded(self, task, reason, result): if isinstance(reason,Success) : self.finished_count +=1 else: self.fail_count +=1 self.completionEvents.put(CompletionEvent(task, reason, result)) self.manager.statusUpdate() def start(self): pass def defaultParallelism(self): return 2 class LocalScheduler(Scheduler): attemptId = 0 def __init__(self, manager): Scheduler.__init__(self,manager) def nextAttempId(self): self.attemptId += 1 return self.attemptId def submitTasks(self, tasks): #self.completionEvents.join() self.taskNum = self.taskNum + len(tasks) self.started = True self.manager.statusUpdate() logger.debug("submit %s tasks in LocalScheduler", len(tasks)) for task in tasks: _, reason, result = run_task(task, self.nextAttempId()) self.taskEnded(task, reason, result) def run_task_in_process(task, tid): logger.debug("run task in process %s %s", task, tid) try: return run_task(task, tid) except KeyboardInterrupt: sys.exit(0) class MultiProcessScheduler(LocalScheduler): def __init__(self, manager,threads): LocalScheduler.__init__(self,manager) self.threads = threads self.tasks = {} self.pool = multiprocessing.Pool(self.threads or self.defaultParallelism()) self.started = True def submitTasks(self, tasks): if not tasks: return if not self.started: logger.error("process pool stopped") return self.taskNum = self.taskNum + len(tasks) self.manager.statusUpdate() logger.info("Got a job with %d tasks", self.taskNum) start = time.time() def callback(args): tid, reason, result = args task = self.tasks.pop(tid) self.taskEnded(task, reason, result) logger.info("Task %s finished (%d/%d)", tid, self.finished_count, self.taskNum) if self.finished_count == self.taskNum: logger.info("%d tasks finished in %.1f seconds" + " "*20, self.finished_count, time.time() - start) for task in tasks: self.tasks[task.id] = task self.pool.apply_async(run_task_in_process, [task, self.nextAttempId()], callback=callback) def shutdown(self): self.pool.terminate() self.pool.join() self.started = False logger.debug("process pool stopped") def defaultParallelism(self): return multiprocessing.cpu_count() class StandaloneScheduler(Scheduler): def __init__(self, manager,workerType): Scheduler.__init__(self,manager) self.workerType = workerType self.slaveTasks = {} self.current_task_num = 0 self.futureResults = {} self.shutdowned = False self.lock = threading.RLock() def futureResultCheck(): while not self.shutdowned: finishedTaskIds = [] for tid in self.futureResults : logger.debug(self.futureResults[tid]) (v_tid,state,results) = self.futureResults[tid] if results.ready and self.slaveTasks.has_key(tid) : if state == Task.TASK_FINISHED : try : self.taskEnded(self.slaveTasks[tid], Success(), results.value) logger.debug("Task %s finished - (%d/%d)", tid, self.finished_count, self.taskNum) except CommunicationError,ce: #logger.error("CommunicationErrorCommunicationError") continue except Exception,e : self.taskEnded(self.slaveTasks[tid], OtherFailure(e), None) logger.debug("Task %s fail - (%d/%d)", tid, self.fail_count, self.taskNum) logger.error(traceback.print_exc()) if state == Task.TASK_ERROR : self.taskEnded(self.slaveTasks[tid], results.value, None) # data is typeof OtherFailure logger.debug("Task %s failed - (%d/%d)", tid, self.fail_count, self.taskNum) self.slaveTasks.pop(tid) finishedTaskIds.append(tid) for f_tid in finishedTaskIds: self.popFutureResults(f_tid) time.sleep(0.5) logger.info("%s,(%d/%d) tasks finished" + " "*20, self.workerType,self.finished_count, self.taskNum) spawn(futureResultCheck) @safe def putFutureResults(self,tid,value): self.futureResults[tid] = value @safe def popFutureResults(self,tid): self.futureResults.pop(tid) def submitTasks(self, tasks): if not tasks: return self.started = True start = time.time() self.current_task_num = len(tasks) self.taskNum = self.taskNum + self.current_task_num self.manager.statusUpdate() logger.info("Got a job with %d tasks", self.taskNum) workers = self.manager.getWaitingWorkers(self.workerType, True) if len(workers) == 0 : logging.error("no %s worker found",self.workerType) return j = random.randint(0, len(workers)) for task in tasks: if j == len(workers) : j = 0 logger.debug("dispather task(%s) to %s" % (task.id,workers[j])) w = workers[j].doTask(task) self.slaveTasks[task.id]=task self.putFutureResults(task.id,w) j += 1 def defaultParallelism(self): return multiprocessing.cpu_count() def shutdown(self): self.shutdowned = True class FactoryScheduler(Scheduler): def __init__(self, manager, addr, warehouse): Scheduler.__init__(self,manager) self.addr = addr self.warehouse = warehouse self.fail_count = 0 def submitTasks(self, tasks): if not tasks: return self.taskNum = self.taskNum + len(tasks) if len(self.addr.split(",")) > 2 : self.mysqlTasks(self.addr,self.warehouse,tasks) else: self.kafkaTasks(self.addr,self.warehouse,tasks) self.manager.statusUpdate() logger.info("(%d) tasks are waiting in warehouse" + " "*20, self.taskNum) def mysqlTasks(self,connectStr,warehouse,tasks): urls = connectStr.split(","); mysqlIpAndPort = urls[0].split(":") db = None try : db = MySQLdb.connect(host=mysqlIpAndPort[0], port = int(mysqlIpAndPort[1]),db =urls[1], user=urls[2],passwd=urls[3]) cur = db.cursor() count=cur.execute("select * from t_job where job_id='" + self.manager.name + "'") if count == 0: value=[self.manager.name,1,'factory'] cur.execute('insert into t_job values(%s,%s,%s,now())',value) values=[] for task in tasks: values.append((task.id,cPickle.dumps(task),0,task.priority,self.manager.name)) cur.executemany('insert into t_task (task_id,task_desc,status,priority,job_id) values(%s,%s,%s,%s,%s)',values) db.commit() cur.close() finally: if db : db.close() def kafkaTasks(self, addr, topic,tasks): try : from kafka import SimpleProducer, KafkaClient, KeyedProducer except: logger.error("kafka-python is not installed") raise Exception("kafka-python is not installed") kafka_client = None try : kafka_client = KafkaClient(addr) producer = KeyedProducer(kafka_client) for task in tasks: #self.producer.send_messages(self.warehouse,task.id, json.dumps(task,default=object2dict)) producer.send_messages(topic, self.manager.name, cPickle.dumps(task)) finally: if kafka_client: kafka_client.close() def shutdown(self): pass def profile(f): def func(*args, **kwargs): path = '/tmp/worker-%s.prof' % os.getpid() import cProfile import pstats func = f cProfile.runctx('func(*args, **kwargs)', globals(), locals(), path) stats = pstats.Stats(path) stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(20) stats.sort_stats('cumulative') stats.print_stats(20) return func class MesosScheduler(Scheduler): def __init__(self, manager, master, options): Scheduler.__init__(self,manager) self.master = master self.cpus = options.cpus self.mem = parse_mem(options.mem) self.gpus = options.gpus self.task_per_node = options.parallel or multiprocessing.cpu_count() self.options = options self.group = options.group self.last_finish_time = 0 self.executor = None self.driver = None self.lock = threading.RLock() self.task_waiting = [] self.task_launched = {} self.slaveTasks = {} self.starting = False def start_driver(self): name = 'OpenCluster' if self.options.name : name = "%s-%s" % (name,self.options.name) else: name = "%s-%s" % (name,datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")) if len(name) > 256: name = name[:256] + '...' framework = mesos_pb2.FrameworkInfo() framework.user = getuser() if framework.user == 'root': raise Exception("OpenCluster is not allowed to run as 'root'") framework.name = name framework.hostname = socket.gethostname() self.driver = MesosSchedulerDriver(self, framework, self.master) self.driver.start() logger.debug("Mesos Scheudler driver started") self.shuttingdown = False self.last_finish_time = time.time() self.stopped = False # # def check(): # while self.started: # now = time.time() # if not self.task_waiting and now - self.last_finish_time > MAX_IDLE_TIME: # logger.info("stop mesos scheduler after %d seconds idle", now - self.last_finish_time) # self.shutdown() # break # time.sleep(1) # # if len(self.task_success()) + len(self.task_failed) == self.taskNum: # self.shutdown() # spawn(check) @safe def registered(self, driver, frameworkId, masterInfo): self.started = True logger.debug("connect to master %s:%s(%s), registered as %s", int2ip(masterInfo.ip), masterInfo.port, masterInfo.id, frameworkId.value) self.executor = self.getExecutorInfo(str(frameworkId.value)) @safe def reregistered(self, driver, masterInfo): logger.warning("re-connect to mesos master %s:%s(%s)", int2ip(masterInfo.ip), masterInfo.port, masterInfo.id) @safe def disconnected(self, driver): logger.debug("framework is disconnected") @safe def getExecutorInfo(self, framework_id): execInfo = mesos_pb2.ExecutorInfo() execInfo.executor_id.value = "multiframework" execInfo.command.value = '%s %s' % ( sys.executable, # /usr/bin/python.exe or .../python os.path.abspath(os.path.join(os.path.dirname(__file__), 'simpleexecutor.py')) ) v = execInfo.command.environment.variables.add() v.name = 'UID' v.value = str(os.getuid()) v = execInfo.command.environment.variables.add() v.name = 'GID' v.value = str(os.getgid()) if hasattr(execInfo, 'framework_id'): execInfo.framework_id.value = str(framework_id) Script = os.path.realpath(sys.argv[0]) if hasattr(execInfo, 'name'): execInfo.name = Script execInfo.data = marshal.dumps((Script, os.getcwd(), sys.path, dict(os.environ), self.task_per_node, env.environ)) return execInfo @safe def clearCache(self): self.task_launched.clear() self.slaveTasks.clear() @safe def submitTasks(self, tasks): if not tasks: return self.completionEvents.join() #Blocks until all items in the events queue have been gotten and processed. self.clearCache() self.task_waiting.extend(tasks) self.taskNum = self.taskNum + len(tasks) logger.debug("Got job with %d tasks", len(tasks)) if not self.started and not self.starting: self.starting = True self.start_driver() while not self.started: self.lock.release() time.sleep(0.01) self.lock.acquire() self.requestMoreResources() self.manager.statusUpdate() def requestMoreResources(self): if self.started: self.driver.reviveOffers() @safe def resourceOffers(self, driver, offers): rf = mesos_pb2.Filters() if not self.task_waiting: rf.refuse_seconds = 5 for o in offers: driver.launchTasks(o.id, [], rf) return random.shuffle(offers) self.last_offer_time = time.time() for offer in offers: if self.shuttingdown: print "Shutting down: declining offer on [%s]" % offer.hostname driver.declineOffer(offer.id) continue attrs = self.getAttributes(offer) if self.options.group and attrs.get('group', 'None') not in self.options.group: driver.launchTasks(offer.id, [], rf) continue cpus, mem, gpus = self.getResources(offer) logger.debug("got resource offer %s: cpus:%s, mem:%s, gpus:%s at %s", offer.id.value, cpus, mem, gpus, offer.hostname) logger.debug("attributes,gpus:%s",attrs.get('gpus', None)) sid = offer.slave_id.value tasks = [] while (len(self.task_waiting)>0 and cpus >= self.cpus and mem >= self.mem and (self.gpus==0 or attrs.get('gpus', None) is not None)): logger.debug("Accepting resource on slave %s (%s)", offer.slave_id.value, offer.hostname) t = self.task_waiting.pop() t.state = mesos_pb2.TASK_STARTING t.state_time = time.time() task = self.create_task(offer, t, cpus) tasks.append(task) self.task_launched[t.id] = t self.slaveTasks.setdefault(sid, set()).add(t.id) cpus -= self.cpus mem -= self.mem # gpus -= self.gpus operation = mesos_pb2.Offer.Operation() operation.type = mesos_pb2.Offer.Operation.LAUNCH operation.launch.task_infos.extend(tasks) driver.acceptOffers([offer.id], [operation]) @safe def offerRescinded(self, driver, offer_id): logger.debug("rescinded offer: %s", offer_id) if self.task_waiting: self.requestMoreResources() def getResources(self, offer): cpus, mem, gpus = 0, 0, 0 for r in offer.resources: if r.name == 'gpus': gpus = float(r.scalar.value) elif r.name == 'cpus': cpus = float(r.scalar.value) elif r.name == 'mem': mem = float(r.scalar.value) return cpus, mem, gpus def getResource(self, res, name): for r in res: if r.name == name: return r.scalar.value return 0 def getAttribute(self, attrs, name): for r in attrs: if r.name == name: return r.scalar.value def getAttributes(self, offer): attrs = {} for a in offer.attributes: attrs[a.name] = a.scalar.value return attrs def create_task(self, offer, t, cpus): task = mesos_pb2.TaskInfo() task.task_id.value = t.id task.slave_id.value = offer.slave_id.value task.name = "task(%s/%d)" % (t.id, self.taskNum) task.executor.MergeFrom(self.executor) task.data = compress(cPickle.dumps((t, t.tried), -1)) cpu = task.resources.add() cpu.name = "cpus" cpu.type = 0 # mesos_pb2.Value.SCALAR cpu.scalar.value = min(self.cpus, cpus) mem = task.resources.add() mem.name = "mem" mem.type = 0 # mesos_pb2.Value.SCALAR mem.scalar.value = self.mem # # gpu = task.resources.add() # gpu.name = "gpus" # gpu.type = 0 # mesos_pb2.Value.SCALAR # gpu.scalar.value = self.gpus return task @safe def statusUpdate(self, driver, update): logger.debug("Task %s in state [%s]" % (update.task_id.value, mesos_pb2.TaskState.Name(update.state))) tid = str(update.task_id.value) if tid not in self.task_launched: # check failed after launched for t in self.task_waiting: if t.id == tid: self.task_launched[tid] = t self.task_waiting.remove(t) break else: logger.debug("Task %s is finished, ignore it", tid) return t = self.task_launched[tid] t.state = update.state t.state_time = time.time() self.last_finish_time = t.state_time if update.state == mesos_pb2.TASK_RUNNING: self.started = True # to do task timeout handler elif update.state == mesos_pb2.TASK_LOST: self.task_launched.pop(tid) if t.tried < self.options.retry: t.tried += 1 logger.warning("task %s lost, retry %s", t.id, update.state, t.tried) self.task_waiting.append(t) # try again else: self.taskEnded(t, OtherFailure("task lost,exception:" + str(update.data)), "task lost") elif update.state in (mesos_pb2.TASK_FINISHED, mesos_pb2.TASK_FAILED, mesos_pb2.TASK_ERROR, mesos_pb2.TASK_KILLED): self.task_launched.pop(tid) slave = None for s in self.slaveTasks: if tid in self.slaveTasks[s]: slave = s self.slaveTasks[s].remove(tid) break if update.state == mesos_pb2.TASK_FINISHED : self.taskEnded(t, Success(), update.data) if update.state == mesos_pb2.TASK_ERROR : logger.error(update.message) self.taskEnded(t, OtherFailure(update.message), update.message) driver.abort() self.shutdown() if update.state == mesos_pb2.TASK_FAILED or update.state == mesos_pb2.TASK_KILLED or update.state == mesos_pb2.TASK_LOST: if t.tried < self.options.retry: t.tried += 1 logger.warning("task %s failed with %s, retry %s", t.id, update.state, t.tried) self.task_waiting.append(t) # try again else: self.taskEnded(t, OtherFailure("exception:" + str(update.data)), None) logger.error("task %s failed on %s", t.id, slave) if not self.task_waiting: self.requestMoreResources() # request more offers again @safe def check(self, driver): now = time.time() for tid, t in self.task_launched.items(): if t.state == mesos_pb2.TASK_STARTING and t.state_time + 30 < now: logger.warning("task %s lauched failed, assign again", tid) if not self.task_waiting: self.requestMoreResources() t.tried += 1 t.state = -1 self.task_launched.pop(tid) self.task_waiting.append(t) # TODO: check run time @safe def shutdown(self): if not self.started: return wait_started = datetime.datetime.now() while (len(self.task_launched) > 0) and \ (SHUTDOWN_TIMEOUT > (datetime.datetime.now() - wait_started).seconds): time.sleep(1) logger.debug("total:%d, task finished: %d,task failed: %d", self.taskNum, self.finished_count, self.fail_count) self.shuttingdown = True # self.driver.join() self.driver.stop(False) #self.driver = None logger.debug("scheduler stop!!!") self.stopped = True self.started = False @safe def error(self, driver, code): logger.warning("Mesos error message: %s", code) def defaultParallelism(self): return 16 def frameworkMessage(self, driver, executor, slave, data): logger.warning("[slave %s] %s", slave.value, data) def executorLost(self, driver, executorId, slaveId, status): logger.warning("executor at %s %s lost: %s", slaveId.value, executorId.value, status) self.slaveTasks.pop(slaveId.value, None) def slaveLost(self, driver, slaveId): logger.warning("slave %s lost", slaveId.value) self.slaveTasks.pop(slaveId.value, None) def killTask(self, job_id, task_id, tried): tid = mesos_pb2.TaskID() tid.value = "%s:%s:%s" % (job_id, task_id, tried) self.driver.killTask(tid) <file_sep>import sys import os import logging sys.path.extend([os.path.join(os.path.abspath(os.path.dirname(__file__)),'..')]) from opencluster.ui.main import WebServer from opencluster.configuration import Conf,setLogger logger = logging.getLogger(__name__) if __name__ == "__main__" : setLogger("OCWeb","") thisServer = WebServer(Conf.getWebServers()) thisServer.start()<file_sep>import os,sys import re import copy import time import meta import importlib import imp TaskStateName = { 6: "TASK_STAGING", # Initial state. Framework status updates should not use. 0: "TASK_STARTING", 1: "TASK_RUNNING", 2: "TASK_FINISHED", # TERMINAL. 3: "TASK_FAILED", # TERMINAL. 4: "TASK_KILLED", # TERMINAL. 5: "TASK_LOST", # TERMINAL. 7: "TASK_ERROR" } class ObjectBean(object): def __init__(self): self.obj = None self.name = "" self.vid = 0l self.createTime = 0l def toObject(self): return self.obj def getName(self): return self.name def getVid(self): return self.vid def getDomain(self): if self.name : return FactoryObjValue.getDomainNode(self.name)[0] else : return None def getNode(self): if self.name : keys = FactoryObjValue.getDomainNode(self.name) if len(keys) == 2 : return keys[1] return None def toString(self): return "%s:%s" %(self.name , obj) class ObjectBeanList(list) : def __init__(self,vid): super(ObjectBeanList,self).__init__() self.vid = vid class ObjValue(dict): def __init__(self): super(ObjValue,self).__init__() def getWidely(self, regex): p = re.compile(regex) obj = ObjValue() for key in self.keys() : if p.match(key) : obj[key] = self[key] return obj def removeWidely(self, regex): p = re.compile(regex) obj = ObjValue() keys = [] for key in self.keys() : if p.match(key) : keys.append(key) obj[key] = self[key] for key in keys : self.remove(key) return obj def setObj(self, k, v): self[k] = v def getObj(self, k): if self.has_key(k) : return self[k] def remove(self, key): obj = None if self.has_key(key) : obj = self[key] del self[key] return obj def putAll(self,d): if len(d) == 0 : return for (k,v) in d.items() : self.setObj(k,v) def isEmpty(self): return len(self.items()) <= 0 class Task: TASK_STAGING = 6 # Initial state. TASK_STARTING = 0 TASK_RUNNING = 1 TASK_FINISHED = 2 TASK_FAILED = 3 TASK_KILLED = 4 TASK_LOST = 5 TASK_ERROR = 7 def __init__(self, id, tried = 0,state = 6,state_time = 0,workerClass=None,data = None,workDir = None,priority=1,resources={"cpus":0,"mem":0,"gpus":0},warehouse="",jobName=""): self.id = id self.tried = tried self.state = state self.state_time = state_time self.workerClass = workerClass self.data = data self.workDir = workDir self.priority = priority self.resources = resources self.warehouse = warehouse self.jobName = jobName self.result = None def run(self,attemptId): sys.path.extend([self.workDir]) moduleAndClass = self.workerClass.split(".") workerModule = importlib.import_module('.'.join(moduleAndClass[:-1])) worker = getattr(workerModule, moduleAndClass[-1])() return worker.doTask(self.data); def getStateName(self): return TaskStateName[self.state] def preferredLocations(self): return self.locs def __str__(self): return "task:{id:%s,state:%s,tried:%s,workerClass:%s,workDir:%s}"%(self.id,self.getStateName(),self.tried,self.workerClass,self.workDir) class ManagerOption(object): def __init__(self, cpus=1, mem = 100,gpus = 0,parallel = 0,group=None,workertype = None,warehouse = None,retry=0,name=""): self.cpus = cpus self.mem = mem self.gpus = gpus self.parallel = parallel self.group = group self.workertype = workertype self.warehouse = warehouse self.retry = retry self.name = name class CompletionEvent: def __init__(self, task, reason, result): self.task = task self.reason = reason self.result = result class TaskEndReason: pass class Success(TaskEndReason): pass class OtherFailure(TaskEndReason): def __init__(self, message): self.message = message def __str__(self): return '<OtherFailure %s>' % self.message class FutureResult(TaskEndReason): def __init__(self, id, state, message='', result=None): self.id = id self.message = message self.state = state self.result = result def __str__(self): return 'FutureResult[%s], message : %s,state : %s' % (self.message,TaskStateName[self.state]) class FactoryObjValue(ObjValue): def getNodeWidely(self, nodeKey): p = re.compile(nodeKey + "\\..*") obj = ObjValue() getobj = self.getObj(nodeKey) if getobj : obj.setObj(nodeKey,getobj) for key in self.keys() : if p.match(key) : obj.setObj(key,self.get(key)) return obj def getNodeByPrefix(self, prefix): p = re.compile(prefix + "*") obj = ObjValue() for key in self.keys() : if p.match(key) : obj.setObj(key,self.get(key)) return obj def getNode(self, domain, node): ov = ObjValue() if domain : if node : domainNodeKey = self.getDomainNodekey(domain, node) obj = self.getObj(domainNodeKey) version = self.getObj(meta.getMetaVersion(domainNodeKey)) createBy = self.getObj(meta.getMetaCreater(domainNodeKey)) creatip = self.getObj(meta.getMetaCreaterIP(domainNodeKey)) creattime = self.getObj(meta.getMetaCreateTime(domainNodeKey)) prop = self.getObj(meta.getMetaProperties(domainNodeKey)) updateby = self.getObj(meta.getMetaUpdater(domainNodeKey)) updateip = self.getObj(meta.getMetaUpdaterIP(domainNodeKey)) updatetime = self.getObj(meta.getMetaUpdateTime(domainNodeKey)) timeout = self.getObj(meta.getMetaTimeout(domainNodeKey)) meetadata = self.getObj(meta.getMeta(domainNodeKey)) if obj: ov.setObj(domainNodeKey,obj) if version: ov.setObj(meta.getMetaVersion(domainNodeKey), version) if createBy : ov.setObj(meta.getMetaCreater(domainNodeKey), createBy) if creatip : ov.setObj(meta.getMetaCreaterIP(domainNodeKey), creatip) if creattime : ov.setObj(meta.getMetaCreateTime(domainNodeKey), creattime) if prop : ov.setObj(meta.getMetaProperties(domainNodeKey), prop) if updateby : ov.setObj(meta.getMetaUpdater(domainNodeKey), updateby) if updateip : ov.setObj(meta.getMetaUpdaterIP(domainNodeKey), updateip) if timeout : ov.setObj(meta.getMetaTimeout(domainNodeKey), timeout) if meetadata : ov.setObj(meta.getMeta(domainNodeKey), meetadata) else : ov = self.getNodeWidely(domain) return ov @classmethod def getDomainNode(cls, domainNodeKey): return domainNodeKey.split(".") @classmethod def checkGrammer(cls,k): p = re.compile("^[a-z0-9A-Z_-]+$") if k and p.match(k) : return True else: return False @classmethod def getDomainNodekey(self, domain, node): if node is None: return domain else : return "%s.%s" % (domain, node) def getFactoryInfo(self): return copy.deepcopy(self) def removeDomain(self,domain): ov = ObjValue() if domain : obj = self.remove(domain) version = self.remove(meta.getMetaVersion(domain)) createBy = self.remove(meta.getMetaCreater(domain)) creatip = self.remove(meta.getMetaCreaterIP(domain)) creattime = self.remove(meta.getMetaCreateTime(domain)) if obj : ov.setObj(domain, obj) if version : ov.setObj(meta.getMetaVersion(domain), version) if createBy : ov.setObj(meta.getMetaCreater(domain), createBy) if creatip : ov.setObj(meta.getMetaCreaterIP(domain), creatip) if creattime : ov.setObj(meta.getMetaCreateTime(domain), creattime) return ov def removeNode(self, domain, node): ov = ObjValue() if domain : if node : domainNodeKey = self.getDomainNodekey(domain, node) obj = self.remove(domainNodeKey) version = self.remove(meta.getMetaVersion(domainNodeKey)) createBy = self.remove(meta.getMetaCreater(domainNodeKey)) creatip = self.remove(meta.getMetaCreaterIP(domainNodeKey)) creattime = self.remove(meta.getMetaCreateTime(domainNodeKey)) prop = self.remove(meta.getMetaProperties(domainNodeKey)) updateby = self.remove(meta.getMetaUpdater(domainNodeKey)) updateip = self.remove(meta.getMetaUpdaterIP(domainNodeKey)) updatetime = self.remove(meta.getMetaUpdateTime(domainNodeKey)) metadata = self.remove(meta.getMeta(domainNodeKey)) if obj : ov.setObj(domainNodeKey, obj) if version : ov.setObj(meta.getMetaVersion(domainNodeKey), version) if createBy : ov.setObj(meta.getMetaCreater(domainNodeKey), createBy) if creatip : ov.setObj(meta.getMetaCreaterIP(domainNodeKey), creatip) if creattime : ov.setObj(meta.getMetaCreateTime(domainNodeKey), creattime) if prop : ov.setObj(meta.getMetaProperties(domainNodeKey), prop) if updateby : ov.setObj(meta.getMetaUpdater(domainNodeKey), updateby) if updateip : ov.setObj(meta.getMetaUpdaterIP(domainNodeKey), updateip) if updatetime : ov.setObj(meta.getMetaUpdateTime(domainNodeKey), updatetime) if metadata : ov.setObj(meta.getMeta(domainNodeKey), metadata) else : ov = self.removeNodeWidely(domain) return ov def removeNodeWidely(self, nodeKey): obj = ObjValue() node = self.remove(nodeKey) p = re.compile(nodeKey + "\\..*") if node : obj.setObj(nodeKey, node) keys = [] for key in self.keys() : if p.match(key) : keys.append(key) return obj def getFactoryInfoExp(self,exp): keys = [] for key in self.keys() : if key.find(meta.METACREATETIME) > -1 : domainNodeKey = key[0:key.find(meta.METACREATETIME)] keyArr = self.getDomainNode(domainNodeKey) timeout = self.getObj(meta.getMetaTimeout(domainNodeKey)) createtime = long(self.get(key)) if timeout is not None : if time.time()- createtime > long(self.getObj(meta.getMetaTimeout(domainNodeKey))) : keys.append(keyArr) continue if keyArr and len(keyArr)==2 : propValue = self.getObj(meta.getMeta(domainNodeKey)) if propValue is None or propValue != meta.HEARTBEAT : if time.time()-long(self.get(key)) > exp : keys.append(keyArr) return keys if __name__ == "__main__" : obj = FactoryObjValue() obj["_worker_workerUVFITS"] = "1" obj["_worker_workerdemo"] = "0" for (k,v) in obj.items() : print k,v p = re.compile("_worker_*") obj = ObjValue() if p.match("_worker_workerdemo.") : print "1" obj2 = FactoryObjValue() obj2["ddx"] = "dxxx" obj.putAll(obj2) print FactoryObjValue.checkGrammer("2323x2dsdafa") <file_sep>import random import logging from opencluster.worker import Worker from opencluster.factory import FactoryContext from opencluster.util import port_opened class Service(Worker): def __init__(self,workerType, level=logging.DEBUG): super(Service, self).__init__(workerType,level) def waitWorkingByService(self, host, port=None) : self.host = host self.port = port if self.host is None: self.host = "127.0.0.1" if self.port is None: self.port = random.randint(30000, 40000) while port_opened(self.host, self.port) : self.port = random.randint(30000, 40000) FactoryContext.startWorker(self, self.workerType, self.host, self.port, "_service_")<file_sep>import os import logging import web import wsgiref import datetime import mimetypes import time import traceback from opencluster.item import FactoryObjValue from opencluster.configuration import Conf from opencluster.factory import FactoryContext from api import * logger = logging.getLogger(__name__) PWD = os.path.abspath(os.path.dirname(__file__)) urls = [ "/res/(.*)", "StaticRes", "/", "Index", "/jobs", "Jobs", "/nodes", "Nodes", "/workers", "Workers", "/services", "Services", "/node/(.+)", "Node", "/nodeWorker", "WorkerOperation", "/nodeService", "ServiceOperation", "/about/(about)", "About", "/about/(contact)", "About", ] urls.extend(apiUrls) urls.extend(["*","WebHandler"]) app = web.application(tuple(urls),globals()) folder_templates_full_path = PWD + Conf.getWebTemplatesPath() def render(params={},partial=True): global_vars = dict({'title':'OpenCluster'}.items() + params.items()) if not partial: return web.template.render(folder_templates_full_path, globals=global_vars) else: return web.template.render(folder_templates_full_path, base='layout', globals=global_vars) def titled_render(subtitle=''): subtitle = subtitle + ' - ' if subtitle else '' return render({'title': subtitle + ' OpenCluster'}) class FactoryInstance(object): _instance = None _lastTime = None def __init__(self): pass @staticmethod def get(): if not FactoryInstance._instance or time.time()-FactoryInstance._lastTime > 30: logger.info("Factory Instance Init......") FactoryInstance._instance = FactoryContext.getDefaultFactory() logger.info("Factory Instance Init......22222222") FactoryInstance._lastTime = time.time() return FactoryInstance._instance class WebServer(object) : def __init__(self,__server): server = __server.split(":") self.server = (server[0],int(server[1])) self.setup_session_folder_full_path() # web.config.static_path = PWD + Conf.getWebStaticPath() def start(self) : app.run(self.server) def setup_session_folder_full_path(self): # global session # # if not web.config.get("_session"): # folder_sessions_full_path = PWD + Conf.getWebSessionsPath() # session = web.session.Session(app, web.session.DiskStore(folder_sessions_full_path), initializer = {"username": None}) # web.config._session = session # else: # session = web.config._session pass def server_static(filename, mime_type=None): ''''' Serves a file statically ''' if mime_type is None: mime_type = mimetypes.guess_type(filename)[0] web.header('Content-Type', bytes('%s' % mime_type)) filename = os.path.join(Conf.getWebStaticFullPath(), filename) if not os.path.exists(filename): raise web.NotFound() stat = os.stat(filename) web.header('Content-Length', '%s' % stat.st_size) web.header('Last-Modified', '%s' % web.http.lastmodified(datetime.datetime.fromtimestamp(stat.st_mtime))) return wsgiref.util.FileWrapper(open(filename, 'rb'), 16384) class StaticRes(object): def GET(self, name): return server_static(name) class About(object): def GET(self, name): if name=="about" : return titled_render("About").about(about = "About") elif name == "contact" : return titled_render("Contact").about(about = "Contact") else: return web.NotFound() class WebHandler(object): def GET(self): return "OpenCluster" class Index(object): def GET(self): try : nodes = FactoryInstance.get().getNodes("_node_") or {} workers = FactoryInstance.get().getNodeByPrefix("_worker_") or [] services = FactoryInstance.get().getNodeByPrefix("_service_") or [] jobs = FactoryInstance.get().getNodes("_manager_") or [] retNodes = [] totalMemory = 0 totalCPU = 0 usedMemory = 0 usedCPU = 0 for v in nodes: retNodes.append(v.obj) totalMemory += v.obj.totalMemory totalCPU += v.obj.cpuCount usedMemory += v.obj.usedMemory usedCPU += v.obj.cpuTotalPercent if totalMemory > 0 : usedMemory = int(usedMemory*100/totalMemory) if totalCPU > 0 : usedCPU = float(usedCPU/len(nodes)) totalMemory = float(totalMemory/1024) dataCPU = [{"value":"%.2f"%usedCPU,"color":"#F38630","label":"Used"},{"value":"%.2f"%(100-usedCPU),"color":"#E0E4CC","label":"UnUsed"}] dataMem = [{"value":"%.2f"%usedMemory,"color":"#F38630","label":"Used"},{"value":"%.2f"%(100-usedMemory),"color":"#E0E4CC","label":"UnUsed"}] return titled_render().index(nodes = retNodes,jobs=jobs,services=services,workers=workers,dataCPU = dataCPU,dataMem = dataMem,totalCPU=totalCPU,totalMemory=totalMemory) except Exception, e: return titled_render().error(error=e.message) class Nodes(object): def GET(self): try : nodes = FactoryInstance.get().getNodes("_node_") or {} workers = FactoryInstance.get().getNodeByPrefix("_worker_") or [] services = FactoryInstance.get().getNodeByPrefix("_service_") or [] retNodes = [] for v in nodes: retNodes.append(v.obj) return titled_render().nodes(nodes = retNodes,services=services,workers=workers) except Exception, e: return titled_render().error(error=e.message) class Services(object): def GET(self): try : nodes = FactoryInstance.get().getNodes("_node_") or {} services = FactoryInstance.get().getNodeByPrefix("_service_") or [] serviceTypes = FactoryInstance.get().getNodeByPrefix("_service_",True) or [] return titled_render().services(services=services,serviceTypes=serviceTypes,time = time) except Exception, e: return titled_render().error(error=e.message) class Workers(object): def GET(self): try : nodes = FactoryInstance.get().getNodes("_node_") or {} workers = FactoryInstance.get().getNodeByPrefix("_worker_") or [] workerTypes = FactoryInstance.get().getNodeByPrefix("_worker_",True) or [] retNodes = [] for v in nodes: retNodes.append(v.obj) return titled_render().workers(nodes = retNodes,workers=workers,workerTypes=workerTypes,time = time) except Exception, e: return titled_render().error(error=e.message) class Node(object): def GET(self,host): try : node = FactoryInstance.get().getDomainNode("_node_",str(host)) workers = FactoryInstance.get().getNodeByPrefix("_worker_") or [] services = FactoryInstance.get().getNodeByPrefix("_service_") or [] retWorkers = [] for v in workers: if "".join(v.obj.split(":")[0].split(".")) == str(host) : retWorkers.append(v) retServices = [] for v in services : if "".join(v.obj.split(":")[0].split(".")) == str(host) : retServices.append(v) if node is None : raise Exception("Node(%) is not found"%host) node.obj.startTime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(node.obj.startTime)) return titled_render().node(node = node.obj,services=retServices,workers=retWorkers) except Exception, e: return titled_render().error(error=e.message) class WorkerOperation(object): def GET(self): try : req = web.input() workerType = req.workerType host = req.host action = req.action node = FactoryInstance.get().getDomainNode("_node_",str(host)) if node is None : raise Exception("Node(%s) is not found"%host) node.obj.startTime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(node.obj.startTime)) nodeService = getNodeService(node.obj) if action=="start" : nodeService.startNewWorker(workerType) elif action == "stop" : keyArr = FactoryObjValue.getDomainNode(workerType) worker = FactoryInstance.get().getDomainNode(keyArr[0],keyArr[1]) whostPort = worker.obj.split(":") nodeService.stopWorker(keyArr[0],whostPort[1]) elif action == "stopAll" : nodeService.stopAllWorker(workerType) web.seeother("node/"+host) except Exception, e: return titled_render().error(error=e.message) class ServiceOperation(object): def GET(self): try : req = web.input() serviceType = req.serviceType host = req.host action = req.action node = FactoryInstance.get().getDomainNode("_node_",str(host)) if node is None : raise Exception("Node(%s) is not found"%host) node.obj.startTime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(node.obj.startTime)) nodeService = getNodeService(node.obj) if action=="start" : nodeService.startNewService(serviceType) elif action == "stop" : keyArr = FactoryObjValue.getDomainNode(serviceType) worker = FactoryInstance.get().getDomainNode(keyArr[0],keyArr[1]) shostPort = worker.obj.split(":") nodeService.stopService(keyArr[0],shostPort[1]) elif action == "stopAll" : keyArr = FactoryObjValue.getDomainNode(serviceType) nodeService.stopAllService(keyArr[0]) web.seeother("node/"+host) except Exception, e: traceback.print_exc() return titled_render().error(error=e.message) class Jobs(object): def GET(self): try : jobs = FactoryInstance.get().getNodes("_manager_") or [] retJobs = [] for v in jobs: retJobs.append(v.obj) return titled_render().jobs(jobs = retJobs) except Exception, e: return web.internalerror() def getNodeService(node) : return FactoryContext.getNodeDaemon(node) if __name__ == "__main__" : thisServer = WebServer(Conf.getWebServers()) thisServer.start()<file_sep>import sys,os import psutil import time from collections import OrderedDict from configuration import Conf class Node(object) : ''' Disk : mb Memory : mb CPUs : int CPU Frequency: MHZ ''' mSize = 1024*1024l gSize = 1024*1024*1024l def __init__(self,host,port,name): self.host = host self.port = port self.name = name self.lastTime = 0l self.startTime = psutil.boot_time() self.totalDisk = 0l self.freeDisk = 0l self.usedDisk = 0l self.percentDisk = 0l self.totalMemory = 0l self.usedMemory = 0l self.availableMemory = 0l self.percentMemory = 0l self.cpuCount = 0 self.cpuTotalPercent = 0 self.availWorkers = OrderedDict() self.availServices = OrderedDict() self.workers = OrderedDict() self.services = OrderedDict() self.diskPath = Conf.getNodeDiskPath() def calRes(self) : phyMem = psutil.virtual_memory() self.lastTime = time.time() self.totalMemory = phyMem.total/Node.mSize self.usedMemory = phyMem.used/Node.mSize self.availableMemory = phyMem.available/Node.mSize self.percentMemory = phyMem.percent self.cpuCount = psutil.cpu_count() self.cpuTotalPercent = psutil.cpu_percent() disk = psutil.disk_usage(self.diskPath) self.totalDisk = disk.total/Node.mSize self.freeDisk = disk.free/Node.mSize self.usedDisk = disk.used/Node.mSize self.percentDisk = disk.percent return self def __str__(self): return "Node:" + self.host + ":" + str(self.port) + ",serviceNum:" + str(len(self.services)) + ",nodeNum:" + str(len(self.workers)) def __repr__(self): return "Node:" + self.host + ":" + str(self.port) + ",serviceNum:" + str(len(self.services)) + ",nodeNum:" + str(len(self.workers)) class FileObj(object): def __init__(self,fileName): self.fileName = fileName self.modifiedTime = "" self.type = "" self.size = "" class NodeFile(object) : def __init__(self, rootDir): self.rootDir = rootDir def listDir(self,retDir): absDir = os.path.join(self.rootDir,retDir) if not os.path.exists(absDir) : raise Exception("dir[%s] does not exists"%absDir) if not os.path.isdir(absDir) : raise Exception("[%s] is not dir"%absDir) fileList = os.listdir(absDir) or [] retList = [] for f in fileList : absFileName = os.path.join(absDir,f) fileObj = FileObj(f) fileObj.modifiedTime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getmtime(absFileName))) if os.path.isfile(absFileName) : fileObj.size = str(os.path.getsize(absFileName)) tArr = os.path.splitext(absFileName) if len(tArr) == 2: fileObj.type = tArr[1] elif os.path.isdir(absFileName) : fileObj.type = "D" elif os.path.islink(absFileName): fileObj.type = "L" retList.append(fileObj) retList.sort(cmp=lambda x,y : cmp(x.type,y.type),reverse = True) return retList def readByte(self,fileName,begin,length): absFileName = os.path.join(self.rootDir,fileName) if not os.path.exists(absFileName) : raise Exception("[%s] does not exists"%absFileName) try : f = open(fileName,"rb") f.seek(begin,0) return f.read(length) finally: if f : f.close() def readWholeFile(self,fileName) : BLOCK_SIZE = 102400 absFileName = os.path.join(self.rootDir,fileName) if not os.path.exists(absFileName) : raise Exception("[%s] does not exists"%absFileName) with open(absFileName, 'rb') as f: while True: block = f.read(BLOCK_SIZE) if block: yield block else: return def remove(self,fileName): absFileName = os.path.join(self.rootDir,fileName) if not os.path.exists(absFileName) : raise Exception("[%s] does not exists"%absFileName) if os.path.isfile(absFileName): return os.remove(absFileName) if os.path.isdir(absFileName): return os.rmdir(absFileName) return False def rename(self,fileName,newName): absFileName = os.path.join(self.rootDir,fileName) newFileName = os.path.join(self.rootDir,newName) if not os.path.exists(absFileName) : raise Exception("[%s] does not exists"%absFileName) return os.rename(absFileName,newFileName) def createDir(self,curDir,dirName): absFileName = os.path.join(self.rootDir,curDir) if not os.path.exists(absFileName) : raise Exception("[%s] does not exists"%absFileName) absFileName = os.path.join(absFileName,dirName) return os.makedirs(absFileName) def writeFile(self,fileName,fileByte): absFileName = os.path.join(self.rootDir,fileName) if os.path.exists(absFileName) : raise Exception("file exists") with open(absFileName, "wb") as f: f.write(fileByte) return True <file_sep>import random import traceback from Pyro4.errors import CommunicationError from opencluster.factoryleader import FactoryLeader from opencluster.item import * from opencluster.errors import * from opencluster.hbdaemon import HbDaemon class FactoryLocal(object): def __init__(self, host, port, serviceName, servers): self.factoryLeader = FactoryLeader(host, port, serviceName, servers) self.serverCount = len(servers) self.factory = self.factoryLeader.getLeaderFactory() self.sid = None self.getSessionId(0) def getSessionId(self,count=0): try : sid = self.factory.getSessionId() if not self.sid : self.sid = sid except Exception,e : logger.error("%s maybe is shutdown,can't connected. Try getNextLeader" % self.factoryLeader.thisServer) if count < self.serverCount : self.factory = self.factoryLeader.getNextLeader() if self.factory : self.getSessionId(count+1) def createDomain(self, domain, ob): self.__put(domain,str(time.time()).replace(".",""),ob,False,0,None) def createDomainNode(self, domain, node, ob, isHeartBeat=False,timeout=None): self.__put(domain,node,ob,isHeartBeat,0, timeout) def __put(self,domain,node,obj,isHearBeat,count,timeout=None): ob = None if obj is None : return None if FactoryObjValue.checkGrammer(domain) and FactoryObjValue.checkGrammer(node) : try: ov = self.factory.create(domain,node,obj,self.sid,isHearBeat,timeout) ob = self.ovToBean(ov,domain,node) if ob and isHearBeat : HbDaemon.runPutTask(self.factory,self.factoryLeader,domain,node,obj,self.sid) except Exception,e : logger.error("factorylocal.__put:"+str(e)) if isinstance(e,CommunicationError): self.factory = self.factoryLeader.getNextLeader() if self.factory : ob = self.__put(domain,node,obj,isHearBeat,count+1,timeout) if isinstance(e,ClosetoOverError) : logger.error("put error:%s" % e.errorPrint()) else: logger.error("domain:%s,node:%s is not valid string"%(domain,node)) return ob def update(self, domain, node, obj,count=0): ob = None if obj is None : return None if FactoryObjValue.checkGrammer(domain) and FactoryObjValue.checkGrammer(node) : try: ov = self.factory.update(domain,node,obj,self.sid) ob = self.ovToBean(ov,domain,node) except Exception,e : logger.error("factorylocal.update:"+str(e)) if isinstance(e,CommunicationError): self.factory = self.factoryLeader.getNextLeader() if self.factory : ob = self.update(domain,node,obj,count+1) if isinstance(e,ClosetoOverError) : logger.error("update error:%s" % e.errorPrint()) return ob def getNodes(self, domain,count=0): objList = None if domain is None : ov = self.factory.getNodes() return objList if FactoryObjValue.checkGrammer(domain) : try: ov = self.factory.get(domain,None,self.sid) objList = self.ovToBeanList(ov,domain) except Exception,e : logger.error(e) if isinstance(e,CommunicationError): self.factory = self.factoryLeader.getNextLeader() if self.factory : ob = self.getNodes(domain,count+1) if isinstance(e,ClosetoOverError) : logger.error("get Nodes error:%s" % e.errorPrint()) return objList def getNodeByPrefix(self, prefix, isDomain=False, count = 0): objList = None try: ov = self.factory.getNodesByPrefix(prefix) objList = self.ovToBeanList2(ov,isDomain) except Exception,e : logger.error(e) if isinstance(e,CommunicationError) and count > 3: self.factory = self.factoryLeader.getNextLeader() if self.factory : ob = self.getNodeByPrefix(prefix,isDomain,count+1) if isinstance(e,ClosetoOverError) : logger.error("get Nodes by prefix error:%s" % e.errorPrint()) return objList def getDomainNode(self, domain, node,count=0): ob = None if FactoryObjValue.checkGrammer(domain) and FactoryObjValue.checkGrammer(node): try: ov = self.factory.get(domain,node,self.sid) ob = self.ovToBean(ov,domain,node) except Exception,e : logger.error(e) if isinstance(e,CommunicationError): self.factory = self.factoryLeader.getNextLeader() if self.factory : ob = self.getDomainNode(domain,node,count+1) return ob def getLastest(self, domain, node, oldObj,count=0): ob = None if FactoryObjValue.checkGrammer(domain) and FactoryObjValue.checkGrammer(node): try: vid = 0l if oldObj : vid = oldObj.vid ov = self.factory.getLastest(domain,node,self.sid,vid) ob = self.ovToBean(ov,domain,node) except Exception,e : logger.error(e) if isinstance(e,CommunicationError): self.factory = self.factoryLeader.getNextLeader() if self.factory : ob = self.getLastest(domain,node,oldObj,count+1) return ob def getNodesLastest(self, domain, oldObjList,count=0): obList = None if FactoryObjValue.checkGrammer(domain): try: vid = 0l if oldObjList : vid = oldObjList.vid ov = self.factory.getLastest(domain,None,self.sid,vid) obList = self.ovToBeanList(ov,domain) except Exception,e : logger.error(e) if isinstance(e,CommunicationError): self.factory = self.factoryLeader.getNextLeader() if self.factory : ob = self.getNodesLastest(domain,oldObjList,count+1) if isinstance(e,ClosetoOverError) : logger.error("getNodesLastest error:%s" % e.errorPrint()) return obList def delete(self, domain, node,count=0): ob = None if FactoryObjValue.checkGrammer(domain) and FactoryObjValue.checkGrammer(node): try: ov = self.factory.delete(domain,node,self.sid) ob = self.ovToBean(ov,domain,node) except Exception,e : logger.error(e) if isinstance(e,CommunicationError): self.factory = self.factoryLeader.getNextLeader() if self.factory : ob = self.delete(domain,node,count+1) return ob def deleteDomain(self, domain, count=0): obList = None if FactoryObjValue.checkGrammer(domain): try: ov = self.factory.delete(domain,None,self.sid) obList = self.ovToBeanList(ov,domain) except Exception,e : logger.error(e) if isinstance(e,CommunicationError): self.factory = self.factoryLeader.getNextLeader() if self.factory : ob = self.deleteDomain(domain,count+1) if isinstance(e,ClosetoOverError) : logger.error("deleteDomain Nodes error:%s" % e.errorPrint()) return obList def setDeletable(self, domain,obj=None): pass def addLastestListener(self, domain, obj): pass def ovToBean(self,ov,domain,node): if ov and not ov.isEmpty() : domainNodeKey = FactoryObjValue.getDomainNodekey(domain,node) bean = ObjectBean() bean.name = domainNodeKey bean.obj = ov.getObj(domainNodeKey) return bean else : return None def ovToBeanList(self,ov,domain) : if ov and not ov.isEmpty() : objList = ObjectBeanList(ov.getObj(meta.getMetaVersion(domain))) nodeVersion = ov.getWidely(meta.getMetaVersion(domain + "..*")) for key in nodeVersion.keys() : obp = ObjectBean() obp.vid = long(nodeVersion.getObj(key)) obp.name = key[0:key.find(meta.METAVERSION)] obp.obj = ov.getObj(obp.name) objList.append(obp) return objList def ovToBeanList2(self,ov,isDomain) : objList = ObjectBeanList(random.random()) keyLen = 2 if ov and not ov.isEmpty() : if isDomain: keyLen = 1 for key in ov.keys() : if key.find(meta.METACREATETIME) > -1 : domainNodeKey = key[0:key.find(meta.METACREATETIME)] keyArr = FactoryObjValue.getDomainNode(domainNodeKey) if keyArr and len(keyArr) == keyLen : obp = ObjectBean() obp.vid = long(ov.getObj(meta.getMetaVersion(domainNodeKey))) obp.name = domainNodeKey obp.obj = ov.getObj(domainNodeKey) obp.createTime = ov.getObj(meta.getMetaCreateTime(domainNodeKey)) objList.append(obp) return objList
2f364946442953c36c74b1987bffc3d7cb55fb2a
[ "Markdown", "INI", "Python", "Text", "Shell" ]
33
Python
ITking666/opencluster
c7d4905174c57458b3d83f3659529242f899651e
3d7a48b6d6905e1aef8aa433dde5a3ecb9ffcbef
refs/heads/master
<repo_name>pcastellanos/NetCoreMVC<file_sep>/DataAccess/ITasksRepository.cs using System.Collections.Generic; using TodoApp.Models; namespace TodoApp.DataAccess{ public interface ITasksRepository{ List<Task> All(); Task Get(int id); bool Delete(int id); void Update(Task task); void Add(Task task); } }<file_sep>/StartUp.cs using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using TodoApp.DataAccess; namespace TodoApp { public class StartUp { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSingleton<ITasksRepository,TasksRepository>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseMvcWithDefaultRoute(); } } }<file_sep>/Models/Task.cs using System.ComponentModel.DataAnnotations; namespace TodoApp.Models{ public class Task{ [Required] public int Id { get; set; } [Required] public string Name { get; set; } [Required] public string Notes { get; set; } public bool Done { get; set; } } }<file_sep>/DataAccess/TasksRepository.cs using System; using System.Collections.Generic; using TodoApp.Models; namespace TodoApp.DataAccess { public class TasksRepository : ITasksRepository { private static List<Task> tasks; public TasksRepository() { InitData(); } public void Add(Task task) { tasks.Add(task); } public List<Task> All() { return tasks; } public bool Delete(int id) { Task task = tasks.Find(t => t.Id == id); bool deleted = false; if (task != null) { tasks.Remove(task); deleted = true; } return deleted; } public Task Get(int id) { Task task = tasks.Find(t => t.Id == id); return task; } public void Update(Task task) { throw new NotImplementedException(); } #region private methods private static void InitData() { tasks = new List<Task>(); Task task1 = new Task() { Id = 1, Name = "Task1", Notes = "note1" }; Task task2 = new Task() { Id = 2, Name = "Task2", Notes = "note2" }; Task task3 = new Task() { Id = 3, Name = "Task3", Notes = "note3" }; Task task4 = new Task() { Id = 4, Name = "Task4", Notes = "note4" }; Task task5 = new Task() { Id = 5, Name = "Task5", Notes = "note5" }; tasks.Add(task1); tasks.Add(task2); tasks.Add(task3); tasks.Add(task4); tasks.Add(task5); } #endregion } }<file_sep>/Controllers/TaskController.cs using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using TodoApp.Models; using TodoApp.DataAccess; namespace TodoApp.Controllers { [Route("api/[controller]")] public class TaskController: Controller { private ITasksRepository repository; public TaskController(ITasksRepository repository) { this.repository = repository; } [HttpGet] //GET /api/Task public List<Task> GetAll() { return repository.All(); } [HttpGet("{id}")] //GET /api/Task/1 public IActionResult GetById(int id) { var task = repository.Get(id); if (task == null) { return NotFound(); } return new ObjectResult(task); } //POST /api/Task [HttpPost] public bool Create([FromBody] Task task) { bool created = true; if (task == null) return !created; task.Id = repository.All().Count + 1; repository.Add(task); return created; } //DELETE /api/Task/6 [HttpDelete("{id}")] public void Delete(int id) { repository.Delete(id); } } }
47512d858fa3a1e42fdf96a095be6684c57a7e4d
[ "C#" ]
5
C#
pcastellanos/NetCoreMVC
6899c1073c4afafad7408ba68babc0c8accafebe
337a9e841bd79dc37a6d9cea29d839766a465b7d
refs/heads/master
<repo_name>arasraj/Recommender_System<file_sep>/generate.py import nearestn import db import sys from persist import * def main(): nn = nearestn.NearestNeighbors() db_instance = db.DB() db_instance.userset() db_instance.itemset() ratings = db_instance.get_ratings() nn.index(ratings) nn.sim_matrix() nn.recommend(None) def test(): nn = nearestn.NearestNeighbors() bookset = load_obj('test_bookset.pkl') ratings = load_obj('test_ratings.pkl') index, avgrating = nn.index(ratings) knn = nn.sim_matrix(index, avgrating) nn.test_recommend(bookset, knn) if __name__ == '__main__': try: dotest = sys.argv[1] except: dotest = None if dotest: test() else: main() <file_sep>/persist.py import cPickle as pickle def serialize_obj(obj, filename): """ Writes obj (in this case a dict) to disk """ f = open(filename, 'wb') pickle.dump(obj, f) f.close() def load_obj(filename): data = open(filename, 'rb') obj = pickle.load(data) data.close() return obj <file_sep>/cleaner.py import db import re import Levenshtein as levens from fuzzywuzzy import fuzz class Cleanser(): """ The dataset had numerous alternative versions books that were not necessary. This class contains functions to find and delete such books. SeatGeek's fuzzy string matching library was initially used but found to be too computationly slow for this dataset. As a result Google's Levenshtein library was used because it's python module is implemented in C. Finding the correct value of the threshold of whether two titles are similar was somewhat difficult. If the value is set to high the algorithm misses some books that are indeed the same but with slightly different titles. Threshold values that are two low will consider books titles the same when they are not. The appropriate value I found to produce the best results was 0.887. """ def __init__(self): db_instance = db.DB() def process_titles(self): titles = db_instance.get_tiles() # Book titles often contained non-essential information such as the binding and edition. # This was usually between parens. As a result, all information between parens was # discarded. # Levenshtien.set_ratio() expects a list as an argument titles = [(re.sub(r'\(.+\)', '', title[0]).strip().split(), title[0]) for title in titles] return titles def print_dups(self, bookids): for bookid1, bookid2, booktitle1, booktitle2 in bookids: print booktitle1 print booktitle2 print '' print 'Len dups:', len(bookids) def delete_dups(self, dups): c = self.local_conn.cursor() # When two books are found with the same title, the one with the longer # title is deleted. This is because the longer title usually contains # the non-essential information. for bookid1, bookid2, booktitle1, booktitle2 in dups: largest_title = bookid1 if len(booktitle1) > len(booktitle2) else bookid2 db_instance.delete_title(largest_title) def finddups(self, titles): """ Finds title duplicates using approximate string matching techniques. """ print 'Len titles:', len(titles) indextobook = self.load('indextobook.pkl') total = 0 dups = [] for i in xrange(len(titles)): ititle = titles[i][0] orig_title = titles[i][1] for j in xrange(i+1, len(titles)): #sim = fuzz.token_sort_ratio(titles[i][0], titles[j][0]) ratio = levens.setratio(ititle, titles[j][0]) if ratio > 0.887: print indextobook[i], indextobook[j] dups.append((indextobook[i], indextobook[j], orig_title, titles[j][1])) total += 1 print i print 'Total dups:', total return dups def process(self): titles = self.gettitles() bookids = self.finddups(titles) #self.deletedups(bookids) self.printdups(bookids) <file_sep>/nearestn.py import db import sys import numpy import string from persist import * from collections import defaultdict from scipy import sparse from numpy.linalg import norm class NearestNeighbors: def index(self, data): """ Creates index of books to userid-rating. The average rating for an individual user is also calculated for later processing during the computation of item-item similarity. This is to account for the different rating scales users are likely to have. data: tuple of (userid, bookid, rating) obtained from db """ # load indexes of books and users into memory booktoindex = load_obj('booktoindex.pkl') usertoindex = load_obj('usertoindex.pkl') # used to calculate the average user rating userratings = defaultdict(list) # main index idx_dict = defaultdict(dict) for rating in data: userid, bookid, user_rating = rating[1:] # get book/user index from their id bookindex = booktoindex[bookid] userindex = usertoindex[userid] idx_dict[bookindex][userindex] = user_rating userratings[userindex].append(user_rating) # turn the index into a list for easier processing when computing item similarities idx_list = [idx_dict[i] for i, _ in enumerate(idx_dict)] #serialize_obj(idx_list, 'index.pkl') # find user average rating avg = lambda l: float(sum(l)) / len(l) avgrating = dict( (index, avg(ratings)) for index, ratings in userratings.iteritems()) #serialize_obj(avgrating, 'avgrating.pkl') return (idx_list, avgrating) #print len(idx_list) def sim_matrix(self, index, avgrating): """ Stores a item-item similarity "matrix" to disk. This matrix is actually a dictionary of bookids -> similarbookid, similarity score. This representation of similarities is more space efficient than a matrix due to the sparse nature of the data. Adjusted Cosine similarity is used to compute item-item similarities. This is useful because this approach accounts for differences in user rating scales. """ #index = load_obj('index.pkl') books = load_obj('indextobook.pkl') bookstoindex = load_obj('booktoindex.pkl') usersindex = load_obj('usertoindex.pkl') #avgrating = load_obj('avgrating.pkl') indexlen = len(index) usersetlen = len(usersindex) print 'indexlen', indexlen print 'books', len(books) print 'users', len(usersindex) # hold k nearest neighbors. knn = defaultdict(list) # compute n(n-1)/2 similarities instead of n^2 for i, outer in enumerate(index): for j in xrange(i+1, indexlen): inner = index[j] # only calculate similarity if there are enough users who have # co-rated the same books. Here the threshold is set at 2, but # should be increased as the sample size increases. This optimization # greatly impacts the efficiency of this loop. # Also store userids that are found to satisfy this condition inorder # to avoid operations on vectors of enormous size. intersection = set(outer.iterkeys()).intersection(inner.iterkeys()) intersections_userid = list(intersection) if len(intersections_userid) >= 4: vec1 = self.create_vector(outer, avgrating, intersections_userid) vec2 = self.create_vector(inner, avgrating, intersections_userid) # calculate adjusted cosine sim cos_sim = numpy.dot(vec1, vec2) / (norm(vec1) * norm(vec2)) # similarities are symmetric so store both knn[i].append((j, cos_sim, len(intersections_userid))) knn[j].append((i, cos_sim, len(intersections_userid))) print i #serialize_obj(dict(knn), 'knn_dict.pkl') for k,v in knn.iteritems(): print k,v print i return knn def create_vector(self, ratings_dict, avgrating, intersection_bookids): """ Creates a vector (list) of size len(intersections). The dimensions are the ratings of the users of the co-rated items. The average rating for an indivdual user is subtracted from their associated actual rating (to account of differences in user rating tendencies). """ return [ratings_dict[intersect] - float(avgrating[intersect]) for intersect in intersection_bookids] def recommend(self, knn): """ Creates and html page displaying recommendations books. The books that are aligned left (A) are the "given" books while those books underneath A and indented are recommended based on A. This is showing the knn data structure. This can easily be adapted to recommend a book given that a user likes another book. """ db_instance = db.DB() #knn = load_obj('knn_dict.pkl') indextobook = load_obj('indextobook.pkl') html = ['<html><body><table>'] for book1, ratings in knn.iteritems(): tmp = [] for book2, sim, iters in ratings: # Set a threshold for what are considered "similar enough books". This is highly # dependent on the data. if sim > 0.20: title, desc, author, image, salesrank = db_instance.getbookattrs(indextobook[book2]) tmp.append('<tr><td width="150px"></td><td><img src="http://ecx.images-amazon.com/images/I/%s" \ width="75"><br>Title: %s<br>Description: %s<br>Authors: %s<br>SalesRank: %s<br>Adj \ Cosine Sim: %f</td><td>Intersection: %d</td></tr>' % (image, title, desc, author, salesrank, sim, iters)) if tmp: title, desc, author, image, salesrank = db_instance.getbookattrs(indextobook[book1]) html.append('<tr><td colspan=2><img src="http://ecx.images-amazon.com/images/I/%s" width="75px"> \ <br>Title: %s<br>Desc: %s<br>Authors: %s<br>SalesRank: %s</td></tr>' % (image, title, desc, author, salesrank)) html.extend(tmp) html.append('</table></body></html>') # write html page to disk with open('bookrec.html', 'w') as f: f.write('\n'.join(html)) def test_recommend(self, bookset, knn): """ There is a lot of duplication between here and recommend(). This method was added for testing purposes only. """ bookset = load_obj('test_bookset.pkl') #db_instance = db.DB() #knn = load_obj('knn_dict.pkl') indextobook = load_obj('indextobook.pkl') html = ['<html><body><table>'] for book1, ratings in knn.items(): tmp = [] for book2, sim, iters in ratings: # Set a threshold for what are considered "similar enough books". This is highly # dependent on the data. if sim > 0.20: title, desc, author, image, salesrank = bookset[indextobook[book2]] tmp.append('<tr><td width="150px"></td><td><img src="http://ecx.images-amazon.com/images/I/%s" \ width="75"><br>Title: %s<br>Description: %s<br>Authors: %s<br>SalesRank: %s<br>Adj \ Cosine Sim: %f</td><td>Intersection: %d</td></tr>' % (image, title, desc, author, salesrank, sim, iters)) if tmp: title, desc, author, image, salesrank = bookset[indextobook[book1]] html.append('<tr><td colspan=2><img src="http://ecx.images-amazon.com/images/I/%s" width="75px"> \ <br>Title: %s<br>Desc: %s<br>Authors: %s<br>SalesRank: %s</td></tr>' % (image, title, desc, author, salesrank)) html.extend(tmp) html.append('</table></body></html>') # write html page to disk with open('bookrec.html', 'w') as f: f.write('\n'.join(html)) def cosine_sim(vec1, vec2): """ Static function used to debug. Numpy functions are used in actual computation for optimization. """ num = sum([vec1[i]*vec2[i] for i in xrange(len(vec1))]) print num result = num / (norm(vec1) * norm(vec2)) print numpy.dot(vec1, vec2) result2 = numpy.dot(vec1, vec2) / (norm(vec1) * norm(vec2)) return (result, result2) <file_sep>/db.py import string import MySQLdb as mysqldb from persist import * try: from config import * except: pass class DB: """ All book information was obtained from Amazon. A lot of the data was "dirty" and not properly cleansed. """ def __init__(self): # create both local and remote (DB server) self.remote_conn = mysqldb.connect(host=REMOTE_HOST, user=REMOTE_USER, passwd=<PASSWORD>, db=REMOTE_DB) self.local_conn = mysqldb.connect(host=HOST, user=USER, passwd=PASSWD, db=LOCAL_DB) def get_remote_books(self): """ Get all books from remote db server. """ c = self.remote_conn.cursor() c.execute(""" select id, title, description, authors, image_code, sales_rank, rating, stat_reviews from books where title is not null; """) result = c.fetchall() c.close() return result def sample_users(self): """ Get a sample of users to test the recommender system on. Users that rated around 20 books were chosen. """ c = self.remote_conn.cursor() c.execute(""" select customer_id, count(customer_id) as c from reviews group by customer_id order by c desc limit 4000, 5000 """) result = c.fetchall() c.close() return result def insert_sample_users(self, userids): """ Take sample from remote server and insert into local mysql instance """ c = self.local_conn.cursor() i = 0 for userid in userids: c.execute(""" insert into sampleid values (%d, '%s') """ % (i, userid[0])) i += 1 c.close() def get_remote_ratings(self): """ Get all book ratings from remote db. Make sure that the book did not have a rating of 0 (not sure why these were here in the first place) and that the book was somewhat popular (eg. salesrank < 10000). """ c = self.remote_conn.cursor() c.execute(""" select id, book_id, user_id, customer_id, rating from reviews where rating > 0 and book_id in \ (select id from books where sales_rank < 10000); """) #c.execute(""" select id, book_id, user_id, customer_id, # rating from reviews where rating > 0 and book_id in \ # (select id from books where sales_rank < 30000) order by rand() limit 10000;""") #print 'row count %d' % c.rowcount result = c.fetchall() c.close() return result def insert_ratings(self, items): """ Store ratings on local db instance """ c = self.local_conn.cursor() for item in items: #if bookid is not null item2or3 = item[2] if item[2] else item[3] c.execute("insert into ratings values(%d, '%s', %d, %d)" % (item[0], item2or3, item[1], item[4])) c.close() def insert_books(self, items): """ Grab books from dev server and put on local """ c = self.local_conn.cursor() i=0 errors = [] for item in items: # quick hack to handle titles/descriptions with double quotes in them. # (screws with python string formating). item1 = string.replace(item[1], '"', '\\"') if item[1] else '' item2 = string.replace(item[2], '"', '\\"') if item[2] else '' item3 = string.replace(item[3], '"', '\\"') if item[3] else '' #if item[1]: item1 = string.replace(item[1], '"', '\\"') #else: item1 = '' #if item[2]: item2 = string.replace(item[2], '"', '\\"') #else: item2 = '' #if item[3]: item3 = string.replace(item[3], '"', '\\"') #else: item3 = '' try: c.execute(""" insert into books values(%d, "%s", "%s", "%s", "%s", %d, %d, %d) """ % (item[0], item1, item2, item3, item[4], item[5], item[6], item[7])) except: errors.append(str(item[0])) print ' '.join(errors) c.close() def get_ratings(self): """ Get ratings from local db. Used when indexing. """ c = self.local_conn.cursor() c.execute(""" select id, userid, bookid, rating from ratings; """) #return c.fetchmany(10) results = c.fetchall() # used for testing serialize_obj(results, 'test_ratings.pkl') return results def get_test_books(self): """ Get sample set of books for testing """ c = self.local_conn.cursor() c.execute(""" select * from books where id in (select distinct bookid from ratings); """) results = c.fetchall() # used for testing bookset = {} for id, title, desc, authors, image, salesrank, _ , _ in results: bookset[id] = (title, desc, authors, image, salesrank) serialize_obj(bookset, 'test_bookset.pkl') def userset(self): """ Unique users are found. Indexes of userid -> index number and index numer -> userid are created. This is useful for created the ratings index of bookids -> (userid -> rating). """ c = self.local_conn.cursor() c.execute(""" select distinct userid from ratings """) result = c.fetchall() users = [user[0] for user in result] # create index numbers starting from 0 indextouser = list(enumerate(users)) serialize_obj(dict(indextouser), 'indextouser.pkl') usertoindex = dict([(b,a) for a,b in indextouser]) serialize_obj(usertoindex, 'usertoindex.pkl') print len(usertoindex) def itemset(self): """ Find unique bookids """ c = self.local_conn.cursor() c.execute(""" select distinct bookid from ratings; """) result = c.fetchall() c.close() items = [item[0] for item in result] items.sort() indextobook = list(enumerate(items)) serialize_obj(dict(indextobook), 'indextobook.pkl') booktoindex = dict([(b,a) for a,b in indextobook]) serialize_obj(booktoindex, 'booktoindex.pkl') def getbookattrs(self, bookid): c = self.local_conn.cursor() c.execute(""" select title, description, authors, image, salesrank from books where books.id=%d; """ % bookid) attrs = c.fetchone() c.close() return attrs def get_titles(self): c = self.local_conn.cursor() c.execute(""" select title from books where books.id in (select distinct bookid from ratings); """) titles = c.fetchall() c.close() return titles def delete_title(self, bookid): c = self.local_conn.cursor() c.execute("delete from ratings where bookid = %d" % bookid) self.local_conn.commit()
63ccd9e4263995b4fab56e059ccd84ae7938c94b
[ "Python" ]
5
Python
arasraj/Recommender_System
5df188d1d6684c5776ecfea761355a6d0821527d
815b7059427a35b10ad5d51031727344c5a1a720
refs/heads/master
<repo_name>quangtran99/itiviec<file_sep>/src/pages/Detail.js import React, { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import { Badge, Button, Row, Container, Col } from "react-bootstrap"; import { faMapMarker } from "@fortawesome/free-solid-svg-icons"; import { faCalendar } from "@fortawesome/free-solid-svg-icons"; import { faDollarSign } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import moment from "moment"; const apiAddress = process.env.REACT_APP_SERVER_URL; export default function Detail({ props }) { console.log("whats inside of props?", props); let { id } = useParams(); let [job, setJob] = useState(null); let getDetailData = async () => { let url = `${apiAddress}/jobs/${id}`; // importnat let response = await fetch(url); let result = await response.json(); console.log("you can get only one exactly job", result); setJob(result); }; useEffect(() => { getDetailData(); }, []); if (job == null) { return <div>loading</div>; } return ( <div className="App"> <div className="navigation"> <Container> <img className="logo-itviec" alt="itviec" src="https://itviec.com/assets/logo-itviec-65afac80e92140efa459545bc1c042ff4275f8f197535f147ed7614c2000ab0f.png" /> </Container> </div> <div className="container wrapper d-flex justify-content-center"> <div className="card-w"> <div className="card inset"> <div className="card__text"> <Row> <Col> <img src={job.img} /> </Col> <Col xs={10}> <h4>{job.title}</h4> <div style={{ paddingTop: "10px", color: "grey" }}> <FontAwesomeIcon icon={faDollarSign} style={{ marginRight: "10px" }} />{" "} {job.salary} </div> <div style={{ color: "grey" }}> <FontAwesomeIcon icon={faMapMarker} style={{ marginRight: "10px" }} />{" "} {job.city} District {job.district} </div> <div style={{ paddingTop: "20px" }}> <h2>Benefit</h2> <ul className="benefit-list" style={{ fontSize: "18px" }}> {job.benefits.map((benefit) => ( <li>{benefit}</li> ))} </ul> </div> <div style={{ color: "blue" }}> <FontAwesomeIcon icon={faCalendar} style={{ marginRight: "10px" }} /> {moment(job.time).fromNow()} </div> <div style={{ paddingTop: "20px" }}> <h2>Description</h2> <div>{job.description}</div> </div> <Row className="apply-style"> <h5> {job.tags.map((tag) => ( <Badge variant="secondary" style={{ margin: "5px" }}> {tag} </Badge> ))} </h5> <Button variant="danger" style={{ width: "100%", marginTop: "30px", fontSize: "18px" }} >APPLY</Button> </Row> </Col> </Row> </div> </div> </div> </div> </div> ); }<file_sep>/src/pages/Jobs.js import React, { useEffect, useState } from "react"; import { useHistory, useLocation } from "react-router-dom"; import { Row, Col, Container, Form } from "react-bootstrap"; import JobCards from "../components/JobCards" import { faSearch } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; const apiAddress = process.env.REACT_APP_SERVER_URL; function useQuery() { return new URLSearchParams(useLocation().search); } export default function Jobs() { let query = useQuery(); let history = useHistory(); let [jobList, setJobList] = useState([]); // for show on UI let [keyword, setKeyword] = useState(query.get("q")); let [originalList, setOriginalList] = useState([]); // keep the orignal list const getData = async () => { try { let url = `${apiAddress}/jobs`; console.log("url", url); let response = await fetch(url); let result = await response.json(); console.log("Result", result); setJobList(result); setOriginalList(result); } catch (err) { console.log("err", err.message); } }; const searchByKeyword = (e) => { let filteredList = originalList; if (e) { e.preventDefault(); console.log("keyword?", keyword); history.push(`/jobs?q=${keyword}`); } if (keyword) { filteredList = originalList.filter((job) => job.title.toLowerCase().includes(keyword.toLowerCase()) ); } setJobList(filteredList); }; useEffect(() => { getData(); }, []); useEffect(() => { searchByKeyword(); }, [originalList]); if (jobList.length == 0) { return <h1>loading</h1>; } return ( <div> <div className="background-header"> <Container> <Col> {" "} <img className="logo-itviec" alt="itviec" src="https://itviec.com/assets/logo-itviec-65afac80e92140efa459545bc1c042ff4275f8f197535f147ed7614c2000ab0f.png" /> </Col> <Form onSubmit={(e) => searchByKeyword(e)}> <Row className="search-form-wrapper"> <Col xs={12} md={10}> <div className="search-section-wrapper"> <Row className="search-field-wrapper" noGutters={true}> <FontAwesomeIcon icon={faSearch} className="icon-fasearch" /> <Col col={12}> <input type="text" value={keyword} className="search-box" onChange={(e) => setKeyword(e.target.value)} placeholder="Keyword skill(Java,IOS...),Job Title..." /> </Col> </Row> </div> </Col> <Col xs={12} md={2}> <button className="search-button" type="submit">Search</button> </Col> </Row> </Form> </Container> </div> <Container> <div className="job-list"> {jobList.map((job) => { return ( <JobCards job={job} /> ); })} </div> </Container> </div> ); } // 1. when we click the title // 2. goto detail page // 3. go to detail page means : you call the url for detail page // 4. url for detail page?: /jobs/:id <file_sep>/src/App.js import React from "react"; import "./App.css"; import Login from "./pages/Login"; import Jobs from "./pages/Jobs"; import Detail from "./pages/Detail"; import { Switch, Route, Redirect } from "react-router-dom"; import { useSelector } from "react-redux"; import 'bootstrap/dist/css/bootstrap.min.css'; function App() { let user = useSelector((state) => state.user); const ProtectedRoute = (props) => { if (user.isAuthenticated === true) { return <Route {...props} />; } else { return <Redirect to="/login" />; } }; return ( <div className="App"> <Switch> <Route exact path="/" component={Jobs} /> <Route exact path="/login" component={Login} /> <Route exact path="/jobs" component={Jobs} /> {/* <Route exact path ="/jobs" component={Jobs}/> */} <ProtectedRoute path="/jobs/:id" render={(props) => <Detail jobtitle="hahaha" {...props} />} /> </Switch> </div> ); } export default App; // if you want to see detail page, you need to login
db12300a35651c24208f72be55f96ffc015b77a9
[ "JavaScript" ]
3
JavaScript
quangtran99/itiviec
3f4d2f42fc23c9dc2f34d794a32d6a8cad7b40f2
811ab735e1c5cf2c54e5d32795e1134a649f304b
refs/heads/master
<repo_name>cb4292/PLC-Volatility-Plugin<file_sep>/frame_tool.py import volatility.obj as obj import volatility.plugins.linux.common as common import json import socket import volatility.plugins.linux.netstat as linux_netstat import tempfile import sys import os import volatility.utils as utils import volatility.conf as conf import volatility.plugins.linux.plthook as plthook up_one = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, up_one) from resources.strategy_classes import * # Usage python volatility/vol.py --[absolute path to]/plc_mal_tools/ -f [dump file] --profile=[profile of target os] frametool --configuration [absolute path to configuration file].json class FrameTool(common.AbstractLinuxIntelCommand): plc_type = {} def __init__(self, config, *args, **kwargs): common.AbstractLinuxIntelCommand.__init__(self, config, *args, **kwargs) self._config.add_option('CONFIGURATION', short_option = "c", default = None, help = "Provide configuration file directory", action = 'store') def get_config(self, configuration_file): configuration_dict = {"firmware": None, "protocol": None, "targets": []} config = open(configuration_file) content = json.load(config) try: configuration_dict["firmware"] = content["firmware"] print "Acquired firmware config." except: print "Unable to load firmware type, check config file." try: configuration_dict["protocol"] = content["protocol"] print "Acquired protocol config." except: print "Unable to load protocol type, check config file." try: configuration_dict["targets"] = content["targets"] print "Acquired targets config." except: print "Unable to load targets, check config file. Target values\ should be strings in an array." return configuration_dict def configure(self): self.jsn_file = str(self._config.CONFIGURATION) print "Building...\n" self.plc_type = self.get_config(self.jsn_file) self.strategy = decider(self) return def calculate(self): #Prepare configuration for passing to method based on firmware/protocol common.set_plugin_members(self) plugin_conf = self.configure() #pass self to arbitrary method, return conns object, which can be further analyzed conns = self.strategy.get_IO_conns() connected_pids = [] hooks = [] # for line in conns: connected_pids.append(line[0]) print(str(line[0])) for pid in connected_pids: curr_hook = self.strategy.hooked_funcs(str(pid)) hooks.append(curr_hook) outs = (conns, hooks) return outs def render_text(self, outfd, data): outfd.write("Completing analysis\n") outfd.write("The following processes are connected to targeted devices: \n") outfd.write("-" * 40 +"\n") for line in data[0]: outfd.write(line[1]) outfd.write("-" * 40 +"\n") outfd.write("The following hooks were found in the connected process' protocol library: \n") show_hooks = self.strategy.filter_for_elfs(outfd, data[1]) show_hooks() <file_sep>/README.md # PLC-Volatility-Plugin<file_sep>/strategy_classes.py import volatility.obj as obj import volatility.plugins.linux.common as common import volatility.plugins.linux.netstat as linux_netstat import volatility.plugins.linux.plthook as plthook import volatility.utils as utils import volatility.conf as conf import socket class Strategy(common.AbstractLinuxIntelCommand): def __init__(self, previous_object): if previous_object: self._config = previous_object._config self.plc_type = previous_object.plc_type def get_IO_conns(targets): print "Please choose firmware type." class Open_plc(Strategy): def __init__(self, *args): super(Open_plc, self).__init__(*args) def get_IO_conns(targets): print "Please choose IO communication protocol." class Open_plc_modbusTCP(Open_plc): def __init__(self, *args): super(Open_plc_modbusTCP, self).__init__(*args) def get_IO_conns(plugin_obj): #setup for passing obj to outside plugin plugin_conf = conf.ConfObject() plugin_conf.PROFILE = plugin_obj._config.PROFILE common.set_plugin_members(plugin_obj) net_plugin = linux_netstat.linux_netstat(plugin_conf) data = net_plugin.calculate() filtered_conns = Open_plc_modbusTCP.filter_for_targets(plugin_obj, data) return filtered_conns def hooked_funcs(plugin_obj, proc_id): plugin_conf = conf.ConfObject() plugin_conf.PROFILE = plugin_obj._config.PROFILE plugin_conf.PID = proc_id common.set_plugin_members(plugin_obj) hook_plugin = plthook.linux_plthook(plugin_conf) hooks = hook_plugin.calculate() return hooks def filter_for_elfs(self, outfd, data): #based on plthook renderer common.set_plugin_members(self) for proc_id in data: outfd.write("" * 40 + "\n") self.table_header(outfd, [("Task", "10"), ("ELF Start", "[addrpad]"), ("ELF Name", "24"), ("Symbol", "24"), ("Resolved Address", "[addrpad]"), ("H", "1"), ("Target Info", "")]) ignore = frozenset(self._config.IGNORE) #In addition to displaying output of plthook scan, filters for specific modbus library for task in proc_id: for soname, elf, elf_start, elf_end, addr, symbol_name, hookdesc, hooked in task.plt_hook_info(): if not hooked and not self._config.ALL: continue if hookdesc in ignore: continue if hookdesc == '[RTLD_LAZY]' and not self._config.ALL: continue if soname != 'libmodbus.so.5': continue self.table_row(outfd, task.pid, elf_start, soname if soname else '[main]', \ symbol_name, addr, '!' if hooked else ' ', hookdesc) def filter_for_targets(plugin_obj, data): #Iterate through netstat data, looking for target IPs; based on linux_netstat renderer conns_to_sens_acts = [] sens_acts = plugin_obj.plc_type["targets"] for targ in sens_acts: for conn in data: for ents in conn.netstat(): if ents[0] == socket.AF_INET: (_, proto, saddr, sport, daddr, dport, state) = ents[1] fields = "{0:8s} {1:<16}:{2:>5} {3:<16}:{4:>5} {5:<15s} {6:>17s}/{7:<5d}\n" connection = fields.format(proto, saddr, sport, daddr, dport, state, conn.comm, conn.pid) #print(connection) source = str(saddr) destination = str(daddr) if (source == targ) or (destination == targ): #print(connection) conns_to_sens_acts.append((conn.pid, connection)) return conns_to_sens_acts #Function to mutate Frame object into specific solution def decider(frame_object): """ map {} is the dictionary of builder functions. As the list of possible configuration classes grows, this dictionary should be updated so the appropriate class can be chosen. JSON configuration file entries should also be based on the keys of this dictionary. The keys should be a simple concatenation of the firmware and the protocol, e.g. to select the class Open_plc_modbusTCP, the firmware entry in the configuration file should be 'OpenPLC', and the protocol entry should be 'ModbusTCP'. """ #Recast functions #recast function for OpenPLC on Modbust TCP def OpenPLCModbusTCP(abstract_strat): strat = Open_plc_modbusTCP(abstract_strat) return strat config_dictionary = frame_object.plc_type selector = config_dictionary["firmware"] + config_dictionary["protocol"] map = {"OpenPLCModbusTCP": OpenPLCModbusTCP} chosen_method = map.get(selector, lambda: "Invalid type.") specific_strategy = chosen_method(frame_object) print("Configuration processed... Your device is a: " + str(selector)) return specific_strategy
64027e69c4ad8c45d31fc8e4fddecb7389de7bcb
[ "Markdown", "Python" ]
3
Python
cb4292/PLC-Volatility-Plugin
c8694ff425fd709fff3511d986830ab3e55d4053
723528e46901dc0d4add84e6c036b8f82686d8d3
refs/heads/master
<repo_name>scflai/cubealgdb<file_sep>/webpage/index.js let i = "hello"; console.log(i); //console.log("hello world"); if (i == "hello") { alert("owo"); } else { alert("uwu"); }<file_sep>/src/cubedb/Db.java package cubedb; //cubedb import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.ArrayList; //import cubedb.FetchAlgs; public class Db { public static void main(String[] args) throws Exception { //getConnection(); setTimezone(); createTable(); insertIntoTable(); System.out.println("finished"); //FetchAlgs.importAlgs(); } public static Connection getConnection() throws Exception { //establishes connection try { String driver = "com.mysql.cj.jdbc.Driver"; String url = "jdbc:mysql://localhost/cubedb?useSSL=false&allowPublicKeyRetrieval=true&allowPublicKeyRetrieval=true"; String username = "sam"; String password = "<PASSWORD>"; Class.forName(driver); Connection con = DriverManager.getConnection(url, username, password); System.out.println("Connected"); return con; } catch(Exception e) { System.out.println(e); } return null; } public static void setTimezone() throws Exception { //sets timezone Connection con = getConnection(); PreparedStatement create = con.prepareStatement("SET @@global.time_zone = '+00:00'"); create.executeUpdate(); } public static void createTable() throws Exception { //creates table Connection con = getConnection(); try { PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS algorithms(id int NOT NULL AUTO_INCREMENT, img varchar(255), alg varchar(255), rating int, PRIMARY KEY(id))"); create.executeUpdate(); System.out.println("Table created"); } catch (Exception e) { System.out.println(e); } } public static void insertIntoTable() throws Exception { //inserts into table Connection con = getConnection(); ArrayList<String> algList = new ArrayList<String>(); algList = FetchAlgs.importAlgs(); int j = 0; while (j < algList.size()) { String var1 = "https://i.imgur.com/ekCeTkF.png"; String var2 = algList.get(j); int var3 = 100; try { //Connection con = getConnection(); PreparedStatement create = con.prepareStatement("INSERT INTO algorithms (img, alg, rating) VALUES('"+var1+"', '"+var2+"', '"+var3+"')"); create.executeUpdate(); System.out.println(algList.get(j) + " Inserted"); j++; } catch (Exception e) { System.out.println(e); } } } }
2d2b24665857b39ce02bb8dac1dff5779efabc19
[ "JavaScript", "Java" ]
2
JavaScript
scflai/cubealgdb
9af8575559bbf910c5c507a716c7c6b773fc53dd
4df7a9c6dbdf69158c715eba123941a837ea4168
refs/heads/main
<file_sep>from inky import InkyWHAT from PIL import Image, ImageFont, ImageDraw from font_fredoka_one import FredokaOne def show_countdown(count): w, h = font.getsize(count) x = (inky_display.WIDTH / 2) - (w / 2) y = (inky_display.HEIGHT) - (h / 2) draw.text(( (inky_display.WIDTH / 2) - (w / 2), (0), count, inky_display.RED, font )) def show_message(message): w, h = font.getsize(message) x = (inky_display.WIDTH / 2) - (w / 2) y = (inky_display.HEIGHT) - (h / 2) draw.text(( (inky_display.WIDTH / 2) - (w / 2), (inky_display.HEIGHT) - (h / 2)), message, inky_display.RED, font ) inky_display = InkyWHAT("red") inky_display.set_border(inky_display.WHITE) img = Image.new("P", (inky_display.WIDTH, inky_display.HEIGHT)) draw = ImageDraw.Draw(img) font = ImageFont.truetype(FredokaOne, 36) show_countdown("20") show_message("Days Unil Christmas!") inky_display.set_image(img) inky_display.show()
0b35ee79078f68a107400deea64ba4e497e7eb9a
[ "Python" ]
1
Python
joshJarr/inky-tests
78909a96ec199676d2e0cca2b0fe4bc3b4293f22
a2a8bf7169f9ea0b0dc30b9d1770ec48413d5bba
refs/heads/master
<repo_name>devop06/Doranco<file_sep>/WebApplication1/WebApplication1/Controllers/AccountController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; using WebApplication1.Models.Entity; using WebApplication1.ViewModel; namespace WebApplication1.Controllers { public class AccountController : Controller { // GET: Account public ActionResult Login() { return View(); } /// <summary> /// /// </summary> /// <param name="_v"></param> /// <param name="returnUrl">Url désiré avant la redirection sur page de log</param> /// <returns></returns> [ValidateAntiForgeryToken] [HttpPost] public ActionResult Login(ConnexionViewModel _v, string ReturnUrl) { if (!ModelState.IsValid) { return View(_v); } else { User _u = UserData.GetLesUtilisateurs().FirstOrDefault(util => util.pseudo == _v.Identifiant && util.password == _v.<PASSWORD> || util.mail == _v.Identifiant); if (_u != null) { FormsAuthentication.SetAuthCookie(_u.pseudo, false); if (!string.IsNullOrWhiteSpace(ReturnUrl) && Url.IsLocalUrl(ReturnUrl)) return Redirect(ReturnUrl); else return RedirectToAction("Index", controllerName: "Home"); } else { ViewBag.Error = "Il semble que votre compte soit inexistant"; return View(_v); } } } public ActionResult LogOff() { FormsAuthentication.SignOut(); return RedirectToAction("Index", controllerName: "Home"); } [Authorize] public ActionResult Profil() { string _pseudo = HttpContext.User.Identity.Name; User _u = UserData.GetLesUtilisateurs().FirstOrDefault(u => u.pseudo == _pseudo); if (_u == null) return View("~/Views/Shared/Error.cshtml"); else { UserViewModel _uViewModel = new UserViewModel() { Nom = _u.nom, Ville = _u.ville, Adresse = _u.adresse, CodePostale = _u.codePostale, Mail = _u.mail, Pseudo = _u.pseudo, Prenom = _u.prenom }; return View(_uViewModel); } } /// <summary> /// ne change pas les valeurs dans la liste /// </summary> /// <returns></returns> [Authorize] // [ValidateAntiForgeryToken] [HttpPost] public ActionResult Profil(UserViewModel _userViewModel) { if(ModelState.IsValid) { User _u = UserData.GetLesUtilisateurs().Single(u => u.pseudo == _userViewModel.Pseudo); _u.prenom = _userViewModel.Prenom; _u.nom = _userViewModel.Nom; _u.ville = _userViewModel.Ville; _u.mail = _userViewModel.Mail; _u.password = <PASSWORD>; _u.codePostale = _userViewModel.CodePostale; _u.adresse = _userViewModel.Adresse; ViewBag.Sucess = "Profil modifié avec succès !"; return View(_userViewModel); } return View(_userViewModel); } public ActionResult CreateAccount() { return View((new CreateViewModel())); } [HttpPost] public ActionResult CreateAccount(CreateViewModel _createViewModel) { var _u = (from util in UserData.GetLesUtilisateurs() where util.mail == _createViewModel.Email || util.pseudo == _createViewModel.Pseudo select util).ToList(); if (_u.Count() > 0) { // voir affichage dans la vue ModelState.AddModelError("mailExist", "ce mail ou ce pseudo, ou il est déjà utilisé"); return View(_createViewModel); } else { UserData.GetLesUtilisateurs().Add( new Models.Entity.User { mail = _createViewModel.Email, pseudo = _createViewModel.Pseudo, password = _createViewModel.Password }); return RedirectToAction("index", "home"); } } } }<file_sep>/WebApplication1/WebApplication1/ViewModel/ConnexionViewModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace WebApplication1.ViewModel { public class ConnexionViewModel { [Required] public String Identifiant { get; set; } [Required] public String Password { get; set; } } }<file_sep>/WebApplication1/WebApplication1/ViewModel/CreateViewModel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace WebApplication1.ViewModel { public class CreateViewModel :IValidatableObject { [Required] [DisplayName("Choisis un pseudo :")] public string Pseudo { get; set; } [DataType(DataType.EmailAddress)] [EmailAddress] [DisplayName("Ton mail :")] public string Email { get; set; } [Required] [StringLength(30, ErrorMessage = "Ton mot de passe doit contenir au moins {0} caractères", MinimumLength = 6)] [DisplayName("Un mot de passe :")] [DataType(DataType.Password)] public string Password { get; set; } [Required] [DisplayName("Entre ton mot de passe à nouveau :")] [DataType(DataType.Password)] public string VerifPassword { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if(Password != <PASSWORD>) { yield return new ValidationResult("Les mots de passe ne semblent pas identiques...", new[] { "Password", "<PASSWORD>" }); } } } }<file_sep>/WebApplication1/WebApplication1/ViewModel/UserViewModel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace WebApplication1.ViewModel { public class UserViewModel : IValidatableObject { [DisplayName("Pseudonyme :")] public string Pseudo { get; set; } [DataType(DataType.EmailAddress)] [EmailAddress] [DisplayName("Email :")] public string Mail { get; set; } [DisplayName("Ton nom de famille :")] public string Nom { get; set; } [DisplayName("Ton prénom :")] public string Prenom { get; set; } [DisplayName("Ton adresse :")] public string Adresse { get; set; } [DisplayName("Votre adresse :")] public string CodePostale { get; set; } [DisplayName("Dans quelle ville habites-tu ?")] public string Ville { get; set; } [DisplayName("Saisis un nouveau mot de passe :")] [Required] public string Password { get; set; } [DisplayName("Saisis à nouveau le mot de passe :")] [Required] public string VerifPassword { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (Password != <PASSWORD>) yield return new ValidationResult("Mot de passe non identique...", new[] {"Password", "<PASSWORD>" }); } } }<file_sep>/WebApplication1/WebApplication1/UserData.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using WebApplication1.Models.Entity; namespace WebApplication1 { public static class UserData { public static List<Models.Entity.User> ListUser = new List<User>() { new User() { id = 1, pseudo = "toto", password = "<PASSWORD>", mail = "<EMAIL>", ville = "Paris", adresse = "4 rue de tata", codePostale = "75012", nom = "nom", prenom = "prenom" } }; public static List<Models.Entity.User> GetLesUtilisateurs() { return ListUser; } } }
01dc2065eb556401b3c3d699004e0a124618f722
[ "C#" ]
5
C#
devop06/Doranco
ccf11f09d5b8ae602b4a15c298f53a35978b7976
6715e04788444c00af3d05acbaa262aa79ffe9dd
refs/heads/master
<repo_name>isabella232/edge-rocket-examples<file_sep>/helloworld/hello_params.lua local renderTemplate = function(string, params) if not params then params = string string = params[1] end return (string.gsub(string, "({([^}]+)})", function(full,i) return params[i] or full end)) end local hello_html = [[ <html><head><title>Hello World</title></head><body> <img src="http://www.verisigninc.com/resources/img/logo.png" /> <h1>EdgeRocket</h1> <p>Hello {name}</p> </body></html> ]] local params = request.getParams() local name = params["name"] or "" response.addHeader("Content-Type", "text/html") response.setBody(renderTemplate {hello_html, name = name} ) <file_sep>/helloworld/hello_data.lua local renderTemplate = function(string, params) if not params then params = string string = params[1] end return (string.gsub(string, "({([^}]+)})", function(full,i) return params[i] or full end)) end local hello_html = [[ <html><head><title>Hello World</title></head><body> <img src="http://www.verisigninc.com/resources/img/logo.png" /> <h1>EdgeRocket</h1> <p>Hello <a href="mailto:{email}">{name}</a></p> </body></html> ]] local params = request.getParams() local user = params["user"] or "" local emailAddress = db.get("email", user) response.addHeader("Content-Type", "text/html") response.setBody(renderTemplate {hello_html, name = user, email=emailAddress} ) <file_sep>/css/css.lua -- this script will serve a CSS file from within the db -- create an endpoint similiar to this (change "user") -- http://css.user.er.edgerocket.com/ -- and map this script to that endpoint -- Also, create a db called "css" where you store your css data -- and ensure that the service has access to that table -- For this example, -- a url like http://css.user.er.edgerocket.com/styles.css -- request.getPath() will return "/styles.css" -- strip of the leading slash local css_name = string.sub(request.getPath(), 2) -- css_file should now be "styles.css" -- for this example, there should be an entry in the css table with -- a key of "styles.css" and the value should be the actuall css -- get the css file from the db local css_file = db.get("css", css_name) -- css_file will contain the contents of the css file or -- nil if not found -- to add other style sheets, simply add then to the table if css_file == nil then -- if we don't find the file, return a 404 response.addHeader("Content-Type", "text/html") response.addHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate") response.addHeader("Pragma", "no-cache") response.addHeader("Expires", "Fri, 01 Jan 1990 00:00:00 GMT") response.setResponseCode("404") response.setResponseText("Not Found") else -- if we found the css file, return it response.addHeader("Content-Type", "text/css") response.setBody(css_file) end <file_sep>/gravatr/README.md Avatar Lookup Service ===================== This example is modeled after the [gravatar](http://www.gravatar.com) service which maps an email address to an avatar image. It is used on various websites such as forums, blogs, GitHub, issue tracking services, etc. It allows you to associate your image with one or more of your email addresses. The avatar images are stored as JSON objects in the _avatars_ table of the format: ```javascript { "mime_type":"image/png", "image":"<Base64 encoded image>" } ``` <file_sep>/bit/bits.lua local renderTemplate = function(string, params) if not params then params = string string = params[1] end return (string.gsub(string, "({([^}]+)})", function(full,i) return params[i] or full end)) end local unary_view = [[ <html><head><title>EdgeRocket</title></head><body> <p>{op} {lhs} = {result} </p> </body></html> ]] local binary_view = [[ <html><head><title>EdgeRocket</title></head><body> <p>{lhs} {op} {rhs} = {result} </p> </body></html> ]] local params = request.getParams() local op = params["op"] local lhs = params["lhs"] local rhs = params["rhs"] local operations = { ["and"] = function() return bit.band(lhs, rhs), binary_view end, ["or"] = function() return bit.bor(lhs, rhs), binary_view end, ["xor"] = function() return bit.bxor(lhs, rhs), binary_view end, ["not"] = function() return bit.bnot(lhs), unary_view end, ["lshift"] = function() return bit.lshift(lhs, rhs), binary_view end, ["rshift"] = function() return bit.rshift(lhs, rhs), binary_view end } local result, view = operations[op]() response.addHeader("Content-Type", "text/html") response.setBody(renderTemplate {view, op = op, lhs = lhs, rhs = rhs, result = result}) <file_sep>/gravatr/gravatr.lua local function applyStringParams(string, params) if not params then params = string string = params[1] end return (string.gsub(string, "({([^}]+)})", function(full,i) return params[i] or full end)) end -- strip initial '/' local requestURI = string.sub(request.getPath(), 2) local responseData local mimeType if string.len(requestURI) == 0 then responseData = "" else responseData = db.get("avatars", requestURI) or "" if responseData ~= "" then -- { "mime_type":"image/png", TODO: switch to gmatch mimeType = string.sub(responseData, 16, 24) -- this will return the empty string if the input is not valid Base64 encoded responseData = base64.decode(string.sub(responseData, 36, -4)) end end local unknownKeyTemplate = [[ <html><head><title>grava.tr</title></head><body> <img src="http://www.verisigninc.com/resources/img/logo.png" /> <h1>Verisign Avatar Service</h1> http://grava.tr/{key} was not found. Learn more about this service <a href="#">here</a> </body></html> ]] if responseData == "" then response.addHeader("Content-Type", "text/html") response.addHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate") response.addHeader("Pragma", "no-cache") response.addHeader("Expires", "Fri, 01 Jan 1990 00:00:00 GMT") response.setResponseCode("404") response.setResponseText("Not Found") response.setBody(applyStringParams{ unknownKeyTemplate, key=requestURI}) else response.addHeader("Content-Type", mimeType) response.setBody(responseData) end <file_sep>/helloworld/hello_html.lua -- This is the html we want to return. In Lua, a string that spans several lines -- can be delimited with double square brackets. local hello_html = [[ <html><head><title>Hello World</title></head><body> <img src="http://www.verisigninc.com/resources/img/logo.png" /> <h1>EdgeRocket</h1> <p>Hello World</p> </body></html> ]] response.addHeader("Content-Type", "text/html") response.setBody(hello_html) <file_sep>/basicauth/basicauth.lua local encodedCredentials = request.getHeaderValue(HTTP_HEADER.AUTHORIZATION) response.addHeader("Content-Type", "text/html") response.addHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate") response.addHeader("Pragma", "no-cache") response.addHeader("Expires", "Fri, 01 Jan 1990 00:00:00 GMT") if encodedCredentials ~= "" then local encodedDetails = string.gsub(encodedCredentials, "Basic ", "") local credentials = base64.decode(encodedDetails) -- if credentials is empty then it means that the details were not a valid Base64 encoding if credentials ~= "" then local username, password = string.match(credentials, "(%w+):(%w+)") local compare = db.get("auth", username) if compare == password then response.setBody("Congratulations! Your username and password worked!") return end end end response.setResponseCode(401) response.setResponseText("Unauthorized") response.addHeader("WWW-Authenticate", "Basic realm=\"edgerocket\"") response.setBody("Authentication Required") <file_sep>/edgepress/edgepress.lua -- This the main page for the website and we use template to render -- the site. The basic workflow is: -- 1) Determine the hostname as this is used as a portion of the key. -- 2) Retrieve template for the page -- 3) Retrieve all of the substitution variables for the template -- 4) Render the template and return it local renderTemplate = function(template, params) for k,v in pairs(params) do template = string.gsub(template, k, v) end return template end local host = request.getHeaderValue(HTTP_HEADER.HOST) local template = db.get("ep-templates", host .. ":main") local name = db.get("ep-vars", host .. ":owner") local location = db.get("ep-vars", host .. ":address") local openclose = db.get("ep-vars", host .. ":hours") local desc = db.get("ep-vars", host .. ":description") local tuser = db.get("ep-vars", host .. ":twitter") local links = db.get("ep-vars", host .. ":pages") local paramTbl = {} paramTbl['{owner}'] = name; paramTbl['{address}'] = location; paramTbl['{hours}'] = openclose; paramTbl['{description}'] = desc; paramTbl['{pages}'] = links; paramTbl['{twitter}'] = tuser; response.addHeader("Content-Type", "text/html") response.addHeader("Access-Control-Allow-Origin", "*") response.setBody(renderTemplate(template,paramTbl)) return 0 <file_sep>/getvalue/getvalue.lua local renderTemplate = function(string, params) if not params then params = string string = params[1] end return (string.gsub(string, "({([^}]+)})", function(full,i) return params[i] or full end)) end local found_html = [[ <html><head><title>EdgeRocket</title></head><body> <p>{table}.{key} = {value}</p> </body></html> ]] local notfound_html = [[ <html><head><title>EdgeRocket</title></head><body> <p>{table}.{key} Not Found</p> </body></html> ]] local params = request.getParams() local table = params["table"] local key = params["key"] response.addHeader("Content-Type", "text/html") if table == nil or key == nil then response.setResponseCode("404") response.setResponseText("Not Found") response.setBody(renderTemplate {notfound_html, table = table, key = key}) else local value = db.get(table, key) response.setBody(renderTemplate {found_html, table = table, key = key, value = value}) end <file_sep>/edgepress/README.md Edgepress ========= Edge Press makes it easy to create a main website page with some basic information as well as subpages. Each of the pages contains a header which can be updated via Twitter. This application is meant to be multi-tenanted, thus the hostname is included in each of the queries to the Edge Rocket data tables. Currently three scripts are used to implement the 'customer' view of the website: * _edgepress.lua_: This is the primary entry point to the website and builds the main page by displaying the content selected for the front page of the site. * _posts.lua_: This script is responsible for finding the requested post and displaying it. Main Page --------- The main page pulls a template from the Edge Rocket database (from the _ep-templates_ table) along with substitution variables (from the _ep-vars_ table) and then simply combines them and returns the resulting web page. Subpages -------- Each of the subpages performs the same role as the main page script, but uses a different set of variables and potentially a different template. Feed ---- Originally, Edgepress was envisioned as a blogging platform and so the notion of RSS/Atom feeds was useful. Here they serve more as an example of how to create RSS/Atom feeds on top of Edge Rocket, though they do provided a complete list of sub-pages as they are added.<file_sep>/lustache/starterscript.lua -- This is a simple example of an EdgeRocket script -- that will generate an HTML page based on the value of -- some get parameters and will make simple database queries. -- lustache is a lua version of the JavaScript mustache templating library -- https://github.com/Olivine-Labs/lustache local lustache = require "lustache" -- EdgeRocket automatically imports the "request," "response," and "db" modules -- so there is no need to require them (though it is safe to do so). -- Get a lua table of the get parameters passed in the url. -- For example, if the url is http://<yourdomain>/<path>/<path>?a=123&b=test -- then params would be a lua table like: -- params['a'] = "123" -- params['b'] = "test" local params = request.getParams() -- Get an optional message parameter passed in as a get parameter; -- if not present, it will be set to nil. local custom_message = params["message"] -- Get a value from the "Small sample lookup table" table identified by the key "hello" local hello_message = db.get("Small sample lookup table", "hello") or "" -- Get a value from the "Small sample lookup table" table identified by the key "welcome" local welcome_message = db.get("Small sample lookup table", "welcome") or "" -- Create a "model" that will be rendered in HTML. -- It is always recommended to use local variables as below, -- as this is faster than using global variables (specified without 'local'). local model = { custom = custom_message, hello = hello_message, welcome = welcome_message } -- Create an HTML template that will be used to render our page. -- In lua, multiline strings can be delimited with double square brackets. local html_template = [[ <html> <head> <title>Welcome to EdgeRocket</title> </head> <body> <h1>{{hello}}</h1> <p>{{welcome}}</p> {{#custom}}<p>{{custom}}</p>{{/custom}} </body> <html> ]] -- Render the HTML template using the values in the model. output = lustache:render(html_template, model) -- Set the content type to "text/html"; -- there is no default for this so it MUST be set. response.addHeader("Content-Type", "text/html") -- Set the response body to the rendered template. response.setBody(output) <file_sep>/helloworld/README.md # Hello World These are some basic scripts to show how to return simple responses in EdgeRocket. ## hello.lua This is the simplest script possible. It returns "Hello World" as plain text. ## hello_html.lua This example shows sending a simple HTML string to the browser. ## hello_params.lua This example how to get parameters from the URL request. http://host/helloparams/?name=_name_ This will return HTML with Hello _name_ ## hello_data.lua This example shows how to get data from a table and renders the values.<file_sep>/getvalue/README.md # getvalue.lua This script will retrieve a value from a table and key specified as a get parameter to the url. For example, http://host/getvalue/?table=_table_&key=_key_ This will get the value "key" from the table "table" and return the value in HTML<file_sep>/json/json.lua local json = require "json" local lua_table = {a = 1, b = 2, c = {d = 3, e = 4}} local encoded_json = json:encode(lua_table) local json_in = '{"a":1,"b":2,"c":{"d":3,"e":4}}' local decoded_json = json:decode(json_in) local function dump(o) if type(o) == 'table' then local s = '{ ' for k,v in pairs(o) do if type(k) ~= 'number' then k = '"'..k..'"' end s = s .. '['..k..'] = ' .. dump(v) .. ',' end return s .. '} ' else return tostring(o) end end local renderTemplate = function(string, params) if not params then params = string string = params[1] end return (string.gsub(string, "({([^}]+)})", function(full,i) return params[i] or full end)) end local html = [[ <html><head><title>JSON Samples</title></head><body> <h1>Encoded (Lua Table to JSON)</h1> <p>{encoded}</p> <h1>Decoded (JSON - Lua Table)</h1> <p>{decoded}</p> </body></html> ]] response.addHeader("Content-Type", "text/html") response.setBody(renderTemplate(html, {encoded = encoded_json, decoded = dump(decoded_json)})) <file_sep>/json/README.md # json.lua This script demonstrates using the json module to encode from lua tables --> JSON and decode from JSON --> lua tables.<file_sep>/README.md Overview ======== This repository contains a selection of example scripts which run on the Edge Rocket platform. Each script resides in its own subdirectory and contains a more detailed README file. For an example of a single Edge Rocket application (service) which is composed of multiple scripts take a look at the edgepress project. <file_sep>/basicauth/README.md HTTP Basic Auth =============== This is an implementation of HTTP Basic Auth. It prompts the client for username/password. The credentials are pulled from the table named _auth_. Currently the password is assumed to be stored in the data table in plain text, if that's not the case you can always hash the password returned by the base64.decode. <file_sep>/bit/README.md # bits.lua This script shows how to use some of the bitwise operations in the bits library <file_sep>/edgepress/pages.lua -- This script handles the subpages for the website: -- 1) Determine the hostname as this is used as a portion of the key. -- 2) Retrieve template for the page -- 3) Retrieve all of the substitution variables for the template -- 4) Render the template and return it local renderTemplate = function(template, params) for k,v in pairs(params) do template = string.gsub(template, k, v) end return template end local host = request.getHeaderValue(HTTP_HEADER.HOST) local page = string.sub(request.getPath(), string.len("/pages/")+1) local template = db.get("ep-templates", host .. ":page") local name = db.get("ep-vars", host .. ":owner") local body = db.get("ep-vars", host .. ":" .. page .. ":content") local links = db.get("ep-vars", host .. ":pages") if body == nil then template = db.get("ep-templates", host .. ":404") end -- TODO: Once we have a JSON -> Lua table converter we need to get the page 'name' which corresponds to this page out of the links table. local paramTbl = {} paramTbl['{owner}'] = name; paramTbl['{pagename}'] = page; paramTbl['{content}'] = body; paramTbl['{pages}'] = links; response.addHeader("Content-Type", "text/html") response.setBody(renderTemplate(template,paramTbl)) return 0 <file_sep>/edgepress/admin.lua local renderTemplate = function(template, params) for k,v in pairs(params) do template = string.gsub(template, k, v) end return template end local encodedCredentials = request.getHeaderValue(HTTP_HEADER.AUTHORIZATION) if encodedCredentials ~= "" then local encodedDetails = string.gsub(encodedCredentials, "Basic ", "") local credentials = base64.decode(encodedDetails) -- if credentials is empty then it means that the details were not a valid Base64 encoding if credentials ~= "" then local username, password = string.match(credentials, "(%w+):(%w+)") local compare = db.get("ep-auth", username) if compare == password then local host = request.getHeaderValue(HTTP_HEADER.HOST) local template = db.get("ep-templates", host .. ":admin") local name = db.get("ep-vars", host .. ":owner") local links = db.get("ep-vars", host .. ":pages") local apikey = db.get("ep-vars", host .. ":apikey") local paramTbl = {} paramTbl['{owner}'] = name paramTbl['{pages}'] = links paramTbl['{apikey}'] = apikey paramTbl['{cid}'] = '12' -- need a way to get the collection id from the db for ep_vars paramTbl['{hostname}'] = request.getHost() response.addHeader("Content-Type", "text/html") response.setBody(renderTemplate(template,paramTbl)) return 0 end end end response.setResponseCode(401) response.setResponseText("Unauthorized") response.addHeader("WWW-Authenticate", "Basic realm=\"edgepress\"") response.setBody("Authentication Required") return 0 <file_sep>/helloworld/hello.lua -- Set the Content-Type header to text/plain response.addHeader("Content-Type", "text/plain") -- set the body of the response to "Hello World" response.setBody("Hello World")
c63df27f69d2277d26204c1800889dcdd025284d
[ "Markdown", "Lua" ]
22
Lua
isabella232/edge-rocket-examples
bd35f317d776937ba1e4919f8a7632602a87980f
f0bdd24ab895be431f5672a86dba1abde9b5857d
refs/heads/master
<repo_name>jimmytuc/node-sms<file_sep>/index.js var argv = require('optimist').argv; var models = require('./lib/models'); //var dirty = require('dirty'); var fs = require('fs'); var sms = require('./lib/sms'); //var runDir = argv.d || process.cwd(); var runDir = process.cwd(); var config = require(runDir + '/config'); var storageDir = '/tmp/.smsd/'; var nl = (process.platform === 'win32' ? '\r\n' : '\n'); function utf8 (txt) { // http://www.developershome.com/sms/gsmAlphabet.asp // http://spin.atomicobject.com/2011/09/08/converting-utf-8-to-the-7-bit-gsm-default-alphabet/ return new Buffer(txt).toString('utf8'); } var Library = { readNewMessagesAsModelFromFile: function (callback) { var newMessages = new models.Messages(); this.readAllMessagesFromFile(function(messagesAsStr){ newMessages = new models.Messages(JSON.parse(messagesAsStr)); callback(newMessages); }); }, readAllMessagesFromFile: function (next) { fs.readFile(storageDir+'messages.json', function(err, messagesAsStr){ messagesAsStr = utf8(messagesAsStr); if (err) { throw err; } else if (next) { next(messagesAsStr); } }); }, registerCommand: function (command, callback) { db.on('load', function() { var listener = db.get("listener"); listener.push( command ); db.set("listener", listener, function listenerSaved (){ if (callback) { callback(); } }); }); }, sendMessage: function (messageObj) { // messageObj has attributes: to (phone number), message (text), success (callback) sms.send({ to: messageObj.to, // Recipient Phone Number, lead by +49... text: messageObj.message // Text to send }, function(err, result) { // error message in String and result information in JSON if (err) { console.log(err); } messageObj.success(result); }); } }; module.exports = Library; <file_sep>/smsd.js var argv = require('optimist').argv; var sys = require('util'); var fs = require('fs'); var _ = require('underscore'); var dirty = require('dirty'); var sms = require('./lib/sms'); var models = require('./lib/models'); var verboseMode = argv.v || false; //var runDir = (argv.d && !argv.demo) || process.cwd(); var runDir = process.cwd(); if (argv.v) { sys.log("Read smsd configuration from " + runDir + '/config.js'); } var watchMode = false; try { var config = require(runDir + '/config'); } catch (e) { throw "No configuration file found. See documentation to add configuration to current working path!"; } var db = dirty(runDir + '/listener.db'); var storageDir = '/tmp/.smsd/'; /* SMSD can be called with an optional register parameter, that allows a script to register as a service that likes to be informed about incoming messages. All registered services are called on updates. */ var nl = (process.platform === 'win32' ? '\r\n' : '\n'); var listener = []; //var messages = new models.Messages(); db.on('load', function() { listener = db.get('listener') || []; if (argv.register) { // REGISTER LISTENER listener.push( argv.register ); db.set("listener", listener, function listenerSaved (){ console.log(listener); }); } else if (argv.reset) { if (argv.reset =='listener') { db.set("listener", []); } } else if (argv.watch) { // WATCH MESSAGE INPUT AND NOTIFY REGISTERED LISTENER ON UPDATES startDaemon(true); } else if (argv.fetch) { // FETCH MESSAGES FROM GATEWAY AND RETURN DATA fetchMessages(function(newMessages){ process.stdout.write(JSON.stringify(newMessages.toJSON())); }); } else if (argv.read) { // FETCH MESSAGES FROM FILE AND RETURN DATA readAllMessagesFromFile(function(messagesAsStr){ process.stdout.write(messagesAsStr || ''); }); } else if (argv.send) { // SEND MESSAGE if (argv.v) { sys.log("sending message..."); } // this is a workaround for bug in optimist, please give phone numbers by a leading plus sign including country code var to = new String(argv.to); to = (to.indexOf('+') !== 0) ? '+' + to : to; sms.send({ to: to || '', text: argv.message || '' }, function messageSent (response) { if (argv.v) { console.log(response); } }); } else { // WATCH MESSAGE INPUT AND NOTIFY REGISTERED LISTENER ON UPDATES startDaemon(false); } }); function readAllMessagesFromFile (next) { fs.readFile(storageDir+'messages.json', function(err, messagesAsStr){ if (err) { throw err; } else if (next) { next(messagesAsStr); } }); } function saveAllMessagesToFile (newMessages, next) { var messagesAsStr = JSON.stringify(newMessages.toJSON()); if (verboseMode) { sys.log("save to file system..."); sys.log(messagesAsStr); } fs.writeFile(storageDir+'messages.json', messagesAsStr, function(){ if (next) { next(newMessages); } }); } function writeMessagesToLog (newMessages) { if (verboseMode) { sys.log("write to log..."); } var messagesAsStr = ''; newMessages.forEach(function(message){ messagesAsStr = messagesAsStr + JSON.stringify(message.attributes) + "\n"; log(messagesAsStr); }); } function log (text) { var d = new Date(); fs.appendFile(storageDir+'log.txt', d.toJSON() + "\t" + text, function(){}); } function startDaemon (watch) { watchMode = watch; getAllMessagesFromGateway(); } function getAllMessagesFromGateway () { if (verboseMode) { sys.log("fetch all messages from gateway..."); } fetchMessages(function(newMessages){ saveAllMessagesToFile(newMessages, notifyListeners); writeMessagesToLog(newMessages); removeAllMessagesFromGateway(); }); if (watchMode) { setTimeout(getAllMessagesFromGateway, config.timeout || 30000); } } function removeAllMessagesFromGateway () { if (verboseMode) { sys.log("remove all messages from gateway..."); } sms.deletesms(); // remove all messages } function notifyListeners () { if (verboseMode) { sys.log("notify listeners..."); } listener = db.get('listener') || []; // read from data source, as listener could have been added while running if (listener && listener.length>0) { for (var i=0; i<listener.length; i++) { if (verboseMode) { sys.log("call listener: " + listener[i]); } log('notify listener ' + listener[i]); sms._command(listener[i]); } } } function fetchMessages (callback) { var getMessagesCallback = function(response){ // if (verboseMode) { // sys.log(response); // } var newMessages = new models.Messages(); var pattern = config.patterns[config.patternLang]; var headers = new RegExp(pattern.messageSeparator,'g'); var matcher = response.match(headers); var updatesFound = false; if (matcher) { for (var i=0; i<matcher.length; i++) { var message = {}; // get header var header = new RegExp(pattern.messageSeparator,'g'); header.exec(matcher[i]); //console.log(RegExp.$2); for (var index in pattern.separatorAttributes) { var attribute = pattern.separatorAttributes[index]; var idx = new Number(index) + 1; message[attribute] = RegExp['$'+idx]; } // get body var msgextract = response.split(matcher[i]); if (matcher[i+1]) { msgextract = msgextract[1].split(matcher[i+1]); msgextract = msgextract[0]; } else { msgextract = msgextract[1]; } var messageExp = new RegExp(pattern.bodyDefinition.replace(/\\r\\n/g,nl),'g'); messageExp.exec(msgextract); for (var index in pattern.bodyAttributes) { var attribute = pattern.bodyAttributes[index]; var idx = new Number(index) + 1; message[attribute] = RegExp['$'+idx]; } message.hash = encode(message.sendDateStr + message.phoneNumber + 'smsd'); // var matchingMessages = storedMessages.where({hash: message.hash}); // if (_.isEmpty(matchingMessages)) { updatesFound = true; // storedMessages.add(message); newMessages.add(message); // } } } if (updatesFound && callback) { callback(newMessages); } }; if (argv.simulate) { fs.readFile(argv.simulate, 'utf8', function (error, response) { getMessagesCallback(response); }); } else { sms.getsms(getMessagesCallback); } } function encode (txt) { return new Buffer(txt).toString('base64'); } function decode (txt) { return new Buffer(txt, 'base64').toString('utf8'); }
c21f8085da7f8c498be391b639e70861f423179b
[ "JavaScript" ]
2
JavaScript
jimmytuc/node-sms
1b03bd3b9b878d6f7d62fe1a910179b7ca9da424
b37bb478525f6fab85f7c641ca63572db723502f
refs/heads/master
<repo_name>samuelmullin/patterns<file_sep>/sql/ranking.sql /* Allows you to filter and select specific values within a window where the unique identifier you're using (IE object ID) would potentially appear more than once and you just need the row with the MIN or MAX value of a certain attribute */ WITH ranked_data AS ( SELECT table_name.*, ROW_NUMBER() OVER ( /* Row number 1 is the newest record based on date_created */ PARTITION BY object_id ORDER BY table_name.date_created DESC ) AS rn FROM table_name ) SELECT * FROM ranked_data WHERE ranked_data.rn = 1
4265e5473a7d55a730d346fcdd01342dbb2193ac
[ "SQL" ]
1
SQL
samuelmullin/patterns
1ad9d2e6717cd3b54cec3c71bc719da5118f2c05
e4f06b9fe2cdc726e69fc598e124c618fa0fa598
refs/heads/master
<repo_name>Davispc10/Despadmin<file_sep>/test/helpers/aguas_helper_test.rb require 'test_helper' class AguasHelperTest < ActionView::TestCase end <file_sep>/app/views/aguas/show.json.jbuilder json.extract! @agua, :id, :data_compra, :user_id, :created_at, :updated_at <file_sep>/app/models/user.rb class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :despesas_users has_many :despesas, through: :despesas_users has_many :aguas #validates :name, presence: true def qtde_aguas return self.aguas.count end end <file_sep>/db/migrate/20140701132409_create_aguas.rb class CreateAguas < ActiveRecord::Migration def change create_table :aguas do |t| t.date :data_compra t.references :user, index: true t.timestamps end end end <file_sep>/app/controllers/despesas_controller.rb class DespesasController < ApplicationController before_action :set_despesa, only: [:show, :edit, :update, :destroy] load_and_authorize_resource except: [:create] def alterar_status @desp_user = DespesasUser.select { |du| du.user_id == current_user.id }.find { |d| d.despesa_id == @despesa.id} respond_to do |format| if @desp_user.quite == 'nao' if @desp_user.update_attribute(:quite, 1) format.html { redirect_to @despesa, notice: t("successfully_updated") } else format.html { render :show } format.json { render json: @despesa.errors, status: :unprocessable_entity } end else if @desp_user.update_attribute(:quite, 0) format.html { redirect_to @despesa, notice: t("successfully_updated") } else format.html { render :show } format.json { render json: @despesa.errors, status: :unprocessable_entity } end end end end def history @despesas = Despesa.all if !current_user.admin? @despesas = @despesas.select { |d| d.user_ids.include?(current_user.id) } end desp_janeiro = @despesas.select {|d| d.this_month?(1)} desp_fevereiro = @despesas.select {|d| d.this_month?(2)} desp_marco = @despesas.select {|d| d.this_month?(3)} desp_abril = @despesas.select {|d| d.this_month?(4)} desp_maio = @despesas.select {|d| d.this_month?(5)} desp_junho = @despesas.select {|d| d.this_month?(6)} desp_julho = @despesas.select {|d| d.this_month?(7)} desp_agosto = @despesas.select {|d| d.this_month?(8)} desp_setembro = @despesas.select {|d| d.this_month?(9)} desp_outubro = @despesas.select {|d| d.this_month?(10)} desp_novembro = @despesas.select {|d| d.this_month?(11)} desp_dezembro = @despesas.select {|d| d.this_month?(12)} total_desp_janeiro = 0 desp_janeiro.each { |dj| total_desp_janeiro = total_desp_janeiro + dj.valor_por_pessoa } total_desp_fevereiro = 0 desp_fevereiro.each { |dj| total_desp_fevereiro = total_desp_fevereiro + dj.valor_por_pessoa } total_desp_marco = 0 desp_marco.each { |dj| total_desp_marco = total_desp_marco + dj.valor_por_pessoa } total_desp_abril = 0 desp_abril.each { |dj| total_desp_abril = total_desp_abril + dj.valor_por_pessoa } total_desp_maio = 0 desp_maio.each { |dj| total_desp_maio = total_desp_maio + dj.valor_por_pessoa } total_desp_junho = 0 desp_junho.each { |dj| total_desp_junho = total_desp_junho + dj.valor_por_pessoa } total_desp_julho = 0 desp_julho.each { |dj| total_desp_julho = total_desp_julho + dj.valor_por_pessoa } total_desp_agosto = 0 desp_agosto.each { |dj| total_desp_agosto = total_desp_agosto + dj.valor_por_pessoa } total_desp_setembro = 0 desp_setembro.each { |dj| total_desp_setembro = total_desp_setembro + dj.valor_por_pessoa } total_desp_outubro = 0 desp_outubro.each { |dj| total_desp_outubro = total_desp_outubro + dj.valor_por_pessoa } total_desp_novembro = 0 desp_novembro.each { |dj| total_desp_novembro = total_desp_novembro + dj.valor_por_pessoa } total_desp_dezembro = 0 desp_dezembro.each { |dj| total_desp_dezembro = total_desp_dezembro + dj.valor_por_pessoa } data_table = GoogleVisualr::DataTable.new data_table.new_column('string', 'Mês') data_table.new_column('number', 'Despesa') data_table.add_rows(12) data_table.set_cell(0, 0, 'Janeiro') data_table.set_cell(0, 1, total_desp_janeiro) data_table.set_cell(1, 0, 'Fevereiro') data_table.set_cell(1, 1, total_desp_fevereiro) data_table.set_cell(2, 0, 'Março') data_table.set_cell(2, 1, total_desp_marco) data_table.set_cell(3, 0, 'Abril') data_table.set_cell(3, 1, total_desp_abril) data_table.set_cell(4, 0, 'Maio') data_table.set_cell(4, 1, total_desp_maio) data_table.set_cell(5, 0, 'Junho') data_table.set_cell(5, 1, total_desp_junho) data_table.set_cell(6, 0, 'Julho') data_table.set_cell(6, 1, total_desp_julho) data_table.set_cell(7, 0, 'Agosto') data_table.set_cell(7, 1, total_desp_agosto) data_table.set_cell(8, 0, 'Setembro') data_table.set_cell(8, 1, total_desp_setembro) data_table.set_cell(9, 0, 'Outubro') data_table.set_cell(9, 1, total_desp_outubro) data_table.set_cell(10, 0, 'Novembro') data_table.set_cell(10, 1, total_desp_novembro) data_table.set_cell(11, 0, 'Dezembro') data_table.set_cell(11, 1, total_desp_dezembro) opts = { width: 900, height: 400, :title => 'Visão Geral dos Gastos', :hAxis => { :title => 'Mês', :titleTextStyle => {:color => 'gray'}}, bar: { groupWidth: '50%' }, legend: {position: 'none'}, dataOpacity: 0.5, chartArea: {width:'80%',height:'60%'} } @chart = GoogleVisualr::Interactive::ColumnChart.new(data_table, opts) end # GET /despesas # GET /despesas.json def index @despesas = Despesa.all @total = 0 if !current_user.admin? @despesas = @despesas.select { |d| d.user_ids.include?(current_user.id) } @despesas.each { |d| @total = @total + d.valor_por_pessoa unless d.despesas_users.find {|du| du.user_id == current_user.id}.quite == 'sim'} @despesas_user = DespesasUser.select { |du| du.user_id == current_user.id } end end # GET /despesas/1 # GET /despesas/1.json def show if !current_user.admin? @desp_user = DespesasUser.select { |du| du.user_id == current_user.id }.find { |d| d.despesa_id == @despesa.id} end @despesas_users = DespesasUser.all end # GET /despesas/new def new @despesa = Despesa.new @despesa.despesas_users.build @not_admin_users = User.select { |u| !u.admin? } end # GET /despesas/1/edit def edit @not_admin_users = User.select { |u| !u.admin? } end # POST /despesas # POST /despesas.json def create @despesa = Despesa.new(despesa_params) @envolvidos = @despesa.users respond_to do |format| if @despesa.save UserMailer.create_notify_email(current_user, @envolvidos).deliver format.html { redirect_to @despesa, notice: 'Despesa was successfully created.' } format.json { render :show, status: :created, location: @despesa } else format.html { render :new } format.json { render json: @despesa.errors, status: :unprocessable_entity } end end end # PATCH/PUT /despesas/1 # PATCH/PUT /despesas/1.json def update @envolvidos = @despesa.users respond_to do |format| if @despesa.update(despesa_params) UserMailer.update_notify_email(current_user, @envolvidos).deliver format.html { redirect_to @despesa, notice: 'Despesa was successfully updated.' } format.json { render :show, status: :ok, location: @despesa } else format.html { render :edit } format.json { render json: @despesa.errors, status: :unprocessable_entity } end end end # DELETE /despesas/1 # DELETE /despesas/1.json def destroy @despesa.destroy respond_to do |format| format.html { redirect_to despesas_url, notice: 'Despesa was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_despesa @despesa = Despesa.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def despesa_params params.require(:despesa).permit(:descricao, :valor, :data_vencimento, :data_pagamento, :status, :obs, :arquivo, :user_ids => []) end end <file_sep>/db/migrate/20140625124523_add_arquivo_to_despesas.rb class AddArquivoToDespesas < ActiveRecord::Migration def change add_attachment :despesas, :arquivo end end <file_sep>/db/migrate/20140704135901_create_despesas_users.rb class CreateDespesasUsers < ActiveRecord::Migration def change create_table :despesas_users do |t| t.belongs_to :despesa t.belongs_to :user t.integer :quite, default: 0 end #add_index :despesas_users, [:despesa_id, :user_id], # name: "despesas_users_index", # unique: true end end <file_sep>/db/migrate/20140618153944_create_despesas.rb class CreateDespesas < ActiveRecord::Migration def change create_table :despesas do |t| t.string :descricao t.float :valor t.date :data_vencimento t.date :data_pagamento t.integer :status t.string :obs t.timestamps end end end <file_sep>/app/views/aguas/index.json.jbuilder json.array!(@aguas) do |agua| json.extract! agua, :id, :data_compra, :user_id json.url agua_url(agua, format: :json) end <file_sep>/app/models/despesas_user.rb class DespesasUser < ActiveRecord::Base belongs_to :despesa belongs_to :user enum quite: { nao: 0, sim: 1 } end <file_sep>/app/models/agua.rb class Agua < ActiveRecord::Base belongs_to :user default_scope { order(:data_compra => :desc) } validates :user_id, :data_compra, presence: true end <file_sep>/app/models/despesa.rb class Despesa < ActiveRecord::Base enum status: { pendente: 0, paga: 1 } has_attached_file :arquivo do_not_validate_attachment_file_type :arquivo default_scope { order(:status => :asc) } has_many :despesas_users has_many :users, through: :despesas_users validates :descricao, :valor, :data_vencimento, presence: true validates_associated :users, presence: true def vencida? if (self.data_vencimento <=> Date.today) == -1 or (self.data_vencimento <=> Date.today) == 0 return true else return false end end def valor_por_pessoa if self.descricao == "Internet" return ((self.valor - 40) / self.users.count).round(2) else return (self.valor / self.users.count).round(2) end end def this_month?(month) return self.data_vencimento.mon == month end end <file_sep>/app/mailers/user_mailer.rb class UserMailer < ActionMailer::Base default from: "<EMAIL>" def get_emails(people) emails = Array.new people.each { |p| emails << p.email } return emails end def create_notify_email(user, people) @user = user @people = people @url = 'http://pacific-plateau-9356.herokuapp.com/' @emails = get_emails(people) mail(to: @emails, subject: 'New expense') end def update_notify_email(user, people) @user = user @people = people @url = 'http://pacific-plateau-9356.herokuapp.com/' @emails = get_emails(people) mail(to: @emails, subject: 'Expense updated') end end <file_sep>/test/controllers/aguas_controller_test.rb require 'test_helper' class AguasControllerTest < ActionController::TestCase setup do @agua = aguas(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:aguas) end test "should get new" do get :new assert_response :success end test "should create agua" do assert_difference('Agua.count') do post :create, agua: { data_compra: @agua.data_compra, user_id: @agua.user_id } end assert_redirected_to agua_path(assigns(:agua)) end test "should show agua" do get :show, id: @agua assert_response :success end test "should get edit" do get :edit, id: @agua assert_response :success end test "should update agua" do patch :update, id: @agua, agua: { data_compra: @agua.data_compra, user_id: @agua.user_id } assert_redirected_to agua_path(assigns(:agua)) end test "should destroy agua" do assert_difference('Agua.count', -1) do delete :destroy, id: @agua end assert_redirected_to aguas_path end end <file_sep>/app/controllers/aguas_controller.rb class AguasController < ApplicationController before_action :set_agua, only: [:show, :edit, :update, :destroy] load_and_authorize_resource except: [:create] # GET /aguas # GET /aguas.json def index @aguas = Agua.all @not_admin_users = User.select { |u| !u.admin? } array_qtdes_aguas = Array.new @not_admin_users.each do |u| array_qtdes_aguas.push(u.qtde_aguas) end @proximos_compradores_agua = Array.new @not_admin_users.each do |u| @proximos_compradores_agua.push(u) unless u.qtde_aguas != array_qtdes_aguas.min end end # GET /aguas/1 # GET /aguas/1.json def show end # GET /aguas/new def new @agua = Agua.new @not_admin_users = User.select { |u| !u.admin? } end # GET /aguas/1/edit def edit @not_admin_users = User.select { |u| !u.admin? } end # POST /aguas # POST /aguas.json def create @agua = Agua.new(agua_params) respond_to do |format| if @agua.save format.html { redirect_to @agua, notice: 'Agua was successfully created.' } format.json { render :show, status: :created, location: @agua } else format.html { render :new } format.json { render json: @agua.errors, status: :unprocessable_entity } end end end # PATCH/PUT /aguas/1 # PATCH/PUT /aguas/1.json def update respond_to do |format| if @agua.update(agua_params) format.html { redirect_to @agua, notice: 'Agua was successfully updated.' } format.json { render :show, status: :ok, location: @agua } else format.html { render :edit } format.json { render json: @agua.errors, status: :unprocessable_entity } end end end # DELETE /aguas/1 # DELETE /aguas/1.json def destroy @agua.destroy respond_to do |format| format.html { redirect_to aguas_url, notice: 'Agua was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_agua @agua = Agua.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def agua_params params.require(:agua).permit(:data_compra, :user_id) end end
7eb92716d05f319e495d0273fdc8647e5212d63d
[ "Ruby" ]
15
Ruby
Davispc10/Despadmin
cd1ce87c002831a05385a28eac05f8f050507300
abf244a48051bf69efc77cf742203feee4fb750a
refs/heads/master
<file_sep>*Possibly destroy particles once they're static to improve optimization.<file_sep>#include "ParticleManager.h" ParticleManager::ParticleManager(int size, sf::RenderTexture& window) { board.resize(window.getSize().x, std::vector<int>(window.getSize().y)); srand((unsigned int)time(NULL)); particles.resize(size, Particle(0, 0, false, radius, &board, &window, &staticParticles)); for (size_t i = 0; i < particles.size(); i++) { particles[i].setLocation(rand() % (int)(window.getSize().x), rand() % (int)(window.getSize().y)); } particles.push_back(Particle(window.getSize().x / 2, window.getSize().y / 2, true, radius, &board, &window, &staticParticles)); //this is the seed particles.push_back(Particle(window.getSize().x / 2 + 1, window.getSize().y / 2, true, radius, &board, &window, &staticParticles)); //this is the seed particles.push_back(Particle(window.getSize().x / 2 - 1, window.getSize().y / 2, true, radius, &board, &window, &staticParticles)); //this is the seed particles.push_back(Particle(window.getSize().x / 2, window.getSize().y / 2 + 1, true, radius, &board, &window, &staticParticles)); //this is the seed particles.push_back(Particle(window.getSize().x / 2, window.getSize().y / 2 - 1, true, radius, &board, &window, &staticParticles)); //this is the seed } ParticleManager::~ParticleManager() { } void ParticleManager::update() { for (size_t i = 0; i < particles.size(); i++) { staticParticles += particles[i].update(); } } std::vector<std::vector<int>>& ParticleManager::getBoard(){ return board; } bool ParticleManager::isDone() { return (staticParticles >= (particles.size() - 1)); }<file_sep>#pragma once #include <vector> #include <iostream> #include "Particle.h" class ParticleManager { public: ParticleManager(int size, sf::RenderTexture& window); ~ParticleManager(); void update(); std::vector<std::vector<int>>& getBoard(); bool isDone(); private: std::vector<Particle> particles; std::vector<std::vector<int>> board; size_t staticParticles = 5; int radius = 1; }; <file_sep>#include "UIManager.h" UIManager::UIManager(int x, int y, bool fullscreen) { if (fullscreen == false) { window.create(sf::VideoMode(x, y), "Diffusion-Limited Aggregation", sf::Style::Close); } else { window.create(sf::VideoMode(x, y), "Diffusion-Limited Aggregation", sf::Style::Fullscreen); } texture.create(window.getSize().x, window.getSize().y); texture.clear(sf::Color::Black); } void UIManager::start(int x, int y) { window.setSize(sf::Vector2u(x+100, y)); texture.create(window.getSize().x, window.getSize().y); texture.clear(sf::Color::Black); } void UIManager::pollEvent(/*std::vector<std::vector<int>>& board*/) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Resized) { sf::FloatRect visibleArea(0, 0, event.size.width, event.size.height); window.setView(sf::View(visibleArea)); //board.resize(window.getSize().x, std::vector<int>(window.getSize().y)); } if (event.type == sf::Event::Closed) { window.close(); } } } sf::RenderWindow& UIManager::getWindow() { return window; } sf::RenderTexture& UIManager::getTexture() { return texture; } void UIManager::saveDLA() { texture.getTexture().copyToImage().saveToFile("DLA.png"); }<file_sep>#pragma once #include <cstdlib> #include <stdlib.h> #include <ctime> #include <vector> #include "SFML/Graphics.hpp" class Particle { public: Particle(int x, int y, bool seed, int r, std::vector<std::vector<int>> *board, sf::RenderTexture *window, size_t *pStatic); int update(); void setIsStatic(); bool getIsStatic(); void setSeed(double seed); void setLocation(int x, int y); sf::RectangleShape getRectangle(); private: void walk(); sf::RenderTexture *windowP; sf::RectangleShape point; std::vector<std::vector<int>> *boardP; size_t *nStatic; int xPosition; int yPosition; double arrivalTime = 0; double startTime = 0; bool isStatic = false; int radius; int windowX = 0; int windowY = 0; }; <file_sep>#pragma once #include <iostream> #include "ParticleManager.h" #include "UIManager.h" class Scene { public: Scene(); void start(); void getInput(); private: int xresolution = 0; int yresolution = 0; int nParticles = 0; bool isDone = false; bool isFullscreen = false; std::unique_ptr<UIManager> ui; std::unique_ptr<ParticleManager> particles; }; <file_sep>#include "Scene.h" Scene::Scene() { getInput(); ui.reset(new UIManager(xresolution, yresolution, isFullscreen)); particles.reset(new ParticleManager(nParticles, ui->getTexture())); } void Scene::start() { while (ui->getWindow().isOpen()) { ui->pollEvent(); particles->update(); ui->getTexture().display(); ui->getWindow().clear(); sf::Sprite sprite(ui->getTexture().getTexture()); ui->getWindow().draw(sprite); ui->getWindow().display(); if (particles->isDone() && isDone == false) { isDone = true; ui->saveDLA(); std::cout << "Done. Image saved as DLA.PNG"; } } } void Scene::getInput() { std::cout << "X Resolution (if you aren't sure, just put 800): "; std::cin >> xresolution; std::cout << "Y Resolution (if you aren't sure, just put 800): "; std::cin >> yresolution; std::cout << "Number of particles (if you aren't sure, just put 160000): "; std::cin >> nParticles; /* std::cout << "Fullscreen? (y / n): "; char option; std::cin >> option; if (option == 'y') { isFullscreen = true; } else { isFullscreen = false; } */ }<file_sep>#pragma once #include "SFML/Graphics.hpp" class UIManager { public: UIManager(int x, int y, bool fullscreen); void pollEvent(/*std::vector<std::vector<int>>& board*/); sf::RenderWindow& getWindow(); sf::RenderTexture& getTexture(); void saveDLA(); void start(int x, int y); private: sf::RenderWindow window; sf::RenderTexture texture; }; <file_sep>#include "classes/Scene.h" int main() { Scene scene; scene.start(); return 0; }<file_sep># SFMLDLA Diffusion-limited aggregation is the process in which particles stick together. For a more detailed explaination, visit the [wikipedia page](https://en.wikipedia.org/wiki/Diffusion-limited_aggregation) Image of DLA using program: ![DLA Picture](https://camo.githubusercontent.com/5c242e83ff40bf88a6640e85e0ecc91ee9730bda/687474703a2f2f6765656f6f6e2e636f6d2f70726f6a656374732f696d616765732f646c612e706e67 "DLA Simulation") <file_sep>#include "Particle.h" Particle::Particle(int x, int y, bool seed, int r, std::vector<std::vector<int>> *board, sf::RenderTexture *window, size_t *pStatic) { arrivalTime = 0; startTime = 0; nStatic = pStatic; windowP = window; windowX = (*windowP).getSize().x; windowY = (*windowP).getSize().y; boardP = board; xPosition = 0; yPosition = 0; radius = r; srand(time(NULL)); isStatic = seed; point.setSize(sf::Vector2f(radius, radius)); if (seed == true) { xPosition = x; yPosition = y; setIsStatic(); } else { point.setFillColor(sf::Color::White); } } int Particle::update() { if (!isStatic) { walk(); (*boardP)[xPosition][yPosition] = 1; if (xPosition == 0) { //left if (yPosition == 0) {//topleft if ((*boardP)[xPosition][yPosition] == 2 || (*boardP)[xPosition][yPosition] == 2) { setIsStatic(); return 1; } } else if (yPosition == windowY - 1) {//bottomleft if ((*boardP)[xPosition][yPosition] == 2 || (*boardP)[xPosition][yPosition] == 2) { setIsStatic(); return 1; } } else {//middleleft if ((*boardP)[xPosition][yPosition] == 2 || (*boardP)[xPosition][yPosition] == 2 || (*boardP)[xPosition][yPosition] == 2) { setIsStatic(); return 1; } } } else if (xPosition == windowX - 1) {//right if (yPosition == 0) {//topright if ((*boardP)[xPosition][yPosition] == 2 || (*boardP)[xPosition][yPosition] == 2) { setIsStatic(); return 1; } } else if (yPosition == windowY - 1) {//bottomlright if ((*boardP)[xPosition][yPosition] == 2 || (*boardP)[xPosition][yPosition] == 2) { setIsStatic(); return 1; } } else {//middleright if ((*boardP)[xPosition][yPosition + 1] == 2 || (*boardP)[xPosition][yPosition - 1] == 2 || (*boardP)[xPosition - 1][yPosition] == 2) { setIsStatic(); return 1; } } } else {//middle if (yPosition == 0) {//top middle if ((*boardP)[xPosition][yPosition + 1] == 2 || (*boardP)[xPosition + 1][yPosition] == 2 || (*boardP)[xPosition - 1][yPosition] == 2) { setIsStatic(); return 1; } } else if (yPosition == windowY - 1) {//bottom middle if ((*boardP)[xPosition][yPosition - 1] == 2 || (*boardP)[xPosition + 1][yPosition] == 2 || (*boardP)[xPosition - 1][yPosition] == 2) { setIsStatic(); return 1; } } else {//middle middle if ((*boardP)[xPosition][yPosition + 1] == 2 || (*boardP)[xPosition][yPosition - 1] == 2 || (*boardP)[xPosition + 1][yPosition] == 2 || (*boardP)[xPosition - 1][yPosition] == 2) { setIsStatic(); return 1; } } } } return 0; } void Particle::walk() { switch (1 + rand() % 4) { case 1: xPosition += 1; break; case 2: xPosition -= 1; break; case 3: yPosition += 1; break; case 4: yPosition -= 1; break; default: break; } //Prevents particles from going out of bounds. if (xPosition < 0) { xPosition = 0; } else if (xPosition > windowX - 1) { xPosition = windowX - 1; } if (yPosition < 0) { yPosition = 0; } else if (yPosition > windowY - 1) { yPosition = windowY - 1; } } void Particle::setIsStatic() { isStatic = true; sf::Color color((std::sin(sqrt((float)(*nStatic)) / (float)100) + 1) * (255 / 2), 0, 150); point.setFillColor(color); (*boardP)[xPosition][yPosition] = 2; point.setPosition((float)xPosition, (float)yPosition); (*windowP).draw(point); } bool Particle::getIsStatic() { return isStatic; } void Particle::setSeed(double seed) { srand(seed); } void Particle::setLocation(int x, int y) { (*boardP)[xPosition][yPosition] = 0; xPosition = x; yPosition = y; (*boardP)[xPosition][yPosition] = 1; } sf::RectangleShape Particle::getRectangle() { return point; }
1ea943502b9f10090402c10406ff4f1007652626
[ "Markdown", "Text", "C++" ]
11
Text
Geeoon/SFMLDLA
de6285c34f7712be91a4ed6eb7d83bbba2d2494b
8c97a9053015d61e18672e09dda9191f4c71989e
refs/heads/main
<repo_name>Liiv-MetaBang/metabang-backend-mm<file_sep>/src/main/java/com/dkne/metabang/service/ReviewService.java package com.dkne.metabang.service; import com.dkne.metabang.domain.house.House; import com.dkne.metabang.domain.house.HouseRepository; import com.dkne.metabang.domain.review.Review; import com.dkne.metabang.domain.review.ReviewRepository; import com.dkne.metabang.web.dto.ReviewSaveRequestDto; import com.dkne.metabang.web.dto.ReviewUpdateRequestDto; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @RequiredArgsConstructor @Service public class ReviewService { private final HouseRepository houseRepository; private final ReviewRepository reviewRepository; @Transactional public int create(ReviewSaveRequestDto requestDto) { House house = houseRepository.getById(requestDto.getHouse_id()); return reviewRepository.save(Review.builder() .score(requestDto.getScore()) .contents(requestDto.getContents()) .house(house) .build()).getReview_id(); } @Transactional(readOnly = true) public List<Review> findAll(int house_id) { return houseRepository.findById(house_id).get().getReviews(); } @Transactional public int update(int review_id, ReviewUpdateRequestDto requestDto) { Review review = reviewRepository.findById(review_id) .orElseThrow(() -> new IllegalArgumentException("해당 리뷰가 없습니다. review_id=" + review_id)); review.update(requestDto.getContents(), requestDto.getScore()); return review_id; } @Transactional public void delete (int review_id) { Review review = reviewRepository.findById(review_id) .orElseThrow(() -> new IllegalArgumentException("해당 리뷰가 없습니다. review_id=" + review_id)); reviewRepository.delete(review); } } <file_sep>/src/main/java/com/dkne/metabang/MetabangApplication.java package com.dkne.metabang; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MetabangApplication { public static void main(String[] args) { SpringApplication.run(MetabangApplication.class, args); } } <file_sep>/src/main/java/com/dkne/metabang/domain/house/House.java package com.dkne.metabang.domain.house; import javax.persistence.*; import com.dkne.metabang.domain.image.Image; import com.dkne.metabang.domain.review.Review; import com.dkne.metabang.web.dto.ReviewResponseDto; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import java.util.ArrayList; import java.util.List; @Getter @NoArgsConstructor @Entity public class House { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int house_id; @Column(length = 45, nullable = true) private String house_name; @Column(nullable = true) private long price; @Column(nullable = true) private int build_date; @Column(nullable = true) private int area; @Column(nullable = true) private int layer; @Column(length = 45, nullable = false) private String address; @Column(length = 45, nullable = false) private double lng; @Column(nullable = false) private double lat; @Column(nullable = true) private String thumbnail; @JsonIgnore @OneToMany(mappedBy = "house") private List<Review> reviews = new ArrayList<Review>(); @JsonIgnore @OneToMany(mappedBy = "house") private List<Image> images = new ArrayList<Image>(); @Builder public House(int house_id, String house_name, long price, int build_date, int area, int layer, Double lng, Double lat, String address , String thumbnail) { super(); this.house_id = house_id; this.house_name = house_name; this.price = price; this.build_date = build_date; this.area = area; this.layer = layer; this.address = address; this.lat = lat; this.lng = lng; this.thumbnail = thumbnail; } public void update(long price) { this.price = price; } }<file_sep>/src/main/java/com/dkne/metabang/domain/house/HouseRepository.java package com.dkne.metabang.domain.house; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface HouseRepository extends JpaRepository<House, Integer>, JpaSpecificationExecutor<House> { } <file_sep>/src/main/java/com/dkne/metabang/web/dto/HouseFilterRequestDto.java package com.dkne.metabang.web.dto; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor public class HouseFilterRequestDto { private long low_price; private long high_price; private String address; @Builder public HouseFilterRequestDto(long low_price, long high_price, String address) { this.low_price = low_price; this.high_price = high_price; this.address = address; } }<file_sep>/src/main/java/com/dkne/metabang/domain/review/ReviewRepository.java package com.dkne.metabang.domain.review; import com.dkne.metabang.web.dto.ReviewResponseDto; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface ReviewRepository extends JpaRepository<Review, Integer>, JpaSpecificationExecutor<Review> { // @Query("SELECT r FROM Review r left outer join house on house.house_id = #{house_id}") // List<ReviewResponseDto> findAllReview(); } <file_sep>/src/main/java/com/dkne/metabang/web/dto/ReviewUpdateRequestDto.java package com.dkne.metabang.web.dto; import com.dkne.metabang.domain.review.Review; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor public class ReviewUpdateRequestDto { private String contents; private int score; @Builder public ReviewUpdateRequestDto(String contents, int score) { this.contents = contents; this.score = score; } public Review toEntity() { return Review.builder() .contents(contents) .score(score) .build(); } } <file_sep>/README.md # metabang-backend-mm qqri branch maemul &amp; review<file_sep>/src/test/java/com/dkne/metabang/MetabangApplicationTests.java package com.dkne.metabang; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class MetabangApplicationTests { @Test void contextLoads() { } }
8565095344ae76ed13c28c151ce26aa34c5ea18d
[ "Markdown", "Java" ]
9
Java
Liiv-MetaBang/metabang-backend-mm
54f578df0b77ea29705a51b483ab1b3d99be1ae6
063897e67615ad73ee480fb84c9a8becbb814fc4
refs/heads/master
<repo_name>bogga/RMICalculator<file_sep>/Client.java import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; public class Client { public static void main(String[] args) { try { Calculator c = (Calculator) Naming.lookup("rmi://localhost/CalculatorService"); System.out.println("3+21="+ c.add(3, 21)); System.out.println("18-9="+ c.sub(18, 9)); System.out.println("4*17="+ c.mul(4, 17)); System.out.println("70/10="+ c.div(70, 10)); System.out.println("2^5="+ c.pow(2, 5)); } catch (MalformedURLException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } catch (NotBoundException e) { e.printStackTrace(); } catch (java.lang.ArithmeticException e) { e.printStackTrace(); } } }
e5152173a2191f211c58b3c7ed3c6bb6fe066898
[ "Java" ]
1
Java
bogga/RMICalculator
d99bad37c822d325de283d47f06f16d7b21d1dc9
29528d68415cb87f0ef103e96906118d99fe827d
refs/heads/master
<repo_name>ssengupta-pl/TokenManager<file_sep>/src/ui/src/components/Profile.js var React = require('react/addons'); var Reflux = require('reflux'); var EnvironmentStore = require('../stores/EnvironmentStore'); var ActiveProfileStore = require('../stores/ActiveProfileStore'); var ProfileActions = require('../actions/ProfileActions'); var ActiveProfileActions = require('../actions/ActiveProfileActions'); var EnvironmentActions = require('../actions/EnvironmentActions'); var EnvironmentList = require('./EnvironmentList'); var EnvironmentAddForm = require('./EnvironmentAddForm'); var Profile = React.createClass({ mixins: [Reflux.connect(EnvironmentStore, 'environmentList'), Reflux.connect(ActiveProfileStore, 'activeProfile')], getInitialState: function() { return { profileDisplayState: false }; }, componentDidUpdate: function(nextProps) { var thisProfile = nextProps.data.applicationName; var activeProfile = this.state.activeProfile; if (thisProfile === activeProfile) { this.state.profileDisplayState = !this.state.profileDisplayState; if (this.state.profileDisplayState) { EnvironmentActions.load(this.props.data._links.environments.href); this.refs.profileBody.getDOMNode().className = 'profile-body-container-show-true'; } } else { this.refs.profileBody.getDOMNode().className = 'profile-body-container-show-false'; } }, handleProfileToggle: function() { ActiveProfileActions.toggle(this.props.data.applicationName); }, handleProfileDelete: function() { ProfileActions.delete(this.props.data._links.self.href); }, render: function() { return ( <div className="profile-container"> <div className="profile-title-container"> <span className="profile-name"> Application name: {this.props.data.applicationName}&nbsp; Owner: {this.props.data.owner} </span> <span className="profile-action"> <i className="fa fa-toggle-down" onClick={this.handleProfileToggle}></i> </span> <span className="profile-action" onClick={this.handleProfileDelete}> <i className="fa fa-times"></i> </span> </div> <div className={'profile-body-container-show-' + this.state.profileDisplayState} ref="profileBody"> <EnvironmentAddForm profile={this.props.data} /> <EnvironmentList environments={this.state.environmentList} profile={this.props.data} /> </div> </div> ); } }); module.exports = Profile; <file_sep>/src/ui/src/stores/EnvironmentStore.js 'use strict'; var Reflux = require('reflux'); var HTTP = require('superagent'); var EnvironmentActions = require('../actions/EnvironmentActions'); var Constants = require('../Constants.js'); var BaseEnvironmentsUrl = Constants.BaseUrl + '/environments'; var EnvironmentStore = Reflux.createStore({ listenables: [EnvironmentActions], init: function() { this.listenTo(EnvironmentActions.load, this.fetchAll); }, getInitialState: function() { this.environmentList = []; return this.environmentList; }, fetchAll: function(url) { HTTP.get(url) .end(function(req, res) { this.process(res.text); }.bind(this) ); }, onAdd: function(environment, allEnvironmentsUrl) { HTTP.post(BaseEnvironmentsUrl) .set('Content-Type', 'application/json') .send(JSON.stringify(environment)) .end(function() { this.fetchAll(allEnvironmentsUrl); }.bind(this)); }, onDelete: function(environmentUrl, allEnvironmentsUrl) { HTTP.del(environmentUrl) .end(function() { this.fetchAll(allEnvironmentsUrl); }.bind(this)); }, process: function(jsonAsText) { this.environmentList = (!JSON.parse(jsonAsText)._embedded) ? [] : JSON.parse(jsonAsText)._embedded.environments; this.trigger(this.environmentList); } }); module.exports = EnvironmentStore; <file_sep>/src/main/java/com/boundlessgeo/ps/tm/controllers/EnvironmentController.java package com.boundlessgeo.ps.tm.controllers; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.rest.webmvc.RepositoryRestController; import org.springframework.data.rest.webmvc.support.RepositoryEntityLinks; import org.springframework.hateoas.Resource; import org.springframework.hateoas.Resources; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.boundlessgeo.ps.tm.feign.client.GeoServerClient; import com.boundlessgeo.ps.tm.feign.model.GeoServerWorkspace; import com.boundlessgeo.ps.tm.model.Environment; import com.boundlessgeo.ps.tm.model.Workspace; import com.boundlessgeo.ps.tm.repositories.EnvironmentRepository; import com.boundlessgeo.ps.tm.repositories.WorkspaceRepository; import feign.Feign; import feign.auth.BasicAuthRequestInterceptor; import feign.gson.GsonDecoder; @RepositoryRestController public class EnvironmentController { private final RepositoryEntityLinks entityLinks; private final EnvironmentRepository repository; @Autowired public EnvironmentController(RepositoryEntityLinks links, EnvironmentRepository repo) { this.entityLinks = links; this.repository = repo; } @RequestMapping(method = RequestMethod.GET, value = "/environments/{environmentId}/workspaces") public @ResponseBody ResponseEntity<?> getWorkspaces( @PathVariable Long environmentId) { Environment environment = repository.findOne(environmentId); if (null == environment) { return ResponseEntity.notFound().build(); } GeoServerClient client = Feign.builder().decoder(new GsonDecoder()) .requestInterceptor(new BasicAuthRequestInterceptor( environment.getGeoserverUser(), environment.getGeoserverPassword())) .target(GeoServerClient.class, environment.getGeoserverUrl()); List<GeoServerWorkspace> gsWorkspaces = client.workspaces() .getWorkspaces().getWorkspace(); // Go through each GeoServer workspace and check if it is in the // environment's list. List<Resource<Workspace>> resourceList = gsWorkspaces.stream() .map(gsWorkspace -> { Workspace workspace; // Find out if this particular GeoServer work space is in // the environment's list. Optional<Workspace> optionalWorkspace = environment .getWorkspaces().stream().filter(ws -> { return gsWorkspace.getName().equals(ws.getName()); }).findFirst(); if (optionalWorkspace.isPresent()) { // If it is in the list, set the transient registered // flag to true. workspace = optionalWorkspace.get(); workspace.setRegistered(true); } else { // If it is not in the list, create a new Workspace // object with the name from GeoServer, // and set the transient registered flag to false. workspace = new Workspace(); workspace.setName(gsWorkspace.getName()); workspace.setRegistered(false); } return workspace; }).map(workspace -> { // Create a Resource for each Workspace and set the // appropriate links. // (Not sure if this is really necessary.) Resource<Workspace> resource = new Resource<>(workspace); if (workspace.getId() > 0) { resource.add(entityLinks .linkToSingleResource(WorkspaceRepository.class, workspace.getId()) .withSelfRel()); resource.add(entityLinks .linkForSingleResource( WorkspaceRepository.class, workspace.getId()) .slash("environment").withRel("environment")); } return resource; }).collect(Collectors.toList()); Resources<Resource<Workspace>> resources = new Resources<>( resourceList); return ResponseEntity.ok(resources); } } <file_sep>/src/main/java/com/boundlessgeo/ps/tm/feign/client/GeoServerClient.java package com.boundlessgeo.ps.tm.feign.client; import com.boundlessgeo.ps.tm.feign.model.GeoServerWorkspaces; import feign.RequestLine; public interface GeoServerClient { @RequestLine("GET /rest/workspaces.json") GeoServerWorkspaces workspaces(); } <file_sep>/src/main/java/com/boundlessgeo/ps/tm/feign/model/GeoServerWorkspaceExtraLevel.java package com.boundlessgeo.ps.tm.feign.model; import java.util.List; public class GeoServerWorkspaceExtraLevel { List<GeoServerWorkspace> workspace; /** * @return the workspace */ public List<GeoServerWorkspace> getWorkspace() { return workspace; } /** * @param workspace the workspace to set */ public void setWorkspace(List<GeoServerWorkspace> workspace) { this.workspace = workspace; } } <file_sep>/src/ui/src/components/EnvironmentList.js var React = require('react/addons'); var Environment = require('./Environment'); var EnvironmentList = React.createClass({ render: function() { var createEnvironment = function(environment) { return ( <Environment data={environment} profile={this} /> ); }; var environmentList = this.props.environments ? this.props.environments : []; if (environmentList && environmentList.length > 0) { return ( <div> <h2>List of current environments</h2> <div> {environmentList.map(createEnvironment, this.props.profile)} </div> </div> ); } else { return ( <div className="environment-list-header">No environments found!!! Please add one.</div> ); } } }); module.exports = EnvironmentList; <file_sep>/src/main/java/com/boundlessgeo/ps/tm/repositories/TokenRepository.java /** * */ package com.boundlessgeo.ps.tm.repositories; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RestResource; import com.boundlessgeo.ps.tm.model.Token; /** * @author ssengupta */ @RestResource public interface TokenRepository extends CrudRepository<Token, Long> { List<Token> findByTokenValue(@Param("tokenValue") String tokenValue); } <file_sep>/README.md # TokenManager [GS]: http://suite.opengeo.org/opengeo-docs/geoserver/index.html [wiki]: https://github.com/boundlessssengupta/TokenManager/wiki [authkey]: http://docs.geoserver.org/2.8.x/en/user/community/authkey/index.html This project consists of the token generation and verification components that can be used in conjunction with [GeoServer][GS] and the [authkey] module (of GeoServer) to provide a token-based access to OGC services hosted by GeoServer. Details about the architecture and each of the components are described in the [wiki][]. <file_sep>/src/ui/src/stores/TokenStore.js 'use strict'; var Reflux = require('reflux'); var HTTP = require('superagent'); var TokenActions = require('../actions/TokenActions'); var Constants = require('../Constants.js'); var BaseTokensUrl = Constants.BaseUrl + '/tokens'; var TokenStore = Reflux.createStore({ listenables: [TokenActions], init: function() { this.listenTo(TokenActions.load, this.fetchAll); }, getInitialState: function() { this.tokenList = []; return this.tokenList; }, fetchAll: function(url) { HTTP.get(url) .end(function(req, res) { this.process(res.text); }.bind(this) ); }, onGenerate: function(token, allTokensUrl) { HTTP.post(BaseTokensUrl) .set('Content-Type', 'application/json') .send(JSON.stringify(token)) .end(function() { this.fetchAll(allTokensUrl); }.bind(this)); }, onRevoke: function(tokenUrl, allTokensUrl) { HTTP.del(tokenUrl) .end(function() { this.fetchAll(allTokensUrl); }.bind(this)); }, onRevokeAll: function(url) { HTTP.put(url) .set('Content-Type', 'text/uri-list') .send(' ') .end(function() { this.fetchAll(url); }.bind(this)); }, process: function(jsonAsText) { this.tokenList = (!JSON.parse(jsonAsText)._embedded) ? [] : JSON.parse(jsonAsText)._embedded.tokens; this.trigger(this.tokenList); } }); module.exports = TokenStore; <file_sep>/src/ui/src/components/WorkspaceList.js var React = require('react/addons'); var Workspace = require('./Workspace'); var WorkspaceList = React.createClass({ render: function() { var createWorkspace = function(workspace) { return ( <Workspace data={workspace} environment={this.props.environment} /> ); }; return ( <div> <div className="workspace-title">Workspaces ({this.props.data.length})</div> <div className="workspaces"> {this.props.data.map(createWorkspace, this)} </div> </div> ); } }); module.exports = WorkspaceList; <file_sep>/src/ui/src/components/ProfileList.js var React = require('react/addons'); var Profile = require('./Profile'); var ProfileList = React.createClass({ render: function() { var createProfile = function(profile) { return ( <Profile data={profile} /> ); }; return ( <div> <h3>Currently there are {this.props.profiles.length} profile(s) available:</h3> <div> {this.props.profiles.map(createProfile)} </div> </div> ); } }); module.exports = ProfileList; <file_sep>/src/main/java/com/boundlessgeo/ps/tm/repositories/EnvironmentRepository.java /** * */ package com.boundlessgeo.ps.tm.repositories; import org.springframework.data.repository.CrudRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import com.boundlessgeo.ps.tm.model.Environment; import com.boundlessgeo.ps.tm.model.EnvironmentWithProfileName; /** * @author ssengupta */ @RepositoryRestResource(excerptProjection = EnvironmentWithProfileName.class) public interface EnvironmentRepository extends CrudRepository<Environment, Long> { } <file_sep>/src/ui/src/components/ProfileAddForm.js var React = require('react/addons'); var ProfileActions = require('../actions/ProfileActions'); var ProfileAddForm = React.createClass({ getInitialState: function() { return { applicationName: '', owner: '' }; }, handleApplicationNameChange: function(e) { this.setState({ applicationName: e.target.value }); }, handleOwnerChange: function(e) { this.setState({ owner: e.target.value }); }, handleSubmit: function(e) { e.preventDefault(); var applicationName = this.state.applicationName; var owner = this.state.owner; if (applicationName && owner) { ProfileActions.add({ applicationName: applicationName, owner: owner }); } }, render: function() { return ( <div> <h3>Create a new application profile</h3> <form className="profileAddForm"> <input type="text" placeholder="Enter application name" value={this.state.applicationName} onChange={this.handleApplicationNameChange} /> <input type="text" placeholder="Enter owner" value={this.state.owner} onChange={this.handleOwnerChange} /> <button onClick={this.handleSubmit}>Add Profile</button> </form> </div> ); } }); module.exports = ProfileAddForm; <file_sep>/src/ui/src/components/TokenList.js var React = require('react/addons'); var Token = require('./Token'); var TokenAddForm = require('./TokenAddForm'); var TokenActions = require('../actions/TokenActions'); var TokenList = React.createClass({ // handleTokenAdd: function() { // var environment = this.props.environment; // var environmentUrl = environment._links.self.href.replace('{?projection}', ''); // var allTokensUrl = environmentUrl + '/tokens'; // // TokenActions.generate({ // tokenValue: '<PASSWORD>', // environment: environmentUrl // }, allTokensUrl); // }, handleTokenRevokeAll: function() { var environment = this.props.environment; var environmentUrl = environment._links.self.href.replace('{?projection}', ''); var allTokensUrl = environmentUrl + '/tokens'; TokenActions.revokeAll(allTokensUrl); }, shouldComponentUpdate: function(nextProps) { var applicationName = nextProps.profile.applicationName; var environmentName = nextProps.environment.name; var tokenList = nextProps.data; if (tokenList) { if (tokenList.length === 0) { return true; } if (tokenList[0] && tokenList[0]._embedded) { var applicationNameFromToken = tokenList[0]._embedded.environment.profile.applicationName; var environmentNameFromToken = tokenList[0]._embedded.environment.name; if (applicationNameFromToken && environmentNameFromToken) { if ((applicationNameFromToken === applicationName) && (environmentNameFromToken === environmentName)) { return true; } } } } return false; }, render: function() { var createToken = function(token) { return ( <Token data={token} /> ); }; if (this.props.data && this.props.data.length > 0) { return ( <div> <div className="token-title"> <span> User Tokens ({this.props.data.length}) </span> <span className="action" onClick={this.handleTokenRevokeAll}> <i className="fa fa-minus"></i> </span> </div> <div> <TokenAddForm environment={this.props.environment} /> </div> <div> {this.props.data.map(createToken, this.props)} </div> </div> ); } else { return ( <div> <div className="token-title"> <span> User Tokens ({this.props.data.length}) </span> </div> <div> <TokenAddForm environment={this.props.environment} /> </div> <div> <div className="token-list-header">No tokens have been generated yet.</div> </div> </div> ); } } }); module.exports = TokenList; <file_sep>/src/main/java/com/boundlessgeo/ps/tm/model/Workspace.java /** * */ package com.boundlessgeo.ps.tm.model; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Transient; /** * @author ssengupta */ @Entity public class Workspace { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String name; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ENVIRONMENT_ID") private Environment environment; @Transient private boolean registered; /** * @return the id */ public long getId() { return id; } /** * @param id * the id to set */ public void setId(long id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the environment */ public Environment getEnvironment() { return environment; } /** * @param environment * the environment to set */ public void setEnvironment(Environment environment) { this.environment = environment; } /** * @return the registered */ public boolean isRegistered() { return registered; } /** * @param registered the registered to set */ public void setRegistered(boolean registered) { this.registered = registered; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Workspace [id="); builder.append(id); builder.append(", name="); builder.append(name); builder.append(", environment="); builder.append(environment); builder.append("]"); return builder.toString(); } /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (environment == null ? 0 : environment.hashCode()); result = prime * result + (int) (id ^ id >>> 32); result = prime * result + (name == null ? 0 : name.hashCode()); return result; } /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Workspace)) { return false; } Workspace other = (Workspace) obj; if (environment == null) { if (other.environment != null) { return false; } } else if (!environment.equals(other.environment)) { return false; } if (id != other.id) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } } <file_sep>/src/ui/src/stores/ActiveProfileStore.js 'use strict'; var Reflux = require('reflux'); var ActiveProfileActions = require('../actions/ActiveProfileActions'); var ActiveProfileStore = Reflux.createStore({ listenables: [ActiveProfileActions], getInitialState: function() { this.activeProfile = ''; return this.activeProfile; }, onToggle: function(profileName) { this.activeProfile = profileName; this.trigger(this.activeProfile); } }); module.exports = ActiveProfileStore; <file_sep>/src/ui/src/components/Workspace.js var React = require('react/addons'); var WorkspaceActions = require('../actions/WorkspaceActions'); var Workspace = React.createClass({ handleWorkspaceAdd: function() { var environmentUrl = this.props.environment._links.self.href.replace('{?projection}', ''); WorkspaceActions.add({ name: this.props.data.name, environment: environmentUrl }, this.props.environment._links.workspaces.href); }, handleWorkspaceDelete: function() { var workspaceUrl = this.props.data._links.self.href; WorkspaceActions.delete(workspaceUrl, this.props.environment._links.workspaces.href); }, render: function() { if (this.props.data.registered) { return ( <div className="workspace"> <span className="workspace-name">{this.props.data.name}</span> <span className="action" onClick={this.handleWorkspaceDelete}> <i className="fa fa-check-square"></i> </span> </div> ); } else { return ( <div className="workspace"> <span className="workspace-name">{this.props.data.name}</span> <span className="action" onClick={this.handleWorkspaceAdd}> <i className="fa fa-check-square-o"></i> </span> </div> ); } } }); module.exports = Workspace; <file_sep>/src/ui/src/Constants.js 'use strict'; var Constants = { BaseUrl: 'http://localhost:8082' }; module.exports = Constants; <file_sep>/src/main/resources/application.properties server.port=8082 spring.datasource.url=jdbc:postgresql://localhost:5432/tokenmanager spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.username=tmuser spring.datasource.password=<PASSWORD> spring.jpa.hibernate.ddl-auto=create-drop security.user.password=<PASSWORD> logging.level.org.springframework.web=DEBUG logging.level.org.springframework.web.servlet=DEBUG<file_sep>/src/main/java/com/boundlessgeo/ps/tm/model/Environment.java /** * */ package com.boundlessgeo.ps.tm.model; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import com.boundlessgeo.ps.tm.TokenGenerator; /** * @author ssengupta */ @Entity public class Environment { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String name; private String appToken; private String geoserverUrl; private String geoserverUser; private String geoserverPassword; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "PROFILE_ID") private Profile profile; @OneToMany(mappedBy = "environment", cascade = CascadeType.ALL) private List<Token> tokens = new ArrayList<Token>(); @OneToMany(mappedBy = "environment", cascade = CascadeType.ALL) private List<Workspace> workspaces = new ArrayList<Workspace>(); /** * @return the id */ public long getId() { return id; } /** * @param id * the id to set */ public void setId(long id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the appToken */ public String getAppToken() { return appToken; } /** * @param appToken * the appToken to set */ public void setAppToken(String appToken) { this.appToken = TokenGenerator.generate(); } /** * @return the profile */ public Profile getProfile() { return profile; } /** * @param profile * the profile to set */ public void setProfile(Profile profile) { this.profile = profile; } /** * @return the geoserverUrl */ public String getGeoserverUrl() { return geoserverUrl; } /** * @param geoserverUrl * the geoserverUrl to set */ public void setGeoserverUrl(String geoserverUrl) { this.geoserverUrl = geoserverUrl; } /** * @return the geoserverUser */ public String getGeoserverUser() { return geoserverUser; } /** * @param geoserverUser the geoserverUser to set */ public void setGeoserverUser(String geoserverUser) { this.geoserverUser = geoserverUser; } /** * @return the geoserverPassword */ public String getGeoserverPassword() { return <PASSWORD>ver<PASSWORD>; } /** * @param geoserverPassword the geoserverPassword to set */ public void setGeoserverPassword(String geoserverPassword) { this.geoserverPassword = geoserverPassword; } /** * @return the tokens */ public List<Token> getTokens() { return tokens; } /** * @param tokens * the tokens to set */ public void setTokens(List<Token> userTokens) { this.tokens = userTokens; } /** * @return the workspaces */ public List<Workspace> getWorkspaces() { return workspaces; } /** * @param workspaces * the workspaces to set */ public void setWorkspaces(List<Workspace> workspaces) { this.workspaces = workspaces; } /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (appToken == null ? 0 : appToken.hashCode()); result = prime * result + (geoserverUrl == null ? 0 : geoserverUrl.hashCode()); result = prime * result + (int) (id ^ id >>> 32); result = prime * result + (name == null ? 0 : name.hashCode()); result = prime * result + (profile == null ? 0 : profile.hashCode()); result = prime * result + (tokens == null ? 0 : tokens.hashCode()); result = prime * result + (workspaces == null ? 0 : workspaces.hashCode()); return result; } /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Environment)) { return false; } Environment other = (Environment) obj; if (appToken == null) { if (other.appToken != null) { return false; } } else if (!appToken.equals(other.appToken)) { return false; } if (geoserverUrl == null) { if (other.geoserverUrl != null) { return false; } } else if (!geoserverUrl.equals(other.geoserverUrl)) { return false; } if (id != other.id) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (profile == null) { if (other.profile != null) { return false; } } else if (!profile.equals(other.profile)) { return false; } if (tokens == null) { if (other.tokens != null) { return false; } } else if (!tokens.equals(other.tokens)) { return false; } if (workspaces == null) { if (other.workspaces != null) { return false; } } else if (!workspaces.equals(other.workspaces)) { return false; } return true; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { final int maxLen = 2; StringBuilder builder = new StringBuilder(); builder.append("Environment [id="); builder.append(id); builder.append(", name="); builder.append(name); builder.append(", appToken="); builder.append(appToken); builder.append(", geoserverUrl="); builder.append(geoserverUrl); builder.append(", profile="); builder.append(profile); builder.append(", tokens="); builder.append(tokens != null ? tokens.subList(0, Math.min(tokens.size(), maxLen)) : null); builder.append(", workspaces="); builder.append(workspaces != null ? workspaces.subList(0, Math.min(workspaces.size(), maxLen)) : null); builder.append("]"); return builder.toString(); } } <file_sep>/src/ui/src/components/TokenManagerApp.js 'use strict'; var React = require('react/addons'); var ReactTransitionGroup = React.addons.TransitionGroup; var Reflux = require('reflux'); var ProfileActions = require('../actions/ProfileActions'); var ProfileStore = require('../stores/ProfileStore'); var ProfileAddForm = require('./ProfileAddForm'); var ProfileList = require('./ProfileList'); // CSS require('normalize.css'); require('../styles/main.css'); var TokenManagerApp = React.createClass({ mixins: [Reflux.connect(ProfileStore, 'profileList')], componentDidMount: function() { ProfileActions.load(); }, render: function() { return ( <div className="main"> <ReactTransitionGroup transitionName="fade"> <ProfileAddForm /> <ProfileList profiles={this.state.profileList} /> </ReactTransitionGroup> </div> ); } }); module.exports = TokenManagerApp;
2e41b4ddba18a20cba49336c0ed810d85ffbcd39
[ "JavaScript", "Java", "Markdown", "INI" ]
21
JavaScript
ssengupta-pl/TokenManager
735bb5e0658844cc3b7e51af3022757911652194
77cd8d2edf791371b48df41a803b4980e88c3bbd
refs/heads/master
<file_sep>package com.skolarajak.servisi; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import com.skolarajak.model.Vozilo; import com.skolarajak.utils.Konstante; public class AdministriranjeVozila { private static final boolean STATUS = true; private static final double PRAG_RASPODELE_AKTIVNIH_VOZILA = (double) 0.4; // kontrolisemo da li hocemo da imamo private static final int SLOVO_A= 65; // vise aktivnih i neaktivnih private static final int SLOVO_Z= 90; public List<Vozilo> generisi() { List<Vozilo> vozila = new ArrayList<Vozilo>(); for (int i = 0; i < Konstante.UKUPAN_BROJ_VOZILA_U_SISTEMU; i++) { int godinaProizvodnje = dodeliGodinuProizvodnje(); Vozilo vozilo = new Vozilo(godinaProizvodnje); // i promenjeno u godinaProizvodnje, da bi konstante iz // metode radile vozilo.setAktivno(Math.random() > PRAG_RASPODELE_AKTIVNIH_VOZILA); // logicki izraz, ako je veca od 0.5 bice // true, ako je manje jednako od 0.5 // false vozilo.setRegistarskiBroj("Reg-" + i + slucajnoSlovo() + slucajnoSlovo()); vozila.add(vozilo); } return vozila; } public List<Vozilo> euro3Vozila(List<Vozilo> vozila) { // pocetna lista sadrzi sva vozila /* * List<Vozilo> euro3Vozila = new ArrayList<Vozilo>(); // filtrirana privremena * lista rezultata samo euro 3 vozila * for(Vozilo vozilo : vozila) { // proveri elemente u listi * if(vozilo.getGodisteProizvodnje() >= Konstante.EURO_3_GODISTE) { // ako odgovara uslovu * euro3Vozila.add(vozilo); dodaje se u privremenu listu euro 3 vozila * // * } * } */ // Java 8 lambda izraz List<Vozilo> euro3Vozila = vozila.stream() // stream sadrzi listu vozila .filter(v -> v.getGodisteProizvodnje() >= 2000) // filterisi v element liste po kriterijumu za svaki // element postoji v kod koga sledi da je godiste vece // od 2000, ekvivalent if funkciji .collect(Collectors.toList()); // rezultat vrati u listu kolektor u list return euro3Vozila; // vrati euro 3 vozilo godiste >= 2000 } //????? public List<Vozilo> aktivnaVozila(List<Vozilo> vozila){ return null; } private int dodeliGodinuProizvodnje() { // int godina =(int) (Math.random()*(Konstante.MAX_VOZILO_GODISTE - Konstante.MIN_VOZILO_GODISTE + 1) // + Konstante.MIN_VOZILO_GODISTE); //vraca slucajnu godinu izmadju 1960-2000 // za godine smo koristili matematicku funkciju za interval izmedju odredjenih // godina min i max int godina = slucajanBrojUIntervalu(Konstante.MIN_VOZILO_GODISTE, Konstante.MAX_VOZILO_GODISTE); return godina; } private String slucajnoSlovo() { char c = (char) slucajanBrojUIntervalu(SLOVO_A, SLOVO_Z); // interval izmedju 60 i 90 ASCII kod slova return String.valueOf(c); } private int slucajanBrojUIntervalu(int min, int max) { // matematicka funkciju koja generise slucajan broj u // intervalu return (int) (Math.random() * (max - min) + min); } }
6ec13677fa4a381a480edb2f1adddd21fa543905
[ "Java" ]
1
Java
nadat11/skolarajakucionica7
385717d33ad868884d96636c292c93b99644ff39
f47e837577869156c5be087421f623449499f844
refs/heads/master
<repo_name>LockJay42/DungeonGameJam<file_sep>/Gamejam 2 - April 2016/Assets/Scripts/BaseCollisionTrap.cs using UnityEngine; using System.Collections; public class BaseCollisionTrap : MonoBehaviour { public enum TrapKey { Z,X,C,V }; public GameObject Button; public TrapKey trapKey; private KeyCode activateKey; private enum ActiveState { NotActive, Activating, Active, OnCooldown, Dead }; private ActiveState activeState; public ParticleSystem[] ActiveTrapParticleSystem; private KeyCode GetKeyCode(TrapKey key) { if (key == TrapKey.Z) { return KeyCode.Z; } if (key == TrapKey.X) { return KeyCode.X; } if (key == TrapKey.C) { return KeyCode.C; } if (key == TrapKey.V) { return KeyCode.V; } return KeyCode.None; } [Range(0, 1)] public float delay; // Use this for initialization [Range(0, 20)] public float cooldown; void Start () { activateKey = GetKeyCode(trapKey); activeState = ActiveState.NotActive; } void OnCollisionEnter(Collision col) { if (col.gameObject.CompareTag("Player")) { Debug.Log("notBroken"); if (activeState == ActiveState.Active) { Debug.Log("active"); SendMessage("OnPlayerCollision"); //todo add points to dungeon master } } } IEnumerator DeactivateTrap() { activeState = ActiveState.OnCooldown; foreach (var particleSystem in ActiveTrapParticleSystem) { particleSystem.Stop(); } yield return new WaitForSeconds(cooldown); activeState = ActiveState.NotActive; } IEnumerator DoActivateCoroutine() { activeState = ActiveState.Activating; yield return new WaitForSeconds(delay); activeState = ActiveState.Active; foreach(var particleSystem in ActiveTrapParticleSystem) { particleSystem.Play(); } SendMessage("OnActivate"); } // Update is called once per frame void Update () { if(activeState == ActiveState.NotActive && Input.GetKey(activateKey)) { StartCoroutine(DoActivateCoroutine()); Destroy(Button); } } } <file_sep>/Gamejam 2 - April 2016/Assets/Scripts/LevelManager.cs using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class LevelManager{ public static void LoadPlayableLevelRandomly() { SceneManager.LoadScene(Random.Range(1,6)); } public static void LoadNextLevel() { if (SceneManager.GetActiveScene().name == "Level1") SceneManager.LoadScene("Level2"); if (SceneManager.GetActiveScene().name == "Level2") SceneManager.LoadScene("Level3"); if (SceneManager.GetActiveScene().name == "Level3") SceneManager.LoadScene("Level4"); if (SceneManager.GetActiveScene().name == "Level4") SceneManager.LoadScene("Level5"); if (SceneManager.GetActiveScene().name == "Level5") SceneManager.LoadScene("Level6"); //instead of this last one we might want to make a 'win' scene if (SceneManager.GetActiveScene().name == "Level6") SceneManager.LoadScene("Level1"); } } <file_sep>/Gamejam 2 - April 2016/Assets/CollisionForwarder.cs using UnityEngine; using System.Collections; public class CollisionForwarder : MonoBehaviour { void OnCollisionEnter(Collision col) { transform.parent.gameObject.SendMessage("OnCollisionEnter", col); } } <file_sep>/Gamejam 2 - April 2016/Assets/Scripts/ScoreHandler.cs using UnityEngine; using System.Collections; using UnityEngine.UI; public class ScoreHandler : MonoBehaviour { public Text playerOneScore; //public Text playerTwoScore; //public Text playerThreeScore; public Text dungeonMasterScore; public PlayerScript playerOne; //public PlayerScript playerTwo; //public PlayerScript playerThree; public DungeonMaster dungeonMaster; // Use this for initialization void Start() { playerOneScore.text = "0"; //playerTwoScore.text = "0"; //playerThreeScore.text = "0"; dungeonMasterScore.text = "0"; } // Update is called once per frame void Update() { playerOneScore.text = playerOne.score.ToString(); //playerTwoScore.text = playerTwo.score.ToString(); //playerThreeScore.text = playerThree.score.ToString(); dungeonMasterScore.text = dungeonMaster.score.ToString(); } } <file_sep>/Gamejam 2 - April 2016/Assets/Scripts/SpikeTrap.cs using UnityEngine; using System.Collections; [RequireComponent(typeof(BaseCollisionTrap))] public class SpikeTrap : MonoBehaviour { // Use this for initialization //[Range(0, 10)] private float maxDuration = 2; private float duration; private Animator[] animators; bool isActive = false; void Start () { animators = transform.GetComponentsInChildren<Animator>(); GetComponentInChildren<Collider>().enabled = true; } void OnActivate() { foreach (var anim in animators) { anim.SetBool("AnimateSpikes", true); } duration = maxDuration; isActive = true; //run animation GetComponentInChildren<BoxCollider>().center = new Vector3(0,1,0); Debug.Log("colOn"); } void OnPlayerCollision() { GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerScript>().lives -= 1; LevelManager.LoadPlayableLevelRandomly(); } // Update is called once per frame void Update () { if (isActive) { duration -= Time.deltaTime; if(duration <= 0) { foreach (var anim in animators) { anim.SetBool("AnimateSpikes", false); } SendMessage("DeactivateTrap"); //GetComponent<Collider>().enabled = false; isActive = false; } } } }<file_sep>/README.md # DungeonGameJam Dungeon Master Play as a Dungeon Master or Player. The Player must run through the dungeon and survive the traps, which the Dungeon Master sets off to kill the player. <file_sep>/Gamejam 2 - April 2016/Assets/Scripts/PlayerScript.cs using UnityEngine; using System.Collections; public class PlayerScript : MonoBehaviour { //movement variables public Vector3 movement = new Vector3(0, 0, 0); public float movementSpeed = 12f; public float jumpHeight = 10f; public float gravityMultiplier = 2; public float movementDistance = 10; public bool grounded = true; public Rigidbody rb; public int lives; public int score; // Use this for initialization void Start() { tag = "Player"; rb = GetComponent<Rigidbody>(); } // FixedUpdate is called once per frame void FixedUpdate() { //reset velocity and movement vector rb.velocity = new Vector3(0, rb.velocity.y, 0); movement.Set(0, 0, 0); //get analog stick input float x = Input.GetAxis("Horizontal"); //if inputting A then jump if (Input.GetButton("Button A") && grounded) { rb.velocity += new Vector3(rb.velocity.x, jumpHeight, rb.velocity.z); grounded = false; } //if not on the ground if (!grounded) { //increase gravity if falling Vector3 extraGravityForce = (Physics.gravity * gravityMultiplier) - Physics.gravity; rb.AddForce(extraGravityForce); } //set movement variable to input variables movement.Set(x, 0, 0); //calculate final movement vector and apply force to player movement = movement.normalized * movementSpeed * Time.fixedDeltaTime * 100; rb.AddForce(movement * 10); } void OnCollisionEnter() { grounded = true; } void OnCollisionExit() { //Increase gravity when falling grounded = false; Vector3 extraGravityForce = (Physics.gravity * gravityMultiplier) - Physics.gravity; rb.AddForce(extraGravityForce); } } <file_sep>/Gamejam 2 - April 2016/Assets/Scripts/DungeonMaster.cs using UnityEngine; using System.Collections; public class DungeonMaster : MonoBehaviour { //public TrapPlaceholder one; //public TrapPlaceholder two; //public TrapPlaceholder three; //public TrapPlaceholder four; //public TrapPlaceholder five; //Transform cameraMaster; // //public Transform playerOne; //public Transform playerTwo; //public Transform playerThree; public int score; //float pOneX; //float pOneY; // //float pTwoX; //float pTwoY; // //float pThreeX; //float pThreeY; // Use this for initialization void Start() { //cameraMaster = GetComponentInParent<Transform>(); } // Update is called once per frame void Update() { //pOneX = playerOne.position.x; //pOneY = playerOne.position.y; // //pTwoX = playerTwo.position.x; //pTwoY = playerTwo.position.y; // //pThreeX = playerThree.position.x; //pThreeY = playerThree.position.y; } void AddPoint() { //placeholder score score += 10; } //void UpdateCamera() //{ // //find average x value // float xAv = (pOneX + pTwoX + pThreeX) / 3; // // //find average y value // float yAv = (pOneY + pTwoY + pThreeY) / 3; // // Vector3 newPos = new Vector3(xAv, yAv, cameraMaster.position.z); // cameraMaster.position = newPos; // // // //change the orthographic size value // // //find highest/lowest x value // // float hiX = 0; // float hiY = 0; // float loX = 0; // float loY = 0; // // if (pOneX > pTwoX && pOneX > pThreeX) // hiX = pOneX; // else if (pTwoX > pOneX && pTwoX > pThreeX) // hiX = pTwoX; // else if (pThreeX > pOneX && pThreeX > pTwoX) // hiX = pThreeX; // // if (pOneX < pTwoX && pOneX < pThreeX) // loX = pOneX; // else if (pTwoX < pOneX && pTwoX < pThreeX) // loX = pTwoX; // else if (pThreeX < pOneX && pThreeX < pTwoX) // loX = pThreeX; // // //find highest y value // // if (pOneY > pTwoY && pOneY > pThreeY) // hiY = pOneY; // else if (pTwoY > pOneY && pTwoY > pThreeY) // hiY = pTwoY; // else if (pThreeY > pOneY && pThreeY > pTwoY) // hiY = pThreeY; // // if (pOneY < pTwoY && pOneY < pThreeY) // loY = pOneY; // else if (pTwoY < pOneY && pTwoY < pThreeY) // loY = pTwoY; // else if (pThreeY < pOneY && pThreeY < pTwoY) // loY = pThreeY; // // GetComponent<Camera>().orthographicSize = (hiX - loX / hiY - loY) + 5; //} }<file_sep>/Gamejam 2 - April 2016/Assets/Scripts/killScript.cs using UnityEngine; using System.Collections; public class killScript : MonoBehaviour { // Use this for initialization void Start () { } void OnCollisionEnter(Collision col) { if (col.gameObject.CompareTag("Player")) { GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerScript>().lives -= 1; LevelManager.LoadPlayableLevelRandomly(); } } // Update is called once per frame void Update () { } } <file_sep>/Gamejam 2 - April 2016/Assets/Scripts/TrapDoor.cs using UnityEngine; using System.Collections; [RequireComponent(typeof(BaseCollisionTrap))] public class TrapDoor : MonoBehaviour { // Use this for initialization [Range(0, 30)] public float maxDuration; float duration; bool isActive; private Animator[] animators; void Start() { animators = transform.GetComponentsInChildren<Animator>(); GetComponentInChildren<Collider>().enabled = true; } void OnActivate() { GetComponentInChildren<Collider>().enabled = false; Debug.Log ("working"); foreach (var anim in animators) { anim.SetBool("TrapActive", true); } duration = maxDuration; //run animation } void OnPlayerCollision() { //todo Kill player } // Update is called once per frame void Update() { if(isActive) { duration -= Time.deltaTime; if(duration <= 0) { //run close animation SendMessage("DeactivateTrap"); isActive = false; } } } } <file_sep>/Gamejam 2 - April 2016/Assets/Scripts/ExplosiveTrap.cs using UnityEngine; using System.Collections; [RequireComponent(typeof(BaseCollisionTrap))] public class ExplosiveTrap : MonoBehaviour { // Use this for initialization [Range(0, 10)] public float maxDuration; float duration; bool active; void Start() { active = false; GetComponent<Collider>().enabled = false; } void OnActivate() { duration = maxDuration; active = true; GetComponent<Collider>().enabled = true; } // Update is called once per frame void Update() { if (active == true) { duration -= Time.deltaTime; if (duration <= 0) { SendMessage("DeactivateTrap"); active = false; } } } void OnPlayerCollision() { GameObject.FindGameObjectWithTag("player").GetComponent<PlayerScript>().lives -= 1; LevelManager.LoadPlayableLevelRandomly(); } }<file_sep>/Gamejam 2 - April 2016/Assets/Scripts/Chandelier.cs using UnityEngine; using System.Collections; [RequireComponent(typeof(BaseCollisionTrap))] public class Chandelier : MonoBehaviour { // Use this for initialization bool active = false; [Range(0, 20)] public float timeToMaxAcceleration; void Start() { GetComponent<Rigidbody>().useGravity = false; } void OnActivate() { active = true; } void OnPlayerCollision() { GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerScript>().lives -= 1; LevelManager.LoadPlayableLevelRandomly(); } // Update is called once per frame void Update() { if (active) { GetComponent<Rigidbody>().useGravity = true; } } }<file_sep>/Gamejam 2 - April 2016/Assets/Scripts/FlameTrap.cs using UnityEngine; using System.Collections; using DG.Tweening; [RequireComponent(typeof(BaseCollisionTrap))] public class FlameTrap : MonoBehaviour { // Use this for initialization [Range(0, 10)] public float maxHeight; [Range(0, 5)] public float timeToReachMaxHeight; [Range(0, 10)] public float maxDuration; float duration; bool active = false; private float height; private Vector3 initialSize; private BoxCollider boxCollider; void Start() { GetComponent<Collider>().enabled = false; } void SetSize(Vector3 size) { boxCollider.size = size; boxCollider.center = ((size - initialSize)/2); } Vector3 GetSize() { return boxCollider.size; } void OnActivate() { duration = maxDuration; boxCollider = GetComponent<BoxCollider>(); initialSize = boxCollider.size; GetComponent<Collider>().enabled = true; active = true; var newSize = boxCollider.size; newSize.z = maxHeight; DOTween.To(GetSize, SetSize, newSize, timeToReachMaxHeight); //transform.DOScaleY(2, 1).SetLoops(1, LoopType.Yoyo).SetRelative(); duration = maxDuration; } void OnPlayerCollision() { GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerScript>().lives -= 1; LevelManager.LoadPlayableLevelRandomly(); } // Update is called once per frame void Update() { if (active == true) { duration -= Time.deltaTime; if (duration <= 0) { SendMessage("DeactivateTrap"); active = false; GetComponent<Collider>().enabled = false; boxCollider.size = initialSize; } } } } <file_sep>/Gamejam 2 - April 2016/Assets/Scripts/LoadRandomLevel.cs using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class LoadRandomLevel : MonoBehaviour { // Use this for initialization void Start () { } public void loadRandomLevel() { LevelManager.LoadPlayableLevelRandomly(); } // Update is called once per frame void Update () { } }
161fb3a026c9bbe569ada5b8879b1e531bf8ab35
[ "Markdown", "C#" ]
14
C#
LockJay42/DungeonGameJam
8e99fb18ce9b1dd4582cf18a582bd715c8768828
b7308035a3c82dc9efe2cf7a6f8e11a2ebdb5e94
refs/heads/master
<file_sep>package cn.edu.sql.demo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class Demo02 { public static void main(String[] args) { try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/aa","root","man69"); PreparedStatement statement = connection.prepareStatement("select * from xxx"); // PreparedStatement statement = connection.prepareStatement("insert into xxx(id,name)values(1212,'asd');" ); ResultSet res = statement.executeQuery(); while (res.next()){ System.out.print(res.getInt("id")+" "); System.out.println(res.getString("name")); } } catch (Exception e) { System.out.println("errro"); } } } <file_sep>package cn.edu.gof.pattern.Builder; public class AngelBuilder { } <file_sep>package movies.util; //常量类 public class Constant { //管理员权限 public static final int VISITOR_ROLE = 0; public static final int ONLY_VIEW_ROLE = 1; public static final int MOVIE_ADMIN_ROLE = 2; public static final int SHOW_ADMIN_ROLE = 3; public static final int ORDER_ADMIN_ROLE = 4; public static final int FULL_ADMIN_ROLE = 50; public static final int ROOT_ADMIN_ROLE = 99; //放映厅12*9 public static final int HALL_ROW_NUM = 12; public static final int HALL_COLUMN_NUM = 9; //标签名称对应的数据库名称 //电影,场次,订单,用户,票,权限, public static String[] movieLables={"电影编号","电影名称","电影类别","导演","来源国家","出版公司","上映时间"}; public static String[] movieDBFields={"mid","name","type","director","source","publisher","release_Date"}; public static String[] showLables={"场次编号","电影编号","放映厅","放映时间","票价(¥)"}; public static String[] showDBFields={"id","mid","hall","time","price"}; public static String[] orderLables={"订单编号","名字","电话","订单数据"}; public static String[] orderDBFields={"id","name","phone","data"}; public static String[] staffLables={"管理员编号","用户名","用户密码","权限"}; public static String[] staffDBFields={"uid","username","password","role"}; public static String[] ticketLables={"编号","电影名称","时间","票价","座位"}; public static String[] userRoleDescs={"无管理权限","只能管理电影","只能管理场次","只能管理订单","完全管理权限","根管理权限"}; public static int[] userRoleIds={ONLY_VIEW_ROLE ,MOVIE_ADMIN_ROLE,SHOW_ADMIN_ROLE,ORDER_ADMIN_ROLE,FULL_ADMIN_ROLE,ROOT_ADMIN_ROLE}; //时间小时,分钟 public static String[] timeHours={"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"}; public static String[] timeMinutes={"00","05","10","15","20","25","30","35","40","45","50","55"}; } <file_sep>package swinglearn; import javax.swing.*; public class DayforImage { public static void main(String[] args) { new JFUI(); JFrame jf = new JFrame("image插入"); jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jf.setSize(500,500); // 第 1 个 JPanel, 使用默认的浮动布局 JPanel panel01 = new JPanel(); // JFormattedTextField jText = new JFormattedTextField((Document) JIconsmall.getBigImage(15)); // panel01.add(jText); jf.add(panel01); jf.setContentPane(panel01); // jf.pack(); jf.setLocationRelativeTo(null); jf.setVisible(true); } } <file_sep>package movies.util; import movies.take.Movie; import movies.take.Order; import movies.take.Show; import movies.take.Staff; //查询命令,返回SQL代码 public class QueryCreate { //查询命令,获得表格所有记录 public static String queryForResults(String tableName) { String str = " SELECT * from " + tableName; return str; } //用于生成基于整数项的查询命令 public static String queryForResults(String tableName, String fieldName, int fieldVal) { String str = " SELECT * from " + tableName + " WHERE " + fieldName + " = " + fieldVal; return str; } //小数项的查询命令 public static String queryForResults(String tableName, String fieldName, double fieldVal) { String str = " SELECT * from " + tableName + " WHERE " + fieldName + " = " + fieldVal; return str; } //String 的查询命令 用like的方法 public static String queryForResults(String tableName, String fieldName, String fieldVal) { String str = " SELECT * from " + tableName + " WHERE " + fieldName + " LIKE '% " + fieldVal + " %' " ; return str; } //========================= //生成用户身份 public static String queryByCredential(String username, String password) { String str = " SELECT * from staff WHERE username = ' " + username + " 'AND password = ' " + password + " ' " ; return str; } //========================== //更新电影记录命令 public static String queryForUpdate(Movie movie) { String query = " UPDATE movies SET name = ' " + movie.getName() + " ', type = ' " + movie.getType() + " ', director = ' " + movie.getDirector() + " ', source =' " + movie.getSource() + " ', publisher = ' " + movie.getPublisher() + " ', release_date = ' " + movie.getReleaseDate() + " ', WHERE mid = " + movie.getMid();//数字不用加'' return query; } //更新订单表格记录命令 public static String queryForUpdate(Show show) { String query = " UPDATE shows SET mid = " + show.getMid() + " , hall= " + show.getHall() + " , time = ' " + show.getTime() + " ' " + " , price = " + show.getPrice(); if (show.getSeatsUsed() != null) { query += " , seats_used = ' " + show.getSeatsUsed() + " ' " ; } query += " WHERE id= " + show.getId(); return query; } public static String queryForUpdate(Order order) { String query = " UPDATE orders SET name = ' " + order.getName() + " ', phone= ' " + order.getPhone()+ " ' " ; if (order.getData() != null) { query += " , data=' " + order.getData()+ " ' " ; } query += " WHERE id = " + order.getId(); return query; } //管理员权限 public static String queryForUpdate(Staff user) { String query = " UPDATE staff SET username = ' " + user.getUsername() + " ', password = " + <PASSWORD>() + " ', role = " + user.getRole() + " WHERE uid = " + user.getUid(); return query; } //======================= //更新密码 public static String queryForUpdatePass(int userId, String password) { String query = " UPDATE staff SET password = ' " + password + " 'WHERE uid = " + userId; return query; } //======================= //添加命令 public static String queryForAdd(Movie movie){ String query = " INSERT INTO movies " + " (name, type, director, source,publisher,release_date) " + " VALUES (' " + movie.getName()+ " ',' " + movie.getType()+ " ',' " + movie.getDirector()+ " ',' " + movie.getSource()+ " ',' " + movie.getPublisher()+ " ',' " + movie.getReleaseDate()+ " ') " ; return query; } public static String queryForAdd(Show show){ String query = " INSERT INTO shows " + " (mid, hall, time, price,seats_used) " + " VALUES ( " + show.getMid()+ " , " + show.getHall()+ " ,' " + show.getTime()+ " ', " + show.getPrice()+ " ,' " + show.getSeatsUsed()+ " ') " ; return query; } public static String queryForAdd(Order order){ String query = " INSERT INTO orders " + " (name, phone,data) " + " VALUES (' " + order.getName()+ " ',' " + order.getPhone()+ " ',' " + order.getData()+ " ') " ; return query; } public static String queryForAdd(Staff user){ String query = " INSERT INTO staff " + " (username, password, role) " + " VALUES (' " + user.getUsername()+ " ',' " + user.getPassword()+ " ', " + user.getRole()+ " ) " ;//int return query; } //===================== //删除 public static String queryForDelete(String tableName,String idField,int id){ String query= " delete from " +tableName+ " WHERE " +idField+ " = " +id; return query; } }<file_sep>package cn.edu.sql.demo; import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper; import javax.swing.*; import java.awt.*; public class MyFrame1 extends JFrame { public static void main(String[] args) throws Exception { EventQueue.invokeLater(new Runnable() { public void run() { try { // 设置窗口边框样式 BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.translucencyAppleLike; org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF(); UIManager.put("RootPane.setupButtonVisible", false); MyFrame1 myFrame1 = new MyFrame1(); myFrame1.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public MyFrame1(){ setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(500,500); } } <file_sep>package swinglearn; import javax.swing.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class DayforMouse{ public static int width; public static int height; public static void initUI(JFrame jf , JButton jButton,int width,int height) { jButton.addMouseListener(new MouseListener() { private int width=DayforMouse.width; @Override public void mouseClicked(MouseEvent e) {//按下并释放 } @Override public void mousePressed(MouseEvent e) {//按下 jf.setBounds(0,0,100,100); // JPanel jPanel02 =new JPanel(); // jPanel02.setBackground(new Color(220,200,120)); // jf.add(jPanel02); try { for (int i=0;i<600;i+=2){ jf.setSize(width+i,height+i*2); Thread.sleep(1); } } catch (InterruptedException e1) { e1.printStackTrace(); } } @Override public void mouseReleased(MouseEvent e) {//释放 } @Override public void mouseEntered(MouseEvent e) {//进入 } @Override public void mouseExited(MouseEvent e) {//离开 } }); } public DayforMouse(JFrame jFrame,JButton jButton){ new Thread(new Runnable() { @Override public void run() { width =jFrame.getWidth(); height =jFrame.getHeight(); initUI(jFrame,jButton,width,height); } }).start(); } } <file_sep>package swinglearn; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class DayforPopupMenu { public static void main(String[] args) { JFrame jf = new JFrame("测试窗口"); jf.setSize(300, 300); jf.setLocationRelativeTo(null); jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); JPanel panel = new JPanel(); // 直接在内容面板上添加鼠标监听器 panel.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { // 鼠标点击(按下并抬起) } @Override public void mousePressed(MouseEvent e) { // 鼠标按下 } @Override public void mouseReleased(MouseEvent e) { // 鼠标释放 // 如果是鼠标右键,则显示弹出菜单 if (e.isMetaDown()) { showPopupMenu(e.getComponent(), e.getX(), e.getY()); } } @Override public void mouseEntered(MouseEvent e) { // 鼠标进入组件区域 } @Override public void mouseExited(MouseEvent e) { // 鼠标离开组件区域 } }); jf.setContentPane(panel); jf.setVisible(true); } public static void showPopupMenu(Component invoker, int x, int y) { // 创建 弹出菜单 对象 JPopupMenu popupMenu = new JPopupMenu(); // 创建 一级菜单 JMenuItem copyMenuItem = new JMenuItem("复制"); JMenuItem pasteMenuItem = new JMenuItem("粘贴"); JMenu editMenu = new JMenu("编辑"); // 需要 添加 二级子菜单 的 菜单,使用 JMenu JMenuItem fileMenu = new JMenuItem("文件"); // 创建 二级菜单 JMenuItem findMenuItem = new JMenuItem("查找"); JMenuItem replaceMenuItem = new JMenuItem("截图"); // 添加 二级菜单 到 "编辑"一级菜单 editMenu.add(findMenuItem); editMenu.add(replaceMenuItem); // 添加 一级菜单 到 弹出菜单 popupMenu.add(copyMenuItem); popupMenu.add(pasteMenuItem); popupMenu.addSeparator(); // 添加一条分隔符 popupMenu.add(editMenu); popupMenu.add(fileMenu); // 添加菜单项的点击监听器 copyMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("复制 被点击"); } }); findMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("查找 被点击"); } }); replaceMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { new DayforImageCut(); } catch (Exception e1) { e1.printStackTrace(); } } }); // ...... // 在指定位置显示弹出菜单 popupMenu.show(invoker, x, y); } } <file_sep>package movies.ui; import movies.database.Moviedao; import movies.database.ShowDao; import movies.database.StaffDao; import movies.take.Movie; import movies.take.Show; import movies.take.Staff; import movies.util.CheckHandler; import movies.util.Constant; import movies.util.DateHandler; import org.jdatepicker.impl.JDatePickerImpl; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; public class RecordUpdate { private String recordType; private JLabel idLabel; private JTextField idField; private JPanel contentPane; private JPanel queryPane; private JComboBox<String> roleBox; private JComboBox<String> hourBox; private JComboBox<String> minBox; private JComboBox<String> movieBox; private JDatePickerImpl datePicker; private JPanel combinedPane; private JPanel recordPane; private JPanel buttonBar; private JButton btnSave; private List<JTextField> textFields; private List <Integer> moviesIds; public JFrame mainFrame; public RecordUpdate(Container mainContent, String type, JFrame jFrame){ textFields = new ArrayList<JTextField>(); recordType =type; moviesIds =new ArrayList<Integer>(); mainFrame = jFrame; initUI(mainContent); } public void initUI(Container mainContent){ mainContent.removeAll(); contentPane = new JPanel(new BorderLayout()); queryPane = new JPanel(); idLabel = new JLabel(); idField =new JTextField(); buttonBar =new JPanel(); btnSave = new JButton(); queryPane.setLayout(new GridLayout(1,3)); idLabel = new JLabel(recordType+"编号:"); idLabel.setHorizontalAlignment(SwingConstants.RIGHT); idField = new JTextField(); JButton queryBtn = new JButton("查询"); queryBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnQueryActionPerformed(e); } }); queryPane.add(idLabel); queryPane.add(idField); queryPane.add(queryBtn); String[] currLabels = new String[0]; //添加查询结果展示区 if ("电影".equals(recordType)){ currLabels = Constant.movieLables; recordPane.setLayout(new GridLayout(7,2,6,6)); contentPane.setBorder(new EmptyBorder(50,150,100,300)); } if ("场次".equals(recordType)){ currLabels = Constant.showLables; recordPane.setLayout(new GridLayout(6,2,6,6)); contentPane.setBorder(new EmptyBorder(100,150,150,250)); } if ("用户".equals(recordType)){ currLabels = Constant.staffLables; recordPane.setLayout(new GridLayout(4,2,6,6)); contentPane.setBorder(new EmptyBorder(100,150,200,300)); } for (int i = 0; i<currLabels.length;i++){ JLabel entryLabel = new JLabel(); entryLabel.setText(currLabels[i]+":"); entryLabel.setHorizontalAlignment(SwingConstants.RIGHT); JTextField entryField = new JTextField(); if (i==0){ entryField.setEnabled(false); entryField.setBackground(new Color(230,230,230)); }//i==0 recordPane.add(entryLabel); if ("场次".equals(recordType) && "电影名称".equals(currLabels[i])) { List<Movie> movies = Moviedao.getMovies("", ""); String[] movieNames = new String[movies.size()]; for (int m = 0; m < movies.size(); m++) { movieNames[m] = movies.get(m).getName(); moviesIds.add(movies.get(m).getMid()); }//for movieBox = new JComboBox<String>(movieNames); recordPane.add(movieBox); } else if ("电影".equals(recordType) && "上映时间".equals(currLabels[i])) { combinedPane = new JPanel(); datePicker = DateHandler.getDatePicker(); datePicker.setPreferredSize(new Dimension(160, 30)); combinedPane.add(datePicker); recordPane.add(combinedPane); } else if ("场次".equals(recordType) && "放映时间".equals(currLabels[i])) { datePicker = DateHandler.getDatePicker(); datePicker.setPreferredSize(new Dimension(160, 30)); // datePicker.setBorder(new EmptyBorder(10, 0, 0, 20)); recordPane.add(datePicker); combinedPane = new JPanel();//重新赋值面板 // combinedPane.add(datePicker); hourBox = new JComboBox<>(Constant.timeHours); JLabel sepLabel1 = new JLabel("时"); JLabel sepLabel2 = new JLabel("分"); minBox = new JComboBox<>(Constant.timeMinutes); combinedPane.add(hourBox); combinedPane.add(sepLabel1); combinedPane.add(minBox); combinedPane.add(sepLabel2); JLabel timeLabel = new JLabel(""); recordPane.add(timeLabel); timeLabel.setHorizontalAlignment(SwingConstants.RIGHT); recordPane.add(combinedPane); } else if ("用户".equals(recordType) && "权限".equals(currLabels[i])) { roleBox = new JComboBox<>(Constant.userRoleDescs); recordPane.add(roleBox); } else { recordPane.add(entryField); textFields.add(entryField); } }//循环 contentPane.add(queryPane,BorderLayout.NORTH); contentPane.add(recordPane ,BorderLayout.CENTER); buttonBar.setBorder(new EmptyBorder(15,5,5,5)); buttonBar.setLayout(new GridBagLayout()); ((GridBagLayout)buttonBar.getLayout()).columnWeights = new double[]{1.0,0.0,0.0}; ((GridBagLayout)buttonBar.getLayout()).columnWidths = new int[]{0,80,75}; btnSave.setText("保存修改"); btnSave.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnSaveActionPerformed(e); } }); buttonBar.add(btnSave,new GridBagConstraints(1,0,1,1,0.0,0.0,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(0,0,0,5),0,0)); contentPane.add(buttonBar,BorderLayout.SOUTH); contentPane.setVisible(true); mainContent.add(contentPane,BorderLayout.CENTER); }//UI private void btnSaveActionPerformed(ActionEvent e) { if (textFields.get(0).getText().length()==0){ return; }//判断 int itemId = Integer.parseInt(textFields.get(0).getText()); boolean success = false; if ("电影".equals(recordType)){ Movie movie = new Movie(); movie.setMid(itemId); movie.setName(textFields.get(1).getText()); movie.setType(textFields.get(2).getText()); movie.setDirector(textFields.get(3).getText()); movie.setSource(textFields.get(4).getText()); movie.setPublisher(textFields.get(5).getText()); String totalContent = textFields.get(1).getText()+textFields.get(2).getText() +textFields.get(3).getText()+textFields.get(4).getText(); if (CheckHandler.containsDigit(totalContent)){ JOptionPane.showMessageDialog(this.contentPane,"你的输入包含数字,输入非法"); return; }//判断输入非法 movie.setReleaseDate(datePicker.getJFormattedTextField().getText()); success=Moviedao.updateMovie(movie); }//电影 if ("场次".equals(recordType)){ Show show = new Show(); show.setId(itemId); show.setMid(moviesIds.get(movieBox.getSelectedIndex())); if (!CheckHandler.isNumeric(textFields.get(1).getText())){ JOptionPane.showMessageDialog(this.contentPane,"输入放映厅号码必须为整数"); return; }else { show.setHall(Integer.parseInt(textFields.get(1).getText())); } String time = datePicker.getJFormattedTextField().getText(); String hour = hourBox.getSelectedItem().toString(); String minute= minBox.getSelectedItem().toString(); time+=" "+hour+":"+minute; show.setTime(time); if (!CheckHandler.isNumeric(textFields.get(2).getText())){ JOptionPane.showMessageDialog(this.contentPane,"输入价格必须为整数"); return; }else{ show.setPrice(Double.parseDouble(textFields.get(2).getText())); } // System.out.println(show.getHall()+" "+show.getPrice()); success = ShowDao.updateShow(show); }//场次 if ("用户".equals(recordType)){ Staff user = new Staff(); user.setUid(itemId); user.setUsername(textFields.get(1).getText()); user.setPassword(textFields.get(2).getText()); user.setRole(Constant.userRoleIds[roleBox.getSelectedIndex()]); success= StaffDao.updateUser(user); }//用户 if (success){ JOptionPane.showMessageDialog(this.contentPane,"修改成功"); new RecordQuery(contentPane,recordType,mainFrame); contentPane.setBorder(new EmptyBorder(0,50,100,50)); mainFrame.setVisible(true); } }//保存按钮执行 private void btnQueryActionPerformed(ActionEvent e){ int itemId = -1; boolean queryFail = false; try { String idVal = idField.getText(); if (idVal.length()==0){ JOptionPane.showMessageDialog(this.contentPane,"请输入编号查询"); return; }//判断 itemId = Integer.parseInt(idVal); }catch (NumberFormatException ex){ JOptionPane.showMessageDialog(this.contentPane,"输入不正确,请输入整数"); return; } itemId = Integer.parseInt(idField.getText()); if ("电影".equals(recordType)) { Movie movie = Moviedao.getMovie(itemId); if (movie != null) { textFields.get(0).setText(movie.getMid() + ""); textFields.get(1).setText(movie.getName()); textFields.get(2).setText(movie.getType() ); textFields.get(3).setText(movie.getDirector() ); textFields.get(4).setText(movie.getSource() ); textFields.get(5).setText(movie.getPublisher()); datePicker.getJFormattedTextField().setText(movie.getReleaseDate()); } } else { queryFail = true; }//显示电影 if ("场次".equals(recordType)) { Show show = ShowDao.getShow(itemId); if (show != null) { textFields.get(0).setText(show.getId() + ""); textFields.get(1).setText(show.getHall() + ""); textFields.get(2).setText(show.getPrice() + ""); String[] timeMeta = show.getTime().split(" "); movieBox.setSelectedItem(Moviedao.getMovie(show.getMid()).getName()); datePicker.getJFormattedTextField().setText(timeMeta[0]); String[] timeMeta2 = timeMeta[1].split(":"); hourBox.setSelectedItem(timeMeta2[0]); minBox.setSelectedItem(timeMeta2[1]); } else { queryFail = true; } } // if ("订单".equals(recordType)) { // Order order = OrderDao.getOrder(itemId); // if (order != null) { // textFields.get(0).setText(order.getId() + ""); // textFields.get(1).setText(order.getName()); // textFields.get(2).setText(order.getPhone()); // textFields.get(3).setText(order.getData()); // // // } else { // queryFail = true; // }//判断 // // // }//订单 if ("用户".equals(recordType)) { Staff user = StaffDao.getStaff(itemId); if (user != null) { textFields.get(0).setText(user.getUid() + ""); textFields.get(1).setText(user.getUsername()); textFields.get(2).setText(user.getPassword()); int index = CheckHandler.getSelectIndexById(user.getRole()); if (index >= 0) { roleBox.setSelectedIndex(index); } } else { queryFail = true; }//判断 }//用户 textFields.get(0).setEnabled(false); if (queryFail) { JOptionPane.showMessageDialog(this.contentPane, "未检索数据,请调整编号!"); return; }//失败就警告 }//查询btn } <file_sep>package swinglearn; import javax.swing.*; import java.awt.*; import java.io.FileNotFoundException; public class DayforJTabbedPane { public static void main(String[] args) throws FileNotFoundException { new JFUI(); JFrame jf = new JFrame(" "); // 第 1 个 JPanel, 使用默认的浮动布局 JPanel panel01 = new JPanel(); // JTabbedPane jTabbedPane=new JTabbedPane(JTabbedPane.LEFT); JTabbedPane jTabbedPane=new JTabbedPane(); jTabbedPane.setSize(400,400); ImageIcon imageIcon = new ImageIcon("X:\\JDBCMysql\\DayForJavaSql\\jpg\\1GQ34353-7.jpg"); // Icon由图片文件形成 Image image = imageIcon.getImage(); // 但这个图片太大不适合做Icon // 为把它缩小点,先要取出这个Icon的image ,然后缩放到合适的大小 Image smallImage = image.getScaledInstance(192,108,Image.SCALE_SMOOTH); // 再由修改后的Image来生成合适的Icon ImageIcon smallIcon = new ImageIcon(smallImage); ImageIcon imageIcon2= new ImageIcon("X:\\JDBCMysql\\DayForJavaSql\\jpg\\347_170213185021_1.jpg"); // Icon由图片文件形成 Image image2 = imageIcon2.getImage(); // 但这个图片太大不适合做Icon // 为把它缩小点,先要取出这个Icon的image ,然后缩放到合适的大小 Image smallImage2 = image2.getScaledInstance(192,108,Image.SCALE_SMOOTH); // 再由修改后的Image来生成合适的Icon ImageIcon smallIcon2 = new ImageIcon(smallImage2); JButton iconButton = new JButton(smallIcon2); jTabbedPane.addTab("one",iconButton); jTabbedPane.addTab("two", JIconsmall.getIcon(16) ,new Label("Tab2")); jTabbedPane.addTab("three",JIconsmall.getIcon(14) ,new Label("Tab3"),"this is tip3小提示"); jTabbedPane.addTab("1",JIconsmall.getIcon(1) ,new Label("Tab3"),"this is tip3小提示"); jTabbedPane.addTab("2",JIconsmall.getIcon(2) ,new Label("Tab3"),"this is tip3小提示"); jTabbedPane.addTab("3",JIconsmall.getIcon(4) ,new Label("Tab3"),"this is tip3小提示"); jTabbedPane.addTab("4",JIconsmall.getIcon(5) ,new Label("Tab3"),"this is tip3小提示"); jTabbedPane.addTab("5",JIconsmall.getIcon(7) ,new Label("Tab3"),"this is tip3小提示"); jTabbedPane.addTab("6",JIconsmall.getIcon(9) ,new Label("Tab3"),"this is tip3小提示"); jTabbedPane.addTab("7",JIconsmall.getIcon(6) ,new Label("Tab3"),"this is tip3小提示"); jTabbedPane.addTab("8",JIconsmall.getIcon(14) ,new Label("Tab3"),"this is tip3小提示"); //对jTabbedpane JScrollPane scrollPane2 =new JScrollPane(jTabbedPane,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // JScrollPane scrollPane =new JScrollPane(jTabbedPane); // scrollPane2.setViewportView(jTabbedPane); // scrollPane2.setWheelScrollingEnabled(true); // panel01.add(jTabbedPane); // panel01.add(scrollPane2); scrollPane2.add(panel01); jf.setContentPane(scrollPane2); // N:\NAUTO\NieRAutomata\图片 jf.add(panel01); jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jf.setSize(500,500); // jf.pack(); jf.setLocationRelativeTo(null); jf.setVisible(true); } } <file_sep>package movies.database; import movies.take.Staff; import movies.util.QueryCreate; import movies.util.SQLExec; import movies.util.SQLMapper; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; public class StaffDao { //获取多个 public static List<Staff> getStaffs(String field, String value){ List<Staff> users =new ArrayList<Staff>(); try{ String query=""; SQLExec sqlExec = new SQLExec(); if(field.length()==0){ query = QueryCreate.queryForResults("staff"); }else if (field.equals("uid")||field.equals("role")){ query = QueryCreate.queryForResults("staff","field",Integer.parseInt(value)); }else { query = QueryCreate.queryForResults("staff",field,value); } ResultSet resultSet = sqlExec.select(query); Staff user =null; while(resultSet.next()){ user = new Staff(); SQLMapper.mapResToUser(resultSet,user); users.add(user); }//获取Staff全部信息,塞进list }catch (Exception ex){ ex.printStackTrace(); }//Staff的获取测试 return users; } //获取单个 public static Staff getStaff(int userid){ List<Staff> users = getStaffs("uid",userid+""); Staff user =null; if (users.size()>0){ user = users.get(0); } return user; } //管理员登录验证 public static Staff getUserByCredential(String username,String password){ Staff user =null; try{ String query = QueryCreate.queryByCredential(username,password); SQLExec sqlExec = new SQLExec(); ResultSet resultSet = sqlExec.select(query); while (resultSet.next()){ user = new Staff(); SQLMapper.mapResToUser(resultSet,user); } }catch (Exception ex){ ex.printStackTrace(); } return user; } //添加 public static boolean addUser(Staff user){ boolean success =true; try{ String query=QueryCreate.queryForAdd(user); SQLExec sqlExec =new SQLExec(); sqlExec.insert(query); success = true; }catch (Exception ex){ ex.printStackTrace(); } return success; } //更新管理员数据 public static boolean updateUser(Staff user){ boolean success =true; try{ String query=QueryCreate.queryForUpdate(user); SQLExec sqlExec =new SQLExec(); sqlExec.update(query); success = true; }catch (Exception ex){ ex.printStackTrace(); } return success; } //更新管理密码 public static boolean updateUserPass(int userid,String password){ boolean success =true; try{ String query=QueryCreate.queryForUpdatePass(userid,password); SQLExec sqlExec =new SQLExec(); sqlExec.update(query); success = true; }catch (Exception ex){ ex.printStackTrace(); } return success; } //删除 public static boolean deleteUser(int userId){ boolean success =true; try{ String query=QueryCreate.queryForDelete("Staff","uid",userId); SQLExec sqlExec =new SQLExec(); sqlExec.update(query); success = true; }catch (Exception ex){ ex.printStackTrace(); } return success; } } <file_sep>package movies.ui; import movies.database.Moviedao; import movies.database.ShowDao; import movies.database.StaffDao; import movies.take.Movie; import movies.take.Show; import movies.take.Staff; import movies.util.CheckHandler; import movies.util.Constant; import movies.util.DateHandler; import org.jdatepicker.impl.JDatePickerImpl; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; public class RecordAdd { private JPanel recordPane; private JPanel contentPane; private JPanel combinedPane; private JPanel btnBar; private JButton btnSave; private JComboBox<String> roleBox; private JComboBox<String> hourBox; private JComboBox<String> minBox; private JComboBox<String> movieBox; private JDatePickerImpl datePicker; private String recordType; private JFrame mainFram; private java.util.List<JTextField> textFields; private List<Integer> moviesIds; public RecordAdd(Container mainContent, String type, JFrame jFrame){ textFields = new ArrayList<JTextField>(); moviesIds = new ArrayList<Integer>(); recordType =type; mainFram = jFrame; initUI(mainContent); } public void initUI(Container mainContent){ mainContent.removeAll(); contentPane = new JPanel(new BorderLayout()); // contentPane.setBorder(new EmptyBorder(50,50,50,50)); recordPane = new JPanel(); btnBar = new JPanel(); btnSave = new JButton(); String[] currLabels = new String[0]; //不同对象,布局不同 if ("电影".equals(recordType)){ currLabels = Constant.movieLables; recordPane.setLayout(new GridLayout(6,2,6,6)); contentPane.setBorder(new EmptyBorder(100,150,150,300)); } if ("场次".equals(recordType)){ currLabels = Constant.showLables; recordPane.setLayout(new GridLayout(5,2,6,6)); contentPane.setBorder(new EmptyBorder(100,150,200,250)); } if ("用户".equals(recordType)){ currLabels = Constant.staffLables; recordPane.setLayout(new GridLayout(3,2,6,6)); contentPane.setBorder(new EmptyBorder(150,150,250,300)); } for(int i =0;i<currLabels.length;i++) { JLabel entryLabel = new JLabel(); entryLabel.setText(currLabels[i] + " : "); entryLabel.setHorizontalAlignment(SwingConstants.RIGHT); JTextField entryField = new JTextField(); recordPane.add(entryLabel); if ("场次".equals(recordType) && "电影名称".equals(currLabels[i])) { List<Movie> movies = Moviedao.getMovies("", ""); String[] movieNames = new String[movies.size()]; for (int m = 0; m < movies.size(); m++) { movieNames[m] = movies.get(m).getName(); moviesIds.add(movies.get(m).getMid()); }//for movieBox = new JComboBox<String>(movieNames); recordPane.add(movieBox); } else if ("电影".equals(recordType) && "上映时间".equals(currLabels[i])) { combinedPane = new JPanel(); datePicker = DateHandler.getDatePicker(); datePicker.setPreferredSize(new Dimension(160, 30)); combinedPane.add(datePicker); recordPane.add(combinedPane); } else if ("场次".equals(recordType) && "放映时间".equals(currLabels[i])) { datePicker = DateHandler.getDatePicker(); datePicker.setPreferredSize(new Dimension(140, 20)); // datePicker.setBorder(new EmptyBorder(10, 0, 0, 20)); recordPane.add(datePicker); combinedPane = new JPanel(); // combinedPane.add(datePicker); hourBox = new JComboBox<>(Constant.timeHours); JLabel sepLabel1 = new JLabel("时"); JLabel sepLabel2 = new JLabel("分"); minBox = new JComboBox<>(Constant.timeMinutes); combinedPane.add(hourBox); combinedPane.add(sepLabel1); combinedPane.add(minBox); combinedPane.add(sepLabel2); JLabel timeLabel = new JLabel(""); recordPane.add(timeLabel); timeLabel.setHorizontalAlignment(SwingConstants.RIGHT); recordPane.add(combinedPane); } else if ("用户".equals(recordType) && "权限".equals(currLabels[i])) { roleBox = new JComboBox<String>(Constant.userRoleDescs); recordPane.add(roleBox); } else { recordPane.add(entryField); textFields.add(entryField); } }//for contentPane.add(recordPane,BorderLayout.CENTER); btnBar.setBorder(new EmptyBorder(12,0,0,0)); btnBar.setLayout(new GridBagLayout()); ((GridBagLayout)btnBar.getLayout()).columnWeights = new double[]{1.0,0.0,0.0}; ((GridBagLayout)btnBar.getLayout()).columnWidths = new int[]{0,80,75}; btnSave.setText("添加"+recordPane); btnSave.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnSaveActionPerformed(e); } }); btnBar.add(btnSave,new GridBagConstraints(1,0,1,1,0.0,0.0,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(0,0,0,5),0,0)); contentPane.add(btnBar,BorderLayout.SOUTH); mainContent.add(contentPane,BorderLayout.CENTER); }//UI private void btnSaveActionPerformed(ActionEvent e){ if (CheckHandler.checkEmptyField(textFields)){ JOptionPane.showMessageDialog(this.contentPane,"有些项为空,请输入内容"); return; } boolean success = false; if ("电影".equals(recordType)){ Movie movie = new Movie(); movie.setName(textFields.get(0).getText()); movie.setType(textFields.get(1).getText()); movie.setDirector(textFields.get(2).getText()); movie.setSource(textFields.get(3).getText()); movie.setPublisher(textFields.get(4).getText()); String totalContent = textFields.get(1).getText()+textFields.get(2).getText() +textFields.get(3).getText()+textFields.get(4).getText(); if (CheckHandler.containsDigit(totalContent)){ JOptionPane.showMessageDialog(this.contentPane,"你的输入包含数字,输入非法"); return; }//判断输入非法 movie.setReleaseDate(datePicker.getJFormattedTextField().getText()); success=Moviedao.updateMovie(movie); }//电影 if ("场次".equals(recordType)){ Show show = new Show(); show.setMid(moviesIds.get(movieBox.getSelectedIndex())); if (!CheckHandler.isNumeric(textFields.get(0).getText())){ JOptionPane.showMessageDialog(this.contentPane,"输入放映厅号码必须为整数"); return; }else { show.setHall(Integer.parseInt(textFields.get(1).getText())); } String time = datePicker.getJFormattedTextField().getText(); String hour = hourBox.getSelectedItem().toString(); String minute= minBox.getSelectedItem().toString(); time+=" "+hour+":"+minute; show.setTime(time); if (!CheckHandler.isNumeric(textFields.get(1).getText())){ JOptionPane.showMessageDialog(this.contentPane,"输入价格必须为数字"); return; }else{ show.setPrice(Double.parseDouble(textFields.get(1).getText())); } show.setSeatsUsed(""); success = ShowDao.addShow(show); }//场次 if ("用户".equals(recordType)){ Staff user = new Staff(); user.setUsername(textFields.get(0).getText()); user.setPassword(textFields.get(1).getText()); user.setRole(Constant.userRoleIds[roleBox.getSelectedIndex()]); success= StaffDao.addUser(user); }//用户 if (success){ JOptionPane.showMessageDialog(this.contentPane,"添加成功"); new RecordQuery(contentPane,recordType,mainFram); contentPane.setBorder(new EmptyBorder(0,50,100,50)); mainFram.setVisible(true); } }//保存按钮函数 } <file_sep>package swinglearn; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class DayforNewJFame { public static void main(String[] args) { new DayforNewJFame(); } public static void show(JFrame jf){ jf.setVisible(false); JFrame jf2= new JFrame("新窗口"); JPanel jp=new JPanel(); JLabel jl = new JLabel("新创了"); JButton jb = new JButton("返回"); jb.setBounds(10,10,50,50); jb.setAlignmentX(10); jb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { jf.setVisible(true); jf2.setVisible(false); } }); jp.add(jb); jp.add(jl); jf2.add(jp); jf2.setVisible(true); jf2.setBounds(40,40,200,300); jf2.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public DayforNewJFame(){ JFrame jf = new JFrame("创建窗口"); JPanel jp = new JPanel(); JButton jButton = new JButton("new JFAME"); jButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { show(jf); } }); jButton.setBounds(100,100,50,100); jp.add(jButton); jf.add(jp); jf.setBounds(20,20,500,600); jf.setVisible(true); jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } } <file_sep>package swinglearn; import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper; import javax.swing.*; import java.awt.*; public class Beautiful extends JFrame { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { // 设置窗口边框样式 BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.translucencyAppleLike; org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF(); UIManager.put("RootPane.setupButtonVisible", false); Beautiful myFrame1 = new Beautiful(); myFrame1.setVisible(true); myFrame1.setVisible(true); myFrame1.setSize(500,500); } catch (Exception e) { e.printStackTrace(); } } }); } public Beautiful(){ setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } } <file_sep>package cn.edu.gof.pattern.Builder; public class DevilBuilder { } <file_sep>package swinglearn; import javax.swing.*; public class JFUI extends JFrame { public JFUI (){ // try { // for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { // if ("Windows".equals(info.getName())) { // javax.swing.UIManager.setLookAndFeel(info.getClassName()); // break; // } // } // }catch(Exception e) { // System.out.println(e); // } // EventQuxeue.invokeLater(new Runnable() { // public void run() { // try { // // // 设置窗口边框样式 // BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.translucencyAppleLike; // org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF(); // UIManager.put("RootPane.setupButtonVisible", false); // // // } catch (Exception e) { // e.printStackTrace(); // } // } // }); } } <file_sep>package cn.edu.gof.pattern.Builder; public class Actor { } <file_sep>package swinglearn; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class DayforJMenuBar { public static void main(String[] args) { JFrame jf = new JFrame("标题栏"); jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jf.setSize(500,500); // 第 1 个 JPanel, 使用默认的浮动布局 JPanel panel01 = new JPanel(); jf.add(panel01); //标题栏 JMenuBar JMenu JMenuItem JMenuBar jMenuBar = new JMenuBar(); JMenu file =new JMenu("文件"); JMenu edit =new JMenu("编辑"); JMenu help =new JMenu("帮助"); //设置图标 // file.setIcon(JIconsmall.getIconSetWH(17,198,108)); // edit.setIcon(JIconsmall.getIconSetWH(17,198,108)); // help.setIcon(JIconsmall.getIconSetWH(17,198,108)); //添加进入JMenuBar jMenuBar.add(file); jMenuBar.add(edit); jMenuBar.add(help); // file new MenuItem; JMenuItem newfile = new JMenuItem("新建"); JMenuItem openfile= new JMenuItem("打开"); JMenuItem exitfile= new JMenuItem("关闭"); //MenuItem方法 newfile.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("新建"); new DayforNewJFame(); } }); //添加进入Menu file.add(newfile); file.add(openfile); file.addSeparator(); file.add(exitfile); //edit中子菜单 JMenuItem copy = new JMenuItem("复制"); JMenuItem cut= new JMenuItem("剪接"); JMenuItem put= new JMenuItem("粘贴"); cut.setMnemonic(KeyEvent.VK_N); cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.ALT_MASK)); cut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("使用"); } }); jf.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getModifiersEx()==KeyEvent.CTRL_DOWN_MASK && e.getKeyCode()=='C'){ System.out.println("CTRL+C"); } } }); exitfile.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("被点击"); } }); edit.add(cut); edit.add(copy); edit.add(put); JMenuItem imageCut =new JMenuItem("截图"); help.add(imageCut); JMenuItem select =new JMenuItem("查询"); help.add(select); select.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new DayforGetOwner(); } }); imageCut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("截图"); try { new DayforImageCut(); } catch (Exception e1) { System.out.println("截图错误"); } } }) ; jf.setJMenuBar(jMenuBar); // jf.pack(); jf.setLocationRelativeTo(null); jf.setVisible(true); } } <file_sep>package cn.edu.gof.pattern.simpleFactory; public class master { public static void main(String[] args) { // simpleFactoryPattern sfp; // interfaceABC ifabc; interfaceABC ifabc; ifabc=simpleFactoryPattern.get("C"); ifabc.show(); } } <file_sep>package movies.ui; import movies.database.Moviedao; import movies.database.OrderDao; import movies.database.ShowDao; import movies.database.StaffDao; import movies.take.Movie; import movies.take.Order; import movies.take.Show; import movies.take.Staff; import movies.util.CheckHandler; import movies.util.Constant; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; public class RecordQuery { //查询 private String recordType; private JTable recordTable; private JPanel contentPane; private JComboBox<String> queryBox; private JTextField queryValue; public RecordQuery(Container mainContent, String type, JFrame jFrame){ recordType =type; initUI(mainContent); } public void initUI(Container mainContent){ //移除面板控件 //用户操作界面=》面板 mainContent.removeAll(); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(50,50,50,50)); //添加查询功能模块区域 final JPanel queryPane = new JPanel(); queryPane.setLayout(new GridLayout(1,3)); String[] fields =null; if ("电影".equals(recordType)){ fields = Constant.movieLables; } if ("场次".equals(recordType)){ fields = Constant.showLables; } if ("订单".equals(recordType)){ fields = Constant.orderLables; } if ("用户".equals(recordType)){ fields = Constant.staffLables; } //添加查询结果显示表格 queryBox = new JComboBox<String>(fields); queryValue = new JTextField(); JButton queryBtn = new JButton("查询"); queryBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnQueryActionPerformed(e); } }); JButton resetBtn = new JButton("重置"); queryBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnResetActionPerformed(e); } }); //点击表格内记录,将弹出编辑框 queryPane.add(queryBox); queryPane.add(queryValue); queryPane.add(queryBtn); queryPane.add(resetBtn); contentPane.add(queryPane); //显示当前内容区 final JPanel resultPane =new JPanel(); resultPane.setPreferredSize(new Dimension(600,400)); recordTable = new JTable(); final BorderLayout borderLayout = new BorderLayout(); borderLayout.setVgap(5); resultPane.setLayout(borderLayout); contentPane.add(resultPane); final JScrollPane scrollPane =new JScrollPane(); resultPane.add(scrollPane); paintTable("",""); scrollPane.setViewportView(recordTable); recordTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int row = recordTable.rowAtPoint(e.getPoint()); int col = recordTable.columnAtPoint(e.getPoint()); if (row>=0&&col>=0){ int item = (int )recordTable.getValueAt(row,0); new RecordEditDialog(recordType,item,recordTable,row); }//判断是否越界 } }); contentPane.setVisible(true); mainContent.add(contentPane,BorderLayout.CENTER); }//UI //处理查询不同类型的数据 private void btnQueryActionPerformed(ActionEvent e){ String field = ""; if ("电影".equals(recordType)){ field = Constant.movieDBFields[queryBox.getSelectedIndex()]; } if ("场次".equals(recordType)){ field = Constant.showDBFields[queryBox.getSelectedIndex()]; } if ("订单".equals(recordType)){ field = Constant.orderDBFields[queryBox.getSelectedIndex()]; } if ("用户".equals(recordType)){ field = Constant.showDBFields[queryBox.getSelectedIndex()]; } String value = queryValue.getText(); if(value.length()==0){ JOptionPane.showMessageDialog(this.contentPane,"请输入关键词再索引"); return; } paintTable(field,value); } //重新加载数据库所有记录 private void btnResetActionPerformed(ActionEvent e){ paintTable("",""); } //获取特定表格 private void paintTable(String field,String value){ DefaultTableModel model = new DefaultTableModel(); recordTable.setModel(model); recordTable.setEnabled(false); Object[][] tbData = null; int i =0 ; if("电影".equals(recordType)){ List<Movie> movies = Moviedao.getMovies(field,value); tbData = new Object[movies.size()][Constant.movieLables.length]; for(Movie m : movies){ tbData[i][0] = m.getMid(); tbData[i][1] = m.getName(); tbData[i][2] = m.getType(); tbData[i][3] = m.getDirector(); tbData[i][4] = m.getSource(); tbData[i][5] = m.getPublisher(); tbData[i][6] = m.getReleaseDate(); i++; }//电影赋值结果 model.setDataVector(tbData,Constant.movieLables); }//结果为电影 if("场次".equals(recordType)){ List<Show> shows = ShowDao.getShows(field,value); tbData = new Object[shows.size()][Constant.showLables.length]; for(Show s : shows){ tbData[i][0] = s.getId(); tbData[i][1] = Moviedao.getMovie(s.getMid()).getName(); tbData[i][2] = s.getHall(); tbData[i][3] = s.getTime(); tbData[i][4] = s.getPrice(); i++; }//赋值结果 model.setDataVector(tbData,Constant.showLables); }//表格结果 if("订单".equals(recordType)){ List<Order> orders = OrderDao.getOrders(field,value); tbData = new Object[orders.size()][Constant.orderLables.length]; for(Order order: orders){ tbData[i][0] = order.getId(); tbData[i][1] = order.getName(); tbData[i][2] = order.getPhone(); tbData[i][3] = order.getData(); tbData[i][4] = order.getDatatime(); i++; }//赋值结果 model.setDataVector(tbData,Constant.orderLables); }//表格结果 if("用户".equals(recordType)){ List<Staff> staffs = StaffDao.getStaffs(field,value); tbData = new Object[staffs.size()][Constant.staffLables.length]; for(Staff staff: staffs ){ tbData[i][0] = staff.getUid(); tbData[i][1] = staff.getUsername(); tbData[i][2] = staff.getPassword(); // tbData[i][3] = staff.getRole(); //检测数据权限是否有效 int index = CheckHandler.getSelectIndexById(staff.getRole()); if (index>=0){ tbData[i][3] = Constant.userRoleDescs[index]; }else{ tbData[i][3]=""; } i++; }//赋值结果 model.setDataVector(tbData,Constant.staffLables); }//表格结果 } } <file_sep>package swinglearn; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; public class Day01forPanel { public static void main(String[] args) { JFrame jf = new JFrame("用户登录"); jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jf.setSize(500,500); // 第 1 个 JPanel, 使用默认的浮动布局 JPanel panel01 = new JPanel(); panel01.add(new JLabel("用户名")); panel01.add(new JTextField(10)); // 第 2 个 JPanel, 使用默认的浮动布局 JPanel panel02 = new JPanel(); panel02.add(new JLabel("密 码")); panel02.add(new JPasswordField(10)); // 第 3 个 JPanel, 使用浮动布局, 并且容器内组件居中显示 JPanel panel03 = new JPanel(new FlowLayout(FlowLayout.CENTER)); panel03.add(new JButton("登录")); panel03.add(new JButton("注册")); // 创建一个垂直盒子容器, 把上面 3 个 JPanel 串起来作为内容面板添加到窗口 // Box vBox = Box.createVerticalBox(); // Box vBox = Box.createHorizontalBox(); // vBox.add(panel01); // vBox.add(panel02); // vBox.add(panel03); // jf.setContentPane(vBox); // jf.add(panel01,BorderLayout.NORTH); // jf.add(panel02,BorderLayout.CENTER); // jf.add(panel03,BorderLayout.SOUTH); JPanel mainPanel =new JPanel(new GridLayout(0,1)); mainPanel.setBorder(new EmptyBorder(10,10,10,10)); mainPanel.add(panel01,BorderLayout.CENTER); mainPanel.add(panel02); mainPanel.add(panel03); jf.add(mainPanel,BorderLayout.CENTER); // jf.pack(); jf.setLocationRelativeTo(null); jf.setVisible(true); } } <file_sep>package movies.ui; import movies.util.CheckHandler; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; public class OrderShowDialog extends JDialog { public OrderShowDialog(String orderData){ initUI(orderData); } private void initUI(String orderData) { setTitle("查看订单详情"); setResizable(false); Container contentPane =getContentPane(); setSize(400,400); JPanel dialogpane =new JPanel(new BorderLayout()); dialogpane.setBorder(new EmptyBorder(20,20,20,20)); JLabel jLabel =new JLabel(); jLabel.setText(CheckHandler.showOrder(orderData)); jLabel.setVerticalAlignment(SwingConstants.TOP); jLabel.setPreferredSize(new Dimension(350,350)); dialogpane.add(jLabel); contentPane.add(dialogpane,BorderLayout.CENTER); setResizable(false); setLocationRelativeTo(getOwner()); setVisible(true); } } <file_sep>package cn.edu.gof.pattern.Builder; public class HeroBuilder { }
21f61a1d9be1c33dd5626adefa2108419d2010f5
[ "Java" ]
23
Java
Tool-69-man/JDBC
b3bb68cea4aead8db9ecb79310b8826a82c3b2af
9cc9b1ec85aa716b113a43285fd2a52a6a053dd5
refs/heads/master
<repo_name>dvschramm/learnyounode<file_sep>/test8.js var http = require('http'); var url = process.argv[2]; var buf = ""; http.get(url, function(res){ res.on("data", function(data){ buf = buf + data.toString(); }); res.on("end", function(){ console.log(buf.length); console.log(buf); }); });
362823ffc290ff860a9e203114070daa0ccc9d98
[ "JavaScript" ]
1
JavaScript
dvschramm/learnyounode
26372b0c255c98721638f95b329090fa13a9e499
2f3ce26115750d5e4d1b234f734e7c25577cd8e4
refs/heads/master
<file_sep>package pp.game.handlers.entity; import org.andengine.engine.handler.*; public interface IMonsterUpdateHandler extends IUpdateHandler { } <file_sep>package pp.game.entities; abstract class BaseEntity implements IBaseEntity { private Object data; public BaseEntity() { } @Override public Object getUserData() { return data; } @Override public void setUserData(Object data) { this.data = data; } } <file_sep>package pp.game.entities; import pp.game.utils.geometry.*; public enum WeaponType { // RUNNER(100, Player.DEFAULT_PLAYER_SPEED * 0.50f, 5, 0.5f), // ZOMBIE(250, Player.DEFAULT_PLAYER_SPEED * 0.17f, 15, 1), // SPIDER(150, Player.DEFAULT_PLAYER_SPEED * 0.33f, 10, 0.75f); AK_47 (200, 0.13f, 1.5f, 12 * SceneLayoutUtils.VELOCITY_ADJUST_COEF, 30), PM (90, 0.5f, 1.0f, 6 * SceneLayoutUtils.VELOCITY_ADJUST_COEF, 7), SHOTGUN (85, 0.7f, 1.5f, 11 * SceneLayoutUtils.VELOCITY_ADJUST_COEF, 5), UZI (100, 0.09f, 1.0f, 13 * SceneLayoutUtils.VELOCITY_ADJUST_COEF, 30), FLAMETHROWER(0, 0, 0, 0, 0), LASER(0, 0, 0, 0, 0), M_32(0, 0, 0, 0, 0), REMINGTON(0, 0, 0, 0, 0); private float damage; private float shotDelay; private float reloadDelay; private float bulletSpeed; private int magazineVolume; private WeaponType(float damage, float shotDelay, float reloadDelay, float bulletSpeed, int magazineVolume) { this.damage = damage; this.shotDelay = shotDelay; this.reloadDelay = reloadDelay; this.bulletSpeed = bulletSpeed; this.magazineVolume = magazineVolume; } public float getDamage() { return damage; } public float getShotDelay() { return shotDelay; } public float getReloadDelay() { return reloadDelay; } public float getBulletSpeed() { return bulletSpeed; } public int getMagazineVolume() { return magazineVolume; } } <file_sep>package pp.game.level; import pp.game.handlers.*; import pp.game.handlers.level.*; class TestLevelInitializer extends ConfigLevelInitializer { private ILevelHandler handler; public TestLevelInitializer(ConfigLevelType type) { super(type); } public TestLevelInitializer(ConfigLevelType type, ILevelHandler handler) { super(type); this.handler = handler; } public ILevelHandler getLevelHandler() { return handler == null ? new TestLevelHandler((BasicLevelHandler)super.getLevelHandler()) : handler; } } <file_sep>package pp.game.entities; public enum BonusType { NONE(0), AK_47 (0.3f), FLAMETHROWER (0.3f), LASER (0.3f), SHOTGUN (0.3f), UZI (0.3f), HP_SMALL (0.4f), HP_MEDIUM (0.3f), HP_LARGE (0.2f), FREEZE (0.4f), SPEED (0.4f), BULLETS (0.4f); private float chance; private BonusType(float chance) { this.chance = chance; } public float getChance() { return chance; } } <file_sep>package pp.game.textures; public enum BulletTextureType { AK_47("weapons/AK_47/player.png"), FLAMETHROWER("weapons/Flamethrower/player.png"), LASER("weapons/Laser/player.png"), M_32("weapons/M_32/player.png"), PM("weapons/PM/player.png"), REMINGTON("weapons/Remington/player.png"), SHOTGUN("weapons/Shotgun/player.png"), UZI("weapons/UZI/player.png"); private String assetPath; private BulletTextureType(String assetPath) { this.assetPath = assetPath; } public String getAssetPath() { return assetPath; } } <file_sep>package pp.game.physics; import com.badlogic.gdx.physics.box2d.*; class EntityTypeInfo { float shapeSizeCoef; FixtureDef fixtureDef; public EntityTypeInfo() { } public EntityTypeInfo(float shapeSizeCoef, FixtureDef fixtureDef) { this.shapeSizeCoef = shapeSizeCoef; this.fixtureDef = fixtureDef; } } <file_sep>package pp.game.level; import pp.game.handlers.level.*; import pp.game.utils.type.*; import android.util.*; public class LevelFactory { public static ILevelInitializer getLevel(LevelType type) { try { switch (type) { case TEST_HIGH_HP_MANY_MONSTERS: case TEST_HIGH_HP_ONE_MONSTER: case TEST_LOW_HP_ONE_MONSTER: case TEST_BONUS_SPAWN: return new TestLevelInitializer(TypeConverter.getConfigLevelType(type), TestLevelManulHandlerFactory.createHandler(type)); case TEST_LOW_HP_FREQUENT_SPAWN: case TEST_NO_MONSTERS: case TEST_HIGH_HP_NORMAL_SPAWN: return new TestLevelInitializer(TypeConverter.getConfigLevelType(type)); case SURVIVAL: return new ConfigLevelInitializer(TypeConverter.getConfigLevelType(type)); } } catch (Exception e) { RuntimeException re = new RuntimeException("Error initializing level " + type, e); Log.e("", "", re); throw re; } return null; } } <file_sep>package pp.game.handlers.entity; import org.andengine.entity.sprite.*; import pp.game.entities.*; import pp.game.handlers.*; import pp.game.textures.*; import pp.game.utils.*; import pp.game.utils.geometry.*; import pp.game.utils.type.*; public class BasicMonsterUpdateHandler extends DieableUpdateHandler implements IMonsterUpdateHandler { private static final float MIN_COORD_DIFF = 20f; private Player player; private Monster monster; private AnimatedSprite aliveSprite; private MonsterWalkTextureType monsterWalkType; private long[] durations; private class BasicMonsterHandlerCommand implements IHandlerCommand { public BasicMonsterHandlerCommand() { } @Override public void execute() { if (!monster.isDead()) { Point reverseDirection = GeometryUtils.convertToDirection( new Point(aliveSprite.getX(), aliveSprite.getY()), new Point(player.getShape().getX(), player.getShape().getY())); Point direction = new Point(-reverseDirection.x, -reverseDirection.y); monster.getAliveSprite().setRotation(monster.getAliveSprite().getRotation() + 180); animateAndRun(direction); } } } public BasicMonsterUpdateHandler(Monster monster) { setEntities(monster, Player.getInstance()); setCommands(new BasicMonsterHandlerCommand()); this.monster = monster; aliveSprite = monster.getAliveSprite(); player = Player.getInstance(); monsterWalkType = TypeConverter.getMonsterWalkTextureType(monster.getMonsterType()); durations = new long[monsterWalkType.getTilesCount()]; for (int i = 0; i < durations.length; i++) { durations[i] = monsterWalkType.getAnimationDuration(); } } private void animateAndRun(final Point direction) { if (!monster.getAliveSprite().isAnimationRunning()) { monster.getAliveSprite().animate(durations, true); } monster.getBody().setLinearVelocity(monster.getMonsterType().getWalkSpeed() * direction.x, monster.getMonsterType().getWalkSpeed() * direction.y); } @Override protected void onUpdate() { Point diffAbs = new Point(); Point direction = GeometryUtils.convertToDirection( new Point(aliveSprite.getX(), aliveSprite.getY()), new Point(player.getShape().getX(), player.getShape().getY()), diffAbs); aliveSprite.setRotation(GeometryUtils.getRotation(direction)); if ((diffAbs.x + diffAbs.y) / 2 > MIN_COORD_DIFF) { animateAndRun(direction); } else { monster.getAliveSprite().stopAnimation(); monster.getAliveSprite().setCurrentTileIndex( CalcUtils.getGreaterOrEqual(monsterWalkType.getStopTiles(), monster.getAliveSprite().getCurrentTileIndex())); monster.getBody().setLinearVelocity(0, 0); } } } <file_sep>package pp.game.audio; public enum GameMusicType { BASE_0("music/game/base_0.ogg"), BASE_1("music/game/base_1.ogg"), BASE_2("music/game/base_2.ogg"), END_GAME("music/game/end_game.ogg"), LOW_HP("music/game/low_hp.ogg"); private String assetPath; private GameMusicType(String assetPath) { this.assetPath = assetPath; } public String getAssetPath() { return assetPath; } } <file_sep>package pp.game.observers; import pp.game.entities.*; public interface IDieableObservable extends IObservable<IDieableEntity> { } <file_sep>package pp.game.observers; public interface IObserver<T> { void onChanged(T observable); } <file_sep>package pp.game.handlers.level; import pp.game.entities.*; import pp.game.handlers.*; import pp.game.level.*; import pp.game.scene.*; import pp.game.utils.concurrent.*; public class TestLevelManulHandlerFactory { private TestLevelManulHandlerFactory() { } private static class LevelHandler extends DelayedUpdateHandler implements ILevelHandler { private Runnable runnable; @Override public void onUpdate() { runnable.run(); } public void setRunnable(Runnable runnable) { this.runnable = runnable; } } public static ILevelHandler createHandler(LevelType type) { final LevelHandler handler = new LevelHandler(); handler.setRequiredDelay(0); switch (type) { case TEST_HIGH_HP_ONE_MONSTER: case TEST_LOW_HP_ONE_MONSTER: handler.setRunnable(new Runnable() { @Override public void run() { GameScene.getInstance().attachChild(Monster.getMonster( MonsterType.SPIDER).getAliveSprite()); GameScene.getInstance().unregisterUpdateHandler(handler); } }); break; case TEST_HIGH_HP_MANY_MONSTERS: final int MONSTERS_COUNT = 7; final MonsterType MONSTER_TYPE = MonsterType.RUNNER; handler.setRunnable(new Runnable() { @Override public void run() { for (int i = 0; i < MONSTERS_COUNT; i++) { GameScene.getInstance().attachChild(Monster.getMonster( MONSTER_TYPE).getAliveSprite()); } GameScene.getInstance().unregisterUpdateHandler(handler); } }); break; case TEST_BONUS_SPAWN: final float BONUS_SPAWN_DELAY = 1f; handler.setRunnable(new Runnable() { @Override public void run() { BonusManager.getInstance().spawnBonus(); } }); handler.setRequiredDelay(BONUS_SPAWN_DELAY); break; } return handler; } } <file_sep>package pp.game.handlers.contact; import pp.game.audio.*; import pp.game.entities.*; import pp.game.handlers.*; import pp.game.scene.*; public class PlayerMonsterContactUpdateHandler extends DelayedUpdateHandler implements IContactHandler { private Monster monster; private Player player = Player.getInstance(); public PlayerMonsterContactUpdateHandler(Monster monster) { this.monster = monster; setRequiredDelay(monster.getMonsterType().getAttackSpeed()); hitPlayer(); } private void hitPlayer() { if (!player.isDead() && !monster.isDead()) { if (player.getAliveSprite().collidesWith(monster.getAliveSprite())) { player.adjustCurrentHP(-monster.getMonsterType().getDamage()); AudioHolder.getInstance().playEntityHitSound( EntityHitSoundType.getRandomPlayerSound()); } else { GameScene.getInstance().unregisterUpdateHandler(this); } } } @Override protected void onUpdate() { hitPlayer(); } } <file_sep>package pp.game; public interface IPausable extends IPrioritized { void pause(); void resume(); } <file_sep>package pp.game.entities; import java.util.*; import org.andengine.entity.sprite.*; import org.andengine.opengl.vbo.*; import pp.game.*; import pp.game.audio.*; import pp.game.handlers.*; import pp.game.handlers.entity.*; import pp.game.level.*; import pp.game.observers.*; import pp.game.physics.*; import pp.game.scene.*; import pp.game.textures.*; import pp.game.utils.geometry.*; public class Player extends DieableEntity implements IPreparable, IResetable, IDieableObservable { private static final Player INTANCE = new Player(); private AnimatedSprite legsSprite; private IGameScene scene; private Weapon weapon; private float playerSpeed; private Set<IObserver<IDieableEntity>> observers = new HashSet<IObserver<IDieableEntity>>(); private class PlayerUpdateHandler extends DieableUpdateHandler { public PlayerUpdateHandler() { setEntities(Player.this); setCommands(new IHandlerCommand() { @Override public void execute() { GameScene.getInstance().unregisterUpdateHandler( PlayerUpdateHandler.this); } }); } @Override protected void onUpdate() { weapon.getSprite().setPosition(getAliveSprite()); legsSprite.setPosition(getAliveSprite()); } } private Player() { Game.getGameInstance().addPreparable(this); TextureHolder holder = TextureHolder.getInstance(); VertexBufferObjectManager vertexManager = Game.getGameActivity() .getVertexBufferObjectManager(); setAliveSprite(new Sprite(0, 0, holder.getTexture(SingleTextureType.STUB), vertexManager)); getAliveSprite().setAlpha(0); setDeadSprite(new AnimatedSprite(0, 0, holder.getTiledTexture( SingleTiledTextureType.PLAYER_DEATH), vertexManager)); legsSprite = new AnimatedSprite(0, 0, holder.getTiledTexture( SingleTiledTextureType.PLAYER_WALK), vertexManager); legsSprite.setCurrentTileIndex(((int[])((Object[]) SingleTiledTextureType.PLAYER_WALK.getUserData())[0])[0]); } public static Player getInstance() { return INTANCE; } private void notifyObservers() { for (IObserver<IDieableEntity> observer : observers) { observer.onChanged(this); } } @Override public AnimatedSprite getDeadSprite() { return (AnimatedSprite)super.getDeadSprite(); } @Override public void prepare(ILevel level) { PhysicsManager physicsManager = PhysicsManager.getInstance(); float x = SceneLayoutUtils.BACKGROUND_MAX_X / 2f; float y = SceneLayoutUtils.BACKGROUND_MAX_Y / 2f; scene = GameScene.getInstance(); getAliveSprite().setPosition(x, y); getAliveSprite().setRotation(0); SceneLayoutUtils.adjustPlayer(this); super.setCurrentHP(level.getInitialPlayerHP()); setMaxHP(level.getMaxPlayerHP()); setIdDead(false); setPlayerSpeed(SceneLayoutUtils.DEFAULT_PLAYER_SPEED); setAliveBody(physicsManager.createBody(this)); setWeapon(Weapon.getWeapon(WeaponType.PM)); Game.getGameActivity().getEngine().getCamera().setChaseEntity(getAliveSprite()); scene.attachChild(getAliveSprite()); scene.attachChild(legsSprite); scene.registerUpdateHandler(new PlayerUpdateHandler()); } @Override public void reset() { if (!isDead()) { PhysicsManager.getInstance().removeBody(getAliveBody()); } } @Override public Priority getPriority() { return Priority.MEDIUM; } @Override public EntityType getEntityType() { return EntityType.PLAYER; } @Override public void adjustCurrentHP(float value) { super.adjustCurrentHP(value); notifyObservers(); } @Override protected void setCurrentHP(float currentHP) { super.setCurrentHP(currentHP); notifyObservers(); } @Override public void setMaxHP(float maxHP) { super.setMaxHP(maxHP); notifyObservers(); } @Override public void die() { PhysicsManager.getInstance().removeBody(getAliveBody()); scene.detachChild(weapon.getSprite(), false); scene.detachChild(legsSprite); scene.unregisterUpdateHandlers(new EndGameHandlersMatcher()); scene.attachChild(getDeadSprite()); getDeadSprite().setPosition(getAliveSprite()); Game.getGameActivity().getEngine().getCamera().setChaseEntity(getDeadSprite()); getDeadSprite().animate(SingleTiledTextureType.PLAYER_DEATH.getAnimationDuration(), false); AudioHolder.getInstance().playSound(SoundType.PLAYER_DEATH); scene.setCurrentMusic(GameMusicType.END_GAME); } @Override public void addObservable(IObserver<IDieableEntity> observer) { observers.add(observer); } @Override public void removeObservable(IObserver<IDieableEntity> observer) { observers.remove(observer); } public void setWeapon(Weapon newWeapon) { if (this.weapon != null) { scene.detachChild(this.weapon.getSprite()); newWeapon.setWeaponBonus(weapon.getWeaponBonus()); } this.weapon = newWeapon; scene.attachChild(SceneLayoutUtils.adjustWeapon(newWeapon).getSprite()); } public Weapon getWeapon() { return weapon; } public float getPlayerSpeed() { return playerSpeed; } public void setPlayerSpeed(float playerSpeed) { this.playerSpeed = playerSpeed; } public AnimatedSprite getLegsSprite() { return legsSprite; } } <file_sep>package pp.game.textures; import pp.game.entities.*; import pp.game.utils.*; import pp.game.utils.geometry.*; public enum MonsterWalkTextureType { RUNNER("monsters/runner/walk.png", 24, 6, 4, 0.5f, CalcUtils.getMonsterAnimationDuration(MonsterType.RUNNER), new int[] { 7, 15 }), ZOMBIE("monsters/zombie/walk.png", 24, 6, 4, CalcUtils.getMonsterAnimationDuration(MonsterType.ZOMBIE), new int[] { 8, 20 }), SPIDER("monsters/spider/walk.png", 13, 4, 4, CalcUtils.getMonsterAnimationDuration(MonsterType.SPIDER), new int[] { 0, 4, 8 }); public static final int MONSTER_TEXTURE_HEIGHT = 128; public static final int MONSTER_TEXTURE_WIDTH = 128; private String assetPath; private int tilesCount; private int rows; private int columns; private int animationDuration; private int[] stopTiles; private MonsterWalkTextureType(String assetPath, int tilesCount, int rows, int columns, int animationDuration, int[] stopTiles) { this.assetPath = SceneLayoutUtils.IS_HD ? new StringBuilder(assetPath).insert(assetPath.lastIndexOf('/') + 1, "hd_").toString() : assetPath; this.tilesCount = tilesCount; this.rows = rows; this.columns = columns; this.animationDuration = animationDuration; this.stopTiles = stopTiles; } private MonsterWalkTextureType(String assetPath, int tilesCount, int rows, int columns, float animationDurationAdjustCoef, int animationDuration, int[] stopTiles) { this(assetPath, tilesCount, rows, columns, (int)(animationDuration / animationDurationAdjustCoef), stopTiles); } public String getAssetPath() { return assetPath; } public int getTilesCount() { return tilesCount; } public int getRows() { return rows; } public int getColumns() { return columns; } public int getAnimationDuration() { return animationDuration; } public int[] getStopTiles() { return stopTiles; } }<file_sep>package pp.game.scene.hud; public enum FontSize { SMALL, MEDIUM; } <file_sep>package pp.game.audio; public enum WeaponShotSoundType { AK_47("weapons/AK_47/shot.ogg"), FLAMETHROWER("weapons/Flamethrower/shot.ogg"), LASER("weapons/Laser/shot.ogg"), PM("weapons/PM/shot.ogg"), SHOTGUN("weapons/Shotgun/shot.ogg"), UZI("weapons/UZI/shot.ogg"); private String assetPath; private WeaponShotSoundType(String assetPath) { this.assetPath = assetPath; } public String getAssetPath() { return assetPath; } } <file_sep>package pp.game.handlers; import org.andengine.engine.handler.*; import org.andengine.entity.*; import pp.game.utils.concurrent.*; public class UnregisterHandlerCommand implements IHandlerCommand { private IEntity entity; private IUpdateHandler handler; public UnregisterHandlerCommand(IEntity entity, IUpdateHandler handler) { this.entity = entity; this.handler = handler; } @Override public void execute() { ConcurrentUtils.removeHandlerFromEntity(entity, handler); } } <file_sep>package pp.game.audio; public enum WeaponReloadSoundType { AK_47("weapons/AK_47/reload.ogg"), FLAMETHROWER("weapons/Flamethrower/reload.ogg"), LASER("weapons/Laser/reload.ogg"), PM("weapons/PM/reload.ogg"), SHOTGUN("weapons/Shotgun/reload.ogg"), UZI("weapons/UZI/reload.ogg"); private String assetPath; private WeaponReloadSoundType(String assetPath) { this.assetPath = assetPath; } public String getAssetPath() { return assetPath; } } <file_sep>package pp.game.handlers.entity; import pp.game.entities.*; import pp.game.handlers.*; public abstract class DieableUpdateHandler extends UpdateHandler { private IDieableEntity[] entities; private IHandlerCommand[] commands; private boolean executed = false; public DieableUpdateHandler() { this(new IDieableEntity[0], new IHandlerCommand[0]); } public DieableUpdateHandler(IDieableEntity[] entities) { this(entities, new IHandlerCommand[0]); } public DieableUpdateHandler(IDieableEntity[] entities, IHandlerCommand[] commands) { this.entities = entities; this.commands = commands; } protected void setEntities(IDieableEntity...entities) { this.entities = entities; } protected void setCommands(IHandlerCommand...commands) { this.commands = commands; } @Override final public void onUpdate(float secondsElapsed) { for (IDieableEntity entity : entities) { if (entity.isDead()) { if (!executed) { for (IHandlerCommand command : commands) { command.execute(); } } executed = true; return; } } onUpdate(); } protected abstract void onUpdate(); } <file_sep>package pp.game; public interface IDestroyable extends IPrioritized { void destroy(); } <file_sep>package pp.game.utils.geometry; import org.andengine.util.math.*; import pp.game.utils.*; public class GeometryUtils { public static float getRotation(Point direction) { float x = direction.x; float y = direction.y; x *= CalcUtils.COORD_ADJUST_COEF; y *= CalcUtils.COORD_ADJUST_COEF; double b = Math.abs(x); double c = MathUtils.distance(0, 0, x, y); float cornerL = (float)Math.toDegrees(Math.asin(Math.abs(b / c))); if (x >= 0 && y >= 0) { cornerL = 180 - cornerL; } else if (x < 0 && y >= 0) { cornerL += 180; } else if (x < 0 && y < 0) { cornerL = 360 - cornerL; } return cornerL; } public static Point convertToDirection(Point to) { return convertToDirection(new Point(0, 0), to, null); } public static Point convertToDirection(Point from, Point to) { return convertToDirection(from, to, null); } public static Point convertToDirection(Point from, Point to, Point diffAbsDst) { float dX = to.x - from.x; float dY = to.y - from.y; float xAbs = Math.abs(dX); float yAbs = Math.abs(dY); if (diffAbsDst != null) { diffAbsDst.x = xAbs; diffAbsDst.y = yAbs; } if (xAbs > yAbs) { dY /= xAbs; dX = Math.signum(dX); } else { dX /= yAbs; dY = Math.signum(dY); } return new Point(dX, dY); } } <file_sep>package pp.game.scene; import org.andengine.entity.scene.background.*; import org.andengine.entity.scene.menu.*; import org.andengine.entity.scene.menu.item.*; import org.andengine.entity.sprite.*; import org.andengine.opengl.vbo.*; import org.andengine.util.debug.*; import pp.game.*; import pp.game.textures.*; import pp.game.utils.geometry.*; class MainMenuScene extends MenuScene { private static final int MAIN_MENU_ITEMS_COUNT = 3; public MainMenuScene(IOnMenuItemClickListener listener) { super(Game.getGameActivity().getEngine().getCamera(), listener); TextureHolder holder = TextureHolder.getInstance(); VertexBufferObjectManager manager = Game.getGameActivity().getVertexBufferObjectManager(); SpriteMenuItem item; setBackground(new SpriteBackground(SceneLayoutUtils.adjustSpriteToScreenSize( new Sprite(0, 0, holder.getTexture(MenuTextureType.MAIN_MENU_BACKGROUND), manager)))); addMenuItem(item = new SpriteMenuItem(MainScene.MAIN_MENU_NEW_GAME, holder.getTexture(MenuTextureType.MAIN_MENU_NEW_GAME), manager)); SceneLayoutUtils.adjustToCenteredListItem(item, 0, MAIN_MENU_ITEMS_COUNT); addMenuItem(item = new SpriteMenuItem(MainScene.MAIN_MENU_HIGH_SCORES, holder.getTexture(MenuTextureType.MAIN_MENU_HIGH_SCORES), manager)); SceneLayoutUtils.adjustToCenteredListItem(item, 1, MAIN_MENU_ITEMS_COUNT); addMenuItem(item = new SpriteMenuItem(MainScene.MAIN_MENU_EXIT, holder.getTexture(MenuTextureType.MAIN_MENU_EXIT), manager)); SceneLayoutUtils.adjustToCenteredListItem(item, 2, MAIN_MENU_ITEMS_COUNT); } @Override public void back() { } } <file_sep>package pp.game.textures; public enum PlayerControlTextureType { MOVE_BASE("textures/controls/onscreen_control_base.png"), MOVE_KNOB("textures/controls/onscreen_control_knob.png"), SHOOT_BASE("textures/controls/onscreen_control_base.png"), SHOOT_KNOB("textures/controls/onscreen_control_knob.png"); private String assetPath; private PlayerControlTextureType(String assetPath) { this.assetPath = assetPath; } public String getAssetPath() { return assetPath; } } <file_sep>package pp.game.textures; import pp.game.utils.geometry.*; public enum BonusTextureType { AK_47("weapons/AK_47/image.png"), FLAMETHROWER("weapons/Flamethrower/image.png"), LASER("weapons/Laser/image.png"), PM("weapons/PM/image.png"), SHOTGUN("weapons/Shotgun/image.png"), UZI("weapons/UZI/image.png"), HP_SMALL("textures/bonus/hp_small.png"), HP_MEDIUM("textures/bonus/hp_medium.png"), HP_LARGE("textures/bonus/hp_large.png"), SPEED("textures/bonus/speed.png"), BULLETS("textures/bonus/bullets.png"), FREEZE("textures/bonus/freeze.png"); private String assetPath; private BonusTextureType(String assetPath) { this.assetPath = SceneLayoutUtils.IS_HD ? new StringBuilder(assetPath).insert(assetPath.lastIndexOf('/') + 1, "hd_").toString() : assetPath; } public String getAssetPath() { return assetPath; } } <file_sep>package pp.game.level; import pp.game.handlers.*; import pp.game.handlers.level.*; public interface ILevelInitializer { ILevel getLevel(); ILevelHandler getLevelHandler(); } <file_sep>package pp.game.textures; import java.util.*; import org.andengine.opengl.texture.*; import org.andengine.opengl.texture.atlas.bitmap.*; import org.andengine.opengl.texture.atlas.bitmap.source.*; import org.andengine.opengl.texture.atlas.buildable.builder.*; import org.andengine.opengl.texture.atlas.buildable.builder.ITextureAtlasBuilder.TextureAtlasBuilderException; import org.andengine.opengl.texture.region.*; import pp.game.*; import pp.game.utils.geometry.*; import android.content.res.*; public class TextureHolder implements IDestroyable { private static final TextureHolder INSTANCE = new TextureHolder(); private HashMap<SingleTiledTextureType, ITiledTextureRegion> singleTiledTextures; private HashMap<MonsterWalkTextureType, ITiledTextureRegion> monsterWalkTiledTextures; private HashMap<MonsterDeathTextureType, ITiledTextureRegion> monsterDeathTiledTextures; private HashMap<WeaponTextureType, ITextureRegion> weaponTextures; private HashMap<PlayerControlTextureType, ITextureRegion> playerControlTextures; private HashMap<MenuTextureType, ITextureRegion> menuTextures; private HashMap<SingleTextureType, ITextureRegion> singleTextures; private HashMap<BonusTextureType, ITextureRegion> bonusTextures; private HashMap<BackgroundTextureType, AssetBitmapTextureAtlasSource> backgroundTextures; private BuildableBitmapTextureAtlas atlas; private List<ITextureRegion> texturesToUnload = new ArrayList<ITextureRegion>(); private TextureHolder() { int atlasSize = SceneLayoutUtils.IS_HD ? 4096 : 2048; TextureManager textureManager = Game.getGameActivity().getTextureManager(); AssetManager assets = Game.getGameActivity().getAssets(); atlas = new BuildableBitmapTextureAtlas(textureManager, atlasSize, atlasSize, TextureOptions.BILINEAR_PREMULTIPLYALPHA); singleTiledTextures = new HashMap<SingleTiledTextureType, ITiledTextureRegion>(); for (SingleTiledTextureType value : SingleTiledTextureType.values()) { singleTiledTextures.put(value, BitmapTextureAtlasTextureRegionFactory .createTiledFromAsset(atlas, assets, value.getAssetPath(), value.getColumns(), value.getRows())); } monsterWalkTiledTextures = new HashMap<MonsterWalkTextureType, ITiledTextureRegion>(); for (MonsterWalkTextureType value : MonsterWalkTextureType.values()) { monsterWalkTiledTextures.put(value, BitmapTextureAtlasTextureRegionFactory .createTiledFromAsset(atlas, assets, value.getAssetPath(), value.getColumns(), value.getRows())); } monsterDeathTiledTextures = new HashMap<MonsterDeathTextureType, ITiledTextureRegion>(); for (MonsterDeathTextureType value : MonsterDeathTextureType.values()) { monsterDeathTiledTextures.put(value, BitmapTextureAtlasTextureRegionFactory .createTiledFromAsset(atlas, assets, value.getAssetPath(), value.getColumns(), value.getRows())); } weaponTextures = new HashMap<WeaponTextureType, ITextureRegion>(); for (WeaponTextureType value : WeaponTextureType.values()) { weaponTextures.put(value, BitmapTextureAtlasTextureRegionFactory .createFromAsset(atlas, assets, value.getAssetPath())); } playerControlTextures = new HashMap<PlayerControlTextureType, ITextureRegion>(); for (PlayerControlTextureType value : PlayerControlTextureType.values()) { playerControlTextures.put(value, BitmapTextureAtlasTextureRegionFactory .createFromAsset(atlas, assets, value.getAssetPath())); } backgroundTextures = new HashMap<BackgroundTextureType, AssetBitmapTextureAtlasSource>(); for (BackgroundTextureType value : BackgroundTextureType.values()) { backgroundTextures.put(value, AssetBitmapTextureAtlasSource.create( assets, value.getAssetPath())); } menuTextures = new HashMap<MenuTextureType, ITextureRegion>(); for (MenuTextureType value : MenuTextureType.values()) { menuTextures.put(value, BitmapTextureAtlasTextureRegionFactory .createFromAsset(atlas, assets, value.getAssetPath())); } singleTextures = new HashMap<SingleTextureType, ITextureRegion>(); for (SingleTextureType value : SingleTextureType.values()) { singleTextures.put(value, BitmapTextureAtlasTextureRegionFactory .createFromAsset(atlas, assets, value.getAssetPath())); } bonusTextures = new HashMap<BonusTextureType, ITextureRegion>(); for (BonusTextureType value : BonusTextureType.values()) { bonusTextures.put(value, BitmapTextureAtlasTextureRegionFactory .createFromAsset(atlas, assets, value.getAssetPath())); } try { atlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>( 0, 1, 1)); } catch (TextureAtlasBuilderException e) { throw new RuntimeException( "Полный пиздец, ибо текстуры нихуя не загрузились.", e); } atlas.load(); Game.getGameInstance().addDestroyable(this); } public static TextureHolder getInstance() { return INSTANCE; } public AssetBitmapTextureAtlasSource getTexture(BackgroundTextureType type) { return backgroundTextures.get(type); } public ITextureRegion getTexture(WeaponTextureType type) { return weaponTextures.get(type); } public ITextureRegion getTexture(BonusTextureType type) { return bonusTextures.get(type); } public ITextureRegion getTexture(PlayerControlTextureType type) { return playerControlTextures.get(type); } public ITextureRegion getTexture(MenuTextureType type) { return menuTextures.get(type); } public ITextureRegion getTexture(SingleTextureType type) { return singleTextures.get(type); } public ITiledTextureRegion getTiledTexture(MonsterWalkTextureType type) { return monsterWalkTiledTextures.get(type); } public ITiledTextureRegion getTiledTexture(MonsterDeathTextureType type) { return monsterDeathTiledTextures.get(type); } public ITiledTextureRegion getTiledTexture(SingleTiledTextureType type) { return singleTiledTextures.get(type); } public void addTextureToUnload(ITextureRegion texture) { texturesToUnload.add(texture); } @Override public void destroy() { // TextureManager manager = Game.getGameActivity().getTextureManager(); // // for (ITextureRegion texture : singleTiledTextures.values()) { // manager.unloadTexture(texture.getTexture()); // } // for (ITextureRegion texture : monsterWalkTiledTextures.values()) { // manager.unloadTexture(texture.getTexture()); // } // for (ITextureRegion texture : monsterDeathTiledTextures.values()) { // manager.unloadTexture(texture.getTexture()); // } // for (ITextureRegion texture : weaponTextures.values()) { // manager.unloadTexture(texture.getTexture()); // } // for (ITextureRegion texture : playerControlTextures.values()) { // manager.unloadTexture(texture.getTexture()); // } // for (ITextureRegion texture : menuTextures.values()) { // manager.unloadTexture(texture.getTexture()); // } // for (ITextureRegion texture : singleTextures.values()) { // manager.unloadTexture(texture.getTexture()); // } // for (ITextureRegion texture : bonusTextures.values()) { // manager.unloadTexture(texture.getTexture()); // } // for (ITextureRegion texture : texturesToUnload) { // manager.unloadTexture(texture.getTexture()); // } // // atlas.unload(); } @Override public Priority getPriority() { return Priority.MEDIUM; } } <file_sep>package pp.game.textures; import pp.game.utils.geometry.*; public enum WeaponTextureType { AK_47("weapons/AK_47/player.png"), FLAMETHROWER("weapons/Flamethrower/player.png"), LASER("weapons/Laser/player.png"), PM("weapons/PM/player.png"), SHOTGUN("weapons/Shotgun/player.png"), UZI("weapons/UZI/player.png"); private String assetPath; private WeaponTextureType(String assetPath) { this.assetPath = SceneLayoutUtils.IS_HD ? new StringBuilder(assetPath).insert(assetPath.lastIndexOf('/') + 1, "hd_").toString() : assetPath; } public String getAssetPath() { return assetPath; } } <file_sep>package pp.game.scene.hud; import org.andengine.entity.modifier.*; import org.andengine.entity.text.*; import org.andengine.opengl.font.*; import org.andengine.util.color.*; import pp.game.*; import pp.game.audio.*; import pp.game.entities.*; import pp.game.entities.IDieableEntity.HPState; import pp.game.level.*; import pp.game.observers.*; import pp.game.scene.*; import pp.game.utils.geometry.*; class PlayerHPIndicator extends Text { private static final int MAX_CHARACTERS_TO_DRAW = 7; private static final int X = 10; private static final int Y = 10; private static final float SCALE_MODIFIER_DURATION = 1; private Color fullHPColor; private Color mediumHPColor; private Color lowHPColor; private class PlayerHPIndicatorObserver implements IPreparable, IResetable, IDieableObserver { private HPState prevHPState; private HPState currentHPState; private ILevel level; private boolean prepared = false; public PlayerHPIndicatorObserver() { Game.getGameInstance().addPreparable(this); } @SuppressWarnings("incomplete-switch") private void updateIndicator(IDieableEntity entity) { currentHPState = Player.getInstance().getHPState(); if (currentHPState != prevHPState) { switch (currentHPState) { case HIGH: setColor(fullHPColor); GameScene.getInstance().setCurrentMusic(level.getMusic()); break; case MEDIUM: setColor(mediumHPColor); GameScene.getInstance().setCurrentMusic(level.getMusic()); break; case LOW: setColor(lowHPColor); GameScene.getInstance().setCurrentMusic(GameMusicType.LOW_HP); break; } } setText(String.valueOf((int)entity.getCurrentHP())); } @Override public Priority getPriority() { return Priority.LOW; } @Override public void prepare(ILevel level) { this.level = level; onChanged(Player.getInstance()); prevHPState = null; updateIndicator(Player.getInstance()); prepared = true; } @Override public void reset() { prepared = false; } @Override public void onChanged(IDieableEntity observable) { if (!prepared) { return; } updateIndicator(observable); prevHPState = currentHPState; } } private PlayerHPIndicator(IFont font) { super(X, Y, font, "", MAX_CHARACTERS_TO_DRAW, Game.getGameActivity() .getVertexBufferObjectManager()); fullHPColor = new Color(0, 0.8f, 0); mediumHPColor = new Color(0.8f, 0.8f, 0); lowHPColor = new Color(0.8f, 0, 0); registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier( new ScaleModifier(SCALE_MODIFIER_DURATION, 0.8f, 1.2f), new ScaleModifier(SCALE_MODIFIER_DURATION, 1.2f, 0.8f)))); } static PlayerHPIndicator getHpIndicator() { Font font = GameHUDSettings.getFont(android.graphics.Color.WHITE, FontSize.SMALL); PlayerHPIndicator indicator = new PlayerHPIndicator(font); SceneLayoutUtils.adjustGameHUDText(indicator); Player.getInstance().addObservable(indicator.new PlayerHPIndicatorObserver()); return indicator; } } <file_sep>package pp.game.handlers; import pp.game.entities.*; import pp.game.handlers.entity.*; public class HandlerFactory { private HandlerFactory() { } public static IMonsterUpdateHandler getMonsterHandler(Monster monster) { return new BasicMonsterUpdateHandler(monster); } } <file_sep>package pp.game.scene.hud; import org.andengine.entity.text.*; import org.andengine.opengl.font.*; import org.andengine.util.*; import org.andengine.util.debug.*; import pp.game.*; import pp.game.entities.*; import pp.game.observers.*; import pp.game.utils.geometry.*; import android.graphics.*; class WeaponMagazineIndicator extends Text { private static final int MAX_CHARACTERS_TO_DRAW = 5; private static final int Y = 10; private static final float MAGIC_X_ADJUST_COEF = 0.32f; private class WeaponMagazineObserver implements IObserver<Weapon> { public WeaponMagazineObserver() { } @Override public void onChanged(Weapon weapon) { setText(weapon.getCurrentBullets() + "/" + weapon.getWeaponType().getMagazineVolume()); } } private WeaponMagazineIndicator(IFont font) { super(0, Y, font, "", MAX_CHARACTERS_TO_DRAW, new TextOptions(HorizontalAlign.LEFT), Game.getGameActivity().getVertexBufferObjectManager()); } static WeaponMagazineIndicator getMagazineIndicator() { Font font = GameHUDSettings.getFont(Color.rgb(189, 183, 107), FontSize.SMALL); WeaponMagazineIndicator indicator = new WeaponMagazineIndicator(font); SceneLayoutUtils.adjustGameHUDText(indicator); indicator.setX(SceneLayoutUtils.WIDTH - GameHUD.SMALL_TEXTURE_WIDTH * MAGIC_X_ADJUST_COEF); Weapon.addObservable(indicator.new WeaponMagazineObserver()); return indicator; } } <file_sep>package pp.game.scene; import org.andengine.entity.scene.*; import org.andengine.entity.scene.menu.*; import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener; import org.andengine.entity.scene.menu.item.*; import pp.game.*; import pp.game.audio.*; import pp.game.level.*; import pp.game.scene.hud.*; public class MainScene extends Scene implements IOnMenuItemClickListener, IChildClickListener, IPreparable { static final int MAIN_MENU_NEW_GAME = 0x0; static final int MAIN_MENU_HIGH_SCORES = 0x1; static final int MAIN_MENU_EXIT = 0x2; static final int PAUSE_MENU_RESUME = 0x3; static final int PAUSE_MENU_MAIN_MENU = 0x4; private MainMenuScene mainMenuScene; private PauseMenuScene pauseMenuScene; private HighScoresMenuScene highScoresScene; public MainScene() { Game.getGameInstance().addPreparable(this); mainMenuScene = new MainMenuScene(this); pauseMenuScene = new PauseMenuScene(this); highScoresScene = new HighScoresMenuScene(this); GameScene.setChildClickListener(this); setChildScene(mainMenuScene); } @Override public void back() { } @Override public boolean onMenuItemClicked(MenuScene scene, IMenuItem item, float localX, float localY) { switch (item.getID()) { case MAIN_MENU_NEW_GAME: clearChildScene(); setChildScene(GameScene.scene()); Game.getGameInstance().start(LevelFactory.getLevel(LevelType.SURVIVAL)); break; case MAIN_MENU_HIGH_SCORES: clearChildScene(); highScoresScene.update(); setChildScene(highScoresScene); break; case MAIN_MENU_EXIT: Game.getGameInstance().exit(); break; case PAUSE_MENU_RESUME: clearChildScene(); Game.getGameInstance().resume(); AudioHolder.getInstance().playGameMusic(GameScene.getInstance().getCurrentMusic(), true); setChildScene(GameScene.scene()); break; case PAUSE_MENU_MAIN_MENU: clearChildScene(); Game.getGameInstance().stop(); setChildScene(mainMenuScene); break; } return true; } @Override public void onChildClicked(int ID) { switch (ID) { case ClickCodes.GAME_SCENE_BACK: clearChildScene(); Game.getGameInstance().pause(); AudioHolder.getInstance().playMenuMusic(MenuMusicType.MENU); setChildScene(pauseMenuScene); break; case ClickCodes.GAME_ACTIVITY_BACK: getChildScene().back(); break; case ClickCodes.HIGH_SCORES_SCENE_BACK: clearChildScene(); setChildScene(mainMenuScene); break; } } @Override public void prepare(ILevel level) { } @Override public Priority getPriority() { return Priority.LOW; } } <file_sep>package pp.game.textures; public enum MenuTextureType { MAIN_MENU_EXIT("textures/menu/main_menu_exit.png"), MAIN_MENU_NEW_GAME("textures/menu/main_menu_new_game.png"), MAIN_MENU_HIGH_SCORES("textures/menu/main_menu_high_scores.png"), MAIN_MENU_BACKGROUND("textures/menu/main_menu_background.png"), PAUSE_MENU_MAIN_MENU("textures/menu/pause_menu_main_menu.png"), PAUSE_MENU_RESUME("textures/menu/pause_menu_resume.png"); private String assetPath; private MenuTextureType(String assetPath) { this.assetPath = assetPath; } public String getAssetPath() { return assetPath; } } <file_sep>package pp.game.audio; public enum SoundType { PLAYER_DEATH("player/sounds/death.ogg"); private String assetPath; private SoundType(String assetPath) { this.assetPath = assetPath; } public String getAssetPath() { return assetPath; } } <file_sep>package pp.game.entities; import org.andengine.entity.sprite.*; import com.badlogic.gdx.physics.box2d.*; abstract class DieableEntity extends BaseEntity implements IDieableEntity { private static final float FULL_HP_COEF = 0.8f; private static final float MEDIUM_HP_COEF = 0.5f; private volatile boolean isDead = false; private float currentHP; private float maxHP; private volatile HPState hpState; private Sprite aliveSprite; private Sprite deadSprite; private Body aliveBody; private Body deadBody; public DieableEntity() { } protected abstract void die(); private void adjustHPState() { float playerHPCoef = getCurrentHP() / getMaxHP(); if (playerHPCoef >= FULL_HP_COEF) { hpState = HPState.HIGH; } else if (playerHPCoef >= MEDIUM_HP_COEF) { hpState = HPState.MEDIUM; } else if (getCurrentHP() != 0) { hpState = HPState.LOW; } else { hpState = HPState.DEAD; } } @Override public float getCurrentHP() { return currentHP; } @Override public void adjustCurrentHP(float value) { this.currentHP += value; if (currentHP <= 0) { if (!isDead()) { die(); } isDead = true; currentHP = 0; } else if (currentHP > maxHP) { currentHP = maxHP; } adjustHPState(); } @Override public float getMaxHP() { return maxHP; } @Override public void setMaxHP(float maxHP) { this.maxHP = maxHP; adjustHPState(); } @Override public boolean isDead() { return isDead; } @Override public Sprite getAliveSprite() { return aliveSprite; } @Override public Sprite getDeadSprite() { return deadSprite; } @Override public Body getBody() { return isDead() ? getDeadBody() : getAliveBody(); } @Override public Sprite getShape() { return isDead() ? getDeadSprite() : getAliveSprite(); } @Override public HPState getHPState() { return hpState; } protected void setIdDead(boolean isDead) { this.isDead = isDead; } protected void setCurrentHP(float currentHP) { this.currentHP = currentHP; adjustHPState(); } protected void setAliveSprite(Sprite aliveSprite) { this.aliveSprite = aliveSprite; } protected void setDeadSprite(Sprite deadSprite) { this.deadSprite = deadSprite; } @Override public Body getAliveBody() { return aliveBody; } protected void setAliveBody(Body aliveBody) { this.aliveBody = aliveBody; } @Override public Body getDeadBody() { return deadBody; } protected void setDeadBody(Body deadBody) { this.deadBody = deadBody; } }
77dd547b8adabe3a7ff911ef41977816f065f02b
[ "Java" ]
37
Java
templatevk/EverGame
a2874489b349924b04cee6d2dd22ff940c0e5eb8
5307deb7bf909029f69135147613b4d2fdf57343
refs/heads/master
<file_sep> -- -- Base de datos: `indra_prueba` -- CREATE DATABASE IF NOT EXISTS `indra_prueba`; USE `indra_prueba`; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `clientes` -- CREATE TABLE `clientes` ( `id` int(11) NOT NULL, `nombre` varchar(30) NOT NULL, `apellidos` varchar(60) NOT NULL, `dni` varchar(10) NOT NULL, `direccion` varchar(250) NOT NULL, `telefono` varchar(20) NOT NULL, `email` varchar(60) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Estructura de tabla para la tabla `productos` -- CREATE TABLE `productos` ( `codigo` int(11) NOT NULL, `nombre` varchar(120) NOT NULL, `descripcion` varchar(250) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Estructura de tabla para la tabla `clientes_productos` -- CREATE TABLE `clientes_productos` ( `id` int(11) NOT NULL, `cod_cliente` int(11) NOT NULL, `cod_producto` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indices de la tabla `clientes` -- ALTER TABLE `clientes` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `clientes_productos` -- ALTER TABLE `clientes_productos` ADD PRIMARY KEY (`id`), ADD KEY `codcliente` (`cod_cliente`), ADD KEY `codproductos` (`cod_producto`); -- -- Indices de la tabla `productos` -- ALTER TABLE `productos` ADD PRIMARY KEY (`codigo`); -- -- AUTO_INCREMENT de la tabla `clientes` -- ALTER TABLE `clientes` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT de la tabla `clientes_productos` -- ALTER TABLE `clientes_productos` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37; -- -- Filtros para la tabla `clientes_productos` -- ALTER TABLE `clientes_productos` ADD CONSTRAINT `codcliente` FOREIGN KEY (`cod_cliente`) REFERENCES `clientes` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `codproductos` FOREIGN KEY (`cod_producto`) REFERENCES `productos` (`codigo`) ON DELETE CASCADE ON UPDATE CASCADE; COMMIT; <file_sep><?php include "../../config.php"; $NA = $_POST['NA']; $NL = $_POST['NL']; if( $stmt = $conn -> prepare("CALL pLibrosAutores (?, ?, @p1)") ){ $stmt -> bind_param("ss",$NA,$NL); $stmt -> execute(); $stmt = $conn -> prepare("SELECT @p1"); $stmt -> bind_result($p1); $stmt -> execute(); while($stmt -> fetch()){ if ($p1==0){ ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Exito!</strong> Se ha registrado el autor para ese libro. </div> <?php }else { ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Error!</strong> Hubo un error el autor para ese libro. CodError: <?php $p1 ?> </div> <?php }; } $stmt -> close(); } ?> <file_sep>-- phpMyAdmin SQL Dump -- version 4.3.1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jan 02, 2015 at 09:51 PM -- Server version: 5.5.35-1ubuntu1 -- PHP Version: 5.5.9-1ubuntu4 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `biodata` -- -- -------------------------------------------------------- -- -- Table structure for table `ajaxtrap` -- CREATE TABLE IF NOT EXISTS `ajaxtrap` ( `kode` int(5) NOT NULL, `nama` varchar(45) NOT NULL, `gender` varchar(15) NOT NULL, `phone` varchar(12) NOT NULL, `alamat` text NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; -- -- Dumping data for table `ajaxtrap` -- INSERT INTO `ajaxtrap` (`kode`, `nama`, `gender`, `phone`, `alamat`) VALUES (1, 'Ghazali', 'Laki-laki', '9876544', 'Sigli'), (2, 'Bukhari', 'Laki-laki', '8765544', 'Banda Aceh'), (3, 'Boyhaki', 'Laki-laki', '8765544', 'Grong-grong, Pidie'), (4, 'Monicha', 'Perempuan', '987655', 'Bambi, Pidie'); -- -- Indexes for dumped tables -- -- -- Indexes for table `ajaxtrap` -- ALTER TABLE `ajaxtrap` ADD PRIMARY KEY (`kode`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `ajaxtrap` -- ALTER TABLE `ajaxtrap` MODIFY `kode` int(5) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php include 'db.php'; $cod_cliente = $_POST['cod_cliente']; $cod_producto = $_POST['cod_producto']; $con = connectDB(); $stmt = $con->prepare("delete from clientes_productos where cod_cliente = ? and cod_producto = ?"); $stmt->bind_param('ii',$cod_cliente, $cod_producto ); if($stmt->execute()){ echo 1; }else{ echo 0; } mysqli_close($con); ?><file_sep><!--<NAME>--> <html lang="es"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" charset="utf8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="../logo.jpg" type="image/jpg" sizes="32x32"> <title>Biblioteca</title> <!-- Bootstrap --> <link href="../css/bootstrap.min.css" rel="stylesheet"> <style> .ir-arriba { background: rgba(0,0,0,0.5) url(../img/iconoarriba.png) no-repeat center center; display:none; padding:20px; font-size:20px; color:#fff; cursor:pointer; position: fixed; bottom:20px; right:20px; } </style> </head> <body onload="viewdata()"> <?php include('../menu.html'); ?> <div class="container"> <h3>Monedas</h3> </div> <p><br/></p> <div class="container"> <!-- Button trigger modal --> <span class="ir-arriba icon-arrow-up2"></span> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"> Añadir Moneda </button> <br/> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content" style="width:700px"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Añadir Moneda</h4> </div> <div class="modal-body"> <form> <div class="form-group"> <label style="margin:7px" for="NM">Nombre Moneda</label> <input class="form-control" type="text" id="NM" required> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button> <button type="button" id="save" class="btn btn-primary">Guardar Cambios</button> </div> </div> </div> </div> <div id="info"></div> <br/> <div id="viewdata"></div> </div> <!-- jQuery --> <script src="../js/jquery.min.js"></script> <script src="../js/bootstrap.min.js"></script> <script> $('#monedas').addClass("active"); function viewdata(){ $.ajax({ type: "GET", url: "php/getdata.php" }).done(function( data ) { $('#viewdata').html(data); }); } $('#save').click(function(){ var NM = $('#NM').val(); var datas="NM="+NM; document.getElementById("NM").value = ""; $.ajax({ type: "POST", url: "php/newdata.php", data: datas }).done(function( data ) { $('#info').html(data); viewdata(); }); }); function updatedata(str){ var id = str; var NM = $('#NM'+str).val(); var datas="NM="+NM; $.ajax({ type: "POST", url: "php/updatedata.php?id="+id, data: datas }).done(function( data ) { $('#info').html(data); viewdata(); }); } function deletedata(str){ var r = confirm("¿Deseas eliminar esta moneda (si esta siendo usada no se podrá borrar)?"); if (r == true) { var id = str; $.ajax({ type: "GET", url: "php/deletedata.php?id="+id }).done(function( data ) { $('#info').html(data); viewdata(); }); } else { } } $(document).ready(function(){ $('.ir-arriba').click(function(){ $('body, html').animate({ scrollTop: '0px' }, 300); }); $(window).scroll(function(){ if( $(this).scrollTop() > 0 ){ $('.ir-arriba').slideDown(300); } else { $('.ir-arriba').slideUp(300); } }); }); </script> </body> </html> <file_sep> <table class="table table-bordered table-hover"> <thead> <tr> <th>Autor</th> <th>Libro</th> <th width="20%">Editar</th> </tr> </thead> <tbody> <tr> <?php include "../../config.php"; $res = $conn->query("select * from libroAutores inner join autor on autor.codAutor = libroAutores.codAutor inner join libros on libros.codLibro = libroAutores.codLibro"); while ($row = $res->fetch_assoc()) { ?> <td><?php echo $row['nombreAutor']; ?></td> <td><?php echo $row['nombreLibro']; ?></td> <td style="color:black"> <a class="btn btn-danger btn-sm" onclick="deletedata('<?php echo $row['codAutor']; ?>', '<?php echo $row['codLibro']; ?>' )" ><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></a> <!-- Modal --> </td> </tr> <?php } ?> </tbody> </table> <file_sep><!--<NAME>--> <html lang="es"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" charset="utf8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="../logo.jpg" type="image/jpg" sizes="32x32"> <title>Biblioteca</title> <!-- Bootstrap --> <link href="../css/bootstrap.min.css" rel="stylesheet"> <style> .ir-arriba { background: rgba(0,0,0,0.5) url(../img/iconoarriba.png) no-repeat center center; display:none; padding:20px; font-size:20px; color:#fff; cursor:pointer; position: fixed; bottom:20px; right:20px; } </style> </head> <body onload="viewdata()"> <?php include('../menu.html'); ?> <div class="container"> <h3>Libro/Autor</h3> </div> <p><br/></p> <div class="container"> <!-- Button trigger modal --> <span class="ir-arriba icon-arrow-up2"></span> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"> Añadir Libro/Autor </button> <br/> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content" style="width:700px"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Añadir Libro/Autor</h4> </div> <div class="modal-body"> <form> <div class="form-group"> <td><label for="NA">Libro</label></td> <td> <select class="form-control" type="text" id="NA"> <?php include "../config.php"; $sqli="select * from libros"; $resi=mysqli_query($conn, $sqli); while($fila=mysqli_fetch_array($resi)){ echo "<option value=".$fila['ISBN'].">".$fila['nombreLibro']." (".$fila['ISBN'].")</option>"; } ?> </select> </td> </div> </form> <div class="form-group"> <td><label for="NL">Autor</label></td> <td> <select class="form-control" type="text" id="NL"> <?php include "../config.php"; $sqli="select * from autor"; $resi=mysqli_query($conn, $sqli); while($fila=mysqli_fetch_array($resi)){ echo "<option value=".$fila['codAutor'].">".$fila['nombreAutor']."</option>"; } ?> </select> </td> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button> <button type="button" id="save" class="btn btn-primary">Guardar Cambios</button> </div> </div> </div> </div> <div id="info"></div> <br/> <div id="viewdata"></div> </div> <!-- jQuery --> <script src="../js/jquery.min.js"></script> <script src="../js/bootstrap.min.js"></script> <script> $('#librosautores').addClass("active"); function viewdata(){ $.ajax({ type: "GET", url: "php/getdata.php" }).done(function( data ) { $('#viewdata').html(data); }); } $('#save').click(function(){ var NA = $('#NA').val(); var NL = $('#NL').val(); var datas="NA="+NA+"&NL="+NL document.getElementById("NA").value = ""; document.getElementById("NL").value = ""; $.ajax({ type: "POST", url: "php/newdata.php", data: datas }).done(function( data ) { $('#info').html(data); viewdata(); }); }); function deletedata(str,nl){ var r = confirm("¿Deseas eliminar el autor para este libro?"); if (r == true) { var id = str; var nl = nl; $.ajax({ type: "GET", url: "php/deletedata.php?id="+id+"&nl="+nl }).done(function( data ) { $('#info').html(data); viewdata(); }); } else { } } $(document).ready(function(){ $('.ir-arriba').click(function(){ $('body, html').animate({ scrollTop: '0px' }, 300); }); $(window).scroll(function(){ if( $(this).scrollTop() > 0 ){ $('.ir-arriba').slideDown(300); } else { $('.ir-arriba').slideUp(300); } }); }); </script> </body> </html> <file_sep><?php include 'db.php'; include 'producto.php'; $id = $_POST['id']; $con = connectDB(); $cod_cliente = NULL; $cod_producto = NULL; $nombre_producto = NULL; $resultado = []; $stmt = $con->prepare("select cp.cod_cliente, p.codigo, p.nombre from clientes_productos cp inner join productos p on cp.cod_producto = p.codigo where cp.cod_cliente = ?"); $stmt->bind_param('i',$id); if (!$stmt->execute()) { echo "Falló la ejecución: (" . $con->errno . ") " . $con->error; } if (!$stmt->bind_result($cod_cliente,$cod_producto, $nombre_producto)) { echo "Falló la vinculación de los parámetros de salida: (" . $stmt->errno . ") " . $stmt->error; } while ($stmt->fetch()) { array_push($resultado, array('cod_cliente' => $cod_cliente, 'cod_producto' => $cod_producto, 'nombre_producto' => $nombre_producto )); } mysqli_close($con); header('Content-Type: application/json'); echo json_encode($resultado); /* print_r($arr[0]->getCodigo());*/ ?><file_sep><!--<NAME>--> <html lang="es"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" charset="utf8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="../logo.jpg" type="image/jpg" sizes="32x32"> <title>Biblioteca</title> <!-- Bootstrap --> <link href="../css/bootstrap.min.css" rel="stylesheet"> <style> .ir-arriba { background: rgba(0,0,0,0.5) url(../img/iconoarriba.png) no-repeat center center; display:none; padding:20px; font-size:20px; color:#fff; cursor:pointer; position: fixed; bottom:20px; right:20px; } #elAutor{ display:flex; justify-content:center; margin-bottom:5px; } #autoro{ width:100%; margin-right:4px; } .autores{ width:100%; height:200px; overflow-y:scroll; } #anadir{ display:flex; align-items: center; justify-content: center; } </style> </head> <body onload="viewdata()"> <?php include('../menu.html'); ?> <div class="container"> <h3>Autores</h3> </div> <p><br/></p> <div class="container"> <!-- Button trigger modal --> <span class="ir-arriba icon-arrow-up2"></span> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"> Añadir libro </button> <br/> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content" style="width:700px"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Añadir Libro</h4> </div> <div class="modal-body"> <form> <div class="form-group"> <label style="margin:7px" for="NL">Nombre Libro</label> <input class="form-control" type="text" id="NL" placeholder="Nombre Libro" required> </div> <div class="form-group"> <label style="margin:7px" for="ISBN">ISBN</label> <input class="form-control " type="text" id="ISBN" placeholder="Nombre Libro" required> </div> <div class="form-group"> <label style="margin:7px" for="FI">Fecha Introducción:</label> <input class="form-control" type="date" id="FI" placeholder="Fecha Introduccion" required> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button> <button type="button" id="save" class="btn btn-primary">Guardar Cambios</button> </div> </div> </div> </div> <div id="info"></div> <br/> <div id="viewdata"></div> </div> <!-- jQuery --> <script src="../js/jquery.min.js"></script> <script src="../js/bootstrap.min.js"></script> <script> $('#libros').addClass("active"); function viewdata(){ $.ajax({ type: "GET", url: "php/getdata.php" }).done(function( data ) { $('#viewdata').html(data); }); } $('#save').click(function(){ var NL = $('#NL').val(); var ISBN = $('#ISBN').val(); var FI = $('#FI').val(); var datas="NL="+NL+"&ISBN="+ISBN+"&FI="+FI; document.getElementById("NL").value = ""; document.getElementById("ISBN").value = ""; document.getElementById("FI").value = ""; $.ajax({ type: "POST", url: "php/newdata.php", data: datas }).done(function( data ) { $('#info').html(data); viewdata(); }); }); function updatedata(str){ var id = str; var NL = $('#NL'+str).val(); var ISBN = $('#ISBN'+str).val(); var FI = $('#FI'+str).val(); var datas="NL="+NL+"&ISBN="+ISBN+"&FI="+FI; $.ajax({ type: "POST", url: "php/updatedata.php?id="+id, data: datas }).done(function( data ) { $('#info').html(data); viewdata(); }); } function deletedata(str){ var NL = $('#NL'+str).val(); var r = confirm("¿Deseas eliminar el libro " +NL+" ?"); if (r == true) { var id = str; $.ajax({ type: "GET", url: "php/deletedata.php?id="+id }).done(function( data ) { $('#info').html(data); viewdata(); }); } else { } } $(document).ready(function(){ $('.ir-arriba').click(function(){ $('body, html').animate({ scrollTop: '0px' }, 300); }); $(window).scroll(function(){ if( $(this).scrollTop() > 0 ){ $('.ir-arriba').slideDown(300); } else { $('.ir-arriba').slideUp(300); } }); }); </script> </body> </html> <file_sep><?php class Cliente { protected $id; protected $nombre; protected $apellidos; protected $dni; protected $direccion; protected $telefono; protected $email; public function __construct($id,$nombre,$apellidos,$dni,$direccion,$telefono,$email) { $this->id = $id; $this->nombre = $nombre; $this->apellidos = $apellidos; $this->dni = $dni; $this->direccion = $direccion; $this->telefono = $telefono; $this->email = $email; } public function getId(){ return $this->id; } public function getNombre(){ return $this->nombre; } public function getApellidos(){ return $this->apellidos; } public function getDni(){ return $this->dni; } public function getDireccion(){ return $this->direccion; } public function getTelefono(){ return $this->telefono; } public function getEmail(){ return $this->email; } public function setNombre($nombre){ $this->nombre = $nombre; } public function setApellidos($apellidos){ $this->apellidos = $apellidos; } public function setDni($dni){ $this->dni = $dni; } public function setDireccion($direccion){ $this->direccion = $direccion; } public function setTelefono($telefono){ $this->telefono = $telefono; } public function setEmail($email){ $this->email = $email; } public function getObject(){ return $this->id."|".$this->nombre." ".$this->apellidos." ".$this->dni." ".$this->direccion." ".$this->telefono." ".$this->email; } } ?><file_sep><?php header('Location: productos.html'); ?><file_sep><?php include('config.php'); $peticion="call pListaEjemplares(?);"; if($stmt = $conn -> prepare($peticion)) { $ISBN = "paco"; $stmt->bind_param( 's', $ISBN); $stmt->execute(); $stmt ->bind_result($campo1, $campo2,$campo3,$campo4,$campo5); while($stmt->fetch()){ echo $campo1,$campo2,$campo3,$campo4; } $stmt->close(); } ?> <?php include('config.php'); $ISBN = "75-845-3215-P"; if( $stmt = $conn -> prepare("CALL pCantidadEjemplares (?, @p1, @p2);") ){ $stmt -> bind_param("s",$ISBN); $stmt -> execute(); $stmt = $conn -> prepare("SELECT @p1 , @p2"); $stmt -> bind_result($p1,$p2); $stmt -> execute(); while($stmt -> fetch()){ echo $p1." "; echo $p2; } $stmt -> close(); ?> <?php include('config.php'); $ISBN = "75-845-3215-P"; $COD = "A002"; if( $stmt = $conn -> prepare("CALL pLibrosAutores (?, ?, @p1)") ){ $stmt -> bind_param("ss",$ISBN,$COD); $stmt -> execute(); $stmt = $conn -> prepare("SELECT @p1"); $stmt -> bind_result($p1); $stmt -> execute(); while($stmt -> fetch()){ echo $p1; } $stmt -> close(); } ?> <?php include('config.php'); $COD = "<NAME>"; if( $stmt = $conn -> prepare("Select fnumAutorLibro(?)") ){ $stmt -> bind_param("s",$COD); $stmt -> bind_result($CODIGO); $stmt -> execute(); while($stmt -> fetch()){ echo $CODIGO; } $stmt -> close(); } ?> <file_sep><?php function connectDB(){ //Configuracion de la base de datos $url = 'localhost'; //url $user = 'root'; //usuario $pass = ''; //<PASSWORD> $db = 'indra_prueba2'; //nombre db $con = null; try { $con = new mysqli($url, $user, $pass,$db); //conexion a la bd if ($con->connect_errno) { printf("Falló la conexión: %s\n", $con->connect_error); exit(); } } catch(PDOException $e){ print "Error: ". $e->getMessage()."<br/>"; //mensaje de error die(); } return $con; } ?> <file_sep><?php include 'db.php'; include 'producto.php'; $arr= array(); $con = connectDB(); $i=0; $sql = $con->query("select * from productos order by codigo asc"); while ($row = $sql->fetch_assoc()) { $producto = new Producto($row['codigo'], $row['nombre'], $row['descripcion']); $arr[$i] = array('codigo'=> $producto->getCodigo(), 'nombre'=> $producto->getNombre(), 'descripcion'=>$producto->getDescripcion() ); $i++; } mysqli_close($con); header('Content-Type: application/json'); echo json_encode($arr); ?><file_sep><?php include 'db.php'; include 'cliente.php'; $arr= array(); $con = connectDB(); $i=0; $sql = $con->query("select * from clientes order by id asc"); while ($row = $sql->fetch_assoc()) { $producto = new Cliente($row['id'], $row['nombre'], $row['apellidos'], $row['dni'], $row['direccion'], $row['telefono'], $row['email'] ); $arr[$i] = array('id'=> $producto->getId(), 'nombre'=> $producto->getNombre(), 'apellidos'=>$producto->getApellidos(), 'dni'=>$producto->getDni(), 'direccion'=>$producto->getDireccion(), 'telefono'=>$producto->getTelefono(), 'email'=>$producto->getEmail() ); $i++; } header('Content-Type: application/json'); echo json_encode($arr); ?><file_sep> <table class="table table-bordered table-hover"> <thead> <tr> <th width="50%">Nombre del Libro</th> <th>ISBN</th> <th>Fecha Introducion</th> <th>Editar</th> </tr> </thead> <tbody> <tr> <?php include "../../config.php"; $res = $conn->query("select * from libros order by codLibro desc"); while ($row = $res->fetch_assoc()) { ?> <td><?php echo $row['nombreLibro']; ?></td> <td><?php echo $row['ISBN']; ?></td> <td><?php echo $row['fechaIntro']; ?></td> <td style="color:black"> <a class="btn btn-warning btn-sm" data-toggle="modal" data-target="#myModal<?php echo $row['codLibro']; ?>"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a> <a class="btn btn-danger btn-sm" onclick="deletedata('<?php echo $row['codLibro'] ?>')" ><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></a> <!-- Modal --> <div class="modal fade" id="myModal<?php echo $row['codLibro']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel<?php echo $row['codLibro']; ?>" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content" style="width:700px"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel<?php echo $row['codLibro']; ?>">Editar Datos</h4> </div> <div class="modal-body"> <form> <table> <div class="form-group"> <label style="margin:7px" for="CA">Nombre Libro: </label> <input class="form-control" type="text" id="NL<?php echo $row['codLibro']; ?>" value="<?php echo $row['nombreLibro']; ?>" required> </div> <div class="form-group"> <label style="margin:7px" for="NA">ISBN: </label> <input class="form-control" type="text" id="ISBN<?php echo $row['codLibro']; ?>" value="<?php echo $row['ISBN']; ?>" required> </div> <div class="form-group"> <label style="margin:7px" for="NA">Fecha de Introducción: </label> <input class="form-control" type="date" id="FI<?php echo $row['codLibro']; ?>" value="<?php echo $row['fechaIntro']; ?>" required> </div> </tr> </table> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button> <button type="button" onclick="updatedata('<?php echo $row['codLibro']; ?>')" class="btn btn-primary">Guardar Cambios</button> </div> </div> </div> </div> </td> </tr> <?php } ?> </tbody> </table> <file_sep><?php class Producto { protected $codigo; protected $nombre; protected $descripcion; public function __construct($codigo,$nombre,$descripcion) { $this->codigo = $codigo; $this->nombre = $nombre; $this->descripcion = $descripcion; } public function getCodigo(){ return $this->codigo; } public function getNombre(){ return $this->nombre; } public function getDescripcion(){ return $this->descripcion; } public function setNombre($nombre){ $this->nombre = $nombre; } public function setDescripcion($descripcion){ $this->descripcion = $descripcion; } public function getObject(){ return $this->nombre." ".$this->descripcion." ".$this->codigo; } } ?><file_sep><?php include "../../config.php"; if(isset($_GET['id'])){ $id = $_GET['id']; $NL = $_POST['NL']; $ISBN = $_POST['ISBN']; $FI = $_POST['FI']; $stmt = $conn->prepare("update libros set nombreLibro=?,ISBN=?,fechaIntro=? where codLibro=?"); $stmt->bind_param('sssd', $NL,$ISBN,$FI,$id); if($stmt->execute()){ ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Exito!</strong> Se han actualizado los datos. </div> <?php } else{ ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Error!</strong> Se ha producido un error. </div> <?php } } else{ ?> <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Alerta!</strong>Revise los datos </div> <?php } ?> <file_sep><?php include 'db.php'; $codigo = $_POST['codigo']; $con = connectDB(); $stmt = $con->prepare("delete from productos where codigo=?"); $stmt->bind_param('s',$codigo); if($stmt->execute()){ echo 1; }else{ if ($stmt->error) { printf("Errormessage: %s\n", $stmt->mysqli_stmt_error); } echo 0; } mysqli_close($con); /* print_r($arr[0]->getCodigo());*/ ?><file_sep><?php include "../../config.php"; if(isset($_GET['id'])){ $id = $_GET['id']; $stmt = $conn->prepare("delete from autor where codAutor=?"); $stmt->bind_param('s', $id); if($stmt->execute()){ ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Exito!</strong> Se ha eliminado el autor con exito. </div> <?php } else{ ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Error!</strong> Se ha producido un error al eliminar. </div> <?php } } else{ ?> <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Alerta!</strong> </div> <?php } ?> <file_sep><?php header('Location: Autores/'); exit; ?> <file_sep><?php include "../../config.php"; $NL = $_POST['NL']; $ISBN = $_POST['ISBN']; $FI = $_POST['FI']; $stmt = $conn->prepare("INSERT INTO libros VALUES ('',?,?,?)"); $stmt->bind_param('sss', $NL,$ISBN,$FI); if($stmt->execute()){ ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Exito!</strong> Se ha registrado el libro. </div> <?php } else{ ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Error!</strong> Hubo un error al registrar el libro, revise sus datos. </div> <?php } ?> <file_sep><?php include 'db.php'; $codigo = $_POST['codigo']; $nombre = $_POST['nombre']; $descripcion = $_POST['descripcion']; $con = connectDB(); $stmt = $con->prepare("update productos set nombre=?,descripcion=? where codigo=?"); $stmt->bind_param('sss', $nombre,$descripcion,$codigo); if($stmt->execute()){ echo 1; }else{ echo 0; } mysqli_close($con); /* print_r($arr[0]->getCodigo());*/ ?><file_sep><?php include 'db.php'; include 'producto.php'; $nombre = $_POST['nombre']; $apellidos = $_POST['apellidos']; $dni = $_POST['dni']; $direccion = $_POST['direccion']; $telefono = $_POST['telefono']; $email = $_POST['email']; $con = connectDB(); $stmt = $con->prepare("insert into clientes values('',?,?,?,?,?,?)"); $stmt->bind_param('ssssss', $nombre, $apellidos, $dni, $direccion, $telefono, $email); if($stmt->execute()){ echo 1; }else{ echo 0; printf("Error: %s.\n", $stmt->error); } mysqli_close($con); ?><file_sep><?php include "../../config.php"; $LB = $_POST['LB']; $IM = $_POST['IM']; $MN = $_POST['MN']; $stmt = $conn->prepare("INSERT INTO ejemplares VALUES ('',?,?,?)"); $stmt->bind_param('dsd', $LB,$IM,$MN); if($stmt->execute()){ ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Exito!</strong> Se ha registrado el ejemplar. </div> <?php } else{ ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Error!</strong> Hubo un error al registrar el ejemplar. </div> <?php } ?> <file_sep><?php include 'db.php'; include 'producto.php'; $id = $_POST['id']; $con = connectDB(); $cod_producto = NULL; $nombre_producto = NULL; $resultado = []; $stmt = $con->prepare("SELECT codigo,nombre FROM productos WHERE codigo Not IN (SELECT Cod_producto FROM clientes_productos where cod_cliente = ?);"); $stmt->bind_param('i',$id); if (!$stmt->execute()) { echo "Falló la ejecución: (" . $con->errno . ") " . $con->error; } if (!$stmt->bind_result($cod_producto, $nombre_producto)) { echo "Falló la vinculación de los parámetros de salida: (" . $stmt->errno . ") " . $stmt->error; } while ($stmt->fetch()) { array_push($resultado, array('cod_cliente' => $id, 'cod_producto' => $cod_producto, 'nombre_producto' => $nombre_producto )); } mysqli_close($con); header('Content-Type: application/json'); echo json_encode($resultado); /* print_r($arr[0]->getCodigo());*/ ?><file_sep> <table class="table table-bordered table-hover"> <thead> <tr> <th width="20%">Nombre del Libro</th> <th>Importe</th> <th>Moneda</th> <th>Editar</th> </tr> </thead> <tbody> <tr> <?php include "../../config.php"; $res = $conn->query("select codEjemplar, ejemplares.codLibro,importe,tipoMoneda,nombreLibro,ISBN,fechaIntro,codMoneda,nombreMoneda from ejemplares inner join libros on ejemplares.codLibro = libros.codLibro inner join monedas on ejemplares.tipoMoneda = monedas.codMoneda order by codEjemplar desc"); while ($row = $res->fetch_assoc()) { ?> <td><?php echo $row['nombreLibro']; ?></td> <td><?php echo $row['importe']; ?></td> <td><?php echo $row['nombreMoneda']; ?></td> <td style="color:black"> <a class="btn btn-warning btn-sm" data-toggle="modal" data-target="#myModal<?php echo $row['codEjemplar']; ?>"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a> <a class="btn btn-danger btn-sm" onclick="deletedata('<?php echo $row['codEjemplar']; ?>')" ><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></a> <!-- Modal --> <div class="modal fade" id="myModal<?php echo $row['codEjemplar']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel<?php echo $row['codEjemplar']; ?>" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content" style="width:700px"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel<?php echo $row['codEjemplar']; ?>">Editar Datos</h4> </div> <div class="modal-body"> <form> <table> <label style="margin:7px" for="LB">Nombre del libro: </label> <select class="form-control" type="text" id="LB<?php echo $row['codEjemplar'];?>" value="<?php echo $row['codLibro']; ?>" > <?php $sqli="select * from libros"; $resi=mysqli_query($conn, $sqli); while($fila=mysqli_fetch_array($resi)){ if($fila['codLibro']==$row['codLibro']){ echo "<option value=".$fila['codLibro']." selected>".$fila['nombreLibro']." (".$fila['ISBN'].")</option>"; }else{ echo "<option value=".$fila['codLibro'].">".$fila['nombreLibro']." (".$fila['ISBN'].")</option>"; } } ?> </select> <div class="form-group"> <label style="margin:7px" for="IM">Importe: </label> <input class="form-control" type="text" id="IM<?php echo $row['codEjemplar']; ?>" value="<?php echo $row['importe']; ?>"> </div> <label style="margin:7px" for="MN">Moneda: </label> <select class="form-control" type="text" id="MN<?php echo $row['codEjemplar'];?>" value="<?php echo $row['nombreMoneda'];?>"> <?php $sqli="select * from monedas"; $resi=mysqli_query($conn, $sqli); while($fila=mysqli_fetch_array($resi)){ if($fila['codMoneda']==$row['tipoMoneda']){ echo "<option value=".$fila['codMoneda']." selected>".$fila['nombreMoneda']."</option>"; }else{ echo "<option value=".$fila['codMoneda'].">".$fila['nombreMoneda']."</option>"; } } ?> </select> </tr> </table> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button> <button type="button" onclick="updatedata('<?php echo $row['codEjemplar']; ?>')" class="btn btn-primary">Guardar Cambios</button> </div> </div> </div> </div> </td> </tr> <?php } ?> </tbody> </table> <file_sep><?php include "../../config.php"; if(isset($_GET['id'])){ $id = $_GET['id']; $NM = $_POST['NM']; $stmt = $conn->prepare("update monedas set nombreMoneda=? where codMoneda=?"); $stmt->bind_param('sd', $NM,$id); if($stmt->execute()){ ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Exito!</strong> Se han actualizado los datos. </div> <?php } else{ ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Error!</strong> Se ha producido un error. </div> <?php } } else{ ?> <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Alerta!</strong>Revise los datos </div> <?php } ?> <file_sep><?php include "../../config.php"; $CA = $_POST['CA']; $NA = $_POST['NA']; $stmt = $conn->prepare("INSERT INTO autor VALUES (?,?)"); $stmt->bind_param('ss', $CA,$NA); if($stmt->execute()){ ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Exito!</strong> Se ha registrado el autor. </div> <?php } else{ ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Error!</strong> Hubo un error al registrar el autor. </div> <?php } ?> <file_sep><?php header('Location: ../Autores/'); exit; ?> <file_sep><?php include 'db.php'; $id = $_POST['id']; $con = connectDB(); $stmt = $con->prepare("delete from clientes where id=?"); $stmt->bind_param('s',$id); if($stmt->execute()){ echo 1; }else{ echo 0; } mysqli_close($con); ?><file_sep># PHP-Prueba Para desplegar el proyecto se necesitará servidores de: 1. **Apache** 2. **Mysql** El proyecto incluye un archivo sql (**bd_PHP.sql**) que tendrás que importar en el servidor Mysql. En la carpeta PHP hay un archivo llamado bd.php en el cual puedes configurar las credenciales de la bd por si fuera necesario. También incluye un archivo JSON (productos.json) el cual se puede utilizar para insertar los productos desde la pagina de productos. <file_sep> var productos=[]; var table; $(document).ready(()=>{ getProducts(); this.table = $("#dtproductos").DataTable(); $('#file-input').on('change',readFile); $('#updateButton').click(()=>updateProducts()); }); function getProducts(){ //Obtencion de los productos $.getJSON("../php/getProductos.php").done((response)=>{ this.productos = response; this.productos.length this.productos.forEach(element => { this.table.row.add( [ element.codigo, element.nombre, element.descripcion, "<button class='btn btn-dark' onClick='updateModalProducts(["+element.codigo+",\""+element.nombre+"\",\""+element.descripcion+"\"])'>✏</button> "+ "<button class='btn btn-dark' onClick='deleteProducts("+element.codigo+")'>🗑</button>" ]) .draw() .node(); }); }); } $(()=>{$("#json-url-button").click( ()=>{ //Insertar productos mediante url var TXT_URL = $("#input-url").val(); $.ajax ( { url : TXT_URL, dataType: "text", success : function (data) { setProducts(data); } } ); $("#input-url").val(''); }); }); function readFile(e) { //Leer archivo json var file = e.target.files[0]; if (file) { var lector = new FileReader(); lector.onload = function(e) { var content = e.target.result; setProducts(content); } }; lector.readAsText(file); $('#file-input').wrap('<form>').closest('form').get(0).reset(); $('#file-input').unwrap(); } function deleteProducts(codigo){ //Eliminar el producto seleccionado var conf = confirm("Estas seguro de eliminar este campo"); if (conf == true) { txt = "You pressed OK!"; $.ajax({ data: {codigo : codigo}, url: '../php/deleteProductos.php', type: 'post', beforeSend: function () { }, success: (response)=>{ if(response==1){ $('#alerts').html( "<div class='alert alert-success' role='alert'>"+ "<button type='button' class='close' data-dismiss='alert'>x</button> Los datos han sido borrados correctamente</div>" ) }else{ $('#alerts').html( "<div class='alert alert-danger' role='alert'>"+ "<button type='button' class='close' data-dismiss='alert'>x</button> Ha ocurrido un error a borrar los datos </div>" ) } alertAnimation(); this.table.rows().remove().draw(); alertAnimation(); getProducts(); }, error: (response)=>{ $('#alerts').html( "<div class='alert alert-danger' role='alert'>"+ "<button type='button' class='close' data-dismiss='alert'>x</button> Se ha producido un error: "+response+"</div>" ) this.table.rows().remove().draw(); alertAnimation(); getProducts(); } }); } } function setProducts(products){ //Añadir productos $.ajax({ data: {products : products}, url: '../php/setProductos.php', type: 'post', beforeSend: function () { }, success: (response)=>{ if(response != 0){ $('#alerts').html( "<div class='alert alert-success' role='alert'>"+ "<button type='button' class='close' data-dismiss='alert'>x</button> Los datos han sido añadidos correctamente</div>" ) }else{ $('#alerts').html( "<div class='alert alert-danger' role='alert'>"+ "<button type='button' class='close' data-dismiss='alert'>x</button> Ha ocurrido un error al insertar los datos </div>" ) } alertAnimation(); this.table.rows().remove().draw(); $('#addProducts').modal('toggle'); alertAnimation(); getProducts(); }, error: (response)=>{ $('#alerts').html( "<div class='alert alert-danger' role='alert'>"+ "<button type='button' class='close' data-dismiss='alert'>x</button> Se ha producido un error: "+response+"</div>" ) this.table.rows().remove().draw(); $('#addProducts').modal('toggle'); alertAnimation(); getProducts(); } }); } var activeProduct; function updateModalProducts(product){ //Abrir modal editar productos this.activeProduct = product; $("#actCodigo").val(product[0]) $("#actNombre").val(product[1]) $("#actDescripcion").val(product[2]) $("#updateProducts").modal(); } function updateProducts(){ //Actualizar productos this.activeProduct[1] = $("#actNombre").val(); this.activeProduct[2] = $("#actDescripcion").val(); $.ajax({ data: {codigo : this.activeProduct[0] ,nombre : this.activeProduct[1] ,descripcion : this.activeProduct[2] }, url: '../php/updateProductos.php', type: 'post', beforeSend: function () { }, success: (response)=>{ if(response==1){ $('#alerts').html( "<div class='alert alert-success' role='alert'>"+ "<button type='button' class='close' data-dismiss='alert'>x</button> Los datos han sido actualizados correctamente</div>" ) }else{ $('#alerts').html( "<div class='alert alert-danger' role='alert'>"+ "<button type='button' class='close' data-dismiss='alert'>x</button> Ha ocurrido un error al actualizar los datos </div>" ) } alertAnimation(); this.table.rows().remove().draw(); $('#updateProducts').modal('toggle'); alertAnimation(); getProducts(); }, error: (response)=>{ $('#alerts').html( "<div class='alert alert-danger' role='alert'>"+ "<button type='button' class='close' data-dismiss='alert'>x</button> Se ha producido un error: "+response+"</div>" ) this.table.rows().remove().draw(); $('#updateProducts').modal('toggle'); alertAnimation(); getProducts(); } }); } function alertAnimation(){ //animaciones de feedback $("#alerts").fadeTo(2000, 500).slideUp(500, function(){ $("#alerts").slideUp(500); })}; <file_sep><?php include 'db.php'; include 'producto.php'; $productos = $_POST['products']; $con = connectDB(); $arr= array(); $productos_array = json_decode($productos, true); foreach ($productos_array as $id => $producto) { $arr[$id]= new Producto($producto['codigo'], $producto['nombre'], $producto['descripcion']); } foreach($arr as $id => $producto){ $codigo = $producto->getCodigo(); $nombre = $producto->getNombre(); $descripcion = $producto->getDescripcion(); $stmt = $con->prepare("insert into productos values(?,?,?)"); $stmt->bind_param('sss',$codigo, $nombre, $descripcion); if($stmt->execute()){ echo 1; }else{ echo 0; } } mysqli_close($con); /* print_r($arr[0]->getCodigo());*/ ?><file_sep><?php include 'db.php'; $id = $_POST['id']; $nombre = $_POST['nombre']; $apellidos = $_POST['apellidos']; $dni = $_POST['dni']; $direccion = $_POST['direccion']; $telefono = $_POST['telefono']; $email = $_POST['email']; $con = connectDB(); $stmt = $con->prepare("update clientes set nombre=?,apellidos=?,dni=?,direccion=?,telefono=?,email=? where id=?"); $stmt->bind_param('ssssssi', $nombre,$apellidos,$dni,$direccion,$telefono,$email,$id); if($stmt->execute()){ echo 1; }else{ echo 0; } mysqli_close($con); ?><file_sep><?php include "../../config.php"; $NM = $_POST['NM']; if($_POST['NM']==""){ echo "No se permiten valores vacios"; }else{ $stmt = $conn->prepare("INSERT INTO monedas VALUES ('',?)"); $stmt->bind_param('s', $NM); if($stmt->execute()){ ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Exito!</strong> Se ha registrado la moneda. </div> <?php } else{ ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Error!</strong> Hubo un error al registrar la moneda. </div> <?php }} ?> <file_sep><?php include "../../config.php"; if(isset($_GET['id'])){ $id = $_GET['id']; $CA = $_POST['CA']; $NA = $_POST['NA']; $stmt = $conn->prepare("update autor set codAutor=?,nombreAutor=? where codAutor=?"); $stmt->bind_param('sss', $CA,$NA,$id); if($stmt->execute()){ ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Exito!</strong> Se han actualizado los datos. </div> <?php } else{ ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Error!</strong> Se ha producido un error. </div> <?php } } else{ ?> <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Alerta!</strong>Revise los datos </div> <?php } ?> <file_sep><?php include "../../config.php"; if(isset($_GET['id'])){ $id = $_GET['id']; $LB = $_POST['LB']; $IM = $_POST['IM']; $MN = $_POST['MN']; $stmt = $conn->prepare("update ejemplares set codLibro=?,importe=?,tipoMoneda=? where codEjemplar=?"); $stmt->bind_param('dsdd', $LB,$IM,$MN,$id); if($stmt->execute()){ ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Exito!</strong> Se han actualizado los datos. </div> <?php } else{ ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Error!</strong> Se ha producido un error. </div> <?php } } else{ ?> <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Alerta!</strong>Revise los datos </div> <?php } ?>
50cffaa07021831a59989644ea2136ba5e10e26b
[ "Markdown", "SQL", "JavaScript", "PHP" ]
38
SQL
HMLuis94/PHP-Prueba
6e3074be19de02db4051bff406ca93b97425e608
b294c8c1c9e69ad78455a84f65fbb366fbf0ad03
refs/heads/master
<file_sep>[package] name = "sqlx-adapter" version = "0.2.6" authors = ["<NAME> <<EMAIL>>","<NAME> <<EMAIL>>"] edition = "2018" license = "Apache-2.0" description = "Sqlx adapter for casbin-rs" homepage= "https://github.com/casbin-rs/sqlx-adapter" readme= "README.md" [dependencies] casbin = { version = "1.1.2", default-features = false, features = ["incremental"] } sqlx = {version = "0.3.5", default-features = false, features = [ "macros" ]} async-trait = "0.1.36" dotenv = { version = "0.15.0", default-features = false } tokio = { version = "0.2.21", default-features = false, optional = true } async-std = { version = "1.6.2", default-features = false, optional = true } [features] default = ["postgres", "runtime-async-std"] #databases postgres = ["sqlx/postgres"] mysql = ["sqlx/mysql"] #async runtime runtime-tokio = ["casbin/runtime-tokio", "sqlx/runtime-tokio"] runtime-async-std = ["casbin/runtime-async-std", "sqlx/runtime-async-std"] [dev-dependencies] async-std = { version = "1.6.2", features = [ "attributes" ] } tokio = { version = "0.2.21", features = [ "full" ] } <file_sep>use crate::Error; use casbin::{error::AdapterError, Error as CasbinError, Result}; use sqlx::{error::Error as SqlxError, pool::Pool}; use crate::models::{CasbinRule, NewCasbinRule}; #[cfg(feature = "postgres")] pub type Connection = sqlx::PgConnection; #[cfg(feature = "mysql")] pub type Connection = sqlx::MySqlConnection; type ConnectionPool = Pool<Connection>; #[cfg(feature = "postgres")] pub async fn new(mut conn: &ConnectionPool) -> Result<u64> { sqlx::query!( "CREATE TABLE IF NOT EXISTS casbin_rules ( id SERIAL PRIMARY KEY, ptype VARCHAR NOT NULL, v0 VARCHAR NOT NULL, v1 VARCHAR NOT NULL, v2 VARCHAR NOT NULL, v3 VARCHAR NOT NULL, v4 VARCHAR NOT NULL, v5 VARCHAR NOT NULL, CONSTRAINT unique_key_sqlx_adapter UNIQUE(ptype, v0, v1, v2, v3, v4, v5) ); " ) .execute(&mut conn) .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err))))) } #[cfg(feature = "mysql")] pub async fn new(mut conn: &ConnectionPool) -> Result<u64> { sqlx::query!( "CREATE TABLE IF NOT EXISTS casbin_rules ( id INT NOT NULL AUTO_INCREMENT, ptype VARCHAR(12) NOT NULL, v0 VARCHAR(128) NOT NULL, v1 VARCHAR(128) NOT NULL, v2 VARCHAR(128) NOT NULL, v3 VARCHAR(128) NOT NULL, v4 VARCHAR(128) NOT NULL, v5 VARCHAR(128) NOT NULL, PRIMARY KEY(id), CONSTRAINT unique_key_sqlx_adapter UNIQUE(ptype, v0, v1, v2, v3, v4, v5) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;", ) .execute(&mut conn) .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err))))) } #[cfg(feature = "postgres")] pub async fn remove_policy(mut conn: &ConnectionPool, pt: &str, rule: Vec<String>) -> Result<bool> { let rule = normalize_casbin_rule(rule, 0); sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = $1 AND v0 = $2 AND v1 = $3 AND v2 = $4 AND v3 = $5 AND v4 = $6 AND v5 = $7", pt.to_string(), rule[0], rule[1], rule[2], rule[3], rule[4], rule[5] ) .execute(&mut conn) .await .map(|n| n == 1) .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err))))) } #[cfg(feature = "mysql")] pub async fn remove_policy(mut conn: &ConnectionPool, pt: &str, rule: Vec<String>) -> Result<bool> { let rule = normalize_casbin_rule(rule, 0); sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = ? AND v0 = ? AND v1 = ? AND v2 = ? AND v3 = ? AND v4 = ? AND v5 = ?", pt.to_string(), rule[0], rule[1], rule[2], rule[3], rule[4], rule[5] ) .execute(&mut conn) .await .map(|n| n == 1) .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err))))) } #[cfg(feature = "postgres")] pub async fn remove_policies( conn: &ConnectionPool, pt: &str, rules: Vec<Vec<String>>, ) -> Result<bool> { let mut transaction = conn .begin() .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; for rule in rules { let rule = normalize_casbin_rule(rule, 0); sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = $1 AND v0 = $2 AND v1 = $3 AND v2 = $4 AND v3 = $5 AND v4 = $6 AND v5 = $7", pt.to_string(), rule[0], rule[1], rule[2], rule[3], rule[4], rule[5] ) .execute(&mut transaction) .await .and_then(|n| { if n == 1 { Ok(true) } else { Err(SqlxError::RowNotFound) } }) .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; } transaction .commit() .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; Ok(true) } #[cfg(feature = "mysql")] pub async fn remove_policies( conn: &ConnectionPool, pt: &str, rules: Vec<Vec<String>>, ) -> Result<bool> { let mut transaction = conn .begin() .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; for rule in rules { let rule = normalize_casbin_rule(rule, 0); sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = ? AND v0 = ? AND v1 = ? AND v2 = ? AND v3 = ? AND v4 = ? AND v5 = ?", pt.to_string(), rule[0], rule[1], rule[2], rule[3], rule[4], rule[5] ) .execute(&mut transaction) .await .and_then(|n| { if n == 1 { Ok(true) } else { Err(SqlxError::RowNotFound) } }) .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; } transaction .commit() .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; Ok(true) } #[cfg(feature = "postgres")] pub async fn remove_filtered_policy( mut conn: &ConnectionPool, pt: &str, field_index: usize, field_values: Vec<String>, ) -> Result<bool> { let field_values = normalize_casbin_rule(field_values, field_index); let boxed_query = if field_index == 5 { Box::new(sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = $1 AND (v5 is NULL OR v5 = $2)", pt.to_string(), field_values[5] )) } else if field_index == 4 { Box::new(sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = $1 AND (v4 is NULL OR v4 = $2) AND (v5 is NULL OR v5 = $3)", pt.to_string(), field_values[4], field_values[5] )) } else if field_index == 3 { Box::new(sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = $1 AND (v3 is NULL OR v3 = $2) AND (v4 is NULL OR v4 = $3) AND (v5 is NULL OR v5 = $4)", pt.to_string(), field_values[3], field_values[4], field_values[5] )) } else if field_index == 2 { Box::new(sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = $1 AND (v2 is NULL OR v2 = $2) AND (v3 is NULL OR v3 = $3) AND (v4 is NULL OR v4 = $4) AND (v5 is NULL OR v5 = $5)", pt.to_string(), field_values[2], field_values[3], field_values[4], field_values[5] )) } else if field_index == 1 { Box::new(sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = $1 AND (v1 is NULL OR v1 = $2) AND (v2 is NULL OR v2 = $3) AND (v3 is NULL OR v3 = $4) AND (v4 is NULL OR v4 = $5) AND (v5 is NULL OR v5 = $6)", pt.to_string(), field_values[1], field_values[2], field_values[3], field_values[4], field_values[5] )) } else { Box::new(sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = $1 AND (v0 is NULL OR v0 = $2) AND (v1 is NULL OR v1 = $3) AND (v2 is NULL OR v2 = $4) AND (v3 is NULL OR v3 = $5) AND (v4 is NULL OR v4 = $6) AND (v5 is NULL OR v5 = $7)", pt.to_string(), field_values[0], field_values[1], field_values[2], field_values[3], field_values[4], field_values[5] )) }; boxed_query .execute(&mut conn) .await .map(|n| n >= 1) .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err))))) } #[cfg(feature = "mysql")] pub async fn remove_filtered_policy( mut conn: &ConnectionPool, pt: &str, field_index: usize, field_values: Vec<String>, ) -> Result<bool> { let field_values = normalize_casbin_rule(field_values, field_index); let boxed_query = if field_index == 5 { Box::new(sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = ? AND (v5 is NULL OR v5 = ?)", pt.to_string(), field_values[5] )) } else if field_index == 4 { Box::new(sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = ? AND (v4 is NULL OR v4 = ?) AND (v5 is NULL OR v5 = ?)", pt.to_string(), field_values[4], field_values[5] )) } else if field_index == 3 { Box::new(sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = ? AND (v3 is NULL OR v3 = ?) AND (v4 is NULL OR v4 = ?) AND (v5 is NULL OR v5 = ?)", pt.to_string(), field_values[3], field_values[4], field_values[5] )) } else if field_index == 2 { Box::new(sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = ? AND (v2 is NULL OR v2 = ?) AND (v3 is NULL OR v3 = ?) AND (v4 is NULL OR v4 = ?) AND (v5 is NULL OR v5 = ?)", pt.to_string(), field_values[2], field_values[3], field_values[4], field_values[5] )) } else if field_index == 1 { Box::new(sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = ? AND (v1 is NULL OR v1 = ?) AND (v2 is NULL OR v2 = ?) AND (v3 is NULL OR v3 = ?) AND (v4 is NULL OR v4 = ?) AND (v5 is NULL OR v5 = ?)", pt.to_string(), field_values[1], field_values[2], field_values[3], field_values[4], field_values[5] )) } else { Box::new(sqlx::query!( "DELETE FROM casbin_rules WHERE ptype = ? AND (v0 is NULL OR v0 = ?) AND (v1 is NULL OR v1 = ?) AND (v2 is NULL OR v2 = ?) AND (v3 is NULL OR v3 = ?) AND (v4 is NULL OR v4 = ?) AND (v5 is NULL OR v5 = ?)", pt.to_string(), field_values[0], field_values[1], field_values[2], field_values[3], field_values[4], field_values[5] )) }; boxed_query .execute(&mut conn) .await .map(|n| n >= 1) .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err))))) } #[cfg(feature = "postgres")] pub(crate) async fn load_policy(mut conn: &ConnectionPool) -> Result<Vec<CasbinRule>> { let casbin_rules: Vec<CasbinRule> = sqlx::query_as!(CasbinRule, "SELECT * from casbin_rules") .fetch_all(&mut conn) .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; Ok(casbin_rules) } #[cfg(feature = "mysql")] pub(crate) async fn load_policy(mut conn: &ConnectionPool) -> Result<Vec<CasbinRule>> { let casbin_rules: Vec<CasbinRule> = sqlx::query_as!(CasbinRule, "SELECT * from casbin_rules") .fetch_all(&mut conn) .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; Ok(casbin_rules) } #[cfg(feature = "postgres")] pub(crate) async fn save_policy<'a>( conn: &ConnectionPool, rules: Vec<NewCasbinRule<'a>>, ) -> Result<()> { let mut transaction = conn .begin() .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; sqlx::query!("DELETE FROM casbin_rules") .execute(&mut transaction) .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; for rule in rules { sqlx::query!( "INSERT INTO casbin_rules ( ptype, v0, v1, v2, v3, v4, v5 ) VALUES ( $1, $2, $3, $4, $5, $6, $7 )", rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4, rule.v5 ) .execute(&mut transaction) .await .and_then(|n| { if n == 1 { Ok(true) } else { Err(SqlxError::RowNotFound) } }) .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; } transaction .commit() .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; Ok(()) } #[cfg(feature = "mysql")] pub(crate) async fn save_policy<'a>( conn: &ConnectionPool, rules: Vec<NewCasbinRule<'a>>, ) -> Result<()> { let mut transaction = conn .begin() .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; sqlx::query!("DELETE FROM casbin_rules") .execute(&mut transaction) .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; for rule in rules { sqlx::query!( "INSERT INTO casbin_rules ( ptype, v0, v1, v2, v3, v4, v5 ) VALUES ( ?, ?, ?, ?, ?, ?, ? )", rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4, rule.v5 ) .execute(&mut transaction) .await .and_then(|n| { if n == 1 { Ok(true) } else { Err(SqlxError::RowNotFound) } }) .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; } transaction .commit() .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; Ok(()) } #[cfg(feature = "postgres")] pub(crate) async fn add_policy(mut conn: &ConnectionPool, rule: NewCasbinRule<'_>) -> Result<bool> { sqlx::query!( "INSERT INTO casbin_rules ( ptype, v0, v1, v2, v3, v4, v5 ) VALUES ( $1, $2, $3, $4, $5, $6, $7 )", rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4, rule.v5 ) .execute(&mut conn) .await .map(|n| n == 1) .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; Ok(true) } #[cfg(feature = "mysql")] pub(crate) async fn add_policy(mut conn: &ConnectionPool, rule: NewCasbinRule<'_>) -> Result<bool> { sqlx::query!( "INSERT INTO casbin_rules ( ptype, v0, v1, v2, v3, v4, v5 ) VALUES ( ?, ?, ?, ?, ?, ?, ? )", rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4, rule.v5 ) .execute(&mut conn) .await .map(|n| n == 1) .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; Ok(true) } #[cfg(feature = "postgres")] pub(crate) async fn add_policies( conn: &ConnectionPool, rules: Vec<NewCasbinRule<'_>>, ) -> Result<bool> { let mut transaction = conn .begin() .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; for rule in rules { sqlx::query!( "INSERT INTO casbin_rules ( ptype, v0, v1, v2, v3, v4, v5 ) VALUES ( $1, $2, $3, $4, $5, $6, $7 )", rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4, rule.v5 ) .execute(&mut transaction) .await .and_then(|n| { if n == 1 { Ok(true) } else { Err(SqlxError::RowNotFound) } }) .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; } transaction .commit() .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; Ok(true) } #[cfg(feature = "mysql")] pub(crate) async fn add_policies( conn: &ConnectionPool, rules: Vec<NewCasbinRule<'_>>, ) -> Result<bool> { let mut transaction = conn .begin() .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; for rule in rules { sqlx::query!( "INSERT INTO casbin_rules ( ptype, v0, v1, v2, v3, v4, v5 ) VALUES ( ?, ?, ?, ?, ?, ?, ? )", rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4, rule.v5 ) .execute(&mut transaction) .await .and_then(|n| { if n == 1 { Ok(true) } else { Err(SqlxError::RowNotFound) } }) .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; } transaction .commit() .await .map_err(|err| CasbinError::from(AdapterError(Box::new(Error::SqlxError(err)))))?; Ok(true) } fn normalize_casbin_rule(mut rule: Vec<String>, field_index: usize) -> Vec<String> { rule.resize(6 - field_index, String::from("")); rule }
1b9969328ac4a9440643d33a038e857cf71e5e90
[ "TOML", "Rust" ]
2
TOML
bodymindarts/sqlx-adapter
78a4c7aa9a5bb38d68a96cf2374790fcabafcded
611f77e9ab09bc1d0b9a9164716f4dd22acaea59
refs/heads/master
<repo_name>avesk/file_formater<file_sep>/format265.c #include <stdio.h> #include <string.h> int main(){ char input[512]; char strFile[512]; int line; //char *lw = ".LW", *lm = ".LM", *ls = ".LS", *ft = ".FT"; //int lwFlg = 0, lmFlg = 0, lsFlg = 0, ftFlg = 0; FILE *pToFile = fopen("badformat.txt","r"); while(fgets(input, 512, pToFile)){ strncat(strFile, input, 512); /** THis seems to be producing some unexpected output in strFile **/ } printf("%s", strFile); /** Test the substrs and the flags**/ // printf("LW: %s and flag is: %d \n", lw, lwFlg ); // printf("LM: %s and flag is: %d \n", lm, lmFlg ); // printf("LS: %s and flag is: %d \n", ls, lsFlg ); // printf("FT: %s and flag is: %d \n", ft, ftFlg ); /** switch(){ case } **/ fclose(pToFile); return 0; } <file_sep>/sudo_code_for_format265.c #include <stdio.h> #include <string.h> int main(int argc, char *argv[]){ int ch, num_char; char formatted_str[512]; char unformatted_str[512]; if(argc < 2){ fprintf(stderr, "Please provide a file name\n"); exit(1); } FILE *file = fopen(argv[1], "r"); if(file == NULL){ fprintf(stderr, "unable to open %s\n", argv[1]); exit(1); } is_format_cmd(); /** Turns on formating comand flags **/ set_format_value(); /** Sets formatting command values **/ lwf_txt = lw_format(lwflg, lw_val, unformatted_str); /** each format function returns a formated string in their repective format if their formating flag is set **/ lmf_txt = lm_format(lmflg, lm_val, lwf_txt); lsf_txt = ls_format;(lsflg, ls_val, lmf_txt); formatted_str = rmv_ft_cmd(); /** Removes all .FT* commands from the string **/ printf("%s", formatted_str); return 0; } const char *lw_format(int lw_flg, int format value, char *unformatted_txt[512]){ char *formatted_txt[512]; if(lw_flag == 1){ while(input != EndOfText){ if(input==".FT0"){ /**Dont format the text**/ /**Set FT flag to 0**/ } if(ftflag==0 && input!=".FT0"){ /**Dont format the text**/ } else{ /** format the text accordingly **/ } } else return unformatted_txt; return *formatted_txt; } /** Similar syntax for the remaining three functions **/
805100d5ac9d2150b5c6bb9cb4d7e62f422dcda5
[ "C" ]
2
C
avesk/file_formater
e004b33cf01e0be7fd6ad49d78858ceee0e9b8a1
2b11d7efe9d645d7b132bbcb647e6fde5588e016
refs/heads/master
<file_sep>window.onerror = function(e){ log(e); } window.objFace = {}; var Facebook = { urlAppFace : 'http://migre.me/efht7', urlApp : 'http://salvesocial.com/kimberly/cha-de-bebe/', myId : '', accessToken : '<KEY>', compartilheApp : function(e){ //e.preventDefault(); FB.ui({ method: 'feed', link: Facebook.urlAppFace, picture: Facebook.urlApp + 'img/share.jpg', name: '<NAME> - Huggies® Turma da Mônica©', caption: 'De Huggies Turma da Mônica', description: 'Chegou a hora de preparar o seu chá! E a receita é simples: reunir quem você ama para comemorar a chegada do novo bebê. Conheça a nova ferramenta para criar um Chá de Bebê delicioso.' }, function(response){ log(response); }); }, /** *Tras os amigos do Facebook */ getFriends : function(callback){ var that = this; if(window.objFace.friendList){ if(typeof(callback) == 'function'){ callback(); } } that.getLoginStatus(function(){ FB.api('/me/friends', 'get', { access_token: that.accessToken }, function(response) { window.objFace.friendList = response.data; FaceEvent.addListenerSeach(); FaceEvent.appendFriends(); FaceEvent.setFriendInvited(); if(typeof(callback) == 'function'){ callback(); } }); }); }, getLoginStatus : function (callbackConnected){ // callbackConnected(); // return true; FB.getLoginStatus(function(response) { if (response.status === 'connected') { var authResponse = FB.getAuthResponse(); Facebook.accessToken = authResponse.access_token; Facebook.myId = authResponse.userID; callbackConnected(); } else { FB.login(function(response) { if (response.authResponse) { callbackConnected(); }else{ alert("Você deve aceitar o aplicativo para participar"); window.location.reload(); } }, { scope: 'user_about_me,email, user_events, friends_events, create_event, publish_stream, read_stream, publish_stream, friends_photos, user_photos,rsvp_event ' }); } }); } , /** *Retorna os albums do usuário no face *@param int albumId id do album, parametro passado pela função getPhotos **/ getAlbumsPhotos : function(callback){ var that = this; if(window.objFace.albums){ callback(); return; } that.getLoginStatus(function(){ FB.api('/me/albums?fields=id,name,count,photos.limit(1).fields(source)', 'get', {}, function(response) { if(response.hasOwnProperty('data')){ //SE NÃO TER AUTORIZAÇÃO DE PEGAR FOTOS if(response.data.length == 0){ FB.login(function(response) { if (response.authResponse) { Facebook.getAlbumsPhotos(callback); }else{ alert("Você deve aceitar o aplicativo para participar"); } }, { scope: 'user_photos' }); return; } window.objFace.albums = {}; $.each(response.data, function(i, val){ window.objFace.albums[val.id] = val; }); if(typeof(callback) == 'function'){ callback(response); return; } }else{ log(response); } }); }); } , getPhotos : function(albumId, callback){ var that = this; that.getLoginStatus(function(){ FB.api(albumId +'/photos?fields=images,id', 'get', {}, function(response) { if(response.hasOwnProperty('data')){ //SE NÃO TER AUTORIZAÇÃO DE PEGAR FOTOS if(response.data.length == 0){ FB.login(function(response) { if (response.authResponse) { Facebook.getPhotos(callback); }else{ alert("Você deve aceitar o aplicativo para participar"); } }, { scope: 'user_photos' }); return; } window.objFace.photos = {}; $.each(response.data, function(i, val){ window.objFace.photos[val.id] = val; }); if(response.hasOwnProperty('paging')){ if(response.paging.hasOwnProperty('next')){ FB.api(response.paging.next, 'get', {}, function(response) { if(response.hasOwnProperty('data')){ $.each(response.data, function(i, val){ window.objFace.photos[val.id] = val; }); } }) } } if(typeof(callback) == 'function'){ callback(response); return; } }else{ log(response); } }); }); }, /** *Publicando o album com as fotos do chá no facebook **/ deployAlbum : function (){ if($(this).hasClass('bt_aguarde')){ return; } Loading.show(); var postData = "classe=EventInvited&method=getInvitesJson"; $.ajax({ url: 'ajax.php', type: "POST", data: postData }).done( function(response){ if(typeof(response) == 'string'){ response = $.parseJSON(response); } var priv = { 'value' : 'CUSTOM', 'friends' : 'SOME_FRIENDS', 'allow' : response.friends.join(',') }; FB.login(function (response) { if (response.authResponse) { FB.api('/me/albums/', 'post', { message:'As fotos do '+global.teaName+' ficaram muito legais! Dê uma olhada e comente. ', name:'<NAME>', privacy : priv }, function(response){ Album.addIdAlbumFace(response.id); var $imgs = $('#listAlbumPhotoC img').not('.capaAl'); var total = $imgs.length; $imgs.each(function(i, val){ var filename = $(val).data('imgname'); var imgURL = Facebook.urlApp + 'userfiles/fotos/t3_'+filename; FB.api(response.id + '/photos', 'post', { position: i, url:imgURL }, function(r){ if(total <= (i + 1)){ Loading.hide(); $('.light-sucesso').fadeIn(); Ga.trackAlbumCompartilheSuccess(); } }); }); }); } else { window.alert('Você deve aceitar o aplicativo.'); } },{ scope: 'publish_stream' }); }); }, /** *Envia um convite marcando os convidados **/ sendInviteFriends : function($friends){ var imgURL = Facebook.urlApp +'userfiles/convites/'+global.eventFaceId+'.jpg'; var aTags = []; var friends = []; var teaName = $('#nomecha'); if(teaName.length){ teaName = teaName.val(); }else{ teaName = global.teaName; } $.each($friends, function(i,val){ var friendId = $(val).val(); friends.push(friendId); aTags.push({ x:"30", y: "30", tag_uid : friendId }); }); var priv = { 'value' : 'CUSTOM', 'friends' : 'SOME_FRIENDS', 'allow' : friends.join(',') }; FB.api('/me/albums/', 'post', { message:'', name:'convite', privacy : priv }, function(response){ log(response) FB.api(response.id + '/photos', 'post', { message: teaName+'\n\ Eba! Nosso bebê está chegando e para comemorarmos preparamos um Chá de Bebê inesquecível. Você não ficar de fora dessa festa.\n\ Acesse o aplicativo Chá de Bebê Huggies Turma da Mônica e participe da brincadeira. \n\ '+Facebook.urlAppFace, url:imgURL, tags : aTags }); }); }, /** * Compartilha uma imagem avisando que o album está pronto com um link do chá * no facebook ***/ shareMemoryBook : function(){ Loading.show(); var postData = "classe=EventInvited&method=getInvitesJson"; var imgURL = Facebook.urlApp + 'img/livrodememorias_gde_compartilhar.jpg'; var aTags = []; $.ajax({ url: 'ajax.php', type: "POST", data: postData }).done( function(response){ if(typeof(response) == 'string'){ response = $.parseJSON(response); } $.each(response.friends, function(i,val){ aTags.push({ x:"30", y: "30", tag_uid : val }); }); var priv = { 'value' : 'CUSTOM', 'friends' : 'SOME_FRIENDS', 'allow' : response.friends.join(',') }; FB.api('/me/albums/', 'post', { name:'Album de memórias', privacy : priv }, function(response){ FB.api(response.id + '/photos', 'post', { message: 'Olha que legal o Livro de Memórias com as curiosidades do ano em que o bebê nasceu para ele ver quando crescer. Esse presente foi criado com o aplicativo Chá de Bebê Huggies Turma da Mônica. Faça o seu também.\n'+Facebook.urlAppFace, url: imgURL, tags : aTags }, function(response){ Loading.hide(); $('.light-share').fadeIn(); Ga.trackLivroCompartilheSuccess(); }); }); } ); } } <file_sep># Exemplo de Readme ------------------------------------- Repositório padrão para novos projetos ## Responsáveis: * Back-end : Alexsandro * Front-end : Karol * GP : Maíra ## Analytics * O atendimento não passou o ID ainda * Tem eventos para a área de produtos ## Informações importantes * Versão de Qa no seguinte endereco [salveqa.hospedagemdesites.ws/] * Esse app tem integração com Myhuggies no momento do cadastro do evento, nas classes Event - MyHuggies; * Esse App tem uma tarefa cron que executa o arquivo cron-enviar-carta.php uma vez no dia as 04:00 * Esse App tem tageamento no google analitycs onde tudo está no arquivo googleAnalitycs.js * Hospedado no Media temple [http://mediatemple.net/landing/grid/?gclid=CPuPvP3807wCFY1r7AodAmQA-Q] ## Passos para deploy * Executar o "grunt build" dentro do projeto * Dar push para o servidor de QA * Dar push para o servidor de produção ## Suporte para mobile * Existe uma versão para celular na pasta /mobile * Existe uma verificação no config.php que redireciona para /mobile quando celular ### Integração MyHuggies * Integração feita no cadastro/editar evento; * Estou passando o nome, email, semana de gestação, e o id do Facebook, se quem está criando o evento for a mãe caso contrário, não passo o id do Face * Não estou usando nenhuma informação do Myhuggies, apenas cadastrando se já nao estiver cadastrada; * Toda integração está nas classes Event e Myhuggies; * Toda regra de negocio de Myhuggies foram feitas pelo Jefferson. <file_sep>var PRJ = PRJ || {}; ; (function() { 'use strict'; var method, noop = function() { }, methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn']; var length = methods.length, console = (window.console = window.console || {}); while (length--) { method = methods[length]; // Only stub undefined methods. if (!console[method]) { console[method] = noop; } } //console.log shortcut window.l = function(args) { console.log(args); } /* * Analytics * No html deve ter data-ga="Categoria|evento|rotulo" * */ $('[data-ga]').click(function(event) { var data = $(this).data('ga').split('|'); if (data[3] && data[3] === "waitredirect") { event.preventDefault(); PRJ.trackGARedirect($(this), data[0], data[1], data[2]); } else { PRJ.trackAnalytics(data[0], data[1], data[2]); } }); PRJ.trackAnalytics = function(cat, action, label) { if (typeof (_gaq) !== 'undefined') { _gaq.push(['_trackEvent', cat, action, label]); } else { if (typeof (ga) !== 'undefined') { ga('send', 'event', cat, action, label); } } }; var pagesViews = []; PRJ.trackPageviewGA = function (page, title) { var pageTitle = page + title; if($.inArray(pageTitle, pagesViews) == '-1'){ if(typeof(ga) !== 'undefined') { ga('send', 'pageview', { 'page': page, 'title': title }); } pagesViews.push(pageTitle); } } PRJ.trackGARedirect = function(button, event, action, label) { // track trackAnalytics(event, action, label); // redirect if (button.attr('target') !== '_blank') { setTimeout(function() { window.self.location = button.attr('href'); }, 500); } }; /** * Ajax * */ PRJ.ajax = function(postData, done) { var ajax = $.ajax({ type: "POST", url: "ajax.php", data: postData }); ajax.done(done); return ajax; }; PRJ.parseJson = function(r) { if (typeof (r) == 'string') { r = $.parseJSON(r); } return r; }; /** * Placeholder Cross Browser * */ if (!Modernizr.input.placeholder) { $('[placeholder]').focus(function() { var $input = $(this); if ($input.val() == $input.attr('placeholder')) { $input.val(''); $input.removeClass('placeholder'); } }).blur(function() { var $input = $(this); if ($input.val() == '' || $input.val() == $input.attr('placeholder')) { $input.addClass('placeholder'); $input.val($input.attr('placeholder')); } }).blur(); $('[placeholder]').parents('form').submit(function() { $(this).find('[placeholder]').each(function() { var $input = $(this); if ($input.val() == $input.attr('placeholder')) { $input.val(''); } }) }); } }());
315996248f0f76d31fc999f01e02b528c71c9f7e
[ "JavaScript", "Markdown" ]
3
JavaScript
Salveagenciainterativa/starter
15ba6f2451befe841a64b6ac89013a7dcf88e8ba
fa29a255d7441a207a41c9b01350fa2b206c7d1a
refs/heads/master
<repo_name>FrankyS4/experiencia2<file_sep>/enviar.php <?php function Filtro($texto) { return htmlspecialchars(trim($texto), ENT_QUOTES); } $anio = isset($_POST['anio']) ? (int) $_POST['anio'] : 0; $name = isset($_POST['name']) ? Filtro($_POST['name']) : ''; $FechaNac = isset($_POST['FechaNac']) ? Filtro($_POST['FechaNac']) : ''; $sexo = isset($_POST['sexo']) ? Filtro($_POST['sexo']) : ''; $Apellido = isset($_POST['Apellido']) ? Filtro($_POST['Apellido']) : ''; $correo = isset($_POST['correo']) ? Filtro($_POST['correo']) : ''; $color = isset($_POST['color']) ? Filtro($_POST['color']) : ''; $urlP = isset($_POST['urlP']) ? Filtro($_POST['urlP']) : ''; $error = ''; ?>
9a26fa8f90aaf666065b07c0a7f2c9d2385c5990
[ "PHP" ]
1
PHP
FrankyS4/experiencia2
c3dca022e8b2e6e0d04aa0e9dcc326bbfcfb6d02
2eff5f3734a19bc0114f429d50bb84c5f46d2c57
refs/heads/master
<repo_name>EddyBeaupre/meshStatus<file_sep>/meshUtils/wlcCollector.cs using Renci.SshNet; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace meshUtils { public class wlcCollector { private PasswordConnectionInfo sshInfo; private SshClient sshClient; private ShellStream sshShell; private String meshData = String.Empty; private List<meshInfo> info = null; private String userName; private String userPassword; private EventLogger eventLogger; private void Logger(String msg, EventLogEntryType level, Exception ex = null) { if (ex != null) { eventLogger.WriteEntry(msg, level, ex); } else { eventLogger.WriteEntry(msg, level); } } public List<meshInfo> getInfo { get { return this.info; } } /// <summary> /// Capture until the next prompt /// </summary> /// <param name="stream">Stream to capture from</param> /// <param name="prompt">Prompt to wait for</param> /// <param name="time">timeout in seconds</param> /// <returns>String object of the captured text</returns> private String waitPrompt(String prompt, int time) { try { TimeSpan timeout = new TimeSpan(0, 0, time); return (sshShell.Expect(prompt, timeout)); } catch (Exception ex) { Logger("wlcCollector.waitPrompt : Exception :", EventLogEntryType.Error, ex); return String.Empty; } } /// <summary> /// Capture until the next prompt then send a command. /// </summary> /// <param name="stream">Stream to capture from</param> /// <param name="prompt">Prompt to wait for before sending command</param> /// <param name="command">Command to send to the stream</param> /// <param name="time">timeout in seconds</param> /// <returns>String object of the captured text</returns> private String waitPromptCmd(String prompt, String command, int time) { try { String data = waitPrompt(prompt, time); if (data != null) { writeStream(command); } return data; } catch (Exception ex) { Logger("wlcCollector.waitPromptCmd : Exception :", EventLogEntryType.Error, ex); return String.Empty; } } /// <summary> /// Send a command then capture the result. /// </summary> /// <param name="stream">Stream to capture from</param> /// <param name="prompt">Prompt to wait for after the command is sent</param> /// <param name="command">Command to send to the stream</param> /// <param name="time">Timeout in seconds</param> /// <returns>String object of the captured text</returns> private String cmdPromptWait(String prompt, String command, int time) { try { if (writeStream(command)) { return (waitPrompt(prompt, time)); } else { return String.Empty; } } catch (Exception ex) { Logger("wlcCollector.cmdPromptWait : Exception :", EventLogEntryType.Error, ex); return String.Empty; } } /// <summary> /// write a command to the stream /// </summary> /// <param name="stream">Stream to write to</param> /// <param name="command">Command to send to the stream</param> private bool writeStream(String command) { try { StreamWriter writer = new StreamWriter(sshShell); writer.AutoFlush = true; writer.NewLine = "\r"; writer.WriteLine(command); return true; } catch (Exception ex) { Logger("wlcCollector.writeStream : Exception :", EventLogEntryType.Error, ex); return false; } } private bool getMeshApTree() { try { String data; Logger("wlcCollector.getMeshApTree : En attente de 'User'.", EventLogEntryType.Information); data = waitPromptCmd("User:", userName, 60); if (data == null) { Logger("wlcCollector.getMeshApTree : Délais dépasser.", EventLogEntryType.Information); return false; } Logger("wlcCollector.getMeshApTree : En attente de 'Password'.", EventLogEntryType.Information); data = waitPromptCmd("Password:", userPassword, 30); if (data == null) { Logger("wlcCollector.getMeshApTree : Délais dépasser.", EventLogEntryType.Information); return false; } Logger("wlcCollector.getMeshApTree : En attente de '(Cisco Controller)'.", EventLogEntryType.Information); data = waitPromptCmd("(Cisco Controller) >", "config paging disable", 30); if (data == null) { Logger("wlcCollector.getMeshApTree : Délais dépasser.", EventLogEntryType.Information); return false; } Logger("wlcCollector.getMeshApTree : En attente de '(Cisco Controller)'.", EventLogEntryType.Information); data = waitPrompt("(Cisco Controller) >", 30); if (data == null) { Logger("wlcCollector.getMeshApTree : Délais dépasser.", EventLogEntryType.Information); return false; } Logger("wlcCollector.getMeshApTree : En attente de 'show mesh ap tree'.", EventLogEntryType.Information); data = cmdPromptWait("(Cisco Controller) >", "show mesh ap tree", 30); if (data == null) { Logger("wlcCollector.getMeshApTree : Délais dépasser.", EventLogEntryType.Information); return false; } Logger("wlcCollector.getMeshApTree : Traitement de la réponse du contrôleur.", EventLogEntryType.Information); data = data.Replace("\n", ""); String[] stringSeparator = new String[] { "\r" }; String[] tmp = data.Split(stringSeparator, StringSplitOptions.RemoveEmptyEntries); data = String.Empty; Boolean stringAdd = false; foreach (String s in tmp) { if (s.StartsWith("[Sector")) { if (stringAdd) { data = data + Environment.NewLine; } else { stringAdd = true; } } if (s.StartsWith("Number")) { stringAdd = false; } if (stringAdd) { if (!s.StartsWith("----------")) { data = data + s.Replace("|-", "").Trim() + Environment.NewLine; } } } meshData = data; Logger("wlcCollector.getMeshApTree : Fin.", EventLogEntryType.Information); return true; } catch (Exception ex) { Logger("wlcCollector.getMeshApTree : Exception :", EventLogEntryType.Error, ex); return false; } } private int countSector() { try { if (meshData != String.Empty) { int count = 0; String[] stringSeparator = new String[] { Environment.NewLine }; String[] tmp = meshData.Split(stringSeparator, StringSplitOptions.RemoveEmptyEntries); foreach (String s in tmp) { if (s.StartsWith("[Sector")) { count++; } } return count; } else { return 0; } } catch (Exception ex) { Logger("wlcCollector.countSector : Exception :", EventLogEntryType.Error, ex); return 0; } } private String getSector(int sector) { try { if (meshData != String.Empty) { bool found = false; String sc = String.Empty; String[] stringSeparator = new String[] { Environment.NewLine }; String[] tmp = meshData.Split(stringSeparator, StringSplitOptions.RemoveEmptyEntries); foreach (String s in tmp) { if (found) { if (!s.StartsWith("[Sector")) { sc += s + Environment.NewLine; } else { found = false; } } if (s.StartsWith("[Sector " + sector.ToString() + "]")) { found = true; } } return sc; } else { return String.Empty; } } catch (Exception ex) { Logger("wlcCollector.getSector : Exception :", EventLogEntryType.Error, ex); return String.Empty; } } private String[] parseAP(String s) { try { int x = s.IndexOf("["); String[] stringSeparator = new String[] { "," }; String[] apInfo = s.Substring(x + 1, s.Length - (x + 2)).Split(stringSeparator, StringSplitOptions.RemoveEmptyEntries); return new String[] { s.Substring(0, x), apInfo[0], apInfo[1], apInfo[2] }; } catch (Exception ex) { Logger("wlcCollector.parseAP : Exception :", EventLogEntryType.Error, ex); return new String[] { String.Empty }; } } private List<meshInfo> parseMesh() { try { if (meshData != String.Empty) { List<meshInfo> data = new List<meshInfo>(); for (int i = 1; i <= countSector(); i++) { data.AddRange(parseSector(i)); } return (data); } else { return null; } } catch (Exception ex) { Logger("wlcCollector.parseMesh : Exception :", EventLogEntryType.Error, ex); return null; } } private List<meshInfo> parseSector(int sector) { try { List<String[]> apInfo = new List<string[]>(); List<meshInfo> data = new List<meshInfo>(); String[] stringSeparator = new String[] { Environment.NewLine }; String[] tmp = getSector(sector).Split(stringSeparator, StringSplitOptions.RemoveEmptyEntries); foreach (String s in tmp) { apInfo.Add(parseAP(s)); } for (int i = 0; i < apInfo.Count; i++) { String apParent = String.Empty; String[] apDetail = getAPState(apInfo[i][0]); if (apInfo[i][1] == "*") { apInfo[i][1] = "0"; } if (apInfo[i][2] == "*") { apInfo[i][2] = "0"; } if (Convert.ToInt32(apInfo[i][1]) > 0) { for (int j = i; j >= 0; j--) { if (Convert.ToInt32(apInfo[i][1]) > Convert.ToInt32(apInfo[j][1])) { apParent = apInfo[j][0]; break; } } } data.Add(new meshInfo(sector, apInfo[i][0], apParent, apInfo[i][2], apDetail[0], apDetail[1], apDetail[2])); } return data; } catch (Exception ex) { Logger("wlcCollector.parseSector : Exception :", EventLogEntryType.Error, ex); return null; } } private String[] getAPState(String name) { try { String upTime = String.Empty; String capTime = String.Empty; String joinTime = String.Empty; String data = cmdPromptWait("(Cisco Controller) >", "show ap config general " + name, 30); if (data == null) { return null; } data = data.Replace("\n", ""); String[] stringSeparator = new String[] { "\r" }; String[] tmp = data.Split(stringSeparator, StringSplitOptions.RemoveEmptyEntries); foreach (String s in tmp) { if (s.StartsWith("AP Up Time")) { upTime = s.Substring(50); } if (s.StartsWith("AP LWAPP Up Time")) { capTime = s.Substring(50); } if (s.StartsWith("Join Taken Time")) { joinTime = s.Substring(50); } } return new String[] { upTime, capTime, joinTime }; } catch (Exception ex) { Logger("wlcCollector.getAPState : Exception :", EventLogEntryType.Error, ex); return new String[] { String.Empty }; } } public wlcCollector(String address, String name, String password, EventLogger eventlogger = null) { eventLogger = eventlogger; try { Logger("wlcCollector : Démarrage", EventLogEntryType.Information); userName = name; userPassword = <PASSWORD>; Logger("wlcCollector : Création du client SSH", EventLogEntryType.Information); sshInfo = new PasswordConnectionInfo(address, name, password); sshClient = new SshClient(sshInfo); Logger("wlcCollector : Connexion du client SSH", EventLogEntryType.Information); sshClient.Connect(); Logger("wlcCollector : Création du shell SSH", EventLogEntryType.Information); sshShell = sshClient.CreateShellStream("dumb", 80, 25, 800, 600, 1024); if (getMeshApTree()) { info = parseMesh(); } Logger("wlcCollector : Arret", EventLogEntryType.Information); } catch (Exception ex) { Logger("wlcCollector : Exception : ", EventLogEntryType.Information, ex); } } } } <file_sep>/meshUtils/meshInfo.cs using System; namespace meshUtils { public class meshInfo { private Int32 sector; private String name; private String parent; private Int32 snr; private TimeSpan up; private TimeSpan association; private TimeSpan join; public Int32 getSector { get { return this.sector; } } public String getName { get { return this.name; } } public String getParent { get { return this.parent; } } public Int32 getSNR { get { return this.snr; } } public TimeSpan getUpTime { get { return this.up; } } public TimeSpan getAssociationTime { get { return this.association; } } public TimeSpan getJoinTime { get { return this.join; } } /// <summary> /// Convert WLC time to timespan. /// </summary> /// <param name="data">Timespan in WLC format (D days, HH h MM m SS s)</param> /// <returns>A TimeSpan with the WLC timespan</returns> private TimeSpan convertWLCTimeSpan(String data) { try { if (data != String.Empty) { Int32 days = Convert.ToInt32(data.Substring(0, data.IndexOf(" days,"))); Int32 hours = Convert.ToInt32(data.Substring(data.IndexOf(", ") + 2, data.IndexOf(" h") - (data.IndexOf(", ") + 2))); Int32 min = Convert.ToInt32(data.Substring(data.IndexOf("h ") + 2, data.IndexOf(" m") - (data.IndexOf("h ") + 2))); Int32 sec = Convert.ToInt32(data.Substring(data.IndexOf("m ") + 2, data.IndexOf(" s") - (data.IndexOf("m ") + 2))); return (new TimeSpan(days, hours, min, sec)); } else { return (new TimeSpan(0, 0, 0, 0)); } } catch(Exception ex) { return (new TimeSpan(0, 0, 0, 0)); } } public meshInfo(Int32 sc, String nm, String pr, Int32 sr, TimeSpan ut, TimeSpan at, TimeSpan jt) { this.sector = sc; this.name = nm; this.parent = pr; this.snr = sr; this.up = ut; this.association = at; this.join = jt; } public meshInfo(String sc, String nm, String pr, String sr, String ut, String at, String jt) { this.sector = Convert.ToInt32(sc); this.name = nm; this.parent = pr; this.snr = Convert.ToInt32(sr); this.up = convertWLCTimeSpan(ut); this.association = convertWLCTimeSpan(at); this.join = convertWLCTimeSpan(jt); } public meshInfo(Int32 sc, String nm, String pr, String sr, String ut, String at, String jt) { this.sector = sc; this.name = nm; this.parent = pr; this.snr = Convert.ToInt32(sr); this.up = convertWLCTimeSpan(ut); this.association = convertWLCTimeSpan(at); this.join = convertWLCTimeSpan(jt); } } } <file_sep>/meshConfigEditor/meshConfigDialog.cs using meshUtils; using System; using System.Windows.Forms; namespace meshConfigEditor { public partial class meshConfigDialog : Form { meshConfigUtils config = new meshConfigUtils(); public meshConfigDialog() { InitializeComponent(); config.ReadXML(); userName.Text = config.Decrypt(config.config.userName); userPassword.Text = config.Decrypt(config.config.userPassword); serverAddress.Text = config.config.serverAddress; if(config.config.serverTimeout < 20 ) { config.config.serverTimeout = 20; } serverDelay.Text = config.config.serverTimeout.ToString(); filePath.Text = config.config.filePath; } private void filePath_MouseClick(object sender, MouseEventArgs e) { FolderBrowserDialog fbd = new FolderBrowserDialog(); DialogResult result = fbd.ShowDialog(); config.config.filePath = fbd.SelectedPath; filePath.Text = config.config.filePath; } private void saveConfig_Click(object sender, EventArgs e) { Application.Exit(); } private void doSaveConfig() { config.config.userName = config.Encrypt(userName.Text); config.config.userPassword = config.Encrypt(userPassword.Text); config.config.serverAddress = serverAddress.Text; config.config.serverTimeout = Convert.ToInt32(serverDelay.Text); if (config.config.serverTimeout < 20) { config.config.serverTimeout = 20; } config.config.filePath = filePath.Text; config.WriteXML(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { switch(MessageBox.Show("Sauvegarder la configuration? ?", "Sortie", MessageBoxButtons.YesNoCancel)) { case DialogResult.Yes: doSaveConfig(); break; case DialogResult.No: break; default: e.Cancel = true; break; } } } } <file_sep>/meshConfig/meshConfig.cs using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace meshConfig { public class meshConfig { public String userName; public String userPassword; public String serverAddress; public Int32 serverTimeout; public String filePath; } public class meshConfigUtils { public meshConfig config; static readonly string PasswordHash = "<PASSWORD>"; static readonly string SaltKey = "dOo6Ias0r4S7rgSitTH43miD"; static readonly string VIKey = "<KEY>"; String configFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "meshStatusConfig.xml"); public Boolean ReadXML() { try { if (File.Exists(configFile)) { System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(meshConfig)); System.IO.StreamReader file = new System.IO.StreamReader(configFile); config = (meshConfig)reader.Deserialize(file); file.Close(); return true; } else { config = new meshConfig(); return false; } } catch { config = new meshConfig(); return false; } } public Boolean WriteXML() { try { System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(meshConfig)); System.IO.StreamWriter file = new System.IO.StreamWriter(configFile); writer.Serialize(file, config); file.Close(); return true; } catch { return false; } } public string Encrypt(string plainText) { try { byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros }; var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey)); byte[] cipherTextBytes; using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); cipherTextBytes = memoryStream.ToArray(); cryptoStream.Close(); } memoryStream.Close(); } return Convert.ToBase64String(cipherTextBytes); } catch { return string.Empty; } } public string Decrypt(string encryptedText) { try { if ((encryptedText != String.Empty) && (encryptedText != null)) { byte[] cipherTextBytes = Convert.FromBase64String(encryptedText); byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8); var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None }; var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey)); var memoryStream = new MemoryStream(cipherTextBytes); var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); byte[] plainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memoryStream.Close(); cryptoStream.Close(); return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray()); } else { return string.Empty; } } catch { return string.Empty; } } } } <file_sep>/meshUtils/eventLogger.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace meshUtils { public class EventLogger { private EventLog eventLog; private EventLogEntryType logLevel; public EventLogger(EventLog eventlog, String source, String logtype, EventLogEntryType loglevel) { eventLog = eventlog; eventLog.Source = source; eventLog.Log = logtype; logLevel = loglevel; } public EventLogger(EventLog eventlog, String source, String logtype) { eventLog = eventlog; eventLog.Source = source; eventLog.Log = logtype; logLevel = EventLogEntryType.Information; } public void WriteEntry(String message, EventLogEntryType type, Exception ex) { if (eventLog != null) { if (type < EventLogEntryType.Error) { type = EventLogEntryType.Error; } if (type > EventLogEntryType.FailureAudit) { type = EventLogEntryType.FailureAudit; } if (message != String.Empty) { if (type <= logLevel) { if (ex != null) { eventLog.WriteEntry( message + Environment.NewLine + ex.ToString(), type); } else { eventLog.WriteEntry(message, type); } } } } } public void WriteEntry(String message, EventLogEntryType type) { WriteEntry(message, type, null); } } } <file_sep>/meshStatusService/serviceControl.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using meshUtils; namespace meshStatusService { public partial class serviceControl : ServiceBase { private delegate void mainCallback_delegate(int status, Object data); private meshConfigUtils config = new meshConfigUtils(); private wlcPooler pooler = null; private EventLogger eventLogger = null; public serviceControl() { InitializeComponent(); config.ReadXML(); eventLogger = new EventLogger(this.EventLog, this.ServiceName, "Application", config.config.debugLevel); } public void mainCallback(int status, Object data) { try { switch (status) { case 1: DateTime timeStamp = DateTime.Now; if (data != null) { String fileName; if (config.config.dateTimeFileName == true) { fileName = Path.Combine(config.config.filePath, String.Concat("meshStatus-", timeStamp.ToString("yyyyMMddHHmmss"), ".csv")); } else { fileName = Path.Combine(config.config.filePath, String.Concat("meshStatus", ".csv")); } try { try { if (File.Exists(fileName)) { File.Delete(fileName); } } catch (Exception ex) { eventLogger.WriteEntry("Impossible d'effacer " + fileName + ".", EventLogEntryType.Warning, ex); } using (StreamWriter outfile = new StreamWriter(fileName, false)) { foreach (meshInfo s in (List<meshInfo>)data) { outfile.WriteLine(s.getSector + "," + s.getName + "," + s.getParent + "," + s.getSNR + "," + s.getUpTime.ToString(@"dd\.hh\:mm\:ss") + "," + s.getAssociationTime.ToString(@"dd\.hh\:mm\:ss") + "," + s.getJoinTime.ToString(@"dd\.hh\:mm\:ss")); } } } catch (Exception ex) { eventLogger.WriteEntry("Impossible de crée " + fileName + ".", EventLogEntryType.Warning, ex); } } break; case 0: stopPooler(); break; default: break; } } catch (Exception ex) { eventLogger.WriteEntry("Une exception est survenue.", EventLogEntryType.Error, ex); stopPooler(); } } private void stopPooler() { if (pooler.threadRun) { pooler.threadRun = false; } else { Stop(); } } protected override void OnStart(string[] args) { try { eventLogger.WriteEntry("Lecture de la configuration.", EventLogEntryType.Information); if (!Directory.Exists(config.config.filePath)) { eventLogger.WriteEntry("Le répertoire de destination n'existe pas. Vérifiez la configuration.", EventLogEntryType.Warning); stopPooler(); } if ((config.config.userPassword == String.Empty) || config.config.userPassword == null) { eventLogger.WriteEntry("Un mot de passe est nécessaire. Vérifiez la configuration.", EventLogEntryType.Error); stopPooler(); } if ((config.config.userName == String.Empty) || config.config.userName == null) { eventLogger.WriteEntry("Un nom d'utilisateur est nécessaire. Vérifiez la configuration.", EventLogEntryType.Error); stopPooler(); } if ((config.config.serverAddress == String.Empty) || config.config.serverAddress == null) { eventLogger.WriteEntry("L'adresse du serveur est nécessaire. Vérifiez la configuration.", EventLogEntryType.Error); stopPooler(); } if (config.config.serviceTimeout < config.minServiceTimeout) { eventLogger.WriteEntry("Ajuste l'interval minimum d'intérrogation du serveur a " + config.minServiceTimeout.ToString() + ".", EventLogEntryType.Warning); config.config.serviceTimeout = config.minServiceTimeout; } eventLogger.WriteEntry("Démarrage du service.", EventLogEntryType.Information); pooler = new wlcPooler(Convert.ToInt32(config.config.serviceTimeout), config.config.serverAddress, config.Decrypt(config.config.userName), config.Decrypt(config.config.userPassword), mainCallback, eventLogger); } catch (Exception ex) { eventLogger.WriteEntry("Une exception est survenue.", EventLogEntryType.Error, ex); stopPooler(); } } protected override void OnStop() { try { eventLogger.WriteEntry("Le service est arreter.", EventLogEntryType.Information); } catch (Exception ex) { eventLogger.WriteEntry("Une exception est survenue.", EventLogEntryType.Error, ex); } } } } <file_sep>/meshUtils/wlcPooler.cs using System; using System.Diagnostics; using System.Threading; namespace meshUtils { public class wlcPooler { public delegate void mainCallback(int status, Object data); private mainCallback callback = null; private Thread threadWorker; public Boolean threadRun = false; private String wlcIP; private String wlcUser; private String wlcPassword; private Int32 wlcScanTime; private EventLogger eventLogger = null; private void Logger(String msg, EventLogEntryType level, Exception ex = null) { if (ex != null) { eventLogger.WriteEntry(msg, level, ex); } else { eventLogger.WriteEntry(msg, level); } } public wlcPooler(Int32 scan, String ip, String user, String password, mainCallback cb, EventLogger eventlogger = null) { eventLogger = eventlogger; try { callback = cb; wlcIP = ip; wlcUser = user; wlcPassword = <PASSWORD>; wlcScanTime = scan; this.threadWorker = new Thread(new ThreadStart(this.pooler)); this.threadWorker.Name = "meshStatus.pooler"; this.threadWorker.IsBackground = true; this.threadWorker.Start(); Logger("wlcPooler : initialisé.", EventLogEntryType.Information); } catch (Exception ex) { Logger("wlcPooler : Erreur lors de l'initialisation.", EventLogEntryType.Information, ex); } } private void pooler() { try { Boolean sleep = false; threadRun = true; Logger("wlcPooler.pooler : Démarrage.", EventLogEntryType.Information); while (threadRun) { if (sleep) { for (int i = 0; i < wlcScanTime; i++) { if (threadRun) { callback(2, (Object)"Prochain scan : " + (wlcScanTime - i).ToString() + " secondes"); Thread.Sleep(1000); } } } if (threadRun) { callback(2, (Object)"Scan en progression..."); wlcCollector wlc = new wlcCollector(wlcIP, wlcUser, wlcPassword, eventLogger); callback(1, (Object)wlc.getInfo); } if (!sleep) { sleep = true; } } Logger("wlcPooler.pooler : Arret.", EventLogEntryType.Information); callback(0, null); } catch (Exception ex) { threadRun = false; Logger("wlcPooler.pooler : Exception.", EventLogEntryType.Error, ex); callback(2, (Object)"Erreur :" + ex.ToString()); callback(0, null); } } } } <file_sep>/meshStatus/meshStatusGUI.cs using System; using System.Diagnostics; using meshUtils; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; namespace meshStatus { public partial class meshStatusGUI : Form { private delegate void mainCallback_delegate(int status, Object data); private wlcPooler pooler = null; private Boolean scanStatus = false; private Boolean exitApp = false; private int splitHeight; private int splitWidth; private int buttonHeight; private int buttonWidth; private List<Button> buttonList = new List<Button>(); private meshConfigUtils config = new meshConfigUtils(); private EventLogger eventLogger = null; public meshStatusGUI() { InitializeComponent(); config.ReadXML(); statusLabel.Text = "En attente de démarrage"; for (int i = 0; i < 100; i++) { Button bt = new Button(); bt.Location = new Point(0, 0); bt.Height = 0; bt.Width = 0; bt.BackColor = SystemColors.ButtonFace; bt.ForeColor = SystemColors.ControlText; this.Controls.Add(bt); buttonList.Add(bt); eventLogger = new EventLogger(eventLog, "meshStatusGUI", "Application", config.config.debugLevel); } } public void mainCallback(int status, Object data) { switch (status) { case 2: if(statusStrip.InvokeRequired) { mainCallback_delegate d = new mainCallback_delegate(mainCallback); this.Invoke(d, new object[] { status, data }); } else { statusLabel.Text = data.ToString(); } break; case 1: // monitor is started and running for device. if (this.InvokeRequired) { mainCallback_delegate d = new mainCallback_delegate(mainCallback); this.Invoke(d, new object[] { status, data }); } else { DateTime timeStamp = DateTime.Now; int i = 0; if (data != null) { foreach (meshInfo s in (List<meshInfo>)data) { buttonList[i].Text = s.getName + Environment.NewLine + s.getParent + " (" + s.getSNR + ")" + Environment.NewLine; if (s.getSNR >= 20) { buttonList[i].BackColor = Color.Green; buttonList[i].ForeColor = Color.White; } else if ( (s.getSNR < 20) & (s.getSNR >= 16) ) { buttonList[i].BackColor = Color.Yellow; buttonList[i].ForeColor = Color.Black; } else if ((s.getSNR <16) & (s.getSNR >= 1)) { buttonList[i].BackColor = Color.Red; buttonList[i].ForeColor = Color.Black; } else { buttonList[i].BackColor = Color.LightGreen; buttonList[i].ForeColor = Color.Black; } i++; } for (; i < 100; i++) { buttonList[i].Text = ""; buttonList[i].BackColor = SystemColors.ButtonFace; buttonList[i].ForeColor = SystemColors.ControlText; } } } break; case 0: if (this.InvokeRequired) { mainCallback_delegate d = new mainCallback_delegate(mainCallback); this.Invoke(d, new object[] { status, data }); } else { scanStatus = false; marcheArretToolStripMenuItem.Text = "Démarrage"; marcheArretToolStripMenuItem.Enabled = true; configurationToolStripMenuItem.Enabled = true; statusLabel.Text = "En attente de démarrage"; if (exitApp) { Application.Exit(); } } break; default: break; } } private void meshStatusGUI_FormClosing(object sender, FormClosingEventArgs e) { if (scanStatus) { e.Cancel = true; exitApp = true; pooler.threadRun = false; configurationToolStripMenuItem.Enabled = false; marcheArretToolStripMenuItem.Enabled = false; } } private void meshStatusGUI_Resize(object sender, EventArgs e) { int i = 0; splitHeight = statusStrip.Top - menuStrip1.Bottom; buttonHeight = splitHeight / 10; splitWidth = menuStrip1.Width ; buttonWidth = splitWidth / 10; for (int y = menuStrip1.Bottom; y < splitHeight ; y += buttonHeight) { for (int x = menuStrip1.Left; x < splitWidth ; x += buttonWidth) { buttonList[i].Location = new Point(x, y); buttonList[i].Height = buttonHeight; buttonList[i].Width = buttonWidth; i++; } } } private void configurationToolStripMenuItem_Click(object sender, EventArgs e) { meshConfigDialog md = new meshConfigDialog(config); md.ShowDialog(); } private void sortieToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void marcheArretToolStripMenuItem_Click(object sender, EventArgs e) { if (!scanStatus) { scanStatus = true; marcheArretToolStripMenuItem.Text = "Arrêt"; configurationToolStripMenuItem.Enabled = false; pooler = new wlcPooler(Convert.ToInt32(config.config.serverTimeout), config.config.serverAddress, config.Decrypt(config.config.userName), config.Decrypt(config.config.userPassword), mainCallback, eventLogger); } else { pooler.threadRun = false; marcheArretToolStripMenuItem.Enabled = false; } } } } <file_sep>/meshStatusServiceControl/serviceControlDialog.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.ServiceProcess; using meshUtils; using meshStatus; namespace meshStatusServiceControl { public partial class serviceControlDialog : Form { public serviceControlDialog() { InitializeComponent(); try { switch (serviceStatus("meshStatusService")) { case "Running": startButton.Text = "Arrêt"; statusLabel.Text = "Service démarrer"; break; case "Stopped": startButton.Text = "Démarrage"; statusLabel.Text = "Service arreter"; break; default: startButton.Text = "Désactivé"; startButton.Enabled = false; statusLabel.Text = "L'état du service est inconnue"; break; } } catch (Exception e) { startButton.Text = "!!! Erreur !!!"; startButton.Enabled = false; statusLabel.Text = e.ToString(); throw; } } private void startButton_Click(object sender, EventArgs e) { try { switch (serviceStatus("meshStatusService")) { case "Running": startButton.Text = "Démarrage"; statusLabel.Text = "Service en arret"; StopService("meshStatusService", 30000); statusLabel.Text = "Service arreter"; break; case "Stopped": startButton.Text = "Arrêt"; statusLabel.Text = "Service en démarrage"; StartService("meshStatusService", 30000); statusLabel.Text = "Service démarrer"; break; default: startButton.Text = "Désactivé"; startButton.Enabled = false; statusLabel.Text = "L'état du service est inconnue"; break; } } catch (Exception ex) { startButton.Text = "!!! Erreur !!!"; startButton.Enabled = false; statusLabel.Text = ex.ToString(); } } private void configButton_Click(object sender, EventArgs e) { meshConfigUtils config = new meshConfigUtils(); config.ReadXML(); meshConfigDialog md = new meshConfigDialog(config); md.ShowDialog(); switch (serviceStatus("meshStatusService")) { case "Running": switch (MessageBox.Show("Redémarrer le service?", "Service en marche", MessageBoxButtons.YesNo)) { case DialogResult.Yes: statusLabel.Text = "Redémarrage"; RestartService("meshStatusService", 30000); statusLabel.Text = "Service démarrer"; break; default: break; } break; default: break; } } public void StartService(string serviceName, int timeoutMilliseconds) { try { ServiceController service = new ServiceController(serviceName); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(timeoutMilliseconds)); } catch { statusLabel.Text = "Erreur lors du démarrage"; } } public void StopService(string serviceName, int timeoutMilliseconds) { ServiceController service = new ServiceController(serviceName); try { TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); } catch { // ... } } public void RestartService(string serviceName, int timeoutMilliseconds) { ServiceController service = new ServiceController(serviceName); try { int millisec1 = Environment.TickCount; TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); // count the rest of the timeout int millisec2 = Environment.TickCount; timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1)); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); } catch { // ... } } public String serviceStatus(string serviceName) { ServiceController service = new ServiceController("meshStatusService"); return service.Status.ToString(); } } } <file_sep>/meshUtils/meshConfigDialog.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using meshUtils; using System.Diagnostics; namespace meshStatus { public partial class meshConfigDialog : Form { meshConfigUtils config; // Content item for the combo box private class cbItem { public EventLogEntryType Value; public cbItem(EventLogEntryType value) { Value = value; } public override string ToString() { return Value.ToString(); } } public meshConfigDialog(meshConfigUtils cfg) { InitializeComponent(); config = cfg; userName.Text = config.Decrypt(config.config.userName); userPassword.Text = config.Decrypt(config.config.userPassword); serverAddress.Text = config.config.serverAddress; if (config.config.serverTimeout < config.minServerTimeout) { config.config.serverTimeout = config.minServerTimeout; } if (config.config.serviceTimeout < config.minServiceTimeout) { config.config.serviceTimeout = config.minServiceTimeout; } serverInterval.Text = config.config.serverTimeout.ToString(); serviceInterval.Text = config.config.serviceTimeout.ToString(); filePath.Text = config.config.filePath; if (config.config.debugLevel < EventLogEntryType.Error) { config.config.debugLevel = EventLogEntryType.Error; } if (config.config.debugLevel > EventLogEntryType.FailureAudit) { config.config.debugLevel = EventLogEntryType.FailureAudit; } debugCombo.Items.Add(new cbItem(EventLogEntryType.Error)); debugCombo.Items.Add(new cbItem(EventLogEntryType.Warning)); debugCombo.Items.Add(new cbItem(EventLogEntryType.Information)); debugCombo.Items.Add(new cbItem(EventLogEntryType.SuccessAudit)); debugCombo.Items.Add(new cbItem(EventLogEntryType.FailureAudit)); debugCombo.SelectedIndex = debugCombo.FindStringExact(config.config.debugLevel.ToString()); dateTimeFileName.Checked = config.config.dateTimeFileName; } private void meshConfigDialog_FormClosing(object sender, FormClosingEventArgs e) { switch (MessageBox.Show("Sauvegarder la configuration? ?", "Sortie", MessageBoxButtons.YesNoCancel)) { case DialogResult.Yes: config.config.userName = config.Encrypt(userName.Text); config.config.userPassword = config.Encrypt(userPassword.Text); config.config.serverAddress = serverAddress.Text; config.config.serverTimeout = Convert.ToInt32(serverInterval.Text); config.config.serviceTimeout = Convert.ToInt32(serviceInterval.Text); config.config.filePath = filePath.Text; cbItem tmp = (cbItem)debugCombo.SelectedItem; config.config.dateTimeFileName = dateTimeFileName.Checked; config.config.debugLevel = tmp.Value; config.WriteXML(); break; case DialogResult.No: break; default: e.Cancel = true; break; } } private void filePath_MouseClick(object sender, MouseEventArgs e) { FolderBrowserDialog fbd = new FolderBrowserDialog(); DialogResult result = fbd.ShowDialog(); config.config.filePath = fbd.SelectedPath; filePath.Text = config.config.filePath; } private void serverInterval_Validating(object sender, CancelEventArgs e) { if (Convert.ToInt32(serverInterval.Text) < config.minServerTimeout) { serverInterval.Text = config.minServerTimeout.ToString(); } } private void serviceInterval_Validating(object sender, CancelEventArgs e) { if (Convert.ToInt32(serviceInterval.Text) < config.minServiceTimeout) { serviceInterval.Text = config.minServiceTimeout.ToString(); } } private void debugCombo_SelectedIndexChanged(object sender, EventArgs e) { cbItem tmp = (cbItem)debugCombo.SelectedItem; } } } <file_sep>/meshStatus/meshConfigDialog.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using meshUtils; namespace meshStatus { public partial class meshConfigDialog : Form { meshConfigUtils config; public meshConfigDialog(meshConfigUtils cfg) { InitializeComponent(); config = cfg; userName.Text = config.Decrypt(config.config.userName); userPassword.Text = config.Decrypt(config.config.userPassword); serverAddress.Text = config.config.serverAddress; if (config.config.serverTimeout < 20) { config.config.serverTimeout = 20; } if (config.config.serviceTimeout < 60) { config.config.serviceTimeout = 60; } serverInterval.Text = config.config.serverTimeout.ToString(); serviceInterval.Text = config.config.serviceTimeout.ToString(); filePath.Text = config.config.filePath; } private void meshConfigDialog_FormClosing(object sender, FormClosingEventArgs e) { switch (MessageBox.Show("Sauvegarder la configuration? ?", "Sortie", MessageBoxButtons.YesNoCancel)) { case DialogResult.Yes: config.config.userName = config.Encrypt(userName.Text); config.config.userPassword = config.Encrypt(userPassword.Text); config.config.serverAddress = serverAddress.Text; config.config.serverTimeout = Convert.ToInt32(serverInterval.Text); config.config.serviceTimeout = Convert.ToInt32(serviceInterval.Text); if (config.config.serverTimeout < 20) { config.config.serverTimeout = 20; } if (config.config.serviceTimeout < 60) { config.config.serviceTimeout = 60; } config.config.filePath = filePath.Text; config.WriteXML(); break; case DialogResult.No: break; default: e.Cancel = true; break; } } private void filePath_MouseClick(object sender, MouseEventArgs e) { FolderBrowserDialog fbd = new FolderBrowserDialog(); DialogResult result = fbd.ShowDialog(); config.config.filePath = fbd.SelectedPath; filePath.Text = config.config.filePath; } } }
11cf9c1937d3abbc50b5bc1ef667d617217ce45b
[ "C#" ]
11
C#
EddyBeaupre/meshStatus
8e184f26a26c99eeac0e31d818f40f84ae591cb5
9d68c78b866f46b35f799b79d21bc1ec6bd96456
refs/heads/master
<repo_name>pullgo/huaweiweb<file_sep>/public/javascripts/script.js /*导航效果*/ var i = 0; $(".hw1_nav_left li").mouseover(function(){ i=$(this).index(); $(".hw1_menu_section").eq(i).css({"top":"48px","z-index":"1"}) .siblings().css({"top":"-500px","z-index":"-1"}); }) $(".hw1_nav_left li").mouseout(function(){ $(".hw1_menu_section").eq(i).css({"top":"-500px","z-index":"-1"}); },function(){ }) /*banner 自动切换*/ var a = 0; var s = 1; var time = 0; var time1 = 0; junmper(); clearInterval(time1); function junmper(){ s = a*-1500; $(".banner_conter_navdiv ul li").eq(a).addClass("bg").siblings().removeClass("bg"); $(".banner_conter_pic li").animate({left:s+'px'},1000); a++; if(a==3) a=0; } function showp(){ $(".banner_conter_pic li img").fadeOut(500).fadeIn(500); $(".banner_conter_pic li h1").fadeOut(500).fadeIn(500); $(".banner_conter_pic li h2").fadeOut(500).fadeIn(500); $(".banner_conter_pic .hw1_btn").fadeOut(300).fadeIn(300); $(".banner_conter_pic .hw1_btn_t").fadeOut(500).fadeIn(500); } time=setInterval("junmper()",2500); time1=setInterval("showp()",1500); /*点击左右切换*/ var z = 0; var d = 0; $(".prev").click(function(){ clearInterval(time); clearInterval(time1); $(".banner_conter_navdiv ul li").eq(a).addClass("bg").siblings().removeClass("bg"); d=$(this).index(); $(".banner_conter_pic ul li").eq(z).animate({left:"-1500px"},300); $(".banner_conter_pic ul li").eq(d).css("left","1500px"); $(".banner_conter_pic ul li").eq(d).animate({left:"0px"},300); z=d; }); $(".next").click(function(){ clearInterval(time); clearInterval(time1); $(".banner_conter_navdiv ul li").eq(a).addClass("bg").siblings().removeClass("bg"); $(".banner_conter_pic ul li").eq(z).animate({left:"1500px"},300); $(".banner_conter_pic ul li").eq(d).css("left","-1500px"); $(".banner_conter_pic ul li").eq(d).animate({left:"0px"},300); z=d; }); /*鼠标放上左右箭头消失效果*/ $(".banner_conter_pic ").hover(function(){ $(".prev").css("display","block"); $(".next").css("display","block"); },function(){ $(".prev").css("display","none"); $(".next").css("display","none"); }); /*鼠标放上字 和图片移动效果*/ for(var i=0;i<$(".content_inner_box").length;i++){ $(".content_inner_box").eq(i).mouseover(function(){ $(this).find("img").animate({"background":"rgba(0,0,0,0.5)"},100); $(this).find("p").animate({bottom:"23px"},500); $(this).find("h3").animate({bottom:"90px"},300); }) } <file_sep>/public/javascripts/login.js //鼠标点击输入框变色 $(".user").click(function(){ $(this).addClass("user-active").siblings().removeClass("user-active"); }) $(".password1").click(function(){ $(this).addClass("password1-active").siblings().removeClass("password1-active"); }) //登录验证 validate.js start... $("#reg").validate(); /* rules:{ use:{ required:true, minlength:2, }, password1:{ required:true, minlength:6, }, }, massages:{ use:{ required : "账号不得为空", minlength: "账号不得少于2位", remote:'账号被占用!', }, password1:{ required:"密码不得为空!", minlength:"长度不得少于6位!", }, }, }); */ //登录验证 validate.js ending.. //邮箱自动补全 start... //数据源的使用 $("#reg").autocomplete({ delay:0,//延迟出现 autoFocus:true,//默认选中第一个 source:function(request,response){ var hosts = ['qq.com','163.com','263.com','sina.com.cn','gmail.com','hotmail.com'], term = request.term,//获取用户输入的内容 name = term,//邮箱的用户名 host = '',//域名 ix = term.indexOf('@'),//@的位置 result = [];//最终出现的邮箱列表 //当有@的时候重新分配用户名和域名 result.push(term);//不在数据源中的重新加上去 if(ix > -1){ name = term.slice(0,ix); host = term.slice(ix + 1); } if(name){ //如果用户输入@以及后面的域名则提示相对于的域名 //如果还没有输入@以及后面的域名则提示全部域名 var findedHosts = []; if(host){ findedHosts = $.grep(hosts,function(value,index){ return value.indexOf(host) > -1 }); }else{ findedHosts = hosts; } var findedResult = $.map(findedHosts,function(value,index){ return name + '@' + value; }); result = result.concat(findedResult);//避免与前面的result覆盖 } response(result); }, }); //邮箱自动补全 ending.... <file_sep>/public/javascripts/add.php <?php /*header("Content-Type:text/html;charset=utf-8"),*/ sleep(3); /*echo"<h2>你好<h2>";*/ required ('config.php'); $query = "INSERT INTO user (user,pass,email,sex,birthday,date) VALUES ('{$_GET['user']}',sha1('{$_GET['pass']}'),'{$_GET['email']}','{$_GET['sex']}','{$_GET['birthday']}',NOW())"; mysql_query($query) or die('新增失败! '.mysql_error()); echo mysql_affected_rows(); mysql_close(); ?><file_sep>/routes/index.js var express = require('express'); var indexRouter = express.Router(); /* GET home page. */ indexRoute.post("http://www.edaoj.com/login",function(req,res){ res.send({username:req.params.username,password:req.params.password}); }) module.exports = indexRoute;
e3bbc88f29d7e361f56a69bd84c148c7f5a0dd45
[ "JavaScript", "PHP" ]
4
JavaScript
pullgo/huaweiweb
0099626054bfd3e0a099e5df1aeafdc57f382a06
ba459537b5ef20a4bf9cc2fbf1ebf21259b65288
refs/heads/master
<file_sep>tap "homebrew/bundle" tap "homebrew/cask" tap "homebrew/cask-drivers" tap "homebrew/cask-versions" tap "homebrew/core" tap "paulp/extras" brew "ammonite-repl" brew "consul" brew "git" brew "giter8" brew "gradle" brew "htop" brew "jenv" brew "mas" brew "node" brew "ntfs-3g" brew "p7zip" brew "tree" brew "vault" brew "vim" brew "youtube-dl" brew "zsh" brew "zsh-autosuggestions" brew "zsh-syntax-highlighting" brew "paulp/extras/sbtx", args: ["HEAD"] cask "android-file-transfer" cask "atom" cask "digikam" cask "discord" cask "docker" cask "evernote" cask "google-chrome" cask "ichm" cask "iterm2" cask "java" cask "java8" cask "kiibohd-configurator" cask "libreoffice" cask "postman" cask "slack" cask "spectacle" cask "virtualbox" cask "visual-studio-code" mas "Amphetamine", id: 937984704 <file_sep># My dotfiles ## Installation ``` cd ~ git clone --bare https://github.com/jchoffmann/dotfiles.git .dot source .zshrc dot checkout dot config --local status.showUntrackedFiles no ``` See also: https://developer.atlassian.com/blog/2016/02/best-way-to-store-dotfiles-git-bare-repo/ ## Dotfile inspirations: * https://github.com/mathiasbynens/dotfiles * https://github.com/ahmetb/dotfiles
8e4c287c85c1bcfbb3f1d0aa182c9355ddb5afee
[ "Markdown", "Ruby" ]
2
Ruby
jchoffmann/dotfiles
a89d3981f313e0cd51c97e4cf98e13bcda2eaf44
0858e392fb841ba2738317a64f3fae6d35b16da1
refs/heads/lineage-15.1
<repo_name>OriginalBugsX/device_motorola_woods<file_sep>/README.md # Device Tree for Motorola E4 (8.0 , 3.18.35+) The Moto E4 (codenamed _"woods"_) is a mid-range smartphone from Motorola. ![Moto E4](https://github.com/dev4wds/local_manifest/raw/los-14.1/device/motorola-moto-e4.jpg "Moto E4") Basic | Spec Sheet -------:|:------------------------- CPU | Quad-core 1.3 GHz Cortex-A53 Chipset | MediaTek MT6737 GPU | Mali-T720 Memory | 2GB RAM Shipped Android Version | 7.1 Storage | 16GB MicroSD | Up to 64GB Battery | Li-Pol 2800mAh battery Display | 720 x 1280 pixels, 5.0 inches Camera | Main 8MP / Front 5MP, autofocus, LED flash Copyright 2017 - The LineageOS Project. Thanks to olegsvs, danielhk, Zormax, xcore995, SRT. Credit : - @darklord4822 ### Working: - [x] Wifi - [x] Sound - [x] LiveDisplay - [ ] Ril - [ ] Codecs - [ ] Camera, flashlight - [x] Radio - [ ] Fingerprint - [ ] Bluetooth - [x] Sensors - [ ] Hotspot - ... ### NOTE with nano editor, edit these files by Commenting out the line : in ( system/sepolicy/public ) domain.te [ line number : 227 on 15.0 & or 230 on 15.1 ] in ( system/core/init ) init.cpp [ line number : 401 on 15.0 & or 434 on 15.1 ] example : Comment line : 230 `nano +230 system/sepolicy/public/domain.te` Comment line : 434 `nano +434 system/core/init/init.cpp` now ..., Copy ```SkUserConfig.h``` & ```SkUserConfigManual.h``` to destination ```external/skia/include/core``` with below command ``` cp external/skia/include/config/SkUserConfig.h external/skia/include/core cp external/skia/include/config/SkUserConfigManual.h external/skia/include/core ``` <file_sep>/vendorsetup.sh # for var in eng user userdebug; do add_lunch_combo lineage_woods-$var done # Patches cd system/core git apply -v ../../device/motorola/woods/patches/0001-system_core.patch cd ../.. cd hardware/interfaces git apply -v ../../device/motorola/woods/patches/0002-hardware_interfaces.patch cd ../.. echo " ============ " echo " ============ " echo "PATCH DONE !!!" echo "" echo "" <file_sep>/patches/check-patches.sh #!/bin/bash cd ../../../.. cd system/core git apply -v --check ../../device/motorola/woods/patches/0001-system_core.patch cd ../.. cd hardware/interfaces git apply -v --check ../../device/motorola/woods/patches/0002-hardware_interfaces.patch cd ../..
683a8767f533d91fb7dcb23530441d43e0306b33
[ "Markdown", "Shell" ]
3
Markdown
OriginalBugsX/device_motorola_woods
9e3eaae55f76a8b64db914bdfc80c02edba763e9
d8f2ee1ec7475e26fbaa4cb1a17d6d26783c9bea
refs/heads/master
<repo_name>mootez/Bananas<file_sep>/Resources/ui/common/WindowGroup.js //function WindowGroup(parentWin, title) { function WindowGroup(title, controller) { //function WindowGroup(title) { //var NavigationController = require('ui/common/NavigationController'); //controller = new NavigationController(); var self = Ti.UI.createWindow({ title:title, backgroundColor:'white' }); var win_child = Ti.UI.createWindow({ title: L('newWindow'), backgroundColor: 'white' }); var win_grandchild = Ti.UI.createWindow({ title: L('newWindow'), backgroundColor: 'white' }); var button = Ti.UI.createButton({ height:44, width:200, title:L('openWindow'), top:20 }); self.add(button); var addWinToTab = function(nextWindow) { //parentWin.containingTab.open(nextWindow); controller.open(nextWindow); //Ti.UI.currentTab.open(nextWindow); // This is an option, but I don't think that's what we want }; button.addEventListener('click', function() { //containingTab attribute must be set by parent tab group on //the window for this work //parentWin.containingTab.open(win_child); controller.open(win_child); }); var button_child = Ti.UI.createButton({ height:44, width:200, title:L('openWindow'), top:20 }); button_child.addEventListener('click', function() {addWinToTab(win_grandchild)}); win_child.add(button_child); //button_child.addEventListener('click', function() { //containingTab attribute must be set by parent tab group on //the window for this work // self.containingTab.open(win_grandchild); //}); return self; }; module.exports = WindowGroup; <file_sep>/Resources/ui/common/TableWindow.js function TableWindow(controller) { var FruitWindow = require('ui/common/FruitWindow'); var WindowGroup = require('ui/common/WindowGroup'); var ListGroup = require('ui/common/ListGroup'); var TestWindow = require('ui/common/TestWindow'); var self = controller.createWindow('Table Window'); var tableData = [ {title:'Apples', price:'1.25', color: 'black', hasChild:true}, {title:'Grapes', price:'1.50', color: 'black', hasChild:true}, {title:'Oranges', price:'2.50', color: 'black', hasChild:true}, {title:'Bananas', price:'1.50', color: 'black', hasChild:true}, {title:'Pears', price:'1.40', color: 'black', hasChild:true}, {title:'Kiwis', price:'1.00', color: 'black', hasChild:true} ]; var table = Ti.UI.createTableView({ data:tableData }); self.add(table); var fruitWins = []; for (var i = 0; i < tableData.length; i++) { if (tableData[i].title == 'Grapes') { fruitWins[i] = new TestWindow(controller); } else if (tableData[i].title == 'Bananas') { fruitWins[i] = new ListGroup(tableData[i].title, controller); } else { fruitWins[i] = new FruitWindow(tableData[i].price, tableData[i].title, controller); } } //add behavior table.addEventListener('click', function(e) { Ti.API.info("I clicked on row " + e.index + " with title " + e.rowData.title); controller.open(fruitWins[e.index]); }); return self; }; module.exports = TableWindow; <file_sep>/Resources/ui/common/FruitWindow.js function FruitWindow(price, title, controller) { var self = controller.createWindow(title); var view = Ti.UI.createView(); var label = Ti.UI.createLabel({ text: '$' + price, height:'auto', width:'auto', color:'#000' }); view.add(label); self.add(view); return self; }; module.exports = FruitWindow;
9ff2b9d88fa093e074bcd06b29c63ff054397f00
[ "JavaScript" ]
3
JavaScript
mootez/Bananas
e679698f97f9a5b7f96a3e7d4c4cd3a5d669dde3
cd67d7e72b952fac4b764f02e245de51a6e07cf6
refs/heads/master
<repo_name>FranciszekKorga/gitrepoo<file_sep>/README.md # gitrepoo Repozyterium dla nam ## Polecenia git-a: 1) *git status* - pokazuje zmiany w repozytoriium 2) git pull - sciaga ewentualne zmiany z repozytorium zdalnego 3) git add . - dodanie plikow i zmian do repozytorium ' 4) git commit -"opis zmian" - zatwierzdzenie zmian 5) git push - wysylanie zmian do repozytorium zdlanego <file_sep>/Python/petla2.py #!/usr/bin/env python # -*- coding: utf-8 -*- def suma_parzystych(): wynik = 0 for i in range(0,101,2): print(i) wynik = wynik + i print(wynik) def suma_nieparzystych(): wynik = 0 for i in range(0,101,3): wynik - wynik + i print(wynik) def sumuj_liczby(): """ funkcja pobiera ;iczby od uzytkownika i sumuje dopkuji suma nie przekroczy wartosci 75. """ suma = 0 while suma < 75: liczba = int(input('Podaj liczbe: ')) suma = suma + liczba print("suma liczba:", suma) def main(args): sumuj_liczby() # [0, 1, 2, 3, 4] # suma_parzystych() # suma_nieparzystych() return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv))
e2153af769116677b8a60c2dd6a63babba7e6874
[ "Markdown", "Python" ]
2
Markdown
FranciszekKorga/gitrepoo
e2105f93567d4fd559240643f58aab0313ab7e9e
3a728471758fb0c8307e20e3b4b330a2c1a3bef9
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public GameObject player; public Transform SpawnPoint; // Update is called once per frame void Update () { PlayerTarget playerTarget = player.GetComponent<PlayerTarget>(); if (playerTarget.IsDead == true) { playerTarget.IsDead = false; player.transform.position = SpawnPoint.position; player.SetActive(true); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Grenade : MonoBehaviour { public float delay = 3f; public float radius = 5f; public float force = 700f; public float DamageAmount = 40f; public GameObject explosionEffect; public GameObject HealthBar; public GameObject gernadeExplosion; float countdown; bool hasExploded = false; // Use this for initialization void Start () { countdown = delay; } // Update is called once per frame void Update () { countdown -= Time.deltaTime; if (countdown <= 0 && !hasExploded) { Explode(); hasExploded = true; Destroy(gernadeExplosion, 1.8f); } } void Explode () { gernadeExplosion = Instantiate(explosionEffect, transform.position, transform.rotation); Collider [] colliders = Physics.OverlapSphere(transform.position, radius); foreach (Collider nearbyObject in colliders) { ZombieTarget target = nearbyObject.GetComponent<ZombieTarget>(); if (target != null) { target.TakeDamage(30); } EnemyHealthBar stats = nearbyObject.GetComponent<EnemyHealthBar>(); if (stats != null) { stats.ChangeHealth(-30); } } Destroy(gameObject); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ZombieSpawner : MonoBehaviour { public GameObject zombie; private Vector3 RandomPosition; // Use this for initialization void Start () { InvokeRepeating("SpawnZombie", 1, 2); } // Update is called once per frame void Update () { RandomPosition.x = Random.Range(.5f, 4f); RandomPosition.z = Random.Range(.5f, 4f); RandomPosition.y = 0; } void SpawnZombie () { Instantiate(zombie, transform.position + RandomPosition, Quaternion.identity); } } <file_sep>using System.Collections; using UnityEngine; public class GunScript : MonoBehaviour { public float damage = 10f; public float fireRate = 15f; public float CurrentAmmo; public float MaxAmmoInClip; public float MaxAmmo; public float ReloadTime = 1f; public float Smooth = .5f; float bulletDistance; public float minDamage; public float maxDamage; public float dropOffStart; public float dropOffEnd; public Canvas Crosshair; public Animator anim; public ParticleSystem muzzleFlash; public Quaternion EmptyOriginalRotation; public GameObject Empty; public GameObject hitPointGB; public Animator animator; public Camera fpsCam; public Transform gunEnd; public float RecoilAmount = 2f; Vector3 Recoil; private float nextTimeToFire = 0f; private void Start() { EmptyOriginalRotation = new Quaternion(0,0,0,0); } // Update is called once per frame void Update () { if (Input.GetButton("Fire1") && CurrentAmmo > 0 && Time.time >= nextTimeToFire && MaxAmmo > 0) { muzzleFlash.Play(); nextTimeToFire = Time.time + 1f / fireRate; Shoot(); animator.SetBool("IsShooting", true); CurrentAmmo--; } else { animator.SetBool("IsShooting", false); } StartCoroutine(RecoilReset()); #region ADS if (Input.GetMouseButton(1)) { fpsCam.fieldOfView = 30f; RecoilAmount = 0.01f; } else { RecoilAmount = .05f; fpsCam.fieldOfView = 60f; } if (Input.GetMouseButton(1) && Input.GetKey(KeyCode.Alpha1) || Input.GetMouseButton(1) && Input.GetKey(KeyCode.Alpha3)) { animator.SetBool("ADS", false); fpsCam.fieldOfView = 60f; Crosshair.enabled = true; } #endregion ADS #region Reloading Input if (Input.GetKeyDown(KeyCode.R) && MaxAmmo > 0) { StartCoroutine(Reloading()); } #endregion Reloading Input } void Shoot () { RaycastHit hit; if (Physics.Raycast(fpsCam.transform.position, (fpsCam.transform.forward + UnityEngine.Random.insideUnitSphere * RecoilAmount).normalized, out hit)) { bulletDistance = hit.distance; if (bulletDistance <= dropOffStart) { ZombieTarget target = hit.transform.GetComponent<ZombieTarget>(); if (target != null) { target.TakeDamage(maxDamage); } } if (bulletDistance >= dropOffEnd) { ZombieTarget target = hit.transform.GetComponent<ZombieTarget>(); if (target != null) { target.TakeDamage(minDamage); } } GameObject impactGO = Instantiate(hitPointGB, hit.point, Quaternion.LookRotation(hit.point)); Destroy(impactGO, 2f); Empty.transform.Rotate(new Vector3(-.3f, 0, 0)); EnemyHealthBar stats = hit.transform.GetComponent<EnemyHealthBar>(); if (stats) { stats.ChangeHealth(-10); } } else { Destroy(Instantiate(hitPointGB), 2f); } } #region Reloading private IEnumerator Reloading () { float bulletsToLoad = MaxAmmoInClip - CurrentAmmo; float bulletsToDeduct = (MaxAmmo >= bulletsToLoad) ? bulletsToLoad : MaxAmmo; yield return new WaitForSeconds(ReloadTime); MaxAmmo -= bulletsToDeduct; CurrentAmmo += bulletsToDeduct; } #endregion Reloading private IEnumerator RecoilReset() { for (float duration = 1; duration >= 0; duration -= .1f) { Empty.transform.rotation = Quaternion.Slerp(Empty.transform.rotation, EmptyOriginalRotation, Smooth); yield return new WaitForSeconds(.01f); } if (Input.GetButtonUp("Fire1") || CurrentAmmo == 0) { for (float duration = 1; duration >= 0; duration -= .1f) { Empty.transform.rotation = Quaternion.Slerp(new Quaternion(0, 0, 0, 0), new Quaternion(0, 0, 0, 0), Smooth); yield return new WaitForSeconds(.01f); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SniperShoot : MonoBehaviour { public Camera fpsCam; public Canvas Crosshair; public Animator animSniper; public Animator animArms; public GameObject hitPointGB; public GameObject Empty; public float damage; public float range; public float RecoilAmount; public float ReloadTime; public float FireRate; public float currentAmmo; public float maxAmmo; private float NextTimeToFire = 0f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0) && currentAmmo > 0 && Time.time >= NextTimeToFire) { NextTimeToFire = Time.time + 1f / FireRate; Shoot(); currentAmmo--; Empty.transform.Rotate(new Vector3(-20f, 0, 0)); } if (Input.GetMouseButton(1)) { animSniper.SetBool("IsScoped", true); animArms.SetBool("ADS", true); Crosshair.enabled = false; RecoilAmount = 0; } else { RecoilAmount = .2f; animSniper.SetBool("IsScoped", false); animArms.SetBool("ADS", false); Crosshair.enabled = true; } if (Input.GetKey(KeyCode.Alpha1) || Input.GetKey(KeyCode.Alpha3)) { fpsCam.fieldOfView = 60f; Crosshair.enabled = true; } if (Input.GetKeyDown(KeyCode.R)) { StartCoroutine(Reload()); } } void Shoot () { RaycastHit hit; if (Physics.Raycast(fpsCam.transform.position, (fpsCam.transform.forward + UnityEngine.Random.insideUnitSphere * RecoilAmount).normalized, out hit, range)) { Instantiate(hitPointGB, hit.point, Quaternion.identity); ZombieTarget target = hit.transform.GetComponent<ZombieTarget>(); if (target != null) { target.TakeDamage(damage); } EnemyHealthBar stats = hit.transform.GetComponent<EnemyHealthBar>(); if (stats) { stats.ChangeHealth(-50); } } } private IEnumerator Reload() { yield return new WaitForSeconds(ReloadTime); currentAmmo = maxAmmo; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GernadeShoot : MonoBehaviour { public GameObject gernadePrefab; public GameObject gunEnd; public float GernadeCurrentAmmo = 1; float ReloadTime = 3; // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0) && GernadeCurrentAmmo > 0) { ShootGernade(); GernadeCurrentAmmo--; } if (Input.GetKeyDown(KeyCode.R)) { StartCoroutine(Reloading()); } } void ShootGernade () { Rigidbody gernadeClone; gernadeClone = Instantiate(gernadePrefab, gunEnd.transform.position, gunEnd.transform.rotation).GetComponent<Rigidbody>(); gernadeClone.velocity = transform.TransformDirection(Vector3.forward * 20); } private IEnumerator Reloading() { Debug.Log("GernadeReloading"); yield return new WaitForSeconds(ReloadTime); GernadeCurrentAmmo = 1; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class ZombieScript : MonoBehaviour { public Animator anim; public GameObject player; private NavMeshAgent nav; public Vector3 DistanceBetweenPlayerAndZombie; private AudioSource zombieAudio; // Use this for initialization void Awake () { nav = GetComponent<NavMeshAgent>(); zombieAudio = GetComponent<AudioSource>(); } // Update is called once per frame void Update () { DistanceBetweenPlayerAndZombie = transform.position - player.transform.position; if (DistanceBetweenPlayerAndZombie.magnitude <= 30) { nav.SetDestination(player.transform.position); anim.SetBool("IsWalking", true); } else { anim.SetBool("IsWalking", false); nav.SetDestination(gameObject.transform.position); } //AUDIO if (DistanceBetweenPlayerAndZombie.magnitude <= 10) { zombieAudio.volume = .4f; } else if (DistanceBetweenPlayerAndZombie.magnitude <= 20) { zombieAudio.volume = .25f; } else if (DistanceBetweenPlayerAndZombie.magnitude <= 30) { zombieAudio.volume = .1f; } else { zombieAudio.volume = 0; } } public void OnTriggerEnter(Collider other) { if (GameObject.FindGameObjectWithTag("Player")) { InvokeRepeating("Attack", .5f, 1); anim.SetBool("IsAttacking", true); } } public void OnTriggerExit(Collider other) { CancelInvoke("Attack"); anim.SetBool("IsAttacking", false); } public void Attack() { PlayerTarget target = player.transform.GetComponent<PlayerTarget>(); if (target != null) { target.PlayerDamage(10); } } } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.AI; public class ZombieTarget : MonoBehaviour { public Animator anim; public GameObject Zombie; public float health = 50f; public float DieTime; private NavMeshAgent nav; public Canvas healthbar; public GameObject player; public void TakeDamage(float amount) { health -= amount; if (health <= 0f) { nav = GetComponent<NavMeshAgent>(); nav.enabled = false; anim.SetTrigger("IsDead"); anim.SetBool("IsWalking", false); StartCoroutine(Die()); } } private IEnumerator Die () { yield return new WaitForSeconds(DieTime); Destroy(healthbar); Destroy(gameObject); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerTarget : MonoBehaviour { public GameObject player; public float health = 200; public bool IsDead = false; public void PlayerDamage (float amount) { health -= amount; if (health <= 0) { Die(); } } void Die() { player.SetActive(false); IsDead = true; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraZoom : MonoBehaviour { public float fieldOfView = 60f; // Use this for initialization void Start () { Camera.main.fieldOfView = fieldOfView; } // Update is called once per frame void Update () { if (Input.GetMouseButton(1)) { Camera.main.fieldOfView = 30f; } else { Camera.main.fieldOfView = fieldOfView; } } }
7003862fbacdd2dce59830986c4e8332d0d5dca7
[ "C#" ]
10
C#
Eletrax/GameShowcase
75e1100d39c7f9aece2bb4c6b148dc47dd45ec6a
1fafb88ca85757f7614fcc6e8c6c549ae46cf094
refs/heads/main
<repo_name>thaerbraizat/city-explorer-api<file_sep>/models/movies.model.js class Movies { constructor(movies) { this.title = movies.original_title; this.votes = movies.vote_count; this.img = "https://image.tmdb.org/t/p/w200" + movies.poster_path; // http://image.tmdb.org/t/p/w185/nBNZadXqJSdt05SHLqgT0HuC5Gm.jpg } } module.exports=Movies;<file_sep>/README.md # city-explorer-api ## Author: <NAME> ## Version: 1.0.0 ## Overview This is an api server for my city explorer app. getting the weather for the searched region. and it's a search about all movies based on city name. ## Getting Started Enter the name of the city or region you want to display the map and weather for 16 days and all movies have cityname , and then click on Explore. ## Architecture This is build as a server using node js and express. ## Change Log 28th June 2021, lab07 (creating back end app and connect it with front end in lab 06) Credit and Collaborations [youtube channel](https://www.youtube.com/channel/UCFbNIlppjAuEX4znoulh0Cw) [web request-response cycle](image/206039358_897750141085215_5794384071806934268_n.jpg)
2ba6c467add37336dd563804fddb3ebfb3bdc63b
[ "JavaScript", "Markdown" ]
2
JavaScript
thaerbraizat/city-explorer-api
9d5b10b7015d57919ef0a15ccf008edea3f8c0a9
60841010fa5e3b57bcf100e3131d3b98f0ffbc2a
refs/heads/master
<repo_name>stricklerxc/simple-security-groups-example<file_sep>/requirements.txt cfn-flip==1.2.2 click==7.1.1 PyYAML==5.3.1 six==1.14.0 troposphere==2.6.0 <file_sep>/simple_sg/parse.py import re import yaml from troposphere import Ref from troposphere.ec2 import SecurityGroup, SecurityGroupIngress def parse_yaml(file): with open(file, 'r') as file_handler: return yaml.load(file_handler.read(), Loader=yaml.Loader) def parse_rule(rule): sg_regex = re.compile( r"^(udp|tcp|icmp|all|icmpv6)?:?/?/?" # Match Protocol r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2}):" # Match CIDR r"(\d{1,5})-?(\d{1,5})?" # Match Ports ) protocol, cidr, from_port, to_port = sg_regex.match(rule).groups() if not protocol: protocol = 'tcp' elif protocol == 'all': protocol = '-1' if not to_port: to_port = from_port return (protocol, cidr, int(from_port), int(to_port)) def create_sg(**kwargs): sg = SecurityGroup( kwargs['id'], GroupName=kwargs['name'], GroupDescription=kwargs['description'] ) return sg def create_sg_ingress_rules(source_sg, rules): rule_objs = [] for rule in rules: _id, definition, description = rule.split(' | ') ingress_obj = SecurityGroupIngress( f'{source_sg.title}{_id}Ingress', Description=description, GroupId=Ref(source_sg)) (ingress_obj.IpProtocol, ingress_obj.CidrIp, ingress_obj.FromPort, ingress_obj.ToPort) = parse_rule(definition) rule_objs.append(ingress_obj) return rule_objs <file_sep>/README.md # Simple Security Groups - Example ## Overview Example repository for simplifying security group management. ## Requirements 1. Python 3+ 2. AWS Account ## Usage 1. Install necessary packages ```bash $ pip install -r requirements.txt ``` 2. Add Security Group Definition to example.yml ```yaml - id: <Logical ID for CloudFormation Resource> name: <GroupName> description: <GroupDescription> rules: ingress: - <Logical ID for SecurityGroupIngress Resource> | <IpProtocol>://<CIDR Block>:<Port(s)> | <Description> ``` 3. Execute module to print out CloudFormation Template ```bash $ python -m simple_sg Description: CloudFormation Template for dynamic Security Groups (generated by Troposphere) Outputs: TestSecurityGroup: Description: Test Security Group Value: !Ref 'TestSecurityGroup' Resources: TestSecurityGroup: Properties: GroupDescription: Test Security Group GroupName: Test SG Type: AWS::EC2::SecurityGroup TestSecurityGroupNetworkHttpIngress: Properties: CidrIp: 192.168.1.0/8 Description: Allow HTTP Traffic from internal network. FromPort: 80 GroupId: !Ref 'TestSecurityGroup' IpProtocol: tcp ToPort: 80 Type: AWS::EC2::SecurityGroupIngress TestSecurityGroupNetworkSshIngress: Properties: CidrIp: 192.168.1.1/8 Description: Allow SSH Traffic from internal network. FromPort: 22 GroupId: !Ref 'TestSecurityGroup' IpProtocol: tcp ToPort: 22 Type: AWS::EC2::SecurityGroupIngress TestSecurityGroupNetworkTcpIngress: Properties: CidrIp: 192.168.1.0/24 Description: Allow all tcp traffic from subnet. FromPort: 0 GroupId: !Ref 'TestSecurityGroup' IpProtocol: tcp ToPort: 65535 Type: AWS::EC2::SecurityGroupIngress TestSecurityGroupNetworkUdpIngress: Properties: CidrIp: 192.168.1.0/24 Description: Allow all udp traffic from subnet. FromPort: 0 GroupId: !Ref 'TestSecurityGroup' IpProtocol: udp ToPort: 65535 Type: AWS::EC2::SecurityGroupIngress ```<file_sep>/simple_sg/__main__.py import simple_sg.parse from troposphere import Output, Ref, Template template = Template( Description='CloudFormation Template for dynamic Security Groups (generated by Troposphere)' ) security_groups = simple_sg.parse.parse_yaml('example.yml') for sg_definition in security_groups: sg = simple_sg.parse.create_sg(**sg_definition) sg_output = Output( sg_definition['id'], Description=sg_definition['description'], Value=Ref(sg)) template.add_resource(sg) template.add_output(sg_output) rules = simple_sg.parse.create_sg_ingress_rules( sg, sg_definition['rules']['ingress'] ) template.add_resource(rules) print(template.to_yaml())
8f8a56908675020e4dd2b3b5859fe769727c1d11
[ "Markdown", "Python", "Text" ]
4
Text
stricklerxc/simple-security-groups-example
39d1a0b4a573395e82ec557995c89e10c2009552
95278da4e405b0f8d16dfcdcfb4402993926db5c
refs/heads/main
<repo_name>JazDonofrio/POO-Python<file_sep>/JazDonofrio/caja_de_ahorro.py """ Ejercicio 1: Modelar el objeto caja de ahorro: - un titular - un saldo y debera poder: - depositar un monto - puedeExtraer un monto - extraer un monto - en el caso de querer extraer un monto superior al monto disponible arrojara una excepcion ValueError("Imposible realizar extracción.") Realizar los test necesarios que validen el comportamiento. """ print("Hola")
e739b14c7ba1c41ba38b8b5399af2e3fc40363ee
[ "Python" ]
1
Python
JazDonofrio/POO-Python
bd84cf997d0c20c43e5ada5abb69003d2d0f4dbc
2c60a47ab61832df732bab40ed2312b2c276bd46
refs/heads/master
<repo_name>paramana/email<file_sep>/examples/index.php <?php require __DIR__ . '/../vendor/autoload.php'; require "messages.php"; require "config.php"; require "../email.class.php"; $mail_maps = [ "contact" => [ "subject" => ["default" => "People Contacting"], "email_to" => ["default" => "<EMAIL>"], "email_cc" => ["default" => "<EMAIL>"], "email_bcc" => ["default" => "<EMAIL>"], "name" => ["id" => "from_name", "strip" => true, "required" => true], "email" => ["id" => "email_from", "strip" => true, "default" => '<EMAIL>', "validate" => "email"], "message" => ["strip" => true], "extra_msg" => ["strip" => true] ] ]; $email = Email::i(); $email->set_mail_maps($mail_maps); $email->send("contact", [ "subject" => "hey mate", "name" => "me", "email" => "<EMAIL>", "message" => "how are you?", "extra_msg"=>"again?" ]); <file_sep>/templates/contact.html.php This e-mail is from: <strong><?= $from_name ?></strong> <br /> with email: <strong><?= $email_from ?></strong> <br /> <?= $from_name ?> wrote: <br /> <p> <?= $message ?> <?= $param["extra_msg"] ?> </p><file_sep>/email.class.php <?php // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; /** * A class for sending email with PHPMailer */ class Email { /** * if not present, nothing will be executed - Fatal error */ private static $instance; /** @var Securimage */ private $Securimage; /* * The mapping of mailing types and fields */ private $mail_maps = []; /* * The mapping of SMTP configuration */ private $smtp_config_map = []; /* * The default name */ private $default_name = ""; /* * The default email address */ private $default_email = ""; /* * The location of the email templates */ private $template_dir = ""; /* * A honey pot field to protect from spam */ private $honeypot_field = "honeypot"; private $use_smtp = false; public $print_output = true; public $debug = 0; private $smtp_auth; private $smtp_secure; private $smtp_host; private $smtp_port; private $smtp_username; private $smtp_password; private function __construct() { if (isset(static::$instance)) { throw new Exception("An instance of " . get_called_class() . " already exists."); } if (defined("EMAIL_DEBUG") && EMAIL_DEBUG == true) { $this->debug = 3; } if (defined("EMAIL_DEFAULT_NAME")) { $this->default_name = EMAIL_DEFAULT_NAME; } if (defined("EMAIL_DEFAULT_ADDRESS")) { $this->default_email = EMAIL_DEFAULT_ADDRESS; } if (defined("EMAIL_HONEYPOT_FIELD")) { $this->honeypot_field = EMAIL_HONEYPOT_FIELD; } $this->template_dir = defined("EMAIL_TEMPLATES_DIR") ? EMAIL_TEMPLATES_DIR : __DIR__ . "/templates/"; if (defined("MAIL_SMTP_CONFIG") && !empty(MAIL_SMTP_CONFIG)) { $this->use_smtp = true; if (file_exists(MAIL_SMTP_CONFIG)) { require_once(MAIL_SMTP_CONFIG); $this->smtp_auth = $smtp_auth; $this->smtp_secure = $smtp_secure; $this->smtp_host = $smtp_host; $this->smtp_port = $smtp_port; $this->smtp_username = $smtp_username; $this->smtp_password = $<PASSWORD>; } } else if (defined("SMTP_ENABLED") && !empty(SMTP_ENABLED) && defined("SMTP_USERNAME")) { $this->use_smtp = true; $this->smtp_auth = SMTP_AUTH; $this->smtp_secure = SMTP_SECURE; $this->smtp_host = SMTP_HOST; $this->smtp_port = SMTP_PORT; $this->smtp_username = SMTP_USERNAME; $this->smtp_password = <PASSWORD>; } } /** * No clone allowed, * both internally and externally */ private function __clone() { throw new Exception("An instance of " . get_called_class() . " cannot be cloned."); } /** * the common sense method to retrieve the instance */ final public static function i() { return isset(static::$instance) ? static::$instance : static::$instance = new static; } /** * PHP5 style destructor * * @return bool true */ function __destruct() { return true; } /** * * Sets the mail maps * * @param array $mail_maps */ public function set_mail_maps($mail_maps = []) { $this->mail_maps = $mail_maps; } public function set_smtp_config_map($smtp_config_map = []) { if (empty($smtp_config_map)) { return; } $this->use_smtp = true; $this->smtp_config_map = $smtp_config_map; } public function set_secure_image_class($Securimage) { $this->Securimage = $Securimage; } private function _response_output($status = "SUCCESS", $message = "", $opt = []) { if (!$this->print_output) { if ($status != "SUCCESS") { return ["status" => $status, "message" => $message]; } return $message; } return response_message($status, $message, $opt); } /** * Sends an email * * @param array $param email parameters * @param array $attachments * * @return boolean true on success * @throws phpmailerException */ private function _send_email($param, $attachments) { if (!isset($param["email_to"])) { return false; } $email_to = trim($param["email_to"]); if (empty($email_to)) { return false; } $email_cc = !empty($param['email_cc']) ? $param['email_cc'] : ''; $email_bcc = !empty($param['email_bcc']) ? $param['email_bcc']: ''; $email_from = !empty($param["email_from"]) ? $param["email_from"] : $this->default_email; $email_reply = !empty($param["email_reply"]) ? $param["email_reply"] : $email_from; $from_name = !empty($param["from_name"]) ? $param["from_name"] : $this->default_name; $subject = !empty($param["subject"]) ? ("=?UTF-8?B?" . base64_encode($param["subject"]) . "?=") : ""; $message = !empty($param["message"]) ? $param["message"] : ""; $smtp_account_id = !empty($param["email_account_id"]) ? $param["email_account_id"] : $email_from; $from_name_encoded = "=?UTF-8?B?" . base64_encode($from_name) . "?="; $from_reply_name = !empty($param["from_reply_name"]) ? $param["from_reply_name"] : $from_name; $from_reply_name_enc = "=?UTF-8?B?" . base64_encode($from_reply_name) . "?="; $html_message = $message; if (isset($param["template"])) { ob_start(); require $param["template"]; $message = ob_get_contents(); ob_end_clean(); $message = $this->_parse_template($message, $param); $html_message = empty($param["html_template"]) ? preg_replace('/\\n/', '<br/>', $message) : $message; } if (isset($param["template_plaintext"])) { ob_start(); require $param["template_plaintext"]; $message = ob_get_contents(); ob_end_clean(); $message = $this->_parse_template($message, $param); $plaintext_message = strip_tags($message); } $mail = new PHPMailer(); if ($this->use_smtp) { $mail->SMTPDebug = $this->debug ? SMTP::DEBUG_SERVER : false; $mail->isSMTP(); if ($this->smtp_config_map && !empty($this->smtp_config_map[$smtp_account_id])) { $config_map = $this->smtp_config_map[$smtp_account_id]; $mail->SMTPAuth = $config_map["auth"]; $mail->SMTPSecure = $config_map["secure"]; $mail->Host = $config_map["host"]; $mail->Port = $config_map["port"]; $mail->Username = $config_map["username"]; $mail->Password = $config_map["<PASSWORD>"]; } else if (isset($this->smtp_username) && $email_from == $this->smtp_username) { $mail->SMTPAuth = $this->smtp_auth; $mail->SMTPSecure = $this->smtp_secure; $mail->Host = $this->smtp_host; $mail->Port = $this->smtp_port; $mail->Username = $this->smtp_username; $mail->Password = $<PASSWORD>; } } array_map(function ($email_address) use ($mail) { if (!empty(trim($email_address))) { $mail->AddAddress(trim($email_address)); } }, explode(",", $email_to)); array_map(function ($email_address) use ($mail) { if (!empty(trim($email_address))) { $mail->addCC(trim($email_address)); } }, explode(',', $email_cc)); array_map(function ($email_address) use ($mail) { if (!empty(trim($email_address))) { $mail->addBCC(trim($email_address)); } }, explode(',', $email_bcc)); $mail->SetFrom($email_from, $from_name_encoded); $mail->AddReplyTo($email_reply, $from_reply_name_enc); $mail->CharSet = 'UTF-8'; $mail->Subject = $subject; // NOTE: After updating to PHPMailer > 6 check if this is still necessary $html_message = preg_replace('/\s+/', ' ', $html_message); // This automatically sets Body and AltBody, that's why we override the plaintext message next $mail->MsgHTML($html_message); if (isset($plaintext_message)) { $mail->AltBody = $plaintext_message; } if (!empty($attachments)) { foreach ($attachments as $attachment) { $mail->AddAttachment($attachment["path"], $attachment["name"]); } } $email_res = $mail->Send(); $mail->clearAddresses(); if (!$email_res) { // mail($email_to, $subject, $message, "From: $email_from\r\nReply-To: $email_from\r\nX-Mailer: DT_formmail"); // we return the error, if mailer failed that's not good... error_log("Email not send: " . $mail->ErrorInfo); return $mail->ErrorInfo; } return true; } /* * Checks the email parameters based on the list of options * from the mail_maps * * @param string $type the name of the email * @param array $param the parameters passed * @param boolean $view if is a view or not * * @return mixed depends on the handle of your response function */ private function validate($type = "", array $param = [], $view=false) { if (!array_key_exists($type, $this->mail_maps) || empty($this->mail_maps[$type])) { return "No email map found"; } $config_map = $this->mail_maps[$type]; $mail_param = []; foreach ($config_map as $key => $value) { if (!$view && $key == "has_captcha" && !empty($value)) { if (empty($param["captcha_hash"]) || empty($param["captcha_code"]) || !$this->_validate_captcha($param["captcha_hash"], $param["captcha_code"])) { return "error-captcha"; } } if (!empty($value["id"]) && $key != $value["id"]) { $param[$key] = $param[$value["id"]]; } if (!empty($value["value"])) { $param[$key] = $value["value"]; } if (!isset($param[$key]) || strlen(trim($param[$key])) <= 0) { if (!empty($value["required"])) { return $key . " is required"; } if (!isset($value["default"])) { $param[$key] = ""; continue; } $param[$key] = $value["default"]; } if (!empty($value["strip"])) { $param[$key] = stripslashes(strip_tags($param[$key])); } if ($key == "subject") { $param[$key] = stripslashes(strip_tags($param[$key])); } if (!empty($value["validate"])) { if ($value["validate"] == "email") { $email_param = explode(",", $param[$key]); foreach ($email_param as &$email) { $email = trim($email); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { return $email . " is not valid"; } } } } $mail_param[$key] = $param[$key]; } if (file_exists($this->template_dir . $type . ".html.php")) { $mail_param["template"] = $this->template_dir . $type . ".html.php"; if (!empty($config_map["html_template"])) { $mail_param["html_template"] = true; } if (!empty($config_map["email_account_id"])) { $mail_param["email_account_id"] = $config_map["email_account_id"]; } } if (file_exists($this->template_dir . $type . ".txt.php")) { $mail_param["template_plaintext"] = $this->template_dir . $type . ".txt.php"; if (!empty($config_map["plaintext_template"])) { $mail_param["plaintext_template"] = true; } } return $mail_param; } public static function send($param = "", $extra = [], $attachments = []) { $that = static::$instance; $request = !empty($_REQUEST) ? $that->sanitize_request($_REQUEST) : []; if (empty($param)) { return $that->_response_output("EMAIL_FAIL", "no parameters passed"); } if (!empty($request[$that->honeypot_field]) && (bool) $request[$that->honeypot_field] == TRUE) { return $that->_response_output("VALIDATION_ERROR", "spam"); } $extra = array_merge($extra, $request); $valid = $that->validate($param, $extra); if (!is_array($valid)) { return $that->_response_output("EMAIL_FAIL", $valid); } $mail_response = $that->_send_email($valid, $attachments); if ($mail_response !== true) { return $that->_response_output("EMAIL_FAIL", "email not send: " . $mail_response); } return $that->_response_output("SUCCESS", "email send"); } public static function view($type) { $that = static::$instance; $request = !empty($_REQUEST) ? $that->sanitize_request($_REQUEST) : []; $accepts = $_SERVER['HTTP_ACCEPT'] ?? 'text/html'; if (empty($type)) { return $that->_response_output("EMAIL_FAIL", "Email view not found"); } $param = $that->validate($type, $request, true); if (!is_array($param)) { return $that->_response_output("EMAIL_FAIL", $param); } if (empty($param["template"])) { return $that->_response_output("NOT_FOUND", "Email template not found"); } $param["view_mode"] = true; ob_start(); if (strrpos($accepts, "text/plain") !== false) { require $param["template_plaintext"]; $contentType = "text"; } else { require $param["template"]; $contentType = "html"; } $message = ob_get_contents(); ob_end_clean(); $message = $that->_parse_template($message, $param); return $that->_response_output("SUCCESS", $message, ["content_type" => $contentType]); } private function _parse_template($template, $param) { if (!function_exists('parse_email_template')) { return $template; } return parse_email_template($template, $param); } private function sanitize_request($request, $remove_breaks = false){ if ( !is_array($request) ) { return stripslashes(strip_all_tags($request, $remove_breaks)); } foreach ($request as &$value) { if ( !is_array($value) ){ $value = stripslashes(strip_all_tags($value, $remove_breaks)); } else { $value = $this->sanitize_request($value, $remove_breaks); } } return $request; } public static function get_captcha() { $that = static::$instance; if (empty($that->Securimage)) { return $that->_response_output("NOT_FOUND", "");; } $captcha_code = $that->Securimage->getCode(true); if (empty($captcha_code)) { $that->Securimage->createCode(); $captcha_code = $that->Securimage->getCode(true); } return $that->_response_output("SUCCESS", $captcha_code); } private function _validate_captcha($captcha_hash, $captcha_code) { if (empty($this->Securimage)) { return true; } if (!is_string($captcha_code)) { return false; } $captcha = $this->Securimage->getCode(true); if (!$this->Securimage->check($captcha_code)) { return false; } if (md5($captcha["code"] . $captcha["time"]) != $captcha_hash) { return false; } return true; } } <file_sep>/examples/config.php <?php /* the default name on email */ define("EMAIL_DEFAULT_NAME", "its me"); /* the default email */ define("EMAIL_DEFAULT_ADDRESS", "<EMAIL>"); /* the phpmailer path */ define("PHPMAILER_LOC", "phpmailer.class.php"); ?><file_sep>/examples/messages.php <?php function response_message($code="", $extra="") { $STATUSES = [ "HACKING" => 500, "EMAIL_FAIL" => 500, "SUCCESS" => 200 ]; $status = $STATUSES[$code]; if ($status != 200) { http_response_code($status); $response = "Error: " . $code . " Message: " . $extra; error_log($response); } else { $response = "Message: " . $extra; } echo $response; return $response; } <file_sep>/README.md PHP email === A simple PHP email class that validates email parameters based on a set of rules and sends it with PHPMailer Use it like: ```php require "messages.php"; require "config.php"; require "class.email.php"; $mail_maps = [ "contact" => [ "subject" => [ "id" => "subject", "default" => "People Contacting" ], "email_to" => [ "id" => "email_to", "default" => "<EMAIL>" ], "name" => [ "id" => "from_name", "strip" => true, "required" => true ], "email" => [ "id" => "email_from", "strip" => true, "default" => '<EMAIL>', "validate" => "email" ], "message" => [ "id" => "message", "strip" => true ] ] ]; $Email = Email::i(); $Email->set_mail_maps($mail_maps); $Email->execute([ "cmd" => "contact", "type" => "contact", "subject" => "hey mate", "name" => "me", "email" => "<EMAIL>", "message" => "how are you?" ]); ``` You can pass the SMTP configuration as an array with a similar structure to ```txt array(2) { ["email@platform"]=> array(6) { ["username"]=> string(0) "" ["password"]=> string(0) "" ["host"]=> string(20) "smtp-relay.gmail.com" ["port"]=> string(3) "587" ["secure"]=> string(3) "tls" ["auth"]=> string(1) "1" } ["email@platform2"]=> array(6) { ["username"]=> string(0) "" ["password"]=> string(0) "" ["host"]=> string(20) "smtp-relay.gmail.com" ["port"]=> string(3) "587" ["secure"]=> string(3) "tls" ["auth"]=> string(1) "1" } } ```
8a2c254eb1df95fab228c23980cc859e67ef06e6
[ "Markdown", "PHP" ]
6
PHP
paramana/email
a13fbe853fe8a804901edf8e7e59589b71a8323c
707a4da4dd688a0b42d256f2894a51c262afc66b
refs/heads/main
<file_sep>array1 = bytearray("string","utf-8") print(array1)<file_sep># CCAvenue-payment This application is built for integration of CCAvenue payment gateway with a django-website.<file_sep>from Crypto.Cipher import AES import hashlib from binascii import hexlify, unhexlify import base64, re from Crypto.Cipher import AES from Crypto import Random from django.conf import settings def pad(data): """ ccavenue method to pad data. :param data: plain text :return: padded data. """ length = 16 - (len(data) % 16) data += chr(length)*length return data def unpad(data): """ ccavenue method to unpad data. :param data: encrypted data :return: plain data """ return data[0:-data[-1]] def encrypt(raw, key): raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(bytes(key.encode()), AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw.encode())) def decrypt(cipher_text, working_key): """ Method decrypt cc-avenue response. :param cipher_text: encrypted data :param working_key: working data :return: list """ cipher_text = base64.b64decode(cipher_text) iv = cipher_text[:AES.block_size] cipher = AES.new(bytes(working_key.encode()), AES.MODE_CBC, iv) plain_data = unpad(cipher.decrypt(cipher_text[AES.block_size:])).decode('utf-8') print(plain_data) plain_data_list = plain_data.split('&') final_pay_list = [] for data in plain_data_list: final_pay_dict = {} final_pay_dict[data.split('=')[0]] = data.split('=')[1] final_pay_list.append(final_pay_dict) return final_pay_list<file_sep>asgiref==3.4.1 Django==3.2.6 django-taggit==1.5.1 pycryptodome==3.10.1 python-decouple==3.4 pytz==2021.1 sqlparse==0.4.1 <file_sep>from django.shortcuts import HttpResponse, render from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .utils import * def checkout(request): p_merchant_id = settings.CC_MERCHANT_ID # current site domain current_site = settings.CURRENT_SITE_DOMAIN p_order_id = '0001' p_currency = settings.CC_CURRENCY p_amount = '100' p_redirect_url = str(current_site) + '/payment_success/' p_cancel_url = str(current_site) + '/payment_cancel/' p_language = settings.CC_LANG p_billing_name = 'Foo Bar' p_billing_address = '12/Foo Bar' p_billing_city = 'Tinsukia' p_billing_state = 'Assam' p_billing_zip = '786125' p_billing_country = settings.CC_BILL_CONTRY p_billing_tel = '9957767675' p_billing_email = '<EMAIL>' p_delivery_name = '' p_delivery_address = '' p_delivery_city = '' p_delivery_state = '' p_delivery_zip = '' p_delivery_country = 'India' p_delivery_tel = '' p_merchant_param1 = '' p_merchant_param2 = '' p_merchant_param3 = '' p_merchant_param4 = '' p_merchant_param5 = '' p_promo_code = '' p_customer_identifier = '' merchant_data = 'merchant_id=' + p_merchant_id + '&' + 'order_id=' + p_order_id + '&' + "currency=" + p_currency + \ '&' + 'amount=' + p_amount + '&' + 'redirect_url=' + p_redirect_url + '&' + 'cancel_url=' + p_cancel_url + \ '&' + 'language=' + p_language + '&' + 'billing_name=' + p_billing_name + '&' + 'billing_address=' + p_billing_address + \ '&' + 'billing_city=' + p_billing_city + '&' + 'billing_state=' + p_billing_state + '&' + 'billing_zip=' + p_billing_zip + \ '&' + 'billing_country=' + p_billing_country + '&' + 'billing_tel=' + p_billing_tel + '&' + 'billing_email=' + p_billing_email + \ '&' + 'delivery_name=' + p_delivery_name + '&' + 'delivery_address=' + p_delivery_address + '&' + 'delivery_city=' + p_delivery_city + \ '&' + 'delivery_state=' + p_delivery_state + '&' + 'delivery_zip=' + p_delivery_zip + '&' + 'delivery_country=' + p_delivery_country + \ '&' + 'delivery_tel=' + p_delivery_tel + '&' + 'merchant_param1=' + p_merchant_param1 + '&' + 'merchant_param2=' + p_merchant_param2 + \ '&' + 'merchant_param3=' + p_merchant_param3 + '&' + 'merchant_param4=' + p_merchant_param4 + '&' + 'merchant_param5=' + p_merchant_param5 + \ '&' + 'promo_code=' + p_promo_code + '&' + 'customer_identifier=' + p_customer_identifier + '&' encryption = encrypt(merchant_data, settings.CC_WORKING_KEY) params = { 'p_redirect_url': p_redirect_url, 'encryption': encryption, 'access_code': settings.CC_ACCESS_CODE, 'cc_url': settings.CC_URL, 'p_amount': p_amount } return render(request, 'payment.html', params) @csrf_exempt def payment_success(request): """ Method to handel cc-ave payment success. :param request: :return: """ response_data = request.POST response_chiper = response_data.get('encResp') payment_list = decrypt(response_chiper, settings.CC_WORKING_KEY) # payment success code return HttpResponse('DONE') @csrf_exempt def payment_cancel(request): """ Method to handel cc-ave. :param request: data :return: status """ response_data = request.POST response_chiper = response_data.get('encResp') payment_list = decrypt(response_chiper, settings.CC_WORKING_KEY) print(payment_list) # payment cancel code return HttpResponse('Cancel') <file_sep>from . import views from django.urls import path urlpatterns = [ path('', views.checkout, name='checkout'), path('payment_success/', views.payment_success, name='payment_success'), path('payment_cancel/', views.payment_cancel, name='payment_cancel'), ]
495a418c82f4592790285630c4f11efe06e79421
[ "Markdown", "Python", "Text" ]
6
Python
vishalpandeyvip/CCAvenue-payment
3fa239bf9657dff52a7cae620496bb45639af586
9b535f29b5a62f14af21c00164fd046d8149bfeb
refs/heads/master
<file_sep># C-Tutorial Solutions for the programming challenges part in the book C++ From Control Structures through Objects 8th Edition readme <file_sep>9.4. Test Scores #2 Modify the program of Programming Challenge 2 to allow the user to enter name-score pairs. For each student taking a test, the user types the student’s name followed by the student’s integer test score. Modify the sorting function so it takes an array holding the student names and an array holding the student test scores. When the sorted list of scores is displayed, each student’s name should be displayed along with his or her score. In stepping through the arrays, use pointers rather than array subscripts. <file_sep>#include <iostream> using namespace std; const int COLS = 3; const int rows = 3; void receiveData(int [][COLS], int); int checkColumns(int [][COLS], int); int checkRows(int [][COLS], int); int checkDiagonals(int [][COLS], int); bool checkTotal(int, int, int); int main() { int numbers[rows][COLS]; int sumColumns; int sumRows; int sumDiagonals; receiveData(numbers, rows); sumColumns = checkColumns(numbers, rows); sumRows = checkRows(numbers, rows); sumDiagonals = checkDiagonals(numbers, rows); checkTotal(sumRows, sumColumns, sumDiagonals); if(checkTotal) cout << "This is a Lo Shu Square" << endl; else{ cout << "stop at check total" << endl; cout << "This is not a Lo Shu Square" << endl;} cin.get(); cin.get(); return 0; } void receiveData(int numbers[][COLS], int rows) { cout << "Enter array of data: " << endl; cout << "---------------------" << endl; for (int r = 0; r < rows; r++) { for (int c = 0; c < COLS; c++) { cin >> numbers[r][c]; } } } int checkColumns(int numbers[][COLS], int rows) { int sum[3]; for (int i = 0; i < COLS; i++) { sum[i] = numbers[0][i] + numbers[1][i] + numbers[2][i]; } if (sum[0] != sum[1] || sum[1] != sum[2]) { cout << "Stop at check columns" << endl; cout << "This is not a Lo Shu Square" << endl; cin.get(); cin.get(); exit(0); } return sum[0]; } int checkRows(int numbers[][COLS], int rows) { int sum[3]; for (int i = 0; i < rows; i++) { sum[i] = numbers[i][0] + numbers[i][1] + numbers[i][2]; } if (sum[0] != sum[1] || sum[1] != sum[2]) { cout << "Stop at check rows" << endl; cout << "This is not a Lo Shu Square" << endl; cin.get(); cin.get(); exit(0); } return sum[0]; } int checkDiagonals(int numbers[][COLS], int rows) { int sum[2] = {0, 0}; for (int r = 0; r < rows; r++) { for (int c = 0; c < COLS; c++) { sum[0] += numbers[r][c]; sum[1] += numbers[rows - r - 1][COLS - c - 1]; } } if (sum[0] != sum[1]) { cout << "Stop at check Diagonals" << endl; cout << "This is not a Lo Shu Square" << endl; cin.get(); cin.get(); exit(0); } return sum[0]; } bool checkTotal(int sum1, int sum2, int sum3) { if (sum1 != sum2 || sum2 != sum3) return false; else return true; } <file_sep>#include <iostream> #include <string> #include <vector> using namespace std; void findFrequent(string); int main() { string input; cout << "Enter a string: "; getline(cin, input); findFrequent(input); cin.get(); cin.get(); return 0; } void findFrequent(string input) // this function search all charactres, from 'a', to 'w', count each, and find the largest one { vector<int> stats1; vector<char> stats2; char x; int index = 0; for (char x = 97; x < 123; x++) { int i = -1; int count = 0; while (input.find(x, i + 1) != -1) { int index = input.find(x, i + 1); i = index; count++; } if (count > 0) cout << "Character """ << x << """ has " << count << " occurrences.\n"; stats1.push_back(count); stats2.push_back(x); index++; } int maxIndex; int maxCount = stats1[0]; for (int i = 1; i < index; i++) { if (maxCount < stats1[i]) { maxCount = stats1[i]; maxIndex = i; } } cout << "-------------------------------" << endl; cout << "The most frequent character is """ << stats2[maxIndex] << """ with " << stats1[maxIndex] << " occurrences.\n"; } <file_sep>#ifndef NUMBERLIST #define NUMBRELIST class NumberList { private: // declare a struct for list struct node { int value; // value store in this struct node *next; // next pointer point to next struct }; node *head; // beginning list head pointer public: // constructor NumberList() { head = nullptr; } ~NumnberList(); ~NumberList(); void appendNode(int ); void insertNode(int , int ); void deleteNode(int ); void displayList() const; }; #endif <file_sep>10.1. String Length Write a function that returns an integer and accepts a pointer to a C-string as an argument. The function should count the number of characters in the string and return that number. Demonstrate the function in a simple program that asks the user to input a string, passes it to the function, and then displays the function’s return value. <file_sep>13.1. Date Design a class called Date . The class should store a date in three integers: month , day , and year . There should be member functions to print the date in the following forms: 12/25/2014 December 25, 2014 25 December 2014 Demonstrate the class by writing a complete program implementing it. Input Validation: Do not accept values for the day greater than 31 or less than 1. Do not accept values for the month greater than 12 or less than 1. <file_sep>18.13. Inventory Bin Queue Modify the program you wrote for Programming Challenge 12 so it uses a queue instead of a stack. Compare the order in which the parts are removed from the bin for each program. <file_sep>#include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; int main() { const int days = 30; const int months = 3; string names[3] = {"June ", "July ", "August"}; string weathers[months][days]; ifstream myFile; int count = 0; myFile.open("weather.txt"); for (int x = 0; x < months; x++) for (int y = 0; y < days; y++) myFile >> weathers[x][y]; for (int x = 0; x < months; x++) { cout << names[x] << ": "; for (int y = 0; y < days; y++) { cout << weathers[x][y] << " "; } cout << endl; } cout << endl; cout << endl; int s[3]; int c[3]; int r[3]; for (int x = 0; x < months; x ++) { s[x] = 0; c[x] = 0; r[x] = 0; cout << names[x] << ": "; for (int y = 0; y < days; y++) { if (weathers[x][y] == "s" || weathers[x][y] == "S") s[x] += 1; if (weathers[x][y] == "c" || weathers[x][y] == "C") c[x] += 1; if (weathers[x][y] == "r" || weathers[x][y] == "R") r[x] += 1; } cout << s[x] << " days sunny, " << c[x] << " days cloudy, " << r[x] << " days rainy." << endl; } int index1 = 0; int index2 = 0; int index3 = 0; int highest1 = s[0]; int highest2 = r[0]; int highest3 = c[0]; for (int i = 1; i < months; i++) { if (s[i] > highest1){highest1 = s[i]; index1 = i;} if (c[i] > highest1){highest1 = c[i]; index2 = i;} if (r[i] > highest1){highest1 = r[i]; index3 = i;} } cout << names[index1] << " has the highest sunny days with: " << highest1 << " days." << endl; cout << names[index2] << " has the highest cloudy days with: " << highest2 << " days." << endl; cout << names[index3] << " has the highest rainny days with: " << highest3 << " days." << endl; myFile.close(); cin.get(); cin.get(); return 0; } <file_sep>#ifndef COIN_H #define COIN_H #include <string> class Coin { private: double value; std::string sideUp; public: Coin(); void toss(); std::string getSideUp(); double getValue(); void setValue(double ); bool checkCoin(); }; #endif <file_sep>12.2. File Display Program Write a program that asks the user for the name of a file. The program should display the contents of the file on the screen. If the file’s contents won’t fit on a single screen, the program should display 24 lines of output at a time, and then pause. Each time the program pauses, it should wait for the user to strike a key before the next 24 lines are displayed. <file_sep>#include <iostream> #include <fstream> #include <string> using namespace std; int main() { char ch; string fileName; string input; fstream file; int line = 1; // to count the line up to 24 lines cout << "Enter the name of the file: "; cin >> fileName; cin.ignore(); // ignore the '\n' at the end of the file name file.open(fileName, ios::in); if (file) { getline(file, input); while (file) { cout << line << ": "; cout << input << endl; getline(file, input); line++; } file.close(); } else cout << "Cannot open file.\n"; cin.get(); cin.get(); return 0; } <file_sep>#include <iostream> #include <fstream> #include <string> using namespace std; void arrayToFile(string, int*, int); void fileToArray(string, int*, int); int main() { int size; int *arr = nullptr; string fileName; int newSize; int *newArr = nullptr; cout << "Enter the number of numbers in array: "; cin >> size; arr = new int[size]; cout << "Enter the array: "; for (int count = 0; count < size; count++) cin >> arr[size]; cout << "Now enter the name of the file you want to save: "; cin.ignore(); getline(cin, fileName); cout << "Saving...." << endl; arrayToFile(fileName, arr, size); cout << "Finish!!" << endl; cout << "Enter the number you want to get: "; cin >> newSize; newArr = new int[newSize]; cout << "Enter the name of the file you want to get data: "; cin.ignore(); getline(cin, fileName); fileToArray(fileName, newArr, newSize); cout << "Your array: "; for (int count = 0; count < newSize; count++) cout << newArr[count] << " "; cout << endl; cin.get(); cin.get(); return 0; } void arrayToFile(string fileName, int *arr, int size) { fstream outputFile(fileName, ios::out | ios::binary); outputFile.write(reinterpret_cast<char *>(arr), size); outputFile.close(); } void fileToArray(string fileName, int *arr, int size) { fstream inputFile(fileName, ios::in | ios::binary); inputFile.read(reinterpret_cast<char *>(arr), size); inputFile.close(); } // need to work more <file_sep>11.3. Corporate Sales Data Write a program that uses a structure to store the following data on a company division: Division Name (such as East, West, North, or South) First-Quarter Sales Second-Quarter Sales Third-Quarter Sales Fourth-Quarter Sales Total Annual Sales Average Quarterly Sales The program should use four variables of this structure. Each variable should represent one of the following corporate divisions: East, West, North, and South. The user should be asked for the four quarters’ sales figures for each division. Each division’s total and average sales should be calculated and stored in the appropriate member of each structure variable. These figures should then be displayed on the screen. <file_sep>12. Coin Toss Simulator Write a class named Coin . The Coin class should have the following member variable: • A string named sideUp . The sideUp member variable will hold either “heads” or “tails” indicating the side of the coin that is facing up. The Coin class should have the following member functions: • A default constructor that randomly determines the side of the coin that is facing up (“heads” or “tails”) and initializes the sideUp member variable accordingly. • A void member function named toss that simulates the tossing of the coin. When the toss member function is called, it randomly determines the side of the coin that is facing up (“heads” or “tails”) and sets the sideUp member variable accordingly. • A member function named getSideUp that returns the value of the sideUp member variable. Write a program that demonstrates the Coin class. The program should create an instance of the class and display the side that is initially facing up. Then, use a loop to toss the coin 20 times. Each time the coin is tossed, display the side that is facing up. The program should keep count of the number of times heads is facing up and the number of times tails is facing up, and display those values after the loop finishes. <file_sep>#ifndef GRADEACTIVITY_H #define GRADEACTIVITY_H class GradeActivity { private: double score; public: GradeActivity() { score = 0.0; } GradeActivity(double s) { score = s; } void setScore(double s) { score = s; } double getScore() const { return score; } char getLetterGrade () const; }; #endif <file_sep>#include <iostream> #include "Array.h" int main() { int size; double num; std::cout << "Enter array size: "; std::cin >> size; Array numbers(size); for (int i = 0; i < size; i++) { std::cout << "Enter element #" << i + 1 << ": "; std::cin >> num; numbers.setElement(i, num); } std::cout << "The highest number is: " << numbers.findHighest() << std::endl; std::cout << "The lowest number is: " << numbers.findLowest() << std::endl; std::cout << "The average of the array: " << numbers.findAverage() << std::endl; std::cin.get(); std::cin.get(); return 0; } <file_sep>#include <iostream> #include <string> #include "Queue.h" using namespace std; int main() { string name; const int SIZE = 5; Queue<string> stack(SIZE); while (!stack.isFull()) { cout << "Enter a name: "; getline(cin, name); stack.enqueue(name); } cout << "\nYou entered: " << endl; while (!stack.isEmpty()) { stack.dequeue(name); cout << name << endl; } cin.get(); cin.get(); return 0; } <file_sep>#include <iostream> #include "MathStack.h" #include "DynamicStack.h" using namespace std; int main() { MathStack<double> stack; double numb; cout << "Now pushing: " << endl; for (numb = 1; numb < 6; numb++) { cout << "Pushing " << numb << endl; stack.push(numb); } cout << "Multiplying all" << endl; stack.multAll(); stack.pop(numb); cout << "The result is: " << numb << endl; cin.get(); cin.get(); return 0; } <file_sep>#include <iostream> #include <string> using namespace std; struct Test { string name; int id; int *test; // set test as pointer for dynamically allocating double averageGrade; char courseGrade; }; void input(Test *, int); char courseGrade(int ); void displayData(Test ); int main() { int numStudents; int numGrades; cout << "Enter the number of students: "; cin >> numStudents; cout << "Enter the number of grades each students has: "; cin >> numGrades; Test *student = nullptr; student = new Test[numStudents]; // dynamically create array of struct for (int index = 0; index < numStudents; index++) input(&student[index], numGrades); cout << endl; cout << "Here is the information: \n"; cout << "-------------------------------------------\n"; for (int index = 0; index < numStudents; index++) { displayData(student[index]); cout << endl; } cin.get(); cin.get(); return 0; } void input(Test *student, int numGrades) { int totalGrade = 0; cout << "Enter the ID of student: "; cin >> student->id; cout << "Enter student's name: "; cin.ignore(); getline(cin, student->name); student->test = nullptr; student->test = new int[numGrades]; // dynamically create array of integer for (int index = 0; index < numGrades; index++) { cout << "Enter grade #" << index + 1 << ": "; cin >> student->test[index]; totalGrade += student->test[index]; } student->averageGrade = totalGrade / numGrades; student->courseGrade = courseGrade(student->averageGrade); } char courseGrade(int grade) { char courseGrade; if (grade < 100 && grade >= 91) courseGrade = 'A'; else if (grade > 81) courseGrade = 'B'; else if (grade > 71) courseGrade = 'C'; else if (grade > 61) courseGrade = 'D'; else courseGrade = 'F'; return courseGrade; } void displayData(Test student) { cout << "Student's name: " << student.name << endl; cout << "Student's ID: " << student.id << endl; cout << "Student's average test score: " << student.averageGrade << endl; cout << "Student's course grade: " << student.courseGrade << endl; } <file_sep>#include <iostream> #include "NumberList.h" using namespace std; int main() { NumberList list; list.appendNode(1); list.appendNode(2); list.appendNode(3); list.appendNode(4); list.appendNode(5); list.appendNode(6); list.appendNode(7); list.appendNode(8); list.appendNode(9); list.displayNode(); cout << endl; list.reverseNode(); list.displayNode(); cin.get(); cin.get(); return 0; } <file_sep>#include <iostream> #include "NumberList.h" using namespace std; int main() { NumberList num; num.appendNode(1); num.appendNode(3); num.appendNode(2); num.appendNode(10); num.appendNode(12); num.insertNode(1, 100); num.displayList(); cin.get(); cin.get(); return 0; } <file_sep>#include <iostream> #include <iomanip> #include <string> #include <cctype> #include "RetailItem.h" #include "CashRegister.h" void displayTable(); const int NUM_ITEM = 3; RetailItem item[NUM_ITEM] = {RetailItem("Jacket", 12, 59.95), RetailItem("Designer Jeans", 40, 34.95), RetailItem("Shirt", 20, 24.95)}; int main() { CashRegister cash; int quantity; int index; double price; char ch = 'y'; while (toupper(ch) == 'Y') { displayTable(); std::cout << "Enter the item you want to buy: "; std::cin >> index; while (index > 3 || index < 1) { std::cout << "Invalid product!!\n" << "Enter again!!\n" << "Enter the item you want to buy: "; std::cin >> index; } index -= 1; std::cout << "Enter quantity: "; std::cin >> quantity; while (quantity < 0) { std::cout << "Invalid quantity!!\n" << "Enter again!!\n" << "Enter quantity: "; std::cin >> quantity; } while (quantity > item[index].getUnits()) { std::cout << "The item you want to buy is out of stock!!\n" << "Enter lesser amount!!\n" << "Enter quantity: "; std::cin >> quantity; } price = item[index].getPrice(); cash.setCost(price); cash.setQuantity(quantity); item[index].subTractUnits(quantity); std::cout << "Product: " << item[index].getDescription() << "\t"; std::cout << "Quantity: " << quantity << std::endl; std::cout << "\nSubtotal : " << cash.getSubTotal() << std::endl; std::cout << "Tax : " << cash.getTax() << std::endl; std::cout << "-----------------------" <<std::endl; std::cout << "TotalPrice: " << cash.getTotal() << std::endl << std::endl; std::cout << "Do you want to continue? ['Y' / 'N']: "; std::cin.ignore(); std::cin.get(ch); } std::cin.get(); std::cin.get(); return 0; } void displayTable() { std::cout << std::left << std::setw(15) << " " << std::setw(25) << "Description" << std::setw(25) << "Units on Hand" << std::setw(25) << "Price" << std::endl; std::cout << "--------------------------------------" << "--------------------------------------" << std::endl; for (int count = 0; count < NUM_ITEM; count++) { std::cout << std::left << "Item #" << std::setw(9) << count + 1 << std::setw(25) << item[count].getDescription() << std::setw(25) << item[count].getUnits() << std::setw(25) << item[count].getPrice() << std::endl; } } <file_sep>#include <iostream> using namespace std; int dosomething(int *, int *); int main() { int *x; int *y; x = nullptr; y = nullptr; x = new int; y = new int; cout << "Enter x, y: "; cin >> *x >> *y; cout << "The result is: " << dosomething(x, y) << endl; delete x; delete y; cin.get(); cin.get(); return 0; } int dosomething(int *x, int *y) { int temp = *x; *x = *y * 10; *y = temp * 10; return *x + *y; } <file_sep>#include <iostream> #include <string> using namespace std; void sortSelectArr(int *, string *, int); void showArr(int *, string *, int); int main() { int size; cout << "Enter number of students: "; cin >> size; int *scores = nullptr; string *names = nullptr; scores = new int[size]; names = new string[size]; for (int index = 0; index < size; index++) { cout << "Enter name and grade of student #" << index + 1 << ": "; cin >> names[index] >> scores[index]; } sortSelectArr(scores, names, size); showArr(scores, names, size); delete [] score; delete [] names; score = nullptr; names = nullptr; cin.get(); cin.get(); return 0; } void sortSelectArr(int *scores, string *names, int size) { int startScan, maxIndex, maxValue; string tempNames; for (startScan = 0; startScan < size - 1; startScan++) { maxIndex = startScan; maxValue = scores[maxIndex]; tempNames = names[maxIndex]; for (int index = startScan + 1; index < size; index++) { if (maxValue < scores[index]) { maxIndex = index; maxValue = scores[maxIndex]; } } scores[maxIndex] = scores[startScan]; scores[startScan] = maxValue; names[maxIndex] = names[startScan]; names[startScan] = tempNames; } } void showArr(int *scores, string *names, int size) { cout << "Grades showed in descending order\n\n"; cout << "STD\tNames\t\tScores\n"; cout << "---------------------------------"; for (int count = 0; count < size; count++) { cout << count + 1 << "\t" << names[count] << "\t\t" << scores[count] << endl; } } <file_sep>13.17. Cash Register Design a CashRegister class that can be used with the InventoryItem class discussed in this chapter. The CashRegister class should perform the following: 1. Ask the user for the item and quantity being purchased. 2. Get the item’s cost from the InventoryItem object. 3. Add a 30% profit to the cost to get the item’s unit price. 4. Multiply the unit price times the quantity being purchased to get the purchase subtotal. 5. Compute a 6% sales tax on the subtotal to get the purchase total. 6. Display the purchase subtotal, tax, and total on the screen. 7. Subtract the quantity being purchased from the onHand variable of the InventoryItem class object. Implement both classes in a complete program. Feel free to modify the InventoryItem class in any way necessary. Input Validation: Do not accept a negative value for the quantity of items being purchased. <file_sep>#ifndef INVENTORYQUEUE_H #define INVENTORYQUEUE_H #include <string> using namespace std; class InventoryQueue { private: struct QueueNode { QueueNode *next; string serialNumber; string date; string partLot; }; QueueNode *front; QueueNode *rear; int numItems; public: InventoryQueue() { front = nullptr; rear = nullptr; numItems = 0; } ~InventoryQueue(); void enqueue(string, string, string); void dequeue(string &, string &, string &); void display(); bool isEmpty(); }; #endif <file_sep>#ifndef ARRAY_H #define ARRAY_H class Array { private: double *arr; int size; public: Array(int ); ~Array(); void setElement(int, double); double getElement(int); double findHighest(); double findLowest(); double findAverage(); }; #endif <file_sep>#include <iostream> #include <iomanip> #include <vector> using namespace std; void selectSort(double *, int); double findMedian(double *, int); int main() { int size = 0; double input; vector<double> num; cout << "Enter array of numbers (-1 to quit): "; do { cin >> input; num.push_back(input); size += 1; } while (input != -1); size = size - 1; double *arr = nullptr; arr = new double[size]; for (int index = 0; index < size; index++) arr[index] = num[index]; selectSort(arr, size); cout << "The median of this array is: "; cout << findMedian(arr, size) << endl; delete [] arr; arr = nullptr; cin.get(); cin.get(); return 0; } void selectSort(double *arr, int size) { int startScan, minIndex; double minValue; for (startScan = 0; startScan < size - 1; startScan++) { minIndex = startScan; minValue = arr[minIndex]; for (int count = startScan + 1; count < size; count++) { if (minValue > arr[count]) { minIndex = count; minValue = arr[minIndex]; } } arr[minIndex] = arr[startScan]; arr[startScan] = minValue; } } double findMedian(double *arr, int size) { if (size % 2 == 0) return (arr[size / 2] + arr[size / 2 - 1]) / 2; else return arr[size / 2]; } <file_sep>10.3. Word Counter Write a function that accepts a pointer to a C-string as an argument and returns the number of words contained in the string. For instance, if the string argument is “Four score and seven years ago” the function should return the number 6. Demonstrate the function in a program that asks the user to input a string and then passes it to the function. The number of words in the string should be displayed on the screen. Optional Exercise: Write an overloaded version of this function that accepts a string class object as its argument. <file_sep>#include <iostream> #include "Date.h" int main() { int day, month, year; std::cout << "Enter day: "; std::cin >> day; std::cout << "Enter month: "; std::cin >> month; std::cout << "Enter year: "; std::cin >> year; Date day1(day, month, year); day1.showDate1(); day1.showDate2(); day1.showDate3(); std::cin.get(); std::cin.get(); return 0; } <file_sep>#include "InventoryQueue.h" #include <iostream> #include <string> using namespace std; InventoryQueue::~InventoryQueue() { QueueNode *nodePtr = new QueueNode; if (isEmpty()) return; else { nodePtr = front; while (nodePtr) { nodePtr = front->next; delete front; front = nodePtr; } } } void InventoryQueue::enqueue(string numb, string date, string lot) { QueueNode *nodePtr = new QueueNode; nodePtr->serialNumber = numb; nodePtr->date = date; nodePtr->partLot = lot; nodePtr->next = nullptr; if (isEmpty()) { front = nodePtr; rear = nodePtr; } else { rear->next = nodePtr; rear = nodePtr; } numItems++; } void InventoryQueue::dequeue(string &numb, string &date, string &lot) { QueueNode *nodePtr = new QueueNode; if (isEmpty()) cout << "The queue is empty" << endl; else { nodePtr = front; numb = nodePtr->serialNumber; date = nodePtr->date; lot = nodePtr->partLot; nodePtr = front->next; delete front; front = nodePtr; numItems--; } } bool InventoryQueue::isEmpty() { bool status; if (numItems == 0) status = true; else status = false; return status; } void InventoryQueue::display() { QueueNode *nodePtr; if (isEmpty()) cout << "The queue is empty" << endl; else { cout << "There are " << numItems << " items left" << endl; nodePtr = front; while (nodePtr) { cout << "Serial Number: " << nodePtr->serialNumber << endl; cout << "Manufacuring Date: " << nodePtr->date << endl; cout << "Part Lot: " << nodePtr->partLot << endl; cout << endl; nodePtr = nodePtr->next; } } } <file_sep>17.6. Member Insertion by Position Modify the list class you created in the previous programming challenges by adding a member function for inserting a new item at a specified position. A position of 0 means that the value will become the first item on the list, a position of 1 means that the value will become the second item on the list, and so on. A position equal to or greater than the length of the list means that the value is placed at the end of the list. <file_sep>#ifndef NUMBERLIST_H #define NUMBERLIST_H // this class is different because I add the previous pointer, // this pointer will point to the previous struct // so I can easily go back the struct list up to head class NumberList { private: struct ListNode { double value; ListNode *next; ListNode *previous; // previous pointer }; ListNode *head; public: NumberList() { head = nullptr; } /*~NumberList();*/ void appendNode(double ); void insertNode(double ); void deleteNode(double ); void reverseNode(); void displayNode(); }; #endif <file_sep>#include "Coin.h" #include <string> #include <cstdlib> #include <ctime> Coin::Coin() { srand(time(0)); toss(); } void Coin::toss() { std::string values[2] = {"heads", "tails"}; int i; i = rand() % 2; sideUp = values[i]; } std::string Coin::getSideUp() { return sideUp; } double Coin::getValue() { return value; } void Coin::setValue(double v) { value = v; } bool Coin::checkCoin() { if (sideUp == "heads") return true; else if (sideUp == "tails") return false; } <file_sep>12.9. File Encryption Filter File encryption is the science of writing the contents of a file in a secret code. Your encryption program should work like a filter, reading the contents of one file, modifying the data into a code, and then writing the coded contents out to a second file. The second file will be a version of the first file, but written in a secret code. Although there are complex encryption techniques, you should come up with a simple one of your own. For example, you could read the first file one character at a time, and add 10 to the ASCII code of each character before it is written to the second file. <file_sep>#ifndef CASHREGISTER_H #define CASHREGISTER_H class CashRegister { private: int item; int quantity; double cost; public: void setItem(int i) { item = i; } void setQuantity(int q) { quantity = q; } void setCost(double c) { cost = c; } double getSubTotal() { return (cost * 130 / 100 * quantity); } double getTax() { double subTotal = getSubTotal(); return (subTotal * 6 / 100); } double getTotal() { double subTotal = getSubTotal(); double tax = getTax(); return subTotal + tax; } }; #endif <file_sep>#include <iostream> #include <cctype> #include <cstring> #include <string> using namespace std; int wordCount(char *); int wordCount(string); // overload function receive string type int main() { int count; const int STR_SIZE = 80; char input1[STR_SIZE]; string input2; cout << "Enter a string: "; // cin.getline(input1, STR_SIZE); getline(cin, input2); // count = wordCount(input1); count = wordCount(input2); cout << "The string has " << count << " words.\n"; cin.get(); cin.get(); return 0; } int wordCount(char *input) { int count = 0, index = 0; while (input[index] != '\0') { index++; if (isspace(input[index]) != 0) count++; } return count + 1; } int wordCount(string input) { int count = 0, index = 0; int total = input.length(); for (int index = 0; index < total; index++) { if (input.at(index) == ' ') count++; } return count + 1; } <file_sep>10.2. Backward String Write a function that accepts a pointer to a C-string as an argument and displays its contents backward. For instance, if the string argument is “ Gravity ” the function should display “ ytivarG ”. Demonstrate the function <file_sep>#include <iostream> #include <string> using namespace std; struct MovieData { string title; string director; int year; int times; }; void showData(MovieData *); int main() { const int num = 2; // Initializing an array of struct MovieData movies[num] = {{"<NAME>", "<NAME>", 2004, 190}, {"Buddha", "<NAME>", 1997, 240}}; // for loop to display the content of the array for (int index = 0; index < num; index++) { cout << "Movies #" << index + 1 << ": " << endl; showData(&movies[index]); cout << endl; } cin.get(); cin.get(); return 0; } // take pointer to a struct as an argument void showData(MovieData *movies) { cout << "Title: " << movies->title << endl; cout << "Director: " << movies->director << endl; cout << "Year Release: " << movies->year << endl; cout << "Times in minutes: " << movies->times << endl; } <file_sep>#include "NumberList.h" #include <iostream> using namespace std; void NumberList::appendNode(int v) { node *newNode; node *nodePtr; // store value in appened node newNode = new node; newNode->next = nullptr; newNode->value = v; // if there are no nodes in the list // make new node the fist node if (!head) head = newNode; else { nodePtr = head; while (nodePtr->next) nodePtr = nodePtr->next; // until nodePtr point to the end node nodePtr->next = newNode; } } void NumberList::displayList() const { node *nodePtr; // to move along the array nodePtr = head; while (nodePtr) { cout << nodePtr->value << endl; nodePtr = nodePtr->next; } } void NumberList::deleteNode(int v) { node *nodePtr; node *previousNode; // this pointer point to struct right after that of nodePtr; if (!head) return; if (head->value == v) { nodePtr = head->next; delete head; head = nodePtr; } else { nodePtr = head; previousNode = nullptr; while (nodePtr->value != v && nodePtr != nullptr) { previousNode = nodePtr; nodePtr = nodePtr->next; } if (nodePtr) { previousNode->next = nodePtr->next; delete nodePtr; } } } void NumberList::insertNode(int index, int v) { node *newNode = new node; node *nodePtr; node *previousNode = nullptr; newNode->value = v; // check if the position is correct if (index >= 1) { nodePtr = head; previousNode = nullptr; // moving the nodePtr as along as it point to the correct // position for (int i = 1; i < index; i++) { previousNode = nodePtr; nodePtr = nodePtr->next; if (nodePtr == nullptr) return; } // if index == 1, which means insert the number // at the beginning of the array if (previousNode == nullptr) { newNode->next = head; head = newNode; } else // place newNode pointer between previousNode and ptrNode { previousNode->next = newNode; newNode->next = nodePtr; } } else return; } NumberList::~NumberList() { node *nodePtr; node *nextNode; nodePtr = head; while(nodePtr) { nextNode = nodePtr->next; delete nodePtr; nodePtr = nextNode; } } <file_sep>7.15. vector Modification Modify the National Commerce Bank case study presented in Program 7-23 so pin1 , pin2 , and pin3 are vector s instead of arrays. You must also modify the testPIN function to accept a vector instead of an array. <file_sep>#include <iostream> #include <string> #include "ProductionWorker.h" int main() { std::string name; int number; std::string date; int shift; std::cout << "Enter the name of employee: "; getline(std::cin, name); std::cout << "Enter the ID number of employee: "; std::cin >> number; std::cout << "Enter the date of employee: "; std::cin.ignore(); getline(std::cin, date); std::cout << "Enter the shift of employee (1 for day, 2 for night): "; std::cin >> shift; ProductionWorker employee1; employee1.setName(name); employee1.setDate(date); employee1.setNumber(number); employee1.setShift(shift); employee1.selectRate(); std::cout << "Name: " << employee1.getName() << std::endl; std::cout << "ID : " << employee1.getNumber() << std::endl; std::cout << "Date: " << employee1.getDate() << std::endl; std::cout << "Rate: " << employee1.getPayRate() << std::endl; return 0; } <file_sep>6. Case Study Modification #1 Modify Program 9-19 (the United Cause case study program) so it can be used with any set of donations. The program should dynamically allocate the donations array and ask the user to input its values. 7. Case Study Modification #2 Modify Program 9-19 (the United Cause case study program) so the arrptr array is sorted in descending order instead of ascending order. <file_sep>#include <iostream> #include <vector> #include <string> using namespace std; const int types = 5; void receiveData(int [], string []); void processing(int [], string [], int &, int &, int &); void showData(int [], string [], int, int, int); int main() { string names[] = {"mild", "medium", "sweet", "hot", "zesty"}; int sales[5]; int highestIndex; int lowestIndex; int total; receiveData(sales, names); processing(sales, names, highestIndex, lowestIndex, total); showData(sales, names, highestIndex, lowestIndex, total); cin.get(); cin.get(); return 0; } void receiveData(int sales[], string names[]) { for (int i = 0; i < types; i++) { string name; cout << "Enter the sales of " << names[i] << ": "; cin >> sales[i]; } } void processing(int sales[], string names[], int &highestIndex, int &lowestIndex, int &total) { total = 0; highestIndex = 0; lowestIndex = 0; int highest = sales[0]; int lowest = sales[0]; for (int i = 1; i < types; i++) { if (highest < sales[i]) { highest = sales[i]; highestIndex = i; } if (lowest > sales[i]) { lowest = sales[i]; lowestIndex = i; } total += sales[i]; } } void showData(int sales[], string names[], int highestIndex, int lowestIndex, int total) { cout << "Salsa\t\tSales" << endl; cout << "------\t\t------" << endl; for (int i = 0; i < types; i++) { cout << names[i] << "\t\t" << sales[i] << endl; } cout << "----------------------" << endl; cout << "Highest product is " << names[highestIndex] << ", with " << sales[highestIndex] << endl; cout << "Lowest product is " << names[lowestIndex] << ", with " << sales[lowestIndex] << endl; cout << "Total product is: " << total << endl; } <file_sep>#ifndef DAYOFYEAR_H #define DAYOFYEAR_H #include <string> using namespace std; class DayofYear { private: string result; // int day; // day in month, ex int month; // index of string array months; static int days[12]; // static array to initialize inside class static string months[12]; // static array to initialize inside class public: DayofYear(int ); // member function receive number to compute day and month string print(); // member function return the string result <line 10> }; #endif <file_sep>#ifndef EMPLOYEE_H #define EMPLOYEE_H #include <string> class Employee { private: std::string name; int id; std::string department; std::string position; public: Employee(std::string, int, std::string, std::string); Employee(std::string, int); Employee(); void setName(std::string); std::string getName(); void setID(int); int getID(); void setDepart(std::string); std::string getDepart(); void setPosi(std::string); std::string getPosi(); }; #endif <file_sep>#include <iostream> #include <string> #include <iomanip> using namespace std; struct Drinks { string name; double cost; int number; }; double buyDrinks(Drinks *); // chose what kind of drink user want to buy // will return money earned from this transaction void displayDrinks(Drinks *); // display the content of the table int main() { char order; double total = 0; Drinks type[5] = {{"Cola ", 0.75, 20}, {"Root Beer ", 0.75, 20}, {"Lemon-Lime", 0.75, 20}, {"Grape Soda", 0.80, 20}, {"Cream Soda", 0.80, 20}}; displayDrinks(type); do { cout << "Do you want to buy any drinks? ('Y' / 'N') "; cin >> order; while (order != 'n' && order != 'N' && order != 'y' && order != 'Y') { cout << "ERROR: Invalid input, enter 'Y' or 'N': "; cin >> order; } if (order == 'n' || order == 'N') break; total += buyDrinks(type); } while (order == 'y' || order == 'Y'); displayDrinks(type); cout << "\nThe money this machine earned: $" << total << endl; cin.get(); cin.get(); return 0; } void displayDrinks(Drinks *type) { cout << "-----------------------------------------------------------\n"; cout << "Drink Name\t\tCost\t\tNumber in Machine" << endl; cout << "-----------------------------------------------------------\n"; for (int index = 0; index < 5; index++) { cout << fixed << showpoint << setprecision(2); cout << type[index].name << "\t\t" << type[index].cost << "\t\t" << type[index].number << endl; } cout << endl; } double buyDrinks(Drinks *type) { bool found = false; int index; int num; double sum; double cash; string input; cout << "Enter name of drink: "; cin.ignore(); getline(cin, input); for (index = 0; index < 5; index++) if (type[index].name.find(input) != string::npos) // if condition to find if the input name is contained in the type[index].name { found = true; break; } if (!found) // if not found { cout << "There is no drink you want!!" << endl; return 0; } else // if found { cout << "Enter the number of drink: "; cin >> num; if (num > type[index].number) { cout << "Not enought drinks, there are only " << type[index].number << " drinks left" << endl; return 0; } else { sum = num * type[index].cost; cout << "Put in cash: $"; cin >> cash; if (cash < num) { cout << "Not enought cash!!" << endl; return 0; } else { cout << "Return: $" << cash - sum << endl; type[index].number = type[index].number - num; return sum; } } } } <file_sep>10.9. Most Frequent Character Write a function that accepts either a pointer to a C-string, or a string object, as its argument. The function should return the character that appears most frequently in the string. Demonstrate the function in a complete program. <file_sep>#ifndef NUMBERLIST_H #define NUMBERLIST_H class NumberList { private: struct ListNode { double value; ListNode *next; ListNode *previous; }; ListNode *head; public: NumberList() { head = nullptr; } /*~NumberList();*/ void appendNode(double ); void insertNode(int, double ); void deleteNode(double ); void reverseNode(); void displayNode(); }; #endif <file_sep>#ifndef DYNAMICQUEUE_H #define DYNAMICQUEUE_H #include <iostream> using namespace std; template <class T> class DynamicQueue { private: QueueNode { T value; QueueNode *next; } QueueNode *front; QueueNode *rear; int numItems; public: DynamicQueue(); ~DynamicQueue(); void enqueue(T ); void dequeue(T &); bool isEmpty() const; void clear(); }; template <class T> DynamicQueue::DynamicQueue() { front = nullptr; rear = nullptr; numItems = 0; } template <class T> DynamicQueue::~DynamicQueue() { clear(); } template <class T> void DynamicQueue::enqueue(T item) { QueueNode *newNode; newNode = new QueueNode; newNode->value = item; newNode->next = nullptr; if (isEmpty()) { front = newNode; rear = newNode; numItems++; } else { rear->next = newNode; rear = newNode; numItems++; } } template <class T> void DynamicQueue::dequeue(T &item) { QueueNode *temp = new QueueNode; if (isEmpty()) cout << "The queue is empty" << endl; else { item = front->value; temp = front->next;] delete front; front = temp; numItems--; } } template <class T> bool DynamicQueue<T>::isEmpty() { bool status; if (numItems > 0) status = false; else status = true; return status; } template <class T> void DynamicQueue<T>::clear() { T value; while (!isEmpty()) dequeue(value); } #endif <file_sep>13. Drink Machine Simulator Write a program that simulates a soft drink machine. The program should use a structure that stores the following data: Drink Name Drink Cost Number of Drinks in Machine The program should create an array of five structures. The elements should be initialized with the following data: Drink Name Cost Number in Machine Cola .75 20 Root Beer .75 20 Lemon-Lime .75 20 Grape Soda .80 20 Cream Soda .80 20 Each time the program runs, it should enter a loop that performs the following steps: A list of drinks is displayed on the screen. The user should be allowed to either quit the program or pick a drink. If the user selects a drink, he or she will next enter the amount of money that is to be inserted into the drink machine. The program should display the amount of change that would be returned and subtract one from the number of that drink left in the machine. If the user selects a drink that has sold out, a message should be displayed. The loop then repeats. When the user chooses to quit the program it should display the total amount of money the machine earned. <file_sep>2. Employee Class Write a class named Employee that has the following member variables: • name. A string that holds the employee’s name. • idNumber. An int variable that holds the employee’s ID number. • department. A string that holds the name of the department where the employee works. • position. A string that holds the employee’s job title. The class should have the following constructors: • A constructor that accepts the following values as arguments and assigns them to the appropriate member variables: employee’s name, employee’s ID number, department, and position. • A constructor that accepts the following values as arguments and assigns them to the appropriate member variables: employee’s name and ID number. The department and position fields should be assigned an empty string ( "" ). • A default constructor that assigns empty strings ( "" ) to the name , department , and position member variables, and 0 to the idNumber member variable. Write appropriate mutator functions that store values in these member variables and accessor functions that return the values in these member variables. Once you have written the class, write a separate program that creates three Employee objects to hold the following data. Name ID Number Department Position <NAME> 47899 Accounting Vice President <NAME> 39119 IT Programmer <NAME> 81774 Manufacturing Engineer The program should store this data in the three objects and then display the data for each employee on the screen.2. Employee Class Write a class named Employee that has the following member variables: • name. A string that holds the employee’s name. • idNumber. An int variable that holds the employee’s ID number. • department. A string that holds the name of the department where the employee works. • position. A string that holds the employee’s job title. The class should have the following constructors: • A constructor that accepts the following values as arguments and assigns them to the appropriate member variables: employee’s name, employee’s ID number, department, and position. • A constructor that accepts the following values as arguments and assigns them to the appropriate member variables: employee’s name and ID number. The department and position fields should be assigned an empty string ( "" ). • A default constructor that assigns empty strings ( "" ) to the name , department , and position member variables, and 0 to the idNumber member variable. Write appropriate mutator functions that store values in these member variables and accessor functions that return the values in these member variables. Once you have written the class, write a separate program that creates three Employee objects to hold the following data. Name ID Number Department Position <NAME> 47899 Accounting Vice President <NAME> 39119 IT Programmer <NAME> 81774 Manufacturing Engineer The program should store this data in the three objects and then display the data for each employee on the screen. <file_sep>17.4. List Reverse Modify the linked list class you created in the previous programming challenges by adding a member function named reverse that rearranges the nodes in the list so that their order is reversed. Demonstrate the function in a simple driver program. <file_sep>#ifndef EMPLOYEE_H #define EMPLOYEE_H #include <string> class Employee { private: std::string name; int number; std::string date; public: Employee() { name = ""; number = 0; date = ""; } Employee(std::string n, int num, std::string d) { name = n; number = num; date = d; } void setName(std::string n) { name = n; } void setNumber(int num) { number = num; } void setDate(std::string d) { date = d; } std::string getName() { return name; } int getNumber() { return number; } std::string getDate() { return date; } }; #endif <file_sep>#include <iostream> #include <string> #include "DynamicQueue.h" using namespace std; int main() { string name; DynamicQueue<string> queue; while (true) { cout << "Enter name: "; getline(cin, name); if (name == "q") break; queue.enqueue(name); } cout << "\nName in your list: " << endl; while (!queue.isEmpty()) { queue.dequeue(name); cout << name << endl; } cin.get(); cin.get(); return 0; } <file_sep>#ifndef DYNAMICSTACK_H #define DYNAMICSTACK_H #include <iostream> using namespace std; template <class T> class DynamicStack { private: struct StackNode { StackNode *next; T value; }; StackNode *top; public: DynamicStack() { top = nullptr; } ~DynamicStack(); void pop(T & ); void push(T ); bool isEmpty(); }; // destructor template <class T> DynamicStack<T>::~DynamicStack() { StackNode *nodePtr, *nextPtr; nodePtr = top; // position nodePtr to the top node of the stack while (nodePtr) // the loop stop when nodePtr = nullptr { nextPtr = nodePtr->next; delete nodePtr; nodePtr = nextPtr; } } // member function tp pop argument out of stack template <class T> void DynamicStack<T>::pop(T &item) { // if there is no node in the stack if (isEmpty()) cout << "The stack is empty" << endl; else { StackNode *nodePtr = nullptr; // create new nodePtr item = top->value; // assign num as the value of top node nodePtr = top->next; // position nodePtr the next pointer of top node delete top; // delete top node top = nodePtr; // assign top node new position } } // member function to push new arugment to the stack template <class T> void DynamicStack<T>::push(T item) { StackNode *newNode = nullptr; newNode = new StackNode; newNode->value = item; // if the stack is empty, make new node the top node if (isEmpty()) { top = newNode; newNode->next = nullptr; } // else assign the new node the next node of top node else { newNode->next = top; top = newNode; } } // member function returns true if the stack is empty, // return false is the stack is not empty template <class T> bool DynamicStack<T>::isEmpty() { bool status; if (top) status = false; else status = true; return status; } #endif <file_sep>#ifndef DATE_H #define DETA_H class Date { private: int day; int month; int year; void initDay(int d); void initMonth(int m); void initYear(int y); public: /*Date (int = 1, int = 1, int = 1) { initDay(1), initMonth(1), initYear(1) };*/ Date (int d, int m, int y) { initDay(d); initMonth(m); initYear(y); }; void showDate1(); void showDate2(); void showDate3(); }; #endif <file_sep>#include <iostream> #include "InventoryQueue.h" #include <string> using namespace std; const int PUSH_CHOICE = 1, POP_CHOICE = 2, QUIT_CHOICE = 3; void menu(int &); void pushItem(InventoryQueue &); void popItem(InventoryQueue &); void displayItem(InventoryQueue &); int main() { int choice; InventoryQueue queue; do { menu(choice); if (choice != QUIT_CHOICE) { switch (choice) { case PUSH_CHOICE: pushItem(queue); break; case POP_CHOICE: popItem(queue); break; } } } while (choice != QUIT_CHOICE); displayItem(queue); cin.get(); cin.get(); return 0; } void menu(int &choice) { cout << "1. Push an item into queue " << endl; cout << "2. Pop an item out of queue" << endl; cout << "3. Quit " << endl; cout << "Enter your choice: "; cin >> choice; while (choice < PUSH_CHOICE || choice > QUIT_CHOICE) { cout << "Invalid choice" << endl; cout << "Enter your choice: "; cin >> choice; } } void pushItem(InventoryQueue &queue) { string numb, date, lot; cout << "Enter the serial number: "; cin.ignore(); getline(cin, numb); cout << "Enter the manufacturing date: "; getline(cin, date); cout << "Enter the part lot: "; getline(cin, lot); queue.enqueue(numb, date, lot); cout << "Item has been pushed in" << endl; cout << endl; } void popItem(InventoryQueue &queue) { string numb, date, lot; queue.dequeue(numb, date, lot); if (queue.isEmpty()) return; else { cout << "Item has been popped out" << endl; cout << "Serial Number: " << numb << endl; cout << "Manufacturing Date: " << date << endl; cout << "Part's Lot: " << lot << endl; cout << endl; } } void displayItem(InventoryQueue &queue) { queue.display(); } <file_sep>#ifndef COIN_H #define COIN_H #include <string> class Coin { private: std::string sideUp; public: Coin(); void toss(); std::string getSideUp(); }; #endif <file_sep>13.13. Tossing Coins for a Dollar For this assignment, you will create a game program using the Coin class from Programming Challenge 12. The program should have three instances of the Coin class: one representing a quarter, one representing a dime, and one representing a nickel. When the game begins, your starting balance is $0. During each round of the game, the program will toss the simulated coins. When a coin is tossed, the value of the coin is added to your balance if it lands heads-up. For example, if the quarter lands headsup, 25 cents is added to your balance. Nothing is added to your balance for coins that land tails-up. The game is over when your balance reaches $1 or more. If your balance is exactly $1, you win the game. You lose if your balance exceeds $1. <file_sep>#include <iostream> #include <string> #include "Employee.h" Employee::Employee(std::string n, int i, std::string d, std::string p) { name = n; id = i; department = d; position = p; } Employee::Employee(std::string n, int i) { name = n; id = i; department = " "; position = " "; } Employee::Employee() { name = " "; id = 0; department = " "; position = " "; } void Employee::setName(std::string n) { name = n; } std::string Employee::getName() { return name; } void Employee::setID(int i) { id = i; } int Employee::getID() { return id; } void Employee::setDepart(std::string d) { department = d; } std::string Employee::getDepart() { return department; } void Employee::setPosi(std::string p) { position = p; } std::string Employee::getPosi() { return position; } <file_sep>7.8. Lo Shu Magic Square The Lo Shu Magic Square is a grid with 3 rows and 3 columns shown in Figure 7-19 . The Lo Shu Magic Square has the following properties: • The grid contains the numbers 1 through 9 exactly. • The sum of each row, each column, and each diagonal all add up to the same number. This is shown in Figure 7-20 . In a program you can simulate a magic square using a two-dimensional array. Write a function that accepts a two-dimensional array as an argument, and determines whether the array is a Lo Shu Magic Square. Test the function in a program. Figure 7-19: 4 | 9 | 2 ---------- 3 | 5 | 7 ---------- 8 | 1 | 6 <file_sep>#include <iostream> #include "GradeActivity.h" using namespace std; int main() { double testScore; GradeActivity test; cout << "Enter your numeric test score: "; cin >> testScore; test.setScore(testScore); cout << "The grade for that test is: " << test.getLetterGrade() << endl; return 0; } <file_sep>9.2. Test Scores #1 Write a program that dynamically allocates an array large enough to hold a userdefined number of test scores. Once all the scores are entered, the array should be passed to a function that sorts them in ascending order. Another function should be called that calculates the average score. The program should display the sorted list of scores and averages with appropriate headings. Use pointer notation rather than array notation whenever possible. Input Validation: Do not accept negative numbers for test scores. <file_sep>#ifndef NUMBER_H #define NUMBER_H #include <string> #include <stdlib.h> #include <iostream> using namespace std; class Number { private: int u; static char number[4]; static string lessThan20[20]; static string ten[10]; public: Number(char num[], int c) { for (int i = c - 1; i >= 0; i--) number[i + 4 - c] = num[i]; if (c != 4) for (int i = 0; i < 4 - c; i++) number[i] = '0'; }; string printString() { string print = ""; if ((number[0] - '0') > 0) { print.append(lessThan20[(number[0] - '0')]); print.append(" thousand "); } if ((number[1] - '0') > 0) { print.append(lessThan20[(number[1] - '0')]); print.append(" hundred and "); } if ((number[2] - '0') > 1) { print.append(ten[number[2] - '0']); print.append(" "); print.append(lessThan20[(number[3] - '0')]); return print; } else if ((number[2] - '0') == 1) { char x = number[2]; char y = number[3]; int num = atoi(&x) * 10 + atoi(&y); print.append(lessThan20[num]); } else if ((number[2] - '0') == 0) print.append(lessThan20[(number[3] - '0')]); return print; }; }; #endif <file_sep>#include <iostream> #include <fstream> #include <string> using namespace std; //Function prototype char getChoice(); int main() { const int size = 1000; // number of names on each lists char choice; // choose gender's names string names[size]; // array of string to store names on each list string input; // string to get input name int amount[size]; // array of integer to store number of names ifstream inputFile; int i = 0; choice = getChoice(); if (choice == 'b') inputFile.open("boynames.txt"); // choice b opens boynames if (choice == 'g') inputFile.open("girlnames.txt"); // choice g opens girlnames if (!inputFile.is_open()) // if statement when cannot read text file { cout << "ERROR: Cannot load data from file." << endl; cin.get(); cin.get(); exit(0); } while (i < size) { inputFile >> names[i] >> amount[i]; // reading data, names, from text file and store to names and amount array. i += 1; } cout << "Finish reading data" << endl; // read data successfully while (true) // infinite loop require users to enter names { i = 0; cout << "Enter name (Enter ""q"" to quit): "; cin >> input; if (input == "q") break; // Press q to quit the program while (input.compare(names[i]) != 0 && i < size) // function will return 0 if two strings match { i += 1; if (i == size) break; // names[size] will be invalid (line 41), so we need to break when i equal to size } if (i < size) cout << names[i] << " ranked " << i + 1 << " with " << amount[i] << " names." << endl; else cout << input << " is not found." << endl; // when i == size, which means the program read all data but cannot find any similar names } cin.get(); cin.get(); return 0; } // function definition char getChoice() // return char type 'b' for boy, 'g' for girl { char c; do { cout << "Choose boys' names or girls' names (b/g): "; cin >> c; if (c != 'b' && c != 'g') cout << "ERROR: Only choice 'b' or 'g' accepted!" << endl; } while (c != 'b' && c != 'g'); return c; } <file_sep>#include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; int main() { string fileName; // name of the file string search; // string users want to find in the file string input; // read each lines individually fstream file; vector<int> lineString; // vector to store the line which has search string int line = 1; int count = 0; cout << "Enter the name of file: "; cin >> fileName; cin.ignore(); // ignore the '\n' character at the end of the file name file.open(fileName, ios::in); cout << "Enter the string you want to find: "; getline(cin, search); cin.ignore(); // read each line individually, so the delimiter is '\n' getline(file, input, '\n'); while(file) { if (input.find(search) != string::npos) { count++; lineString.push_back(line); cout << "Line " << line << ": "; cout << input << endl; } line++; getline(file, input, '\n'); } cout << "There are " << count << " occurences" << endl; cout << "Lines: "; for (int i = 0; i < count; i++) { cout << lineString[i] << " "; } file.close(); cin.get(); cin.get(); return 0; } // we can read each sentences or each words individually, // simply by replacing '\n' by '.' or ' ' as delimiter in // the getline function // for example: getline(file, input, '.'); <line 26> <file_sep>4. Weather Statistics Write a program that uses a structure to store the following weather data for a particular month: Total Rainfall High Temperature Low Temperature Average Temperature The program should have an array of 12 structures to hold weather data for an entire year. When the program runs, it should ask the user to enter data for each month. (The average temperature should be calculated.) Once the data are entered for all the months, the program should calculate and display the average monthly rainfall, the total rainfall for the year, the highest and lowest temperatures for the year (and the months they occurred in), and the average of all the monthly average temperatures. Input Validation: Only accept temperatures within the range between –100 and +140 degrees Fahrenheit. 5. Weather Statistics Modification Modify the program that you wrote for Programming Challenge 4 so it defines an enumerated data type with enumerators for the months ( JANUARY , FEBRUARY , etc.). The program should use the enumerated type to step through the elements of the array. <file_sep>#include <iostream> #include <string> #include "DayofYear.h" using namespace std; int main() { int day; string print; cout << "Enter day in year: "; cin >> day; DayofYear dayInYear(day); print = dayInYear.print(); cout << "Your date is: " << print << endl; cin.get(); cin.get(); return 0; } <file_sep>#include <iostream> using namespace std; void processing(char [], char [], int); int main() { const int questions = 20; char answer[questions] = {'A', 'D', 'B', 'B', 'C', 'B', 'A', 'B', 'C', 'D', 'A', 'C', 'D', 'B', 'D', 'C', 'C', 'A', 'D', 'B'}; char receive[questions]; processing(answer, receive, questions); cin.get(); cin.get(); return 0; } void processing(char answer[], char receive[], int questions) { int grade = 0; int i = 0; do { cout << "Answer for questions " << i + 1 << ": "; cin >> receive[i]; if (receive[i] != 'A' && receive[i] != 'B' && receive[i] != 'C' && receive[i] != 'D') cout << "Error: Invalid answer!! Only choices A, B, C, D are accepted!!" << endl; else { if (receive[i] == answer[i]) grade += 1; i += 1; } } while ((receive[i] != 'A' && receive[i] != 'B' && receive[i] != 'C' && receive[i] && 'D') && i < questions); cout << "Your grade is : " << grade << endl; if (grade >= 15) cout << "Congratulations!! You passed the exam!! " << endl; else cout << "You are not qualified" << endl; } <file_sep>#include <iostream> using namespace std; void arrSelectSort(int *[], int); void showArrPtr(int *[], int); int main() { int size; cout << "Enter number of donations: "; cin >> size; // dynamically allocate array of integers int *donations = nullptr; donations = new int[size]; // dynamically allocate array of pointers int **arr = nullptr; arr = new int*[size]; // assign elements in pointers array to null pointer for (int count = 0; count < size; count++) { arr[count] = nullptr; } cout << "Enter donations: "; for (int count = 0; count < size; count++) { cin >> donations[count]; arr[count] = &donations[count]; // get the address of the donation array } arrSelectSort(arr, size); showArrPtr(arr, size); cin.get(); cin.get(); return 0; } void arrSelectSort(int *arr[], int size) { int minIndex, startScan; int *minValue; for (startScan = 0; startScan < size - 1; startScan++) { minIndex = startScan; minValue = arr[minIndex]; for (int index = startScan + 1; index < size; index++) { if (*minValue > *(arr[minIndex])) { minIndex = index; minValue = arr[minIndex]; } } arr[minIndex] = arr[startScan]; arr[startScan] = minValue; } } void showArrPtr(int *arr[], int size) { cout << "The donations in ascending order: "; for (int count = 0; count < size; count++) { cout << *arr[count] << endl; } cout << endl; } <file_sep>#include "InventoryStack.h" InventoryStack::~InventoryStack() { StackNode *nodePtr; nodePtr = top; while (!isEmpty()) { nodePtr = top->next; delete top; top = nodePtr; } } void InventoryStack::push(string numb, string date, string lot) { StackNode *nodePtr = new StackNode; nodePtr->serialNumber = numb; nodePtr->date = date; nodePtr->partLot = lot; if (isEmpty()) { top = nodePtr; top->next = nullptr; } else { nodePtr->next = top; top = nodePtr; } numItems++; } void InventoryStack::pop(string &numb, string &date, string &lot) { StackNode *nodePtr = new StackNode; if (isEmpty()) cout << "The stack is empty" << endl; else { nodePtr = top; numb = nodePtr->serialNumber; date = nodePtr->date; lot = nodePtr->partLot; nodePtr = top->next; delete top; top = nodePtr; numItems--; } } void InventoryStack::display() { StackNode *nodePtr = new StackNode; if (isEmpty()) cout << "The stack is empty" << endl; else { nodePtr = top; int num = numItems; while (nodePtr) { string number = nodePtr->serialNumber; string date = nodePtr->date; string lot = nodePtr->partLot; cout << "Item #" << num << endl; cout << "Serial Number : " << number << endl; cout << "Date of manufacturing: " << date << endl; cout << "Part's Lot : " << lot << endl; cout << endl; num--; nodePtr = nodePtr->next; } } } bool InventoryStack::isEmpty() { bool status; if (top) status = false; else status = true; return status; } <file_sep> #include <iostream> #include <string> using namespace std; int findSum(string); int main() { int sum; string input; cout << "Enter an array of number\n" << "and I will find the sum: "; getline(cin, input); sum = findSum(input); cout << "The sum is: " << sum << endl; cin.get(); cin.get(); return 0; } int findSum(string input) { int len = input.length(); int sum = 0; for (int i = 0; i < len; i++) { int temp = input[i] - '0'; sum += temp; } return sum; } <file_sep>#include <iostream> #include <vector> using namespace std; int main() { // initialize variables int total; // number of different elements in the array int size; // number of elements of the input array int *num = nullptr; // dynamically allocate num array which stores input elements vector<int> vec; // create vec vector which store only distinct elements; int *count = nullptr; // dynamically allocate count array which stores the occurences of each elements in num array cout << "Enter number of elements in array: "; cin >> size; num = new int[size]; cout << "Enter array: "; // get input element for (int index = 0; index < size; index++) cin >> num[index]; // set the first element of the vec vector as the first element of the num array vec.push_back(num[0]); total = 1; // set the entire vec vector for (int index = 1; index < size; index++) { bool foundNew = true; // condition when getting a new element for (int i = 0; i < index; i++) if (num[index] == num[i]) foundNew = false; if (foundNew) // if found new element { vec.push_back(num[index]); // push back the vec vector total += 1; } } count = new int[total]; // set up the count array // if the for loop get a repeated element, // the program will increase the coressponding element to 1 for (int index = 0; index < total; index++) { count[index] = 0; for (int i = 0; i < size; i++) { if (vec[index] == num[i]) count[index] += 1; } } // find the maximum element in te count array int maxCount = count[0]; int maxIndex = 0; for (int i = 1; i < total; i++) { if(maxCount < count[i]) { maxCount = count[i]; maxIndex = i; } } // print out the result cout << "The most frequent element is: "; cout << vec[maxIndex]; cout << ", with " << maxCount << " occurences.\n"; // clear the memory delete [] num; delete [] count; num = nullptr; count = nullptr; cin.get(); cin.get(); return 0; } <file_sep>#ifndef DYNAMICSTACK_H #define DYNAMICSTACK_H #include <iostream> using namespace std; template <class T> class DynamicStack { private: struct StackNode { StackNode *next; T value; }; StackNode *top; public: DynamicStack() { top = nullptr; } ~DynamicStack(); void push(T ); void pop(T & ); bool isEmpty() const; }; template <class T> DynamicStack<T>::~DynamicStack() { StackNode *nodePtr; nodePtr = top; while (!isEmpty()) { nodePtr = top->next; delete top; top = nodePtr; } } template <class T> void DynamicStack<T>::push(T item) { StackNode *nodePtr; nodePtr = new StackNode; nodePtr->value = item; if (isEmpty()) { top = nodePtr; top->next = nullptr; } else { nodePtr->next = top; top = nodePtr; } } template <class T> void DynamicStack<T>::pop(T &item) { StackNode *nodePtr; if (isEmpty()) cout << "The stack is empty " << endl; else { nodePtr = top; item = nodePtr->value; nodePtr = top->next; delete top; top = nodePtr; } } template <class T> bool DynamicStack<T>::isEmpty() const { bool status; if(top) status = false; else status = true; return status; } #endif <file_sep>17.1. Your Own Linked List Design your own linked list class to hold a series of integers. The class should have member functions for appending, inserting, and deleting nodes. Don’t forget to add a destructor that destroys the list. Demonstrate the class with a driver program. <file_sep>#include <iostream> #include <iomanip> using namespace std; void selectSort(double *, int); double findMedian(double *, int); int main() { int size; double *arr = nullptr; cout << "Enter number of integer: "; cin >> size; arr = new double[size]; cout << "Enter array of number: "; for (int count = 0; count < size; count++) cin >> arr[count]; cout << "The median of this array is: "; cout << findMedian(arr, size) << endl; delete [] arr; arr = nullptr; cin.get(); cin.get(); return 0; } void selectSort(double *arr, int size) { int startScan, minIndex; double minValue; for (startScan = 0; startScan < size - 1; startScan++) { minIndex = startScan; minValue = arr[minIndex]; for (int count = 0; count < size; count++) { if (minValue > arr[count]) { minIndex = count; minValue = arr[minIndex]; } } arr[minIndex] = arr[startScan]; arr[startScan] = minValue; } } double findMedian(double *arr, int size) { if (size % 2 == 0) return (arr[size / 2] + arr[size / 2 - 1]) / 2; else return arr[size / 2]; } <file_sep>#include <iostream> #include <fstream> #include <string> #include <cstdlib> using namespace std; int main() { string fileName; string input; int size = 0; cout << "Enter a string [Finish by '#']: "; getline(cin, input); while(true) { if (input[size] == '#') break; else size++; } // encrypt the file switch the last for (int count = 0; count < size; count++) { if (input[count] >= 65 && input[count] <= 122) input[count] = 122 - input[count] + 65; else if (input[count] >= 32 && input[count] <= 47) input[count] = 65 + rand() % (122 - 65); } cout << "Address: " << &input << endl; cout << "Enter file's name to save: "; getline(cin, fileName); // there are two ways to write a string to a file // 1. use file.put(ch) with file is fstream object and // ch is a char // 2. use file.write(&str[0], size), with &str[0] is the // address of the first string, size is the size of // string of characters. // In this example, I use 2nd way. fstream outputFile(fileName, ios::out); outputFile.write(&input[0], size); outputFile.close(); cin.get(); cin.get(); return 0; } <file_sep>#include <iostream> #include <string> #include "Date.h" void Date::initDay(int d) { if (d < 31 && d > 0) day = d; else { std::cout << "Invalide value" << std::endl; exit(EXIT_FAILURE); } } void Date::initMonth(int m) { if (m < 13 && m > 0) month = m; else { std::cout << "Invalide value" << std::endl; exit(EXIT_FAILURE); } } void Date::initYear(int y) { if (y > 0) year = y; else { std::cout << "Invalide value" << std::endl; exit(EXIT_FAILURE); } } void Date::showDate1() { std::cout << day << "/" << month << "/" << year << std::endl; } void Date::showDate2() { std::string strMonth; switch(month) { case 1: strMonth = "January"; break; case 2: strMonth = "Febuary"; break; case 3: strMonth = "March"; break; case 4: strMonth = "April"; break; case 5: strMonth = "May"; break; case 6: strMonth = "June"; break; case 7: strMonth = "July"; break; case 8: strMonth = "August"; break; case 9: strMonth = "September"; break; case 10: strMonth = "October"; break; case 11: strMonth = "November"; break; case 12: strMonth = "December"; break; } std::cout << strMonth << " " << day << ", " << year << std::endl; } void Date::showDate3() { std::string strMonth; switch(month) { case 1: strMonth = "January"; break; case 2: strMonth = "Febuary"; break; case 3: strMonth = "March"; break; case 4: strMonth = "April"; break; case 5: strMonth = "May"; break; case 6: strMonth = "June"; break; case 7: strMonth = "July"; break; case 8: strMonth = "August"; break; case 9: strMonth = "September"; break; case 10: strMonth = "October"; break; case 11: strMonth = "November"; break; case 12: strMonth = "December"; break; } std::cout << day << " " << strMonth << " " << year << std::endl; } <file_sep>11.12. Course Grade Write a program that uses a structure to store the following data: Member Name Description Name Student name Idnum Student ID number Tests Pointer to an array of test scores Average Average test score Grade Course grade The program should keep a list of test scores for a group of students. It should ask the user how many test scores there are to be and how many students there are. It should then dynamically allocate an array of structures. Each structure’s Tests member should point to a dynamically allocated array that will hold the test scores. After the arrays have been dynamically allocated, the program should ask for the ID number and all the test scores for each student. The average test score should be calculated and stored in the average member of each structure. The course grade should be computed on the basis of the following grading scale: Average Test Grade Course Grade 91–100 A 81–90 B 71–80 C 61–70 D 60 or below F The course grade should then be stored in the Grade member of each structure. Once all this data is calculated, a table should be displayed on the screen listing each student’s name, ID number, average test score, and course grade. Input Validation: Be sure all the data for each student is entered. Do not accept negative numbers for any test score. <file_sep>#ifndef QUEUE_H #define QUEUE_H #include <iostream> using namespace std; template <class X> class Queue { private: X *queueArray; int queueSize; int front; int rear; int numItems; public: Queue (int); Queue (const Queue &); ~Queue(); void enqueue(X ); void dequeue(X &); bool isEmpty() const; bool isFull() const; void clear(); }; template <class X> Queue<X>::Queue(int s) { queueArray = new X[s]; queueSize = s; front = -1; rear = -1; numItems = 0; } template <class X> Queue<X>::Queue(const Queue &obj) { queueArray = new X[obj.queueSize]; queueSize = obj.queueSize; front = obj.front; rear = obj.rear; numItems = obj.numItems; } template <class X> Queue<X>::~Queue() { delete [] queueArray; } template <class X> void Queue<X>::enqueue(X item) { if (isFull()) cout << "The stack is full " << endl; else { front = (front + 1) % queueSize; queueArray[front] = item; numItems++; } } template <class X> void Queue<X>::dequeue(X &item) { if (isEmpty()) cout << "The stack is empty " << endl; else { rear = (rear + 1) % queueSize; item = queueArray[rear]; numItems--; } } template <class X> bool Queue<X>::isFull() const { bool status; if (numItems < queueSize) status = false; else status = true; return status; } template <class X> bool Queue<X>::isEmpty() const { bool status; if (numItems > 0) status = false; else status = true; return status; } template <class X> void Queue<X>::clear() { front = -1; rear = -1; numItems = 0; } #endif <file_sep>#include <iostream> #include "InventoryStack.h" #include <string> using namespace std; const int PUSH_CHOICE = 1, POP_CHOICE = 2, QUIT_CHOICE = 3; void menu(int &); void pushItem(InventoryStack &); void popItem(InventoryStack &); void displayItem(InventoryStack &); int main() { int choice; InventoryStack stack; do { menu(choice); if (choice != QUIT_CHOICE) { switch (choice) { case PUSH_CHOICE: pushItem(stack); break; case POP_CHOICE: popItem(stack); break; } } } while (choice != QUIT_CHOICE); displayItem(stack); cin.get(); cin.get(); return 0; } void menu(int &choice) { cout << "1. Push an item into stack " << endl; cout << "2. Pop an item out of stack" << endl; cout << "3. Quit " << endl; cout << "Enter your choice: "; cin >> choice; while (choice < PUSH_CHOICE || choice > QUIT_CHOICE) { cout << "Invalid choice" << endl; cout << "Enter your choice: "; cin >> choice; } } void pushItem(InventoryStack &stack) { string numb, date, lot; cout << "Enter the serial number: "; cin.ignore(); getline(cin, numb); cout << "Enter the manufacturing date: "; getline(cin, date); cout << "Enter the part lot: "; getline(cin, lot); stack.push(numb, date, lot); cout << "Item has been pushed in" << endl; } void popItem(InventoryStack &stack) { string numb, date, lot; stack.pop(numb, date, lot); if (stack.isEmpty()) return; else { cout << "Item has been popped out" << endl; cout << "Serial Number: " << numb << endl; cout << "Manufacturing Date: " << date << endl; cout << "Part's Lot: " << lot << endl; } } void displayItem(InventoryStack &stack) { stack.display(); } <file_sep>9.8. Mode Function In statistics, the mode of a set of values is the value that occurs most often or with the greatest frequency. Write a function that accepts as arguments the following: A) An array of integers B) An integer that indicates the number of elements in the array The function should determine the mode of the array. That is, it should determine which value in the array occurs most often. The mode is the value the function should return. If the array has no mode (none of the values occur more than once), the function should return −1. (Assume the array will always contain nonnegative values.) Demonstrate your pointer prowess by using pointer notation instead of array notation in this function. <file_sep>14.2. Day of the Year Assuming that a year has 365 days, write a class named DayOfYear that takes an integer representing a day of the year and translates it to a string consisting of the month followed by day of the month. For example, Day 2 would be January 2 . Day 32 would be February 1 . Day 365 would be December 31. The constructor for the class should take as parameter an integer representing the day of the year, and the class should have a member function print() that prints the day in the month–day format. The class should have an integer member variable to represent the day and should have static member variables holding string objects that can be used to assist in the translation from the integer format to the month-day format. Test your class by inputting various integers representing days and printing out their representation in the month–day format <file_sep>#include <iostream> #include <string> #include <iomanip> #include "Employee.h" int main() { const int NUM_EMP = 3; Employee employee[NUM_EMP] = { Employee("<NAME>", 47899, "Accounting ", "Vice President"), Employee("<NAME> ", 39119, "IT ", "Programmer "), Employee("<NAME> ", 81774, "Manufacturing", "Engineer ") }; std::cout << "Name " << "ID " << "Department " << "Position " << std::endl; for (int count = 0; count < NUM_EMP; count++) { std::cout << employee[count].getName() << std::setw(15) << employee[count].getID() << "\t\t" << employee[count].getDepart() << "\t\t" << employee[count].getPosi() << std::endl; } std::cin.get(); std::cin.get(); return 0; } // Program should use cstring instead of string. While using cstring, we can define the number of char, // which can align the table better <file_sep>13.10. Number Array Class Design a class that has an array of floating-point numbers. The constructor should accept an integer argument and dynamically allocate the array to hold that many numbers. The destructor should free the memory held by the array. In addition, there should be member functions to perform the following operations: • Store a number in any element of the array • Retrieve a number from any element of the array • Return the highest value stored in the array • Return the lowest value stored in the array • Return the average of all the numbers stored in the array Demonstrate the class in a program. <file_sep>#ifndef INVENTORYSTACK_H #define INVENTORYSTACK_H #include <string> #include <iostream> using namespace std; class InventoryStack { private: struct StackNode { StackNode *next; string serialNumber; string date; string partLot; }; StackNode *top; int numItems; public: InventoryStack() { top = nullptr; numItems = 0; } ~InventoryStack(); void push(string, string, string ); void pop(string &, string &, string & ); void display(); bool isEmpty(); }; #endif <file_sep>#include <iostream> #include "Array.h" Array::Array(int s) { size = s; arr = new double[size]; for (int i = 0; i < size; i++) arr[i] = 0; } Array::~Array() { delete [] arr; } void Array::setElement(int i, double v) { arr[i] = v; } double Array::getElement(int i) { return arr[i]; } double Array::findHighest() { double highest = arr[0]; for (int i = 1; i < size; i++) if (arr[i] > highest) highest = arr[i]; return highest; } double Array::findLowest() { double lowest = arr[0]; for (int i = 1; i < size; i++) if (arr[i] < lowest) lowest = arr[i]; return lowest; } double Array::findAverage() { double sum = 0; for (int i = 0; i < size; i++) sum += arr[i]; return sum / size; } <file_sep>#include "NumberList.h" // function definition // basically, this function will flip the array of struct from left to right // now head pointer would be the last struct void NumberList::reverseNode() { ListNode *nodePtr; // to traverse the array of struct ListNode previousNode; // point to previous node int i = 0; // to count the number of struct in this array nodePtr = head; nodePtr->previous = nullptr; // the previous pointer of head pointer is nullptr // with that in mind, the array is end two side by two nullptr // get to the end struct while (nodePtr->next) { nodePtr = nodePtr->next; i += 1; } head = nodePtr; // assign head pointer new position // while inside the array while (i >= 0) { nodePtr->next = nodePtr->previous; nodePtr = nodePtr->previous; // move the nodePtr back to the beginning i -= 1; } } <file_sep>#include <iostream> #include <string> #include "Number.h" using namespace std; int main() { char num[4] = {'0', '0', '0', '0'}; int count = 0; char n; string printResult; cout << "Enter number: "; while (count < 4) { cin.get(n); if (n == '\n') break; num[count] = n; count++; } Number number(num, count); printResult = number.printString(); cout << "Your number is: " << printResult << endl; cin.get(); cin.get(); return 0; } <file_sep>#include <iostream> #include <fstream> #include <string> #include <cctype> using namespace std; int main() { string outName; // name of the output file string inName; // name of input file fstream outFile; fstream inFile; char input; // a character variable that will store character of input file individually cout << "Enter the name of the input file: "; cin.ignore(); getline(cin, inName); cout << "Enter the name of the output file: "; cin.ignore(); getline(cin, outName); inFile.open(inName, ios::in); outFile.open(outName, ios::out); if(inFile) { // firstly, we need to get the first character of input file, // capitalize it, and then put it into the output file inFile.seekg(0L, ios::cur); // set the pointer to the first character of input file inFile.get(input); // get that character outFile.seekp(0L, ios::cur); // set the pointer tp the first character of output file outFile.put(toupper(input)); // capitalize by toupper member function and put it into output file while (inFile.eof() == false) / { inFile.seekg(0L, ios::cur); inFile.get(input); outFile.seekp(0L, ios::cur); outFile.put(tolower(input)); // decapitalize all character in the middle of the sentences //***************************************************************************************** // when the program meet the '.' character, which indicating the end of the sentence, * // in the output file, we need to put a blank ' ' character next to the current offset, * // then capitalize the next character and put it in the next offset * //***************************************************************************************** if (input == '.') // when meet the '.' character { outFile.seekp(0L, ios::cur); outFile.put(' '); // put blank character ' ' to the next offset inFile.seekg(1L, ios::cur); //get the character of the next two offset inFile.get(input); // store it in input variable outFile.seekp(0L, ios::cur); // get the address of the next character outFile.put(toupper(input)); // capitalize input variable and put it in the ouput file } } inFile.close(); // close file outFile.close(); // close file } else cout << "Cannot open the input file. " << endl; cin.get(); cin.get(); return 0; } <file_sep>9. Median Function In statistics, when a set of values is sorted in ascending or descending order, its median is the middle value. If the set contains an even number of values, the median is the mean, or average, of the two middle values. Write a function that accepts as arguments the following: A) An array of integers B) An integer that indicates the number of elements in the array The function should determine the median of the array. This value should be returned as a double . (Assume the values in the array are already sorted.) Demonstrate your pointer prowess by using pointer notation instead of array notation in this function. <file_sep>#include <iostream> #include <cstring> using namespace std; int countChar(char *); int main() { const int STR_SIZE = 20; char string[STR_SIZE]; int num; cout << "Enter a string: "; // getline member function which get the // whole line of input, including the [SPACE] cin.getline(string, STR_SIZE); num = countChar(string); cout << "The number of characters: " << num << endl; cin.get(); cin.get(); return 0; } int countChar(char *string) { int num = 0; int index = 0; while (string[index] != '\0') { index++; num++; } return num; } <file_sep>#include "Coin.h" #include <string> #include <cstdlib> #include <ctime> Coin::Coin() { srand(time(0)); toss(); } void Coin::toss() { std::string values[2] = {"heads", "tails"}; int i; i = rand() % 2; sideUp = values[i]; } std::string Coin::getSideUp() { return sideUp; } <file_sep>#include <iostream> #include <fstream> #include <string> using namespace std; int main() { char ch; string fileName; string input; fstream file; int line; // to count the line up to 24 lines cout << "Enter the name of the file: "; cin >> fileName; cin.ignore(); // ignore the '\n' at the end of the file name file.open(fileName, ios::in); if (file) // if can open the file { getline(file, input, '\n'); // read a line in the file and put into input string while (file) // while true { line = 1; while (line <= 24) { cout << input << endl; getline(file, input); line++; // count up to 24 } cout << "Enter the continue: "; cin.get(ch); } } else cout << "Cannot open the file!" << endl; cin.get(); cin.get(); return 0; } <file_sep>#include <iostream> using namespace std; int *reversedArray(int *, int); int main() { int size; cout << "Enter number of element in your array: "; cin >> size; // dynamically allocate num array int *num = nullptr; num = new int[size]; // receive element for (int i = 0; i < size; i++) cin >> num[i]; // dynamically allocate reversed array int *rvs = nullptr; rvs = new int[size]; // reverse array function call rvs = reversedArray(num, size); cout << "Reversed array: "; for (int index = 0; index < size; index++) cout << rvs[index] << " "; cout << endl; // clear array from memory delete [] num; delete [] rvs; num = nullptr; rvs = nullptr; cin.get(); cin.get(); return 0; } // function definition int *reversedArray(int *num, int size) { int *arr = nullptr; arr = new int[size]; for (int index = 0; index < size; index++) arr[index] = num[size - 1 - index]; return arr; } <file_sep>#include "NumberList.h" // insert the number according to the index, // if index = 0, put the number at the beginning of the array // if index > length of array, put the number at the end of the array void NumberList::insertNode(int index, double num) { ListNode *newNode; // to store the value of new number ListNode *nodePtr; // to traverse the array ListNode *previousNode; newNode = new ListNode; // dynamically allocate new truct newNode->value = num; // store the number value // if the index = 0, put number at the beginning of the array if (index == 0) { newNode->next = head; head = newNode; } // if index is greater than 0 else { int i = 0; nodePtr = head; // traverse the nodePtr as long as it reach the index or it surpass the lenght of array while (nodePtr->next != nullptr && i < index) { previousNode = nodePtr; nodePtr = nodePtr->next; i += 1; } // if the index surpass the length of array, which mean nodePtr->next is nullptr if (nodePtr->next == nullptr) { nodePtr->next = newNode; newNode->next = nullptr; } // if the index is inside the array else { // put the newNode between previousNode and nodePtr previousNode->next = newNode; newNode->next = nodePtr; } } } <file_sep>#include <iostream> #include <string> using namespace std; struct Sales { string name; double first; double second; double third; double fourth; double total; double average; }; Sales receiveData(); void showData(Sales); const int num = 4; int main() { Sales division[num]; for (int index = 0; index < num; index++) { cout << "Enter data for division " << index + 1 << ": " << endl; division[index] = receiveData(); cout << endl; } for (int index = 0; index < num; index++) { cout << "Division " << index + 1 << ": " << endl; showData(division[index]); cout << endl; } cin.get(); cin.get(); return 0; } Sales receiveData() { Sales data; cout << "Name: "; cin.ignore(); // ignore '\n' character getline(cin, data.name); cout << "First-Quater Sales: $"; cin >> data.first; cout << "Second-Quater Sales: $"; cin >> data.second; cout << "Third-Quater Sales: $"; cin >> data.third; cout << "Fourth-Quater Sales: $"; cin >> data.fourth; data.total = (data.first + data.second + data.third + data.fourth); data.average = data.total / 4; return data; } void showData(Sales data) { cout << "Name: " << data.name << endl; cout << "Total Sales: $" << data.total << endl; cout << "Average Sales: $" << data.average << endl; } <file_sep>12.6. String Search Write a program that asks the user for a file name and a string to search for. The program should search the file for every occurrence of a specified string. When the string is found, the line that contains it should be displayed. After all the occurrences have been located, the program should report the number of times the string appeared in the file. <file_sep>#ifndef RETAILITEM_H #define RETAILITEM_H #include <string> class RetailItem { private: std::string desc; int units; double price; public: RetailItem(std::string d, int u, double p) { desc = d; units = u; price = p; } void setDescription(std::string d) { desc = d; } void setUnits(int u) { units = u; } void setPrice(double p) { price = p; } std::string getDescription() { return desc; } int getUnits() { return units; } double getPrice() { return price; } }; #endif <file_sep>#include <iostream> #include <string> using namespace std; const int size = 12; struct Weather { int rain; int highTemp; int lowTemp; double averTemp; }; enum Months {JANUARY, FEBUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER}; void showMonth(Months ); // because struct is stored in memory in one location // we understand array of struct is a normal array void processData(Weather []); // or void processData(Weather *); int main() { Weather data[size]; Months index; for (index = JANUARY; index <= DECEMBER; index = static_cast<Months>(index + 1)) { cout << "Enter data for "; showMonth(index); cout << ": " << endl; cout << "Rain Fall: "; cin >> data[index].rain; cout << "Highest Temperature: "; cin >> data[index].highTemp; cout << "Lowest Temperature: "; cin >> data[index].lowTemp; cout << "Average Temperature: "; cin >> data[index].lowTemp; } processData(data); cin.get(); cin.get(); return 0; } void showMonth(Months index) { switch(index) { case JANUARY : cout << "January"; break; case FEBUARY : cout << "Febuary"; break; case MARCH : cout << "March"; break; case APRIL : cout << "April"; break; case MAY : cout << "May"; break; case JUNE : cout << "June"; break; case JULY : cout << "July"; break; case AUGUST : cout << "August"; break; case SEPTEMBER: cout << "September"; break; case OCTOBER : cout << "October"; break; case NOVEMBER : cout << "November"; break; case DECEMBER : cout << "December"; } } void processData(Weather data[]) { int totalRain = 0; double averRain; int highestTemp = data[0].highTemp; int lowestTemp = data[0].lowTemp; for (int index = 0; index < size; index++) { totalRain += data[index].rain; if (highestTemp < data[index].highTemp) highestTemp = data[index].highTemp; if (lowestTemp > data[index].lowTemp) lowestTemp = data[index].lowTemp; } averRain = totalRain / size; cout << "Total Rain: " << totalRain << endl; cout << "Average Rain: " << averRain << endl; cout << "Highest Temperature: " << highestTemp << endl; cout << "Lowest Temperature: " << lowestTemp << endl; } <file_sep>9. 5. Pointer Rewrite The following function uses reference variables as parameters. Rewrite the function so it uses pointers instead of reference variables, and then demonstrate the function in a complete program. int doSomething(int &x, int &y) { int temp = x; x = y * 10; y = temp * 10; return x + y; } <file_sep>#include <iostream> #include <fstream> #include <string> using namespace std; const int DESC_SIZE = 30; struct InventoryItem { char desc[DESC_SIZE]; int qty; int price; }; void readFile(InventoryItem , fstream &, int ); void writeFile(InventoryItem , fstream & , int ); int main() { int itemNum; string fileName("Inventory.dat"); InventoryItem item = {" ", 0, 0}; fstream file(fileName, ios::in | ios::out | ios::binary); char go; do { cout << "Do you want to write or read or quit: "; cin.ignore(); cin.get(go); cout << "Enter the inventory number: "; cin >> itemNum; if (go == 'r') readFile(item, file, itemNum); else if (go == 'w') writeFile(item, file, itemNum); } while (go != 'q'); file.close(); cin.get(); cin.get(); return 0; } void readFile(InventoryItem item, fstream &file, int itemNum) { file.clear(); file.seekg(itemNum * sizeof(item), ios::beg); file.read(reinterpret_cast<char *>(&item), sizeof(item)); cout << "Item number " << itemNum << ": " << endl; cout << "Description: " << item.desc << endl; cout << "Quantity: " << item.qty << endl; cout << "Price: " << item.price << endl; } void writeFile(InventoryItem item, fstream &file, int itemNum) { file.clear(); file.seekp(itemNum * sizeof(item), ios::beg); cout << "Item number " << itemNum << ": " << endl; cout << "Description: "; cin.ignore(); cin.getline(item.desc, DESC_SIZE); cout << "Quantity: "; cin >> item.qty; cout << "Price: "; cin >> item.price; file.write(reinterpret_cast<char *>(&item), sizeof(item)); } <file_sep>18.12. Inventory Bin Stack Design an inventory class that stores the following members: serialNum : An integer that holds a part's serial number. manufactDate : A member that holds the date the part was manufactured. lotNum : An integer that holds the part's lot number. The class should have appropriate member functions for storing data into, and retrieving data from, these members. Next, design a stack class that can hold objects of the class described above. If you wish, you may use the template you designed in Programming Challenge 1 or 2. Last, design a program that uses the stack class described above. The program should have a loop that asks the user if he or she wishes to add a part to inventory, or take a part from inventory. The loop should repeat until the user is finished. If the user wishes to add a part to inventory, the program should ask for the serial number, date of manufacture, and lot number. The data should be stored in an inventory object, and pushed onto the stack. If the user wishes to take a part from inventory, the program should pop the top-most part from the stack and display the contents of its member variables. When the user finishes the program, it should display the contents of the member values of all the objects that remain on the stack. <file_sep>#include <iostream> #include <string> #include "Coin.h" int main() { Coin coin; for (int i = 0; i < 20; i++) { coin.toss(); std::cout << coin.getSideUp() << std::endl; } std::cin.get(); std::cin.get(); return 0; } <file_sep>#include <iostream> #include <string> #include "Coin.h" int main() { double sum = 0; char ch; Coin coin1, coin2, coin3; coin1.setValue(0.05); coin2.setValue(0.1); coin3.setValue(0.25); while (sum < 1) { std::cout << "Your current point is: " << sum << std::endl; coin1.toss(); coin2.toss(); coin3.toss(); std::cout << coin1.getValue() << ": " << coin1.getSideUp() << std::endl; std::cout << coin2.getValue() << ": " << coin1.getSideUp() << std::endl; std::cout << coin3.getValue() << ": " << coin3.getSideUp() << std::endl; if (coin1.checkCoin() == true) sum += coin1.getValue(); if (coin2.checkCoin() == true) sum += coin2.getValue(); if (coin3.checkCoin() == true) sum += coin3.getValue(); std::cout << "[ENTER] to toss again!!"; std::cin.get(ch); } std::cout << "your point is: " << sum << std::endl; if (sum == 1) std::cout << "You win!!" << std::endl; else std::cout << "You lose!!" << std::endl; std::cin.get(); std::cin.get(); return 0; } <file_sep>7.17. Name Search If you have downloaded this book’s source code from the companion Web site, you will find the following files in this chapter’s folder: • GirlNames.txt—This file contains a list of the 200 most popular names given to girls born in the United States from 2000 to 2009. • BoyNames.txt—This file contains a list of the 200 most popular names given to boys born in the United States from 2000 to 2009. Write a program that reads the contents of the two files into two separate arrays or vector s. The user should be able to enter a boy’s name, a girl’s name, or both, and the application should display messages indicating whether the names were among the most popular. <file_sep>11.1. Movie Data Write a program that uses a structure named MovieData to store the following information about a movie: Title Director Year Released Running Time (in minutes) The program should create two MovieData variables, store values in their members, and pass each one, in turn, to a function that displays the information about the movie in a clearly formatted manner. <file_sep>12.7. Sentence Filter Write a program that asks the user for two file names. The first file will be opened for input and the second file will be opened for output. (It will be assumed that the first file contains sentences that end with a period.) The program will read the contents of the first file and change all the letters to lowercase except the first letter of each sentence, which should be made uppercase. The revised contents should be stored in the second file. <file_sep>14.1. Numbers Class Design a class Numbers that can be used to translate whole dollar amounts in the range 0 through 9999 into an English description of the number. For example, the number 713 would be translated into the string seven hundred thirteen , and 8203 would be translated into eight thousand two hundred three . The class should have a single integer member variable: int number; and a static array of string objects that specify how to translate key dollar amounts into the desired format. For example, you might use static strings such as string lessThan20[20] = {"zero", "one", ..., "eighteen", "nineteen"}; string hundred = "hundred"; string thousand = "thousand"; The class should have a constructor that accepts a nonnegative integer and uses it to initialize the Numbers object. It should have a member function print() that prints the English description of the Numbers object. Demonstrate the class by writing a main program that asks the user to enter a number in the proper range and then prints out its English description. <file_sep>12.4. Tail Program Write a program that asks the user for the name of a file. The program should display the last 10 lines of the file on the screen (the “tail” of the file). If the file has fewer than 10 lines, the entire file should be displayed, with a message indicating the entire file has been displayed. <file_sep>#include <iostream> #include <cstring> using namespace std; const int STR_SIZE = 80; void convertString(char *, char *); int main() { char string[STR_SIZE]; // string to store the input char string1[STR_SIZE]; // string to store the reversed string cout << "Enter a string: "; cin.getline(string, STR_SIZE); cout << "You entered: " << string1 << endl; convertString(string, string); cout << "The reversed string is: " << string1 << endl; cin.get(); cin.get(); return 0; } void convertString(char *string, char *string1) { int num_size = 0; int index = 0; while (string[index] != '\0') // find the total characters { num_size++; index++; } cout << "num_size: " << num_size << endl; for (int index = 0; index < num_size; index++) { string1[index] = string[num_size - 1 - index]; } string1[num_size] = '\0'; // assign the null character to finish the string } // Q: This function cannot work when use returning pointer // from sub function. // Q: Cannot use "string" alone, // ex: convertString(string, string) (line 17) <file_sep>#ifndef PRODUCTIONWORKER_H #define PRODUCTIONWORKER_H #include "Employee.h" #include <iostream> class ProductionWorker : public Employee { private: int shift1, shift2; double payRate1, payRate2; int shift; double payRate; public: ProductionWorker() : Employee() { shift1 = 1; shift2 = 2; payRate1 = 1.5; payRate2 = 2.0; } void setShift(int s) { if (s == shift1) shift = shift1; else if (s == shift2) shift = shift2; else std::cout << "Invalid value!!" << std::endl; } void selectRate() { if (shift == shift1) payRate = payRate1; else if (shift == shift2) payRate = payRate2; } double getPayRate() { return payRate; } }; #endif <file_sep>7.10. Driver’s License Exam The local Driver’s License Office has asked you to write a program that grades the written portion of the driver’s license exam. The exam has 20 multiple choice questions. Here are the correct answers: 1. A 2. D 3. B 4. B 5. C 6. B 7. A 8. B 9. C 10. D 11. A 12. C 13. D 14. B 15. D 16. C 17. C 18. A 19. D 20. B Your program should store the correct answers shown above in an array. It should ask the user to enter the student’s answers for each of the 20 questions, and the answers should be stored in another array. After the student’s answers have been entered, the program should display a message indicating whether the student passed or failed the exam. (A student must correctly answer 15 of the 20 questions to pass the exam.) It should then display the total number of correctly answered questions, the total number of incorrectly answered questions, and a list showing the question numbers of the incorrectly answered questions. Input Validation: Only accept the letters A, B, C, or D as answers. <file_sep>#include <iostream> #include <iomanip> #include <string> #include "RetailItem.h" int main() { const int NUM_ITEM = 3; RetailItem item[NUM_ITEM] = {RetailItem("Jacket", 12, 59.95), RetailItem("Designer Jeans", 40, 34.95), RetailItem("Shirt", 20, 24.95)}; std::cout << std::left << std::setw(15) << " " << std::setw(25) << "Description" << std::setw(25) << "Units on Hand" << std::setw(25) << "Price" << std::endl; std::cout << "--------------------------------------" << "--------------------------------------" << std::endl; for (int count = 0; count < NUM_ITEM; count++) { std::cout << std::left << "Item #" << std::setw(9) << count + 1 << std::setw(25) << item[count].getDescription() << std::setw(25) << item[count].getUnits() << std::setw(25) << item[count].getPrice() << std::endl; } std::cin.get(); std::cin.get(); return 0; } // std::setw() to set the width of each strings // std::left to justify the strings on the left // originally, strings are justify on the right // we don't need to use cstring anymore <file_sep>#include <iostream> using namespace std; //function prototype void bubbleSort(int [], int); void selectSort(int [], int); int main() { char choice, // c again; const int size = 10; do { int num[size] = {1, 52, 62, 12, 67, 86, 44, 90, 77, 33}; // print elements before sorting cout << "Before sorting: "; for (int i = 0; i < size; i++) cout << num[i] << " "; cout << endl; // choose bubble sort or selection sort cout << "Selection sort or Bubble sort? ('s' or 'b'): "; cin >> choice; if (choice == 's') selectSort(num, size); else bubbleSort(num, size); // print elements after sorting cout << "After sort: "; for (int i = 0; i < size; i++) cout << num[i] << " "; cout << endl; cout << "Again? (y / n): "; cin >> again; } while (again == 'y' || again == 'Y'); cin.get(); cin.get(); return 0; } //*********************************************************************** // Definition of function bubble sort. * // Set default swap to false. * // Compare two nearest elements. If former element is bigger than later * // element, swap the positions of two element, and set swap to true. * // The while loop will check wether swap is true or false, if true, the * // loop will start over again. If false, the array is sorted. * //*********************************************************************** void bubbleSort(int num [], int size) { bool swap; int temp; do { swap = false; // set swap to false, means there is no swap yet for (int i = 0; i < size; i++) { if (num[i] > num[i + 1]) // compare two nearest elements { // if true, swap their positions temp = num[i]; num[i] = num[i + 1]; num[i + 1] = temp; swap = true; // set swap to true } } } while (swap); // if swap is true, the code will run again from line 55 } //*********************************************************************** // Definition of function selection sort. * // * // * //*********************************************************************** void selectSort(int num [], int size) { int startSort, minValue, // smallest elements in the array from startSort index to the last index minIndex; // index of the smallest element for (startSort = 0; startSort < size - 1; startSort++) { minIndex = startSort; // set minIndex as the startSort index minValue = num[minIndex]; // set minValue as the element of minIndex for (int index = startSort + 1; index < size; index++) // find the smallest elements of the rest array { if (minValue > num[index]) // if statement to find the smaller element { minValue = num[index]; minIndex = index; } } num[minIndex] = num[startSort]; // if true, swap the positions of the smallest element to the start sort index num[startSort] = minValue; } } <file_sep>#include <iostream> #include <string> #include "DynamicStack.h" using namespace std; const int PUSH_CHOICE = 1, POP_CHOICE = 2, QUIT_CHOICE = 3; void menu(int & ); void pushItem(DynamicStack<string> & ); void popItem(DynamicStack<string> & ); int main() { int choice; DynamicStack<string> stack; do { menu(choice); if (choice != QUIT_CHOICE) { switch (choice) { case PUSH_CHOICE: pushItem(stack); break; case POP_CHOICE: popItem(stack); break; } } } while (choice != QUIT_CHOICE); cin.get(); cin.get(); return 0; } void menu(int &choice) { cout << "1. Push an item into stack " << endl; cout << "2. Pop an item out of stack" << endl; cout << "3. Quit " << endl; cout << "Enter your choice: "; cin >> choice; while (choice < PUSH_CHOICE || choice > QUIT_CHOICE) { cout << "Invalid choice" << endl; cout << "Enter your choice: "; cin >> choice; } } void pushItem(DynamicStack<string> &stack) { string item; cout << "Enter your book's name: "; cin.ignore(); getline(cin, item); stack.push(item); cout << item << " has been pushed in" << endl; } void popItem(DynamicStack<string> &stack) { string item; if (stack.isEmpty()) cout << "No more item in the stack " << endl; else { stack.pop(item); cout << item << " has been pop out " << endl; } } <file_sep>#include <iostream> #include <iomanip> using namespace std; void sortSelectArr(double *[], int); void showArr(double *[], int); double average(double *[], int); int main() { double aver; const int max_size = 10; int size; cout << "Enter number of scores (maximum 10): "; cin >> size; double score[max_size]; // array of score // set array of pointer point to score array, // all elements is null pointer double *ptr[max_size] = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}; for (int i = 0; i < size; i++) { cout << "Enter score #" << i + 1 << ": "; cin >> score[i]; // receive score ptr[i] = &score[i]; // point the pointer store in ptr array to the score array } sortSelectArr(ptr, size); // select sort showArr(ptr, size); cout << fixed << showpoint << setprecision(4); aver = average(ptr, size); cout << "The average score is: " << aver << endl; delete [] ptr; ptr = nullptr; cin.get(); cin.get(); return 0; } //*********************************************************** // Definition of the select sort function * // This function change the position of the elements which * // contains the address of the pointer point to score array,* // and thus changing the position of the scores's elements * //*********************************************************** void sortSelectArr(double *score[], int size) { int startScan, minIndex; double *minValue; for (startScan = 0; startScan < size - 1; startScan++) { minIndex = startScan; minValue = score[minIndex]; for (int index = startScan + 1; index < size; index++) { if (*minValue > *score[index]) { minIndex = index; minValue = score[index]; } } score[minIndex] = score[startScan]; score[startScan] = minValue; } } void showArr(double *score[], int size) { cout << "You entered: "; for (int count = 0; count < size; count++) cout << *score[count] << " "; cout << endl; } double average(double *ptr[], int size) { double sum = 0; for (int index = 0; index < size; index++) sum += *ptr[index]; return sum / size; } <file_sep>5. Line Numbers (This assignment could be done as a modification of the program in Programming Challenge 2.) Write a program that asks the user for the name of a file. The program should display the contents of the file on the screen. Each line of screen output should be preceded with a line number, followed by a colon. The line numbering should start at 1. Here is an example: 1:<NAME> 2:127 Academy Street 3:Brasstown, NC 28706 <file_sep>#ifndef MATHSTACK_H #define MATHSTACK_H #include "DynamicStack.h" template <class T> class MathStack : public DynamicStack<T> { public: MathStack() : DynamicStack() {} void mult(); void div(); void addAll(); void multAll(); }; template <class T> void MathStack<T>::mult() { T first; T second; pop(first); pop(second); if (isEmpty()) cout << "The stack is empty" << endl; else { first = first * second; push(first); } } template <class T> void MathStack<T>::div() { T first; T second; pop(first); pop(second); if (isEmpty()) cout << "The stack is empty" << endl; else { first = first / second; push(first); } } template <class T> void MathStack<T>::addAll() { T sum = 0; T num; if (isEmpty()) cout << "The stack is empty" << endl; else { while (!isEmpty()) { pop(num); sum += num; } push(sum); } } template <class T> void MathStack<T>::multAll() { T sum = 1; T num; if (isEmpty()) cout << "The stack is empty" << endl; else { while (!isEmpty()) { pop(num); sum *= num; } push(sum); } } #endif <file_sep>5. RetailItem Class Write a class named RetailItem that holds data about an item in a retail store. The class should have the following member variables: • description . A string that holds a brief description of the item. • unitsOnHand . An int that holds the number of units currently in inventory. • price . A double that holds the item’s retail price. Write a constructor that accepts arguments for each member variable, appropriate mutator functions that store values in these member variables, and accessor functions that return the values in these member variables. Once you have written the class, write a separate program that creates three RetailItem objects and stores the following data in them. Description Units On Hand Price Item #1 Jacket 12 59.95 Item #2 Designer Jeans 40 34.95 Item #3 Shirt 20 24.95 <file_sep>#include "DayofYear.h" #include <string> #include <sstream> using namespace std; int DayofYear::days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; string DayofYear::months[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; //********************************************************************* // this member function first compare the day to the number of day * // of the first month, January. If day is bigger than number of day * // in January, 31, day will keep subtract to that number, and then * // compare to the next month. If day smaller than the number of day * // in month, keep return that number and return the month * //********************************************************************* DayofYear::DayofYear(int d) { for (int i = 0; i < 12; i++) { if (d > days[i]) d -= days[i]; else { month = i; day = d; break; } } } string DayofYear::print() { // stringstream stringstream out; out << day; // convert an integer day to string d string d = out.str(); // at the beginning, result = ""; result.append(months[month]); //result = "Febuary" result.append(" "); // result = "Febuary " result.append(d); // result = "Febuary 28" return result; } <file_sep>This is the first program I write in Vim, Linux 2/2/2016 9:33 PM <file_sep>#include <iostream> #include <vector> using namespace std; //Prototype bool checkPIN(vector<int>, vector<int>, int); int main() { const int size = 7; //Initialize arrays: int pin1Array[size] = {1, 2, 3, 4, 5, 6, 7}; int pin2Array[size] = {2, 3, 4, 6, 1, 2, 5}; int pin3Array[size] = {1, 1, 1, 5, 6, 9, 8}; //Emulate vector by array: vector<int> pin1(&pin1Array[0], &pin1Array[0] + size); vector<int> pin2(&pin2Array[0], &pin2Array[0] + size); vector<int> pin3(&pin3Array[0], &pin3Array[0] + size); if (checkPIN(pin1, pin2, size)) cout << "ERROR: pin1 and pin2 report to be the same." << endl; else cout << "SUCCESS: pin1 and pin2 are different." << endl; if (checkPIN(pin2, pin3, size)) cout << "ERROR: pin2 and pin3 report to be the same." << endl; else cout << "SUCCESS: pin2 and pin3 are different." << endl; if (checkPIN(pin1, pin1, size)) cout << "SUCCESS: pin1 and pin1 report to be the same." << endl; else cout << "ERROR: pin1 and pin1 are different." << endl; cin.get(); cin.get(); return 0; } //Function definition, receive two vector as arguments, //named pin1 and pin2 bool checkPIN(vector<int> pin1, vector<int> pin2, int size) { for (int i = 0; i < size; i++) if (pin1[i] != pin2[i]) return false; return true; } <file_sep>#include <iostream> #include <string> #include <vector> using namespace std; void findFrequent(string); int main() { string input; cout << "Enter a string: "; getline(cin, input); findFrequent(input); cin.get(); cin.get(); return 0; } void findFrequent(string input) { vector<int> stats1; vector<char> stats2; int index; for (index = 1; index < input.length(); index++) { int count = 1; for (int i = 0; i < index; i++) { if (input[index] == input[i]) count++; } stats1.push_back(count); stats2.push_back(input[index]); } int maxCount = stats1[0]; int maxIndex; for (int i = 1; i < stats1.size(); i++) { if (maxCount < stats1[i]) { maxCount = stats1[i]; maxIndex = i; } } cout << "Most frequent character is " << stats2[maxIndex] << " with " << stats1[maxIndex] << " occurences.\n"; }
34eb52c76fb34cfda98a76a63c957ba8c4c70041
[ "Markdown", "Text", "C++" ]
126
Markdown
phn10/C-Tutorial
8bd95907b5b15673eba72876634719f47132e19a
74091fa7b2664dc23de82b74773c7976fabedb0c
refs/heads/master
<repo_name>YongdongHe/HiFriends<file_sep>/app/src/main/java/club/hifriends/BaseBlankActivity.java package club.hifriends; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; import club.hifriends.auth.AuthHelper; /** * Created by heyon on 2016/1/29. */ public class BaseBlankActivity extends Activity{ AuthHelper authHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.authHelper = new AuthHelper(this); } public void showMsg(String msg){ Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show(); } public AuthHelper getAuthHepler(){ return authHelper; } public void startActivityAndFinish(Intent intent){ startActivity(intent); finish(); } } <file_sep>/app/src/main/java/club/hifriends/auth/AuthHelper.java package club.hifriends.auth; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.widget.Toast; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; import org.json.JSONException; import org.json.JSONObject; import java.net.ConnectException; import java.net.SocketTimeoutException; import club.hifriends.BaseAppCompatActivity; import club.hifriends.BaseBlankActivity; import okhttp3.Call; /** * Created by heyon on 2016/1/29. */ public class AuthHelper { private Context context; private Activity activity; public static String url = "http://172.16.58.3:8000/"; // public static String url = "http://192.168.1.107:8000/";//测试用本地服务 private SharedPreferences pref; private SharedPreferences.Editor editor; public AuthHelper(final Activity activity){ this.activity = activity; this.context = activity.getBaseContext(); this.pref = activity.getSharedPreferences("hifriends", Context.MODE_PRIVATE); this.editor = activity.getSharedPreferences("hifriends", Context.MODE_PRIVATE).edit(); } public void checkAuth(){ //检查uuid的正确情况,如果正确则更新个人信息 String uuid = getUUID(); if(uuid == ""){ Toast.makeText(context, "请登录", Toast.LENGTH_SHORT); doLogout(); return; } OkHttpUtils .get() .url(AuthHelper.url+"user/info") .addParams("uuid",uuid) .build() .execute(new StringCallback() { @Override public void onError(Call call, Exception e) { //错误检测 if (e instanceof SocketTimeoutException) { Toast.makeText(context, "网络连接超时", Toast.LENGTH_SHORT); } else if (e instanceof ConnectException) { Toast.makeText(context, "网络连接错误", Toast.LENGTH_SHORT); } else { Toast.makeText(context, "\"未知错误\"", Toast.LENGTH_SHORT); } } @Override public void onResponse(String response) { try { JSONObject json_res = new JSONObject(response); if (json_res.getInt("code") == 200) { ////如果返回的状态码是200则说明uuid正确,则更新各类个人信息 setAuthCache("name", json_res.getJSONObject("content").getString("name")); setAuthCache("phone", json_res.getJSONObject("content").getString("phone")); } else { //如果返回的状态码不是200则说明uuid不对,需要重新授权,则注销当前登录 Toast.makeText(context, "登录信息已失效,请重新登录", Toast.LENGTH_SHORT); doLogout(); } } catch (JSONException e) { e.printStackTrace(); } } }); } public void doLogout() throws ClassCastException{ //清除信息 setAuthCache("uuid", ""); setAuthCache("name", ""); setAuthCache("phone", ""); //跳转到登录页 Intent intent = new Intent(context,LoginActivity.class); if(activity instanceof BaseAppCompatActivity){ ((BaseAppCompatActivity) activity).startActivityAndFinish(intent); }else if (activity instanceof BaseBlankActivity) { ((BaseBlankActivity) activity).startActivityAndFinish(intent); }else{ throw new ClassCastException(); } } public String getUUID(){ //获得存储的uuid String uuid = pref.getString("uuid",""); return uuid; } public String getAuthCache(String cacheName){ //可用 /** * uuid 认证用uuid * cardnuim 一卡通号 * schoolnum 学号 * name 名字 * sex 性别 */ //获得存储的某项信息 String authCache = pref.getString(cacheName,""); return authCache; } public boolean setAuthCache(String cacheName,String cacheValue){ //用于更新存储的某项信息 editor.putString(cacheName, cacheValue); return editor.commit(); } } <file_sep>/app/src/main/java/club/hifriends/activity/ActivityHelper.java package club.hifriends.activity; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import club.hifriends.activity.beans.ActivityItem; /** * Created by heyon on 2016/1/31. */ public class ActivityHelper { public static ArrayList<ActivityItem> transfromJSONtoArrayList(JSONArray jsonArray) throws JSONException{ ArrayList<ActivityItem> list = new ArrayList<>(); //遍历json数组 Log.d("activityHelper",jsonArray.length()+""); for(int i = 0;i<jsonArray.length();i++){ JSONObject activityItem = jsonArray.optJSONObject(i); list.add(new ActivityItem( activityItem.getString("leader"), activityItem.getString("time"), activityItem.getString("label"), activityItem.getString("id"), activityItem.getString("title"), activityItem.getString("content") )); } return list; } } <file_sep>/app/src/main/java/club/hifriends/activity/beans/ActivityItem.java package club.hifriends.activity.beans; /** * Created by heyon on 2016/1/31. */ public class ActivityItem { private String tips;//顶端提示 private String leader;//活动发起者 private String time; private String label;//活动标签 private String activity_id;//活动id private String title; private String content;//活动内容 public ActivityItem(String leader, String time, String label, String activity_id, String title,String content) { this.leader = leader; this.time = time; this.label = label; this.activity_id = activity_id; this.title = title; this.content = content; } public String getTips() { return leader+" 发起了活动"; } public String getLeader() { return leader; } public String getTime() { return time; } public String getLabel() { return label; } public String getActivity_id() { return activity_id; } public String getTitle(){ return title; } public String getContent() { return content; } } <file_sep>/README.md # HiFriends HiFriends-Android 更新日志 2016/2/3 23:49:23 测试版本alpha1.0基础功能: 1.发布和参与活动 2.拨打参与者手机号 已知bug: 1.多个空页面(没时间写了,暂时先写了很简单的基础功能) 2.活动页参与人数标签一直都是0 3.个人信息更新后,侧边栏并不会马上更新个人信息 4.页面多个EditView在第二次点击时键盘不会将其顶上去,导致输入框被键盘遮住 <file_sep>/app/src/main/java/club/hifriends/auth/LoginActivity.java package club.hifriends.auth; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; import org.json.JSONException; import org.json.JSONObject; import java.net.ConnectException; import java.net.SocketTimeoutException; import club.hifriends.BaseBlankActivity; import club.hifriends.MainActivity; import club.hifriends.R; import okhttp3.Call; /** * Created by heyon on 2016/1/28. */ public class LoginActivity extends BaseBlankActivity { EditText et_phone; EditText et_psd; Button btn_log; ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_auth_login); et_phone = (EditText)findViewById(R.id.et_login_phone); et_psd = (EditText)findViewById(R.id.et_login_psd); btn_log = (Button)findViewById(R.id.btn_login_login); btn_log.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doLogin(); } }); } private void doLogin(){ btn_log.setEnabled(false); progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setMessage("登录中"); progressDialog.show(); String phone = et_phone.getText().toString(); String psd = et_psd.getText().toString(); OkHttpUtils .post() .url(AuthHelper.url+"auth/dolog") .addParams("phone",phone) .addParams("psd",psd) .build() .execute(new StringCallback() { @Override public void onError(Call call, Exception e) { progressDialog.dismiss(); btn_log.setEnabled(true); if (e instanceof SocketTimeoutException) { showMsg("网路连接超时"); } else if (e instanceof ConnectException) { showMsg("网络连接错误"); } else { showMsg("未知错误"); } } @Override public void onResponse(String response) { progressDialog.dismiss(); btn_log.setEnabled(true); try { JSONObject json_res = new JSONObject(response); showMsg(json_res.getString("content")); if (json_res.getInt("code") == 200) { String uuid = json_res.getString("uuid"); getAuthHepler().setAuthCache("uuid", uuid); startActivity(new Intent(getBaseContext(), MainActivity.class)); finish(); } } catch (JSONException e) { e.printStackTrace(); showMsg("数据解析错误"); } } } ); } } <file_sep>/app/src/main/java/club/hifriends/auth/SelectFragment.java package club.hifriends.auth; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import club.hifriends.R; /** * Created by heyon on 2016/1/28. */ public class SelectFragment extends Fragment { View fragmentContainer; public SelectFragment(){ } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //获得fragment的布局 fragmentContainer = inflater.inflate(R.layout.fragment_auth_select,container,false); //为登录和注册按钮绑定跳转 Button btn_login = (Button)fragmentContainer.findViewById(R.id.auth_btn_login); btn_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startActivity(new Intent(getActivity().getBaseContext(),LoginActivity.class)); } }); Button btn_register = (Button)fragmentContainer.findViewById(R.id.auth_btn_register); btn_register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startActivity(new Intent(getActivity().getBaseContext(),RegisterActivity.class)); } }); return fragmentContainer; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
c1dd2e8d4133ee53def7a315676943c1affd8e1e
[ "Markdown", "Java" ]
7
Java
YongdongHe/HiFriends
cc2cb085dd053d7b6459214ca158b1e19a57c6d6
56c6941cc778b78d4757e6f5ee24fab890911f59
refs/heads/master
<repo_name>abapat/Tweemo-PHP<file_sep>/README.md TweetBeat ======== Twitter sentimental analysis project <file_sep>/PHP/graph.php <html> <head> <style type="text/css"> body{color:white; background-color:black; font-family:arial;} h1{color:yellow;} img{display:inline-block; float:left; height:300px; margin-top:75px; margin-left:50px;} #chart_div{width:900px; height:500px; display:inline-block; float:right; margin-left:auto; margin-right:auto;} ul{list-style-type:none;} #tweets{margin-top:500px;} </style> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> var data, options; var rows = new Array(); var doneLoadingGoogle = false; var doneLoadingRows = false; var chart; var tweets = new Array(); function loadPackages(){ google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(setChart); } //sets up the columns and options function setChart(){ data = new google.visualization.DataTable(); data.addColumn('string', 'Month'); data.addColumn('number', 'Feeling'); options = { backgroundColor: 'white', title: 'AMIT', pointSize: 10, vAxis: { title: 'Happiness Level', gridlines: {color: 'blue'}, baseline: 0, baselineColor: 'red', minValue: -1, maxValue: 1, titleTextStyle: {color: 'blue'}, textStyle: {color: 'cornflowerblue'} }, hAxis: { title: 'Month', gridlines: {color: 'blue'}, titleTextStyle: {color: 'blue'}, textStyle: {color: 'cornflowerblue'}, slantedTextAngle: 90 }, legend: { textStyle: {color: 'blue'}, }, legend: { position: 'none' }, series: {0:{color:'#F38921'}}, titleTextStyle: { color: 'black', fontSize: 24 }/*, curveType: 'function'*/ }; drawChart(); } //renders the chart function drawChart() { if(!doneLoadingRows){ doneLoadingGoogle = true; return; } data.addRows(rows); chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); google.visualization.events.addListener(chart, 'select', selectHandler ); } //creates a pop-up when a dot is selected function selectHandler() { var selectedItem = chart.getSelection()[0]; if (selectedItem) { var twtArr = tweets[selectedItem.row]; if(twtArr[0] !=""){ document.getElementById("negMsg").innerHTML="Most Negative Tweet : "+twtArr[0]; document.getElementById("negScore").innerHTML="Feeling : "+twtArr[1]; } else{ document.getElementById("negMsg").innerHTML=""; document.getElementById("negScore").innerHTML=""; } if(twtArr[2] != ""){ document.getElementById("posMsg").innerHTML="Most Positive Tweet : "+twtArr[2]; document.getElementById("posScore").innerHTML="Feeling : "+twtArr[3]; } else{ document.getElementById("posMsg").innerHTML=""; document.getElementById("posScore").innerHTML=""; } } } function </script> <?php function openFile($filename){ $file = fopen($filename, "r") or die("Unable to open file!"); if ($file) { $latestDate = NULL; $totalScore = 0; $count = 0; $maxPos = array("score"=>0, "tweet"=>""); $maxNeg = array("score"=>0, "tweet"=>""); while (($line = fgets($file)) !== false) { //gets the tweet id $idx = strpos($line, " "); $id = substr($line, 0, $idx); $line = substr($line, $idx+1, strlen($line)); //gets the date $idx = strpos($line, " "); $date = substr($line, 0, $idx); $line = substr($line, $idx+1, strlen($line)); $dateArr = explode("@", $date); //alters $dateArr[0] so that the graph aggregates data monthly //$idx = strrpos($dateArr[0], "-"); //$dateArr[0] = substr($dateArr[0], 0, $idx); //gets the score $idx = strrpos($line, " "); $score = substr($line, $idx, strlen($line)); $line = substr($line, 0, $idx); //this is done again b/c there was an extra space at the end of each line. $idx = strrpos($line, " "); $score = (double)substr($line, $idx, strlen($line)); $line = substr($line, 0, $idx); //gets the tweet $idx = strrpos($line, " "); $tweet = str_replace("\"","&quot;",substr($line, 0, $idx)); //initializing first date if($latestDate == NULL){ $latestDate = $dateArr[0]; $totalScore += $score; //sets the maxPos/maxNeg tweet if($score >= 0){ $maxPos["score"] = $score; $maxPos["tweet"] = $tweet; } else{ $maxNeg["score"] = $score; $maxNeg["tweet"] = $tweet; } } //if we've past the current date, then create a new row else if($latestDate != NULL && strcmp($latestDate, $dateArr[0]) != 0){ //create the string that would display in a mini-window $winStr = ""; if($totalScore > 0) $winStr .= "Most Positive Tweet : ".$maxPos["tweet"]; if($totalScore < 0) $winStr .= "Most Negative Tweet : ".$maxNeg["tweet"]; echo("<script text=\"text/javascript\"> tweets.push([\"".$maxNeg["tweet"]."\", ".$maxNeg["score"].", \"".$maxPos["tweet"]."\", ".$maxPos["score"]."]); rows.push(['".$latestDate."',".($totalScore/($count+1))."]); </script>"); $latestDate = $dateArr[0]; $totalScore = $score; //[re]sets the maxPos and maxNeg tweet if($score >= 0){ $maxPos["score"] = $score; $maxPos["tweet"] = $tweet; $maxNeg["score"] = 0; $maxNeg["tweet"] = ""; } else{ $maxNeg["score"] = $score; $maxNeg["tweet"] = $tweet; $maxPos["score"] = 0; $maxPos["tweet"] = ""; } $count = 0; } else{ $totalScore += $score; $count++; //sets the maxPos/maxNeg tweet if($score > $maxPos["score"]){ $maxPos["score"] = $score; $maxPos["tweet"] = $tweet; } if($score < $maxNeg["score"]){ $maxNeg["score"] = $score; $maxNeg["tweet"] = $tweet; } } } } else { echo "ERROR : File Not Found."; } fclose($file); //finished processing all rows; if we're connected to the google packages then render the graph echo("<script text=\"text/javascript\"> if(doneLoadingGoogle) drawChart(); else{ doneLoadingRows = true; } </script>" ); } ?> </head> <body> <script type="text/javascript"> loadPackages(); </script> <?php openfile("cacheConanOBrien.txt"); ?> <br /> <img src = 'https://pbs.twimg.com/profile_images/1132696610/securedownload_normal.jpeg' /> <span id="chart_div"></span> <br /> <br /> <ul id="tweets"> <li id="negMsg"> </li> <ul> <li id="negScore"></li> </ul> <li id="posMsg"> </li> <ul> <li id="posScore"></li> </ul> </ul> </body> </html><file_sep>/textToSentiment.php <?php /** Object that encapsulates the sentiment of a tweet */ class sentiment { public $score=""; //The score the tweet has recieved between 1->-1 public $type=""; //The type of tweet, positve, negative, neutral } function getTweetSentiment($tweet){ require_once 'Alchemy/alchemyapi_php/alchemyapi.php'; $alchemyapi = new AlchemyAPI(); //Object that represents the alchemy API $firstChar = $tweet[0]; //Gets first character of the tweet $tweetSentiment = new sentiment; if($firstChar == 'R' || $firstChar == '@'){ //If it's retweet or mention, get to the meat of the tweet $colonIndex = strpos($tweet, ':'); $tweet = substr($tweet, $colonIndex+1); } try{ $response = $alchemyapi->sentiment("text", $tweet, null); //Send a sentiment alchemy request if (strcmp($response['status'], "ERROR") != 0) { $tweetSentiment->type = $response['docSentiment']['type']; //Set the type if (strcmp($tweetSentiment->type, "neutral") == 0) $tweetSentiment->score = 0.00; else $tweetSentiment->score = $response['docSentiment']['score']; //Set the score } } catch(Exception $e){ echo 'Caught Exception: ', $e->getMessage(), "\n"; //Catch the exception if the request breaks somehow } return $tweetSentiment; // return object } function getNumHashTags($line){ return substr_count($line, '#'); } ?><file_sep>/index.php <html> <head> <title>Welcome to TweetBeat, the Twitter sentiment site!</title> <!-- Bootstrap --> <link href="styles/bootstrap-3.2.0/css/bootstrap.min.css" rel="stylesheet"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Custom styles for this template --> <link href="styles/cover.css" rel="stylesheet"> <link href="styles/index.css" rel="stylesheet"> <link href="styles/clouds.css" rel="stylesheet"> <script src="javascript/index.js"></script> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <!--<script type="text/javascript"></script>--> </head> <!-- ~~~~~~~~~~~~~~~~~~~~ PHP Starts~~~~~~~~~~~~~~~~ --> <?php include 'PHP/process.php'; if (isset($_POST['value'])) { $twitterHandle = $_POST['value']; search($twitterHandle); } if (isset($_GET['search'])) { $twitterHandle = $_GET['search']; openFile("Cache Files/cache".$twitterHandle.".txt"); } //finished processing all rows; if we're connected to the google packages then render the graph echo("<script text=\"text/javascript\"> if(doneLoadingGoogle) drawChart(); else{ doneLoadingRows = true; } </script>" ); ?> <!-- ~~~~~~~~~~~~~~~~~~ HTML Starts ~~~~~~~~~~~~~~~~~~~ --> <body> <div id="clouds"> <div class="site-wrapper"> <div class="site-wrapper-inner"> <div class="cover-container"> <!-- POTENTIALLY USEFUL NAVBAR CODE <div class="masthead clearfix"> <div class="inner"> <h3 class="masthead-brand">TweetBeat</h3> <ul class="nav masthead-nav"> <li class="active"><a href="#">About</a></li> </ul> </div> </div> --> <div class="inner cover"> <h1 class="cover-heading">TweetBeat</h1> <p class="lead">The Twitter Sentiment Analysis Tool</p> </div> <div id="searchFormDiv"> <input type="text" id="searchBar" placeholder="Enter Twitter Handle Here!"/> <input text="Search" id="searchButton" type="submit" /> <!--<div id="balanceDiv"></div>--> </div> </div> <script type="text/javascript"> loadPackages(); </script> <div> </div> <div id="chart_container"> <br /> <!--<img src = 'https://pbs.twimg.com/profile_images/1132696610/securedownload_normal.jpeg' /> IMAGE THING--> <span id="chart_div"></span> <br /> <br /> </div> <div id="totalCount"></div> <br /> <div id="count"></div> <ul id="tweets"> <li id="negMsg"> </li> <ul> <li id="negScore"></li> </ul> <li id="posMsg"> </li> <ul> <li id="posScore"></li> </ul> </ul> </div> </div> </div> <div class="cloud x1"></div> <!-- Time for multiple clouds to dance around --> <div class="cloud x2"></div> <div class="cloud x3"></div> <div class="cloud x4"></div> <div class="cloud x5"></div> </body> </html> <file_sep>/PHP/process.php <?php include 'textToSentiment.php'; require_once('TwitterAPIExchange.php'); global $settings, $twitter, $name, $pic, $path, $TweetsPulled, $TweetsAnalyzed, $tweets; class date { public $month; public $day; public $year; public $time; } //******************** $TweetsPulled = 200; $TweetsAnalyzed = 200; //********************* $settings = array( 'oauth_access_token' => "<KEY>", 'oauth_access_token_secret' => "<KEY>", 'consumer_key' => "<KEY>", 'consumer_secret' => "<KEY>" ); $twitter = new TwitterAPIExchange($settings); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /* * Searches for handle and prints semantic analysis to cache */ function search($term) { global $name, $path, $TweetsPulled, $TweetsAnalyzed, $tweets; $name = $term; $path = "Cache Files/cache".$name.".txt"; $id = getID($name); $pic = getProfilePic($id, $name); $max_id = getNextID($path); //gets next tweet to cache, creates file if new cache to be made $tweets = getTweets($name, $id, $TweetsPulled, $max_id); if (!isset($tweets) || count($tweets) < 1) { echo("<script> alert('Bad Twitter Handle'); </script>"); return; } $res = parseData($tweets, $TweetsAnalyzed); } /* * Gets all friends of user function getFriends($name) { $url = "https://api.twitter.com/1.1/friends/ids.json"; $getfield = "?screen_name=".$name."&count=5000"; $requestMethod = "GET"; $arr = null; try { $var = $twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest(); $arr = (json_decode($var)); } catch (Exception $e) { echo("Error $e"); } return $arr; } */ /* * Gets URL of profile pic * @param userID, screen name * @return string, URL of profile pic */ function getProfilePic($id, $name) { global $settings, $twitter; $url = "https://api.twitter.com/1.1/users/show.json"; $getfield = "?user_id=".$id."&screen_name=".$name; $requestMethod = "GET"; $arr = null; try { $var = $twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest(); $arr = (json_decode($var)); } catch (Exception $e) { echo("Error $e"); } $img = $arr->profile_image_url; return str_replace("_normal", "", $img); } /** * Given a screen name, outputs ID */ function getID($name) { global $settings, $twitter; $url = "https://api.twitter.com/1.1/users/lookup.json"; $getfield = "?screen_name=" . $name; $requestMethod = "GET"; $arr = null; try { $var = $twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest(); $arr = (json_decode($var)); //print_r($arr); if (isset($arr->errors)) { error($arr->errors); return; } } catch (Exception $e) { echo("Error $e"); } $id = $arr[0]->id; return $id; } /* * Shows error, refreshes page */ function error($err) { $str = $err[0]->message; echo("<script> alert('".$str."'); window.open('index.php','_self'); </script>"); } /** * Gets JSON data into array- tweet data. params: id, name of person, num of tweets to pull, num < 200 * if max ID is -1, gets most recent. Else, gets tweets older than maxID */ function getTweets($name, $id, $num, $maxID) { global $settings, $twitter; //$maxID = (int) $maxID; if ($num > 200) { $num = 200; } $url = "https://api.twitter.com/1.1/statuses/user_timeline.json"; $getfield = "?count=".$num."&exclude_replies=true&include_rts=false&user_id=".$name."&screen_name=".$name; if (strcmp($maxID,"-1") != 0) { $getfield = $getfield."&max_id=".$maxID; } $requestMethod = "GET"; $arr = null; try { $var = $twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest(); $arr = (json_decode($var)); } catch (Exception $e) { echo("Error $e"); } return $arr; } /* * Gets ID of last tweet in array parsed from JSON */ function getLastTweetID($arr) { $ind = count($arr) - 1; $id = $arr[$ind]->id_str; return $id; } /** * @param Array, tweet object * @return Date object, date of tweet */ function getTweetDate($arr) { $str = $arr->created_at; $sArr = explode(" ", $str); $date = new Date(); $date->month = $sArr[1]; $date->day = $sArr[2]; $date->year = $sArr[5]; $date->time = $sArr[3]; return $date; } /** * @param Array, tweet object * @return String, ID of tweet */ function getTweetID($arr) { $id = $arr->id_str; return $id; } /** * @param Array, tweet object * @return String, Tweet text */ function getTweetText($arr) { $str = $arr->text; $str = preg_replace('/[[:^print:]]/', '', $str); //parse out weird chars return $str; } /* * Cleans links from tweet */ function cleanTweet($str) { $pos = stripos($str, "http"); if ($pos === false) { } else { $str = substr($str, 0, $pos); } return $str; } /** * Parses JSON object for tweets, gets sentiment object & writes to file with date * @param array of JSON data, number of tweets to analyze */ function parseData($arr, $num) { global $path; $count = 0; $flag = file_exists($path); $res = array(); //for debug $ind = 0; foreach ($arr as $tweet) { if ($flag == true) { $flag = false; continue; } $date = getTweetDate($tweet); $id = getTweetID($tweet); $str = getTweetText($tweet); $str = cleanTweet($str); if (strlen($str) < 5) continue; //using alchamy $sentiment = getTweetSentiment($str); $result = array(); $result[0] = $id; $result[1] = $date; $result[2] = $str; $result[3] = $sentiment->type; $result[4] = $sentiment->score; $resultString = getCacheString($result); writeInfo($result); writeData($resultString); $res[$ind++] = $resultString; if ($count > $num) break; $count++; } return $res; } function writeInfo($res) { $str = "Name: " .$name. "\tMonth: " . $result[1]->month . "\tScore: " . $res[4] . "\r\nTweet: " . $res[2] . "\r\n\r\n"; write($str); } function write($str) { $filename = "TweetData.txt"; if (!file_exists($filename)) { $file = fopen($filename, "a"); } file_put_contents($filename, $string, FILE_APPEND); } /** * Given a string, it writes the string to the a file for the particular twitter user declared in the * Global name identifier. It creates a file if a file for that user doesn't exist, and appends to it * if it does. * @param: String to write to file */ function writeData($string){ global $path; $filename = $path; if (!file_exists($filename)) { $file = fopen($filename, "a"); } file_put_contents($filename, $string, FILE_APPEND); } /** * Returns the string that needs to be written to the cache file. Modular method for getting the string, can be echoed or * written to file. */ function getCacheString($arr){ $count = 0; $string = ""; foreach($arr as &$value){ if($count==1){ $tweetDate = $arr[1]; $string = $string.($tweetDate->year)."-".($tweetDate->month)."-".($tweetDate->day)."@".($tweetDate->time)." "; } else{ $string = $string.$value." "; } $count++; } $string = $string."\r\n"; return $string; } /** * Return the oldest ID received in cache * @param String to file * @return String representation of oldest ID */ function getNextID($filepath){ $exists = file_exists($filepath); if ($exists == false) return "-1"; $line = ''; $f = fopen($filepath, 'r'); $cursor = -1; fseek($f, $cursor, SEEK_END); $char = fgetc($f); /** * Trim trailing newline chars of the file */ while ($char === "\n" || $char === "\r") { fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } /** * Read until the start of file or first newline char */ while ($char !== false && $char !== "\n" && $char !== "\r") { /** * Prepend the new char */ $line = $char.$line; fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } $indexOfFirstSpace = stripos($line, ' '); $line = substr($line, 0, $indexOfFirstSpace); return $line; } function openFile($filename){ $file = fopen($filename, "r") or die("Unable to open file!"); if ($file) { $latestDate = NULL; $totalScore = 0; $count = 0; $maxPos = array("score"=>0, "tweet"=>""); $maxNeg = array("score"=>0, "tweet"=>""); while(true) { if(($line = fgets($file)) !== false){ //gets the tweet id $idx = strpos($line, " "); $id = substr($line, 0, $idx); $line = substr($line, $idx+1, strlen($line)); //gets the date $idx = strpos($line, " "); $date = substr($line, 0, $idx); $line = substr($line, $idx+1, strlen($line)); $dateArr = explode("@", $date); //alters $dateArr[0] so that the graph aggregates data monthly $idx = strrpos($dateArr[0], "-"); $dateArr[0] = substr($dateArr[0], 0, $idx); //gets the score $idx = strrpos($line, " "); $score = substr($line, $idx, strlen($line)); $line = substr($line, 0, $idx); //this is done again b/c there was an extra space at the end of each line. $idx = strrpos($line, " "); $score = (double)substr($line, $idx, strlen($line)); $line = substr($line, 0, $idx); //gets the tweet $idx = strrpos($line, " "); $tweet = str_replace("\"","&quot;",substr($line, 0, $idx)); } //initializing first date if($latestDate == NULL){ $latestDate = $dateArr[0]; $totalScore += $score; //sets the maxPos/maxNeg tweet if($score >= 0){ $maxPos["score"] = $score; $maxPos["tweet"] = $tweet; } else{ $maxNeg["score"] = $score; $maxNeg["tweet"] = $tweet; } } //if we've past the current date or reached the end of file, then create a new row else if($line===false || ($latestDate != NULL && strcmp($latestDate, $dateArr[0]) != 0)){ //create the string that would display in a mini-window echo("<script text=\"text/javascript\"> tweets.push([".($count+1).",\"".$maxNeg["tweet"]."\", ".$maxNeg["score"].", \"".$maxPos["tweet"]."\", ".$maxPos["score"]."]); rows.push(['".$latestDate."',".($totalScore/($count+1))."]); </script>"); $latestDate = $dateArr[0]; $totalScore = $score; //[re]sets the maxPos and maxNeg tweet if($score >= 0){ $maxPos["score"] = $score; $maxPos["tweet"] = $tweet; $maxNeg["score"] = 0; $maxNeg["tweet"] = ""; } else{ $maxNeg["score"] = $score; $maxNeg["tweet"] = $tweet; $maxPos["score"] = 0; $maxPos["tweet"] = ""; } $count = 0; } else{ $totalScore += $score; $count++; //sets the maxPos/maxNeg tweet if($score > $maxPos["score"]){ $maxPos["score"] = $score; $maxPos["tweet"] = $tweet; } if($score < $maxNeg["score"]){ $maxNeg["score"] = $score; $maxNeg["tweet"] = $tweet; } } //if we reached the end of the file, then exit loop if($line === false) break; } } else { echo "ERROR : File Not Found."; } fclose($file); } ?> <file_sep>/oldPages/page.php <html> <head> <title>Welcome to TweetBeat, the twitter sentiment site!</title> <!-- Bootstrap --> <link href="styles/bootstrap-3.2.0/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="styles/cover.css" rel="stylesheet"> </head> <body> <div id="clouds"> <div class="site-wrapper"> <div class="site-wrapper-inner"> <div class="cover-container"> <div class="masthead clearfix"> <div class="inner"> <h3 class="masthead-brand">TweetBeat</h3> <ul class="nav masthead-nav"> <li class="active"><a href="#">About</a></li> </ul> </div> </div> <div class="inner cover"> <h1 class="cover-heading">TweetBeat</h1> <p class="lead">The Twitter Sentiment Analysis Tool</p> </div> <div id="searchFormDiv"> <input id="searchBar" placeholder="Enter Twitter Handle Here!"/> <button id="searchButton">Search</button> </div> </div> </div> </div> </div> </div> <div class="cloud x1"></div> <!-- Time for multiple clouds to dance around --> <div class="cloud x2"></div> <div class="cloud x3"></div> <div class="cloud x4"></div> <div class="cloud x5"></div> </div> </div> </body> </html> <?php ?>
40e70b74a70007b26880f6248189014fb68fc4bc
[ "Markdown", "PHP" ]
6
Markdown
abapat/Tweemo-PHP
d41b6a38c6faa0cc849eae00017161c719036586
1f659c9c5b0439d9ce62635d25578288b02243eb
refs/heads/master
<file_sep> Algorithm: Step 1 : Take input from user: a := lower limit b := upper limit Step 2 : Calculating mid value for biased probability mid_val := (a+b)/2 Step 3 : Calculate range of biased numbers by mid_val (excluding mid_val) eg. 73% above 5 and 27% below 5 min_list := min_list will contain value from range 'a' to mid_val-1 max_list := max_list will contain value from range mid_val+1 to b+1 Step 4 : Calculate random number using Linear congruential generator(Pseudo-random Number Genrator) while(length of max_list =! 73) number = (current_time +increment_value * multiplier) % mod value = number/mod value_in_range = (mid_val+1) + value * ((b+1)-(mid_val+1)) add value_in_range to max_list while(length of min_list =! 27) number = (current_time +increment_value * multiplier) % mod value = number/mod value_in_range = a + value * ((mid_val-1)-a) add value_in_range to min_list Step 5 : Show min_list , max_list and final_list (concatenation of min_list and max_list) Explanation: 1. First take the lower limit and upper limit of range from user. Calculate mid value from these two limits to separate the range into two parts upper range and lower range. 2. Then create two list say min_list which will contain values from lower limit to mid value(excluding) and max_list which will contain values from mid value (excluding) to upper limit. 3. Start the while loop1 until the length of max_list becomes 73. In this loop random number is generated using Linear congruential generator(LCG) method in which an equation is used ie [number = (increment + current time * multiplier) % mod] and then 'number' generated from this equation is put into [value = number / mod] (which will give output value between 0 and 1). And this value is put into a formula [lower limit + value * (upper limit - lower limit] to calculate random number in given desired range. Then add final value to max_list 4. Start the second while loop2 until the length of min list becomes 27. Same procedure is done as above while loop1 Then add final value to min_list 5. Print both the max_list and min_list 6. Then print final_list ie concatenated list of max_list and min_list <file_sep>import math import time class RandomNumberGenerator(): def __init__(self, current_time=time.time(), multiplier=1664525, increment=1013904223, modulus=math.pow(2, 32)): # initialise variable self.multiplier = multiplier self.increment = increment self.modulus = modulus self.current_time = current_time def lcg(self): # Creating Pseudo-Rnadom Number Genrator using LCG self.current_time = int(self.increment + self.current_time * self.multiplier) % self.modulus value = 0 value = self.current_time / self.modulus return value def lcg_to_range(self,min,max): # Generating random number in given range lcg = self.lcg() value = min + lcg * (max-min) return value if __name__ == "__main__": obj = RandomNumberGenerator() min_list = [] max_list = [] final_list = [] min_limit = int(input("Enter Lower value of range\n")) max_limit =int(input("Enter Upper value of range\n")) mid_val = (min_limit + max_limit) / 2 while len(max_list) != 73: val = int(obj.lcg_to_range(mid_val+1, max_limit+1)) max_list.append(val) continue while len(min_list) != 27: val = int(obj.lcg_to_range(min_limit,mid_val-1)) min_list.append(val) continue print("Number of values in max_list :" + str(len(max_list))) print(max_list) print("Number of values in min_list :" + str(len(min_list))) print(min_list) final_list = min_list+max_list print("Final list: ") print(final_list)
bda38c229c40236ea81b9e488d51f7af3cbf9f15
[ "Markdown", "Python" ]
2
Markdown
Akshu2596/codeforNash
20959f3c2363701c13995a5036374cda381740c6
c3b1e88ea7d6fc1b94623071671e144fdebb58af
refs/heads/master
<file_sep>cmake_minimum_required(VERSION 3.13.3) project(tictactoe) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_POSITION_INDEPENDENT_CODE ON) add_subdirectory(src) add_subdirectory(app) enable_testing() add_subdirectory(googletest) add_subdirectory(tests)<file_sep>Tic Tac Toe ----------- The well-known game, now in C++. (Yet another toy project) <file_sep>cmake_minimum_required(VERSION 3.13.3) set(This cmdtictactoe) set(Sources main.cpp ) add_executable(${This} ${Sources}) target_link_libraries(${This} PUBLIC tictactoe )<file_sep>cmake_minimum_required(VERSION 3.13.3) set(This ttictactoe) set(Sources tictactoe_test.cpp ) add_executable(${This} ${Sources}) target_link_libraries(${This} PUBLIC gtest_main tictactoe ) add_test( NAME ${This} COMMAND ${This} )<file_sep>#include "state.hpp" #include <cassert> using namespace tictactoe; State::State(bool cross_begins) : m_turn(cross_begins ? Symbol::CROSS : Symbol::CIRCLE), m_phase(Phase::RUNNING) {} Symbol State::getTurn() const { return m_turn; } Board const& State::getBoard() const { return m_board; } Phase State::getPhase() const { return m_phase; } bool State::update(Tile t) { if (m_phase != Phase::RUNNING) return false; auto symbol_at_t = m_board.getTileSymbol(t); if (!symbol_at_t) return false; if (*symbol_at_t != Symbol::EMPTY) return false; if (!m_board.setTileSymbol(t, m_turn)) assert(0); updatePhase(); nextTurn(); return true; } void State::nextTurn() { if (m_turn == Symbol::CIRCLE) m_turn = Symbol::CROSS; else m_turn = Symbol::CIRCLE; } void State::updatePhase() { static const Tile combinations[][3] = { { Tile::A0, Tile::A1, Tile::A2 }, { Tile::B0, Tile::B1, Tile::B2 }, { Tile::C0, Tile::C1, Tile::C2 }, { Tile::A0, Tile::B0, Tile::C0 }, { Tile::A1, Tile::B1, Tile::C1 }, { Tile::A2, Tile::B2, Tile::C2 }, { Tile::A0, Tile::B1, Tile::C2 }, { Tile::A2, Tile::B1, Tile::C0 } }; for (auto const& combination : combinations) { Symbol symbols[3]; for (int i = 0; i < 3; ++i) symbols[i] = *m_board.getTileSymbol(combination[i]); if (symbols[0] != Symbol::EMPTY && symbols[0] == symbols[1] && symbols[1] == symbols[2]) { m_phase = (symbols[0] == Symbol::CROSS) ? Phase::CROSS_WON : Phase::CIRCLE_WON; return; } } bool has_empty_tile = false; for (Tile t = First<Tile>; t < Tile::MAX; ++t) { if (*m_board.getTileSymbol(t) == Symbol::EMPTY) { has_empty_tile = true; break; } } if (!has_empty_tile) m_phase = Phase::CATS_GAME; }<file_sep>#include <optional> #include <cassert> #include <iostream> #include "state.hpp" using namespace std; using namespace tictactoe; void printTurn(Symbol s) { char c; switch (s) { case Symbol::CIRCLE: c = 'O'; break; case Symbol::CROSS: c = 'X'; break; default: assert(0); c = '?'; break; } cout << "Turn: " << c << endl; } void printBoard(Board const& b) { int cnt = 0; cout << " A B C\n0 "; for (Tile t = First<Tile>; t < Tile::MAX; ++t) { auto symbol_opt = b.getTileSymbol(t); assert(symbol_opt); auto symbol = *symbol_opt; char c; switch (symbol) { case Symbol::EMPTY: c = '_'; break; case Symbol::CIRCLE: c = 'O'; break; case Symbol::CROSS: c = 'X'; break; default: assert(0); c = '?'; break; } cout << c << " "; ++cnt; if (cnt % 3 == 0) cout << endl; if (cnt % 3 == 0 && cnt < 9) cout << (cnt / 3) << " "; } } optional<Tile> maybeGetTile() { char column; int column_idx; int line_idx; cout << "Tile = "; cin >> column >> line_idx; if (column >= 'a' && column <= 'c') column_idx = column - 'a'; else if (column >= 'A' && column <= 'C') column_idx = column - 'A'; else return nullopt; if (line_idx < 0 || line_idx > 2) return nullopt; int idx = column_idx + 3 * line_idx; return static_cast<Tile>(static_cast<int>(First<Tile>) + idx); } void printPhase(Phase ph) { string msg; switch (ph) { case Phase::RUNNING: msg = "Ongoing..."; break; case Phase::CIRCLE_WON: msg = "O won!"; break; case Phase::CROSS_WON: msg = "X won!"; break; case Phase::CATS_GAME: msg = "Cat's game..."; break; default: msg = "?"; assert(0); break; } cout << msg << endl; } optional<bool> maybeGetBool(const char* yes, const char* no) { cout << "* " << no << endl; cout << "* " << yes << endl; cout << ">>> "; string opt; cin >> opt; if (opt == yes) return true; else if (opt == no) return false; else return nullopt; } int main(int argc, char** argv) { cout << "Who begins?" << endl; auto crosses = maybeGetBool("X", "O"); while (!crosses) { cout << "Invalid input" << endl; crosses = maybeGetBool("X", "O"); } State s(*crosses); while (s.getPhase() == Phase::RUNNING) { cout << endl; printBoard(s.getBoard()); printTurn(s.getTurn()); auto tile = maybeGetTile(); while (!tile || !s.update(*tile)) { cout << "Invalid tile" << endl; tile = maybeGetTile(); } } printBoard(s.getBoard()); printPhase(s.getPhase()); return 0; }<file_sep>#ifndef TICTACTOE_STATE_H #define TICTACTOE_STATE_H #include "types.hpp" #include "board.hpp" namespace tictactoe { class State { Symbol m_turn; Board m_board; Phase m_phase; public: // Start with an empty board and // with one of the players beggining State(bool cross_begins); // Get turn (current player) Symbol getTurn() const; // Get constant reference to board Board const& getBoard() const; // Get current phase Phase getPhase() const; // Put current players' symbol in tile t // Returns true if successful bool update(Tile t); private: void updatePhase(); void nextTurn(); }; } #endif<file_sep>#include "board.hpp" #include <algorithm> using namespace tictactoe; using namespace std; Board::Board() { fill(m_matrix, m_matrix + size(m_matrix), Symbol::EMPTY); } optional<Symbol> Board::getTileSymbol(Tile t) const { auto idx_opt = getIndex(t); if (!idx_opt) return nullopt; return m_matrix[*idx_opt]; } bool Board::setTileSymbol(Tile t, Symbol s) { auto idx_opt = getIndex(t); if (!idx_opt) return false; m_matrix[*idx_opt] = s; return true; } optional<size_t> Board::getIndex(Tile t) { if (!TileCheck(t)) return nullopt; return static_cast<size_t>(t) - static_cast<size_t>(First<Tile>); }<file_sep>#ifndef TICTACTOE_BOARD_H #define TICTACTOE_BOARD_H #include "types.hpp" #include <optional> namespace tictactoe { class Board { Symbol m_matrix[9]; public: // Start with an empty board Board(); // Getter and setter std::optional<Symbol> getTileSymbol(Tile t) const; bool setTileSymbol(Tile t, Symbol s); private: static std::optional<size_t> getIndex(Tile t); }; } #endif<file_sep>#include <iostream> #include "board.hpp" #include "types.hpp" #include "state.hpp" #include <gtest/gtest.h> using namespace std; using namespace tictactoe; TEST(BoardTests, InitialState) { Board b; for (Tile t = First<Tile>; t < Tile::MAX; ++t) { auto symbol_opt = b.getTileSymbol(t); ASSERT_TRUE(symbol_opt) << "t=" << static_cast<int>(t); auto symbol = *symbol_opt; EXPECT_EQ(symbol, Symbol::EMPTY) << "t=" << static_cast<int>(t); } EXPECT_FALSE(b.getTileSymbol(Tile::MIN)); EXPECT_FALSE(b.getTileSymbol(Tile::MAX)); } TEST(BoardTests, SetAndGet) { Board b; b.setTileSymbol(Tile::A1, Symbol::CIRCLE); auto symbol_opt = b.getTileSymbol(Tile::A1); ASSERT_TRUE(symbol_opt); EXPECT_EQ(*symbol_opt, Symbol::CIRCLE); } TEST(TypeTests, TileCheck) { for (Tile t = First<Tile>; t < Tile::MAX; ++t) EXPECT_TRUE(TileCheck(t)); EXPECT_FALSE(TileCheck(Tile::MIN)); EXPECT_FALSE(TileCheck(Tile::MAX)); } TEST(TypeTests, SymbolCheck) { for (Symbol s = First<Symbol>; s < Symbol::MAX; ++s) EXPECT_TRUE(SymbolCheck(s)); EXPECT_FALSE(SymbolCheck(Symbol::MIN)); EXPECT_FALSE(SymbolCheck(Symbol::MAX)); } TEST(TypeTests, PhaseCheck) { for (Phase ph = First<Phase>; ph < Phase::MAX; ++ph) EXPECT_TRUE(PhaseCheck(ph)); EXPECT_FALSE(PhaseCheck(Phase::MIN)); EXPECT_FALSE(PhaseCheck(Phase::MAX)); } TEST(StateTests, InitialState) { auto cross_st = State(true); EXPECT_EQ(cross_st.getTurn(), Symbol::CROSS); EXPECT_EQ(cross_st.getPhase(), Phase::RUNNING); for (Tile t = First<Tile>; t < Tile::MAX; ++t) { auto symbol_opt = cross_st.getBoard().getTileSymbol(t); ASSERT_TRUE(symbol_opt) << "t=" << static_cast<int>(t); auto symbol = *symbol_opt; EXPECT_EQ(symbol, Symbol::EMPTY) << "t=" << static_cast<int>(t); } auto circle_st = State(false); EXPECT_EQ(circle_st.getTurn(), Symbol::CIRCLE); EXPECT_EQ(circle_st.getPhase(), Phase::RUNNING); for (Tile t = First<Tile>; t < Tile::MAX; ++t) { auto symbol_opt = circle_st.getBoard().getTileSymbol(t); ASSERT_TRUE(symbol_opt) << "t=" << static_cast<int>(t); auto symbol = *symbol_opt; EXPECT_EQ(symbol, Symbol::EMPTY) << "t=" << static_cast<int>(t); } } class GameSimulation { State st; public: GameSimulation(bool crosses_first) : st(crosses_first) {} State const& getState() const { return st; } State& getState() { return st; } void feedMoves(Tile const* begin, Tile const* end, bool expected) { for (Tile const* t = begin; t != end; ++t) { EXPECT_EQ(expected, st.update(*t)) << "Tile = " << static_cast<int>(*t) << endl << "Phase = " << static_cast<int>(st.getPhase()) << endl << "Turn = " << static_cast<int>(st.getTurn()); } } }; TEST(StateTests, CatsGame) { auto game = GameSimulation(true); static const Tile moves[] = { Tile::A0, Tile::C2, Tile::C0, Tile::B0, Tile::B1, Tile::A2, Tile::A1, Tile::C1, Tile::B2 }; game.feedMoves(moves, moves + size(moves), true); EXPECT_EQ(game.getState().getPhase(), Phase::CATS_GAME); } TEST(StateTests, CrossWon) { auto game = GameSimulation(true); static const Tile moves[] = { Tile::A0, Tile::B1, Tile::B0, Tile::A2, Tile::C0 }; game.feedMoves(moves, moves + size(moves), true); EXPECT_EQ(game.getState().getPhase(), Phase::CROSS_WON); } TEST(StateTests, CirclesWon) { auto game = GameSimulation(false); static const Tile moves[] = { Tile::A0, Tile::B1, Tile::B0, Tile::A2, Tile::C0 }; game.feedMoves(moves, moves + size(moves), true); EXPECT_EQ(game.getState().getPhase(), Phase::CIRCLE_WON); } TEST(StateTests, OverrideTile) { auto game = GameSimulation(true); static const Tile moves[] = { Tile::A0, // CROSS Tile::B1 // CIRCLE }; game.feedMoves(moves, moves + size(moves), true); EXPECT_EQ(game.getState().getPhase(), Phase::RUNNING); game.feedMoves(moves, moves + size(moves), false); EXPECT_EQ(game.getState().getPhase(), Phase::RUNNING); EXPECT_TRUE(game.getState().update(Tile::B0)); EXPECT_EQ(game.getState().getPhase(), Phase::RUNNING); } TEST(StateTests, AfterEnd) { auto game = GameSimulation(false); static const Tile moves[] = { Tile::A0, Tile::B1, Tile::B0, Tile::A2, Tile::C0 }; game.feedMoves(moves, moves + size(moves), true); EXPECT_FALSE(game.getState().update(Tile::C1)); // C1 is empty } TEST(StateTests, InvalidUpdateTile) { auto game = GameSimulation(true); static const Tile moves[] = { Tile::MIN, Tile::MAX }; game.feedMoves(moves, moves + size(moves), false); EXPECT_EQ(game.getState().getPhase(), Phase::RUNNING); }<file_sep>#ifndef TICTACTOE_TYPES_H #define TICTACTOE_TYPES_H #define CHECK_OPERATOR_ON(T) \ inline constexpr bool T ## Check(T t) \ { \ return (static_cast<int>(t) > static_cast<int>(T::MIN)) && \ (static_cast<int>(t) < static_cast<int>(T::MAX)); \ } #define FIRST_OPERATOR_ON(T) \ template<> \ constexpr T First<T> = static_cast<T>(static_cast<int>(T::MIN) + 1); #define ADD_OPERATOR_ON(T) \ inline constexpr T operator+(T t1, T t2) { \ return static_cast<T>(static_cast<int>(t1) + static_cast<int>(t2)); \ } \ inline constexpr T& operator+=(T& t1, T& t2) { \ return t1 = t1 + t2; \ } \ inline constexpr T& operator++(T& t) { \ return t = static_cast<T>(static_cast<int>(t) + 1); \ } namespace tictactoe { template<typename T> constexpr T First = T(); // // | | // A0 | B0 | C0 // _____|______|______ // | | // A1 | B1 | C1 // _____|______|______ // | | // A2 | B2 | C2 // | | // enum class Tile { MIN, A0, B0, C0, A1, B1, C1, A2, B2, C2, MAX, }; enum class Symbol { MIN, EMPTY, CROSS, CIRCLE, MAX }; enum class Phase { MIN, RUNNING, CROSS_WON, CIRCLE_WON, CATS_GAME, MAX, }; FIRST_OPERATOR_ON(Tile) FIRST_OPERATOR_ON(Symbol) FIRST_OPERATOR_ON(Phase) CHECK_OPERATOR_ON(Tile) CHECK_OPERATOR_ON(Symbol) CHECK_OPERATOR_ON(Phase) ADD_OPERATOR_ON(Tile) ADD_OPERATOR_ON(Symbol) ADD_OPERATOR_ON(Phase) } #undef CHECK_OPERATOR_ON #undef ADD_OPERATOR_ON #undef FIRST_OPERATOR_ON #endif
80b1bdca197048138846db6243075a0ad2512098
[ "Text", "CMake", "C++" ]
11
CMake
guidanoli/tictactoe
85924747eb84f5ce25e7221fa4e8330cb2c4936d
dfb26d838d2c93dbd6f33cc141b7cdc4b01d0078
refs/heads/master
<file_sep>""" ~ working with data in text files ~ A common thing to do with Python is to process data files. You can use the built-in `csv` module to work with delimited text. We'll open the files like this: - inside a `with` block -- notice the indentation on subsequent lines - in `r` ("read") mode - as some_variable that gives you a handle to the file object - with the newline argument set to a blank string Inside the with block, we'll create a `csv.reader` object and hand it the file object variable as an argument. You can then _iterate_ over the rows in the data file, with each row as a list of items in the row. """ import csv with open('../data/lotto.csv', 'r', newline='') as infile: reader = csv.reader(infile) for row in reader: county = row[0] retailer = row[1] address = row[2] city = row[3] date_claimed = row[4] game = row[5] amount = row[6] claimant_name = row[7] claimant_city = row[8] claimant_state = row[9] # print(city) """ You can also use a `csv.DictReader` object instead of a `csv.reader` object, which will treat each row as a dictionary instead of a list. The keys will be the items in the header row. I like using `csv.DictReader` better because it's easier to keep track of where everything is. """ with open('../data/lotto.csv', 'r', newline='') as infile: reader = csv.DictReader(infile) for row in reader: county = row['County'] retailer = row['Selling Retailer'] address = row['Business Address'] city = row['City'] date_claimed = row['Date Claimed'] game = row['Game'] amount = row['Prize Amount'] claimant_name = row["Primary Claimant's Name"] claimant_city = row["Claimant's City"] claimant_state = row['State'] # print(city) """ ~ use conditional logic to filter data ~ """ with open('../data/lotto.csv', 'r', newline='') as infile: reader = csv.DictReader(infile) for row in reader: county = row['County'] retailer = row['Selling Retailer'] address = row['Business Address'] city = row['City'] date_claimed = row['Date Claimed'] game = row['Game'] amount = row['Prize Amount'] claimant_name = row["Primary Claimant's Name"] claimant_city = row["Claimant's City"] claimant_state = row['State'] if city.strip() == 'KINGSTON': print(row) """ ~ writing to a CSV ~ Unsurprisingly, you can also write to a CSV (use 'w' mode). The `csv.writer` object's `writerow()` method expects a list; the `csv.DictWriter`'s method expects a dictionary. """ # write lists with open('test-writer.csv', 'w') as outfile: writer = csv.writer(outfile) headers = ['name', 'age', 'profession'] writer.writerow(headers) journos = [ ['Frank', 52, 'Reporter'], ['Sally', 37, 'Editor'], ['Pat', 41, 'Producer'] ] for journo in journos: writer.writerow(journo) # write dictionaries # notice that you have to specify the headers when you # create the `DictWriter` object -- you pass a list to # the `fieldnames` keyword argument -- and they have # to match exactly the keys in the dictionaries # of the rows you're writing out with open('test-dictwriter.csv', 'w') as outfile: headers = ['name', 'age', 'profession'] writer = csv.DictWriter(outfile, fieldnames=headers) writer.writeheader() journos = [ {'name': 'Frank', 'age': 52, 'profession': 'Reporter'}, {'name': 'Sally', 'age': 37, 'profession': 'Editor'}, {'name': 'Pat', 'age': 41, 'profession': 'Producer'} ] for journo in journos: writer.writerow(journo) """ EXERCISES: - Open the lotto.csv file and loop over the rows -- print only the records where the claimant's state is NY - Create a couple of rows of data -- anything, doesn't matter -- and write them out to a CSV file """ <file_sep>beautifulsoup4==4.6.0 bs4==0.0.1 geopy==1.11.0 requests==2.14.2 <file_sep>ire_2017_location = 'Phoenix, AZ' ire_2017_year = 2017 <file_sep># ire-2017-python-101 Slither your way to success! A low-key introduction to the Python programming language at the 2017 IRE Conference in Phoenix, Arizona. - **When:** Saturday (6/24) - **Where:** Pinnacle Peak 3 - **What:** You'll learn how to write and run a Python script, and you'll leave with a basic understanding of data types, useful tools, common use cases and some examples of how journalists are using programming to solve reporting problems. You'll also learn strategies for overcoming common obstacles for a beginning programmer. ## Afterward ### Get up and running with Python on your own computer If you're running Windows, [follow this tutorial by <NAME>](http://www.anthonydebarros.com/2015/08/16/setting-up-python-in-windows-10/). If you're running Mac or Linux, check out [this tutorial by <NAME>](http://docs.python-guide.org/en/latest/starting/install3/osx/). If you run into trouble, ask for help! (👇👇👇 _Keep reading_ 👇👇👇) ### Don't get discouraged! As you learn to code, you will get stuck. Many times. Don't get discouraged! **Learn to love error messages.** They can be scary at first, but error messages will show you what went wrong, on what line, with clues about how to fix it. If you're not sure what an error means, start by Googling it. **Find a newsroom project that Python can help you solve (rather than setting out to "learn Python").** Python is just a tool that you can use to achieve some journalistic end. Don't feel like you have to be a master before you can start writing scripts -- find a project and get cracking. **Break the problem into manageable chunks.** Take things one step at a time. Don't think about everything you need to do in order to get an Slack alert whenever a batch of new campaign finance data is posted that includes the governor's family. Think about what you need to do in order to fetch the page. Then think about what you need to do to parse the HTML. Then worry about writing a function to hit Slack. Etc. Sketching out your ideas on paper, in _pseudocode_, can be a good way to break things down. In other words, write out the things you want to accomplish informally, not worrying about syntax -- just get the ideas down on paper. Then come back and translate what you have into working code. **Ask for help.** There are many, many people in the journalism community who want to help you succeed. Here are just a handful of places where you can post Python questions and get help from working journalists: - [NICAR-L](https://www.ire.org/resource-center/listservs/subscribe-nicar-l/) - [Newsnerdery Slack](http://newsnerdery.org/) (check the #python channel) - [Lonely Coder's Club Slack](https://lcc-slack.herokuapp.com/) - [CAR Study Hall Slack](https://docs.google.com/forms/d/e/1FAIpQLSeI4othkRdgbCT0V2LRMeJklY1LfmUySkmnd0jNoWBfJswNUw/viewform) - [PythonJournos](https://github.com/PythonJournos/LearningPython/wiki) **... but Google your problem first.** It is _highly unlikely_ that you are the first person in history to encounter your problem. If you have an error message, Google it. If you are trying to remember "how to open a csv file in python," Google it. The ProPublica nerds have a [great post](https://www.propublica.org/nerds/item/how-to-ask-programming-questions) on question-asking strategies. **Find a coding buddy or mentor, or both.** It's nice to have somebody who's learning alongside you, and it's _extra_ nice to have a mentor who's willing to help you through the baby steps.<file_sep>""" ~ geocoding ~ You can use Python to geocode addresses in a data file. `geopy` is one library that will help you do this. It gives you several options for geocoing; we're going to use Google's geocoder. The steps: - create a new geocoder instance - open the data file - loop over the rows - inside the loop, construct an address to feed to the geocoder - geocode the address and print the lat/lng returned """ # import the Google geocoder from geopy # import Python's csv and time libaries from geopy.geocoders import GoogleV3 import csv import time # Make a geolocator object # Set the `timeout` keyword argument to 5 (seconds) geolocator = GoogleV3(timeout=5) # in a `with` block, open the file to read from and the file to write to with open('../data/payday.csv', 'r', newline='') as address_file: # make a DictReader object reader = csv.DictReader(address_file) # start for loop here for row in reader: # Put the address in a Google-recognizable string: ADDRESS, CITY, STATE ZIP addr = '{} {} {}, {}, {}'.format( row['STADDR'].strip(), row['STADDR2'].strip(), row['CITY'], row['STATE'], row['ZIP'] ) # Geocode that string location = geolocator.geocode(addr) # print the address and results print(addr, location.latitude, location.longitude) # Before we do all of this with the next row, pause for two seconds. time.sleep(2) # Alert us with a printed message when this completes and close both files. print('All done!')<file_sep>""" ~ post to an API ~ *** NOTE: If you are trying out this script at any point after the 2017 IRE conference in Phoenix, it will not work. You can adapt it to work with your _own_ slack team, tho. LMK if you get stuck. *** Let's post some data to an API. To make it interesting, let's post a message on Slack. To make it ~even more~ interesting, let's post a message to an IRE employee slack channel. And we'll do it in three! easy! steps! 1. Grab a string -- a secret "webhook" URL token that allows you to post data to our slack channel -- that your computer is helping keep track of for us. 2. Format your message data in a way that the Slack API will understand. 3. Send the message data to the webhook URL you grabbed in step 1. """ import os import requests import json # grab the webhook URL from your computer's environment # if it's not there, return None slack_webhook = os.environ.get('IRE_2017_SLACK_HOOK', None) # check to see if you have the URL if slack_webhook: # if you do, build a dictionary of payload data payload = { 'channel': '#ire-python-101-alerts', 'username': 'IRE Python Bot', 'icon_emoji': ':ire:', 'text': 'sup' } # turn it into a string of JSON payload_as_json = json.dumps(payload) # send it to slack! r = requests.post(slack_webhook, data=payload_as_json) else: # if you don't have it, print a message to the terminal print('You don\'t have the IRE_SLACK_WEBHOOK' ' environmental variable') """ EXERCISES: Read through the Slack documentation -- https://api.slack.com/incoming-webhooks -- and post a message to our Slack channel ... - with a different emoji - with an image URL instead of an emoji - with a link in it - with other kinds of fancy formatting """ <file_sep>""" ~ printing things~ Use the `print()` function to print things to your console """ print('hello') print('hello', 'IRE') print('hello' + ' IRE') print('i am', 32, 'years old') """ ~ assigning variables ~ Use = to assign values to variables for later use. """ my_name = 'Cody' print(my_name) my_age = 22 + 10 print(my_age) my_age_in_10_years = my_age + 10 print(my_age_in_10_years) """ ~ basic data types: strings ~ Anything sandwiched between two quotes -- single or double, doesn't matter as long as they match. """ a_string = 'hello, i am a string' another_string = "hello, i am another string" an_escaped_string = 'hello, i\'m a string with an escaped apostrophe' """ ~ basic data types: integers ~ A whole number. """ my_age = 32 my_age_10_years_ago = my_age - 10 """ ~ basic data types: floats ~ A number with a decimal. """ pct_of_whole = 45.6 """ ~ basic data types: booleans ~ True or False -- often used to test conditions. Always title case, never in quotes. """ my_boolean = True my_other_boolean = False """ ~ basic data types: lists ~ A collection of items inside square brackets. You can get the number of items in a list using the `len()` function. """ my_list = [1, 2, 3, 'hello', True, ['a', 'b', 'c']] my_list_count = len(my_list) print('There are', my_list_count, 'items in my list') # to access items, use bracket notation and the index number # counting in Python starts at zero, # so to get the first item in a list, use [0] first_item = my_list[0] print(first_item) """ ~ basic data types: dictionaries ~ Maps keys to values inside curly brackets. NOTE: Dictionaries don't keep track of order. """ my_dict = {'a': 1, 'b': 2, 'c': 3} # to access items in a dictionary, you can # use bracket notation and the key print(my_dict['a']) """ ~ type() ~ You can check the type of a thing with the `type()` function. """ print(type(43)) print(type(32.0)) print(type('True')) print(type(True)) print(type([1, 2, 3])) print(type({'a': 1, 'b': 2, 'c': 3})) """ ~ dir() ~ You can check the attributes and methods of a thing with the `dir()` function. """ print(dir(43)) print(dir(32.0)) print(dir('True')) print(dir(True)) print(dir([1, 2, 3])) print(dir({'a': 1, 'b': 2, 'c': 3})) """ ~ string methods: concatenating/formatting ~ A simple way to combine strings is `+`; a more advanced way that supports more data types is `format()`. https://pyformat.info/ """ my_string = 'Hello' + ' IRE!' my_other_string = '{} My name is <NAME>.'.format(my_string) print(my_other_string) """ ~ strip whitespace from strings ~ Use `strip()` to strip whitespace characters from either side of a string. """ my_ugly_string = ' hello ' my_pretty_string = my_ugly_string.strip() """ ~ join a list together into a string ~ Sometimes you want to join the string elements of a list together. """ month = '06' day = '11' year = '1985' date_list = [year, month, day] joined_date = '-'.join(date_list) print(joined_date) """ ~ `for` loop to iterate over a list ~ If you want to do something to each item in a list (or other kind of iterable), you can use a `for` loop. NOTE the indentation on subsequent lines. """ my_word_list = ['hello', 'IRE', 'how', 'are', 'you'] for word in my_word_list: print(word) """ ~ replace parts of strings ~ Use `replace()` to replace parts of a string with something else. (NOTE: You can chain string functions together.) """ string_1 = 'Wal-Mart Corp.' string_2 = 'Wal-Mart Corp., Inc.' string_3 = 'WalMart' string_1_clean = string_1.replace(' Corp.', '') \ .replace(', Inc.', '') \ .replace('WalMart', 'Wal-Mart') """ ~ conditional logic ~ Just like in Excel, you can use conditional logic (IF [something], DO [thing A], else IF [other thing], DO [thing B], etc.) NOTE the indentation on subsequent lines """ date_string_to_test = '2000-01-01' # slice out the year and use the `int()` function # to turn the string into an integer year = int(date_string_to_test[:4]) if year < 2000: print('old and busted') elif year == 2000: print('the start of a new millenium!') else: print('new hotness') """ ~ importing modules ~ You can import built-in Python libraries, third-party libraries and your own scripts """ import csv import requests import my_cool_vars as mcv print(mcv.ire_2017_location) print(mcv.ire_2017_year) """ EXERCISES: - Create a list of strings of ingredients for a salsa recipe and assign it to the variable `salsa_list` - Create a dictionary with the following key/value pairs and assign it to the variable `salsa_dict`: - 'recipe_name': a string that's the name of your salsa recipe - 'ingredients': whatever variable you saved your list of ingredients as - 'heat_level': an integer representing how hot your recipe is - perform a logical test to print out whether your recipe's heat level is above 10, under 10 or exactly 10 """ <file_sep>""" ~ scrape a website ~ We are going to scrape a simple web page. The steps: - Inspect the source of the page and note the pattern - Use `requests` to fetch the page - Use `BeautifulSoup` to parse the HTML into Python objects - Target the elements on the page with the data you want First, we're going to practice on an HTML file saved locally. """ from bs4 import BeautifulSoup with open('../practice-table.html', 'r') as html_file: html_code = html_file.read() soup = BeautifulSoup(html_code, 'html.parser') # find table by position on the page # find_all returns a list of matching elements, and we want the second ([1]) one # song_table = soup.find_all('table')[1] # by class name # => with `find`, you can pass in a dictionary of element attributes to match on # song_table = soup.find('table', {'class': 'song-table'}) # by ID # song_table = soup.find('table', {'id': 'my-cool-table'}) # by style song_table = soup.find('table', {'style': 'width: 95%;'}) # get table rows but skip the header row # more on list slicing: http://pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/ table_rows = song_table.find_all('tr')[1:] for row in table_rows: # get a list of cells in the row cols = row.find_all('td') # the track number is is in the first ([0]) "column" # the `.string` attribute gets the contents of a BeautifulSoup Tag object track_number = cols[0].string # the song title is in the second ([1]) "column" song_title = cols[1].string print(track_number + '.', song_title) """ Now let's scrape an actual page -- a table of certified lead burn instructors in Texas. """ import requests # define URL url = 'http://texasagriculture.gov/Portals/0/Reports/PIR/certified_lead_burn_instructors.html' # fetch it r = requests.get(url) # soup the text soup = BeautifulSoup(r.text, 'html.parser') # find the table table = soup.find('table', {'summary': 'CERTIFIED LEAD BURN INSTRUCTORS LIST'}) # find the rows, using slice to leave off # the header row rows = table.find_all('tr')[1:] # loop over the rows for row in rows: cols = row.find_all('td') name = cols[1].string.strip() addr = cols[2].string.strip() city = cols[3].string.strip() state = cols[4].string.strip() zip_code = cols[5].string.strip() phone = cols[6].string.strip() eff_date = cols[7].string.strip() print([name, addr, city, state, zip_code, phone, eff_date]) """ EXERCISE: - Filter the results so that you only print out the instructors from Austin - Instead of printing, write the results to a CSV """
b8331a1e2dfa0169532342c69f6cb218807b6c51
[ "Markdown", "Python", "Text" ]
8
Python
jasongrotto/ire-2017-python-101
3ceb70efeb802bac800f3a6cf20460197210d87a
1490bd13f717bdcce6a8368cc544d6930cfbd02c
refs/heads/master
<file_sep>import json import flask import numpy as np import pandas as pd import random from os import listdir, scandir from os.path import isfile, join app = flask.Flask(__name__) app.secret_key = "super secret key" app.config["DEBUG"] = True # Loading the data mypath = "./for_autoq" subfolders = [f.path for f in scandir(mypath) if f.is_dir() ] topic_dict = {} # get the names of the files in each folder for sub in subfolders: onlyfiles = [f for f in listdir(sub) if isfile(join(sub, f))] for file in onlyfiles: try: df = pd.read_json(str(sub+"/"+file)) for entry in range(0, len(df['data'])): topic_dict[df['data'][entry]['title']] = str(sub+"/"+file) except: continue topic_list = list(topic_dict.keys()) topic_list.sort() # home page for site @app.route('/', methods=['GET', 'POST']) def home(): flask.session['Correct'] = 0 flask.session['Incorrect'] = 0 flask.session['Blank'] = 0 flask.session['id_list'] = [] return flask.render_template("index.html") # home page for site @app.route('/topic_select', methods=['GET', 'POST']) def topic(): return flask.render_template("topic_select.html", topic_list = topic_list) @app.route('/about_us', methods=['GET']) def about_us(): return flask.render_template("about_us.html") @app.route('/our_project', methods=['GET']) def our_project(): return flask.render_template("our_project.html") @app.route('/article', methods=['GET', 'POST']) def api_article(): # when a particular topic has been selected if flask.request.method == 'POST': # Then get the data from the form title = flask.request.form['topic_select'] else: if flask.session.get('title', None) != None: title = flask.session.get('title') article_title = title.title() # STILL NEED TO ADD VALIDATION df_art = pd.read_json(topic_dict[title]) # determine the number in the json file for this article indicator = False topic = 0 while indicator == False: if df_art.data.iloc[topic]['title'] == title: indicator = True else: topic += 1 # create article context article = [] for paragraph in range(0, len(df_art.data.iloc[topic]['paragraphs'])): article.append(df_art.data.iloc[topic]['paragraphs'][paragraph]['context']) # cannot store entire article in the session variables because too large radio_buttons = ['answer_0', 'answer_1', 'answer_2', 'answer_3', 'answer_4'] id_list = flask.session.get("id_list") qs = {} q_achoices = {} q_correcta = {} answer_choices = ['Answer 1', 'Answer 2', 'Answer 3'] # stand-in for actual data for p in range(0, len(df_art['data'].iloc[topic]['paragraphs'])): if df_art['data'].iloc[topic]['paragraphs'][p]['qas'] != []: for q in range(0, len(df_art['data'].iloc[topic]['paragraphs'][p]['qas'])): if len(df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['distractors']) > 2: # if len(answer_choices) > 2: qs[df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['id']] = df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['question'] q_correcta[df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['id']] = df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['answers'][0]['text'] answer_choices = df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['distractors'] + [df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['answers'][0]['text']] # answer_choices = ['Answer 1', 'Answer 2', 'Answer 3'] # stand-in for actual data # answer_choices.append(df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['answers'][0]['text']) random.shuffle(answer_choices) q_achoices[df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['id']] = answer_choices # need to find 5 random questions # first figure out which questions are available avail_qs = list(set(qs.keys()) - set(id_list)) if len(avail_qs) >= 5: current_qs = random.sample(avail_qs, 5) else: current_qs = avail_qs id_list += current_qs # check to see which questions are still available if len(set(qs.keys()) - set(id_list)) > 0: more_qs = "yes" else: more_qs = "no" flask.session['questions'] = qs flask.session['id_list'] = id_list flask.session['current_qs'] = current_qs flask.session['topic'] = topic flask.session['article_title'] = article_title flask.session['title'] = title flask.session['q_correcta'] = q_correcta flask.session['more_qs'] = more_qs return flask.render_template("article.html", title = article_title, article = article, numbering = list(range(len(current_qs))), id_list = current_qs, questions = qs, q_achoices = q_achoices, radio_buttons = radio_buttons) # return flask.render_template("article.html", title = article_title, article = article) @app.route('/random', methods=['GET', 'POST']) def api_random(): # when a particular topic has been selected if flask.request.method == 'GET': # Then get the data from the form title = random.sample(topic_list, 1)[0] article_title = title.title() # STILL NEED TO ADD VALIDATION df_art = pd.read_json(topic_dict[title]) # determine the number in the json file for this article indicator = False topic = 0 while indicator == False: if df_art.data.iloc[topic]['title'] == title: indicator = True else: topic += 1 # create article context article = [] for paragraph in range(0, len(df_art.data.iloc[topic]['paragraphs'])): article.append(df_art.data.iloc[topic]['paragraphs'][paragraph]['context']) # cannot store entire article in the session variables because too large radio_buttons = ['answer_0', 'answer_1', 'answer_2', 'answer_3', 'answer_4'] id_list = flask.session.get("id_list") qs = {} q_achoices = {} q_correcta = {} answer_choices = ['Answer 1', 'Answer 2', 'Answer 3'] # stand-in for actual data for p in range(0, len(df_art['data'].iloc[topic]['paragraphs'])): if df_art['data'].iloc[topic]['paragraphs'][p]['qas'] != []: for q in range(0, len(df_art['data'].iloc[topic]['paragraphs'][p]['qas'])): if len(df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['distractors']) > 2: # if len(answer_choices) > 2: qs[df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['id']] = df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['question'] q_correcta[df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['id']] = df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['answers'][0]['text'] answer_choices = df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['distractors'] + [df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['answers'][0]['text']] # answer_choices = ['Answer 1', 'Answer 2', 'Answer 3'] # stand-in for actual data # answer_choices.append(df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['answers'][0]['text']) random.shuffle(answer_choices) q_achoices[df_art['data'].iloc[topic]['paragraphs'][p]['qas'][q]['id']] = answer_choices # need to find 5 random questions avail_qs = list(set(qs.keys()) - set(id_list)) if len(avail_qs) >= 5: current_qs = random.sample(avail_qs, 5) else: current_qs = avail_qs id_list += current_qs if len(set(list(qs.keys())) - set(id_list)) > 0: more_qs = "yes" else: more_qs = "no" flask.session['questions'] = qs flask.session['id_list'] = id_list flask.session['current_qs'] = current_qs flask.session['topic'] = topic flask.session['article_title'] = article_title flask.session['title'] = title flask.session['q_correcta'] = q_correcta flask.session['more_qs'] = more_qs return flask.render_template("article.html", title = article_title, article = article, numbering = list(range(len(qs))), id_list = current_qs, questions = qs, q_achoices = q_achoices, radio_buttons = radio_buttons) @app.route('/check_answers', methods=['GET', 'POST']) def api_grade(): article_title = flask.session.get('article_title', None) title = flask.session.get('title', None) # import list of questions and answers current_qs = flask.session.get('current_qs', None) q_questions = flask.session.get('questions', None) q_correcta = flask.session.get('q_correcta', None) # Then need to recreate the article - cannot pass through session data because too large df_art = pd.read_json(topic_dict[title]) # determine the number in the json file for this article indicator = False topic = 0 while indicator == False: if df_art.data.iloc[topic]['title'] == title: indicator = True else: topic += 1 # create article context article = [] for paragraph in range(0, len(df_art.data.iloc[topic]['paragraphs'])): article.append(df_art.data.iloc[topic]['paragraphs'][paragraph]['context']) # Bring in users answers numbering = list(range(len(current_qs))) user_answers = {} radio_buttons = {} for q in numbering: a_num = "answer_"+str(q) try: answer = flask.request.form[a_num] except: answer = "Not Answered" user_answers[current_qs[q]] = answer radio_buttons[current_qs[q]] = "q_" + str(q) # check if user answer is correct correct = {} if flask.session.get("Correct", None) == None: num_corr = 0 else: num_corr = flask.session.get("Correct") if flask.session.get("Incorrect", None) == None: num_wrong = 0 else: num_wrong = flask.session.get("Incorrect") if flask.session.get("Blank", None) == None: num_blank = 0 else: num_blank = flask.session.get("Blank") answer_color = {} for q in current_qs: if (user_answers[q] == q_correcta[q]): correct[q] = "Correct" answer_color[q] = "correct" num_corr += 1 elif user_answers[q] == "Not Answered": correct[q] = "Not Answered" answer_color[q] = "blank" num_blank += 1 else: correct[q] = "Incorrect" answer_color[q] = "incorrect" num_wrong += 1 if flask.session['more_qs'] == "yes": render = "check_answers.html" else: render = "check_no_more_qs.html" flask.session['Correct'] = num_corr flask.session['Incorrect'] = num_wrong flask.session['Blank'] = num_blank return flask.render_template(render, article = article, answers = user_answers, title = article_title, questions = current_qs, q_list = q_questions, numbering = numbering, correct = correct, answer_color = answer_color, correct_answers = q_correcta, radio_buttons = radio_buttons) # return flask.render_template("check_answers.html", article = article) @app.route('/score', methods=['GET', 'POST']) def api_score(): num_corr = flask.session.get("Correct", None) num_wrong = flask.session.get("Incorrect", None) num_blank = flask.session.get("Blank", None) radio_buttons = ['q_0', 'q_1', 'q_2', 'q_3', 'q_4'] bad_qs = [] for a in radio_buttons: try: bad_q = flask.request.form[a] bad_qs.append(bad_q) except: # bad_qs.append("WHY") continue flask.session['Bad_q'] = bad_qs return flask.render_template("score_card.html", num_corr = num_corr, num_wrong = num_wrong, num_blank = num_blank) @app.route('/feedback', methods=['GET', 'POST']) def api_feedback(): bad_qs = flask.session.get("Bad_q", "Nothing here") return flask.render_template("feedback.html", bad_qs = bad_qs) if __name__ == '__main__': app.run() <file_sep>Flask==1.0.2 gunicorn==19.4.5 itsdangerous==0.24 Jinja2==2.10 MarkupSafe==1.0 Werkzeug==0.14.1 numpy==1.15.1 pandas==0.23.4 <file_sep># AutoQ: Improving reading comprehension through automatic question generation Repository for Question Generation project, W210 Capstone for UCB MIDS. <NAME>, <NAME>, <NAME>, <NAME> ## About Our Project AutoQ is the first free web app with automatically generated reading comprehension questions targeted to English language learners. Our product utilizes state of the art machine learning and natural language processing techniques to create a vast and topical collection of multiple-choice questions that mimic English-language exam formats. We currently offer over 100,000 practice questions on over 10,000 Wikipedia articles. [Our site](https://autoq-2019.herokuapp.com/) is designed to help improve reading comprehension for English-language learners or for anyone looking to study up on a new topic. Starting with the articles from Wikipedia, we have developed algorithms to produce reading comprehension questions designed to mimic the style of questions seen on the TOEFL exam. Improving reading comprehension is achieved from practice on new material. ## Do it Yourself We employed several techniques to achieve this result. The below instructions walk through our approach. Input and output folders can be updated from within the scripts. ### 1. Preprocess Wikipedia articles Raw text to Wikipedia articles was obtained from [Wikimedia dumps](https://dumps.wikimedia.org/). For the rest of the pipeline, it shoudl be formatted the same was as SQuAD datasets. From this directory, run the preprocessing script to break up the Wikipedia articles into paragraphs and save them into the `wikipedia_squad` folder. ``` sh preprocess.sh``` ### 2. Select relevant sentences to query Using the paragraphs from the Wikipedia articles, we identify the most “important” sentences to ask questions about. In general, the first and last sentences of each paragraphs often introduce key information or summarize information in the paragraph, so we examine those. We assume that words that appear most frequently are most important (and likely good indicators of the main topic), and therefore the most “important” sentences contain these frequent words. From this directory, run the sentence selection script to select important sentences and save them, labeled with their location (in `labeled_sentences`) and unlabled for question generation (in `unlabeled_sentences`). ``` sh sentence_selection.sh``` ### 3. Question Generation We then feed these important sentences into our Question Generation model, an attention-based bidirectional LSTM, inspired by Du et al.'s 2017 paper, [Learning to Ask: Neural Question Generation for Reading Comprehension](https://arxiv.org/abs/1705.00106). We implement it using Torch on top of the [Open Neural Machine Translation](http://opennmt.net/) framework. Our approach is adapted from [GenerationQ](https://github.com/drewserles/GenerationQ). From this directory, run the question generation script to generate questions for the important sentences, save them in the `questions` folder, and add them back to the SQuAD-formatted Wikipedia articles (done with a call to `add_questions.py`, overwriting the files in `wikipedia_squad`). ``` sh question_generation.sh``` ### 3. Question Answering To make these questions useful as a tool for reading comprehension, we must also generate their answers, so users can compare their results. We generate these also with a bidirectional LSTM, which we chose for its relative simplictiy and competitive performance on our validation set. Our implementation was modelled after part of Facebook’s 2017 paper [Reading Wikipedia to Answer Open-Domain Questions](https://arxiv.org/abs/1704.00051), and [implemented via PyTorch](https://github.com/facebookresearch/DrQA). From this directory, run the question answering script to generate answers to our questions, save them in the `answers` folder, and add them back to the SQuAD-formatted Wikipedia articles (done with a call to `add_answers.py`, saving the files in `wikipedia_squad_w_answers`). ``` sh question_answering.sh``` <file_sep><!doctype html> <title>Reading Comprehension Automatic Question Generation</title> <link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}"> <h1>AutoQ<br> <img src = "{{url_for('static', filename='white-transparent_background.svg')}}" alt = "no logo" style="width:128px;height:128px;"></h1> <div class = "tagline"> <h2>Improving reading comprehension through automatic question generation</h2> </div> <div class=page> <p>You can select a passage from our data set and you will be given a reading comprehension question to go with it.</p> <p>You can select a specific topic from our data set:</p> <form name = "topic_select" action = "/article", method='post'> <select name = "topic_select"> <option value=" "></option> {% for o in topic_list %} <option value="{{ o }}">{{ o }}</option> {% endfor %} </select> <input type="submit" value="Go to this article" /> </form> <br> <p>Or, you can let us choose a random topic for you:</p> <form name = "random_select" action = "/random" /> <input type="submit" value = "Go to a random article" method = "get"/> </form> </div> <br> <div class = "home_page"> <form name = "home_page" action = "/" /> <input type="submit" value = "Back to home page" method = "get"/> </form> </div> <file_sep>#!/usr/bin/env python3 import json import itertools import ast import argparse import os import pandas as pd from collections import defaultdict import nltk import string import operator import math import re ################################################# # # Begin processing # Three steps to this. # ################################################# def sents_and_weights(d,paragraphs): """Clean sentences, remove digit, punctuation, upper case to lower Args: d,paragraphs = d is article number within file, paragraphs is just paragraphs Return: labeled sentences: stemmed sentences: word distribution: """ # Create dictionaries for labeled & stemmed sentences to populate labeled_sentences = {} stemmed_sentences = {} # Create word distribution dictionaries # these needs to be a default dict so it returns 0 if word not found word_cts = defaultdict(int) word_distr = defaultdict(int) # initialize for stemming stop_words = nltk.corpus.stopwords.words('english') stemmer = nltk.stem.PorterStemmer() tokenize = nltk.word_tokenize sent_splitter = nltk.data.load('tokenizers/punkt/english.pickle') # helper function for tracking stemmed words def stem_and_add(wd): word_cts[wd] += 1 word_cts['total_count'] += 1 return stemmer.stem(wd) # need to go through each 'paragraph' (context) to gather info about sentences for i,context in enumerate(paragraphs): paragraph = context['context'] # split paragraph into sentences, make sure to keep digits, etc. together #sentences = context['context'].split('. ') #last one still has a period at the end #print(len(paragraph)) if len(paragraph) > 75: sentences = sent_splitter.tokenize(context['context'].strip()) else: break # iterate through sentences to tokenize, calculate overall word distribution for j,original_sentence in enumerate(sentences): # Remove all digits sentence = ''.join([x for x in original_sentence if not x.isdigit()]) # Remove all punctuation (OK to include periods since it's been split) sentence = ''.join([x for x in sentence if x not in string.punctuation]) # Lowercase everything sentence = sentence.strip() sentence = sentence.lower() # Split into words & rejoin (remove extra spaces) sentence = ' '.join(sentence.split()) tokenized_stemmed_sent = [stem_and_add(word) for word in nltk.tokenize.word_tokenize(sentence) if not word in stop_words] # keep track of tokenized for calculating sentence weight in next step # save list of unprocessed sentences for later # but we're only selecting from the first and last sentences in the paragraphs if (original_sentence == sentences[0]) | (original_sentence == sentences[-1]): if not original_sentence.startswith('[[File:'): labeled_sentences[(d,i,j)] = original_sentence.replace('\n', ' ') stemmed_sentences[(d,i,j)] = tokenized_stemmed_sent # update our word dictionary to be relative frequencies rather than absolute values for word, ct in word_cts.items(): # but keep our total count, we may want that later (not sure) if not word == 'total_count': word_distr[word] = word_cts[word] / word_cts['total_count'] #print(sorted(word_distr.items(), key=lambda k: k[1], reverse=True)) return labeled_sentences,stemmed_sentences,word_distr def calc_sent_weight(word_dist, stemmed_sents): """Compute weight with respect to sentences Args: word_distribution: dict with word: weight stemmed_sents: list with Return: sentence_weight: dict of weight of each sentence. key = sentence #, value = weight """ sentences_weight = {} # Iterate through each word in each sentence, if word distribution and sentence id are in dictionary, # add to existing word distribution. Else, sentence weight for given sentence equals current word distribution for key, words in stemmed_sents.items(): #print(words) # Sentence weight equals sum of word distributions divided by length of cleaned sentence if len(words) == 0: weight = 0 else: weight = sum([word_dist[word] for word in words]) / len(words) sentences_weight[key] = weight sentences_weight = sorted(sentences_weight.items(), key=operator.itemgetter(1), reverse=True) #print('sentence weight: ',sentences_weight) return sentences_weight def topically_important_sentence(sentences_weight, labeled_sentences): """Select topically import sentences Args: sentence_weight: list of tuples, (sentence_num, sentence_weight) computed in sentence_weight paragraph: set of sentences Return: sentences_selected: dict, topically important sentences selected """ final_sentences = {} total_sentences = len(sentences_weight) # how many sentences to retain num_sentences_selected = math.ceil(float(0.20) * total_sentences) # key of selected sentences (# order of sentence in paragraph) #sentences_selected_key = [] # dictionary of all sentences sentences_dict = {} flag = 0 # select num_sentences_selected # of sentences from list of sentence weights selected_keys = [k for k,v in sentence_weight[0:num_sentences_selected]] for sent_key in selected_keys: pre_processed_sentence = labeled_sentences[sent_key] processed_sentence = pre_processed_sentence.lower() #lowercase processed_sentence = processed_sentence.replace('[[','') # remove brackets indicating links processed_sentence = processed_sentence.replace(']]','') processed_sentence = processed_sentence.replace(']','') processed_sentence = processed_sentence.replace('[','') processed_sentence = re.sub('(?<!\d)([.,!?()])(?<!\d)', r' \1 ', processed_sentence) processed_sentence = re.sub(r'\(','-lrb- ',processed_sentence) # replace left parens, add space after processed_sentence = re.sub(r'\)',' -rrb-',processed_sentence) # replace left parens, add space after processed_sentence = re.sub(r'\([^)]*\)', '',processed_sentence) #replace brackets in links processed_sentence = re.sub('(?<=\s)\"','`` ',processed_sentence) # replace first double quotes with `` processed_sentence = re.sub(r'\"', " ''", processed_sentence) # replace second double quote with two single quotes '' final_sentences[sent_key] = processed_sentence return final_sentences if __name__ == "__main__": parser = argparse.ArgumentParser( description='setence_selection.py') parser.add_argument('--input-dir', type=str, default='./wikipedia_data/wikipedia_squad', help=('Directory to read original squad-formatted file from.'), required=True) parser.add_argument('--out-dir-labeled', type=str, default='./wikipedia_data/labeled_sentences', help=('Directory to read original squad-formatted file from.'), required=True) parser.add_argument('--out-dir-unlabeled', type=str, default='./wikipedia_data/unlabeled_sentences', help=('Directory to read original squad-formatted file from.'), required=True) args = parser.parse_args() wiki_squad = args.input_dir labeled_sents = args.out_dir_labeled unlabeled_sents = args.out_dir_unlabeled total_skipped = 0 total_selected = 0 for foldername in os.listdir(wiki_squad): input_subfolder = wiki_squad + foldername output_subfolder_labeled = labeled_sents + foldername output_subfolder_unlabeled = unlabeled_sents + foldername if not os.path.exists(output_subfolder_labeled): os.mkdir(output_subfolder_labeled) if not os.path.exists(output_subfolder_unlabeled): os.mkdir(output_subfolder_unlabeled) # these are not files, just folders print("Selecting topical sentences for files in {} folder...".format(foldername)) num_skipped = 0 num_selected = 0 # each file represents several (variable #) wikipedia articles for filename in os.listdir(input_subfolder): input_file = input_subfolder + '/' + filename # save these to different directories of labeled and unlabeled sentences output_file_labeled = open(output_subfolder_labeled + '/' + filename, "w") output_file_unlabeled = open(output_subfolder_unlabeled + '/' + filename, "w") with open(input_file) as json_file: data = json.load(json_file) data = pd.DataFrame.from_dict(data) df = data['data'] # for each article in the file for row,value in df.iteritems(): try: # here is where we clean and stem words, build word distribution labeled_sentences, stemmed_sentences, word_distribution = sents_and_weights(row,value['paragraphs']) # use this word distribution to get weights for each sentence and calculate most important sentences sentence_weight = calc_sent_weight(word_distribution,stemmed_sentences) # pull out most important sentences # and keep track of where they came from: (doc #, context #, sentence #) chosen_sentences = topically_important_sentence(sentence_weight,labeled_sentences) except: num_skipped += 1 print("Skipping article:",value['title']) else: num_selected += 1 for sents in chosen_sentences.items(): #save selected sentences directly to file, for onmt model output_file_unlabeled.write(str(sents[1])+'\n') # keep track of their locations, though output_file_labeled.write(str(sents)+'\n') total_skipped += num_skipped total_selected += num_selected print("Completing files in {} folder... {} articles processed, {} articles skipped.\n".format(foldername,num_selected,num_skipped)) print("Sentence selection complete. Total {} articles processed, {} skipped for question generation.".format(total_selected, total_skipped)) <file_sep>def enc_dec_model_inputs(): inputs = tf.placeholder(tf.int32, [None, None], name='input') targets = tf.placeholder(tf.int32, [None, None], name='targets') target_sequence_length = tf.placeholder(tf.int32, [None], name='target_sequence_length') max_target_len = tf.reduce_max(target_sequence_length) return inputs, targets, target_sequence_length, max_target_len<file_sep>def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, max_target_sequence_length, vocab_size, output_layer, batch_size, keep_prob): """ Create a inference process in decoding layer :return: BasicDecoderOutput containing inference logits and sample_id """ dec_cell = tf.contrib.rnn.DropoutWrapper(dec_cell, output_keep_prob=keep_prob) helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(dec_embeddings, tf.fill([batch_size], start_of_sequence_id), end_of_sequence_id) decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell, helper, encoder_state, output_layer) outputs, _, _ = tf.contrib.seq2seq.dynamic_decode(decoder, impute_finished=True, maximum_iterations=max_target_sequence_length) return outputs<file_sep>--- title: "Inter-Rater Agreement" output: html_notebook --- Inter-rater reliability: http://www.cookbook-r.com/Statistical_analysis/Inter-rater_reliability/ https://dkpro.github.io/dkpro-statistics/inter-rater-agreement-tutorial.pdf https://www.statisticshowto.datasciencecentral.com/inter-rater-reliability/ ```{r} library(irr) clarity <- read.csv('/Users/joannahuang/Downloads/Clarity_Eval.csv') fluency <- read.csv('/Users/joannahuang/Downloads/fluency.csv') grammaticality <- read.csv('/Users/joannahuang/Downloads/grammaticality.csv') answer_existence <- read.csv('/Users/joannahuang/Downloads/answer_existence.csv') ``` ```{r} head(answer_existence) ``` ```{r} prep_clarity = clarity[-c(1,2, 203),] prep_fluency = fluency[-c(1,2, 203),] prep_gram = grammaticality[-c(1,2, 203),] prep_answer = answer_existence[-c(1,2, 203),] rownames(prep_clarity) <- prep_clarity$SUM.of.Clarity rownames(prep_fluency) <- prep_fluency$SUM.of.Fluency rownames(prep_gram) <- prep_gram$SUM.of.Grammatical_Num rownames(prep_answer) <- prep_answer$SUM.of.Present_Num prep_clarity = subset(prep_clarity, select = -c(SUM.of.Clarity,WorkerId,X.38)) prep_fluency = subset(prep_fluency, select = -c(SUM.of.Fluency,WorkerId,X.38)) prep_gram = subset(prep_gram, select = -c(SUM.of.Grammatical_Num,WorkerId,X.38)) prep_answer = subset(prep_answer, select = -c(SUM.of.Present_Num,WorkerId,X.38)) head(prep_answer) #write.csv(prep, file = "processed_clarity.csv") ``` ```{r} # The basic idea is to consider each pairwise agreement of raters # and average over all items i kappam.fleiss(prep_clarity, detail=TRUE) kappam.fleiss(prep_fluency, detail=TRUE) kappam.fleiss(prep_gram, detail=TRUE) kappam.fleiss(prep_answer, detail=TRUE) ``` Potential reason for low Kappa: In short, a lack of heterogeneity produces a high estimate of chance agreement given the kappa coefficient's assumptions. This, in turn, produces a lower kappa score. https://stats.stackexchange.com/questions/153225/why-does-fleisss-kappa-decrease-with-increased-response-homogeneity <file_sep>#!/usr/bin/env python3 """A script to re-format dumped Wikipedia in the format that SQuAD uses, for future processing and display.""" import json import itertools import ast import argparse import os parser = argparse.ArgumentParser() parser.add_argument('--input-dir', type=str, default='/tmp', help=('Directory to read original Wikipedia file from.'), required=True) parser.add_argument('--out-dir', type=str, default='/tmp', help=('Directory to write squad-formatted file to ' '(wiki_XX.json)'), required=True) args = parser.parse_args() wiki_dump = args.input_dir wiki_squad = args.out_dir ################################################# # # Begin processing # ################################################# # iterate through dump of wikipedia articles total_articles = 0 total_skipped = 0 for foldername in os.listdir(wiki_dump): input_subfolder = wiki_dump + foldername output_subfolder = wiki_squad + foldername if not os.path.exists(output_subfolder): os.mkdir(output_subfolder) # these are not files, just folders print("Processing files in {} folder...".format(foldername)) num_articles = 0 num_skipped = 0 # each file represents several (variable #) wikipedia articles for filename in os.listdir(input_subfolder): if not filename.startswith('.'): f = open(input_subfolder + '/' + filename) # each file of articles will become a separate .json of articles # this helps if we run into issues, we can just discard a whole file and move on # set up json format for squad-like listing of articles wikipedia_data_dict = {"data": [], "version" : 1.0} # save this to the 'wikipedia_squad' folder of correctly-formatted dicts of wikipedia articles output_file = output_subfolder + '/' + filename # each line represents a different wikipedia article # we will ignore the id and url for now, not needed for line in f: line_dict = ast.literal_eval(line) title = line_dict['title'] # for some reason, empty articles are included. They should be disregarded try: text = line_dict['text'].split("\n\n",1)[1] # title is duplicated within text as well except: num_skipped += 1 print("Skipping article:",title) else: # arbitrary length, should eliminate articles like "disambiguation" articles, etc. if len(text) > 1000: num_articles += 1 # Break text up into paragraphs paras = text.split("\n\n") context = [{'context': para.rstrip(), 'qas' : []} for para in paras] wikipedia_data_dict['data'].append({'title' : title, 'paragraphs' : context}) # in case we don't have any articles in the file to add if (wikipedia_data_dict['data']): with open(output_file, 'w') as outfile: json.dump(wikipedia_data_dict, outfile) total_articles += num_articles total_skipped += num_skipped print("Completing files in {} folder... {} articles processed, {} skipped.\n".format(foldername,num_articles,num_skipped)) print("Reformatting complete. Total {} articles processed for question generation, {} skipped.".format(total_articles,total_skipped))<file_sep>def seq2seq_model(input_data, target_data, keep_prob, batch_size, target_sequence_length, max_target_sentence_length, source_vocab_size, target_vocab_size, enc_embedding_size, dec_embedding_size, rnn_size, num_layers, target_vocab_to_int): """ Build the Sequence-to-Sequence model :return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput) """ enc_outputs, enc_states = encoding_layer(input_data, rnn_size, num_layers, keep_prob, source_vocab_size, enc_embedding_size) dec_input = process_decoder_input(target_data, target_vocab_to_int, batch_size) train_output, infer_output = decoding_layer(dec_input, enc_states, target_sequence_length, max_target_sentence_length, rnn_size, num_layers, target_vocab_to_int, target_vocab_size, batch_size, keep_prob, dec_embedding_size) return train_output, infer_output<file_sep>MCTest Dataset ======== Baseline models as well as more complex ones for doing question answering on the MCTest dataset. Dependencies: ``` protobuf numpy pandas nltk ``` Word embeddings can be used from a model file created by [word2vec](https://github.com/danielfrg/word2vec). ## Running baseline models First, clone the repo and compile the protobuf: ``` git clone https://github.com/mcobzarenco/mctest.git cd mctest protoc --python_out=. mctest.proto ``` To parse the raw data (dev + train combined), remove stopwords and save it as a length delimted protobuf flat file: ``` cat data/MCTest/mc160.dev.tsv data/MCTest/mc160.train.tsv | \ ./parse.py --rm-stop data/stopwords.txt -o proto > train160-stop.words ``` Also create a file with the ground truth for dev + train: ``` cat data/MCTest/mc160.dev.ans data/MCTest/mc160.train.ans > train160.ans ``` To run the sliding window with distance baseline: ``` ./baseline.py --train train160-stop.words --truth train160.ans --distance [model] window_size = None distance = True [results] All accuracy [400]: 0.5600 Single accuracy [185]: 0.5946 Multiple accuracy [215]: 0.5302 ``` #### Word embeddings First, [word2vec](https://github.com/danielfrg/word2vec) should be installed and a model file with embeddings created. Say the model file is `mctest.vec.bin`, the following command will parse the raw data (dev + train combined), replace the words with their corresponding embedding and save that to disk: ``` cat data/MCTest/mc160.dev.tsv data/MCTest/mc160.train.tsv | \ ./parse.py --model-file mctest.vec.bin --rm-punct -o proto > train160-punct-mctest.embed ``` To run the sliding window model over the embeddings: ``` ./baseline-embed.py --train train160-punct-mctest.embed --truth train160.ans [model] window_size = None All accuracy [400]: 0.5775 Single accuracy [185]: 0.6108 Multiple accuracy [215]: 0.5488 ``` <file_sep># Testing TF NMT model as a baseline 1. Visit and clone: `git clone https://github.com/tensorflow/nmt` 2. Make sure you have the correct version of tensorflow installed for the version you'd like to clone: 1. Use `git checkout -b [branch-name]` to navigate between branches as needed 2. Potential branches are `tf-1.2` and `tf-1.4` 3. Follow the instructions at `https://github.com/tensorflow/nmt/tree/master#hands-on--lets-train-an-nmt-model` to run the demo (instructions repeated here). It'll download files and run the model. Let's train our very first NMT model, translating from Vietnamese to English! The entry point of our code is nmt.py. We will use a small-scale parallel corpus of TED talks (133K training examples) for this exercise. All data we used here can be found at: https://nlp.stanford.edu/projects/nmt/. We will use tst2012 as our dev dataset, and tst2013 as our test dataset. Run the following command to download the data for training NMT model: ```nmt/scripts/download_iwslt15.sh /tmp/nmt_data``` Run the following command to start the training: ```mkdir /tmp/nmt_model python -m nmt.nmt \ --src=vi --tgt=en \ --vocab_prefix=/tmp/nmt_data/vocab \ --train_prefix=/tmp/nmt_data/train \ --dev_prefix=/tmp/nmt_data/tst2012 \ --test_prefix=/tmp/nmt_data/tst2013 \ --out_dir=/tmp/nmt_model \ --num_train_steps=12000 \ --steps_per_stats=100 \ --num_layers=2 \ --num_units=128 \ --dropout=0.2 \ --metrics=bleu ``` 4. If that works, use the data files found in `baseline/data` to run (from the top directory in the `nmt` repo!!) it on our own text: ```mkdir [PATH_TO_W210_REPO]/baseline/model/ python -m nmt.nmt \ --src=para --tgt=ques \ --vocab_prefix=[PATH_TO_W210_REPO]/baseline/data/vocab \ --train_prefix=[PATH_TO_W210_REPO]/baseline/data/train \ --dev_prefix=[PATH_TO_W210_REPO]/baseline/data/dev \ --test_prefix=[PATH_TO_W210_REPO]/baseline/data/test \ --out_dir=[PATH_TO_W210_REPO]/baseline/model/ \ --num_train_steps=16000 \ --steps_per_stats=500 \ --num_layers=2 \ --num_units=600 \ --dropout=0.3 \ --metrics=bleu ``` <file_sep>python wrong_answer_gen.py \ --input-dir wikipedia_data/wikipedia_squad/ \ # update as necessary! --input-dir wikipedia_data/for_autoq/ # update as necessary!<file_sep>def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, target_sequence_length, max_summary_length, output_layer, keep_prob): """ Create a training process in decoding layer :return: BasicDecoderOutput containing training logits and sample_id """ dec_cell = tf.contrib.rnn.DropoutWrapper(dec_cell, output_keep_prob=keep_prob) # for only input layer helper = tf.contrib.seq2seq.TrainingHelper(dec_embed_input, target_sequence_length) decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell, helper, encoder_state, output_layer) # unrolling the decoder layer outputs, _, _ = tf.contrib.seq2seq.dynamic_decode(decoder, impute_finished=True, maximum_iterations=max_summary_length) return outputs<file_sep>from collections import Counter from nltk.corpus import stopwords from nltk.tokenize import word_tokenize import string from collections import defaultdict stop_words = set(stopwords.words('english')) punc = set(string.punctuation) # Files from GenerationQ with open(‘src-train.txt', 'r') as i: input = i.read() with open(‘tgt-train.txt', 'r') as o: output = o.read() # Get top 45k most frequent tokens from src-train # Preprocessing: remove digits, stopwords (according to nltk), punctuation, and lowercase wordcount = defaultdict(int) for line in input.split(‘\n’): line = ''.join([x for x in line if not x.isdigit()]) line = ''.join([x for x in line if x not in punc]) line = ‘’.join([x.lower() for x in line]) for word in word_tokenize(line): if word not in stop_words: if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 # write to input_45k file counter_obj = Counter(wordcount) file = open('input_45k.txt',"w") for word,count in counter_obj.most_common(n=45000): file.write(word+'\n') # Get top 28k most frequent tokens from tgt-train # Preprocessing: remove digits, stopwords (according to nltk), punctuation, and lowercase wordcount_output = defaultdict(int) for line in output.split(‘\n’): line = ''.join([x for x in line if not x.isdigit()]) line = ''.join([x for x in line if x not in punc]) line = ‘’.join([x.lower() for x in line]) for w in word_tokenize(line): if word not in stop_words: if w not in wordcount_output: wordcount_output[w] = 1 else: wordcount_output[w] += 1 # write to output_28k file counter_obj_output = Counter(wordcount_output) file_ouput = open(‘output_28k’,”w”) for word,count in counter_obj_output.most_common(n=28000): file_ouput.write(word+'\n') <file_sep>#!/usr/bin/env python3 import json import argparse import os parser = argparse.ArgumentParser() parser.add_argument('--input-question-dir', type=str, default='/tmp', help=('Directory to read original Wikipedia file from.'), required=True) parser.add_argument('--input-sentence-dir', type=str, default='/tmp', help=('Directory to read original Wikipedia file from.'), required=True) parser.add_argument('--out-dir', type=str, default='/tmp', help=('Directory to write squad-formatted file to ' '(wiki_XX.json)'), required=True) args = parser.parse_args() questions = args.input_question_dir labeled_sents = args.input_sentence_dir wiki_squad = args.out_dir ################################################# # # Begin processing # Three steps to this. # ################################################# total_questions = 0 for foldername in os.listdir(labeled_sents): input_subfolder_q = questions + foldername input_subfolder_s = labeled_sents + foldername output_subfolder = wiki_squad + foldername print("Adding questions to squad-formatted Wikipedia files in {} folder...".format(foldername)) num_questions = 0 # each file represents several (variable #) wikipedia articles for filename in os.listdir(input_subfolder_q): # input file is questions with scores input_file_q = input_subfolder_q + '/' + filename input_file_s = input_subfolder_s + '/' + filename output_file = output_subfolder + '/' + filename with open(output_file) as json_file: data = json.load(json_file) wiki_dict = data['data'] with open(input_file_q) as f: pred_questions = f.read().splitlines() pred_questions = pred_questions[::2] # start with the 1st line, take every other line with open(input_file_s) as f2: for line_q,line_s in zip(pred_questions,f2): #print(line_q) #print(line_s + '\n') line_tuple = eval(line_s) item_id = line_tuple[0] doc = wiki_dict[item_id[0]] # pull the whole document context = doc["paragraphs"][item_id[1]] num_questions += 1 total_questions += 1 context['qas'].append({"question": line_q.rstrip(), "answers": [], "id": str(item_id)}) with open(output_file, 'w') as outfile: json.dump(data, outfile) print("Completed adding {} questions to squad-formatted Wikipedia files in {} folder.\n".format(num_questions, foldername)) print("Complete. Added {} total questions to squad-formatted files.".format(total_questions))<file_sep>def decoding_layer(dec_input, encoder_state, target_sequence_length, max_target_sequence_length, rnn_size, num_layers, target_vocab_to_int, target_vocab_size, batch_size, keep_prob, decoding_embedding_size): """ Create decoding layer :return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput) """ target_vocab_size = len(target_vocab_to_int) dec_embeddings = tf.Variable(tf.random_uniform([target_vocab_size, decoding_embedding_size])) dec_embed_input = tf.nn.embedding_lookup(dec_embeddings, dec_input) cells = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.LSTMCell(rnn_size) for _ in range(num_layers)]) with tf.variable_scope("decode"): output_layer = tf.layers.Dense(target_vocab_size) train_output = decoding_layer_train(encoder_state, cells, dec_embed_input, target_sequence_length, max_target_sequence_length, output_layer, keep_prob) with tf.variable_scope("decode", reuse=True): infer_output = decoding_layer_infer(encoder_state, cells, dec_embeddings, target_vocab_to_int['<GO>'], target_vocab_to_int['<EOS>'], max_target_sequence_length, target_vocab_size, output_layer, batch_size, keep_prob) return (train_output, infer_output)<file_sep>def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_vocab_size, encoding_embedding_size): """ :return: tuple (RNN output, RNN state) """ embed = tf.contrib.layers.embed_sequence(rnn_inputs, vocab_size=source_vocab_size, embed_dim=encoding_embedding_size) stacked_cells = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.LSTMCell(rnn_size), keep_prob) for _ in range(num_layers)]) outputs, state = tf.nn.dynamic_rnn(stacked_cells, embed, dtype=tf.float32) return outputs, state<file_sep>import sentence_selection import json from pprint import pprint paragraphs = open("/home/joanna_huang/GenerationQ/model/bucket-w210/AA/wiki_00", "r") f = open("new-sent-test.txt", "w+") for p in paragraphs: data = json.loads(p) context = data['text'] cleaned_data = sentence_selection.clean_sentences(context) word_distr = sentence_selection.word_distribution(cleaned_data) sentence_weight = sentence_selection.sentence_weight(word_distr,cleaned_data) chosen_sent = sentence_selection.topically_important_sentence(sentence_weight, context) for key,val in chosen_sent.items(): f.write(str(val)+'.\n') <file_sep>cd /Users/sdatta/wikipedia_w251 for filepath in $(ls -1 ./wikipedia/json_out/*/*) do grep -io "\"id\": .* \"title\": \"[0-9a-z ]*\"" ${filepath} /dev/null|awk -F"[,:]" 'BEGIN{OFS="|";} {print $1,$3,$5":"$6,$8}'|sed -e 's/| /|/g' -e 's/ |/|/g'|sed -e 's/"//g'|cut -d "/" -f4- done > parse.sh.nohup.out <file_sep>#!/bin/sh generationq_dir="/home/julia_buffinton/GenerationQ/model" model="${generationq_dir}/trained/600rnn_step_16000.pt" # updated to model with lowest perplexity data_files="./wikipedia_data" start_time=$(date "+%s") files=0 # This should contain folders of files with sentences, that we will generate Qs for unlabeled_sents="${data_files}/unlabeled_sentences/" questions="${data_files}/questions/" wiki_squad="${data_files}/wikipedia_squad/" labeled_sents="${data_files}/labeled_sentences/" for foldername in $(ls ${unlabeled_sents}) do input_subfolder="${unlabeled_sents}${foldername}" output_subfolder="${questions}${foldername}" mkdir -p ${output_subfolder} echo "Beginning question generation for files in ${foldername} folder..." # each file represents questions for several (variable #) Wikipedia articles for filename in $(ls ${input_subfolder}) do # input file is unlabeled sentence input_file="${input_subfolder}/${filename}" # save list of questions output_file="${output_subfolder}/${filename}" python -W ignore ${generationq_dir}/test.py -model "${model}" -src ${input_file} -output "${output_file}" -replace_unk -beam_size 3 -gpu 0 -batch_size 30 now_time=$(date "+%s") files=`expr $files + 1` if [ `expr $files % 20` -eq 0 ] then if [ $files == 20 ] then time_taken=`expr $now_time - $start_time` echo "Processed 20 files in ${time_taken} seconds, total: ${files} files" else time_taken=`expr $now_time - $chunk_time` echo "Processed 20 files in ${time_taken} seconds, total: ${files} files" chunk_begin=${now_time} fi fi done done total_time=`expr $now_time - $start_time` echo "\nCompleted ${files} files in ${total_time} seconds" python add_questions.py --input-question-dir ${questions} --input-sentence-dir ${labeled_sents} --out-dir ${wiki_squad} <file_sep>#!/usr/bin/env python """ Choose sentence from paragraph """ import nltk import os import math import string import operator from collections import defaultdict, OrderedDict def clean_sentences(paragraph): """Clean sentences, remove digit, punctuation, upper case to lower Args: sentences: sentences to be cleaned Return: sentences_processed: dict of cleaned sentences """ flag = 0 sentence_processed = {} # Remove all punctuation except periods punc = set(string.punctuation) punc.remove('.') # Remove all digits paragraph = ''.join([x for x in paragraph if not x.isdigit()]) paragraph = ''.join([x for x in paragraph if x not in punc]) # Lowercase everything paragraph = ''.join([x.lower() for x in paragraph]) # Split into words paragraph = ' '.join(paragraph.split()) stop_words = nltk.corpus.stopwords.words('english') stemmer = nltk.stem.PorterStemmer() tokenize = nltk.word_tokenize for sentence in paragraph.split('.'): sentence = sentence.strip() sentence = [stemmer.stem(word) for word in tokenize( sentence) if not word in stop_words] if sentence: sentence_processed[flag] = sentence flag += 1 print('sentence_processed: ' + str(sentence_processed)) return sentence_processed def word_distribution(sentence_processed): """Compute word probabilistic distribution which is calculated by \ term frequency divided by total word count""" word_distr = defaultdict(int) word_count = 0.0 # For each word in each sentence, count number of times each word appears as well as total words in sentence for k in sentence_processed: for word in sentence_processed[k]: word_distr[word] += 1 word_count += 1 for word in word_distr: word_distr[word] = word_distr[word] / word_count return word_distr def sentence_weight(word_distribution, sentence_processed): """Compute weight with respect to sentences Args: word_distribution: probabilistic distribution of terms in document sentence_processed: dict of processed sentences generated by clean_sentences Return: sentence_weight: dict of weight of each sentence """ sentence_weight = {} # Iterate through each word in each sentence, if word distribution and sentence id are in dictionary, # add to existing word distribution. Else, sentence weight for given sentence equals current word distribution for sentence_id in sentence_processed: for word in sentence_processed[sentence_id]: if word_distribution[word] and sentence_id in sentence_weight: sentence_weight[sentence_id] += word_distribution[word] else: sentence_weight[sentence_id] = word_distribution[word] # Sentence weight equals sum of word distributions divided by length of cleaned sentence sentence_weight[sentence_id] = sentence_weight[ sentence_id] / float(len(sentence_processed[sentence_id])) sentence_weight = sorted(sentence_weight.items( ), key=operator.itemgetter(1), reverse=True) print('sentence_weight: ' + str(sentence_weight)) return sentence_weight def topically_important_sentence(sentence_weight, paragraph): """Select topically import sentences Args: sentence_weight: dict, weight of sentences computed in sentence_weight sentences: set of sentences Return: sentences_selected: dict, topically important sentences selected """ sentence_length = len(sentence_weight) # how many sentences to retain num_sentences_selected = math.ceil(float(0.05) * sentence_length) num_sentences_selected = int(num_sentences_selected) # key of selected sentences sentences_selected_key = [] # dictionary of all sentences sentences_dict = {} flag = 0 # select num_sentences_selected # of sentences from list of sentence weights for k, v in sentence_weight[0:num_sentences_selected]: sentences_selected_key.append(k) # Iterate through sentences in raw text and assign a id number print('paragraph: ' + str(paragraph)) for sentence in paragraph.split('.'): if sentence: sentences_dict[flag] = sentence flag += 1 print('sentences_dict: ' + str(sentences_dict)) sentences_selected = OrderedDict() print('sentences_selected_key: ' + str(sentences_selected_key)) print('sentences_selected: ' + str(sentences_selected)) for key in sentences_selected_key: sentences_selected[key] = sentences_dict[key] return sentences_selected <file_sep>python preprocess.py \ --input-dir wikipedia_data/wikipedia_dump/ \ --out-dir wikipedia_data/wikipedia_squad/ \ <file_sep>--- title: "R Notebook" output: pdf_document --- Unpaired Two-Samples T-Test http://www.sthda.com/english/wiki/unpaired-two-samples-t-test-in-r ```{r} data <- read.csv('/Users/juliabuffinton/Documents/MIDS/W210_Synthetic_Capstone/w210-capstone-qg/mturk_prep/All_results.csv') head(data) ``` ```{r} qgen <- data[data$Qgen==TRUE,] squad <- data[data$Qgen==FALSE,] ``` ```{r} library(dplyr) library(tidyr) data.summary <- group_by(data,Qgen) %>% select(Clarity,Fluency) %>% # select variables to summarise summarise_each(funs(median = median, mean = mean, sd = sd)) data.summary ``` ```{r} # Plot weight by group and color by group library("ggpubr") ggboxplot(data, x = "Qgen", y = "Clarity", color = "Qgen", palette = c("#00AFBB", "#E7B800"), ylab = "Clarity", xlab = "Qgen") ggboxplot(data, x = "Qgen", y = "Fluency", color = "Qgen", palette = c("#00AFBB", "#E7B800"), ylab = "Fluency", xlab = "Qgen") ``` Preleminary test to check independent t-test assumptions - Assumption 1: Are the two samples independents? - Assumtion 2: Are the data from each of the 2 groups follow a normal distribution? - Assumption 3. Do the two populations have the same variances? Use Shapiro-Wilk normality test: Null hypothesis: the data are normally distributed - Alternative hypothesis: the data are not normally distributed ```{r} # Shapiro-Wilk normality test for Qgen's Clarity with(data, shapiro.test(Clarity[Qgen == TRUE])) # Shapiro-Wilk normality test for Non-Qgens's Clarity with(data, shapiro.test(Clarity[Qgen == FALSE])) # Shapiro-Wilk normality test for Qgen's Fluency with(data, shapiro.test(Fluency[Qgen == TRUE])) # Shapiro-Wilk normality test for Non-Qgens's Fluency with(data, shapiro.test(Fluency[Qgen == FALSE])) ``` From the output, the two p-values are less than the significance level 0.05 implying that the distribution of the data are significantly different from the normal distribution so we cannot assume normality for the Clarity or Fluency distributions. ```{r} # Use F-test to test for homogeneity in variances print(var.test(Clarity ~ Qgen, data = data)) print(var.test(Fluency ~ Qgen, data = data)) ``` The p-value of F-test is less than the significance level alpha = 0.05. Therefore, there is a significant difference between the variances of the two sets of data. Since the variances of the two groups being compared are different (heteroscedasticity), we use the Welch t test, an adaptation of Student t-test that takes into account the variance of each of the two groups. ```{r} print(t.test(qgen$Clarity, squad$Clarity, var.equal=FALSE)) print(t.test(qgen$Fluency, squad$Fluency, var.equal=FALSE)) ``` Both differences are statistically significant. Inter-rater reliability: http://www.cookbook-r.com/Statistical_analysis/Inter-rater_reliability/ https://dkpro.github.io/dkpro-statistics/inter-rater-agreement-tutorial.pdf ```{r} library(irr) data %>% group_by(WorkerId) %>% summarize(n()) ``` <file_sep>import json import ast with open('DrQA-input-squad-dev.json') as f: docs_qs = json.load(f) ans_file = open('DrQA-input-squad-dev-single.preds','r') answers = ast.literal_eval(ans_file.read()) docs_qa = {} for key, value in docs_qs.items(): qa = {} for k, v in answers.items(): for q in range(len(value)): if int(k) == int(value[q][‘qid’]): qa[value[q][‘question’]] = v docs_qa[key] = qa # with open('doc_qa-squad-dev.txt','w') as file: # file.write(json.dumps(docs_qa)) df = pd.DataFrame(columns =['text','qas']) df['text'] = list(docs_qa.keys()) df['qas'] = list(docs_qa.values()) df.to_csv('docs_qa.csv') <file_sep>python sentence_selection.py \ --input-dir wikipedia_data/wikipedia_squad/ \ --out-dir-labeled wikipedia_data/labeled_sentences/ \ --out-dir-unlabeled wikipedia_data/unlabeled_sentences/<file_sep>def process_decoder_input(target_data, target_vocab_to_int, batch_size): # get '<GO>' id go_id = target_vocab_to_int['<GO>'] after_slice = tf.strided_slice(target_data, [0, 0], [batch_size, -1], [1, 1]) after_concat = tf.concat( [tf.fill([batch_size, 1], go_id), after_slice], 1) return after_concat<file_sep>#!/usr/bin/env python3 import json import argparse import os parser = argparse.ArgumentParser() parser.add_argument('--input-answer-dir', type=str, default='/tmp', help=('Directory to read answer file from.'), required=True) parser.add_argument('--input-squad-dir', type=str, default='/tmp', help=('Directory to read original Wikipedia file from.'), required=True) parser.add_argument('--out-dir', type=str, default='/tmp', help=('Directory to write squad-formatted file to ' '(wiki_XX.json)'), required=True) args = parser.parse_args() answers = args.input_answer_dir wiki_squad = args.input_squad_dir output = args.out_dir ################################################# # # Begin processing # Three steps to this. # ################################################# for foldername in os.listdir(answers): input_subfolder_a = answers + foldername output_subfolder = output + foldername squad_subfolder = wiki_squad + foldername if not os.path.exists(output_subfolder): os.mkdir(output_subfolder) print("Adding answers to squad-formatted Wikipedia files in {} folder...".format(foldername)) # each file represents several (variable #) wikipedia articles for filename in os.listdir(input_subfolder_a): # input file is questions with scores input_file_a = input_subfolder_a + '/' + filename squad_file = squad_subfolder + '/' + filename[:7] output_file = output_subfolder + '/' + filename[:7] with open(squad_file) as json_file: data = json.load(json_file) wiki_dict = data['data'] with open(input_file_a) as f: qa_data = json.load(f) for key, value in qa_data.items(): item_id = eval(key) doc = wiki_dict[item_id[0]] # pull the whole document context = doc["paragraphs"][item_id[1]] # find the appropriate paragraph for i,question in enumerate(context['qas']): #each paragraph may have several associated questions, so need to find the right one if question['id'] == key: #print(key) question['answers'].append({'answer_start' : 0, 'text': value[0][0]}) final_output = output_file + '.json' with open(final_output, 'w') as outfile: json.dump(data, outfile)<file_sep>#!/usr/bin/env python3 import json import ast import numpy as np import pandas as pd import nltk import spacy import argparse import os from spacy import displacy from collections import Counter import random;random.seed(1) import en_core_web_sm import textacy import re import unidecode from text2digits import text2digits import time t2d = text2digits.Text2Digits() nlp = en_core_web_sm.load() def preprocess(answer): # Remove extra punctuations and lowercase answer prep_answer = answer.lstrip('\'') prep_answer = prep_answer.rstrip('.') prep_answer = prep_answer.replace('\""','') prep_answer = prep_answer.replace('\"','') prep_answer = prep_answer.replace('\"','') prep_answer = prep_answer.lower() return prep_answer def check_answer_type(raw_answer): answer_type = [] tokenized_answer = nlp(preprocess(raw_answer)) # get part of speech for answer pos_answer = [token.pos_ for token in tokenized_answer] # create month list to identify date answers month_list = ['january', 'jan', 'february', 'feb', 'march', 'april', \ 'may','june', 'july', 'august', 'aug', 'september', 'sept',\ 'october', 'oct', 'nov', 'dec','november', 'december'] if raw_answer[0].isupper(): # Check if it's a date if str(tokenized_answer[0]).lower() in month_list: answer_type.append('DATE') else: answer_type.append('PROPN') elif '°C' in raw_answer: answer_type.append('MEASUREMENT') elif (pos_answer[0]=='VERB') and (len(raw_answer)<2): answer_type.append('VERB') elif (pos_answer[0]=='VERB') and (len(raw_answer)>=2): answer_type.append('VP') # conditional for "to be" verbs elif (pos_answer[0]=='PART') and (pos_answer[1]=='VERB'): answer_type.append('VP') elif (pos_answer[0]=='ADV'): if len(tokenized_answer)>1: if (pos_answer[1]=='ADJ'): answer_type.append('ADJ') elif (pos_answer[1]=='PUNCT') and (pos_answer[2]=='ADJ'): answer_type.append('ADJ') elif (pos_answer[1]=='VERB'): answer_type.append('VP') else: answer_type.append('ADV') else: answer_type.append('ADV') elif (pos_answer[0]=='NUM') | (pos_answer[0]=='PUNCT'): month_present = [1 for i in month_list if i in raw_answer.lower()] BC_AD = [1 for i in ['AD','BC'] if i in raw_answer.lower()] measurement_present = [1 for i in ['minutes', 'hours', 'seconds', 'days','%','°C','°F'] if i in raw_answer] if month_present!=[]: answer_type.append('DATE') elif BC_AD!=[]: answer_type.append('YEAR') elif measurement_present!=[]: answer_type.append('MEASUREMENT') else: answer_type.append('NUM') elif pos_answer[0]=='ADJ': answer_type.append('ADJ') elif (pos_answer[0]=='NOUN') | (pos_answer[0]=='X'): month_present = [1 for i in month_list if i in raw_answer.lower()] # check if it's a hyphen-separated adjective if re.findall(r'\w+(?:-\w+)+'.lower(),raw_answer): answer_type.append('ADJ') # check if there's a digit in the answer elif bool(re.search(r'\d', raw_answer)): # check for currency symbols if bool(re.search(r'([£\$€])', raw_answer)): answer_type.append('MONEY') elif str(tokenized_answer[1])=='-': answer_type.append('SCORE') elif month_present!=[]: answer_type.append('DATE') else: answer_type.append('YEAR') else: answer_type.append('NOUN') elif pos_answer[0]=='ADP': answer_type.append('ADP') elif pos_answer[0]=='DET': if pos_answer[1]=='NOUN': answer_type.append('NOUN') elif pos_answer[1]=='PROPN': answer_type.append('PROPN') elif pos_answer[0]=='SYM': answer_type.append('MONEY') else: answer_type.append('Unknown type') return answer_type def generate_distractor(df, topic, paragraph, qid, question, answer, answer_type): wrong_answers=[] #preprocess answer correct_answer = nlp(unidecode.unidecode(preprocess(answer))) # get answer pos ans_length = len(correct_answer) ans_tag = [token.tag_ for token in correct_answer] ans_pos = [token.pos_ for token in correct_answer] # tokenize paragraph article = nlp(unidecode.unidecode(paragraph)) doc = textacy.Doc(paragraph, lang='en_core_web_sm') # Preprocessing for same sentence distractor generation # get all sentences in paragraph sent_detector = nltk.data.load('tokenizers/punkt/english.pickle') sent_list = sent_detector.tokenize(paragraph.strip()) # find sentence that has answer for s in sent_list: if answer in s: ans_sent = s # tokenize sentence sentence = nlp(ans_sent) sent = textacy.Doc(sentence, lang='en_core_web_sm') # Preprocessing for same topic distractor generation # choose random paragraph from same topic topic_index = next((index for (index, d) in enumerate(df['data']) if d["title"] == topic), None) index_list = list(range(len(df['data'][topic_index]['paragraphs']))) # make sure isn't the same paragraph as current paragraph p_index = next((index for (index, d) in enumerate(df['data'][topic_index]['paragraphs'])\ if d["context"] == paragraph), None) index_list.remove(p_index) # Choose 5 random paragraphs from the same article alt_p_index = random.choices(index_list,k=5) alt_p_list = [df['data'][topic_index]['paragraphs'][i]['context'] for i in alt_p_index] alt_article_list = [nlp(alt_p) for alt_p in alt_p_list] alt_paragraph_list = [textacy.Doc(alt_p, lang='en_core_web_sm') for alt_p in alt_p_list] ent_list = [str(i).lower() for i in list(article.ents)] # print('ent_list: ' + str(ent_list)) # print('correct answer: ' + str(correct_answer)) if str(correct_answer) in ent_list: answer_type.append('ENTITY') # print('in entity list') ent_labels = [x.label_ for x in article.ents] # get all named entities in sentence sent_ent_list = [str(i).lower() for i in list(sentence.ents)] sent_labels = [x.label_ for x in sentence.ents] alt_article_ent_list = [] alt_article_labels = [] for p in alt_article_list: p_ent_list = [str(i).lower() for i in list(p.ents)] p_labels = [x.label_ for x in p.ents] alt_article_ent_list.extend(p_ent_list) alt_article_labels.extend(p_labels) # print('alt_article_ent: ' + str(alt_article_ent_list)) # print('alt_article_labels: ' + str(alt_article_labels)) merged=set(ent_labels+sent_ent_list+alt_article_ent_list) max_length = max(len(ent_list), len(sent_ent_list), len(alt_article_ent_list)) # create table of named entities ne_pd = pd.DataFrame() ne_pd['entity'] = ent_list + (['NA'] * (max_length - len(ent_list))) ne_pd['label'] = list(ent_labels) + (['NA'] * (max_length - len(ent_list))) ne_pd['sent_entity'] = sent_ent_list + (['NA'] * (max_length - len(sent_ent_list))) ne_pd['sent_label'] = list(sent_labels) + (['NA'] * (max_length - len(sent_ent_list))) ne_pd['altp_entity'] = alt_article_ent_list + (['NA'] * (max_length - len(alt_article_ent_list))) ne_pd['altp_label'] = list(alt_article_labels) + (['NA'] * (max_length - len(alt_article_ent_list))) ans_label = [ne_pd[ne_pd['entity']==e]['label'].values[0] for e in ne_pd['entity'] if e in str(correct_answer)] # print('answer label: ' + str(ans_label)) # This filters scores such as 49-15 that are labeled as "DATE" alt_ans_list = list(ne_pd[(ne_pd['label'].isin(ans_label))]['entity']) alt_ans_list.extend(list(ne_pd[(ne_pd['sent_label'].isin(ans_label))]['sent_entity'])) alt_ans_list.extend(list(ne_pd[(ne_pd['altp_label'].isin(ans_label))]['altp_entity'])) # print('alt_ans_list: ' + str(alt_ans_list)) if (['DATE'] in ans_label) | (ans_label==['DATE']): score_list=[] if 'SCORE' in answer_type: num_list = re.findall(r'(\d+-?){1,2}',paragraph) # Iterate through same topic articles to find all numbers for p in alt_p_list: num_list.extend(re.findall(r'(\d+-?){1,2}',p)) for n in range(len(num_list)-1): score = num_list[n][:2]+'-'+num_list[n+1][:2] score_list.append(score) wrong_answers = score_list else: filtered_month = set(['January', 'Jan', 'February', 'March', 'April', \ 'May','June', 'July', 'August', 'September', \ 'October','November','December'])-set([(str(correct_answer[0]).capitalize())]) month_list=random.sample(filtered_month,5) day_list = random.sample(range(1, 30), 5) year_list = random.sample(range(1300,2050), 5) random_date = [str(m)+' '+str(d)+','+str(y) for m in month_list for d in day_list for y in year_list] alt_ans_list.extend(random_date) if len(alt_ans_list)<=3: if (['TIME'] in ans_label) | (ans_label==['TIME']) | (['PERCENT'] in ans_label) | (ans_label==['PERCENT']): random_time = [str(num)+' ' +str(correct_answer[-1]) for num in random.sample(range(1, 60), 5)] alt_ans_list.extend(random_time) elif (['MONEY'] in ans_label) | (ans_label==['MONEY']): currency = answer[0] random_money = [answer[0]+str(num)+' ' +str(correct_answer[-1]) for num in random.sample(range(1, 60), 5)] alt_ans_list.extend(random_money) elif (['DATE'] in ans_label) | (ans_label==['DATE']): filtered_month = set(['January', 'Jan', 'February', 'March', 'April', \ 'May','June', 'July', 'August', 'September', \ 'October','November','December'])-set([(str(correct_answer[0]).capitalize())]) month_list=random.sample(filtered_month,5) day_list = random.sample(range(1, 30), 5) year_list = random.sample(range(1300,2050), 5) random_date = [str(m)+' '+str(d)+','+str(y) for m in month_list for d in day_list for y in year_list] alt_ans_list.extend(random_date) elif (['ORDINAL'] in ans_label) | (ans_label==['ORDINAL']) | (['CARDINAL'] in ans_label) | (ans_label==['CARDINAL']): # print('answer is ORDINAL') correct_ans_pos = str(['r'+str(token.pos_)+'l' for token in \ correct_answer])[1:-1].replace("'r","<").replace("l'",">").replace(',','+',1).replace(',','*').replace(' ','')+'+' # print(correct_ans_pos) alt_ans_list=[] for p in alt_paragraph_list: p_list = [l.text.lower() for l in textacy.extract.pos_regex_matches(p, correct_ans_pos)] alt_p_list.extend(p_list) alt_ans_list.extend(alt_p_list) else: correct_ans_pos = str(['r'+'PROPN'+'l' for token in \ correct_answer])[1:-1].replace("'r","<").replace("l'",">").replace(',','+',1).replace(',','*').replace(' ','')+'+' alt_ans_list=[] for p in alt_paragraph_list: p_list = [l.text.lower() for l in textacy.extract.pos_regex_matches(p, correct_ans_pos)] alt_p_list.extend(p_list) alt_ans_list.extend(alt_p_list) wrong_answers = alt_ans_list elif 'PROPN' in answer_type: doc_list = [l.text.lower() for l in textacy.extract.pos_regex_matches(doc, r'<PROPN>+')] sent_list = [l.text.lower() for l in textacy.extract.pos_regex_matches(sent, r'<PROPN>+')] alt_p_list=[] for p in alt_paragraph_list: p_list = [l.text.lower() for l in textacy.extract.pos_regex_matches(p, r'<PROPN>+')] alt_p_list.extend(p_list) merged = set(doc_list+sent_list+alt_p_list) wrong_answers=merged elif 'NUM' in answer_type: doc_list = [l.text.lower() for l in textacy.extract.pos_regex_matches(doc, r'<NUM>+')] sent_list = [l.text.lower() for l in textacy.extract.pos_regex_matches(sent, r'<NUM>+')] alt_p_list=[] for p in alt_paragraph_list: p_list = [l.text.lower() for l in textacy.extract.pos_regex_matches(p, r'<NUM>+')] alt_p_list.extend(p_list) merged = set(doc_list+sent_list+alt_p_list) wrong_answers = [t2d.convert(str(i)).lstrip() for i in merged] if len(str(correct_answer))==4: wrong_answers = [i if len(i)==4 else str(correct_answer)[:2]+str(random.sample(range(0, 99),1)[0]) for i in wrong_answers] elif 'DATE' in answer_type: filtered_month = set(['January', 'Jan', 'February', 'March', 'April', \ 'May','June', 'July', 'August', 'September', \ 'October','November','December'])-set([(str(correct_answer[0]).capitalize())]) month_list=random.sample(filtered_month,5) if ans_length==1: wrong_answers=month_list else: day_list = random.sample(range(1, 30), 5) year_list = random.sample(range(1300,2050), 5) random_date = [str(m)+' '+str(d)+','+str(y) for m in month_list for d in day_list for y in year_list] wrong_answers=random_date else: merged=[] correct_ans_pos = str(['r'+str(token.pos_)+'l' for token in \ correct_answer])[1:-1].replace("'r","<").replace("l'",">").replace(',','+',1).replace(',','*').replace(' ','')+'+' # print('correct_ans_pos: ' + str(correct_ans_pos)) doc_list = [l.text.lower() for l in textacy.extract.pos_regex_matches(doc, correct_ans_pos)] sent_list = [l.text.lower() for l in textacy.extract.pos_regex_matches(sent, correct_ans_pos)] alt_p_list=[] for p in alt_paragraph_list: p_list = [l.text.lower() for l in textacy.extract.pos_regex_matches(p, correct_ans_pos)] alt_p_list.extend(p_list) merged = set(doc_list+sent_list+alt_p_list) wrong_answers=list(merged) if len(wrong_answers)<=3: if '<NOUN>' in correct_ans_pos: for p in alt_paragraph_list: p_list = [l.text.lower() for l in textacy.extract.pos_regex_matches(p,r'<NOUN>+')] wrong_answers.extend(p_list) elif '<VERB>' in correct_ans_pos: for p in alt_paragraph_list: p_list = [l.text.lower()for l in textacy.extract.pos_regex_matches(p,r'<VERB>+')] wrong_answers.extend(p_list) if 'VP' in answer_type: if len(wrong_answers) >= 3: for i in wrong_answers: if isinstance(i, str): item = nlp(i) if (item[0].tag_ == ans_tag[0]) and (item[-1].pos_ == ans_pos[-1]): wrong_answers.append(item) if 'VERB' in answer_type: if len(wrong_answers) >= 3: for i in wrong_answers: if isinstance(i, str): item = nlp(i) if (item[0].tag_ == ans_tag[0]): wrong_answers.append(item.orth_) if 'ADJ' in answer_type: hyphen_sep_words = re.findall(r'\w+(?:-\w+)+'.lower(),paragraph) hyphen_sep_words_sent = re.findall(r'\w+(?:-\w+)+'.lower(),ans_sent) alt_p_hyphen_sep_words=[] for p in alt_p_list: p_hyphen_sep_words = re.findall(r'\w+(?:-\w+)+'.lower(),p) alt_p_hyphen_sep_words.extend(p_hyphen_sep_words) # alt_topic_hyphen_sep_words = re.findall(r'\w+(?:-\w+)+'.lower(),alt_topic_paragraph) hyphen_words = hyphen_sep_words+hyphen_sep_words_sent+alt_p_hyphen_sep_words # print('hyphen_words: ' + str(hyphen_words)) for w in hyphen_words: wrong_answers.append(w) if 'YEAR' in answer_type: wrong_answer = [i for i in wrong_answers if len(i)==4] if 'MEASUREMENT' in answer_type: wrong_answers = [t2d.convert(str(nlp(i)[0])).lstrip()+' ' + str(correct_answer[-1]) for i in merged] if 'MONEY' in answer_type: currency = answer[0] random_money = [answer[0]+str(num)+' ' +str(correct_answer[-1]) for num in random.sample(range(1, 60), 5)] wrong_answers.extend(random_money) if 'ADP' in answer_type: wrong_answers = [i for i in wrong_answers if i[0]==correct_answer[0].orth_] #Remove distractors with part of answer in it answer_found=False filtered_wrong_answers = [] if ('MEASUREMENT' not in answer_type) and ('NUM' not in answer_type) and ('MONEY' not in answer_type)\ and ('SCORE' not in answer_type) and ('DATE' not in answer_type): print('not measurement, num, date, money') for i in wrong_answers: answer_found=False for word in range(len(correct_answer)): if (correct_answer[word].orth_ in ['the','of','a','an','that','to','between', 'and']): answer_found=False elif (correct_answer[word].orth_ in str(i)): answer_found=True if answer_found==False: filtered_wrong_answers.append(i) filtered_wrong_answers=[item for item in filtered_wrong_answers if item not in ['a','an','the','that','it','who','what', '',""]] else: filtered_wrong_answers = wrong_answers # if not enough filtered answers, choose first tokens of paragraph up to length of answer if len(set(filtered_wrong_answers))<3: for article in alt_article_list: if len(article)>ans_length: filtered_wrong_answers.append(article[:ans_length]) return (topic, paragraph, qid, question, correct_answer, answer_type, random.sample(list(set(filtered_wrong_answers)),3)) def generate_wrong_answers(in_file,out_file): with open(in_file) as f: df = json.load(f) topics = [] paragraphs = [] questions = [] qids = [] answers = [] autoq = pd.DataFrame() data = df['data'] for title in range(len(df['data'])): #print(df['data'][title]['title']) for p in range(len(df['data'][title]['paragraphs'])): if df['data'][title]['paragraphs'][p]['qas'] == []: topics.append(df['data'][title]['title']) paragraphs.append(df['data'][title]['paragraphs'][p]['context']) questions.append('') answers.append('') qids.append('') else: for qa in range(len(df['data'][title]['paragraphs'][p]['qas'])): topics.append(df['data'][title]['title']) paragraphs.append(df['data'][title]['paragraphs'][p]['context']) questions.append(df['data'][title]['paragraphs'][p]['qas'][qa]['question']) qids.append(df['data'][title]['paragraphs'][p]['qas'][qa]['id']) answers.append(df['data'][title]['paragraphs'][p]['qas'][qa]['answers'][0]['text']) autoq['topics'] = topics autoq['paragraphs'] = paragraphs autoq['questions'] = questions autoq['id'] = qids autoq['answers'] = answers start = time.time() distractors = [] for i in range(len(autoq)): try: answer_type = check_answer_type(autoq.loc[i]['answers']) #print('answer_type: ' + str(answer_type)) topic, paragraph, qid, question, correct_answer, answer_type, wrong_answers = generate_distractor(df, autoq.loc[i]['topics'], autoq.loc[i]['paragraphs'], autoq.loc[i]['id'],autoq.loc[i]['questions'], autoq.loc[i]['answers'], answer_type) distractors.append(wrong_answers) except: print("error occurred for sample#: " + str(i)) distractors.append(['NA']) autoq['distractors']=distractors autoq['distractor_length'] = [1 if (len(autoq.loc[i]['distractors'])==1) else 0 for i in list(autoq.index.values) ] print("Progress: processed {} records in {:.2f} minutes".format(len(autoq),(time.time()-start)/60)) new_distractors = [] for i in range(len(autoq)): processed_list = [] for item in autoq.loc[i]['distractors']: if not isinstance(item,str): text_version = item.text processed_list.append(text_version) else: processed_list.append(item) new_distractors.append(processed_list) autoq['new_distractors']=new_distractors wiki_dict = df['data'] for record in range(len(autoq)): qid = autoq.loc[record]['id'] for title in range(len(wiki_dict)): for p in range(len(wiki_dict[title]['paragraphs'])): if wiki_dict[title]['paragraphs'][p]['qas'] == []: continue else: for qa in range(len(wiki_dict[title]['paragraphs'][p]['qas'])): if qid==wiki_dict[title]['paragraphs'][p]['qas'][qa]['id']: wiki_dict[title]['paragraphs'][p]['qas'][qa]['distractors'] = autoq.loc[record]['new_distractors'] df['data']=wiki_dict with open(out_file, 'w') as outfile: json.dump(df, outfile) ########################################################################################### if __name__ == "__main__": parser = argparse.ArgumentParser( description='wrong_answer_gen.py') parser.add_argument('--input-dir', type=str, default='./wikipedia_data/for_autoq', help=('Directory to read original squad-formatted file from.'), required=True) parser.add_argument('--out-dir', type=str, default='./wikipedia_data/for_autoq_mc', help=('Directory to write squad-formatted file with distractors to.'), required=True) args = parser.parse_args() wiki_squad = args.input_dir wiki_squad_final = args.out_dir for foldername in os.listdir(wiki_squad): if not foldername.startswith('.'): input_subfolder = wiki_squad + foldername output_subfolder = wiki_squad_final + foldername if not os.path.exists(output_subfolder): os.mkdir(output_subfolder) print("Generating wrong answers for files in {} folder...".format(foldername)) for filename in os.listdir(input_subfolder): if not filename.startswith('.'): input_file = input_subfolder + '/' + filename output_file = output_subfolder + '/' + filename generate_wrong_answers(input_file,output_file) <file_sep>#!/bin/sh qa_dir="/home/joanna_huang/DrQA" model="${qa_dir}/data/reader/single.mdl" qa_predict="${qa_dir}/scripts/reader/predict.py" start_time=$(date "+%s") files=0 data_files="./data/datasets" # This should contain folders of files with lists of Wikipedia articles wiki_squad="${data_files}/wikipedia_squad/" answers="${data_files}/answers/" ouput="${data_files}/for_autoq/" for foldername in $(ls -1 ${wiki_squad}) do echo "foldername: ${foldername}" input_subfolder="${wiki_squad}${foldername}" output_subfolder="${answers}${foldername}" mkdir -p ${output_subfolder} echo "Beginning question answering for files in ${foldername} folder..." for filename in $(ls -1 ${input_subfolder}) do echo "filename: ${filename}" input_file="${input_subfolder}/${filename}" output_file="${output_subfolder}/${filename}" python ${qa_predict} --model ${model} --out-dir ${output_subfolder} ${input_file} now_time=$(date "+%s") time_taken=`expr $now_time - $start_time` echo "Completed ${files} files in ${time_taken} seconds" files=`expr $files + 1` done done python add_answers.py --input-question-dir ${answers} --input-squad-dir ${wiki_squad} --out-dir ${wiki_squad} <file_sep>import pandas as pd import glob import os import numpy as np import concurrent.futures import time #https://forums.fast.ai/t/python-parallel-processing-tips-and-applications/2092 path = "/Users/sdatta/json_out" allFiles = glob.glob(os.path.join(path,"*/*")) np_array_list = [] start = time.time() def read_json(in_file): file_substr = "/".join(in_file.split(sep="/")[-2:]) print("Started ", file_substr," at ",time.time()) l_df = pd.read_json(in_file, lines=True) l_df['filename'] = file_substr return l_df.as_matrix() with concurrent.futures.ProcessPoolExecutor() as executor: for file in allFiles: np_array_list.append(read_json(file)) done = time.time() elapsed = done - start print("Time taken ",elapsed) comb_np_array = np.vstack(np_array_list) big_frame = pd.DataFrame(comb_np_array, columns=['id', 'text', 'title', 'url','filename']) print(big_frame.head(2)['filename'])
41f879d21a6268588de5958d68c6789d6d1806e1
[ "HTML", "Markdown", "Python", "Text", "RMarkdown", "Shell" ]
31
Python
juliabuffinton/w210-capstone-qg
957138fc6e04d085ca64e372848811af71b2ea1d
77cba4c4b7b682d62ce03cad00884fff5b004bc0
refs/heads/master
<file_sep># Habit Tracker App ## Guia de Preparação do ambiente 1. Dê permissão de execução para o script *build.sh* 2. Execute o script, atentando-se às saídas disponibilizadas no terminal: Elas possuem as informações sobre os diretórios onde os repositórios das dependências foram clonados, assim como o diretório para onde os JARs destas dependências foram movidos após o processo de compilação com o Maven 3. Importe o projeto Android baixado pelo scrip (encontra-se por padrão em **/home/${USER}/Projetos/HabitTracking/habitTracking_app**): Abra o Android Studio, clique em "*Open an existing Android Studio project*" e navegue até o caminho onde o script baixou o projeto (apontado acima). 4. Após a finalização da importação, vá até a opção **Project Structure**: Use o atalho *Ctrl+Shift+Alt+S* ou navegue através do menu *File>Project Structure* e navegue até *Modules>app*, indo depois até a aba *Dependencies*. Clique no botão para adicionar uma nova dependência (ou use o atalho *Alt+Insert*) e selecione a opção **Jar dependency**; adicione as dependências presentes no diretório **libs**.<file_sep>#!/bin/bash PURPLE='\033[0;35m' GREEN='\033[1;92m' NC='\033[0m' LINEBREAK='\n\n' echo -e "[${PURPLE}INFO${NC}] Criando estrutura de diretórios para o projeto...\n\n" PROJ_ROOT=/home/${USER}/Projetos/HabitTracking REPO=/home/${USER}/.m2/local_repo if [ -d "$PROJ_ROOT" ]; then rm -rf $PROJ_ROOT; fi if [ -d "$REPO" ]; then rm -rf $REPO; fi mkdir -p $PROJ_ROOT; mkdir -p $REPO; echo -e "${BOLD}[${PURPLE}INFO${NC}] CLONANDO REPOSITÓRIOS..." echo -e "${LINEBREAK}${BOLD}[${PURPLE}INFO${NC}] Clonando repositório principal do projeto em ${GREEN}$PROJ_ROOT/habitTracking_app${NC}...\n" git clone https://github.com/antonieti/android-semestral-proj.git $PROJ_ROOT/habitTracking_app echo -e "${LINEBREAK}${BOLD}[${PURPLE}INFO${NC}] Clonando repositório de ENTIDADES em ${GREEN}$PROJ_ROOT/entities${NC}...\n" git clone https://github.com/antonieti/habit-tracking-entities.git $PROJ_ROOT/entities echo -e "${LINEBREAK}${BOLD}[${PURPLE}INFO${NC}] Clonando repositório de REPOSITÓRIOS em ${GREEN}$PROJ_ROOT/repository${NC}...\n" git clone https://github.com/antonieti/habit-tracking-repository.git $PROJ_ROOT/repository echo -e "${LINEBREAK}${BOLD}[${PURPLE}INFO${NC}] Iniciando processo de compilação com Maven (gerando JARs das bibliotecas e dependências) -----> Verifique o diretório ${GREEN}/home/${USER}/.m2/local_repo${NC}...\n\n" cd $PROJ_ROOT/entities mvn clean install && cp ./target/habittrackingentities-1.0-SNAPSHOT.jar /home/${USER}/.m2/local_repo cd $PROJ_ROOT/repository mvn clean install && cp ./target/habittrackingrepository-1.0-SNAPSHOT.jar /home/${USER}/.m2/local_repo echo -e "${LINEBREAK}Copiando dependências geradas para o diretório de libs do projeto: Verificar o diretório${LINEBREAK}\t${GREEN}$PROJ_ROOT/habitTracking_app/app/libs${NC}${LINEBREAK}após finalização do processo${LINEBREAK}\t\t\t\e[3;96mMay the Force be with you!\e[0m" mkdir -p $PROJ_ROOT/habitTracking_app/app/libs/ && cp -r /home/${USER}/.m2/local_repo/* $PROJ_ROOT/habitTracking_app/app/libs/
a2acdb78597f27773a0d077dfcf6574d4c3a7f69
[ "Markdown", "Shell" ]
2
Markdown
antonieti/build_habittracking
0aff9942dc5733b9d1947b63744d7ee38ad698bc
af53d35bb0bed76672864cb582cd7598769eb8b7
refs/heads/master
<file_sep>import os def isInt(x): try: int(x) except ValueError: return False return True def isCorrectInput(x): try: x = x.split(" ") for i in range(0, len(x)): if int(x[i]) != float(x[i]): return False x[i] = int(x[i]) except ValueError: return False return True def isComputableInput(F_x, modvalue): for i in range(0, len(F_x)): if F_x[i] >= modvalue: return False return True #gets a list with coefficients in descending order and adds/subtract def addPoly(p1, p2): res = [] maxsize = max(len(p1), len(p2)) p1 = [0 for i in range(0,maxsize-len(p1))] + p1 p2 = [0 for i in range(0,maxsize-len(p2))] + p2 for i in range(0, maxsize): res.append(p1[i] ^ p2[i]) return res, (p1,p2) def rembasic(n1, n2): res = n1 #print len(bin(n1)[2:]) #print len(bin(n2)[2:]) for i in range(len(bin(n1)[2:])-len(bin(n2)[2:]), -1, -1): res ^= n2 << i if res < n2: break #print bin(res) if len(bin(res)[2:])-1 >= len(bin(n2)[2:])-1: res ^= n2 #print bin(res) return res def multbasic(n1, n2, P_x): res = 0 sn2 = bin(n2)[2:] sn2 = sn2[::-1] for i in range(len(sn2)): res ^= int(sn2[i]) * (n1 << i) #print res if len(bin(res)[2:])-1 > len(bin(P_x)[2:])-2: res = rembasic(res, P_x) #print res return res def multPoly(p1, p2, P_x): P_x = [str(P_x[i]) for i in range(len(P_x))] resmatrix = [[0 for i in range((len(p1)-1)+(len(p2)-1)+1)] for i in range(len(p2))] for i in range(len(p2)): for j in range(len(p1)): resmatrix[i][-(j+1+i)] = multbasic(p1[-(j+1)], p2[-(i+1)], int('0b' + ''.join(P_x), 2)) res = [0 for i in range(len(resmatrix[0]))] #print res #print resmatrix for i in range(len(res)): for j in range(len(resmatrix)): res[i] ^= resmatrix[j][i] return res, resmatrix def divPoly(n1, n2, P_x): P_x = [str(P_x[i]) for i in range(len(P_x))] quot = [] res = n1 rem = [] div = n2 + [0 for i in range(len(res)-len(n2))] leading_co = res[0] rem.append(div) reslist = [] #print leading_co for i in range(len(n1)-len(n2)+1): reslist.append([(multbasic(leading_co,div[j],int('0b' + ''.join(P_x), 2))) for j in range(len(res))]) #print div quot.append(leading_co) rem.append([res[j] ^ (multbasic(leading_co,div[j],int('0b' + ''.join(P_x), 2))) for j in range(len(res))]) res = rem[-1] res = res[1:] div = n2 + [0 for i in range(len(res)-len(n2))] leading_co = res[0] #print leading_co if quot == []: quot = [0] return quot, res, rem, reslist def printResult(p1, p2, res, oper): os.system("cls") print "\nA(x):", for i in range(0, len(p1) - 1): if p1[i] > 0: if p1[i] > 1 and i < len(p1) - 2: print str(p1[i]) + "x^" + str(len(p1) - i - 1), elif i < len(p1) - 2: print "x^" + str(len(p1) - i - 1), if p1[i] > 1 and i == len(p1) - 1: print str(p1[i]) + "x", elif i == len(p1) - 2: print "x", if i < len(p1) - 1 and p1[i+1] > 0: print "+", if p1[-1] > 0: print str(p1[-1]) else: print "" print "B(x):", for i in range(0, len(p2) - 1): if p2[i] > 0: if p2[i] > 1 and i < len(p2) - 2: print str(p2[i]) + "x^" + str(len(p2) - i - 1), elif i < len(p2) - 2: print "x^" + str(len(p2) - i - 1), if p2[i] > 1 and i == len(p2) - 2: print str(p2[i]) + "x", elif i == len(p2) - 2: print "x", if i < len(p2) - 1 and p2[i+1] > 0: print "+", if p2[-1] > 0: print str(p2[-1]) else: print "" if oper == "/": print "A(x) " + oper + " B(x):", for i in range(0, len(res[0]) - 1): if res[0][i] > 0: if res[0][i] > 1 and i < len(res[0]) - 2: print str(res[0][i]) + "x^" + str(len(res[0]) - i - 1), elif i < len(res[0]) - 2: print "x^" + str(len(res[0]) - i - 1), if res[0][i] > 1 and i == len(res[0]) - 2: print str(res[0][i]) + "x", elif i == len(res[0]) - 2: print "x", if i < len(res[0]) - 1 and res[0][i+1] > 0: print "+", if res[0] == [0]: print "0" elif res[0][-1] > 0: print str(res[0][-1]) else: print "" print "Remainder:", for i in range(0, len(res[1]) - 1): if res[1][i] > 0: if res[1][i] > 1 and i < len(res[1]) - 2: print str(res[1][i]) + "x^" + str(len(res[1]) - i - 1), elif i < len(res[1]) - 2: print "x^" + str(len(res[1]) - i - 1), if res[1][i] > 1 and i == len(res[1]) - 2: print str(res[1][i]) + "x", elif i == len(res[1]) - 2: print "x", if i < len(res[1]) - 1 and res[1][i+1] > 0: print "+", if res[1][-1] > 0: print str(res[1][-1]) else: print "" print "------------------------------------------------------------------------" print "Solution in detail:\n" print " ", for j in range(len(p1)-len(res[0])): print ' ', for j in res[0]: print j, print "\n-------------" print " ", for i in p1: print i, print " = A\nXOR", for i in range(min(len(res[2]), len(res[3]))): if i > 0: print " ", for j in range(len(p1)-len(res[2][i])): print 0, for j in res[2][i]: print j, print " = A\nXOR", for j in range(len(p1)-len(res[3][i])): print 0, for j in res[3][i]: print j, print " = B * " + str(res[0][i]) + "x^" + str(min(len(res[2]), len(res[3]))-i-1) print "-------------" print " ", for j in range(len(p1)-len(res[1])): print ' ', for j in res[1]: print j, print " = Remainder" else: print "A(x) " + oper + " B(x):", for i in range(0, len(res[0]) - 1): if res[0][i] > 0: if res[0][i] > 1 and i < len(res[0]) - 2: print str(res[0][i]) + "x^" + str(len(res[0]) - i - 1), elif i < len(res[0]) - 2: print "x^" + str(len(res[0]) - i - 1), if res[0][i] > 1 and i == len(res[0]) - 2: print str(res[0][i]) + "x", elif i == len(res[0]) - 2: print "x", if i < len(res[0]) - 1 and res[0][i+1] > 0: print "+", if res[0][-1] > 0: print str(res[0][-1]) else: print "" if oper == "*": print "------------------------------------------------------------------------" print "Solution in detail:\n" for j in range(len(res[0])-len(p1)): print ' ', for i in p1: print i, print "" print "x", for j in range(len(res[0])-len(p2)-1): print ' ', for i in p2: print i, print "" print "-" * (len(res[0])*2) hasLeading = False for i in res[1]: hasLeading = False for j in i: if j != 0: hasLeading = True if not hasLeading: print ' ', else: print j, print "" print "-" * (len(res[0])*2) for i in res[0]: print i, print "" if oper == "+" or oper == "-": print "------------------------------------------------------------------------" print "Solution in detail:\n" for j in range(len(res[0])-len(p1)+1): print ' ', for i in p1: print i, print "" print oper, for j in range(len(res[0])-len(p2)): print ' ', for i in p2: print i, print "" print "", print "-" * (len(res[0])*2) print " ", for i in res[0]: print i, print "" print "" os.system("pause") A_x = "" B_x = "" P_x = "" while not isCorrectInput(A_x): os.system("cls") A_x = raw_input("\nEnter coefficients for A(x), separated by a space\nEx. x^4 + x + 1 -> 1 0 0 1 1\n:: ") while not isCorrectInput(B_x): os.system("cls") B_x = raw_input("\nEnter coefficients for B(x), separated by a space\nEx. x^4 + x + 1 -> 1 0 0 1 1\n:: ") while not isCorrectInput(P_x): os.system("cls") P_x = raw_input("\nEnter coefficients for P(x), separated by a space\nEx. x^4 + x + 1 -> 1 0 0 1 1\n:: ") A_x = A_x.split(' ') B_x = B_x.split(' ') P_x = P_x.split(' ') A_x = [int(i) for i in A_x] B_x = [int(i) for i in B_x] P_x = [int(i) for i in P_x] GF_value = 2**(len(P_x)-1) os.system("cls") print "\nSelect an operation:\n" print "1 - A(x) + B(x)" print "2 - A(x) - B(x)" print "3 - A(x) * B(x)" print "4 - A(x) / B(x)" print "" selection = 0 str_inp = "" while selection < 1 or selection > 4: while not isInt(str_inp): str_inp = raw_input(":: ") selection = int(str_inp) str_inp = "" if isComputableInput(A_x, GF_value) and isComputableInput(B_x, GF_value): if selection == 1: printResult(A_x, B_x, addPoly(A_x, B_x), "+") if selection == 2: printResult(A_x, B_x, addPoly(A_x, B_x), "-") if selection == 3: printResult(A_x, B_x, multPoly(A_x, B_x, P_x), "*") if selection == 4: printResult(A_x, B_x, divPoly(A_x, B_x, P_x), "/") else: print "\nCoefficient values for A(x) and B(x) must be less than " + str(GF_value) + "."
d26da4b60d447db8b5137c91c29623a70a021c19
[ "Python" ]
1
Python
pogirae/FiniteFields
1fbe7528216dd659a0656a02ee62d603db0d6bfa
28dd08c21ea51634a6f211b387750da43975f718
refs/heads/master
<repo_name>wgimson/Treeme<file_sep>/src/pages/hello-treeme/hello-treeme.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; /** * Generated class for the HelloTreemePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ // @IonicPage() @Component({ selector: 'page-hello-treeme', templateUrl: 'hello-treeme.html', }) export class HelloTreemePage { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad HelloTreemePage'); } }
f781c6701f1c09e8d92ef625028611186bfe26c6
[ "TypeScript" ]
1
TypeScript
wgimson/Treeme
9df37b25c3421977393ba6da0fe67fd66decd899
ebc9fdbd3e7d88a2eb42bff095c7831d47dc07a0
refs/heads/master
<repo_name>jiaziang/MyAlarm<file_sep>/src/com/jiaziang8/alarm/service/Contacts.java package com.jiaziang8.alarm.service; import java.io.InputStream; import java.util.ArrayList; import com.jeremyfeinstein.slidingmenu.example.R; import com.jiaziang8.alarm.util.Constants; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Photo; import android.text.TextUtils; import android.util.Log; public class Contacts { Context mContext = null; private static final String[] PHONES_PROJECTION = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID }; /** 联系人显示名称 **/ private static final int PHONES_DISPLAY_NAME_INDEX = 0; /** 电话号码 **/ private static final int PHONES_NUMBER_INDEX = 1; /** 头像ID **/ private static final int PHONES_PHOTO_ID_INDEX = 2; /** 联系人的ID **/ private static final int PHONES_CONTACT_ID_INDEX = 3; /** 联系人名称 **/ public static ArrayList<String> mContactsName = new ArrayList<String>(); /** 联系人号码 **/ public static ArrayList<String> mContactsNumber = new ArrayList<String>(); /** 联系人头像 **/ public static ArrayList<Bitmap> mContactsPhonto = new ArrayList<Bitmap>(); public static Contacts instance; public Contacts(Context context){ this.mContext = context; instance = this; } public void getPhoneContacts() { ContentResolver resolver = mContext.getContentResolver(); Cursor phoneCursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null); if (phoneCursor != null) { while (phoneCursor.moveToNext()) { String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX); phoneNumber = phoneNumber.replaceAll(" ", ""); if(phoneNumber.indexOf("+86")==0){ phoneNumber = phoneNumber.substring(3); } if (TextUtils.isEmpty(phoneNumber) || isExited(phoneNumber)) continue; String contactName = phoneCursor .getString(PHONES_DISPLAY_NAME_INDEX); Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX); Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX); Bitmap contactPhoto = null; if (photoid > 0) { Uri uri = ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, contactid); InputStream input = ContactsContract.Contacts .openContactPhotoInputStream(resolver, uri); contactPhoto = BitmapFactory.decodeStream(input); } else { contactPhoto = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.contact_photo); mContactsName.add(contactName); mContactsNumber.add(phoneNumber); mContactsPhonto.add(contactPhoto); } } if (Build.VERSION.SDK_INT > 14) { phoneCursor.close(); } } } private boolean isExited(String phonenumber) { for (String number : mContactsNumber) { if (number.equals(phonenumber)) { return true; } } return false; } public static String getNamaByNumber(String number){ int i = 0; for (String theNumber:mContactsNumber){ Log.v(Constants.LOG_TAG, "number is "+theNumber); Log.v(Constants.LOG_TAG, "name is"+mContactsName.get(i)); if(number.trim().equals(theNumber.trim().replaceAll(" ", ""))||("+86"+number.trim()).equals(theNumber.trim().replaceAll(" ", ""))){ return mContactsName.get(i); } i++; } return number; } } <file_sep>/src/com/jeremyfeinstein/slidingmenu/example/SmsConfirmActivity.java package com.jeremyfeinstein.slidingmenu.example; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import com.jiaziang8.alarm.service.MyService; import com.jiaziang8.alarm.util.Constants; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class SmsConfirmActivity extends Activity { //private static final String ServletUrl = Constants.url+"/AlarmServer/CheckServlet"; private static final int REGIST_SUCCESS = 1; private static final int REGIST_FAILER = 0; String accountString ; TextView info; EditText checknumber; Button regetButton; Button registButton; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg){ int time = msg.what; if (time>0){ regetButton.setText("重新获取验证码("+time+"s)"); } else { regetButton.setEnabled(true); regetButton.setText("重新获取验证码"); } } }; private Handler uIHandler = new Handler(){ @Override public void handleMessage(Message msg){ switch (msg.what) { case REGIST_SUCCESS: Toast.makeText(SmsConfirmActivity.this, "注册成功!", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("account", accountString); intent.putExtras(bundle); intent.setClass(SmsConfirmActivity.this,ViewPagerActivity.class); startActivity(intent); SmsConfirmActivity.this.finish(); break; case REGIST_FAILER: Toast.makeText(SmsConfirmActivity.this,"验证码错误~" ,Toast.LENGTH_SHORT).show(); default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sms_confirm); Intent intent = this.getIntent(); Bundle bundle = intent.getExtras(); if(bundle!=null){ accountString = bundle.getString("account"); } info = (TextView)this.findViewById(R.id.info); checknumber = (EditText)this.findViewById(R.id.checknumber); regetButton = (Button)this.findViewById(R.id.reget); registButton = (Button)this.findViewById(R.id.regist); info.setText("已经向"+accountString+"发送短信"); regetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //reget_checknumber(); regetButton.setEnabled(false); new timeThread().start(); } }); registButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { submit(); } }).start(); } }); new timeThread().start(); } private void submit(){ HttpPost post = new HttpPost(MyService.CHECKURL); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("username", accountString)); param.add(new BasicNameValuePair("checknumber", checknumber.getText().toString())); try { post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(post); if(response.getStatusLine().getStatusCode()==201){ Message msg= new Message(); msg.what=REGIST_SUCCESS; uIHandler.sendMessage(msg); } if(response.getStatusLine().getStatusCode()==202){ Message msg = new Message(); msg.what = REGIST_FAILER; uIHandler.sendMessage(msg); } } catch (Exception e) { } } private class timeThread extends Thread{ private int time = 60; @Override public void run(){ while(time>-1){ Message msg = new Message(); msg.what = time; handler.sendMessage(msg); time --; try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } } } @Override public boolean onKeyDown(int keyCode,KeyEvent event){ if(keyCode ==KeyEvent.KEYCODE_BACK){ AlertDialog isExit = new AlertDialog.Builder(this).create(); isExit.setTitle("提示?"); isExit.setMessage("放弃本次注册?"); isExit.setButton(AlertDialog.BUTTON_POSITIVE,"确认", listener); isExit.setButton(AlertDialog.BUTTON_NEGATIVE,"取消", listener); isExit.show(); } return false; } DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case AlertDialog.BUTTON_POSITIVE: SmsConfirmActivity.this.finish(); break; case AlertDialog.BUTTON_NEGATIVE: break; default: break; } } }; } <file_sep>/src/com/jeremyfeinstein/slidingmenu/example/SetingFragment.java package com.jeremyfeinstein.slidingmenu.example; import java.io.File; import java.io.IOException; import com.jiaziang8.alarm.service.MyService; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.RelativeLayout; public class SetingFragment extends Fragment { private RelativeLayout homepageRelativeLayout; private RelativeLayout notificationTextView; private RelativeLayout reviewRelativeLayout; private RelativeLayout settingsRelativeLayout; private ImageView userheadImageView; private File cache; public static Activity instance = null; public static Handler handler; public static final int REFRESHIMAGE = 1; @Override public void onCreate(Bundle savedInstance) { super.onCreate(savedInstance); instance = getActivity(); cache = new File(Environment.getExternalStorageDirectory(), "MyRecord/cache"); if (!cache.exists()) { cache.mkdirs(); } handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case REFRESHIMAGE: refreshUserHead(); break; default: break; } } }; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.settings, null); notificationTextView = (RelativeLayout) view .findViewById(R.id.notification); reviewRelativeLayout = (RelativeLayout) view.findViewById(R.id.review); settingsRelativeLayout = (RelativeLayout) view .findViewById(R.id.setting); userheadImageView = (ImageView) view.findViewById(R.id.setting_head); homepageRelativeLayout = (RelativeLayout) view .findViewById(R.id.firstpage); homepageRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { ViewPagerActivity.changeToHomepage(); try { ViewPagerActivity.isFROMSETTTING = true; Runtime runtime = Runtime.getRuntime(); runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK); } catch (IOException e) { Log.e("Exception when doBack", e.toString()); } } }); notificationTextView.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("account", ViewPagerActivity.account); bundle.putBoolean("hasMainActivity", true); intent.putExtras(bundle); intent.setClass(getActivity(), NotificationActivity.class); startActivity(intent); } }); reviewRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("account", ViewPagerActivity.account); bundle.putBoolean("hasMainActivity", true); intent.putExtras(bundle); intent.setClass(getActivity(), ReviewActivity.class); startActivity(intent); } }); settingsRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("account", ViewPagerActivity.account); intent.putExtras(bundle); intent.setClass(getActivity(), SettingActivity.class); startActivity(intent); } }); userheadImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("account", ViewPagerActivity.account); intent.putExtras(bundle); intent.setClass(getActivity(), SettingActivity.class); startActivity(intent); } }); asyncloadImage(userheadImageView); return view; } private void asyncloadImage(ImageView imageView) { MyService imageMyService = new MyService(); AsyncImageTask task = new AsyncImageTask(imageMyService, imageView); task.execute(ViewPagerActivity.account); } private final class AsyncImageTask extends AsyncTask<String, Integer, Uri> { private MyService service; private ImageView imageView; public AsyncImageTask(MyService myService, ImageView imageView) { this.service = myService; this.imageView = imageView; } @Override protected Uri doInBackground(String... params) { try { String path = service.getHeadPathByAccount(params[0]); if (path.equals("")) return null; path = MyService.GETHEADURL + path.substring(path.lastIndexOf("/")); return service.getImageURI(path, cache); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Uri result) { super.onPostExecute(result); if (imageView != null && result != null) { imageView.setImageURI(result); } } } public static Handler getHandler() { return handler; } public void refreshUserHead() { asyncloadImage(userheadImageView); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } } <file_sep>/src/com/jeremyfeinstein/slidingmenu/example/ContactsActivity.java package com.jeremyfeinstein.slidingmenu.example; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.TreeSet; import com.jiaziang8.alarm.object.ContactPeople; import com.jiaziang8.alarm.service.Contacts; import com.jiaziang8.alarm.ui.AddFriendOnClickListener; import com.jiaziang8.alarm.ui.MyButton; import com.jiaziang8.alarm.util.StringHelper; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; public class ContactsActivity extends Activity { private HashMap<String, Integer> selector;// 存放含有索引字母的位置 private LinearLayout layoutIndex; Context mContext = null; Contacts contacts; // 记录联系人信息的类 ListView mListView = null; private List<ContactPeople> peoples = null; private List<ContactPeople> newPeoples = new ArrayList<ContactPeople>(); private TextView tv_show; private String[] indexStr = { "#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; MyListAdapter mAdapter = null; private int height;// 字体高度 private boolean flag = false; public static String account = ""; public static Handler handler; private List<HashMap<String, Object>> mData ; private RelativeLayout backRelativeLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.friend_list_main); mContext = this; if(ViewPagerActivity.contacts!=null){ ViewPagerActivity.contacts.getPhoneContacts(); }else{ contacts = new Contacts(getApplicationContext()); contacts.getPhoneContacts(); } Intent intent = getIntent(); Bundle bundle = intent.getExtras(); account = bundle.getString("account"); layoutIndex = (LinearLayout) this.findViewById(R.id.layout); layoutIndex.setBackgroundColor(Color.parseColor("#00ffffff")); mListView = (ListView) findViewById(R.id.listView); tv_show = (TextView) findViewById(R.id.tv); tv_show.setVisibility(View.GONE); backRelativeLayout = (RelativeLayout)this.findViewById(R.id.back_layout); backRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { try { Runtime runtime = Runtime.getRuntime(); runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK); } catch (IOException e) { Log.e("Exception when doBack", e.toString()); } } }); mData = BaseActivity.getData(); setData(); String[] allNames = sortIndex(peoples); sortList(allNames); selector = new HashMap<String, Integer>(); for (int j = 0; j < indexStr.length; j++) { for (int i = 0; i < newPeoples.size(); i++) { if (newPeoples.get(i).getName().equals(indexStr[j])) { selector.put(indexStr[j], i); } } } mAdapter = new MyListAdapter(this, newPeoples); mListView.setAdapter(mAdapter); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { } }); handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: Toast.makeText(ContactsActivity.this, "请求已发送~!", Toast.LENGTH_LONG).show(); break; case 0: Toast.makeText(ContactsActivity.this, "添加好友失败~", Toast.LENGTH_LONG).show(); break; case 2: Toast.makeText(ContactsActivity.this, "该好友已添加过~", Toast.LENGTH_LONG).show(); default: break; } } }; } @Override public void onWindowFocusChanged(boolean hasFocus) { // 在oncreate里面执行下面的代码没反应,因为oncreate里面得到的getHeight=0 if (!flag) {// 这里为什么要设置个flag进行标记,我这里不先告诉你们,请读者研究,因为这对你们以后的开发有好处 height = layoutIndex.getMeasuredHeight() / indexStr.length; getIndexView(); flag = true; } } //滑动右侧拼音索引 public void getIndexView(){ LinearLayout.LayoutParams params = new LayoutParams( LayoutParams.WRAP_CONTENT, height); for (int i = 0; i < indexStr.length; i++) { final TextView tv = new TextView(this); tv.setLayoutParams(params); tv.setText(indexStr[i]); tv.setPadding(10, 0, 10, 0); layoutIndex.addView(tv); layoutIndex.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { float y = event.getY(); int index = (int) (y / height); if (index > -1 && index < indexStr.length) {// 防止越界 String key = indexStr[index]; if (selector.containsKey(key)) { int pos = selector.get(key); if (mListView.getHeaderViewsCount() > 0) {// 防止ListView有标题栏,本例中没有。 mListView.setSelectionFromTop( pos + mListView.getHeaderViewsCount(), 0); } else { mListView.setSelectionFromTop(pos, 0);// 滑动到第一项 } tv_show.setVisibility(View.VISIBLE); tv_show.setText(indexStr[index]); } } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: layoutIndex.setBackgroundColor(Color .parseColor("#606060")); break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: layoutIndex.setBackgroundColor(Color .parseColor("#00ffffff")); tv_show.setVisibility(View.GONE); break; } return true; } }); } } //把people对象按顺序加进newPeople private void sortList(String[] allNames) { for (int i = 0; i < allNames.length; i++) { if (allNames[i].length() != 1) { for (int j = 0; j < peoples.size(); j++) { if (allNames[i].substring(0,allNames[i].length()-1).equals(peoples.get(j).getPinYinName())) { ContactPeople p = new ContactPeople("@"+peoples.get(j) .getName(), peoples.get(j).getPinYinName(),peoples.get(j).getNumber()); newPeoples.add(p); } } } else { newPeoples.add(new ContactPeople(allNames[i])); } } //Log.v("Alarm", "newpeople:"+newPeoples.size()); } public String[] sortIndex(List<ContactPeople> persons) { TreeSet<String> set = new TreeSet<String>(); for (ContactPeople people : persons) { set.add(StringHelper.getPinYinHeadChar(people.getName()).substring( 0, 1)); } String[] names = new String[persons.size() + set.size()]; int i = 0; for (String string : set) { names[i] = string; i++; } String[] pinYinNames = new String[persons.size()]; for (int j = 0; j < persons.size(); j++) { persons.get(j).setPinYinName( StringHelper .getPingYin(persons.get(j).getName().toString())); pinYinNames[j] = StringHelper.getPingYin(persons.get(j).getName() .toString())+"@"; } System.arraycopy(pinYinNames, 0, names, set.size(), pinYinNames.length); Arrays.sort(names, String.CASE_INSENSITIVE_ORDER); //Log.v("Alarm", "names:"+names.length); return names; } public void setData() { peoples = new ArrayList<ContactPeople>(); int i=0; for (String name : Contacts.mContactsName) { ContactPeople people = new ContactPeople(name); people.setNumber(Contacts.mContactsNumber.get(i)); peoples.add(people); i++; } //Log.v("Alarm", peoples.size()+""); } class MyListAdapter extends BaseAdapter { // Contacts contacts; private List<ContactPeople> list; private Context context; private ViewHolder viewHolder; public MyListAdapter(Context context, List<ContactPeople> peoples) { this.context = context; this.list = peoples; } @Override public int getCount() { return list.size(); } @Override public boolean areAllItemsEnabled() { return false; } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public boolean isEnabled(int position) { // TODO Auto-generated method stub if (list.get(position).getName().length() == 1)// 如果是字母索引 return false;// 表示不能点击 return super.isEnabled(position); } @Override public View getView(int position, View convertView, ViewGroup parent) { boolean isAdded = false; String item = list.get(position).getName(); String number = list.get(position).getNumber(); viewHolder = new ViewHolder(); if (item.length() == 1) { convertView = LayoutInflater.from(context).inflate(R.layout.index, null); viewHolder.indexTv = (TextView) convertView .findViewById(R.id.indexTv); viewHolder.indexTv.setText(list.get(position).getName()); } else { convertView = LayoutInflater.from(context).inflate(R.layout.item, null); viewHolder.itemTv = (TextView) convertView .findViewById(R.id.itemTv); for(int i = 0;i<mData.size();i++){ if(mData.get(i).get("number").equals(number)){ isAdded = true; break; } } if(!isAdded){ viewHolder.myButton = (MyButton)convertView.findViewById(R.id.add_friend); viewHolder.myButton.setHandler(handler); viewHolder.myButton.setFriend(number); viewHolder.myButton.setname(item.substring(1)); viewHolder.myButton.setOnClickListener(AddFriendOnClickListener .getAddFriendOnClickListenerInstance()); }else{ viewHolder.myButton = (MyButton)convertView.findViewById(R.id.add_friend); viewHolder.myButton.setEnabled(false); viewHolder.myButton.setTextColor(getResources().getColor(R.color.black)); viewHolder.myButton.setText("已添加"); } viewHolder.itemTv.setText(list.get(position).getName().substring(1)); } return convertView; } private class ViewHolder { private TextView indexTv; private TextView itemTv; private MyButton myButton; } } } <file_sep>/src/com/jeremyfeinstein/slidingmenu/example/FriendListFragment.java package com.jeremyfeinstein.slidingmenu.example; import java.io.File; import java.util.HashMap; import java.util.List; import com.jiaziang8.alarm.service.MyService; import com.jiaziang8.alarm.ui.MyButton; import com.jiaziang8.alarm.ui.MyOnClickListener; import com.jiaziang8.alarm.util.Constants; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class FriendListFragment extends Fragment { String account = ""; private static final int LIST_OK = 1; private static final int DELETE_OK = 2; private static final int REFRESH_DATA = 3; private ListView friendList; private static List<HashMap<String, Object>> mData; private File cache; private Button addfriend; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case LIST_OK: MyAdapter adapter = new MyAdapter(getActivity()); friendList.setAdapter(adapter); adapter.notifyDataSetChanged(); // addfriend.setEnabled(true); break; case DELETE_OK: Toast.makeText(getActivity(), "删除好友成功~", Toast.LENGTH_SHORT) .show(); break; case REFRESH_DATA: // addfriend.setEnabled(false); refreshData(); break; default: break; } } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_friends_list, null); account = ViewPagerActivity.account; cache = new File(Environment.getExternalStorageDirectory(), "MyRecord/cache"); if (!cache.exists()) { cache.mkdirs(); } friendList = (ListView) view.findViewById(R.id.friends_listview); /* * addfriend = (Button)view.findViewById(R.id.addfriend); * addfriend.setEnabled(false); addfriend.setOnClickListener(new * View.OnClickListener() { * * @Override public void onClick(View arg0) { Intent add_friendIntent = * new Intent(); Bundle bundle = new Bundle(); * bundle.putString("account", account); * add_friendIntent.setClass(getActivity(), ContactsActivity.class); * add_friendIntent.putExtras(bundle); startActivity(add_friendIntent); * } }); */ new Thread(new Runnable() { @Override public void run() { mData = MyService.getData(account); Message msg = new Message(); //Log.v(Constants.LOG_TAG, "mData is" + mData); msg.what = LIST_OK; handler.sendMessage(msg); } }).start(); return view; } public class MyAdapter extends BaseAdapter { private LayoutInflater mInflater; public MyAdapter(Context context) { this.mInflater = LayoutInflater.from(context); } @Override public int getCount() { return mData.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) convertView = mInflater .inflate(R.layout.friend_list_item, null); TextView nameTextView = (TextView) convertView .findViewById(R.id.name); TextView numberTextView = (TextView) convertView .findViewById(R.id.number); ImageView uerheadImageView = (ImageView) convertView .findViewById(R.id.friend_head); MyButton addthis = (MyButton) convertView .findViewById(R.id.addthis); nameTextView.setText(mData.get(position).get("name").toString()); numberTextView .setText(mData.get(position).get("number").toString()); addthis.setIndex(position); String name = mData.get(position).get("name").toString(); addthis.setname(name); addthis.setHandler(handler); addthis.setFriend(mData.get(position).get("number").toString()); addthis.setAcount(ViewPagerActivity.account); addthis.setOnClickListener(MyOnClickListener.getInstance()); String pathString = mData.get(position).get("path").toString(); asyncloadImage(uerheadImageView, pathString); return convertView; } private void asyncloadImage(ImageView imageView, String path) { MyService imageMyService = new MyService(); AsyncImageTask task = new AsyncImageTask(imageMyService, imageView); task.execute(path); } private final class AsyncImageTask extends AsyncTask<String, Integer, Uri> { private MyService service; private ImageView imageView; public AsyncImageTask(MyService myService, ImageView imageView) { this.service = myService; this.imageView = imageView; } @Override protected Uri doInBackground(String... params) { try { String path = params[0]; if (path.equals("")) return null; path = MyService.GETHEADURL + path.substring(path.lastIndexOf("/")); return service.getImageURI(path, cache); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Uri result) { super.onPostExecute(result); if (imageView != null && result != null) { imageView.setImageURI(result); } } } } public void refreshData() { new Thread(new Runnable() { @Override public void run() { mData = MyService.getData(account); Message msg = new Message(); msg.what = LIST_OK; handler.sendMessage(msg); } }).start(); } public static List<HashMap<String, Object>> getData() { return mData; } public Handler getHandler() { return handler; } } <file_sep>/src/com/jiaziang8/alarm/object/PushObject.java package com.jiaziang8.alarm.object; public class PushObject { private String pushMessage; public PushObject(String pushMessage){ this.pushMessage = pushMessage; } public String getPushmessage(){ return pushMessage; } public void setPushMessage(String pushMessage){ this.pushMessage = pushMessage; } } <file_sep>/src/com/jiaziang8/alarm/ui/NotificationButton.java package com.jiaziang8.alarm.ui; import android.content.Context; import android.os.Handler; import android.util.AttributeSet; import android.widget.Button; public class NotificationButton extends Button { private int id ; private String account; private String name; private String selfAccount; private int mDays; private int mHour; private int mMinute; private String filename; private String time; private String wordsToSay; private Handler handler; public NotificationButton(Context context) { super(context); } public NotificationButton(Context context, AttributeSet aSet) { super(context, aSet); } public NotificationButton(Context context, AttributeSet aSet, int defStyle) { super(context, aSet, defStyle); } public void setId(int id){ this.id = id; } public int getId(){ return this.id; } public void setAccount(String account){ this.account = account; } public String getAccount(){ return this.account; } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } public void setselfAccount(String selfAccount){ this.selfAccount =selfAccount; } public String getselfAccount(){ return this.selfAccount; } public void setmDays(int mDays){ this.mDays = mDays; } public int getmDays(){ return this.mDays; } public void setmHour(int mHour){ this.mHour = mHour; } public int getmHour(){ return this.mHour; } public void setmMinute(int mMinute){ this.mMinute = mMinute; } public int getMinute(){ return this.mMinute; } public void setFilename(String filename){ this.filename = filename; } public String getFilename(){ return this.filename; } public void setTime(String time){ this.time = time; } public String getTime(){ return this.time; } public void setWordsToSay(String wordstosay){ this.wordsToSay = wordstosay; } public String getWordsToSay(){ return this.wordsToSay; } public void setHandler(Handler handler){ this.handler = handler; } public Handler getHandler(){ return this.handler; } } <file_sep>/src/com/jeremyfeinstein/slidingmenu/example/StartActivity.java package com.jeremyfeinstein.slidingmenu.example; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import cn.jpush.android.api.InstrumentedActivity; import cn.jpush.android.api.JPushInterface; import com.jiaziang8.alarm.util.Constants; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class StartActivity extends InstrumentedActivity { private EditText account; private EditText password; private Button connect; private Button regist; private static final String ServletUrl = Constants.url + "/AlarmServer2/LoginServlet"; private static String ACCOUNT = ""; private static final int MSG = 1; private static final int LOGIN_ERROR = 2; private static final int INTERNET_ERROR = 3; //public static Contacts contacts; private SharedPreferences sharedPreferences; private static Context startContext; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG: /* Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();*/ Intent contentIntent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("account", ACCOUNT); contentIntent.setClass(StartActivity.this, ViewPagerActivity.class); contentIntent.putExtras(bundle); startActivity(contentIntent); StartActivity.this.finish(); break; case LOGIN_ERROR: Toast.makeText(StartActivity.this, "账号或密码错误", Toast.LENGTH_SHORT).show();; break; case INTERNET_ERROR: Toast.makeText(StartActivity.this, "请检查网络连接是否正常", Toast.LENGTH_SHORT).show();; break; default: ; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); startContext = this; sharedPreferences = this.getSharedPreferences("userInfo", Context.MODE_WORLD_READABLE); //如果自动登陆 if (sharedPreferences.getBoolean("AUTO_LOGIN", false)) { new Thread(new Runnable() { @Override public void run() { String accountString = sharedPreferences.getString( "account", ""); String passwordString = sharedPreferences.getString( "password", ""); if (login(accountString, passwordString)) { if (JPushInterface .isPushStopped(getApplicationContext())) { JPushInterface.resumePush(getApplicationContext()); } if (ACCOUNT.indexOf("+86") == 0) { ACCOUNT = ACCOUNT.substring(3); } JPushInterface.setAlias(getApplicationContext(), ACCOUNT, null); Message msg = new Message(); msg.what = MSG; handler.sendMessage(msg); } else{ Message message = new Message(); message.what = INTERNET_ERROR; handler.sendMessage(message); } } }).start(); } else { setContentView(R.layout.activity_start); account = (EditText) this.findViewById(R.id.account); password = (EditText) this.findViewById(R.id.password); connect = (Button) this.findViewById(R.id.connect); regist = (Button) this.findViewById(R.id.regist); account.setText(sharedPreferences.getString("account", "")); account.setSelection(account.getText().length()); //点击登陆 connect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { public void run() { if (login(account.getText().toString(), password .getText().toString())) { Editor editor = sharedPreferences.edit(); editor.putString("account", account.getText() .toString()); editor.putString("password", password.getText() .toString()); editor.putBoolean("AUTO_LOGIN", true).commit(); if (JPushInterface .isPushStopped(getApplicationContext())) { JPushInterface .resumePush(getApplicationContext()); } if (ACCOUNT.indexOf("+86") == 0) { ACCOUNT = ACCOUNT.substring(3); } JPushInterface.setAlias( getApplicationContext(), ACCOUNT, null); Message msg = new Message(); msg.what = MSG; handler.sendMessage(msg); }else{ Message message = new Message(); message.what = LOGIN_ERROR; handler.sendMessage(message); } } }).start(); } }); //点击注册 regist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent registIntent = new Intent(); registIntent.setClass(StartActivity.this, RegistActivity.class); startActivity(registIntent); StartActivity.this.finish(); } }); } } public static boolean login(String account, String password) { HttpPost post = new HttpPost(ServletUrl); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("username", account)); param.add(new BasicNameValuePair("userpwd", password)); try { post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8)); try { HttpResponse response = new DefaultHttpClient().execute(post); //登陆成功 if (response.getStatusLine().getStatusCode() == 201) { ACCOUNT = account; return true; } else if(response.getStatusLine().getStatusCode() == 202){ return false; } return false; } catch (ClientProtocolException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); return false; } } @Override public void onResume() { super.onResume(); JPushInterface.onResume(this); } @Override public void onPause() { super.onPause(); JPushInterface.onPause(this); } } <file_sep>/src/com/jeremyfeinstein/slidingmenu/example/ProblemsActivity.java package com.jeremyfeinstein.slidingmenu.example; import java.io.IOException; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.widget.RelativeLayout; public class ProblemsActivity extends Activity{ private RelativeLayout backRelativeLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.problems); backRelativeLayout = (RelativeLayout)this.findViewById(R.id.back_layout); backRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { try { Runtime runtime = Runtime.getRuntime(); runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK); } catch (IOException e) { Log.e("Exception when doBack", e.toString()); } } }); } } <file_sep>/src/com/jiaziang8/alarm/ui/DeleteReviewListener.java package com.jiaziang8.alarm.ui; import com.jeremyfeinstein.slidingmenu.example.ReviewActivity; import com.jiaziang8.alarm.service.MyService; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; public class DeleteReviewListener implements OnClickListener{ public static DeleteReviewListener instance = null; Context context = null; public DeleteReviewListener(){ } public static DeleteReviewListener getInstance() { if (instance == null) { instance = new DeleteReviewListener(); } return instance; } @Override public void onClick(View view){ final View deleteReView = (deleteReviewButton)view ; context = ((deleteReviewButton)deleteReView).getContext(); final int id = ((deleteReviewButton)deleteReView).getId(); AlertDialog.Builder builder = new Builder(context); builder.setMessage("确认删除本记录?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new Thread(new Runnable() { @Override public void run() { boolean isDeleted = MyService.deleteReview(id); if(isDeleted){ Message message = new Message(); message.what = ReviewActivity.DELETE_OK; ((deleteReviewButton)deleteReView).getHandler().sendMessage(message); } } }).start(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); } } <file_sep>/src/com/example/soundtouchdemo/RecordingThread.java package com.example.soundtouchdemo; import java.util.concurrent.BlockingQueue; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.Handler; import android.util.Log; public class RecordingThread extends Thread { private static int FREQUENCY = 16000; private static int CHANNEL = AudioFormat.CHANNEL_IN_MONO; private static int ENCODING = AudioFormat.ENCODING_PCM_16BIT; private volatile boolean setToStopped = false; private Handler handler; private static int bufferSize = AudioRecord.getMinBufferSize(FREQUENCY, CHANNEL, ENCODING); private BlockingQueue<short[]> recordQueue; public RecordingThread(Handler handler, BlockingQueue<short[]> recordQueue){ this.handler = handler; this.recordQueue = recordQueue; } public void stopRecording(){ this.setToStopped = true; } @Override public void run(){ AudioRecord audioRecord = null; try { //Log.v("Alarm", "bufferLength:"+bufferSize); short[] buffer = new short[bufferSize]; //------1280 audioRecord = new AudioRecord( MediaRecorder.AudioSource.MIC, FREQUENCY, CHANNEL, ENCODING, bufferSize*2); int state = audioRecord.getState(); if (state == AudioRecord.STATE_INITIALIZED) { audioRecord.startRecording(); //shandler.obtainMessage(Settings.MSG_RECORDING_START).sendToTarget(); boolean flag = true; while (!setToStopped) { int len = audioRecord.read(buffer, 0, buffer.length); Log.v("Alarm", "hufferLength~~~~~~~~~~~~~"+buffer.length); // 去掉全0数据 if(flag){ double sum = 0.0; for(int i = 0; i < len; i++){ sum += buffer[i]; } if(sum == 0.0){ continue; }else{ flag = false; } } Log.v("Alarm", "len:"+len); short[] data = new short[len]; System.arraycopy(buffer, 0, data, 0, len); recordQueue.add(data); } //handler.sendEmptyMessage(Settings.MSG_RECORDING_STOP); audioRecord.stop(); } else { //handler.sendEmptyMessage(Settings.MSG_RECORDING_STATE_ERROR); } } catch (Exception e) { //handler.sendEmptyMessage(Settings.MSG_RECORDING_EXCEPTION); } finally { try { audioRecord.release(); audioRecord = null; //handler.sendEmptyMessage(Settings.MSG_RECORDING_RELEASE); } catch (Exception e) { } } } } <file_sep>/src/com/jiaziang8/alarm/service/MyReceiver.java package com.jiaziang8.alarm.service; import com.google.gson.Gson; import com.jeremyfeinstein.slidingmenu.example.NotificationActivity; import com.jeremyfeinstein.slidingmenu.example.ReviewActivity; import com.jiaziang8.alarm.object.AddFriendMessage; import com.jiaziang8.alarm.object.PushMessage; import com.jiaziang8.alarm.object.PushObject; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import cn.jpush.android.api.JPushInterface; public class MyReceiver extends BroadcastReceiver { private static final String TAG = "JPush"; private Gson gson; @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); gson = new Gson(); Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle)); if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) { String regId = bundle .getString(JPushInterface.EXTRA_REGISTRATION_ID); Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId); // send the Registration Id to your server... } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent .getAction())) { Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE)); // processCustomMessage(context, bundle); } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent .getAction())) { Log.d(TAG, "[MyReceiver] 接收到推送下来的通知"); int notifactionId = bundle .getInt(JPushInterface.EXTRA_NOTIFICATION_ID); Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId); } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent .getAction())) { Log.d(TAG, "[MyReceiver] 用户点击打开了通知"); String whatString = bundle.getString("cn.jpush.android.EXTRA"); PushObject pushObject = gson.fromJson(whatString, PushObject.class); Log.v("JPush", "whatString:"+whatString); String pushMessageString = pushObject.getPushmessage(); PushMessage pushMessage = gson.fromJson(pushMessageString, PushMessage.class); Log.v("JPush", pushMessage.toString()); if(pushMessage.getType().equals("add_friend")){ String message = pushMessage.message; AddFriendMessage addFriendMessage = gson.fromJson(message, AddFriendMessage.class); String user = addFriendMessage.user; String friend = addFriendMessage.friend; Intent intent2 = new Intent(); Bundle bundle2 = new Bundle(); bundle2.putString("account", friend); bundle2.putBoolean("hasMainActivity", false); intent2.putExtras(bundle2); intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent2.setClass(context, NotificationActivity.class); context.startActivity(intent2); Log.v("JPush", "user:"+user+" friend:"+friend); } else if(pushMessage.getType().equals("add_alarm")){ String message = pushMessage.message; AddFriendMessage addFriendMessage = gson.fromJson(message, AddFriendMessage.class); String user = addFriendMessage.user; String friend = addFriendMessage.friend; Intent intent3 = new Intent(); Bundle bundle3 = new Bundle(); bundle3.putString("account", friend); bundle3.putBoolean("hasMainActivity", false); intent3.putExtras(bundle3); intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent3.setClass(context, NotificationActivity.class); context.startActivity(intent3); }else if(pushMessage.getType().equals("accept_alarm")){ String message = pushMessage.message; AddFriendMessage addFriendMessage = gson.fromJson(message, AddFriendMessage.class); String user = addFriendMessage.user; String friend = addFriendMessage.friend; Intent intent4 = new Intent(); Bundle bundle4 = new Bundle(); bundle4.putString("account", user); bundle4.putBoolean("hasMainActivity", false); intent4.putExtras(bundle4); intent4.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent4.setClass(context, ReviewActivity.class); context.startActivity(intent4); } //Log.v("JPush", "user:"+userString+" friend:"+friendString); } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent .getAction())) { Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA)); // 在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的Activity, // 打开一个网页等.. } else { Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction()); } } // 打印所有的 intent extra 数据 private static String printBundle(Bundle bundle) { StringBuilder sb = new StringBuilder(); for (String key : bundle.keySet()) { if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) { sb.append("\nkey:" + key + ", value:" + bundle.getInt(key)); } else { sb.append("\nkey:" + key + ", value:" + bundle.getString(key)); } } return sb.toString(); } } <file_sep>/src/com/jeremyfeinstein/slidingmenu/example/SettingActivity.java package com.jeremyfeinstein.slidingmenu.example; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import org.apache.http.Header; import cn.jpush.android.api.JPushInterface; import com.jiaziang8.alarm.service.MyService; import com.jiaziang8.alarm.ui.SelectPicPopupWindow; import com.jiaziang8.alarm.util.Constants; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Bitmap; import android.media.AudioManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Message; import android.provider.MediaStore; import android.provider.Settings; import android.util.Base64; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Toast; public class SettingActivity extends Activity { private SharedPreferences sharedPreferences; private ImageView userheadImageView; private RelativeLayout imageRelativeLayout; private RelativeLayout problemRelativeLayout; private RelativeLayout aboutRelativeLayout; private CheckBox dontCheckBox; private Button exitButton; private RelativeLayout backRelativeLayout; // 自定义的弹出框类 SelectPicPopupWindow menuWindow; private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照 private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择 private static final int PHOTO_REQUEST_CUT = 3;// 结果 private Bitmap bitmap; private static final int ALARM_STREAM_TYPE_BIT = 1 << AudioManager.STREAM_ALARM; private File cache; /* 头像名称 */ private static final String PHOTO_FILE_NAME = "temp_photo.jpg"; private File tempFile; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.setting_content); sharedPreferences = getSharedPreferences("userInfo", Context.MODE_WORLD_READABLE); dontCheckBox = (CheckBox)this.findViewById(R.id.dont_onoff); userheadImageView = (ImageView) this.findViewById(R.id.user_head); imageRelativeLayout = (RelativeLayout)this.findViewById(R.id.head_layout); problemRelativeLayout = (RelativeLayout)this.findViewById(R.id.problem_layout); aboutRelativeLayout = (RelativeLayout)this.findViewById(R.id.about_layout); exitButton = (Button)this.findViewById(R.id.exit_button); cache = new File(Environment.getExternalStorageDirectory(), "MyRecord/cache"); if(!cache.exists()){ cache.mkdirs(); } backRelativeLayout = (RelativeLayout)this.findViewById(R.id.back_layout); backRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { try { Runtime runtime = Runtime.getRuntime(); runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK); } catch (IOException e) { Log.e("Exception when doBack", e.toString()); } } }); problemRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(); intent.setClass(getApplicationContext(), ProblemsActivity.class); startActivity(intent); } }); aboutRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(); intent.setClass(getApplicationContext(), AboutActivity.class); startActivity(intent); } }); imageRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // 实例化SelectPicPopupWindow menuWindow = new SelectPicPopupWindow(SettingActivity.this, itemsOnClick); // 显示窗口 menuWindow.showAtLocation( SettingActivity.this.findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置 } }); int ringerModeStreamTypes = Settings.System.getInt( getContentResolver(), Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); if((ringerModeStreamTypes&(~ALARM_STREAM_TYPE_BIT))==ringerModeStreamTypes){ dontCheckBox.setChecked(true); }else{ dontCheckBox.setChecked(false); } dontCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { int ringerwhat =Settings.System.getInt( getContentResolver(), Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); @Override public void onCheckedChanged(CompoundButton arg0, boolean ischecked) { if(ischecked){ ringerwhat &= ~ALARM_STREAM_TYPE_BIT; }else{ ringerwhat |= ALARM_STREAM_TYPE_BIT; } Settings.System.putInt(getContentResolver(), Settings.System.MODE_RINGER_STREAMS_AFFECTED, ringerwhat); } }); exitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Editor editor = sharedPreferences.edit(); editor.putBoolean("AUTO_LOGIN", false).commit(); JPushInterface.stopPush(getApplicationContext()); //停止推送服务 SettingActivity.this.finish(); SetingFragment.instance.finish(); } }); asyncloadImage(userheadImageView); } //为弹出窗口实现监听类 private OnClickListener itemsOnClick = new OnClickListener(){ public void onClick(View v) { menuWindow.dismiss(); switch (v.getId()) { case R.id.btn_take_photo: camera(); break; case R.id.btn_pick_photo: gallery(); break; default: break; } } }; /* * 从相册获取 */ public void gallery() { // 激活系统图库,选择一张图片 Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent, PHOTO_REQUEST_GALLERY); } /* * 从相机获取 */ public void camera() { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); // 判断存储卡是否可以用,可用进行存储 if (hasSdcard()) { intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment .getExternalStorageDirectory(), PHOTO_FILE_NAME))); } startActivityForResult(intent, PHOTO_REQUEST_CAMERA); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PHOTO_REQUEST_GALLERY) { if (data != null) { // 得到图片的全路径 Uri uri = data.getData(); crop(uri); } } else if (requestCode == PHOTO_REQUEST_CAMERA) { if (hasSdcard()) { tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME); crop(Uri.fromFile(tempFile)); } else { Toast.makeText(SettingActivity.this, "未找到存储卡,无法存储照片!", 0).show(); } } else if (requestCode == PHOTO_REQUEST_CUT) { try { bitmap = data.getParcelableExtra("data"); //this.userheadImageView.setImageBitmap(bitmap); //~~~~~~~~~~~~~~~ if(tempFile!=null){ boolean delete = tempFile.delete(); } upload(); } catch (Exception e) { e.printStackTrace(); } } super.onActivityResult(requestCode, resultCode, data); } /** * 剪切图片 * * @function: * @author:Jerry * @date:2013-12-30 * @param uri */ private void crop(Uri uri) { // 裁剪图片意图 Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); // 裁剪框的比例,1:1 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // 裁剪后输出图片的尺寸大小 intent.putExtra("outputX", 100); intent.putExtra("outputY", 100); intent.putExtra("scale", true); // 图片格式 intent.putExtra("outputFormat", "JPEG"); intent.putExtra("noFaceDetection", true);// 取消人脸识别 intent.putExtra("return-data", true);// true:不返回uri,false:返回uri startActivityForResult(intent, PHOTO_REQUEST_CUT); } private boolean hasSdcard() { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { return true; } else { return false; } } private void asyncloadImage(ImageView imageView){ MyService imageMyService = new MyService(); AsyncImageTask task = new AsyncImageTask(imageMyService, imageView); task.execute(ViewPagerActivity.account); } private final class AsyncImageTask extends AsyncTask<String, Integer, Uri>{ private MyService service; private ImageView imageView; public AsyncImageTask(MyService myService,ImageView imageView){ this.service = myService; this.imageView = imageView; } @Override protected Uri doInBackground(String... params){ try { String path = service.getHeadPathByAccount(params[0]); if(path.equals("")) return null; path = MyService.GETHEADURL+path.substring(path.lastIndexOf("/")); return service.getImageURI(path, cache); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Uri result){ super.onPostExecute(result); if(imageView!=null&&result!=null){ imageView.setImageURI(result); } } } /* * 上传图片 */ public void upload() { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 25, out); out.flush(); out.close(); byte[] buffer = out.toByteArray(); byte[] encode = Base64.encode(buffer, Base64.DEFAULT); String photo = new String(encode); RequestParams params = new RequestParams(); params.put("photo", photo); params.put("account", ViewPagerActivity.account); String url = MyService.HEADURL; AsyncHttpClient client = new AsyncHttpClient(); client.post(url, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { if (statusCode == 200) { Toast.makeText(SettingActivity.this, "头像上传成功!", 0) .show(); //通知主界面和本界面更新头像 Message message = new Message() ; message.what = SetingFragment.REFRESHIMAGE; SetingFragment.getHandler().sendMessage(message); asyncloadImage(userheadImageView); } else { Toast.makeText(SettingActivity.this, "网络访问异常,错误码:" + statusCode, 0).show(); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { Toast.makeText(SettingActivity.this, "网络访问异常,错误码 > " + statusCode, 0).show(); } }); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/README.md 一个给别人设置自己的语音闹钟的Android Project~ 添加变音功能哟~ <file_sep>/src/com/jiaziang8/alarm/service/MyService.java package com.jiaziang8.alarm.service; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import android.R.string; import android.net.Uri; import android.util.Log; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.jiaziang8.alarm.object.savedAlarmObject; import com.jiaziang8.alarm.util.Constants; import com.jiaziang8.alarm.util.MD5; public class MyService { public static final String FRIENDS_URL = Constants.url + "/AlarmServer2/GetFriendsServlet"; public static final String ADD_FRIEND_URL = Constants.url + "/AlarmServer2/AddFriendServlet"; public static final String NOTIFICATION_URL = Constants.url + "/AlarmServer2/NotificationServlet"; public static final String REALLYADDFRIEND_URL = Constants.url + "/AlarmServer2/ReallyAddFriendServlet"; public static final String REFUSEADDFRIEND_URL = Constants.url + "/AlarmServer2/RefuseAddFriendServlet"; public static final String REFUSEALARM_URL = Constants.url +"/AlarmServer2/RefuseAlarmServlet"; public static final String DELETEFRIEND_URL = Constants.url + "/AlarmServer2/DeleteFriendServlet"; public static final String CHANGESAVEDALARMSTATE = Constants.url + "/ChangeSavedAlarmStateServlet"; public static final String GETREVIEWITEMS = Constants.url + "/AlarmServer2/ReviewGetItemsServlet"; public static final String GETHEADPATH = Constants.url + "/AlarmServer2/GetHeadPathServlet"; public static final String DELETEREVIEW = Constants.url +"/AlarmServer2/DeleteReviewServlet"; public static final String HEADURL = Constants.url +"/AlarmServer2/UploadImgServlet"; public static final String UPLOADALARMURL = Constants.url +"/AlarmServer2/UploadServlet"; public static final String GETHEADURL = Constants.url +"/AlarmServer2/Head"; public static final String REGISTURL = Constants.url + "/AlarmServer2/RegistServlet"; public static final String DOWNURL = Constants.url + "/AlarmServer2/DownLoadServlet"; public static final String CHECKURL = Constants.url +"/AlarmServer2/CheckServlet"; public static final int COUNT = 10; //获取好友列表 public static List<HashMap<String, Object>> getData(String account) { ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>(); HttpPost post = new HttpPost(FRIENDS_URL); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("account", account)); try { post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(post); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); if (inputStream == null) { Log.v(Constants.LOG_TAG, "InputStream null!!~~~"); } String result = ConvertToString(inputStream); if (result.length() == 0) return list; result = result.substring(0, result.length() - 1); String[] friendsStrings = result.split(" "); for (String friendNumber : friendsStrings) { HashMap<String, Object> map2 = new HashMap<String, Object>(); String[] temStrings = friendNumber.split("@"); if(temStrings.length==1){ map2.put("path", ""); }else{ map2.put("path", temStrings[1]); } map2.put("number", temStrings[0]); String nameString = Contacts.getNamaByNumber(temStrings[0]); map2.put("name", nameString); list.add(map2); } return list; } else { return list; } } catch (Exception e) { e.printStackTrace(); return list; } } //获取通知列表 public static List<HashMap<String, Object>> getNotification(String account) { ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>(); HttpPost post = new HttpPost(NOTIFICATION_URL); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("account", account)); Gson gson = new Gson(); try { post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(post); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); if (inputStream == null) { Log.v(Constants.LOG_TAG, "InputStream null!!~~~"); } // 返回的数据 String result = ConvertToString(inputStream); ArrayList<savedAlarmObject> notificationList = gson.fromJson( result, new TypeToken<ArrayList<savedAlarmObject>>() { }.getType()); for (savedAlarmObject notificationObject : notificationList) { HashMap<String, Object> map2 = new HashMap<String, Object>(); map2.put("id", notificationObject.id); map2.put("account", notificationObject.account); String accountname = Contacts .getNamaByNumber(notificationObject.account); map2.put("friend", notificationObject.friend); map2.put("name", accountname); map2.put("mDays", notificationObject.mDays); map2.put("mHour", notificationObject.mHour); map2.put("mMinute", notificationObject.mMinute); map2.put("filename", notificationObject.filename); map2.put("time", notificationObject.time); map2.put("wordsToSay", notificationObject.wordsToSay); map2.put("path", notificationObject.path); list.add(map2); } return list; } else { return list; } } catch (Exception e) { e.printStackTrace(); return list; } } //获取日志列表 public static List<HashMap<String, Object>> getItems(int start, String account) { ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>(); HttpPost post = new HttpPost(GETREVIEWITEMS); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("account", account)); param.add(new BasicNameValuePair("start", String.valueOf(start))); Gson gson = new Gson(); try { post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(post); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); if (inputStream == null) { Log.v(Constants.LOG_TAG, "InputStream null!!~~~"); } // 返回的数据 String result = ConvertToString(inputStream); ArrayList<savedAlarmObject> notificationList = gson.fromJson( result, new TypeToken<ArrayList<savedAlarmObject>>() { }.getType()); for (savedAlarmObject notificationObject : notificationList) { HashMap<String, Object> map2 = new HashMap<String, Object>(); map2.put("id", notificationObject.id); map2.put("account", notificationObject.account); String accountname = Contacts .getNamaByNumber(notificationObject.account); map2.put("friend", notificationObject.friend); map2.put("name", accountname); map2.put("mDays", notificationObject.mDays); map2.put("mHour", notificationObject.mHour); map2.put("mMinute", notificationObject.mMinute); map2.put("filename", notificationObject.filename); map2.put("time", notificationObject.time); map2.put("wordsToSay", notificationObject.wordsToSay); list.add(map2); } return list; } else { return list; } } catch (Exception e) { e.printStackTrace(); return list; } } //添加好友请求 public static int addfriend(String user, String friend) { HttpPost post = new HttpPost(ADD_FRIEND_URL); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("user", user)); param.add(new BasicNameValuePair("friend", friend)); try { post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(post); if (response.getStatusLine().getStatusCode() == 200) { return 1; } else if (response.getStatusLine().getStatusCode() == 201) { return 0; } else { return 2; } } catch (Exception e) { e.printStackTrace(); return 0; } } //接受添加好友请求 添加好友 public static boolean reallyAddFriend(String user, String friend) { HttpPost post = new HttpPost(REALLYADDFRIEND_URL); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("user", user)); param.add(new BasicNameValuePair("friend", friend)); try { post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(post); if (response.getStatusLine().getStatusCode() == 200) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); return false; } } //拒绝添加好友 public static boolean refuseAddFriend(String user, String friend) { HttpPost post = new HttpPost(REFUSEADDFRIEND_URL); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("user", user)); param.add(new BasicNameValuePair("friend", friend)); try { post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(post); if (response.getStatusLine().getStatusCode() == 200) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); return false; } } public static boolean refuseAlarm(int id){ HttpPost post = new HttpPost(REFUSEALARM_URL); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> param = new ArrayList<NameValuePair>(); String idString = String.valueOf(id); param.add(new BasicNameValuePair("id", idString)); try { post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(post); if (response.getStatusLine().getStatusCode() == 200) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); return false; } } //删除好友 public static boolean deleteFriend(String user, String friend) { HttpPost post = new HttpPost(DELETEFRIEND_URL); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("user", user)); param.add(new BasicNameValuePair("friend", friend)); try { post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(post); if (response.getStatusLine().getStatusCode() == 200) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); return false; } } //删除日志 public static boolean deleteReview(int id){ HttpPost post = new HttpPost(DELETEREVIEW); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> param = new ArrayList<NameValuePair>(); String idString = String.valueOf(id); param.add(new BasicNameValuePair("id", idString)); try { post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(post); if (response.getStatusLine().getStatusCode() == 200) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); return false; } } //获取用户头像文件路径 public String getHeadPathByAccount(String account) { HttpPost post = new HttpPost(GETHEADPATH); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("account", account)); try { post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(post); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); String result = ConvertToString(inputStream); return result; } } catch (Exception e) { e.printStackTrace(); } return ""; } //获取图片Uri public Uri getImageURI(String path, File cache) throws Exception { String name = MD5.getMD5(path) + path.substring(path.lastIndexOf(".")); File file = new File(cache, name); if (file.exists()) { return Uri.fromFile(file); } else { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); conn.setDoInput(true); if (conn.getResponseCode() == 200) { InputStream is = conn.getInputStream(); FileOutputStream fos = new FileOutputStream(file); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } is.close(); fos.close(); // 返回一个URI对象 return Uri.fromFile(file); } } return null; } //Inputstream转String public static String ConvertToString(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder result = new StringBuilder(); String line = null; try { while ((line = bufferedReader.readLine()) != null && (!line.equals(""))) { result.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { inputStreamReader.close(); inputStream.close(); bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } return result.toString(); } } <file_sep>/src/com/jeremyfeinstein/slidingmenu/example/NotificationActivity.java package com.jeremyfeinstein.slidingmenu.example; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import cn.jpush.android.api.JPushInterface; import com.cn.daming.deskclock.Alarm.DaysOfWeek; import com.cn.daming.deskclock.SetAlarm; import com.jiaziang8.alarm.service.Contacts; import com.jiaziang8.alarm.service.MyService; import com.jiaziang8.alarm.ui.AcceptAddFriendListener; import com.jiaziang8.alarm.ui.AlarmDetailListener; import com.jiaziang8.alarm.ui.NotificationButton; import com.jiaziang8.alarm.ui.RefuseAddFriendListener; import com.jiaziang8.alarm.ui.RefuseAlarmListener; import com.jiaziang8.alarm.util.Constants; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; public class NotificationActivity extends Activity { static String account = ""; public static final int LIST_OK = 1; public static final int REFRESH_LIST = 2; public static final int DOWNLOAD_COMPLET = 3; public static final int FINISH_ACTIVITY = 4; private ListView notificatinoListView; private static List<HashMap<String, Object>> mData; private Myadapter myadapter; private boolean hasMainActivity; private SharedPreferences sharedPreferences; private Context context; private File cache; private Contacts contacts; // private ImageButton back_button; private RelativeLayout backRelativeLayout; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case LIST_OK: if (myadapter == null) { myadapter = new Myadapter(NotificationActivity.this); } notificatinoListView.setAdapter(myadapter); myadapter.notifyDataSetChanged(); break; case REFRESH_LIST: refreshNotification(); break; case DOWNLOAD_COMPLET: int mHour = msg.arg1; int mMunite = msg.arg2; DaysOfWeek daysOfWeek = (DaysOfWeek) msg.obj; SetAlarm.popAlarmSetToast(context, mHour, mMunite, daysOfWeek); // Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show(); break; case FINISH_ACTIVITY: if (!hasMainActivity) { Intent contentIntent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("account", account); contentIntent.setClass(NotificationActivity.this, ViewPagerActivity.class); contentIntent.putExtras(bundle); startActivity(contentIntent); } NotificationActivity.this.finish(); default: break; } } }; @Override public void onCreate(Bundle savedInstance) { super.onCreate(savedInstance); context = this; requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.notification); backRelativeLayout = (RelativeLayout) this .findViewById(R.id.back_layout); sharedPreferences = this.getSharedPreferences("userInfo", Context.MODE_WORLD_READABLE); Intent intent = getIntent(); Bundle bundle = intent.getExtras(); account = bundle.getString("account"); cache = new File(Environment.getExternalStorageDirectory(), "MyRecord/cache"); if (!cache.exists()) { cache.mkdirs(); } backRelativeLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { try { Runtime runtime = Runtime.getRuntime(); runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK); } catch (IOException e) { Log.e("Exception when doBack", e.toString()); } } }); // 判断由通知栏或者主界面进入 if (bundle.getBoolean("hasMainActivity") == true) { hasMainActivity = true; } else hasMainActivity = false; notificatinoListView = (ListView) this .findViewById(R.id.notification_listview); if (ViewPagerActivity.contacts != null) { ViewPagerActivity.contacts.getPhoneContacts(); } else { contacts = new Contacts(getApplicationContext()); contacts.getPhoneContacts(); } new Thread(new Runnable() { @Override public void run() { mData = MyService.getNotification(account); Message message = new Message(); message.what = LIST_OK; handler.sendMessage(message); } }).start(); } public class Myadapter extends BaseAdapter { private LayoutInflater mInflater; public Myadapter(Context context) { this.mInflater = LayoutInflater.from(context); } @Override public int getCount() { return mData.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { int id; String account; String name; String selfAccount; int mDays; int mHour; int mMinute; String filename; String time; String wordsToSay; String path; id = (int) mData.get(position).get("id"); mDays = (int) mData.get(position).get("mDays"); account = (String) mData.get(position).get("account"); selfAccount = (String) mData.get(position).get("friend"); name = (String) mData.get(position).get("name"); mHour = (int) mData.get(position).get("mHour"); mMinute = (int) mData.get(position).get("mMinute"); filename = (String) mData.get(position).get("filename"); time = (String) mData.get(position).get("time"); wordsToSay = (String) mData.get(position).get("wordsToSay"); path = (String) mData.get(position).get("path"); // 添加好友的请求 if (mDays == -1) { if (convertView == null) convertView = mInflater.inflate(R.layout.notification_item, null); TextView notificationTextView = (TextView) convertView .findViewById(R.id.notification_info); TextView notificationTextView2 = (TextView) convertView .findViewById(R.id.notification_text); TextView notificationtimeTextView = (TextView) convertView .findViewById(R.id.notification_time); NotificationButton refuseButton = (NotificationButton) convertView .findViewById(R.id.refuse_button); NotificationButton acceptButton = (NotificationButton) convertView .findViewById(R.id.accept_button); ImageView notification_headImageView = (ImageView) convertView .findViewById(R.id.notification_head); refuseButton.setId(id); refuseButton.setAccount(account); refuseButton.setName(name); refuseButton.setselfAccount(selfAccount); refuseButton.setmDays(mDays); refuseButton.setmHour(mHour); refuseButton.setmMinute(mMinute); refuseButton.setFilename(filename); refuseButton.setTime(time); refuseButton.setWordsToSay(wordsToSay); refuseButton.setHandler(handler); acceptButton.setId(id); acceptButton.setAccount(account); acceptButton.setName(name); acceptButton.setselfAccount(selfAccount); acceptButton.setmDays(mDays); acceptButton.setmHour(mHour); acceptButton.setmMinute(mMinute); acceptButton.setFilename(filename); acceptButton.setTime(time); acceptButton.setWordsToSay(wordsToSay); acceptButton.setHandler(handler); notificationtimeTextView.setText(time); notificationTextView.setText(name); notificationTextView2.setText("请求添加你为好友"); refuseButton.setOnClickListener(RefuseAddFriendListener .getInstance()); acceptButton.setOnClickListener(AcceptAddFriendListener .getInstance()); asyncloadImage(notification_headImageView, path); } else { //设置闹钟的请求 if (convertView == null) convertView = mInflater.inflate( R.layout.notification_alarm_item, null); TextView notificationTextView = (TextView) convertView .findViewById(R.id.notification_info); /* * TextView notificationTextView2 = (TextView)convertView * .findViewById(R.id.notification_text); */ TextView notificationtimeTextView = (TextView) convertView .findViewById(R.id.notification_time); TextView notificationAlarmTimeTextView = (TextView) convertView .findViewById(R.id.notification_alarm_time); TextView notificationRepeatInfoTextView = (TextView) convertView .findViewById(R.id.notification_repeat_info); NotificationButton refuseButton = (NotificationButton) convertView .findViewById(R.id.refuse_button); NotificationButton acceptButton = (NotificationButton) convertView .findViewById(R.id.accept_button); ImageView notification_headImageView = (ImageView) convertView .findViewById(R.id.notification_head); refuseButton.setId(id); refuseButton.setAccount(account); refuseButton.setName(name); refuseButton.setselfAccount(selfAccount); refuseButton.setmDays(mDays); refuseButton.setmHour(mHour); refuseButton.setmMinute(mMinute); refuseButton.setFilename(filename); refuseButton.setTime(time); refuseButton.setWordsToSay(wordsToSay); refuseButton.setHandler(handler); acceptButton.setId(id); acceptButton.setAccount(account); acceptButton.setName(name); acceptButton.setselfAccount(selfAccount); acceptButton.setmDays(mDays); acceptButton.setmHour(mHour); acceptButton.setmMinute(mMinute); acceptButton.setFilename(filename); acceptButton.setTime(time); acceptButton.setWordsToSay(wordsToSay); acceptButton.setHandler(handler); notificationtimeTextView.setText(time); notificationTextView.setText(name + "给你设置了一个闹钟"); // notificationTextView2.setText("给你设置了一个闹钟"); String mHourString = ""; String mMinuteString = ""; if (mHour < 10) { mHourString = "0" + String.valueOf(mHour); } else mHourString = String.valueOf(mHour); if (mMinute < 10) { mMinuteString = "0" + String.valueOf(mMinute); } else mMinuteString = String.valueOf(mMinute); notificationAlarmTimeTextView.setText("时间 " + mHourString + ":" + mMinuteString); DaysOfWeek daysOfWeek = new DaysOfWeek(mDays); String daysOfWeekStr = daysOfWeek.toString( NotificationActivity.this, true); notificationRepeatInfoTextView.setText(daysOfWeekStr); refuseButton.setOnClickListener(RefuseAlarmListener .getInstance()); acceptButton.setOnClickListener(AlarmDetailListener .getInstance()); asyncloadImage(notification_headImageView, path); } return convertView; } private void asyncloadImage(ImageView imageView, String path) { MyService imageMyService = new MyService(); AsyncImageTask task = new AsyncImageTask(imageMyService, imageView); task.execute(path); } private final class AsyncImageTask extends AsyncTask<String, Integer, Uri> { private MyService service; private ImageView imageView; public AsyncImageTask(MyService myService, ImageView imageView) { this.service = myService; this.imageView = imageView; } @Override protected Uri doInBackground(String... params) { try { String path = params[0]; if (path.equals("")) return null; path = Constants.url + "/AlarmServer/Head/" + path.substring(path.lastIndexOf("/")); return service.getImageURI(path, cache); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Uri result) { super.onPostExecute(result); if (imageView != null && result != null) { imageView.setImageURI(result); } } } } public void refreshNotification() { new Thread(new Runnable() { @Override public void run() { mData = MyService.getNotification(account); Message message = new Message(); message.what = LIST_OK; handler.sendMessage(message); } }).start(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && !hasMainActivity) { new Thread(new Runnable() { @Override public void run() { String accountString = sharedPreferences.getString( "account", ""); String passwordString = sharedPreferences.getString( "password", ""); if (StartActivity.login(accountString, passwordString)) { if (JPushInterface .isPushStopped(getApplicationContext())) { JPushInterface.resumePush(getApplicationContext()); } if (account.indexOf("+86") == 0) { account = account.substring(3); } JPushInterface.setAlias(getApplicationContext(), account, null); Intent contentIntent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("account", account); contentIntent.setClass(NotificationActivity.this, ViewPagerActivity.class); contentIntent.putExtras(bundle); startActivity(contentIntent); NotificationActivity.this.finish(); } } }).start(); /* * else //NotificationActivity.this.finish(); * super.onKeyDown(keyCode, event); */ return true; } return super.onKeyDown(keyCode, event); } } <file_sep>/src/com/jiaziang8/alarm/object/People.java package com.jiaziang8.alarm.object; public class People { public String name; public String number; public People(String name,String number){ this.name = name; this.number = number; } } <file_sep>/src/com/jiaziang8/alarm/object/ContactPeople.java package com.jiaziang8.alarm.object; public class ContactPeople { private String name ; private String pinYinName; private String number; public ContactPeople(String name) { super(); this.name = name; } public ContactPeople(String name, String pinYinName) { super(); this.name = name; this.pinYinName = pinYinName; } public ContactPeople(String name,String pinYinName,String number){ super(); this.name = name; this.pinYinName = pinYinName; this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPinYinName() { return pinYinName; } public void setPinYinName(String pinYinName) { this.pinYinName = pinYinName; } public void setNumber(String number){ this.number = number; } public String getNumber(){ return number; } } <file_sep>/src/com/jeremyfeinstein/slidingmenu/example/MyAlarmFragment.java package com.jeremyfeinstein.slidingmenu.example; import java.util.Calendar; import com.cn.daming.deskclock.Alarm; import com.cn.daming.deskclock.Alarms; import com.cn.daming.deskclock.DigitalClock; import com.cn.daming.deskclock.SetAlarm; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; public class MyAlarmFragment extends Fragment{ static final String PREFERENCES = "AlarmClock"; /** * This must be false for production. If true, turns on logging, test code, * etc. */ static final boolean DEBUG = false; private SharedPreferences mPrefs; private LayoutInflater mFactory; private ListView mAlarmsList; private Cursor mCursor; String account = ""; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); mFactory = LayoutInflater.from(getActivity()); //取getSharedPreferences中key==“AlarmClock”的值 mPrefs = getActivity().getSharedPreferences(PREFERENCES, 0); //获取闹钟的cursor mCursor = Alarms.getAlarmsCursor(getActivity().getContentResolver()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.alarm_clock, null); account = ViewPagerActivity.account; mAlarmsList = (ListView) view.findViewById(R.id.alarms_list); AlarmTimeAdapter adapter = new AlarmTimeAdapter(getActivity(), mCursor); mAlarmsList.setAdapter(adapter); mAlarmsList.setVerticalScrollBarEnabled(true); return view; } /** * listview的适配器继承CursorAdapter * * @author wangxianming 也可以使用BaseAdapter */ private class AlarmTimeAdapter extends CursorAdapter { public AlarmTimeAdapter(Context context, Cursor cursor) { super(context, cursor); } public View newView(Context context, Cursor cursor, ViewGroup parent) { View ret = mFactory.inflate(R.layout.alarm_time, parent, false); DigitalClock digitalClock = (DigitalClock) ret .findViewById(R.id.digitalClock); digitalClock.setLive(false); return ret; } // 把view绑定cursor的每一项 public void bindView(View view, Context context, Cursor cursor) { final Alarm alarm = new Alarm(cursor); final int id = alarm.id; View indicator = view.findViewById(R.id.indicator); // 闹钟开关~~~~~~~~~~~~ final CheckBox clockOnOff = (CheckBox) indicator.findViewById(R.id.clock_onoff); Button deleteButton= (Button)view.findViewById(R.id.delete_alarm); clockOnOff.setChecked(alarm.enabled); // 对checkbox设置监听,使里外一致 /* clockOnOff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton arg0, boolean ischecked) { updateIndicatorAndAlarm(clockOnOff.isChecked(), alarm); } });*/ indicator.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { clockOnOff.toggle(); updateIndicatorAndAlarm(clockOnOff.isChecked(), alarm); } }); deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { new AlertDialog.Builder(getActivity()) .setTitle(getString(R.string.delete_alarm)) .setMessage(getString(R.string.delete_alarm_confirm)) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int w) { Alarms.deleteAlarm(getActivity(), id); } }) .setNegativeButton(android.R.string.cancel, null) .show(); } }); DigitalClock digitalClock = (DigitalClock) view .findViewById(R.id.digitalClock); // set the alarm text final Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, alarm.hour); c.set(Calendar.MINUTE, alarm.minutes); digitalClock.updateTime(c); digitalClock.setTypeface(Typeface.DEFAULT); // Set the repeat text or leave it blank if it does not repeat. TextView daysOfWeekView = (TextView) digitalClock .findViewById(R.id.daysOfWeek); final String daysOfWeekStr = alarm.daysOfWeek.toString( getActivity(), false); if (daysOfWeekStr != null && daysOfWeekStr.length() != 0) { daysOfWeekView.setText(daysOfWeekStr); daysOfWeekView.setVisibility(View.VISIBLE); } else { daysOfWeekView.setVisibility(View.GONE); } } }; // 更新checkbox private void updateIndicatorAndAlarm(boolean enabled, Alarm alarm) { /* bar.setImageResource(enabled ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);*/ Alarms.enableAlarm(getActivity(), alarm.id, enabled); if (enabled) { SetAlarm.popAlarmSetToast(getActivity(), alarm.hour, alarm.minutes, alarm.daysOfWeek); } } /* * (non-Javadoc) * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long) * 创建菜单的点击事件响应 */ //每一个闹钟的事件相应 /* public void onItemClick(AdapterView<?> adapterView, View v, int pos, long id) { Intent intent = new Intent(getActivity(), SetAlarm.class); intent.putExtra(Alarms.ALARM_ID, (int) id); startActivity(intent); }*/ } <file_sep>/src/com/jiaziang8/alarm/ui/deleteReviewButton.java package com.jiaziang8.alarm.ui; import android.content.Context; import android.os.Handler; import android.util.AttributeSet; import android.widget.Button; public class deleteReviewButton extends Button{ private int id ; private Handler handler; public deleteReviewButton(Context context){ super(context); } public deleteReviewButton(Context context,AttributeSet aSet){ super(context, aSet); } public deleteReviewButton(Context context,AttributeSet aSet,int defStyle){ super(context, aSet, defStyle); } public void setHandler(Handler handler){ this.handler = handler; } public Handler getHandler(){ return this.handler; } public void setId(int id){ this.id = id; } public int getId(){ return id ; } }
d01647ce21110552277f333579ef0f88a7aea8f3
[ "Markdown", "Java" ]
20
Java
jiaziang/MyAlarm
4d95b83f5e40f6f3f4d08783dabae69c1dca0a82
e2165b509c2fa3bf3871be06be6708a2e22cd028
refs/heads/master
<repo_name>YoonHong/eng_quiz<file_sep>/includes/eng_quiz_admin.inc <?php function _eng_quiz_pc_admin_quiz_list() { // $content['preface']['#markup'] = t( 'Student Quiz List' ); $content['table'] = _eng_quiz_admin_ql_table( 'latest' ); return $content; } function _eng_quiz_pc_admin_list_by_quiz() { $content['table'] = _eng_quiz_admin_aList_byQuiz_table( ); return $content; } function _eng_quiz_pc_admin_list_by_student() { $content['table'] = _eng_quiz_admin_aList_byStudent_table( ); return $content; } function _eng_quiz_pc_admin_list_by_quiz_sub( $id ) { $content['table'] = _eng_quiz_admin_ql_table( 'byquiz', $id ); $content['link_back'] = array( '#markup' => l('back', 'eng_quiz/admin/quiz'), '#prefix' => '<div style="margin-top:20px;">', '#suffix' => '</div>', ); return $content; } function _eng_quiz_pc_admin_list_by_student_sub( $id ) { $content['table'] = _eng_quiz_admin_ql_table( 'bystudent', $id ); $content['link_back'] = array( '#markup' => l('back', 'eng_quiz/admin/student'), '#prefix' => '<div style="margin-top:20px;">', '#suffix' => '</div>', ); return $content; } function _eng_quiz_admin_ql_table( $type, $tid = '' ) { $content = array(); $user = $GLOBALS['user']; $uid = $user->uid; $query = db_select('eng_quiz_student_qlist', 'sq')->extend('PagerDefault'); $query->join('eng_quiz_main', 'mq', 'mq.id = sq.mid'); $query->join('users', 'user', 'user.uid = sq.uid'); $query->fields('mq',array('title', 'type')) ->fields('user',array('name')) ->fields('sq',array('id', 'mid', 'uid', 'cnt', 'created')) ->condition('sq.retest', 'N', '='); if ( $type == 'byquiz' ) { $query->condition('mq.id', $tid, '='); } else if ( $type == 'bystudent' ) { $query->condition('user.uid', $tid, '='); } $query->limit(20) ->orderBy('sq.created', 'DESC'); $result = $query->execute(); if ($result->rowCount() > 0 ) { foreach ($result as $entity) { // Get Cnt of Sub Quiz] $total_cnt = db_query( 'SELECT COUNT(*) FROM {eng_quiz_sub} A WHERE 1=1 AND A.mid = :mid', array(':mid' => $entity->mid) )->fetchField(); $profile=profile2_load_by_user($entity->uid,'main'); if ( isset($profile->field_full_name) && count($profile->field_full_name) > 0 ) { $rName = $profile->field_full_name['und'][0]['value']; } else { $rName = ''; } if ( $type == "bystudent" ) { $optId = $tid; } else { $optId = $entity->mid; } // Create tabular rows for our entities. $rows[] = array( 'data' => array( 'uid' => $entity->name, 'name' => $rName, 'title' => l($entity->title, 'eng_quiz/student/'.$entity->id.'/qanswer/'.$uid), 'cnt' => ''.$entity->cnt.' / '.$total_cnt, 'created' => format_date( $entity->created, 'custom', 'Y-M-d' ), 'retest' => l(t('ReTest'), 'eng_quiz/admin/'.$entity->id.'/'.$type.'/retest/'.$optId), 'del' => l(t('x'), 'eng_quiz/admin/'.$entity->id.'/'.$type.'/del/'.$optId), ), ); } // Put our entities into a themed table. See theme_table() for details. $content['entity_table'] = array( '#theme' => 'table', '#rows' => $rows, '#header' => array( t('User ID'), t('User Name'), t('Quiz Title'), t('Result'), t('Test Date'), t('ReTest'), t('Del'), ), ); // Attach the pager theme. $content['entity_pager'] = array('#theme' => 'pager'); } else { // There were no entities. Tell the user. $content[] = array( '#type' => 'item', '#markup' => t('No Item!!!'), ); } return $content; } function _eng_quiz_admin_aList_byQuiz_table( ){ $content = array(); $query = db_select('eng_quiz_main', 'd')->extend('PagerDefault'); $query->fields('d', array('id', 'type', 'title', 'created', 'useYn')); $result = $query //->condition('d.useYn', $yn, '=') ->limit(20) ->orderBy('d.id', 'DESC') ->execute(); if ($result->rowCount() > 0 ) { $rows = array(); foreach ($result as $entity) { // Create tabular rows for our entities. $rcnt_query = db_query( "SELECT COUNT(*) rcnt FROM {eng_quiz_student_qlist} WHERE mid = :mid AND retest = 'N' ", array(':mid' => $entity->id,) ); $result = $rcnt_query->fetchObject(); $rcnt = ''; if( $result->rcnt > 0 ) { $rcnt = l( $result->rcnt.' ( View List )' , 'eng_quiz/admin/quiz/'.$entity->id ); } else { $rcnt = '0'; } $rows[] = array( 'data' => array( 'id' => $entity->id, 'title' => $entity->title, 'type' => $entity->type, 'rcnt' => $rcnt, 'created' => format_date( $entity->created, 'custom', 'Y-M-d' ), 'used' => $entity->useYn, ), ); } // Put our entities into a themed table. See theme_table() for details. $content['entity_table'] = array( '#theme' => 'table', '#rows' => $rows, '#header' => array(t('ID'), t('Title'), t('Type'), t('Result Count'), t('Created Date'), t('Use'), ), '#empty' => t('No Quiz!!!'), ); // Attach the pager theme. $content['entity_pager'] = array('#theme' => 'pager'); } else { $content[] = array( '#type' => 'item', '#markup' => t('No Quiz!!!'), ); } return $content; } function _eng_quiz_admin_aList_byStudent_table( ){ $content = array(); $query = db_select('users', 'u')->extend('PagerDefault'); $query->leftJoin('users_roles', 'r', 'u.uid = r.uid'); $query->fields('u', array('uid', 'name', 'mail', 'created', 'status')); $query->fields('r', array('rid',)); $result = $query ->condition('u.status', 1, '=') ->isNull('r.rid') ->limit(20) ->execute(); if ($result->rowCount() > 0 ) { $rows = array(); foreach ($result as $entity) { // Create tabular rows for our entities. $rcnt = 0; $rcnt_query = db_query( "SELECT COUNT(*) rcnt FROM {eng_quiz_student_qlist} WHERE uid = :uid AND retest = 'N' ", array(':uid' => $entity->uid,) ); $result = $rcnt_query->fetchObject(); if( $result->rcnt > 0 ) { $rcnt = l( $result->rcnt.' ( View List )' , 'eng_quiz/admin/student/'.$entity->uid ); } else { $rcnt = '0'; } $rows[] = array( 'data' => array( 'uid' => $entity->name, 'name' => _eng_quiz_get_user_name($entity->uid), 'rid' => $rcnt, ), ); } // Put our entities into a themed table. See theme_table() for details. $content['entity_table'] = array( '#theme' => 'table', '#rows' => $rows, '#header' => array(t('User ID'), t('User Name'), t('Result Count'), ), ); // Attach the pager theme. $content['entity_pager'] = array('#theme' => 'pager'); } else { $content[] = array( '#type' => 'item', '#markup' => t('No Quiz!!!'), ); } return $content; } function _eng_quiz_pc_admin_latest_del( $id, $mid ) { return drupal_get_form('_eng_quiz_pc_admin_quiz_del_form', $id, 'latest', $mid ); } function _eng_quiz_pc_admin_byquiz_del( $id, $mid ) { return drupal_get_form('_eng_quiz_pc_admin_quiz_del_form', $id, 'byquiz', $mid ); } function _eng_quiz_pc_admin_bystudent_del( $id, $mid ) { return drupal_get_form('_eng_quiz_pc_admin_quiz_del_form', $id, 'bystudent', $mid ); } function _eng_quiz_pc_admin_quiz_del_form($form, &$form_state, $id, $type, $mid) { $form['delid'] = array( '#type' => 'value', '#value' => $id, ); $form['mid'] = array( '#type' => 'value', '#value' => $mid, ); $form['rtype'] = array( '#type' => 'value', '#value' => $type, ); $form['question'] = array( '#markup' => t( "Do you want to delete this Quiz Result?" ), '#prefix' => '<h1 class=title>', '#suffix' => '</h1>', ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Confirm'), ); $form['link_cancel'] = array( '#markup' => t( '<a href="javascript:window.history.go(-1);">Cancel</a>' ), ); return $form; } function _eng_quiz_pc_admin_quiz_del_form_submit($form, &$form_state) { $did = $form_state['values']['delid']; $rtype = $form_state['values']['rtype']; $mid = $form_state['values']['mid']; $redirect = 'eng_quiz/admin/latest'; if( $rtype == 'byquiz' ) { $redirect = 'eng_quiz/admin/quiz/'.$mid; } else if( $rtype == 'bystudent' ) { $redirect = 'eng_quiz/admin/student/'.$mid; } db_delete('eng_quiz_student_qlist') ->condition('id', $did) ->execute(); $msg = t( "The Quiz Result has been deleted." ); drupal_set_message( $msg ); $form_state['redirect'] = $redirect; } function _eng_quiz_pc_admin_latest_retest( $id, $mid ) { return drupal_get_form('_eng_quiz_pc_admin_retest_form', $id, 'latest', $mid); } function _eng_quiz_pc_admin_byquiz_retest( $id, $mid ) { return drupal_get_form('_eng_quiz_pc_admin_retest_form', $id, 'byquiz', $mid); } function _eng_quiz_pc_admin_bystudent_retest( $id, $mid ) { return drupal_get_form('_eng_quiz_pc_admin_retest_form', $id, 'bystudent', $mid); } function _eng_quiz_pc_admin_retest_form($form, &$form_state, $id, $type, $mid) { $form['rid'] = array( '#type' => 'value', '#value' => $id, ); $form['rtype'] = array( '#type' => 'value', '#value' => $type, ); $form['mid'] = array( '#type' => 'value', '#value' => $mid, ); $form['question'] = array( '#markup' => t( "Do you want to make this Quiz ReTested?" ), '#prefix' => '<h1 class=title>', '#suffix' => '</h1>', ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Confirm'), ); $form['link_cancel'] = array( '#markup' => t( '<a href="javascript:window.history.go(-1);">Cancel</a>' ), ); return $form; } function _eng_quiz_pc_admin_retest_form_submit($form, &$form_state) { $rid = $form_state['values']['rid']; $rtype = $form_state['values']['rtype']; $mid = $form_state['values']['mid']; $redirect = 'eng_quiz/admin/latest'; if( $rtype == 'byquiz' ) { $redirect = 'eng_quiz/admin/quiz/'.$mid; } else if( $rtype == 'bystudent' ) { $redirect = 'eng_quiz/admin/student/'.$mid; } db_update('eng_quiz_student_qlist') ->fields(array( 'retest' => 'Y', )) ->condition('id', $rid, '=') ->execute(); $msg = t( "Completed!" ); drupal_set_message( $msg ); $form_state['redirect'] = $redirect; } <file_sep>/includes/eng_quiz_sub.inc <?php function _eng_quiz_pc_sub_list( $mid ) { $main_entity = _eng_quiz_get_single_entity( 'eng_quiz_main' , $mid ); return drupal_get_form('_eng_quiz_sub_list_form', $main_entity); } function _eng_quiz_pc_sub_edit($mid, $sid) { $qmain = _eng_quiz_get_single_entity( 'eng_quiz_main' , $mid ); $qsub = _eng_quiz_get_single_entity( 'eng_quiz_sub' , $sid ); return drupal_get_form('_eng_quiz_sub_list_form', $qmain, $qsub); } function _eng_quiz_pc_sub_del($mid, $sid) { return drupal_get_form('_eng_quiz_pc_sub_del_from', $mid, $sid ); } function _eng_quiz_pc_sub_del_from($form, &$form_state, $mid, $sid) { $form['mid'] = array( '#type' => 'value', '#value' => $mid, ); $form['sid'] = array( '#type' => 'value', '#value' => $sid, ); $form['question'] = array( '#markup' => t( "Do you want to delete this Questin?" ), '#prefix' => '<h1 class=title>', '#suffix' => '</h1>', ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Confirm'), ); $form['link_cancel'] = array( '#markup' => t( '<a href="javascript:window.history.go(-1);">Cancel</a>' ), ); return $form; } function _eng_quiz_pc_sub_del_from_submit($form, &$form_state) { $sid = $form_state['values']['sid']; $mid = $form_state['values']['mid']; $redirect = 'eng_quiz/sub/'.$mid; db_delete('eng_quiz_sub') ->condition('id', $sid) ->execute(); db_delete('eng_quiz_sub_opt') ->condition('sid', $sid) ->execute(); _eng_quiz_sub_answer_delete( $sid ); $msg = t( "The Question has been deleted." ); drupal_set_message( $msg ); $form_state['redirect'] = $redirect; } function _eng_quiz_sub_list_form($form, &$form_state, $qmain = null, $qsub = null) { if( $qsub == null ) { $isUpdate = false; $formNoDisp = false; } else { $isUpdate = true; $formNoDisp = true; $anwserList = _eng_quiz_get_answer_list( $qsub->id ); } $form['v_main_quiz'] = array( '#type' => 'value', '#value' => $qmain, ); $form['v_sid'] = array( '#type' => 'value', '#value' => isset($qsub->id) ? $qsub->id : null, ); $form['mQuiz'] = array( '#type' => 'markup', '#markup' => t( ' <p>Title : @title <br/>Type : @type</p> ', array('@title' => $qmain->title, '@type' => $qmain->type, ) ), ); $sList = _eng_quiz_get_sub_list( $qmain->id ); $rows = array(); foreach ($sList as $entity) { // Create tabular rows for our entities. if ( $entity->type == 2 ) { $eType = '주관식'; } else { $eType = '객관식'; } $txt_qtitle = mb_strcut( $entity->title, 0, 130,'utf-8'); $rows[] = array( 'data' => array( // 'id' => $entity->id, // 'item_description' => l($entity->title, 'test_quiz/test/' . $entity->id), 'title' => t('@title', array( '@title'=>$txt_qtitle ) ), // 'title' => $txt_qtitle , 'type' => t( '@type', array( '@type'=>$eType, ) ), 'edit_del' => t('!E / !D', array('!E' => l(t('Edit'), 'eng_quiz/sub/'.$qmain->id.'/edit/'.$entity->id), '!D' => l(t('Del'), 'eng_quiz/sub/'.$qmain->id.'/del/'.$entity->id), ) ), ), ); } $form['qlist'] = array( '#prefix' => '<div id="qSubList">', '#suffix' => '</div>', '#tree' => TRUE, '#theme' => 'table', '#header' => array(t('Question?'), t('Type'), t('Edit / Del')), '#rows' => $rows, ); if ( $isUpdate ) { $dft_qType = $qsub->type; } else { $dft_qType = 1; } $form['question_type'] = array( '#title' => t('Question Type?'), '#type' => 'select', '#options' => array(1 => 'Select...', 2 =>'주관식', 3 => '객관식', ), '#default_value' => $dft_qType, '#disabled' => $formNoDisp, '#ajax' => array( 'callback' => '_eng_quiz_ajax_add_question_callback', 'wrapper' => 'questions_wrapper', ), ); $form['questions_fieldset'] = array( '#type' => 'fieldset', // These provide the wrapper referred to in #ajax['wrapper'] above. '#prefix' => '<div id="questions_wrapper">', '#suffix' => '</div>', ); if ( $isUpdate || !empty($form_state['values']['question_type'])) { if ( $isUpdate ) { $vQType = $qsub->type; } else { $vQType = $form_state['values']['question_type']; } if ( $vQType != 1 ) { // Empty $form['questions_fieldset']['question'] = array( '#type' => 'textarea', '#title' => t('Question :'), '#default_value' => isset($qsub->title) ? $qsub->title : '', '#required' => TRUE, ); if ( $vQType == 2 ) { $form['questions_fieldset']['answer_fieldset'] = array( '#type' => 'fieldset', '#title' => t('Answer :'), '#prefix' => '<div id="answers-wrapper">', '#suffix' => '</div>', ); $form['questions_fieldset']['answer_fieldset']['answers']['a1'] = array( '#type' => 'textfield', //'#title' => t('Answer :'), '#default_value' => isset($qsub->answer) ? $qsub->answer : '', //'#required' => TRUE, //'#field_suffix' => l(t('X'), 'test'), ); $lenAList = sizeof( $anwserList ); for ( $i = 0; $i < _eng_quiz_get_answer_num(); $i++ ) { $va = 'a' . ( $i + 1 ); $dftAns = ""; if ( $i < $lenAList ) { $dftAns = $anwserList[ $i ]->answer; } $form['questions_fieldset']['answer_fieldset']['answers'][$va] = array( '#type' => 'textfield', '#default_value' => $dftAns, ); } } else if ( $vQType == 3 ) { if ( $isUpdate ) { $dftOptCnt = $qsub->opt_cnt; $dftAns = $anwserList[0]->answer; } else { $dftOptCnt = 4; $dftAns = 0; } $form['questions_fieldset']['opt_cnt'] = array( '#title' => t('How many options?'), '#type' => 'select', '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7,), '#default_value' => $dftOptCnt, '#disabled' => $formNoDisp, '#ajax' => array( 'callback' => '_eng_quiz_ajax_add_option_callback', 'wrapper' => 'options_wrapper', ), ); $form['questions_fieldset']['box'] = array( '#type' => 'fieldset', // These provide the wrapper referred to in #ajax['wrapper'] above. '#prefix' => '<div id="options_wrapper">', '#suffix' => '</div>', ); if (empty($form_state['values']['opt_cnt'])) { $optCnt = $dftOptCnt; } else { $optCnt = $form_state['values']['opt_cnt']; } $arrOptAns[0] = t('Select...'); for ($i = 1; $i <= $optCnt; $i++) { $arrOptAns[$i] = t('Option @ans', array('@ans'=>$i,)); } $form['questions_fieldset']['box']['answer'] = array( '#title' => t('Answer :'), '#type' => 'select', //'#options' => array(1 => 'Select...',), '#options' => $arrOptAns, '#default_value' => $dftAns, ); if ( isset( $qsub ) ) { $opts = _eng_quiz_get_opt_list( $qsub->id ); foreach($opts as $opt) { $form['questions_fieldset']['box']['opt'.$opt->seq] = array( '#type' => 'textarea', '#title' => t('Option @num', array('@num'=>$opt->seq,)), '#default_value' => $opt->title, ); } } else { for ($i = 1; $i <= $optCnt; $i++) { $form['questions_fieldset']['box']['opt'.$i] = array( '#type' => 'textarea', '#title' => t('Option @num', array('@num'=>$i,)), ); } } } } } $form['submit'] = array( '#type' => 'submit', '#value' => $isUpdate ? t('Update Question!') : t('Save Question!'), // '#weight' => 50, ); $form['link_cancel'] = array( '#markup' => t('!link', array('!link' => l(t('Cancel'), 'eng_quiz/main')) ), ); return $form; } function _eng_quiz_ajax_add_question_callback($form, $form_state) { // $form['questions_fieldset']['box']['answerS']['#value'] = ''; return $form['questions_fieldset']; } function _eng_quiz_ajax_add_option_callback($form, $form_state) { // $form['questions_fieldset']['box']['answerO']['#value'] = 0; return $form['questions_fieldset']['box']; } function _eng_quiz_sub_list_form_validate($form, &$form_state) { //dpm( format_date(REQUEST_TIME, 'custom', 'Y-m-d' ) ) ; $v_qtype = $form_state['values']['question_type']; if ( $v_qtype == 1 ) { form_set_error('title', t('Select Question Type!!!')); } else if ( $v_qtype == 2 ) { // 주관식 답안 입력 여부 체크 if( isset( $form_state['values']['a1'] ) ) { $numAns = _eng_quiz_get_answer_num(); $cnt = 0; for( $i = 1; $i <= $numAns; $i++ ) { $va = "a" . $i; $txt = trim($form_state['values'][$va]); if( !$txt ) { $cnt++; } } if ( $cnt === $numAns ) { form_set_error( 'title', t('At least one Answer should be entered!') ); } } } } function _eng_quiz_sub_list_form_submit($form, &$form_state) { $v_main_quiz = $form_state['values']['v_main_quiz']; $mid = $v_main_quiz->id; $sid = $form_state['values']['v_sid']; $qtype = $form_state['values']['question_type']; if(isset($sid)) { $entity = _eng_quiz_get_single_entity('eng_quiz_sub', $sid); }else{ $entity = entity_create('eng_quiz_sub', array('id' => null)); } $entity->title = $form_state['values']['question']; $entity->type = $qtype; $entity->mid = $mid; if( $qtype == 3 ) { // 객관식 $entity->opt_cnt = $form_state['values']['opt_cnt'];; } if( $entity->id == null ) { // Insert drupal_write_record('eng_quiz_sub', $entity); if( $qtype == 3 ) { // 객관식 $cnt = $form_state['values']['opt_cnt']; for( $i = 1; $i <= $cnt; $i++ ) { $ent_opt = entity_create('eng_quiz_sub_opt', array('id' => null)); $ent_opt->sid = $entity->id; $ent_opt->seq = $i; $ent_opt->title = $form_state['values']['opt'.$i]; drupal_write_record('eng_quiz_sub_opt', $ent_opt); } // Answer _eng_quiz_sub_answer_insert( $entity->id, 1, $form_state['values']['answer'] ); } else if ( $qtype == 2 ) { // 주관식 Answer _eng_quiz_sub_sq_answer( $entity->id, $form_state ); } } else { // Edit drupal_write_record('eng_quiz_sub', $entity, 'id'); if( $qtype == 3 ) { // 객관식 $opts = _eng_quiz_get_opt_list( $entity->id ); foreach($opts as $opt) { $opt->title = $form_state['values']['opt'.$opt->seq]; drupal_write_record('eng_quiz_sub_opt', $opt, 'id'); } _eng_quiz_sub_answer_delete( $entity->id ); _eng_quiz_sub_answer_insert( $entity->id, 1, $form_state['values']['answer'] ); } else if ( $qtype == 2 ) { // 주관식 Answer _eng_quiz_sub_answer_delete( $entity->id ); _eng_quiz_sub_sq_answer( $entity->id, $form_state ); } } $form_state['redirect'] = 'eng_quiz/sub/'.$mid; } // 주관식 답변 function _eng_quiz_sub_sq_answer ( $sid, $form_state ) { $numAns = _eng_quiz_get_answer_num(); $seq = 1; for( $i = 1; $i <= $numAns; $i++ ) { $va = "a" . $i; $txt = trim($form_state['values'][$va]); if( $txt ) { _eng_quiz_sub_answer_insert( $sid, $seq, $txt ); $seq++; } } } function _eng_quiz_sub_answer_delete( $sid ){ db_delete('eng_quiz_sub_answer') ->condition('sid', $sid) ->execute(); } function _eng_quiz_sub_answer_insert( $sid, $seq, $answer ) { $ent_answer = entity_create('eng_quiz_sub_answer' , array() ); $ent_answer->sid = $sid; $ent_answer->seq = $seq; $ent_answer->answer = $answer; $ent_answer->save(); } <file_sep>/includes/eng_quiz_main.inc <?php function _eng_quiz_pc_main_list_useY( ) { return _eng_quiz_pc_main_list( 'Y' ); } function _eng_quiz_pc_main_list_useN( ) { return _eng_quiz_pc_main_list( 'N' ); } function _eng_quiz_pc_main_list( $yn ) { $content['preface']['#markup'] = t('Add Quiz !link.', array('!link' => l(t('here'), 'eng_quiz/main/add')) ); $content['table'] = _eng_quiz_pc_main_list_table( $yn ); return $content; } function _eng_quiz_pc_main_list_table( $yn ){ $content = array(); $query = db_select('eng_quiz_main', 'd')->extend('PagerDefault'); $query->fields('d', array('id', 'type', 'title', 'created', 'useYn')); $result = $query ->condition('d.useYn', $yn, '=') ->limit(20) ->orderBy('d.id', 'DESC') ->execute(); if ($result->rowCount() > 0 ) { $rows = array(); foreach ($result as $entity) { // Create tabular rows for our entities. $rows[] = array( 'data' => array( 'id' => $entity->id, 'title' => l($entity->title, 'eng_quiz/sub/' . $entity->id ), 'type' => $entity->type, 'created' => format_date( $entity->created, 'custom', 'Y-M-d' ), 'used' => $entity->useYn, 'edit' => l(t('edit'), 'eng_quiz/main/'.$entity->id.'/edit'), 'del' => l(t('del'), 'eng_quiz/main/'.$entity->id.'/del'), ), ); } // Put our entities into a themed table. See theme_table() for details. $content['entity_table'] = array( '#theme' => 'table', '#rows' => $rows, '#header' => array(t('ID'), t('Title'), t('Type'), t('Created Date'), t('Use'), t('Edit'), t('Del') ), '#empty' => t('No Quiz!!!'), ); // Attach the pager theme. $content['entity_pager'] = array('#theme' => 'pager'); } else { $content[] = array( '#type' => 'item', '#markup' => t('No Quiz!!!'), ); } return $content; } function _eng_quiz_pc_main_add() { $entity = entity_create('eng_quiz_main', array('id' => null)); return drupal_get_form('_eng_quiz_main_add_form', $entity); } function _eng_quiz_pc_main_edit( $id ) { $entity = _eng_quiz_get_single_entity('eng_quiz_main', $id); return drupal_get_form('_eng_quiz_main_add_form', $entity); } function _eng_quiz_pc_main_del( $id ) { $entity = _eng_quiz_get_single_entity('eng_quiz_main', $id); return drupal_get_form('_eng_quiz_main_del_form', $entity); } function _eng_quiz_main_add_form($form, &$form_state, $eng_quiz_main = NULL) { $form['basic_entity'] = array( '#type' => 'value', '#value' => $eng_quiz_main, ); $form['title'] = array( '#title' => t('Quiz Title'), '#type' => 'textfield', '#default_value' => isset($eng_quiz_main->title) ? $eng_quiz_main->title : '', '#required' => TRUE, ); $form['type'] = array( '#title' => t('Quiz Type'), '#type' => 'textfield', '#default_value' => isset($eng_quiz_main->type) ? $eng_quiz_main->type : '', '#required' => TRUE, ); if ( isset($eng_quiz_main->useYn) ) { $form['useYn'] = array( '#title' => t('Use : Yes or No?'), '#type' => 'select', '#options' => array( 'Y' => 'Yes', 'N' => 'No', ), '#default_value' => $eng_quiz_main->useYn, ); } $form['submit'] = array( '#type' => 'submit', '#value' => isset($eng_quiz_main->id) ? t('Update') : t('Save'), ); $form['link_cancel'] = array( '#markup' => t( '<a href="javascript:window.history.go(-1);">back</a>' ), ); return $form; } function _eng_quiz_main_add_form_validate($form, &$form_state) { //dpm( format_date(REQUEST_TIME, 'custom', 'Y-m-d' ) ) ; //form_set_error('title', t('Le champ courriel est invalide.')); } function _eng_quiz_main_add_form_submit($form, &$form_state) { $org_entity = $form_state['values']['basic_entity']; if( $org_entity->id == null ) { // Insert $entity = entity_create('eng_quiz_main', array('id' => null)); } else { // Edit $entity = entity_create('eng_quiz_main', array('id' => $org_entity->id)); } $entity->title = $form_state['values']['title']; $entity->type = $form_state['values']['type']; if( $org_entity->id == null ) { // Insert $entity->created = REQUEST_TIME; drupal_write_record('eng_quiz_main', $entity); } else { // Edit $entity->useYn = $form_state['values']['useYn']; $entity->changed = REQUEST_TIME; drupal_write_record('eng_quiz_main', $entity, 'id'); } $form_state['redirect'] = 'eng_quiz/main/list'; } function _eng_quiz_main_del_form($form, &$form_state, $entity) { $form['basic_entity'] = array( '#type' => 'value', '#value' => $entity, ); $question = t( "@title : Are you sure you want to delete this Quiz?" , array('@title' => $entity->title,) ); $path = 'eng_quiz/main/list'; $description = t( "This cannot be undone." ); $yes = t( "Confirm" ); $no = t( "Cancel" ); return confirm_form( $form, $question, $path, $description, $yes, $no ); } function _eng_quiz_main_del_form_submit($form, &$form_state) { $org_entity = $form_state['values']['basic_entity']; db_delete('eng_quiz_main') ->condition('id', $org_entity->id) ->execute(); $msg = t( "The Quiz ( @title ) has been deleted." , array('@title' => $org_entity->title,) ); drupal_set_message( $msg ); $form_state['redirect'] = 'eng_quiz/main/list'; } <file_sep>/includes/eng_quiz_student.inc <?php function _eng_quiz_pc_student_quiz() { $content['preface']['#markup'] = t('Select a Quiz.'); $content['table'] = _eng_quiz_view_sq_list(); return $content; } function _eng_quiz_pc_student_qprocess( $mid ) { drupal_add_css('.form-item .option {font-size: 16px;}', array('type' => 'inline')); return drupal_get_form('_eng_quiz_student_qprocess_form', $mid); } function _eng_quiz_pc_student_quiz_history() { $content['preface']['#markup'] = t('Quiz History For @name!!!', array('@name' => $GLOBALS['user']->name) ); $content['table'] = _eng_quiz_view_sq_history(); return $content; } function _eng_quiz_pc_student_qanswer( $sqid, $uid ) { $sq_entity = _eng_quiz_get_single_entity( 'eng_quiz_student_qlist' , $sqid ); $mid = $sq_entity->mid; $qmain = _eng_quiz_get_single_entity( 'eng_quiz_main' , $mid ); $testDate = format_date( $sq_entity->created, 'custom', 'Y-M-d' ); $content['quiz_info'] = array( '#markup' => t('Tite: @title <br/>Test Date : @td', array('@title'=>$qmain->title, '@td'=>$testDate, ) ), '#prefix' => '<div>', '#suffix' => '</div>', ); // Quiz List $slist = _eng_quiz_get_sub_list( $mid ); // Student Answer List $sAList = _eng_quiz_get_student_qlist( $sqid ); $idx = 0; foreach ($slist as $sub) { $idx++; // Answer List $aList = _eng_quiz_get_answer_list( $sub->id ); $txtAns = ""; foreach ($aList as $ans) { if ( $txtAns ) { $txtAns .= " , "; } $txtAns .= $ans->answer; } $content['question'.$idx] = array( '#markup' => t('Q@idx : @title', array('@idx'=>$idx, '@title'=>$sub->title, ) ), '#prefix' => '<div style="padding-top:10px;">', '#suffix' => '</div>', ); if( $sub->type == 3 ) { // 객관식 문항 $active = _eng_quiz_get_opt_questions( $sub->id ); $content['opt'.$idx] = array( '#theme' => 'item_list', '#items' => $active, '#type' => 'ol', ); } $content['answer'.$idx] = array( '#markup' => t('A@idx : @answer', array('@idx'=>$idx, '@answer'=>$txtAns, ) ), '#prefix' => '<div>', '#suffix' => '</div>', ); $content['user_answer'.$idx] = array( '#markup' => t('Your Answer : @answer', array( '@answer'=>$sAList[$idx-1]->answer, ) ), '#prefix' => '<div>', '#suffix' => '</div>', ); } $content['link_back'] = array( '#markup' => t( '<a href="javascript:window.history.go(-1);">back</a>' ), '#prefix' => '<div style="margin-top:20px;">', '#suffix' => '</div>', ); return $content; } function _eng_quiz_view_sq_history() { $content = array(); $user = $GLOBALS['user']; $uid = $user->uid; $query = db_select('eng_quiz_student_qlist', 'sq')->extend('PagerDefault'); $query->join('eng_quiz_main', 'mq', 'mq.id = sq.mid'); $query->condition('sq.uid', $uid, '='); $query->condition('sq.retest', 'N', '='); $query->fields('mq',array('title', 'type')) ->fields('sq',array('id', 'mid', 'uid', 'cnt', 'created')); $query->limit(20) ->orderBy('sq.created', 'DESC'); $result = $query->execute(); if ($result->rowCount() > 0 ) { foreach ($result as $entity) { // Get Cnt of Sub Quiz] $total_cnt = db_query( 'SELECT COUNT(*) FROM {eng_quiz_sub} A WHERE 1=1 AND A.mid = :mid', array(':mid' => $entity->mid) )->fetchField(); // Create tabular rows for our entities. $rows[] = array( 'data' => array( 'id' => $entity->mid, 'title' => l($entity->title, 'eng_quiz/student/'.$entity->id.'/qanswer/'.$uid), 'cnt' => ''.$entity->cnt.' / '.$total_cnt, 'created' => format_date( $entity->created, 'custom', 'Y-M-d' ), ), ); } // Put our entities into a themed table. See theme_table() for details. $content['entity_table'] = array( '#theme' => 'table', '#rows' => $rows, '#header' => array(t('ID'), t('Title'), t('Cnt'), t('Test Date')), ); // Attach the pager theme. $content['entity_pager'] = array('#theme' => 'pager'); } else { // There were no entities. Tell the user. $content[] = array( '#type' => 'item', '#markup' => t('No History!!!'), ); } return $content; } function _eng_quiz_view_sq_list() { $content = array(); $user = $GLOBALS['user']; $uid = $user->uid; $query = db_select('eng_quiz_main', 'mq')->extend('PagerDefault'); $query->leftJoin('eng_quiz_student_qlist', 'sq', "mq.id = sq.mid AND sq.retest = 'N' AND sq.uid = ".$uid); $query->fields('mq',array('id', 'title', 'type', 'created')) ->fields('sq',array('mid', 'uid')) ->condition('mq.useYn', 'Y', '=') ->isNull('sq.mid'); $result = $query->limit(20) ->orderBy('mq.id', 'DESC') ->execute(); if ($result->rowCount() > 0 ) { foreach ($result as $entity) { // Create tabular rows for our entities. $rows[] = array( 'data' => array( 'id' => $entity->id, 'title' => l($entity->title, 'eng_quiz/student/'.$entity->id.'/qprocess'), 'type' => $entity->type, 'created' => format_date( $entity->created, 'custom', 'Y-M-d' ), ), ); } // Put our entities into a themed table. See theme_table() for details. $content['entity_table'] = array( '#theme' => 'table', '#rows' => $rows, '#header' => array(t('ID'), t('Title'), t('Type'), t('Created Date'),), ); // Attach the pager theme. $content['entity_pager'] = array('#theme' => 'pager'); } else { // There were no entities. Tell the user. $content[] = array( '#type' => 'item', '#markup' => t('No Quiz!!!'), ); } return $content; } function _eng_quiz_student_qprocess_form($form, &$form_state, $mid) { $qmain = _eng_quiz_get_single_entity( 'eng_quiz_main' , $mid ); $form['v_mid'] = array( '#type' => 'value', '#value' => $mid, ); $form['mQuiz'] = array( '#type' => 'markup', '#markup' => t( ' <p>Title : @title <br/>Type : @type</p> ' , array('@title' => $qmain->title, '@type' => $qmain->type, )), '#prefix' => '<div style="font-size:20px;">', '#suffix' => '</div>', ); $slist = _eng_quiz_get_sub_list( $mid ); $idx = 0; foreach ($slist as $sub) { $idx++; $form['subListNo'.$idx] = array( '#type' => 'markup', '#markup' => 'Q '.$idx.' :', '#prefix' => '<div style="font-size:16px; margin-top:35px;">', '#suffix' => '</div>', ); $form['subListQ'.$idx] = array( '#type' => 'markup', '#markup' => nl2br($sub->title), '#prefix' => '<div style="background-color: #f2f2f2; font-size:16px; padding:10px 10px 10px 10px;">', '#suffix' => '</div>', ); if ( $sub->type == 2) { // 주관식 $form['A'.$idx] = array( '#type' => 'textfield', '#required' => TRUE, '#size' => 130, ); } else if ( $sub->type == 3 ) { // 객관식 // $active = array(0 => t('Closed'), 1 => t('Active')); $active = _eng_quiz_get_opt_questions( $sub->id ); $form['A'.$idx] = array( '#type' => 'radios', '#required' => TRUE, '#options' => $active, '#prefix' => '<div style="font-size:16px;">', '#suffix' => '</div>', ); } } $form['submit'] = array( '#type' => 'submit', '#value' => t('Submit!'), // '#weight' => 50, ); $form['link_cancel'] = array( '#markup' => t( '<a href="javascript:window.history.go(-1);">back</a>' ), ); return $form; } function _eng_quiz_get_opt_questions( $sid ){ $opts = _eng_quiz_get_opt_list( $sid ); $active = array(); $idx = 0; foreach($opts as $opt) { $idx++; $active[$idx] = nl2br($opt->title); } return $active; } function _eng_quiz_student_qprocess_form_submit($form, &$form_state) { $user = $GLOBALS['user']; $mid = $form_state['values']['v_mid']; // Insert Data to eng_quiz_student_qlist $entity = entity_create('eng_quiz_student_qlist', array('id' => null)); $entity->uid = $user->uid; $entity->mid = $mid; $entity->cnt = 0; $entity->created = REQUEST_TIME; drupal_write_record('eng_quiz_student_qlist', $entity); $slist = _eng_quiz_get_sub_list( $mid ); $idx = 0; $cnt = 0; foreach ($slist as $sub) { $idx++; $data = array( 'sid' => $sub->id, 'sqid' => $entity->id, 'answer' => $form_state['values']['A'.$idx], ); drupal_write_record('eng_quiz_student_qlist_dtl', $data); if ( _eng_quiz_student_check_answer( $sub->id, $form_state['values']['A'.$idx] ) ) { $cnt++; } } //$entity2 = _eng_quiz_get_entity( 'eng_quiz_student_qlist', $entity->id); $entity->cnt = $cnt; drupal_write_record('eng_quiz_student_qlist', $entity, 'id'); return $form_state['redirect'] = 'eng_quiz/student/quiz/history'; } function _eng_quiz_student_check_answer( $sid, $sAns ){ $rv = false; $aList = _eng_quiz_get_answer_list( $sid ); $len = sizeof( $aList ); for( $i = 0; $i < $len; $i++ ) { $a = $aList[ $i ]->answer; if( $a == $sAns ) { $rv = true; break; } } return $rv; }
114e73a8704bbddda787c3789fc447af43e0a761
[ "PHP" ]
4
PHP
YoonHong/eng_quiz
c473e6e7ecb841a9c05af6f44e27435b7211dccd
8380eec14696dbe2c67f166eb480cf535359aeb6
refs/heads/master
<file_sep>import lineDDA from './algorithms/line/dda'; import lineMP from './algorithms/line/mp'; import lineBresenham from './algorithms/line/bresenham'; import circleMP from './algorithms/circle/mp'; // <<<<<<< 2cad1b87257fe92bfe3d933ad17df94411c43c80 import polygonScan from './algorithms/polygon/scan'; // ======= import cohen from './algorithms/cuts/cohen'; // >>>>>>> test export default [ { name: '直线', algorithms: [ { name: 'DDA', callback: lineDDA }, { name: '中点法', callback: lineMP }, { name: 'Bresenham', callback: lineBresenham } ], checkIfFinished(points) { return points.length === 2; } }, { name: '圆', algorithms: [ { name: '中点法', callback: circleMP } ], checkIfFinished(points) { return points.length === 2; } }, { // <<<<<<< 2cad1b87257fe92bfe3d933ad17df94411c43c80 name: '多边形', algorithms: [ { name: '扫描线', callback: polygonScan } ], checkIfFinished(points) { const { length } = points; if (length < 4) return false; return points[length - 2].x === points[length - 1].x && points[length - 2].y === points[length - 1].y; } }, // ======= { name: '裁剪', algorithms: [ { name: 'cohen', callback: cohen } ], checkIfFinished(points) { return points.length === 4; // >>>>>>> test } } ]; <file_sep>import dda from '../line/dda'; const L = 1; const R = 2; const B = 4; const T = 8; const LT = 9; const RT = 10; const LB = 5; const RB = 6; // dda({ }) function Encode(pt, left, right) { let ptx = 0; // ptx是返回的端点编码 // ************** 给直线的端点编码 *************** if (pt.x < left.x) { ptx = ptx | L; } else if (pt.x > right.x) { ptx = ptx | R; } if (pt.y < right.y) { ptx = ptx | B; } else if (pt.y > left.y) { ptx = ptx | T; } return ptx; } // ************** end of 给直线的端点编码 *************** // function wantpush(lineptx1, lineptx2) { // for (var i = lineptx2; i >= lineptx1; i--) { // let push1 = []; // push1.push(); // } // } export default ({ selectedPixels }) => { let [line1, line2, left, right] = selectedPixels; // line1是直线的第一个端点,line2是直线的第二个端点 // left是矩形框的左上角端点,right是矩形框的右下角端点 let outline = []; let fills = []; let lineptx1 = 0; let lineptx2 = 0; lineptx1 = Encode(line1, left, right); debugger; lineptx2 = Encode(line2, left, right); // lineptx1和2是直线两个端点的编码 // ********用编码判断直线是否需要裁剪并进行绘制*********** // ***计算直线与各边的交点*** let rightside = { x: 0, y: 0 }; let leftside = { x: 0, y: 0 }; let topside = { x: 0, y: 0 }; let bottomside = { x: 0, y: 0 }; // rightside, leftside, topside, bottomside是直线与上下左右的交点(可能在延长线上) rightside.x = right.x; rightside.y = (line1.y - line2.y) / (line1.x - line2.x) * (right.x - line2.x) + line2.y; leftside.x = left.x; leftside.y = (line1.y - line2.y) / (line1.x - line2.x) * (left.x - line2.x) + line2.y; topside.y = left.y; topside.x = line2.x + ((line1.x - line2.x) / (line1.y - line2.y) * (left.y - line2.y)); bottomside.y = right.y; bottomside.x = line2.x + ((line1.x - line2.x) / (line1.y - line2.y) * (right.y - line2.y)); leftside = Math.round(leftside); rightside = Math.round(rightside); topside = Math.round(topside); bottomside = Math.round(bottomside); // ***计算直线与各边的交点*** // if(lineptx1 & lineptx2){ 不画 } switch(lineptx1){ case T:{ line1.y = left.y; line1.x = topside.x; break; } case L:{ line1.x = left.x; line1.y = leftside.y; break; } case B:{ line1.y = right.y; line1.x = bottomside.x; break; } case R:{ line1.x = right.x; line1.y = rightside.y; break; } case LT:{ } } if (lineptx1 | lineptx2 === 0) { return dda({ selectedPixels: [line1, line2] }); } else if (lineptx1 & lineptx2 !== 0) { return { outline, fills }; } // if (lineptx1 & lineptx2 != 0) { // } // return { outline,fills }; }; <file_sep>export default ({ selectedPixels }) => { let outline = []; let fills = []; let [start, end] = selectedPixels; let dx = end.x - start.x; let dy = end.y - start.y; let r=Math.sqrt(dx*dx+dy*dy); // ****************************算法实现**************************** let x, y, d; x=0; y=Math.round(r); let e=1-r; outline.push(...CirclePoints({x+start.x, y+start.y})); // 画八分对称性的其他点   while (x<=y) { if(e<0)   e+=2*x+3; // d<0,取右侧点,d增    else   { e+=2*(x-y)+5; y--;} // d>=0,取右下点,d增    x++;    outline.push(...CirclePoints({x+start.x, y-start.y})); // 画八分对称性的其他点   } console.log(outline); // ****************************算法实现**************************** return { outline, fills }; } function CirclePoints({ x, y }) { let outline = []; outline.push({ x: x, y: y }); outline.push({ x: y, y: x }); outline.push({ x: -x, y: y }); outline.push({ x: y, y: -x }); outline.push({ x: x, y: -y }); outline.push({ x: -y, y: x }); outline.push({ x: -x, y: -y }); outline.push({ x: -y, y: -x }); return outline; }
a337c718176370230c2b49006635fda1e24a89ce
[ "JavaScript" ]
3
JavaScript
HanMufu/computer-graphics
8477c6ee96b87f5a0e7671bf23da0245d2b563e1
3dd66abf0569228e2de1634c23d14fa937b624da
refs/heads/master
<file_sep>CREATE TABLE med_supp ( id SERIAL PRIMARY KEY, company VARCHAR NOT NULL, company_old VARCHAR NOT NULL, naic VARCHAR NOT NULL, plan VARCHAR NOT NULL, state VARCHAR NOT NULL, area VARCHAR NOT NULL, zip_lookup_code VARCHAR NOT NULL, gender VARCHAR NOT NULL, t_nt VARCHAR NOT NULL, couple_fac VARCHAR NOT NULL, eff_date TIMESTAMP, rate_type VARCHAR NOT NULL, age_for_sorting VARCHAR NOT NULL, -- Lowest_Rate_ VARCHAR NOT NULL, -- Highest_Rate_ VARCHAR NOT NULL, age VARCHAR NOT NULL, policy_fee VARCHAR, household_discount VARCHAR, monthly_rate VARCHAR NOT NULL, quarterly_rate VARCHAR NOT NULL, semi_annual_rate VARCHAR NOT NULL, annual_rate VARCHAR NOT NULL ) <file_sep>use actix_web::{web, get, post, App, Responder, HttpServer, error, HttpRequest, HttpResponse}; use deadpool_redis::{Config, Pool}; use deadpool_redis::redis::AsyncCommands; use diesel::PgConnection; use actix_web::web::Json; use chrono::NaiveDateTime; use serde::Deserialize; use rust_practice_actix_diesel::models::{NewZipCode, NewMedSupp}; use rust_practice_actix_diesel::{create_post, get_posts, create_zip_code, create_med_supp, search_med_supp, establish_connection}; fn json_error_handler(err: error::JsonPayloadError, _req: &HttpRequest) -> error::Error { let detail = err.to_string(); let response = match &err { error::JsonPayloadError::ContentType => { HttpResponse::UnsupportedMediaType().content_type("text/plain").body(detail) } _ => HttpResponse::BadRequest().content_type("text/plain").body(detail), }; error::InternalError::from_response(err, response).into() } #[get("/{id}/{name}/index.html")] async fn index(path_params: web::Path<(String, u32)>, pg_connection: web::Data<PgConnection>) -> impl Responder { create_post(&pg_connection, "post title 1", "post body 1"); let posts = get_posts(&pg_connection); Json(posts) } #[post("/zip-codes")] async fn create_zip_code_handler(new_item: web::Json<NewZipCode>, pg_connection: web::Data<PgConnection>) -> impl Responder { let zip_code = create_zip_code(&pg_connection, &new_item); Json(zip_code) } #[post("/med-supp")] async fn create_med_supp_handler(new_item: web::Json<NewMedSupp>, pg_connection: web::Data<PgConnection>) -> impl Responder { let med_supp = create_med_supp(&pg_connection, &new_item); Json(med_supp) } #[derive(Deserialize)] pub struct MedSuppQuoteRequest { zip5: String, age: String, gender: String, tobacco: String, plan: String, } #[get("/med-supp")] async fn med_supp_quote_list(web::Query(info): web::Query<MedSuppQuoteRequest>, pg_connection: web::Data<PgConnection>) -> impl Responder { let thing = search_med_supp( &pg_connection, info.zip5, info.plan, info.age, info.gender, info.tobacco, ); Json(thing) } #[actix_rt::main] async fn main() -> std::io::Result<()> { HttpServer::new(move || App::new() .data(establish_connection()) .service( index ).service( create_zip_code_handler ) .service( create_med_supp_handler ) .service( med_supp_quote_list ) ) .workers(num_cpus::get()) .bind("0.0.0.0:8080")? .run() .await }<file_sep># rust practice actix diesel Example actix web server with postgres and diesel ### Setup: 1) Install redis server 2) Install rustup https://rustup.rs/ 3) clone this repo 4) Add a file named `.env` to the project 5) Add the connection url to the file like: (DATABASE_URL=postgres://diesel_demo:[email protected]/diesel_demo) 6) diesel migration run 5) `cargo run --package rust-practice-actix-diesel --bin rust-practice-actix-diesel --release` ### Usage: ``` GET /med-supp?zip5=68154&plan=F&age=65&gender=Female&tobacco=Non-Tobacco HTTP/1.1 Host: 127.0.0.1:8080 ``` ```shell script siege -c1000 -r 50 -H 'http://127.0.0.1:8080/med-supp?zip5=68154&plan=F&age=65&gender=Female&tobacco=Non-Tobacco' ``` <file_sep>pub mod schema; pub mod models; #[macro_use] extern crate diesel; extern crate dotenv; use diesel::prelude::*; use diesel::pg::PgConnection; use dotenv::dotenv; use std::env; use self::models::{Post, NewPost}; use crate::models::{ZipCode, NewZipCode, NewMedSupp, MedSupp}; use diesel::sql_query; use actix_web::http::header::q; pub fn establish_connection() -> PgConnection { dotenv().ok(); let database_url = env::var("DATABASE_URL") .expect("DATABASE_URL must be set in .env file"); PgConnection::establish(&database_url) .expect(&format!("Error connecting to {}", database_url)) } pub fn create_post<'a>(conn: &PgConnection, title: &'a str, body: &'a str) -> Post { use schema::posts; let new_post = NewPost { title: title, body: body, }; diesel::insert_into(posts::table) .values(&new_post) .get_result(conn) .expect("Error saving new post") } pub fn get_posts(conn: &PgConnection) -> std::vec::Vec<Post> { use self::schema::posts::dsl::*; let results = posts.filter(published.eq(false)) .limit(5) .load::<Post>(conn) .expect("Error loading posts"); results } pub fn create_zip_code<'a>( conn: &PgConnection, new_zip_code: &NewZipCode, ) -> ZipCode { use schema::zip_codes; diesel::insert_into(zip_codes::table) .values(new_zip_code) .get_result(conn) .expect("Error saving new post") } pub fn create_med_supp<'a>( conn: &PgConnection, new_med_supp: &NewMedSupp, ) -> MedSupp { use schema::med_supp; diesel::insert_into(med_supp::table) .values(new_med_supp) .get_result(conn) .expect("Error saving new post") } pub fn get_zip_lookup_codes(conn: &PgConnection, zip5: String) -> std::vec::Vec<std::string::String> { use schema::zip_codes::dsl::*; zip_codes .select(zip_lookup_code) .distinct() .filter(zip_5.eq(zip5)) .load::<String>(conn) .expect("error loading area") } fn build_search_med_supp_query( zip5: String, plan: String, age: String, gender: String, tobacco: String, ) -> String { format!("select med_supp.* from med_supp inner join zip_codes on med_supp.zip_lookup_code = zip_codes.zip_lookup_code where zip_codes.zip_5 = '{zip5}' and med_supp.eff_date > '2018-01-01'and med_supp.age = '{age}' and med_supp.gender = '{gender}' and med_supp.plan = '{plan}' and med_supp.t_nt = '{tobacco}' ", zip5=zip5, age=age, gender=gender, plan=plan, tobacco=tobacco) } pub fn search_med_supp( conn: &PgConnection, zip5_: String, plan_: String, age_: String, gender_: String, tobacco_: String, ) -> Vec<MedSupp>{ use schema::med_supp::dsl::*; let query_string = build_search_med_supp_query( zip5_, plan_, age_, gender_, tobacco_ ); // ^ THIS IS A TEXT BOOK EXAMPLE OF A SQL INJECTION VULNERABILITY ^ sql_query(query_string).load::<MedSupp>(conn).unwrap() // let zip_code_areas = get_zip_lookup_codes(zip5); // // let data = med_supp // // .inner_join(zip_codes::table.zip_lookup_code.on(med_supp::table.zip_lookup_code)) // .filter(zip_code_area.in()) // .filter(age.eq("65")) // .load::<MedSupp>(conn) // .expect("error loading med_supps"); } <file_sep>CREATE TABLE zip_codes ( id SERIAL PRIMARY KEY, zip_lookup_code VARCHAR NOT NULL, state VARCHAR NOT NULL, county VARCHAR NOT NULL, city VARCHAR NOT NULL, zip_3 VARCHAR NOT NULL, zip_5 VARCHAR NOT NULL )<file_sep>table! { med_supp (id) { id -> Int4, company -> Varchar, company_old -> Varchar, naic -> Varchar, plan -> Varchar, state -> Varchar, area -> Varchar, zip_lookup_code -> Varchar, gender -> Varchar, t_nt -> Varchar, couple_fac -> Varchar, eff_date -> Nullable<Timestamp>, rate_type -> Varchar, age_for_sorting -> Varchar, age -> Varchar, policy_fee -> Nullable<Varchar>, household_discount -> Nullable<Varchar>, monthly_rate -> Varchar, quarterly_rate -> Varchar, semi_annual_rate -> Varchar, annual_rate -> Varchar, } } table! { posts (id) { id -> Int4, title -> Varchar, body -> Text, published -> Bool, } } table! { zip_codes (id) { id -> Int4, zip_lookup_code -> Varchar, state -> Varchar, county -> Varchar, city -> Varchar, zip_3 -> Varchar, zip_5 -> Varchar, } } // joinable!(med_supp -> zip_codes (zip_lookup_code)); allow_tables_to_appear_in_same_query!( med_supp, posts, zip_codes, ); <file_sep>[package] name = "rust-practice-actix-diesel" version = "0.1.0" authors = ["tcross <<EMAIL>>"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] num_cpus = "1.13.0" actix = "0.10.0-alpha.3" actix-web = "3.0.0-beta.1" actix-rt = "1.1.1" deadpool-redis = "0.6.0" serde_json = "1.0.56" serde = { version = "1.0.114", features = ["derive"] } diesel = { version = "1.4.4", features = ["postgres", "serde_json", "chrono"] } dotenv = "0.15.0" chrono = { version = "0.4", features = ["serde"] } <file_sep>use super::schema::posts; use super::schema::zip_codes; use super::schema::med_supp; use serde::Serialize; use serde::Deserialize; use diesel::deserialize::QueryableByName; #[derive(Insertable)] #[table_name="posts"] pub struct NewPost<'a> { pub title: &'a str, pub body: &'a str, } #[derive(Queryable, Serialize)] pub struct Post { pub id: i32, pub title: String, pub body: String, pub published: bool, } #[derive(Insertable, Deserialize)] #[table_name="zip_codes"] pub struct NewZipCode { pub zip_lookup_code: String, pub state: String, pub county: String, pub city: String, pub zip_3: String, pub zip_5: String, } #[derive(Queryable, Serialize)] pub struct ZipCode { pub id: i32, pub zip_lookup_code: String, pub state: String, pub county: String, pub city: String, pub zip_3: String, pub zip_5: String, } #[derive(Insertable, Deserialize)] #[table_name="med_supp"] pub struct NewMedSupp { pub company: String, pub company_old: String, pub naic: String, pub plan: String, pub state: String, pub area: String, pub zip_lookup_code: String, pub gender: String, pub t_nt: String, pub couple_fac: String, pub eff_date: Option<chrono::NaiveDateTime>, pub rate_type: String, pub age_for_sorting: String, pub age: String, pub policy_fee: Option<String>, pub household_discount: Option<String>, pub monthly_rate: String, pub quarterly_rate: String, pub semi_annual_rate: String, pub annual_rate: String, } #[derive(QueryableByName, Queryable, Serialize)] #[table_name="med_supp"] pub struct MedSupp { pub id: i32, pub company: String, pub company_old: String, pub naic: String, pub plan: String, pub state: String, pub area: String, pub zip_lookup_code: String, pub gender: String, pub t_nt: String, pub couple_fac: String, pub eff_date: Option<chrono::NaiveDateTime>, pub rate_type: String, pub age_for_sorting: String, pub age: String, pub policy_fee: Option<String>, pub household_discount: Option<String>, pub monthly_rate: String, pub quarterly_rate: String, pub semi_annual_rate: String, pub annual_rate: String, }
b39fd88294c462a5d23c234ea7a561ddf77472b0
[ "Markdown", "SQL", "TOML", "Rust" ]
8
SQL
chmoder/rust-practice-actix-diesel
b691ec7c917641b55c5c06d4d974fa1970df3730
b927c8eb79e7b0af495ffc41dd0e048cde3508b7
refs/heads/master
<file_sep>import pandas as pd import numpy as np df = pd.DataFrame({ 'Name': ['<NAME>', '<NAME>', '<NAME>'], 'Age': [20, 21, 20], 'MailID': ['<EMAIL>','<EMAIL>','<EMAIL>'], 'Phone Number' : [9568225077,7895436723,8456738902] }) print(df)
932906cc62d79ce5b3ee6fafbfb5ebef3f0264fd
[ "Python" ]
1
Python
Akhilgupta17/Acadview_Assignment_18
ba1f662f21682309801afc2e08339d9bfcc9c6bf
5ab05ea44a68c6296d60a76a4578c01f269855da
refs/heads/master
<file_sep>package com.ps.functional.monad.result; import java.util.Objects; public class ErrorType { public enum Severity { CRITICAL, MODERATE, MINOR, WARNING, DEBUG, UNKNOWN } public enum ErrorSource { INTERNAL, CLIENT, EXTERNAL, UNKNOWN, MULTIPLE } private final String message; private final int code; private final Severity severity; private final ErrorSource errorSource; private final String errorName; private ErrorType( String message, int code, ErrorType.Severity severity, ErrorType.ErrorSource errorSource, String name) { this.message = Objects.requireNonNull(message, "message"); this.code = code; this.severity = Objects.requireNonNull(severity, "severity"); this.errorSource = Objects.requireNonNull(errorSource, "errorSource"); this.errorName = Objects.requireNonNull(name, "errorName"); } public static ErrorType of( String message, int code, ErrorType.Severity severity, ErrorType.ErrorSource errorSource, String errorName) { return new ErrorType(message, code, severity, errorSource, errorName); } public String getMessage() { return message; } public int getCode() { return code; } public Severity getSeverity() { return severity; } public ErrorSource getErrorSource() { return errorSource; } public String getErrorName() { return errorName; } public String show() { return code + " - " + errorName + ", Sev: " + severity.toString() + ", Source: " + errorSource.toString() + ", Message: " + message; } } <file_sep>package com.ps.functional.util; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; public interface FunctionUtils { /* Casts any one argument method reference to a Function type */ static <T, R> Function<T, R> function(Function<T, R> function) { return function; } /* Casts any two arguments method reference to a BiFunction type */ static <T, U, R> BiFunction<T, U, R> biFunction(BiFunction<T, U, R> biFunction) { return biFunction; } /* Negates the predicate */ static <T> Predicate<T> not(Predicate<T> predicate) { return predicate.negate(); } }<file_sep>package com.ps.functional.monad.optional; import java.util.Optional; import java.util.function.BiFunction; public interface Optionals { static <R, T, Z> Optional<Z> lift(Optional<T> left, Optional<R> right, BiFunction<? super T, ? super R, ? extends Z> function) { return left.flatMap(leftVal -> right.map(rightVal -> function.apply(leftVal, rightVal))); } static <R, T, Z> BiFunction<Optional<T>, Optional<R>, Optional<Z>> lift(BiFunction<? super T, ? super R, ? extends Z> function) { return (left, right) -> left.flatMap(leftVal -> right.map(rightVal -> function.apply(leftVal, rightVal))); } }
c827bd821c612ede8f0cbebd11115dcecd14f74e
[ "Java" ]
3
Java
shotishu/functional-java
5e672dafc78a1015f2da2378b60cf754597855f0
4f62bee534cf86e5c6d63e747b8b722deb7c6f56
refs/heads/master
<file_sep>package com.example.christopher.reminder.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.example.christopher.reminder.R; import com.example.christopher.reminder.model.Task; import java.util.List; /** * Created by Christopher on 04/10/2015. */ public class MyAdapter extends ArrayAdapter { protected LayoutInflater inflater; private TextView title; private TextView content; public MyAdapter(Context context, List<Task> tasks) { super(context, R.layout.customlist,tasks); } @Override public View getView(int position, View convertView, ViewGroup parent) { Task task = (Task) getItem(position); inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView=inflater.inflate(R.layout.customlist,null); title = (TextView)convertView.findViewById(R.id.txttitle); content = (TextView)convertView.findViewById(R.id.txtcontent); title.setText(task.getTitle()); content.setText(task.getContent()); return convertView; } } <file_sep>package com.example.christopher.reminder.storageData; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.example.christopher.reminder.model.Task; import java.util.ArrayList; import java.util.List; /** * Created by Christopher on 04/10/2015. */ public class MysqlLite extends SQLiteOpenHelper { private static final int version= 1; /*database name */ private static final String db_name = "remind"; /* table name*/ private static final String table_event = "task"; /* table column*/ private static final String KEY_ID = "id"; private static final String KEY_TITLE = "title"; private static final String KEY_CONTENT = "content"; /* create table */ private static final String create_table_task= "CREATE TABLE "+ table_event +"("+KEY_ID+" INTEGER PRIMARY KEY,"+KEY_TITLE+" TEXT,"+KEY_CONTENT+" TEXT"+")"; private static final String get_all_task = "SELECT * FROM " + table_event; public MysqlLite(Context context) { super(context, db_name, null, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(create_table_task); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+ table_event ); onCreate(db); } public void addTask(Task task) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_TITLE,task.getTitle()); values.put(KEY_CONTENT,task.getContent()); db.insert(table_event, null, values); db.close(); } public List<Task> getAllTasks() { List<Task> tasksList = new ArrayList<Task>(); SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(get_all_task, null); if (cursor.moveToFirst()){ do { Task task = new Task(); task.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID))); task.setTitle(cursor.getString(cursor.getColumnIndex(KEY_TITLE))); task.setContent(cursor.getString(cursor.getColumnIndex(KEY_CONTENT))); tasksList.add(task); }while (cursor.moveToNext()); } return tasksList; } /*public Task getTask(int id) { } public int updateTask(Task task) {} public void deleteTask(Task task) {}*/ }
6878cff418c6e30d5dabb05418d20f3a0a2644d2
[ "Java" ]
2
Java
irvinemanouana/Reminder
e0f9873d782af89e7c4d953b9ae319f615c091a9
d032aba42b3bd447b81d545157c6ebedfc39a7c6
refs/heads/master
<repo_name>AngelusProductions/fly-to-the-moon<file_sep>/spec/features/page_opens.rb require 'rails_helper' feature "user enters page" do scenario "and react has div to render" do visit root_path expect(page.title).to have_content("Seats Project") expect(page).to have_css('div#app') end end <file_sep>/app/javascript/react/containers/Plane.js import React, { Component } from 'react' import Section from '../components/Section' class Plane extends Component { constructor(props) { super(props) this.state = { firstDimensions: [10, 4], businessDimensions: [5, 6], economyDimensions: [30, 8], selectedSeatId: null, seats: [] } this.selectSeat = this.selectSeat.bind(this) } componentDidMount() { fetch('/api/v1/seats') .then(response => { if (response.ok) { return response } else { let errorMessage = `${response.status} (${response.statusText})`, error = new Error(errorMessage) throw(error) } }) .then(response => response.json()) .then(data => this.setState({ seats: data }) ) .catch(error => console.error(`Error in fetch: ${error.message}`)) } selectSeat(e) { const selectedSeatId = parseInt(e.target.id) if ( !this.state.seats[selectedSeatId - 1].occupied && selectedSeatId != this.state.selectedSeatId) { document.getElementById("audio").play() this.setState({ selectedSeatId: selectedSeatId }) } } render() { let first = "", business = "", economy = "" let audio = <audio id="audio" src="https://s3.amazonaws.com/seats-project/SFX/pop.mp3" /> if (this.state.seats.length > 0) { const firstSeats = this.state.seats.filter( seat => seat.section === "First" ) const businessSeats = this.state.seats.filter( seat => seat.section === "Business" ) const economySeats = this.state.seats.filter( seat => seat.section === "Economy" ) const firstRows = this.state.firstDimensions[0] const businessRows = this.state.businessDimensions[0] const firstRowsOffset = 0 const businessRowsOffset = firstRows const economyRowsOffset = businessRowsOffset + businessRows first = <Section seats={firstSeats} section={"first"} selectSeat={this.selectSeat} selectedSeatId={this.state.selectedSeatId} dimensions={this.state.firstDimensions} rowsOffset={firstRowsOffset} /> business = <Section seats={businessSeats} section={"business"} selectSeat={this.selectSeat} selectedSeatId={this.state.selectedSeatId} dimensions={this.state.businessDimensions} rowsOffset={businessRowsOffset} /> economy = <Section seats={economySeats} section={"economy"} selectSeat={this.selectSeat} selectedSeatId={this.state.selectedSeatId} dimensions={this.state.economyDimensions} rowsOffset={economyRowsOffset} /> } return ( <div> {first} {business} {economy} {audio} </div> ) } } export default Plane <file_sep>/db/migrate/20190218051703_create_seats.rb class CreateSeats < ActiveRecord::Migration[5.2] def change create_table :seats do |t| t.string :letter, null: false t.integer :row, null: false t.string :section, null: false t.boolean :occupied, null: false end end end <file_sep>/spec/models/seat_spec.rb require 'rails_helper' describe Seat do it { should have_valid(:letter).when("A") } it { should_not have_valid(:letter).when("AB", "") } it { should have_valid(:section).when("First") } it { should_not have_valid(:section).when("Second") } it { should have_valid(:row).when(1) } it { should_not have_valid(:row).when(-1, "one") } it { should have_valid(:occupied).when(true, false) } it { should_not have_valid(:occupied).when(nil) } end <file_sep>/README.md # <NAME> Submission Thank you for inviting me to participate in this challenge. Below are a few instructions and notes to get it working. **Getting Started:** - if you do not have Ruby on Rails, React or PostgreSQL installed, please do so - run `$ bundle` - run `$ bundle exec rake db:drop && bundle exec rake db:create && bundle exec rake db:migrate && bundle exec rake db:rollback && bundle exec rake db:migrate && bundle exec rake db:seed` - run `$ yarn install` - run `$ rails s` - in another tab, run `$ yarn run start` - navigate to `localhost:3000` - run `$ rspec` to run test suites <file_sep>/db/seeds.rb require 'json' json = File.read('seats.json') seatsArray = JSON.parse(json) seatsArray.sort_by!{ |seat| [seat["row"], seat["letter"]]} seatsArray.each do |seat| Seat.create!(seat) end <file_sep>/app/models/seat.rb class Seat < ApplicationRecord validates :letter, presence: true, length: { maximum: 1 } validates :row, presence: true, numericality: { only_integer: true, :greater_than => 0 } validates :section, presence: true, inclusion: { in: ["First", "Business", "Economy"] } validates :occupied, inclusion: { in: [true, false] } end
29670b3b163f0ba3abce9c783a281a45d012dc89
[ "JavaScript", "Ruby", "Markdown" ]
7
Ruby
AngelusProductions/fly-to-the-moon
f9e0afc6cf37119550efc91642d1532b37565e13
6a295de9a3c46653aff484ef621aa4c42a25db5b
refs/heads/master
<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" Position::Position(){ id = COMPONENT_POSITION; x = y = z = r = 0.0; } Position::Position(float gx, float gy){ id = COMPONENT_POSITION; x = gx; y = gy; z = 0; r = 0.0; } Position::Position(float gx, float gy, float gz){ id = COMPONENT_POSITION; x = gx; y = gy; z = gz; r = 0; } Position::Position(float gx, float gy, float gz, float gr){ id = COMPONENT_POSITION; x = gx; y = gy; r = gr; } Component *Position::spawn(std::string sig, std::string args){ std::vector<std::string> arguments = split(args, ' '); arguments.erase(arguments.begin()); if(sig.compare("ff") == 0){ return new Position(stof(arguments[0]), stof(arguments[1])); }else if(sig.compare("ii") == 0){ return new Position(stof(arguments[0]), stof(arguments[1])); }else if(sig.compare("fff")){ return new Position(stof(arguments[0]), stof(arguments[1]), stof(arguments[2])); }else if(sig.compare("iii")){ return new Position(stof(arguments[0]), stof(arguments[1]), stof(arguments[2])); }else if(sig.compare("ffff")){ return new Position(stof(arguments[0]), stof(arguments[1]), stof(arguments[2]), stof(arguments[3])); }else if(sig.compare("iiii")){ return new Position(stof(arguments[0]), stof(arguments[1]), stof(arguments[2]), stof(arguments[3])); } return new Position(); } float Position::getX(){ return x; } float Position::getY(){ return y; } float Position::getZ(){ return z; } float Position::getR(){ return r; } void Position::setX(float get){ x = get; } void Position::setY(float get){ y = get; } void Position::setZ(float get){ z = get; } void Position::setR(float get){ r = get; }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "messages.h" DeltaMessage::DeltaMessage(){ delta = 0.0; fromType = SYSTEM_TIMEKEEPER; messageType = MESSAGE_DELTA; } DeltaMessage::DeltaMessage(float d){ delta = d; fromType = SYSTEM_TIMEKEEPER; messageType = MESSAGE_DELTA; } Message::Message(){ fromType = 0; messageType = MESSAGE_UNDEFINED; }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "ld33.h" int windowheight = 720; int windowwidth = 1280; std::string title = "LD33"; double libVersion = 0.1; GLFWwindow* window; Engine *theEngine; bool final = true; Registry* getRegistry(){ return &(theEngine->registry); } void buildRegistry(){ /* float xMaps[4] = {0.0, 1.0, 1.0, 0.0}; float yMaps[4] = {0.0, 0.0, 1.0, 1.0}; theEngine->registry.addTextureMapped("default", "default", xMaps, yMaps); */ theEngine->loadXUPL("res/stockComponents.xupl"); theEngine->loadXUPL("res/stockResources.xupl"); theEngine->registry.Register(new Color(), "color"); theEngine->registry.Register(new Position(), "position"); theEngine->registry.Register(new Dimensions(), "dimensions"); theEngine->registry.Register(new Vector(), "vector"); theEngine->registry.Register(new Texture(), "texture"); theEngine->registry.Register(new TextMessage(), "textmessage"); theEngine->registry.Register(new ClickDrag(), "clickdrag"); theEngine->registry.Register(new Center(), "center"); theEngine->registry.Register(new TimedMessage(), "timedmessage"); theEngine->registry.Register(new Property(COMPONENT_SCROLL), "scroll"); theEngine->registry.Register(new BarGraph(), "bargraph"); theEngine->registry.Register(new StringMessageOnClick(), "stringmessageonclick"); /* New Ludum Dare Components */ theEngine->registry.Register(new Property(LD33_UFOFLYINGCOMPONENT), "ufoflying"); theEngine->registry.Register(new Property(LD33_ISUFOCOMPONENT), "isufo"); theEngine->registry.Register(new Property(LD33_UFOBEAMINGCOMPONENT), "ufobeaming"); theEngine->registry.Register(new Property(LD33_UFOBEAMEFFECTCOMPONENT), "ufobeameffect"); theEngine->registry.Register(new Property(LD33_UFOENGINEEFFECTCOMPONENT), "ufoengineeffect"); theEngine->registry.Register(new Property(LD33_ABDUCTIBLECOMPONENT), "abductible"); theEngine->registry.Register(new Property(LD33_BRAINWASHABLECOMPONENT), "brainwashable"); theEngine->registry.Register(new Property(LD33_BRAINWASHEDCOMPONENT), "brainwashed"); theEngine->registry.Register(new Property(LD33_RELEASABLECOMPONENT), "releasable"); theEngine->registry.Register(new Property(LD33_EMPLOYABLECOMPONENT), "employable"); theEngine->registry.Register(new Property(LD33_EMPLOYEDCOMPONENT), "employed"); theEngine->registry.Register(new Property(LD33_WINPROGRESS), "winprogress"); theEngine->registry.Register(new Property(LD33_ISENGINEER), "isengineer"); theEngine->registry.Register(new Property(LD33_ISDJ), "isdj"); } int main(){ if(!final){ windowheight = 860; } std::cout<<"Loaded SkilLib v" << libVersion << "\n"; theEngine = new Engine(); theEngine->addSystem(new WindowSystem(windowwidth, windowheight, title)); theEngine->addSystem(new TimekeeperSystem()); theEngine->addSystem(new MovementSystem()); theEngine->addSystem(new RenderSystem()); theEngine->addSystem(new ClickDragSystem()); theEngine->addSystem(new CenterSystem(windowwidth, windowheight)); theEngine->addSystem(new TimedMessageSystem()); theEngine->addSystem(new SceneSystem()); theEngine->addSystem(new DepthSystem()); theEngine->addSystem(new ScrollSystem(2048, 2048)); theEngine->addSystem(new BarGraphSystem()); theEngine->addSystem(new StringMessageOnClickSystem()); /* LD33 Specific Systems */ theEngine->addSystem(new UFOControlSystem()); theEngine->addSystem(new UFOParticleSystem()); theEngine->addSystem(new AbductionSystem()); theEngine->addSystem(new WinLossSystem()); std::cout<<"\nSystems added\n"; theEngine->loadXUPL("res/ld33.xupl"); buildRegistry(); std::cout<<"\nRegistry built\n"; theEngine->loadXUPL("res/startingEntities.xupl"); theEngine->start(); } <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> #include "ld33.h" CorruptionSystem::Corruption(){ id = LD33_CORRUPTIONSYSTEM; } void WinLossSystem::update(float delta){ if(winprogress == 5){ winprogress = 0; notoriety = 0; messageSystems(new LoadSceneMessage("win")); } if(notoriety>5){ winprogress = 0; notoriety = 0; messageSystems(new LoadSceneMessage("lose")); } }<file_sep>#include "skilLib.h" #include "components.h" #include <string> #include <iostream> TimedMessage::TimedMessage(){ id = COMPONENT_TIMEDMESSAGE; remaining = 0; message = ""; } TimedMessage::TimedMessage(float t, std::string m){ id = COMPONENT_TIMEDMESSAGE; remaining = t; message = m; } std::string TimedMessage::getTarget(){ return message; } float TimedMessage::getTime(){ return remaining; } void TimedMessage::progress(float delta){ remaining -= delta; } Component *TimedMessage::spawn(std::string sig, std::string args){ std::vector<std::string> arguments = split(args, ' '); arguments.erase(arguments.begin()); if(sig.compare("fs") == 0){ return new TimedMessage(stof(arguments[0]), arguments[1]); } return new TimedMessage(); } <file_sep>Notes Current ToDo stack: Implement Registry based creation of Components Implement IOManager reading Implement file-based loading of resources (Textures, color schemes, etc) IOManager should have load method Implement text rendering Implement keyboard input and binding Implement dev console Implement hitboxes Implement collisions Notes: May want to stop unnecessary function calls for non-update systems May want to add range class for easy load/unload of resources? Perhaps a "Collection" class that holds the ranges for all resource types (Graphics, Audio, etc.) System: IOManager loads Collections Collections store entity definitions and sfx in an easy to load/unload format Entities store sound effects, component lists, animations Animations store metadata (fps, frame numbers, base (ex. "brickWallBuild" would be the base for the animation "brickWallBuild01" to "brickWallBuild60")) <file_sep>#include <iostream> #include <string> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" extern Engine *theEngine; void Engine::loadXUPL(std::string path){ std::vector<std::string> theFile = io->getFileAsVector(path); for(int x = 0; x < theFile.size(); x++){ // If space blank or comment, skip it if(theFile[x].size() < 2 || (theFile[x][0] == '/' && theFile[x][1] == '/')){ // do nothing }else if(theFile[x] == "resetEntities"){ entities.clear(); // Component }else if(theFile[x] == "component"){ std::string name; std::vector<std::string> sigs; x++; while(x < theFile.size() && theFile[x].size() > 2){ std::vector<std::string> params = split(theFile[x], ':'); params[0].erase(params[0].begin()); params[1].erase(params[1].begin()); if(params[0] == "name"){ name=params[1]; } if(params[0] == "signature"){ sigs.push_back(params[1]); } x++; } registry.declare(name, sigs); // Texture }else if(theFile[x] == "texture"){ std::string name; std::string path; x++; while(x < theFile.size() && theFile[x].size() > 2){ std::vector<std::string> params = split(theFile[x], ':'); params[0].erase(params[0].begin()); params[1].erase(params[1].begin()); if(params[0] == "name"){ name = params[1]; } if(params[0] == "path"){ path = params[1]; } x++; } registry.addTextureUnmapped(name, path); // Mapped Texture }else if(theFile[x] == "textureMapped"){ std::string name; std::string tex; float xMaps[4] = {0.0, 1.0, 1.0, 0.0}; float yMaps[4] = {0.0, 0.0, 1.0, 1.0}; x++; while(x < theFile.size() && theFile[x].size() > 2){ std::vector<std::string> params = split(theFile[x], ':'); params[0].erase(params[0].begin()); params[1].erase(params[1].begin()); if(params[0] == "name"){ name = params[1]; } if(params[0] == "tex"){ tex = params[1]; } if(params[0] == "xmaps"){ std::vector<std::string> maps = split(params[1], ' '); for(int y = 0; y<4; y++){ xMaps[y] = stof(maps[y]); } } if(params[0] == "ymaps"){ std::vector<std::string> maps = split(params[1], ' '); for(int y = 0; y<4; y++){ yMaps[y] = stof(maps[y]); } } x++; } registry.addTextureMapped(name, tex, xMaps, yMaps); }else if(theFile[x] == "tileset"){ std::string name; std::string tex; float width; float height; x++; while(x < theFile.size() && theFile[x].size() > 2){ std::vector<std::string> params = split(theFile[x], ':'); params[0].erase(params[0].begin()); params[1].erase(params[1].begin()); if(params[0] == "name"){ name = params[1]; } if(params[0] == "tex"){ tex = params[1]; } if(params[0] == "width"){ width = stof(params[1]); } if(params[0] == "height"){ height = stof(params[1]); } x++; } int z = 0; for(float y = 0; y < height; y+= 1){ for(float x = 0; x < width; x+=1){ float xMaps[4] = {x/width, x/width + 1/width, x/width + 1/width, x/width}; float yMaps[4] = {1-(y/height + 1/height), 1-(y/height + 1/height), 1-y/height, 1-y/height}; registry.addTextureMapped(name + std::to_string(z), tex, xMaps, yMaps); z++; } } }else if(theFile[x] == "entity"){ std::vector<std::string> components; Entity *tmp = new Entity(); x++; while(x < theFile.size() && theFile[x].size() > 2){ std::vector<std::string> params = split(theFile[x], ':'); params[0].erase(params[0].begin()); params[1].erase(params[1].begin()); if(params[0] == "component"){ tmp->addComponent(registry.getComponent(params[1])); } x++; } theEngine->addEntity(tmp); } } registry.rePoint(); } Engine::Engine(){ delta = 0.0; io = new IOManager(); settings = new SettingsManager(io); keybinds = new KeybindManager(io); registry = Registry(); } Entity *Engine::getEntity(int index){ return entities.at(index); } int Engine::numEntities(){ return entities.size(); } void Engine::addEntity(Entity *ent){ ent->setPos(entities.size()); entities.push_back(ent); } void Engine::removeEntity(int entIndex){ if(entIndex < entities.size()){ entities.erase(entities.begin()+entIndex); } } bool Engine::addSystem(System *sys){ for(int x = 0; x < systems.size(); x++){ if(systems.at(x)->getID() == sys->getID()){ return false; } } systems.push_back(sys); return true; } bool Engine::removeSystem(int sysID){ for(int x = 0; x < systems.size(); x++){ if(systems.at(x)->getID() == sysID){ systems.erase(systems.begin()+x); return true; } } return false; } void Engine::update(){ for(int x = 0; x < systems.size(); x++){ systems.at(x)->update(delta); } //Position *pos = dynamic_cast<Position*>(entities.at(90)->getComponent(COMPONENT_POSITION)); //std::cout<<pos->getY()<<"\n"; } void Engine::start(){ running = true; while(running){ update(); } } void Engine::shutDown(){ running = false; } void Engine::recieveMessage(Message *m){ bool found = false; switch(m->messageType){ case MESSAGE_DELTA: DeltaMessage *deltaMSG = static_cast<DeltaMessage*>(m); delta = deltaMSG->delta; found = true; break; } if(!found){ for(int x = 0; x < systems.size(); x++){ systems.at(x)->message(m); } } } void messageSystems(Message *m){ theEngine->recieveMessage(m); } void shutDownEverything(){ theEngine->shutDown(); } <file_sep>#include <stdio.h> #include <iostream> #include <string> #include "skilLib.h" RegTextureMapped::RegTextureMapped(std::string gName, std::string gFull){ tex = getRegistry()->getTexture(gFull); name = gName; source = gFull; float tmpx[4] = {0.0, 1.0, 1.0, 0.0}; float tmpy[4] = {0.0, 0.0, 1.0, 1.0}; for(int z = 0; z < 4; z++){ x[z] = tmpx[z]; y[z] = tmpy[z]; } } RegTextureMapped::RegTextureMapped(std::string gName, std::string gFull, float *gx, float *gy){ tex = getRegistry()->getTexture(gFull); name = gName.c_str(); source = gFull.c_str(); for(int z = 0; z<4; z++){ x[z] = gx[z]; y[z] = gy[z]; } } GLuint RegTextureMapped::getTex(){ return tex->texture; } void RegTextureMapped::consoleDump(){ std::cout<<"Mapped Texture. Name: " << name << " Address: " <<this<< " Source: " << source << "\n"; std::cout<<"Points: (" << x[0] <<", "<<y[0]<<")("<< x[1] <<", "<<y[1]<<")("<< x[2] <<", "<<y[2]<<")("<< x[3] <<", "<<y[3]<<")\n"; std::cout<<"===================================================\n"; } void RegTextureMapped::rePoint(){ tex = getRegistry()->getTexture(source); }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> #include "ld33.h" extern Engine *theEngine; extern float scrollx; extern float scrolly; AbductionSystemHandler::AbductionSystemHandler(){ // Nothing doing } void AbductionSystemHandler::handle(Message *m, Entity *ent){ // Nothing doing here lol } void AbductionSystemHandler::handle(Message *m, System *sys){ AbductionSystem *as = static_cast<AbductionSystem*>(sys); if(m->messageType == MESSAGE_STRING){ StringMessage *sm = static_cast<StringMessage*>(m); if(sm->message.find("Release") != std::string::npos){ int place = std::stof(sm->message.substr(7)); int property; switch(place){ case 1: property = LD33_PLACEONE; break; case 2: property = LD33_PLACETWO; break; case 3: property = LD33_PLACETHREE; break; case 4: property = LD33_PLACEFOUR; break; case 5: property = LD33_PLACEFIVE; break; } float x, y; for(int i = 0; i < theEngine->numEntities(); i++){ Entity* ent = theEngine->getEntity(i); if(ent->hasComponent(LD33_ISUFOCOMPONENT)){ Position *pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); x = pos->getX(); y = pos->getY(); } } for(int i = 0; i < theEngine->numEntities(); i++){ Entity* ent = theEngine->getEntity(i); if(ent->hasComponent(property)){ if(ent->hasComponent(LD33_ABDUCTIBLECOMPONENT)){ Position *pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); pos->setX(x); pos->setY(y-32); ent->addComponent(new Property(COMPONENT_SCROLL)); if(ent->hasComponent(LD33_ISDJ) && ent->hasComponent(LD33_BRAINWASHEDCOMPONENT)){ Entity* ent2 = new Entity(); ent2->addComponent(new Dimensions(128, 128)); ent2->addComponent(new Texture("book")); ent2->addComponent(new Property(LD33_ABDUCTIBLECOMPONENT)); ent2->addComponent(new Property(LD33_WINPROGRESS)); ent2->addComponent(new Position(768+scrollx, 640+scrolly)); ent2->addComponent(new Property(COMPONENT_SCROLL)); theEngine->addEntity(ent2); } if(ent->hasComponent(LD33_ISENGINEER) && ent->hasComponent(LD33_BRAINWASHEDCOMPONENT)){ Entity* ent2 = new Entity(); ent2->addComponent(new Dimensions(128, 128)); ent2->addComponent(new Texture("fuel")); ent2->addComponent(new Property(LD33_ABDUCTIBLECOMPONENT)); ent2->addComponent(new Property(LD33_WINPROGRESS)); ent2->addComponent(new Position(1216+scrollx, 640+scrollx)); ent2->addComponent(new Property(COMPONENT_SCROLL)); theEngine->addEntity(ent2); } }else{ theEngine->removeEntity(i); i--; } switch(place){ case 1: as->slot1 = false; break; case 2: as->slot2 = false; break; case 3: as->slot3 = false; break; case 4: as->slot4 = false; break; case 5: as->slot5 = false; break; } } } } if(sm->message.find("Employ") != std::string::npos){ int place = std::stof(sm->message.substr(6)); int property; switch(place){ case 1: property = LD33_PLACEONE; break; case 2: property = LD33_PLACETWO; break; case 3: property = LD33_PLACETHREE; break; case 4: property = LD33_PLACEFOUR; break; case 5: property = LD33_PLACEFIVE; break; } for(int i = 0; i < theEngine->numEntities(); i++){ Entity* ent = theEngine->getEntity(i); if(ent->hasComponent(property)){ if(ent->hasComponent(LD33_ABDUCTIBLECOMPONENT)){ ent->addComponent(new Property(LD33_EMPLOYEDCOMPONENT)); messageSystems(new StringMessage("WINPROGRESS")); }else{ theEngine->removeEntity(i); i--; } } } } if(sm->message.find("Brainwash") != std::string::npos){ int place = std::stof(sm->message.substr(9)); int property; switch(place){ case 1: property = LD33_PLACEONE; break; case 2: property = LD33_PLACETWO; break; case 3: property = LD33_PLACETHREE; break; case 4: property = LD33_PLACEFOUR; break; case 5: property = LD33_PLACEFIVE; break; } for(int i = 0; i < theEngine->numEntities(); i++){ Entity* ent = theEngine->getEntity(i); if(ent->hasComponent(property)){ if(ent->hasComponent(LD33_ABDUCTIBLECOMPONENT)){ ent->addComponent(new Property(LD33_BRAINWASHEDCOMPONENT)); } } } } } }<file_sep>#ifndef _LD33 #define _LD33 #include <vector> #include <string> #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" const int LD33_ISUFOCOMPONENT = 100; const int LD33_UFOFLYINGCOMPONENT = 101; const int LD33_UFOBEAMINGCOMPONENT = 102; const int LD33_UFOBEAMEFFECTCOMPONENT = 103; const int LD33_UFOENGINEEFFECTCOMPONENT = 104; const int LD33_ABDUCTIBLECOMPONENT = 105; const int LD33_BRAINWASHABLECOMPONENT = 106; const int LD33_BRAINWASHEDCOMPONENT = 107; const int LD33_RELEASABLECOMPONENT = 108; const int LD33_EMPLOYABLECOMPONENT = 109; const int LD33_EMPLOYEDCOMPONENT = 110; const int LD33_WINPROGRESS = 111; const int LD33_PLACEONE = 112; const int LD33_PLACETWO = 113; const int LD33_PLACETHREE = 114; const int LD33_PLACEFOUR = 115; const int LD33_PLACEFIVE = 112; const int LD33_ISENGINEER = 113; const int LD33_ISDJ = 114; const int LD33_ISMECHANIC = 115; const int LD33_UFOCONTROLSYSTEM = 101; const int LD33_UFOPARTICLESYSTEM = 102; const int LD33_ABDUCTIONSYSTEM = 103; const int LD33_WINLOSSSYSTEM = 104; const int LD33_CORRUPTIONSYSTEM = 105; class UFOControlSystem : public System{ public: UFOControlSystem(); void update(float delta); float UFOBob; }; class UFOParticleSystem : public System{ public: UFOParticleSystem(); void update(float delta); float ufox; float ufoy; bool toggleBeam; bool toggleEngine; bool beamActive; bool engineActive; }; class AbductionSystem : public System{ public: AbductionSystem(); void update(float delta); float ufox; float ufoy; bool beam; Entity* currentAbductee; float progress; bool slot1; bool slot2; bool slot3; bool slot4; bool slot5; }; class WinLossSystem : public System{ public: WinLossSystem(); void update(float h); int winprogress; float notoriety; }; class WinLossSystemHandler : public MessageHandler{ public: WinLossSystemHandler(); void handle(Message*, Entity*); void handle(Message*, System*); }; #endif<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" extern Engine *theEngine; System::System(){ handler = new MessageHandler(); } void System::engineMessage(Message *m){ theEngine->recieveMessage(m); } Entity *System::entityAt(int index){ return theEngine->getEntity(index); } int System::numEntities(){ return theEngine->numEntities(); } void System::recieveMessage(Message *m){ /* default shouldn't need to do much I think */ } void System::setIndex(int ind){ index = ind; } int System::getID(){ return id; } void System::message(Message* msg){ handler->handle(msg, this); }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> extern Engine* theEngine; extern int windowheight; ClickDragSystem::ClickDragSystem(){ id = SYSTEM_CLICKDRAG; } void ClickDragSystem::update(float delta){ for(int iterator = 0; iterator < numEntities(); iterator++){ Entity *ent = entityAt(iterator); if(ent->hasComponent(COMPONENT_POSITION) && ent->hasComponent(COMPONENT_DIMENSIONS) && ent->hasComponent(COMPONENT_CLICKDRAG)){ ClickDrag *cd = static_cast<ClickDrag*>(ent->getComponent(COMPONENT_CLICKDRAG)); Position *pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); Dimensions *dim = static_cast<Dimensions*>(ent->getComponent(COMPONENT_DIMENSIONS)); bool active = cd->getActive(); double mousex; double mousey; glfwGetCursorPos(window, &mousex,&mousey); mousey = windowheight - mousey; bool clicked = (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1) == GLFW_PRESS); if(!active && clicked){ if(mousex > pos->getX() - dim->getWidth()/2 && mousex < pos->getX()+dim->getWidth()/2){ if(mousey > pos->getY() - dim->getHeight()/2 && mousey < pos->getY()+dim->getHeight()/2){ cd->initiate(pos->getX() - mousex, pos->getY() - mousey); active = true; } } } if(active&&clicked){ pos->setX(mousex + cd->getXOffset()); pos->setY(mousey + cd->getYOffset()); } if(active && !clicked){ cd->release(); } } }; } <file_sep> #include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> #include "ld33.h" extern Engine* theEngine; extern int windowheight; AbductionSystem::AbductionSystem(){ id = LD33_ABDUCTIONSYSTEM; handler = new AbductionSystemHandler(); ufox = ufoy = progress = 0; beam = false; currentAbductee = new Entity(); slot1 = slot2 = slot3 = slot4 = slot5 = false; } float abductSpeed = 10; Entity* buttonFactory(float x, float y, float r, float g, float b, std::string text, std::string message, int place){ Entity *tmp = new Entity(); tmp->addComponent(new Position(x, y, 5)); tmp->addComponent(new Color(r,g,b,1)); tmp->addComponent(new TextMessage(text, "fixedWhite", 12, -30)); tmp->addComponent(new Dimensions(60, 24)); tmp->addComponent(new StringMessageOnClick(message)); int property; switch(place){ case 1: property = LD33_PLACEONE; break; case 2: property = LD33_PLACETWO; break; case 3: property = LD33_PLACETHREE; break; case 4: property = LD33_PLACEFOUR; break; case 5: property = LD33_PLACEFIVE; break; } tmp->addComponent(new Property(property)); return tmp; } void AbductionSystem::update(float delta){ if(!beam){ if(currentAbductee->hasComponent(COMPONENT_POSITION)){ Position* pos = static_cast<Position *>(currentAbductee->getComponent(COMPONENT_POSITION)); pos->setY(pos->getY() - progress*abductSpeed); } if(currentAbductee->hasComponent(COMPONENT_VELOCITY)) static_cast<Vector*>(currentAbductee->getComponent(COMPONENT_VELOCITY))->setYComponent(0); currentAbductee = new Entity(); progress = 0; } if(progress > 2.5){ bool placeable = true; int place; if(!slot1){ place = 1; slot1 = true; currentAbductee->addComponent(new Property(LD33_PLACEONE)); }else if(!slot2){ slot2 = true; place = 2; currentAbductee->addComponent(new Property(LD33_PLACETWO)); }else if(!slot3){ slot3 = true; place = 3; currentAbductee->addComponent(new Property(LD33_PLACETHREE)); }else if(!slot4){ slot4 = true; place = 4; currentAbductee->addComponent(new Property(LD33_PLACEFOUR)); }else if(!slot5){ slot5 = true; place = 5; currentAbductee->addComponent(new Property(LD33_PLACEFIVE)); }else{ placeable = false; } static_cast<Vector*>(currentAbductee->getComponent(COMPONENT_VELOCITY))->setYComponent(0); if(placeable){ currentAbductee->removeComponent(COMPONENT_SCROLL); Position* pos = static_cast<Position *>(currentAbductee->getComponent(COMPONENT_POSITION)); pos->setY(655); pos->setX(320+150*(place-1)); pos->setZ(3); if(currentAbductee->hasComponent(LD33_RELEASABLECOMPONENT)) theEngine->addEntity(buttonFactory(320+150*(place-1)-30, 625, 0.1, 0.6, 0.2, "Release", "Release"+std::to_string(place), place)); if(currentAbductee->hasComponent(LD33_BRAINWASHABLECOMPONENT)) theEngine->addEntity(buttonFactory(320+150*(place-1)+30, 625, 1.0, 0.0, 0.0, "Brainwash", "Brainwash"+std::to_string(place), place)); if(currentAbductee->hasComponent(LD33_EMPLOYABLECOMPONENT)) theEngine->addEntity(buttonFactory(320+150*(place-1)+30, 625, 0.0, 0.0, 0.7, "Employ", "Employ"+std::to_string(place), place)); if(currentAbductee->hasComponent(LD33_WINPROGRESS)) messageSystems(new StringMessage("WINPROGRESS")); currentAbductee = new Entity(); } progress = 0; return; } for(int iterator = 0; iterator < numEntities(); iterator++){ Entity *ent = entityAt(iterator); if(ent->hasComponent(LD33_ISUFOCOMPONENT)){ beam = ent->hasComponent(LD33_UFOBEAMINGCOMPONENT); if(ent->hasComponent(COMPONENT_POSITION)){ Position* pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); ufox = pos->getX(); ufoy = pos->getY(); } } if(ent->hasComponent(LD33_ABDUCTIBLECOMPONENT) && beam){ if(ent->hasComponent(COMPONENT_POSITION)){ Position* pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); int x = pos->getX(); int y = pos->getY(); if(abs(x-ufox) < 40 && y < ufoy && y > ufoy-64){ currentAbductee = ent; if(ent->hasComponent(COMPONENT_VELOCITY)){ static_cast<Vector*>(currentAbductee->getComponent(COMPONENT_VELOCITY))->setYComponent(abductSpeed); static_cast<Vector*>(currentAbductee->getComponent(COMPONENT_VELOCITY))->setXComponent(0); }else{ ent->addComponent(new Vector(abductSpeed, 3.14159/2.0, COMPONENT_VELOCITY)); } progress += delta; } } } }; } <file_sep>#ifndef _skilLibComponents #define _skilLibComponents #include <stdio.h> #include <vector> #include <GLFW/glfw3.h> #include <string> #include "skilLib.h" #include "systems.h" #include "messages.h" const int COMPONENT_NONE = 0; const int COMPONENT_COLOR = 1; const int COMPONENT_POSITION = 2; const int COMPONENT_DIMENSIONS = 3; const int COMPONENT_TEXTURE = 4; //not yet iomplemented const int COMPONENT_VECTOR = 5; const int COMPONENT_VELOCITY = 6; const int COMPONENT_ACCELERATION = 7; const int COMPONENT_TEXTMESSAGE = 8; const int COMPONENT_ANGULARVELOCITY = 9; const int COMPONENT_CLICKDRAG = 10; const int COMPONENT_CENTER = 11; const int COMPONENT_TIMEDMESSAGE = 12; const int COMPONENT_PROPERTY = 13; const int COMPONENT_SCROLL = 14; const int COMPONENT_BARGRAPH = 15; const int COMPONENT_STRINGMESSAGEONCLICK = 16; class NullComponent : public Component{ public: NullComponent(); Component *spawn(std::string, std::string); }; class Color : public Component{ public: Color(); Color(float gr, float gg, float gb, float ga); Component *spawn(std::string, std::string); float getR(); float getG(); float getB(); float getA(); void setR(float get); void setG(float get); void setB(float get); void setA(float get); protected: float r, g, b, a; }; class Position : public Component{ public: Position(); Position(float gx, float gy); Position(float gx, float gy, float gz); Position(float gx, float gy, float gz, float gr); Component *spawn(std::string, std::string); float getX(); float getY(); float getZ(); float getR(); void setX(float get); void setY(float get); void setZ(float get); void setR(float get); protected: float x, y, z, r; }; class Dimensions : public Component{ public: Dimensions(); Dimensions(int gw, int gh); Component *spawn(std::string, std::string); int getWidth(); int getHeight(); void setWidth(int get); void setHeight(int get); protected: int width, height; }; //Class Vector yet implemented. Wait until back on the ground and wifi is available. class Vector : public Component{ public: Vector(); Vector(float gmag, float gdir); Vector(float gmag, float gdir, int gid); Component *spawn(std::string, std::string); float getMagnitude(); float getDirection(); float getXComponent(); float getYComponent(); void setMagnitude(float gmag); void setDirection(float gdir); void setXComponent(float x); void setYComponent(float y); void add(Vector vec2); protected: void updateComponents(); void updateDirection(); float magnitude; float direction; float xComponent; float yComponent; }; class Texture : public Component{ public: Component* spawn(std::string, std::string); Texture(); Texture(std::string); RegTextureMapped * tex; }; class TextMessage : public Component{ public: Component* spawn(std::string, std::string); TextMessage(); TextMessage(std::string msg, std::string fnt, int size); TextMessage(std::string msg, std::string fnt, int size, int pad); int getSize(); int getPadding(); std::string getMessage(); std::string getFont(); void setSize(int size); void setPadding(int pad); void setMessage(std::string msg); void setFont(std::string fnt); protected: int fontSize; int padding; std::string message; std::string font; }; class ClickDrag : public Component{ public: Component* spawn(std::string, std::string); ClickDrag(); float getXOffset(); float getYOffset(); bool getActive(); void initiate(float x, float y); void release(); protected: float xOffset; float yOffset; bool active; }; class Center : public Component{ public: Component* spawn(std::string, std::string); Center(); Center(bool h, bool v); bool getHorizontal(); bool getVertical(); void setHorizontal(bool); void setVertical(bool); protected: bool horizontal; bool vertical; }; class TimedMessage : public Component{ public: Component *spawn(std::string, std::string); TimedMessage(); TimedMessage(float t, std::string m); void progress(float delta); std::string getTarget(); float getTime(); float remaining; std::string message; }; class Property : public Component{ public: Component *spawn(std::string, std::string); Property(); Property(int gID); }; class BarGraph : public Component{ public: Component* spawn(std::string, std::string); BarGraph(); BarGraph(std::string gID, float centerx, float centery, float rat, float max, float orientation); std::string gid; float maximum; float x; float y; float dir; float ratio; }; class StringMessageOnClick : public Component{ public: Component* spawn(std::string, std::string); StringMessageOnClick(); StringMessageOnClick(std::string msg); std::string message; }; #endif <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> extern Engine* theEngine; extern int windowheight; extern int windowwidth; ScrollSystem::ScrollSystem(int mw, int mh){ id = SYSTEM_SCROLL; handler = new ScrollSystemHandler(); mapWidth = mw; mapHeight = mh; } void ScrollSystem::update(float delta){ // We do nothing! } <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include <unistd.h> #include "skilLib.h" #include "systems.h" #include "messages.h" float targetFPS = 60; TimekeeperSystem::TimekeeperSystem(){ ticks = 0; fps = 0; delta = 0; lastSecond = 0; lastTime = 0; currentTime = 0; } void TimekeeperSystem::update(float delta){ lastTime = currentTime; currentTime = glfwGetTime(); ticks++; if(currentTime - lastSecond > 1){ fps = ticks; lastSecond = currentTime; ticks = 0; } delta = currentTime - lastTime; engineMessage(new DeltaMessage(delta)); } int TimekeeperSystem::getFPS(){ return fps; } double TimekeeperSystem::getCurrentTime(){ return currentTime; } int TimekeeperSystem::getDelta(){ return delta; } <file_sep>#ifndef _skilLib #define _skilLib #include <stdio.h> #include <vector> #include <GLFW/glfw3.h> #include <string> const float SKILLIB_VERSION = 0.1; class Setting; class IOManager; class SettingsManager; class Engine; class MessageHandler; class Message; class Registry; extern GLFWwindow* window; void shutDownEverything(); void messageSystems(Message *m); Registry* getRegistry(); std::vector<std::string> split(std::string, char); std::vector<std::string> splitForStrings(std::string, char); /* Class Animation */ class Animation{ Animation(std::string getName, int getFps, int getNumFrames, std::string getPathBase); Animation(std::string getName, int getFps, int getNumFrames, std::string getPathBase, std::string getExtension); GLuint* nextFrame(double delta); GLuint* frameAt(int x); void reset(); private: std::string name; double deltaT; int currentFrame; int fps; int numFrames; std::string pathBase; std::string extension; std::vector<GLuint*> frames; }; class Test{ public: Test(); Test(int emacs); bool isEmacsFun; bool doesSaveWork; }; /* Class Setting Holds a double value and a string name. Might need to have capability to set non-double value */ class Setting{ public: Setting(); Setting(std::string getName); Setting(std::string getName, double getValue); std::string getName(); double getValue(); void setValue(double newVal); std::string saveValue(); private: std::string name; double value; }; /* Class IOManager Handles Input/Output related tasks, particularly file operations. KeyDown seems like it should perhaps be placed in another place, with callback based system instead of the current polling based one. */ class IOManager{ public: IOManager(); IOManager(GLFWwindow* getwindow); GLFWwindow* window; bool keyDown(int key); std::string getFileAsString(std::string filename); std::vector<std::string> getFileAsVector(std::string filename); void saveFile(std::string filename, std::string contents); void writeFile(std::string filename, std::vector<std::string> lines); }; /* Class SettingsManager Stores instances of the class Settings Can load and save to files Will return double value for setting when fed name value. */ class SettingsManager{ public: SettingsManager(); SettingsManager(IOManager *getio); SettingsManager(IOManager *io, std::string settingFile); double getSetting(std::string name); void setSetting(std::string, double value); void displaySettings(); void reloadSettings(); void saveSettings(); protected: IOManager* io; std::vector<Setting> settings; std::string filename; }; /* Class KeybindManager Basically a settings manager for keys. Designed to keep keybinds and settings in separate files. Also makes it easier to check for what key we check. Only need to poll for intended action (ie "walkLeft") to recieve bool */ class KeybindManager: SettingsManager{ public: KeybindManager(); KeybindManager(IOManager *getio); KeybindManager(IOManager *getio, std::string settingFile); bool isDown(std::string name); //Scan 1-350 for keybinds }; /* Class Message Base class to enable messages between components and engines. Seemed more useful when I wrote it. Currently only seems to be used to send the Delta message? */ class Message{ public: Message(); Message(int type); int fromType; int messageType; }; /* Class Component Base component. These are critical to our system here. Holds a bit of data, that differs based on what type of component it is. */ class Component{ public: Component(); virtual ~Component(); virtual Component *spawn(std::string sig, std::string args) = 0; /* virtual Component* construct() = 0; virtual Component* construct(std::string args) = 0; */ //virtual void update(float delta) = 0; int getID(); void setID(int getid); int id; }; /* Class Entity Similarly critical for the function of the system. An Entity is essentially just a wrapper for components. All that the class really does is handle messages and hold components. */ class Entity{ public: Entity(); Entity(MessageHandler *gmh); Entity(MessageHandler *gmh, int p); void message(Message* msg); bool addComponent(Component* comp); bool removeComponent(int compID); bool hasComponent(int compID); Component *getComponent(int compID); void update(int delta); void setPos(int p); int pos; protected: MessageHandler *mh; std::vector<Component*> components; }; /* Class System Like a component, except that it plugs into the Engine instead of an Entity, and it has functions, not data. */ class System{ public: System(); virtual void update(float delta) = 0; void setIndex(int ind); void engineMessage(Message *m); void recieveMessage(Message *m); Entity *entityAt(int index); int numEntities(); int getID(); int id; int index; void message(Message* msg); MessageHandler *handler; }; /* Class MessagedHandler It handles messages. Base class, plugs into System or Entity. */ class MessageHandler{ public: MessageHandler(); virtual void handle(Message *m, Entity *ent); virtual void handle(Message *m, System *sys); }; /* Class EntityDef Entity definition Can be cloned to Entity. Holds references to Animations, SFX, and components */ class EntityDef{ public: EntityDef(); std::vector<std::string> components; std::vector<std::string> animations; std::vector<std::string> sounds; private: //Collection *collection; }; class RegComponent{ public: RegComponent(); RegComponent(std::string gName, std::vector<std::string> gSignatures); std::string name; Component *seed; std::vector<std::string> signatures; void consoleDump(); }; class RegTexture{ public: RegTexture(std::string gName); RegTexture(std::string gName, std::string path); GLuint texture; std::string name; void consoleDump(); }; class RegTextureMapped{ public: RegTextureMapped(std::string gName, std::string gFull); RegTextureMapped(std::string gName, std::string gFull, float *gx, float *gy); GLuint getTex(); std::string name; std::string source; float x[4]; float y[4]; RegTexture* tex; void consoleDump(); void rePoint(); }; class Registry{ public: Registry(); bool Register(Component* c, std::string name); bool declare(std::string name, std::vector<std::string> signatures); bool addTextureUnmapped(std::string name, std::string path); bool addTextureMapped(std::string name, std::string source, float *gx, float *ogy); RegTexture *getTexture(std::string); RegTextureMapped *getTextureMapped(std::string); // Needs to have an add audio eventually void dump(); void rePoint(); Component* getComponent(std::string args); private: std::vector<RegComponent> components; std::vector<RegTexture> unmappedTextures; std::vector<RegTextureMapped> mappedTextures; }; /* Class Engine The core of the library. Holds vectors of Entities and Systems. Game loop is here. Also has some auxillary features such as Settings and Keybinds */ class Engine{ public: Engine(); void addEntity(Entity *ent); void removeEntity(int entIndex); bool addSystem(System *sys); bool removeSystem(int sysID); void recieveMessage(Message *m); void start(); void update(); void shutDown(); Entity *getEntity(int index); int numEntities(); IOManager *io; Registry registry; void loadXUPL(std::string path); protected: SettingsManager *settings; KeybindManager *keybinds; bool running; float delta; std::vector<Entity*> entities; std::vector<System*> systems; }; #endif <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include <math.h> MovementSystem::MovementSystem(){ id = SYSTEM_MOVEMENT; } void MovementSystem::update(float delta){ for(int x = 0; x < numEntities(); x++){ Entity* ent = entityAt(x); if(ent->hasComponent(COMPONENT_POSITION) && ent->hasComponent(COMPONENT_VELOCITY)){ Position *pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); Vector *vel = static_cast<Vector*>(ent->getComponent(COMPONENT_VELOCITY)); float x = pos->getX(); float y = pos->getY(); float mag = vel->getMagnitude(); float dir = vel->getDirection(); if(mag != 0){ float xchange = (mag * delta) * cos(dir); float ychange = (mag * delta) * sin(dir); pos->setX(x+xchange); pos->setY(y+ychange); } if(ent->hasComponent(COMPONENT_ACCELERATION)){ Vector *accel = static_cast<Vector*>(ent->getComponent(COMPONENT_ACCELERATION)); vel->add(Vector(accel->getMagnitude()*delta, accel->getDirection())); } } if(ent->hasComponent(COMPONENT_ANGULARVELOCITY) && ent->hasComponent(COMPONENT_POSITION)){ Position *pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); Vector *angular = static_cast<Vector*>(ent->getComponent(COMPONENT_ANGULARVELOCITY)); pos->setR(pos->getR() - angular->getMagnitude()*delta*angular->getDirection()); } } }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> extern Engine *theEngine; SceneSystemHandler::SceneSystemHandler(){ // Nothing doing } void SceneSystemHandler::handle(Message *m, Entity *ent){ // Nothing doing here lol } void SceneSystemHandler::handle(Message *m, System *sys){ SceneSystem *ss = static_cast<SceneSystem*>(sys); if(m->messageType == MESSAGE_CHANGESCENE){ LoadSceneMessage *lsm = static_cast<LoadSceneMessage*>(m); for(int i = 0; i < ss->names.size(); i++){ if(ss->names.size() == 0) return; if(ss->names[i] == lsm->scene) theEngine->loadXUPL(ss->paths[i]); } } }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> extern Engine *theEngine; BarGraphSystemHandler::BarGraphSystemHandler(){ // Nothing doing } void BarGraphSystemHandler::handle(Message *m, Entity *ent){ // Nothing doing here lol } void BarGraphSystemHandler::handle(Message *m, System *sys){ BarGraphSystem *bgs = static_cast<BarGraphSystem*>(sys); if(m->messageType == MESSAGE_BARGRAPH_SET){ SetBarGraphMessage *sg = static_cast<SetBarGraphMessage*>(m); for(int i = 0; i < theEngine->numEntities(); i++){ Entity* ent = theEngine->getEntity(i); if(ent->hasComponent(COMPONENT_BARGRAPH) && ent->hasComponent(COMPONENT_DIMENSIONS) && ent->hasComponent(COMPONENT_POSITION)){ BarGraph* bar = static_cast<BarGraph*>(ent->getComponent(COMPONENT_BARGRAPH)); if(bar->gid == sg->target){ Position* pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); Dimensions* dim = static_cast<Dimensions*>(ent->getComponent(COMPONENT_DIMENSIONS)); float length = sg->value * bar->ratio; dim->setWidth(length); pos->setX(bar->x - bar->maximum/2 + length/2); } } } } if(m->messageType == MESSAGE_BARGRAPH_CHANGE){ ChangeBarGraphMessage *sg = static_cast<ChangeBarGraphMessage*>(m); for(int i = 0; i < theEngine->numEntities(); i++){ Entity* ent = theEngine->getEntity(i); if(ent->hasComponent(COMPONENT_BARGRAPH) && ent->hasComponent(COMPONENT_DIMENSIONS) && ent->hasComponent(COMPONENT_POSITION)){ BarGraph* bar = static_cast<BarGraph*>(ent->getComponent(COMPONENT_BARGRAPH)); if(bar->gid == sg->target){ Position* pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); Dimensions* dim = static_cast<Dimensions*>(ent->getComponent(COMPONENT_DIMENSIONS)); float length = dim->getWidth() + sg->change * bar->ratio; if(length > bar->maximum) length = bar->maximum; dim->setWidth(length); pos->setX(bar->x - bar->maximum/2 + length/2); } } } } }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> #include "ld33.h" extern Engine* theEngine; BarGraphSystem::BarGraphSystem(){ id = SYSTEM_BARGRAPH; handler = new BarGraphSystemHandler(); } void BarGraphSystem::update(float delta){ // Do Nothing } <file_sep>#include "skilLib.h" #include "components.h" #include <string> #include <iostream> Texture::Texture(){ id = COMPONENT_TEXTURE; tex = getRegistry()->getTextureMapped("default"); } Texture::Texture(std::string name){ id = COMPONENT_TEXTURE; tex = getRegistry()->getTextureMapped(name); } Component *Texture::spawn(std::string sig, std::string args){ std::vector<std::string> arguments = split(args, ' '); arguments.erase(arguments.begin()); if(sig.compare("s") == 0){ return new Texture(arguments[0]); } return new Texture(); } <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> StringMessage::StringMessage(){ messageType = MESSAGE_STRING; message = "null"; } StringMessage::StringMessage(std::string str){ messageType = MESSAGE_STRING; message = str; }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> extern Engine* theEngine; extern int windowheight; SceneSystem::SceneSystem(){ id = SYSTEM_LOADSCENE; handler = new SceneSystemHandler(); names.push_back("main"); paths.push_back("res/mainMenu.xupl"); names.push_back("win"); paths.push_back("res/win.xupl"); names.push_back("lose"); paths.push_back("res/lose.xupl"); } void SceneSystem::update(float delta){ // We do nothing! } <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> extern Engine* theEngine; extern int windowheight; extern bool final; StringMessageOnClickSystem::StringMessageOnClickSystem(){ id = SYSTEM_STRINGMESSAGEONCLICK; } void StringMessageOnClickSystem::update(float delta){ for(int iterator = 0; iterator < numEntities(); iterator++){ Entity *ent = entityAt(iterator); if(ent->hasComponent(COMPONENT_STRINGMESSAGEONCLICK)){ StringMessageOnClick *smoc = static_cast<StringMessageOnClick*>(ent->getComponent(COMPONENT_STRINGMESSAGEONCLICK)); Position *pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); Dimensions *dim = static_cast<Dimensions*>(ent->getComponent(COMPONENT_DIMENSIONS)); double mousex; double mousey; glfwGetCursorPos(window, &mousex,&mousey); mousey = windowheight - mousey; bool clicked = (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1) == GLFW_PRESS); if(clicked){ if(!final){ std::cout<<"("<<mousex<<","<<mousey<<")\n"; std::cout<<"("<<pos->getX()<<","<<pos->getY()<<")\n\n"; } if(mousex > pos->getX() - dim->getWidth()/2 && mousex < pos->getX()+dim->getWidth()/2){ if(mousey > pos->getY() - dim->getHeight()/2 && mousey < pos->getY()+dim->getHeight()/2){ messageSystems(new StringMessage(smoc->message)); } } } } }; } <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> extern Engine* theEngine; extern int windowheight; TimedMessageSystem::TimedMessageSystem(){ std::cout<<"sup"; id = SYSTEM_TIMEDMESSAGE; } void TimedMessageSystem::update(float delta){ for(int iterator = 0; iterator < numEntities(); iterator++){ Entity *ent = entityAt(iterator); if(ent->hasComponent(COMPONENT_TIMEDMESSAGE)){ TimedMessage *tm = static_cast<TimedMessage*>(ent->getComponent(COMPONENT_TIMEDMESSAGE)); tm->progress(delta); if(tm->getTime() <= 0){ if(tm->getTarget() == "loadMainMenu"){ messageSystems(new LoadSceneMessage("main")); } } } } } <file_sep># Skillib-Main An updated manifestation of the SkilLib Engine. Began as a fork for a game, but I started that too early. It's my implementation of an Entity-Component based model. The engine has a collection of "Systems" which are run automatically. These "Systems" are executed every time the engine loops. Some, like WindowSystem, perform basic tasks to keep OpenGL happy. Others, like MovementSystem, will iterate over entities, and will act accordingly to those entities containing the appropriate components. For example, the MovementSystem will alter an entity's Position component data based on information from a Velocity or RotationalVelocity vector. Entities are merely a dummy storage place for Components. They are capable of storing and releasing Components, but not much else. Components, similarly, are simply storage containers for data. On its own, the collection of data [16, 16, 100, 100, 100, 50, 1, "beachball"] means nothing. Even breaking it down into its parts, [100,100] [16, 16] [100, 0] [1, 1] ["beachball"] doesn't mean anything without knowing what you're looking at. But if we identify these components with a unique identifier, we, like the engine will know exactly what we're looking at. With IDs, [16, 16](3) [100, 100](2) [100, 0](6) [1, 1](9) ["beachball"](4), the engine can tell that we're talking about an object that is 16pixels wide by 16 pixels wide, with initial position of (100, 100). It also sees that we are moving at a velocity of 100px/s at an angle of 0 radians from the x axis and is rotating clockwise at 1 radian per second. Finally, we see that this object is textured to look like a beach ball. <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> extern Engine* theEngine; const float PI = 3.141592654; RenderSystem::RenderSystem(){ id = SYSTEM_RENDER; } bool SHOW_VECTORS = false; int renderMode(Entity* ent){ /* 0 - Error, do nothing 1 - Wireframe 2 - Color 3 - Texture */ if(ent->hasComponent(COMPONENT_POSITION) && ent->hasComponent(COMPONENT_DIMENSIONS)){ if(ent->hasComponent(COMPONENT_COLOR)) return 2; if(ent->hasComponent(COMPONENT_TEXTURE)) return 3; return 1; } if(ent->hasComponent(COMPONENT_TEXTMESSAGE)) return 4; return 0; } void RenderSystem::update(float delta){ for(int iterator = 0; iterator < numEntities(); iterator++){ Entity *ent = entityAt(iterator); int mode = renderMode(ent); Color* color; Dimensions* dim; Position* pos; Texture* tex; float x, y, z, r, w, h; if(mode > 0){ if(mode != 4){ dim = static_cast<Dimensions*>(ent->getComponent(COMPONENT_DIMENSIONS)); w = dim->getWidth(); h = dim->getHeight(); }else{ w = h = 0; } pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); x = pos->getX(); y = pos->getY(); z = pos->getZ(); r = pos->getR(); }else{ // Default to zero x = y = r = w = h = 0; } // x and y corners float xC[4] = {x-w/2, x+w/2, x+w/2, x-w/2}; float yC[4] = {y-h/2, y-h/2, y+h/2, y+h/2}; if(r != 0){ float l = sqrt(pow(w/2,2) + pow(h/2, 2)); float thetas[4] = {7.0*PI/4.0, PI/4.0, 3.0*PI/4.0, 5.0*PI/4.0}; for(int i = 0; i<4; i++){ xC[i] = x + ( cos(r + thetas[i]) * l ); yC[i] = y + ( sin(r +thetas[i]) * l ); } } // Wireframe Mode if(mode == 1){ glDisable(GL_TEXTURE_2D); glColor3f(0.0, 1.0, 0.3); for(int i = 0; i < 4; i++){ glLineWidth(1); glBegin(GL_LINES); glVertex2f(xC[i],yC[i]); if(i<3) glVertex2f(xC[i+1], yC[i+1]); else glVertex2f(xC[0], yC[0]); glEnd(); } glBegin(GL_LINES); glVertex2f(x,y); glVertex2f(x+cos(r)*w/2, y+sin(r)*w/2); glEnd(); } // Colored Mode if(mode == 2){ color = static_cast<Color*>(ent->getComponent(COMPONENT_COLOR)); float r = color->getR(); float g = color->getG(); float b = color->getB(); float a = color->getA(); glDisable(GL_TEXTURE_2D); glColor4f(r,g,b,a); glBegin(GL_QUADS); for(int i = 0; i<4; i++){ glVertex2i(xC[i],yC[i]); } glEnd(); } // Textured Mode if(mode == 3){ tex = static_cast<Texture*>(ent->getComponent(COMPONENT_TEXTURE)); float *xMap = tex->tex->x; float *yMap = tex->tex->y; glEnable(GL_TEXTURE_2D); glColor3f(1.0, 1.0, 1.0); glBindTexture(GL_TEXTURE_2D, tex->tex->getTex()); glBegin(GL_QUADS); for(int i = 0; i<4; i++){ glTexCoord2f(xMap[i], yMap[i]); glVertex2i(xC[i], yC[i]); } glEnd(); glDisable(GL_TEXTURE_2D); } if(ent->hasComponent(COMPONENT_TEXTMESSAGE)){ TextMessage *txt = static_cast<TextMessage*>(ent->getComponent(COMPONENT_TEXTMESSAGE)); std::string fnt = txt->getFont(); std::string text = txt->getMessage(); int padding = txt->getPadding(); int size = txt->getSize(); glEnable(GL_TEXTURE_2D); for(int i = 0; i < text.size(); i++){ int ascii = text[i] - 32; RegTextureMapped* tmpTex = theEngine->registry.getTextureMapped(fnt + std::to_string(ascii)); float *xMap = tmpTex->x; float *yMap = tmpTex->y; glColor3f(1.0, 1.0, 1.0); glBindTexture(GL_TEXTURE_2D, tmpTex->getTex()); glBegin(GL_QUADS); glTexCoord2f(xMap[0], yMap[0]); glVertex2i(x+padding+size*i*.5, y); glTexCoord2f(xMap[1], yMap[1]); glVertex2i(x+size*.5+padding+size*i*.5, y); glTexCoord2f(xMap[2], yMap[2]); glVertex2i(x+size*.5+padding+size*i*.5, y+size); glTexCoord2f(xMap[3], yMap[3]); glVertex2i(x+padding+size*i*.5, y+size); glEnd(); } glDisable(GL_TEXTURE_2D); } /* If vectors showing for debug purposes */ if(ent->hasComponent(COMPONENT_VELOCITY) && SHOW_VECTORS){ Vector *vel = static_cast<Vector*>(ent->getComponent(COMPONENT_VELOCITY)); float direction = vel->getDirection(); glDisable(GL_TEXTURE_2D); glColor4f(0.0, 0.0, 1.0, 1.0); float endx = x + vel->getXComponent(); float endy = y + vel->getYComponent(); glBegin(GL_TRIANGLE_FAN); glVertex2f(x, y); for(int theta = 0; theta < 360; theta += 5){ glVertex2f(x+sin(theta*3.14/180) * 5, y + cos(theta*3.14/180) * 5); } glEnd(); glLineWidth(2.0); glBegin(GL_LINES); glVertex2f(x, y); glVertex2f(endx, endy); glEnd(); float offset = 5*3.14/6; glBegin(GL_LINES); glVertex2f(endx, endy); glVertex2f(endx+10*cos(direction+offset), endy+10*sin(direction+offset)); glEnd(); glBegin(GL_LINES); glVertex2f(endx, endy); glVertex2f(endx+10*cos(direction-offset), endy+10*sin(direction-offset)); glEnd(); } glColor3f(1.0, 1.0, 1.0); } } <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> #include "ld33.h" extern Engine* theEngine; extern int windowwidth; extern int windowheight; const float PI = 3.141592654; bool toggleShift = false; bool toggleSpace = false; UFOControlSystem::UFOControlSystem(){ id = LD33_UFOCONTROLSYSTEM; UFOBob = 0; } void UFOControlSystem::update(float delta){ for(int iterator = 0; iterator < numEntities(); iterator++){ Entity *ent = entityAt(iterator); if(ent->hasComponent(LD33_ISUFOCOMPONENT) && ent->hasComponent(COMPONENT_VELOCITY)){ Vector* vel = static_cast<Vector*>(ent->getComponent(COMPONENT_VELOCITY)); bool w, a, s, d, space, shift; int speed = 150; int vertical, horizontal; vertical = horizontal = 0; w = (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS); a = (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS); s = (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS); d = (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS); space = (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS); shift = (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS); if(!space) toggleSpace = false; if(space && !toggleSpace){ if(ent->hasComponent(LD33_UFOFLYINGCOMPONENT)){ ent->removeComponent(LD33_UFOFLYINGCOMPONENT); }else{ ent->addComponent(new Property(LD33_UFOFLYINGCOMPONENT)); } toggleSpace = true; } if(!shift) toggleShift = false; if(shift && !toggleShift){ if(ent->hasComponent(LD33_UFOBEAMINGCOMPONENT)){ ent->removeComponent(LD33_UFOBEAMINGCOMPONENT); }else{ ent->addComponent(new Property(LD33_UFOBEAMINGCOMPONENT)); } toggleShift = true; } if(w != s){ if(w) vertical = speed; if(s) vertical = -speed; } if(a != d){ if(a) horizontal = -speed; if(d) horizontal = speed; } if(!ent->hasComponent(LD33_UFOFLYINGCOMPONENT) || ent->hasComponent(LD33_UFOBEAMINGCOMPONENT)) horizontal = vertical = 0; Position* pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); if((pos->getX() < 32 && horizontal < 0) || (pos->getX() > windowwidth-32 && horizontal > 0)){ messageSystems(new ScrollMessage(horizontal*delta, 0)); vel->setXComponent(0); }else{ vel->setXComponent(horizontal); } if((pos->getY() < 32 && vertical < 0) || (pos->getY() > windowheight-32-136 && vertical > 0)){ messageSystems(new ScrollMessage(0, vertical*delta)); vel->setYComponent(0); }else{ vel->setYComponent(vertical); } UFOBob += 2* delta; if(UFOBob > 2*3.14) UFOBob = 0; Vector v = Vector(10*cos(UFOBob), 3.14159/2); if(ent->hasComponent(LD33_UFOFLYINGCOMPONENT)) vel->add(v); } } } <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" bool is_number(std::string s){ for(int x = 0; x < s.size(); x++){ if(s[x] >= 45 && s[x] <= 57 && s[x] != 47){ // could still be a number }else{ return false; } } return true; } std::vector<std::string> split(std::string input, char delim){ std::stringstream stream(input); std::vector<std::string> tmp; std::string item; while(std::getline(stream, item, delim)){ tmp.push_back(item); } return tmp; } std::vector<std::string> splitForStrings(std::string input, char delim){ std::vector<std::string> arguments = split(input, delim); int openQuote; int quoteChar; for(int x = 1; x < arguments.size(); x++){ if((arguments[x][0] == '"' || arguments[x][0] == 39)){ openQuote = x; quoteChar = arguments[x][0]; if(!(arguments[x][arguments[x].size()-1] == '"' || arguments[x][arguments[x].size()-1] == 39)){ x++; while(arguments[x][arguments[x].size()-1] != quoteChar){ arguments[openQuote] = arguments[openQuote] + " " + arguments[x]; arguments.erase(arguments.begin()+x); } arguments[openQuote] = arguments[openQuote] + " " + arguments[x]; arguments.erase(arguments.begin()+x); } arguments[openQuote] = arguments[openQuote].substr(1, arguments[openQuote].size()-2); } } return arguments; } Registry::Registry(){ } bool Registry::Register(Component* c, std::string name){ for(int x = 0; x < components.size(); x++){ if(name.compare(components.at(x).name) == 0){ components.at(x).seed = c; return true; } } return false; } bool Registry::declare(std::string name, std::vector<std::string> signatures){ for(int x = 0; x < components.size(); x++){ if(name.compare(components.at(x).name) == 0){ // Do nothing, component already declared return false; } } components.push_back(RegComponent(name, signatures)); return true; } RegTexture* Registry::getTexture(std::string name){ for(int x=0; x< unmappedTextures.size(); x++){ if(unmappedTextures.at(x).name == name){ return &unmappedTextures.at(x); } } return &unmappedTextures.at(0); } RegTextureMapped* Registry::getTextureMapped(std::string name){ for(int x=0; x<mappedTextures.size(); x++){ if(mappedTextures.at(x).name == name){ return &mappedTextures.at(x); } } std::cout<<"Error: Mapped Texture '"<<name<<"' not found. Using default.\n"; return &mappedTextures.at(1); } Component* Registry::getComponent(std::string args){ std::string signature; std::vector<std::string> arguments = splitForStrings(args, ' '); std::string name = arguments.at(0); for(int x = 1; x<arguments.size(); x++){ std::string tmp=arguments.at(x); if(tmp[0] == '\'' || tmp[0] == '"'){ signature.push_back('s'); }else if(tmp == "void"){ signature.push_back('void'); }else if(tmp == "true"){ signature.push_back('b'); }else if(tmp == "false"){ signature.push_back('b'); }else if(tmp.find('.') == std::string::npos){ if(is_number(tmp)){ signature.push_back('i'); }else{ signature.push_back('s'); } }else{ if(is_number(tmp)){ signature.push_back('f'); }else{ signature.push_back('s'); } } } if(signature == "") signature = "void"; for(int x = 0; x < components.size(); x++){ if(name.compare(components.at(x).name) == 0){ std::vector<std::string> sigs = components.at(x).signatures; for(int y = 0; y < sigs.size(); y++){ if(sigs.at(y).compare(signature) == 0){ return components.at(x).seed->spawn(signature, args); } } std::cout<<"Error: Signature " << signature << " not found for component " << name << "\n"; return new NullComponent(); } } std::cout<<"Error: Component " << name << " not found\n"; return new NullComponent(); } bool Registry::addTextureUnmapped(std::string name, std::string path){ for(int x = 0; x < unmappedTextures.size(); x++){ if(name.compare(unmappedTextures.at(x).name) == 0){ return false; } } unmappedTextures.push_back(RegTexture(name, path)); return true; } bool Registry::addTextureMapped(std::string name, std::string source, float *gx, float *gy){ for(int x = 0; x < mappedTextures.size(); x++){ if(name.compare(mappedTextures.at(x).name) == 0){ return false; } } mappedTextures.push_back(RegTextureMapped(name, source, gx, gy)); return true; } void Registry::dump(){ std::cout<<"\n\n\n\n===================================================\n\nBEGINNING REGISTRY DUMP\n\n"; std::cout<<"===================================================\n"; for(int x = 0; x < components.size(); x++){ components[x].consoleDump(); } for(int x = 0; x < unmappedTextures.size(); x++){ unmappedTextures[x].consoleDump(); } for(int y = 0; y < mappedTextures.size(); y++){ mappedTextures[y].consoleDump(); } } void Registry::rePoint(){ for(int x = 0; x < mappedTextures.size(); x++){ mappedTextures[x].rePoint(); } }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" ClickDrag::ClickDrag(){ xOffset = 0; yOffset = 0; active = false; id = COMPONENT_CLICKDRAG; } Component* ClickDrag::spawn(std::string sig, std::string args){ return new ClickDrag(); } float ClickDrag::getXOffset(){ return xOffset; } float ClickDrag::getYOffset(){ return yOffset; } bool ClickDrag::getActive(){ return active; } void ClickDrag::initiate(float x, float y){ active = true; xOffset = x; yOffset = y; } void ClickDrag::release(){ active = false; } <file_sep>#include "skilLib.h" #include "components.h" #include <string> #include <iostream> Property::Property(){ id = COMPONENT_PROPERTY; } Property::Property(int gID){ id = gID; } Component *Property::spawn(std::string sig, std::string args){ return new Property(id); } <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> #include "ld33.h" WinLossSystem::WinLossSystem(){ id = LD33_WINLOSSSYSTEM; handler = new WinLossSystemHandler(); winprogress = 0; notoriety = 0; } void WinLossSystem::update(float delta){ if(winprogress >= 5){ winprogress = 0; notoriety = 0; messageSystems(new LoadSceneMessage("win")); } if(notoriety>120){ winprogress = 0; notoriety = 0; messageSystems(new LoadSceneMessage("lose")); } notoriety += delta; }<file_sep>#include <vector> #include <string.h> #include <sstream> #include <iostream> std::vector<std::string> split2(std::string input, char delim){ std::stringstream stream(input); std::vector<std::string> tmp; std::string item; while(std::getline(stream, item, delim)){ tmp.push_back(item); } return tmp; } void spawn(std::string args){ std::string signature; std::vector<std::string> arguments = split2(args, ' '); std::vector<bool> bools; std::vector<std::string> strings; std::vector<float> floats; std::vector<int> ints; for(int x = 0; x<arguments.size(); x++){ std::string tmp=arguments.at(x); if(tmp[0] == '\'' || tmp[0] == '"'){ signature.push_back('s'); //I'm not sure if this needs to be 2 or 3... strings.push_back(tmp.substr(1,tmp.size()-2)); }else if(tmp == "true"){ signature.push_back('b'); bools.push_back(true); }else if(tmp == "false"){ signature.push_back('b'); bools.push_back(false); }else if(tmp.find('.') == std::string::npos){ try { int tmpint = std::stoi(tmp); if(std::to_string(tmpint) == tmp){ signature.push_back('i'); ints.push_back(tmpint); }else{ signature.push_back('s'); strings.push_back(tmp); } } catch (...) { signature.push_back('s'); strings.push_back(tmp); } }else{ try { float tmpfloat = std::stof(tmp); if(std::to_string(tmpfloat).substr(0,tmp.size()) == tmp){ signature.push_back('f'); floats.push_back(tmpfloat); }else{ signature.push_back('s'); strings.push_back(tmp); } } catch (...) { signature.push_back('s'); strings.push_back(tmp); } } std::cout<<signature<<"\n"; } std::cout<<signature; } int main(){ spawn("'vector' false trueasd 14.5vds 10.5 1"); return 0; }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" MessageHandler::MessageHandler(){} void MessageHandler::handle(Message *m, Entity *ent){ //Nothing doing } void MessageHandler::handle(Message *m, System *sys){ //Nothing doing } Entity::Entity(){ mh = new MessageHandler(); } Entity::Entity(MessageHandler *gmh){ mh = gmh; } Entity::Entity(MessageHandler *gmh, int p){ mh = gmh; pos = p; } void Entity::setPos(int p){ pos = p; } void Entity::message(Message *msg){ mh->handle(msg, this); } bool Entity::addComponent(Component *comp){ for(int x = 0; x < components.size(); x++){ if(components.at(x)->getID() == comp->getID()){ return false; } } components.push_back(comp); return true; } bool Entity::removeComponent(int compID){ for(int x = 0; x < components.size(); x++){ if(components.at(x)->getID() == compID){ components.erase(components.begin()+x); return true; } } return false; } bool Entity::hasComponent(int compID){ for(int x = 0; x < components.size(); x++){ if(components.at(x)->getID() == compID){ return true; } } return false; } Component *Entity::getComponent(int compID){ for(int x = 0; x < components.size(); x++){ if(components.at(x)->getID() == compID){ return components.at(x); } } return new NullComponent(); // will this eventually bog down memory? } void Entity::update(int delta){ for(int x = 0; x < components.size(); x++){ //components.at(x)->update(delta); } }<file_sep>#ifndef _skilLibMessaging #define _skilLibMessaging #include <stdio.h> #include <vector> #include <GLFW/glfw3.h> #include <string> #include "skilLib.h" #include "systems.h" const int MESSAGE_UNDEFINED = -1; const int MESSAGE_DELTA = 1; const int MESSAGE_CONSOLEOUT = 2; const int MESSAGE_CHANGESCENE = 3; const int MESSAGE_SCROLL = 4; const int MESSAGE_BARGRAPH_CHANGE = 5; const int MESSAGE_BARGRAPH_SET = 6; const int MESSAGE_STRING = 7; class DeltaMessage : public Message{ public: DeltaMessage(); DeltaMessage(float d); float delta; }; class ConsoleOutMessage : public Message{ public: ConsoleOutMessage(); ConsoleOutMessage(std::string msg); std::string message; }; class LoadMainMenuMessage : public Message{ public: LoadMainMenuMessage(); }; class LoadSceneMessage : public Message{ public: LoadSceneMessage(); LoadSceneMessage(std::string s); std::string scene; }; class SceneSystemHandler : public MessageHandler{ public: SceneSystemHandler(); void handle(Message*, Entity*); void handle(Message*, System*); }; class ScrollSystemHandler : public MessageHandler{ public: ScrollSystemHandler(); void handle(Message*, Entity*); void handle(Message*, System*); }; class AbductionSystemHandler : public MessageHandler{ public: AbductionSystemHandler(); void handle(Message*, Entity*); void handle(Message*, System*); }; class BarGraphSystemHandler : public MessageHandler{ public: BarGraphSystemHandler(); void handle(Message*, Entity*); void handle(Message*, System*); }; class ChangeBarGraphMessage : public Message{ public: ChangeBarGraphMessage(); ChangeBarGraphMessage(std::string tar, float delta); std::string target; float change; }; class SetBarGraphMessage : public Message{ public: SetBarGraphMessage(); SetBarGraphMessage(std::string tar, float val); std::string target; float value; }; class ScrollMessage : public Message{ public: ScrollMessage(); ScrollMessage(float cx, float cy); float changex; float changey; }; class StringMessage : public Message{ public: StringMessage(); StringMessage(std::string str); std::string message; }; #endif <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" Dimensions::Dimensions(){ id = COMPONENT_DIMENSIONS; width = height = 0; } Dimensions::Dimensions(int gw, int gh){ id = COMPONENT_DIMENSIONS; width = gw; height = gh; } Component *Dimensions::spawn(std::string sig, std::string args){ std::vector<std::string> arguments = split(args, ' '); arguments.erase(arguments.begin()); if(sig.compare("ii") == 0){ return new Dimensions(stoi(arguments[0]), stoi(arguments[1])); } return new Dimensions(); } int Dimensions::getWidth(){ return width; } int Dimensions::getHeight(){ return height; } void Dimensions::setWidth(int get){ width = get; } void Dimensions::setHeight(int get){ height = get; } <file_sep>#include "skilLib.h" #include <string> #include <iostream> #include <sstream> Setting::Setting(){ name = "UnnamedSetting"; value = 0.0; } Setting::Setting(std::string getName){ name = getName; } Setting::Setting(std::string getName, double getValue){ name = getName; value = getValue; } double Setting::getValue(){ return value; } void Setting::setValue(double newVal){ value = newVal; } std::string Setting::getName(){ return name; } std::string Setting::saveValue(){ std::ostringstream strs; strs << value; return name + ":" + strs.str() + ";"; }<file_sep>#include "skilLib.h" #include <vector> #include <string> #include <stdlib.h> #include <iostream> KeybindManager::KeybindManager(){ filename = "keybinds.txt"; io = new IOManager(); reloadSettings(); } KeybindManager::KeybindManager(IOManager *getio){ filename = "keybinds.txt"; io = getio; reloadSettings(); } KeybindManager::KeybindManager(IOManager *getio, std::string settingFile){ filename = settingFile; io = getio; reloadSettings(); } bool KeybindManager::isDown(std::string name){ return io->keyDown(getSetting(name)); } SettingsManager::SettingsManager(){ filename = "settings.txt"; io = new IOManager(); reloadSettings(); } SettingsManager::SettingsManager(IOManager *getio){ filename = "settings.txt"; io = getio; reloadSettings(); } SettingsManager::SettingsManager(IOManager *getio, std::string settingFile){ filename = settingFile; io = getio; reloadSettings(); } double SettingsManager::getSetting(std::string name){ for(int x = 0; x < settings.size(); x++){ Setting tmp = settings.at(x); if(tmp.getName() == name){ return tmp.getValue(); } } return 0.0; } void SettingsManager::setSetting(std::string name, double value){ for(int x = 0; x < settings.size(); x++){ Setting tmp = settings.at(x); if(tmp.getName() == name){ settings.at(x).setValue(value); break; } } } void SettingsManager::reloadSettings(){ std::string file = io->getFileAsString(filename); bool isfirst = true; std::string first = ""; std::string second = ""; for(int x = 0; x < file.size(); x++){ if(file.substr(x, 1) == ":"){ isfirst = false; }else if(file.substr(x, 1) == ";"){ isfirst = true; settings.push_back(Setting(first, atof(second.c_str()))); first = ""; second = ""; }else if(isfirst){ first += file[x]; }else{ second += file[x]; } } } void SettingsManager::displaySettings(){ std::cout<<"displaying settings"; for(int x = 0; x < settings.size(); x++){ Setting tmp = settings.at(x); std::cout<<"("<<tmp.getName()<<", "<<tmp.getValue()<<")\n"; } } void SettingsManager::saveSettings(){ std::vector<std::string> strings; for(int x = 0; x < settings.size(); x++){ strings.push_back(settings.at(x).saveValue()); } io->writeFile(filename, strings); }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" NullComponent::NullComponent(){ id = COMPONENT_NONE; } Component* NullComponent::spawn(std::string sig, std::string args){ return new NullComponent(); }<file_sep>#include "skilLib.h" #include "components.h" #include <string> #include <iostream> Center::Center(){ id = COMPONENT_CENTER; horizontal = vertical = false; } Center::Center(bool h, bool v){ id = COMPONENT_CENTER; horizontal = h; vertical = v; } bool Center::getHorizontal(){ return horizontal; } bool Center::getVertical(){ return vertical; } void Center::setHorizontal(bool h){ horizontal = h; } void Center::setVertical(bool v){ vertical = v; } Component *Center::spawn(std::string sig, std::string args){ std::vector<std::string> arguments = split(args, ' '); arguments.erase(arguments.begin()); if(sig.compare("bb") == 0){ bool h, v; h = (arguments[0].compare("true") == 0); v = (arguments[1].compare("true") == 0); return new Center(h, v); } return new Center(); } <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" /* This IS NOT a typical component!!! This is merely the registry wrapper for a component, its name, and its signatures. */ RegComponent::RegComponent(){ name = "null"; signatures.push_back("ERR"); seed = new NullComponent(); } RegComponent::RegComponent(std::string gName, std::vector<std::string> gSignatures){ name = gName; signatures = gSignatures; seed = new NullComponent(); // Registry needs components to register, seed will be replaced. } void RegComponent::consoleDump(){ std::cout<<"Component. Name: " << name << " Address: " <<this<< "\n"; std::cout<<"Sources: "; for(int x = 0; x < signatures.size(); x++){ std::cout<<signatures[x]<<" "; } std::cout<<"\n===================================================\n"; }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> extern Engine* theEngine; extern int windowheight; CenterSystem::CenterSystem(){ id = SYSTEM_CENTER; } CenterSystem::CenterSystem(int w, int h){ id = SYSTEM_CENTER; width = w; height = h; } void CenterSystem::update(float delta){ for(int iterator = 0; iterator < numEntities(); iterator++){ Entity *ent = entityAt(iterator); if(ent->hasComponent(COMPONENT_POSITION) && ent->hasComponent(COMPONENT_CENTER)){ Center *c = static_cast<Center*>(ent->getComponent(COMPONENT_CENTER)); Position *pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); if(c->getHorizontal()) pos->setX(width/2); if(c->getVertical()) pos->setY(height/2); } }; } <file_sep>#ifndef _skilLibSystems #define _skilLibSystems #include <stdio.h> #include <vector> #include <GLFW/glfw3.h> #include <string> #include "skilLib.h" const int SYSTEM_DEBUG = 0; const int SYSTEM_WINDOW = 1; const int SYSTEM_TIMEKEEPER = 2; const int SYSTEM_MOVEMENT = 3; const int SYSTEM_COLLISION = 4; const int SYSTEM_RENDER = 5; const int SYSTEM_INPUT = 6; const int SYSTEM_GARBAGECOLLECT = 7; const int SYSTEM_CLICKDRAG = 8; const int SYSTEM_CENTER = 9; const int SYSTEM_LOADSCENE = 10; const int SYSTEM_TIMEDMESSAGE = 11; const int SYSTEM_DEPTH = 12; const int SYSTEM_SCROLL = 13; const int SYSTEM_BARGRAPH = 14; const int SYSTEM_STRINGMESSAGEONCLICK = 15; class WindowSystem : public System{ public: WindowSystem(); WindowSystem(int gwidth, int gheight, std::string gtitle); void initializeWindow(); void closeWindow(); void update(float delta); protected: int width; int height; char* title; }; class TimekeeperSystem : public System{ public: TimekeeperSystem(); void update(float delta); double getCurrentTime(); int getDelta(); int getFPS(); protected: int ticks; int fps; float delta; double lastTime; double lastSecond; double currentTime; }; class MovementSystem : public System{ public: MovementSystem(); void update(float delta); // The method where the float delta actually matters }; class CollisionSystem : public System{ public: CollisionSystem(); void update(float delta); }; class RenderSystem : public System{ public: RenderSystem(); void update(float delta); protected: }; class InputSystem : public System{ public: InputSystem(); void update(); }; class ClickDragSystem : public System{ public: ClickDragSystem(); void update(float delta); }; class CenterSystem : public System{ public: CenterSystem(); CenterSystem(int w, int h); void update(float delta); protected: int width; int height; }; class SceneSystem : public System{ public: SceneSystem(); void update(float delta); void addScene(std::string name, std::string path); std::vector<std::string> names; std::vector<std::string> paths; }; class TimedMessageSystem : public System{ public: TimedMessageSystem(); void update(float delta); }; class DepthSystem : public System{ public: DepthSystem(); void update(float delta); }; class ScrollSystem : public System{ public: ScrollSystem(); ScrollSystem(int mw, int mh); void update(float delta); int mapWidth; int mapHeight; }; class BarGraphSystem : public System{ public: BarGraphSystem(); void update(float delta); }; class StringMessageOnClickSystem : public System{ public: StringMessageOnClickSystem(); void update(float delta); }; #endif <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include <math.h> const float PI = 3.141592654; Vector::Vector(){ id = COMPONENT_VECTOR; magnitude = 0.0; direction = 0.0; updateComponents(); } Vector::Vector(float gmag, float gdir){ id = COMPONENT_VECTOR; magnitude = gmag; direction = gdir; updateComponents(); } Vector::Vector(float gmag, float gdir, int gid){ id = gid; magnitude = gmag; direction = gdir; updateComponents(); } Component *Vector::spawn(std::string sig, std::string args){ std::vector<std::string> arguments = split(args, ' '); arguments.erase(arguments.begin()); if(sig.compare("ff") == 0){ return new Vector(stof(arguments[0]), stof(arguments[1])); }else if(sig.compare("ffi") == 0){ return new Vector(stof(arguments[0]), stof(arguments[1]), stoi(arguments[2])); }else if(sig.compare("ffs") == 0){ int type = 0; if(arguments[2].compare("velocity") == 0){ type = COMPONENT_VELOCITY; } if(arguments[2].compare("acceleration") == 0){ type = COMPONENT_ACCELERATION; } if(arguments[2].compare("angularVelocity") == 0){ type = COMPONENT_ANGULARVELOCITY; } return new Vector(stof(arguments[0]), stof(arguments[1]), type); } return new Vector(); } void Vector::updateComponents(){ xComponent = magnitude * cos(direction); yComponent = magnitude * sin(direction); } void Vector::updateDirection(){ direction = atan(yComponent/xComponent); if(xComponent < 0) direction += PI; if(direction > 2*PI) direction -= 2*PI; magnitude = sqrt(pow(xComponent,2) + pow(yComponent,2)); } void Vector::add(Vector vec2){ xComponent += vec2.getMagnitude() * cos(vec2.getDirection()); yComponent += vec2.getMagnitude() * sin(vec2.getDirection()); updateDirection(); } void Vector::setXComponent(float x){ xComponent = x; updateDirection(); } void Vector::setYComponent(float y){ yComponent = y; updateDirection(); } void Vector::setMagnitude(float gmag){ magnitude = gmag; updateComponents(); } void Vector::setDirection(float gdir){ direction = gdir; updateComponents(); } float Vector::getMagnitude(){ return magnitude; } float Vector::getDirection(){ return direction; } float Vector::getXComponent(){ return xComponent; } float Vector::getYComponent(){ return yComponent; }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> #include "ld33.h" extern Engine* theEngine; const float PI = 3.141592654; UFOParticleSystem::UFOParticleSystem(){ id = LD33_UFOPARTICLESYSTEM; ufox = 0; ufoy = 0; toggleBeam = false; toggleEngine = false; beamActive = false; engineActive = false; } void UFOParticleSystem::update(float delta){ for(int iterator = 0; iterator < numEntities(); iterator++){ Entity *ent = entityAt(iterator); if(ent->hasComponent(LD33_ISUFOCOMPONENT)){ engineActive = ent->hasComponent(LD33_UFOFLYINGCOMPONENT); beamActive = ent->hasComponent(LD33_UFOBEAMINGCOMPONENT); Position* pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); ufox = pos->getX(); ufoy = pos->getY(); } if(engineActive && !toggleEngine){ Entity *tmpBurner = new Entity(); tmpBurner->addComponent(new Position(ufox, ufoy-5, -1)); tmpBurner->addComponent(new Dimensions(18, 11)); tmpBurner->addComponent(new Color(.85, 0, 0, .4)); tmpBurner->addComponent(new Property(LD33_UFOENGINEEFFECTCOMPONENT)); theEngine->addEntity(tmpBurner); Entity *tmpBurner2 = new Entity(); tmpBurner2->addComponent(new Position(ufox, ufoy-5, -1)); tmpBurner2->addComponent(new Dimensions(12, 8)); tmpBurner2->addComponent(new Color(.85, .85, 0, .6)); tmpBurner2->addComponent(new Property(LD33_UFOENGINEEFFECTCOMPONENT)); theEngine->addEntity(tmpBurner2); } if(beamActive && !toggleBeam){ Entity *tmpBurner = new Entity(); tmpBurner->addComponent(new Position(ufox, ufoy-32, -1)); tmpBurner->addComponent(new Dimensions(18, 64)); tmpBurner->addComponent(new Color(.25, .85, 1, .4)); tmpBurner->addComponent(new Property(LD33_UFOBEAMEFFECTCOMPONENT)); theEngine->addEntity(tmpBurner); } toggleEngine = engineActive; toggleBeam = beamActive; if(ent->hasComponent(LD33_UFOBEAMEFFECTCOMPONENT) && !beamActive){ theEngine->removeEntity(iterator); iterator--; } if(ent->hasComponent(LD33_UFOENGINEEFFECTCOMPONENT)){ Position *pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); pos->setX(ufox); pos->setY(ufoy-5); } if(ent->hasComponent(LD33_UFOENGINEEFFECTCOMPONENT) && !engineActive){ std::cout<<"Removed Engine"; theEngine->removeEntity(iterator); iterator--; } } } <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h"<file_sep>#include <iostream> #include <stdio.h> #include <fstream> #include <string> #include <cstring> #include <GLFW/glfw3.h> #include "skilLib.h" IOManager::IOManager(){ } IOManager::IOManager(GLFWwindow* getwindow){ window = getwindow; } bool IOManager::keyDown(int key){ if(glfwGetKey(window, key)){ return true; } return false; } std::string IOManager::getFileAsString(std::string filename){ std::string line; std::string total; char* filechar = new char[filename.size()+1]; filechar[filename.size()]=0; memcpy(filechar, filename.c_str(), filename.size()); std::ifstream file (filechar); if(file.is_open()){ while(getline(file, line)){ total += line; } file.close(); } return total; } std::vector<std::string> IOManager::getFileAsVector(std::string filename){ std::string line; std::vector<std::string> tmp; char* filechar = new char[filename.size()+1]; filechar[filename.size()]=0; memcpy(filechar, filename.c_str(), filename.size()); std::ifstream file (filechar); if(file.is_open()){ while(getline(file, line)){ tmp.push_back(line); } file.close(); } return tmp; } void IOManager::writeFile(std::string filename, std::vector<std::string> lines){ std::string line; std::string total; char* filechar = new char[filename.size()+1]; filechar[filename.size()]=0; memcpy(filechar, filename.c_str(), filename.size()); std::ofstream file; file.open(filechar); for(int x = 0; x < lines.size(); x++){ file<<lines.at(x); std::cout<<lines.at(x); } file.close(); }<file_sep>#include "skilLib.h" #include "components.h" #include <string> #include <iostream> BarGraph::BarGraph(){ id = COMPONENT_BARGRAPH; gid = "nul"; maximum = x = y = dir = ratio = 0; } BarGraph::BarGraph(std::string gID, float centerx, float centery, float rat, float max, float orientation){ id = COMPONENT_BARGRAPH; gid = gID; x = centerx; y = centery; ratio = rat; maximum = max; dir = orientation; } Component *BarGraph::spawn(std::string sig, std::string args){ std::vector<std::string> arguments = splitForStrings(args, ' '); arguments.erase(arguments.begin()); if(sig.compare("sfffff") == 0){ return new BarGraph(arguments[0], stof(arguments[1]), stof(arguments[2]), stof(arguments[3]), stof(arguments[4]), stof(arguments[5])); } return new BarGraph(); } <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> extern Engine* theEngine; DepthSystem::DepthSystem(){ id = SYSTEM_DEPTH; } void DepthSystem::update(float delta){ bool isSorted = false; while(!isSorted){ isSorted = true; for(int i = 0; i < theEngine->numEntities()-1; i++){ Entity *ent1 = theEngine->getEntity(i); Entity *ent2 = theEngine->getEntity(i+1); int z1, z2;; if(ent1->hasComponent(COMPONENT_POSITION)){ z1 = static_cast<Position*>(ent1->getComponent(COMPONENT_POSITION))->getZ(); }else{ // Surely we'll never have more entities than that, right? z1 = -9001; } if(ent2->hasComponent(COMPONENT_POSITION)){ z2 = static_cast<Position*>(ent2->getComponent(COMPONENT_POSITION))->getZ(); }else{ // Surely we'll never have more entities than that, right? z2 = -9001; } if(z1 > z2){ theEngine->removeEntity(i); theEngine->addEntity(ent1); isSorted = false; } } } }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> LoadSceneMessage::LoadSceneMessage(){ scene = ""; messageType = MESSAGE_CHANGESCENE; } LoadSceneMessage::LoadSceneMessage(std::string s){ messageType = MESSAGE_CHANGESCENE; scene = s; }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "messages.h" ChangeBarGraphMessage::ChangeBarGraphMessage(){ messageType = MESSAGE_BARGRAPH_CHANGE; change = 0; target = "nul"; } ChangeBarGraphMessage::ChangeBarGraphMessage(std::string tar, float delta){ messageType = MESSAGE_BARGRAPH_CHANGE; target = tar; change = delta; } SetBarGraphMessage::SetBarGraphMessage(){ messageType = MESSAGE_BARGRAPH_SET; target = "nul"; value = 0; } SetBarGraphMessage::SetBarGraphMessage(std::string tar, float val){ messageType = MESSAGE_BARGRAPH_SET; target = tar; value = val; }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> extern Engine *theEngine; float scrollx; float scrolly; ScrollSystemHandler::ScrollSystemHandler(){ // Nothing doing } void ScrollSystemHandler::handle(Message *m, Entity *ent){ // Nothing doing here lol } void ScrollSystemHandler::handle(Message *m, System *sys){ ScrollSystem *ss = static_cast<ScrollSystem*>(sys); if(m->messageType == MESSAGE_SCROLL){ ScrollMessage *sm = static_cast<ScrollMessage*>(m); float cx = sm->changex; float cy = sm->changey; scrollx -=cx; scrolly -=cy; for(int i = 0; i < theEngine->numEntities(); i++){ Entity* ent = theEngine->getEntity(i); if(ent->hasComponent(COMPONENT_SCROLL) && ent->hasComponent(COMPONENT_POSITION)){ Position* pos = static_cast<Position*>(ent->getComponent(COMPONENT_POSITION)); pos->setX(pos->getX() - cx); pos->setY(pos->getY() - cy); } } } }<file_sep>#include <iostream> #include <string> using namespace std int main() { string test = "45"; int myint = stoi(test); cout << myint << '\n'; }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include <GL/gl.h> //#include <GL/glx.h> WindowSystem::WindowSystem(){ std::string str = "SkilLib test"; title = new char[str.length() + 1]; strcpy(title, str.c_str()); width = 512; height = 512; id = SYSTEM_WINDOW; initializeWindow(); } WindowSystem::WindowSystem(int gwidth, int gheight, std::string gtitle){ title = new char[gtitle.length() + 1]; strcpy(title, gtitle.c_str()); title = new char[gtitle.length() + 1]; strcpy(title, gtitle.c_str()); width = gwidth; height = gheight; id = SYSTEM_WINDOW; initializeWindow(); } void WindowSystem::update(float delta){ glfwSwapBuffers(window); glViewport(0,0,width,height); glClearColor(0.0f, 0.0f, 0.0f, 0.5f); glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); glFlush(); glTranslatef(0.0f,0.0f,-5.0f); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, width, 0.0, height, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glfwPollEvents(); if(glfwGetKey(window, GLFW_KEY_ESCAPE) || glfwWindowShouldClose(window)){ closeWindow(); } } void WindowSystem::initializeWindow(){ glfwInit(); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); window = glfwCreateWindow(width, height, title, NULL, NULL); if(!window){ glfwTerminate(); } glfwMakeContextCurrent(window); glfwSwapInterval(1); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void WindowSystem::closeWindow(){ glfwDestroyWindow(window); glfwTerminate(); shutDownEverything(); }<file_sep>#include <iostream> #include <stdio.h> #include <string> #include <GL/glew.h> #include <GLFW/glfw3.h> #include "SOIL.h" #include "skilLib.h" RegTexture::RegTexture(std::string gName){ name = gName; texture = SOIL_load_OGL_texture ( "res/defaultTexture.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT ); } RegTexture::RegTexture(std::string gName, std::string path){ name = gName.c_str(); const char* s = path.c_str(); texture = SOIL_load_OGL_texture ( s, SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y ); if( 0 == texture){ std::cout<<"SOIL: Error loading image (" << name << ", " << path << "): " << SOIL_last_result() << "\n"; texture = SOIL_load_OGL_texture ( "res/defaultTexture.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y ); } glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } void RegTexture::consoleDump(){ std::cout<<"Unmapped Texture. Name: " << name << " Address: " <<this<< " Tex Address: " << texture << "\n"; std::cout<<"===================================================\n"; }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" Color::Color(){ r = g = b = 0.0; a = 1.0; id = COMPONENT_COLOR; } Color::Color(float gr, float gg, float gb, float ga){ r = gr; g = gg; b = gb; a = ga; id = COMPONENT_COLOR; } Component* Color::spawn(std::string sig, std::string args){ std::vector<std::string> arguments = split(args, ' '); arguments.erase(arguments.begin()); if(sig.compare("ffff") == 0){ std::cout<<"Created new Color with values R:" << arguments[0] << " G:" << arguments[1] << " B:" << arguments[2] << " A:" << arguments[3] << "\n"; return new Color(stof(arguments[0]), stof(arguments[1]), stof(arguments[2]), stof(arguments[3])); } return new Color(); } float Color::getR(){ return r; } float Color::getG(){ return g; } float Color::getB(){ return b; } float Color::getA(){ return a; } void Color::setR(float get){ r = get; } void Color::setG(float get){ g = get; } void Color::setB(float get){ b = get; } void Color::setA(float get){ a = get; }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> #include "ld33.h" extern Engine *theEngine; WinLossSystemHandler::WinLossSystemHandler(){ // Nothing doing } void WinLossSystemHandler::handle(Message *m, Entity *ent){ // Nothing doing here lol } void WinLossSystemHandler::handle(Message *m, System *sys){ WinLossSystem *wl = static_cast<WinLossSystem*>(sys); if(m->messageType == MESSAGE_STRING){ StringMessage *sm = static_cast<StringMessage*>(m); if(sm->message == "WINPROGRESS") wl->winprogress++; if(sm->message == "notoriety+") wl->notoriety++; if(sm->message == "notoriety-") wl->notoriety--; } }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" Component::Component(){ id = COMPONENT_NONE; } Component::~Component(){ } int Component::getID(){ return id; } void Component::setID(int getid){ id = getid; } <file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" #include <math.h> ScrollMessage::ScrollMessage(){ messageType = MESSAGE_SCROLL; changex = changey = 0; } ScrollMessage::ScrollMessage(float cx, float cy){ messageType = MESSAGE_SCROLL; changex = cx; changey = cy; }<file_sep>#include "skilLib.h" #include "components.h" #include <string> #include <iostream> TextMessage::TextMessage(){ id = COMPONENT_TEXTMESSAGE; message = "Hello, World!"; font = "monospaceWhite"; fontSize = 32; padding = 5; } TextMessage::TextMessage(std::string msg, std::string fnt, int size){ id = COMPONENT_TEXTMESSAGE; message = msg; font = fnt; fontSize = size; padding = 5; } TextMessage::TextMessage(std::string msg, std::string fnt, int size, int pad){ id = COMPONENT_TEXTMESSAGE; message = msg; font = fnt; fontSize = size; padding = pad; } Component *TextMessage::spawn(std::string sig, std::string args){ std::vector<std::string> arguments = splitForStrings(args, ' '); arguments.erase(arguments.begin()); if(sig.compare("ssi") == 0){ return new TextMessage(arguments[0], arguments[1], stoi(arguments[2])); } if(sig.compare("ssii") == 0){ return new TextMessage(arguments[0], arguments[1], stoi(arguments[2]), stoi(arguments[3])); } return new TextMessage(); } int TextMessage::getSize(){ return fontSize; } int TextMessage::getPadding(){ return padding; } std::string TextMessage::getMessage(){ return message; } std::string TextMessage::getFont(){ return font; } void TextMessage::setSize(int size){ if(size > 0) fontSize = size; } void TextMessage::setPadding(int pad){ padding = pad; } void TextMessage::setMessage(std::string msg){ message = msg; } void TextMessage::setFont(std::string fnt){ font = fnt; }<file_sep>#include <iostream> #include <ctime> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <string.h> #include <vector> #include "SOIL.h" #include "skilLib.h" #include "systems.h" #include "components.h" #include "messages.h" StringMessageOnClick::StringMessageOnClick(){ message = "null"; id = COMPONENT_STRINGMESSAGEONCLICK; } StringMessageOnClick::StringMessageOnClick(std::string msg){ message = msg; id = COMPONENT_STRINGMESSAGEONCLICK; } Component* StringMessageOnClick::spawn(std::string sig, std::string args){ std::vector<std::string> arguments = split(args, ' '); arguments.erase(arguments.begin()); if(sig.compare("s") == 0){ return new StringMessageOnClick(arguments[0]); } return new StringMessageOnClick(); }
a846c10dcb46fdf5beaf7c4e1b4244fa81a18568
[ "Markdown", "Text", "C++" ]
62
C++
askillin/LD33
484db4800bd600d3f002cc8d014e79761424d4b4
cfe314b0e041629e858e5ea110c554ca9278656e
refs/heads/master
<file_sep>import 'antd/lib/index.css'; import './framework.css';<file_sep>#webpack示例项目 *基于ant.design* ##evn ``` node 4.x ``` ##dev ``` sudo npm install webpack -g sudo npm install webpack-dev-server -g npm install npm run dev-server ``` ##build ``` npm run build-dev //build-test build-pro ``` ##约定 - 每个页面为一个单独组件,每个页面所用到的资源都放到一个文件夹下面,比如home ``` home -img -home.jpg -home.jsx -style.less ``` - 所有的get请求最终没有被截获的都打到index.html ##需要学习的内容 - React基础语法 - React Router插件 - React Flux应用架构 ##待解决问题 - 执行构建有些慢 - 根据地址定位左侧菜单 目前使用全局持有菜单句柄的方法,有点恶心,有没有好一点的方法? - 根据左侧菜单修改右上角对应的面包屑 - 由于这个是一个单页面应用,从新发送ajax请求的时候,一些ajax请求需要被打断,否则用户网络情况不好,点击了多个按钮,最终不能确定哪个ajax会被执行,会导致页面错乱问题. - 组件之间的通信 - 父级->子级 props - 子级->父级 props传递事件? - 没有级联关系组件之间 flux - 同一个组件,使用不同的react-router path,会导致这个组件渲染页面特变慢 ``` 比如: path: 'aaaaa', component: Dashboard path: 'bbbbb', component: Dashboard 这样一个路由,会导致Dashboard渲染页面特别慢 ``` ##报错 ``` webpack.config.js中使用argv报错: Option '-d' not supported. Trigger 'webpack -h' for more details. 目前自己写了个循环处理传入的参数 ``` ##dev-server 结合webpack-dev-server 可以做到代码改动,浏览器自动刷新. *使用webpack-dev-server 作为静态服务器,以--inline方式启动,js中会添加热刷新相关的代码.前后端各添加一个开发服务器的配置,对项目基本无侵入.* nodejs为例: - 后台正式服务器添加一个启动模式: ``` exports.devserver = { static_url_prefix: 'http://localhost:8086/s/' //这个指向webpack-dev-server服务器 }; ``` - 前端webpack添加一个启动模式: ``` "devserver": { "path": '../public', "publicPath": 'http://localhost:8086/s/' //这个指向webpack-dev-server服务器 }, ``` - webpack-dev-server 启动方式:(以devserver方式启动) ``` webpack-dev-server --port 8086 --cfg.clean=false --cfg.runmod=devserver --progress --inline ``` - 后端启动方式:(以devserver方式启动) ``` PORT=3001 NODE_ENV=devserver npm start ``` - 浏览器输入下面连接访问,就可以达到热刷新,尤其适合刷屏 调整页面细节情况. ``` http://localhost:3001/ ``` <file_sep>import './style.less'; import React from 'react'; import ReactDOM from 'react-dom'; import {message, Breadcrumb, Button } from 'antd' import Page from '../page/Page'; import Request from '../request/Request'; var hideLoading = null; /* * 更新state之后触发的方法: * shouldComponentUpdate * componentWillUpdate * render * componentDidUpdate * * 向DOM中加入组件触发的方法: * getDefaultProps //在组件类创建的时候调用一次,以后在向DOM中添加组件就不会调用此方法. * getInitialState * componentWillMount * render * componentDidMount //发送 AJAX 请求,可以在该方法中执行这些操作 * * 组件从 DOM 中移除的时候立刻被调用 * componentWillUnmount * 在组件接收到新的 props 的时候调用。在初始化渲染的时候,该方法不会调用。 * componentWillReceiveProps * * * */ /* * 组件是 React 里复用代码最佳方式,但是有时一些复杂的组件间也需要共用一些功能。 * 有时会被称为 跨切面关注点。React 使用 mixins 来解决这类问题。 * */ let SetIntervalMixin = { getInitialState(){ return { loadingClass: '' } }, componentWillMount: function () { this.intervals = []; }, setInterval: function () { this.intervals.push(setInterval.apply(null, arguments)); }, componentWillUnmount: function () { this.intervals.map(clearInterval); /* * 组件被移除DMO,清除未完成的ajax * */ this.req.abort(); if (this.hideLoading) { this.hideLoading(); this.hideLoading = null; } }, get(url, {data={},end=function () { }}){//带有默认值的函数,写的好难看... let that = this; that.hideLoading = message.loading('正在加载...', 0); that.setState({ loadingClass: 'loading' }); that.req = Request .get(url) .query(data) .end(function (err, res) { end(err, res); if (that.hideLoading) { that.hideLoading(); that.hideLoading = null; } that.setState({ loadingClass: '' }); }); } }; const Dashboard = React.createClass({ /* * 在组件挂载之前调用一次。返回值将会作为 this.state 的初始值。 * */ getInitialState(){ console.log('getInitialState'); return { seconds: 0, testAjax: 'testAjax' } }, /* * 在组件类创建的时候调用一次,然后返回值被缓存下来。 * 如果父组件没有指定 props 中的某个键,则此处返回的对象中的相应属性将会合并到 this.props (使用 in 检测属性)。 * */ getDefaultProps(){ console.log('getDefaultProps'); return { test: 'I\'m a test' } }, /* * 指定props类型,如果类型不对,浏览器控制台会输出警告,但是不会抛错. * */ propTypes: { test: React.PropTypes.string }, /* * 引用 mixin * */ mixins: [SetIntervalMixin], /* * statics 对象允许你定义静态的方法,这些静态的方法可以在组件类上调用。 * 调用方法:Dashboard.customMethod('bar') * * 在这个块儿里面定义的方法都是静态的,意味着你可以在任何组件实例创建之前调用它们,这些方法不能获取组件的 props 和 state。 * 如果你想在静态方法中检查 props 的值,在调用处把 props 作为参数传入到静态方法。 * */ statics: { customMethod: function (foo) { return foo === 'bar'; } }, /* * 服务器端和客户端都只调用一次,在初始化渲染执行之前立刻调用。 * 如果在这个方法内调用 setState,render() 将会感知到更新后的 state,将会执行仅一次,尽管 state 改变了。 * */ componentWillMount(){ console.log('componentWillMount'); }, /* * 在初始化渲染执行之后立刻调用一次,仅客户端有效(服务器端不会调用)。 * 在生命周期中的这个时间点,组件拥有一个 DOM 展现,你可以通过 this.getDOMNode() 来获取相应 DOM 节点。 * * 如果想和其它 JavaScript 框架集成,使用 setTimeout 或者 setInterval 来设置定时器,或者发送 AJAX 请求,可以在该方法中执行这些操作。 * */ componentDidMount: function () { console.log('componentDidMount'); //console.log(this.getDOMNode());// 过时了 //console.log(ReactDOM.findDOMNode(this)); this.setInterval(this.tick, 5000); // 调用 mixin 的方法 let that = this; that.get('/dashboard.json', { data: {query: 'Manny', range: '1..5', order: 'desc'}, end(err, res) { console.log(err, res); console.log(res.body); that.setState({ testAjax: res.body.name }); } }); }, /* * 在接收到新的 props 或者 state,将要渲染之前调用。该方法在初始化渲染的时候不会调用,在使用 forceUpdate 方法的时候也不会。 * 如果确定新的 props 和 state 不会导致组件更新,则此处应该 返回 false。 * */ shouldComponentUpdate(nextProps, nextState){ console.log('shouldComponentUpdate'); return true; }, /* * 在接收到新的 props 或者 state 之前立刻调用。在初始化渲染的时候该方法不会被调用。 * 使用该方法做一些更新之前的准备工作。 * */ componentWillUpdate(nextProps, nextState){ console.log('componentWillUpdate'); }, /* * 在组件的更新已经同步到 DOM 中之后立刻被调用。该方法不会在初始化渲染的时候调用。 * 使用该方法可以在组件更新之后操作 DOM 元素。 * */ componentDidUpdate(prevProps, prevState){ console.log('componentDidUpdate'); }, /* * 在组件从 DOM 中移除的时候立刻被调用。 * 在该方法中执行任何必要的清理,比如无效的定时器,或者清除在 componentDidMount 中创建的 DOM 元素。 * 清理未返回的ajax?? * */ componentWillUnmount(){ console.log('componentWillUnmount'); }, /* * 在组件接收到新的 props 的时候调用。在初始化渲染的时候,该方法不会调用。 * 用此函数可以作为 react 在 prop 传入之后, render() 渲染之前更新 state 的机会。老的 props 可以通过 this.props 获取到。 * 在该函数中调用 this.setState() 将不会引起第二次渲染。 * */ componentWillReceiveProps(nextProps){ console.log('componentWillReceiveProps'); }, tick: function () { this.setState({seconds: this.state.seconds + 1}); }, handleClick(){ let that = this; that.get('/dashboard.json', { end(err, res) { console.log(err, res); console.log(res.body); that.setState({ testAjax: res.body.name }); } }); }, render() { console.log('render'); return ( <Page className={this.state.loadingClass}> <div id="admin-page-header" className="admin-page-header"> <h1 className="admin-page-header-title">Dashboard</h1> <Breadcrumb> <Breadcrumb.Item>首页</Breadcrumb.Item> <Breadcrumb.Item href="">应用中心</Breadcrumb.Item> <Breadcrumb.Item href="">应用列表</Breadcrumb.Item> <Breadcrumb.Item>某应用</Breadcrumb.Item> </Breadcrumb> </div> <div className="admin-page-content"> <div className={"admin-page-content-inner "}> <div className="dashboard"> <Button type="primary" onClick={this.handleClick}>发起ajax请求</Button> <Button>次按钮</Button> <Button type="ghost">幽灵按钮</Button> <Button type="dashed">虚线按钮</Button> <p>npm run server 运行一个server 并且打开默认浏览器!</p> <p>开发过程中,修改文件,浏览器会自动刷新,特别适合双屏/大屏开发!</p> <p>随着项目复杂度的增加,不知道会不会慢。目前的相应速度还是可以接受的。</p> <p>希望不卡吧。哈哈。写起来真的就挺爽了。一保存浏览器就自动刷新了。想你的时候,你在哪里?</p> <p>如何优化构建速度?哈哈快一些</p> <p>{this.props.test}</p> <p> React has been running for {this.state.seconds} seconds. </p> <p>ajax result: {this.state.testAjax}</p> </div> </div> </div> </Page> ); } }); console.log(Dashboard.customMethod('bar')); export default Dashboard; <file_sep>import './style.css'; import React from 'react'; import ReactDOM from 'react-dom'; import { Menu} from 'antd'; import {getMenus} from '../MenusAndRouts' const Sidebar = React.createClass({ getInitialState() { _sidebar = this; var menus = getMenus(this.props.collapse); return { current: menus.current, openKeys: menus.openKeys }; }, handleClick(e) { console.log('click menu', e); this.setState({ current: e.key, openKeys: e.keyPath.slice(1) // 点击是会关闭其他菜单,如果不需要改变其他菜单状态,注释掉这里即可. }); }, onToggle(info){ if(this.props.collapse) return;//折叠状态时,不改变打开菜单状态,否则切回展开状态,无法恢复打开状态. this.setState({ openKeys: info.openKeys }); }, render() { return ( <div className="admin-sidebar" style={{width:this.props.collapse?60:240,overflow:this.props.collapse?'visible':'auto'}}> <Menu openKeys={this.state.openKeys} selectedKeys={[this.state.current]} onClick={this.handleClick} onOpen={this.onToggle} onClose={this.onToggle} style={{marginLeft:-8}} mode={this.props.collapse?'vertical':'inline'}> {getMenus(this.props.collapse).menus} </Menu> </div> ); } }); export default Sidebar; <file_sep>import './style.css'; import React from 'react'; import { Breadcrumb } from 'antd' import Page from '../page/Page'; const Dashboard = React.createClass({ render() { return ( <Page> <div id="admin-page-header" className="admin-page-header"> <h1 className="admin-page-header-title">Dashboard</h1> <Breadcrumb> <Breadcrumb.Item>首页</Breadcrumb.Item> <Breadcrumb.Item href="">应用中心</Breadcrumb.Item> <Breadcrumb.Item href="">应用列表</Breadcrumb.Item> <Breadcrumb.Item>某应用</Breadcrumb.Item> </Breadcrumb> </div> <div className="admin-page-content"> <div className="admin-page-content-inner"> <h1>首页</h1> </div> </div> </Page> ); } }); export default Dashboard; <file_sep>#!/usr/bin/env bash supervisor -w ./app,./configs ./bin/run.js<file_sep># www-nodejs-ant-design-web nodejs 结合ant.design demo项目 ##项目中使用的技术/框架 TODO 把对应的官网网址写到下面。 - nodejs - express - mongoDB - ant.design - webpack ##纠结的问题 - 所有的文件命名用不用都加后缀?user_dao.js user_controller.js user_model.js ##启动项目 指定端口 启动模式 > PORT=1234 NODE_ENV=test npm start 全局安装supervisor > sudo npm install -g supervisor 如果安装成功了,但是命令还是不可用,可能由于nmp没有设置号,运行如下命令,创建一个软连接: > sudo ln -s /usr/local/srv/node-v5.0.5-linux-x64/bin/supervisor /usr/bin/supervisor 自动重启 > cd bin > supervisor -w ../app,../configs run.js > PORT=1234 NODE_ENV=test supervisor -w ../app,../configs run.js -w 参数为逗号分割的文件或路径,当这里的文件改变,将自动重启app.js,这里监听的是app目录和configs目录 前端相关说明请参见:assets/README.md <file_sep>import './style.less'; import React from 'react'; import { Breadcrumb, Button } from 'antd' import {Link} from 'react-router' import createBrowserHistory from 'history/lib/createBrowserHistory' const browserHistory = createBrowserHistory(); import Page from '../page/Page'; export default React.createClass({ goBack(){ browserHistory.goBack() }, render() { return ( <Page> <div id="admin-page-header" className="admin-page-header"> <h1 className="admin-page-header-title">NotFound</h1> <Breadcrumb> <Breadcrumb.Item><Link to="home">首页</Link></Breadcrumb.Item> <Breadcrumb.Item>未找到</Breadcrumb.Item> </Breadcrumb> </div> <div className="admin-page-content"> <div className="admin-page-content-inner"> <h1>404</h1> <p>您访问的页面不存在</p> <Button onClick={this.goBack}><Link to="javascript:;">返回上一级</Link></Button> <Button> <Link to="home">返回首页</Link></Button> </div> </div> </Page> ); } }); <file_sep>import Request from 'superagent'; export default Request;<file_sep>import './style.less'; import React from 'react'; const Page = React.createClass({ render() { return ( <div className= {"admin-page " + this.props.className}> <div className="admin-page-loading"></div> {this.props.children} </div> ); } }); export default Page; <file_sep>#!/usr/bin/env bash cd assets && npm run build-watch<file_sep>import '../common/lib'; import Routes from '../component/Routes'; import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render(<Routes />, document.getElementById('framework')); <file_sep>import React from 'react'; import { Menu, Icon } from 'antd'; import FAIcon from './faicon/FAIcon'; import {Link} from 'react-router' const SubMenu = Menu.SubMenu; import MyForm from '../component/myform/MyForm' import Dashboard from '../component/dashboard/Dashboard' import MyTime from '../component/mytime/MyTime' const openAll = false; var oriMenus = [//左侧菜单与路由公用的数据 {key: '1', text: '主面板', icon: 'fa-tachometer'/*, open: true*/}, {key: '11', parentKey: '1', text: '仪表盘', icon: 'fa-arrow-right', /* current: true,*/ path: 'dashboard1', component: Dashboard}, {key: '12', parentKey: '1', text: '三级导航', icon: 'fa-th-list'}, {key: '121', parentKey: '12', text: '我的表单', icon: 'fa-arrow-right', path: 'myForm1', component: MyForm}, {key: '122', parentKey: '12', text: '我的时间', icon: 'fa-arrow-right', path: 'myTime1', component: MyTime}, {key: '2', text: '商务查询', icon: 'fa-binoculars'}, {key: '21', parentKey: '2', text: '仪表盘222', icon: 'fa-arrow-right', path: 'dashboard2', component: Dashboard}, {key: '22', parentKey: '2', text: '三级导航222', icon: 'fa-th-list'}, {key: '221', parentKey: '22', text: '我的表单', icon: 'fa-arrow-right', path: 'myForm2', component: MyForm}, {key: '222', parentKey: '22', text: '我的时间', icon: 'fa-arrow-right', path: 'myTime2', component: MyTime}, {key: '3', text: '用户列表', icon: 'fa-th-list'}, {key: '31', parentKey: '3', text: '仪表盘', icon: 'fa-arrow-right', path: 'dashboard3', component: Dashboard}, {key: '32', parentKey: '3', text: '我的表单', icon: 'fa-arrow-right', path: 'myForm3', component: MyForm}, {key: '33', parentKey: '3', text: '我的时间', icon: 'fa-arrow-right', path: 'myTime3', component: MyTime}, {key: '4', text: '我的', icon: 'fa-user'}, {key: '41', parentKey: '4', text: '我的邮件', icon: 'fa-arrow-right', path: 'dashboard4', component: Dashboard}, {key: '42', parentKey: '4', text: '我的提醒', icon: 'fa-arrow-right', path: 'myForm4', component: MyForm}, {key: '43', parentKey: '4', text: '个人设置', icon: 'fa-arrow-right', path: 'myTime4', component: MyTime} ]; /* *根据sildebarMenus构造routes。 *rows:菜单数据。 */ function convert(rows, collapse) { function exists(rows, parentKey) { for (let i = 0; i < rows.length; i++) { if (rows[i].key == parentKey) return true; } return false; } var menus = []; var nodes = []; var openKeys = []; var current = ''; var oriMenus = {}; // 获得所有顶级菜单 处理菜单初始化状态 for (let i = 0; i < rows.length; i++) { let row = rows[i]; row.subMenus = [];//存放当前菜单的子菜单 oriMenus[row.key] = row; if (openAll) { if (!row.path) { openKeys.push(row.key); } } else if (row.open) { openKeys.push(row.key); } if (row.current) { current = row.key; } if (!exists(rows, row.parentKey)) { nodes.push(row); menus.push( <SubMenu key={row.key} title={<span><FAIcon type={row.icon} />{collapse?'':row.text}</span>}> {row.subMenus} </SubMenu> ) } } var toDo = []; for (let i = 0; i < nodes.length; i++) { toDo.push(nodes[i]); } while (toDo.length) { var node = toDo.shift();// 父菜单 var subMenus = node.subMenus; // 处理子菜单 for (let i = 0; i < rows.length; i++) { let row = rows[i]; if (row.parentKey == node.key) { var child = row; if (child.path) {//含有path,就说明没有子菜单了. subMenus.push( <Menu.Item key={child.key}> <FAIcon type={child.icon}/> <Link to={child.path} activeClassName="active">{child.text}</Link> </Menu.Item> ); } else {// 含有子菜单 subMenus.push( <SubMenu key={child.key} title={<span><FAIcon type={child.icon} />{child.text}</span>}> {child.subMenus} </SubMenu> ); } if (node.childRoutes) { node.childRoutes.push(child); } else { node.childRoutes = [child]; } toDo.push(child); } } } return { routs: nodes,//具有层级关系的路由 menus: menus, oriMenus: oriMenus, openKeys: openKeys, current: current }; }// end or convert(rows) var collapseData = convert(oriMenus, true); var noCollapseData = convert(oriMenus, false); export function getMenus(collapse) { return collapse ? collapseData : noCollapseData; } export var MenuRouts = { routs: noCollapseData.routs, oriMenus: oriMenus };
010010862bda1a782781f2b9ade6aa9575b2b71e
[ "JavaScript", "Markdown", "Shell" ]
13
JavaScript
love-peach/www-nodejs-ant-design-web
894abf207a29750d020f5a46dbd3a173570aa2b0
0ddebbf00c247b43787611c3be9829fde845cd84
refs/heads/master
<file_sep>from .models import TodoItem from django.shortcuts import render from .serializers import TodoItemSerializer from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated class TodoItemViewSet(viewsets.ModelViewSet): queryset = TodoItem.objects.all().order_by('createdAt') serializer_class = TodoItemSerializer # permission_classes = [IsAuthenticated] <file_sep>const csrfToken = '<KEY>'; export default class TodoItemService { constructor(){ this._apiBase = 'http://127.0.0.1:8000'; } async getItems (url) { const res = await fetch(`${this._apiBase}${url}`); if (!res.ok){throw new Error(`Ошибка при оброботке ${url}, статус ${res.status}`)} return await res.json(); } async createItem(url,data){ const res = await fetch(`${this._apiBase}${url}`,{ method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken.value }, body: JSON.stringify(data) }); if (!res.ok){throw new Error(`Ошибка при оброботке ${url}, статус ${res.status}`)} return await res.json(); } async deleteItem(url){ const res = await fetch(`${this._apiBase}${url}`,{ method: 'DELETE', }); if (!res.ok){throw new Error(`Ошибка при оброботке ${url}, статус ${res.status}`)} return await res.json(); } async updateItem(url,data){ const res = await fetch(`${this._apiBase}${url}`,{ method: 'PUT', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken.value }, body: JSON.stringify(data) }); if (!res.ok){throw new Error(`Ошибка при оброботке ${url}, статус ${res.status}`)} return await res.json(); } getAllTodos(){ return this.getItems(`/api/v1/todo/`); } getTodoById(id){ return this.getItems(`/api/v1/todo/${id}/`); } createTodo(data){ return this.createItem(`/api/v1/todo/`,data); } deleteTodo(id){ return this.deleteItem(`/api/v1/todo/${id}/`); } updateTodo(id,data){ return this.updateItem(`/api/v1/todo/${id}/`,data); } }<file_sep># Generated by Django 3.2 on 2021-04-30 09:37 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='TodoItem', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('task', models.CharField(max_length=255)), ('isDone', models.BooleanField(default=False)), ('createdAt', models.DateTimeField(auto_now=True)), ], options={ 'verbose_name': 'Задача', 'verbose_name_plural': 'Задачи', }, ), ] <file_sep>from django.db import models from django.db.models import fields from .models import TodoItem from rest_framework import serializers class TodoItemSerializer(serializers.ModelSerializer): class Meta: model = TodoItem fields = ['id','task','isDone','createdAt']<file_sep>from django.urls import path,include from rest_framework import routers from .views import TodoItemViewSet router = routers.DefaultRouter() router.register(r'todo',TodoItemViewSet) urlpatterns = [ path('',include(router.urls)) ]<file_sep>import {React} from 'react'; export default function TodoItem({todo}) { return ( <div> <div className="todo-item"> <p>{todo.task}</p> <button>{todo.isDone}</button> </div> </div> ); } <file_sep>from django.db import models # Create your models here. class TodoItem(models.Model): task = models.CharField(max_length=255) isDone = models.BooleanField(default=False) createdAt = models.DateTimeField(auto_now=True) def __str__(self): return self.task class Meta: verbose_name = 'Задача' verbose_name_plural = 'Задачи'
fca1edf135c49edf08a51d6758a18b0bffe69309
[ "JavaScript", "Python" ]
7
Python
BakdauletBolatE/myfirstTodo
c8e9f29afca06ce2198847770c777f96c09eefbb
9d1daa8ac08806524dff1cc975d165dca8fb1b1f
refs/heads/master
<file_sep># Instrumentation example ## Build * ``cd mkdir build`` * ``export LLVM_DIR=/path/to/llvm-build/lib/cmake/llvm`` * ``cmake ..`` * ``make`` ## Run test * ``clang -Xclang -load -Xclang MyFunctionPass/libMyFunctionPass.so test.c -c`` * ``clang test.o libtest.c`` <file_sep># Install LLVM ## Download LLVM from github git clone https://github.com/llvm/llvm-project.git ## Config and build LLVM and Clang * ``cd llvm-project`` * ``mkdir build`` * ``cd build`` * ``cmake -G <generator> [options] ../llvm`` For example, if you want to build only LLVM and Clang on Linux with release version, you can run: * ``cmake -DLLVM_ENABLE_PROJECTS=clang -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release ../llvm-project/llvm/`` If you want to build with libcxx and libcxxabi, you can run: * ``cmake -DLLVM_ENABLE_PROJECTS="clang;libcxx;libcxxabi" -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release ../llvm-project/llvm/`` Some common build system generators are: * ``Ninja`` --- for generating [Ninja](https://ninja-build.org) build files. Most llvm developers use Ninja. * ``Unix Makefiles`` --- for generating make-compatible parallel makefiles. * ``Visual Studio`` --- for generating Visual Studio projects and solutions. * ``Xcode`` --- for generating Xcode projects. Some Common options: * ``-DLLVM_ENABLE_PROJECTS='...'`` --- semicolon-separated list of the LLVM sub-projects you'd like to additionally build. Can include any of: clang, clang-tools-extra, libcxx, libcxxabi, libunwind, lldb, compiler-rt, lld, polly, or debuginfo-tests. For example, to build LLVM, Clang, libcxx, and libcxxabi, use ``-DLLVM_ENABLE_PROJECTS="clang;libcxx;libcxxabi"``. * ``-DCMAKE_INSTALL_PREFIX=directory`` --- Specify for *directory* the full path name of where you want the LLVM tools and libraries to be installed (default ``/usr/local``). * ``-DCMAKE_BUILD_TYPE=type`` --- Valid options for *type* are Debug, Release, RelWithDebInfo, and MinSizeRel. Default is Debug. * ``-DLLVM_ENABLE_ASSERTIONS=On`` --- Compile with assertion checks enabled (default is Yes for Debug builds, No for all other build types). * ``cmake --build . [-- [options] <target>]`` or your build system specified above directly. * The default target (i.e. ``ninja`` or ``make``) will build all of LLVM. * The ``check-all`` target (i.e. ``ninja check-all``) will run the regression tests to ensure everything is in working order. * CMake will generate targets for each tool and library, and most LLVM sub-projects generate their own ``check-<project>`` target. * Running a serial build will be **slow**. To improve speed, try running a parallel build. That's done by default in Ninja; for ``make``, use the option ``-j NNN``, where ``NNN`` is the number of parallel jobs, e.g. the number of CPUs you have. <file_sep>#include "llvm/Pass.h" #include "llvm/IR/Function.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" using namespace llvm; namespace { class MyFunctionPass : public FunctionPass { public: static char ID; MyFunctionPass() : FunctionPass(ID) {} virtual bool runOnFunction(Function &F) { outs() << "Hello: "; outs().write_escaped(F.getName()) << "\n"; return false; } }; } char MyFunctionPass::ID = 0; static RegisterPass<MyFunctionPass> X("myfunction", "My Function Pass"); static void registerPass(const PassManagerBuilder &, legacy::PassManagerBase &PM) { PM.add(new MyFunctionPass()); } static RegisterStandardPasses RegisterTheSpindlePass(PassManagerBuilder::EP_EarlyAsPossible, registerPass); <file_sep>#include "llvm/Pass.h" #include "llvm/IR/Function.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Type.h" using namespace llvm; namespace { class MyFunctionPass : public FunctionPass { public: static char ID; static uint64_t functionID; MyFunctionPass() : FunctionPass(ID) {} virtual bool runOnFunction(Function &F) { outs() << functionID ++ << "\n"; outs() << "Hello: "; outs().write_escaped(F.getName()) << "\n"; auto BBBegin = F.begin(); auto InstBegin = BBBegin->begin(); IRBuilder<> Builder(BBBegin->getFirstNonPHI()); std::vector<Type *> argsType; auto funcID = ConstantInt::get(Type::getInt64Ty(F.getContext()), functionID); argsType.push_back(Type::getInt64Ty(F.getContext())); ArrayRef<Type *> argsRef(argsType); auto funcType = FunctionType::get(Builder.getVoidTy(), argsRef, false); auto M = F.getParent(); auto recordMallocFunc = M->getOrInsertFunction("__enter_function", funcType); Builder.CreateCall(recordMallocFunc, {funcID}); return false; } }; } char MyFunctionPass::ID = 0; uint64_t MyFunctionPass::functionID = 0; static RegisterPass<MyFunctionPass> X("myfunction", "My Function Pass"); static void registerPass(const PassManagerBuilder &, legacy::PassManagerBase &PM) { PM.add(new MyFunctionPass()); } static RegisterStandardPasses RegisterTheSpindlePass(PassManagerBuilder::EP_EarlyAsPossible, registerPass);
a9d614571460eb2587881934a9aa1102d4e23cf1
[ "Markdown", "C++" ]
4
Markdown
xinxin1000/llvm-examples
ff411c93693824dbe37fd1922f8d70aac59a2e56
c340df759e5b9772abea847d7cebfca401198da9
refs/heads/master
<file_sep># Source .bashrc # Only edit .bashrc if [ -f ~/.bashrc ]; then source ~/.bashrc fi <file_sep>#!/usr/bin/env bash function symlink { ln -nsf $1 $2 } for file in dotfiles/.[^.]*; do if [[ $file != "dotfiles/.DS_Store" ]]; then path="$(pwd)/$file" base="$(basename $file)" target="$HOME/$base" echo "linking $base" rm -rf target symlink $path $target fi done<file_sep>#!/bin/sh function append { DOSSIER_COMMIT=$(git log --format="$(basename "$PWD"), %H, %ai, %s" -1) cd ~/Code/dossier git pull --rebase && \ cd - && \ echo $DOSSIER_COMMIT >> ~/Code/dossier/commits && \ cd ~/Code/dossier && \ git add -A && \ git commit -m "$DOSSIER_COMMIT" && \ git push cd - } append > /dev/null 2>&1<file_sep># Dev Config A repo for the things I need to get an osx dev machine up and running. Dotfiles should also work for linux. <file_sep># OSX - Preferences -> Trackpad -> Uncheck Scroll Direction Natural - Preferences -> Energy Saver -> Battery -> Uncheck Slightly Dim<file_sep># Mac Apps - 1Password - Alfred - AppCleaner - Audacity - Chromium - Cyberduck - Divvy - Dropbox - Firefox - GIMP - HeyFocus - ImageOptim - LICEcap - MacVim - MAMP - MS Office - MuseScore - Omnifocus - PIA - Postman - Sequel Pro - Slack - Sourcetree - Spotify - Sublime - Tunnelblick - uTorrent - VirtualBox - VS Code - VLC - Xcode <file_sep># Prompt #PS1="\[\e[0;32m\]\W\[\e[m\\e[1;37m\] λ \[\e[m\]" source ~/.bash-powerline # Generic bin paths PATH=$PATH:/usr/local/bin PATH=$PATH:/opt/local/bin PATH=$PATH:/usr/local/sbin # App-specific Paths PATH=$PATH:$HOME/.npm-global/bin PATH=$PATH:$HOME/.composer/vendor/bin PATH=$PATH:$HOME/Code/go/bin PATH=$PATH:$HOME/.cabal/bin PATH=$PATH:$HOME/.gem/ruby/2.6.0/bin PATH=$PATH:/Library/Developer/Toolchains/swift-latest.xctoolchain/usr/bin PATH=/usr/local/opt/ruby/bin:$PATH export PATH # Specific Paths export NODE_PATH="/usr/local/lib/node_modules" export GOPATH="/Users/$USER/Code/go/" export GOROOT="/usr/local/go" # thefuck eval $(thefuck --alias) # rvm [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Util functions function md () { mkdir -p "$@" && eval cd "\"\$$#\""; } # Set Default Editor export EDITOR="/usr/bin/vim" # git Completion if [ -f ~/.git-completion ]; then . ~/.git-completion fi # Bash Completion bind "set completion-ignore-case on" bind "set show-all-if-ambiguous on" # Colors alias ls='ls -GFh' # Alias alias ll='ls -al' alias rm="echo Use 'del', or the full path i.e. '/bin/rm'" alias del='rmtrash' # History export HISTTIMEFORMAT="%d/%m/%y %T "
d2ee64c063cee64df44d2b860d130397bbc13cd7
[ "Markdown", "Shell" ]
7
Shell
garrettreed/config
ebd581564f1830f91efd6463fdc682e22b2e2a35
57c20d534704c52596b74b37f1308abc04fc4094
refs/heads/master
<file_sep>using ClickHouse.Ado; using ClickHouse.Net; using ClickHouse.Net.Entities; using System; using System.Collections.Generic; using System.Linq; namespace ConnectApp { class Program { private const string host = "localhost"; private const string port = "9000"; private const string username = "default"; private const string password = ""; private const string database = "datasets"; private const string tableName = "events"; private static readonly string ConnectionString = $"Compress=True;CheckCompressedHash=False;Compressor=lz4;Host={host};Port={port};User={username};Password={password};SocketTimeout=600000;Database={database};"; static void Main(string[] args) { var db = new ClickHouseDatabase( new ClickHouseConnectionSettings(ConnectionString), new ClickHouseCommandFormatter(), new ClickHouseConnectionFactory(), null, new DefaultPropertyBinder()); var columns = db.DescribeTable(tableName).ToArray(); var text = string.Join("\n", columns.Select(c => $"{c.Name}: {c.Type}")); Console.WriteLine($"table description: {text}"); // db.Open(); // need to check database / table exists first? // var command = objToInsert.GetInsertCommand(); // db.ExecuteNonQuery(command); // command = $"SELECT count(*) FROM {tableName}"; // var resultItem = db.ExecuteQueryMapping<long>(command, convention: new UnderscoreNamingConvention()).Single(); // db.Close(); } } } <file_sep># My Clickhouse Test Test of ClickHouse db (usage, tooling, platforms, performance, etc). Includes: - Data Generator script - Query Scripts - .NET Connection example apps ## Requirements - [.NET SDK](https://dotnet.microsoft.com/download) - clickhouse-server - clickhouse-client - [WSL](https://docs.microsoft.com/en-us/windows/wsl/install-win10) (optional) - [Powershell Core](https://github.com/PowerShell/PowerShell) (optional) ### Data generator script Runs on any dotnet environment that supports fsi ([dotnet core SDK out of the box](https://dotnet.microsoft.com/download)). ## Usage Setup server, connect and create required databases & tables. ### Create schema ```SQL CREATE DATABASE datasets ``` ```SQL CREATE TABLE datasets.events ( `Uid` UUID, `GroupId` UUID, `Reference` String, `State` Enum( 'created' = 1, 'requested' = 2, 'received' = 3, 'approved' = 4, 'rejected' = 5 ), `Errors` Array(String), `OccurredAt` DateTime, `InsertedAt` DateTime ) ENGINE = MergeTree() PARTITION BY toYYYYMM(OccurredAt) ORDER BY (OccurredAt, GroupId, Uid); ``` ### Data Generator script Change config options at the top of the file then run ``` dotnet fsi generatedata.fsx ``` An output of 5 million items takes ~30seconds (640MB csv file) on an old pc. ### Insert Data ``` clickhouse-client --query "INSERT INTO datasets.events FORMAT CSV" < gendata.csv ``` Should take several seconds. CSV format is: ```csv Uid, GroupId, Reference, State, Errors, OccurredAt, InsertedAt ``` Example SQL Insert: ```SQL INSERT INTO datasets.events VALUES('86218b86-f8ac-44d6-84ec-e8a0a65bc41a','410578df-9c6c-4b17-82c1-6f648b070795',0,'created',[],toDateTime('2010/03/28 13:42:56'),toDateTime('2020/03/28 13:42:56')); ``` ### Apps / Tools ``` dotnet run ``` ## Examples ### Dataset: ontime #### Count All ``` 183953732 0.021 sec ``` #### Count for OriginState 1213878 Elapsed: 1.998 sec. Processed 183.95 million rows, 367.93 MB (92.05 million rows/s., 184.11 MB/s.) #### Count for Carrier ```SQL SELECT count(*) FROM datasets.ontime WHERE toString(Carrier) = 'HA' GROUP BY Carrier ``` 1005566 1 rows in set. Elapsed: 1.760 sec. Processed 183.95 million rows, 367.93 MB (104.50 million rows/s., 209.02 MB/s.) #### Count for UniqueCarrier ```SQL SELECT count(*) FROM datasets.ontime WHERE toString(UniqueCarrier) = '9E' GROUP BY UniqueCarrier ``` 1547825 1 rows in set. Elapsed: 2.595 sec. Processed 183.95 million rows, 1.29 GB (70.90 million rows/s., 496.27 MB/s.) ### Dataset: events #### Count All ```SQL SELECT count(*) FROM events ``` 44999011 0.004 sec #### Count for GroupId ```SQL SELECT count(*) FROM datasets.events WHERE GroupId = 'cbb0dff4-8934-4cad-af8b-5dc74aa5a8f4' ``` 74343 1 rows in set. Elapsed: 0.073 sec. Processed 24.19 million rows, 387.10 MB (329.08 million rows/s., 5.27 GB/s.) ### Query Aggregated State Totals (Directly) **NOTE:** MAY CRASHES SERVER IN CONTAINER IF DATA > ~20million ```SQL SELECT GroupId, countIf(State = 'created') as CreatedCount, countIf(State = 'requested') as RequestedCount, countIf(State = 'received') as ReceivedCount, countIf(State = 'approved') as ApprovedCount, countIf(State = 'rejected') as RejectedCount, max(OccurredAt) as LastOccurredAt FROM ( SELECT State, GroupId, OccurredAt FROM datasets.events GROUP BY GroupId, Uid, State, OccurredAt ) GROUP BY GroupId ``` 8500 rows in set. Elapsed: 9.321 sec. Processed 27.50 million rows, 1.02 GB (2.95 million rows/s., 109.17 MB/s.) This is getting slow, lets try improving it (by maybe 2000x) with views below. see /scripts for other queries ## Further Usage (views) ### Create derived table to be updated ```SQL CREATE TABLE datasets.current_event_state ( `GroupId` UUID, `CreatedCount` UInt64, `RequestedCount` UInt64, `ReceivedCount` UInt64, `ApprovedCount` UInt64, `RejectedCount` UInt64, `LastOccurredAt` DateTime ) ENGINE = SummingMergeTree() PARTITION BY toYYYYMM(LastOccurredAt) ORDER BY (GroupId, LastOccurredAt); ``` ### Create the materialized view that will update the above table ```SQL CREATE MATERIALIZED VIEW datasets.current_event_state_mv TO current_event_state AS SELECT GroupId, countIf(State = 'created') as CreatedCount, countIf(State = 'requested') as RequestedCount, countIf(State = 'received') as ReceivedCount, countIf(State = 'approved') as ApprovedCount, countIf(State = 'rejected') as RejectedCount, max(OccurredAt) as LastOccurredAt FROM ( SELECT State, GroupId, OccurredAt FROM datasets.events GROUP BY GroupId, Uid, State, OccurredAt ) GROUP BY GroupId ``` ### (Optional) Update derived table if there was existing data prior. Normally it would have a date constraint up to the point currently processing data is arriving. ```SQL INSERT INTO current_event_state SELECT GroupId, countIf(State = 'created') as CreatedCount, countIf(State = 'requested') as RequestedCount, countIf(State = 'received') as ReceivedCount, countIf(State = 'approved') as ApprovedCount, countIf(State = 'rejected') as RejectedCount, max(OccurredAt) as LastOccurredAt FROM ( SELECT State, GroupId, OccurredAt FROM datasets.events GROUP BY GroupId, Uid, State, OccurredAt ) GROUP BY GroupId ``` ### Query raw view data for GroupId ```SQL SELECT GroupId, CreatedCount, RequestedCount, ReceivedCount, ApprovedCount, RejectedCount, LastOccurredAt FROM current_event_state WHERE GroupId = 'cbb0dff4-8934-4cad-af8b-5dc74aa5a8f4' ``` 1 rows in set. Elapsed: 0.003 sec. Processed 2.80 thousand rows, 167.76 KB (872.58 thousa nd rows/s., 52.35 MB/s.) ### Query Aggregated State Totals (From View) ```SQL SELECT sum(CreatedCount) AS TotalCreatedCount, sum(RequestedCount) AS TotalRequestedCount, sum(ReceivedCount) AS TotalReceivedCount, sum(ApprovedCount) AS TotalApprovedCount, sum(RejectedCount) AS TotalRejectedCount FROM current_event_state ``` 1 rows in set. Elapsed: 0.004 sec. Processed 25.30 thousand rows, 1.01 MB (5.48 million r ows/s., 219.37 MB/s.) ## License [MIT](https://choosealicense.com/licenses/mit/) ## Notes - Insert perf may be affected since generated data is not sorted by date - TODO: generation perf could be optimised, also not taking advantage of multiple cores, not needed yet<file_sep>// NOTE: bug in .net ADO client - Exception on inserting Guids // Exception has occurred: CLR/System.NotSupportedException // An unhandled exception of type 'System.NotSupportedException' occurred in ClickHouse.Ado.dll: 'Unknown column type UUID' // at ClickHouse.Ado.Impl.ColumnTypes.ColumnType.Create(String name) // at ClickHouse.Ado.Impl.Data.ColumnInfo.Read(ProtocolFormatter formatter, Int32 rows) // at ClickHouse.Ado.Impl.Data.Block.Read(ProtocolFormatter formatter) // at ClickHouse.Ado.Impl.ProtocolFormatter.ReadPacket(Response rv) // at ClickHouse.Ado.Impl.ProtocolFormatter.ReadSchema() // at ClickHouse.Ado.ClickHouseCommand.Execute(Boolean readResponse, ClickHouseConnection connection) // at ClickHouse.Ado.ClickHouseCommand.ExecuteNonQuery() // at ClickHouse.Net.ClickHouseDatabase.<>c__DisplayClass26_0`1.<BulkInsert>b__0(ClickHouseCommand cmd) // at ClickHouse.Net.ClickHouseDatabase.Execute(Action`1 body, String commandText) // at ClickHouse.Net.ClickHouseDatabase.BulkInsert[T](String tableName, IEnumerable`1 columns, IEnumerable`1 bulk) // at InsertTool.Program.Main(String[] args) using ClickHouse.Ado; using ClickHouse.Net; using ClickHouse.Net.Entities; using System; using System.Collections.Generic; using System.Linq; namespace InsertTool { class Program { private const string host = "localhost"; private const string port = "9000"; private const string username = "default"; private const string password = ""; private const string database = "datasets"; private const string tableName = "events"; private static readonly string ConnectionString = $"Compress=True;CheckCompressedHash=False;Compressor=lz4;Host={host};Port={port};User={username};Password={<PASSWORD>};SocketTimeout=600000;Database={database};"; static void Main(string[] args) { using(var db = new ClickHouseDatabase( new ClickHouseConnectionSettings(ConnectionString), new ClickHouseCommandFormatter(), new ClickHouseConnectionFactory(), null, new DefaultPropertyBinder())) { db.Open(); var data = new EventData { Uid = Guid.NewGuid(), GroupId = Guid.NewGuid(), Reference = "Test" + Guid.NewGuid(), State = State.created, Errors = Enumerable.Empty<string>().ToList(), OccurredAt = DateTime.UtcNow, InsertedAt = DateTime.UtcNow, }; var cols = new[] { "Uid","GroupId","Reference","State","Errors","OccurredAt","InsertedAt" }; var bulkdata = new[] { data }; db.BulkInsert(tableName, cols, bulkdata); db.Close(); } } class EventData { public Guid Uid; public Guid GroupId; public String Reference; public State State; public List<String> Errors; public DateTime OccurredAt; public DateTime InsertedAt; } enum State { created = 1, requested = 2, received = 3, approved = 4, rejected = 5 } } }
756f00668dba20668f3a77cb716e265d3ae3ae66
[ "Markdown", "C#" ]
3
C#
dmannock/myclickhousetest
026941ecbdc052bb0253571d2002df0c08787750
4b073682f2d16fde63679229249965a166f737c0
refs/heads/master
<file_sep>#ifndef RENDER_DIRECTX_H #define RENDER_DIRECTX_H struct RenderDirectX { virtual void render_loop(); }; #endif<file_sep>#ifndef RENDER_H #define RENDER_H #include "IRender.h" template <typename T> class Renderer : IRender { void MainLoop() final { mRenderManager.render_loop(); } T mRenderManager; }; #endif<file_sep>#include <iostream> #include <memory> /* std::shared_ptr< template <typenmae T> struct impl : */ int main(int argc, char const *argv[]) { std::cout<< "First Try" << std::endl; return 0; } <file_sep>#include "renderOpenGL.h" void RenderOpengGL::render_loop() { }<file_sep>#include "renderDirectX.h" void RenderDirectX::render_loop() { }<file_sep>#include "renderOpenGL.h" #include "renderDirectX.h" #include <memory> #include "config.h" struct IRender : RenderOpengGL, RenderDirectX { virtual void render_loop() = 0; }; std::unique_ptr<IRender> RenderFactory(const CONFIG::cRender &config) { if (config.rendererChoice == CONFIG::eRenderer::OPENGL) { /* cod } else { /* code */ } }<file_sep>#ifndef RENDER_OPENGL_H #define RENDER_OPENGL_H struct RenderOpengGL { virtual void render_loop(); }; #endif<file_sep>namespace CONFIG { enum eRenderer { VULKAN = 0x00, OPENGL = 0x01, DIRECTX = 0x02 }; class cRender { public: const eRenderer rendererChoice; }; };
678f8d3f5003882dfd44cf8b7de0eff34d6e4aad
[ "C", "C++" ]
8
C
mrbarnable/Wvatha
15af1df0d25bac82c46ca3764c394e9308baf1df
debde05ce748d9ee9d42ea1289bdd9ed8c233683
refs/heads/master
<file_sep>import idx2numpy from datetime import datetime import matplotlib.pyplot as plt import math import requests step = 50 def to_string(data): output = "" for x in data: for y in x: output += "%03d" % y return output def to_list(data): k = int(math.sqrt(len(data) / 3)) output = [[0 for i in range(k)] for i in range(k)] for i in range(k): for j in range(k): output[i][j] = int(data[(i * k + j) * 3:(i * k + j + 1) * 3]) return output def send_data(amount): global top_hash start = datetime.now() for i in range(amount): files = { 'file': (top_hash + "\n" + str(i) + "\n" + to_string(imagearray[i])), } response = requests.post('https://ipfs.infura.io:5001/api/v0/add', files=files) p = response.json() hash = p['Hash'] top_hash = hash print(str(i) + ' https://ipfs.infura.io/ipfs/' + hash) if i % step == 0: f = open("steps.txt", "a") f.write(str(i) + " " + hash + "\n") f.close() try: f = open("top_hash.txt", "w+") f.write(top_hash) f.close() print("Top hash successfully updated.") except: print("Error updating top hash. Check file.") exit(-1) end = datetime.now() print("Data upload done after", (end - start), amount, "items sent.") def get_data(amount): start = datetime.now() retrieved_data = [] top_hash_local = top_hash i = 0 while i < amount: params = ( ('arg', top_hash_local), ) response = requests.post('https://ipfs.infura.io:5001/api/v0/block/get', params=params) my_response_data = response.text.split('\n') print("Received", top_hash_local) top_hash_local = my_response_data[1][-46:] retrieved_data.append(my_response_data[3][:2352]) i += 1 if not top_hash_local.startswith("Qm"): break end = datetime.now() print("Data receival done after", (end - start), len(retrieved_data), "items received.") return retrieved_data def get_block(block_id): global top_hash data = "" previous_hash = "" top_hash_local = top_hash f = open("steps.txt", "r") lines = f.readlines() for l in lines: if int(l[0:1]) > block_id: top_hash_local = l[2:] break condition = True while condition: params = ( ('arg', top_hash_local), ) response = requests.post('https://ipfs.infura.io:5001/api/v0/block/get', params=params) my_response_data = response.text.split('\n') this_id = int(my_response_data[2]) if this_id == block_id: condition = False data = my_response_data[3][:2352] previous_hash = top_hash_local top_hash_local = my_response_data[1][-46:] print("Found block", previous_hash) return data imagefile = 't10k-images.idx3-ubyte' imagearray = idx2numpy.convert_from_file(imagefile) f = open("top_hash.txt", "r") top_hash = f.read() f.close() # send_data(10) # data = get_data(5) block = get_block(2)
bf5f5fcb94de8b7117c6a9c817653b567261b512
[ "Python" ]
1
Python
antdamj/bsc-thesis-blockchain
72997ea63b708dc1e8c3727c5c8db3bb49b90604
07fea6f940c008aeaeed067d00d045fc304afc9f
refs/heads/master
<repo_name>tomatau/node-hook-filename<file_sep>/README.md [![Circle CI](https://circleci.com/gh/tomatau/node-hook-filename.svg?style=svg)](https://circleci.com/gh/tomatau/node-hook-filename) # node-hook-filename Hooking node require calls for specific requests to only return the filename or the return value of a callback. ## Usage ### Returning filename ```js const nhf = require('node-hook-filename') nhf([ /\.scss/, /\.svg/ ]) const scssAsset = require('../path/too/filename.scss') const svgAsset = require('../path/too/filename.svg') const normalRequire = require('../path/too/js/file') // scssAsset === '../path/too/filename.scss' // svgAsset === '../path/too/filename.svg' // normalRequire is unaffected ``` ### Passing a callback function ```js const nhf = require('node-hook-filename') nhf([ /config/ ], (filename) => 'foo ' + filename) const configRequire = require('config') // configRequire will return 'foo config' ``` Handy if you are running a universal/isomorphic app that requires asset files. This is mostly useful for **testing** and not production ready! Greatly influenced by https://github.com/bahmutov/node-hook ### Bonus There's a normalize function you can supply as callback if you like ```js const nhf = require('node-hook-filename') nhf([ /config/ ], nhf.normalize) const file = require('./file-in-my-app') // file === '/my-ap/file-in-my-app' ``` This is handy to avoid absolute URLs whilst enforcing consistency It assumes you are running commands from the root of your project <file_sep>/test/fixtures/test.js module.exports = { not: 'affected' }<file_sep>/test/fixtures/configjson.js module.exports = { also: 'not affected' }<file_sep>/index.js const Module = require('module') const path = require('path') const originalLoad = Module._load module.exports = function(regexs, override) { override = override ? override : request => request Module._load = function(request, parent, isMain) { return regexs.some(regex => regex.test(request)) ? override(request, parent) : originalLoad.call(this, request, parent, isMain) } } module.exports.normalize = (request, parent) => path .resolve(parent.id, '..', request) .replace(path.parse(process.cwd()).dir, '') <file_sep>/test/index.spec.js const assert = require('assert') const sinon = require('sinon') const nhf = require('../index') describe('node-hook-filename module overrides', () => { context('Given Override Extensions', ()=> { before(()=> { nhf([ /\.json/, /dummy/ ]) }) it('should modify require to return the filenames', ()=> { const filename = './fixtures/config.json' const actual = require(filename) assert.equal(actual, filename) }) it('should not modify require for non matched files', ()=> { const actual = require('./fixtures/test') assert.deepEqual(actual, { not: 'affected' }) }) it('should only modify require for a complete string match', ()=> { const actual = require('./fixtures/configjson.js') assert.deepEqual(actual, { also: 'not affected' }) }) }) context('Given Override Extension With Callback', ()=> { const callback = sinon.spy(() => ({ y: 'z' })) before(()=> { nhf([ /\.ext/, /\.ext2/ ], callback) }) afterEach(()=> { callback.reset() }) it('should invoke the callback with the matching filename', ()=> { const filename = './fixtures/matching.ext' require(filename) assert.ok(callback.calledWith(filename)) callback.reset() const filename2 = './fixtures/matching.ext2' require(filename2) assert.ok(callback.calledWith(filename2)) }) it('should modify the return value to eql the return from callback', ()=> { const filename = './fixtures/matching.ext' const actual = require(filename) assert.deepEqual(actual, callback()) }) }) })
87b7e7d8ece6c0bf5a2a9bf944dcec2249cfec88
[ "Markdown", "JavaScript" ]
5
Markdown
tomatau/node-hook-filename
09660c9a57d46ff635f30dc3244ad673ac25625a
dcd9453fb2c8d51aaf05d914ee313c39b83b751d
refs/heads/master
<file_sep>// Package icn contains icn API versions. // // This file ensures Go source parsers acknowledge the icn package // and any child packages. It can be removed if any other Go source files are // added to this package. package icn
85e3ce52c01f12a3c1cdacbec710c5caaede5b02
[ "Go" ]
1
Go
cheng1li/ewan-operator
28e7618ac13f0e8222cf491420b605cdc01e50db
5472d81a616a977d088be32e3cb9dcfe8a7d3463
refs/heads/master
<file_sep>#!/bin/bash -eux export PATH=$PATH:/usr/local/bin if [[ ! -d "supercollider" ]]; then echo "cloning supercollider repository..." git clone --recursive https://github.com/supercollider/supercollider else ( echo "supercollider already downloaded..." echo "checking for updates..." cd supercollider git pull git submodule update --init --recursive ) fi if [[ ! -d "libossia" ]]; then echo "now cloning libossia" git clone --recursive https://github.com/OSSIA/libossia else ( echo "libossia already downloaded..." echo "checking for updates..." cd libossia git pull git submodule update --init --recursive ) fi mkdir -p build ( cd build export OS_IS_LINUX=0 export OS_IS_OSX=0 if [[ -d "/proc" ]]; then export OS_IS_LINUX=1 else export OS_IS_OSX=1 # Set-up OS X dependencies export HOMEBREW_BIN=$(command -v brew) if [[ "$HOMEBREW_BIN" == "" ]]; then echo "Homebrew is not installed." echo "Please install it by running the following command:" echo ' /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"' exit 1 fi if brew ls --versions [email protected] > /dev/null; then echo "[email protected] with brew correctly installed" else echo "installing [email protected] with homebrew" brew install [email protected] fi if brew ls --versions boost > /dev/null; then echo "boost already installed" else echo "installing boost with homebrew" brew install boost fi export CMAKE_BIN=$(command -v cmake) if [[ "$CMAKE_BIN" == "" ]]; then brew install cmake fi fi # CMake and build libossia echo "now building libossia..." cmake ../libossia -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=ossia-inst -DOSSIA_PYTHON=0 -DOSSIA_NO_QT=1 -DOSSIA_TESTING=0 -DOSSIA_STATIC=1 -DOSSIA_NO_SONAME=1 -DOSSIA_PD=0 -DBOOST_ROOT=/usr/local/opt/boost/include -DOSSIA_NO_QT=1 make -j8 echo "libossia built succesfully... installing" make install # Cleaning up rm -rf libossia build ) cd supercollider git checkout 3.8 # always latest stable version cd SCClassLibrary if [[ ! -d "Ossia" ]]; then mkdir Ossia fi cd ../.. # Copy OssiaClassLibrary and overwrite some sc files yes | cp -rf Ossia/Overwrites/root/CMakeLists.txt supercollider yes | cp -rf Ossia/Overwrites/lang/CMakeLists.txt supercollider/lang yes | cp -rf Ossia/Overwrites/lang/PyrPrimitive.cpp supercollider/lang/LangPrimSource yes | cp -rf Ossia/Classes/ossia.sc supercollider/SCClassLibrary/Ossia yes | cp -rf Ossia_light supercollider/SCClassLibrary yes | cp -rf Ossia/HelpSource/Guides/OssiaReference.schelp supercollider/HelpSource/Guides yes | cp -rf Ossia/HelpSource/Classes supercollider/HelpSource/Classes yes | cp -rf Ossia/HelpSource/Help.schelp supercollider/HelpSource shopt -s dotglob nullglob mv supercollider/HelpSource/Classes/Classes supercollider/HelpSource/Classes/Ossia mv supercollider/HelpSource/Classes/Ossia/* supercollider/HelpSource/Classes/ rm -rf supercollider/HelpSource/Classes/Ossia cd build/ossia-inst/include if [[ ! -d "ossia-sc" ]]; then mkdir ossia-sc fi cd ../../.. # move the ossia prim header into ossia include directory... # the header should maybe be present in libossia repository... yes | cp -rf Ossia/Primitives/pyrossiaprim.h build/ossia-inst/include/ossia-sc # build supercollider cd supercollider mkdir -p build cd build cmake .. -DCMAKE_PREFIX_PATH=/usr/local/opt/[email protected] -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX=../../build -DSYSTEM_BOOST=ON -DBoost_INCLUDE_DIR=/usr/local/opt/boost/include -DBoost_DIR=/usr/local/opt/boost make -j8 make install <file_sep>#'LOSSIA': light ossia version, without primitives this light version is based on the old mgulibSC, only supporting Minuit protocol. Just include the folder in SuperCollider's path, no custom build needed for this one. <file_sep># ossia-sc : libossia bindings for supercollider ## Installing ### macOS - clone this repository, cd into it - run ./build.sh - SuperCollider folder with application should be installed in build/SuperCollider the script clones a fresh version of supercollider (as of this day, version 3.8.0), adds and builds the libossia dependencies for sclang. Depending on your connection, the install process may take a little while, because of the complete download and build of the two applications. for now, see: https://ossia.github.io/?javascript#introduction for early documentation of the ossia extension.
04fdb29cdb55bcf125ac719b6d7db8f688450c57
[ "Markdown", "Shell" ]
3
Shell
pchdev/ossia-sc
14e38fa9a6bcf89e4216ebe7a4571b34220c123c
7917a9315d8043af61c586df48746b6dc3e1c502
refs/heads/main
<repo_name>vincenzo-donato/laravel-boolpress<file_sep>/laravel/app/Http/Controllers/Admin/PostController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; use Illuminate\Http\Request; use Illuminate\Support\Str; use App\Post; use App\Tag; class PostController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // RECUPERO TUTTI I POST $posts = Post::all(); // ARRAY D'APPOGGIO $data = [ 'posts' => $posts ]; // RITORNO SU ROTTA + DATA PER DATI return view('admin.post.index',$data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // RECUPERO TUTTI I TAG $tags = Tag::all(); // ARRAY D'APPOGGIO $data = [ 'tags' => $tags ]; // RITORNO SU ROTTA + DATI return view('admin.post.create',$data); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // RECUPERO TUTTI I DATI DAL FORM $data = $request->all(); // RECUPERO GLI ID DA TABELLA $idUser = Auth::id(); // CONTROLLO SU FORM $request->validate([ 'name' => 'unique:posts|required|max:80', 'description' => 'required', ]); // RECUPERO DATO POST FORM $new = new Post(); // DO UN VALORE AL USER_ID $new->user_id = $idUser; // SLUG INSERITO AL NOME $new->slug = Str::slug($data['name']); // IMPOSTAZIONI IMG $cover = Storage::put('Post_cover',$data['cover']); $data['cover'] = $cover; $new->cover = $data['cover']; // FILLABLE PER EVITARE DI RISCRIVERE TUTTI I VALORI $new->fill($data); // SALVO IL NUOVO POST $new->save(); // SALVO ENTRAMBI GLI ID (TAG E POST) if(array_key_exists('tags',$data)){ $new->tags()->sync($data['tags']); } // REINDIRIZZO LA ROTTA E DOPO UN STATUS return redirect()->route('post.index')->with('status','Nuovo Post Aggiunto Correttamente'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show(Post $post) { // PRENDO TUTTI I POST $data = [ 'post' => $post ]; // RITORNO PAG + DATI POST return view('admin.post.show',$data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit(Post $post) { // RECUPERO TUTTI I TAG $tags = Tag::all(); // INSERISCO I POST E I TAG IN UNA ARRAY D'APPOGGIO $data = [ 'new' => $post, 'tags' => $tags ]; // RITORNO PAG + DATI return view('admin.post.edit',$data); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, Post $post) { // RECUPERO TUTTI I DATI FORM MODIFICATI $data = $request->all(); // CONTROLLO VALIDITA' $request->validate([ 'name' => 'required|max:80', 'description' => 'required', ]); if(array_key_exists('cover',$data)){ $cover = Storage::put('Post_cover',$data['cover']); $data['cover'] = $cover; } // SOVRASCRIVO I VECCHI DATI CON QUELLI NUOVI $post->update($data); // CONTROLLO PER ID TAG POST MODIFICATO if(array_key_exists('tags',$data)){ $post->tags()->sync($data['tags']); } // RETURN QUESTA VOLTA VERRA' REINDIRIZZATA ALLA PAGINA DEI POST return redirect()->route('post.index')->with('status','Post Modificato Correttamente'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Post $post) { // SVUOTO I TAG $post->tags()->sync([]); // RECUPERO L'ELEMENTO TRAMITE ID E LO CANCELLO CON IL COMANDO DELETE $post->delete(); // REINDIRIZZO LA PAGE A POST ADMIN INDEX return redirect()->route('post.index')->with('status','Post Cancellato Correttamente'); } } <file_sep>/laravel/app/Email.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Email extends Model { // CREO LE FILLABLE CON I DATI RICHIESTI protected $fillable = ['email','oggetto','contenuto']; } <file_sep>/laravel/app/Http/Controllers/PostController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Facade\FlareClient\View; use App\Mail\SendNewMail; use Illuminate\Support\Facades\Mail; use App\Post; use App\Tag; use App\User; use App\Email; class PostController extends Controller { // METODO PER INDEX POST public function index(){ // RECUPERO TUTTI I DATI POST $posts = Post::all(); // ARRAY D'APPOGGIO $data = [ 'posts' => $posts ]; // INDIRIZZO LA PAG + DATI return view('guest.post.index',$data); } // METODO PER POST SHOW public function show($slug){ // RECUPERO IL DATO SCELTO TRAMITE LO SLUG $post = Post::where('slug',$slug)->first(); // ARRAY D'APPOGGIO $data = [ 'post' => $post ]; // RITORNO PAG + DATI RICHIESTI return view('guest.post.show',$data); } // METODO PER TAG SHOW public function tag(){ // RECUPERO TUTTI I DATI POST $users = Tag::all(); // ARRAY D'APPOGGIO $data = [ 'tags' => $users ]; // INDIRIZZO LA PAG + DATI return view('guest.page.tags',$data); } // METODO PER USER SHOW public function user(){ // RECUPERO TUTTI I DATI POST $users = User::all(); // ARRAY D'APPOGGIO $data = [ 'users' => $users ]; // INDIRIZZO LA PAG + DATI return view('guest.page.users',$data); } // METODO PRITORNO PAGINA SCRITTURA EMAIL public function request(){ // INDIRIZZO LA PAG return view('guest.emailRequest'); } // METODO PER RICHIESTA INVIO EMAIL public function requestSend(Request $request){ // RECUPERO TUTTI I DATI POST $data = $request->all(); // CONTROLLO SU FORM PER CAMPI OBBLIGATORI $request->validate([ 'email' => 'required', 'contenuto' => 'required' ]); // LI MEMORIZZO TRAMITE LE FILLABLE E SALVO $newEmail = new Email(); $newEmail->fill($data); $newEmail->save(); // GRAZIE ALLA CLASSE MAIL POSSO INVIARE AL DESTINATARIO IL CONTENUTO DELLA MIA EMAIL Mail::to('<EMAIL>')->send(new SendNewMail($newEmail)); // REINDIZZO LA PAGINA CON UNO STATUS DI CONFERMA DELL'INVIO DELL'EMAIL return redirect()->route('request.guest.post')->with('status','Email inviata Correttamente'); } } <file_sep>/laravel/app/Tag.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Tag extends Model { // CREO FILLABLE PER I DATI RICHIESTI protected $fillable = ['name','slug']; // CREO COLLEGAMENTO POST TAG MOLTI A MOLTI public function posts(){ return $this->belongsToMany('App\Post'); } } <file_sep>/laravel/app/Http/Controllers/Admin/HomeController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Str; use Illuminate\Support\Facades\Auth; use App\Post; use App\Tag; use App\User; class HomeController extends Controller { // CONTROLLER HOME INDEX POST public function index() { $posts = Post::all(); $data = [ 'posts' => $posts ]; return view('admin.post.index',$data); } // CONTROLLER HOME INDEX TAG public function show() { $tags = Tag::all(); $data = [ 'tags' => $tags ]; return view('admin.page.tags',$data); } // CONTROLLER HOME INDEX USER public function user() { $users = User::all(); $data = [ 'users' => $users ]; return view('admin.page.users',$data); } // CONTROLLER METODO PER INFO UTENTE public function profile(){ return view ('admin.user.profile'); } // CONTROLLER METODO PER CREARE TOKEN PER UTENTE public function generaToken(){ $api_token = Str::random(70); $user = Auth::user(); $user->api_token = $api_token; $user->save(); return redirect()->route('profile'); } } <file_sep>/laravel/database/seeds/TagSeeder.php <?php use Illuminate\Database\Seeder; use Faker\Generator as Faker; use Illuminate\Support\Str; use App\Tag; class TagSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run(Faker $faker) { // CICLO 3 VOLTE PER CREARE DATI TAG FAKER for ($i = 0; $i < 3; $i++){ $posizione = 1; $newTag = new Tag(); $newTag->name = $faker->sentence(3,true); $slug = Str::slug($newTag->name); $slugInit = $slug; $postRecent = Tag::where('slug',$slug)->first(); while($postRecent){ $slug = $slugInit . '-' . $posizione; $postRecent = Tag::where('slug',$slug)->first(); $posizione++; } $newTag->slug = $slug; $newTag->save(); } } } <file_sep>/laravel/routes/web.php <?php use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Auth; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ // COLLEGAMENTO HOME Route::get('/','HomeController@index')->name('home.page'); // COLLEGAMENTO TAGS DA ADMIN Route::get('/tags','Admin\HomeController@show')->name('tag.page'); // COLLEGAMENTO USERS DA ADMIN Route::get('/users','Admin\HomeController@user')->name('user.page'); // COLLEGAMENTO INDEX POSTS Route::get('/posts','PostController@index')->name('index.guest.post'); // COLLEGAMENTO TAG LATO LOG OUT Route::get('/tagslogout','PostController@tag')->name('tags.guest.post'); // COLLEGAMENTO USER LATO LOG OUT Route::get('/userslogout','PostController@user')->name('users.guest.post'); // COLLEGAMENTO SHOW POST Route::get('/posts{slug}','PostController@show')->name('show.guest.post'); // COLLEGAMENTO EMAIL Route::get('/emailRequest','PostController@request')->name('request.guest.post'); // COLLEGAMENTO INVIO EMAIL Route::post('/emailRequest','PostController@requestSend')->name('send.email'); Auth::routes(); // ROTTE PER ADMIN Route::prefix('admin') ->namespace('Admin') ->middleware('auth') ->group(function () { Route::get('/', 'HomeController@index')->name('home'); Route::get('/profile','HomeController@profile')->name('profile'); Route::post('/genera-token','HomeController@generaToken')->name('genera-token'); Route::resource('/post', 'PostController'); }); <file_sep>/laravel/app/Post.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { // CREO LE FILLABLE CON I DATI RICHIESTI protected $fillable = ['name','slug','description','cover']; // COLLEGAMENTO FRA I POST E USER UN USER A MOLTI POST public function user(){ return $this->belongsTo('App\User'); } // COLLEGAMENTO FRA POST E TAG MOLTI A MOLTI public function tags(){ return $this->belongsToMany('App\Tag'); } } <file_sep>/laravel/database/seeds/PostSeeder.php <?php use Illuminate\Database\Seeder; use App\Post; use App\User; use Carbon\Carbon; use Faker\Generator as Faker; use Illuminate\Support\Str; class PostSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run(Faker $faker) { // CICLO PER CREARE 5 POST CON DATI FAKER for ($i = 0; $i < 5; $i++){ $posizione = 1; $userCount = count(User::all()->toArray()); $newPost = new Post(); $newPost->user_id = rand(1,$userCount); $newPost->name = $faker->sentence(); $newPost->description = $faker->text(); $slug = Str::slug($newPost->name); $slugInit = $slug; $postRecent = Post::where('slug',$slug)->first(); while($postRecent){ $slug = $slugInit . '-' . $posizione; $postRecent = Post::where('slug',$slug)->first(); $posizione++; } $newPost->slug = $slug; $newPost->save(); } } }
32dc73d9302b4757fd1d2a47527feadc0f96f9bf
[ "PHP" ]
9
PHP
vincenzo-donato/laravel-boolpress
ce42eab6940610acddf0468c89fdb01fbdb42458
55a4e3694649fa2935401a5de4028e721efdcc51
refs/heads/master
<file_sep>library(tidyverse) occ_simulation <- function(nyears, lambda, alpha, beta){ data_matrix <- matrix(, nrow = nyears, ncol = 6) for (z in 1:nyears){ data_matrix[z][1] <- z } for (yr in 1:nyears){ poisson_sim = rpois(1, lambda) for (number_of_events in poisson_sim){ if (number_of_events == 1){ beta_sim = rbeta(1, alpha, beta) data_matrix[yr, 2] <- beta_sim } else if (number_of_events == 2){ for (i in 2:3){ beta_sim = rbeta(1, alpha, beta) data_matrix[yr, i] <- beta_sim } } else if (number_of_events == 3){ for (i in 2:4){ beta_sim = rbeta(1, alpha, beta) data_matrix[yr, i] <- beta_sim } } else if (number_of_events == 4){ for (i in 2:5){ beta_sim = rbeta(1, alpha, beta) data_matrix[yr, i] <- beta_sim } } else{ for (i in 2:6){ beta_sim = rbeta(1, alpha, beta) data_matrix[yr, i] <- beta_sim } } } } sorted_matrix <- cbind(data_matrix[,1],t(apply(data_matrix[,2:6],1,function(x) sort(x)))) G <- sorted_matrix %>% as.data.frame %>% pivot_longer(-V1) %>% ggplot(aes(x=factor(V1),y=value,color=name,group=name))+ geom_point()+ labs(color='Column',x='Time (Years)', y ='Probability')+ theme_bw() return(G) } manual = occ_simulation(10, 10, 2, 20) manual<file_sep># R-Projects A amalgamation of different projects/files I have worked on or created while developing my knowledge of R. <file_sep>dice_probs = c(4/10, 5/10, 1/10) trial = sample(1:3, size = 1000000, replace = TRUE, prob = dice_probs) par(mfrow = c(1,2)) hist(trial, breaks = seq(0,3, 1), probability = TRUE, col = rainbow(6), main = "Results of Biased Dice Rolls", xlab = "Number") expected = sample(1:3, size = 1000000, replace = TRUE) hist(expected, breaks = seq(0,3, 1), probability = TRUE, col = rainbow(6), main = "Results of Unbiased Dice Rolls", xlab = "Number")<file_sep>#----------COMMENTS #---R program to generate plots of OEP/AEP for poisson and clustered models and compare to historical data #---code is specific to one country, plan is to launch multiple jobs in parallel using a script, inputing arguments #---note that for efficiency, we may eventually want to split up some of the simulation computation across many processors #---which can be done by bringing in the seed initialization by using an argument #---CLEANED UP VERSION OF ORIGINAL driver.R FOR CREATION OF FINALIZED EWS model #---NOTE THAT UNLIKE THE GENERATION OF THE SIMULATION FILES --- I AM NOT (PAINSTAKINGLY) TAKING OUT OPTIONS IN THE CODE - THESE ARE HARD CODED AND OK #---THIS CODE IS FOR MODEL DEVELOPMENT ONLY and NOT INTENDED to be USED FOR FINALIZATION OF SIMULATION FILES #---------- #----------CLEAR + SOURCE rm(list=ls()) #---analytic solutions obtained from wang paper source('wang_utilitiesK.R') #---routines consistent with RL implementations source('white_paper_routines.R') #---plot routines source('plots.R') #---------- #----------PARAMETERS TO SPECIFY, INCLUDING ON/OFF SWITCHES #---various on/off switches LOAD.IN.HFREQ=FALSE RUN.SIMS=TRUE RUN.WANG=FALSE optimal.beta.config=1 #dummy optimal configuration for eu windstorm RUN.RL.CLUSTERS=FALSE RUN.RL=FALSE INTENSITY.FILTER=TRUE NAHU=FALSE EUWS=TRUE #---following is a condition put in specifically to allow manipulation of mid-atlantic losses in NAHU clustering, and other versions of sub-clustering MA.SPECIAL.CLUSTER=FALSE INTENSITY.SPECIAL.CLUSTER=FALSE data.table = 'ClusteredData_IED_STOCH_EUWS2011_HIST_ERA40INT_winter_test5v_3_split_w4_9' #---file for the new EWS2011 model eventid.rates = 'EUWS11.RATES.FINAL' #---csv file where we load in a regions elt which contains the high freq events not in the clustered data elt.with.high.freq = 'hfelt_' #---number of grid points for integral/distribution approximations --- for analytic calculations only ngrid = 2^12 #---new EWS2011 model --- noting the change of formatting #---we note that these data were extracted from the database #---note that this file does not have a header as we are specifying explicitly ssi.filename='/home/skhare/clustering/get_euws2011_data/ssiews11.csv'; ssi=read.csv(ssi.filename,header=F) ssi.eu=ssi[,2] #---------- #----------READ COMMAND LINE ARGUMENTS, LOAD IN HISTORICAL LOSS DATA, CLUSTER DEFS, EVENT EXPOSURES ETC. #---region gotten via command line argument (commented out when testing) args=commandArgs() args = args[length(args)] args<-strsplit(args,",") #---set the variable which indicates the geographic region #region <- as.character(args[[1]][1]); region; print('the region') region='eu' #---set the seed for the random number generation #seed <- as.numeric(args[[1]][2]); seed; print('the seed'); set.seed(seed); seed.number = as.character(seed) seed=7 #---set a file description of which cluster we are using #description <- as.character(args[[1]][3]) description='test' #---read ELT table with cluster definitions filename = paste('data/',data.table,'.csv',sep='') print(filename) data = read.csv(filename,header=T) #---get the pressures as an indicator of intensity --- vorticity in future models pressure.header=paste('pressure') print(pressure.header) pressure=data[,pressure.header] #---get event ids eventids = data[,'event_id'] #---get losses loss.header=paste('mean.loss.',region,sep='') print(loss.header) loss=data[,loss.header] #---get the mid-atlantic losses, only if we are creating a special mid-atlantic cluster if(MA.SPECIAL.CLUSTER){ loss.header=paste('mean.loss.','ma',sep='') lossma=data[,loss.header] } #---if for european windstorm, get losses on target countries, france, germany, and uk #if(EUWS){ # loss.header=paste('mean.loss.','de',sep='') # lossde=data[,loss.header] # loss.header=paste('mean.loss.','fr',sep='') # lossfr=data[,loss.header] # loss.header=paste('mean.loss.','gb',sep='') # lossgb=data[,loss.header] #} #---get stdi stdi.header=paste('stdi.loss.',region,sep='') std.ind=data[,stdi.header] #---get stdc stdc.header=paste('stdc.loss.',region,sep='') std.corr=data[,stdc.header] #---get exposure exposure.header=paste('exposure.',region,sep='') expsr=data[,exposure.header] #---get cluster designations cluster.num=data[,'Cluster'] #---record the orignal cluster definitions in anticipation of upcoming manipulations cluster.num.original=data[,'Cluster'] #---some filtering based on pressure/vorticity (need to ensure consistency when we define the cluster search space) if(INTENSITY.FILTER){ if(NAHU){ print('intensity filtering on hurricane') } if(EUWS){ #REMEBER CRUCIALLY THAT THE TAKE CONDITION IS SPECIFYING MAKING THIS POISSON #below is a statement about only clustering storms with appreciable intensity over countries of interest #dumping storms out of clusters which do not cause any appreciable loss in france, germany and the uk #take = which((lossde < 5e+8 ) & (lossgb < 1e+9 ) & (lossfr < 5e+8)) #take = which((data[,"max.int.de"] < 30 | data[,"max.int.fr"] < 30 | data[,"max.int.gb"] < 30) ) #take = which(data[,"max.int.wind"] < 37.5) #as of august 24th, 2010 --- we have a cutoff of 1.0 on the ssi for the old/current model and i believe that this was the #threshold used in the proposal results #take = which(ssi.eu < 4.5) #the following ssi cutoff was used for the old model ####take = which(ssi.eu < 1.0) #take = which((lossde < 5e+8 ) | (lossgb < 7e+8 ) | (lossfr < 2e+8)) #take = which((lossde < 5e+8 | lossde > 1.5e+9) & (lossgb < 1e+9 | lossgb > 2e+9) & (lossfr < 5e+8 | lossfr > 1.5e+9)) #take = which(pressure > 950) #take = which(data[,"max.int.country"]=='' & data[,"pressure"] > 950 ) #take=which(data[,"pressure"] > 960) #take=which(data[,"mean.loss.eu"] < 5e+8) #LOGIC OF FOLLOWING CODE #FOR EACH CLUSTER, WE TAKE THE 80TH PERCENTILE IN SSI. EVERYTHING UPTO THE 80TH PERCENTILE IN SSI IS TREATED AS POISSON #SO EACH ORIGINAL CLUSTER, IN EFFECT, HAS A SUB-CLUSTER OF STRONG STORMS, WHICH WE MODULATE USING THE GAMMA DISTRIBUTION #THE IDEA IS THAT WHEN VIEWED AS A WHOLE, THE ENTIRE CLUSTER, WHICH IS AN ADMIXTURE OF POISSON AND NB, CAN BE VIEWED TOGETHER, AND WE CAN LOOK AT ITS OVERDISPERSION #AS A WHOLE --- THE TRICK OF ALL THIS IS THAT THE SUB-CLUSTERS ARE STRONG STORMS, WHICH WE CAN MANIPULATE QUITE STRONGLY, AND THUS SEE APPRECIABLE IMPACTS #ON THE TAIL STATISTICS num.base.clusters = length(unique(cluster.num)) #dump out 3/4's of the clusters based entirely on ssi (percentage is tunable) alltake=c() for (i in 1:num.base.clusters){ #convoluted logic to take take = which(cluster.num == i) nnn = length(take) #note that for the final EWS implementation we have nnn*0.8 and if (threshold < 3.0){threshold = 3.0} threshold = sort(ssi.eu[take])[ceiling(nnn*0.80)] if (threshold < 3.0){threshold = 3.0} indices = which(cluster.num == i) ssis = ssi.eu[indices] takessi = which(ssis < threshold) take = indices[takessi] alltake=c(alltake,take) } take=alltake #dumping the unwanted clusters the 'cluster that we will treat as solely as poisson cluster.num[take] = num.base.clusters+1 } } browser() #---filter out zero loss events --- actually filtering out more severely to avoid getting eroneous beta distribution parameters take = which(loss>10000) loss=loss[take]; std.ind=std.ind[take]; std.corr=std.corr[take]; expsr=expsr[take]; cluster.num=cluster.num[take]; eventids=eventids[take]; pressure=pressure[take]; cluster.num.original=cluster.num.original[take]; #---also get the mid-atlantic losses if(MA.SPECIAL.CLUSTER){lossma=lossma[take]} #---get rates --- first we read in all possible event ids and rates, which crucially, ***are sorted in ascending eventid*** filename = paste('data/',eventid.rates,'.csv',sep='') print(filename) classes = c(rep('numeric',2)) eventids.and.rates = read.csv(filename,colClasses=classes,skip=0,header=F) #---take the appropriate set of event ids and rates from the full set of event ids, with an error check take=is.element(eventids.and.rates[,1],eventids) take=which(take) eventids.subset=eventids.and.rates[take,1] rates.subset=eventids.and.rates[take,2] if (length(eventids) == length(eventids.subset)){ eventids=eventids.subset rate=rates.subset print('finished getting associated rates') } else { print('!!!program failure, event ids for which we do not have a rate!!!') browser() } #---load in the high frequency event losses, and append to clustered data (no filtering necessary) - optional, only for EU data if(LOAD.IN.HFREQ){ filename = paste('data/',elt.with.high.freq,region,'.csv',sep='') print(filename) classes = c(rep('numeric',2)) high.freq.elt = read.csv(filename,colClasses=classes,skip=0,header=F) hfeventids = high.freq.elt[,1] hflosses = high.freq.elt[,2] hfstd.ind = high.freq.elt[,3] hfstd.corr = high.freq.elt[,4] hfexpsr = high.freq.elt[,5] hfrate = high.freq.elt[,6] n.hf.events = length(hfeventids) eventids=c(eventids, hfeventids) loss = c(loss, hflosses) std.ind = c(std.ind, hfstd.ind) std.corr = c(std.corr, hfstd.corr) expsr = c(expsr, hfexpsr) rate = c(rate, hfrate) #---augment the cluster.num array to represent the hf events in EUWS, if we are doing intensity filtering, we throw them in with the previously defined poisson cluster if(INTENSITY.FILTER){ num.clusters = length(unique(cluster.num)) } else { num.clusters = length(unique(cluster.num))+1 } add.high.freq.cluster = array(num.clusters,n.hf.events) cluster.num = c(cluster.num, add.high.freq.cluster) cluster.num.original = c(cluster.num.original,add.high.freq.cluster) } num.clusters = length(unique(cluster.num)) #---load in the historical data for this region #---get mean loss ratio and standard deviations of the event loss, and also maximum loss mlr = loss / expsr std = (std.corr + std.ind) / expsr #---get the maximum loss over the entire event set for grid discretization MAXLOSS = max(loss) #---------- #browser() #----------DEFINE WHICH CLUSTERS ARE POISSON or NB (HF EVENTS ARE TREATED AS POISSON), AND SET THE VARIANCES if(FALSE){ #---code for our favourite cluster on the current european windstorm model cluster.num = array(0,c(length(loss))); take = !loss > 5e8; cluster.num[take] = 1 take = loss > 5e8; cluster.num[take] = 2 num.beta.combinations = 1 num.clusters = length(unique(cluster.num)) poisson.or.nb <- array('dummy', c(num.clusters)) betas <- array(0,c(num.clusters,num.beta.combinations)) betas[] = 6 poisson.or.nb[1] = 'poisson' poisson.or.nb[2] = 'negative binomial'} if(FALSE){ #---code for search space! naive european cluster (1,2,3) are cluster, the 4th weak storm cluster is treated as poisson #---load in the beta search space #---assign the poisson cluster a dummy variance of one num.beta.combinations = 1000 betas = array(0,c(num.clusters,num.beta.combinations)) betas[num.clusters,] = 1 ijk = 1 for (i in seq(10,200,by=20)){ for (j in seq(10,200,by=20)){ for (k in seq(10,200,by=20)){ betas[1,ijk] = i; betas[2,ijk] = j; betas[3,ijk] = k ijk = ijk + 1 } } } poisson.or.nb = array(0,c(num.clusters,num.beta.combinations)) poisson.or.nb[1] = 'negative binomial' poisson.or.nb[2] = 'negative binomial' poisson.or.nb[3] = 'negative binomial' poisson.or.nb[4] = 'poisson' } #---next case is where we might consider doing some kind of sub-clustering to make MA come out correctly #---note that this is a beta search space definition for US hurricane if(FALSE){ #SUCCESSIVE CLUSTER DEFINITIONS WHICH ARE GETTING OVER-WRITTEN #---code for search space for NAHU cluster defined in R:\Clustering.Simulations\NAHU2011\CLUSTERS\ClusteredData_IED_STOCH_HIST_test1v_4.csv #---load in the beta search space #---first cluster num.beta.combinations = 10^4 betas = array(0,c(num.clusters,num.beta.combinations)) ijk = 1 for (i in seq(0.5,5,by=1)){ for (j in seq(0.5,5,by=1)){ for (k in seq(0.5,5,by=1)){ for (n in seq(0.5,5,by=1)){ betas[1,ijk] = i; betas[2,ijk] = j; betas[3,ijk] = k; betas[4,ijk] = n ijk = ijk + 1 } } } } poisson.or.nb = array(0,c(num.clusters,num.beta.combinations)) poisson.or.nb[1] = 'negative binomial' poisson.or.nb[2] = 'negative binomial' poisson.or.nb[3] = 'negative binomial' poisson.or.nb[4] = 'negative binomial' #MA SPECIAL CLUSTER #temp code to put in special clustering for the MA - essentially redefining what is above, and adding in a special MA cluster if(MA.SPECIAL.CLUSTER){ num.clusters = num.clusters+1 num.beta.combinations=5^5 betas = array(0,c(num.clusters, num.beta.combinations)) #have a special subcluster of storms causing at least X=50000000 loss in MA take = which(lossma > 5e+6) cluster.num[take] = 5 #recompute the beta parameter space ijk = 1 for (i in seq(0.5,5,by=1)){ for (j in seq(0.5,5,by=1)){ for (k in seq(0.5,5,by=1)){ for (n in seq(0.5,5,by=1)){ for (m in seq(0.5,100,by=20)){ betas[1,ijk] = i; betas[2,ijk] = j; betas[3,ijk] = k; betas[4,ijk] = n; betas[5,ijk] = m ijk = ijk + 1 } } } } } poisson.or.nb = array(0,c(num.clusters,num.beta.combinations)) poisson.or.nb[1] = 'negative binomial' poisson.or.nb[2] = 'negative binomial' poisson.or.nb[3] = 'negative binomial' poisson.or.nb[4] = 'negative binomial' poisson.or.nb[5] = 'negative binomial' } #NAHU --- note that this is the definition of the clusters i used in generating the 'proposal' results for NAHU #the basic idea for the results i have sent is to start with the kossin-like definitions of the superclusters #do the sub-clustering on intensity (which is done very simply with the landfalling pressure which correlates very well with loss) #well, this isn't really sub-clustering, cause we could treat the low intensity storms using a negative binomial, but i didn't feel this #was necessary. the idea was then to play around with the beta factors on the clusters 1 and 4, so that we end up matching the overall #over-dispersion if(INTENSITY.SPECIAL.CLUSTER){ #---in each cluster, only accept storms beyond a certain intensity num.clusters = num.clusters+1 take = which(pressure > 950) cluster.num[take] = 5 # num.beta.combinations=10^4 num.beta.combinations=1 betas = array(0,c(num.clusters, num.beta.combinations)) #---set the poisson cluster gamma distribution variance to dummy constant value betas[5,] = 1 #---recompute the beta parameter space ijk = 1 # for (i in seq(0.5,10,by=1)){ # for (j in seq(0.5,10,by=1)){ # for (k in seq(0.5,10,by=1)){ # for (n in seq(0.5,10,by=1)){ # betas[1,ijk] = i; betas[2,ijk] = j; betas[3,ijk] = k; betas[4,ijk] = n # ijk = ijk + 1 # } # } # } # } betas[1,] = 1; betas[2,] = 1; betas[3,] = 1; betas[4,] = 1; poisson.or.nb = array(0,c(num.clusters,num.beta.combinations)) poisson.or.nb[1] = 'negative binomial' poisson.or.nb[2] = 'poisson' poisson.or.nb[3] = 'poisson' poisson.or.nb[4] = 'negative binomial' poisson.or.nb[5] = 'poisson' } } #4-cluster case EUROWIND if(FALSE){ #---search space definition for ERA 40 mailier clusters num.beta.combinations = 1 betas = array(0,c(num.clusters,num.beta.combinations)) #---set the betas of the poisson clusters to 1 betas[num.clusters,] = 1 betas[1,] = 1 betas[2,] = 1 betas[3,] = 1 #ijk = 1 #for (i in seq(0.5,60,by=2)){ # for (j in seq(0.5,60,by=2)){ # betas[2,ijk] = i; betas[3,ijk] = j # ijk = ijk + 1 # } # } poisson.or.nb = array(0,c(num.clusters,num.beta.combinations)) poisson.or.nb[1] = 'poisson' poisson.or.nb[2] = 'negative binomial' poisson.or.nb[3] = 'poisson' poisson.or.nb[4] = 'poisson' } #THE FOLLOWING IS THE PARAMETERIZATION OF THE EWS CLUSTERS if(TRUE){ #---search space definition for ERA40 (mailier type) clusters num.beta.combinations = 1 betas = array(0,c(num.clusters,num.beta.combinations)) #---set the betas of the poisson clusters to 1 betas[num.clusters,] = 1 betas[1,] = 1 betas[2,] = 1 betas[3,] = 1 betas[4,] = 1 betas[5,] = 1 betas[6,] = 1 betas[7,] = 1 betas[8,] = 1 betas[9,] = 1 #ijk = 1 #for (i in seq(0.5,60,by=2)){ # for (j in seq(0.5,60,by=2)){ # betas[2,ijk] = i; betas[3,ijk] = j # ijk = ijk + 1 # } # } poisson.or.nb = array(0,c(num.clusters,num.beta.combinations)) poisson.or.nb[1] = 'negative binomial' poisson.or.nb[2] = 'negative binomial' poisson.or.nb[3] = 'poisson' poisson.or.nb[4] = 'negative binomial' poisson.or.nb[5] = 'negative binomial' poisson.or.nb[6] = 'negative binomial' poisson.or.nb[7] = 'negative binomial' poisson.or.nb[8] = 'negative binomial' poisson.or.nb[9] = 'negative binomial' poisson.or.nb[10]= 'poisson' } #---------- #----------COMMENTS #---we now have: #--->>> mlr, std, exposure, cluster.num, rate + cluster definitions <<< #---which are all the arrays we require to compute the oep and aep #---------- #----------WANG ANALYTIC THEORY (!UPDATE FOR ZERO LOSS THRESHOLD!) #---original.poisson.mixture = poisson.mixture( mlr, std, rate, expsr, loss, 5e8 , 6 ) if(RUN.WANG){ print('before analytic solution for K clusters') print(date()) WANG = poisson.mixtureK( mlr, std, rate, expr, loss, num.clusters, cluster.num, betas, poisson.or.nb, ngrid ) print(date()) print('after analytic solution for K clusters') #list k.clusters.analytic contains: #xx(ngrid) - losses #EEF(ngrid) #OEPpoi(ngrid) #OEP2poi(ngrid) #OEP3poi(ngrid) #AEPpoi(ngrid) #OEP(num.beta.combinations, ngrid) #AEP(num.beta.combinations, ngrid) #---code to dump OEP curves to file for the different beta parameter combinations (and associated losses) filename = paste('OEPclustered.', description, '.', region, '.csv', sep='') write.csv(WANG$OEP, file=filename) filename = paste('Losses.', description, '.', region, '.csv', sep='') write.csv(WANG$xx, file=filename) filename = paste('OEPpoisson.', description, '.', region, '.csv', sep='') write.csv(WANG$OEPpoi, file=filename) filename = paste('Betas.', description,'.', region,'.csv', sep='') write.csv(betas, filename) filename = paste('OverD.', description,'.', region,'.csv', sep='') write.csv(WANG$overdispersion, file=filename) filename = paste('RatesInClusters.', description,'.', region,'.csv', sep='') write.csv(WANG$rates.in.clusters, file=filename) filename = paste('AEPclustered.', description, '.', region, '.csv', sep='') write.csv(WANG$AEP, file=filename) filename = paste('AEPpoisson.', description, '.', region, '.csv', sep='') write.csv(WANG$AEPpoi, file=filename) #---record the aal due for each cluster, over this entire region aal.bycluster = array(0,c(num.clusters)) for (i in 1:num.clusters){take = which(cluster.num == i); aal.bycluster[i] = sum( rate[take] * loss[take])} filename = paste('AALbycluster.', description, '.', region, '.csv', sep='') write.csv(aal.bycluster, file=filename) } #---------- #for physical sub-clustering on the original euws case #betas[1,]=16 #betas[2,]=1 #betas[3,]=1 #betas[4,]=4 #betas[5,]=4 #betas[6,]=4 #betas[7,]=2 #betas[8,]=1 #betas[9,]=4 #betas[10,]=1 #temp code for automated choice of over-dispersions for the 10 cluster case #for EWS, the target over-dispersions come from analysis of the ERA 40 data target.od=c(6.47/6.32,2.26/2.22,1,9.59/8.86,13.44/9.56,10.33/5.86,4.35/3.88,11.92/9.58,12.44/10.64,1) if(TRUE){ for(i in 1:num.clusters){ take=which(cluster.num==i) rate.clusi = sum(rate[take]) if (rate.clusi > 0){betas[i,]= (target.od[i] - 1)/sum(rate.clusi)} #note, for empty clusters, we set the beta to one --- instead of using the above formula which would generate an infinity if (rate.clusi == 0){betas[i,] = 1} #note that it does then matter what we set it to if the rate is truly zero } } #betas=betas*15 #####*3 #betas[5,]=betas[5,]*4 #betas[6,]=betas[6,]*.7 #betas[7,]=betas[7,]*1 #multiplication for the weak case with the new model betas=betas*18 betas[4,] = betas[4,] * 0.4 betas[5,] = betas[5,] * 0.5 betas[7,] = betas[7] * 1.1 betas[8,] = betas[8,] * 0.20 betas[9,] = betas[9,]*1.4 betas[6,] = betas[6,] * 0.60 #---permanently fix the EU tuned betas (these yield acceptable results as of feb 14th, 2011) #---FOLLOWING GAMMA DISTRIBUTIONS GENERATE SETS OF RESULTS #betas[1] = 153.396622 #betas[2,] = 11.366536 #betas[3,] = 0.000000 #betas[4,] = 2.858247 #betas[5,] = 41.169611 #betas[6,] = 573.982675 #betas[7,] = 313.943917 #betas[8,] = 10.196645 #betas[9,] = 102.287620 #betas[10,] = 0.000000 #weak case #1 --- as of february 21st, 2011 #betas[1,] = 47.936 #betas[2,] = 3.552 #betas[3,] = 0.00 #betas[4,] = 0.714 #betas[5,] = 12.8655 #betas[6,] = 107.62 #betas[7,] = 98.107 #betas[8,] = 2.124 #betas[9,] = 31.96 #betas[10,] = 0.00 #weak case #2 --- as of february 21st, 2011 #THIS HAS BEEN SIGNED OFF BY ROBERT-MUIR-WOOD betas[1,] = 86.3 betas[2,] = 6.393 betas[3,] = 0.00 betas[4,] = 1.286 betas[5,] = 23.157 betas[6,] = 193.719 betas[7,] = 176.59 betas[8,] = 3.823442 betas[9,] = 57.536786 betas[10,] = 0.00 #---JUNE 1ST, 2010 --- MAKING MAJOR CODE CHANGE TO RUN SIMULATIONS IN MEAN MODE #----------CODE TO GENERATE VARIOUS SIMULATIONS---***some early versions of simulation codes copy and pasted to bottom of this file*** #---this version is optimized for speed, *except* we still need to loop over the number of years, and sample from the events, as it does not appear #---that we can insert arrays of probabilities into the R sample function if(RUN.SIMS){ #---set the number of years in this simulation nyears=10^4 #---set parameter which selects out the configuration of beta parameters we'll want to look at beta.config=optimal.beta.config EPs = array(0, c(nyears)); for(i in 1:nyears){EPs[i] = 1 - i/nyears} #---for the K cluster model gammas = array(0,c(num.clusters,nyears)) for (i in 1:num.clusters){ if (poisson.or.nb[i] == 'poisson') { gammas[i,] = 1 } if (poisson.or.nb[i] == 'negative binomial'){ gammas[i,] = rgamma(nyears, shape=1/betas[i,beta.config], scale=betas[i,beta.config])} } rates.of.clusters = array(0,c(num.clusters,nyears)) for (i in 1:num.clusters){ rates.of.clusters[i,] = sum( rate[which(cluster.num==i)] ) } for (i in 1:num.clusters){ rates.of.clusters[i,] = rates.of.clusters[i,] * gammas[i,] } num.events.in.clusters = array(0,c(num.clusters,nyears)) for (i in 1:num.clusters){ num.events.in.clusters[i,] = rpois(nyears,rates.of.clusters[i,]) } #---compute the time series of events, corresponding to the orignal cluster defs, but maintaining sub-clustering rates.of.clusters.original = array(0,c(num.clusters,nyears)) for (i in 1:num.clusters){ #---for the case where we have the original cluster defined to be poisson if (poisson.or.nb[i] == 'poisson'){rates.of.clusters.original[i,] = sum(rate[which(cluster.num.original==i)])} #---for the case where we take the original cluster, but do some negative binomial sub-clustering if (poisson.or.nb[i] == 'negative binomial'){ #get the positions associated with the original cluster take=which(cluster.num.original==i) all.rates.i=rate[take] all.sub.cluster.num = cluster.num[take] take=which(all.sub.cluster.num==i) #we treat the ones that we are sub-clustering as negative binomial, drawn from the prescribed gamma rates.of.clusters.original[i,] = sum(all.rates.i[take]) * gammas[i,] take=which(all.sub.cluster.num != i) #the events do not remain in this cluster i after sub-clustering are treated as poisson #my rule is that if we have an original cluster, some of which gets sub-clustered, the remaining events are poisson rates.of.clusters.original[i,] = rates.of.clusters.original[i,] + sum(all.rates.i[take]) } } num.events.in.clusters.original = array(0, c(num.clusters,nyears)) for (i in 1:num.clusters){ num.events.in.clusters.original[i,] = rpois(nyears,rates.of.clusters.original[i,]) } all.losses.cluster = NULL for (i in 1:num.clusters){ take = which(cluster.num == i) ids = eventids[take] mlrs = mlr[take] stds = std[take] rate.base = rate[take] exps = expsr[take] all.ids.cluster.i = NULL #can we somehow pass arrays of prob's to the sample function so we need not loop over the number of years for (j in 1:nyears){ if(num.events.in.clusters[i,j] > 0){all.ids.cluster.i = c(all.ids.cluster.i, sample(ids, num.events.in.clusters[i,j], replace = TRUE, prob = rate.base * gammas[i,j])) } } take = match(all.ids.cluster.i,ids) means = mlrs[take] sigmas = stds[take] exposures = exps[take] beta.coeffs = get.alpha.beta.vec(means, sigmas) all.non.zero.losses = rbeta( sum(num.events.in.clusters[i,]), shape1 = beta.coeffs[,1], shape2 = beta.coeffs[,2] ) * exposures all.losses.cluster.i = array(0, c(nyears, max(num.events.in.clusters[i,])) ) endj = 0 for (j in 1:nyears){ if(num.events.in.clusters[i,j] > 0){ endj = endj + num.events.in.clusters[i,j] startj = endj - num.events.in.clusters[i,j] + 1 all.losses.cluster.i[j,1:num.events.in.clusters[i,j]] = all.non.zero.losses[startj:endj] } } all.losses.cluster = cbind(all.losses.cluster, all.losses.cluster.i) } #---ensure the losses in each year are sorted in descending order all.losses.cluster = t(apply(all.losses.cluster,1,sort)) num.cols = dim(all.losses.cluster)[2] all.losses.cluster = all.losses.cluster[,num.cols:1] AGG = apply(all.losses.cluster,1,sum) OMX = sort(all.losses.cluster[,1]) OE2 = sort(all.losses.cluster[,2]) OE3 = sort(all.losses.cluster[,3]) OE4 = sort(all.losses.cluster[,4]) #---for the usual Poisson model (agrees with analytic solution) num.poisson.events = rpois(nyears,sum(rate)) total.num.poisson.events = sum(num.poisson.events) all.ids = sample( eventids, total.num.poisson.events, replace = TRUE, prob = rate ) take = match(all.ids,eventids) means = mlr[take] sigmas = std[take] exposures = expsr[take] beta.coeffs = get.alpha.beta.vec(means, sigmas) all.non.zero.losses = rbeta( total.num.poisson.events, shape1 = beta.coeffs[,1], shape2 = beta.coeffs[,2] ) * exposures all.losses.poisson = array(0,c(nyears,max(num.poisson.events))) endj = 0 for (j in 1:nyears){ if(num.poisson.events[j] > 0){ endj = endj + num.poisson.events[j] startj = endj - num.poisson.events[j] + 1 all.losses.poisson[j,1:num.poisson.events[j]] = sort( all.non.zero.losses[startj:endj], decreasing = TRUE) } } AGGP = apply(all.losses.poisson,1,sum) OMXP = sort(all.losses.poisson[,1]) OE2P = sort(all.losses.poisson[,2]) OE3P = sort(all.losses.poisson[,3]) OE4P = sort(all.losses.poisson[,4]) #save the clustered and poisson assumption results filename = paste('ALossesclustered.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(AGG, file=filename) filename = paste('OLossesclustered.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(OMX, file=filename) filename = paste('OE22222clustered.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(OE2, file=filename) filename = paste('OE33333clustered.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(OE3, file=filename) filename = paste('OE44444clustered.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(OE4, file=filename) filename = paste('ALossespoissonnn.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(AGGP, file=filename) filename = paste('OLossespoissonnn.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(OMXP, file=filename) filename = paste('OE22222poissonnn.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(OE2P, file=filename) filename = paste('OE33333poissonnn.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(OE3P, file=filename) filename = paste('OE44444poissonnn.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(OE4P, file=filename) filename = paste('numofstormssssss.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(t(num.events.in.clusters), file=filename) filename = paste('numofstormspoiss.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(num.poisson.events, file=filename) filename = paste('allcluslossessss.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(all.losses.cluster, file=filename) filename = paste('allpoislossessss.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(all.losses.poisson, file=filename) filename = paste('numofstormsorign.', description, '.', region, '.seed', seed, '.csv', sep='') write.csv(t(num.events.in.clusters.original), file=filename) } #---------- #----------GET EQUIVALENT CALCS TO WHAT IS IN RL if(RUN.RL){ print('before RL poisson calculations') print(date()) RL8.0.Poisson = wp_oep_aep ( rate, loss, expsr, std, mlr, 'poisson', NA, MAXLOSS, ngrid ) print(date()) print('after the RL poisson calculations') } #list RL8.0.Poisson contains: #xx(ngrid) - losses, and does not include the zero loss level #OEP(ngrid + 1) - includes zero loss level #AEP(ngrid + 1) - includes zero loss level #---------- #----------GET RESULTS USING CONVOLUTIONS AS IN RL FOR K CLUSTERS (!UPDATE FOR ZERO LOSS THRESHOLD!) #---notes about the RL implementation: note that we get exactly the same OEP, but different #---AEPs when we go to the wang implementation, especially for high rate events. #---is the difference in AEP due to some truncation in the convolution? or the fact that #---we're not summing to an infinite number events. does the RL implementation allow for #---expanded convolutions? if we get time, we should understand a bit more about what may #---be wrong with the implementation of the AEP in RL if(RUN.RL.CLUSTERS){ print('before the RL implementation for K clusters') print(date()) #---first loop over clusters to get cluster CEPs and convolutions, which need not be repeated CEP.clusters = array(0,c(num.clusters,ngrid)) MAXEVENTS.clusters = array(0,c(num.clusters)) rates.clusters = array(0,c(num.clusters)) #initialize collection of aggregate density matrix with null dAEP.clusters = c() for (j in 1:num.clusters){ take = which(cluster.num==j) cep.daep = get.cep.daep(rate[take], loss[take], expsr[take], std[take], mlr[take], MAXLOSS, ngrid, betas[j,i]) rates.clusters[j] = sum(rate[take]) #list cep.daep contains: #xx(ngrid) - losses (!same for each cluster, since input MAXLOSS is the same for each cluster!) #CEP(ngrid) #dAEP(MAXEVENTS,ngrid) #MAXEVENTS CEP.clusters[j,] = cep.daep$CEP dAEP.clusters=rbind(dAEP.clusters, cep.daep$dAEP) MAXEVENTS.clusters[j] = cep.daep$MAXEVENTS } RL.clusters = get.RL.clusters( CEP.clusters, dAEP.clusters, MAXEVENTS.clusters, num.beta.combinations, num.clusters, poisson.or.nb, betas, ngrid, rates.clusters, cep.daep$xx) #list RL.clusters contains: #xx(ngrid) - losses and does not include the zero loss level #OEP(ngrid + 1) - includes the zero loss level #AEP(ngrid + 1) - includes the zero loss level print(date()) print('after the RL implemenation for K clusters') } #---------- #---some junk/commented out code below #---simulation gotten from a pure poisson process, and outputs a year event table #if (FALSE){ #nyears=10^5 #nevents.per.year = rpois(nyears,sum(rate)) #table.events = array(0,c(nyears,max(nevents.per.year))) #table.losses = array(0,c(nyears,max(nevents.per.year))) #for (i in 1:nyears){ # npicks = nevents.per.year[i] # the.events = sample(eventids, npicks, replace=TRUE, prob = rate) # table.events[i,1:npicks] = the.events # take = which(is.element(eventids,the.events)) # table.losses[i,1:length(take)] = loss[take] #} #write.csv(table.events, file = "euws.ied.with.pla.csv") #aal = sum(table.losses/nyears) #} #---naive simulation code to verify analytic theories and compute OEPN curves - for cluster and poisson #if (FALSE){ # nyears=10^4 # beta.config=1 # gammas=array(1,c(num.clusters)) # AGG <- AGGP <- OMX <- OMXP <- OE2 <- OE2P <- OE3 <- OE3P <- array(0,c(nyears)) # gamma.check = array(0,c(num.clusters,nyears)) # EPs = array(0, c(nyears)) # for (i in 1:nyears){ # #---get random losses for the conditionally Poisson cluster, and the Poisson assumption as well # ratei = rate # for (j in 1:num.clusters){ # if (poisson.or.nb[j] == 'poisson') {gammas[j] = 1} # if (poisson.or.nb[j] == 'negative binomial') {gammas[j] = rgamma(1,shape=1/betas[j,beta.config],scale=betas[j,beta.config]); take = which(cluster.num == j); ratei[take] = gammas[j] * ratei[take]; gamma.check[j,i] = gammas[j] } # } # nevents.yeari = rpois(1,sum(ratei)) # nevents.yeariP = rpois(1,sum(rate)) # the.eventsi = sample(eventids, nevents.yeari, replace = TRUE, prob = ratei) # the.eventsiP = sample(eventids, nevents.yeariP, replace = TRUE, prob = rate) # take = match(the.eventsi ,eventids) # takeP = match(the.eventsiP,eventids) # std.losses = std[take] # std.lossesP = std[takeP] # mlrs = mlr[take] # mlrsP = mlr[takeP] # exposures.i = expsr[take] # exposures.iP = expsr[takeP] # the.random.losses.i = array(0, c(length(mlrs)) ) # the.random.losses.iP = array(0, c(length(mlrsP)) ) # #---cover the zero event case # if (nevents.yeari == 0){AGG[i] <- OMX[i] <- OE2[i] <- OE3[i] <- 0} # if (nevents.yeariP == 0){AGGP[i] <- OMXP[i] <- OE2P[i] <- OE3P[i] <- 0} # #---cover the case where we have at least one event - clusters # if (nevents.yeari > 0){ # for (ijk in 1:nevents.yeari) { beta.coeffs=get.alpha.beta(mlrs[ijk],std.losses[ijk]); the.random.losses.i[ijk] = rbeta(1, shape1 = beta.coeffs[1], shape2 = beta.coeffs[2]) * exposures.i[ijk] } # RLC = sort(the.random.losses.i, decreasing=TRUE) # if (nevents.yeari == 1){ AGG[i] <- OMX[i] <- RLC[1]; OE2[i] <- OE3[i] <- 0 } # if (nevents.yeari == 2){ AGG[i] = sum(RLC); OMX[i] = RLC[1]; OE2[i] = RLC[2]; OE3[i] = 0 } # if (nevents.yeari > 2){ AGG[i] = sum(RLC); OMX[i] = RLC[1]; OE2[i] = RLC[2]; OE3[i] = RLC[3] } # } # #---cover the case where we have at least one event - Poisson # if (nevents.yeariP > 0){ # for (ijk in 1:nevents.yeariP) { beta.coeffs=get.alpha.beta(mlrsP[ijk],std.lossesP[ijk]); the.random.losses.iP[ijk] = rbeta(1, shape1 = beta.coeffs[1], shape2 = beta.coeffs[2]) * exposures.iP[ijk] } # RLP = sort(the.random.losses.iP, decreasing=TRUE) # if (nevents.yeariP == 1) { AGGP[i] <- OMXP[i] <- RLP[1]; OE2P[i] <- OE3P[i] <- 0 } # if (nevents.yeariP == 2) { AGGP[i] = sum(RLP); OMXP[i] = RLP[1]; OE2P[i] = RLP[2]; OE3P[i] = 0 } # if (nevents.yeariP > 2) { AGGP[i] = sum(RLP); OMXP[i] = RLP[1]; OE2P[i] = RLP[2]; OE3P[i] = RLP[3] } # } # EPs[i] = 1 - i/nyears # } # #---sort all the simulated losses, in ascending order # #---clustered simulations # AGG = sort(AGG) # OMX = sort(OMX) # OE2 = sort(OE2) # OE3 = sort(OE3) # #---poisson assumption simulations # AGGP = sort(AGGP) # OMXP = sort(OMXP) # OE2P = sort(OE2P) # OE3P = sort(OE3P) #} <file_sep> set.seed(1) ########## # simplified simulation routine for the high frequency poisson case ########## get.id.sim.HF <- function( ratek, idsk, Nyears ){ ########## # determine number of years with nevents given our choice of frequency distribution ########## #---get average annual rate applicable across frequency distributions lamda = sum(as.numeric(ratek)) #---lamda above specifies the one parameter poisson distribution nevents.in.sim = NULL ni.array = NULL ni = 0 while (ni >= 0){ #---get the probability of ni events from the poisson distribution and multiply by Nyears #---good aspect of R is that there is nothing wrong with analytic evaluation numerically #nyears.with.ni = Nyears * exp(-lamda) * lamda^ni / factorial( ni ) nyears.with.ni = Nyears * dpois(ni, lambda = lamda) rounded.nyears.with.ni = round(nyears.with.ni) if (rounded.nyears.with.ni >= 1){nevents.in.sim = rbind(nevents.in.sim, rounded.nyears.with.ni); ni.array = c(ni.array,ni); ni = ni + 1} print(ni); print(rounded.nyears.with.ni) #browser() # if we are on the left side of the distribution, we want to keep going, make sure ni>5 so we keep going # these manipulations are inexact under some circumstances and used with caution in testing phase if (rounded.nyears.with.ni < 1) { if (ni > 66){ ni = -99 }else{ ni = ni + 1 } } } #--if we have not filled up all the years then we increase the number of years with zero losses as an approximation if (sum(nevents.in.sim) < Nyears){nevents.in.sim[1] = nevents.in.sim[1] + (Nyears - sum(nevents.in.sim))} ########## # stratified year, event id and genesis date simulation ########## #---get the number of events per year over the Nyears num.per.year = NULL for (i in 1:length(ni.array)){ # print(i) num.per.year = c( num.per.year, array(ni.array[i],c(nevents.in.sim[i])) ) } # browser() #---randomly shuffle the time series over the Nyears random.years = sample(num.per.year,Nyears,replace=FALSE,prob=NULL) #---get the list of years with non-zero events, and repeat year number M times if there are M events in a particular year allyears = seq(1,Nyears,by=1) take = which(random.years > 0) allyears = allyears[take] num.events.non.zero.years = random.years[take] #---create an array holding the list of years yearssim = array( 0, c(sum(num.events.non.zero.years)) ) #---get the mother list of years dumi = 1 for (i in 1:length(allyears)){ yearssim[dumi:(dumi+num.events.non.zero.years[i]-1)] = allyears[i] dumi = dumi + num.events.non.zero.years[i] } #---get representative sample of the conditional event distribution (not sorting in terms of loss as unnecessary) num.samples.ced = sum(num.events.non.zero.years) #---partition 0-->>1 with midpoints right.partition = seq(1, num.samples.ced, by=1) / num.samples.ced left.partition = seq(0, (num.samples.ced-1), by=1) / num.samples.ced midpoints.partition = (left.partition + right.partition)/2.0 #---now getting the cummulative event distribution event.probs = ratek / sum( ratek ) cumsum.events = cumsum(event.probs) #---sweep over all possible events (picking events consistent with our partitioning of the uniform distribution) #---adding in simulation of base genesis dates idsimulation = array(0,c(num.samples.ced)) # genesis.simulation = array("0",c(num.samples.ced)) dumi = 1 for (i in 1:length(ratek)){ # print(i) take = which( midpoints.partition <= cumsum.events[i] ) #---if there are any events to take, add to the idsimulation list, and then ignore by setting to value greater than 1 if(length(take) > 0){idsimulation[dumi:(dumi + length(take) - 1)] = idsk[i] # genesis.simulation[dumi:(dumi + length(take) - 1)] = as.character(as.Date(datesk[i],"%d/%m/%y")) midpoints.partition[take] = 99.0} dumi = dumi + length(take) } #---spread the sample ids across the years randomly (keeping track of the associated genesis dates by using the match function) random.ids = sample(idsimulation, num.samples.ced, replace=FALSE, prob=NULL) take = match(random.ids, idsimulation) # associated.genesis.dates = genesis.simulation[take] print('completed event id simulation') ########## # stratified sampling of associated loss quantiles ########## #---get the simulation of the loss quantiles (obtained from random shuffling of the midpoints.partition used for the conditional event distribution) #---using left/right partitions stored in memory allsortedquantiles = (right.partition + left.partition)/2.0 randomquantiles = sample(allsortedquantiles, num.samples.ced, replace=FALSE, prob=NULL) print('completed stratified sampling of the loss quantiles') ########## # return stratified years simulation, event/source ids, random loss quantiles, genesis dates and randomized dates ########## #---return the list of simulation year, ids, and loss quantiles return(list( yearssim=yearssim, random.ids=random.ids, randomquantiles=randomquantiles )) } <file_sep>library(ggplot2) #setting initial conditions and number of trials n = 1000000 one = two = three = 0 #iterating through a uniform distribution for (i in 1:n){ random = runif(1, min = 0, max = 1) #counting the number of times 1, 2 and 3 are rolled if (0.0 <= random && random < 0.4){ one = one + 1 } else if (0.4 <= random && random < 0.9){ two = two + 1 } else { three = three + 1 } } #swapping to density num_rolled = c((one/n), (two/n), (three/n)) #plotting results par(mfrow = c(1,2)) #results using uniform distribution barplot(num_rolled, main="Biased Dice Simulation (Uniform)", xlab="Number Rolled", ylab="Density", names.arg=c("One","Two","Three"), border="blue", col = heat.colors(3)) #comparison against inbuilt sample function dice_probs = c(4/10, 5/10, 1/10) trial = sample(1:3, size = n, replace = TRUE, prob = dice_probs) expected = sample(1:3, size = n, replace = TRUE) hist(trial, breaks = seq(0,3, 1), probability = TRUE, main = "Biased Dice Simulation (Sample)", xlab = "Number Rolled", col = heat.colors(3)) <file_sep>#setting initial conditions trials = 1000 lambda = 20 #creating empty list to store our variables poisson_list = c() #running the trials for (i in 1:trials){ #setting values for simulation of poisson X = 0 P = 1 #simulating poisson using runif while (P >= exp(-lambda)){ U = runif(1, min = 0, max = 1) P = U * P X = X + 1 } #appending values to the end of the list poisson_list = c(poisson_list, X) } #graphing our results hist(poisson_list, main = "Histogram of Unif Pois", xlab = "Number") #using inbuilt poisson function to compare against trial = rpois(trials, lambda) #plotting our results hist(trial, main = "Histogram of RPois", xlab = "Number")<file_sep>decimal.ticks <- function(fn.minexp = -4, fn.maxexp = +4){ yy = c() for (ii in (fn.minexp:fn.maxexp)){ ymin <- 10^ii; yy <- c(yy, seq(ymin, 10*ymin, by = ymin) ) } decimal.ticks <- unique(yy) } plot.oep <- function ( lim.x2, lim.y1, filename, legend.text, leg.cex, wp.poi, wp.neg, wp.mix, wp.rl8 ) { lim.x1 = 0 ax.size = 2 lab.size = 1.6 png(filename,width=1000,height=1000,type='cairo1') idx = c(2:length(wp.poi$OEP)) plot(wp.poi$xx,wp.poi$OEP[idx],log=c('y'),type='l', lty=2,lwd=4,col='blue', axes = F, bg = 'transparent', cex = 1.5, xlab = '', ylab = '', ylim=c(lim.y1,1),xlim=c(lim.x1,lim.x2)) lines(wp.neg$xx,wp.neg$OEP[idx],col='red',lty=2,lwd=4) lines(wp.mix$xx,wp.mix$OEP[idx],col='black',lty=1,lwd=4) lines(wp.rl8$xx, wp.rl8$OEP[idx], col='gray',lty=1,lwd=4) legend('topright',legend.text, lwd=rep(4,4,4,4),lty=c(2,2,1,1),col=c('blue','red','black','gray'), cex=leg.cex) xticks <- seq(0,lim.x2, by = 1e9) lab = xticks/1e+9 axis(side=1, at = xticks, labels = lab, las = 1, tck = 0.02, cex.axis = ax.size) #mtext(side = 1, 'Hazard', cex = lab.size, padj = +2) xticks.2 <- seq(0,lim.x2, by = 1e+8) abline(v = xticks.2,lwd=.2) axis(side=1, at = xticks.2, labels = NA, tck = 0.01) ## X Axis (top) axis(side=3, at = xticks, labels = NA, tck = 0.02) axis(side=3, at = xticks.2, labels = NA, tck = 0.01) ## EP Y Axis yticks <- 10^seq(-10, 0) axis(side=2, at = yticks, labels = yticks, las = 1, tck = -0.02, cex.axis = ax.size) mtext(side = 2, 'EF', cex = lab.size, padj = -3) yticks.2 <- decimal.ticks() abline(h = yticks.2,lwd=.2) axis(side=2, at = yticks.2, labels = NA, las = 1, tck = -0.01, cex.axis = ax.size) ## RP Y Axis my.rps <- c(2,5,10,20,25,50,100,200,250,500,1000,5000) yticks.lbl <- c(1,my.rps) yticks<- 1./yticks.lbl axis(side=4, at = yticks, labels = yticks.lbl, las = 1, tck = -0.01, pos= lim.x2 , cex.axis = ax.size) mtext(side = 4, 'RP', cex = lab.size, padj = 3) xx.txt <- lim.x2/3 yy.txt <- 1/400 my.lab = paste(country) text(xx.txt, yy.txt, my.lab, cex = 3, pos = 2, col = 'black', bg = 'white' ) dev.off() } plot.aep <- function ( lim.x2, lim.y1, filename, legend.text, leg.cex, wp.poi, wp.neg, wp.mix, wp.rl8 ) { lim.x1 = 0 ax.size = 2 lab.size = 1.6 png(filename,width=1000,height=1000,type='cairo1') idx = c(2:length(wp.poi$AEP)) plot(wp.poi$xx,wp.poi$AEP[idx],log=c('y'),type='l', lty=2,lwd=4,col='blue', axes = F, bg = 'transparent', cex = 1.5, xlab = '', ylab = '', ylim=c(lim.y1,1),xlim=c(lim.x1,lim.x2)) lines(wp.neg$xx,wp.neg$AEP[idx],col='red',lty=2,lwd=4) lines(wp.mix$xx,wp.mix$AEP[idx],col='black',lty=1,lwd=4) lines(wp.rl8$xx, wp.rl8$AEP[idx], col='gray',lty=1,lwd=4) legend('topright',legend.text, lwd=rep(4,4,4,4),lty=c(2,2,1,1),col=c('blue','red','black','gray'), cex=leg.cex) xticks <- seq(0,lim.x2, by = 1e9) lab = xticks/1e+9 axis(side=1, at = xticks, labels = lab, las = 1, tck = 0.02, cex.axis = ax.size) #mtext(side = 1, 'Hazard', cex = lab.size, padj = +2) xticks.2 <- seq(0,lim.x2, by = 1e+8) abline(v = xticks.2,lwd=.2) axis(side=1, at = xticks.2, labels = NA, tck = 0.01) ## X Axis (top) axis(side=3, at = xticks, labels = NA, tck = 0.02) axis(side=3, at = xticks.2, labels = NA, tck = 0.01) ## EP Y Axis yticks <- 10^seq(-10, 0) axis(side=2, at = yticks, labels = yticks, las = 1, tck = -0.02, cex.axis = ax.size) mtext(side = 2, 'EF', cex = lab.size, padj = -3) yticks.2 <- decimal.ticks() abline(h = yticks.2,lwd=.2) axis(side=2, at = yticks.2, labels = NA, las = 1, tck = -0.01, cex.axis = ax.size) ## RP Y Axis my.rps <- c(2,5,10,20,25,50,100,200,250,500,1000,5000) yticks.lbl <- c(1,my.rps) yticks<- 1./yticks.lbl axis(side=4, at = yticks, labels = yticks.lbl, las = 1, tck = -0.01, pos= lim.x2 , cex.axis = ax.size) mtext(side = 4, 'RP', cex = lab.size, padj = 3) xx.txt <- lim.x2/3 yy.txt <- 1/400 my.lab = paste(country) text(xx.txt, yy.txt, my.lab, cex = 3, pos = 2, col = 'black', bg = 'white' ) dev.off() } plot.check.aep <- function ( lim.x2, lim.y1, filename, legend.text, leg.cex, wp.poi, wp.neg, wp.mix, sol ) { lim.x1 = 0 ax.size = 2 lab.size = 1.6 png(filename,width=1000,height=1000,type='cairo1') idx = c(2:length(wp.poi$AEP)) plot(wp.poi$xx,wp.poi$AEP[idx],log=c('y'),type='l', lty=1,lwd=4,col='blue', axes = F, bg = 'transparent', cex = 1.5, xlab = '', ylab = '', ylim=c(lim.y1,1),xlim=c(lim.x1,lim.x2)) lines(wp.neg$xx,wp.neg$AEP[idx],col='red',lty=1,lwd=4) lines(wp.mix$xx,wp.mix$AEP[idx],col='black',lty=1,lwd=4) lines(sol$xx, sol$AEPpoi, col='blue',lty=2,lwd=3) lines(sol$xx, sol$AEPneg, col='red',lty=2,lwd=3) lines(sol$xx, sol$AEPmix, col='black',lty=2,lwd=3) legend('topright',legend.text, lwd=rep(4,4,4,3,3,3),lty=c(1,1,1,2,2,2),col=c('blue','red','black','blue','red','black'), cex=leg.cex) xticks <- seq(0,lim.x2, by = 1e9) lab = xticks/1e+9 axis(side=1, at = xticks, labels = lab, las = 1, tck = 0.02, cex.axis = ax.size) #mtext(side = 1, 'Hazard', cex = lab.size, padj = +2) xticks.2 <- seq(0,lim.x2, by = 1e+8) abline(v = xticks.2,lwd=.2) axis(side=1, at = xticks.2, labels = NA, tck = 0.01) ## X Axis (top) axis(side=3, at = xticks, labels = NA, tck = 0.02) axis(side=3, at = xticks.2, labels = NA, tck = 0.01) ## EP Y Axis yticks <- 10^seq(-10, 0) axis(side=2, at = yticks, labels = yticks, las = 1, tck = -0.02, cex.axis = ax.size) mtext(side = 2, 'EF', cex = lab.size, padj = -3) yticks.2 <- decimal.ticks() abline(h = yticks.2,lwd=.2) axis(side=2, at = yticks.2, labels = NA, las = 1, tck = -0.01, cex.axis = ax.size) ## RP Y Axis my.rps <- c(2,5,10,20,25,50,100,200,250,500,1000,5000) yticks.lbl <- c(1,my.rps) yticks<- 1./yticks.lbl axis(side=4, at = yticks, labels = yticks.lbl, las = 1, tck = -0.01, pos= lim.x2 , cex.axis = ax.size) mtext(side = 4, 'RP', cex = lab.size, padj = 3) xx.txt <- lim.x2/3 yy.txt <- 1/400 my.lab = paste(country) text(xx.txt, yy.txt, my.lab, cex = 3, pos = 2, col = 'black', bg = 'white' ) dev.off() } <file_sep>par(mfrow=c(1,2)) N = 10000 y_rpois = rpois(N, lambda = 5) hist(y_rpois, breaks = 100, xlab = "Number Rolled", main = "Poisson Distribution") x = seq(0, 1, by = 0.01) y = dbeta(x, 50, 50) plot(x, y, main = "Beta Distribution", xlab = "Probability", ylab = "Frequency",)<file_sep> # SPREAD COEFFICIENTS my_acoeff <- function ( n,M ) { ac = array(0,dim=c(M,n)) for ( i in 1:M ) { ac[i,1]= 1/factorial(i) } for ( j in 2:n ) { ac[1,j]=0 } for ( i in 2:M ) { for ( j in 2:n ) { ac[i,j] = 1/i * ( ( i - ( j-1) ) * ac[(i-1),(j-1)] + ( (j-1) + 1 ) * ac[(i-1),j] ) } } return(ac) } #small coding changes made by <NAME> to correct a few small bugs wp_oep_aep <- function ( rate, loss, expsr, std, mlr, DIST, alpha, maxloss , ngrid) { N = length(rate) nthrs = ngrid #----------------------------------------- # FREQUENCY DISTRIBUTION GENERATION #----------------------------------------- LAMBDA = sum(rate) if ( DIST == 'poisson' ) { MAXEVENTS = pmax(20,qpois((1-1/20000),LAMBDA)) feq.dist = vector() tmp = vector() for ( k in 1:(MAXEVENTS+1) ){ #feq.dist[k] = exp(-LAMBDA) * LAMBDA^(k-1) / factorial(k-1) feq.dist[k] = dpois((k-1),LAMBDA) } } else { #crucially we are picking from a negative binomial mu = LAMBDA va = LAMBDA + LAMBDA^2 * (alpha) r = mu^2/(va-mu) p = r/(r+mu) MAXEVENTS = pmax(20,qnbinom((1-1/20000),prob=p,size=r)) feq.dist = vector() for ( k in 1:(MAXEVENTS+1) ) { feq.dist[k] = dnbinom((k-1),prob=p,size=r) } } print(paste('MAXEVENTS', MAXEVENTS)) #----------------------------------------- # LOSS THRESHOLD TABLE (LTT) #----------------------------------------- dx = maxloss*2 / nthrs xx = c((1:nthrs)*dx) LTT = array(0,dim=c(nthrs,2)) LTT[,1] = xx #----------------------------------------- # BETA COEFFICIENTS from ELT #----------------------------------------- beta.coeff = get.alpha.beta(mlr,std) #----------------------------------------------------------- # CONDITIONAL EXCEEDANCE PROBABILITY (CEP) #---------------------------------------------------------- FX <- CEP <- array(0,nthrs) for ( i in 1:N ) { if ( i %% 100 == 0 ) { print(i) } this.aa = beta.coeff[i,1] this.bb = beta.coeff[i,2] this.lambda = rate[i] this.xx = LTT[,1]/expsr[i] this.FX = pbeta(this.xx , shape1 = this.aa, shape2 = this.bb ) FX = FX + (this.lambda/LAMBDA) * this.FX CEP = CEP + (this.lambda/LAMBDA) * (1-this.FX) } #----------------------------------------------------------- # OCCURRENCE EXCEEDANCE PROBABILITY (OEP) #---------------------------------------------------------- OEP = vector('numeric',nthrs+1) if ( DIST == 'poisson' ) { OEP[1] = 1 - exp(-LAMBDA) OEP[2:(nthrs+1)] = 1 - exp( - LAMBDA * CEP ) } else { OEP[1] = 1 - (1 + LAMBDA * alpha * (CEP) )^(-1/alpha) #why is the index here starting at 2? OEP[2:(nthrs+1)] = 1 - ( 1 + LAMBDA * alpha * ( CEP )) ^ (-(1/alpha)) } #----------------------------------------------------------- # SEVERITY DENSITY FUNCTION (SDF) #---------------------------------------------------------- nthrs = length(CEP) SDF = vector('numeric',nthrs) hold = c(1,CEP) for ( i in 1:nthrs ) { SDF[i] = hold[i] - hold[i+1] } #----------------------------------------------------------- # AGGREGATE EXCEEDANCE PROBABILITY (AEP) #---------------------------------------------------------- # zero filling for no-wrap convolution tmp = vector('numeric',nthrs) tmp[1:length(SDF)]=SDF SDF = tmp AC = my_acoeff(nthrs,MAXEVENTS) Sconv = SDF dAEP = array(0,dim=c(MAXEVENTS,nthrs)) for ( k in 1:(MAXEVENTS-1) ) { print(paste('EVENT ; ',k)) hold = convolve(AC[k,],rev(Sconv),type='o')[1:nthrs] dAEP[k,] = feq.dist[k+1]*hold[1:nthrs] Sconv = convolve(SDF,rev(Sconv),type='o')[1:nthrs] } #<NAME> has made change to the code below that that we pick MAXEVENTS hold = convolve(AC[k+1,],rev(Sconv),type='o')[1:nthrs] dAEP[MAXEVENTS,] = feq.dist[MAXEVENTS+1]*hold[1:nthrs] cAEP = colSums(dAEP,na.rm=TRUE) AEP= vector('numeric',nthrs+1) AEP[1] = 1-feq.dist[1] for ( i in 2:(nthrs+1) ) { AEP[i] = AEP[i-1]-cAEP[i-1] } #note that the AEP is of ngrid + 1 dimension, and includes the zero loss level, also the OEP return(list(xx=LTT[,1],OEP=OEP,AEP=AEP)) } #RL.clusters = get.RL.clusters( CEP.clusters, dAEP.clusters, MAXEVENTS.clusters, num.beta.combinations, num.clusters, poisson.or.nb, betas, ngrid, cep.daep$xx, rates.clusters) #function written by <NAME> to get OEP/AEP for K clusters consistent with convolutions in RL #passing in CEP.clusters(num.clusters,ngrid), dAEP.clusters(MAXEVENTS.clusters*num.clusters,ngrid) #note that we have written the code to include the zero loss level #---------- get.RL.clusters <- function( CEP.clusters, dAEP.clusters, MAXEVENTS.clusters, num.beta.combinations, num.clusters, poisson.or.nb, betas, ngrid, rates.clusters, xx) { OEP.clusters <- AEP.clusters <- array(0,c(num.beta.combinations,(ngrid+1))) for (i in 1:num.beta.combinations){ #--->>> #OEP (coded to include the zero loss level) cdf.mix = array(1,c(ngrid+1)) for (cn in 1:num.clusters ){ CEP.cn = c(1,CEP.clusters[cn,]) if (poisson.or.nb[cn] == 'poisson') {cdf.mix = cdf.mix * exp(-rates.clusters[cn] * CEP.cn) } if (poisson.or.nb[cn] == 'negative binomial') {cdf.mix = cdf.mix * (1 + rates.clusters[cn] * betas[cn,i] * CEP.cn)^( -1/betas[cn,i] )} } OEP.clusters[i,] = 1. - cdf.mix #--->>> #--->>> #AEP (coded to include the zero loss level) dum.int = 0 charac.func = array(1,c(ngrid+1)) for (cn in 1:num.clusters){ max.events.cn = MAXEVENTS.clusters[cn] daep.cn = array(0,c(max.events.cn, ngrid)); daep.cn = dAEP.clusters[(dum.int + 1) : (dum.int + max.events.cn),]; dum.int = dum.int + max.events.cn if (poisson.or.nb[cn] == 'poisson') { freq.dist = array( dpois(c(1:max.events.cn), rates.clusters[cn]), c(max.events.cn, ngrid) ) freq.dist.0 = dpois(0,rates.clusters[cn]) daep.cn = freq.dist* daep.cn } if (poisson.or.nb[cn] == 'negative binomial') { mu = rates.clusters[cn]; va = rates.clusters[cn] + rates.clusters[cn]^2 * (betas[cn,i]); r = mu*mu/(va-mu); p = r/(r+mu) freq.dist = array( dnbinom( c(1:max.events.cn), prob=p, size=r), c(max.events.cn, ngrid) ) freq.dist.0 = dnbinom(0, prob=p, size=r) daep.cn = freq.dist * daep.cn } caep.cn = colSums(daep.cn, na.rm=TRUE) #get the aep for this particular cluster aep = vector('numeric', (ngrid + 1)) aep[1] = 1 - freq.dist.0 for (ijk in 2:(ngrid+1)){ aep[ijk] = aep[ijk-1] - caep.cn[ijk-1] } cdf.nc = 1 - aep #note that in the original code, the charac.func is only on the ngrid (not ngrid + 1) #should be 100% that this is not having an impact daep = cdf.nc - c(0,cdf.nc[1:ngrid]) charac.func = charac.func * fft(daep) } AEP.clusters[i,] = 1 - cumsum(Re(fft(charac.func,inverse=TRUE))/(ngrid+1)) # finally compute the AEP #--->>> } return(list(xx=xx,OEP=OEP.clusters,AEP=AEP.clusters)) } #---------- #routine to get the cep and daep (with no multiplication by the frequencies) #idea is to, for one particular definition of cluster groupings, strip out the calculations that need not #be repeated, so we can try many different configurations of the variances #note that we are always getting the MAXEVENTS using a poisson distribution with twice the input rate get.cep.daep <- function ( rate, loss, expsr, std, mlr, maxloss , ngrid, alpha) { N = length(rate) nthrs = ngrid LAMBDA = sum(rate) #determine the MAXEVENTS, determined from poisson with TWICE the input LAMBDA, which should 'cover' NB cases MAXEVENTS = pmax(20,qpois((1-1/20000),2*LAMBDA)) dx = maxloss*2 / nthrs xx = c((1:nthrs)*dx) LTT = array(0,dim=c(nthrs,2)) LTT[,1] = xx beta.coeff = get.alpha.beta(mlr,std) #get the CEP array CEP(ngrid) FX <- CEP <- array(0,nthrs) for ( i in 1:N ) { # if ( i %% 100 == 0 ) { print(i) } this.aa = beta.coeff[i,1] this.bb = beta.coeff[i,2] this.lambda = rate[i] this.xx = LTT[,1]/expsr[i] this.FX = pbeta(this.xx , shape1 = this.aa, shape2 = this.bb ) FX = FX + (this.lambda/LAMBDA) * this.FX CEP = CEP + (this.lambda/LAMBDA) * (1-this.FX) } nthrs = length(CEP) SDF = vector('numeric',nthrs) hold = c(1,CEP) #now difference the cdf (1-ep) to get the value of the density on the grid for ( i in 1:nthrs ) { SDF[i] = hold[i] - hold[i+1] } #now convolve the severity distribution n=1,n=2,n=3 etc. times to take care of all possible aggregations, upto MAXEVENTS AC = my_acoeff(nthrs,MAXEVENTS) Sconv = SDF dAEP = array(0,dim=c(MAXEVENTS,nthrs)) for ( k in 1:(MAXEVENTS-1) ) { # print(paste('EVENT ; ',k)) hold = convolve(AC[k,],rev(Sconv),type='o')[1:nthrs] dAEP[k,] = hold[1:nthrs] #dAEP[k,] = feq.dist[k+1]*hold[1:nthrs] Sconv = convolve(SDF,rev(Sconv),type='o')[1:nthrs] } #<NAME> has made change to the code below so that we pick MAXEVENTS hold = convolve(AC[k+1,],rev(Sconv),type='o')[1:nthrs] dAEP[MAXEVENTS,] = hold[1:nthrs] return(list(xx=LTT[,1],CEP=CEP,dAEP=dAEP, MAXEVENTS = MAXEVENTS)) } <file_sep> #---function written by <NAME> which generalizes wang's analytical theory to K clusters #---cluster number is found in the incoming array clutser.num #---array poisson.or.nb == 1 if we have a cluster, and 0 is subset of events is treated as poisson #---we return both pure poisson and clustered aep and oeps (as a function of the loss discretization) #---this function generalizes the poisson.mixture function #---we will later create a vectorized version to avoid looping over all the events #---note, i have tested replacement of the loop using vectorized code and it was slower #---hypothesis for why vectorized code slower is the increase in the amount of matrix multiplies #---note that for the case of the favourite german cluster, we get exact agreement between this generalized #---code and the original poisson.mixture routine #---should update for zero loss thresholds poisson.mixtureK <- function( mlr, std, rate, expsr, loss, nclusters, cluster.num, betas, poisson.or.nb, ngrid ) { #---some parameters defining computational grid (for computation of subset CEPs) nn = ngrid max.ll = 2.0*max(loss) dx = max.ll / nn xx = c((1:nn)*dx) #---get the overall rate and the beta distribution parameters, rates for the cluster subsets alpha.beta = get.alpha.beta(mlr,std) lambda=sum(rate) LC = array(0,c(nclusters)) for (k in 1:nclusters){ take = which(cluster.num == k); LC[k] = sum(rate[take]) } #---init entire event set weighted cummulative loss distribution - 1 - FX is the CEP FX <- aep.fx <- array(0,nn) #---init weighted cummulative loss distributions per cluster FC <- aep.fc <- array(0,c(nclusters,nn)) #---loop event by event, first get overall number of events fn.nevents = length(mlr) for ( ievent in 1:fn.nevents ) { #---get the ceps by integration this.lambda = rate[ievent] this.aa = alpha.beta[ievent,1] this.bb = alpha.beta[ievent,2] this.mlr = mlr[ievent] this.std = std[ievent] this.xx = xx/expsr[ievent] this.dx = dx/expsr[ievent] this.FX = pbeta(this.xx[1:nn] , shape1 = this.aa, shape2 = this.bb ) #---FX for poisson model FX = FX + (this.lambda/lambda) * this.FX #---FC for clustered model FC[cluster.num[ievent],] = FC[cluster.num[ievent],] + (this.lambda/LC[cluster.num[ievent]]) * this.FX #---do the differencing to get approximation weighted event loss pdf (note that we want to discretize for the fft) FX2 = pbeta(this.xx[2:nn-1] + this.dx/2, shape1= this.aa, shape2 = this.bb) FX1 = pbeta(this.xx[2:nn-1] - this.dx/2, shape1= this.aa, shape2 = this.bb) this.fx = array(0.,nn) this.fx[1] = pbeta(this.xx[1] - this.dx/2, shape1= this.aa, shape2 = this.bb) this.fx[2:nn] = FX2 - FX1 #---aep.fx for poisson model aep.fx = aep.fx + (this.lambda/lambda) * this.fx #---aep.fc for clustered model aep.fc[cluster.num[ievent],] = aep.fc[cluster.num[ievent],] + (this.lambda/LC[cluster.num[ievent]]) * this.fx } #---perform poisson calculations (have added in the OEP2 and OEP3 for the poisson assumption) OEP = 1 - exp(-lambda*(1-FX)) OEP2 = 1 - exp(-lambda*(1-FX))*(1 + lambda*(1-FX)) OEP3 = 1 - exp(-lambda*(1-FX))*(1 + lambda*(1-FX)) - (1/2)*exp(-lambda*(1-FX))*(lambda*(1-FX))^2 EEF = (1-FX)*lambda fx.hat.poisson = exp( -lambda * ( 1-fft(aep.fx) ) ) AEP = 1 - cumsum(Re(fft(fx.hat.poisson,inverse=TRUE)/nn)) #---loop over all different beta combinations num.beta.combinations = length(betas[1,]) OEPcluster <- AEPcluster <- array(0,c(num.beta.combinations,nn)) for (ijk in 1:num.beta.combinations){ #---perform calculations for the clusters - oep oep.factors = array(0,c(nclusters,nn)) for (k in 1:nclusters){ #---NB if (poisson.or.nb[k] == 'negative binomial') oep.factors[k,] = ( 1 - LC[k]*betas[k,ijk]*(FC[k,]-1) ) ^ (-(1/betas[k,ijk])) #---Poisson if (poisson.or.nb[k] == 'poisson') oep.factors[k,] = exp(-LC[k]*(1 - FC[k,])) } oep.product.pgfs = array(1.,nn); for (k in 1:nclusters){ oep.product.pgfs = oep.product.pgfs * oep.factors[k,] } OEPcluster[ijk,] = 1 - oep.product.pgfs #---perform calculations for the clusters - aep #---here we are using the probability generating function of the negative binomial distribution (derived from mixing gamma+poisson) aep.factors = array(0,c(nclusters,nn)) for (k in 1:nclusters){ #---NB if (poisson.or.nb[k] == 'negative binomial') aep.factors[k,] = ( 1 - LC[k]*betas[k,ijk]*(fft(aep.fc[k,]) - 1) ) ^ (-(1/betas[k,ijk])) #---Poisson if (poisson.or.nb[k] == 'poisson') aep.factors[k,] = exp(-LC[k] * (1 - fft(aep.fc[k,])) ) } aep.product.pgfs = array(1.,nn); for (k in 1:nclusters){ aep.product.pgfs = aep.product.pgfs * aep.factors[k,] } AEPcluster[ijk,] = 1 - cumsum(Re(fft(aep.product.pgfs,inverse=TRUE)/nn)) } #---compute the implied overdispersion parameters for each cluster (gotten from the analytic formula) overdispersion = betas; for (i in 1:nclusters){ overdispersion[i,] = LC[i] * overdispersion[i,] }; overdispersion = overdispersion + 1 #---return the clustered, and the unclustered EPs and also the EEFs return(list(xx=xx,EEF=EEF,OEPpoi=OEP,AEPpoi=AEP,OEP=OEPcluster,AEP=AEPcluster,OEP2poi=OEP2,OEP3poi=OEP3,overdispersion=overdispersion,rates.in.clusters=LC)) } #original version of poisson mixture code poisson.mixture <- function ( mlr, std, rate, expsr, loss, thrs, alpha ) { # alpha is 1/alpha in 7.1 wang li = sum(rate[loss<thrs]) lc = sum(rate[!loss<thrs]) lambda = sum(rate) #assuming some grid to get the weighted event loss distributions, could expand this grid #note that we are essentially differencing the cdf alpha.beta = get.alpha.beta(mlr,std) ## computation of grid of losses nn = 2^12 max.ll = 2.0*max(loss) dx = max.ll / nn xx = c((1:nn)*dx) fn.nevents = length(mlr) FI <- FC <- FX <- aep.fx <- aep.fi <- aep.fc <- array(0,nn) for ( ievent in 1:fn.nevents ) { this.lambda = rate[ievent] this.aa = alpha.beta[ievent,1] this.bb = alpha.beta[ievent,2] this.mlr = mlr[ievent] this.std = std[ievent] this.xx = xx/expsr[ievent] this.dx = dx/expsr[ievent] this.FX = pbeta(this.xx[1:nn] , shape1 = this.aa, shape2 = this.bb ) FX = FX + (this.lambda/lambda) * this.FX if ( loss[ievent] < thrs ) { FI = FI + (this.lambda/li) * this.FX } else { FC = FC + (this.lambda/lc) * this.FX } FX2 <- pbeta(this.xx[2:nn-1] + this.dx/2, shape1= this.aa, shape2 = this.bb) FX1 <- pbeta(this.xx[2:nn-1] - this.dx/2, shape1= this.aa, shape2 = this.bb) this.fx = array(0.,nn) #it works perfectly fine, but why do we integrate from 0 to x(1) - dx/2 and not x(1) + dx/2 ??? this.fx[1] = pbeta(this.xx[1] - this.dx/2, shape1= this.aa, shape2 = this.bb) this.fx[2:nn] <- FX2 - FX1 aep.fx <- aep.fx + (this.lambda/lambda) * this.fx # pdf weighted average if ( loss[ievent] < thrs ) { aep.fi = aep.fi + ( this.lambda/li ) * this.fx } else { aep.fc = aep.fc + ( this.lambda/lc ) * this.fx } } OEP = 1 - exp(-lambda*(1-FX)) fl_c = ( 1 - lc*alpha * ( FC - 1)) ^ (-(1/alpha)) fl_i = exp(-li*(1-FI)) OEPmix = 1- fl_c*fl_i fx.hat.poisson = exp( -lambda * ( 1-fft(aep.fx) ) ) AEP = 1 - cumsum(Re(fft(fx.hat.poisson,inverse=TRUE)/nn)) fx.nc = ( 1 - lc*alpha * ( fft(aep.fc) - 1)) ^ (-(1/alpha)) fx.ni = exp( -li * ( 1-fft(aep.fi) ) ) fx.nb = array(0.,nn) for ( i in 1:nn) { fx.nb[i] = fx.ni[i]*fx.nc[i] } AEPmix = 1 - cumsum(Re(fft(fx.nb,inverse=TRUE))/nn) #inverse fourier transform of the product of pgs of characteristics # key thing for a correlated cluster, is that you can't multiply the pgs for each event together, you need to use the joint expression AEPpoi = 1 - cumsum(Re(fft(fx.ni,inverse=TRUE))/nn) AEPneg = 1 - cumsum(Re(fft(fx.nc,inverse=TRUE))/nn) EEF = (1-FX)*lambda return(list(xx=xx,EEF=EEF,OEP=OEP,OEPmix=OEPmix,AEP=AEP,AEPmix=AEPmix, fx.ni=fx.ni,fx.nb=fx.nb,AEPpoi=AEPpoi,AEPneg=AEPneg)) } #routine to get the alpha and beta coefficients of the BETA distribution get.alpha.beta <- function ( mu, sig ) { N = length(mu) beta.coeff = array(0,dim=c(N,2)) for ( i in 1:N ) { beta.coeff[i,1] = (mu[i]^2 * ( 1-mu[i] ))/sig[i]^2 - mu[i] beta.coeff[i,2] = ( beta.coeff[i,1] *( 1- mu[i]))/mu[i] } return(beta.coeff) } #vectorized version of get.alpha.beta routine get.alpha.beta.vec <- function ( mu, sig ) { beta.coeff.mat = array(0,c(length(mu),2)) beta.coeff.mat[,1] = (mu^2*(1-mu))/sig^2 - mu beta.coeff.mat[,2] = beta.coeff.mat[,1]*(1-mu)/mu return(beta.coeff.mat) } <file_sep>########## # routine to generate Nyears simulations of event ids based on a poisson or negative binomial distribution # used for any sub-event set whether negative binomial (for overall rate) or poisson # note that for years without events, nothing is output ########## get.id.sim.SCk <- function( ratek, idsk, datesk, Nyears, poisson.or.nb, var.gamma ){ ########## # determine number of years with nevents given our choice of frequency distribution ########## #---get average annual rate applicable across frequency distributions lamda = sum(as.numeric(ratek)) if ( poisson.or.nb == "poisson" ){ #---lamda above specifies the one parameter poisson distribution nevents.in.sim = NULL ni.array = NULL ni = 0 while (ni >= 0){ #---get the probability of ni events from the poisson distribution and multiply by Nyears #---good aspect of R is that there is nothing wrong with analytic evaluation numerically nyears.with.ni = Nyears * exp(-lamda) * lamda^ni / factorial( ni ) # nyears.with.ni = Nyears * dpois(ni, lambda = lamda) rounded.nyears.with.ni = round(nyears.with.ni) if (rounded.nyears.with.ni >= 1){nevents.in.sim = rbind(nevents.in.sim, rounded.nyears.with.ni); ni.array = c(ni.array,ni); ni = ni + 1} # if we are on the left side of the distribution, we want to keep going, make sure ni>5 so we keep going # these manipulations are inexact under some circumstances and used with caution in testing phase # the final test of whether or not this is technically correct will be the sim platform results if (rounded.nyears.with.ni < 1) { if (ni > 5){ ni = -99 }else{ ni = ni + 1 } } } if (sum(nevents.in.sim) < Nyears){nevents.in.sim[1] = nevents.in.sim[1] + (Nyears - sum(nevents.in.sim))} } if ( poisson.or.nb == "negative binomial" ){ #---frequency distribution is negative binomial with mean = lamda and variance = lamda + var.gamm*lamda^2 #---using definition 6.3 in the Klugman loss model book ... using r and B (beta) definitions r = 1.0/var.gamma B = var.gamma * lamda #---compute num of years with 0,1,2, ... storms until rounded number of years to nearest integer is 0 #---init an nevents array which stores number of years with 0,1,2,3,...,MAX number of storms #---start by computing number of years with zero events #---recovering missing years by adding in a few zero years #---i don't believe that our use of the analytic formula is leading to any numerical difficulty due to op order #---note that for the ews clustered cases, i have not noticed any problem of this code 'stopping' on the left hand side of the distribution nevents.in.sim = NULL ni.array = NULL ni = 0 while (ni >= 0){ nyears.with.ni = Nyears * ( choose( (ni+r-1), ni ) * (1/(1+B))^r * (B/(1+B))^ni ) rounded.nyears.with.ni = round(nyears.with.ni) if (rounded.nyears.with.ni >= 1){nevents.in.sim = rbind(nevents.in.sim, rounded.nyears.with.ni); ni.array = c(ni.array,ni); ni = ni + 1} if (rounded.nyears.with.ni < 1) {ni = -99} print(rounded.nyears.with.ni) } if (sum(nevents.in.sim) < Nyears){nevents.in.sim[1] = nevents.in.sim[1] + (Nyears - sum(nevents.in.sim))} } ########## # stratified year, event id and genesis date simulation ########## #---get the number of events per year over the Nyears num.per.year = NULL for (i in 1:length(ni.array)){ # print(i) num.per.year = c( num.per.year, array(ni.array[i],c(nevents.in.sim[i])) ) } #---randomly shuffle the time series over the Nyears random.years = sample(num.per.year,Nyears,replace=FALSE,prob=NULL) #---get the list of years with non-zero events, and repeat year number M times if there are M events in a particular year allyears = seq(1,Nyears,by=1) take = which(random.years > 0) allyears = allyears[take] num.events.non.zero.years = random.years[take] #---create an array holding the list of years yearssim = array( 0, c(sum(num.events.non.zero.years)) ) #---get the mother list of years dumi = 1 for (i in 1:length(allyears)){ yearssim[dumi:(dumi+num.events.non.zero.years[i]-1)] = allyears[i] dumi = dumi + num.events.non.zero.years[i] } #---get representative sample of the conditional event distribution (not sorting in terms of loss as unnecessary) num.samples.ced = sum(num.events.non.zero.years) #---partition 0-->>1 with midpoints right.partition = seq(1, num.samples.ced, by=1) / num.samples.ced left.partition = seq(0, (num.samples.ced-1), by=1) / num.samples.ced midpoints.partition = (left.partition + right.partition)/2.0 #---now getting the cummulative event distribution event.probs = ratek / sum( ratek ) cumsum.events = cumsum(event.probs) #---sweep over all possible events (picking events consistent with our partitioning of the uniform distribution) #---adding in simulation of base genesis dates idsimulation = array(0,c(num.samples.ced)) genesis.simulation = array("0",c(num.samples.ced)) dumi = 1 for (i in 1:length(ratek)){ # print(i) take = which( midpoints.partition <= cumsum.events[i] ) #---if there are any events to take, add to the idsimulation list, and then ignore by setting to value greater than 1 if(length(take) > 0){idsimulation[dumi:(dumi + length(take) - 1)] = idsk[i] genesis.simulation[dumi:(dumi + length(take) - 1)] = as.character(as.Date(datesk[i],"%d/%m/%y")) midpoints.partition[take] = 99.0} dumi = dumi + length(take) } #---spread the sample ids across the years randomly (keeping track of the associated genesis dates by using the match function) random.ids = sample(idsimulation, num.samples.ced, replace=FALSE, prob=NULL) take = match(random.ids, idsimulation) associated.genesis.dates = genesis.simulation[take] print('completed event id simulation') ########## # stratified sampling of associated loss quantiles ########## #---get the simulation of the loss quantiles (obtained from random shuffling of the midpoints.partition used for the conditional event distribution) #---using left/right partitions stored in memory allsortedquantiles = (right.partition + left.partition)/2.0 randomquantiles = sample(allsortedquantiles, num.samples.ced, replace=FALSE, prob=NULL) print('completed stratified sampling of the loss quantiles') ########## # randomization of genesis dates by monthly bin ########## #---randomize the associated genesis dates within monthly bins (adding +- 15 days) by doing a stratified sampling #---filling remainder days with zero increments. note that our base year is 2011 and some increments will push us into 2010 and 2012 #---changing back to year 2011 will be done at a script level min.day = -15 max.day = 15 num.days = 1 - min.day + max.day num.each.increment = floor(num.samples.ced/num.days) num.missing = num.samples.ced - num.each.increment*num.days plus.minus.days = array(-99,c(num.samples.ced)) plus.minus.days[1:num.missing] = 0 dumi = num.missing+1 for (i in seq(-15,15,by=1)){ plus.minus.days[dumi:(dumi+num.each.increment-1)] = i dumi = dumi + num.each.increment } random.day.increments = sample(plus.minus.days) ran.dates = as.Date(associated.genesis.dates) + random.day.increments print('completed date randomization') ########## # return stratified years simulation, event/source ids, random loss quantiles, genesis dates and randomized dates ########## #---return the list of simulation year, ids, and loss quantiles return(list( yearssim=yearssim, random.ids=random.ids, randomquantiles=randomquantiles, associated.genesis.dates=associated.genesis.dates, ran.dates=ran.dates )) } ########## # routine to generate ep statistics from simulation array (which includes randomized losses) # ***assumes that simyear array is in ascending order*** # ***need to be very careful when filling in the agg.loss array to fill in the appropriate years*** # ***above will not matter for the overall statistics, but is crucial when we are considering ordering*** ########## get.AEPOEP.from.simarray <- function ( simarray, Nyears ){ #---get simyear and lossses simyear = simarray[,1] losses = as.numeric(simarray[,5]) #---define aggregate and occurrence loss arrays over all years and initializing to zero agg.loss = array(0,c(Nyears)) occ.loss = array(0,c(Nyears)) #---get starting indeces of unique years ... this will result in skipping 'missing' years duplicates = duplicated(simyear) start.indeces = which(duplicates == FALSE) unique.years = unique(simyear) num.unique.years = length(unique.years) #---loop over all years except the last (filling in correct years!) for (i in 1:(num.unique.years-1)){ #---note again that these year.to.fill's will on occassion skip years when there are not events, but those years are zeroed at the start so ok year.to.fill = unique.years[i] #---in what follows we are taking the data that belongs to the year of interest agg.loss[year.to.fill] = sum(losses[start.indeces[i]:(start.indeces[i+1]-1)]) occ.loss[year.to.fill] = max(losses[start.indeces[i]:(start.indeces[i+1]-1)]) } #---get the last year inefficiently but only once #---we are getting the last year for which there are simulation data available final.year = unique.years[ num.unique.years ] take = which( simyear == final.year ) agg.loss[ final.year ] = sum( losses[take] ) occ.loss[ final.year ] = max( losses[take] ) return(list( occ.loss=occ.loss, agg.loss=agg.loss )) } get.AEPOEP.HF <- function ( year, sim.losses, Nyears ){ #---get simyear and lossses simyear = year losses = sim.losses #---define aggregate and occurrence loss arrays over all years and initializing to zero agg.loss = array(0,c(Nyears)) occ.loss = array(0,c(Nyears)) #---get starting indeces of unique years ... this will result in skipping 'missing' years duplicates = duplicated(simyear) start.indeces = which(duplicates == FALSE) unique.years = unique(simyear) num.unique.years = length(unique.years) #---loop over all years except the last (filling in correct years!) for (i in 1:(num.unique.years-1)){ #---note again that these year.to.fill's will on occassion skip years when there are not events, but those years are zeroed at the start so ok year.to.fill = unique.years[i] #---in what follows we are taking the data that belongs to the year of interest agg.loss[year.to.fill] = sum(losses[start.indeces[i]:(start.indeces[i+1]-1)]) occ.loss[year.to.fill] = max(losses[start.indeces[i]:(start.indeces[i+1]-1)]) print(i) } #---get the last year inefficiently but only once #---we are getting the last year for which there are simulation data available final.year = unique.years[ num.unique.years ] take = which( simyear == final.year ) agg.loss[ final.year ] = sum( losses[take] ) occ.loss[ final.year ] = max( losses[take] ) return(list( occ.loss=occ.loss, agg.loss=agg.loss )) } ########## # simplified simulation routine for the high frequency poisson case ########## get.id.sim.HF <- function( ratek, idsk, Nyears ){ ########## # determine number of years with nevents given our choice of frequency distribution ########## #---get average annual rate applicable across frequency distributions lamda = sum(as.numeric(ratek)) #---lamda above specifies the one parameter poisson distribution nevents.in.sim = NULL ni.array = NULL ni = 0 while (ni >= 0){ #---get the probability of ni events from the poisson distribution and multiply by Nyears #---good aspect of R is that there is nothing wrong with analytic evaluation numerically #nyears.with.ni = Nyears * exp(-lamda) * lamda^ni / factorial( ni ) nyears.with.ni = Nyears * dpois(ni, lambda = lamda) rounded.nyears.with.ni = round(nyears.with.ni) if (rounded.nyears.with.ni >= 1){nevents.in.sim = rbind(nevents.in.sim, rounded.nyears.with.ni); ni.array = c(ni.array,ni); ni = ni + 1} print(ni); print(rounded.nyears.with.ni) browser() # if we are on the left side of the distribution, we want to keep going, make sure ni>5 so we keep going # these manipulations are inexact under some circumstances and used with caution in testing phase if (rounded.nyears.with.ni < 1) { if (ni > 66){ ni = -99 }else{ ni = ni + 1 } } } if (sum(nevents.in.sim) < Nyears){nevents.in.sim[1] = nevents.in.sim[1] + (Nyears - sum(nevents.in.sim))} ########## # stratified year, event id and genesis date simulation ########## #---get the number of events per year over the Nyears num.per.year = NULL for (i in 1:length(ni.array)){ # print(i) num.per.year = c( num.per.year, array(ni.array[i],c(nevents.in.sim[i])) ) } browser() #---randomly shuffle the time series over the Nyears random.years = sample(num.per.year,Nyears,replace=FALSE,prob=NULL) #---get the list of years with non-zero events, and repeat year number M times if there are M events in a particular year allyears = seq(1,Nyears,by=1) take = which(random.years > 0) allyears = allyears[take] num.events.non.zero.years = random.years[take] #---create an array holding the list of years yearssim = array( 0, c(sum(num.events.non.zero.years)) ) #---get the mother list of years dumi = 1 for (i in 1:length(allyears)){ yearssim[dumi:(dumi+num.events.non.zero.years[i]-1)] = allyears[i] dumi = dumi + num.events.non.zero.years[i] } #---get representative sample of the conditional event distribution (not sorting in terms of loss as unnecessary) num.samples.ced = sum(num.events.non.zero.years) #---partition 0-->>1 with midpoints right.partition = seq(1, num.samples.ced, by=1) / num.samples.ced left.partition = seq(0, (num.samples.ced-1), by=1) / num.samples.ced midpoints.partition = (left.partition + right.partition)/2.0 #---now getting the cummulative event distribution event.probs = ratek / sum( ratek ) cumsum.events = cumsum(event.probs) #---sweep over all possible events (picking events consistent with our partitioning of the uniform distribution) #---adding in simulation of base genesis dates idsimulation = array(0,c(num.samples.ced)) # genesis.simulation = array("0",c(num.samples.ced)) dumi = 1 for (i in 1:length(ratek)){ # print(i) take = which( midpoints.partition <= cumsum.events[i] ) #---if there are any events to take, add to the idsimulation list, and then ignore by setting to value greater than 1 if(length(take) > 0){idsimulation[dumi:(dumi + length(take) - 1)] = idsk[i] # genesis.simulation[dumi:(dumi + length(take) - 1)] = as.character(as.Date(datesk[i],"%d/%m/%y")) midpoints.partition[take] = 99.0} dumi = dumi + length(take) } #---spread the sample ids across the years randomly (keeping track of the associated genesis dates by using the match function) random.ids = sample(idsimulation, num.samples.ced, replace=FALSE, prob=NULL) take = match(random.ids, idsimulation) # associated.genesis.dates = genesis.simulation[take] print('completed event id simulation') ########## # stratified sampling of associated loss quantiles ########## #---get the simulation of the loss quantiles (obtained from random shuffling of the midpoints.partition used for the conditional event distribution) #---using left/right partitions stored in memory allsortedquantiles = (right.partition + left.partition)/2.0 randomquantiles = sample(allsortedquantiles, num.samples.ced, replace=FALSE, prob=NULL) print('completed stratified sampling of the loss quantiles') ########## # return stratified years simulation, event/source ids, random loss quantiles, genesis dates and randomized dates ########## #---return the list of simulation year, ids, and loss quantiles return(list( yearssim=yearssim, random.ids=random.ids, randomquantiles=randomquantiles )) } <file_sep>dice_function <- function(probs, xvals, trials){ data = NULL cumulative = cumsum(probs) for(i in 1:trials){ uniform = runif(1) data = c(data, findInterval(uniform, cumulative)) ylim = max(probs)*trials } pdf (file = "D:\\Documents\\Programming\\R Projects\\Shree's Project\\Week 4\\Dice Plot (100000 Trials).pdf", width = 4, height = 4) barplot(table(data), col = rgb(0.8, 0.1, 0.1, 0.6), xlab = "X Values", ylab = "Frequency", main = "Histogram of Manual Dice Rolling", ylim = c(0, ylim)) theoretical = sample((min(xvals)):max(xvals), size = trials, replace = TRUE, prob = probs) hist(theoretical, col = rgb(0.8, 0.1, 0.1, 0.6), main = "Histogram of Theoretical Dice Rolling", xlab = "X Values") dev.off() } poisson_function <- function(lambda, trials){ data = NULL for (i in 1:trials){ X = 0 P = 1 while (P >= exp(-lambda)){ U = runif(1, min = 0, max = 1) P = U * P X = X + 1 } data = c(data, X) } pdf (file = "D:\\Documents\\Programming\\R Projects\\Shree's Project\\Week 4\\Poisson Plot (100000 Trials).pdf", width = 4, height = 4) barplot(table(data), col = rgb(0.8, 0.1, 0.1, 0.6), xlab = "X Values", ylab = "Frequency", main = "Histogram of Manual Poisson") theoretical = rpois(trials, lambda) hist(theoretical, main = "Histogram of Theoretical Poisson", col = rgb(0.8, 0.1, 0.1, 0.6), xlab = "X Values", ylab = "Frequency", breaks = 30) dev.off() } a = c(0.05, 0.05, 0.4, 0.3, 0.2) b = c(0, 1, 2, 3, 4) manual_dice = dice_function(a, b, 100000) manual_poisson = poisson_function(20, 100000)<file_sep>#setting initial conditions N = 10000 alpha = 5 beta = 5 par(mfrow = c(1,2)) #running the simulation U = runif(N) b_rand = qbeta(U, alpha, beta) #plotting the results hist(b_rand, xlab = "Value", col="skyblue", main = "Runif For Beta Distribution") #draw N beta distributed values y_rbeta = rbeta(N, shape1 = alpha, shape2 = beta) #plot of randomly drawn beta density plot(density(y_rbeta), main = "Beta Distribution With Rbeta")<file_sep>occ_simulation2 = function(n_year, lambda, alpha, beta, max_event){ beta_events = matrix(rbeta(n_year * max_event, shape1 = alpha, shape2 = beta), nrow = n_year) n_events_per_year = rpois(n_year, lambda = lambda) for(i in which(n_events_per_year < max_event)) { beta_events[i, (n_events_per_year[i] + 1):max_event] = NA } cbind(1:n_year, beta_events) } occ_simulation2(n_year = 10, lambda = 10, alpha = 2, beta = 20, max_event = 5)<file_sep># Write a function that samples from an n-dimensional vector of xvals(n) and probs(n), m times, only using the uniform distribution. # # This function applies to any discrete probability vector that I feed into (which can be derived from a coin, a poisson, #or even a continuous pdf like beta (which requires numerical integration)). sampling_function <- function(m, xvals, probs){ uniform = runif(m, min = min(xvals), max = (xvals)) } xvalues = c(1, 2, 3, 4, 5) probs = c(0.2, 0.2, 0.2, 0.2, 0.2) sample_result = do.call(sampling_function, xvalues, probs)<file_sep>for (i in 1:10){ n = rpois (1,lambda = 2); print(n); if (n > 0) { for (i in 1:n){ b = rbeta (1, shape1 = 1, shape2 = 1.5); print(b) } } }
69708faf3007553114221ab959fa3aa5f3033444
[ "Markdown", "R" ]
17
R
Nhyi/R-Projects
cda7f68a3ab7eb21ba738dbaecfc732931dafb9e
5f038461248d31a691e81bfc7c3f6c728058e80f
refs/heads/master
<file_sep>-- 1. Pick HELLOWORLD as the unique identifier. -- 2. Pick /lh and /lowesthealth as slash commands local EventFrame = CreateFrame("frame") EventFrame:RegisterEvent("UNIT_HEALTH") EventFrame:SetScript("OnEvent", function(self,event,...) LowestPercentHealth=1 for i=1,4,1 do --Checks the Party's Health Health = UnitHealth("party" .. i) HealthMax = UnitHealthMax("party" .. i) PercentHealth = Health/HealthMax if PercentHealth < LowestPercentHealth then LowestPercentHealth = PercentHealth LowestHealthPlayer = UnitName("party" .. i) end end if UnitHealth("player")/UnitHealthMax("player") < LowestPercentHealth then --Checking if the Player is lower. LowestPercentHealth = UnitHealth("player")/UnitHealthMax("player") LowestHealthPlayer = UnitName("player") end ChatFrame1:AddMessage(LowestHealthPlayer.." - " .. math.floor(LowestPercentHealth * 100 + .5).."%") end) function LowestHealth_ShowMessage() message("This is a message.") end
7d057c38be871afe3b70b9c0004780144db5efb2
[ "Lua" ]
1
Lua
ProximityMicrowave/LowestHealth
89e379eaed841e6a0461cdbce4493ebdda19a403
770d496386e07902ab94c93202adf127cfb82a4b
refs/heads/master
<repo_name>linux-hyz/deletenote<file_sep>/note.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdbool.h> #include <errno.h> #include "note.h" #include "x_lib.h" int blank_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask); int single_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask); int multi_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask); int code_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask); struct note_choice choices[] = { {0, blank_note}, {1, single_note}, {2, multi_note}, {3, code_note}, }; int blank_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask) { fputs(buffer, stats->wrfp); if(mask&0x3) { stats->note +=mask&0x1; stats->combine+=(mask&0x2)>>1; } else { stats->count++; stats->blank++; } } int code_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask) { fputs(buffer, stats->wrfp); if(mask&0x3) { stats->combine++; } else { stats->count++; stats->code ++; } } int single_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask) { bool front = x_ispair(buffer, offset, '\"'); bool behind = x_ispair(buffer+offset, strlen(buffer)-offset, '\"'); if((!front)&&(!behind)) { fputs(buffer, stats->wrfp); return 0; } if(!(mask&0x3)/*mask == 0*/) { stats->count++; if(arg) { buffer[offset] = '\n'; buffer[offset+1] = '\0'; fputs(buffer, stats->wrfp); stats->combine++; } else { stats->note++; } return 0; } //mask != 0 if(arg) { buffer[offset] = '\n'; buffer[offset+1] = '\0'; fputs(buffer, stats->wrfp); stats->combine++; } else { stats->note +=mask&0x1; stats->combine+=(mask&0x2)>>1; } return 0; } int multi_note_tail(char* buffer) { int offset; for(offset = 0; offset < strlen(buffer); offset++) { if((buffer[offset] == '*') && (buffer[offset+1] == '/')) { break; } } return offset; } int multi_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask) { if(!(mask&0x3)) { stats->count++; } if(arg) { fwrite(buffer, offset, 1, stats->wrfp); mask=(0x1<<1); } else { if(mask == 0) mask = (0x1<<0); } // char* s = buffer + offset + 2; do{ s += multi_note_tail(s); if(s[0] != '\0') { goto find; } s = buffer; fgets(s, 1024, stats->rdfp); if(feof(stats->rdfp)) { break; } mask=(0x1<<0); stats->note ++; stats->count++; }while(!feof(stats->rdfp)); return -1; find: s += 2; uint8_t flag = 0; int offset2 = check_note(s, strlen(s), &flag); int type = flag&0x03; bool arg2 = (flag&0x04) >> 2; if(choices[type].handle(stats, s, offset2, arg2, mask) == -1) { return -1; } return 0; } int trim_buf(char* buffer) { char* p = buffer; while(*p == ' ' || *p == '\t') p++; return p - buffer; } int check_note(char* buffer, int len, uint8_t* flag) { // int i = trim_buf(buffer); // if(buffer[i] == '\n') { //blank line. *flag |= 0x00; return i; } // if(buffer[i] != '/') { *flag |= 0x04; } // for(; i < len; i++) { if(buffer[i] == '/') { if(buffer[i+1] == '/') { //single line note. *flag |= 0x01; return i; } else if(buffer[i+1] == '*') { //multi line note. *flag |= 0x02; return i; } } } //code line. *flag |= 0x03; return i; } <file_sep>/stats.h #ifndef __STATS_H_ #define __STATS_H_ #include <stdio.h> #include <stdbool.h> #include "note.h" bool stats_initialize(struct statistics* stats, char* rdfile, char* wrfile); int stats_note(struct statistics* stats); int stats_copy(struct statistics* stats); void stats_print(struct statistics* stats, FILE* fp); void stats_clean(struct statistics* stats); #endif <file_sep>/main.c #include <stdio.h> #include <sys/stat.h> #include <assert.h> #include <errno.h> #include "x_lib.h" #include "stats.h" int lpfn_work(char* path, char* name, int type, void* arg) { assert((type==0)||(type==1)); // char* s = (char* )arg; char buff[1024]; snprintf(buff, 1024, "%s/%s", s, name); // if(type == 0) { if(mkdir(buff, 0755) == -1) { printf("create directory[%s] error.\n", buff); return -1; } if(x_readdir(path, lpfn_work, buff) < 0) { printf("open directory[%s] error.\n", path); } } else if(type == 1) { struct statistics stats; if(!stats_initialize(&stats, path, buff)) { printf("statstic initialize error.\n"); return -1; } // int len; char* str = x_lastbyte(name, strlen(name), '.', &len); if((len == 1) && ((strncmp(str, "c", 1) != 0) || (strncmp(str, "h", 1) != 0))) { stats_note(&stats); stats_print(&stats, stdout); } else { stats_copy(&stats); } // stats_clean(&stats); } else { assert(0); } return 0; } int main(int argc, char* argv[]) { if(argc != 2) { printf("Usage: ./note arg [dir or path]\n"); return -1; } // char* s = strdup(argv[1]); int result; if((result = x_dirorfile(s)) < 0) { printf("[%s] is not directory or file.\n", s); return -1; } // int len; char* str = x_lastbyte(s, strlen(s), '/', &len); if(len <= 0) { str = s; len = strlen(s); } time_t now = time(NULL); char path[1024]; snprintf(path, 1024, "./%lld_%.*s", now, len, str); //start if(result == 0/*directory*/) { if(mkdir(path, 0755) == -1) { printf("create folder[%s] error.\n", path); return -2; } // if(x_readdir(s, lpfn_work, path) < 0) { printf("open directory[%s] error.\n", s); return -3; } } else if(result == 1/*file*/) { struct statistics stats; if(!stats_initialize(&stats, s, path)) { return -1; } stats_note(&stats); stats_print(&stats, stdout); } return 0; } <file_sep>/stats.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdbool.h> #include <errno.h> #include "stats.h" #include "note.h" extern struct note_choice choices[]; bool stats_initialize(struct statistics* stats, char* rdfile, char* wrfile) { //filename snprintf(stats->filename, sizeof(stats->filename), "%s", rdfile); //open file waiting for reading if((stats->rdfp = fopen(rdfile, "r")) == NULL) { printf("open file[%s] error: %s\n", stats->filename, strerror(errno)); return false; } // if((stats->wrfp = fopen(wrfile, "w")) == NULL) { printf("open file[%s] error: %s\n", stats->filename, strerror(errno)); return false; } // stats->count = 0; stats->blank = 0; stats->note = 0; stats->code = 0; stats->combine = 0; return true; } int stats_note(struct statistics* stats) { FILE* fp = stats->rdfp; while(!feof(fp)) { char buffer[1024]; fgets(buffer, sizeof(buffer), fp); if(feof(fp)) { break; } // uint8_t flag = 0; int offset = check_note(buffer, strlen(buffer), &flag); int type = flag&0x03; bool arg = (flag&0x04) >> 2; if(choices[type].handle(stats, buffer, offset, arg, 0) == -1) { break; } } return 0; } int stats_copy(struct statistics* stats) { char buf[1024]; int num; while(1) { if((num = fread(buf, 1, 1024, stats->rdfp)) != 1024) { if(!feof(stats->rdfp)) { printf("copy file[%s] error.\n", stats->filename); return -1; } else { fwrite(buf, 1, num, stats->wrfp); break; } } fwrite(buf, 1, 1024, stats->wrfp); } return 0; } void stats_print(struct statistics* stats, FILE* fp) { fprintf(fp, "file : %s\n" "count: %d\n" "blank: %d\n" "note : %d\n" "code : %d\n" "combine: %d\n",stats->filename, stats->count, stats->blank, stats->note, stats->code, stats->combine); } void stats_clean(struct statistics* stats) { fclose(stats->rdfp); fclose(stats->wrfp); } <file_sep>/x_lib.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #include <stdbool.h> #include "x_lib.h" int x_dirorfile(char* s) { struct stat st; lstat(s, &st); if(S_ISDIR(st.st_mode)) { return 0; } else if(S_ISREG(st.st_mode)) { return 1; } return -1; } int x_readdir(char* dir, callback lpfn, void* arg) { DIR* dp; if((dp = opendir(dir)) == NULL) { return -1; } struct dirent* dt; while((dt = readdir(dp)) != NULL) { if(strncmp(dt->d_name, ".", 1) == 0) continue; if(strncmp(dt->d_name, "CVS", 3) == 0) continue; char s[1024]; snprintf(s, 1024, "%s/%s", dir, dt->d_name); int result; if((result = x_dirorfile(s)) < 0) { continue; } if(lpfn(s, dt->d_name, result, arg) < 0) { continue; } } closedir(dp); return 0; } char* x_lastbyte(char* begin, int len, char ch, int* retlen) { if(len <= 0) goto nofind; char* end = begin + len - 1; if(*end == ch) goto nofind; while(end >= begin) { if(*end == ch) { end++; *retlen = begin + len - end; return end; } end--; } nofind: *retlen = 0; return NULL; } bool x_ispair(char* buffer, int len, char c) { bool ispair = true; int i; // for(i = 0; i < len; i++) { if(buffer[i] == c) { ispair = !ispair; } } return ispair; } <file_sep>/note.h #ifndef __NOTE_H_ #define __NOTE_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdbool.h> #include <errno.h> struct statistics { char filename[1024]; FILE* rdfp; FILE* wrfp; int count; int blank; int note; int code; int combine; }; typedef int (*lpfn)(struct statistics*, char*, int, bool, int); struct note_choice { int choice; lpfn handle; }; int check_note(char* buffer, int len, uint8_t* flag); #endif <file_sep>/Makefile all: debug SOURCE=main.c x_lib.c stats.c note.c DST=mynote debug: gcc -ggdb -o $(DST) $(SOURCE) release: gcc -O2 -o $(DST) $(SOURCE) clean: rm -f $(DST) <file_sep>/x_lib.h #ifndef __X_LIB_H__ #define __X_LIB_H_ #include <stdio.h> #include <stdbool.h> typedef int (*callback)(char*, char*, int, void*); int x_dirorfile(char* s); int x_readdir(char* dir, callback lpfn, void* arg); char* x_lastbyte(char* begin, int len, char ch, int* retlen); bool x_ispair(char* buffer, int len, char c); #endif
9ad163ffebddaebf3373cfbd1c004e88828bb727
[ "C", "Makefile" ]
8
C
linux-hyz/deletenote
5cfbe8592a363a01f2dfa9e1c9eb25c3c689466b
0cd86112f50fde10a0599988cfd9db32b59261a7
refs/heads/main
<repo_name>cunhaleandro/sefaz_desafio<file_sep>/com.sefaz.desafio/src/com/sefaz/desafio/model/User.java package com.sefaz.desafio.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) protected int id; protected String name; protected String email; protected String phone; protected String pass; public User() { } public User(String name, String email, String phone, String pass) { super(); this.name = name; this.email = email; this.phone = phone; this.pass = pass; } public User(int id, String name, String email, String phone) { super(); this.id = id; this.name = name; this.email = email; this.phone = phone; } public User(int id, String name, String email, String phone, String pass) { super(); this.id = id; this.name = name; this.email = email; this.phone = phone; this.pass = pass; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } }
027d73e2533e299972c8f1dc59ba6af231a16f71
[ "Java" ]
1
Java
cunhaleandro/sefaz_desafio
ce46f17b6c8c69647802dfdd7eb681aa1290e518
c9586c0ab957bb6b28b36cc2893fe33e3ac87370
refs/heads/master
<file_sep>const input = document.querySelector('#todo-input'); const button = document.querySelector('#todo-button'); const ul = document.querySelector('#todo-ul'); const todoItems = []; function handleSubmit(e) { e.preventDefault(); let listItem = document.createElement('li'); listItem.innerHTML = input.value; ul.appendChild(listItem); listItem.appendChild(createDeleteButton()); input.value = ''; } function createDeleteButton() { let deleteButton = document.createElement('button'); deleteButton.innerHTML = 'Delete'; deleteButton.addEventListener('click', handleDelete); return deleteButton; } function handleDelete() { this.parentNode.remove(); } button.addEventListener('click', handleSubmit)<file_sep># ![](https://ga-dash.s3.amazonaws.com/production/assets/logo-9f88ae6c9c3871690e33280fcf557f33.png) SOFTWARE ENGINEERING IMMERSIVE ## Dom Manipulation w/ Forms ### The Humble Text Input Mouse (and other various) keyboard events are a good first attempt to process user interactions and update the DOM in process, but there are many more and potentially richer methods at our disposal. _Input_ tags are one of these methods. Perhaps the most commonly recognized is the "text" input: ```html <input type="text" /> ``` Notice that it is a self-closing tag. It has no children or inner content exposed directly. Text inputs manage the state of the text inside them automatically. Forms can manage several inputs, text or others, using the `name` attribute on the element, but for now let's just extract the value of the input with javascript. ```js const input = document.querySelector('input'); const value = input.value; ``` The `input` element returned by `querySelector` includes a `value` property that can either be read or updated: ```js input.value = 'doggo'; console.log(input.value); ``` All we need is a button or click event to trigger some code to fetch the value out of the input and then perform a given action with it, e.g., creating a new element and appending it to the DOM. ##### Mini-Exercise Let's write up a form with a text input and a button: - Create a ```<form></form>``` element. - All form attributes are optional. You can build a form without the ```<form>``` tag just using ```inputs``` and ```buttons``` but you won't have access to some features specifically designed for ```forms```. - The `action` attribute defines the location (URL) where the form's collected data should be sent when it is submitted. This is the built-in attribute that causes forms to reload a page, and the reason we often have to use ```preventDefault()``` when submitting data. If you decide to build a form without using ```<form>``` tags then you won't need ```preventDefault()``` later on. - Add a text input to the html: `<input />`. Notice how this tag is self closing. - ```inputs``` have have a ```type``` attribute. The most common is ```text```. - The ```value``` attribute keeps track of the content (or state) inside the input field. This will be very important later. - ```autoFocus``` is an attribute that can be added to force focus to this specific input when the page loads. - The ```autoComplete``` attribute can be set to 'on' or 'off', though it is 'on' by default. When it is 'on,' it will remember and suggest entries previously entered as the input value. - Add a ```<button></button>``` - Inside a form, a ```button``` and an ```<input type='submit'>``` can be used almost interchangeably. If you use a submit input for this exercise, be sure to assign it a specific class or ID so we can destinguish between inputs later on with JavaScript. - For good measure, let's create a ```<section>``` tag. This is where our to-do list will be rendered, so let's give it a class name 'todo-list' Now let's jump into the our JS file: - Query select for all of the elements we just created (remember, if you used a submit input instead of a button, you'll need to grab your inputs by ID or class, not by tag name). #### List Some Todos Begin by initializing an empty array and storing it as a variable. This array will eventually contain a set of strings that represent each item on our to-do list. Now write a function (using whatever syntax you like) that uses a loop to display the items from our array inside the ```section``` tag we created in our HTML. - You can utilize ```<ul>``` and ```<li>``` tags for a list, but to simplify for this exercise, we're just going to create each item as a ```<p>``` tag. To test that this function works, let's hardcode some to-do items into our array and call the function. We should see each item from the array printed out in the browser. #### Add a Todo Register a click event listener on the ```button``` or ```submit```. This click needs to call a function that should: - extract the value of the text input - add the value to the `todos` array - call the the function that loops through our array and prints them out. Uh oh, you may have some duplicates! - In the looping function, add a command that resets the ```innerHTML``` of our ```<section>``` to an empty string before it loops and prints. - For good measure let's reset the value of our text input on the click event function as well. If we've done this correctly, all items we enter into the input field should be printed to our list! #### Bonus Try to add an additional button for deleting a Todo. After that, can you think of a way to _edit_ an existing Todo?
5204b5f82654841e2e2a1be5bc1d3d688602b059
[ "JavaScript", "Markdown" ]
2
JavaScript
jamespmernin/Todo-List-Form-Vanilla-JavaScript
1de677c35f170fec9561c8848414fd13ea13bdf9
87e1cd1c0208555ce6550fbeb1213ef994900daa
refs/heads/master
<repo_name>SDHaines/bcupdate<file_sep>/bcupdate.php #!/usr/local/bin/php <?php require_once '/usr/local/valCommon/BigComm.php'; require_once '/usr/local/valCommon/Counterpoint.php'; $ignoredItemList = "'10001', '10024', '10025','AGE_VERIFY','CLEAR_DL_DATA', 'CUST_ADD','LOTTO','LOTTO P/O','MISC','MO FEE','MONEYXFER', 'SCRATCHER P/O','SWIPE_DL','TEMPLATE'"; $oldItems = array (); $newItems = array (); $updateItems = array (); $oldBcInfo = array(); $tsql = "SELECT BC_ITEM_NO AS 'id', ADDL_DESCR_1 AS 'name', ITEM_NO AS 'sku', PRC_1 AS 'price', CASE TAX_CATEG_COD WHEN 'ALCOHOL' THEN '0' ELSE '5' END 'tax_class_id', QTY_AVAIL AS 'inventory_level', BARCOD AS 'upc' FROM VI_IM_ITEM_WITH_INV_AND_INV_TOTS WHERE BARCOD IS NOT NULL AND ITEM_TYP = 'I' AND STAT = 'A' AND ITEM_NO NOT IN ( $ignoredItemList ) "; $data = counterpointQuickQuery( $tsql ); if ( $data === null or $data === false ){ die ( "Can't query database for item list\n" ); } foreach( $data as $row ) { $qtyAvail = (int) $row['inventory_level']; if ( $qtyAvail < 0 ) { $qtyAvail = 0; } $row['price'] = sprintf (" %.02f", $row['price'] ); if ( isset( $row['id'] ) ) { $oldItems[$row['sku']] = array ( 'id' => $row['id'], 'name' => $row['name'], 'inventory_level' => $qtyAvail, 'description' => $row['name'], 'price' => $row['price'], 'cost_price' => $row['price'] ); } else { $newItems[$row['sku']] = ( object ) array ( 'name' => $row['name'], 'type' => 'physical', 'sku' => $row['sku'], 'description' => $row['name'], 'weight' => '1', 'price' => $row['price'], 'cost_price' => $row['price'], 'tax_class_id' => $row['tax_class_id'], 'inventory_level' => $qtyAvail , 'inventory_tracking' => 'product', 'is_visible' => false, 'upc' => $row['upc'], 'availability' => 'available', 'categories' => [23] ); } } $nextPage = 1; while ( $nextPage ){ $response = vcCurl( "GET", $vcBigCommProductUrl, $vcBigCommCurlHeaders, $vcBigCommCurlData ); if ( $response->responseCode == 200 ){ $nextPage = vcBigCommGetNextPage( $response ); for ( $i = 0; $i < $response->body->meta->pagination->count; $i++ ) { $p = $response->body->data[$i]; if ( ! isset ( $oldItems[$p->sku] ) ) continue; $currInventory = $oldItems[$p->sku]['inventory_level']; $currPrice = $oldItems[$p->sku]['price']; if ($p->inventory_level != $currInventory or $p->price != $currPrice ) { $updateItems[] = $oldItems[$p->sku]; $oldBcInfo[$p->sku] = $p; } } } else { print_r( $response ); } } $itemCount = count( $updateItems ); print "################### update ###################\n"; printf ( "%3d item%s need%s to be updated\n", $itemCount, $itemCount == 1 ? "" : "s", $itemCount == 1 ? "s" : "" ); while ( $update10 = array_splice ( $updateItems, 0, 10 ) ) { $data = json_encode( $update10 ); $response = vcCurl( "PUT", $vcBigCommProductUrl, $vcBigCommCurlHeaders, $data ); if ( $response->responseCode == 200 ) { $d = $response->body->data; $count = count( $d ); for ( $i = 0; $i < $count; $i++ ) { $sku = $d[$i]->sku; $oldQty = $oldBcInfo[$sku]->inventory_level; $oldPrice = $oldBcInfo[$sku]->price; $newQty = $d[$i]->inventory_level; $newPrice = $d[$i]->price; print "item_no: {$sku} {$d[$i]->name} updated sucessfully. "; printf ( "%s%s\n", $oldQty != $newQty ? "qty: $oldQty->$newQty " : "", $oldPrice != $newPrice ? "price: $oldPrice->$newPrice" : "" ); } } else { print "******************* Items not updated *******************\n"; print_r( $response ); print_r( $update10 ); print "******************* Items not updated *******************\n\n"; } } print "################### update ###################\n\n"; $itemCount = count ( $newItems ); print "#*#*#*#*#*#*#*#*#*# add new #*#*#*#*#*#*#*#*#*#\n"; printf ( "%3d item%s need%s to be added\n", $itemCount, $itemCount == 1 ? "" : "s", $itemCount == 1 ? "s" : "" ); foreach ( $newItems as $item ) { $data = json_encode( $item ); $response = vcCurl( "POST", $vcBigCommProductUrl, $vcBigCommCurlHeaders, $data ); if ( $response->responseCode == 200 ){ $d = $response->body->data; print "item_no: $d->sku $d->name added as id: $d->id qty: $d->inventory_level price: $d->price\n"; $bcItemNo = $response->body->data->id; $sku = $response->body->data->sku; $tsql = "UPDATE IM_ITEM SET BC_ITEM_NO = '$bcItemNo' WHERE ITEM_NO = '$sku'"; $dummy = null; $result = counterpointQuickQuery( $tsql, $dummy, $dummy, true, true ); if ( $result == 1 ) { print "cell BC_ITEM_NO for IM_ITEM.ITEM_NO $sku has been updated with value $bcItemNo\n"; } else { print "unexpected result: $result updating cell BC_ITEM_NO for IM_ITEM.ITEM_NO $sku with value $bcItemNo\n"; } } else { print "******************* Big Commerce item not added *******************\n"; print_r( $response ); print_r( $item ); print "******************* Big Commerce item not added *******************\n"; } } print "#*#*#*#*#*#*#*#*#*# add new #*#*#*#*#*#*#*#*#*#\n\n"; exit; ?>
47de2d8c044efb509ce66ce29c55eef604ae9000
[ "PHP" ]
1
PHP
SDHaines/bcupdate
50985e868a4ca2cf964b294a3f8133031a9b8af6
78c2c03433780240fb123a464f7c3da29e6d1f30
refs/heads/main
<file_sep># A-piano-Test-3- just uploading it here so it doesnt get lost will maybe integrate this into something else . to play use the first row of the qwerty keyboard i.e ( Q , W , R ...) see it here ... https://piano.lelouchcodes.repl.co/ <file_sep>const WhiteKeys = ["q","w","e","r","t","y","u","i","o","p","[","]","\\","'"] const BlackKeys = ['1','2','3','4','5','6','7','8','9','0'] const keys = document.querySelectorAll(".key") const whiteKeys =document.querySelectorAll(".key.white") const blackKeys =document.querySelectorAll(".key.black") keys.forEach(key=>{ key.addEventListener("click",() => playKey(key)) }) document.addEventListener("keydown",keyPressed) function keyPressed(event){ if(event.repeat){ return } const key = event.key; const WhiteKeyIndex = WhiteKeys.indexOf(key) const BlackKeyIndex = BlackKeys.indexOf(key) if(WhiteKeyIndex>-1){ playKey(whiteKeys[WhiteKeyIndex]) } if(BlackKeyIndex>-1){ playKey(blackKeys[BlackKeyIndex]) } } document.addEventListener("keydown",(e)=>{ if (e.repeat) { return; } if(e.keyCode==71){ //G playKey(whiteKeys[4]) } if(e.keyCode==67){ //C playKey(whiteKeys[0]) } if(e.keyCode==68){ //D playKey(whiteKeys[1]) } if(e.keyCode==65){//A playKey(whiteKeys[5]) } if(e.keyCode==70){//F playKey(whiteKeys[3]) } if(e.keyCode==66){//B playKey(whiteKeys[6]) } }) function playKey(key){ const keyAudio = document.getElementById(key.dataset.note); keyAudio.play() keyAudio.currentTime = 0 //starts replaying the music from 0 sec which is the starting time of the music. key.classList.add("active") keyAudio.addEventListener('ended',()=>{ key.classList.remove("active") }) }
1d9cffc1c1318366231b1e77f4695363468867e7
[ "Markdown", "JavaScript" ]
2
Markdown
Devansh-lelouch/A-piano-Test-3-
1f9d4d810f5667ce62c1edfc00725b7f3fc7ed4b
5a866a48c30f578720a02141cb0740b5ae4f5d60