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
<repo_name>tws0002/Maya-TurnTable<file_sep>/README.md # Maya-TurnTable Turntable maker script for Maya <file_sep>/main.py import maya.cmds as cmds import maya.cmds as cmds class Turntable: def __init__(self): self.obj = cmds.ls('object')[0] cmds.ctxEditMode() cmds.CenterPivot('{}'.format(self.obj)) cmds.ctxEditMode() cmds.makeIdentity('{}'.format(self.obj), t=True, r=True) def sethdri(self): hdr_list = ['night', 'overcast', 'studio', 'sunny'] cmds.setAttr('hdrDome.tex0', '\\\\192.168.3.6\\assets\_Software\Maya\Scripts\maya\\turntable\hdri\\{}.hdr' .format(hdr_list[0]), type='string') def setbackground(self): status = 0 if status == 0: cmds.setAttr('hdrDomeShape.background_enable', 1) status = 1 else: cmds.setAttr('hdrDomeShape.background_enable', 0) status = 0 def setcamera(self, *args): cmds.viewFit('maincamera', '{}'.format(self.obj)) cmds.setKeyframe('{}'.format(self.obj)) insta = Turntable() def createwindow(insta): # create a window if cmds.window('tableturn', ex=True): cmds.deleteUI('tableturn') cmds.window('tableturn') cmds.columnLayout() cmds.button(label='foofoo', command=insta.setcamera) cmds.showWindow('tableturn') createwindow(insta)
17fa0c3342f36613d01f0828d3d2d963ae1abcda
[ "Markdown", "Python" ]
2
Markdown
tws0002/Maya-TurnTable
9e6d96e6966642bbb64b3e43a15574599889f2fb
0386e91017a9dd1dc3f26057e1f79d93424d7ef2
refs/heads/main
<file_sep>from typing import Dict REMOVED = 'removed' UPDATED = 'updated' ADDED = 'added' EQUAL = 'equal' DICT = 'dict' def compare_dictionaries(dict_1: dict, dict_2: dict) -> Dict[str, list]: all_keys = (dict_1.keys() | dict_2.keys()) diff_keys1 = (dict_1.keys() - dict_2.keys()) diff_keys2 = (dict_2.keys() - dict_1.keys()) result = {} for key in all_keys: orig_value = dict_1.get(key) new_value = dict_2.get(key) if key in diff_keys1: value = [REMOVED, orig_value, None] elif key in diff_keys2: value = [ADDED, new_value, None] elif isinstance(orig_value, dict) and isinstance(new_value, dict): value = [DICT, compare_dictionaries(orig_value, new_value), None] elif orig_value == new_value: value = [EQUAL, orig_value, None] else: value = [UPDATED, orig_value, new_value] result[key] = value return result <file_sep># Difference generator [![Actions Status](https://github.com/DirtyHippy/python-project-lvl2/workflows/hexlet-check/badge.svg)](https://github.com/DirtyHippy/python-project-lvl2/actions) [![Maintainability](https://api.codeclimate.com/v1/badges/a99a88d28ad37a79dbf6/maintainability)](https://codeclimate.com/github/DirtyHippy/python-project-lvl2/maintainability) [![Linter](https://github.com/DirtyHippy/python-project-lvl2/workflows/linter/badge.svg)](https://github.com/DirtyHippy/python-project-lvl2/actions) [![Test Coverage](https://api.codeclimate.com/v1/badges/50b02185e2d65163855c/test_coverage)](https://codeclimate.com/github/DirtyHippy/python-project-lvl2/test_coverage) --- ## Installation Difference generator ```bash pip install git+https://github.com/DirtyHippy/python-project-lvl2.git ``` [![asciicast](https://asciinema.org/a/Ih7jeaHGhZVJt7SiVshnUvlSl.svg)](https://asciinema.org/a/Ih7jeaHGhZVJt7SiVshnUvlSl) ## Usage Difference generator ```bash gendiff -h ``` [![asciicast](https://asciinema.org/a/s6HmeNCm2nPRhEkHuKH32xVks.svg)](https://asciinema.org/a/s6HmeNCm2nPRhEkHuKH32xVks)<file_sep>[tool.poetry] name = "hexlet-code" version = "0.1.0" description = "gendiff" authors = ["dirty_hippy <<EMAIL>>"] repository = "https://github.com/DirtyHippy/python-project-lvl2.git" packages = [ { include = "gendiff" }, ] [tool.poetry.dependencies] python = "^3.8" PyYAML = "^5.4.1" [tool.poetry.dev-dependencies] flake8 = "^3.9.2" autopep8 = "^1.5.7" ipython = "^7.27.0" pytest = "^6.2.5" mypy = "^0.910" pytest-cov = "^2.12.1" types-PyYAML = "^5.4.10" [tool.poetry.scripts] gendiff = "gendiff.scripts.gendiff:main" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" <file_sep>import itertools from gendiff.comparator import REMOVED, UPDATED, ADDED, EQUAL, DICT from typing import Dict signs = { EQUAL: ' ', ADDED: '+ ', REMOVED: '- ', UPDATED: '- ' } indent = ' ' indent_sign = ' ' def format_dict(dict_value: dict, depth: int) -> str: lines = [] for key, value in dict_value.items(): lines.append(format_line(key, EQUAL, format_value(value, depth + 1), depth)) result = itertools.chain("{", lines, [indent * depth + "}"]) return '\n'.join(result) def format_line(key: str, diff_type: str, value, depth: int) -> str: return f"{indent * depth}{indent_sign}{signs[diff_type]}{key}: {value}" def format_value(value, depth: int): if isinstance(value, str): return f"{value}" elif value is True: return "true" elif value is False: return "false" elif value is None: return "null" elif isinstance(value, dict): return format_dict(value, depth) return value def to_stylish_format(difference: Dict[str, list], depth: int = 0) -> str: lines = [] for key in sorted(difference.keys()): diff_type, first_value, second_value = difference[key] if diff_type == DICT: lines.append(format_line(key, EQUAL, to_stylish_format(first_value, depth + 1), depth)) else: lines.append(format_line(key, diff_type, format_value(first_value, depth + 1), depth)) if diff_type == UPDATED: lines.append(format_line(key, ADDED, format_value(second_value, depth + 1), depth)) result = itertools.chain("{", lines, [indent * depth + "}"]) return '\n'.join(result) def format(difference: Dict[str, list]) -> str: return to_stylish_format(difference) <file_sep>import os from json import load from yaml import safe_load from gendiff.comparator import compare_dictionaries from gendiff.output import plain, stylish, json from typing import Dict STYLISH = 'stylish' PLAIN = 'plain' JSON = 'json' def load_file(file_path: str) -> dict: file_ext = os.path.splitext(file_path)[1].lower() with open(file_path, "r") as f: if file_ext == ".json": return load(f) elif file_ext == ".yml" or file_ext == ".yaml": return safe_load(f) else: raise Exception("wrong data format") def get_diff(difference: Dict[str, list], format: str) -> str: if format == PLAIN: return plain.format(difference) elif format == JSON: return json.format(difference) elif format == STYLISH: return stylish.format(difference) else: raise Exception("wrong format") def generate_diff(file_path1: str, file_path2: str, format=STYLISH) -> str: difference = compare_dictionaries(load_file(file_path1), load_file(file_path2)) return get_diff(difference, format) <file_sep>import json from typing import Dict def format(difference: Dict[str, list]) -> str: return json.dumps(difference) <file_sep>#!/usr/bin/env python import argparse from gendiff.generator import JSON, PLAIN, STYLISH, generate_diff def main(): parser = argparse.ArgumentParser(description='Generate diff') parser.add_argument('first_file', type=str) parser.add_argument('second_file', type=str) parser.add_argument('-f', '--format', choices=[STYLISH, PLAIN, JSON], default=STYLISH, help='set format of output') args = parser.parse_args() print(generate_diff(args.first_file, args.second_file, args.format)) if __name__ == '__main__': main() <file_sep>import os import pytest from gendiff.generator import PLAIN, STYLISH, generate_diff def get_fixture_path(file_name): current_dir = os.path.dirname(os.path.abspath(__file__)) return os.path.join(current_dir, 'fixtures/', file_name) def read(file_path): with open(file_path, 'r') as f: result = f.read() return result def simple_expected_value(test_path: str): return read(get_fixture_path(f'{test_path}simple_stylish.txt')) def nested_expected_value(test_path: str): return read(get_fixture_path(f'{test_path}nested_stylish.txt')) def nested_expected_value_plain_format(test_path: str): return read(get_fixture_path(f'{test_path}nested_plain.txt')) simple_json1 = 'simple1.json' simple_json2 = 'simple2.json' simple_yml1 = 'simple1.yml' simple_yml2 = 'simple2.yml' nested_json1 = 'nested1.json' nested_json2 = 'nested2.json' nested_yml1 = 'nested1.yaml' nested_yml2 = 'nested2.yaml' test1_path = 'test1/' test2_path = 'test2/' @ pytest.mark.parametrize("file1, file2, test_path, test_function, format", [ (simple_json1, simple_json2, test1_path, simple_expected_value, STYLISH), # noqa E501 (simple_yml1, simple_yml2, test1_path, simple_expected_value, STYLISH), # noqa E501 (nested_json1, nested_json2, test1_path, nested_expected_value, STYLISH), # noqa E501 (nested_yml1, nested_yml2, test1_path, nested_expected_value, STYLISH), # noqa E501 (nested_json1, nested_json2, test1_path, nested_expected_value_plain_format, PLAIN), # noqa E501 (nested_yml1, nested_yml2, test1_path, nested_expected_value_plain_format, PLAIN), # noqa E501 (nested_json1, nested_json2, test2_path, nested_expected_value, STYLISH), # noqa E501 (nested_yml1, nested_yml2, test2_path, nested_expected_value, STYLISH), # noqa E501 (nested_json1, nested_json2, test2_path, nested_expected_value_plain_format, PLAIN), # noqa E501 (nested_yml1, nested_yml2, test2_path, nested_expected_value_plain_format, PLAIN)]) # noqa E501 def test_generate_diff(file1, file2, test_path, test_function, format): assert test_function(test_path) == generate_diff(get_fixture_path(test_path + file1), get_fixture_path(test_path + file2), format) <file_sep>install: poetry install diff: poetry run gendiff build: poetry build publish: poetry publish --dry-run package-install: python3 -m pip install --user dist/*.whl lint: poetry run flake8 gendiff poetry run mypy gendiff test: poetry run pytest test-coverage: poetry run pytest --cov=gendiff --cov-report xml <file_sep>from gendiff.comparator import REMOVED, UPDATED, ADDED, EQUAL, DICT from typing import Dict templates = { ADDED: "Property '{}' was added with value: {}", REMOVED: "Property '{}' was removed", UPDATED: "Property '{}' was updated. From {} to {}" } def format_line(key: str, diff_type: str, first_value, second_value) -> str: if diff_type == ADDED: return templates[diff_type].format(key, format_value(first_value)) elif diff_type == REMOVED: return templates[diff_type].format(key) elif diff_type == UPDATED: return templates[diff_type].format(key, format_value(first_value), format_value(second_value)) raise Exception("wrong diff_type") def format_value(value): if isinstance(value, (dict, list)): return "[complex value]" elif isinstance(value, str): return f"'{value}'" elif value is True: return "true" elif value is False: return "false" elif value is None: return "null" return value def format(difference: Dict[str, list]) -> str: return to_plain_format(difference) def to_plain_format(difference: Dict[str, list], path: str = '') -> str: result = [] for key in sorted(difference.keys()): current_path = f'{path}.{key}' if path else key diff_type, first_value, second_value = difference[key] if diff_type == DICT: result.append(to_plain_format(first_value, current_path)) elif diff_type != EQUAL: result.append(format_line(current_path, diff_type, first_value, second_value)) return "\n".join(result)
87cb98201048a145e4350d2a84a8566b5caacb5c
[ "Markdown", "TOML", "Python", "Makefile" ]
10
Python
DirtyHippy/python-project-lvl2
91b9427231cd3fde4677e35cf16aa3de6bec8860
13c6273abbebdbbb387f407a9885f9e8eb064a83
refs/heads/master
<file_sep> using System; using System.Collections.Generic; using System.Reflection; using System.Text; using RimWorld; using Verse; using Harmony; namespace Psychology.Harmony { [HarmonyPatch(typeof(PawnObserver), "ObserveSurroundingThings")] public static class PawnObserver_ObserveSurroundingPatch { //Transpiler? [HarmonyPostfix] public static void DesensitizeViaCorpse(PawnObserver __instance) { Pawn pawn = Traverse.Create(__instance).Field("pawn").GetValue<Pawn>(); if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Sight)) { return; } RoomGroup roomGroup = pawn.GetRoomGroup(); Map map = pawn.Map; int num = 0; while ((float)num < 100f) { IntVec3 intVec = pawn.Position + GenRadial.RadialPattern[num]; if (intVec.InBounds(map)) { if (intVec.GetRoomGroup(map) == roomGroup) { if (GenSight.LineOfSight(intVec, pawn.Position, map, true, null, 0, 0)) { List<Thing> thingList = intVec.GetThingList(map); for (int i = 0; i < thingList.Count; i++) { IThoughtGiver thoughtGiver = thingList[i] as IThoughtGiver; if (thoughtGiver != null) { Thought_Memory thought_Memory = thoughtGiver.GiveObservedThought(); if (thought_Memory != null && thought_Memory.def == ThoughtDefOf.ObservedLayingCorpse) { if (!pawn.story.traits.HasTrait(TraitDefOfPsychology.BleedingHeart) && !pawn.story.traits.HasTrait(TraitDefOf.Psychopath) && !pawn.story.traits.HasTrait(TraitDefOf.Bloodlust) && !pawn.story.traits.HasTrait(TraitDefOfPsychology.Desensitized)) { if (((pawn.GetHashCode() ^ (GenLocalDate.DayOfYear(pawn) + GenLocalDate.Year(pawn) + (int)(GenLocalDate.DayPercent(pawn) * 5) * 60) * 391) % 1000) == 0) { pawn.story.traits.GainTrait(new Trait(TraitDefOfPsychology.Desensitized)); pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.RecentlyDesensitized, null); } } } } } } } } num++; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; namespace Psychology { public class MentalState_Histrionic : MentalState { public override RandomSocialMode SocialModeMax() { return RandomSocialMode.SuperActive; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Verse; using RimWorld; using Harmony; using System.Reflection.Emit; namespace Psychology.Harmony { [HarmonyPatch(typeof(ThoughtWorker_CabinFever), "CurrentStateInternal")] public static class ThoughtWorker_CabinFeverPatch { [HarmonyTranspiler] public static IEnumerable<CodeInstruction> OutdoorsyModifier(IEnumerable<CodeInstruction> instrs) { foreach (CodeInstruction itr in instrs) { yield return itr; float floatOperand; if(itr.opcode == OpCodes.Ldc_R4 && float.TryParse(""+itr.operand, out floatOperand) && floatOperand == 2.5f) { yield return new CodeInstruction(OpCodes.Ldarg_1); yield return new CodeInstruction(OpCodes.Ldc_R4, 1f); yield return new CodeInstruction(OpCodes.Ldc_R4, 0f); yield return new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(ThoughtWorker_CabinFeverPatch), "HasOutdoorsyTraitVal", new Type[] { typeof(Pawn), typeof(float), typeof(float) })); yield return new CodeInstruction(OpCodes.Sub); } else if (itr.opcode == OpCodes.Ldc_R4 && float.TryParse("" + itr.operand, out floatOperand) && floatOperand == 7.5f) { yield return new CodeInstruction(OpCodes.Ldarg_1); yield return new CodeInstruction(OpCodes.Ldc_R4, 2.5f); yield return new CodeInstruction(OpCodes.Ldc_R4, 0f); yield return new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(ThoughtWorker_CabinFeverPatch), "HasOutdoorsyTraitVal", new Type[] { typeof(Pawn), typeof(float), typeof(float) })); yield return new CodeInstruction(OpCodes.Sub); } } } public static float HasOutdoorsyTraitVal(Pawn pawn, float val1, float val2) { return (pawn.story.traits.HasTrait(TraitDefOfPsychology.Outdoorsy) ? val1 : val2); } } } <file_sep>using Verse; using Verse.AI; using RimWorld; namespace Psychology { public class ThoughtWorker_WorkingPassion : ThoughtWorker { protected override ThoughtState CurrentStateInternal(Pawn p) { if (!p.Spawned) return (ThoughtState)false; if (!p.RaceProps.Humanlike) return (ThoughtState)false; if (p.jobs == null) return (ThoughtState)false; if (p.jobs.curJob == null) return (ThoughtState)false; JobDef job = p.jobs.curJob.def; SkillDef skill = null; //WHY don't jobs have skills associated with them?! if (job == JobDefOf.Tame) skill = SkillDefOf.Animals; else if (job == JobDefOf.Shear) skill = SkillDefOf.Animals; else if (job == JobDefOf.Slaughter) skill = SkillDefOf.Animals; else if (job == JobDefOf.Milk) skill = SkillDefOf.Animals; else if (job == JobDefOf.Train) skill = SkillDefOf.Animals; else if (job == JobDefOf.BuildRoof) skill = SkillDefOf.Construction; else if (job == JobDefOf.Deconstruct) skill = SkillDefOf.Construction; else if (job == JobDefOf.FinishFrame) skill = SkillDefOf.Construction; else if (job == JobDefOf.FixBrokenDownBuilding) skill = SkillDefOf.Construction; else if (job == JobDefOf.Uninstall) skill = SkillDefOf.Construction; else if (job == JobDefOf.BuildRoof) skill = SkillDefOf.Construction; else if (job == JobDefOf.RemoveRoof) skill = SkillDefOf.Construction; else if (job == JobDefOf.SmoothFloor) skill = SkillDefOf.Construction; else if (job == JobDefOf.RemoveFloor) skill = SkillDefOf.Construction; else if (job == JobDefOf.Harvest) skill = SkillDefOf.Growing; else if (job == JobDefOf.Sow) skill = SkillDefOf.Growing; else if (job == JobDefOf.DeliverFood) skill = SkillDefOf.Medicine; else if (job == JobDefOf.FeedPatient) skill = SkillDefOf.Medicine; else if (job == JobDefOf.TakeToBedToOperate) skill = SkillDefOf.Medicine; else if (job == JobDefOf.TakeWoundedPrisonerToBed) skill = SkillDefOf.Medicine; else if (job == JobDefOf.TendPatient) skill = SkillDefOf.Medicine; else if (job == JobDefOf.VisitSickPawn) skill = SkillDefOf.Medicine; else if (job == JobDefOf.Rescue) skill = SkillDefOf.Medicine; else if (job == JobDefOf.AttackMelee) skill = SkillDefOf.Melee; else if (job == JobDefOf.Mine) skill = SkillDefOf.Mining; else if (job == JobDefOf.Research) skill = SkillDefOf.Intellectual; else if (job == JobDefOf.Hunt) skill = SkillDefOf.Shooting; else if (job == JobDefOf.AttackStatic) //no idea if this is right skill = SkillDefOf.Shooting; else if (job == JobDefOf.EscortPrisonerToBed) skill = SkillDefOf.Social; else if (job == JobDefOf.PrisonerAttemptRecruit) skill = SkillDefOf.Social; else if (job == JobDefOf.PrisonerExecution) skill = SkillDefOf.Social; else if (job == JobDefOf.PrisonerFriendlyChat) skill = SkillDefOf.Social; else if (job == JobDefOf.DeliverFood) skill = SkillDefOf.Social; else if (job == JobDefOf.DoBill) { LocalTargetInfo info = p.jobs.curJob.GetTarget(TargetIndex.A); if (info == null) return (ThoughtState)false; IBillGiver billGiver = info.Thing as IBillGiver; if (billGiver == null) return (ThoughtState)false; if (billGiver.BillStack == null) return (ThoughtState)false; if (billGiver.BillStack.FirstShouldDoNow == null) return (ThoughtState)false; if (billGiver.BillStack.FirstShouldDoNow.recipe == null) return (ThoughtState)false; skill = billGiver.BillStack.FirstShouldDoNow.recipe.workSkill; } if (skill == null) return (ThoughtState)false; if (p.skills.GetSkill(skill).passion != Passion.Major) return (ThoughtState)false; return (ThoughtState)true; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using Verse; using Verse.AI; using RimWorld; using UnityEngine; using Verse.Grammar; using System.Reflection; namespace Psychology { public class Hediff_Conversation : HediffWithComps { public override void PostMake() { base.PostMake(); this.realPawn = pawn as PsychologyPawn; if (this.realPawn == null) { this.pawn.health.RemoveHediff(this); } } public override void ExposeData() { base.ExposeData(); Scribe_References.Look(ref this.otherPawn, "otherPawn"); Scribe_Defs.Look(ref this.topic, "topic"); Scribe_Values.Look(ref this.waveGoodbye, "waveGoodbye"); } public override void Tick() { base.Tick(); if(this.realPawn == null) { this.realPawn = this.pawn as PsychologyPawn; } if (this.otherPawn == null) { this.pawn.health.RemoveHediff(this); return; } if (!this.otherPawn.Spawned || !this.pawn.Spawned || !InteractionUtility.CanReceiveInteraction(this.pawn) || !InteractionUtility.CanReceiveInteraction(this.otherPawn)) { this.pawn.health.RemoveHediff(this); return; } if ((this.pawn.Position - this.otherPawn.Position).LengthHorizontalSquared >= 54f || !GenSight.LineOfSight(this.pawn.Position, this.otherPawn.Position, this.pawn.Map, true)) { this.pawn.health.RemoveHediff(this); return; } if (this.otherPawn.Dead || this.otherPawn.Downed || this.otherPawn.InAggroMentalState) { this.pawn.health.RemoveHediff(this); return; } if (this.pawn.IsHashIntervalTick(200)) { if (Rand.Value > 1f - (this.ageTicks / 400000f)) { this.pawn.health.RemoveHediff(this); return; } else if (Rand.Value < 0.2f && this.pawn.Map != null) { MoteMaker.MakeInteractionBubble(this.pawn, otherPawn, InteractionDefOf.DeepTalk.interactionMote, InteractionDefOf.DeepTalk.Symbol); } } } public override void PostRemoved() { base.PostRemoved(); if (this.realPawn == null) { this.realPawn = this.pawn as PsychologyPawn; } if (this.realPawn != null && this.otherPawn != null) { Hediff otherConvo = otherPawn.health.hediffSet.hediffs.Find(h => h is Hediff_Conversation && ((Hediff_Conversation)h).otherPawn == this.realPawn); if(otherConvo != null) { this.otherPawn.health.RemoveHediff(otherConvo); } string talkDesc; if (this.ageTicks < 500) { int numShortTalks = int.Parse("NumberOfShortTalks".Translate()); talkDesc = "ShortTalk" + Rand.RangeInclusive(1, numShortTalks); } else if (this.ageTicks < 1500) { int numNormalTalks = int.Parse("NumberOfNormalTalks".Translate()); talkDesc = "NormalTalk" + Rand.RangeInclusive(1, numNormalTalks); } else if (this.ageTicks < 5000) { int numLongTalks = int.Parse("NumberOfLongTalks".Translate()); talkDesc = "LongTalk" + Rand.RangeInclusive(1, numLongTalks); } else { int numEpicTalks = int.Parse("NumberOfEpicTalks".Translate()); talkDesc = "EpicTalk" + Rand.RangeInclusive(1, numEpicTalks); } //We create a dynamic def to hold this thought so that the game won't worry about it being used anywhere else. ThoughtDef def = new ThoughtDef(); def.defName = this.pawn.GetHashCode() + "Conversation" + topic.defName; def.label = topic.defName; def.durationDays = 60f; def.nullifyingTraits = new List<TraitDef>(); def.nullifyingTraits.Add(TraitDefOf.Psychopath); def.thoughtClass = typeof(Thought_MemorySocialDynamic); ThoughtStage stage = new ThoughtStage(); //Base opinion mod is 5 to the power of controversiality. float opinionMod = Mathf.Pow(5f, topic.controversiality); //Multiplied by difference between their personality ratings, on an exponential scale. opinionMod *= Mathf.Lerp(-1.25f, 1.25f, Mathf.Pow(1f-Mathf.Abs(this.realPawn.psyche.GetPersonalityRating(topic) - this.otherPawn.psyche.GetPersonalityRating(topic)),3)); //Cool pawns are liked more. opinionMod += Mathf.Pow(2f, topic.controversiality) * (0.5f - this.otherPawn.psyche.GetPersonalityRating(PersonalityNodeDefOf.Cool)); //The length of the talk has a large impact on how much the pawn cares. opinionMod *= 5f * (this.ageTicks / (GenDate.TicksPerHour * 2.25f)); //talkModifier[talkLength] //If they had a bad experience, the more polite the pawn is, the less they're bothered by it. opinionMod *= (opinionMod < 0f ? 0.5f + (1f - this.otherPawn.psyche.GetPersonalityRating(PersonalityNodeDefOf.Polite)) : 1f); //The more judgmental the pawn, the more they're affected by all conversations. opinionMod *= 0.5f + this.realPawn.psyche.GetPersonalityRating(PersonalityNodeDefOf.Judgmental); if (opinionMod < 0f) { opinionMod *= PopulationModifier; } stage.label = "ConversationStage".Translate() + " " + topic.conversationTopic; stage.baseOpinionOffset = Mathf.RoundToInt(opinionMod); def.stages.Add(stage); /* The more they know about someone, the less likely small thoughts are to have an impact on their opinion. * This helps declutter the Social card without preventing pawns from having conversations. * They just won't change their mind about the colonist as a result. */ if (Rand.Value < Mathf.InverseLerp(0f, this.realPawn.psyche.TotalThoughtOpinion(this.otherPawn), 250f+Mathf.Abs(stage.baseOpinionOffset)) && stage.baseOpinionOffset != 0) { this.pawn.needs.mood.thoughts.memories.TryGainMemory(def, this.otherPawn); } if (this.waveGoodbye && this.pawn.Map != null) { InteractionDef endConversation = new InteractionDef(); endConversation.defName = "EndConversation"; RulePack goodbyeText = new RulePack(); FieldInfo RuleStrings = typeof(RulePack).GetField("rulesStrings", BindingFlags.Instance | BindingFlags.NonPublic); List<string> text = new List<string>(1); text.Add("logentry->" + talkDesc.Translate(topic.conversationTopic)); RuleStrings.SetValue(goodbyeText, text); endConversation.logRulesInitiator = goodbyeText; endConversation.logRulesRecipient = goodbyeText; FieldInfo Symbol = typeof(InteractionDef).GetField("symbol", BindingFlags.Instance | BindingFlags.NonPublic); Symbol.SetValue(endConversation, Symbol.GetValue(InteractionDefOf.DeepTalk)); PlayLogEntry_InteractionConversation log = new PlayLogEntry_InteractionConversation(endConversation, realPawn, this.otherPawn, new List<RulePackDef>()); Find.PlayLog.Add(log); MoteMaker.MakeInteractionBubble(this.pawn, this.otherPawn, InteractionDefOf.Chitchat.interactionMote, InteractionDefOf.Chitchat.Symbol); } } } public float PopulationModifier { get { if(this.pawn.IsColonist && this.pawn.Map != null) { return Mathf.Clamp01(this.pawn.Map.mapPawns.FreeColonistsCount / 8f); } else { return 1f; } } } public PsychologyPawn realPawn; public PsychologyPawn otherPawn; public PersonalityNodeDef topic; public bool waveGoodbye; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using RimWorld; using Verse; using Verse.Sound; using Harmony; using System.Reflection.Emit; namespace Psychology.Harmony.Optional { public static class PresetLoaderPatch { [HarmonyPostfix] public static void AddPsyche(ref EdB.PrepareCarefully.CustomPawn __result, EdB.PrepareCarefully.SaveRecordPawnV3 record) { if(SaveRecordPawnV3Patch.savedPawns.Keys.Contains(record)) { Pawn pawn = __result.Pawn; if (pawn != null && pawn is PsychologyPawn) { PrepareCarefully.SaveRecordPsycheV3 psycheSave = SaveRecordPawnV3Patch.savedPawns[record]; PsychologyPawn realPawn = pawn as PsychologyPawn; realPawn.psyche.upbringing = psycheSave.upbringing; foreach (PersonalityNode node in realPawn.psyche.PersonalityNodes) { PersonalityNode savedNode = psycheSave.nodes.Find(n => n.def == node.def); if(savedNode != null) { node.rawRating = savedNode.rawRating; } } if(PsychologyBase.ActivateKinsey()) { realPawn.sexuality.sexDrive = psycheSave.sexDrive; realPawn.sexuality.romanticDrive = psycheSave.romanticDrive; realPawn.sexuality.kinseyRating = psycheSave.kinseyRating; } } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using RimWorld; using Verse; using Verse.Sound; using Harmony; using System.Reflection.Emit; namespace Psychology.Harmony.Optional { public static class SaveRecordPawnV3Patch { [HarmonyPostfix] public static void ExposePsycheData(EdB.PrepareCarefully.SaveRecordPawnV3 __instance) { if(customPawns.Keys.Contains(__instance.id) && Scribe.mode == LoadSaveMode.Saving) { EdB.PrepareCarefully.CustomPawn pawn = customPawns[__instance.id] as EdB.PrepareCarefully.CustomPawn; if(pawn.Pawn is PsychologyPawn) { PrepareCarefully.SaveRecordPsycheV3 psycheSave = new PrepareCarefully.SaveRecordPsycheV3(pawn.Pawn); psycheSave.ExposeData(); } } else if (Scribe.mode == LoadSaveMode.LoadingVars) { PrepareCarefully.SaveRecordPsycheV3 psycheSave = new PrepareCarefully.SaveRecordPsycheV3(); psycheSave.ExposeData(); savedPawns.Add(__instance, psycheSave); } } public static Dictionary<object, PrepareCarefully.SaveRecordPsycheV3> savedPawns = new Dictionary<object, PrepareCarefully.SaveRecordPsycheV3>(); public static Dictionary<string, object> customPawns = new Dictionary<string, object>(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using RimWorld.Planet; using Verse; using Verse.AI.Group; namespace Psychology { public class Hediff_PlannedDate : Hediff { public override void ExposeData() { base.ExposeData(); Scribe_References.Look(ref this.partner, "partner"); Scribe_Values.Look(ref this.hour, "hour", 0); Scribe_Values.Look(ref this.day, "day", 0); } public override void Tick() { base.Tick(); if(!LovePartnerRelationUtility.LovePartnerRelationExists(this.pawn, this.partner)) { this.pawn.health.RemoveHediff(this); } else if(Find.TickManager.TicksGame >= this.day && GenLocalDate.HourOfDay(this.pawn) == this.hour) { if(this.pawn.GetTimeAssignment() != TimeAssignmentDefOf.Work && this.partner.GetTimeAssignment() != TimeAssignmentDefOf.Work && !this.pawn.Drafted && !this.partner.Drafted && PartyUtility.AcceptableGameConditionsToStartParty(this.pawn.Map) && this.pawn.Map == this.partner.Map) { pawn.jobs.StopAll(); if (pawn.Awake() && partner.Awake()) { LordMaker.MakeNewLord(this.pawn.Faction, new LordJob_Date(this.pawn, this.partner), this.pawn.Map, new Pawn[] { this.pawn, this.partner }); } else if(pawn.Awake()) { this.pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.MissedDate, this.partner); } else { this.partner.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.MissedDate, this.pawn); } } else { this.pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.DateCancelled); this.partner.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.DateCancelled); } this.pawn.health.RemoveHediff(this); } } public Pawn partner; public int hour; public int day; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; namespace Psychology { public class JobGiver_Compulsion : ThinkNode_JobGiver { protected override Job TryGiveJob(Pawn pawn) { if (!pawn.story.WorkTagIsDisabled(WorkTags.Cleaning) && pawn.Map.listerFilthInHomeArea.FilthInHomeArea.Count > 0) { Thing closestFilth = pawn.Map.listerFilthInHomeArea.FilthInHomeArea.RandomElement(); if (closestFilth != null && pawn.CanReserveAndReach(closestFilth, PathEndMode.Touch, Danger.Some)) { return new Job(JobDefOf.Clean, closestFilth); } } if (!pawn.story.WorkTagIsDisabled(WorkTags.Hauling) && pawn.Map.listerHaulables.ThingsPotentiallyNeedingHauling().Count > 0) { Thing thing = pawn.Map.listerHaulables.ThingsPotentiallyNeedingHauling().RandomElement(); if (thing != null && HaulAIUtility.PawnCanAutomaticallyHaulFast(pawn, thing, true) && pawn.CanReserveAndReach(thing, PathEndMode.Touch, Danger.Some)) { return HaulAIUtility.HaulToStorageJob(pawn, thing); } } return null; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; using Verse.AI.Group; using UnityEngine; namespace Psychology { public class LordToil_Election : LordToil { public LordToil_Election(IntVec3 spot) { this.spot = spot; } public override void UpdateAllDuties() { for (int i = 0; i < this.lord.ownedPawns.Count; i++) { this.lord.ownedPawns[i].mindState.duty = new PawnDuty(DutyDefOfPsychology.Vote, this.spot, -1f); } } public override ThinkTreeDutyHook VoluntaryJoinDutyHookFor(Pawn p) { return DutyDefOfPsychology.Vote.hook; } public override void Notify_ReachedDutyLocation(Pawn pawn) { LordJob_Joinable_Election election = pawn.GetLord().LordJob as LordJob_Joinable_Election; PsychologyPawn voter = pawn as PsychologyPawn; if(election != null && voter != null && !election.voters.Contains(pawn.GetHashCode())) { election.voters.Add(pawn.GetHashCode()); if(election.candidates.Find(c => c.pawn == voter) == null) { List<Pair<PsychologyPawn, float>> possibleVotes = new List<Pair<PsychologyPawn, float>>(); foreach (Candidate candidate in election.candidates) { float issueWeighting = 0f; candidate.nodes.ForEach(p => issueWeighting += Mathf.Pow((1f - Mathf.Abs(candidate.pawn.psyche.GetPersonalityRating(p) - voter.psyche.GetPersonalityRating(p))), 2) * Mathf.Pow(10, p.controversiality)); possibleVotes.Add(new Pair<PsychologyPawn, float>(candidate.pawn, issueWeighting+voter.relations.OpinionOf(candidate.pawn))); } IEnumerable<Pair<PsychologyPawn, float>> orderedPossibleVotes = (from v in possibleVotes orderby v.Second descending select v); if (Prefs.DevMode && Prefs.LogVerbose) { StringBuilder voteString = new StringBuilder("[Psychology] Vote weights for " + voter.LabelShort + ": "); foreach (Pair<PsychologyPawn, float> v in orderedPossibleVotes) { voteString.Append(v.First.LabelShort + " " + v.Second + " "); } Log.Message(voteString.ToString()); } election.votes.Add(orderedPossibleVotes.First().First.LabelShort); } else { election.votes.Add(voter.LabelShort); } } } private IntVec3 spot; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Harmony; namespace Psychology.Harmony { [HarmonyPatch(typeof(NegativeInteractionUtility), "NegativeInteractionChanceFactor")] public static class NegativeInteractionUtility_ChancePatch { [HarmonyPostfix] public static void NewFormula(ref float __result, Pawn initiator, Pawn recipient) { PsychologyPawn realInitiator = initiator as PsychologyPawn; if (realInitiator != null) { SimpleCurve opinionCurve = Traverse.Create(typeof(NegativeInteractionUtility)).Field("CompatibilityFactorCurve").GetValue<SimpleCurve>(); __result /= opinionCurve.Evaluate(initiator.relations.CompatibilityWith(recipient)); __result *= 2f * realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Aggressive); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; using Harmony; namespace Psychology.Harmony { [HarmonyPatch(typeof(PawnComponentsUtility), "CreateInitialComponents")] public static class PawnComponentsUtility_CreateInitialPatch { [HarmonyPostfix] public static void CreatePsychologyComponents(Pawn pawn) { if (pawn.RaceProps.Humanlike) { PsychologyPawn realPawn = pawn as PsychologyPawn; if (PsychologyBase.ActivateKinsey()) { if (realPawn != null) { realPawn.sexuality = new Pawn_SexualityTracker(realPawn); } } if (realPawn != null) { realPawn.psyche = new Pawn_PsycheTracker(realPawn); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Harmony; namespace Psychology.Harmony { [HarmonyPatch(typeof(InteractionWorker_DeepTalk), "RandomSelectionWeight")] public static class InteractionWorker_DeepTalk_SelectionWeightPatch { [HarmonyPrefix] public static bool PsychologyException(InteractionWorker_DeepTalk __instance, Pawn initiator, Pawn recipient) { return !(initiator is PsychologyPawn || recipient is PsychologyPawn); } } } <file_sep>using System; using System.Linq; using System.Collections.Generic; using RimWorld; using Verse; using Verse.AI; using Verse.AI.Group; using System.Reflection; namespace Psychology { public class JobGiver_SpendTimeTogether : JobGiver_GetJoy { protected override Job TryGiveJob(Pawn pawn) { LordToil_HangOut toil = pawn.GetLord().CurLordToil as LordToil_HangOut; Pawn friend = (pawn == toil.friends[0] ? toil.friends[1] : toil.friends[0]); if (pawn.needs.food.CurLevel < 0.33f) { return null; } if (friend.needs.food.CurLevel < 0.33f) { return null; } if(LovePartnerRelationUtility.LovePartnerRelationExists(pawn, friend) && pawn.jobs.curDriver != null && pawn.jobs.curDriver.layingDown == LayingDownState.NotLaying && (pawn.IsHashIntervalTick(GenDate.TicksPerHour) || friend.IsHashIntervalTick(GenDate.TicksPerHour))) { return new Job(JobDefOf.LayDown, pawn.ownership.OwnedBed); } if (toil.hangOut != null && toil.hangOut.GetTarget(TargetIndex.A) != null && !pawn.CanReserve(toil.hangOut.GetTarget(TargetIndex.A), toil.hangOut.def.joyMaxParticipants, 0, null)) { Log.Message("can't reserve the target of the hangout"); /* Try our best to figure out which JoyGiver was used for the unreservable job. */ int prefix = "JoyGiver".Count(); var def = ( from j in DefDatabase<JoyGiverDef>.AllDefs where j.jobDef == toil.hangOut.def || (j.jobDef == null && DefDatabase<JobDef>.GetNamedSilentFail(nameof(j.giverClass).Substring(prefix)) == toil.hangOut.def) select j ).FirstOrDefault(); if (def != null) { Log.Message("giving job of def " + def.defName); do { toil.hangOut = base.TryGiveJobFromJoyGiverDefDirect(def, pawn); } while (toil.hangOut.GetTarget(TargetIndex.A).Thing.GetRoom() != friend.GetRoom()); } else { toil.hangOut = null; } } if (toil.hangOut == null || toil.ticksToNextJoy < Find.TickManager.TicksGame) { toil.hangOut = base.TryGiveJob(pawn); toil.ticksToNextJoy = Find.TickManager.TicksGame + Rand.RangeInclusive(GenDate.TicksPerHour, GenDate.TicksPerHour * 3); } if(pawn.needs.joy.CurLevel < 0.8f) { return toil.hangOut; } Log.Message("no joy hangout available"); IntVec3 root = WanderUtility.BestCloseWanderRoot(toil.hangOut.targetA.Cell, pawn); Func<Pawn, IntVec3, bool> validator = delegate (Pawn wanderer, IntVec3 loc) { IntVec3 wanderRoot = root; Room room = wanderRoot.GetRoom(pawn.Map); return room == null || WanderUtility.InSameRoom(wanderRoot, loc, pawn.Map); }; pawn.mindState.nextMoveOrderIsWait = !pawn.mindState.nextMoveOrderIsWait; IntVec3 wanderDest = RCellFinder.RandomWanderDestFor(pawn, root, 5f, validator, PawnUtility.ResolveMaxDanger(pawn, Danger.Some)); if (!wanderDest.IsValid || pawn.mindState.nextMoveOrderIsWait) { if ((pawn.Position - friend.Position).LengthHorizontalSquared >= 42f && friend.jobs.curJob.def != JobDefOf.Goto) { Log.Message("friend not nearby, going to friend"); IntVec3 friendDest = RCellFinder.RandomWanderDestFor(pawn, friend.Position, 5f, validator, PawnUtility.ResolveMaxDanger(pawn, Danger.Some)); pawn.Map.pawnDestinationManager.ReserveDestinationFor(pawn, friendDest); return new Job(JobDefOf.Goto, friendDest); } Log.Message("waiting"); return null; } Log.Message("wandering"); pawn.Map.pawnDestinationManager.ReserveDestinationFor(pawn, wanderDest); return new Job(JobDefOf.GotoWander, wanderDest); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; using UnityEngine; namespace Psychology { public class MentalState_Paranoia : MentalState { public override RandomSocialMode SocialModeMax() { return RandomSocialMode.Off; } public override void MentalStateTick() { base.MentalStateTick(); if(pawn.IsHashIntervalTick(1000)) { string[] ramblings = { "You goddamned idiots! We're doomed!", "They're coming! They'll destroy us!", "This place is cursed!", "We're all going to die!", "Curse this place!", "Our old lives are gone. We are shadows of the dead!", "This miserable place will be our tomb!", "The sooner we die, the sooner the suffering ends!", "You fools! You are puppets on strings!", "Can't you see? We are mere playthings!", "They laugh at our torment! They cackle!", "Are you happy now? We are all going to die!", "You stand a stone's throw from oblivion!", "The worst is yet to come! We are not prepared!", "It's all hopeless! We're wasting our time!", "Why are we here? Just to suffer?", "Our minds are not our own!", "Your foolishness has doomed us all!", "Run, while you still can!", "This accursed hellhole will be our grave!", "We are mere pawns in the hands of fate!", "I'm wasting my time. You are all blind and deaf!", "It will never get better! We will never be saved!", "We have never been more alone and unwanted!", "We work, we sicken, we die, and for what?", "Any one of you could die at any moment!", "We are all better off dead!", "This is just a dream, we can still wake up!", "Every moment you draw breath prolongs the agony!", "If anyone was looking out for us, do you really think we would be in such dire straits?", "Consciousness is a festering wound!" }; if(Rand.Value < 0.75f) { Vector3 pos = pawn.DrawPos + pawn.Drawer.renderer.BaseHeadOffsetAt(pawn.Rotation); MoteMaker.ThrowText(pos, pawn.Map, ramblings.RandomElement(), Color.Lerp(Color.black, Color.red, 0.85f), 3.85f); foreach (Pawn p in pawn.Map.mapPawns.AllPawns) { if(p.RaceProps.Humanlike && p != pawn && (pawn.Position - p.Position).LengthHorizontalSquared <= 36f && GenSight.LineOfSight(pawn.Position, p.Position, pawn.Map, true)) { p.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.HeardParanoia); } } } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using UnityEngine; namespace Psychology { public static class RendezvousUtility { public static float ColonySizeFactor(Pawn pawn) { return Mathf.Clamp01(pawn.Map.mapPawns.FreeColonistsCount / 8f); } public static float TimeAssignmentFactor(Pawn pawn, int hour) { if(pawn.timetable.GetAssignment(hour) == TimeAssignmentDefOf.Joy) { return 1.25f; } if (pawn.timetable.GetAssignment(hour) == TimeAssignmentDefOf.Sleep) { return 0.9f; } if (pawn.timetable.GetAssignment(hour) == TimeAssignmentDefOf.Anything) { return 0.33f; } return 0f; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using RimWorld; using RimWorld.Planet; using Verse; using Verse.AI.Group; using Verse.Grammar; using HugsLib.Settings; using Harmony; using UnityEngine; namespace Psychology { public class PsychologyBase : HugsLib.ModBase { private static bool kinsey = true; private static KinseyMode mode = KinseyMode.Realistic; public static bool notBabyMode = true; public static bool elections = true; private SettingHandle<bool> toggleKinsey; private SettingHandle<bool> toggleEmpathy; private SettingHandle<KinseyMode> kinseyMode; private SettingHandle<bool> toggleIndividuality; private SettingHandle<bool> toggleElections; public enum KinseyMode { Realistic, Invisible, Gaypocalypse }; static public bool ActivateKinsey() { return kinsey; } static public KinseyMode KinseyFormula() { return mode; } static public bool IndividualityOn() { return notBabyMode; } static public bool ActivateElections() { return elections; } public override string ModIdentifier { get { return "Psychology"; } } private static void RemoveTrait(Pawn pawn, TraitDef trait) { pawn.story.traits.allTraits.RemoveAll(t => t.def == trait); } private static ThoughtDef AddNullifyingTraits(String name, TraitDef[] traits) { ThoughtDef thought = ThoughtDef.Named(name); if (thought != null) { if (thought.nullifyingTraits == null) { thought.nullifyingTraits = new List<TraitDef>(); } foreach (TraitDef conflict in traits) { thought.nullifyingTraits.Add(conflict); } } return thought; } private static ThoughtDef ModifyThoughtStages(ThoughtDef thought, int[] stages) { for (int stage = 0; stage < thought.stages.Count; stage++) { thought.stages[stage].baseMoodEffect = stages[stage]; } return thought; } public override void SettingsChanged() { kinsey = toggleKinsey.Value; mode = kinseyMode.Value; notBabyMode = toggleIndividuality.Value; elections = toggleElections.Value; } public override void DefsLoaded() { if (ModIsActive) { /* Mod settings */ toggleEmpathy = Settings.GetHandle<bool>("EnableEmpathy", "EmpathyChangesTitle".Translate(), "EmpathyChangesTooltip".Translate(), true); toggleKinsey = Settings.GetHandle<bool>("EnableSexuality", "SexualityChangesTitle".Translate(), "SexualityChangesTooltip".Translate(), true); kinseyMode = Settings.GetHandle<KinseyMode>("KinseyMode", "KinseyModeTitle".Translate(), "KinseyModeTooltip".Translate(), KinseyMode.Realistic, null, "KinseyMode_"); toggleIndividuality = Settings.GetHandle<bool>("EnableIndividuality", "IndividualityTitle".Translate(), "IndividualityTooltip".Translate(), true); toggleElections = Settings.GetHandle<bool>("EnableElections", "ElectionsTitle".Translate(), "ElectionsTooltip".Translate(), true); notBabyMode = toggleIndividuality.Value; elections = toggleElections.Value; if (PsychologyBase.ActivateKinsey()) { mode = kinseyMode.Value; } /* Mod conflict detection */ TraitDef bisexual = DefDatabase<TraitDef>.GetNamedSilentFail("Bisexual"); TraitDef asexual = DefDatabase<TraitDef>.GetNamedSilentFail("Asexual"); if (bisexual != null || asexual != null || !toggleKinsey) { if (toggleKinsey) { Logger.Message("KinseyDisable".Translate()); } kinsey = false; } /* Conditional vanilla Def edits */ ThoughtDef knowGuestExecuted = AddNullifyingTraits("KnowGuestExecuted", new TraitDef[] { TraitDefOfPsychology.BleedingHeart }); if (knowGuestExecuted != null && toggleEmpathy) { knowGuestExecuted = ModifyThoughtStages(knowGuestExecuted, new int[] { -1, -2, -4, -5 }); } ThoughtDef knowColonistExecuted = AddNullifyingTraits("KnowColonistExecuted", new TraitDef[] { TraitDefOfPsychology.BleedingHeart }); if (knowColonistExecuted != null && toggleEmpathy) { knowColonistExecuted = ModifyThoughtStages(knowColonistExecuted, new int[] { -1, -2, -4, -5 }); } ThoughtDef knowPrisonerDiedInnocent = AddNullifyingTraits("KnowPrisonerDiedInnocent", new TraitDef[] { TraitDefOfPsychology.BleedingHeart }); if (knowPrisonerDiedInnocent != null && toggleEmpathy) { knowPrisonerDiedInnocent = ModifyThoughtStages(knowPrisonerDiedInnocent, new int[] { -4 }); } ThoughtDef knowColonistDied = AddNullifyingTraits("KnowColonistDied", new TraitDef[] { TraitDefOfPsychology.BleedingHeart }); if (knowColonistDied != null && toggleEmpathy) { knowColonistDied = ModifyThoughtStages(knowColonistDied, new int[] { -2 }); } ThoughtDef colonistAbandoned = AddNullifyingTraits("ColonistAbandoned", new TraitDef[] { TraitDefOfPsychology.BleedingHeart }); if (colonistAbandoned != null && toggleEmpathy) { colonistAbandoned = ModifyThoughtStages(colonistAbandoned, new int[] { -2 }); } ThoughtDef colonistAbandonedToDie = AddNullifyingTraits("ColonistAbandonedToDie", new TraitDef[] { TraitDefOfPsychology.BleedingHeart }); if (colonistAbandonedToDie != null && toggleEmpathy) { colonistAbandonedToDie = ModifyThoughtStages(colonistAbandonedToDie, new int[] { -4 }); } ThoughtDef prisonerAbandonedToDie = AddNullifyingTraits("PrisonerAbandonedToDie", new TraitDef[] { TraitDefOfPsychology.BleedingHeart }); if (prisonerAbandonedToDie != null && toggleEmpathy) { prisonerAbandonedToDie = ModifyThoughtStages(prisonerAbandonedToDie, new int[] { -3 }); } ThoughtDef knowPrisonerSold = AddNullifyingTraits("KnowPrisonerSold", new TraitDef[] { TraitDefOfPsychology.BleedingHeart }); if (knowPrisonerSold != null && toggleEmpathy) { knowPrisonerSold = ModifyThoughtStages(knowPrisonerSold, new int[] { -4 }); } ThoughtDef knowGuestOrganHarvested = AddNullifyingTraits("KnowGuestOrganHarvested", new TraitDef[] { TraitDefOfPsychology.BleedingHeart }); if (knowGuestOrganHarvested != null && toggleEmpathy) { knowGuestOrganHarvested = ModifyThoughtStages(knowGuestOrganHarvested, new int[] { -4 }); } ThoughtDef knowColonistOrganHarvested = AddNullifyingTraits("KnowColonistOrganHarvested", new TraitDef[] { TraitDefOfPsychology.BleedingHeart }); if (knowColonistOrganHarvested != null && toggleEmpathy) { knowColonistOrganHarvested = ModifyThoughtStages(knowColonistOrganHarvested, new int[] { -4 }); } ThoughtDef beauty = AddNullifyingTraits("KnowColonistOrganHarvested", new TraitDef[] { TraitDefOfPsychology.BleedingHeart }); if (knowColonistOrganHarvested != null && toggleEmpathy) { knowColonistOrganHarvested = ModifyThoughtStages(knowColonistOrganHarvested, new int[] { -4 }); } IEnumerable<ThingDef> things = (from m in LoadedModManager.RunningMods from def in m.AllDefs.OfType<ThingDef>() where typeof(Pawn).IsAssignableFrom(def.thingClass) select def); foreach (ThingDef t in things) { if (t.race.intelligence == Intelligence.Humanlike && (DefDatabase<ThinkTreeDef>.GetNamedSilentFail("Zombie") == null || t.race.thinkTreeMain != DefDatabase<ThinkTreeDef>.GetNamedSilentFail("Zombie"))) { t.thingClass = typeof(PsychologyPawn); t.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Pawn_Psyche))); t.recipes.Add(RecipeDefOfPsychology.TreatPyromania); t.recipes.Add(RecipeDefOfPsychology.TreatChemicalInterest); t.recipes.Add(RecipeDefOfPsychology.TreatChemicalFascination); t.recipes.Add(RecipeDefOfPsychology.TreatDepression); if (!t.race?.hediffGiverSets?.NullOrEmpty() ?? false) { if (t.race.hediffGiverSets.Contains(DefDatabase<HediffGiverSetDef>.GetNamed("OrganicStandard"))) { t.race.hediffGiverSets.Add(DefDatabase<HediffGiverSetDef>.GetNamed("OrganicPsychology")); } } } } /* * Now to enjoy the benefits of having made a popular mod! * This will be our little secret. */ Backstory childMe = new Backstory(); childMe.bodyTypeMale = BodyType.Male; childMe.bodyTypeFemale = BodyType.Female; childMe.slot = BackstorySlot.Childhood; childMe.SetTitle("Child soldier"); childMe.SetTitleShort("Scout"); childMe.baseDesc = "NAME was born into a dictatorial outlander society on a nearby rimworld. Their chief export was war, and HE was conscripted at a young age into the military to serve as a scout due to HIS runner's build. HECAP learned how to use a gun, patch wounds on the battlefield, and communicate with HIS squad. It was there HE earned HIS nickname."; childMe.skillGains.Add("Shooting", 4); childMe.skillGains.Add("Medicine", 2); childMe.skillGains.Add("Social", 1); childMe.requiredWorkTags = WorkTags.Violent; childMe.shuffleable = false; childMe.PostLoad(); childMe.ResolveReferences(); //Disabled until I can be bothered to code it so they're actually siblings. /*Backstory adultMale = new Backstory(); adultMale.bodyTypeMale = BodyType.Male; adultMale.bodyTypeFemale = BodyType.Female; adultMale.slot = BackstorySlot.Adulthood; adultMale.SetTitle("Missing in action"); adultMale.SetTitleShort("P.O.W."); adultMale.baseDesc = "Eventually, HE was captured on a mission by one of his faction's many enemies. HECAP was tortured for information, the techniques of which HE never forgot. When they could get no more out of HIM, HE was sent to a prison camp, where HE worked for years before staging an escape and fleeing into civilization."; adultMale.skillGains.Add("Crafting", 4); adultMale.skillGains.Add("Construction", 3); adultMale.skillGains.Add("Mining", 2); adultMale.skillGains.Add("Social", 1); adultMale.spawnCategories = new List<string>(); adultMale.spawnCategories.AddRange(new string[] { "Civil", "Raider", "Slave", "Trader", "Traveler" }); adultMale.shuffleable = false; adultMale.PostLoad(); adultMale.ResolveReferences();*/ Backstory adultFemale = new Backstory(); adultFemale.bodyTypeMale = BodyType.Male; adultFemale.bodyTypeFemale = BodyType.Female; adultFemale.slot = BackstorySlot.Adulthood; adultFemale.SetTitle("Battlefield medic"); adultFemale.SetTitleShort("Medic"); adultFemale.baseDesc = "HECAP continued to serve in the military, being promoted through the ranks as HIS skill increased. HECAP learned how to treat more serious wounds as HIS role slowly transitioned from scout to medic, as well as how to make good use of army rations. HECAP built good rapport with HIS squad as a result."; adultFemale.skillGains.Add("Shooting", 4); adultFemale.skillGains.Add("Medicine", 3); adultFemale.skillGains.Add("Cooking", 2); adultFemale.skillGains.Add("Social", 1); adultFemale.spawnCategories = new List<string>(); adultFemale.spawnCategories.AddRange(new string[] { "Civil", "Raider", "Slave", "Trader", "Traveler" }); adultFemale.shuffleable = false; adultFemale.PostLoad(); adultFemale.ResolveReferences(); /*PawnBio maleMe = new PawnBio(); maleMe.childhood = childMe; maleMe.adulthood = adultMale; maleMe.gender = GenderPossibility.Male; maleMe.name = NameTriple.FromString("Nathan 'Jackal' Tarai"); maleMe.PostLoad(); SolidBioDatabase.allBios.Add(maleMe);*/ PawnBio femaleMe = new PawnBio(); femaleMe.childhood = childMe; femaleMe.adulthood = adultFemale; femaleMe.gender = GenderPossibility.Female; femaleMe.name = NameTriple.FromString("Elizabeth 'Eagle' Tarai"); femaleMe.PostLoad(); SolidBioDatabase.allBios.Add(femaleMe); BackstoryDatabase.AddBackstory(childMe); //BackstoryDatabase.AddBackstory(adultMale); BackstoryDatabase.AddBackstory(adultFemale); } } public override void MapLoaded(Map map) { if (ModIsActive && PsychologyBase.ActivateKinsey()) { /* Remove Gay trait from pawns if Kinsey scale is enabled */ IEnumerable<Pawn> gayPawns = (from p in map.mapPawns.AllPawns where p.RaceProps.Humanlike && p.story.traits.HasTrait(TraitDefOf.Gay) select p); foreach (Pawn pawn in gayPawns) { RemoveTrait(pawn, TraitDefOf.Gay); PsychologyPawn realPawn = pawn as PsychologyPawn; if (realPawn != null && realPawn.sexuality.kinseyRating < 5) { realPawn.sexuality.kinseyRating = Rand.RangeInclusive(5, 6); } } } } public override void Tick(int currentTick) { //Constituent tick if (currentTick % GenDate.TicksPerHour*2 == 0) { Map playerFactionMap = Find.WorldObjects.FactionBases.Find(b => b.Faction.IsPlayer).Map; IEnumerable<Pawn> constituents = (from p in playerFactionMap.mapPawns.FreeColonistsSpawned where !p.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && p.GetTimeAssignment() != TimeAssignmentDefOf.Work && p.Awake() select p); if(constituents.Count() > 0) { Pawn potentialConstituent = constituents.RandomElementByWeight(p => 0.0001f + Mathf.Pow(Mathf.Abs(0.7f - p.needs.mood.CurLevel), 2)); IEnumerable<Pawn> activeMayors = (from m in playerFactionMap.mapPawns.FreeColonistsSpawned where !m.Dead && m.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).worldTileElectedOn == potentialConstituent.Map.Tile && m.GetTimeAssignment() != TimeAssignmentDefOf.Work && m.GetTimeAssignment() != TimeAssignmentDefOf.Sleep && m.GetLord() == null && m.Awake() select m); if (potentialConstituent != null && activeMayors.Count() > 0) { Pawn mayor = activeMayors.RandomElement(); //There should only be one. PsychologyPawn psychologyConstituent = potentialConstituent as PsychologyPawn; IntVec3 gather = default(IntVec3); bool foundBed = false; if (mayor.ownership != null && mayor.ownership.OwnedBed != null) { gather = mayor.ownership.OwnedBed.Position; foundBed = true; } if ((psychologyConstituent == null || Rand.Value < (1f - psychologyConstituent.psyche.GetPersonalityRating(PersonalityNodeDefOf.Independent)) / 5f) && (foundBed || RCellFinder.TryFindPartySpot(mayor, out gather))) { List<Pawn> pawns = new List<Pawn>(); pawns.Add(mayor); pawns.Add(potentialConstituent); Lord meeting = LordMaker.MakeNewLord(mayor.Faction, new LordJob_VisitMayor(gather, potentialConstituent, mayor, (potentialConstituent.needs.mood.CurLevel < 0.4f)), mayor.Map, pawns); if (!foundBed) { mayor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.MayorNoBedroom); } } } } } //Election tick if (currentTick % (GenDate.TicksPerDay/4f) == 0) { foreach (FactionBase factionBase in Find.WorldObjects.FactionBases) { //If the base isn't owned or named by the player, no election can be held. if (!factionBase.Faction.IsPlayer || !factionBase.namedByPlayer) { continue; } //Self-explanatory. if (!PsychologyBase.ActivateElections()) { continue; } //If the base is not at least a year old, no election will be held. if ((Find.TickManager.TicksGame - factionBase.creationGameTicks) / GenDate.TicksPerYear < 1) { continue; } //A base must have at least 7 people in it to hold an election. if (factionBase.Map.mapPawns.FreeColonistsSpawnedCount < 7) { continue; } //If an election is already being held, don't start a new one. if (factionBase.Map.gameConditionManager.ConditionIsActive(GameConditionDefOfPsychology.Election) || factionBase.Map.lordManager.lords.Find(l => l.LordJob is LordJob_Joinable_Election) != null) { continue; } //Elections are held in the fall and during the day. if (GenLocalDate.Season(factionBase.Map) != Season.Fall || (GenLocalDate.HourOfDay(factionBase.Map) < 7 || GenLocalDate.HourOfDay(factionBase.Map) > 20)) { continue; } //If an election has already been completed this year, don't start a new one. IEnumerable<Pawn> activeMayors = (from m in factionBase.Map.mapPawns.FreeColonistsSpawned where !m.Dead && m.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).worldTileElectedOn == factionBase.Map.Tile && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).yearElected == GenLocalDate.Year(factionBase.Map.Tile) select m); if (activeMayors.Count() > 0) { continue; } //Try to space out the elections so they don't all proc at once. if (Rand.RangeInclusive(1, 15 - GenLocalDate.DayOfSeason(factionBase.Map.Tile)) > 1) { continue; } IncidentParms parms = new IncidentParms(); parms.target = factionBase.Map; parms.faction = factionBase.Faction; FiringIncident fi = new FiringIncident(IncidentDefOfPsychology.Election, null, parms); Find.Storyteller.TryFire(fi); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Harmony; using UnityEngine; using System.Reflection; namespace Psychology.Harmony { [HarmonyPatch(typeof(TraitSet), "GainTrait")] public static class TraitSet_GainTraitPatch { [HarmonyPrefix] public static bool KinseyException(ref TraitSet __instance, Trait trait) { Pawn pawn = Traverse.Create(__instance).Field("pawn").GetValue<Pawn>(); PsychologyPawn realPawn = pawn as PsychologyPawn; if (realPawn != null && PsychologyBase.ActivateKinsey() && trait.def == TraitDefOf.Gay) { return false; } if (realPawn != null && PsychologyBase.ActivateKinsey() && realPawn.sexuality.romanticDrive < 0.5f) { if (trait.def == TraitDefOfPsychology.Codependent) { return false; } } if (realPawn != null && PsychologyBase.ActivateKinsey() && realPawn.sexuality.sexDrive < 0.5f) { if (trait.def == TraitDefOfPsychology.Lecher) { return false; } } return true; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; using Harmony; using UnityEngine; namespace Psychology.Harmony { [HarmonyPatch(typeof(JobGiver_DoLovin), "TryGiveJob")] public static class JobGiver_DoLovin_JobPatch { [HarmonyPostfix] public static void CancelJob(ref Job __result, Pawn pawn) { Pawn partnerInMyBed = LovePartnerRelationUtility.GetPartnerInMyBed(pawn); PsychologyPawn realPawn = pawn as PsychologyPawn; PsychologyPawn realPartner = partnerInMyBed as PsychologyPawn; if (realPawn != null && realPartner != null && PsychologyBase.ActivateKinsey() && realPawn.sexuality != null && realPartner.sexuality != null) { float random = Rand.ValueSeeded((pawn.GetHashCode() ^ (GenLocalDate.DayOfYear(pawn) + GenLocalDate.Year(pawn) + (int)(GenLocalDate.DayPercent(pawn) * 2) * 60) * 391)); if (random > realPawn.sexuality.AdjustedSexDrive && random > realPartner.sexuality.AdjustedSexDrive) { __result = null; } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Harmony; using UnityEngine; using System.Reflection; namespace Psychology.Harmony { [HarmonyPatch(typeof(PawnGenerator), "GenerateTraits")] public static class PawnGenerator_GenerateTraitsPatch { [HarmonyPriority(Priority.First)] [HarmonyPrefix] public static bool KinseyException(ref Pawn pawn, PawnGenerationRequest request) { PsychologyPawn newPawn = pawn as PsychologyPawn; if (newPawn != null) { newPawn.psyche.Initialize(); if (PsychologyBase.ActivateKinsey()) { while (newPawn.sexuality.kinseyRating > 2 && !request.AllowGay) { newPawn.sexuality.GenerateSexuality(); } if (LovePartnerRelationUtility.HasAnyLovePartnerOfTheSameGender(pawn) || LovePartnerRelationUtility.HasAnyExLovePartnerOfTheSameGender(pawn)) { while (newPawn.sexuality.kinseyRating < 2) { newPawn.sexuality.GenerateSexuality(); } } else if (LovePartnerRelationUtility.HasAnyLovePartnerOfTheOppositeGender(pawn) || LovePartnerRelationUtility.HasAnyExLovePartnerOfTheOppositeGender(pawn)) { while (newPawn.sexuality.kinseyRating > 4) { newPawn.sexuality.GenerateSexuality(); } } pawn = newPawn; } } return true; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using UnityEngine; namespace Psychology { public class InteractionWorker_Conversation : InteractionWorker { public override float RandomSelectionWeight(Pawn initiator, Pawn recipient) { PsychologyPawn realRecipient = recipient as PsychologyPawn; PsychologyPawn realInitiator = initiator as PsychologyPawn; if (realRecipient == null || realInitiator == null) { return 0f; } return Mathf.Max(0f, 0.45f + (realRecipient.psyche.GetPersonalityRating(PersonalityNodeDefOf.Friendly)-0.6f) + (realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Extroverted)-0.5f)); } public override void Interacted(Pawn initiator, Pawn recipient, List<RulePackDef> extraSentencePacks) { PsychologyPawn realInitiator = initiator as PsychologyPawn; PsychologyPawn realRecipient = recipient as PsychologyPawn; PersonalityNode topic = (from node in realInitiator.psyche.PersonalityNodes where !node.Core select node).RandomElementByWeight(node => realInitiator.psyche.GetConversationTopicWeight(node.def, realRecipient)); Hediff_Conversation initiatorHediff = (Hediff_Conversation)HediffMaker.MakeHediff(HediffDefOfPsychology.HoldingConversation, realInitiator); initiatorHediff.otherPawn = realRecipient; initiatorHediff.topic = topic.def; initiatorHediff.waveGoodbye = true; realInitiator.health.AddHediff(initiatorHediff); Hediff_Conversation recipientHediff = (Hediff_Conversation)HediffMaker.MakeHediff(HediffDefOfPsychology.HoldingConversation, realRecipient); recipientHediff.otherPawn = realInitiator; recipientHediff.topic = topic.def; recipientHediff.waveGoodbye = false; realRecipient.health.AddHediff(recipientHediff); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Harmony; namespace Psychology.Harmony { [HarmonyPatch(typeof(InteractionUtility), "CanReceiveRandomInteraction")] public static class InteractionUtility_CanReceive_Patch { [HarmonyPostfix] public static void PsychologyAddonsForCanReceive(ref bool __result, Pawn p) { __result = __result && !p.health.hediffSet.HasHediff(HediffDefOfPsychology.HoldingConversation) && (p.Map.lordManager.lords.Find(l => l.LordJob is LordJob_VisitMayor) == null || !p.Map.lordManager.lords.Find(l => l.LordJob is LordJob_VisitMayor).ownedPawns.Contains(p)); } } [HarmonyPatch(typeof(InteractionUtility), "CanInitiateRandomInteraction", new[] { typeof(Pawn) })] public static class InteractionUtility_CanInitiate_Patch { [HarmonyPostfix] public static void PsychologyAddonsForCanInitiate(ref bool __result, Pawn p) { __result = __result && !p.health.hediffSet.HasHediff(HediffDefOfPsychology.HoldingConversation) && (p.Map.lordManager.lords.Find(l => l.LordJob is LordJob_VisitMayor) == null || !p.Map.lordManager.lords.Find(l => l.LordJob is LordJob_VisitMayor).ownedPawns.Contains(p)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; namespace Psychology { public class JobGiver_MakeAdvance : ThinkNode_JobGiver { protected override Job TryGiveJob(Pawn pawn) { if(pawn.interactions.InteractedTooRecentlyToInteract() || lastRomanceTick > Find.TickManager.TicksGame - 1000) { return null; } Predicate<Thing> validator = delegate (Thing t) { Pawn pawn3 = (Pawn)t; return pawn3 != pawn && pawn3.Spawned && !pawn3.Dead && !pawn3.Downed && pawn3.Awake() && pawn3.IsColonist; }; Pawn pawn2 = (Pawn)GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.Pawn), PathEndMode.OnCell, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator); if (pawn2 == null) { return null; } if(Rand.Value > 0.005f && new InteractionWorker_RomanceAttempt().SuccessChance(pawn2, pawn) > 0f) { return new Job(JobDefOfPsychology.MakeAdvance, pawn2); } else if(Rand.Value < 0.5f) { return new Job(JobDefOf.Goto, pawn2); } return null; } int lastRomanceTick = -9999; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI.Group; using UnityEngine; namespace Psychology { public class InteractionWorker_HangOut : InteractionWorker { public override float RandomSelectionWeight(Pawn initiator, Pawn recipient) { if(initiator.guest.IsPrisoner || recipient.guest.IsPrisoner) { return 0f; } PsychologyPawn realRecipient = recipient as PsychologyPawn; PsychologyPawn realInitiator = initiator as PsychologyPawn; if (realRecipient == null || realInitiator == null) { return 0f; } if (initiator.GetLord() != null || recipient.GetLord() != null) { return 0f; } if (initiator.Drafted || recipient.Drafted) { return 0f; } if (!PartyUtility.AcceptableGameConditionsToStartParty(initiator.Map)) { return 0f; } if (initiator.health.summaryHealth.SummaryHealthPercent < 1f || recipient.health.summaryHealth.SummaryHealthPercent < 1f) { return 0f; } if (initiator.Faction != recipient.Faction) { return 0f; } float initiatorFactor = 0f; float recipientFactor = 0f; if (initiator.relations.OpinionOf(recipient) > -20) { initiatorFactor = realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Extroverted) + 0.15f + Mathf.InverseLerp(0f, 100f, initiator.relations.OpinionOf(recipient)); recipientFactor = realRecipient.psyche.GetPersonalityRating(PersonalityNodeDefOf.Friendly); } else if(initiator.relations.OpinionOf(recipient) <= -20) { initiatorFactor = Mathf.InverseLerp(0f, 0.4f, realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Empathetic)-0.6f); recipientFactor = realRecipient.psyche.GetPersonalityRating(PersonalityNodeDefOf.Trusting); } float scheduleFactor = 0f; if (initiator.GetTimeAssignment() == TimeAssignmentDefOf.Anything) { scheduleFactor = 0.33f; } else if (initiator.GetTimeAssignment() == TimeAssignmentDefOf.Joy) { scheduleFactor = 1f; } if (initiator.mindState.IsIdle && recipient.mindState.IsIdle && initiator.GetTimeAssignment() != TimeAssignmentDefOf.Work && recipient.GetTimeAssignment() != TimeAssignmentDefOf.Work) { scheduleFactor = 5f; } return 0.05f * initiatorFactor * recipientFactor * scheduleFactor * RendezvousUtility.ColonySizeFactor(initiator); } public override void Interacted(Pawn initiator, Pawn recipient, List<RulePackDef> extraSentencePacks) { initiator.jobs.StopAll(); recipient.jobs.StopAll(); Lord meeting = LordMaker.MakeNewLord(initiator.Faction, new LordJob_HangOut(initiator, recipient), initiator.Map, new Pawn[] { initiator, recipient }); } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Harmony; using System.Reflection; using System.Reflection.Emit; using UnityEngine; namespace Psychology.Harmony { [HarmonyPatch(typeof(InspectPaneUtility), "DoTabs")] public static class InspectPaneUtility_ITabPatch { [HarmonyTranspiler] public static IEnumerable<CodeInstruction> FixTabs(IEnumerable<CodeInstruction> instr, ILGenerator generator) { var myLabel = generator.DefineLabel(); int found = 0; int skipTwo = 0; foreach(CodeInstruction instruct in instr) { yield return instruct; int intOperand; if (instruct.opcode == OpCodes.Ldc_R4 && int.TryParse("" +instruct.operand, out intOperand)) { if (intOperand == 72) { found += 1; } } else if(found == 2) { skipTwo += 1; if(skipTwo == 2) { yield return new CodeInstruction(OpCodes.Ldloc_1); //ldloc.1 (num) yield return new CodeInstruction(OpCodes.Ldc_R4, 0.0); //ldc.r4 0 (num < 0) yield return new CodeInstruction(OpCodes.Bge_Un_S, myLabel); //bge (to nop) yield return new CodeInstruction(OpCodes.Ldc_R4, 360f); //ldc.r4 360 yield return new CodeInstruction(OpCodes.Stloc_1); //stloc.1 (num = 360) yield return new CodeInstruction(OpCodes.Ldloc_0); //ldloc.0 (y) yield return new CodeInstruction(OpCodes.Ldc_R4, 30f); //ldc.r4 30 yield return new CodeInstruction(OpCodes.Sub); //sub (y -= 30) yield return new CodeInstruction(OpCodes.Stloc_0); //stloc.0 (y) yield return new CodeInstruction(OpCodes.Nop) { labels = { myLabel } }; //nop } } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; using UnityEngine; namespace Psychology { public class JobGiver_Tantrum : ThinkNode_JobGiver { protected override Job TryGiveJob(Pawn pawn) { if (lastTickTantrumed > Find.TickManager.TicksGame - 2000 || Rand.Value < 0.5f) { return null; } Predicate<Thing> validator = delegate (Thing t) { return !t.IsBurning() && t.def.useHitPoints; }; Building building = (Building)GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.BuildingArtificial), PathEndMode.Touch, TraverseParms.For(TraverseMode.ByPawn, Danger.Deadly, true), 9999f, validator); if (building != null) { lastTickTantrumed = Find.TickManager.TicksGame; int maxNumMeleeAttacks = Rand.RangeInclusive(10, 30) + (Rand.Value < 0.1f ? Rand.RangeInclusive(10,30) : 0); pawn.guilt.Notify_Guilty(); return new Job(JobDefOf.AttackMelee, building) { maxNumMeleeAttacks = maxNumMeleeAttacks, expiryInterval = 50000, canBash = true }; } return null; } private int lastTickTantrumed = -9999; } } <file_sep>using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using UnityEngine; using Verse; using RimWorld; using Harmony; namespace Psychology.Harmony { [HarmonyPatch(typeof(ChildRelationUtility), "ChanceOfBecomingChildOf")] public static class ChildRelationUtility_ChanceOfBecomingChildOf_Patch { [HarmonyPostfix] public static void KinseyFactor(ref float __result, Pawn father, Pawn mother, Pawn child) { /* Kinsey-enabled pawns shouldn't have the Gay trait, so we can just apply the sexuality modifier here. */ if (father != null && child != null && child.GetFather() == null) { PsychologyPawn realFather = father as PsychologyPawn; if (PsychologyBase.ActivateKinsey() && realFather != null) { __result *= Mathf.InverseLerp(6f, 0f, realFather.sexuality.kinseyRating); } } if (mother != null && child != null && child.GetMother() == null) { PsychologyPawn realMother = mother as PsychologyPawn; if (PsychologyBase.ActivateKinsey() && realMother != null) { __result *= Mathf.InverseLerp(6f, 0f, realMother.sexuality.kinseyRating); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; using Harmony; namespace Psychology.Harmony { [HarmonyPatch(typeof(MentalBreaker), "TryDoRandomMoodCausedMentalBreak")] public static class MentalBreaker_AnxietyPatch { [HarmonyPostfix] public static void AddAnxiety(MentalBreaker __instance, ref bool __result) { if (__result) { Pawn pawn = Traverse.Create(__instance).Field("pawn").GetValue<Pawn>(); int intensity; int.TryParse("" + (byte)Traverse.Create(__instance).Property("CurrentDesiredMoodBreakIntensity").GetValue<MentalBreakIntensity>(), out intensity); Hediff hediff = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Anxiety); float PTSDChance = (0.25f - (0.075f * intensity)); if (pawn is PsychologyPawn) { //Laid-back pawns are less likely to get anxiety from mental breaks. PTSDChance -= (pawn as PsychologyPawn).psyche.GetPersonalityRating(PersonalityNodeDefOf.LaidBack) / 10f; } if (hediff != null) { hediff.Severity += 0.15f - (intensity * 0.5f); } else if (Rand.Value <= PTSDChance) { Hediff newHediff = HediffMaker.MakeHediff(HediffDefOfPsychology.Anxiety, pawn, pawn.health.hediffSet.GetBrain()); newHediff.Severity = 0.75f - (intensity * 0.25f); pawn.health.AddHediff(newHediff, null, null); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using RimWorld.Planet; using Verse; namespace Psychology { public class Hediff_Mayor : Hediff { public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref this.yearElected, "yearElected", 0); Scribe_Values.Look(ref this.worldTileElectedOn, "worldTileElectedOn", 0); } public override void PostMake() { base.PostMake(); this.yearElected = GenLocalDate.Year(this.pawn.Map.Tile); this.worldTileElectedOn = this.pawn.Map.Tile; } public override void Tick() { base.Tick(); FactionBase colony = Find.WorldObjects.ObjectsAt(worldTileElectedOn).OfType<FactionBase>().FirstOrDefault(); if (this.pawn.Dead || !PsychologyBase.ActivateElections() || colony == null || colony.Map.lordManager.lords.Find(l => l.LordJob is LordJob_Joinable_Election) != null) { this.pawn.health.RemoveHediff(this); } } public int yearElected; public int worldTileElectedOn; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using RimWorld; using Verse; using Verse.Sound; using Harmony; namespace Psychology.Harmony.Optional { public static class PanelBackstoryPatch { [HarmonyPostfix] public static void AddPsycheEditButton(EdB.PrepareCarefully.PanelBackstory __instance, EdB.PrepareCarefully.State state) { Rect panelRect = __instance.PanelRect; PsychologyPawn pawn = state.CurrentPawn.Pawn as PsychologyPawn; if (pawn != null) { if (pawn.psyche == null || pawn.psyche.PersonalityNodes == null) { pawn.psyche = new Pawn_PsycheTracker(pawn); pawn.psyche.Initialize(); foreach (PersonalityNode node in pawn.psyche.PersonalityNodes) { if (node.rawRating < 0) { node.Initialize(); } } } if (pawn.sexuality == null && PsychologyBase.ActivateKinsey()) { pawn.sexuality = new Pawn_SexualityTracker(pawn); pawn.sexuality.GenerateSexuality(); } Rect rect = new Rect(panelRect.width - 60f, 9f, 22f, 22f); if (rect.Contains(Event.current.mousePosition)) { GUI.color = new Color(0.97647f, 0.97647f, 0.97647f); } else { GUI.color = new Color(0.623529f, 0.623529f, 0.623529f); } GUI.DrawTexture(rect, ContentFinder<Texture2D>.Get("Buttons/ButtonPsyche", true)); if (Widgets.ButtonInvisible(rect, false)) { SoundDefOf.TickLow.PlayOneShotOnCamera(null); Find.WindowStack.Add(new Dialog_EditPsyche(pawn)); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; namespace Psychology { public class JobGiver_Sadism : ThinkNode_JobGiver { protected override Job TryGiveJob(Pawn pawn) { Predicate<Thing> validator = delegate (Thing t) { Pawn pawn3 = (Pawn)t; return !pawn3.Dead && !pawn3.Downed && (pawn3.IsPrisoner || pawn3.RaceProps.Animal); }; Pawn pawn2 = (Pawn)GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, ThingRequest.ForGroup(ThingRequestGroup.Pawn), PathEndMode.OnCell, TraverseParms.For(pawn, Danger.Deadly, TraverseMode.ByPawn, false), 9999f, validator); if (pawn2 == null || Rand.Value > 0.5f || pawn.mindState.MeleeThreatStillThreat) { return null; } return new Job(JobDefOf.AttackMelee, pawn2) { maxNumMeleeAttacks = 25, expiryInterval = 50000, killIncappedTarget = false, canBash = true }; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using RimWorld; using Verse; namespace Psychology.PrepareCarefully { public class SaveRecordPsycheV3 : IExposable { public List<PersonalityNode> nodes = new List<PersonalityNode>(); public int upbringing; public float sexDrive = 1f; public float romanticDrive = 1f; public int kinseyRating = 0; public SaveRecordPsycheV3() { } public SaveRecordPsycheV3(Pawn pawn) { PsychologyPawn realPawn = pawn as PsychologyPawn; if(realPawn != null) { nodes = realPawn.psyche.PersonalityNodes; upbringing = realPawn.psyche.upbringing; if(PsychologyBase.ActivateKinsey()) { sexDrive = realPawn.sexuality.sexDrive; romanticDrive = realPawn.sexuality.romanticDrive; kinseyRating = realPawn.sexuality.kinseyRating; } } } public void ExposeData() { if (Scribe.mode == LoadSaveMode.Saving || Scribe.loader.curXmlParent["personality"] != null) { Scribe_Collections.Look(ref nodes, "personality", LookMode.Deep, null); } Scribe_Values.Look(ref upbringing, "upbringing"); if(PsychologyBase.ActivateKinsey()) { if (Scribe.mode == LoadSaveMode.Saving || Scribe.loader.curXmlParent["sexDrive"] != null) { Scribe_Values.Look(ref sexDrive, "sexDrive"); } if (Scribe.mode == LoadSaveMode.Saving || Scribe.loader.curXmlParent["romanticDrive"] != null) { Scribe_Values.Look(ref romanticDrive, "romanticDrive"); } if (Scribe.mode == LoadSaveMode.Saving || Scribe.loader.curXmlParent["kinseyRating"] != null) { Scribe_Values.Look(ref kinseyRating, "kinseyRating"); } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; using Harmony; using UnityEngine; namespace Psychology { public class Pawn_PsycheTracker : IExposable { public Pawn_PsycheTracker(PsychologyPawn pawn) { this.pawn = pawn; } public void Initialize() { this.upbringing = Mathf.RoundToInt(Rand.ValueSeeded(this.pawn.HashOffset()) * (PersonalityCategories-1))+1; this.nodes = new List<PersonalityNode>(); foreach(PersonalityNodeDef def in DefDatabase<PersonalityNodeDef>.AllDefsListForReading) { nodes.Add(PersonalityNodeMaker.MakeNode(def, this.pawn)); } } public void ExposeData() { Scribe_Values.Look(ref this.upbringing, "upbringing", 0, false); Scribe_Values.Look(ref this.lastDateTick, "lastDateTick", 0, false); Scribe_Collections.Look(ref this.nodes, "nodes", LookMode.Deep, new object[] { this.pawn }); } public float GetPersonalityRating(PersonalityNodeDef def) { return nodes.Find((PersonalityNode n) => n.def == def).AdjustedRating; } public PersonalityNode GetPersonalityNodeOfDef(PersonalityNodeDef def) { return nodes.Find((PersonalityNode n) => n.def == def); } public float GetConversationTopicWeight(PersonalityNodeDef def, PsychologyPawn otherPawn) { /* Pawns will avoid controversial topics until they know someone better. * This isn't a perfect system, but the weights will be closer together the higher totalOpinionModifiers is. */ float weight = 10f/(Mathf.Lerp(1f+(8*def.controversiality), 1f + (def.controversiality/2), Mathf.Clamp01(this.TotalThoughtOpinion(otherPawn)/75) + this.GetPersonalityRating(PersonalityNodeDefOf.Aggressive))); /* Polite pawns will avoid topics they already know are contentious. */ float knownDisagreements = 0f; IEnumerable<Thought_MemorySocialDynamic> allConvos = (from m in this.pawn.needs.mood.thoughts.memories.Memories.OfType<Thought_MemorySocialDynamic>() where m.def.defName.Contains("Conversation") select m); foreach (Thought_MemorySocialDynamic memory in allConvos) { if(memory.CurStage.label == def.defName && memory.opinionOffset < 0f) { knownDisagreements += Mathf.Abs(memory.opinionOffset); } } weight *= Mathf.Clamp01(1f / (knownDisagreements / 50)) * Mathf.Lerp(0.25f, 1f, this.GetPersonalityRating(PersonalityNodeDefOf.Polite)); return weight; } public float TotalThoughtOpinion(PsychologyPawn other) { float knownThoughtOpinion = 1f; IEnumerable<Thought_Memory> convos = (from m in this.pawn.needs.mood.thoughts.memories.Memories where m.def.defName.Contains("Conversation") && m.otherPawn.ThingID == other.ThingID select m); foreach(Thought_Memory m in convos) { knownThoughtOpinion += Mathf.Abs(m.CurStage.baseOpinionOffset); } return knownThoughtOpinion; } public List<PersonalityNode> PersonalityNodes { get { return nodes; } set { nodes = value; } } public int upbringing; public int lastDateTick = 0; private PsychologyPawn pawn; private List<PersonalityNode> nodes; public const int PersonalityCategories = 16; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; using UnityEngine; namespace Psychology { public class MentalState_Tantrum : MentalState { private void BruiseFist(Pawn pawn) { IEnumerable<BodyPartRecord> hands = (from b in pawn.health.hediffSet.GetNotMissingParts() where b.def == BodyPartDefOf.LeftHand || b.def == BodyPartDefOf.RightHand select b); if (hands.Count() > 0) { BodyPartRecord hand = hands.RandomElement(); int num = Mathf.Max(3, GenMath.RoundRandom(pawn.health.hediffSet.GetPartHealth(hand) * Rand.Range(0.1f, 0.25f))); DamageInfo info = new DamageInfo(DamageDefOf.Blunt, num, -1, null, hand, null); pawn.TakeDamage(info); } } public override RandomSocialMode SocialModeMax() { return 0; } public override void MentalStateTick() { base.MentalStateTick(); if(pawn.jobs != null && pawn.jobs.curJob.def == JobDefOf.AttackMelee && pawn.Position.AdjacentTo8Way(pawn.jobs.curJob.targetA.Thing.Position) && pawn.IsHashIntervalTick(200) && Rand.Value < 0.1f) { BruiseFist(pawn); pawn.jobs.EndCurrentJob(JobCondition.InterruptForced); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Harmony; using UnityEngine; using System.Reflection; using System.Reflection.Emit; namespace Psychology.Harmony { [HarmonyPatch(typeof(Page_ConfigureStartingPawns), "DoWindowContents")] public static class Page_ConfigureStartingPawns_WindowPatch { [HarmonyTranspiler] public static IEnumerable<CodeInstruction> AddPsycheDisplay(IEnumerable<CodeInstruction> instr, ILGenerator gen) { LocalBuilder rect8 = gen.DeclareLocal(typeof(Rect)); rect8.SetLocalSymInfo("rect8"); foreach(CodeInstruction itr in instr) { int intOperand; if (itr.opcode == OpCodes.Ldc_R4 && int.TryParse("" + itr.operand, out intOperand) && intOperand == 200) { itr.operand = 150f; } yield return itr; if(itr.opcode == OpCodes.Call && itr.operand == typeof(SocialCardUtility).GetMethod("DrawRelationsAndOpinions")) { yield return new CodeInstruction(OpCodes.Ldloca_S, rect8); yield return new CodeInstruction(OpCodes.Ldloca_S, 6); yield return new CodeInstruction(OpCodes.Call, AccessTools.Property(typeof(Rect),"x").GetGetMethod()); yield return new CodeInstruction(OpCodes.Ldloca_S, 6); yield return new CodeInstruction(OpCodes.Call, AccessTools.Property(typeof(Rect), "yMax").GetGetMethod()); yield return new CodeInstruction(OpCodes.Ldloca_S, 6); yield return new CodeInstruction(OpCodes.Call, AccessTools.Property(typeof(Rect), "width").GetGetMethod()); yield return new CodeInstruction(OpCodes.Ldc_R4, 180f); yield return new CodeInstruction(OpCodes.Call, AccessTools.Constructor(typeof(Rect), new Type[] { typeof(float), typeof(float), typeof(float), typeof(float) })); //Rect rect8 = new Rect(rect6.x, rect6.yMax, rect6.width, 200); yield return new CodeInstruction(OpCodes.Ldc_I4_2); yield return new CodeInstruction(OpCodes.Call, AccessTools.Property(typeof(Text), "Font").GetSetMethod()); //Text.Font = GameFont.Medium; yield return new CodeInstruction(OpCodes.Ldloc_S, rect8); yield return new CodeInstruction(OpCodes.Ldstr, "TabPsyche"); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Translator), "Translate", new Type[] { typeof(string) })); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Widgets), "Label", new Type[] { typeof(Rect), typeof(string) })); //Widgets.Label(rect8, "Psyche".Translate()); yield return new CodeInstruction(OpCodes.Ldc_I4_1); yield return new CodeInstruction(OpCodes.Call, AccessTools.Property(typeof(Text), "Font").GetSetMethod()); //Text.Font = GameFont.Small; yield return new CodeInstruction(OpCodes.Ldloca_S, rect8); yield return new CodeInstruction(OpCodes.Dup); yield return new CodeInstruction(OpCodes.Call, AccessTools.Property(typeof(Rect), "yMin").GetGetMethod()); yield return new CodeInstruction(OpCodes.Ldc_R4, 20f); yield return new CodeInstruction(OpCodes.Add); yield return new CodeInstruction(OpCodes.Call, AccessTools.Property(typeof(Rect), "yMin").GetSetMethod()); //rect7.yMin += 20f; yield return new CodeInstruction(OpCodes.Ldloc_S, rect8); yield return new CodeInstruction(OpCodes.Ldarg_0); yield return new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(Page_ConfigureStartingPawns), "curPawn")); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(PsycheCardUtility), "DrawPsycheMenuCard", new Type[] { typeof(Rect), typeof(Pawn) })); //PsycheCardUtility.DrawPsycheMenuCard(rect8, this.curPawn); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Verse; using RimWorld; using Harmony; namespace Psychology.Harmony { [HarmonyPatch(typeof(ThoughtWorker_Ugly), "CurrentSocialStateInternal")] public static class ThoughtWorker_UglyPatch { [HarmonyPostfix] public static void Disable(ref ThoughtState __result, Pawn pawn, Pawn other) { if (pawn.health.capacities.GetLevel(PawnCapacityDefOf.Sight) == 0f) { __result = false; } if (pawn is PsychologyPawn && other is PsychologyPawn) { __result = false; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using UnityEngine; namespace Psychology { public class PersonalityNodeDef : Def { public void ReloadParents() { parentDefs.Clear(); } public float GetModifier(PersonalityNodeDef def) { PersonalityNodeParent parent = parents.Find((PersonalityNodeParent p) => p.node == def); return (parent.modifier > 0 ? -1/parent.modifier : 1/Mathf.Abs(parent.modifier-1)); } public List<PersonalityNodeDef> ParentNodes { get { if(this.parentDefs == null) { this.parentDefs = new List<PersonalityNodeDef>(); if(!this.parents.NullOrEmpty()) { foreach (PersonalityNodeParent parent in this.parents) { this.parentDefs.Add(parent.node); } } } return this.parentDefs; } } /* Being a woman has an 80% chance to modify this node by this amount, reduced by how gay she is. * This models the cultural impact traditional gender roles have on their personality. * Even in 55XX, the patriarchy has not been vanquished. */ public float femaleModifier; //A list of the DefNames of the parents of this node. public List<PersonalityNodeParent> parents; //What pawns talk about when they talk about this node. public string conversationTopic; //What pawns with a high rating in this node use as a platform issue. public string platformIssueHigh; //What pawns with a low rating in this node use as a platform issue. public string platformIssueLow; //A list of the skills that modify this node. public List<PersonalityNodeSkillModifier> skillModifiers; //A list of the traits that modify this node. public List<PersonalityNodeTraitModifier> traitModifiers; //A list of the work types that being incapable of modify this node. public List<PersonalityNodeIncapableModifier> incapableModifiers; //How much a difference (or similarity) in this node affects what pawns think of each other after a conversation. public float controversiality; //The hours of the day that people with a high rating in this node will prefer to go on dates. public List<int> preferredDateHours; //A list of the actual parent Defs of this node. [Unsaved] private List<PersonalityNodeDef> parentDefs; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using RimWorld.Planet; using Verse; using UnityEngine; namespace Psychology { public class IncidentWorker_Election : IncidentWorker_MakeGameCondition { public override bool TryExecute(IncidentParms parms) { Map map = (Map)parms.target; FactionBase factionBase = Find.WorldObjects.ObjectsAt(map.Tile).OfType<FactionBase>().First(); int duration = Mathf.RoundToInt(this.def.durationDays.RandomInRange * GenDate.TicksPerDay); GameCondition cond = GameConditionMaker.MakeCondition(this.def.gameCondition, duration, 0); map.gameConditionManager.RegisterCondition(cond); Find.LetterStack.ReceiveLetter("LetterLabelNewElection".Translate(factionBase.Label), "LetterNewElection".Translate(factionBase.Label), LetterDefOf.Good, new TargetInfo(map.Center, map, false), null); return true; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI.Group; using UnityEngine; namespace Psychology { public class InteractionWorker_PlanDate : InteractionWorker { public override float RandomSelectionWeight(Pawn initiator, Pawn recipient) { if(!initiator.IsColonist || !recipient.IsColonist) { return 0f; } if(!PartyUtility.AcceptableGameConditionsToStartParty(initiator.Map)) { return 0f; } PsychologyPawn realRecipient = recipient as PsychologyPawn; PsychologyPawn realInitiator = initiator as PsychologyPawn; if (realRecipient == null || realInitiator == null) { return 0f; } if(!LovePartnerRelationUtility.LovePartnerRelationExists(initiator,recipient)) { return 0f; } if(realInitiator.psyche.lastDateTick >= Find.TickManager.TicksGame - GenDate.TicksPerDay*7 || realRecipient.psyche.lastDateTick >= Find.TickManager.TicksGame - GenDate.TicksPerDay * 7) { return 0f; } if(initiator.health.summaryHealth.SummaryHealthPercent < 1f || recipient.health.summaryHealth.SummaryHealthPercent < 1f) { return 0f; } return 1.2f * realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Romantic) * (1f - realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Independent)) * realRecipient.psyche.GetPersonalityRating(PersonalityNodeDefOf.Romantic) * (1f - realRecipient.psyche.GetPersonalityRating(PersonalityNodeDefOf.Independent)) * RendezvousUtility.ColonySizeFactor(initiator); } public override void Interacted(Pawn initiator, Pawn recipient, List<RulePackDef> extraSentencePacks) { PsychologyPawn realRecipient = recipient as PsychologyPawn; PsychologyPawn realInitiator = initiator as PsychologyPawn; //Choose a time that works with their schedule, based on their personality Dictionary<int, float> possibleHours = new Dictionary<int, float>(); for (int i = 0; i < GenDate.HoursPerDay; i++) { possibleHours.Add(i, 0f); } foreach (PersonalityNodeDef d in DefDatabase<PersonalityNodeDef>.AllDefsListForReading) { if(d.preferredDateHours != null) { foreach (int h in d.preferredDateHours) { possibleHours[h] += (Mathf.Pow(Mathf.Abs(0.5f - realInitiator.psyche.GetPersonalityRating(d)), 2) / (1.3f - realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Aggressive)) + Mathf.Pow(Mathf.Abs(0.5f - realRecipient.psyche.GetPersonalityRating(d)), 2) / (1.3f - realRecipient.psyche.GetPersonalityRating(PersonalityNodeDefOf.Aggressive)) / 2f); } } } int hour = possibleHours.Keys.RandomElementByWeight(h => possibleHours[h] * RendezvousUtility.TimeAssignmentFactor(initiator, h) * RendezvousUtility.TimeAssignmentFactor(recipient, h)); //More Spontaneous couples will plan their dates sooner; possibly even immediately! int day = Find.TickManager.TicksGame + Mathf.RoundToInt(GenDate.TicksPerDay * 5 * (((1f - realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Spontaneous)) + (1f - realRecipient.psyche.GetPersonalityRating(PersonalityNodeDefOf.Spontaneous))) / 2f)); Hediff_PlannedDate plannedDate = HediffMaker.MakeHediff(HediffDefOfPsychology.PlannedDate, initiator) as Hediff_PlannedDate; plannedDate.partner = recipient; plannedDate.day = day; plannedDate.hour = hour; initiator.health.AddHediff(plannedDate); realInitiator.psyche.lastDateTick = day; realRecipient.psyche.lastDateTick = day; if (Prefs.DevMode && Prefs.LogVerbose) { Log.Message(initiator.LabelShort + " planned date with " + recipient.LabelShort + " for hour " + hour + " on date " + GenDate.DateFullStringAt(GenDate.TickGameToAbs(day), Find.WorldGrid.LongLatOf(initiator.Map.Tile))); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; using Harmony; namespace Psychology.Harmony { [HarmonyPatch(typeof(VoluntarilyJoinableLordsStarter), "Tick_TryStartParty")] public static class VoluntarilyJoinableLordsStarter_StartPartyPatch { [HarmonyPrefix] public static bool ExtraSocialiteParties(VoluntarilyJoinableLordsStarter __instance) { //Transpiler? Map map = Traverse.Create(__instance).Field("map").GetValue<Map>(); if (map.IsPlayerHome) { return false; } int socialiteMod = 1; IEnumerable<Pawn> allPawnsSpawned = map.mapPawns.FreeColonistsSpawned; foreach (Pawn pawn in allPawnsSpawned) { if (pawn.RaceProps.Humanlike && pawn.story.traits.HasTrait(TraitDefOfPsychology.Socialite)) { socialiteMod++; } } if (Find.TickManager.TicksGame % GenDate.TicksPerHour * 2 == 0) { if (Rand.MTBEventOccurs(40f, GenDate.TicksPerDay, (GenDate.TicksPerHour * 2f * socialiteMod))) { Traverse.Create(__instance).Field("startPartyASAP").SetValue(true); } if (Traverse.Create(__instance).Field("startPartyASAP").GetValue<bool>() && Find.TickManager.TicksGame - Traverse.Create(__instance).Field("lastLordStartTick").GetValue<int>() >= (int)(GenDate.TicksPerSeason * 2 / socialiteMod) && PartyUtility.AcceptableGameConditionsToStartParty(map)) { Traverse.Create(__instance).Method("TryStartParty", new object[] { }).GetValue(); } } return false; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; using UnityEngine; namespace Psychology { public class MentalState_FellPlotting : MentalState { public override RandomSocialMode SocialModeMax() { return RandomSocialMode.Off; } public override void MentalStateTick() { base.MentalStateTick(); if (target == null) { IEnumerable<Pawn> rivals = (from c in pawn.Map.mapPawns.FreeColonistsSpawned where pawn.relations.OpinionOf(c) < -20 orderby pawn.relations.OpinionOf(c) descending select c); if (rivals.Count() == 0) { Log.ErrorOnce(pawn.LabelShort + " was in Fell Plotting mental break but has no rivals.", 100 + pawn.GetHashCode()); this.RecoverFromState(); return; } target = rivals.First(); } else if(enactingPlot && target.Dead) { pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.SuccessfulPlot, target); this.RecoverFromState(); return; } if(pawn.IsHashIntervalTick(500) && !enactingPlot) { string[] murmurings = { "HISCAP fault...", "This is all HIS fault...", "I can't let HIM get away with it...", "HECAP thinks HE's smart, does HE?", "I'll show HIM...", "Traitors... saboteurs... conspirators...", "HECAP mocks me...", "How dare HE...", "HECAP thinks I don't notice?", "I must do this myself... no one can be trusted.", "For the good of us all...", "I'll solve this problem myself...", "[muttering]", "[growling]", "[hissing]", "[murmuring]", "[incomprehensible babbling]", "Idiot!", "Fiend!", "Vulture!", "Monster!", "Liar!", "Behind my back... always behind my back...", "The source of all our problems...", "HECAP will never see it coming...", "I'll plan it all out...", "I'll think of everything...", "I'll wait until the time is right...", "I will cure this place of its blight!", "If no one else will do it, I will.", "None of them see it... they're all so blind...", "I can do this... I must do this...", "Even now, HE laughs at me...", "Serves HIM right...", "HECAP will be the death of me...", "I should have done this long ago..." }; if(Rand.Value < 0.25f) { Vector3 pos = pawn.DrawPos + pawn.Drawer.renderer.BaseHeadOffsetAt(pawn.Rotation); MoteMaker.ThrowText(pos, pawn.Map, murmurings.RandomElement().AdjustedFor(target), Color.grey, 2.5f); } } } public Pawn target; public bool enactingPlot = false; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; namespace Psychology { public class PsychologyPawn : Pawn { public override void SpawnSetup(Map map, bool respawningAfterLoad) { base.SpawnSetup(map, respawningAfterLoad); if(this.RaceProps.Humanlike) { /* Fixes any improperly-configured psychologies. */ if(this.psyche == null || this.psyche.PersonalityNodes == null) { this.psyche = new Pawn_PsycheTracker(this); this.psyche.Initialize(); } foreach (PersonalityNode node in this.psyche.PersonalityNodes) { if (node.rawRating < 0) { node.Initialize(); } } /* Same for sexuality. */ if (this.sexuality == null && PsychologyBase.ActivateKinsey()) { this.sexuality = new Pawn_SexualityTracker(this); this.sexuality.GenerateSexuality(); } } } public override void ExposeData() { base.ExposeData(); Scribe_Deep.Look(ref this.sexuality, "sexuality", new object[] { this }); Scribe_Deep.Look(ref this.psyche, "psyche", new object[] { this }); } public override string LabelNoCount { get { if (this.Name == null) { return this.KindLabel; } if (this.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor)) { return this.Name.ToStringShort + ", Mayor"; } if (this.story == null || (this.story.adulthood == null && this.story.childhood == null)) { return this.Name.ToStringShort; } return this.Name.ToStringShort + ", " + this.story.TitleShort; } } public Pawn_SexualityTracker sexuality; public Pawn_PsycheTracker psyche; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using UnityEngine; using Harmony; using System.Reflection; namespace Psychology.Harmony { [HarmonyPatch(typeof(InteractionWorker_MarriageProposal), "AcceptanceChance")] public static class InteractionWorker_MarriageProposal_AcceptanceChancePatch { [HarmonyPrefix] public static bool PsychologyException(InteractionWorker_MarriageProposal __instance, ref float __result, Pawn initiator, Pawn recipient) { PsychologyPawn realRecipient = recipient as PsychologyPawn; if (realRecipient != null) { float num = 1.2f; num *= Mathf.InverseLerp(0f, 0.75f, realRecipient.psyche.GetPersonalityRating(PersonalityNodeDefOf.Romantic)); if (PsychologyBase.ActivateKinsey()) { num *= realRecipient.sexuality.AdjustedRomanticDrive; } num *= Mathf.Clamp01(GenMath.LerpDouble(-20f, 60f, 0f, 1f, (float)recipient.relations.OpinionOf(initiator))); __result = Mathf.Clamp01(num); return false; /* If the recipient is a PsychologyPawn, the mod takes over AcceptanceChance for them and the normal method will be ignored. */ } return true; } } [HarmonyPatch(typeof(InteractionWorker_MarriageProposal), "Interacted", new[] { typeof(Pawn), typeof(Pawn), typeof(List<RulePackDef>) })] public static class InteractionWorker_MarriageProposal_InteractedPatch { [HarmonyPrefix] public static bool NewInteracted(InteractionWorker_MarriageProposal __instance, Pawn initiator, Pawn recipient, List<RulePackDef> extraSentencePacks) { //TODO: Turn this into a transpihahaha no. float num = __instance.AcceptanceChance(initiator, recipient); bool flag = Rand.Value < num; bool brokeUp = false; if (flag) { initiator.relations.RemoveDirectRelation(PawnRelationDefOf.Lover, recipient); initiator.relations.AddDirectRelation(PawnRelationDefOf.Fiance, recipient); initiator.needs.mood.thoughts.memories.RemoveMemoriesOfDefWhereOtherPawnIs(ThoughtDefOf.RejectedMyProposal, recipient); recipient.needs.mood.thoughts.memories.RemoveMemoriesOfDefWhereOtherPawnIs(ThoughtDefOf.RejectedMyProposal, initiator); /* Remove custom Psychology rejection thoughts */ foreach (ThoughtDef d in (from tgt in initiator.needs.mood.thoughts.memories.Memories where tgt.def.defName.Contains("RejectedMyProposal") select tgt.def)) { initiator.needs.mood.thoughts.memories.RemoveMemoriesOfDefWhereOtherPawnIs(d, recipient); } foreach (ThoughtDef d in (from tgt in recipient.needs.mood.thoughts.memories.Memories where tgt.def.defName.Contains("RejectedMyProposal") select tgt.def)) { recipient.needs.mood.thoughts.memories.RemoveMemoriesOfDefWhereOtherPawnIs(d, initiator); } initiator.needs.mood.thoughts.memories.RemoveMemoriesOfDefWhereOtherPawnIs(ThoughtDefOf.IRejectedTheirProposal, recipient); recipient.needs.mood.thoughts.memories.RemoveMemoriesOfDefWhereOtherPawnIs(ThoughtDefOf.IRejectedTheirProposal, initiator); extraSentencePacks.Add(RulePackDefOf.Sentence_MarriageProposalAccepted); } else { PsychologyPawn realInitiator = initiator as PsychologyPawn; PsychologyPawn realRecipient = recipient as PsychologyPawn; if (realInitiator != null) { ThoughtDef rejectedProposalDef = new ThoughtDef(); rejectedProposalDef.defName = "RejectedMyProposal" + realInitiator.LabelShort + Find.TickManager.TicksGame; rejectedProposalDef.durationDays = 40f; rejectedProposalDef.thoughtClass = typeof(Thought_MemorySocialDynamic); ThoughtStage rejectedProposalStage = new ThoughtStage(); rejectedProposalStage.label = "rejected my proposal"; rejectedProposalStage.baseOpinionOffset = Mathf.RoundToInt(-30f * realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Romantic) * Mathf.InverseLerp(100f, 5f, realInitiator.relations.OpinionOf(realRecipient))); rejectedProposalDef.stages.Add(rejectedProposalStage); ThoughtDef rejectedProposalMoodDef = new ThoughtDef(); rejectedProposalMoodDef.defName = "RejectedMyProposalMood" + realInitiator.LabelShort + Find.TickManager.TicksGame; rejectedProposalMoodDef.durationDays = 25f; rejectedProposalMoodDef.thoughtClass = typeof(Thought_MemoryDynamic); rejectedProposalMoodDef.stackedEffectMultiplier = 1f; ThoughtStage rejectedProposalMoodStage = new ThoughtStage(); rejectedProposalMoodStage.label = "proposal rejected by {0}"; rejectedProposalMoodStage.baseMoodEffect = Mathf.RoundToInt(-25f * realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Romantic) * Mathf.InverseLerp(100f, 5f, realInitiator.relations.OpinionOf(realRecipient))); if (rejectedProposalMoodStage.baseMoodEffect < -5f) { rejectedProposalMoodStage.description = "My lover isn't ready for that kind of commitment right now, and I understand, but rejection is hard to take."; } else { rejectedProposalMoodStage.description = "I can't believe I got turned down. Maybe we're not meant to be together after all?"; } rejectedProposalMoodDef.stages.Add(rejectedProposalMoodStage); if (rejectedProposalMoodStage.baseMoodEffect > 0) { realInitiator.needs.mood.thoughts.memories.TryGainMemory(rejectedProposalMoodDef, realRecipient); } realInitiator.needs.mood.thoughts.memories.TryGainMemory(rejectedProposalDef, realRecipient); } else { initiator.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.RejectedMyProposal, recipient); } recipient.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.IRejectedTheirProposal, initiator); extraSentencePacks.Add(RulePackDefOf.Sentence_MarriageProposalRejected); if (realRecipient != null && !recipient.story.traits.HasTrait(TraitDefOfPsychology.Codependent) && Rand.Value > 2f * realRecipient.psyche.GetPersonalityRating(PersonalityNodeDefOf.Romantic)) { recipient.interactions.TryInteractWith(initiator, DefDatabase<InteractionDef>.GetNamed("Breakup")); } else if (realRecipient == null && !recipient.story.traits.HasTrait(TraitDefOfPsychology.Codependent) && Rand.Value < 0.4f) { initiator.relations.RemoveDirectRelation(PawnRelationDefOf.Lover, recipient); initiator.relations.AddDirectRelation(PawnRelationDefOf.ExLover, recipient); brokeUp = true; extraSentencePacks.Add(RulePackDefOf.Sentence_MarriageProposalRejectedBrokeUp); } } if (initiator.IsColonist || recipient.IsColonist) { Traverse.Create(__instance).Method("SendLetter", new[] { typeof(Pawn), typeof(Pawn), typeof(bool), typeof(bool) }).GetValue(new object[] { initiator, recipient, flag, brokeUp }); } return false; } } [HarmonyPatch(typeof(InteractionWorker_MarriageProposal), "RandomSelectionWeight", new[] { typeof(Pawn), typeof(Pawn) })] public static class InteractionWorker_MarriageProposal_SelectionWeightPatch { [HarmonyPostfix] internal static void _RandomSelectionWeight(InteractionWorker_MarriageProposal __instance, ref float __result, Pawn initiator, Pawn recipient) { PsychologyPawn realInitiator = initiator as PsychologyPawn; if (realInitiator != null) { if (initiator.gender == Gender.Female) { /* Undo the effect of this in the postfixed method. */ __result /= 0.2f; } __result *= 0.1f + realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Aggressive) + realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Romantic); if(PsychologyBase.ActivateKinsey()) { __result *= realInitiator.sexuality.AdjustedRomanticDrive; } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using RimWorld; using Verse; using Verse.Sound; using Harmony; using System.Reflection.Emit; namespace Psychology.Harmony.Optional { public static class PresetSaverPatch { [HarmonyTranspiler] public static IEnumerable<CodeInstruction> SavePawnRef(IEnumerable<CodeInstruction> instrs, ILGenerator gen) { CodeInstruction last = null; foreach(CodeInstruction itr in instrs) { if (last != null && itr.opcode == OpCodes.Newobj && itr.operand == AccessTools.Constructor(typeof(EdB.PrepareCarefully.SaveRecordPawnV3), new Type[] { typeof(EdB.PrepareCarefully.CustomPawn) })) { yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(PresetSaverPatch), "AddPsycheToDictionary", new Type[] { typeof(EdB.PrepareCarefully.CustomPawn) })); yield return last; } yield return itr; last = itr; } } public static void AddPsycheToDictionary(EdB.PrepareCarefully.CustomPawn pawn) { if(SaveRecordPawnV3Patch.customPawns.ContainsKey(pawn.Id)) { SaveRecordPawnV3Patch.customPawns.Remove(pawn.Id); } SaveRecordPawnV3Patch.customPawns.Add(pawn.Id, pawn); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Harmony; namespace Psychology.Harmony { [HarmonyPatch(typeof(Building_Grave), "Notify_CorpseBuried")] public static class Building_Grave_NotifyCorpseBuried_Patch { [HarmonyPostfix] public static void FillGraveThought(Building_Grave __instance, Pawn worker) { CompArt comp = __instance.GetComp<CompArt>(); if (worker.needs.mood != null && comp != null) { worker.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.FilledGraveBleedingHeart); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Harmony; using UnityEngine; namespace Psychology.Harmony { [HarmonyPatch(typeof(InteractionWorker_RecruitAttempt), "DoRecruit")] public static class InteractionWorker_RecruitAttempt_DoRecruitPatch { [HarmonyPostfix] public static void AddCapturedThoughts(Pawn recruiter, Pawn recruitee) { if (recruitee.RaceProps.Humanlike) { recruitee.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.RecruitedMe, recruiter); recruitee.needs.mood.thoughts.memories.RemoveMemoriesOfDef(ThoughtDefOf.RapportBuilt); IEnumerable<Pawn> allFactionPawns = Find.Maps.SelectMany(m => from p in m.mapPawns.FreeColonistsSpawned where p != recruitee select p); foreach (Pawn pawn in allFactionPawns) { recruitee.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.CapturedMe, pawn); } } } } }
0b20339e99d8c1cde0d353edf0db1c6b1e650bad
[ "C#" ]
46
C#
XNoNameX/Psychology
dd8c8618820f7590f09c68fef60ffca1e5bd8f97
0260a5408f4e71dce616083e9a38f062e433a747
refs/heads/master
<file_sep>package com.example.mvprxjava.UTILS; import com.example.mvprxjava.UTILS.GETNEWS; import io.reactivex.Observable; import retrofit2.http.GET; public interface MODEL { @GET("v2/top-headlines?country=us&apiKey=92f2436407be44c6a15bbe1693fd95ee") Observable<GETNEWS> getNEWS(); } <file_sep>package com.example.mvprxjava.MODEL; import com.example.mvprxjava.UTILS.GETNEWS; import com.example.mvprxjava.UTILS.MODEL; import io.reactivex.Observable; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class MAINMODELDATA implements MainActivityContract.Imodel { Retrofit retrofit = new Retrofit.Builder().baseUrl("https://newsapi.org/") .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); final MODEL model = retrofit.create(MODEL.class); @Override public Observable<GETNEWS> getAllNews() { return model.getNEWS(); } } <file_sep>package com.example.mvprxjava.MODEL; import com.example.mvprxjava.UTILS.GETNEWS; import io.reactivex.Observable; public interface MainActivityContract { interface Iview{ void getAlluserView(Observable<GETNEWS> newsList); } interface Ipresenter{ void getAllNewsPresnters(); } interface Imodel{ Observable<GETNEWS> getAllNews(); } }
75d868ee7e77a69afeab89aceb09071d15d726f5
[ "Java" ]
3
Java
zeyadelosherey/MVP-Retrofit-RXJAVA
832b61e947321d26fd4080ca6d1a53bdc763259b
916eb291b2294d275b747e2c5599100ff11bf9ff
refs/heads/master
<file_sep>def pluralize(lst): nova = set(lst) resp = set() print(nova) for item in nova: print(item) if lst.count(item) > 1: resp.add(item+"s") else: resp.add(item) return resp print(pluralize(["cow", "pig", "cow", "cow"]))<file_sep>def card_hide(card): final = card[-4:] restante = len(card)-4 return restante*"*"+final print(card_hide("8247943269482"))<file_sep>def jazzify(lst): new = [] for accord in lst: if accord[-1] != "7": new.append(accord+"7") else: new.append(accord) return new<file_sep>def mean(x): lst = [int(n) for n in str(x)] soma = sum(lst) return soma/len(lst)<file_sep>def dict_to_list(d): d = sorted(d) print(d) return [(x, d[x]) for x in d.key()] print(dict_to_list({'D': 1, 'B': 2, 'C': 3}))<file_sep>def find_vertex(a, b, c): x = -b/(2*a) y = a*x**2+b*x+c if x == -0: x = abs(x) return [x, y] print(find_vertex(1, 0, 25)) print(find_vertex(-1, 0, 25)) print(find_vertex(1, 10, 4))<file_sep>def correct_stream(user, correct): resp = [] for idx, word in enumerate(user): if word == correct[idx]: resp.append(1) else: resp.append(-1) return resp<file_sep>def to_list(num): lst = [int(i) for i in str(num)] return lst def to_number(lst): newlst = [str(i) for i in lst] return "".join(newlst)<file_sep>def encrypt(word): dici = {"a": "0", "e": "1", "i": "2", "o": "2", "u": "3"} word = list(word) word.reverse() word = "".join(word) palavra = "" for letra in word: if letra in "aeiou": palavra += dici[letra] else: palavra += letra palavra += "aca" return palavra print(encrypt("apple"))<file_sep>def missing_num(lst): lst.sort() anterior = lst[0] missing = None for num in lst: if num == lst[0]: continue else: if num != (anterior + 1): missing = num - 1 anterior = num if missing == None: if lst[0] == 2: missing = 1 else: missing = 10 return missing print(missing_num([1, 2, 3, 4, 6, 7, 8, 9, 10]))<file_sep>def dial(txt): alpha = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] resp = "" for letter in txt: if letter.isalpha(): letter = letter.lower() for idx, letra in enumerate(alpha): if letter in letra: resp += str(idx+2) else: resp += letter return resp print(dial("1-800-HOTLINEBLING"))<file_sep># Enter your code here. Read input from STDIN. Print output to STDOUT file = open("files/findsubword.txt") inp = file.read() inp = inp.split("\n") import re, sys # inp = sys.stdin.read().split("\n") cont = False queries = [] phrases = [] found = 0 for sentence in inp[1:]: if sentence.isdigit(): cont = True continue if cont: queries.append(sentence) else: phrases.append(sentence) foundlst = [] for querie in queries: for phrase in phrases: found += len(re.findall("[A-Za-z]+"+querie+"[A-Za-z]+",phrase)) foundlst.append(found) for num in foundlst: pass print(num) file.close()<file_sep>def is_isogram(word): word = word.lower() for letter in word: if word.count(letter) > 1: return False return True<file_sep>def alphanumeric_restriction(string): def find_type(n): if n.isdigit(): return "digit" elif n.isalpha(): return "letter" else: return "especial" tipo = "" if string == "": return False for idx, letter in enumerate(string): if idx == 0: if find_type(letter) == "especial": return False tipo = find_type(letter) else: tipo2 = find_type(letter) if tipo != tipo2: return False return True print(alphanumeric_restriction("B0ld"))<file_sep>def return_unique(lst): return [i for i in lst if lst.count(i) == 1] print(return_unique([1, 9 ,8, 8, 7, 6, 1, 6]))<file_sep>def is_symmetrical(n): lst = [int(i) for i in str(n)] lst2 = [int(i) for i in str(n)] lst2.reverse() if lst == lst2: return True return False print(is_symmetrical(28682))<file_sep>import math def cars(wheel, body, figure): if wheel < 4 or body < 1 or figure < 2: return 0 else: wheel /= 4 figure /= 2 return math.floor(min(wheel, body, figure)) print(cars(2, 48, 76)) print(cars(43, 15, 87)) print(cars(88, 37, 17))<file_sep>def integer_boolean(n): result = [] for num in n: if num == "1": result.append(True) else: result.append(False) return result<file_sep>def solutions(a, b, c): delta = pow(b,2) - 4 * a * c if delta < 0: return 0 elif delta == 0: return 1 else: return 2 print(solutions(1, 0, -1))<file_sep>def probability(lst, n): percenttotal = 100 / len(lst) percent = 0 for number in lst: if number >= n: percent += percenttotal return round(percent, 1) print(probability([5, 1, 8, 9], 6))<file_sep>class Person: def __init__(self, firstname, lastname, age): self.firstname = firstname self.lastname = lastname self.age = age p1 = Person('Michael', 'Smith', 40) p2 = Person('Alice', 'Waters', 21) p3 = Person('Zoey', 'Jones', 29) p4 = Person('Susan', 'Heffley', 43) p5 = Person('Bob', 'Fredericson', 70) p6 = Person('Braxton', 'Leighsonley', 2) p7 = Person('Joshua', 'Senoron', 99999999999999) people = [p1, p2, p3, p4, p5, p6, p7] def people_sort(lst, idx): resp = [] for person in lst: # print(person.__dict__) resp.append(person) return resp print(people_sort(people, "lastname"))<file_sep>def freed_prisoners(prison): prisoners = [] for n in prison: prisoners.append(1) def troca(prisao): for idx, cela in enumerate(prisao): if cela == 0: prisao[idx] = 1 else: prisao[idx] = 0 if prison[0] == 0: return 0 contador = 0 # Para cada cela na prisão for cell in prison: # Se for a primeira if contador == 0: prisoners[contador] = 0 troca(prison) # Se não for a primeira else: # Se estive fechada, ignore if cell == 0: continue # Se estiver aberta, liberte else: prisoners[contador] = 0 troca(prison) contador += 1 return prisoners.count(0) print(freed_prisoners([1, 1, 0, 0, 0, 1, 0]))<file_sep>def steps_to_convert(string): countupper = 0 countlower = 0 for letter in string: if letter.isupper(): countupper += 1 else: countlower += 1 return min(countupper, countlower) print(steps_to_convert("aba"))<file_sep>import math def shift_to_right(num: int, divisor: int) -> int: return math.floor(num/pow(2, divisor))<file_sep>import math def circle_or_square(rad, area): circun = 2*3.14*rad lado = math.sqrt(area) peri = lado * 4 if circun > peri: return True return False<file_sep>def clone(lst): lst2 = list(lst) lst.append(lst2) return lst print(clone(["1", "2"]))<file_sep>def factorial(n): resp = 1 for num in range(1, n+1): resp *= num return resp print(factorial(5))<file_sep>def unique(lst): newlst = [str(i) for i in lst] valor = [i for i in newlst if newlst.count(i) == 1] valor = "".join(valor) try: valor = int(valor) except: valor = float(valor) return valor print(unique([3, 3, 3, 7.2, 3, 3]))<file_sep>def index_of_caps(word): idxs = [] for idx, letter in enumerate(word): if letter.isupper(): idxs.append(idx) return idxs print(index_of_caps("aLoR"))<file_sep>def remove_vowels(txt): new = [i for i in txt if i not in "aeiou" and i not in "AEIOU"] print(new) return "".join(new) print(remove_vowels("Hello I am Lara"))<file_sep>def split(txt): palavra = "" conjunto = [] match = 0 for letra in txt: if letra == "(": match += 1 palavra += letra elif letra == ")": match -= 1 if match == 0: palavra += letra conjunto.append(palavra) palavra = "" else: palavra += letra return conjunto print(split("(()) () ()"))<file_sep>def replace_vowels(txt, ch): resp = "" for letter in txt: if letter in "aeiou": resp += ch else: resp += letter return resp print(replace_vowels("ola tudo bem", "*"))<file_sep>def sum2(a, b): a = a[::-1] a = a[::-1] adicao = 0 resp = "" restante = len(a) - len(b) if restante != 0: if restante < 0: a += abs(restante)*"0" else: b += abs(restante)*"0" for idx, digit in enumerate(a): soma = int(digit) + int(b[idx]) + adicao if idx == len(a)-1: resp += str(soma)[::-1] else: if soma >= 10: adicao = int(str(soma)[0]) resp += str(soma)[1] else: resp += str(soma) # # if soma >= 10: # if idx == list(enumerate(a))[-1][0]: # resp += str(soma)[0] + str(soma)[1] # else: # adicao = int(str(soma)[0]) # resp += str(soma)[1] # else: # resp += str(soma) resp = resp[::-1] return resp print(sum2("399829967832","88768843793943")) print(399829967832+88768843793943)<file_sep>def binarizar(x, tam=8): bina = str(bin(x)[2:]) if len(bina) < 8: rest = 8 - len(bina) bina = rest * "0" + bina return str(bina) def desbinarizar(x): dec = int(x, 2) return dec print(desbinarizar("0001111")) def bitwise_and(n1, n2): n1, n2 = binarizar(n1), binarizar(n2) novo = [] for idx, num in enumerate(n1): if num == n2[idx] and num == "1": novo.append("1") else: novo.append("0") novo = "".join(novo) return desbinarizar(novo) print(bitwise_and(6, 23)) def bitwise_or(n1, n2): n1, n2 = binarizar(n1), binarizar(n2) novo = [] for idx, num in enumerate(n1): if num == "1" or n2[idx] == "1": novo.append("1") else: novo.append("0") novo = "".join(novo) return desbinarizar(novo) print(bitwise_or(6, 23)) def bitwise_xor(n1, n2): n1, n2 = binarizar(n1), binarizar(n2) novo = [] for idx, num in enumerate(n1): if (n2[idx] == "1" and n2[idx] != num) or (num == "1" and num != n2[idx]): novo.append("1") else: novo.append("0") novo = "".join(novo) return desbinarizar(novo) print(bitwise_xor(7, 12))<file_sep>def rotate(mat): linhas = len(mat) colunas = len(mat[0]) mat.reverse() resp = [] for linha in range(linhas): line = [] for coluna in range(colunas): line.append(mat[coluna][linha]) resp.append(line) return resp print(rotate([[1, 2], [3, 4]])) # 1 2 # 3 4 # 3 1 # 4 2<file_sep>def correct_spacing(string): new = "" ant = False for idx, letra in enumerate(string): if letra == " ": if ant or idx == len(string)+1: continue else: new += letra ant = True else: new += letra ant = False return new print(correct_spacing("( eu gosto de pirulito "))<file_sep>def can_see_stage(seats): linhas = len(seats) colunas = len(seats[0]) anterior = 0 for coluna in range(colunas): for linha in range(linhas): if linha == 0: anterior = seats[linha][coluna] else: if seats[linha][coluna] <= anterior: return False anterior = seats[linha][coluna] return True print(can_see_stage([[4, 2, 3, 2, 1, 1], [2, 4, 4, 3, 2, 2], [5, 5, 5, 5, 4, 4], [6, 6, 7, 6, 5, 5]]))<file_sep>from datetime import date print(date(2020, 5, 13).weekday())<file_sep>def relation_to_luke(name): dici = {"Dart Vader": "father", "Leia": "sister", "Han": "brother in law", "R2D2": "droid"} if dici[name]: return "Luke, I am your "+dici[name] print(relation_to_luke("Dart Vader"))<file_sep>resp = [n for n in range(8, 2)] print(resp)<file_sep>def society_name(friends): letters = [] for friend in friends: letters.append(friend[0]) letters.sort() letters = "".join(letters) letters.upper() return letters<file_sep>def maximum_score(tile_hand): total = 0 for dici in tile_hand: total += dici["score"] return total<file_sep>def cycle_length(lst, n): def swap(lista, pos1, pos2): valor1 = lista[pos1] valor2 = lista[pos2] lista[pos1] = valor2 lista[pos2] = valor1 return lista[pos1] position = lst.index(n) cont = 0 while position+1 != n: n = swap(lst, position, n-1) position = lst.index(n) cont += 1 return cont print(cycle_length([1, 5, 4, 3, 2, 6], 4))<file_sep>def XO(txt): txt = list(txt) count1 = txt.count("x") count1 += txt.count("X") count2 = txt.count("o") count2 += txt.count("O") if count1 == count2: return True return False print(XO("xoxoxo")) print(XO("xox"))<file_sep>def word_builder(lst1, lst2): new = "" for num in range(len(lst1)): new += lst1[lst2[num]] return new print(word_builder(["g", "e", "o"], [1, 0, 2])) print(word_builder(["e", "t", "s", "t"], [3, 0, 2, 1]))<file_sep>def alphabet_soup(txt): txt = list(txt) txt.sort() return "".join(txt)<file_sep>def sum_of_evens(lst): num = 0 for linha in lst: for coluna in linha: if coluna % 2 == 0: num += coluna return num<file_sep>def count_ones(num): cont = 0 binary = str(bin(num))[2:] for letra in binary: if letra == "1": cont += 1 return cont print(count_ones(2))<file_sep>months = { "1": "A", "2": "B", "3": "C", "4": "D", "5": "E", "6": "H", "7": "L", "8": "M", "9": "P", "10": "R", "11": "S", "12": "T" } import re def fiscal_code(person): # SURNAME surname = person["surname"] surname = surname.upper() conso = [n for n in surname if n not in "AEIOU"] conso = "".join(conso) if len(conso) < 3: if len(surname) < 3: surname += "X" else: vogal = re.sub(conso[0], "", surname)[:1] surname = conso + vogal else: surname = conso[:3] # print(surname) # NAME name = person["name"] name = name.upper() conso = [c for c in name if c not in "AEIOU"] conso = "".join(conso) if len(conso) == 3: name = conso elif len(conso) > 3: name = conso[0]+conso[2]+conso[3] elif len(name) < 3: for n in name: if n in "AEIOU": letra = n break name = conso+letra+"X" elif len(conso) < 3: for n in name: if n in "AEIOU": letra = n break name = conso+letra # print(name) # DATA DE NASC E GENERO nasc = person["dob"].split("/") ano = nasc[2][2:4] mes = months[nasc[1]] # homem dia = 0 if person["gender"] == "M": if int(nasc[0]) < 10: dia = "0"+nasc[0][:1] else: dia = nasc[0] else: dia = int(nasc[0])+40 dia = str(dia) # COMPLETO return surname+name+ano+mes+dia print(fiscal_code({ "name": "Brendan", "surname": "Eich", "gender": "M", "dob": "1/12/1961"})) print(fiscal_code({ "name": "Helen", "surname": "Yu", "gender": "F", "dob": "1/12/1950"})) print(fiscal_code({ "name": "Al", "surname": "Capone", "gender": "M", "dob": "17/1/1899"})) print(fiscal_code({ "name": "Mickey", "surname": "Mouse", "gender": "M", "dob": "16/1/1928"})) print(fiscal_code({ "name": "Marie", "surname": "Curie", "gender": "F", "dob": "7/11/1867"}))<file_sep>def index_multiplier(lst): inic = 0 for idx, num in enumerate(lst): inic += num * idx return inic<file_sep>def convert_cartesian(x, y): lst = [] for idx, num in enumerate(x): lst.append([num, y[idx]]) return lst<file_sep> print(censor_string("Today is a Wednesday!", ["Today", "a"], "-"))<file_sep>def tallest_skyscraper(lst): linhas = len(lst) colunas = len(lst[0]) for linha in range(linhas): for coluna in range(colunas): if lst[linha][coluna] == 1: return linhas - linha print(tallest_skyscraper([[0, 1, 0, 0],[0, 1, 0, 0],[0, 1, 1, 0],[1, 1, 1, 1]]))<file_sep>def return_only_integer(lst): lista = [] for num in lst: if not isinstance(num, bool): if isinstance(num, int): lista.append(num) return lista print(return_only_integer([1]))<file_sep>def rearranged_difference(num): num = [int(n) for n in str(num)] nummax, nummin = sorted(num, reverse=True), sorted(num) nummax, nummin = int("".join(map(str, nummax))), int("".join(map(str, nummin))) return nummax - nummin print(rearranged_difference(972882))<file_sep>def leaderboards(lst): truescore = {} resp = [] for dici in lst: truescore.update({dici["name"]: (dici["score"]+(dici["reputation"]*2))}) truescore = sorted(truescore.items(), key=lambda x: x[1], reverse=True) for tupla in truescore: for dici in lst: if tupla[0] == dici["name"]: resp.append(dici) return resp print(leaderboards([{ "name": "a", "score": 100, "reputation": 20 },{ "name": "b", "score": 90, "reputation": 40 },{ "name": "c", "score": 115, "reputation": 30 },]))<file_sep>def id_mtrx(n): if not isinstance(n, int): return "Error" listinha = [[] for i in range(abs(n))] if n > 0: for linha in range(n): for coluna in range(n): if coluna == linha: listinha[linha].append(1) else: listinha[linha].append(0) else: n = abs(n) cont = n - 1 for linha in range(n): for coluna in range(n): if coluna == cont: listinha[linha].append(1) else: listinha[linha].append(0) cont -= 1 return listinha print(id_mtrx(-3))<file_sep>def profit_margin(cost_price, sales_price): profit = 0.0 profit = (cost_price - sales_price) / sales_price profit = round((profit*100), 1) if profit == 0: profit = abs(profit) else: profit = profit*-1 return str(profit)+"%" print(profit_margin(33, 84))<file_sep>def atbash(txt): alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k' ,'l', 'm', 'n' ,'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'y', 'z'] novo = [] for letra in txt: if letra in alpha: idx = -(alpha.index(letra)+1) novo.append(alpha[idx]) else: if letra == " ": novo.append(" ") else: letra.lower() idx = -(alpha.index(letra)+1) novo.append(alpha[idx].upper()) return "".join(novo) print(atbash("abcde"))<file_sep>def uncensor(string, vwls): new = "" cont = 0 for letter in string: if letter == "*": new += vwls[cont] cont += 1 else: new += letter return new<file_sep>def convert_binary(word): alpha0 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"] resp = "" for letter in word: if letter.lower() in alpha0: resp += "0" else: resp += "1" return resp<file_sep>def century_from_year(n): century = (n/100) if century - int(century) != 0: century += 1 return int(century) print(century_from_year(200))<file_sep>import re def has_digit(txt): x = re.search("^.*[0-9].*$", txt) if x: return True return False print(has_digit("Ola l1nda"))<file_sep>def amplify(x): lst = [] for num in range(1, x+1): if num % 4 == 0: lst.append(num*10) else: lst.append(num) return lst<file_sep>def count_layers(rug): print(len(rug)) if len(rug) <= 2: mid = 0 else: mid = (len(rug)//2) last = None count = 0 print(mid) for letter in rug[mid]: if letter != last: print(letter) count += 1 last = letter count = count - count//2 return count print(count_layers([ "AAAA", "ABBA", "AAAA"]))
055b6975c62a2ff17bdfd6c73ac53c5ec9f8765c
[ "Python" ]
65
Python
LaraGastaldi/edabit_exercises
9cf1fbd1ae79f2b0145ce488f4987b06a1b192cf
9a633dd1fcf048a0a6e24c11e643726ca83a21e3
refs/heads/master
<repo_name>sequae92/Hotel-Cluster-Recommendation<file_sep>/exploreTestData.py import pandas as pd import random #import original data destinationsData = pd.read_csv("data/destinations.csv") testData = pd.read_csv("data/test.csv") trainData = pd.read_csv("data/train.csv") #See how many rows are in the training and testing data trainShape = trainData.shape print("Rows in train.csv: ", trainShape) testShape = testData.shape print("Rows in test.csv: ", testShape) #Find out how many unique users are in the training data uniqueUsers = trainData.user_id.unique() print("Unique users: ", len(uniqueUsers)) #Find out approximately how many rows of data for 8000 users sampleUsers = [uniqueUsers[i] for i in sorted(random.sample(range(len(uniqueUsers)), 8000)) ] selectedUserData = trainData[trainData.user_id.isin(sampleUsers)] print("Selected User data size: ", len(selectedUserData)) #convert date to add month and year to the data selectedUserData["date_time"] = pd.to_datetime(selectedUserData["date_time"]) selectedUserData["year"] = selectedUserData["date_time"].dt.year selectedUserData["month"] = selectedUserData["date_time"].dt.month #split into 2 sets, one for training and one for testing train1 = selectedUserData[((selectedUserData.year == 2013) | ((selectedUserData.year == 2014) & (selectedUserData.month < 8)))] test2 = selectedUserData[((selectedUserData.year == 2014) & (selectedUserData.month >= 8))] #then strip out all rows that do not have is_booking = TRUE for our test dataset test2 = test2[test2.is_booking == True] print("Training User data size: ", len(train1)) print("Testing User data size: ", len(test2)) #Write the selected user data to a new file so we can use it for learning train1.to_csv("data/train1.csv") test2.to_csv("data/test2.csv")<file_sep>/alterTestData.py import pandas as pd import random from sklearn.decomposition import PCA # import new test data destinationsData = pd.read_csv("destinations.csv") testData = pd.read_csv("test2.csv") trainData = pd.read_csv("train1.csv") # convert dates # See how many rows are in the training and testing data trainShape = trainData.shape print("Rows in train.csv: ", trainShape) testShape = testData.shape print("Rows in test.csv: ", testShape) pca = PCA(n_components=3) dest_small = pca.fit_transform(destinationsData[["d{0}".format(i + 1) for i in range(149)]]) dest_small = pd.DataFrame(dest_small) dest_small["srch_destination_id"] = destinationsData["srch_destination_id"] print(dest_small) # generate features def calc_fast_features(df): df["date_time"] = pd.to_datetime(df["date_time"]) df["srch_ci"] = pd.to_datetime(df["srch_ci"], format='%Y-%m-%d', errors="coerce") df["srch_co"] = pd.to_datetime(df["srch_co"], format='%Y-%m-%d', errors="coerce") props = {} for prop in ["month", "day", "hour", "minute", "dayofweek", "quarter"]: props[prop] = getattr(df["date_time"].dt, prop) carryover = [p for p in df.columns if p not in ["date_time", "srch_ci", "srch_co"]] for prop in carryover: props[prop] = df[prop] date_props = ["month", "day", "dayofweek", "quarter"] for prop in date_props: props["ci_{0}".format(prop)] = getattr(df["srch_ci"].dt, prop) props["co_{0}".format(prop)] = getattr(df["srch_co"].dt, prop) props["stay_span"] = (df["srch_co"] - df["srch_ci"]).astype('timedelta64[h]') ret = pd.DataFrame(props) ret = ret.join(dest_small, on="srch_destination_id", how='left', rsuffix="dest") ret = ret.drop("srch_destination_iddest", axis=1) return ret df = calc_fast_features(trainData) df.fillna(-1, inplace=True) # generate predictions using Random Forest predictors = [c for c in df.columns if c not in ["hotel_cluster"]] from sklearn import cross_validation from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(n_estimators=10, min_weight_fraction_leaf=0.1) scores = cross_validation.cross_val_score(clf, df[predictors], df['hotel_cluster'], cv=3) print(scores)<file_sep>/README.md # Hotel-Cluster-Recommendation Developed a recommendation system engine which predicts the the hotel cluster most likely to be booked by the user. This is possible after employing collaborative filtering based techniques after thorough data cleaning. Dataset - Expedia User search log dataset ( logs of customer ssearch behaviour) 1.6 Terabytes This was completed as part of Kaggle Data Science challenge. Link- https://www.kaggle.com/c/expedia-hotel-recommendations/
b4506cdc630ee0d2797d6ecf30b97372dd7e569a
[ "Markdown", "Python" ]
3
Python
sequae92/Hotel-Cluster-Recommendation
7998df26a2398ad9e0ce7d1c73e982582e89addd
e06211969be4949da6d18d39c6e614ab6ef71da6
refs/heads/master
<repo_name>Johnloveiv/interactive-decision-tree<file_sep>/_THEME.php <?php define("BOOTSTRAP_THEME","united.bootstrap.min.css");<file_sep>/schema.sql -- phpMyAdmin SQL Dump -- version 3.4.10.1deb1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jan 16, 2014 at 10:09 AM -- Server version: 5.5.34 -- PHP Version: 5.3.10-1ubuntu3.9 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; -- -- Database: `inter-tree` -- -- -------------------------------------------------------- -- -- Table structure for table `admin` -- CREATE TABLE IF NOT EXISTS `admin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(500) NOT NULL, `password` varchar(500) NOT NULL, `email` varchar(500) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`id`, `username`, `password`, `email`) VALUES (1, 'admin', '<PASSWORD>', '<EMAIL>'); -- -------------------------------------------------------- -- -- Table structure for table `referrals` -- CREATE TABLE IF NOT EXISTS `referrals` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(500) NOT NULL, `phone` varchar(15) NOT NULL, `email` varchar(250) NOT NULL, `url` text NOT NULL, `address` text NOT NULL, `address2` text NOT NULL, `city` varchar(250) NOT NULL, `state` varchar(250) NOT NULL, `zip` varchar(10) NOT NULL, `loc` varchar(250) NOT NULL, `status` varchar(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=23 ; -- -------------------------------------------------------- -- -- Table structure for table `referrals_assoc_tree` -- CREATE TABLE IF NOT EXISTS `referrals_assoc_tree` ( `id` int(11) NOT NULL AUTO_INCREMENT, `referral_id` int(11) NOT NULL, `assoc_tree` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ; -- -------------------------------------------------------- -- -- Table structure for table `referrals_clicks` -- CREATE TABLE IF NOT EXISTS `referrals_clicks` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` varchar(100) NOT NULL, `referral_id` varchar(100) NOT NULL, `sess_id` varchar(100) NOT NULL, `time_clicked` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -------------------------------------------------------- -- -- Table structure for table `sessions` -- CREATE TABLE IF NOT EXISTS `sessions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` varchar(100) NOT NULL, `tree_id` varchar(100) NOT NULL, `time_started` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP, `last_link_clicked` varchar(20) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=129 ; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` varchar(100) NOT NULL, `user_ip` varchar(50) NOT NULL, `city` varchar(255) NOT NULL, `region` varchar(255) NOT NULL, `loc` varchar(500) NOT NULL, `zip` varchar(10) NOT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=29 ;
7410781f6d9aaea9b74c16c398d414f459d912f0
[ "SQL", "PHP" ]
2
PHP
Johnloveiv/interactive-decision-tree
83de75f452c846be22067f2cdcc3a7a85a5bc1fe
d916def55d2c39db33ca51976b1f208ec5ed62a3
refs/heads/master
<file_sep>package np.com.shresthakiran.covid19tracker; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import android.os.Bundle; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { CardView cvInfectedNepal, cvRecoveredNepal, cvDeathNepal, cvInfectedWorld, cvRecoveredWorld, cvDeathWorld; TextView tvNepalInfectedCount, tvNepalRecoveredCount, tvNepalDeathCount, tvNepalInfectedCountToday, tvNepalRecoveredCountToday, tvNepalDeathCountToday, tvWorldInfectedCount, tvWorldRecoveredCount, tvWorldDeathCount, tvWorldInfectedCountToday, tvWorldRecoveredCountToday, tvWorldDeathCountToday; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fetchCovid19Data(); } public void fetchCovid19Data(){ final String URLNEPAL = "https://corona.lmao.ninja/v2/countries/Nepal"; final String URLWORLD = "https://corona.lmao.ninja/v2/all"; tvNepalInfectedCount = findViewById(R.id.tvNepalInfectedCount); tvNepalRecoveredCount = findViewById(R.id.tvNepalRecoveredCount); tvNepalDeathCount = findViewById(R.id.tvNepalDeathCount); tvNepalInfectedCountToday = findViewById(R.id.tvNepalInfectedCountToday); tvNepalRecoveredCountToday = findViewById(R.id.tvNepalRecoveredCountToday); tvNepalDeathCountToday = findViewById(R.id.tvNepalDeathCountToday); tvWorldInfectedCount = findViewById(R.id.tvWorldInfectedCount); tvWorldRecoveredCount = findViewById(R.id.tvWorldRecoveredCount); tvWorldDeathCount = findViewById(R.id.tvWorldDeathCount); tvWorldInfectedCountToday = findViewById(R.id.tvWorldInfectedCountToday); tvWorldRecoveredCountToday = findViewById(R.id.tvWorldRecoveredCountToday); tvWorldDeathCountToday = findViewById(R.id.tvWorldDeathCountToday); RequestQueue requestQueue; requestQueue = Volley.newRequestQueue(this); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URLNEPAL, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { String NepalInfectedCount = response.getString("cases"); String NepalRecoveredCount = response.getString("recovered"); String NepalDeathCount = response.getString("deaths"); String NepalInfectedCountToday = response.getString("todayCases"); String NepalRecoveredCountToday = response.getString("todayRecovered"); String NepalDeathCountToday = response.getString("todayDeaths"); tvNepalInfectedCount.setText(NepalInfectedCount); tvNepalRecoveredCount.setText(NepalRecoveredCount); tvNepalDeathCount.setText(NepalDeathCount); tvNepalInfectedCountToday.setText(NepalInfectedCountToday); tvNepalRecoveredCountToday.setText(NepalRecoveredCountToday); tvNepalDeathCountToday.setText(NepalDeathCountToday); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); requestQueue.add(jsonObjectRequest); JsonObjectRequest jsonObjectRequest1 = new JsonObjectRequest(Request.Method.GET, URLWORLD, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { String WorldInfectedCount = response.getString("cases"); String WorldRecoveredCount = response.getString("recovered"); String WorldDeathCount = response.getString("deaths"); String WorldInfectedCountToday = response.getString("todayCases"); String WorldRecoveredCountToday = response.getString("todayRecovered"); String WorldDeathCountToday = response.getString("todayDeaths"); tvWorldInfectedCount.setText(WorldInfectedCount); tvWorldRecoveredCount.setText(WorldRecoveredCount); tvWorldDeathCount.setText(WorldDeathCount); tvWorldInfectedCountToday.setText(WorldInfectedCountToday); tvWorldRecoveredCountToday.setText(WorldRecoveredCountToday); tvWorldDeathCountToday.setText(WorldDeathCountToday); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); requestQueue.add(jsonObjectRequest1); } }
94875177ad8bd71e36cc76564368105242c0a0d8
[ "Java" ]
1
Java
ikiranshrestha/COVID-19-Tracker
f9fe6503e9cb34946e519a0e304efbd2816b1371
f470751e2d570f704216ff4c25aeeb6595003c59
refs/heads/master
<repo_name>mavyasoni786/BaseProjectKotlin<file_sep>/BaseProjectKotlin/app/src/main/java/com/summer/baseprojectkotlin/binding/AppBinding.kt package com.summer.baseprojectkotlin.binding import android.databinding.BindingAdapter import android.support.design.widget.TextInputLayout import android.widget.EditText import com.summer.baseprojectkotlin.base.BaseViewModel import com.summer.baseprojectkotlin.viewmodels.LoginViewModel class AppBinding { companion object { @BindingAdapter("setErrorMessage") @JvmStatic fun setErrorMessage(view: TextInputLayout, errorMessage: String) { view.error = errorMessage } @BindingAdapter("setOnEditorActionListener") @JvmStatic fun setOnEditorActionListener(view: EditText, baseViewModel: BaseViewModel) { if (baseViewModel is LoginViewModel) { var loginViewModel = baseViewModel; view.setOnEditorActionListener(baseViewModel) } } // // @BindingAdapter("registerFacebook") // @JvmStatic // fun registerFacebook(view: LoginButton, baseViewModel: LoginViewModel) { // view.registerCallback(baseViewModel.callbackManager, baseViewModel) // } // // @BindingAdapter("setAdapter") // @JvmStatic // fun setAdapter(view: Spinner, arrayAdapter: ArrayAdapter<String>) { // if (arrayAdapter != null) // view.adapter = arrayAdapter // } // // @BindingAdapter("attachContainer") // @JvmStatic // fun attachContainer(frameLayout: FrameLayout, viewModel: DashboardViewModel) { // viewModel.containerId = frameLayout.id // } // // @BindingAdapter("setDrawer") // @JvmStatic // fun setDrawer(drawerLayout: DrawerLayout, dashboardViewModel: DashboardManagerViewModel) { // dashboardViewModel.drawer = drawerLayout // } // // @BindingAdapter("setNavigationListener") // @JvmStatic // fun setNavigationListener(navigationView: NavigationView, dashboardViewModel: DashboardViewModel) { // navigationView.setNavigationItemSelectedListener(dashboardViewModel) // dashboardViewModel.navigationView = navigationView // dashboardViewModel.loadDashboard() // } // // @BindingAdapter("setToolbar") // @JvmStatic // fun setToolbar(toolbar: Toolbar, dashboardViewModel: DashboardManagerViewModel) { // dashboardViewModel.toolbar = toolbar // dashboardViewModel.setToolbar() // dashboardViewModel.setToggle() // } } }<file_sep>/BaseProjectKotlin/app/src/main/java/com/summer/baseprojectkotlin/MainActivity.kt package com.summer.baseprojectkotlin import android.databinding.DataBindingUtil import android.support.v7.app.AppCompatActivity import android.os.Bundle import com.summer.baseprojectkotlin.databinding.ActivityMainBinding import com.summer.baseprojectkotlin.viewmodels.LoginViewModel class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main) binding.viewModel = LoginViewModel(this) } } <file_sep>/BaseProjectKotlin/app/src/main/java/com/summer/baseprojectkotlin/utils/ItemOffsetDecoration.kt package com.esankamdriod.thepetpeople.utils import android.content.Context import android.graphics.Rect import android.support.v7.widget.RecyclerView import android.view.View class ItemOffsetDecoration(var itemOffset: Int) : RecyclerView.ItemDecoration() { constructor(context: Context, itemOffsetId: Int) : this(context.getResources().getDimensionPixelSize(itemOffsetId)) override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) { super.getItemOffsets(outRect, view, parent, state) outRect!!.left = itemOffset; outRect.right = itemOffset; outRect.bottom = itemOffset; // Add top margin only for the first item to avoid double space between items if (parent!!.getChildLayoutPosition(view) == 0) { outRect.top = itemOffset; } else { outRect.top = 0; } } }<file_sep>/BaseProjectKotlin/app/src/main/java/com/summer/baseprojectkotlin/interfaces/RecyclerViewLongClickHandler.kt package com.esankamdriod.thepetpeople.interfaces interface RecyclerViewLongClickHandler<T> { fun onLongClick(viewModel: T) }<file_sep>/BaseProjectKotlin/app/src/main/java/com/summer/baseprojectkotlin/viewmodels/LoginViewModel.kt package com.summer.baseprojectkotlin.viewmodels import android.content.Intent import android.databinding.ObservableBoolean import android.databinding.ObservableField import android.view.KeyEvent import android.view.View import android.view.inputmethod.EditorInfo import android.widget.TextView import com.summer.baseprojectkotlin.utils.StringUtils import com.summer.baseprojectkotlin.base.BaseViewModel import android.databinding.Bindable import android.support.v7.app.AppCompatActivity import com.summer.baseprojectkotlin.BR import com.summer.baseprojectkotlin.SecondActivity open class LoginViewModel(private val activity: AppCompatActivity) : BaseViewModel(), TextView.OnEditorActionListener { @Bindable var btnText: String = "" set(value) { field = value notifyPropertyChanged(BR.btnText) } //email var emailEnable: ObservableBoolean = ObservableBoolean(false) var email: ObservableField<String> = ObservableField() var emailError: ObservableField<String> = ObservableField("") //password var passwordEnable: ObservableBoolean = ObservableBoolean(false) var password: ObservableField<String> = ObservableField() var passwordError: ObservableField<String> = ObservableField("") fun onClick(view: View) { val strEmail = email.get() val strPassword = password.get() var isValid = true if (!StringUtils.hasContent(strEmail)) { emailEnable.set(true) emailError.set("Please enter email") isValid = false } else if (StringUtils.hasContent(strEmail) && !StringUtils.isEmailValid(strEmail!!)) { emailEnable.set(true) emailError.set("Please enter valid email") isValid = false } else { emailEnable.set(false) } if (!StringUtils.hasContent(strPassword)) { passwordEnable.set(true) passwordError.set("Please enter password") isValid = false } else { passwordEnable.set(false) } if (isValid) { emailEnable.set(false) passwordEnable.set(false) btnText = "Valid" val intent = Intent(activity, SecondActivity::class.java) activity.startActivity(intent) } } override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean { if (actionId == EditorInfo.IME_ACTION_DONE) { onClick(v!!) return true } return false } }<file_sep>/BaseProjectKotlin/app/src/main/java/com/summer/baseprojectkotlin/base/BaseViewModel.kt package com.summer.baseprojectkotlin.base import android.databinding.BaseObservable open class BaseViewModel : BaseObservable() { }<file_sep>/BaseProjectKotlin/app/src/main/java/com/summer/baseprojectkotlin/interfaces/RecyclerViewClickHandler.kt package com.esankamdriod.thepetpeople.interfaces interface RecyclerViewClickHandler<T> { fun onClick(viewModel: T) }
c3afd605e1f30f5bc3343044a70d2062b543cab3
[ "Kotlin" ]
7
Kotlin
mavyasoni786/BaseProjectKotlin
5de58fd43ad1e31e7630c39810faa20d861b033b
60e1e3af7c7aea1821ef0688379650a254044021
refs/heads/master
<repo_name>nassiddharth/Appium<file_sep>/com.appiumpractice/src/main/java/TataBase/baseTataCliq.java package TataBase; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; public class baseTataCliq { protected static AndroidDriver<AndroidElement> driver; public static AndroidDriver<AndroidElement> capabilities() throws MalformedURLException { File appDir = new File("src/test/java"); File app = new File(appDir, "tatacliq-9-6.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(CapabilityType.BROWSER_NAME, ""); capabilities.setCapability("deviceName", "emulator-5554"); capabilities.setCapability("platformVersion", "9"); capabilities.setCapability("platformName", "Android"); //capabilities.setCapability("app", app.getAbsolutePath()); capabilities.setCapability("appPackage", "com.tul.tatacliq"); capabilities.setCapability("appActivity", "com.tul.tatacliq.activities.MainActivity"); capabilities.setCapability("appWaitActivity", "com.tul.tatacliq.activities.MainActivity"); capabilities.setCapability("noReset","true"); capabilities.setCapability("fullReset","false"); driver = new AndroidDriver<AndroidElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS); return driver; } } <file_sep>/com.appiumpractice/src/main/java/Utilities/Report.java package Utilities; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; public class Report { ExtentHtmlReporter htmlReporter; protected static ExtentReports extent; @BeforeSuite public void reportSetup() { htmlReporter=new ExtentHtmlReporter("report.html"); extent = new ExtentReports(); extent.attachReporter(htmlReporter); } @AfterSuite public void reportTear() { extent.flush(); } } <file_sep>/com.appiumpractice/src/main/java/TataCliqAppPOM/MyAccount.java package TataCliqAppPOM; import java.util.Random; import org.openqa.selenium.support.PageFactory; import Utilities.Utility; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.pagefactory.AndroidFindBy; import io.appium.java_client.pagefactory.AppiumFieldDecorator; public class MyAccount extends Utility { private static AndroidDriver<AndroidElement> driver; public MyAccount(AndroidDriver<AndroidElement> driver) { this.driver = driver; PageFactory.initElements(new AppiumFieldDecorator(driver), this); } @AndroidFindBy(id = "com.tul.tatacliq:id/navigation_my_cliq") private AndroidElement myaccount; @AndroidFindBy(xpath = "//android.widget.ImageView[@index='1']") private AndroidElement image; @AndroidFindBy(id = "com.tul.tatacliq:id/txtSignUp") private AndroidElement signuplink; @AndroidFindBy(xpath = "//*[@text='Enter Email']") private AndroidElement emailaddress; @AndroidFindBy(xpath = "//*[@text='Enter Password']") private AndroidElement password; @AndroidFindBy(xpath = "//*[@text='SIGN UP']") private AndroidElement signupbutton; public void myAccount() { myaccount.click(); } public AndroidElement imageView() { return image; } public void signUpLink() { signuplink.click(); } public AndroidElement emailAddress() { return emailaddress; //emailaddress.sendKeys(getSaltString()+ "@mailinator.com"); } public void password() { password.sendKeys("<PASSWORD>"); } public void signUpButton() { signupbutton.click(); } } <file_sep>/com.appiumpractice/src/test/java/IOSAPP/RunIOSApp.java package IOSAPP; import java.io.IOException; import java.net.MalformedURLException; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.openqa.selenium.By; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.Status; import IOSBase.base; import IOSPOM.AlterPage; import IOSPOM.DatePickerPage; import IOSPOM.PickerViewPage; import IOSPOM.SegmentedPage; import IOSPOM.SliderPage; import IOSPOM.SteppersPage; import IOSPOM.SwitchPage; import Utilities.Utility; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.ios.IOSElement; public class RunIOSApp extends base { IOSDriver<IOSElement> driver; Logger logger = Logger.getLogger("Run"); // @BeforeSuite() // public void setUp() throws MalformedURLException { // driver = capabilities(); // PropertyConfigurator.configure("Log4j.properties"); // logger.info("Launching the IOS App and Execution Starts"); // } @Test(priority = 1) public void alertPage() throws IOException { driver = capabilities(); PropertyConfigurator.configure("Log4j.properties"); logger.info("Launching the IOS App and Execution Starts"); AlterPage alertpage = new AlterPage(driver); ExtentTest test = extent.createTest("Alert Page", "Performing Action on Alert Page"); test.log(Status.INFO, "Navigate to Alert Page and performing actions on it"); logger.info("Navigating to Alert Tab and Performing Action on it"); alertpage.alertTab(); alertpage.textEntry(); test.addScreenCaptureFromPath(Utility.getScreenshot(driver)); test.log(Status.INFO, "Clicking on Text Entry"); alertpage.textField(); test.addScreenCaptureFromPath(Utility.getScreenshot(driver)); test.log(Status.INFO, "Entering Title on it"); driver.findElement(By.name("OK")).click(); test.log(Status.INFO, "Clicking on OK button"); driver.navigate().back(); test.log(Status.INFO, "Navigate to Main Page"); Utility.scroll("up"); test.log(Status.INFO, "Scrolling down"); } @Test(priority = 2) public void stepperPage() throws IOException { SteppersPage stepperpage = new SteppersPage(driver); ExtentTest test = extent.createTest("Stepper Page", "Performing Action on Stepper Page"); test.log(Status.INFO, "Navigate to Stepper Page and performing actions on it"); logger.info("Navigating to Steppers Tab and Performing Action on it"); stepperpage.steppersTab(); test.addScreenCaptureFromPath(Utility.getScreenshot(driver)); stepperpage.Increment(); test.log(Status.INFO, "Increment the Value"); stepperpage.Increment(); List<IOSElement> list = stepperpage.incrementCount(); String rowFirstAfterIncrement = list.get(0).getText(); String rowSecond = list.get(1).getText(); test.log(Status.INFO, "Count after increment on First Row"); logger.info("Count after increment on First Row"); test.addScreenCaptureFromPath(Utility.getScreenshot(driver)); System.out.println(rowFirstAfterIncrement); test.log(Status.INFO, "Count of Second Row"); logger.info("Count of Second Row"); System.out.println(rowSecond); stepperpage.Decrement(); String rowFirstAfterDecrement = list.get(0).getText(); test.log(Status.INFO, "Count after decrement on First Row"); logger.info("Count after decrement on First Row"); test.addScreenCaptureFromPath(Utility.getScreenshot(driver)); System.out.println(rowFirstAfterDecrement); driver.navigate().back(); test.log(Status.INFO, "Navigating to Main Page"); } @Test(priority = 3) public void pickerDatePage() throws IOException { PickerViewPage pickerpage = new PickerViewPage(driver); ExtentTest test = extent.createTest("PickerDate Page", "Performing Action on PickerDate Page"); test.log(Status.INFO, "Navigate to PickerDate Page and performing actions on it"); logger.info("Navigating to Picker Tab and Performing Action on it"); pickerpage.pickerTab(); test.addScreenCaptureFromPath(Utility.getScreenshot(driver)); pickerpage.Wheel1(); test.log(Status.INFO, "Chaning the First Wheel Value"); pickerpage.Wheel2(); test.log(Status.INFO, "Changing the Second Wheel Value"); pickerpage.Wheel3(); test.addScreenCaptureFromPath(Utility.getScreenshot(driver)); test.log(Status.INFO, "Changing the Third Wheel Value"); driver.navigate().back(); test.log(Status.INFO, "Navigate to Main Page"); Utility.scroll("down"); test.log(Status.INFO, "Scrolling Up"); } @Test(priority = 4) public void datePage() throws IOException { DatePickerPage datepage = new DatePickerPage(driver); ExtentTest test = extent.createTest("DatePicker Page", "Performing Action on DatePicker Page"); test.log(Status.INFO, "Navigating to DatePicker Tab and Performing Action on it"); logger.info("Navigating to DatePicker Tab and Performing Action on it"); datepage.datePickerTab(); test.addScreenCaptureFromPath(Utility.getScreenshot(driver)); HashMap<String, Object> param = new HashMap<String, Object>(); param.put("order", "next"); param.put("offset", 0.15); param.put("element", driver.findElement(By.xpath("//XCUIElementTypePickerWheel[1]"))); driver.executeScript("mobile: selectPickerWheelValue", param); List<IOSElement> list2 = datepage.changeTime(); list2.get(2).sendKeys("35"); System.out.println(list2.get(2).getAttribute("value")); list2.get(3).sendKeys("PM"); test.log(Status.INFO, "Grabbing changed date and printing it on console"); logger.info("Grabbing changed date"); test.addScreenCaptureFromPath(Utility.getScreenshot(driver)); System.out.println(datepage.fetchDate().get(0).getAttribute("value")); driver.navigate().back(); test.log(Status.INFO, "Navigate to Main Page"); } @Test(priority = 5) public void segmentPage() throws IOException { SegmentedPage segmentpage = new SegmentedPage(driver); ExtentTest test = extent.createTest("Segment Page", "Performing Action on Segment Page"); test.log(Status.INFO, "Navigating to Segment Tab and Performing Action on it"); logger.info("Navigating to Segmented Tab and Performing Action on it"); segmentpage.segmentedTab(); test.addScreenCaptureFromPath(Utility.getScreenshot(driver)); segmentpage.settingsButton(); test.log(Status.INFO, "Selecting Hammer Icon button"); test.addScreenCaptureFromPath(Utility.getScreenshot(driver)); driver.navigate().back(); test.log(Status.INFO, "Navigate to Main Page"); } @Test(priority = 6) public void sliderPage() { SliderPage sliderpage = new SliderPage(driver); ExtentTest test = extent.createTest("Slider Page", "Performing Action on Slider Page"); test.log(Status.INFO, "Navigating to Slider Tab and Performing Action on it"); logger.info("Navigating to Slider Tab and Performing Action on it"); sliderpage.silderTab(); List<IOSElement> slider = sliderpage.changeSlider(); slider.get(0).sendKeys(".5%"); test.log(Status.INFO, "Moving the slider from its original position"); driver.navigate().back(); test.log(Status.INFO, "Navigate to Main Page"); Utility.scroll("up"); test.log(Status.INFO, "Scrolling down"); } @Test(priority = 7) public void switchPage() throws IOException { SwitchPage switchpage = new SwitchPage(driver); ExtentTest test = extent.createTest("Switch Page", "Performing Action on Switch Page"); test.log(Status.INFO, "Navigating to Switch Tab and Performing Action on it"); logger.info("Navigating to Switch Tab and Performing Action on it"); switchpage.switchTab(); test.addScreenCaptureFromPath(Utility.getScreenshot(driver)); switchpage.changeSwitch().get(0).click(); test.addScreenCaptureFromPath(Utility.getScreenshot(driver)); test.log(Status.INFO, "Changing switch from Yes to No"); logger.info("Execution completed"); } @AfterSuite public void tearDown() { ExtentTest test = extent.createTest("End Of Execution", "Execution is Completed"); test.log(Status.INFO, "Execution is Completed"); driver.quit(); } } <file_sep>/com.appiumpractice/src/main/java/AndroidPOM/CartPage.java package AndroidPOM; import java.util.List; import org.openqa.selenium.support.PageFactory; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.pagefactory.AndroidFindBy; import io.appium.java_client.pagefactory.AppiumFieldDecorator; public class CartPage { private static AndroidDriver<AndroidElement> driver; public CartPage(AndroidDriver<AndroidElement> driver) { this.driver = driver; PageFactory.initElements(new AppiumFieldDecorator(driver), this); } @AndroidFindBy(id = "com.androidsample.generalstore:id/productPrice") private List<AndroidElement> countaddedproductprice; @AndroidFindBy(id = "com.androidsample.generalstore:id/totalAmountLbl") private AndroidElement totalproductprice; @AndroidFindBy(className = "android.widget.CheckBox") private AndroidElement checkbox; @AndroidFindBy(xpath = "//*[@text='Please read our terms of conditions']") private AndroidElement termsofconditions; @AndroidFindBy(id = "android:id/button1") private AndroidElement closebutton; @AndroidFindBy(id = "com.androidsample.generalstore:id/btnProceed") private AndroidElement purchasebutton; public List<AndroidElement> countAddedProductPrice() { return countaddedproductprice; } public String totalProductPrice() { return totalproductprice.getText(); } public AndroidElement checkBox() { return checkbox; } public AndroidElement termsOfConditions() { return termsofconditions; } public void closeButton() { closebutton.click(); } public void purchaseButton() { purchasebutton.click(); } } <file_sep>/com.appiumpractice/src/main/java/IOSPOM/PickerViewPage.java package IOSPOM; import org.openqa.selenium.support.PageFactory; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.ios.IOSElement; import io.appium.java_client.pagefactory.AppiumFieldDecorator; import io.appium.java_client.pagefactory.iOSXCUITFindBy; public class PickerViewPage { private static IOSDriver<IOSElement> driver; public PickerViewPage(IOSDriver<IOSElement> driver) { this.driver = driver; PageFactory.initElements(new AppiumFieldDecorator(driver), this); } @iOSXCUITFindBy(accessibility = "Picker View") private IOSElement pickertab; @iOSXCUITFindBy(xpath = "//*[@name='Red color component value']") private IOSElement wheel1; @iOSXCUITFindBy(xpath = "//*[@name='Green color component value']") private IOSElement wheel2; @iOSXCUITFindBy(xpath = "//*[@name='Blue color component value']") private IOSElement wheel3; public void pickerTab() { pickertab.click(); } public void Wheel1() { wheel1.sendKeys("85"); } public void Wheel2() { wheel2.sendKeys("5"); } public void Wheel3() { wheel3.sendKeys("10"); } } <file_sep>/com.appiumpractice/src/test/java/TataCliqApp/CheckOutTest.java package TataCliqApp; import java.net.MalformedURLException; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.Test; import TataBase.baseTataCliq; import TataCliqAppPOM.CheckOutPage; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; public class CheckOutTest extends baseTataCliq { AndroidDriver<AndroidElement> driver; CheckOutPage product; @Test public void selectionOfProduct() throws MalformedURLException, InterruptedException { driver = capabilities(); product=new CheckOutPage(driver); product.myBag(); Thread.sleep(5000); // AndroidElement ele=product.viewDetails(); // WebDriverWait wait=new WebDriverWait(driver, 20); // wait.until(ExpectedConditions.elementToBeClickable(ele)); // ele.click(); //product.viewDetails(); product.scrollToSafe(); product.checkOut(); } } <file_sep>/com.appiumpractice/src/main/java/Utilities/ExcelReader.java package Utilities; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelReader { public FileInputStream fis = null; public FileOutputStream fout = null; private XSSFWorkbook workbook = null; private XSSFSheet sheet = null; private XSSFRow row = null; private XSSFCell cell = null; String path = null; public ExcelReader() throws IOException { path = System.getProperty("/Users/siddharthnashine/eclipse-workspace/com.appiumpractice/TestData/TestData.xlsx"); fis = new FileInputStream(path);// FileInputStream is used to read excel. workbook = new XSSFWorkbook(fis);// workbook is excel file include multiple sheet sheet = workbook.getSheetAt(0);// focusing on particular sheet in workbook. } //get number of rows in selected sheet. public int getSheetRows(String sheetName) { int index = workbook.getSheetIndex(sheetName); workbook.getSheetAt(index); return (sheet.getLastRowNum() + 1); } //get number of columns in selected sheet public int getSheetColumn(String sheetName) { int index = workbook.getSheetIndex(sheetName); workbook.getSheetAt(index); row = sheet.getRow(0); return (row.getLastCellNum()); } //get the values in cell by using sheet name and row number and column number public String getCellData(String sheetName, int rowNum, int colNum) { int index = workbook.getSheetIndex(sheetName); sheet = workbook.getSheetAt(index); row = sheet.getRow(rowNum); cell = row.getCell(colNum); return (cell.getStringCellValue()); } //get the values form cell by using the sheetname and row number and column name public String getCellData(String sheetName, int rowNum, String ColName) { int CellNum = -1; int index = workbook.getSheetIndex(sheetName); sheet = workbook.getSheetAt(index); for (int i = 0; i < getSheetColumn(sheetName); i++) { row = sheet.getRow(0); cell = row.getCell(i); if (cell.getStringCellValue().equals(ColName)) { CellNum = cell.getColumnIndex(); break; } } row = sheet.getRow(rowNum); cell = row.getCell(CellNum); return (cell.getStringCellValue()); } //write the data into sheet. public void setData(String sheetName, int ColNum, int rowNum, String str) { int index = workbook.getSheetIndex(sheetName); sheet = workbook.getSheetAt(index); row = sheet.getRow(rowNum); cell = row.createCell(ColNum); cell.setCellValue(str); try { fout = new FileOutputStream(path); try { workbook.write(fout); fout.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }<file_sep>/com.appiumpractice/src/main/java/IOSPOM/AlterPage.java package IOSPOM; import org.openqa.selenium.support.PageFactory; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.ios.IOSElement; import io.appium.java_client.pagefactory.AppiumFieldDecorator; import io.appium.java_client.pagefactory.iOSXCUITFindBy; public class AlterPage { private static IOSDriver<IOSElement> driver; public AlterPage(IOSDriver<IOSElement> driver) { this.driver = driver; PageFactory.initElements(new AppiumFieldDecorator(driver), this); } @iOSXCUITFindBy(accessibility = "Alert Views") private IOSElement alerttab; @iOSXCUITFindBy(xpath ="//*[@value='Text Entry']") private IOSElement textentry; @iOSXCUITFindBy(className ="XCUIElementTypeTextField") private IOSElement textfield; public void alertTab() { alerttab.click(); } public void textEntry() { textentry.click(); } public void textField() { textfield.sendKeys("hello"); } }<file_sep>/com.appiumpractice/src/test/java/IOSAPP/Run.java package IOSAPP; import java.net.MalformedURLException; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.openqa.selenium.By; import IOSBase.base; import IOSPOM.AlterPage; import IOSPOM.DatePickerPage; import IOSPOM.PickerViewPage; import IOSPOM.SegmentedPage; import IOSPOM.SliderPage; import IOSPOM.SteppersPage; import IOSPOM.SwitchPage; import Utilities.Utility; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.ios.IOSElement; public class Run extends base { public static void main(String[] args) throws MalformedURLException { Logger logger = Logger.getLogger("Run"); PropertyConfigurator.configure("Log4j.properties"); IOSDriver<IOSElement> driver = capabilities(); logger.info("Launching the App"); AlterPage elements = new AlterPage(driver); SteppersPage stepperpage = new SteppersPage(driver); PickerViewPage pickerpage = new PickerViewPage(driver); DatePickerPage datepage = new DatePickerPage(driver); SegmentedPage segmentpage = new SegmentedPage(driver); SliderPage sliderpage = new SliderPage(driver); SwitchPage switchpage = new SwitchPage(driver); //PageFactory.initElements(new AppiumFieldDecorator(driver), ""); logger.info("Navigating to Alert Tab and Performing Action on it"); elements.alertTab(); elements.textEntry(); elements.textField(); driver.findElement(By.name("OK")).click(); driver.navigate().back(); Utility.scroll("up"); logger.info("Navigating to Steppers Tab and Performing Action on it"); stepperpage.steppersTab(); stepperpage.Increment(); stepperpage.Increment(); List<IOSElement> list = stepperpage.incrementCount(); String rowFirstAfterIncrement = list.get(0).getText(); String rowSecond = list.get(1).getText(); logger.info("Count after increment on First Row"); System.out.println(rowFirstAfterIncrement); logger.info("Count of Second Row"); System.out.println(rowSecond); stepperpage.Decrement(); String rowFirstAfterDecrement = list.get(0).getText(); logger.info("Count after decrement on First Row"); System.out.println(rowFirstAfterDecrement); driver.navigate().back(); logger.info("Navigating to Picker Tab and Performing Action on it"); pickerpage.pickerTab(); pickerpage.Wheel1(); pickerpage.Wheel2(); pickerpage.Wheel3(); driver.navigate().back(); Utility.scroll("down"); logger.info("Navigating to DatePicker Tab and Performing Action on it"); datepage.datePickerTab(); HashMap<String, Object> param = new HashMap<String, Object>(); param.put("order", "next"); param.put("offset", 0.15); param.put("element", driver.findElement(By.xpath("//XCUIElementTypePickerWheel[1]"))); driver.executeScript("mobile: selectPickerWheelValue", param); List<IOSElement> list2 = datepage.changeTime(); list2.get(2).sendKeys("35"); System.out.println(list2.get(2).getAttribute("value")); list2.get(3).sendKeys("PM"); logger.info("Grabbing changed date"); System.out.println(datepage.fetchDate().get(0).getAttribute("value")); driver.navigate().back(); logger.info("Navigating to Segmented Tab and Performing Action on it"); segmentpage.segmentedTab(); segmentpage.settingsButton(); driver.navigate().back(); logger.info("Navigating to Slider Tab and Performing Action on it"); sliderpage.silderTab(); List<IOSElement> slider = sliderpage.changeSlider(); slider.get(0).sendKeys(".5%"); driver.navigate().back(); Utility.scroll("up"); logger.info("Navigating to Switch Tab and Performing Action on it"); switchpage.switchTab(); switchpage.changeSwitch().get(0).click(); logger.info("Execution completed"); } } <file_sep>/com.appiumpractice/src/test/java/TataCliqApp/testTataCliqApp.java package TataCliqApp; import java.net.MalformedURLException; import java.util.Random; import org.openqa.selenium.By; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import TataBase.baseTataCliq; import TataCliqAppPOM.MyAccount; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; public class testTataCliqApp extends baseTataCliq { AndroidDriver<AndroidElement> driver; MyAccount maccount; static String address; public static String getSaltString() { String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; StringBuilder salt = new StringBuilder(); Random rnd = new Random(); while (salt.length() < 10) { // length of the random string. int index = (int) (rnd.nextFloat() * SALTCHARS.length()); salt.append(SALTCHARS.charAt(index)); } String saltStr = salt.toString(); return saltStr;} @BeforeTest() public void setUp() throws MalformedURLException { driver = capabilities(); maccount=new MyAccount(driver); } @Test(priority=1) public void myAccount() throws InterruptedException { // MyAccount maccount=new MyAccount(driver); // WebElement image=maccount.imageView(); // WebDriverWait wait = new WebDriverWait(this.driver, 5); // wait.until(ExpectedConditions.elementToBeClickable(image)); // image.click(); maccount.myAccount(); } @Test(priority=2) public void signUp() throws InterruptedException { maccount.signUpLink(); AndroidElement e= driver.findElement(By.xpath("//*[@text='Enter Email']")); e.sendKeys(getSaltString()+ "@<EMAIL>.com"); address=e.getText(); System.out.println(address); maccount.password(); driver.hideKeyboard(); maccount.signUpButton(); Thread.sleep(2000); } @AfterTest() public void end() { System.out.println("end"); } } <file_sep>/com.appiumpractice/src/main/java/TataCliqAppPOM/Categories.java package TataCliqAppPOM; import org.openqa.selenium.support.PageFactory; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.pagefactory.AndroidFindBy; import io.appium.java_client.pagefactory.AppiumFieldDecorator; public class Categories { private static AndroidDriver<AndroidElement> driver; public Categories(AndroidDriver<AndroidElement> driver) { this.driver = driver; PageFactory.initElements(new AppiumFieldDecorator(driver), this); } @AndroidFindBy(id = "com.tul.tatacliq:id/navigation_categories") private AndroidElement category; @AndroidFindBy(xpath = "//android.widget.TextView[@text='Jewellery']") private AndroidElement jewellery; @AndroidFindBy(xpath = "//android.widget.TextView[@text='Precious Jewellery']") private AndroidElement preciousjewellery; @AndroidFindBy(xpath = "//android.widget.TextView[@text='All In Precious Jewellery']") private AndroidElement allpreciousjewellery; @AndroidFindBy(xpath = "//android.widget.LinearLayout[@index='1']") private AndroidElement toggleview; @AndroidFindBy(xpath = "//android.widget.TextView[@text='1']") private AndroidElement selectproduct; @AndroidFindBy(uiAutomator = "new UiScrollable(new UiSelector()" + ".resourceId(\"com.tul.tatacliq:id/recyclerViewProducts\")).scrollIntoView(" + "new UiSelector().text(\"P.C. Chandra Jewellers\"));") private AndroidElement scrolltojewel; @AndroidFindBy(xpath = "//android.widget.TextView[@text='Price Breakup']") private AndroidElement breakpricer; @AndroidFindBy(id = "com.tul.tatacliq:id/imgVShareProd") private AndroidElement shareproduct; @AndroidFindBy(id = "com.tul.tatacliq:id/image_view_close_dialog") private AndroidElement closebreakprice; @AndroidFindBy(uiAutomator = "new UiScrollable(new UiSelector()" + ".resourceId(\"com.tul.tatacliq:id/mainView\")).scrollIntoView(" + "new UiSelector().text(\"Change\"));") private AndroidElement scrolltochangelink; @AndroidFindBy(id = "com.tul.tatacliq:id/editTextEnterPinCode") private AndroidElement entercode; @AndroidFindBy(xpath = "//android.widget.TextView[@text='Submit']") private AndroidElement submit; @AndroidFindBy(id = "com.tul.tatacliq:id/textViewAddToCart") private AndroidElement addtocart; public void category() { category.click(); } public void jewelleryPage() { jewellery.click(); } public void preciousJewellery() { preciousjewellery.click(); } public void allPreciousJewellery() { allpreciousjewellery.click(); } public void toggleView() { toggleview.click(); } public void scrollToJewel() { scrolltojewel.click(); } public void breakPrice() { breakpricer.click(); } public void closeBreakPricerButton() { closebreakprice.click(); } public void shareProductButton() { shareproduct.click(); } public void scrollToChangeLink() { scrolltochangelink.click(); } public void enterCode() { entercode.sendKeys("560103"); } public void submitPin() { submit.click(); } public void addToCart() { addtocart.click(); } } <file_sep>/com.appiumpractice/src/main/java/Utilities/Utility.java package Utilities; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.apache.commons.io.FileUtils; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import IOSBase.base; public class Utility extends base { // public static IOSDriver<IOSElement> driver; public static void scroll(String to) { JavascriptExecutor js = (JavascriptExecutor) driver; Map<String, String> params = new HashMap<String, String>(); params.put("direction", to); js.executeScript("mobile: swipe", params); } public static String getScreenshot(WebDriver driver) { TakesScreenshot ts = (TakesScreenshot) driver; File src = ts.getScreenshotAs(OutputType.FILE); String path = System.getProperty("user.dir") + "/Screenshot/" + System.currentTimeMillis() + ".png"; File destination = new File(path); try { FileUtils.copyFile(src, destination); } catch (IOException e) { System.out.println("Capture Failed " + e.getMessage()); } return path; } public static String getSaltString() { String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; StringBuilder salt = new StringBuilder(); Random rnd = new Random(); while (salt.length() < 10) { // length of the random string. int index = (int) (rnd.nextFloat() * SALTCHARS.length()); salt.append(SALTCHARS.charAt(index)); } String saltStr = salt.toString(); return saltStr;} } <file_sep>/com.appiumpractice/src/main/java/IOSPOM/DatePickerPage.java package IOSPOM; import java.util.List; import org.openqa.selenium.support.PageFactory; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.ios.IOSElement; import io.appium.java_client.pagefactory.AppiumFieldDecorator; import io.appium.java_client.pagefactory.iOSXCUITFindBy; public class DatePickerPage { private static IOSDriver<IOSElement> driver; public DatePickerPage(IOSDriver<IOSElement> driver) { this.driver = driver; PageFactory.initElements(new AppiumFieldDecorator(driver), this); } @iOSXCUITFindBy(accessibility = "Date Picker") private IOSElement datetab; @iOSXCUITFindBy(className = "XCUIElementTypePickerWheel") private List<IOSElement> datepickerwheel; @iOSXCUITFindBy(className = "XCUIElementTypeStaticText") private List<IOSElement> fetchdate; public void datePickerTab(){ datetab.click(); } public List<IOSElement> changeTime() { return datepickerwheel; } public List<IOSElement> fetchDate(){ return fetchdate; } } <file_sep>/com.appiumpractice/src/main/java/IOSPOM/SteppersPage.java package IOSPOM; import java.util.List; import org.openqa.selenium.support.PageFactory; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.ios.IOSElement; import io.appium.java_client.pagefactory.AppiumFieldDecorator; import io.appium.java_client.pagefactory.iOSXCUITFindBy; public class SteppersPage { private static IOSDriver<IOSElement> driver; public SteppersPage(IOSDriver<IOSElement> driver) { this.driver = driver; PageFactory.initElements(new AppiumFieldDecorator(driver), this); } @iOSXCUITFindBy(accessibility = "Steppers") private IOSElement stepperstab; @iOSXCUITFindBy(accessibility = "Increment") private IOSElement increment; @iOSXCUITFindBy(className ="XCUIElementTypeStaticText") private List<IOSElement> incrementcount; @iOSXCUITFindBy(accessibility = "Decrement") private IOSElement decrement; public void steppersTab() { stepperstab.click(); } public void Increment() { increment.click(); } public List<IOSElement> incrementCount() { return incrementcount; } public void Decrement() { decrement.click(); } }
3e434fb7913eeb936463a2c28882dd6bfb01992c
[ "Java" ]
15
Java
nassiddharth/Appium
cf95a7870e866b12512679d1d91083b54948d5c6
e5adc9e6fcff9b843e35935f210ab336a5b69838
refs/heads/master
<repo_name>steroids/swagger<file_sep>/tests/unit/SwaggerTest.php <?php namespace steroids\swagger\tests\unit; use PHPUnit\Framework\TestCase; use steroids\swagger\extractors\AstExtractor; use steroids\swagger\extractors\ClassMethodExtractor; use steroids\swagger\extractors\ModelExtractor; use steroids\swagger\extractors\ObjectExtractor; use steroids\swagger\models\SwaggerContext; use steroids\swagger\tests\mocks\AstController; use steroids\swagger\tests\mocks\BarObject; use steroids\swagger\tests\mocks\FirstController; use steroids\swagger\tests\mocks\FooModel; use steroids\swagger\tests\mocks\ScopeController; use steroids\swagger\tests\mocks\ScopeControllerv; use steroids\swagger\tests\mocks\TestController; use yii\helpers\ArrayHelper; use yii\helpers\Json; class SwaggerTest extends TestCase { public function testObject() { $property = ObjectExtractor::extract(new SwaggerContext(['className' => BarObject::class])); $this->assertFalse($property->isPrimitive); $this->assertEquals(1, count($property->items)); $this->assertEquals('count', $property->items[0]->name); $this->assertEquals('Count items', $property->items[0]->export()['description']); $this->assertEquals('number', $property->items[0]->export()['type']); } public function testModel() { $property = ModelExtractor::extract(new SwaggerContext(['className' => FooModel::class])); $this->assertFalse($property->isPrimitive); $this->assertEquals(2, count($property->items)); $this->assertEquals('id', $property->items[0]->name); $this->assertEquals('number', $property->items[0]->export()['type']); $this->assertEquals('Primary key', $property->items[0]->export()['description']); $this->assertEquals('name', $property->items[1]->name); $this->assertEquals('string', $property->items[1]->export()['type']); $this->assertEquals('Foo name', $property->items[1]->export()['description']); $this->assertEquals('object', $property->export()['type']); } public function testModelLabelFromMeta() { $property = ModelExtractor::extract(new SwaggerContext(['className' => FooModel::class, 'scopes' => [FooModel::SCOPE_DETAIL]])); $this->assertEquals('title', $property->items[3]->name); $this->assertEquals('{"type":"string","description":"Title from meta"}', Json::encode($property->items[3]->export())); } public function testMethodPhpdoc() { $context = new SwaggerContext(['className' => FirstController::class]); $property = ClassMethodExtractor::extract($context->child(['isInput' => true]), 'actionIndex'); $this->assertEquals('id,title', implode(',', ArrayHelper::getColumn($property->items, 'name'))); $property = ClassMethodExtractor::extract($context->child(['isInput' => false]), 'actionIndex'); $this->assertEquals('id,name', implode(',', ArrayHelper::getColumn($property->items, 'name'))); } public function testMethodAst() { $properties = AstExtractor::extract(new SwaggerContext(['className' => FirstController::class]), 'actionGetDetail'); $this->assertEquals( 'foo,flag,6', implode(',', ArrayHelper::getColumn($properties[0]->items, 'name')) ); $this->assertEquals( 'Foo property,Start comment before flag,Multiline comment for "six" value_Second line here...', str_replace("\n", '_', implode(',', ArrayHelper::getColumn($properties[0]->items, 'description'))) ); $this->assertEquals( ',,{"foo": 99}', implode(',', ArrayHelper::getColumn($properties[0]->items, 'example')) ); $this->assertEquals( 'model,model2,model3,confirm,confirms,confirmShort,confirmsShort,title,count,total,strings', implode(',', ArrayHelper::getColumn($properties[0]->items[0]->items, 'name')) ); $this->assertEquals( 'Foo model,,Model3 custom type,Confirm model with id 1,Confirms list,,,,,,', implode(',', ArrayHelper::getColumn($properties[0]->items[0]->items, 'description')) ); $this->assertEquals( 'id,name', // model implode(',', ArrayHelper::getColumn($properties[0]->items[0]->items[0]->items, 'name')) ); $this->assertEquals( 'id,name', // model2 implode(',', ArrayHelper::getColumn($properties[0]->items[0]->items[1]->items, 'name')) ); $this->assertEquals( 'count', // model3 implode(',', ArrayHelper::getColumn($properties[0]->items[0]->items[2]->items, 'name')) ); } public function testScope() { $properties = AstExtractor::extract(new SwaggerContext(['className' => TestController::class]), 'actionScope'); $this->assertEquals('foo', $properties[0]->items[0]->name); $this->assertEquals('Model with scope: SCOPE_DETAIL', $properties[0]->items[0]->description); $this->assertEquals( 'id,name,role,title', implode(',', ArrayHelper::getColumn($properties[0]->items[0]->items, 'name')) ); $this->assertEquals('bar', $properties[0]->items[1]->name); $this->assertEquals('Bar with scope: SCOPE_DEFAULT', $properties[0]->items[1]->description); $this->assertEquals( 'id,name', implode(',', ArrayHelper::getColumn($properties[0]->items[1]->items, 'name')) ); } public function testGenericTypeInput() { $property = ClassMethodExtractor::extract(new SwaggerContext(['className' => TestController::class, 'isInput' => true]), 'actionGenericType'); $this->assertTrue($property->isEmpty()); } public function testGenericType() { $properties = AstExtractor::extract(new SwaggerContext(['className' => TestController::class]), 'actionGenericType'); $this->assertEquals('items', $properties[0]->items[0]->name); $this->assertEquals(true, $properties[0]->items[0]->isArray); $this->assertEquals(2, $properties[0]->items[0]->arrayDepth); $this->assertEquals('{"type":"object","properties":{"items":{"type":"array","items":{"type":"array","items":{"type":"object","properties":{"count":{"type":"number","description":"Count items"}}}}}}}', json_encode($properties[0]->export())); } public function testCustomGetParam() { $property = ClassMethodExtractor::extract(new SwaggerContext(['className' => TestController::class, 'isInput' => true]), 'actionCustomGetParam'); $this->assertEquals('{"type":"object","properties":{"pageSize":{"type":"number","description":"Page size"}}}', json_encode($property->export())); $property = ClassMethodExtractor::extract(new SwaggerContext(['className' => TestController::class, 'isInput' => true]), 'actionCustomGetAliasParam'); $this->assertEquals('{"type":"object","properties":{"pageSize":{"type":"number","description":"Page size"}}}', json_encode($property->export())); } public function testCustomPostParam() { $property = ClassMethodExtractor::extract(new SwaggerContext(['className' => TestController::class, 'isInput' => true]), 'actionCustomPostParam'); $this->assertEquals('{"type":"object","properties":{"query":{"type":"string","description":"Search query"}}}', json_encode($property->export())); } public function testToFrontendCall() { $property = ClassMethodExtractor::extract(new SwaggerContext(['className' => TestController::class]), 'actionToFrontend'); $this->assertEquals('{"type":"object","properties":{"id":{"type":"number","description":"Primary key"},"name":{"type":"string","description":"Foo name"},"role":{"type":"string"},"title":{"type":"string","description":"Title from meta"}}}', json_encode($property->export())); } } <file_sep>/extractors/TypeExtractor.php <?php namespace steroids\swagger\extractors; use steroids\swagger\models\SwaggerContext; use steroids\swagger\models\SwaggerProperty; use yii\base\Exception; use yii\helpers\ArrayHelper; class TypeExtractor { const TYPE_ALIASES = [ 'int' => 'integer', 'bool' => 'boolean', 'double' => 'float', 'true' => 'boolean', 'false' => 'boolean', ]; /** * @param SwaggerContext $context * @param string $rawType * @return SwaggerProperty * @throws Exception * @throws \ReflectionException */ public static function extract(SwaggerContext $context, string $rawType) { // Detect generic array if (preg_match('/array<(([^>,]+),\s*)?([^>]+)>/i', $rawType, $match)) { // TODO How to says, that is key-array object?.. $property = static::extract($context, $match[3]); $property->isArray = true; $property->arrayDepth++; return $property; } // Get only one type // TODO Support multiple types $separatorPos = strpos($rawType, '|'); if ($separatorPos !== false) { $rawType = substr($rawType, 0, $separatorPos); } // Detect array $isArray = preg_match('/\[\]$/', $rawType); $rawType = preg_replace('/\[\]$/', '', $rawType); // Normalize for single type $rawType = ArrayHelper::getValue(self::TYPE_ALIASES, $rawType, $rawType); // Check is single $isPrimitive = ArrayHelper::keyExists($rawType, SwaggerProperty::SINGLE_MAPPING); // Create instance $property = !$isPrimitive && $rawType ? ClassExtractor::extract($context, $rawType) : new SwaggerProperty(['phpType' => $rawType]); $property->isPrimitive = $isPrimitive; $property->isArray = $isArray; return $property; } }<file_sep>/extractors/ClassAttributeExtractor.php <?php namespace steroids\swagger\extractors; use steroids\core\base\BaseSchema; use steroids\core\base\Type; use steroids\swagger\helpers\ExtractorHelper; use steroids\swagger\models\SwaggerContext; use steroids\swagger\models\SwaggerProperty; use yii\db\ActiveQueryInterface; use yii\db\ActiveRecord; use yii\helpers\ArrayHelper; class ClassAttributeExtractor { public static function prepare(SwaggerContext $context, string $attribute) { $rawType = ''; $description = null; $classInfo = new \ReflectionClass($context->className); $childContext = $context->child([ 'attribute' => $attribute, 'fields' => $context->fields, ]); // Find is class php doc (or parent classes) $nowClassInfo = $classInfo; while (true) { foreach (explode("\n", $nowClassInfo->getDocComment()) as $line) { if (!preg_match('/@property(-read)/', $line)) { continue; } $parsedLine = ExtractorHelper::parseCommentType($line); if ($parsedLine['variable'] === $attribute && $parsedLine['type']) { $rawType = $parsedLine['type']; if (!$description && $parsedLine['description']) { $description = $parsedLine['description']; } break; } } // TODO // TODO // TODO foreach lines... // TODO // TODO // if (preg_match('/@property(-read)? +([^ |\n]+) \$' . preg_quote($attribute) . '(\s|\n)[^\n]*/u', $nowClassInfo->getDocComment(), $matchClass)) { // $rawType = $matchClass[2]; // $parsedLine = ExtractorHelper::parseCommentType($matchClass[0]); // if ($parsedLine['type']) { // $rawType = $parsedLine['type']; // if (!$description && $parsedLine['description']) { // $description = $parsedLine['description']; // } // } // } $nowClassInfo = $nowClassInfo->getParentClass(); if (!$nowClassInfo) { break; } } // Find in class property php doc if (!$rawType) { $propertyInfo = $classInfo->hasProperty($attribute) ? $classInfo->getProperty($attribute) : null; if ($propertyInfo) { if ($propertyInfo->getType() && $propertyInfo->getType()->getName()) { $rawType = $propertyInfo->getType()->getName(); } foreach (explode("\n", $propertyInfo->getDocComment()) as $line) { $parsedLine = ExtractorHelper::parseCommentType($line); if (in_array($parsedLine['tag'], ['var', 'type'])) { if (!$rawType && $parsedLine['type']) { $rawType = $parsedLine['type']; $childContext->className = $propertyInfo->getDeclaringClass()->getName(); } } if (!$description && $parsedLine['description']) { $description = $parsedLine['description']; } } } } // Find in getter method if (!$rawType || !$description) { $getter = 'get' . ucfirst($attribute); $methodInfo = $classInfo->hasMethod($getter) ? $classInfo->getMethod($getter) : null; if ($methodInfo) { if (!$rawType && preg_match('/@return +([^ |\n]+)/u', $methodInfo->getDocComment(), $matchMethod)) { $rawType = $matchMethod[1]; $childContext->className = $methodInfo->getDeclaringClass()->getName(); $childContext->comment = $methodInfo->getDocComment(); } if (!$description) { foreach (explode("\n", $methodInfo->getDocComment()) as $line) { $parsedLine = ExtractorHelper::parseCommentType($line); if ($parsedLine['description']) { $description = $parsedLine['description']; break; } } } } } // Normalize $rawType = trim($rawType); return [$childContext, $rawType, $description]; } /** * @param SwaggerContext $context * @param string $attribute * @return SwaggerProperty * @throws \ReflectionException * @throws \yii\base\Exception */ public static function extract(SwaggerContext $context, string $attribute): SwaggerProperty { $context->attribute = $attribute; list($childContext, $rawType, $description) = static::prepare($context, $attribute); // Normalize $rawType = trim($rawType); // Relation detect if ($rawType && class_exists($rawType) && is_subclass_of($rawType, ActiveQueryInterface::class)) { $relation = ExtractorHelper::safeGetRelation($childContext->className, $attribute); if ($relation) { $relationContext = $childContext->child([ 'className' => $relation->modelClass, 'attribute' => $attribute, 'fields' => $childContext->fields, ]); $property = ModelExtractor::extract($relationContext); $property->name = $attribute; $property->isArray = $relation->multiple; return $property; } } // Single $property = TypeExtractor::extract($childContext, $rawType); $property->name = $attribute; $property->phpdoc = $childContext->comment; // Get description from phpdoc if (!$property->description && $description) { $property->description = $description; } // Get description, label from relation attribute if (is_subclass_of($childContext->className, ActiveRecord::class)) { $relation = ExtractorHelper::safeGetRelation($childContext->className, $attribute); if ($relation) { $tmpProperty = static::extract($context, array_values($relation->link)[0]); if (!$property->description) { $property->description = $tmpProperty->description; } } } // Meta model if (method_exists($childContext->className, 'meta') && ($meta = ArrayHelper::getValue($childContext->className::meta(), $attribute)) && ( is_subclass_of($childContext->className, \yii\base\Model::class) || is_subclass_of($childContext->className, BaseSchema::class) )) { /** @var array $meta */ // Required if ($childContext->isInput) { $property->isRequired = ArrayHelper::getValue($meta, 'isRequired') === true; } // Description & example if (!$property->description) { $property->description = ArrayHelper::getValue($meta, 'label'); } if (!$property->example) { $property->example = ArrayHelper::getValue($meta, 'example'); } // Type props /** @var Type $appType */ \Yii::$app->types ->getTypeByModel($childContext->className, $attribute) ->prepareSwaggerProperty($childContext->className, $attribute, $property); } return $property; } }<file_sep>/helpers/TypeScriptHelper.php <?php namespace steroids\swagger\helpers; use steroids\gii\helpers\GiiHelper; use steroids\swagger\models\SwaggerAction; use steroids\swagger\models\SwaggerProperty; use steroids\swagger\models\SwaggerRefsStorage; use yii\helpers\ArrayHelper; use yii\helpers\Inflector; use yii\helpers\Json; use yii\helpers\StringHelper; abstract class TypeScriptHelper { /** * @param SwaggerProperty[] $properties * @param string $relativePath * @param SwaggerRefsStorage $refsStorage * @return string */ public static function generateInterfaces(array $properties, string $relativePath, SwaggerRefsStorage $refsStorage, $imports = [], $isExportDefault = false) { $interfaces = []; foreach ($properties as $name => $property) { if ($refsStorage->getRef($name) && !$isExportDefault) { $importPath = $refsStorage->getRefRelativePath($name, $relativePath); $importPath = preg_replace('/\.(ts|tsx|js|jsx)$/', '', $importPath); $imports[] = "import I$name from '$importPath';"; } else { $usedRefs = []; $interfaces[] = 'export ' . ($isExportDefault ? 'default ' : '') . "interface I$name " . $property->exportTsType('', true, $usedRefs) . "\n"; foreach ($usedRefs as $refName) { $importPath = $refsStorage->getRefRelativePath($refName, $relativePath); $importPath = preg_replace('/\.(ts|tsx|js|jsx)$/', '', $importPath); $interfaceName = StringHelper::basename($importPath); $imports[] = "import $interfaceName from '$importPath';"; } } } $imports = array_unique($imports); return implode( "\n", [ ...$imports, ...(!empty($imports) ? [''] : []), ...$interfaces, ] ); } /** * @param SwaggerAction[] $actions * @param $relativePath * @param SwaggerRefsStorage $refsStorage * @return string */ public static function generateApi($actions, $relativePath, $refsStorage) { $properties = []; foreach ($actions as $action) { if ($action->inputRefName) { $properties[$action->inputRefName] = $action->inputProperty; } if ($action->outputRefName) { $properties[$action->outputRefName] = $action->outputProperty; } } // TODO Move gii method o core? $utilsPath = GiiHelper::getRelativePath($relativePath, 'utils'); return implode( "\n", [ static::generateInterfaces($properties, $relativePath, $refsStorage, [ "import {createMethod} from '$utilsPath';", ]), ...array_map( function ($action) { $input = $action->inputTsType && $action->inputTsType !== 'any' ? 'I' . $action->inputTsType : 'null'; $output = $action->outputTsType && $action->outputTsType !== 'any' ? 'I' . $action->outputTsType : 'null'; $method = lcfirst(Inflector::id2camel($action->actionId)); return "export const $method = createMethod<$input, $output>({\n" . " method: '$action->httpMethod',\n" . " url: '$action->url',\n" . "});\n"; }, $actions, ), ] ); } /** * @param array $json * @return string * @throws \Exception */ public static function jsonToTypes(array $json) { $result = []; foreach (ArrayHelper::getValue($json, 'definitions', []) as $name => $definition) { $result[] = "export interface I$name " . static::property($definition, 1); } return implode("\n\n", $result); } /** * @param string $text * @param int $level * @return string */ protected static function jsdoc(string $text, $level = 0) { return static::indent($level) . implode("\n" . static::indent($level), [ '/**', ...array_map(fn(string $line) => ' * ' . $line, explode("\n", $text)), ' */', ]) . "\n"; } /** * @param array $property * @param int $level * @return string * @throws \Exception */ protected static function property(array $property, $level = 0) { $ref = ArrayHelper::getValue($property, '$ref'); if ($ref) { return 'I' . StringHelper::basename($ref); } switch (ArrayHelper::getValue($property, 'type')) { case 'object': $result = []; foreach ($property['properties'] as $name => $property) { $item = ''; $doc = array_filter([ ArrayHelper::getValue($property, 'description'), ArrayHelper::getValue($property, 'example') ? '@example ' . ArrayHelper::getValue($property, 'example') : null, ]); if (!empty($doc)) { $item .= static::jsdoc(implode("\n", $doc), $level); } $item .= static::indent($level) . $name . '?: ' . static::property($property, $level + 1) . "\n"; $result[] = $item; } return "{\n\n" . implode("\n", $result) . static::indent($level - 1) . '}'; case 'array': if (!empty($property['items'])) { return trim(static::property($property['items'], $level)) . '[]'; } else { return 'array'; } case 'number': case 'boolean': case 'string': return implode(' | ', [ ...array_map( fn(string $value) => str_replace('"', "'", Json::encode($value)), ArrayHelper::getValue($property, 'enum', []) ), $property['type'] ]); } throw new \Exception('Unsupported type: ' . Json::encode($property)); } protected static function indent($level) { return str_repeat(' ', $level); } }<file_sep>/tests/bootstrap.php <?php define('STEROIDS_ROOT_DIR', realpath(__DIR__ . '/../../..')); define('YII_ENV', 'test'); $config = require STEROIDS_ROOT_DIR . '/bootstrap.php'; new \steroids\core\base\ConsoleApplication($config); <file_sep>/events/SwaggerExportEvent.php <?php namespace steroids\swagger\events; use yii\base\Event; class SwaggerExportEvent extends Event { public $json; } <file_sep>/extractors/SchemaExtractor.php <?php namespace steroids\swagger\extractors; use steroids\core\base\BaseSchema; use steroids\swagger\models\SwaggerContext; use steroids\swagger\models\SwaggerProperty; use yii\helpers\StringHelper; class SchemaExtractor { /** * @param SwaggerContext $context * @param array|null $fields * @return SwaggerProperty * @throws \yii\base\Exception */ public static function extract(SwaggerContext $context, array $fields = null) { if ($context->isInput) { return new SwaggerProperty(); } $className = $context->className; /** @var BaseSchema $schema */ $schema = new $className(); // Refs if ($context->refsStorage && !$fields) { $refKey = StringHelper::basename($className); if ($context->refsStorage->hasRef($refKey)) { return $context->refsStorage->getRef($refKey)->clone(); } } if ($fields === null) { $fields = $schema->fields(); } $items = []; foreach ($fields as $key => $value) { if (is_int($key) && is_string($value)) { $key = $value; } $childContext = $context->child([ 'attribute' => $key, ]); if (is_array($value)) { // Relation list($subContext) = ClassAttributeExtractor::prepare($context, 'model'); $items[] = ClassAttributeExtractor::extract($subContext, $key); } elseif (is_string($value)) { $attributes = explode('.', $value); if (count($attributes) > 1) { $childContext = ModelExtractor::prepareContextByPath($childContext, $attributes); $items[] = ClassAttributeExtractor::extract($childContext, $childContext->attribute); } else { $attribute = $value; if ($schema->canGetProperty($attribute, true, false)) { $items[] = ClassAttributeExtractor::extract($childContext, $attribute); } else { $rootProperty = ClassAttributeExtractor::extract($childContext, 'model'); if ($rootProperty->items && count($rootProperty->items) === 1) { $items[] = $rootProperty->items[0]; } } } } } $resultProperty = new SwaggerProperty([ 'items' => $items, ]); // Refs if (isset($refKey)) { $resultProperty->refName = $refKey; $resultProperty->refsStorage = $context->refsStorage; $context->refsStorage->setRef($className, $refKey, $resultProperty); } return $resultProperty; } }<file_sep>/models/SwaggerRefsStorage.php <?php namespace steroids\swagger\models; use steroids\core\helpers\ClassFile; use steroids\gii\helpers\GiiHelper; use yii\base\BaseObject; use yii\helpers\ArrayHelper; class SwaggerRefsStorage extends BaseObject { /** * @var SwaggerProperty[] */ protected array $properties = []; protected array $classNames = []; protected array $counter = []; public function hasRef(string $name): bool { return !!ArrayHelper::getValue($this->properties, $name); } public function getAll() { return $this->properties; } /** * @param string $name * @return SwaggerProperty * @throws \Exception */ public function getRef(string $name) { return ArrayHelper::getValue($this->properties, $name); } public function getRefRelativePath(string $name, $cwd = null) { // Get property class name $className = ArrayHelper::getValue($this->classNames, $name); if (!$className) { return null; } // Detect module id by class name $classFile = ClassFile::createByClass(ltrim($className, '\\'), ''); if (!$classFile->moduleId) { return null; } $path = str_replace('.', DIRECTORY_SEPARATOR, $classFile->moduleId) . DIRECTORY_SEPARATOR . 'interfaces' . DIRECTORY_SEPARATOR . 'I' . $name . '.ts'; if ($cwd) { // TODO Move gii method o core? $path = GiiHelper::getRelativePath($cwd, $path); } return $path; } public function getRefCount(string $name) { return ArrayHelper::getValue($this->counter, $name, 0); } public function increaseRefCount(string $name) { $this->counter[$name] = ArrayHelper::getValue($this->counter, $name, 0) + 1; } public function isInDefinitions(string $name): bool { return true; //return ArrayHelper::getValue($this->counter, $name, 0) > 1; } public function setRef(string $className, string $name, SwaggerProperty $value) { $this->properties[$name] = $value; $this->classNames[$name] = $className; } public function exportDefinitions() { $result = []; foreach ($this->properties as $name => $property) { if ($this->isInDefinitions($name)) { $result[$name] = $property->export(true); } } return !empty($result) ? $result : (object)[]; } } <file_sep>/commands/SwaggerCommand.php <?php namespace steroids\swagger\commands; use steroids\swagger\components\SwaggerBuilder; use yii\console\Controller; class SwaggerCommand extends Controller { public function actionTypes() { (new SwaggerBuilder())->buildTypes(); } } <file_sep>/tests/mocks/TestController.php <?php namespace steroids\swagger\tests\mocks; use yii\web\Controller; class TestController extends Controller { public function actionScope() { return [ /** @type FooModel Model with scope: SCOPE_DETAIL */ 'foo' => new FooModel(), /** @type FooModel Bar with scope: SCOPE_DEFAULT */ 'bar' => new FooModel(), ]; } public function actionGenericType() { /** @var array<string, BarObject[]> $items */ $items = [ 'str' => [ new BarObject(), ], ]; return [ 'items' => $items, ]; } /** * @param int|null $pageSize Page size * @return int */ public function actionCustomGetParam(int $pageSize = null): int { return 1; } /** * @param-get int $pageSize Page size * @return int */ public function actionCustomGetAliasParam(): int { return 1; } /** * @param-post $query Search query * @return int */ public function actionCustomPostParam(): int { return 1; } public function actionToFrontend() { $model = FooModel::findOrPanic(['id' => 1]); return $model->toFrontend(null, null, [FooModel::SCOPE_DETAIL]); } } <file_sep>/typescript/utils.ts interface IApiSendConfig { method?: 'get' | 'post' | 'put' | 'delete' | string, url?: string, params?: Record<string, unknown>, } interface IResponseWrapper<IResponse> { data: IResponse, status?: number, headers?: Record<string, unknown>, [key: string]: unknown, } interface IApiComponent { send?: <IResponse>(config: Record<string, unknown>) => Promise<IResponseWrapper<IResponse>>, } // eslint-disable-next-line import/prefer-default-export export const createMethod = <IRequest, IResponse = null>( config: IApiSendConfig, ) => ( api: IApiComponent, params: IRequest = null, options: Record<string, unknown> = null, ): Promise<IResponseWrapper<IResponse>> => api.send<IResponse>({ ...config, params, options, }); <file_sep>/controllers/SwaggerController.php <?php namespace steroids\swagger\controllers; use steroids\swagger\components\SwaggerBuilder; use steroids\swagger\helpers\TypeScriptHelper; use yii\helpers\Html; use yii\helpers\Url; use yii\web\Controller; class SwaggerController extends Controller { public $redocUrl = 'https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js'; public static function siteMap($baseUrl = 'api') { return [ 'swagger' => [ 'label' => 'Документация', 'url' => ['index'], 'urlRule' => $baseUrl, 'items' => [ 'json' => [ 'url' => ['json'], 'urlRule' => $baseUrl . '/swagger.json', ], 'types' => [ 'url' => ['types'], 'urlRule' => $baseUrl . '/types', ], ], ], ]; } /** * @return string * @throws \yii\base\InvalidConfigException */ public function actionIndex() { $this->layout = '@steroids/core/views/layout-blank'; $this->view->registerJsFile($this->redocUrl); return $this->renderContent( Html::tag('redoc', '', ['spec-url' => Url::to(['/swagger/swagger/json'])]) ); } /** * @return array * @throws \yii\base\InvalidConfigException * @throws \Exception */ public function actionJson() { //\Yii::$app->response->format = Response::FORMAT_JSON; return $this->generateJson(); } /** * @return string * @throws \Exception */ public function actionTypes() { return '<pre>' . TypeScriptHelper::jsonToTypes($this->generateJson()); } protected function generateJson() { return (new SwaggerBuilder())->buildJson(); } } <file_sep>/extractors/AstExtractor.php <?php namespace steroids\swagger\extractors; use PhpParser\Comment; use PhpParser\Node\Expr\Array_; use PhpParser\Node\Expr\ArrayItem; use PhpParser\Node\Expr\Assign; use PhpParser\Node\Expr\ClassConstFetch; use PhpParser\Node\Expr\ConstFetch; use PhpParser\Node\Expr\MethodCall; use PhpParser\Node\Expr\New_; use PhpParser\Node\Expr\StaticCall; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Identifier; use PhpParser\Node\Scalar\DNumber; use PhpParser\Node\Scalar\LNumber; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Stmt\Class_; use PhpParser\Node\Stmt\ClassMethod; use PhpParser\Node\Stmt\Return_; use PhpParser\ParserFactory; use steroids\core\base\Model; use steroids\swagger\helpers\ExtractorHelper; use steroids\swagger\models\SwaggerContext; use steroids\swagger\models\SwaggerProperty; use yii\base\Exception; abstract class AstExtractor { /** * @param SwaggerContext $context * @param string $method * @return array|SwaggerProperty[] * @throws Exception * @throws \ReflectionException */ public static function extract(SwaggerContext $context, string $method) { $classInfo = new \ReflectionClass($context->className); $classCode = file_get_contents($classInfo->getFileName()); $parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7); $ast = $parser->parse($classCode); $classNode = static::findFirst($ast, function ($node) use ($classInfo) { return $node instanceof Class_ && $node->name->name === $classInfo->getShortName(); }); /** @var ClassMethod $methodNode */ $methodNode = static::findFirst($classNode, function ($node) use ($method) { return $node instanceof ClassMethod && $node->name->name === $method; }); if (!$methodNode) { return []; } /** @var Variable[] $variables */ $variables = []; /** @var Assign[] $assignNodes */ $assignNodes = static::findAll($methodNode, function ($node) use ($method) { return $node instanceof Assign; }); foreach ($assignNodes as $assignNode) { if ($assignNode->var instanceof Variable) { $variables[$assignNode->var->name] = $assignNode; } } /** @var SwaggerProperty[] $properties */ $properties = []; foreach ($methodNode->stmts as $stmt) { if ($stmt instanceof Return_) { $properties[] = static::nodeToProperty($context, $stmt->expr, $variables); } } return array_filter($properties); } /** * @param SwaggerContext $context * @param $node * @param Variable[] $variables * @return SwaggerProperty|string[]|null * @throws Exception * @throws \ReflectionException */ protected static function nodeToProperty(SwaggerContext $context, $node, array $variables) { // Array list if ($node instanceof Array_ && !$context->isInput) { $property = new SwaggerProperty(); $property->items = []; foreach ($node->items as $i => $item) { $subProperty = static::nodeToProperty($context->child(), $item, $variables); if ($subProperty) { if (!$subProperty->name) { $subProperty->name = (string)$i; } $property->items[] = $subProperty; } } return $property; } // Array item if ($node instanceof ArrayItem) { $parsedComment = static::parseNodeComments($context, $node); $property = static::nodeToProperty($context, $node->value, $variables); if ($parsedComment['property']) { $parsedComment['property']->name = $property->name; $property = $parsedComment['property']; } if ($property) { $property->description = implode("\n", $parsedComment['comments']) ?: $property->description; $property->example = implode("\n", $parsedComment['examples']) ?: $property->example; if ($node->key instanceof String_) { $property->name = $node->key->value; } if ($node->key instanceof LNumber) { $property->name = (string)$node->key->value; } } return $property; } // Create instance (new Foo()) if ($node instanceof New_ && isset($node->class->parts) && count($node->class->parts) === 1) { $context->addScopes(static::findScopes($node)); return ClassExtractor::extract( $context->child(), $node->class->parts[0] ); } // Active query one() and all() calls if ($node instanceof MethodCall && in_array($node->name->name, ['one', 'all'])) { $context->addScopes(static::findScopes($node)); $staticCallNode = static::findFirst($node, function ($subNode) { return $subNode instanceof StaticCall && $subNode->name->name === 'find'; }); if ($staticCallNode && count($staticCallNode->class->parts) === 1) { $property = ClassExtractor::extract( $context->child(), $staticCallNode->class->parts[0], ); $property->isArray = $node->name->name === 'all'; return $property; } } // Active query findOrPanic(), findOne() and findAll() calls if ($node instanceof StaticCall && in_array($node->name->name, ['findOne', 'findAll', 'findOrPanic']) && count($node->class->parts) === 1) { $context->addScopes(static::findScopes($node)); $property = ClassExtractor::extract( $context->child(), $node->class->parts[0], ); $property->isArray = $node->name->name === 'findAll'; return $property; } // Primitive types $primitives = [ ConstFetch::class => 'boolean', String_::class => 'boolean', LNumber::class => 'integer', DNumber::class => 'float', ]; foreach ($primitives as $primitiveClass => $primitivesType) { if ($node instanceof $primitiveClass) { return new SwaggerProperty([ 'isPrimitive' => true, 'phpType' => $primitivesType, ]); } } // Variable $variableName = null; if ($node instanceof Variable && isset($variables[$node->name])) { $variableName = $node->name; } elseif ($node instanceof MethodCall && $node->var instanceof Variable && isset($variables[$node->var->name])) { $variableName = $node->var->name; } if ($variableName) { $parsedComment = static::parseNodeComments($context, $variables[$variableName]); if ($parsedComment['property']) { return $parsedComment['property']; } $context->addScopes(static::findScopes($node)); return static::nodeToProperty($context, $variables[$variableName]->expr, $variables); } return new SwaggerProperty(); } protected static function parseNodeComments(SwaggerContext $context, $node) { $comments = []; $examples = []; $parsedLines = []; $context->addScopes(static::findScopes($node)); $rawComments = $node->getDocComment() ? [$node->getDocComment()] : $node->getComments(); foreach ($rawComments as $comment) { /** @var $comment Comment\Doc|Comment */ foreach (explode("\n", $comment->getText()) as $line) { $line = preg_replace('/^\/\/|^\s*\/?\*+\/?|\*\/$/', '', $line); $line = trim($line); if ($line) { $parsedLine = ExtractorHelper::parseCommentType($line); if (in_array($parsedLine['tag'], ['var', 'type'])) { $parsedLines[] = $parsedLine; } // Example if ($parsedLine['example']) { $examples[] = ExtractorHelper::fixJson($parsedLine['example']); } // Comment if ($parsedLine['description']) { $comments[] = $parsedLine['description']; // Scopes if (preg_match_all('/SCOPE_([A-Z0-9_]+)/', $parsedLine['description'], $scopeMatches)) { $context->addScopes(array_map(fn($s) => Model::SCOPE_PREFIX . strtolower($s), $scopeMatches[1])); } } } } } // Find property after scopes defined $property = null; foreach ($parsedLines as $parsedLine) { if ($parsedLine['type']) { $property = TypeExtractor::extract($context, $parsedLine['type']); if ($parsedLine['variable']) { $property->name = $parsedLine['variable']; } if (!$property->isEmpty()) { break; } } } if ($property) { $property->description = implode("\n", $comments); $property->example = implode("\n", $examples); } return [ 'comments' => $comments, 'examples' => $examples, 'property' => $property, ]; } protected static function findScopes($astNode) { /** @var ClassConstFetch $node */ $node = static::findFirst($astNode, function ($node) { return $node instanceof ClassConstFetch && $node->name instanceof Identifier && strpos($node->name->name, 'SCOPE_') === 0; }); // TODO Find multiple $scope = $node ? mb_strtolower(preg_replace('/^SCOPE_/', '', $node->name->name)) : null; if ($scope && strpos($scope, Model::SCOPE_PREFIX) !== 0) { $scope = Model::SCOPE_PREFIX . $scope; } return $scope ? [$scope] : []; } protected static function findFirst($astNode, $callback) { $result = static::findAll($astNode, $callback, true); return count($result) === 1 ? $result[0] : null; } protected static function findAll($astNode, $callback, $onlyFirst = false) { $stmts = []; if (is_array($astNode)) { $stmts = array_merge($stmts, $astNode); } if (isset($astNode->stmts)) { $stmts = array_merge($stmts, $astNode->stmts); } if (isset($astNode->var)) { $stmts[] = $astNode->var; } if (isset($astNode->expr)) { $stmts[] = $astNode->expr; } if (isset($astNode->value)) { $stmts[] = $astNode->value; } if (isset($astNode->items)) { $stmts = array_merge($stmts, $astNode->items); } if (isset($astNode->args)) { $stmts = array_merge($stmts, $astNode->args); } $result = []; foreach ($stmts as $stmt) { if (call_user_func($callback, $stmt)) { $result[] = $stmt; if ($onlyFirst) { break; } } $result = array_merge($result, static::findAll($stmt, $callback, $onlyFirst)); } return $result; } }<file_sep>/extractors/SearchModelExtractor.php <?php namespace steroids\swagger\extractors; use steroids\core\base\Model; use steroids\core\base\SearchModel; use steroids\swagger\models\SwaggerContext; use steroids\swagger\models\SwaggerProperty; class SearchModelExtractor { /** * @param SwaggerContext $context * @param array|null $fields * @return SwaggerProperty * @throws \yii\base\Exception */ public static function extract(SwaggerContext $context, array $fields = null) { if (is_subclass_of($context->className, SearchModel::class)) { $searchModel = new $context->className; $modelClassName = $searchModel->fieldsSchema() ?: $searchModel->createQuery()->modelClass; } else { $modelClassName = $context->className; } if ($context->isInput) { // TODO page, pageSize need? or always have? /* 'page' => [ 'description' => 'Page', 'type' => 'number', 'example' => 2, ], 'pageSize' => [ 'description' => 'Page size', 'type' => 'number', 'example' => 50, ], */ if (is_subclass_of($context->className, SearchModel::class)) { return ModelExtractor::extract($context->child(['isInputForGetMethod' => false]), $fields); } else { return ModelExtractor::extract($context->child(['className' => SearchModel::class, 'isInputForGetMethod' => false]), $fields); } } $itemsProperty = ModelExtractor::extract($context->child([ 'className' => $modelClassName, 'fields'=> $fields, 'scopes' => [Model::SCOPE_LIST], ])); $itemsProperty->name = 'items'; $itemsProperty->description = 'Fined items'; $itemsProperty->isArray = true; return new SwaggerProperty([ 'items' => [ ClassAttributeExtractor::extract($context, 'meta'), new SwaggerProperty([ 'name' => 'total', 'description' => 'Total items count', 'phpType' => 'integer', 'isPrimitive' => true, ]), $itemsProperty, ], ]); } }<file_sep>/models/SwaggerContext.php <?php namespace steroids\swagger\models; use yii\base\BaseObject; class SwaggerContext extends BaseObject { public bool $isInput = false; public bool $isInputForGetMethod = false; public ?string $className = null; public ?string $methodName = null; public ?string $attribute = null; public ?array $fields = null; public ?array $scopes = []; public ?string $comment = null; public ?SwaggerRefsStorage $refsStorage = null; /** * @var SwaggerContext */ public $parent; /** * @param array $params * @return $this */ public function child(array $params = []) { return new static(array_merge( [ 'isInput' => $this->isInput, 'isInputForGetMethod' => $this->isInputForGetMethod, 'refsStorage' => $this->refsStorage, 'scopes' => $this->scopes, 'className' => $this->className, ], $params, [ 'parent' => $this, ] )); } public function addScopes($scopes) { $this->scopes = array_unique(array_merge($this->scopes ?: [], $scopes ?: [])); } } <file_sep>/models/SwaggerAction.php <?php namespace steroids\swagger\models; use steroids\swagger\extractors\ClassMethodExtractor; use yii\base\BaseObject; use yii\helpers\Inflector; /** * @property-read string $inputTsType * @property-read string $inputRefName * @property-read string $outputTsType * @property-read string $outputRefName */ class SwaggerAction extends BaseObject { public string $controllerClass; public string $methodName; public string $moduleId; public string $controllerId; public string $actionId; public string $url; public string $httpMethod; public ?SwaggerProperty $inputProperty; public ?SwaggerProperty $outputProperty; public function getInputTsType() { return $this->inputRefName ?: $this->inputProperty->exportTsType(); } public function getInputRefName() { if (!$this->inputProperty->items) { return null; } return ( $this->inputProperty->refName ?: Inflector::id2camel($this->controllerId) . Inflector::id2camel($this->actionId) . 'Request' ); } public function getOutputTsType() { return $this->outputRefName ?: $this->outputProperty->exportTsType(); } public function getOutputRefName() { if (!$this->outputProperty->items) { return null; } return ( $this->outputProperty->refName ?: Inflector::id2camel($this->controllerId) . Inflector::id2camel($this->actionId) . 'Response' ); } /** * @param SwaggerContext $context * @throws \ReflectionException * @throws \yii\base\Exception */ public function extract(SwaggerContext $context) { $context = new SwaggerContext([ 'className' => $this->controllerClass, 'refsStorage' => $context->refsStorage, ]); $this->inputProperty = ClassMethodExtractor::extract($context->child(['isInput' => true, 'isInputForGetMethod' => $this->httpMethod === 'get']), $this->methodName); $this->outputProperty = ClassMethodExtractor::extract($context->child(['isInput' => false]), $this->methodName); } public function export() { $label = preg_replace('/^\/?api\/[^\/]+/', '', $this->url); $title = $this->inputProperty->description ?: $this->outputProperty->description ?: ''; return [ 'summary' => $label, 'description' => '<b>' . strtoupper($this->httpMethod) . ' /' . ltrim($this->url, '/') . '</b><br/>' . $title, 'tags' => [$this->moduleId], 'consumes' => [ 'application/json' ], 'produces' => [ 'application/json' ], 'parameters' => !$this->inputProperty->isEmpty() ? [ [ 'in' => 'body', 'name' => 'request', 'schema' => $this->inputProperty->export(), ] ] : [], 'responses' => [ 200 => [ 'description' => 'Successful operation', 'schema' => !$this->outputProperty->isEmpty() ? $this->outputProperty->export() : null, ], 400 => [ 'description' => 'Validation errors', 'schema' => $this->httpMethod !== 'delete' ? [ 'type' => 'object', 'properties' => [ 'errors' => [ 'type' => 'object', ], ], ] : null, ], ], ]; } } <file_sep>/SwaggerModule.php <?php namespace steroids\swagger; use steroids\core\base\Module; use yii\base\BootstrapInterface; class SwaggerModule extends Module implements BootstrapInterface { /** * Список путей (из sitemap), которые не должны попасть в документацию * @example: gii, *.admin * @var string[] */ public array $skipPaths = [ 'gii', ]; /** * Директория до папки, где будет созданы *.ts файлы с интерфейсами апи * @var string|null */ public ?string $typesOutputDir = null; public function init() { parent::init(); if (!$this->typesOutputDir) { $this->typesOutputDir = STEROIDS_ROOT_DIR . '/types'; } } public function bootstrap($app) { if (!YII_ENV_DEV || !YII_DEBUG) { return; } // TODO Analyze code changes... } }<file_sep>/extractors/ClassMethodExtractor.php <?php namespace steroids\swagger\extractors; use steroids\core\base\CrudApiController; use steroids\swagger\helpers\ExtractorHelper; use steroids\swagger\models\SwaggerContext; use steroids\swagger\models\SwaggerProperty; use yii\base\Exception; class ClassMethodExtractor { /** * @param SwaggerContext $context * @param string $methodName * @return SwaggerProperty * @throws Exception * @throws \ReflectionException */ public static function extract(SwaggerContext $context, string $methodName) { $context->methodName = $methodName; $classInfo = new \ReflectionClass($context->className); if (!$classInfo) { throw new Exception('Not found class: ' . $context->className); } $methodInfo = $classInfo->getMethod($methodName); if (!$methodInfo) { throw new Exception('Not found method "' . $methodName . '" in class: ' . $context->className); } $comment = $methodInfo->getDocComment(); $childContext = $context->child([ 'className' => $methodInfo->getDeclaringClass()->name, 'methodName' => $methodInfo->name, ]); // Detect CRUD controller $className = $context->className; if (is_subclass_of($className, CrudApiController::class) && in_array($context->methodName, ['actionIndex', 'actionCreate', 'actionUpdate', 'actionView'])) { // Get model class $modelClass = $className::modelClass() ?: $className::$modelClass; if ($context->methodName === 'actionIndex') { $modelClass = $className::searchModelClass() ?: $className::$searchModelClass ?: $modelClass; } elseif ($context->isInput) { $viewSchema = $className::viewSchema(); if ($viewSchema) { return SchemaExtractor::extract($childContext->child([ 'className' => $viewSchema, ])); } } // Check model exists if (!$modelClass) { return new SwaggerProperty(); } return $context->methodName === 'actionIndex' ? SearchModelExtractor::extract($childContext->child([ 'className' => $modelClass, 'fields' => (new $className('tmp', 'tmp'))->fields(), ])) : ClassExtractor::extract($childContext, $modelClass); } // Listens if ($childContext->isInput && preg_match_all('/@request-listen-relation\s+([^\s]+)/i', $comment, $listenMatch)) { $childContext->fields = $listenMatch[1]; } $property = null; // Find return type in phpdoc if (preg_match('/@return ([a-z0-9_]+)/i', $comment, $returnMatch)) { $returnProperty = TypeExtractor::extract($childContext, $returnMatch[1]); if ($returnProperty->items) { $property = $returnProperty; } } // Find return type in source AST if (!$property) { $properties = AstExtractor::extract($childContext, $methodInfo->name); if (count($properties) > 0 && (!$childContext->isInput || !$properties[0]->isPrimitive)) { $property = $properties[0]; } } // Request params from phpdoc $requestProperties = []; if ($childContext->isInput) { foreach (explode("\n", $comment) as $line) { $parsedLine = ExtractorHelper::parseCommentType($line); if (in_array($parsedLine['tag'], ['param', 'param-get', 'param-post'])) { $paramProperty = TypeExtractor::extract($childContext, $parsedLine['type'] ?: ''); $paramProperty->name = $parsedLine['variable']; $paramProperty->description = $parsedLine['description']; $requestProperties[] = $paramProperty; } } } /*if ($childContext->isInput && preg_match_all('/@param(-post)? +([^\s\n]+) +([^\s\n]+)( [^\n]+)?/i', $comment, $paramsMatch, PREG_SET_ORDER)) { foreach ($paramsMatch as $paramMatch) { $paramContext = $childContext->child([ 'methodName' => $methodInfo->name, 'comment' => $paramMatch[0], ]); if (strpos($paramMatch[2], '$') === 0) { $paramProperty = TypeExtractor::extract($paramContext, 'string'); $paramProperty->name = substr($paramMatch[2], 1); $requestProperties[] = $paramProperty; } elseif (strpos($paramMatch[3], '$') === 0) { $paramProperty = TypeExtractor::extract($paramContext, $paramMatch[2]); $paramProperty->name = substr($paramMatch[3], 1); $requestProperties[] = $paramProperty; } } }*/ if (count($requestProperties) > 0) { if (!$property || $property->isEmpty()) { $property = new SwaggerProperty(); $property->items = $requestProperties; } } // Blank type if (!$property) { $property = TypeExtractor::extract($childContext, ''); } return $property; } } <file_sep>/tests/mocks/FooModel.php <?php namespace steroids\swagger\tests\mocks; use steroids\core\base\Model; /** * Class FooModel * @package tests\mocks\FooModel * @property-read int $id Primary key */ class FooModel extends Model { /** * @inheritDoc */ public static function meta() { return [ 'id' => [ 'appType' => 'primaryKey', 'label' => 'Primary key from meta', ], 'title' => [ 'label' => 'Title from meta', ], 'role' => [ ], ]; } public function frontendFields($user = null) { return [ self::SCOPE_DEFAULT => [ 'id', 'name', ], self::SCOPE_DETAIL => [ 'role', 'title', ], ]; } /** * @inheritDoc */ public function rules() { return [ ['id', 'integer'], ['title', 'string'], ['title', 'required'], ]; } public function attributes() { // simulate database return ['id', 'role', 'title']; } /** * Foo name * @return string */ public function getName() { return ''; } } <file_sep>/extractors/ClassExtractor.php <?php namespace steroids\swagger\extractors; use Doctrine\Common\Annotations\TokenParser; use steroids\core\base\BaseSchema; use steroids\core\base\SearchModel; use steroids\swagger\models\SwaggerContext; use steroids\swagger\models\SwaggerProperty; use yii\base\Exception; use yii\base\Model; use yii\helpers\ArrayHelper; class ClassExtractor { /** * @param SwaggerContext $context * @param string $className * @param array|null $fields * @return SwaggerProperty * @throws Exception * @throws \ReflectionException */ public static function extract(SwaggerContext $context, string $className, array $fields = null): SwaggerProperty { $className = static::resolveClassName($className, $context->className); $childContext = $context->child([ 'className' => $className, ]); if (is_subclass_of($className, BaseSchema::class)) { return SchemaExtractor::extract($childContext, $fields); } elseif (is_subclass_of($className, SearchModel::class)) { return SearchModelExtractor::extract($childContext, $fields); } elseif (is_subclass_of($className, Model::class)) { return ModelExtractor::extract($childContext, $fields); } return ObjectExtractor::extract($childContext); } /** * @param string $shortName * @param string $inClassName * @return string * @throws \ReflectionException */ public static function resolveClassName(string $shortName, string $inClassName): string { $classInfo = new \ReflectionClass($inClassName); $namespace = $classInfo->getNamespaceName(); // Check name with namespace if (strpos($shortName, '\\') !== false) { return $shortName; } // Fetch use statements $tokenParser = new TokenParser(file_get_contents($classInfo->getFileName())); $useStatements = $tokenParser->parseUseStatements($namespace); $tokenParser = new TokenParser(file_get_contents($classInfo->getParentClass()->getFileName())); $useStatements = array_merge($tokenParser->parseUseStatements($namespace), $useStatements); $className = ArrayHelper::getValue($useStatements, strtolower($shortName), $namespace . '\\' . $shortName); $className = '\\' . ltrim($className, '\\'); return $className; } }<file_sep>/models/SwaggerResult.php <?php namespace steroids\swagger\models; use steroids\swagger\events\SwaggerExportEvent; use yii\base\Component; use yii\helpers\ArrayHelper; class SwaggerResult extends Component { const EVENT_EXPORT = 'export'; public $version = 'v1'; public $siteName; public $hostName; public $adminEmail; public SwaggerRefsStorage $refsStorage; /** * @var SwaggerAction[] */ public array $actions = []; protected $tags = []; protected $paths = []; public function init() { parent::init(); $this->refsStorage = new SwaggerRefsStorage(); } /** * @param SwaggerAction[] $actions */ public function addActions(array $actions) { $this->actions = array_merge($this->actions, $actions); } /** * @return array */ public function toArray() { ArrayHelper::multisort($this->tags, 'name'); $json = [ 'swagger' => '2.0', 'info' => [ 'version' => $this->version, 'title' => $this->siteName . ' API', 'description' => $this->siteName . ' API', 'termsOfService' => 'http://swagger.io/terms/', 'contact' => $this->adminEmail ? ['email' => $this->adminEmail] : (object)[], 'license' => [ 'name' => 'Apache 2.0', 'url' => 'http://www.apache.org/licenses/LICENSE-2.0.html', ] ], 'host' => $this->hostName, 'basePath' => $this->getBasePath(), 'schemes' => [\Yii::$app->request->isSecureConnection ? 'https' : 'http'], 'tags' => [], 'paths' => [], 'definitions' => $this->refsStorage->exportDefinitions(), ]; // Add paths $tags = []; foreach ($this->actions as $action) { // Export $schema = $action->export(); // Add path schema $json['paths'][$action->url][$action->httpMethod] = $schema; // Add tags $tags = array_merge($tags, ArrayHelper::getValue($schema, 'tags', [])); } // Add tags $json['tags'] = array_values(array_map(fn ($name) => ['name' => $name], array_unique($tags))); $event = new SwaggerExportEvent([ 'json' => $json, ]); $this->trigger(self::EVENT_EXPORT, $event); return $event->json; } public function getBasePath() { return '/api/' . preg_replace('/\.[^\.]+$/', '', $this->version); } /** * @return string */ public function __toString() { return json_encode($this->toArray(), JSON_UNESCAPED_SLASHES); } } <file_sep>/components/SwaggerBuilder.php <?php namespace steroids\swagger\components; use steroids\core\components\SiteMapItem; use steroids\core\helpers\ClassFile; use steroids\gii\helpers\GiiHelper; use steroids\swagger\helpers\TypeScriptHelper; use steroids\swagger\models\SwaggerAction; use steroids\swagger\models\SwaggerContext; use steroids\swagger\models\SwaggerResult; use steroids\swagger\SwaggerModule; use yii\base\Component; use yii\helpers\ArrayHelper; use yii\helpers\FileHelper; use yii\helpers\Inflector; use yii\helpers\StringHelper; use yii\web\JsExpression; use yii\web\Request; class SwaggerBuilder extends Component { protected SwaggerResult $result; public function buildJson() { $this->prepare(); // Run extract $context = new SwaggerContext(['refsStorage' => $this->result->refsStorage]); foreach ($this->result->actions as $action) { $action->extract($context); } return $this->result->toArray(); } public function buildTypes() { $this->prepare(); $module = SwaggerModule::getInstance(); /** @var SwaggerAction[][] $controllerActions */ $controllerActions = []; // Run extract $context = new SwaggerContext(['refsStorage' => $this->result->refsStorage]); foreach ($this->result->actions as $action) { $action->extract($context); // Controller file $relativePath = str_replace('.', DIRECTORY_SEPARATOR, $action->moduleId) . DIRECTORY_SEPARATOR . 'api' . DIRECTORY_SEPARATOR . $action->controllerId . '.ts'; $controllerActions[$relativePath][] = $action; } $counts = []; foreach ($this->result->refsStorage->getAll() as $property) { if (is_array($property->items)) { foreach ($property->items as $item) { if ($item->refName) { if (!isset($counts[$item->refName])) { $counts[$item->refName] = 0; } $counts[$item->refName]++; } } } } foreach ($this->result->refsStorage->getAll() as $name => $property) { $relativePath = $this->result->refsStorage->getRefRelativePath($name); FileHelper::createDirectory(dirname($module->typesOutputDir . DIRECTORY_SEPARATOR . $relativePath)); file_put_contents( $module->typesOutputDir . DIRECTORY_SEPARATOR . $relativePath, TypeScriptHelper::generateInterfaces([$name => $property], $relativePath, $this->result->refsStorage, [],true) ); } foreach ($controllerActions as $relativePath => $actions) { FileHelper::createDirectory(dirname($module->typesOutputDir . DIRECTORY_SEPARATOR . $relativePath)); file_put_contents( $module->typesOutputDir . DIRECTORY_SEPARATOR . $relativePath, TypeScriptHelper::generateApi($actions, $relativePath, $this->result->refsStorage) ); } // Add utils.ts $path = $module->typesOutputDir . DIRECTORY_SEPARATOR . 'utils.ts'; if (!file_exists($path)) { FileHelper::createDirectory(dirname($path)); copy(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'typescript' . DIRECTORY_SEPARATOR . 'utils.ts', $path); } // Add index.ts $tree = []; foreach ($controllerActions as $relativePath => $actions) { foreach ($actions as $action) { $tree[$action->moduleId][$action->controllerId] = $relativePath; } } $content = "const api = {\n"; foreach ($tree as $moduleId => $actions) { $content .= " $moduleId: {\n"; foreach ($actions as $controllerId => $relativePath) { $controllerId = lcfirst(Inflector::id2camel($controllerId)); $content .= " $controllerId: require('./$relativePath'),\n"; } $content .= " },\n"; } $content .= "}\n\n"; $content .= "export default api;\n"; file_put_contents($module->typesOutputDir . DIRECTORY_SEPARATOR . 'index.ts', $content); } /** * @throws \yii\base\Exception * @throws \yii\base\InvalidConfigException */ protected function prepare() { // Create json object $this->result = new SwaggerResult([ 'siteName' => \Yii::$app->name, 'hostName' => \Yii::$app->request instanceof Request ? \Yii::$app->request->hostName : null, 'adminEmail' => ArrayHelper::getValue(\Yii::$app->params, 'adminEmail', ''), ]); // Prepare skip path, convert to regexp $skipPaths = SwaggerModule::getInstance()->skipPaths; $skipRegexpParts = []; foreach ($skipPaths as $skipPath) { $skipRegexpParts[] = implode('\\.', array_map( fn($str) => $str === '*' ? '[^\.]+' : preg_quote($str), explode('.', $skipPath), )); } $skipRegexp = '/^' . implode('|', $skipRegexpParts) . '/'; // Store site map items (convert tree to single list) $siteMapItems = $this->fetchSiteMapItemsRecursive( ArrayHelper::getValue(\Yii::$app->siteMap->getItem('api'), 'items'), $skipRegexp ); // Create actions foreach ($siteMapItems as $siteMapItem) { $this->result->addActions($this->createActions($siteMapItem)); } } /** * @param SiteMapItem $item * @return SwaggerAction[] * @throws \yii\base\InvalidConfigException */ protected function createActions(SiteMapItem $item) { // Get route $route = ArrayHelper::getValue($item->normalizedUrl, 0); if (!$route || !is_string($route)) { return []; } // Separate route to module, controller and action ids $moduleId = implode('.', array_filter(array_slice(explode('/', $route), 0, -2))); list($controllerId, $actionId) = array_slice(explode('/', $route), -2, 2); // Get controller class // TODO Нужно научиться правильно получать класс контроллера даже в консольном приложении $controllerClass = 'app\\' . str_replace('.', '\\', $moduleId) . '\\controllers\\' . ucfirst(Inflector::id2camel($controllerId)) . 'Controller'; //$controllerResult = \Yii::$app->createController($route); //$controllerClass = $controllerResult ? get_class($controllerResult[0]) : null; if (!$controllerClass) { return []; } // Get method name $methodName = 'action' . Inflector::id2camel($actionId); if (!(new \ReflectionClass($controllerClass))->hasMethod($methodName)) { return []; } // Get normalized url $url = $item->urlRule; $url = preg_replace('/^([A-Z,]+)\s+/', '', $url); $url = preg_replace('/<([^>:]+)(:[^>]+)?>/', '{$1}', $url); $url = str_replace('{version}', $this->result->version, $url); $url = '/' . ltrim($url, '/'); // Get HTTP methods $httpMethods = preg_match('/^([A-Z,]+)\s+.+/', $item->urlRule, $match) ? StringHelper::explode(strtolower($match[1])) : ['get']; // Create actions $actions = []; foreach ($httpMethods as $httpMethod) { $actions[] = new SwaggerAction([ 'controllerClass' => $controllerClass, 'methodName' => $methodName, 'moduleId' => $moduleId, 'controllerId' => $controllerId, 'actionId' => $actionId, 'url' => $url, 'httpMethod' => $httpMethod, ]); } return $actions; } protected function fetchSiteMapItemsRecursive($items, $skipRegexp) { $result = []; foreach ($items ?: [] as $item) { // Skipped paths (without "api" key) $path = implode('.', array_slice($item->pathIds, 1)); if (preg_match($skipRegexp, $path)) { continue; } // Add $result[] = $item; $result = array_merge($result, $this->fetchSiteMapItemsRecursive($item->items, $skipRegexp)); } return $result; } } <file_sep>/tests/mocks/FirstController.php <?php namespace steroids\swagger\tests\mocks; use steroids\auth\AuthModule; use steroids\auth\models\AuthConfirm; use steroids\auth\models\AuthSocial; use yii\web\Controller; class FirstController extends Controller { public static function apiMap() { return [ 'test.first' => [ 'items' => [ 'index' => '/api/<version>/test/first', 'get-detail' => '/api/<version>/test/first/detail', ], ], ]; } /** * @return FooModel */ public function actionIndex() { return new FooModel(); } public function actionGetDetail() { $model = new FooModel(); return [ // Foo property 'foo' => [ // Foo model 'model' => new FooModel(), 'model2' => $model, /** * Model3 custom type * @var BarObject */ 'model3' => $model, // Confirm model with id 1 'confirm' => AuthConfirm::find()->where(['id' => 1])->one(), // Confirms list 'confirms' => AuthConfirm::find()->where(['id' => 1])->all(), 'confirmShort' => AuthConfirm::findOne(['id' => 1]), 'confirmsShort' => AuthConfirm::findAll(['id' => 1]), 'title' => 'Foo', 'count' => 20, 'total' => 33.5, 'strings' => ['a', 'b', 'c'], // This is comment not worked ], /** Start comment before flag */ 'flag' => true, /** * Multiline comment for "six" value * Second line here... * @example {'foo': 99} */ 6 => 'six', ]; } } <file_sep>/README.md # Swagger API generator Генерирует карту API в виде swagger.json файла, и дает возможность просмотреть его при помощи интерфейса [ReDoc](https://github.com/Redocly/redoc). <file_sep>/models/SwaggerProperty.php <?php namespace steroids\swagger\models; use steroids\core\interfaces\ISwaggerProperty; use steroids\swagger\helpers\ExtractorHelper; use yii\base\BaseObject; use yii\base\Exception; use yii\helpers\ArrayHelper; use yii\helpers\Json; use yii\helpers\StringHelper; class SwaggerProperty extends BaseObject implements ISwaggerProperty { const DEFAULT_TYPE = 'string'; const SINGLE_MAPPING = [ 'string' => 'string', 'integer' => 'number', 'float' => 'number', 'boolean' => 'boolean', 'array' => 'array', 'resource' => 'object', 'null' => 'object', 'callable' => 'object', 'mixed' => 'object', 'void' => 'object', 'object' => 'object', ]; /** * Attribute or property name * @var string|null */ public ?string $name = null; /** * Reference name for entity (class/model) only * @var string|null */ public ?string $refName = null; /** * @var SwaggerRefsStorage|null */ public ?SwaggerRefsStorage $refsStorage = null; /** * Source php type - primitive or class name * @var string|null */ public ?string $phpType = null; /** * Swagger format * @var string|null */ public ?string $format = null; /** * Required flag * @var bool */ public ?bool $isRequired = false; /** * Swagger enum keys * @var string[] */ public ?array $enum = null; /** * Property description * @var string|null */ public ?string $description = null; /** * Example of property value * @var string|null */ public ?string $example = null; /** * Is array of type? * @var bool|null */ public ?bool $isArray = false; /** * Depth array of arrays * @var int */ public int $arrayDepth = 1; /** * Is primitive type? * @var bool|null */ public ?bool $isPrimitive = false; /** * Source phpdoc * @var string|null */ public ?string $phpdoc = null; /** * @var static[]|null */ public ?array $items = null; public function setPhpType(string $value) { $this->phpType = $value; } public function setFormat(string $value) { $this->format = $value; } public function setIsArray(bool $value) { $this->isArray = $value; } public function setEnum(array $keys) { $this->enum = $keys; } public function isEmpty() { return !$this->phpType && !$this->items; } public function clone() { return new static([ 'name' => $this->name, 'refName' => $this->refName, 'refsStorage' => $this->refsStorage, 'phpType' => $this->phpType, 'format' => $this->format, 'isRequired' => $this->isRequired, 'enum' => $this->enum, 'description' => $this->description, 'example' => $this->example, 'isArray' => $this->isArray, 'arrayDepth' => $this->arrayDepth, 'isPrimitive' => $this->isPrimitive, 'phpdoc' => $this->phpdoc, 'items' => $this->items, ]); } public function export($skipRefs = false) { if (!$skipRefs && $this->refName && $this->refsStorage && $this->refsStorage->isInDefinitions($this->refName)) { $schema = [ '$ref' => '#/definitions/' . $this->refName, ]; } else { // Get description and example from phpdoc if ($this->phpdoc) { // Class description if (preg_match('/@property(-read)? +[^ ]+ \$[^ ]+ (.*)/u', $this->phpdoc, $matches)) { if (!empty($matches[2])) { $this->description = $matches[2]; } } else { // Find first comment line as description foreach (explode("\n", $this->phpdoc) as $line) { $line = preg_replace('/^\s*\\/?\*+/', '', $line); $line = trim($line); if ($line && $line !== '/' && substr($line, 0, 1) !== '@') { $this->description = $line; break; } } if (!$this->example && preg_match('/@example (.*)/u', $this->phpdoc, $matches)) { $this->example = trim($matches[1]); } // Get description from type param foreach (explode("\n", $this->phpdoc) as $line) { $parsedLine = ExtractorHelper::parseCommentType($line); if ($parsedLine['description']) { $this->description = $parsedLine['description']; } } } } // Support array/object examples if (!empty($schema['example']) && in_array(substr($schema['example'], 0, 1), ['[', '{'])) { $schema['example'] = Json::decode(ExtractorHelper::fixJson($schema['example'])); } $properties = null; $required = null; // TODO if (!$this->isPrimitive && $this->items) { $properties = []; $required = []; foreach ($this->items as $item) { if ($item->name === null) { throw new Exception('Not found name for item: ...'); } $properties[$item->name] = $item->export(); if ($item->isRequired) { $required[] = $item->name; } } } $schema = [ 'type' => !$this->isPrimitive && $this->items ? 'object' : (ArrayHelper::getValue(self::SINGLE_MAPPING, $this->phpType) ?: self::DEFAULT_TYPE), ]; if ($this->description) { $schema['description'] = $this->description; } if ($this->example) { $schema['example'] = $this->example; } if ($this->format) { $schema['format'] = $this->format; } if (!empty($properties)) { $schema['properties'] = $properties; } } if ($this->isArray && !$skipRefs) { for ($i = 0; $i < $this->arrayDepth; $i++) { $schema = [ 'type' => 'array', 'items' => $schema, ]; } } return $schema; } public function exportTsType($indent = '', $skipRefs = false, &$usedRefs = []) { $type = 'any'; if (!$skipRefs && $this->refName) { $type = 'I' . $this->refName; $usedRefs[] = $this->refName; } elseif (!empty($this->items)) { return implode( "\n", [ '{', ...array_map( function ($item) use ($indent, &$usedRefs) { $lines = ['']; if ($item->description || $item->example) { $lines[] = '/**'; if ($item->description) { $lines[] = ' * ' . $item->description; } if ($item->example) { $lines[] = ' * @example ' . ExtractorHelper::fixJson($item->example); } $lines[] = ' */'; } $lines[] = $item->name . '?: ' . $item->exportTsType($indent . ' ', false, $usedRefs) . ','; return implode( "\n", array_map( fn($line) => $line ? $indent . ' ' . $line : '', $lines, ), ); }, $this->items, ), $indent . '}', ] ); } elseif ($this->isPrimitive && isset(self::SINGLE_MAPPING[$this->phpType]) && $this->phpType !== 'array') { $type = self::SINGLE_MAPPING[$this->phpType]; } // TS linter recommendation - Don't use `object` as a type. The `object` type is currently hard to use. if ($type === 'object') { $type = 'Record<string, unknown>'; } // todo enum // ...array_map( // fn(string $value) => str_replace('"', "'", Json::encode($value)), // ArrayHelper::getValue($property, 'enum', []) // ), if ($this->isArray) { $type .= '[]'; } return $type; } } <file_sep>/tests/mocks/BarObject.php <?php namespace steroids\swagger\tests\mocks; /** * Class BarObject * @package tests\mocks\BarObject */ class BarObject { /** * Count items * @var int */ public int $count = 0; } <file_sep>/extractors/ObjectExtractor.php <?php namespace steroids\swagger\extractors; use steroids\swagger\models\SwaggerContext; use steroids\swagger\models\SwaggerProperty; class ObjectExtractor { /** * @param SwaggerContext $context * @return SwaggerProperty * @throws \ReflectionException */ public static function extract(SwaggerContext $context) { if ($context->isInput) { return new SwaggerProperty(); } return new SwaggerProperty([ 'items' => array_filter( array_map( function (\ReflectionProperty $propertyInfo) use ($context) { return $propertyInfo->isPublic() ? ClassAttributeExtractor::extract( $context->child(['attribute' => $propertyInfo->name]), $propertyInfo->name ) : null; }, (new \ReflectionClass($context->className))->getProperties() ) ), ]); } }<file_sep>/extractors/ModelExtractor.php <?php namespace steroids\swagger\extractors; use steroids\core\base\FormModel; use steroids\core\base\SearchModel; use steroids\swagger\models\SwaggerContext; use steroids\swagger\models\SwaggerProperty; use yii\base\Exception; use yii\base\Model; use yii\helpers\ArrayHelper; use yii\helpers\StringHelper; class ModelExtractor { /** * @param SwaggerContext $context * @param array|null $fields * @return SwaggerProperty * @throws Exception * @throws \ReflectionException */ public static function extract(SwaggerContext $context, array $fields = null): SwaggerProperty { if ($context->isInputForGetMethod) { return new SwaggerProperty(); } if (is_array($fields)) { $context->fields = $fields; } else { $fields = $context->fields; } $className = $context->className; if (!is_string($className) || !class_exists($className)) { throw new \Exception('Invalid class name: ' . $className); } $model = new $className(); // Refs if ($context->refsStorage && !$context->fields && !$context->isInput && !($model instanceof FormModel) && !($model instanceof SearchModel)) { $refKey = StringHelper::basename($className); if (!empty($context->scopes)) { foreach ($context->scopes as $scope) { if ($scope !== \steroids\core\base\Model::SCOPE_LIST) { $refKey .= ucfirst(str_replace(\steroids\core\base\Model::SCOPE_PREFIX, '', $scope)); } } } if ($context->refsStorage->hasRef($refKey)) { return $context->refsStorage->getRef($refKey)->clone(); } } if ($context->isInput) { $fields = []; if ($model instanceof Model) { foreach ($model->safeAttributes() as $attribute) { // Skip params from url // TODO need?? // if (stripos($this->url, '{' . $attribute . '}') !== false) { // continue; // } // Write only params if ($model->canSetProperty($attribute)) { $fields[] = $attribute; } } } } else { // Output schema if ($model instanceof FormModel) { $schema = $model->fieldsSchema(); if ($schema) { return SchemaExtractor::extract($schema, !empty($fields) ? $fields : null); } } if ($fields === null) { $fields = static::getModelFields($context, $model); } } // Detect * => model.* foreach ($fields as $key => $name) { // Syntax: * => model.* if ($key === '*' && preg_match('/\.*$/', $name) !== false) { unset($fields[$key]); $attribute = substr($name, 0, -2); $subProperty = ClassAttributeExtractor::extract($context->child(), $attribute); if ($subProperty) { $subClassName = $subProperty->phpType; if (class_exists($subClassName)) { $subModel = new $subClassName(); foreach (static::getModelFields($context, $subModel) as $key2 => $name2) { $key2 = is_int($key2) ? $name2 : $key2; $fields[$key2] = $attribute . '.' . $name2; } } } } } $items = []; foreach ($fields as $key => $attributes) { if (is_int($key) && is_string($attributes)) { $key = $attributes; } $childContext = $context->child([ 'attribute' => $key, 'fields' => is_array($attributes) ? $attributes : null, ]); // Scope: 'user' => [SCOPE_LIST], if (!empty($attributes) && (is_string($attributes) || is_array($attributes))) { $isAllScopes = true; foreach ((array)$attributes as $scopeName) { if (strpos($scopeName, \steroids\core\base\Model::SCOPE_PREFIX) !== 0) { $isAllScopes = false; break; } } if ($isAllScopes) { $childContext->scopes = (array)$attributes; $attributes = $key; } } // Function: 'user' => function($model) { return ... }, if (is_callable($attributes)) { $items[] = ClassAttributeExtractor::extract($childContext, $key); continue; } // Path to attribute: 'name' => 'user.name' if (is_string($attributes)) { $childContext = static::prepareContextByPath($childContext, explode('.', $attributes)); $items[] = ClassAttributeExtractor::extract($childContext, $childContext->attribute); } } $resultProperty = new SwaggerProperty([ 'items' => $items, ]); // Refs if (isset($refKey)) { $resultProperty->refName = $refKey; $resultProperty->refsStorage = $context->refsStorage; $context->refsStorage->setRef($className, $refKey, $resultProperty); } return $resultProperty; } public static function prepareContextByPath(SwaggerContext $context, array $attributes) { $attribute = array_pop($attributes); // Find sub model for attributes map case if (count($attributes) > 0) { foreach ($attributes as $subAttribute) { $context->attribute = $subAttribute; list($subContext, $subModelClass) = ClassAttributeExtractor::prepare($context, $subAttribute); $subModelClass = ClassExtractor::resolveClassName($subModelClass, $subContext->className); if (!$subModelClass || !class_exists($subModelClass)) { break; } $context = $context->child([ 'className' => $subModelClass, ]); } $context = $context->child([ 'attribute' => $attribute, ]); } return $context; } /** * @param SwaggerContext $context * @param FormModel|Model $model * @return null */ protected static function getModelFields(SwaggerContext $context, $model) { $fields = null; if (method_exists($model, 'frontendFields')) { $scopes = $context->scopes ?: []; if (!in_array(\steroids\core\base\Model::SCOPE_DEFAULT, $scopes)) { array_unshift($scopes, \steroids\core\base\Model::SCOPE_DEFAULT); } $frontendFields = $model->frontendFields(); if ($frontendFields !== null) { $fields = []; foreach ($scopes as $scope) { foreach (ArrayHelper::getValue($frontendFields, $scope, []) as $key => $value) { if (!is_int($key)) { $fields[$key] = $value; } elseif (!in_array($value, $fields) && !isset($fields[$value])) { $fields[] = $value; } } } } } if (!$fields) { $fields = $model->fields(); } return $fields; } }<file_sep>/helpers/ExtractorHelper.php <?php namespace steroids\swagger\helpers; use Doctrine\Common\Annotations\TokenParser; use steroids\swagger\models\SwaggerProperty; use yii\base\Exception; use yii\base\Model; use yii\db\ActiveQuery; use yii\db\ActiveQueryInterface; use yii\helpers\ArrayHelper; abstract class ExtractorHelper { public static function normalizePrimitiveType($string) { $map = [ 'int' => 'integer', 'bool' => 'boolean', 'double' => 'float', 'true' => 'boolean', 'false' => 'boolean', ]; return ArrayHelper::getValue($map, $string, $string); } public static function isPrimitiveType($string) { $list = [ 'string', 'integer', 'float', 'boolean', 'array', 'resource', 'null', 'callable', 'mixed', 'void', 'object', ]; return in_array(static::normalizePrimitiveType($string), $list); } public static function fixJson($json) { if (!in_array(substr($json, 0, 1), ['[', '{'])) { return $json; } $newJSON = ''; $jsonLength = strlen($json); for ($i = 0; $i < $jsonLength; $i++) { if ($json[$i] == '"' || $json[$i] == "'") { $nextQuote = strpos($json, $json[$i], $i + 1); $quoteContent = substr($json, $i + 1, $nextQuote - $i - 1); $newJSON .= '"' . str_replace('"', "'", $quoteContent) . '"'; $i = $nextQuote; } else { $newJSON .= $json[$i]; } } return $newJSON; } /** * @param $modelClassName * @param $name * @return ActiveQuery */ public static function safeGetRelation($modelClassName, $name) { $model = static::safeCreateInstance($modelClassName); if (!$model || !is_string($name)) { return null; } try { $methodInfo = new \ReflectionMethod($model, 'get' . ucfirst($name)); } catch (\ReflectionException $e) { return null; } foreach ($methodInfo->getParameters() as $parameter) { if (!$parameter->isOptional()) { return null; } } if (!method_exists($model, 'getRelation')) { return null; } return $model->getRelation($name, false); } public static function parseCommentType($line) { $line = trim($line); $line = preg_replace('/^\/\/|^\s*\/?\*+\/?|\*\/$/', '', $line); $result = [ 'tag' => null, 'type' => null, 'variable' => null, 'description' => null, 'example' => null, ]; $isFullType = false; foreach (explode(' ', $line) as $str) { $str = trim($str); // Tag if (!$result['tag'] && strpos($str, '@') === 0) { $result['tag'] = substr($str, 1); continue; } // Variable if (!$result['variable'] && strpos($str, '$') === 0) { if ($result['description']) { $result['type'] = $result['description']; $result['description'] = null; } $result['variable'] = substr($str, 1); continue; } // Type switch ($result['tag']) { case 'var': case 'type': case 'return': case 'param': case 'param-get': case 'param-post': if (!$result['variable']) { if (!$result['type']) { $result['type'] = $str; $isFullType = strpos($str, '<') === false; continue 2; } elseif (!$isFullType) { $result['type'] .= ' ' . $str; $isFullType = true; continue 2; } } break; case 'example': $result['example'] .= ($result['example'] ? ' ' : '') . $str; continue 2; } // Other: comment $result['description'] .= ($result['description'] && $str ? ' ' : '') . $str; } return $result; } protected static function safeCreateInstance($modelClass) { if (!class_exists($modelClass)) { return null; } $modelClassInfo = new \ReflectionClass($modelClass); if ($modelClassInfo->isAbstract()) { return null; } $model = null; try { $model = new $modelClass(); } catch (\Exception $e) { } return $model; } }
2caa0a40971aeb1fe235aab4dcf45d8cd0fc9087
[ "Markdown", "TypeScript", "PHP" ]
29
PHP
steroids/swagger
3a8b1ee3010c13d7d7c840941470b5381a4fa110
8daeeb7d9de3e0a884470971b17d02ca360b3901
refs/heads/master
<repo_name>DWtiangu/wwk<file_sep>/os/.svn/pristine/3d/3d6d5f7b9a1865dcbdebb4d028e619629cc17b29.svn-base #ifndef WTK_CORE_WTK_BLOCKQUEUE_H_ #define WTK_CORE_WTK_BLOCKQUEUE_H_ #include "wtk/core/wtk_queue.h" #include "wtk/os/wtk_lockqueue.h" #include "wtk/os/wtk_sem.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_blockqueue wtk_blockqueue_t; struct wtk_blockqueue { WTK_LOCK_QUEUE wtk_sem_t sem; }; int wtk_blockqueue_init(wtk_blockqueue_t *q); int wtk_blockqueue_clean(wtk_blockqueue_t *q); int wtk_blockqueue_push(wtk_blockqueue_t *q,wtk_queue_node_t *n); wtk_queue_node_t* wtk_blockqueue_pop(wtk_blockqueue_t *q,int ms,int *is_timeout); int wtk_blockqueue_wake(wtk_blockqueue_t *q); int wtk_blockqueue_push_front(wtk_blockqueue_t *q,wtk_queue_node_t *n); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/57/5717ff2cbfd751d04cf1ccaac9c0aad241338c9e.svn-base #ifndef WTK_CORE_WTK_STR_ENCODE_H_ #define WTK_CORE_WTK_STR_ENCODE_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_heap.h" #include "wtk/core/wtk_array.h" #ifdef __cplusplus extern "C" { #endif #define utf8_to_gbk_3_s(utf8) utf8_to_gbk_3(utf8,sizeof(utf8)-1) /** * @return chars must be freed. */ char* utf8_to_gbk(const char* utf); /** * @return chars must be freed. */ char* gbk_to_utf8(const char* gbk); #ifdef WIN32 #else /** * @return chars must be freed. */ char* utf8_to_gbk_2(const char* utf,int len); /** * @return chars must be freed. */ char* gbk_to_utf8_2(const char* gbk,int len); /** * @return chars is in static buffer, do not need to be freed, is used for debug. */ char* gbk_to_utf8_3(const char* gbk,int len); char* utf8_to_gbk_3(const char *utf8,int len); #endif int str_is_utf8(const unsigned char* utf,int len); int wtk_utf8_bytes(char c); int wtk_utf8_len(char *data,int len); void wtk_utf8_tolower(char *data,int len); int wtk_utf16_to_utf8(int v,char *buf); int wtk_utf8_to_utf16(char *data); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_queue_slot.c #include "wtk_queue_slot.h" wtk_queue_slot_t* wtk_queue_slot_new(void *data) { wtk_queue_slot_t *s; s=(wtk_queue_slot_t*)wtk_malloc(sizeof(*s)); s->data=data; return s; } int wtk_queue_slot_delete(wtk_queue_slot_t *s,wtk_delete_handler_t dispose) { if(dispose) { dispose(s->data); } wtk_free(s); return 0; } <file_sep>/os/ps/wtk_psys.h #ifndef WTK_OS_PS_WTK_PSYS_H_ #define WTK_OS_PS_WTK_PSYS_H_ #include "wtk/core/wtk_type.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_psys wtk_psys_t; struct wtk_psys { int parent_write_fd[2]; //0 for read and 1 for write int parent_read_fd[2]; int pid; }; int wtk_psys_init(wtk_psys_t *sys,char *cmd); void wtk_psys_clean(wtk_psys_t *sys); /* * @return write bytes; */ int wtk_psys_write(wtk_psys_t *sys,char *data,int bytes); /** * @return read bytes; */ int wtk_psys_read(wtk_psys_t *sys,char *data,int bytes); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/f5/f56f044d93b2f7abb2cccdfd035558b1239a4c53.svn-base #ifndef WTK_FST_STRLIKE_WTK_STRLIKE_H_ #define WTK_FST_STRLIKE_WTK_STRLIKE_H_ #include "wtk/core/wtk_type.h" #include "wtk_strlike_cfg.h" #include "wtk/core/wtk_strbuf.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_strlike wtk_strlike_t; struct wtk_strlike { wtk_strlike_cfg_t *cfg; wtk_heap_t *heap; }; wtk_strlike_t* wtk_strlike_new(wtk_strlike_cfg_t *cfg); void wtk_strlike_delete(wtk_strlike_t *l); float wtk_strlike_process(wtk_strlike_t *l,char *ref,int ref_bytes,char *rec,int rec_bytes); #ifdef __cplusplus }; #endif #endif <file_sep>/os/.svn/pristine/ee/ee58ccbf5cface56cba62da77366db0cc9b03fb5.svn-base #ifndef WTK_OS_WTK_PID_H_ #define WTK_OS_WTK_PID_H_ #include "wtk/core/wtk_type.h" #include "wtk/os/wtk_proc.h" #include "wtk/core/wtk_os.h" #ifdef __cplusplus extern "C" { #endif #ifdef WIN32 #else #include <sys/types.h> #include <sys/wait.h> int pid_kill(pid_t pid); int pid_setup_signal(); void pid_daemonize(); void pid_save_file(pid_t pid,char *fn); void pid_delete_file(pid_t pid,char* pf); int pid_from_file(char *fn); #endif #ifdef __cplusplus }; #endif #endif <file_sep>/os/wtk_thread2.c #include "wtk_thread2.h" int wtk_thread2_run(wtk_thread2_t *t2,wtk_thread_t *t); wtk_thread2_t* wtk_thread2_new(void *ths, wtk_thread2_start_f start, wtk_thread2_stop_f stop, wtk_thread2_process_f process, wtk_thread2_err_f err) { wtk_thread2_t *t; t=(wtk_thread2_t*)wtk_malloc(sizeof(wtk_thread2_t)); t->ths=ths; t->start=start; t->stop=stop; t->process=process; t->err=err; t->run=0; wtk_sem_init(&(t->notify_sem),0); wtk_blockqueue_init(&(t->input_q)); wtk_queue_init(&(t->time_q)); wtk_thread_init(&(t->thread),(thread_route_handler)wtk_thread2_run,t); return t; } void wtk_thread2_delete(wtk_thread2_t *t) { wtk_thread_clean(&(t->thread)); wtk_sem_clean(&(t->notify_sem)); wtk_free(t); } int wtk_thread2_start(wtk_thread2_t *t) { t->run=1; return wtk_thread_start(&(t->thread)); } int wtk_thread2_stop(wtk_thread2_t *t) { t->run=0; wtk_blockqueue_wake(&(t->input_q)); return wtk_thread_join(&(t->thread)); } wtk_thread2_msg_t* wtk_thread2_msg_new(wtk_thread2_msg_type_t type,void *data) { wtk_thread2_msg_t *msg; msg=(wtk_thread2_msg_t*)wtk_malloc(sizeof(wtk_thread2_msg_t)); msg->type=type; msg->data=data; return msg; } void wtk_thread2_msg_delete(wtk_thread2_msg_t *msg) { wtk_free(msg); } void wtk_thread2_msg_start(wtk_thread2_t *t) { wtk_thread2_msg_t *msg; msg=wtk_thread2_msg_new(WTK_THREAD2_START,NULL); wtk_blockqueue_push(&(t->input_q),&(msg->q_n)); } void wtk_thread2_msg_cancel(wtk_thread2_t *t2) { wtk_queue_node_t *qn; wtk_thread2_msg_t *msg; while(1) { qn=wtk_blockqueue_pop(&(t2->input_q),0,NULL); if(!qn){break;} msg=data_offset2(qn,wtk_thread2_msg_t,q_n); if(msg->type==WTK_THREAD2_STOP) { wtk_blockqueue_push(&(t2->input_q),qn); break; } if(t2->err) { t2->err(t2->ths,msg->data); } wtk_thread2_msg_delete(msg); } } void wtk_thread2_msg_process(wtk_thread2_t *t,void *data) { wtk_thread2_msg_t *msg; msg=wtk_thread2_msg_new(WTK_THREAD2_PROCESS,data); wtk_blockqueue_push(&(t->input_q),&(msg->q_n)); } int wtk_thread2_msg_stop(wtk_thread2_t *t) { return wtk_thread2_msg_stop2(t,1); } int wtk_thread2_msg_stop2(wtk_thread2_t *t,int wait_eof) { wtk_thread2_msg_t *msg; msg=wtk_thread2_msg_new(WTK_THREAD2_STOP,NULL); wtk_blockqueue_push(&(t->input_q),&(msg->q_n)); //wtk_debug("wait end1 %p....\n",t); if(wait_eof) { wtk_thread2_msg_wait_stop(t,-1); } //wtk_debug("=============> wait end....\n"); return 0; } int wtk_thread2_msg_wait_stop(wtk_thread2_t *t,int timeout) { return wtk_sem_acquire(&(t->notify_sem),timeout); } wtk_thread2_timer_t* wtk_thread2_timer_new(double delay,wtk_thread2_timer_func_t func,void *ths,void *hook) { wtk_thread2_timer_t *t; t=(wtk_thread2_timer_t*)wtk_malloc(sizeof(wtk_thread2_timer_t)); t->t=time_get_ms()+delay; t->func=func; t->ths=ths; t->hook=hook; return t; } void wtk_thread2_timer_delete(wtk_thread2_timer_t *t) { wtk_free(t); } void wtk_thread2_touch_timer(wtk_thread2_t *dlg) { wtk_queue_node_t *qn; wtk_queue_t *q=&(dlg->time_q); wtk_thread2_timer_t *timer; double t; //wtk_debug("====================> touch timer %d\n",q->length); while(1) { qn=q->pop; if(!qn){break;} timer=data_offset2(qn,wtk_thread2_timer_t,q_n); t=time_get_ms(); //wtk_debug("===========> touch timer %f\n",t-timer->t); //wtk_debug("time=%f,%f\n",t,timer->t); if(timer->t<=t) { wtk_queue_pop(q); timer->func(timer->ths,timer->hook); wtk_thread2_timer_delete(timer); }else { break; } } } void wtk_thread2_add_timer(wtk_thread2_t *dlg,double delay,wtk_thread2_timer_func_t func,void *ths,void *hook) { wtk_thread2_timer_t *timer,*tx; wtk_queue_node_t *qn,*suc; timer=wtk_thread2_timer_new(delay,func,ths,hook); //wtk_debug("time_q=%d\n",dlg->time_q.length); if(dlg->time_q.length>0) { suc=NULL; for(qn=dlg->time_q.pop;qn;qn=qn->next) { tx=data_offset2(qn,wtk_thread2_timer_t,q_n); if(tx->t>timer->t) { suc=qn; break; } } if(suc) { wtk_queue_insert_before(&(dlg->time_q),suc,&(timer->q_n)); }else { wtk_queue_push(&(dlg->time_q),&(timer->q_n)); } }else { wtk_queue_push(&(dlg->time_q),&(timer->q_n)); } } int wtk_thread2_run(wtk_thread2_t *t2,wtk_thread_t *t) { typedef enum { WTK_THREAD2_INIT, WTK_THREAD2_DATA, }wtk_thread2_state_t; wtk_queue_node_t *qn; wtk_thread2_msg_t *msg; wtk_thread2_state_t state; int ret; state=WTK_THREAD2_INIT; while(t2->run) { qn=wtk_blockqueue_pop(&(t2->input_q),100,NULL); if(!qn) { wtk_thread2_touch_timer(t2); continue; } msg=data_offset2(qn,wtk_thread2_msg_t,q_n); switch(state) { case WTK_THREAD2_INIT: if(msg->type==WTK_THREAD2_START) { if(t2->start) { ret=t2->start(t2->ths); if(ret==0) { state=WTK_THREAD2_DATA; }else { wtk_debug("err[%s] start failed\n",t->name); } }else { state=WTK_THREAD2_DATA; } }else { //wtk_debug("err[%s] msg: %d %p\n",t->name,msg->type,t2->err); if(t2->err) { t2->err(t2->ths,msg->data); } } break; case WTK_THREAD2_DATA: switch(msg->type) { case WTK_THREAD2_START: wtk_debug("err[%s] msg: %d\n",t->name,msg->type); break; case WTK_THREAD2_STOP: if(t2->stop) { t2->stop(t2->ths); } //wtk_debug("notify end....\n"); //wtk_debug("notify end2 %p....\n",t); state=WTK_THREAD2_INIT; break; case WTK_THREAD2_PROCESS: if(t2->process) { t2->process(t2->ths,msg->data); } break; } break; } if(msg->type==WTK_THREAD2_STOP) { wtk_sem_release(&(t2->notify_sem),1); } wtk_thread2_msg_delete(msg); } return 0; } <file_sep>/core/.svn/pristine/59/59a10a6117aaf8c3bcaca3703327aba8f152e39d.svn-base #ifndef WTK_CORE_ZIP_WTK_ZIP #define WTK_CORE_ZIP_WTK_ZIP #include "wtk/core/wtk_type.h" #include "wtk_zip_cfg.h" #include "wtk/core/wtk_queue2.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_zip wtk_zip_t; typedef struct wtk_zip_blk wtk_zip_blk_t; typedef struct wtk_zip_item wtk_zip_item_t; struct wtk_zip_item { // wtk_zip_blk_t *prev_blk; // unsigned int id;' wtk_queue_node_t q_n; wtk_queue2_t next_q; unsigned short prev; unsigned char c; unsigned char used:1; }; struct wtk_zip_blk { wtk_queue_node_t q_n; wtk_zip_item_t *item; }; struct wtk_zip { wtk_zip_cfg_t *cfg; wtk_strbuf_t *buf; unsigned int cache_v; int cache_bit; int len; wtk_zip_item_t *item; unsigned short nxt_idx; wtk_zip_item_t *prev_item; unsigned int cnt; //unsigned short prev_idx; unsigned use:1; }; extern unsigned int zip_bit_map[]; wtk_zip_t* wtk_zip_new(wtk_zip_cfg_t *cfg); void wtk_zip_delete(wtk_zip_t *z); void wtk_zip_reset(wtk_zip_t *z); int wtk_zip_file(wtk_zip_t *z,char *ifn,char *ofn); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_queue.h #ifndef _WTK_CORE_WTK_QUEUE_H_ #define _WTK_CORE_WTK_QUEUE_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_str.h" #include <stddef.h> #ifdef __cplusplus extern "C" { #endif struct wtk_heap; typedef struct wtk_queue_node wtk_queue_node_t; typedef struct wtk_queue wtk_queue_t; //#define wtk_queue_node_data(q,type,link) ( (q) ? (void*)((char*)q-(unsigned long)&(((type*)0)->link)) : 0) #define wtk_queue_node_data(q,type,link) (type*)((q)>0 ? (void*)((char*)q-offsetof(type,link)) : 0) #define wtk_queue_node_data_byof(q,off) ( (q)> 0 ? ((void*)((char*)q-off)) : 0) #define wtk_queue_node_init(n) (n)->next=(n)->prev=0 #define wtk_queue_init(q) memset(q,0,sizeof(*q)) typedef void (*queue_push_listener)(void* data); struct wtk_queue_node { wtk_queue_node_t* next; wtk_queue_node_t* prev; }; typedef struct { wtk_queue_node_t q_n; void *hook; }wtk_queue_item_t; typedef struct { wtk_queue_node_t q_n; union { float f; void *p; wtk_string_t str; }v; }wtk_queue_node_v_t; #define WTK_QUEUE \ wtk_queue_node_t *pop; \ wtk_queue_node_t *push; \ int length;\ queue_push_listener listener; \ void *data; \ struct wtk_queue { WTK_QUEUE }; /** * @brief create queue from heap; */ wtk_queue_t* wtk_queue_new_h(struct wtk_heap *h); /** * @brief new queue, just malloc wtk_queue_t memory and init; */ wtk_queue_t* wtk_queue_new(); /** * @brief free memory of wtk_queue_t; */ int wtk_queue_delete(wtk_queue_t *q); /** * @brief init queue struct; */ int wtk_queue_init2(wtk_queue_t *q); /** * @brief push node to the tail of the queue; */ int wtk_queue_push(wtk_queue_t *q,wtk_queue_node_t *n); /** * add src to dst */ void wtk_queue_link(wtk_queue_t *dst,wtk_queue_t *src); /** * @brief push node to the head of the queue; */ int wtk_queue_push_front(wtk_queue_t *q,wtk_queue_node_t *n); /** * @brief remove node from queue; * @warning: make sure node n is in queue; */ int wtk_queue_remove(wtk_queue_t *q,wtk_queue_node_t *n); /** * @brief pop the head node from queue; */ wtk_queue_node_t* wtk_queue_pop(wtk_queue_t *q); wtk_queue_node_t* wtk_queue_pop_back(wtk_queue_t *q); /** * @brief insert n2 node after n, like: * n->next=n2; n2->prev=n; * dono't care about n->next queue list; * n->n00->n01->n02 * => n->n2->n20->n21->n22; * n2->n20->n21->n22 * * this usually used the next node of n is not important,and attach n2; */ void wtk_queue_insert_to(wtk_queue_t *q,wtk_queue_node_t *n,wtk_queue_node_t* n2); /* * @brief insert n2 befor n; */ void wtk_queue_insert_before(wtk_queue_t *q,wtk_queue_node_t *n,wtk_queue_node_t *n2); /** * @brief find value by cmp handler, value is node of queue minus of; */ void* wtk_queue_find(wtk_queue_t *q,int of,wtk_cmp_handler_t cmp,void *user_data); /** * @brief swap n1 and n2 in the queue; */ void wtk_queue_swap(wtk_queue_t *q,wtk_queue_node_t *n1,wtk_queue_node_t *n2); /** * @brief move node the end of queue(push). */ void wtk_queue_touch_node(wtk_queue_t *q,wtk_queue_node_t *n); /** * @brief move node the head of queue(push). */ void wtk_queue_touch_front(wtk_queue_t *q,wtk_queue_node_t *n); /** * @brief set push listener, when push element to the queue, listener is called * notify there is some element is pushed, used for multithread blockqueue; */ void wtk_queue_set_push_listener(wtk_queue_t *q,queue_push_listener l,void *data); /** * @brief traversal node of the queue; * for walk: typedef int (*wtk_walk_handler_t)(void *user_data,void* data); * data: node - of; */ int wtk_queue_walk(wtk_queue_t *q,int of,wtk_walk_handler_t walk,void *user_data); /** * @brief peek node at given index,index is [0,length) */ wtk_queue_node_t* wtk_queue_peek(wtk_queue_t *q,int index); /** * @brief print the queue; * for print:typedef void (*wtk_print_handler_t)(void *data); * data: node -of; */ void wtk_queue_print(wtk_queue_t *q,int of,wtk_print_handler_t print); /** * wtk_cmp_handler_t(wtk_queue_node_t *src,wtk_queue_node_t *dst); */ void wtk_queue_insert(wtk_queue_t *q,wtk_queue_node_t *n,wtk_cmp_handler_t cmp); /** * @brief check queue is valid or not; */ int wtk_queue_check(wtk_queue_t *q); int wtk_queue_node_len(wtk_queue_node_t *qn); wtk_queue_node_t* wtk_queue_find_node(wtk_queue_t *q,wtk_queue_node_t *qn); typedef int (*wtk_queue_node_cmp_f)(wtk_queue_node_t *qn1,wtk_queue_node_t *qn2); void wtk_queue_sort(wtk_queue_t *q,wtk_queue_node_cmp_f cmp); //------------------------ test/example section ------------ void wtk_queue_test_g(); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_jsonkv.h #ifndef WTK_CORE_WTK_JSONKV #define WTK_CORE_WTK_JSONKV #include "wtk/core/wtk_type.h" #include "wtk/core/json/wtk_json_parse.h" #include "wtk/core/wtk_strbuf.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_jsonkv wtk_jsonkv_t; #define wtk_jsonkv_set_s(kv,k,a,a_bytes,v,v_bytes) wtk_jsonkv_set(kv,k,sizeof(k)-1,a,a_bytes,v,v_bytes) #define wtk_jsonkv_set_ss(kv,k,a,v,v_bytes) wtk_jsonkv_set(kv,k,sizeof(k)-1,a,sizeof(a)-1,v,v_bytes) #define wtk_jsonkv_set_sss(kv,k,a,v) wtk_jsonkv_set(kv,k,sizeof(k)-1,a,sizeof(a)-1,v,sizeof(v)-1) #define wtk_jsonkv_get_s(kv,k,a,a_bytes) wtk_jsonkv_get(kv,k,sizeof(k)-1,a,a_bytes) #define wtk_jsonkv_get_ss(kv,k,a) wtk_jsonkv_get(kv,k,sizeof(k)-1,a,sizeof(a)-1) typedef wtk_string_t (*wtk_jsonkv_get_map_f)(void *ths,char *k,int k_len); #define wtk_jsonkv_get_json_s(kv,s) wtk_jsonkv_get_json(kv,s,sizeof(s)-1) struct wtk_jsonkv { wtk_json_parser_t *json_parser; wtk_strbuf_t *dn; wtk_strbuf_t *buf; //used for save json file name wtk_strbuf_t *tmp; void *get_map_ths; wtk_jsonkv_get_map_f get_map; }; wtk_jsonkv_t* wtk_jsonkv_new(char *dn); void wtk_jsonkv_delete(wtk_jsonkv_t *kv); void wtk_jsonkv_reset(wtk_jsonkv_t *kv); void wtk_jsonkv_set_dn(wtk_jsonkv_t *kv,char *dn); wtk_string_t wtk_jsonkv_get_dat(wtk_jsonkv_t *kv,char *k,int k_bytes); wtk_json_t* wtk_jsonkv_get_json(wtk_jsonkv_t *kv,char *k,int k_bytes); void wtk_jsonkv_save_json(wtk_jsonkv_t *kv,char *k,int k_bytes,wtk_json_t *json); void wtk_jsonkv_set_dat(wtk_jsonkv_t *kv,char *k,int k_bytes,char *v,int v_bytes); wtk_string_t wtk_jsonkv_get(wtk_jsonkv_t *kv,char *k,int k_bytes,char *attr,int attr_bytes); void wtk_jsonkv_set(wtk_jsonkv_t *kv,char *k,int k_bytes,char *attr,int attr_bytes,char *v,int v_bytes); #ifdef __cplusplus }; #endif #endif <file_sep>/os/wtk_rw_lock.h #ifndef WTK_OS_WTK_RW_LOCK #define WTK_OS_WTK_RW_LOCK #include "wtk/core/wtk_type.h" #include "wtk_lock.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_rw_lock wtk_rw_lock_t; struct wtk_rw_lock { wtk_lock_t lock; wtk_lock_t xlock; volatile unsigned r; volatile unsigned w; }; void wtk_rw_lock_init(wtk_rw_lock_t *lock); void wtk_rw_lock_clean(wtk_rw_lock_t *lock); void wtk_rw_lock_lock_read(wtk_rw_lock_t *lock); void wtk_rw_lock_unlock_read(wtk_rw_lock_t *lock); void wtk_rw_lock_inc_read(wtk_rw_lock_t *lock); void wtk_rw_lock_dec_read(wtk_rw_lock_t *lock); void wtk_rw_lock_start_write(wtk_rw_lock_t *lock); void wtk_rw_lock_stop_write(wtk_rw_lock_t *lock); void wtk_rw_lock_start_read(wtk_rw_lock_t *lock); void wtk_rw_lock_stop_read(wtk_rw_lock_t *lock); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/49/4936c069a7922ade3daad31b31a5588b5b8abebe.svn-base #ifndef WTK_CORE_WTK_HOARD_H_ #define WTK_CORE_WTK_HOARD_H_ #include "wtk/core/wtk_type.h" #include "wtk_queue.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_hoard wtk_hoard_t; typedef int (*wtk_hoard_bytes_f)(void *data); #define WTK_HOARD \ wtk_queue_node_t *free; \ wtk_queue_node_t *use; \ wtk_new_handler_t newer; \ wtk_delete_handler_t deleter; \ wtk_delete_handler2_t deleter2; \ void *user_data; \ int offset; \ int max_free; \ int cur_free; \ int use_length; struct wtk_hoard { WTK_HOARD /* wtk_queue_node_t *free; //is the last node in the queue. wtk_queue_node_t *use; //the last node in the queue. wtk_new_handler_t newer; wtk_delete_handler_t deleter; void *user_data; int offset; int max_free; int cur_free; int use_length; */ }; /** * @param offet, offsetof wtk_queuenode_t in the user struct; * @param max_free, cache size; * @param newer, object create function; * @param deleter, object delete function; * @param data, newer function app_data; */ int wtk_hoard_init(wtk_hoard_t *h,int offset,int max_free,wtk_new_handler_t newer, wtk_delete_handler_t deleter,void *data); int wtk_hoard_init2(wtk_hoard_t *h,int offset,int max_free,wtk_new_handler_t newer, wtk_delete_handler2_t deleter,void *data); void wtk_hoard_reset(wtk_hoard_t *h); /** * @brief delete all memory; */ int wtk_hoard_clean(wtk_hoard_t *h); /** * @brief pop element; */ void* wtk_hoard_pop(wtk_hoard_t *h); /** * @brief push element; */ int wtk_hoard_push(wtk_hoard_t *h,void* data); int wtk_hoard_bytes(wtk_hoard_t *h,wtk_hoard_bytes_f bf); /* * @brief reuse use queue; */ void wtk_hoard_reuse(wtk_hoard_t *h); void wtk_hoard_pack(wtk_hoard_t *h); //=============== hoard test section ================= void wtk_hoard_test_g(); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/c9/c95a481176611ac147b532be9e694551c6695454.svn-base #include "wtk_heap.h" #include "wtk_array.h" #include "wtk_str_encode.h" #define WTK_HEAP_TRY_CNT 3 wtk_heap_block_t* wtk_heap_block_new(int page_size) { wtk_heap_block_t *blk; char *p; p=(char*)wtk_malloc(page_size); blk=(wtk_heap_block_t*)p; blk->first=p+sizeof(wtk_heap_block_t); blk->end=p+page_size; blk->cur=blk->first; blk->failed=0; return blk; } void wtk_heap_block_reset(wtk_heap_block_t *blk) { blk->cur=blk->first; blk->failed=0; } void wtk_heap_block_delete(wtk_heap_block_t *blk) { wtk_free(blk); } wtk_heap_t* wtk_heap_new(int page_size) { return wtk_heap_new2(page_size,16); } wtk_heap_t* wtk_heap_new2(int page_size,int align_size) { wtk_heap_t *heap; heap=(wtk_heap_t*)wtk_malloc(sizeof(wtk_heap_t)); wtk_queue2_init(&(heap->block_q)); wtk_queue2_init(&(heap->large_q)); heap->align=align_size; heap->page_size=page_size; heap->alloc_size=heap->page_size-sizeof(wtk_heap_block_t); heap->large_thresh=page_size-sizeof(wtk_heap_block_t); heap->cur=wtk_heap_block_new(heap->page_size); wtk_queue2_push(&(heap->block_q),&(heap->cur->q_n)); return heap; } void wtk_heap_delete(wtk_heap_t *heap) { wtk_heap_reset(heap); wtk_heap_block_delete(heap->cur); wtk_free(heap); } void wtk_heap_reset_large(wtk_heap_t *heap) { wtk_queue_node_t *qn; wtk_heap_large_t *l; while(1) { qn=wtk_queue2_pop(&(heap->large_q)); if(!qn){break;} l=data_offset2(qn,wtk_heap_large_t,q_n); if(l->data) { wtk_free(l->data); } } } void wtk_heap_reset(wtk_heap_t *heap) { wtk_queue_node_t *qn; wtk_heap_block_t *blk; wtk_heap_reset_large(heap); wtk_queue2_remove(&(heap->block_q),&(heap->cur->q_n)); while(1) { qn=wtk_queue2_pop(&(heap->block_q)); if(!qn){break;} blk=data_offset2(qn,wtk_heap_block_t,q_n); wtk_heap_block_delete(blk); } wtk_heap_block_reset(heap->cur); wtk_queue2_push(&(heap->block_q),&(heap->cur->q_n)); } char* wtk_heap_malloc_large(wtk_heap_t *heap,int bytes) { wtk_heap_large_t *l; char *p; p=(char*)wtk_malloc(bytes); if(!p){return NULL;} l=(wtk_heap_large_t*)wtk_heap_malloc(heap,sizeof(wtk_heap_large_t)); l->data=p; l->size=bytes; wtk_queue2_push(&(heap->large_q),&(l->q_n)); return p; } void wtk_heap_add_large(wtk_heap_t *heap,char *p,int size) { wtk_heap_large_t* l; l=(wtk_heap_large_t*)wtk_heap_malloc(heap,sizeof(wtk_heap_large_t)); l->data=p; l->size=size; wtk_queue2_push(&(heap->large_q),&(l->q_n)); } char* wtk_heap_malloc_block(wtk_heap_t *heap,int bytes) { wtk_heap_block_t *blk; wtk_queue_node_t *qn; char *p; blk=wtk_heap_block_new(heap->page_size); wtk_queue2_push(&(heap->block_q),&(blk->q_n)); p=wtk_align_ptr(blk->cur,heap->align); if(p+bytes>blk->end) { p=wtk_heap_malloc_large(heap,bytes); }else { blk->cur=p+bytes; } if(heap->cur->failed>=WTK_HEAP_TRY_CNT) { blk=heap->cur; heap->cur=NULL; for(qn=blk->q_n.next;qn;qn=qn->next) { blk=data_offset2(qn,wtk_heap_block_t,q_n); if((blk->failed<WTK_HEAP_TRY_CNT) && (blk->end>blk->cur)) { heap->cur=blk; break; } } if(!heap->cur) { heap->cur=data_offset2(heap->block_q.pop,wtk_heap_block_t,q_n); } } return p; } #ifdef USE_HEAP void* wtk_heap_malloc(wtk_heap_t *heap,int bytes) { return malloc(bytes); } #else void* wtk_heap_malloc(wtk_heap_t *heap,int bytes) { wtk_heap_block_t *blk; char *p; int align; if(bytes<=0) { return NULL; }else if(bytes>heap->large_thresh) { return (void*)wtk_heap_malloc_large(heap,bytes); } align=heap->align; blk=heap->cur; do { p=align>1?wtk_align_ptr(blk->cur,align):blk->cur; if((blk->end-p)>=bytes) { blk->cur=p+bytes; return p; } if(blk->q_n.next) { ++blk->failed; if(blk->failed>=WTK_HEAP_TRY_CNT) { blk=data_offset2(blk->q_n.next,wtk_heap_block_t,q_n); heap->cur=blk; }else { blk=data_offset2(blk->q_n.next,wtk_heap_block_t,q_n); } }else { break; } }while(blk); return (void*)wtk_heap_malloc_block(heap,bytes); } #endif void wtk_heap_free(wtk_heap_t *heap,void *p) { wtk_queue2_t *q=&(heap->block_q); wtk_queue_node_t *qn; wtk_heap_block_t *blk; char *pc=(char*)p; while(1) { qn=wtk_queue2_pop(q); if(!qn){break;} blk=data_offset2(qn,wtk_heap_block_t,q_n); if(blk==heap->cur) { heap->cur=NULL; } if(pc>=blk->first && pc <=blk->cur) { blk->cur=p; wtk_queue2_push(q,&(blk->q_n)); break; }else { wtk_heap_block_delete(blk); } } if(!heap->cur) { if(q->pop) { heap->cur=data_offset2(q->push,wtk_heap_block_t,q_n); }else { heap->cur=wtk_heap_block_new(heap->page_size); wtk_queue2_push(q,&(heap->cur->q_n)); } } } void wtk_heap_free_large(wtk_heap_t *heap,void *p) { wtk_queue_node_t *qn; wtk_heap_large_t *l; for(qn=heap->large_q.pop;qn;qn=qn->next) { l=data_offset2(qn,wtk_heap_large_t,q_n); if(l->data==p) { wtk_queue2_remove(&(heap->large_q),qn); wtk_free(l->data); return; } } } wtk_string_t* wtk_heap_dup_string(wtk_heap_t *h,char *s,int sl) { wtk_string_t *str; str=(wtk_string_t*)wtk_heap_malloc(h,sizeof(*str)+sl); str->len=sl; str->data=(char*)str+sizeof(*str); if(s) { memcpy(str->data,s,sl); } return str; } char* wtk_heap_dup_data(wtk_heap_t *h,const char *s,int l) { char *data; data=(char*)wtk_heap_malloc(h,l); if(!data){goto end;} memcpy(data,s,l); end: return data; } wtk_string_t* wtk_heap_dup_string2(wtk_heap_t *h,char *s,int sl) { wtk_string_t *str; str=(wtk_string_t*)wtk_heap_malloc(h,sizeof(*str)+sl+1); str->len=sl; str->data=(char*)str+sizeof(*str); if(s) { memcpy(str->data,s,sl); } str->data[sl]=0; return str; } void* wtk_heap_zalloc(wtk_heap_t* heap,size_t size) { void *p; p=wtk_heap_malloc(heap,size); if(p) { memset(p,0,size); } return p; } char *wtk_heap_dup_str(wtk_heap_t *heap,char* s) { return wtk_heap_dup_str2(heap,s,s?strlen(s):0); } char* wtk_heap_dup_str2(wtk_heap_t *heap,char *data,int len) { char *d=0; if(len<=0){goto end;} d=(char*)wtk_heap_malloc(heap,len+1); memcpy(d,data,len); d[len]=0; end: return d; } void wtk_heap_fill_string(wtk_heap_t *heap,wtk_string_t *str,char *data,int bytes) { str->data=wtk_heap_dup_data(heap,data,bytes); str->len=bytes; } int wtk_heap_bytes(wtk_heap_t *heap) { wtk_heap_large_t* l; wtk_queue_node_t *qn; int size; size=0; for(qn=heap->large_q.pop;qn;qn=qn->next) { l=data_offset2(qn,wtk_heap_large_t,q_n); size+=l->size; } for(qn=heap->block_q.pop;qn;qn=qn->next) { //p=data_offset2(qn,wtk_heap_block_t,q_n); size+=heap->page_size; } return size; } void wtk_heap_print(wtk_heap_t *heap) { wtk_heap_large_t* l; wtk_heap_block_t *p; wtk_queue_node_t *qn; int count,size; printf("########## Heap #############\n"); size=0;count=0; for(qn=heap->large_q.pop;qn;qn=qn->next) { l=data_offset2(qn,wtk_heap_large_t,q_n); size+=l->size; ++count; } printf("large list:\t%d\n",count); printf("large bytes:\t%d\n",size); size=0;count=0; for(qn=heap->block_q.pop;qn;qn=qn->next) { p=data_offset2(qn,wtk_heap_block_t,q_n); ++count; size+=p->cur-p->first; } printf("block list:\t%d\n",count); printf("block bytes:\t%d\n",size); } wtk_array_t* wtk_utf8_string_to_chars(wtk_heap_t *heap,char *data,int bytes) { char *s,*e; int num; wtk_array_t *a; wtk_string_t *v; a=wtk_array_new_h(heap,bytes,sizeof(wtk_string_t*)); s=data;e=s+bytes; while(s<e) { num=wtk_utf8_bytes(*s); s+=num; if(s>e){break;} //wtk_debug("[%.*s]\n",num,s-num); v=wtk_heap_dup_string(heap,s-num,num); *((wtk_string_t**)(wtk_array_push(a)))=v; } return a; } <file_sep>/core/.svn/pristine/98/98a8efaedca72da671ae5d5211e78676471b1c6f.svn-base #include "wtk_eos.h" wtk_eos_t* wtk_eos_new() { wtk_eos_t *o; o=(wtk_eos_t*)wtk_malloc(sizeof(*o)); o->err=wtk_errno_new(); return o; } int wtk_eos_delete(wtk_eos_t *o) { wtk_errno_delete(o->err); wtk_free(o); return 0; } int wtk_eos_reset(wtk_eos_t *o) { wtk_errno_reset(o->err); return 0; } <file_sep>/core/.svn/pristine/83/8302c886f44140dc4d32f974142849ce86980c1e.svn-base #ifndef WTK_CORE_CFG_WTK_VERSION_CFG_H_ #define WTK_CORE_CFG_WTK_VERSION_CFG_H_ #include "wtk/core/cfg/wtk_local_cfg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_version_cfg wtk_version_cfg_t; struct wtk_version_cfg { char version_buf[sizeof("000.000.000.2012.00.00.00:00:00")]; wtk_string_t ver; }; int wtk_version_cfg_init(wtk_version_cfg_t *cfg,char *v); int wtk_version_cfg_clean(wtk_version_cfg_t *cfg); int wtk_version_cfg_update_local(wtk_version_cfg_t *cfg,wtk_local_cfg_t *lc); int wtk_version_cfg_update(wtk_version_cfg_t *cfg); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/70/7009b8f023a86507b8e2be018e12b8b49b697d56.svn-base #ifndef WTK_CORE_WTK_HARRAY_H_ #define WTK_CORE_WTK_HARRAY_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_heap.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_harray wtk_harray_t; struct wtk_harray { wtk_heap_t *heap; void **slot; int nslot1; int nslot2; }; wtk_harray_t* wtk_harray_new(int nslot1,int nslot2); void wtk_harray_delete(wtk_harray_t *h); int wtk_harray_bytes(wtk_harray_t *h); void wtk_harray_reset(wtk_harray_t *h); void* wtk_harray_get(wtk_harray_t *h,unsigned long idx); void wtk_harray_set(wtk_harray_t *h,unsigned long idx,void *p); #ifdef __cplusplus }; #endif #endif <file_sep>/core/segmenter/wtk_chnpos_model.c #include "wtk_chnpos_model.h" wtk_chnpos_model_t* wtk_chnpos_model_new() { wtk_chnpos_model_t *m; m=(wtk_chnpos_model_t*)wtk_malloc(sizeof(wtk_chnpos_model_t)); m->pos_map=wtk_str_hash_new(137); m->npos=0; m->pos_a=wtk_larray_new(64,sizeof(wtk_string_t*)); m->state_robin=NULL; //wtk_queue_init(&(m->state_q)); m->wrd_map=NULL; m->state_map=NULL;//wtk_str_hash_new(4703); return m; } void wtk_chnpos_model_delete(wtk_chnpos_model_t *m) { wtk_larray_delete(m->pos_a); wtk_str_hash_delete(m->pos_map); if(m->wrd_map) { wtk_str_hash_delete(m->wrd_map); } if(m->state_map) { wtk_hash_delete(m->state_map); } if(m->state_robin) { wtk_robin_delete(m->state_robin); } wtk_free(m); } wtk_chnpos_bmes_t wtk_chnpos_bmes_parse(char *s,int bytes) { if(wtk_str_equal_s(s,bytes,"B")) { return WTK_CHNPOS_B; }else if(wtk_str_equal_s(s,bytes,"M")) { return WTK_CHNPOS_M; }else if(wtk_str_equal_s(s,bytes,"E")) { return WTK_CHNPOS_E; }else //else if(wtk_str_equal_s(s,bytes,"S")) { return WTK_CHNPOS_S; } } unsigned char wtk_chnpos_model_pos_parse(wtk_chnpos_model_t *m,char *pos,int pos_bytes,int insert) { wtk_hash_str_node_t *node; node=(wtk_hash_str_node_t*)wtk_str_hash_find_node3(m->pos_map,pos,pos_bytes,insert); if(!node) { return 0; } if(node->v.u==0) { wtk_string_t *v; v=wtk_heap_dup_string(m->pos_map->heap,pos,pos_bytes); wtk_larray_push2(m->pos_a,&v); node->v.u=++m->npos; } return node->v.u; } wtk_string_t* wtk_chnpos_model_get_pos_str(wtk_chnpos_model_t *m,int idx) { wtk_string_t **strs; strs=(wtk_string_t**)(m->pos_a->slot); return strs[idx-1]; } int wtk_chnpos_model_get_pos_walk(void *data,wtk_hash_str_node_t *node) { void **p; int *pn; p=(void**)data; pn=p[0]; if(node->v.u==*pn) { p[1]=&(node->key); return -1; }else { return 0; } } wtk_string_t* wtk_chnpos_model_get_pos(wtk_chnpos_model_t *m,int n) { void *p[2]; p[0]=&n; p[1]=NULL; wtk_str_hash_walk(m->pos_map,(wtk_walk_handler_t)wtk_chnpos_model_get_pos_walk,p); return (wtk_string_t*)p[1]; } char* wtk_bmes_to_str(int bmes) { char *s=NULL; switch(bmes) { case WTK_CHNPOS_B: s="B"; break; case WTK_CHNPOS_M: s="M"; break; case WTK_CHNPOS_E: s="E"; break; case WTK_CHNPOS_S: s="S"; break; } return s; } void wtk_chnpos_state_print(wtk_chnpos_model_t *m,wtk_chnpos_state_t *item) { wtk_string_t *k; int i; char *s; s=wtk_bmes_to_str(item->bmes); printf("%s ",s); k=wtk_chnpos_model_get_pos(m,item->pos); printf("%.*s %f\n",k->len,k->data,item->start); for(i=0;i<item->narc;++i) { k=wtk_chnpos_model_get_pos(m,item->arcs[i].to->pos); //printf("arc[%d/%d]=%s %.*s %f\n",i,item->narc,wtk_bmes_to_str(item->arcs[i].to->bmes),k->len,k->data,item->arcs[i].prob); if(0) { printf("%s %.*s %f\n",wtk_bmes_to_str(item->arcs[i].to->bmes),k->len,k->data,item->arcs[i].prob); } } } void wtk_chnpos_wrd_print(wtk_chnpos_model_t *m,wtk_chnpos_wrd_t *wrd) { int i; printf("%.*s %d\n",wrd->wrd.len,wrd->wrd.data,wrd->nstate); for(i=0;i<wrd->nstate;++i) { wtk_chnpos_state_print(m,wrd->states[i]); } } wtk_chnpos_wrd_t* wtk_chnpos_model_new_wrd(wtk_chnpos_model_t *m,char *wrd,int wrd_bytes,int nstate) { wtk_heap_t *heap=m->wrd_map->heap; wtk_chnpos_wrd_t *w; // if(wtk_str_equal_s(wrd,wrd_bytes,"囧")) // { // wtk_debug("[%.*s]=%d\n",wrd_bytes,wrd,nstate); // } w=(wtk_chnpos_wrd_t*)wtk_heap_malloc(heap,sizeof(wtk_chnpos_wrd_t)); //w->wrd=wtk_heap_dup_string(heap,wrd,wrd_bytes); wtk_heap_fill_string(heap,&(w->wrd),wrd,wrd_bytes); w->nstate=nstate; w->states=(wtk_chnpos_state_t**)wtk_heap_malloc(heap,sizeof(wtk_chnpos_state_t*)*nstate); wtk_str_hash_add(m->wrd_map,w->wrd.data,w->wrd.len,w); return w; } wtk_chnpos_wrd_t* wtk_chnpos_model_get_wrd(wtk_chnpos_model_t *m,char *wrd,int wrd_bytes) { return (wtk_chnpos_wrd_t*)wtk_str_hash_find(m->wrd_map,wrd,wrd_bytes); } wtk_chnpos_wrd_t wtk_chnpos_model_get_wrd2(wtk_chnpos_model_t *m,char *wrd,int wrd_bytes) { wtk_chnpos_wrd_t *w,tw; w=wtk_chnpos_model_get_wrd(m,wrd,wrd_bytes); if(w && w->nstate>0) { tw=*w; goto end; } wtk_string_set(&(tw.wrd),wrd,wrd_bytes); tw.states=(wtk_chnpos_state_t**)(m->state_robin->r); tw.nstate=m->state_robin->used; end: return tw; } unsigned int wtk_chnpos_state_hash(wtk_chnpos_state_t *state,unsigned int nslot) { unsigned int v; v=(state->pos<<8)+state->bmes; return v%(nslot); } int wtk_chnpos_state_cmp(wtk_chnpos_state_t *src,wtk_chnpos_state_t *dst) { if(src->bmes!=dst->bmes) { return src->bmes-dst->bmes; } if(src->pos!=dst->pos) { return src->pos-dst->pos; } return 0; } wtk_chnpos_state_t* wtk_chnpos_model_get_state(wtk_chnpos_model_t *m,unsigned char bmes,unsigned char pos,int insert) { wtk_heap_t *heap=m->state_map->heap; wtk_hash_node_t *node; wtk_chnpos_state_t state; wtk_chnpos_state_t *s; state.bmes=bmes; state.pos=pos; node=wtk_hash_find_node(m->state_map,&state,(wtk_hash_f)wtk_chnpos_state_hash,(wtk_cmp_f)wtk_chnpos_state_cmp); if(node) { s=node->v; goto end; } if(!insert) { s=NULL; goto end; } s=(wtk_chnpos_state_t*)wtk_heap_malloc(heap,sizeof(wtk_chnpos_state_t)); s->arcs=NULL; s->narc=0; s->emits=NULL; s->nemit=0; s->start=MIN_FLOAT; s->bmes=bmes; s->pos=pos; //wtk_queue_push(&(m->state_q),&(s->q_n)); wtk_hash_add(m->state_map,s,(wtk_hash_f)wtk_chnpos_state_hash); end: return s; } int wtk_chnpos_model_load_state(wtk_chnpos_model_t *m,wtk_source_t *src) { wtk_chnpos_wrd_t *wrd; wtk_strbuf_t *buf; int ret; int num,i,j,nx; unsigned char bmes; unsigned char pos; buf=wtk_strbuf_new(256,1); ret=wtk_source_read_string(src,buf); if(ret!=0){goto end;} if(!wtk_str_equal_s(buf->data,buf->pos,"<state>")) { wtk_debug("[%.*s] not supported\n",buf->pos,buf->data); ret=-1; goto end; } ret=wtk_source_read_int(src,&nx,1,0); if(ret!=0) { wtk_debug("read int failed.\n"); goto end; } m->wrd_map=wtk_str_hash_new(nx/2*2+1); m->state_map=wtk_hash_new(257); for(j=0;j<nx;++j) { ret=wtk_source_read_string(src,buf); if(ret!=0) { wtk_debug("read buf failed.\n"); goto end; } //wtk_debug("[%.*s]\n",buf->pos,buf->data); ret=wtk_source_read_int(src,&num,1,0); if(ret!=0) { wtk_debug("read buf failed.\n"); goto end; } //wtk_debug("num=%d\n",num); wrd=wtk_chnpos_model_new_wrd(m,buf->data,buf->pos,num); for(i=0;i<num;++i) { ret=wtk_source_read_string(src,buf); if(ret!=0) { wtk_debug("read buf failed.\n"); goto end; } //wtk_debug("[%.*s]\n",buf->pos,buf->data); bmes=wtk_chnpos_bmes_parse(buf->data,buf->pos); ret=wtk_source_read_string(src,buf); if(ret!=0) { wtk_debug("read buf failed.\n"); goto end; } pos=wtk_chnpos_model_pos_parse(m,buf->data,buf->pos,1); //wtk_debug("[%.*s]\n",buf->pos,buf->data); //wtk_chnpos_state_item_print(m,item); wrd->states[i]=wtk_chnpos_model_get_state(m,bmes,pos,1); } //wtk_chnpos_state_print(m,state); //exit(0); //wtk_chnpos_wrd_print(m,wrd); //exit(0); } ret=wtk_source_read_string(src,buf); if(ret!=0) { wtk_debug("read buf failed.\n"); goto end; } if(wtk_str_equal_s(buf->data,buf->pos,"</state>")) { ret=0; goto end; } ret=0; end: //wtk_debug("ret=%d\n",ret); //exit(0); wtk_strbuf_delete(buf); return ret; } int wtk_chnpos_model_load_start(wtk_chnpos_model_t *m,wtk_source_t *src) { wtk_strbuf_t *buf; int num,i; int ret; float f; unsigned char bmes; unsigned char pos; wtk_chnpos_state_t *state; buf=wtk_strbuf_new(256,1); ret=wtk_source_read_string(src,buf); if(ret!=0){goto end;} if(!wtk_str_equal_s(buf->data,buf->pos,"<start>")) { wtk_debug("[%.*s] not supported\n",buf->pos,buf->data); ret=-1; goto end; } ret=wtk_source_read_int(src,&num,1,0); if(ret!=0) { wtk_debug("read int failed.\n"); goto end; } for(i=0;i<num;++i) { ret=wtk_source_read_string(src,buf); if(ret!=0) { wtk_debug("read buf failed.\n"); goto end; } //wtk_debug("[%.*s]\n",buf->pos,buf->data); bmes=wtk_chnpos_bmes_parse(buf->data,buf->pos); ret=wtk_source_read_string(src,buf); if(ret!=0) { wtk_debug("read buf failed.\n"); goto end; } //wtk_debug("[%.*s]\n",buf->pos,buf->data); pos=wtk_chnpos_model_pos_parse(m,buf->data,buf->pos,0); ret=wtk_source_read_float(src,&f,1,0); if(ret!=0){goto end;} //wtk_debug("f=%f\n",f); state=wtk_chnpos_model_get_state(m,bmes,pos,1); if(!state) { //wtk_debug("%d pos=%.*s f=%f\n",bmes,buf->pos,buf->data,f); //continue; ret=-1; wtk_debug("bmes=%d pos=%.*s unspported\n",bmes,wtk_chnpos_model_get_pos(m,pos)->len,wtk_chnpos_model_get_pos(m,pos)->data); goto end; } state->start=f; } ret=wtk_source_read_string(src,buf); if(ret!=0) { wtk_debug("read buf failed.\n"); goto end; } if(wtk_str_equal_s(buf->data,buf->pos,"</start>")) { ret=0; goto end; } ret=0; end: //wtk_debug("ret=%d\n",ret); //exit(0); wtk_strbuf_delete(buf); return ret; } int wtk_chnpos_model_load_trans(wtk_chnpos_model_t *m,wtk_source_t *src) { wtk_heap_t *heap=m->state_map->heap; wtk_chnpos_arc_t *arc; wtk_chnpos_state_t *state; wtk_strbuf_t *buf; float f; int num,n; int i,j,ret; unsigned char bmes; unsigned char pos; buf=wtk_strbuf_new(256,1); ret=wtk_source_read_string(src,buf); if(ret!=0){goto end;} if(!wtk_str_equal_s(buf->data,buf->pos,"<trans>")) { wtk_debug("[%.*s] not supported\n",buf->pos,buf->data); ret=-1; goto end; } ret=wtk_source_read_int(src,&num,1,0); if(ret!=0) { wtk_debug("read int failed.\n"); goto end; } m->state_robin=wtk_robin_new(num); //wtk_debug("[%.*s]=%d\n",buf->pos,buf->data,num); for(i=0;i<num;++i) { //wtk_debug("i=%d/%d\n",i,num); ret=wtk_source_read_string(src,buf); if(ret!=0){goto end;} if(wtk_str_equal_s(buf->data,buf->pos,"</trans>")) { ret=0; goto end; } //wtk_debug("[%.*s]\n",buf->pos,buf->data); bmes=wtk_chnpos_bmes_parse(buf->data,buf->pos); ret=wtk_source_read_string(src,buf); if(ret!=0){goto end;} //wtk_debug("[%.*s]\n",buf->pos,buf->data); pos=wtk_chnpos_model_pos_parse(m,buf->data,buf->pos,0); ret=wtk_source_read_int(src,&n,1,0); if(ret!=0){goto end;} //wtk_debug("bmes=%d pos=%d n=%d\n",bmes,pos,n); state=wtk_chnpos_model_get_state(m,bmes,pos,0); if(!state) { wtk_debug("bmes=%d pos=[%.*s] not supported\n",bmes,buf->pos,buf->data); ret=-1; goto end; } state->narc=n; state->arcs=(wtk_chnpos_arc_t*)wtk_heap_malloc(heap,sizeof(wtk_chnpos_arc_t)*n); for(j=0;j<n;++j) { ret=wtk_source_read_string(src,buf); if(ret!=0){goto end;} //wtk_debug("[%.*s]\n",buf->pos,buf->data); bmes=wtk_chnpos_bmes_parse(buf->data,buf->pos); ret=wtk_source_read_string(src,buf); if(ret!=0){goto end;} //wtk_debug("[%.*s]\n",buf->pos,buf->data); pos=wtk_chnpos_model_pos_parse(m,buf->data,buf->pos,0); ret=wtk_source_read_float(src,&f,1,0); if(ret!=0){goto end;} //wtk_debug("bmes=%d pos=%d n=%f\n",bmes,pos,f); arc=state->arcs+j; arc->to=wtk_chnpos_model_get_state(m,bmes,pos,0); if(!state) { wtk_debug("bmes=%d pos=[%.*s] not supported\n",bmes,buf->pos,buf->data); ret=-1; goto end; } arc->prob=f; } wtk_robin_push(m->state_robin,state); //wtk_chnpos_state_print(m,state); //exit(0); } ret=wtk_source_read_string(src,buf); if(ret!=0) { wtk_debug("read buf failed.\n"); goto end; } if(wtk_str_equal_s(buf->data,buf->pos,"</trans>")) { ret=0; goto end; } ret=0; end: //wtk_debug("ret=%d\n",ret); //exit(0); wtk_strbuf_delete(buf); return ret; } int wtk_chnpos_model_load_emit(wtk_chnpos_model_t *m,wtk_source_t *src) { wtk_heap_t *heap=m->state_map->heap; wtk_chnpos_emit_t *emit; wtk_chnpos_state_t *state; wtk_strbuf_t *buf; float f; int num,n; int i,j,ret; unsigned char bmes; unsigned char pos; buf=wtk_strbuf_new(256,1); ret=wtk_source_read_string(src,buf); if(ret!=0){goto end;} if(!wtk_str_equal_s(buf->data,buf->pos,"<emit>")) { wtk_debug("[%.*s] not supported\n",buf->pos,buf->data); ret=-1; goto end; } ret=wtk_source_read_int(src,&num,1,0); if(ret!=0) { wtk_debug("read int failed.\n"); goto end; } //wtk_debug("[%.*s]=%d\n",buf->pos,buf->data,num); for(i=0;i<num;++i) { //wtk_debug("i=%d/%d\n",i,num); ret=wtk_source_read_string(src,buf); if(ret!=0){goto end;} if(wtk_str_equal_s(buf->data,buf->pos,"</emit>")) { ret=0; goto end; } //wtk_debug("[%.*s]\n",buf->pos,buf->data); bmes=wtk_chnpos_bmes_parse(buf->data,buf->pos); ret=wtk_source_read_string(src,buf); if(ret!=0){goto end;} //wtk_debug("[%.*s]\n",buf->pos,buf->data); pos=wtk_chnpos_model_pos_parse(m,buf->data,buf->pos,0); ret=wtk_source_read_int(src,&n,1,0); if(ret!=0){goto end;} //wtk_debug("bmes=%d pos=%d n=%d\n",bmes,pos,n); state=wtk_chnpos_model_get_state(m,bmes,pos,0); if(!state) { wtk_debug("bmes=%d pos=[%.*s] not supported\n",bmes,buf->pos,buf->data); ret=-1; goto end; } state->nemit=n; state->emits=(wtk_chnpos_emit_t*)wtk_heap_malloc(heap,sizeof(wtk_chnpos_emit_t)*n); for(j=0;j<n;++j) { ret=wtk_source_read_string(src,buf); if(ret!=0){goto end;} ret=wtk_source_read_float(src,&f,1,0); if(ret!=0){goto end;} //wtk_debug("bmes=%d pos=%d n=%f\n",bmes,pos,f); emit=state->emits+j; //emit->wrd=wtk_chnpos_model_get_wrd(m,buf->data,buf->pos); emit->wrd=wtk_heap_dup_string(heap,buf->data,buf->pos); if(!emit->wrd) { wtk_debug("%.*s %f not supported\n",buf->pos,buf->data,f); ret=-1; goto end; //continue; } emit->prob=f; } //wtk_chnpos_state_print(m,state); //exit(0); } ret=wtk_source_read_string(src,buf); if(ret!=0) { wtk_debug("read buf failed.\n"); goto end; } if(wtk_str_equal_s(buf->data,buf->pos,"</emit>")) { ret=0; goto end; } ret=0; end: //wtk_debug("ret=%d\n",ret); //exit(0); wtk_strbuf_delete(buf); return ret; } int wtk_chnpos_model_load(wtk_chnpos_model_t *m,wtk_source_t *src) { int ret; ret=wtk_chnpos_model_load_state(m,src); if(ret!=0){goto end;} ret=wtk_chnpos_model_load_start(m,src); if(ret!=0){goto end;} ret=wtk_chnpos_model_load_trans(m,src); if(ret!=0){goto end;} ret=wtk_chnpos_model_load_emit(m,src); if(ret!=0){goto end;} ret=0; end: //wtk_debug("ret=%d\n",ret); return ret; } int wtk_chnpos_wrd_has_state(wtk_chnpos_wrd_t *wrd,wtk_chnpos_state_t *state) { int i; for(i=0;i<wrd->nstate;++i) { if(wrd->states[i]==state) { return 1; } } return 0; } float wtk_chnpos_state_get_emit_prob(wtk_chnpos_state_t *state,wtk_string_t *wrd) { int i; for(i=0;i<state->nemit;++i) { if(wtk_string_cmp(state->emits[i].wrd,wrd->data,wrd->len)==0) { return state->emits[i].prob; } } return MIN_FLOAT; } float wtk_chnpos_state_get_trans_prob(wtk_chnpos_state_t *state,wtk_chnpos_state_t *nxt) { int i; for(i=0;i<state->narc;++i) { if(state->arcs[i].to==nxt) { return state->arcs[i].prob; } } return MIN_FLOAT; } <file_sep>/core/wtk_stack.c #include "wtk_stack.h" #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include "wtk/os/wtk_fd.h" stack_block_t* wtk_stack_new_block(wtk_stack_t *stack,int want_size) { stack_block_t *b; int size; int v; int want; want=want_size+sizeof(stack_block_t); v=(int)(stack->last_alloc_size*(stack->growf+1)); size=max(v,want); size=wtk_round(size,8); stack->last_alloc_size=size; b=(stack_block_t*)wtk_malloc(size); b->next=0; b->pop=b->push=(char*)b + sizeof(stack_block_t); b->end=(char*)b+size; return b; } wtk_stack_t* wtk_stack_new(int init_size,int max_size,float growf) { wtk_stack_t* s; s=(wtk_stack_t*)wtk_malloc(sizeof(wtk_stack_t)); wtk_stack_init(s,init_size,max_size,growf); return s; } int wtk_stack_bytes(wtk_stack_t *s) { int b; stack_block_t* bl; b=sizeof(*s); for(bl=s->pop;bl;bl=bl->next) { b+=sizeof(stack_block_t)+bl->end-bl->pop; } return b; } int wtk_stack_init(wtk_stack_t *s,int init_size,int max_size,float growf) { stack_block_t *b; s->last_alloc_size=0; s->max_size=max_size; s->len=0; s->growf=growf; b=wtk_stack_new_block(s,init_size); s->pop=s->push=s->end=b; return 0; } int wtk_stack_delete(wtk_stack_t* stack) { wtk_stack_clean(stack); wtk_free(stack); return 0; } int wtk_stack_clean(wtk_stack_t *s) { stack_block_t *b,*p; for(b=s->pop;b;b=p) { p=b->next; wtk_free(b); } return 0; } int wtk_stack_reset(wtk_stack_t *s) { stack_block_t *b; s->push=s->pop; for(b=s->pop;b;b=b->next) { b->pop=b->push=(char*)b+sizeof(stack_block_t); } s->len=0; return 0; } int wtk_stack_push(wtk_stack_t* s,const char* data,int len) { stack_block_t *b; int cpy,left,size; left=len; for(b=s->push;b;b=b->next,s->push=b) { size=b->end - b->push; if(size>0) { cpy=min(size,left); memcpy(b->push,data,cpy); b->push+=cpy; left-=cpy; if(left==0){break;} data+=cpy; } if(!b->next) { s->end=b->next=wtk_stack_new_block(s,left); } } s->len += len-left; return 0; } void wtk_stack_push_f(wtk_stack_t *s,const char *fmt,...) { char buf[4096]; va_list ap; int n; va_start(ap,fmt); n=vsprintf(buf,fmt,ap); wtk_stack_push(s,buf,n); va_end(ap); } int wtk_stack_pop2(wtk_stack_t* s,char* data,int len) { stack_block_t *b; int left,size,cpy; int cpyed; left=min(len,s->len); cpyed=0; for(b=s->pop;b && left>0;s->pop=b->next,b->next=0,b=s->pop) { size=b->push-b->pop; if(size > 0) { cpy=min(size,left); if(data) { memcpy(data,b->pop,cpy); data += cpy; } b->pop += cpy; left -= cpy; cpyed+=cpy; if(left==0){break;} } b->push=b->pop=(char*)b+sizeof(*b); if(s->push==b) { break; }else { s->end->next=b; s->end=b; } } s->len -=cpyed; return cpyed; } int wtk_stack_pop3(wtk_stack_t* s,char* data,int len) { stack_block_t *b; int left,size,cpy; left=len; for(b=s->pop;b && left>0;s->pop=b->next,b->next=0,b=s->pop) { size=b->push-b->pop; if(size > 0) { cpy=min(size,left); if(data) { memcpy(data,b->pop,cpy); data += cpy; } b->pop += cpy; left -= cpy; if(left==0){break;} } b->push=b->pop=(char*)b+sizeof(*b); s->end->next=b; s->end=b; } s->len -=len-left; return 0; } int wtk_stack_pop(wtk_stack_t* s,char* data,int len) { int cpyed; int ret; cpyed=wtk_stack_pop2(s,data,len); ret=cpyed==len?0:-1; return ret; } int wtk_stack_push_string(wtk_stack_t* s,const char* str) { return wtk_stack_push(s,str,strlen(str)); } void wtk_stack_merge(wtk_stack_t *s,char* p) { stack_block_t *b; int len; for(b=s->pop;b;b=b->next) { len=b->push-b->pop; memcpy(p,b->pop,len); p+=len; if(b==s->push){return;} } } void wtk_stack_add(wtk_stack_t *dst,wtk_stack_t *src) { stack_block_t *b; int len; for(b=src->pop;b;b=b->next) { len=b->push-b->pop; wtk_stack_push(dst,b->pop,len); if(b==src->push){return;} } } void wtk_stack_copy(wtk_stack_t *s,wtk_strbuf_t *to) { stack_block_t *b; int len; for(b=s->pop;b;b=b->next) { len=b->push-b->pop; wtk_strbuf_push(to,b->pop,len); if(b==s->push){return;} } } int wtk_stack_is_valid(wtk_stack_t * s) { stack_block_t* b; int count,ret; count=0; for(b=s->pop;b;b=b->next) { ret=b->push - b->pop; //wtk_debug("stack check: push=%p,pop=%p\n",b->push,b->pop); if(ret<0) { wtk_debug("stack push is low than pop: push=%p,pop=%p\n",b->push,b->pop); goto end; } count += ret; } ret= count == s->len ? 1 : 0; end: return ret; } int wtk_stack_print(wtk_stack_t* s) { stack_block_t* b; int i; for(b=s->pop,i=0;b;b=b->next,++i) { print_data((char*)b->pop,b->push-b->pop); } return 0; printf("################ stack (%p) #############\n",s); if(s) { for(b=s->pop,i=0;b;b=b->next,++i) { printf("stack(%d,%p -> %p):\t(valid=%d,len=%d)\n",i,b,b->next,(int)(b->pop - b->push), (int)(b->end - (char*)b-sizeof(*b))); print_data((char*)b->pop,b->push-b->pop); } printf("pop:%p,push:%p\n",s->pop,s->push); printf("len: %d\n",s->len); }else { printf("nil.\n"); } printf("####################################\n"); return 0; } int wtk_stack_write(wtk_stack_t *s,FILE *f) { stack_block_t* b; int i,n; int ret; for(b=s->pop,i=0;b;b=b->next,++i) { n=b->push-b->pop; if(n<=0){continue;} ret=fwrite((char*)b->pop,1,n,f); if(ret!=n){ret=-1;goto end;} } ret=0; end: return ret; } int wtk_stack_write2(wtk_stack_t *s,char *fn) { FILE *f; int ret; f=fopen(fn,"wb"); if(f) { ret=wtk_stack_write(s,f); fclose(f); }else { ret=-1; } return ret; } int wtk_stack_read(wtk_stack_t *s,char *fn) { char buf[4096]; int ret=-1; FILE *f=0; f=fopen(fn,"rb"); if(!f){goto end;} while(1) { ret=fread(buf,1,sizeof(buf),f); if(ret>0) { wtk_stack_push(s,buf,ret); } if(ret<sizeof(buf)) { break; } } end: if(f) { fclose(f); } return ret; } int wtk_stack_write_nbfd(wtk_stack_t *s, int fd) { stack_block_t *b; int n, writed; int ret; for(b = s->pop; b ; s->pop = b->next, b->next = 0, b = s->pop) { n = b->push - b->pop; if (n > 0) { ret = wtk_fd_write_nonblock(fd, (char*)b->pop, n, &writed); b->pop += writed; s->len -= writed; if (WTK_EOF == ret || WTK_ERR == ret) { ret = -1; goto end; } if (writed != n) { break; } } b->push = b->pop = (char*)b + sizeof(*b); if (s->push == b){ break; } else { s->end->next = b; s->end = b; } } ret = 0; end: return ret; } <file_sep>/core/segmenter/wtk_prune_cfg.c #include "wtk_prune_cfg.h" int wtk_prune_cfg_init(wtk_prune_cfg_t *cfg) { cfg->min_score=0; cfg->max_score=0; cfg->bin_width=1.0; cfg->count=0; cfg->beam=0; return 0; } int wtk_prune_cfg_clean(wtk_prune_cfg_t *cfg) { return 0; } int wtk_prune_cfg_update_local(wtk_prune_cfg_t *cfg,wtk_local_cfg_t *lc) { wtk_string_t *v; wtk_local_cfg_update_cfg_f(lc,cfg,min_score,v); wtk_local_cfg_update_cfg_f(lc,cfg,max_score,v); wtk_local_cfg_update_cfg_f(lc,cfg,bin_width,v); wtk_local_cfg_update_cfg_f(lc,cfg,beam,v); wtk_local_cfg_update_cfg_i(lc,cfg,count,v); return 0; } int wtk_prune_cfg_update(wtk_prune_cfg_t *cfg) { return 0; } <file_sep>/study_wwk/test.c #include "core/wwk_type.h" int main() { wwk_debug("use myself data\n"); wwk_debug("hello world\n"); return 0; } <file_sep>/os/.svn/pristine/ac/ace83f007148507d9f49f3ccb91c4b48db45d89a.svn-base #ifndef WTK_CORE_WTK_LOCKQUEUE_H_ #define WTK_CORE_WTK_LOCKQUEUE_H_ #include "wtk/core/wtk_queue.h" #include "wtk/os/wtk_lock.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_lockqueue wtk_lockqueue_t; #define WTK_LOCK_QUEUE \ WTK_QUEUE \ wtk_lock_t l; struct wtk_lockqueue { WTK_LOCK_QUEUE }; int wtk_lockqueue_init(wtk_lockqueue_t *q); int wtk_lockqueue_clean(wtk_lockqueue_t *q); int wtk_lockqueue_push(wtk_lockqueue_t *q,wtk_queue_node_t *n); int wtk_lockqueue_push_front(wtk_lockqueue_t *q,wtk_queue_node_t *n); wtk_queue_node_t* wtk_lockqueue_pop(wtk_lockqueue_t *q); #ifdef __cplusplus }; #endif #endif <file_sep>/core/strlike/wtk_chnlike_cfg.h #ifndef WTK_FST_STRLIKE_WTK_CHNLIKE_CFG #define WTK_FST_STRLIKE_WTK_CHNLIKE_CFG #include "wtk/core/cfg/wtk_local_cfg.h" #include "wtk/core/text/wtk_txtpeek_cfg.h" #include "wtk/core/wtk_strdict.h" #include "wtk_strlike_cfg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_chnlike_cfg wtk_chnlike_cfg_t; struct wtk_chnlike_cfg { wtk_txtpeek_cfg_t txtpeek; wtk_strlike_cfg_t strlike; wtk_strdict_t *dict; int hash_hint; char *dict_fn; unsigned use_bin:1; }; int wtk_chnlike_cfg_init(wtk_chnlike_cfg_t *cfg); int wtk_chnlike_cfg_clean(wtk_chnlike_cfg_t *cfg); int wtk_chnlike_cfg_update_local(wtk_chnlike_cfg_t *cfg,wtk_local_cfg_t *lc); int wtk_chnlike_cfg_update(wtk_chnlike_cfg_t *cfg); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_bit_heap.h #ifndef WLIB_CORE_WTK_BIT_HEAP_H_ #define WLIB_CORE_WTK_BIT_HEAP_H_ #include "wtk/core/wtk_type.h" #include "wtk_alloc.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_bit_heap wtk_bit_heap_t; //typedef int (*heap_clean_handler)(void* data); typedef struct _HeapBlock { size_t elem_num; size_t elem_free; size_t first_free; uint8_t *bitmap; uint8_t *data; struct _HeapBlock* next; }HeapBlock; struct wtk_bit_heap { HeapBlock* block_list; //heap_clean_handler cleaner; size_t elem_size; size_t elem_cur; size_t elem_min; size_t elem_max; size_t tot_alloc; size_t tot_used; float growf; }; /** * @brief allocate bitmap heap. */ wtk_bit_heap_t* wtk_bit_heap_new(size_t elem_size,size_t elem_min,size_t elem_max,float growf); /** * @brief allocate bitmap heap with elem_size. */ wtk_bit_heap_t* wtk_bit_heap_new2(size_t elem_size); /** * @brief release all memory. */ int wtk_bit_heap_delete(wtk_bit_heap_t* heap); int wtk_bit_heap_bytes(wtk_bit_heap_t *heap); /** * @brief reset heap. */ int wtk_bit_heap_reset(wtk_bit_heap_t* heap); /** * @brief allocate memory from heap. */ void* wtk_bit_heap_malloc(wtk_bit_heap_t* heap); /** * @brief allocate with zero. */ void* wtk_bit_heap_zmalloc(wtk_bit_heap_t *heap); /** * @brief delete bitmap memory. */ int wtk_bit_heap_free(wtk_bit_heap_t* heap,void* p); /** * @brief check heap is valid or not. */ int wtk_bit_heap_is_valid(wtk_bit_heap_t *heap); /** * @brief print bit heap; */ void wtk_bit_heap_print(wtk_bit_heap_t *heap); //================ test section =============== void wtk_bit_heap_test_g(); #ifdef __cplusplus }; #endif #endif <file_sep>/os/wtk_socket.h #ifndef WTK_OS_WTK_SOCKET_H_ #define WTK_OS_WTK_SOCKET_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_strbuf.h" #ifdef WIN32 #include <winsock2.h> #include <io.h> #include <ws2tcpip.h> #include <windows.h> #else #include <netdb.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <net/if.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/ioctl.h> #include <arpa/inet.h> #include <sys/types.h> #include <netinet/in.h> #include <netinet/tcp.h> #include "wtk_sem.h" #endif #ifdef __cplusplus extern "C" { #endif #ifdef WIN32 int wtk_socketpair(int socks[2], int make_overlapped); #endif typedef struct { int addrlen; struct sockaddr * addr; }wtk_addrinfo_t; wtk_addrinfo_t* wtk_addrinfo_get(char* server,char *port); int wtk_addrinfo_delete(wtk_addrinfo_t *i); struct addrinfo* wtk_socket_get_addrinfo(char* server,char* port); int wtk_socket_free_addr(struct addrinfo* info); /* * @brief returned string must be freed when unused. */ char* wtk_get_host_ip(char *iface); int wtk_get_host_addr(char *iface,struct in_addr *addr); int wtk_socket_get_addr(char *ip,int port,struct sockaddr_in *addr); int wtk_socket_connect(struct sockaddr *ai_addr,socklen_t ai_addrlen,int *pfd); int wtk_socket_connect2(char *ip,int port,int *pfd); int wtk_socket_connect4(char *ip,char* port,int *pfd); /** * @timeout: ms; */ void wtk_socket_set_timeout(int fd,int timeout); /** * @timeout: ms; */ int wtk_socket_connect3(struct sockaddr *ai_addr,socklen_t ai_addrlen,int *pfd,int timeout); int wtk_socket_close_fd(int fd); int wtk_socket_get_port(int fd,int *port); void wtk_socket_print(int fd); int wtk_socket_set_reuse(int fd); /** * @brief crate udp socket and bind, used for send and recv msg; */ int wtk_socket_create_udp_fd(int port); int wtk_socket_create_tcp_listen_fd(int port); int wtk_socket_readable(int fd); #ifdef WIN32 #else int wtk_socket_sendto(int fd,const char *data,int bytes,const struct sockaddr* addr,socklen_t len); int wtk_socket_sendto_host(int fd,const char *data,int bytes,char *host,int port); int wtk_socket_recvfrom(int fd,char *buf,int len,struct sockaddr *addr,socklen_t *addrlen); wtk_addrinfo_t* wtk_addrinfo_get2(char *server,char *port); wtk_addrinfo_t* wtk_addrinfo_get3(char *server,char *port,int timeout); int wtk_socket_send_strmsg(int fd,char *data,int bytes); int wtk_socket_read_strmsg(int fd,wtk_strbuf_t *buf); #endif #ifdef __cplusplus }; #endif #endif <file_sep>/os/.svn/pristine/4f/4fdbcbdae2cf8397ecde4b830157985c6b7b31a9.svn-base #include <malloc.h> #include "wtk_malloc.h" #include "wtk/os/wtk_lock.h" #ifdef USE_MALLOC_HOOK typedef void*(*wtk_malloc_hook_f)(size_t size,const void *caller); typedef void (*wtk_free_hook_f)(void *ptr,const void *caller); wtk_lock_t lock; pid_t pid; wtk_malloc_hook_f old_malloc_hook; wtk_free_hook_f free_malloc_hook; void* wtk_malloc_hook(size_t size,const void *caller); void wtk_free_hook(void *p,const void *caller); void* wtk_malloc_hook(size_t size,const void *caller) { void *p; wtk_lock_lock(&(lock)); __malloc_hook=old_malloc_hook; __free_hook=free_malloc_hook; p=malloc(size); if(pid==getpid()) { wtk_proc_dump_stack2(); printf("DM malloc %s:%d %p %d\n",__FUNCTION__,getpid(),p,(int)size); fflush(stdout); } __malloc_hook=wtk_malloc_hook; __free_hook=wtk_free_hook; wtk_lock_unlock(&(lock)); return p; } void wtk_free_hook(void *p,const void *caller) { if(!p) { //wtk_debug("found nil...\n"); //exit(0); return; } wtk_lock_lock(&(lock)); __malloc_hook=old_malloc_hook; __free_hook=free_malloc_hook; free(p); if(pid==getpid()) { printf("DM free %s:%d %p\n",__FUNCTION__,getpid(),p); fflush(stdout); } //wtk_debug("free (%u) returns %p\n", (unsigned int) size, p); __malloc_hook=wtk_malloc_hook; __free_hook=wtk_free_hook; wtk_lock_unlock(&(lock)); } void wtk_malloc_init() { pid=getpid(); wtk_lock_init(&lock); old_malloc_hook=__malloc_hook; free_malloc_hook=__free_hook; __malloc_hook=wtk_malloc_hook; __free_hook=wtk_free_hook; } #endif <file_sep>/core/wtk_base64.c #include "wtk_base64.h" const char* base64char="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; char* wtk_base64_encode(char* data,int len) { int i, j; unsigned char current; char *base64; base64=(char*)wtk_malloc(len*2); memset(base64,0,len*2); for ( i = 0, j = 0 ; i < len ; i += 3 ) { current = (data[i] >> 2) ; current &= (unsigned char)0x3F; base64[j++] = base64char[(int)current]; current = ( (unsigned char)(data[i] << 4 ) ) & ( (unsigned char)0x30 ) ; if ( i + 1 >= len ) { base64[j++] = '='; base64[j++] = '='; break; } current |= ( (unsigned char)(data[i+1] >> 4) ) & ( (unsigned char) 0x0F ); base64[j++] = base64char[(int)current]; current = ( (unsigned char)(data[i+1] << 2) ) & ( (unsigned char)0x3C ) ; if ( i + 2 >= len ) { base64[j++] = base64char[(int)current]; base64[j++] = '='; break; } current |= ( (unsigned char)(data[i+2] >> 6) ) & ( (unsigned char) 0x03 ); base64[j++] = base64char[(int)current]; current = ( (unsigned char)data[i+2] ) & ( (unsigned char)0x3F ) ; base64[j++] = base64char[(int)current]; } wtk_debug("%d\n",j); base64[j] = '\0'; return base64; } #define CONVERT_PLUS(base, idx, c) \ if (c == '+') { \ base[idx++] = '%'; \ base[idx++] = '2'; \ base[idx++] = 'b'; \ } else { \ base[idx++] = c; \ } char* wtk_base64_encode_url(char* data,int len) { int i, j; unsigned char current; char *base64; base64=(char*)wtk_malloc(len*2); memset(base64,0,len*2); for ( i = 0, j = 0 ; i < len ; i += 3 ) { current = (data[i] >> 2) ; current &= (unsigned char)0x3F; CONVERT_PLUS(base64, j, base64char[(int)current]); current = ( (unsigned char)(data[i] << 4 ) ) & ( (unsigned char)0x30 ) ; if ( i + 1 >= len ) { base64[j++] = '='; base64[j++] = '='; break; } current |= ( (unsigned char)(data[i+1] >> 4) ) & ( (unsigned char) 0x0F ); CONVERT_PLUS(base64, j, base64char[(int)current]); current = ( (unsigned char)(data[i+1] << 2) ) & ( (unsigned char)0x3C ) ; if ( i + 2 >= len ) { base64[j++] = base64char[(int)current]; base64[j++] = '='; break; } current |= ( (unsigned char)(data[i+2] >> 6) ) & ( (unsigned char) 0x03 ); CONVERT_PLUS(base64, j, base64char[(int)current]); current = ( (unsigned char)data[i+2] ) & ( (unsigned char)0x3F ) ; CONVERT_PLUS(base64, j, base64char[(int)current]); } base64[j] = '\0'; return base64; } char* wtk_base64_decode(const char* base64,int len) { int i, j; unsigned char k; unsigned char temp[4]; char *data; data=(char*)wtk_malloc(len); for ( i = 0, j = 0; base64[i] != '\0' ; i += 4 ) { memset( temp, 0xFF, sizeof(temp) ); for ( k = 0 ; k < 64 ; k ++ ) { if ( base64char[k] == base64[i] ) temp[0]= k; } for ( k = 0 ; k < 64 ; k ++ ) { if ( base64char[k] == base64[i+1] ) temp[1]= k; } for ( k = 0 ; k < 64 ; k ++ ) { if ( base64char[k] == base64[i+2] ) temp[2]= k; } for ( k = 0 ; k < 64 ; k ++ ) { if ( base64char[k] == base64[i+3] ) temp[3]= k; } data[j++] = ((unsigned char)(((unsigned char)(temp[0] << 2))&0xFC)) | ((unsigned char)((unsigned char)(temp[1]>>4)&0x03)); if ( base64[i+2] == '=' ) break; data[j++] = ((unsigned char)(((unsigned char)(temp[1] << 4))&0xF0)) | ((unsigned char)((unsigned char)(temp[2]>>2)&0x0F)); if ( base64[i+3] == '=' ) break; data[j++] = ((unsigned char)(((unsigned char)(temp[2] << 6))&0xF0)) | ((unsigned char)(temp[3]&0x3F)); } data[j] = 0; return data; } <file_sep>/os/wtk_lock.h #ifndef WTK_OS_WTK_LOCK_H_ #define WTK_OS_WTK_LOCK_H_ #include "wtk/core/wtk_type.h" #ifdef __cplusplus extern "C" { #endif #ifndef WIN32 typedef pthread_mutex_t wtk_lock_t; #define wtk_lock_init(l) pthread_mutex_init(l,0) #define wtk_lock_clean(l) pthread_mutex_destroy(l) #define wtk_lock_lock(l) pthread_mutex_lock(l) #define wtk_lock_unlock(l) pthread_mutex_unlock(l) #define wtk_lock_trylock(l) pthread_mutex_trylock(l) //int wtk_lock_init2(wtk_lock_t *lock); #else #include <winsock2.h> #include <windows.h> typedef CRITICAL_SECTION wtk_lock_t; /* #define wtk_lock_init(l) (InitializeCriticalSection(l),0) #define wtk_lock_clean(l) DeleteCriticalSection(l),0 #define wtk_lock_lock(l) EnterCriticalSection(l),0 #define wtk_lock_unlock(l) LeaveCriticalSection(l),0 #define wtk_lock_trylock(l) TryEnterCriticalSection(l) */ int wtk_lock_init(wtk_lock_t *l); int wtk_lock_clean(wtk_lock_t *l); int wtk_lock_lock(wtk_lock_t *l); int wtk_lock_unlock(wtk_lock_t *l); int wtk_lock_trylock(wtk_lock_t *l); #endif #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_str_hash.h #ifndef WTK_CORE_WTK_STR_HASH_H_ #define WTK_CORE_WTK_STR_HASH_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_str.h" #include "wtk_queue.h" #include "wtk_heap.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_str_hash wtk_str_hash_t; #define wtk_str_hash_find_s(h,key) wtk_str_hash_find(h,key,sizeof(key)-1) #define wtk_str_hash_remove_s(h,key) wtk_str_hash_remove(h,key,sizeof(key)-1) #define wtk_str_hash_index(h,k,kb) (hash_string_value_len(k,kb,(h)->nslot)) #define wtk_str_hash_add_s(h,k,v) wtk_str_hash_add(h,k,sizeof(k)-1,v) #define wtk_str_hash_find_queue_s(h,k) wtk_str_hash_find_queue(h,k,sizeof(k)-1) #define wtk_str_hash_find_node3_s(h,k,insert) wtk_str_hash_find_node3(h,k,sizeof(k)-1,insert) typedef struct hash_str_node { wtk_queue_node_t n; wtk_string_t key; void* value; }hash_str_node_t; typedef struct { wtk_queue_node_t n; wtk_string_t key; union { int i; unsigned int u; float f; void *value; }v; }wtk_hash_str_node_t; struct wtk_str_hash { wtk_heap_t *heap; wtk_queue_t **slot; int nslot; unsigned use_ref_heap:1; }; /** * @brief create string hash; */ wtk_str_hash_t* wtk_str_hash_new(int nslot); wtk_str_hash_t* wtk_str_hash_new2(int nslot,wtk_heap_t *heap); /** * @brief memory occupied by hash; */ int wtk_str_hash_bytes(wtk_str_hash_t *h); /** * @brief delete string hash; */ int wtk_str_hash_delete(wtk_str_hash_t *h); /** * @brief reset string hash; */ int wtk_str_hash_reset(wtk_str_hash_t *h); /** * @brief add k,v,str hash will not deep copy key, just point to memory of key; */ int wtk_str_hash_add(wtk_str_hash_t *h,char* key,int key_bytes,void *value); /** * @brief add k,v,str hash will copy key */ int wtk_str_hash_add2(wtk_str_hash_t *h,char* key,int key_bytes,void *value); /** * @brief add k,v and the node of hash use the provided node n; */ int wtk_str_hash_add_node(wtk_str_hash_t *h,char* key,int key_bytes,void *value,hash_str_node_t* n); /** * @brief find hash node bye key,and rv is the index of hash slot; */ hash_str_node_t* wtk_str_hash_find_node(wtk_str_hash_t *h, char* key,int key_bytes,uint32_t *rv); hash_str_node_t* wtk_str_hash_find_node2(wtk_str_hash_t *h, char* key,int key_bytes,uint32_t index); /** * find node if not exist create new; */ hash_str_node_t* wtk_str_hash_find_node3(wtk_str_hash_t *h,char *k,int k_bytes,int insert); /** * @brief find node which key start with key */ hash_str_node_t* wtk_str_hash_find_node_pre_key(wtk_str_hash_t *h, char* key,int key_bytes); /** * @brief find v by k; */ void* wtk_str_hash_find(wtk_str_hash_t *h, char* key,int key_bytes); /** * @brief remove hash node by key; */ hash_str_node_t* wtk_str_hash_remove(wtk_str_hash_t *h,char *key,int key_bytes); /** * @brief malloc some memory from heap of hash; */ void* wtk_str_hash_malloc(wtk_str_hash_t *h,int bytes); /** * @brief elem of hash table; */ int wtk_str_hash_elems(wtk_str_hash_t *h); /*-------------------------------------------------------------------------*/ /** * in handler(void* user_data,void* data),data is an pointer to hash_str_node_t. */ /*--------------------------------------------------------------------------*/ int wtk_str_hash_walk(wtk_str_hash_t* h,wtk_walk_handler_t handler,void* user_data); /** * cmp handler(void* user_data, void *v) */ int wtk_str_hash_findc(wtk_str_hash_t*h,char* k,int kb,wtk_cmp_handler_t cmp,void *user_data,void** v); /** * @brief find same have val by key; */ wtk_queue_t* wtk_str_hash_find_queue(wtk_str_hash_t *h,char *k,int k_bytes); //------------------------ iterator section ----------------------- typedef struct { wtk_str_hash_t *hash; wtk_queue_node_t *cur_n; int next_index; }wtk_str_hash_it_t; wtk_str_hash_it_t wtk_str_hash_iterator(wtk_str_hash_t *hash); hash_str_node_t* wtk_str_hash_it_next(wtk_str_hash_it_t *it); //----------------------- new file ------------------------ wtk_str_hash_t* wtk_str_hash_new_file(char *fn); //-------------------------- test/example section ------------------ void wtk_str_hash_test_g(); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_os.h #ifndef WLIB_CORE_WTK_INIT_H_ #define WLIB_CORE_WTK_INIT_H_ #include <stdio.h> #include "wtk_type.h" #include "wtk_str.h" #include "wtk_strbuf.h" #ifdef __cplusplus extern "C" { #endif #ifdef WIN32 #include <stdlib.h> #ifdef WINCE #include <ceconfig.h> #else #include <direct.h> #include <io.h> #endif #define F_OK 0 #define R_OK 4 #define W_OK 2 #define wtk_file_access(fn,m) _access(fn,m) #define wtk_file_exist(fn) wtk_file_access(fn,F_OK) #define wtk_file_readable(fn) wtk_file_access(fn,R_OK) #define wtk_file_writeable(fn) wtk_file_access(fn,W_OK) typedef int (*wtk_dir_walk_handler_t)(void* ,char *fn); //void dir_monitor(const char* path, dir_monitor_handler cb,void* user_data,HANDLE* handle); int wtk_dir_walk(const char* path,wtk_dir_walk_handler_t cb,void* user_data); int wtk_is_dir(char *dn); #else /** * @brief return 0 on success. */ #define wtk_file_access(fn,m) access(fn,m) #define wtk_file_exist(fn) wtk_file_access(fn,F_OK) #define wtk_file_readable(fn) wtk_file_access(fn,R_OK) #define wtk_file_writeable(fn) wtk_file_access(fn,W_OK) #define wtk_file_exeable(fn) wtk_file_access(fn,X_OK) int wtk_is_dir(char *dn); #endif #ifdef WIN32 #define DIR_SEP '\\' #define DIR_SEP1 '/' #else #define DIR_SEP '/' #endif typedef int(*wtk_dir_walk_f)(void *ths,wtk_string_t *fn); #if defined __IPHONE_OS__ #else int wtk_dir_walk(char *dir,void *ths,wtk_dir_walk_f walk); typedef int(*wtk_dir_walk2_f)(void *ths,char *fn); int wtk_dir_walk2(char *dir,void *ths,wtk_dir_walk2_f walk); #endif //------------------------ directory and file section --------------------------- /** * @brief create directory; */ int wtk_mkdir(char* dn); /** * @brief create directory and parent directory if not created; */ int wtk_mkdir_p(char* fn,char sep,int create_last_entry); /** * @brief remove . and .. from fn, and save the result into buf; * @param fn like /home/lz123/wtk/wvite/httpa/8.9/src/../ext/../html to remove .. * @param fn_bytes bytes of fn; * @param buf to save the result; * @param sep use to separate directory: '/','\'; */ void wtk_real_fn(char *fn,int fn_bytes,wtk_strbuf_t *buf,char sep); #define wtk_real_fn_s(fn,buf,sep) wtk_real_fn(fn,sizeof(fn)-1,buf,sep) /** * @directory name for fn; */ wtk_string_t* wtk_dir_name(char *fn,char sep); wtk_string_t wtk_dir_name2(char *data,int len,char sep); /** * @brief realpath of fn; * @return char* must be freed; */ char* wtk_realpath(char *fn,char *buf); wtk_string_t* wtk_dirname(char *fn,char sep); wtk_string_t* wtk_str_left(char *fn,int len,char sep); wtk_string_t* wtk_basename(char* fn,char sep); wtk_string_t* wtk_str_right(char* fn,int len,char sep); wtk_string_t* wtk_real_dirname(char *fn); FILE* wtk_file_open(char* fn,char * mode); //------------------------ file section ---------------------------------------- uint64_t file_length(FILE *f); uint64_t wtk_file_size(char *fn); char* file_read_buf(char* fn, int *n); char* file_read_buf2(char* fn, int fn_len,int *n); int file_write_buf(char* fn, const char* data, size_t len); //------------------------ time section ---------------------------------------- double time_get_ms(); double time_get_cpu(); void wtk_msleep(int ms); //----------------------- compile section -------------------------------------- int wtk_gcc_month(); int wtk_gcc_day(); int wtk_gcc_year(); int wtk_get_build_timestamp(char *buf); int wtk_os_timestamp(char *buf); int wtk_os_timestamp2(wtk_strbuf_t *buf); //------------------------- -------------------------------------------------- char* wtk_search_file(char *fn,wtk_string_t **path,int n,wtk_strbuf_t *buf); unsigned long long wtk_file_lines(char *fn); int wtk_file_read_line(FILE *f,wtk_strbuf_t *buf,unsigned long long index,char *tmp,int tmp_size); int wtk_file_read_line2(FILE *f,wtk_strbuf_t *buf,unsigned long long index); int wtk_file_copy(char *src,char *dst,char sep); int wtk_file_copy2(FILE *fin,char *dst,char sep,int want_len); //[left,right]; int wtk_random(int left,int right); typedef void(*wtk_os_dir_walk_notify_f)(void *ths,char *name,int len); int wtk_os_dir_walk(char *dir,void *ths,wtk_os_dir_walk_notify_f notify); #ifdef __cplusplus }; #endif #endif <file_sep>/os/.svn/pristine/cd/cd0df5067013234aa422bd52b621ddff7389caed.svn-base #include "wtk_tcp_msg.h" #include "wtk/os/wtk_fd.h" wtk_tcp_msg_t* wtk_tcp_msg_new(int cmd_bytes,int data_bytes) { wtk_tcp_msg_t *msg; msg=(wtk_tcp_msg_t*)wtk_malloc(sizeof(wtk_tcp_msg_t)); msg->cmd=wtk_strbuf_new(cmd_bytes,1); msg->data=wtk_strbuf_new(data_bytes,1); return msg; } void wtk_tcp_msg_delete(wtk_tcp_msg_t *msg) { wtk_strbuf_delete(msg->cmd); wtk_strbuf_delete(msg->data); } void wtk_tcp_msg_reset(wtk_tcp_msg_t *msg) { wtk_strbuf_reset(msg->cmd); wtk_strbuf_reset(msg->data); } void wtk_tcp_msg_set(wtk_tcp_msg_t *msg,char *cmd,int cmd_bytes,char* data,int data_bytes) { wtk_strbuf_reset(msg->cmd); wtk_strbuf_push(msg->cmd,cmd,cmd_bytes); wtk_strbuf_reset(msg->data); wtk_strbuf_push(msg->data,data,data_bytes); } void wtk_tcp_msg_set_cmd(wtk_tcp_msg_t *msg,char *cmd,int cmd_bytes) { wtk_strbuf_reset(msg->cmd); wtk_strbuf_push(msg->cmd,cmd,cmd_bytes); } void wtk_tcp_msg_print(wtk_tcp_msg_t *msg) { wtk_debug("========= msg=%p ============\n",msg); printf("cmd=[%.*s]\n",msg->cmd->pos,msg->cmd->data); printf("data=[%.*s]\n",msg->data->pos,msg->data->data); } int wtk_tcp_msg_read_string(wtk_strbuf_t *buf,int fd) { wtk_fd_state_t s; int len; int ret=-1; wtk_strbuf_reset(buf); s=wtk_fd_recv2(fd,(char*)&len,4);//,&read); //wtk_debug("len=%d read=%d\n",len,read); if(s!=WTK_OK)// || read!=4) { wtk_debug("read string len failed state=%d\n",s); perror(__FUNCTION__); //exit(0); goto end; } if(len>0) { wtk_strbuf_expand(buf,len); //wtk_debug("len=%d\n",len); s=wtk_fd_recv2(fd,buf->data,len);//,&read); //print_data(buf->data,read); if(s!=WTK_OK)// || read!=len) { wtk_debug("read string len failed state=%d len=%d\n",s,len); perror(__FUNCTION__); //exit(0); goto end; } buf->pos=len; }else { buf->pos=0; } ret=0; end: return ret; } int wtk_tcp_msg_write_string(int fd,char *data,int bytes) { wtk_fd_state_t s; int writed; int ret=-1; //wtk_debug("send bytes=%d\n",bytes); //print_data(data,bytes); s=wtk_fd_send(fd,(char*)&(bytes),4,&writed); if(s!=WTK_OK || writed!=4) { wtk_debug("write string len failed\n"); goto end; } if(bytes>0) { s=wtk_fd_send(fd,data,bytes,&writed); if(s!=WTK_OK || writed!=bytes) { wtk_debug("write string data failed\n"); goto end; } } ret=0; end: return ret; } int wtk_tcp_msg_read(wtk_tcp_msg_t *msg,int fd) { int ret; ret=wtk_tcp_msg_read_string(msg->cmd,fd); if(ret!=0){goto end;} ret=wtk_tcp_msg_read_string(msg->data,fd); if(ret!=0){goto end;} end: return ret; } int wtk_tcp_msg_write(wtk_tcp_msg_t *msg,int fd) { int ret; ret=wtk_tcp_msg_write_string(fd,msg->cmd->data,msg->cmd->pos); if(ret!=0){goto end;} ret=wtk_tcp_msg_write_string(fd,msg->data->data,msg->data->pos); if(ret!=0){goto end;} ret=0; end: return ret; } <file_sep>/os/wtk_time.c #include "wtk_time.h" #include "wtk/core/wtk_str.h" #include <ctype.h> #include <time.h> static char* month[]={ "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; static char* wkday[]={ "Sun","Mon","Tue","Wed","Thu","Fri","Sat" }; wtk_time_t* wtk_time_new() { wtk_time_t *t; int ret; t=(wtk_time_t*)wtk_malloc(sizeof(*t)); ret=wtk_time_init(t); if(ret!=0) { wtk_time_delete(t); t=0; } return t; } int wtk_time_delete(wtk_time_t *t) { wtk_time_clean(t); wtk_free(t); return 0; } int wtk_time_init(wtk_time_t* t) { int ret; ret=wtk_lock_init(&(t->lock)); if(ret!=0){goto end;} t->slot=0; wtk_string_set(&(t->http_time),0,0); wtk_string_set(&(t->log_time),0,0); ret=wtk_time_update(t); end: return ret; } int wtk_time_clean(wtk_time_t* t) { return wtk_lock_clean(&(t->lock)); } #ifdef WIN32 int wtk_time_update_direct(wtk_time_t* t) { time_t ct; struct tm* m; char *p; int ret,n; t->wtk_cached_time=time_get_ms(); ret=time(&ct); if(ret==-1) { perror("time failed."); goto end; } m=gmtime(&ct); if(!m) { perror("gmtime failed."); goto end; } ++t->slot; if(t->slot>=WTK_TIME_SLOTS) { t->slot=0; } ret=0; p=t->cached_http_time[t->slot]; n=sprintf(p,"%s, %d %s %04d %02d:%02d:%02d GMT",wkday[m->tm_wday],m->tm_mday, month[m->tm_mon],m->tm_year+1900,m->tm_hour,m->tm_min,m->tm_sec); t->http_time.data=p; t->http_time.len=n; p=t->cached_log_time[t->slot]; n=sprintf(p,"%04d/%02d/%02d %02d:%02d:%02d",m->tm_year+1900,m->tm_mon+1,m->tm_mday,m->tm_hour,m->tm_min,m->tm_sec); t->log_time.data=p; t->log_time.len=n; end: return ret; } #else int wtk_time_update_direct(wtk_time_t* t) { struct timeval tv; time_t ct; struct tm xm; struct tm* m; char *p; int ret,n; ret=gettimeofday(&tv,0); if(ret==0) { //t->wtk_cached_time=tv.tv_sec*1000.0+tv.tv_usec*1.0/1000; t->wtk_cached_time=tv.tv_sec*1000.0+tv.tv_usec*0.001;//1.0/1000; }else { perror("gettimeofday failed."); } //wtk_debug("update: %f\n",t->wtk_cached_time); ret=time(&ct); if(ret==-1) { perror("time failed."); goto end; } //m=gmtime(&ct); m=localtime_r(&ct,&xm); if(!m) { perror("gmtime failed."); goto end; } ++t->slot; if(t->slot>=WTK_TIME_SLOTS) { t->slot=0; } t->tm=*m; ret=0; p=t->cached_http_time[t->slot]; n=sprintf(p,"%s, %d %s %04d %02d:%02d:%02d GMT",wkday[m->tm_wday],m->tm_mday, month[m->tm_mon],m->tm_year+1900,m->tm_hour,m->tm_min,m->tm_sec); t->http_time.data=p; t->http_time.len=n; p=t->cached_log_time[t->slot]; n=sprintf(p,"%04d-%02d-%02d %02d:%02d:%02d",m->tm_year+1900,m->tm_mon+1,m->tm_mday,m->tm_hour,m->tm_min,m->tm_sec); t->log_time.data=p; t->log_time.len=n; end: return ret; } #endif int wtk_time_update(wtk_time_t* t) { int ret; ret=wtk_lock_lock(&t->lock); if(ret!=0) { perror(__FUNCTION__); goto end; } ret=wtk_time_update_direct(t); if(ret!=0) { perror(__FUNCTION__); } wtk_lock_unlock(&(t->lock)); end: return 0; } char* wtk_time_g_now() { time_t t; t=time(0); return ctime(&t); } <file_sep>/core/fft/wtk_stft_cfg.c #include "wtk_stft_cfg.h" int wtk_stft_cfg_init(wtk_stft_cfg_t *cfg) { cfg->channel=4; cfg->win=512; cfg->overlap=0.75; cfg->step=cfg->win*cfg->overlap; cfg->use_sine=0; cfg->use_hamming=0; cfg->use_hann=0; cfg->keep_win=0; cfg->use_fftscale=1; return 0; } int wtk_stft_cfg_clean(wtk_stft_cfg_t *cfg) { return 0; } int wtk_stft_cfg_update_local(wtk_stft_cfg_t *cfg,wtk_local_cfg_t *lc) { wtk_string_t *v; wtk_local_cfg_update_cfg_b(lc,cfg,use_fftscale,v); wtk_local_cfg_update_cfg_b(lc,cfg,use_sine,v); wtk_local_cfg_update_cfg_b(lc,cfg,keep_win,v); wtk_local_cfg_update_cfg_b(lc,cfg,use_hamming,v); wtk_local_cfg_update_cfg_b(lc,cfg,use_hann,v); wtk_local_cfg_update_cfg_i(lc,cfg,channel,v); wtk_local_cfg_update_cfg_i(lc,cfg,win,v); wtk_local_cfg_update_cfg_f(lc,cfg,overlap,v); return 0; } int wtk_stft_cfg_update(wtk_stft_cfg_t *cfg) { cfg->step=cfg->win*(1-cfg->overlap); return 0; } <file_sep>/os/wtk_socketproc.h #ifndef WTK_OS_WTK_SOCKETPROC_H_ #define WTK_OS_WTK_SOCKETPROC_H_ #include "wtk/core/wtk_type.h" #include "wtk_pipeproc.h" #include "wtk_fd.h" #include "wtk_pid.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_socketproc wtk_socketproc_t; #define wtk_socketproc_fd(s) ((s)->v[(s)->vi]) struct wtk_socketproc { char *name; pid_t pid; int v[2]; int vi; pipeproc_init_handler init; pipeproc_clean_handler clean; pipeproc_handler handler; void *user_data; }; wtk_socketproc_t* wtk_socketproc_new(char* name,pipeproc_init_handler init, pipeproc_clean_handler clean,pipeproc_handler handler,void *data); int wtk_socketproc_delete(wtk_socketproc_t* p); int wtk_socketproc_start(wtk_socketproc_t* proc); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_kdict.c #include "wtk_kdict.h" wtk_kdict_t* wtk_kdict_new(wtk_strpool_t *pool,int hint,void *ths,wtk_kdict_parse_value_f parse_f) { wtk_kdict_t *k; k=(wtk_kdict_t*)wtk_malloc(sizeof(wtk_kdict_t)); k->pool=pool; k->hash=wtk_str_hash_new(hint); k->parse_ths=ths; k->parse_f=parse_f; return k; } void wtk_kdict_delete(wtk_kdict_t *d) { wtk_str_hash_delete(d->hash); wtk_free(d); } int wtk_kdict_bytes(wtk_kdict_t *d) { return wtk_str_hash_bytes(d->hash)+sizeof(wtk_kdict_t); } int wtk_kdict_load(wtk_kdict_t *d,wtk_source_t *src) { wtk_strbuf_t *buf; wtk_heap_t *heap=d->hash->heap; wtk_string_t *k; void *p; int ret; buf=wtk_strbuf_new(256,1); while(1) { ret=wtk_source_read_string(src,buf); if(ret!=0){ret=0;goto end;} //wtk_debug("[%.*s]\n",buf->pos,buf->data); if(d->pool) { k=wtk_strpool_find(d->pool,buf->data,buf->pos,1); }else { k=wtk_heap_dup_string(heap,buf->data,buf->pos); } //wtk_debug("[%.*s]\n",k->len,k->data); ret=wtk_source_skip_sp(src,NULL); if(ret!=0){goto end;} ret=wtk_source_read_line(src,buf); if(ret!=0){goto end;} wtk_strbuf_strip(buf); if(d->parse_f) { p=d->parse_f(d->parse_ths,d,k,buf->data,buf->pos); }else { if(d->pool) { p=wtk_strpool_find(d->pool,buf->data,buf->pos,1); }else { p=wtk_heap_dup_string(heap,buf->data,buf->pos); } wtk_str_hash_add(d->hash,k->data,k->len,p); } if(!p){ret=-1;goto end;} } ret=0; end: wtk_strbuf_delete(buf); return ret; } int wtk_kdict_load_file(wtk_kdict_t *d,char *fn) { return wtk_source_load_file(d,(wtk_source_load_handler_t)wtk_kdict_load,fn); } void* wtk_kdict_get(wtk_kdict_t *d,char *k,int k_bytes) { return wtk_str_hash_find(d->hash,k,k_bytes); } <file_sep>/core/segmenter/wtk_chnpos_model.h #ifndef WTK_CORE_SEGMENTER_WTK_CHNPOS_MODEL #define WTK_CORE_SEGMENTER_WTK_CHNPOS_MODEL #include "wtk/core/wtk_type.h" #include "wtk/core/cfg/wtk_source.h" #include "wtk/core/wtk_strpool.h" #include "wtk/core/wtk_hash.h" #include "wtk/core/wtk_robin.h" #include "wtk/core/wtk_larray.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_chnpos_model wtk_chnpos_model_t; typedef struct wtk_chnpos_state wtk_chnpos_state_t; typedef struct wtk_chnpos_wrd wtk_chnpos_wrd_t; #define MIN_FLOAT -3.14e15 //B(词首),M (词中),E(词尾)和S(单独成词) typedef enum { WTK_CHNPOS_B=0, WTK_CHNPOS_M, WTK_CHNPOS_E, WTK_CHNPOS_S, }wtk_chnpos_bmes_t; typedef struct { wtk_chnpos_state_t *to; float prob; }wtk_chnpos_arc_t; typedef struct { wtk_string_t *wrd; //wtk_chnpos_wrd_t *wrd; float prob; }wtk_chnpos_emit_t; struct wtk_chnpos_state { //wtk_queue_node_t q_n; wtk_chnpos_arc_t *arcs; wtk_chnpos_emit_t *emits; unsigned short nemit; unsigned short narc; float start;//start prob unsigned char bmes; unsigned char pos; }; struct wtk_chnpos_wrd { wtk_string_t wrd; wtk_chnpos_state_t **states; int nstate; }; struct wtk_chnpos_model { wtk_str_hash_t *pos_map; int npos; //wtk_queue_t state_q; wtk_str_hash_t *wrd_map; wtk_hash_t *state_map; wtk_robin_t *state_robin; wtk_larray_t *pos_a; }; wtk_chnpos_model_t* wtk_chnpos_model_new(); void wtk_chnpos_model_delete(wtk_chnpos_model_t *m); int wtk_chnpos_model_load(wtk_chnpos_model_t *m,wtk_source_t *src); wtk_chnpos_wrd_t* wtk_chnpos_model_get_wrd(wtk_chnpos_model_t *m,char *wrd,int wrd_bytes); wtk_chnpos_wrd_t wtk_chnpos_model_get_wrd2(wtk_chnpos_model_t *m,char *wrd,int wrd_bytes); float wtk_chnpos_state_get_emit_prob(wtk_chnpos_state_t *state,wtk_string_t *wrd); float wtk_chnpos_state_get_trans_prob(wtk_chnpos_state_t *state,wtk_chnpos_state_t *nxt); int wtk_chnpos_wrd_has_state(wtk_chnpos_wrd_t *wrd,wtk_chnpos_state_t *state); void wtk_chnpos_state_print(wtk_chnpos_model_t *m,wtk_chnpos_state_t *item); wtk_string_t* wtk_chnpos_model_get_pos_str(wtk_chnpos_model_t *m,int idx); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/5a/5a5c74b5b56c8819146c72e19b780fcb8d0b6450.svn-base #include "wtk_wvec.h" #include <ctype.h> int wtk_wvec_load(wtk_wvec_t *cfg,wtk_source_t *src) { int v[2]; wtk_strbuf_t *buf; int ret; wtk_wvec_item_t *item; int idx=0; int i; buf=wtk_strbuf_new(256,1); ret=wtk_source_read_int(src,v,2,0); cfg->voc_size=v[0]; cfg->vec_size=v[1]; cfg->wrds=(wtk_wvec_item_t**)wtk_calloc(cfg->voc_size,sizeof(wtk_wvec_item_t*)); cfg->hash=wtk_str_hash_new(cfg->voc_size+3); //cfg->v1=wtk_vecf_new(cfg->vec_size); //cfg->v2=wtk_vecf_new(cfg->vec_size); cfg->v1=(wtk_wvec_float_t*)wtk_calloc(cfg->vec_size,sizeof(wtk_wvec_float_t)); cfg->v2=(wtk_wvec_float_t*)wtk_calloc(cfg->vec_size,sizeof(wtk_wvec_float_t)); while(1) { ret=wtk_source_read_string(src,buf); if(ret!=0){ret=0;goto end;} //wtk_debug("[%.*s]\n",buf->pos,buf->data); item=(wtk_wvec_item_t*)wtk_heap_malloc(cfg->hash->heap,sizeof(wtk_wvec_item_t)); item->wrd_idx=idx; cfg->wrds[idx++]=item; item->name=wtk_heap_dup_string(cfg->hash->heap,buf->data,buf->pos); item->p=(wtk_wvec_float_t*)wtk_calloc(cfg->vec_size,sizeof(wtk_wvec_float_t)); ret=wtk_source_read_double(src,item->p,cfg->vec_size); wtk_str_hash_add(cfg->hash,item->name->data,item->name->len,item); } end: item=cfg->unk=(wtk_wvec_item_t*)wtk_heap_malloc(cfg->hash->heap,sizeof(wtk_wvec_item_t)); item->name=wtk_heap_dup_string(cfg->hash->heap,"unk",3); item->p=(wtk_wvec_float_t*)wtk_calloc(cfg->vec_size,sizeof(wtk_wvec_float_t)); for(i=0;i<cfg->vec_size;++i) { item->p[i]=1.0/cfg->vec_size; } wtk_strbuf_delete(buf); return ret; } wtk_wvec_t* wtk_wvec_new(char *fn) { wtk_wvec_t *v; v=(wtk_wvec_t*)wtk_malloc(sizeof(wtk_wvec_t)); v->hash=NULL; v->wrds=NULL; v->v1=NULL; v->v2=NULL; v->unk=NULL; wtk_source_load_file(v,(wtk_source_load_handler_t)wtk_wvec_load,fn); return v; } void wtk_wvec_delete(wtk_wvec_t *v) { if(v->v1) { wtk_free(v->v1); //wtk_vecf_delete(v->v1); } if(v->v2) { wtk_free(v->v2); //wtk_vecf_delete(v->v2); } if(v->hash) { wtk_str_hash_delete(v->hash); } if(v->wrds) { wtk_free(v->wrds); } wtk_free(v); } wtk_wvec_item_t* wtk_wvec_find(wtk_wvec_t *cfg,char *data,int bytes) { return (wtk_wvec_item_t*)wtk_str_hash_find(cfg->hash,data,bytes); } //float wtk_wvec_snt_to_vec(wtk_wvec_t *v,char *s,int s_bytes,wtk_vecf_t *vec) //{ // int init; // wtk_string_t str; // char *e; // int n; // wtk_wvec_item_t *item; // // wtk_vecf_zero(vec); // e=s+s_bytes; // init=0; // wtk_string_set(&(str),0,0); // while(s<e) // { // n=wtk_utf8_bytes(*s); // if(init==0) // { // if(n>1 || !isspace(*s)) // { // str.data=s; // str.len=0; // init=1; // } // }else // { // if(n==1 && isspace(*s)) // { // str.len=s-str.data; // //wtk_debug("[%.*s]\n",str.len,str.data); // item=wtk_wvec_find(v,str.data,str.len); // if(item) // { // //wtk_vecf_print(item->m); // wtk_vecf_add(vec,item->m->p); // } // str.data=NULL; // init=0; // } // } // s+=n; // } // if(init==1 && str.data>0) // { // str.len=e-str.data; // //wtk_debug("[%.*s]\n",str.len,str.data); // item=wtk_wvec_find(v,str.data,str.len); // if(item) // { // wtk_vecf_add(vec,item->m->p); // } // } // return wtk_vecf_norm(vec); // //return 1.00; //} // // //float wtk_wvec_like(wtk_wvec_t *v,char *s1,int s1_bytes,char *s2,int s2_bytes) //{ // wtk_vecf_t *v1=v->v1; // wtk_vecf_t *v2=v->v2; // float f; // // wtk_wvec_snt_to_vec(v,s1,s1_bytes,v1); // wtk_wvec_snt_to_vec(v,s2,s2_bytes,v2); // f=wtk_vecf_cos(v1,v2); // //wtk_debug("[%.*s]=[%.*s] %f\n",s1_bytes,s1,s2_bytes,s2,f); // return f; //} float wtk_wvec_snt_to_vec(wtk_wvec_t *v,char *s,int s_bytes,wtk_vecf_t *vec) { return 0; } float wtk_wvec_like(wtk_wvec_t *v,char *s1,int s1_bytes,char *s2,int s2_bytes) { return 0; } <file_sep>/core/sha1.h #ifndef QTK_SHA1_H #define QTK_SHA1_H #include "wtk/core/wtk_type.h" /* SHA-1 in C By <NAME> <<EMAIL>> 100% Public Domain */ typedef struct { uint32_t state[5]; uint32_t count[2]; unsigned char buffer[64]; } SHA1_CTX; void QTK_SHA1Transform( uint32_t state[5], const unsigned char buffer[64] ); void QTK_SHA1Init( SHA1_CTX * context ); void QTK_SHA1Update( SHA1_CTX * context, const unsigned char *data, uint32_t len ); void QTK_SHA1Final( unsigned char digest[20], SHA1_CTX * context ); void QTK_SHA1( char *hash_out, const char *str, int len); void QTK_SHA1_hex( char *hash_out, const char *str, int len ); #endif /* SHA1_H */ <file_sep>/core/.svn/pristine/18/18d231c1af16e87ba20c5c3e204804929f03225d.svn-base #ifndef WTK_CORE_WTK_WAVFILE_H_ #define WTK_CORE_WTK_WAVFILE_H_ #include "wtk/core/wavehdr.h" #include "wtk/core/wtk_os.h" #include <stdio.h> #ifdef __cplusplus extern "C" { #endif typedef struct wtk_wavfile wtk_wavfile_t; /* * current used for write wave file. */ struct wtk_wavfile { WaveHeader hdr; FILE *file; int writed; int max_pend; int pending; }; wtk_wavfile_t* wtk_wavfile_new(int sample_rate); void wtk_wavfile_set_channel(wtk_wavfile_t *w,int channel); void wtk_wavfile_set_channel2(wtk_wavfile_t *f,int c,int bytes_per_sample); int wtk_wavfile_delete(wtk_wavfile_t *f); void wtk_wavfile_init(wtk_wavfile_t *f,int sample_rate); void wtk_wavfile_clean(wtk_wavfile_t *f); int wtk_wavfile_open(wtk_wavfile_t *f,char *fn); int wtk_wavfile_open2(wtk_wavfile_t *f,char *prev); int wtk_wavfile_write(wtk_wavfile_t *f,const char *data,int bytes); int wtk_wavfile_writef(wtk_wavfile_t *f,float *data,int len); void wtk_wavfile_write_float(wtk_wavfile_t *f,float **data,int len); int wtk_wavfile_flush(wtk_wavfile_t *f); int wtk_wavfile_close(wtk_wavfile_t *f); void wtk_wavfile_write_mc(wtk_wavfile_t *f,short **mic,int len); void wtk_wavfile_write_int(wtk_wavfile_t *f,int **mic,int len); int wtk_wavfile_cancel(wtk_wavfile_t *f,int n); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/ba/bae444186adae4fe8e5e0212e2192e4b0df203e7.svn-base #include "wtk_slist.h" void wtk_slist_init(wtk_slist_t *list) { list->prev=0; } void wtk_slist_push(wtk_slist_t *list,wtk_slist_node_t *node) { node->prev=list->prev; list->prev=node; } void wtk_slist_push_front(wtk_slist_t *list,wtk_slist_node_t *node) { while(list->prev) { list=list->prev; } node->prev=NULL; list->prev=node; } int wtk_slist_remove(wtk_slist_t *list,wtk_slist_node_t *n) { wtk_slist_node_t *tmp,*prev; for(prev=NULL,tmp=list->prev;tmp;tmp=tmp->prev) { if(tmp==n) { if(prev) { prev->prev=tmp->prev; }else { list->prev=tmp->prev; } return 1; } prev=tmp; } return 0; } wtk_slist_node_t* wtk_slist_pop(wtk_slist_t *list) { wtk_slist_node_t *node; if(list->prev) { node=list->prev; list->prev=node->prev; }else { node=0; } return node; } int wtk_slist_len(wtk_slist_t *l) { wtk_slist_node_t *n; int len=0; for(n=l->prev;n;n=n->prev) { ++len; } return len; } void wtk_slist2_init(wtk_slist2_t *l) { l->pop=l->push=NULL; } void wtk_slist2_push(wtk_slist2_t *l,wtk_slist_node_t *n) { n->prev=NULL; if(l->push) { l->push->prev=n; l->push=n; }else { l->pop=l->push=n; } } wtk_slist_node_t* wtk_slist2_pop(wtk_slist2_t *l) { wtk_slist_node_t *n; if(l->pop) { n=l->pop; if(n==l->push) { l->pop=l->push=NULL; }else { l->pop=n->prev; } return n; }else { return NULL; } } <file_sep>/core/.svn/pristine/f9/f9b3afed31b815f9bc0664874e8be1d0bbd47d82.svn-base #include "wtk_fkv2.h" int wtk_fkv2_load_hdr(wtk_fkv2_t *k) { wtk_hash_str_node_t *node; FILE *f=k->f; char buf[256]; int ret; unsigned char t; int i; if(k->f_of>0) { ret=fseek(f,k->f_of,SEEK_SET); if(ret!=0) { wtk_debug("seek %d failed\n",k->f_of); goto end; } } ret=fread(buf,4,1,f); if(ret!=1){ret=-1;goto end;} //wtk_debug("[%.*s]\n",4,buf); ret=fread(&(k->max),4,1,f); if(ret!=1){ret=-1;goto end;} ret=fread(&(k->step),4,1,f); if(ret!=1){ret=-1;goto end;} ret=fread(&(t),1,1,f); if(ret!=1){ret=-1;goto end;} switch(t) { case 1: k->type=WTK_FKV2_INT; break; case 2: k->type=WTK_FKV2_FLOAT; break; case 3: k->type=WTK_FKV2_STRING; break; } k->nslot=(k->max*1.0/k->step)+1; //wtk_debug("max=%d step=%d type=%d nslot=%d\n",k->max,k->step,t,k->nslot); k->char_map=wtk_str_hash_new(k->max+3); for(i=0;i<k->max;++i) { ret=fread(&(t),1,1,f); if(ret!=1){ret=-1;goto end;} //wtk_debug("t=%d\n",t); ret=fread(buf,1,t,f); if(ret!=t){ret=-1;goto end;} //wtk_debug("[%.*s]\n",t,buf); node=(wtk_hash_str_node_t*)wtk_str_hash_find_node3(k->char_map,buf,t,1); node->v.u=i; } k->slots=(unsigned int*)wtk_malloc(sizeof(unsigned int)*k->nslot); ret=fread(k->slots,sizeof(unsigned int),k->nslot,f); if(ret!=k->nslot){ret=-1;goto end;} k->slot_offset=ftell(f); ret=0; end: return ret; } wtk_fkv2_t* wtk_fkv2_new3(FILE *f,int of,int len,int want_close) { wtk_fkv2_t *k=NULL; int ret; k=(wtk_fkv2_t*)wtk_malloc(sizeof(wtk_fkv2_t)); k->f=f; k->f_of=of; k->f_len=len; k->file_want_close=want_close; k->char_map=NULL; k->slots=NULL; k->buf=wtk_strbuf_new(256,1); ret=wtk_fkv2_load_hdr(k); if(ret!=0) { wtk_fkv2_delete(k); k=NULL; } return k; } wtk_fkv2_t* wtk_fkv2_new(char *fn) { FILE *f; wtk_fkv2_t *k=NULL; f=fopen(fn,"rb"); if(!f){goto end;} k=wtk_fkv2_new3(f,0,-1,1); end: return k; } wtk_fkv2_t* wtk_fkv2_new2(wtk_rbin2_t *rbin,char *fn) { wtk_rbin2_item_t *item; item=wtk_rbin2_get(rbin,fn,strlen(fn)); if(!item) { wtk_debug("[%s] not found\n",fn); return NULL; } return wtk_fkv2_new3(rbin->f,item->pos,item->len,0); } void wtk_fkv2_delete(wtk_fkv2_t* k) { wtk_strbuf_delete(k->buf); if(k->char_map) { wtk_str_hash_delete(k->char_map); } if(k->slots) { wtk_free(k->slots); } if(k->file_want_close && k->f) { fclose(k->f); } wtk_free(k); } void wtk_fkv_env_init(wtk_fkv2_t *k,wtk_fkv_env_t *env) { env->depth=0; env->offset=0; if(k->f_of>0) { env->offset=k->f_of; } env->is_end=0; env->is_err=0; } void wtk_fkv_env_print(wtk_fkv_env_t *env) { printf("depth:%d\n",env->depth); printf("offset:%d\n",env->offset); printf("float:%f\n",env->v.f); printf("end:%d\n",env->is_end); printf("err:%d\n",env->is_err); } int wtk_fkv2_get_slot(wtk_fkv2_t *kv,wtk_fkv_env_t *env,unsigned int offset,unsigned int idx) { FILE *f=kv->f; unsigned int len,ko; unsigned char *data=NULL; unsigned char *s,*e,bytes; unsigned short id; unsigned char type; int ret; ret=fseek(f,offset,SEEK_SET); if(ret!=0) { wtk_debug("set of=%d failed\n",offset); goto end; } //wtk_debug("len=%d\n",len); ret=fread(&len,4,1,f); if(ret!=1) { perror(__FUNCTION__); wtk_debug("read cnt failed,ret=%d offset=%d idx=%d\n",ret,offset,idx); ret=-1;goto end; } data=wtk_malloc(len); ret=fread(data,1,len,f); if(ret!=len) { perror(__FUNCTION__); wtk_debug("read cnt failed,ret=%d offset=%d idx=%d\n",ret,offset,idx); exit(0); ret=-1;goto end; } s=data;e=s+len; //wtk_debug("len=%d\n",len); while(s<e) { //idata=struct.pack("<IHB",len(body_data),ki,t) //ko=*(unsigned int*)s; #ifndef USE_ARM id=((unsigned short*)s)[2]; type=((unsigned char*)s)[6]; #else memcpy(&id,s+4,2); memcpy(&type,s+6,1); #endif //wtk_debug("id=%d/%d type=%d\n",id,idx,type); if(id==idx) { #ifndef USE_ARM ko=*(unsigned int*)s; #else memcpy(&ko,s,sizeof(unsigned int)); #endif env->offset=offset+4+len+ko; //wtk_debug("id=%d\n",id); switch(type) { case 0: env->is_end=0; break; case 1: env->is_end=1; #ifndef USE_ARM env->v.v=*((int*)(s+7)); #else memcpy(&(env->v.v),s+7,sizeof(unsigned int)); #endif break; case 2: env->is_end=1; #ifndef USE_ARM env->v.f=*((float*)(s+7)); #else memcpy(&(env->v.f),s+7,sizeof(float)); #endif break; case 3: #ifndef USE_ARM bytes=*(s+7); #else memcpy(&bytes,s+7,1); #endif //print_data((char*)(s+8+4),bytes-4); wtk_strbuf_reset(kv->buf); wtk_strbuf_push(kv->buf,(char*)(s+8),bytes); wtk_string_set(&(env->v.str),kv->buf->data,kv->buf->pos); env->is_end=1; break; } ret=0; goto end; break; } switch(type) { case 0: s+=7; break; case 1: case 2: s+=11; break; case 3: s+=7; #ifndef USE_ARM s+=*s+1; #else memcpy(&bytes,s,1); s=s+bytes+1; #endif break; default: ret=-1; goto end; break; } } ret=-1; end: if(data) { wtk_free(data); } return ret; } int wtk_fkv2_search_slot(wtk_fkv2_t *kv,wtk_fkv_env_t *e,unsigned int idx) { unsigned int v; int i; i=(int)(idx/kv->step+0.5); v=kv->slots[i]+kv->slot_offset; // if(kv->f_of>0) // { // v+=kv->f_of; // } //wtk_debug("idx=%d i=%d\n",idx,i); return wtk_fkv2_get_slot(kv,e,v,idx); } int wtk_fkv2_search(wtk_fkv2_t *kv,wtk_fkv_env_t *e,unsigned int idx) { int ret; if(e->depth==0) { ret=wtk_fkv2_search_slot(kv,e,idx); }else { ret=wtk_fkv2_get_slot(kv,e,e->offset,idx); } //wtk_debug("ret=%d\n",ret); ++e->depth; return ret; } int wtk_fkv2_get(wtk_fkv2_t *kv,wtk_fkv_env_t *env,char *k,int k_bytes) { wtk_hash_str_node_t *node; int ret=-1; //wtk_debug("[%.*s]\n",bytes,data); //wtk_fkv_env_init(env); env->is_end=0; node=(wtk_hash_str_node_t*)wtk_str_hash_find_node3(kv->char_map,k,k_bytes,0); if(!node) { //wtk_debug("[%.*s] not exist.\n",k_bytes,k); goto end; } ret=wtk_fkv2_search(kv,env,node->v.u); end: if(ret!=0) { env->is_err=1; } return ret; } int wtk_fkv2_has(wtk_fkv2_t *kv,wtk_fkv_env_t *env,char *data,int bytes) { typedef enum { WTK_FKV_INIT, WTK_FKV_ENG, }wtk_fkv_state_t; char *s,*e; int n; wtk_fkv_state_t state; wtk_string_t v; int ret; //wtk_debug("[%.*s]\n",bytes,data); wtk_string_set(&(v),0,0); s=data;e=s+bytes; state=WTK_FKV_INIT; while(s<e) { n=wtk_utf8_bytes(*s); switch(state) { case WTK_FKV_INIT: if(n>1) { ret=wtk_fkv2_get(kv,env,s,n); if(ret!=0){goto end;} }else { if(s+n>=e) { ret=wtk_fkv2_get(kv,env,s,n); if(ret!=0){goto end;} }else { v.data=s; state=WTK_FKV_ENG; } } break; case WTK_FKV_ENG: if(n>1) { v.len=s-v.data; //wtk_debug("[%.*s]\n",v.len,v.data); //wtk_debug("[%.*s]\n",n,s); ret=wtk_fkv2_get(kv,env,v.data,v.len); if(ret!=0){goto end;} ret=wtk_fkv2_get(kv,env,s,n); if(ret!=0){goto end;} state=WTK_FKV_INIT; }else if(s+n>=e) { v.len=s-v.data; //wtk_debug("[%.*s]\n",v.len,v.data); ret=wtk_fkv2_get(kv,env,v.data,v.len); if(ret!=0){goto end;} } break; } s+=n; } ret=0; end: return ret; } <file_sep>/os/.svn/pristine/77/770a24f1ea0ab268fc2c046fce2a304d850886e3.svn-base /* * wtk_atomic.h * * Created on: 2015-7-27 * Author: xjl */ #ifndef WTK_ATOMIC_H_ #define WTK_ATOMIC_H_ #include "wtk/core/wtk_type.h" #ifdef __cplusplus extern "C"{ #endif #define wtk_atomic_cmp_set(ptr,oldvar,newvar) __sync_bool_compare_and_swap(ptr,oldvar,newvar) #define wtk_atomic_fetch_add(var,value) __sync_fetch_and_add(var,value) #define wtk_memory_barrier() __sync_synchronize() #define wtk_cpu_pause() __asm__("pause") #ifdef __cplusplus }; #endif #endif /* WTK_ATOMIC_H_ */ <file_sep>/os/.svn/pristine/4b/4bfc2a96bc38e59fa233b4738c2f316c6147a76c.svn-base #include "wtk_flog.h" #include "wtk/core/wtk_os.h" void wtk_flog_reset(wtk_flog_t *f); wtk_flog_t* wtk_flog_new(int max_pend) { wtk_flog_t *f; f=(wtk_flog_t*)wtk_calloc(1,sizeof(*f)); f->max_pend=max_pend; wtk_flog_reset(f); return f; } int wtk_flog_delete(wtk_flog_t *f) { wtk_flog_reset(f); wtk_free(f); return 0; } void wtk_flog_reset(wtk_flog_t *f) { f->writed=0; f->pending=0; f->write_cb=0; f->app_data=0; wtk_flog_close(f); } void wtk_flog_set_cb(wtk_flog_t *f,void *app_data,wtk_flog_write_cb_f cb) { f->app_data=app_data; f->write_cb=cb; } int wtk_flog_open(wtk_flog_t *f,char *fn,void *cb_hook,wtk_flog_write_cb_f cb) { int ret; wtk_flog_reset(f); wtk_mkdir_p(fn,'/',0); f->file=fopen(fn,"wb"); ret=f->file?0:-1; if(ret!=0){goto end;} wtk_flog_set_cb(f,cb_hook,cb); if(f->write_cb) { ret=f->write_cb(f->app_data,WTK_FLOG_OPEN,f); if(ret<0){goto end;} } ret=0; end: return ret; } int wtk_flog_close(wtk_flog_t *f) { if(f->file) { wtk_flog_flush(f); if(f->write_cb) { f->write_cb(f->app_data,WTK_FLOG_CLOSE,f); } fclose(f->file); f->file=0; } return 0; } int wtk_flog_write(wtk_flog_t *f,const char *data,int bytes) { int ret; ret=fwrite(data,bytes,1,f->file); if(ret!=1){ret=-1;goto end;} f->writed+=bytes; f->pending+=bytes; if(f->max_pend>=0 && f->pending>f->max_pend) { ret=wtk_flog_flush(f); }else { ret=0; } end: return ret; } int wtk_flog_flush(wtk_flog_t *f) { int ret; if(f->pending<=0){return 0;} if(f->write_cb) { ret=f->write_cb(f->app_data,WTK_FLOG_FLUSH,f); if(ret!=0){goto end;} } ret=fflush(f->file); if(ret!=0){goto end;} f->pending=0; end: return ret; } <file_sep>/core/.svn/pristine/50/50ffe5014062fdbb523add561fa33c08dd307797.svn-base #include "wtk_txtparser_cfg.h" #include <ctype.h> /* =============================================================== space=[ \r\t\n] digit=[0-9] alpha=[a-zA-Z] purechar = digit | alpha extchar=:|.|'|!|-|_ char=purechar | extchar inchar=-|'|:|_ sep=,|;|?|!|" note=space*[tsg]:space*[01]space* word=char[inchar|char]*char*(\(note\))* ============================================================ sent=(space*word[sep|space]+)+ */ #define USE_NORM #ifdef USE_NORM #define is_extchar(c) ((c)==':'||(c)=='.'||(c)=='\''||(c)=='!'||(c)=='-'||(c)=='_') #define is_char(c) (isalnum(c)||is_extchar(c)) #define is_inchar(c) ((c)=='-'||(c)=='\''||c==':'||c=='_') #define is_sep(c) ((c)==','||c==';'||c=='?'||c=='!'||c=='\"') #define is_note(c) ((c)=='s'||c=='t'||c=='g') #else #define is_sepchar(c) ((c)==':'||(c)=='.'||(c)=='\''||(c)=='!') #define is_char(c) (isalnum(c)||is_sepchar(c)||c=='-'||c=='_') #define is_inchar(c) ((c)=='-'||(c)=='\''||c==':'||c=='_') #define is_sep(c) ((c)==','||c==';'||c=='?'||c=='!'||c==':') #define is_note(c) ((c)=='s'||c=='t'||c=='g') #endif #define wtk_slot_set_string_s(s,data) wtk_slot_set_string(s,data,sizeof(data)-1) int wtk_txtparser_cfg_init(wtk_txtparser_cfg_t *cfg) { wtk_string_set_s(&(cfg->extchar),":.'!-_"); wtk_string_set_s(&(cfg->schar),":.'!-_"); wtk_string_set_s(&(cfg->inchar),""); wtk_string_set_s(&(cfg->sep),",;?!\""); wtk_string_set_s(&(cfg->note),"stg"); cfg->dotwrd=0; cfg->dot_hash=0; cfg->def_chn_tone=0; cfg->use_chn_tone=0; cfg->use_utf8=0; return 0; } int wtk_txtparser_cfg_clean(wtk_txtparser_cfg_t *cfg) { if(cfg->dot_hash) { wtk_str_hash_delete(cfg->dot_hash); } return 0; } int wtk_txtparser_cfg_update_local(wtk_txtparser_cfg_t *cfg,wtk_local_cfg_t *lc) { wtk_string_t *v; wtk_local_cfg_update_cfg_b(lc,cfg,use_chn_tone,v); wtk_local_cfg_update_cfg_i(lc,cfg,def_chn_tone,v); wtk_local_cfg_update_cfg_string_v(lc,cfg,extchar,v); wtk_local_cfg_update_cfg_string_v(lc,cfg,schar,v); wtk_local_cfg_update_cfg_string_v(lc,cfg,inchar,v); wtk_local_cfg_update_cfg_string_v(lc,cfg,sep,v); wtk_local_cfg_update_cfg_string_v(lc,cfg,note,v); cfg->dotwrd=wtk_local_cfg_find_array_s(lc,"dotwrd"); wtk_local_cfg_update_cfg_b(lc,cfg,use_utf8,v); return 0; } void wtk_txtparser_cfg_add_dot_word(wtk_txtparser_cfg_t* cfg,char *wrd,int wrd_bytes) { wtk_str_hash_t *h=cfg->dot_hash; wtk_string_t *s; void *v; v=wtk_str_hash_find(h,wrd,wrd_bytes); if(v){goto end;} s=wtk_heap_dup_string(h->heap,wrd,wrd_bytes); wtk_str_hash_add(h,s->data,s->len,s); end: return; } void wtk_txtparser_cfg_init_def_dot_hash(wtk_str_hash_t* h) { static wtk_string_t wrd[]={ wtk_string("co."), wtk_string("dr."), wtk_string("inc."), wtk_string("mr."), wtk_string("mrs."), wtk_string("r."), wtk_string("v."), wtk_string("no.")}; int i,n; n=sizeof(wrd)/sizeof(wtk_string_t); for(i=0;i<n;++i) { wtk_str_hash_add(h,wrd[i].data,wrd[i].len,&(wrd[i])); } } int wtk_txtparser_cfg_update(wtk_txtparser_cfg_t *cfg) { int nslot; if(cfg->dotwrd) { nslot=cfg->dotwrd->nslot*2+1; }else { nslot=13; } cfg->dot_hash=wtk_str_hash_new(nslot); if(cfg->dotwrd) { wtk_string_t **strs; int i; strs=(wtk_string_t**)cfg->dotwrd->slot; for(i=0;i<cfg->dotwrd->nslot;++i) { wtk_str_hash_add(cfg->dot_hash,strs[i]->data,strs[i]->len,strs[i]); } }else { wtk_txtparser_cfg_init_def_dot_hash(cfg->dot_hash); } return 0; } int wtk_txtparser_cfg_is_extchar(wtk_txtparser_cfg_t *cfg,char c) { //wtk_debug("c=%c,%#x\n",c,c); //print_data(cfg->extchar.data,cfg->extchar.len); return wtk_string_is_char_in(&(cfg->extchar),c); } int wtk_txtparser_cfg_is_schar(wtk_txtparser_cfg_t *cfg,char c) { return (isalnum(c) || wtk_string_is_char_in(&(cfg->schar),c)); } int wtk_txtparser_cfg_is_char(wtk_txtparser_cfg_t *cfg,char c) { //wtk_debug("isalnum:%d,extchar:%d\n",isalnum(c),wtk_txtparser_cfg_is_extchar(cfg,c)); //return (isupper(c)|| islower(c) || isdigit(c) ||wtk_txtparser_cfg_is_extchar(cfg,c)); return (isalnum(c) || wtk_txtparser_cfg_is_extchar(cfg,c)); } int wtk_txtparser_cfg_is_inchar(wtk_txtparser_cfg_t *cfg,char c) { //wtk_debug("c=%c\n",c); return wtk_string_is_char_in(&(cfg->inchar),c); } int wtk_txtpaser_cfg_is_sep(wtk_txtparser_cfg_t *cfg,char c) { //wtk_debug("c=%c\n",c); return wtk_string_is_char_in(&(cfg->sep),c); } int wtk_txtpaser_cfg_is_note(wtk_txtparser_cfg_t *cfg,char c) { return wtk_string_is_char_in(&(cfg->note),c); } //============================ charactor, for utf8 ======================= /* * @date 2014.06.18 * @auth jfyuan */ int wtk_string_is_str_in(wtk_string_t* s, wtk_string_t* str) { int ret, i; char c = *(str->data); ret = wtk_string_is_char_in(s, c); for(i=1; i < str->len; i++) { c = *(str->data + i); ret &= wtk_string_is_char_in(s, c); } return ret; } int wtk_txtparser_cfg_is_extchar2(wtk_txtparser_cfg_t *cfg, wtk_string_t* str) { return wtk_string_is_str_in(&(cfg->extchar), str); } /* start char of a word */ int wtk_txtparser_cfg_is_schar2(wtk_txtparser_cfg_t *cfg, wtk_string_t* str) { int ret = 0; char c; if(str->len == 1) { c = *(str->data); ret = (isalnum(c) || wtk_string_is_char_in(&(cfg->schar),c)); } else { ret = wtk_string_is_str_in(&(cfg->schar), str); } return ret; } int wtk_txtparser_cfg_is_char2(wtk_txtparser_cfg_t *cfg, wtk_string_t* str) { int ret = 0; char c; if(str->len == 1) { c = *(str->data); ret = (isalnum(c) || wtk_txtparser_cfg_is_extchar(cfg,c)); } else { ret = wtk_txtparser_cfg_is_extchar2(cfg, str); } return ret; } int wtk_txtparser_cfg_is_inchar2(wtk_txtparser_cfg_t *cfg, wtk_string_t* str) { return wtk_string_is_str_in(&(cfg->inchar), str); } int wtk_txtparser_cfg_is_sep2(wtk_txtparser_cfg_t *cfg, wtk_string_t* str) { return wtk_string_is_str_in(&(cfg->sep), str); } <file_sep>/os/wtk_cond.h #ifndef WTK_OS_WTK_COND #define WTK_OS_WTK_COND #include "wtk/os/wtk_thread.h" #include "wtk/os/wtk_lock.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_cond wtk_cond_t; struct wtk_cond { pthread_mutex_t mutex; pthread_cond_t cond; }; void wtk_cond_init(wtk_cond_t *cond); void wtk_cond_clean(wtk_cond_t *cond); int wtk_cond_wait(wtk_cond_t *cond,int ms); int wtk_cond_wake(wtk_cond_t *cond); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/ab/abcbbc49a6922f8f36f8418f92aaadde3ef38c03.svn-base #ifndef WTK_CORE_PARSE_WTK_STR_PARSE_H_ #define WTK_CORE_PARSE_WTK_STR_PARSE_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_strbuf.h" #ifdef __cplusplus extern "C" { #endif /** * use in json,stop when found '\"' */ typedef struct wtk_str_parse wtk_str_parse_t; typedef enum { WTK_STR_PARSE_NORMAL, WTK_STR_PARSE_U0, WTK_STR_PARSE_U1, WTK_STR_PARSE_U2, WTK_STR_PARSE_U3, WTK_STR_PARSE_H0, WTK_STR_PARSE_H1, WTK_STR_PARSE_D0, WTK_STR_PARSE_D1, }wtk_str_parse_xx_t; /* \" \\ \/ \b \f \n \r \t \u four-hex-digits \ddd \xhh */ struct wtk_str_parse { wtk_strbuf_t *buf; int v; char state; //wtk_str_parse_xx_t unsigned esc:1; }; void wtk_str_parse_init(wtk_str_parse_t *p,wtk_strbuf_t *buf); /** * @return: * 0, continue; * 1, string end,found '\"'; * -1, failed; */ int wtk_str_parse_feed(wtk_str_parse_t *p,char c); //----------------------- test str parse --------------------- void test_str_parse(); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_phndict.h #ifndef WTK_CORE_WTK_PHNDICT #define WTK_CORE_WTK_PHNDICT #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_str_hash.h" #include "wtk/core/wtk_strpool.h" #include "wtk/core/wtk_os.h" #include "wtk/core/cfg/wtk_source.h" #include "wtk/core/wtk_str_parser.h" #include "wtk/core/wtk_str.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_phndict wtk_phndict_t; #define wtk_phndict_find_s(dict,w) wtk_phndict_find(dict,w,sizeof(w)-1) typedef struct { wtk_string_t *wrd; int nphn; wtk_strpool_xitem_t **phns; }wtk_phndict_wrd_t; struct wtk_phndict { wtk_str_hash_t* hash; wtk_strpool_t* pool; int nphn; }; wtk_phndict_t* wtk_phndict_new(char *fn); void wtk_phndict_delete(wtk_phndict_t *phn); wtk_phndict_wrd_t* wtk_phndict_find(wtk_phndict_t *dict,char *wrd,int bytes); void wtk_phndict_wrd_print(wtk_phndict_wrd_t *wrd); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/b3/b3da9eb81af3c56fac7780d58bf7856bbce88292.svn-base #ifndef WTK_LEX_WRDVEC_WTK_CLSVEC #define WTK_LEX_WRDVEC_WTK_CLSVEC #include "wtk/core/wtk_type.h" #include "wtk/core/math/wtk_mat.h" #include "wtk/core/cfg/wtk_source.h" #include "wtk/core/wtk_heap.h" #include "wtk/core/wtk_os.h" #include "wtk_clsvec_cfg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_clsvec wtk_clsvec_t; typedef struct { wtk_queue_node_t q_n; wtk_vecf_t *v; wtk_string_t *str; }wtk_clsvec_item_t; typedef struct { wtk_queue_node_t q_n; wtk_queue_t item_q; wtk_vecf_t *v; double sse; }wtk_clsvec_cls_item_t; struct wtk_clsvec { wtk_clsvec_cfg_t *cfg; wtk_string_t **idx_name; wtk_heap_t *glb_heap; wtk_heap_t *heap; wtk_queue_t cls_q; wtk_queue_t item_q; wtk_queue_t output_q; int vsize; float sse_thresh; }; wtk_clsvec_t* wtk_clsvec_new(wtk_clsvec_cfg_t *cfg); void wtk_clsvec_delete(wtk_clsvec_t *v); void wtk_clsvec_process(wtk_clsvec_t *v,char *fn); void wtk_clsvec_print(wtk_clsvec_t *v); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/76/76e3ef88b2fccaae17b243372b144c8abc5012fd.svn-base #ifndef WTK_CORE_WTK_STRMSG_H_ #define WTK_CORE_WTK_STRMSG_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_strbuf.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_strmsg wtk_strmsg_t; typedef enum { WTK_STRMSG_INIT, WTK_STRMSG_MAGIC0, WTK_STRMSG_MAGIC1, WTK_STRMSG_MAGIC2, WTK_STRMSG_MAGIC3, WTK_STRMSG_LEN0, WTK_STRMSG_LEN1, WTK_STRMSG_LEN2, //WTK_STRMSG_LEN3, WTK_STRMSG_VALUE, WTK_STRMSG_END, }wtk_strmsg_state_t; struct wtk_strmsg { wtk_strmsg_state_t state; wtk_strbuf_t *buf; int len; unsigned seek:1; }; void wtk_strmsg_init(wtk_strmsg_t *msg,wtk_strbuf_t *buf,int seek); int wtk_strmsg_feed(wtk_strmsg_t *msg,char *data,int bytes,int *left); int wtk_strmsg_is_filled(wtk_strmsg_t *msg); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/07/072e76a69555399c3f13f9990b4085a9a2049b83.svn-base #ifndef WTK_CORE_WTK_JSON_H_ #define WTK_CORE_WTK_JSON_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_queue.h" #include "wtk/core/wtk_array.h" #include "wtk/core/wtk_heap.h" #include "wtk/core/wtk_strbuf.h" #include "wtk/core/parse/wtk_str_parse.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_json wtk_json_t; typedef struct wtk_json_item wtk_json_item_t; //typedef struct wtk_json_parser wtk_json_parser_t; #define wtk_json_obj_add_ref_str_s(json,item,k,v) wtk_json_obj_add_ref_str(json,item,k,sizeof(k)-1,v) #define wtk_json_obj_add_str_s(json,item,k,v) wtk_json_obj_add_str(json,item,k,sizeof(k)-1,v) #define wtk_json_obj_add_ref_number_s(json,item,k,number) wtk_json_obj_add_ref_number(json,item,k,sizeof(k)-1,number) #define wtk_json_obj_add_item2_s(json,obj,k,item) wtk_json_obj_add_item2(json,obj,k,sizeof(k)-1,item) #define wtk_json_obj_get_s(obj,k) wtk_json_obj_get(obj,k,sizeof(k)-1) #define wtk_json_obj_add_str2_s(json,obj,k,v,v_len) wtk_json_obj_add_str2(json,obj,k,sizeof(k)-1,v,v_len) #define wtk_json_obj_add_str2_ss(json,obj,k,v) wtk_json_obj_add_str2(json,obj,k,sizeof(k)-1,v,sizeof(v)-1) #define wtk_json_array_add_str_s(json,a,s) wtk_json_array_add_str(json,a,s,sizeof(s)-1) #define wtk_json_obj_remove_s(i,k) wtk_json_obj_remove(i,k,sizeof(k)-1) #define wtk_json_item_set_path_str_s(j,s,v,v_len) wtk_json_item_set_path_str(j,s,sizeof(s)-1,v,v_len) #define wtk_json_item_get_path_string_s(item,k) wtk_json_item_get_path_string(item,k,sizeof(k)-1) typedef enum { WTK_JSON_FALSE, WTK_JSON_TRUE, WTK_JSON_NULL, WTK_JSON_STRING, WTK_JSON_NUMBER, WTK_JSON_ARRAY, WTK_JSON_OBJECT, }wtk_json_item_type_t; typedef struct { wtk_queue_node_t q_n; wtk_string_t k; wtk_json_item_t *item; }wtk_json_obj_item_t; typedef struct { wtk_queue_node_t q_n; wtk_json_item_t *item; }wtk_json_array_item_t; struct wtk_json_item { wtk_json_item_type_t type; union{ double number; wtk_string_t *str; wtk_queue_t *array; //wtk_json_array_item_t wtk_queue_t *object; //wtk_json_obj_item_t }v; }; struct wtk_json { wtk_heap_t *heap; wtk_json_item_t *main; }; wtk_json_t* wtk_json_new(); void wtk_json_delete(wtk_json_t *json); void wtk_json_reset(wtk_json_t *json); wtk_json_item_t* wtk_json_new_item2(wtk_heap_t *heap,wtk_json_item_type_t type); wtk_json_item_t* wtk_json_new_number2(wtk_heap_t *heap,double v); wtk_json_item_t* wtk_json_new_string2(wtk_heap_t *heap,char *data,int len); wtk_json_item_t* wtk_json_new_array2(wtk_heap_t *heap); wtk_json_item_t* wtk_json_new_object2(wtk_heap_t *heap); wtk_json_item_t* wtk_json_new_item(wtk_json_t *json,wtk_json_item_type_t type); wtk_json_item_t* wtk_json_new_number(wtk_json_t *json,double v); wtk_json_item_t* wtk_json_new_string(wtk_json_t *json,char *data,int len); wtk_json_item_t* wtk_json_new_array(wtk_json_t *json); wtk_json_item_t* wtk_json_new_object(wtk_json_t *json); wtk_json_item_t* wtk_json_obj_get(wtk_json_item_t *obj,char *key,int key_bytes); wtk_json_item_t* wtk_json_obj_get_first(wtk_json_item_t *obj); wtk_json_obj_item_t* wtk_json_new_obj_item(wtk_json_t *json,char *key,int key_bytes,wtk_json_item_t *item); void wtk_json_obj_add_item(wtk_json_t *json,wtk_json_item_t *obj,wtk_json_obj_item_t *item); void wtk_json_obj_add_item2(wtk_json_t *json,wtk_json_item_t *obj,char *key,int key_bytes,wtk_json_item_t *item); void wtk_json_obj_set_last_item_value(wtk_json_t *json,wtk_json_item_t *obj,wtk_json_item_t *item); wtk_json_item_t* wtk_json_obj_add_ref_str(wtk_json_t *json,wtk_json_item_t *obj,char *key,int key_len,wtk_string_t *v); wtk_json_item_t* wtk_json_obj_add_str(wtk_json_t *json,wtk_json_item_t *obj,char *key,int key_len,wtk_string_t *v); wtk_json_item_t* wtk_json_obj_add_str2(wtk_json_t *json,wtk_json_item_t *obj,char *key,int key_len,char *v,int v_len); wtk_json_item_t* wtk_json_obj_add_ref_number(wtk_json_t *json,wtk_json_item_t *obj,char *key,int key_len,double number); wtk_json_item_t* wtk_json_obj_remove(wtk_json_item_t *item,char *k,int k_len); wtk_json_obj_item_t* wtk_json_obj_get_valid_item(wtk_json_item_t *item); void wtk_json_array_add_item(wtk_json_t *json,wtk_json_item_t *array,wtk_json_item_t *item); void wtk_json_array_add_item2(wtk_json_t *json,wtk_json_item_t *array,wtk_json_item_t *item,int push_front); wtk_json_item_t* wtk_json_array_add_ref_str(wtk_json_t *json,wtk_json_item_t *array,wtk_string_t *v); wtk_json_item_t* wtk_json_array_add_str(wtk_json_t *json,wtk_json_item_t *array,char *data,int bytes); void wtk_json_array_add_ref_number(wtk_json_t *json,wtk_json_item_t *array,double v); wtk_json_item_t* wtk_json_array_get(wtk_json_item_t* item,int idx); int wtk_json_array_has_string_value(wtk_json_item_t *item,char *v,int v_bytes); void wtk_json_array_add_unq_str(wtk_json_t* json,wtk_json_item_t *item,char *v,int v_bytes); void wtk_json_array_remove_string_value(wtk_json_item_t *item,char *v,int v_bytes); //--------------------------------------------- void wtk_json_print(wtk_json_t *json,wtk_strbuf_t *buf); void wtk_json_item_print(wtk_json_item_t *item,wtk_strbuf_t *buf); void wtk_json_item_print2(wtk_json_item_t *item,wtk_strbuf_t *buf); void wtk_json_item_print3(wtk_json_item_t *item); void wtk_json_item_print4(wtk_json_item_t *item); wtk_json_item_t* wtk_json_item_dup(wtk_json_item_t *item,wtk_heap_t *heap); int wtk_json_copy_obj_dict(wtk_json_t *json,wtk_json_item_t *dst,wtk_json_item_t *src); int wtk_json_item_cmp(wtk_json_item_t *src,wtk_json_item_t *dst); /** * return string is ref; */ wtk_string_t* wtk_json_item_get_str_value(wtk_json_item_t *item); /** * returned string must deleted */ wtk_string_t* wtk_json_item_get_str_value2(wtk_json_item_t *item); /** *[pvt.喜欢吃.菜系]=[湘菜] */ int wtk_json_item_set_path_str(wtk_json_t *json,char *k,int k_len,char *v,int v_len); wtk_json_item_t* wtk_json_item_get_path_item(wtk_json_item_t *item,char *k,int k_len,wtk_string_t *last_k); wtk_json_item_t* wtk_json_item_add_path_item(wtk_json_t *json,wtk_json_item_t *item,char *k,int k_len,wtk_json_item_type_t type); wtk_string_t* wtk_json_item_get_path_string(wtk_json_item_t *item,char *k,int k_len); int wtk_json_item_len(wtk_json_item_t *item); wtk_json_item_t* wtk_json_array_get_string_value(wtk_json_item_t *item,char *v,int v_bytes); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/a8/a8de50ee7b98e7a4fe9c7e3c87bdb8bab47f318a.svn-base #include "wtk_qstft_cfg.h" int wtk_qstft_cfg_init(wtk_qstft_cfg_t *cfg) { cfg->lt=1; cfg->lf=7; return 0; } int wtk_qstft_cfg_clean(wtk_qstft_cfg_t *cfg) { return 0; } int wtk_qstft_cfg_update_local(wtk_qstft_cfg_t *cfg,wtk_local_cfg_t *lc) { wtk_string_t *v; wtk_local_cfg_update_cfg_i(lc,cfg,lt,v); wtk_local_cfg_update_cfg_i(lc,cfg,lf,v); return 0; } int wtk_qstft_cfg_update(wtk_qstft_cfg_t *cfg) { return 0; } <file_sep>/core/strlike/wtk_strlike_cfg.h #ifndef WTK_FST_STRLIKE_WTK_STRLIKE_CFG_H_ #define WTK_FST_STRLIKE_WTK_STRLIKE_CFG_H_ #include "wtk/core/cfg/wtk_local_cfg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_strlike_cfg wtk_strlike_cfg_t; struct wtk_strlike_cfg { wtk_str_hash_t *en_filter; wtk_str_hash_t *cn_filter; wtk_str_hash_t *sp_filter;//空格 float cost_del; float cost_ins; float cost_sub; unsigned int use_eq_len:1; unsigned int use_char:1; }; int wtk_strlike_cfg_init(wtk_strlike_cfg_t *cfg); int wtk_strlike_cfg_clean(wtk_strlike_cfg_t *cfg); int wtk_strlike_cfg_update_local(wtk_strlike_cfg_t *cfg,wtk_local_cfg_t *lc); int wtk_strlike_cfg_update(wtk_strlike_cfg_t *cfg); int wtk_strlike_cfg_is_en(wtk_strlike_cfg_t *cfg,char *data,int bytes); int wtk_strlike_cfg_is_cn(wtk_strlike_cfg_t *cfg,char *data,int bytes); int wtk_strlike_cfg_is_sp(wtk_strlike_cfg_t *cfg,char *data,int bytes); #ifdef __cplusplus }; #endif #endif <file_sep>/core/segmenter/wtk_chnpos.c #include "wtk_chnpos.h" #include <ctype.h> wtk_chnpos_t* wtk_chnpos_new(wtk_chnpos_cfg_t *cfg) { wtk_chnpos_t *pos; pos=(wtk_chnpos_t*)wtk_malloc(sizeof(wtk_chnpos_t)); pos->cfg=cfg; pos->heap=wtk_heap_new(4096); if(cfg->use_prune) { pos->prune=wtk_prune_new(&(cfg->prune)); }else { pos->prune=NULL; } //wtk_debug("prune=%p\n",pos->prune); //exit(0); wtk_chnpos_reset(pos); return pos; } void wtk_chnpos_delete(wtk_chnpos_t *pos) { if(pos->prune) { wtk_prune_delete(pos->prune); } wtk_heap_delete(pos->heap); wtk_free(pos); } void wtk_chnpos_reset(wtk_chnpos_t *pos) { if(pos->prune) { wtk_prune_reset(pos->prune); } wtk_heap_reset(pos->heap); pos->frame=0; pos->max_inst=NULL; wtk_queue_init(&(pos->inst_q)); } wtk_chnpos_inst_t* wtk_chnpos_new_inst(wtk_chnpos_t *pos,wtk_chnpos_state_t *state) { wtk_heap_t *heap=pos->heap; wtk_chnpos_inst_t *inst; inst=(wtk_chnpos_inst_t*)wtk_heap_malloc(heap,sizeof(wtk_chnpos_inst_t)); inst->state=state; inst->pth=NULL; //wtk_queue_push(&(pos->inst_q),&(inst->q_n)); return inst; } wtk_chnpos_pth_t* wtk_chnpos_new_pth(wtk_chnpos_t *pos,wtk_string_t *v,int vpos) { wtk_heap_t *heap=pos->heap; wtk_chnpos_pth_t *pth; //wtk_debug("vpos=%d\n",vpos); pth=(wtk_chnpos_pth_t*)wtk_heap_malloc(heap,sizeof(wtk_chnpos_pth_t)); pth->prev=NULL; pth->v=wtk_heap_dup_string(heap,v->data,v->len); pth->pos=vpos; return pth; } void wtk_chnpos_init_network(wtk_chnpos_t *pos,wtk_string_t *obs) { wtk_chnpos_wrd_t wrd; wtk_chnpos_inst_t *inst; int i; float f; wrd=wtk_chnpos_model_get_wrd2(pos->cfg->model,obs->data,obs->len); //wtk_debug("n=%d\n",n); //pth=wtk_chnpos_new_pth(pos,obs); for(i=0;i<wrd.nstate;++i) { f=wrd.states[i]->start+wtk_chnpos_state_get_emit_prob(wrd.states[i],obs); if(f<-1e10) { continue; } inst=wtk_chnpos_new_inst(pos,wrd.states[i]); inst->like=f; inst->pth=wtk_chnpos_new_pth(pos,obs,wrd.states[i]->pos); if(!pos->max_inst || inst->like>pos->max_inst->like) { pos->max_inst=inst; } //wtk_chnpos_state_print(pos->cfg->model,wrd.states[i]); //wtk_debug("inst->like=%f/%f/%f\n",wrd.states[i]->start,inst->like,wtk_chnpos_state_get_emit_prob(wrd.states[i],obs)); wtk_queue_push(&(pos->inst_q),&(inst->q_n)); } //wtk_debug("inst_q=%d\n",pos->inst_q.length); //exit(0); // if(pos->inst_q.length==0) // { // inst=wtk_chnpos_new_inst(pos,NULL); // inst->like=f; // inst->pth=wtk_chnpos_new_pth(pos,obs,-1); // wtk_queue_push(&(pos->inst_q),&(inst->q_n)); // } } int wtk_chnpos_has_path(wtk_queue_t *q,wtk_chnpos_pth_t *pth,int pos) { wtk_queue_node_t *qn; wtk_chnpos_inst_t *inst; for(qn=q->push;qn;qn=qn->prev) { inst=data_offset2(qn,wtk_chnpos_inst_t,q_n); if(inst->pth->prev==pth) { if(inst->pth->pos==pos) { return 1; } }else { break; } } return 0; } void wtk_chnpos_feed(wtk_chnpos_t *pos,wtk_string_t *obs) { wtk_prune_t *prune=pos->prune; wtk_queue_node_t *qn; wtk_chnpos_inst_t *inst,*inst2; wtk_chnpos_wrd_t wrd; wtk_chnpos_arc_t *arc; wtk_queue_t q; int nprev; int nsub; int i; int b; float last_max; float f; if(pos->max_inst) { last_max=pos->max_inst->like; }else { last_max=0; } //wtk_debug("[%.*s] pos=%d prune=%p\n",obs->len,obs->data,pos->inst_q.length,pos->prune); // if(pos->cfg->use_prune && pos->inst_q.length>pos->cfg->prune.count) // { // if(pos->max_inst) // { // last_max=pos->max_inst->like; // wtk_debug("last_max=%f\n",last_max); // if(last_max<-1e5) // { // prune=NULL; // } // }else // { // last_max=0; // } // }else // { // last_max=0; // prune=NULL; // } pos->max_inst=NULL; obs=wtk_heap_dup_string(pos->heap,obs->data,obs->len); //wtk_debug("[%.*s] len=%d\n",obs->len,obs->data,pos->inst_q.length); ++pos->frame; if(pos->frame==1) { wtk_chnpos_init_network(pos,obs); return; } //wtk_debug("len=%d\n",pos->inst_q.length); wtk_queue_init(&(q)); nprev=0; nsub=0; //wtk_debug("last_max=%f\n",last_max); wrd=wtk_chnpos_model_get_wrd2(pos->cfg->model,obs->data,obs->len); for(qn=pos->inst_q.pop;qn;qn=qn->next) { inst=data_offset2(qn,wtk_chnpos_inst_t,q_n); if(inst->state->narc==0) { continue; } nprev+=inst->state->narc; //wtk_debug("state=%p/%p narc=%d pos=%d\n",inst->state,arc->to,inst->state->narc,pos->inst_q.length); for(i=0;i<inst->state->narc;++i) { arc=inst->state->arcs+i; b=wtk_chnpos_wrd_has_state(&wrd,arc->to); if(b) { // if(inst->pth) // { // b=wtk_chnpos_has_path(&(q),inst->pth,arc->to->pos); // if(b) // { // continue; // } // } f=wtk_chnpos_state_get_emit_prob(arc->to,obs); f=inst->like+arc->prob+f; if(prune && f-last_max<prune->cfg->min_score) { continue; } ++nsub; inst2=wtk_chnpos_new_inst(pos,arc->to); inst2->like=f; //wtk_debug("%f %f/%f/%f last=%f\n",inst2->like,inst->like,arc->prob,f,last_max); if(prune)// && inst2->like>-1e5) { wtk_prune_add(prune,inst2->like-last_max); } inst2->pth=wtk_chnpos_new_pth(pos,obs,arc->to->pos); inst2->pth->prev=inst->pth; if(!pos->max_inst || inst2->like>pos->max_inst->like) { //wtk_debug("like=%f/%f/%f/%f\n",inst->like,inst2->like-inst->like,inst2->like,pos->max_inst?pos->max_inst->like:0); //wtk_chnpos_state_print(pos->cfg->model,arc->to); pos->max_inst=inst2; } wtk_queue_push(&(q),&(inst2->q_n)); //wtk_chnpos_state_print(pos->cfg->model,arc->to); //wtk_debug("[%d]\n",q.length); } } } //wtk_debug("nsub=%d\n",nsub); //wtk_debug("len=%d like=%f\n",q.length,pos->max_inst->like); //wtk_debug("len=%d like=%f %.*s\n",q.length,pos->max_inst?pos->max_inst->like:0,obs->len,obs->data); if(nsub==0) { if(nprev==0) { wtk_chnpos_state_t **states; int n; states=(wtk_chnpos_state_t**)(pos->cfg->model->state_robin->r); n=pos->cfg->model->state_robin->nslot; for(qn=pos->inst_q.pop;qn;qn=qn->next) { inst=data_offset2(qn,wtk_chnpos_inst_t,q_n); for(i=0;i<n;++i) { inst2=wtk_chnpos_new_inst(pos,states[i]); inst2->like=inst->like+MIN_FLOAT+wtk_chnpos_state_get_emit_prob(states[i],obs); inst2->pth=wtk_chnpos_new_pth(pos,obs,states[i]->pos); inst2->pth->prev=inst->pth; if(!pos->max_inst || inst2->like>pos->max_inst->like) { pos->max_inst=inst2; } //wtk_debug("inst2_like=%f\n",inst2->like); wtk_queue_push(&(q),&(inst2->q_n)); } } }else { for(qn=pos->inst_q.pop;qn;qn=qn->next) { inst=data_offset2(qn,wtk_chnpos_inst_t,q_n); if(inst->state->narc==0) { continue; } for(i=0;i<inst->state->narc;++i) { arc=inst->state->arcs+i; f=inst->like+arc->prob+wtk_chnpos_state_get_emit_prob(arc->to,obs); if(pos->max_inst && f<pos->max_inst->like-1e5) { continue; } inst2=wtk_chnpos_new_inst(pos,arc->to); inst2->like=f; inst2->pth=wtk_chnpos_new_pth(pos,obs,arc->to->pos); inst2->pth->prev=inst->pth; if(!pos->max_inst || inst2->like>pos->max_inst->like) { pos->max_inst=inst2; } // wtk_debug("inst2_like=%f %f/%f [%.*s]\n",inst2->like,inst->like,arc->prob, // (((wtk_string_t**)pos->cfg->model->pos_a->slot)[arc->to->pos])->len, // (((wtk_string_t**)pos->cfg->model->pos_a->slot)[arc->to->pos])->data); //exit(0); wtk_queue_push(&(q),&(inst2->q_n)); } } } } //wtk_debug("prune=-%p %d/%d\n",prune,prune->count,prune->cfg->count); if(prune) { if(wtk_prune_want_prune(prune)) { wtk_queue_t qx; float f; //float f1; f=wtk_prune_get_thresh(prune); //wtk_debug("prrune thresh=%f\n",f); //f1=f; f+=last_max; wtk_queue_init(&(qx)); while(1) { qn=wtk_queue_pop(&(q)); if(!qn){break;} inst=data_offset2(qn,wtk_chnpos_inst_t,q_n); if(inst->like>f) { //wtk_debug("push[%d/%d] %f/%f\n",qx.length,q.length,inst->like,f); wtk_queue_push(&(qx),qn); } } q=qx; } wtk_prune_reset(prune); } //wtk_debug("len=%d like=%f\n",q.length,pos->max_inst->like); pos->inst_q=q; //wtk_debug("[%.*s] pos=%d\n",obs->len,obs->data,pos->inst_q.length); } void wtk_chnpos_pth_print(wtk_chnpos_t *pos,wtk_chnpos_pth_t *pth) { wtk_string_t *v; if(pth->prev) { wtk_chnpos_pth_print(pos,pth->prev); } //printf("%.*s/%d",pth->v->len,pth->v->data,pth->pos); printf("%.*s",pth->v->len,pth->v->data); v=wtk_chnpos_model_get_pos_str(pos->cfg->model,pth->pos); printf("/%.*s ",v->len,v->data); } void wtk_chnpos_print(wtk_chnpos_t *pos) { printf("like: %f\n",pos->max_inst->like); wtk_chnpos_pth_print(pos,pos->max_inst->pth); printf("\n"); } int wtk_chnpos_parse(wtk_chnpos_t *pos,wtk_string_t **strs,int n) { int i; for(i=0;i<n;++i) { //wtk_debug("v[%d]=[%.*s]\n",i,strs[i]->len,strs[i]->data); wtk_chnpos_feed(pos,strs[i]); if(pos->inst_q.length==0) { return -1; } } //wtk_chnpos_print(pos); return 0; } void wtk_chnpos_test(wtk_chnpos_t *pos,char *data,int bytes) { int init; wtk_string_t k; char *s,*e; int n; s=data; e=s+bytes; init=1; k.data=NULL; while(s<e) { n=wtk_utf8_bytes(*s); if(init==1) { if(n>1 || !isspace(*s)) { k.data=s; init=0; } }else { if(n==1 && isspace(*s)) { k.len=s-k.data; //wtk_debug("%.*s\n",k.len,k.data); wtk_chnpos_feed(pos,&k); k.data=NULL; init=1; } } s+=n; } if(init==0 && k.data) { k.len=e-k.data; //wtk_debug("%.*s\n",k.len,k.data); wtk_chnpos_feed(pos,&k); } wtk_debug("inst=%d %p\n",pos->inst_q.length,pos->max_inst); wtk_chnpos_print(pos); } <file_sep>/os/wtk_socket.c #ifdef WIN32 #else #include <netdb.h> #endif #include "wtk_socket.h" #include "wtk_fd.h" #include "wtk_thread.h" struct addrinfo* wtk_socket_get_addrinfo(char* server,char* port) { struct addrinfo hints,*paddr; paddr=0; memset(&hints,0,sizeof(hints)); hints.ai_flags = AI_CANONNAME; hints.ai_family = AF_INET; hints.ai_socktype=SOCK_STREAM; getaddrinfo(server,port,&hints,&paddr); return paddr; } int wtk_socket_free_addr(struct addrinfo* info) { freeaddrinfo(info); return 0; } wtk_addrinfo_t* wtk_addrinfo_get(char* server,char *port) { wtk_addrinfo_t *wa=0; struct addrinfo* i=0; i=wtk_socket_get_addrinfo(server,port); if(!i){goto end;} wa=(wtk_addrinfo_t*)wtk_malloc(sizeof(*wa)); wa->addrlen=i->ai_addrlen; wa->addr=(struct sockaddr *)wtk_malloc(i->ai_addrlen); memcpy(wa->addr,i->ai_addr,i->ai_addrlen); end: if(i){wtk_socket_free_addr(i);} return wa; } #ifdef WIN32 #else #include <errno.h> wtk_addrinfo_t* wtk_addrinfo_get2(char *server,char *port) { wtk_addrinfo_t *info=0; struct sockaddr_in *addr; struct in_addr *tx; #ifdef __ANDROID__ struct hostent *ent; ent=gethostbyname(server); if(!ent) { perror(__FUNCTION__); wtk_debug("xxxxget host by name[%s:%s] not found ent=%p %s\n",server,port,ent,strerror(errno)); goto end; } tx=(struct in_addr*)(ent->h_addr_list[0]); #else struct hostent host_buf; struct hostent *result; char buf[4096]; int err; int ret; result=0; ret=gethostbyname_r(server,&host_buf,buf,sizeof(buf),&result,&err); if(ret!=0 || !result || result->h_length<=0) { wtk_debug("get host by name[%s:%s] not found\n",server,port); goto end; } tx=(struct in_addr*)(result->h_addr_list[0]); #endif info=(wtk_addrinfo_t*)wtk_malloc(sizeof(wtk_addrinfo_t)); info->addrlen=sizeof(*addr); addr=(struct sockaddr_in*)wtk_calloc(1,info->addrlen); info->addr=(struct sockaddr *)addr; addr->sin_addr=*(tx); addr->sin_port=htons(atoi(port)); addr->sin_family=AF_INET; end: return info; } typedef struct { wtk_thread_t thread; wtk_sem_t sem; char *server; char *port; wtk_addrinfo_t *addrinfo; unsigned end:1; }wtk_socket_route_t; int wtk_socket_route_run(wtk_socket_route_t *route,wtk_thread_t *t) { wtk_sem_t *wait_sem=&(route->sem); pthread_detach(t->handler); route->addrinfo=wtk_addrinfo_get2(route->server,route->port); if(route->end) { wtk_debug("=================================> end = %d.\n",route->end); //wtk_thread_clean(t); if(route->addrinfo){ wtk_addrinfo_delete(route->addrinfo); } wtk_sem_clean(wait_sem); //wtk_free(route); }else { wtk_sem_release(wait_sem,1); } return 0; } wtk_addrinfo_t* wtk_addrinfo_get3(char *server,char *port,int timeout) { wtk_socket_route_t *route; wtk_sem_t *wait_sem; wtk_addrinfo_t *info=0; int ret=-1; //wtk_debug("=======================> get addrinfo3.\n"); route=wtk_malloc(sizeof(wtk_socket_route_t)); route->server=server; route->port=port; route->addrinfo=0; route->end=0; wait_sem=&(route->sem); wtk_sem_init(wait_sem,0); wtk_thread_init(&(route->thread),(thread_route_handler)wtk_socket_route_run,route); wtk_thread_set_name(&(route->thread),"addrinfo2_get"); wtk_thread_start(&(route->thread)); //wtk_debug("=======================> timeout = %d.\n",timeout); ret=wtk_sem_acquire(wait_sem,timeout); //wtk_debug("=======================> ret = %d.\n",ret) if(ret==0) { //wtk_thread_clean(&(route->thread)); //wtk_thread_join(&(route->thread)); info=route->addrinfo; wtk_sem_clean(wait_sem); wtk_free(route); }else { //wtk_debug("=======================> ret = %d.\n",ret) route->end=1; } //wtk_debug("=======================>addrinfo = %p.\n",info); return info; } #endif int wtk_addrinfo_delete(wtk_addrinfo_t *i) { wtk_free(i->addr); wtk_free(i); return 0; } #ifdef WIN32 int wtk_socketpair(int socks[2], int make_overlapped) { union { struct sockaddr_in inaddr; struct sockaddr addr; } a; SOCKET listener; int e; socklen_t addrlen = sizeof(a.inaddr); DWORD flags = (make_overlapped ? WSA_FLAG_OVERLAPPED : 0); int reuse = 1; if (socks == 0) { WSASetLastError(WSAEINVAL); return SOCKET_ERROR; } listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listener == INVALID_SOCKET) return SOCKET_ERROR; memset(&a, 0, sizeof(a)); a.inaddr.sin_family = AF_INET; a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); a.inaddr.sin_port = 0; socks[0] = socks[1] = INVALID_SOCKET; do { if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (char*) &reuse, (socklen_t) sizeof(reuse)) == -1) break; if (bind(listener, &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR) break; if (getsockname(listener, &a.addr, &addrlen) == SOCKET_ERROR) break; if (listen(listener, 1) == SOCKET_ERROR) break; socks[0] = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, flags); if (socks[0] == INVALID_SOCKET) break; if (connect(socks[0], &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR) break; socks[1] = accept(listener, NULL, NULL); if (socks[1] == INVALID_SOCKET) break; closesocket(listener); return 0; } while (0); e = WSAGetLastError(); closesocket(listener); closesocket(socks[0]); closesocket(socks[1]); WSASetLastError(e); return SOCKET_ERROR; } #endif #ifndef WIN32 #include <net/if.h> #include <sys/ioctl.h> char* wtk_get_host_ip(char *iface) { struct in_addr addr; char *name=0; char buf[256]; const char *p; int ret; ret=wtk_get_host_addr(iface,&addr); if(ret!=0){goto end;} p=inet_ntop(AF_INET,&(addr),buf,sizeof(buf)); if(!p){goto end;} name=strdup(p); end: return name; } int wtk_get_host_addr(char *iface,struct in_addr *addr) { struct ifconf ic; struct ifreq *req; char tmp[4096]; int fd,ret; int i,n; ret=-1; ic.ifc_len=sizeof(tmp); ic.ifc_ifcu.ifcu_buf=tmp; fd=socket(AF_INET,SOCK_STREAM,0); if(fd<0){goto end;} ret=ioctl(fd,SIOCGIFCONF,&ic); if(ret!=0){goto end;} n=ic.ifc_len/sizeof(struct ifreq); req=(struct ifreq*)tmp; for(i=0;i<n;++i) { if(strcmp(req[i].ifr_ifrn.ifrn_name,iface)==0) { *addr=((struct sockaddr_in*)&(req[i].ifr_ifru.ifru_addr))->sin_addr; ret=0; break; } } end: return ret; } #endif int wtk_socket_connect(struct sockaddr *ai_addr,socklen_t ai_addrlen,int *pfd) { return wtk_socket_connect3(ai_addr,ai_addrlen,pfd,-1); } void wtk_socket_set_timeout(int fd,int timeout) { struct timeval tv; if(timeout>0) { tv.tv_sec=timeout/1000; tv.tv_usec=(timeout%1000)*1e3; setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv)); setsockopt(fd,SOL_SOCKET,SO_SNDTIMEO,&tv,sizeof(tv)); } } int wtk_socket_connect3(struct sockaddr *ai_addr,socklen_t ai_addrlen,int *pfd,int timeout) { int fd,ret; struct timeval tv; ret=-1; fd=socket(AF_INET,SOCK_STREAM,0); if(fd<0){goto end;} if(timeout>0) { tv.tv_sec=timeout/1000; tv.tv_usec=(timeout%1000)*1e3; setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv)); setsockopt(fd,SOL_SOCKET,SO_SNDTIMEO,&tv,sizeof(tv)); } ret=connect(fd,ai_addr,ai_addrlen); if(ret!=0){goto end;} ret=wtk_fd_set_tcp_client_opt(fd); if(ret!=0){goto end;} *pfd=fd; end: if(ret!=0) { if(fd>0) { #ifdef WIN32 closesocket(fd); #else close(fd); #endif fd=0; } *pfd=INVALID_FD; } return ret; } int wtk_socket_get_addr(char *ip,int port,struct sockaddr_in *addr) { int ret; addr->sin_family=AF_INET; addr->sin_port=htons(port); #ifdef WIN32 ret = inet_addr(ip); if (ret == -1 && strcmp(ip, "255.255.255.255")) { goto end; } addr->sin_addr.S_un.S_addr = ret; #else ret=inet_aton(ip,&(addr->sin_addr)); ret=ret!=0?0:-1; #endif //wtk_debug("ip=%s\n",ip); //print_hex((char*)&(addr->sin_addr),sizeof(addr->sin_addr)); //print_hex((char*)&(addr->sin_port),sizeof(addr->sin_port)); #ifdef WIN32 end: #endif return ret; } int wtk_socket_connect2(char *ip,int port,int *pfd) { struct sockaddr_in addr={0}; int ret; ret=wtk_socket_get_addr(ip,port,&addr); if(ret!=0) { wtk_debug("get addrress failed\n"); goto end; } ret=wtk_socket_connect((struct sockaddr*)&(addr),sizeof(addr),pfd); end: return ret; } int wtk_socket_connect4(char *ip,char *port,int *pfd) { wtk_addrinfo_t* info; int ret=-1; info=wtk_addrinfo_get(ip,port); if(!info) { wtk_debug("get address failed\n"); goto end; } ret=wtk_socket_connect(info->addr,info->addrlen,pfd); end: if(info) { wtk_addrinfo_delete(info); } return ret; } int wtk_socket_close_fd(int fd) { int ret; #ifdef WIN32 ret=closesocket(fd); #else ret=close(fd); #endif return ret; } int wtk_socket_get_port(int fd,int *port) { struct sockaddr_in addr; socklen_t len; int ret; len=sizeof(addr); ret=getsockname(fd,(struct sockaddr*)&addr,&len); if(ret!=0){goto end;} *port=ntohs(addr.sin_port); end: return ret; } void wtk_socket_print(int fd) { #ifndef WIN32 char buf[256]; struct sockaddr_in addr; socklen_t len; int ret; int port; const char *p; len=sizeof(addr); ret=getsockname(fd,(struct sockaddr*)&addr,&len); if(ret!=0){goto end;} port=ntohs(addr.sin_port); p=inet_ntop(AF_INET,(struct sockaddr*)&(addr.sin_addr),buf,sizeof(buf)-1); wtk_debug("local=[%s:%d]\n",p,port); ret=getpeername(fd,(struct sockaddr*)&addr,&len); //wtk_debug("ret=%d\n",ret); if(ret!=0){goto end;} port=ntohs(addr.sin_port); p=inet_ntop(AF_INET,(struct sockaddr*)&(addr.sin_addr),buf,sizeof(buf)-1); wtk_debug("peer=[%s:%d]\n",p,port); end: #endif return; } int wtk_socket_set_reuse(int fd) { int reuse=1; int ret; ret=setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(char*)&reuse,sizeof(reuse)); if(ret!=0) { perror(__FUNCTION__); } return ret; } int wtk_socket_create_udp_fd(int port) { struct sockaddr_in addr={0}; int ret=-1; int fd=-1; fd=socket(AF_INET,SOCK_DGRAM,0); if(fd<0){goto end;} addr.sin_family=AF_INET; if(port<0){port=0;} addr.sin_port=htons(port); addr.sin_addr.s_addr=htonl(INADDR_ANY); ret=bind(fd,(struct sockaddr*)&addr,sizeof(addr)); end: if(ret!=0) { perror(__FUNCTION__); if(fd>0) { #ifdef WIN32 _close(fd); #else close(fd); #endif fd=-1; } } return fd; } int wtk_socket_create_tcp_listen_fd(int port) { struct sockaddr_in addr={0}; int fd; int ret=0; fd=socket(AF_INET,SOCK_STREAM,0); if(fd<0){goto end;} addr.sin_family=AF_INET; addr.sin_port=htons(port); addr.sin_addr.s_addr=htonl(INADDR_ANY); ret=bind(fd,(struct sockaddr*)&addr,sizeof(addr)); if(ret!=0){goto end;} ret=listen(fd,5); end: if(ret!=0) { wtk_socket_close_fd(fd); fd=-1; } return fd; } #ifdef WIN32 #else int wtk_socket_sendto_host(int fd,const char *data,int bytes,char *host,int port) { struct sockaddr_in addr={0}; int ret; addr.sin_family=AF_INET; addr.sin_port=htons(port); #ifdef WIN32 ret=inet_aton(host,&(addr.sin_addr)); #else ret=inet_pton(AF_INET,host,(void *)&(addr.sin_addr)); #endif wtk_debug("ret=%d\n",ret); if(ret!=1){ret=-1;goto end;} ret=wtk_socket_sendto(fd,data,bytes,(struct sockaddr*)&addr,sizeof(addr)); end: return ret; } int wtk_socket_sendto(int fd,const char *data,int bytes,const struct sockaddr* addr,socklen_t len) { int ret; wtk_debug("[\n%.*s\n]\n",bytes,data); ret=sendto(fd,data,bytes,0,addr,len); if(ret==bytes) { ret=0; }else { perror(__FUNCTION__); ret=-1; } return ret; } int wtk_socket_recvfrom(int fd,char *buf,int len,struct sockaddr *addr,socklen_t *addrlen) { int ret; ret=recvfrom(fd,buf,len,0,addr,addrlen); wtk_debug("[\n%.*s\n]\n",ret,buf); return ret; } #endif int wtk_socket_readable(int fd) { fd_set r_set; struct timeval timeout; int ret; timeout.tv_sec=0; timeout.tv_usec=0; FD_ZERO(&(r_set)); FD_SET(fd,&(r_set)); ret=select(fd+1,&(r_set),0,0,&timeout); return ret>0?1:0; } int wtk_socket_send_strmsg(int fd,char *data,int bytes) { wtk_fd_state_t s; int w; int ret=-1; s=wtk_fd_send(fd,(char*)&(bytes),4,&w); if(s!=WTK_OK || w!=4){goto end;} s=wtk_fd_send(fd,data,bytes,&w); if(s!=WTK_OK || w!=bytes){goto end;} ret=0; end: return ret; } int wtk_socket_read_strmsg(int fd,wtk_strbuf_t *buf) { wtk_fd_state_t s; int v; int r; int ret=-1; wtk_strbuf_reset(buf); s=wtk_fd_recv(fd,(char*)&v,4,&r); if(s!=WTK_OK || r!=4){goto end;} //wtk_debug("v=%d\n",v); if(v>10420 || v<=0){goto end;} wtk_strbuf_expand(buf,v); s=wtk_fd_recv(fd,buf->data,v,&r); if(s!=WTK_OK || r!=v){goto end;} buf->pos=v; ret=0; end: return ret; } <file_sep>/os/.svn/pristine/cd/cd70959cc97cfb4f5048c3c7764b2cb7f8dd7778.svn-base #ifndef WTK_OS_TCP_WTK_TCP_LISTEN_CFG #define WTK_OS_TCP_WTK_TCP_LISTEN_CFG #include "wtk/core/cfg/wtk_local_cfg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_tcp_listen_cfg wtk_tcp_listen_cfg_t; struct wtk_tcp_listen_cfg { int port; int backlog; unsigned reuse:1; }; int wtk_tcp_listen_cfg_init(wtk_tcp_listen_cfg_t *cfg); int wtk_tcp_listen_cfg_clean(wtk_tcp_listen_cfg_t *cfg); int wtk_tcp_listen_cfg_update_local(wtk_tcp_listen_cfg_t *cfg,wtk_local_cfg_t *lc); int wtk_tcp_listen_cfg_update(wtk_tcp_listen_cfg_t *cfg); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/9a/9a58f412631eb10fb508928c5a691954e20024c0.svn-base #include "wtk_posdict.h" #include <math.h> wtk_posdict_t* wtk_posdict_new() { wtk_posdict_t *dict; dict=(wtk_posdict_t*)wtk_malloc(sizeof(wtk_posdict_t)); dict->v.map=NULL; dict->use_bin=0; return dict; } void wtk_posdict_delete(wtk_posdict_t *d) { if(d->use_bin) { if(d->v.kv) { wtk_fkv2_delete(d->v.kv); } }else { if(d->v.map) { wtk_str_hash_delete(d->v.map); } } wtk_free(d); } void wtk_posdict_set_kv(wtk_posdict_t *d,char *fn) { d->use_bin=1; d->v.kv=wtk_fkv2_new(fn); } void wtk_posdict_set_kv2(wtk_posdict_t *d,wtk_rbin2_t *rbin,char *fn) { d->use_bin=1; d->v.kv=wtk_fkv2_new2(rbin,fn); //wtk_debug("%s:%p\n",fn,d->v.kv); } wtk_posdict_wrd_t* wtk_posdict_get(wtk_posdict_t *d,char *wrd,int wrd_bytes,int insert) { wtk_posdict_wrd_t *w; wtk_str_hash_t *map; if(d->use_bin) { wtk_fkv_env_t env; int ret; char *s,*e; int n; wtk_fkv_env_init(d->v.kv,&(env)); //wtk_debug("[%.*s]=%p\n",wrd_bytes,wrd,d->v.kv); s=wrd; e=s+wrd_bytes; while(s<e) { n=wtk_utf8_bytes(*s); //wtk_debug("search [%.*s]\n",n,s); ret=wtk_fkv2_get(d->v.kv,&env,s,n); if(ret!=0){return NULL;} //wtk_debug("ret=%d %.*s is_end=%d\n",ret,n,s,env.is_end); s+=n; } if(!env.is_end) { return NULL; } w=&(d->wrd); wtk_string_set(&(w->wrd),wrd,wrd_bytes); memcpy(&(w->freq),env.v.str.data,4); wtk_string_set(&(w->pos),env.v.str.data+4,env.v.str.len-4); //wtk_debug("[%.*s] %f\n",w->pos.len,w->pos.data,w->freq); return w; } map=d->v.map; w=(wtk_posdict_wrd_t*)wtk_str_hash_find(map,wrd,wrd_bytes); if(w || !insert){return w;} w=(wtk_posdict_wrd_t*)wtk_heap_malloc(map->heap,sizeof(wtk_posdict_wrd_t)); w->freq=0; wtk_string_set(&(w->pos),0,0); wtk_heap_fill_string(map->heap,&(w->wrd),wrd,wrd_bytes); wtk_str_hash_add(map,w->wrd.data,w->wrd.len,w); return w; } void wtk_posdict_update_freq(wtk_posdict_t *d,double tot) { wtk_str_hash_it_t it; hash_str_node_t *node; wtk_posdict_wrd_t *wrd; it=wtk_str_hash_iterator(d->v.map); tot=1.0/tot; while(1) { node=wtk_str_hash_it_next(&(it)); if(!node){break;} wrd=(wtk_posdict_wrd_t*)node->value; //wtk_debug("freq=%f\n",wrd->freq); wrd->freq=log(wrd->freq*tot); //wtk_debug("[%.*s]=%f\n",wrd->wrd.len,wrd->wrd.data,wrd->freq); //exit(0); } } int wtk_posdict_load(wtk_posdict_t *d,wtk_source_t *src) { wtk_strbuf_t *buf; wtk_posdict_wrd_t *wrd; float f; int ret; double tot=0; buf=wtk_strbuf_new(256,1); d->v.map=wtk_str_hash_new(40371); while(1) { ret=wtk_source_read_string(src,buf); if(ret!=0){ret=0;break;} wrd=wtk_posdict_get(d,buf->data,buf->pos,1); //wtk_debug("[%.*s]\n",buf->pos,buf->data); ret=wtk_source_read_float(src,&f,1,0); if(ret!=0){goto end;} //wtk_debug("freq=%f\n",f); wrd->freq=f; tot+=f; ret=wtk_source_read_string(src,buf); //wtk_debug("[%.*s]\n",buf->pos,buf->data); if(ret!=0){goto end;} wtk_heap_fill_string(d->v.map->heap,&(wrd->pos),buf->data,buf->pos); //wtk_debug("[%.*s]\n",buf->pos,buf->data); //exit(0); } wtk_posdict_update_freq(d,tot); ret=0; end: //wtk_debug("ret=%d\n",ret); //exit(0); wtk_strbuf_delete(buf); return ret; } <file_sep>/core/cfg/wtk_main_cfg.c #include "wtk_main_cfg.h" wtk_main_cfg_t *wtk_main_cfg_new(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,char *fn) { return wtk_main_cfg_new2(cfg_bytes,init,clean,update_lc,update,fn,1); } wtk_main_cfg_t *wtk_main_cfg_new7(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,wtk_string_t *dir,int update_cfg,char *data,int len) { wtk_main_cfg_t *cfg; void *mc; int ret; cfg=(wtk_main_cfg_t*)wtk_calloc(1,sizeof(*cfg)); cfg->init=init; cfg->clean=clean; cfg->update_lc=update_lc; cfg->update=update; cfg->update2=0; //cfg->update_arg=0; cfg->cfg_bytes=cfg_bytes; mc=cfg->cfg=wtk_calloc(1,cfg_bytes); ret=cfg->init(mc); if(ret!=0) { wtk_debug("init failed.\n"); goto end; } if(data) { cfg->cfile=wtk_cfg_file_new_fn3(dir,data,len,1); if(!cfg->cfile) { ret=-1;goto end; } }else { cfg->cfile=0; } if(update_cfg) { ret=wtk_main_cfg_update_cfg(cfg); } end: if(ret!=0) { wtk_main_cfg_delete(cfg); cfg=0; } return cfg; } wtk_main_cfg_t* wtk_main_cfg_new2(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,char *fn,int update_cfg) { wtk_main_cfg_t *cfg; void *mc; int ret; cfg=(wtk_main_cfg_t*)wtk_calloc(1,sizeof(*cfg)); cfg->init=init; cfg->clean=clean; cfg->update_lc=update_lc; cfg->update=update; cfg->update2=0; //cfg->update_arg=0; cfg->cfg_bytes=cfg_bytes; mc=cfg->cfg=wtk_calloc(1,cfg_bytes); ret=cfg->init(mc); if(ret!=0) { wtk_debug("init failed.\n"); goto end; } if(fn) { cfg->cfile=wtk_cfg_file_new_fn(fn); if(!cfg->cfile) { wtk_debug("%s invalid.\n",fn); ret=-1;goto end; } }else { cfg->cfile=0; } if(update_cfg) { ret=wtk_main_cfg_update_cfg(cfg); } end: if(ret!=0) { wtk_main_cfg_delete(cfg); cfg=0; } return cfg; } wtk_main_cfg_t* wtk_main_cfg_new3(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,char *fn,int argc,char **argv) { wtk_arg_t *arg; wtk_main_cfg_t *cfg; arg=wtk_arg_new(argc,argv); cfg=wtk_main_cfg_new4(cfg_bytes,init,clean,update_lc,update,fn,arg); wtk_arg_delete(arg); return cfg; } wtk_main_cfg_t* wtk_main_cfg_new4(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,char *fn,wtk_arg_t *arg) { return wtk_main_cfg_new5(cfg_bytes,init,clean,update_lc,update,fn,arg,0); } wtk_main_cfg_t* wtk_main_cfg_new5(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,char *fn,wtk_arg_t *arg,char *cfg_section) { return wtk_main_cfg_new6(cfg_bytes,init,clean,update_lc,update,0,fn,arg,cfg_section); } wtk_main_cfg_t* wtk_main_cfg_new6(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update, wtk_main_cfg_update_arg_f update_arg, char *fn,wtk_arg_t *arg,char *cfg_section) { wtk_main_cfg_t *cfg; int ret=0; cfg=wtk_main_cfg_new2(cfg_bytes,init,clean,update_lc,update,fn,0); if(!cfg){goto end;} if(arg) { wtk_local_cfg_update_arg(cfg->cfile->main,arg,1); } ret=wtk_main_cfg_update_cfg2(cfg,cfg_section); if(ret!=0) { wtk_debug("update cfg failed.\n"); goto end; } if(update_arg) { update_arg(cfg->cfg,arg); } end: if(ret!=0) { wtk_main_cfg_delete(cfg); cfg=0; } return cfg; } int wtk_main_cfg_delete(wtk_main_cfg_t *cfg) { if(cfg->cfg) { cfg->clean(cfg->cfg); wtk_free(cfg->cfg); } if(cfg->cfile) { wtk_cfg_file_delete(cfg->cfile); } wtk_free(cfg); return 0; } int wtk_main_cfg_bytes(wtk_main_cfg_t *cfg) { int bytes=cfg->cfg_bytes; if(cfg->cfile) { bytes+=wtk_cfg_file_bytes(cfg->cfile); } return bytes; } void wtk_main_cfg_update(wtk_main_cfg_t *cfg,int argc,char **argv) { wtk_arg_t *arg; arg=wtk_arg_new(argc,argv); wtk_local_cfg_update_arg(cfg->cfile->main,arg,0); wtk_arg_delete(arg); } int wtk_main_cfg_update_cfg_lc(wtk_main_cfg_t *cfg,wtk_local_cfg_t *lc) { int ret; void *mc; mc=cfg->cfg; ret=cfg->update_lc(mc,lc); if(ret!=0) { wtk_local_cfg_print(lc); wtk_debug("update lc failed\n"); goto end; } ret=cfg->update(mc); if(ret!=0) { wtk_local_cfg_print(lc); wtk_debug("update failed\n"); goto end; } end: return ret; } int wtk_main_cfg_update_cfg(wtk_main_cfg_t *cfg) { if(cfg->cfile) { return wtk_main_cfg_update_cfg_lc(cfg,cfg->cfile->main); }else { return 0; } } int wtk_main_cfg_update_cfg2(wtk_main_cfg_t *cfg,char *section) { wtk_local_cfg_t *lc; if(section) { lc=wtk_local_cfg_find_section_lc(cfg->cfile->main,section,strlen(section)); }else { lc=cfg->cfile->main; } return wtk_main_cfg_update_cfg_lc(cfg,lc); } wtk_main_cfg_t *wtk_main_cfg_new_str(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,char *data,int bytes,char *dn) { wtk_main_cfg_t *cfg; void *mc; int ret; cfg=(wtk_main_cfg_t*)wtk_calloc(1,sizeof(*cfg)); cfg->init=init; cfg->clean=clean; cfg->update_lc=update_lc; cfg->update=update; cfg->update2=0; //cfg->update_arg=0; cfg->cfg_bytes=cfg_bytes; mc=cfg->cfg=wtk_calloc(1,cfg_bytes); ret=cfg->init(mc); if(ret!=0) { wtk_debug("init failed.\n"); goto end; } cfg->cfile=wtk_cfg_file_new(); //wtk_cfg_file_add_var_ks(cfg->cfile,"pwd","res",3); wtk_cfg_file_add_var_ks(cfg->cfile,"pwd",dn,strlen(dn)); ret=wtk_cfg_file_feed(cfg->cfile,data,bytes); if(ret!=0) { goto end; } //wtk_local_cfg_print(cfg->cfile->main); if(update_lc) { ret=update_lc(cfg->cfg,cfg->cfile->main); if(ret!=0){goto end;} } if(update) { ret=update(cfg->cfg); if(ret!=0){goto end;} } ret=0; end: if(ret!=0) { wtk_main_cfg_delete(cfg); cfg=0; } return cfg; } <file_sep>/core/.svn/pristine/b2/b2d0a69aa74ad7a9ab6366f9794d04437a751ffe.svn-base #ifndef WTK_FST_REC_WTK_PRUNE_CFG #define WTK_FST_REC_WTK_PRUNE_CFG #include "wtk/core/cfg/wtk_local_cfg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_prune_cfg wtk_prune_cfg_t; struct wtk_prune_cfg { float min_score; float max_score; float bin_width; float beam; int count; }; int wtk_prune_cfg_init(wtk_prune_cfg_t *cfg); int wtk_prune_cfg_clean(wtk_prune_cfg_t *cfg); int wtk_prune_cfg_update_local(wtk_prune_cfg_t *cfg,wtk_local_cfg_t *lc); int wtk_prune_cfg_update(wtk_prune_cfg_t *cfg); #ifdef __cplusplus }; #endif #endif <file_sep>/os/.svn/pristine/ca/ca4782faf42625f680f349df36729a040001ed56.svn-base #ifndef WTK_OS_PS_WTK_PS_H_ #define WTK_OS_PS_WTK_PS_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_str.h" #include "wtk/core/wtk_strmsg.h" #include "wtk_ps_cfg.h" #include "wtk_psys.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_ps wtk_ps_t; struct wtk_ps { wtk_ps_cfg_t *cfg; //wtk_strbuf_t *buf; wtk_psys_t sys; char *tmp; }; wtk_ps_t* wtk_ps_new(wtk_ps_cfg_t *cfg); void wtk_ps_delete(wtk_ps_t *p); /** * @brief end with wtk_string_t *str and NULL */ int wtk_ps_process(wtk_ps_t *p,wtk_strbuf_t *buf,char *cmd,...); //------------------------------------------------------------- int wtk_ps_start(wtk_ps_t *p,char *cmd); void wtk_ps_stop(wtk_ps_t *p); int wtk_ps_restart(wtk_ps_t *p); int wtk_ps_write_arg(wtk_ps_t *p,wtk_string_t *arg); int wtk_ps_write_arg_line(wtk_ps_t *p,wtk_string_t *arg); int wtk_ps_read_result(wtk_ps_t *p,wtk_strbuf_t *buf); /** * @brief read block msg result; */ int wtk_ps_read_result3(wtk_ps_t *p,wtk_strbuf_t *buf); /** * @brief read non-block result */ int wtk_ps_read_result4(wtk_ps_t *p,wtk_strbuf_t *buf,int seek); #ifdef __cplusplus }; #endif #endif <file_sep>/core/param/wtk_module_macro.h #ifndef WTK_CORE_PARAM_WTK_MODULE_MACRO_H_ #define WTK_CORE_PARAM_WTK_MODULE_MACRO_H_ #ifdef __cplusplus extern "C" { #endif #define InitModuleFuncName "init" #define ReleaseModuleFuncName "release" #define CreateEngineFuncName "create_engine" #define DisposeEngineFuncName "dispose_engine" #define CreateHandleFuncName "create_handle" #define DisposeHandleFuncName "dispose_handle" #define CalcFuncName "calc" #define FindFuncName "find" #define GetCalcArgName "get_arg" #define PCM_HEADER_BYTES 44 #ifdef WIN32 #ifndef DLLEXPORT #define DLLEXPORT __declspec( dllexport ) #endif #else #define DLLEXPORT __attribute__ ((visibility("default"))) #endif #ifdef __cplusplus #define DEF_FUNC_MAP() \ static wtk_func_map_t maps[]= \ { \ {InitModuleFuncName,(Pointer)WTK_MODULE_FUNC(init)}, \ {ReleaseModuleFuncName,(Pointer)WTK_MODULE_FUNC(release)}, \ {CreateEngineFuncName,(Pointer)WTK_MODULE_FUNC(create_engine)}, \ {DisposeEngineFuncName,(Pointer)WTK_MODULE_FUNC(dispose_engine)}, \ {CreateHandleFuncName,(Pointer)WTK_MODULE_FUNC(create_handle)}, \ {DisposeHandleFuncName,(Pointer)WTK_MODULE_FUNC(dispose_handle)}, \ {CalcFuncName,(Pointer)WTK_MODULE_FUNC(calc)}, \ {GetCalcArgName,(Pointer)WTK_MODULE_FUNC(get_type)} \ }; \ extern "C" DLLEXPORT Pointer find(char* name) \ { \ Pointer func; \ int i,count; \ func=0; \ if(name) \ { \ count=sizeof(maps)/sizeof(wtk_func_map_t);\ for(i=0;i<count;++i) \ { \ if(strcmp(maps[i].name,name)==0) \ { \ func=maps[i].func; \ break; \ } \ } \ }\ return func;\ } #else #define DEF_FUNC_MAP() \ static wtk_func_map_t maps[]= \ { \ {InitModuleFuncName,(Pointer)WTK_MODULE_FUNC(init)}, \ {ReleaseModuleFuncName,(Pointer)WTK_MODULE_FUNC(release)}, \ {CreateEngineFuncName,(Pointer)WTK_MODULE_FUNC(create_engine)}, \ {DisposeEngineFuncName,(Pointer)WTK_MODULE_FUNC(dispose_engine)}, \ {CreateHandleFuncName,(Pointer)WTK_MODULE_FUNC(create_handle)}, \ {DisposeHandleFuncName,(Pointer)WTK_MODULE_FUNC(dispose_handle)}, \ {CalcFuncName,(Pointer)WTK_MODULE_FUNC(calc)}, \ {GetCalcArgName,(Pointer)WTK_MODULE_FUNC(get_type)} \ }; \ DLLEXPORT Pointer find(char* name) \ { \ Pointer func; \ int i,count; \ func=0; \ if(name) \ { \ count=sizeof(maps)/sizeof(wtk_func_map_t); \ for(i=0;i<count;++i) \ { \ if(strcmp(maps[i].name,name)==0) \ { \ func=maps[i].func; \ break; \ } \ } \ }\ return func;\ } #endif #ifdef __cplusplus }; #endif #endif <file_sep>/core/json/wtk_json_parse.c #include <ctype.h> #include "wtk_json_parse.h" void wtk_json_parser_set_state(wtk_json_parser_t *p,wtk_json_parse_state_t state); int wtk_json_parser_feed(wtk_json_parser_t *p,char c); wtk_json_parser_t* wtk_json_parser_new() { wtk_json_parser_t *p; p=(wtk_json_parser_t*)wtk_malloc(sizeof(wtk_json_parser_t)); p->json=wtk_json_new(); p->heap=wtk_heap_new(4096); p->buf=wtk_strbuf_new(256,1); wtk_json_parser_reset(p); return p; } void wtk_json_parser_delete(wtk_json_parser_t *p) { wtk_heap_delete(p->heap); wtk_strbuf_delete(p->buf); wtk_json_delete(p->json); wtk_free(p); } void wtk_json_parser_reset(wtk_json_parser_t *p) { wtk_queue_init(&(p->stack_q)); wtk_heap_reset(p->heap); p->cur_json=NULL; wtk_json_reset(p->json); wtk_str_parse_init(&(p->str_parse),p->buf); p->cur=0; wtk_queue_init(&(p->stack_q)); wtk_json_parser_set_state(p,WTK_JSON_PARSE_MAIN_WAIT); } void wtk_json_parser_set_state(wtk_json_parser_t *p,wtk_json_parse_state_t state) { p->state=state; p->sub_state=-1; } void wtk_json_parse_push_stack(wtk_json_parser_t *p) { wtk_json_stack_item_t *item; item=(wtk_json_stack_item_t*)wtk_heap_malloc(p->heap,sizeof(wtk_json_stack_item_t)); item->main_state=p->state; item->sub_state=p->sub_state; item->item=p->cur; //wtk_debug("push %d\n",p->state); wtk_queue_push_front(&(p->stack_q),&(item->q_n)); p->cur=NULL; p->value=NULL; } void wtk_json_parse_pop_stack(wtk_json_parser_t *p) { wtk_json_stack_item_t *item; wtk_queue_node_t *n; n=wtk_queue_pop(&(p->stack_q)); item=data_offset(n,wtk_json_stack_item_t,q_n); p->state=item->main_state; p->sub_state=item->sub_state; p->value=p->cur; p->cur=item->item; //wtk_debug("pop %d\n",p->state); } wtk_json_t* wtk_json_parser_get_json(wtk_json_parser_t *p) { return p->cur_json?p->cur_json:p->json; } int wtk_json_parser_feed_main_wait(wtk_json_parser_t *p,char c) { wtk_json_t *json; json=wtk_json_parser_get_json(p); if(c=='[') { p->cur=wtk_json_new_array(json); json->main=p->cur; wtk_json_parser_set_state(p,WTK_JSON_PARSE_ARRAY); }else if(c=='{') { p->cur=wtk_json_new_object(json); json->main=p->cur; wtk_json_parser_set_state(p,WTK_JSON_PARSE_OBJECT); }else if(!isspace(c)) { return -1; } return 0; } int wtk_json_parser_feed_array(wtk_json_parser_t *p,char c) { enum wtk_json_array_state_t { WTK_JSON_ARRAY_WAIT=0, WTK_JSON_ARRAY_VALUE, };//wtk_json_array_state_t; wtk_json_t *json; json=wtk_json_parser_get_json(p); if(p->sub_state==-1) { p->sub_state=WTK_JSON_ARRAY_WAIT; } switch(p->sub_state) { case WTK_JSON_ARRAY_WAIT: if(isspace(c) || c==',') { }else if(c==']') { if(p->stack_q.length>0) { wtk_json_parse_pop_stack(p); } }else { p->sub_state=WTK_JSON_ARRAY_VALUE; wtk_json_parse_push_stack(p); p->state=WTK_JSON_PARSE_WAIT_VALUE; return wtk_json_parser_feed(p,c); } break; case WTK_JSON_ARRAY_VALUE: wtk_json_array_add_item(json,p->cur,p->value); p->sub_state=WTK_JSON_ARRAY_WAIT; return wtk_json_parser_feed(p,c); break; default: wtk_debug("found bug\n"); exit(0); break; } return 0; } int wtk_json_parser_feed_object(wtk_json_parser_t *p,char c) { enum wtk_json_obj_state_t { WTK_JSON_OBJ_WAIT=0, WTK_JSON_KEY, WTK_JSON_WAIT_COLON, WTK_JSON_WAIT_VALUE, }; int ret=0; wtk_strbuf_t *buf=p->buf; wtk_json_t *json; json=wtk_json_parser_get_json(p); if(p->sub_state==-1) { p->sub_state=WTK_JSON_OBJ_WAIT; } //wtk_debug("[%c]\n",c); switch(p->sub_state) { case WTK_JSON_OBJ_WAIT: if(c=='\"') { p->sub_state=WTK_JSON_KEY; wtk_str_parse_init(&(p->str_parse),buf); wtk_strbuf_reset(buf); }else if(c=='}') { if(p->stack_q.length>0) { wtk_json_parse_pop_stack(p); } //wtk_json_item_print(p->cur); }else if(!isspace(c)) { ret=-1; } break; case WTK_JSON_KEY: ret=wtk_str_parse_feed(&(p->str_parse),c); if(ret==-1) { return ret; }else if(ret==1) { wtk_json_obj_add_item2(json,p->cur,p->str_parse.buf->data,p->str_parse.buf->pos,0); //wtk_debug("[%.*s]\n",p->str_parse.buf->pos,p->str_parse.buf->data); p->sub_state=WTK_JSON_WAIT_COLON; } break; case WTK_JSON_WAIT_COLON: if(c==':') { p->sub_state=WTK_JSON_WAIT_VALUE; wtk_json_parse_push_stack(p); p->state=WTK_JSON_PARSE_WAIT_VALUE; } break; case WTK_JSON_WAIT_VALUE: wtk_json_obj_set_last_item_value(json,p->cur,p->value); //wtk_json_item_print(p->cur); /* wtk_json_item_print(p->value); wtk_json_item_print(p->cur); wtk_debug("found value\n"); exit(0); */ p->sub_state=WTK_JSON_OBJ_WAIT; return wtk_json_parser_feed(p,c); break; } return 0; } int wtk_json_parser_feed_value(wtk_json_parser_t *p,char c) { wtk_json_t *json; json=wtk_json_parser_get_json(p); switch(c) { case '\"': wtk_json_parser_set_state(p,WTK_JSON_PARSE_STRING); wtk_str_parse_init(&(p->str_parse),p->buf); break; case '[': p->cur=wtk_json_new_array(json); wtk_json_parser_set_state(p,WTK_JSON_PARSE_ARRAY); break; case '{': p->cur=wtk_json_new_object(json); wtk_json_parser_set_state(p,WTK_JSON_PARSE_OBJECT); break; case 'n': wtk_json_parser_set_state(p,WTK_JSON_PARSE_NULL); break; case 't': wtk_json_parser_set_state(p,WTK_JSON_PARSE_TRUE); break; case 'f': wtk_json_parser_set_state(p,WTK_JSON_PARSE_FALSE); break; default: if(wtk_number_parse_can_parse(c)) { wtk_number_parse_init(&(p->num_parse)); wtk_number_parse_feed(&(p->num_parse),c); wtk_json_parser_set_state(p,WTK_JSON_PARSE_NUMBER); }else if(!isspace(c)) { wtk_debug("un processed[%c]\n",c); exit(0); } break; } return 0; } int wtk_json_parser_feed_string_value(wtk_json_parser_t *p,char c) { wtk_json_t *json; int ret; json=wtk_json_parser_get_json(p); ret=wtk_str_parse_feed(&(p->str_parse),c); if(ret==-1) { return ret; }else if(ret==1) { p->cur=wtk_json_new_string(json,p->str_parse.buf->data,p->str_parse.buf->pos); wtk_json_parse_pop_stack(p); } return 0; } int wtk_json_parser_feed_number_value(wtk_json_parser_t *p,char c) { double v; int ret; wtk_json_t *json; json=wtk_json_parser_get_json(p); ret=wtk_number_parse_feed(&(p->num_parse),c); if(ret==-1) { v=wtk_number_parse_to_value(&(p->num_parse)); //wtk_debug("v=%f\n",v); p->cur=wtk_json_new_number(json,v); wtk_json_parse_pop_stack(p); //wtk_debug("state=%d\n",p->state); return wtk_json_parser_feed(p,c); } return 0; } int wtk_json_parser_feed_null_value(wtk_json_parser_t *p,char c) { enum wtk_json_parser_null_state_t { WTK_JSON_NULL_0, WTK_JSON_NULL_1, WTK_JSON_NULL_2, }; wtk_json_t *json; json=wtk_json_parser_get_json(p); if(p->sub_state==-1) { p->sub_state=WTK_JSON_NULL_0; } switch(p->sub_state) { case WTK_JSON_NULL_0: if(c!='u') { return -1; } p->sub_state=WTK_JSON_NULL_1; break; case WTK_JSON_NULL_1: if(c!='l') { return -1; } p->sub_state=WTK_JSON_NULL_2; break; case WTK_JSON_NULL_2: if(c!='l') { return -1; } p->cur=wtk_json_new_item(json,WTK_JSON_NULL); wtk_json_parse_pop_stack(p); break; } return 0; } int wtk_json_parser_feed_true_value(wtk_json_parser_t *p,char c) { enum wtk_json_parser_true_state_t { WTK_JSON_TRUE_0, WTK_JSON_TRUE_1, WTK_JSON_TRUE_2, WTK_JSON_TRUE_3, }; wtk_json_t *json; json=wtk_json_parser_get_json(p); if(p->sub_state==-1) { p->sub_state=WTK_JSON_TRUE_0; } switch(p->sub_state) { case WTK_JSON_TRUE_0: if(c!='r') { return -1; } p->sub_state=WTK_JSON_TRUE_1; break; case WTK_JSON_TRUE_1: if(c!='u') { return -1; } p->sub_state=WTK_JSON_TRUE_2; break; case WTK_JSON_TRUE_2: if(c!='e') { return -1; } p->cur=wtk_json_new_item(json,WTK_JSON_TRUE); wtk_json_parse_pop_stack(p); break; } return 0; } int wtk_json_parser_feed_false_value(wtk_json_parser_t *p,char c) { enum wtk_json_parser_false_state_t { WTK_JSON_FALSE_0, WTK_JSON_FALSE_1, WTK_JSON_FALSE_2, WTK_JSON_FALSE_3, }; wtk_json_t *json; json=wtk_json_parser_get_json(p); if(p->sub_state==-1) { p->sub_state=WTK_JSON_FALSE_0; } switch(p->sub_state) { case WTK_JSON_FALSE_0: if(c!='a') { return -1; } p->sub_state=WTK_JSON_FALSE_1; break; case WTK_JSON_FALSE_1: if(c!='l') { return -1; } p->sub_state=WTK_JSON_FALSE_2; break; case WTK_JSON_FALSE_2: if(c!='s') { return -1; } p->sub_state=WTK_JSON_FALSE_3; break; case WTK_JSON_FALSE_3: if(c!='e') { return -1; } p->cur=wtk_json_new_item(json,WTK_JSON_FALSE); wtk_json_parse_pop_stack(p); break; } return 0; } int wtk_json_parser_feed(wtk_json_parser_t *p,char c) { int ret; //wtk_debug("[%c:%d]\n",c,p->state); switch(p->state) { case WTK_JSON_PARSE_MAIN_WAIT: ret=wtk_json_parser_feed_main_wait(p,c); break; case WTK_JSON_PARSE_OBJECT: ret=wtk_json_parser_feed_object(p,c); break; case WTK_JSON_PARSE_ARRAY: ret=wtk_json_parser_feed_array(p,c); break; case WTK_JSON_PARSE_WAIT_VALUE: ret=wtk_json_parser_feed_value(p,c); break; case WTK_JSON_PARSE_STRING: ret=wtk_json_parser_feed_string_value(p,c); break; case WTK_JSON_PARSE_NUMBER: ret=wtk_json_parser_feed_number_value(p,c); break; case WTK_JSON_PARSE_NULL: ret=wtk_json_parser_feed_null_value(p,c); break; case WTK_JSON_PARSE_TRUE: ret=wtk_json_parser_feed_true_value(p,c); break; case WTK_JSON_PARSE_FALSE: ret=wtk_json_parser_feed_false_value(p,c); break; default: ret=-1; wtk_debug("not found[state=%d]\n",p->state); exit(0); break; } return ret; } int wtk_json_parser_parse(wtk_json_parser_t *parser,char *data,int len) { return wtk_json_parser_parse2(parser,NULL,data,len); } int wtk_json_parser_parse2(wtk_json_parser_t *parser,wtk_json_t *json,char *data,int len) { int ret; char *p,*e; parser->cur_json=json; p=data;e=data+len; while(p<e) { ret=wtk_json_parser_feed(parser,*p); if(ret!=0) { wtk_debug("process [%c:%d] failed\n",*p,parser->state); wtk_debug("input=[%.*s]\n",len,data); //exit(0); goto end; } ++p; } ret=0; end: //wtk_json_print(parser->json,parser->buf); return ret; } #include "wtk/core/wtk_os.h" int wtk_json_parser_parse_file(wtk_json_parser_t *p,char *fn) { int len; char *data; int ret=-1; data=file_read_buf(fn,&len); if(!data){goto end;} ret=wtk_json_parser_parse(p,data,len); end: if(data) { wtk_free(data); } return ret; } <file_sep>/core/wtk_stridx.c #include "wtk_stridx.h" wtk_stridx_t* wtk_stridx_new(int n) { wtk_stridx_t *si; si=(wtk_stridx_t*)wtk_malloc(sizeof(wtk_stridx_t)); si->items=(wtk_stridx_item_t**)wtk_calloc(n,sizeof(wtk_stridx_item_t*)); si->alloc=n; si->used=0; si->hash=wtk_str_hash_new(n*2+1); return si; } void wtk_stridx_delete(wtk_stridx_t *si) { wtk_str_hash_delete(si->hash); wtk_free(si->items); wtk_free(si); } int wtk_stridx_get_id(wtk_stridx_t *idx,char *data,int bytes,int insert) { wtk_stridx_item_t *item; item=(wtk_stridx_item_t*)wtk_str_hash_find(idx->hash,data,bytes); if(item || insert==0) { goto end; } item=(wtk_stridx_item_t*)wtk_heap_malloc(idx->hash->heap,sizeof(wtk_stridx_item_t)); item->idx=idx->used; idx->items[idx->used]=item; ++idx->used; item->str=wtk_heap_dup_string(idx->hash->heap,data,bytes); wtk_str_hash_add(idx->hash,item->str->data,item->str->len,item); end: return item?item->idx:-1; } wtk_string_t* wtk_stridx_get_str(wtk_stridx_t *idx,int id) { if(id<0 || id>=idx->used) { return NULL; } return idx->items[id]->str; } <file_sep>/os/.svn/pristine/2b/2b6a0a745835127a92600422dc40dc8c56ff03d8.svn-base #ifndef WTK_OS_DAEMON_WTK_DAEMON_CFG_H_ #define WTK_OS_DAEMON_WTK_DAEMON_CFG_H_ #include "wtk/core/cfg/wtk_local_cfg.h" #include "wtk/core/wtk_strbuf.h" #include "wtk/os/wtk_proc.h" #include "wtk/os/wtk_pid.h" #include "wtk/core/wtk_arg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_daemon_cfg wtk_daemon_cfg_t; struct wtk_daemon_cfg { wtk_strbuf_t *fn; wtk_string_t pid_fn; //http.weasel.pid, http is pid_fn,and fn is http.weasel.pid; unsigned daemon:1; unsigned debug:1; unsigned detect_running:1; }; int wtk_daemon_cfg_init(wtk_daemon_cfg_t *cfg); int wtk_daemon_cfg_clean(wtk_daemon_cfg_t *cfg); int wtk_daemon_cfg_update_local(wtk_daemon_cfg_t *cfg,wtk_local_cfg_t *lc); void wtk_daemon_cfg_update_arg(wtk_daemon_cfg_t *cfg,wtk_arg_t *arg); int wtk_daemon_cfg_update(wtk_daemon_cfg_t *cfg); void wtk_daemon_cfg_init_with_main(wtk_daemon_cfg_t *cfg,wtk_local_cfg_t *main); /** * @brief delete daemon process is running or not(use pid file). */ int wtk_daemon_cfg_is_running(wtk_daemon_cfg_t *cfg); /** * @brief check daemon process is running or not. if allow multi-daemon process,generate new pid file. * @return 0 on success else failed. */ int wtk_daemon_cfg_recheck(wtk_daemon_cfg_t *cfg); void wtk_daemon_cfg_print_usage(); #ifdef __cplusplus }; #endif #endif <file_sep>/os/.svn/pristine/3a/3a0128334b5102a30eef5ab15574e21b2af36f49.svn-base #include "wtk_pipequeue.h" #ifdef WIN32 #include <io.h> #include <winsock2.h> #include <windows.h> #include <io.h> #include <ws2tcpip.h> #include "wtk/os/wtk_socket.h" #define close closesocket #else #include <sys/socket.h> #include <sys/types.h> #endif int wtk_pipequeue_init(wtk_pipequeue_t *q) { int ret; memset(q,0,sizeof(wtk_pipequeue_t)); wtk_lockqueue_init((wtk_lockqueue_t*)q); #ifdef WIN32 //ret=_pipe( q->pipe_fd, 0, 0 ); ret=wtk_socketpair(q->pipe_fd,0); #else ret=pipe(q->pipe_fd); //ret=socketpair(AF_INET,SOCK_STREAM,0,q->pipe_fd); #endif if(ret!=0){goto end;} ret=wtk_fd_set_nonblock(q->pipe_fd[0]); end: return ret; } int wtk_pipequeue_clean(wtk_pipequeue_t *q) { wtk_lockqueue_clean((wtk_lockqueue_t*)q); #ifdef WIN32 closesocket(q->pipe_fd[0]); closesocket(q->pipe_fd[1]); #else close(q->pipe_fd[0]); close(q->pipe_fd[1]); #endif return 0; } int wtk_pipequeue_push(wtk_pipequeue_t *q,wtk_queue_node_t *n) { int ret; wtk_lockqueue_push((wtk_lockqueue_t *)q,n); ret=wtk_pipequeue_touch_write(q); return ret? 0 : -1; } int wtk_pipequeue_touch_write(wtk_pipequeue_t* q) { #ifdef WIN32 return send(q->pipe_fd[1],"m",1,0); #else return write(q->pipe_fd[1],"m",1); #endif } int wtk_pipequeue_touch_read(wtk_pipequeue_t* q) { char b; #ifdef WIN32 return recv(q->pipe_fd[0],&b,1,0); #else return read(q->pipe_fd[0],&b,1); #endif } wtk_queue_node_t* wtk_pipequeue_pop(wtk_pipequeue_t *q) { wtk_queue_node_t* n; int ret; n=0; ret=wtk_pipequeue_touch_read(q); if(ret!=1) { //wtk_debug("%d\n",WSAGetLastError ()); //perror(__FUNCTION__); goto end; } n=wtk_lockqueue_pop((wtk_lockqueue_t *)q); end: return n; } <file_sep>/core/.svn/pristine/04/04d3d2fb86a38c8c07631bc2eb298be77a09b9d4.svn-base #include "wtk_vpool.h" void* wtk_vpool_new_item(wtk_vpool_t *v) { switch(v->type) { case WTK_VPOOL_BITHEAP: return wtk_bit_heap_malloc(v->v.bitheap); break; case WTK_VPOOL_HEAP: return wtk_heap_malloc(v->v.heap,v->alloc); break; case WTK_VPOOL_CHEAP: return wtk_malloc(v->alloc); break; } return NULL; } int wtk_vpool_delete_item(wtk_vpool_t *v,void *data) { switch(v->type) { case WTK_VPOOL_BITHEAP: wtk_bit_heap_free(v->v.bitheap,data); break; case WTK_VPOOL_HEAP: break; case WTK_VPOOL_CHEAP: wtk_free(data); break; } return 0; } wtk_vpool_t* wtk_vpool_new(int bytes,int max_free) { return wtk_vpool_new2(bytes,max_free,max_free); } wtk_vpool_t* wtk_vpool_new2(int bytes,int max_free,int reset_free) { //return wtk_vpool_new3(bytes,max_free,reset_free,WTK_VPOOL_HEAP); return wtk_vpool_new3(bytes,max_free,reset_free,WTK_VPOOL_BITHEAP); } wtk_vpool_t* wtk_vpool_new3(int bytes,int max_free,int reset_free,wtk_vpool_type_t type) { return wtk_vpool_new4(bytes,max_free,reset_free,type,128); } wtk_vpool_t* wtk_vpool_new4(int bytes,int max_free,int reset_free,wtk_vpool_type_t type,int max_item) { wtk_vpool_t *v; v=(wtk_vpool_t*)wtk_malloc(sizeof(*v)); v->max=max_item; v->type=type; v->bytes=bytes; v->alloc=bytes+sizeof(wtk_queue_node_t); //v->alloc=wtk_round(bytes+sizeof(wtk_queue_node_t),16); v->reset_free=reset_free; v->cache=wtk_robin_new(1024); if(v->bytes>v->max) { v->type=WTK_VPOOL_CHEAP; wtk_hoard_init2(&(v->hoard),bytes,max_free, (wtk_new_handler_t)wtk_vpool_new_item, (wtk_delete_handler2_t)wtk_vpool_delete_item, v); }else { switch(v->type) { case WTK_VPOOL_BITHEAP: v->v.bitheap=wtk_bit_heap_new(v->alloc,4096/v->alloc,40960,1.0); //计算中删除耗时 /* wtk_hoard_init2(&(v->hoard),bytes,max_free, (wtk_new_handler_t)wtk_vpool_new_item, (wtk_delete_handler2_t)wtk_vpool_delete_item, v); */ break; case WTK_VPOOL_HEAP: v->v.heap=wtk_heap_new(4096); break; case WTK_VPOOL_CHEAP: break; } wtk_hoard_init2(&(v->hoard),bytes,max_free, (wtk_new_handler_t)wtk_vpool_new_item, (wtk_delete_handler2_t)0, v); } return v; } void wtk_vpool_delete(wtk_vpool_t *v) { wtk_robin_delete(v->cache); switch(v->type) { case WTK_VPOOL_BITHEAP: wtk_bit_heap_delete(v->v.bitheap); break; case WTK_VPOOL_HEAP: wtk_heap_delete(v->v.heap); break; case WTK_VPOOL_CHEAP: wtk_hoard_clean(&(v->hoard)); break; } wtk_free(v); } int wtk_vpool_bytes(wtk_vpool_t *v) { int n; switch(v->type) { case WTK_VPOOL_BITHEAP: n=wtk_bit_heap_bytes(v->v.bitheap); break; case WTK_VPOOL_HEAP: n=wtk_heap_bytes(v->v.heap); break; case WTK_VPOOL_CHEAP: n=v->hoard.use_length+v->hoard.cur_free; n*=v->alloc; break; default: n=0; break; } return n; } void wtk_vpool_reset(wtk_vpool_t *v) { int max_free; wtk_robin_reset(v->cache); switch(v->type) { case WTK_VPOOL_BITHEAP: wtk_hoard_reset(&(v->hoard)); wtk_bit_heap_reset(v->v.bitheap); break; case WTK_VPOOL_HEAP: wtk_hoard_reset(&(v->hoard)); wtk_heap_reset(v->v.heap); break; case WTK_VPOOL_CHEAP: max_free=v->hoard.max_free; v->hoard.max_free=v->reset_free; //wtk_debug("max free=%d\n",v->hoard.max_free); wtk_hoard_reuse(&(v->hoard)); v->hoard.max_free=max_free; //wtk_debug("max free=%d cur_free=%d\n",v->hoard.max_free,v->hoard.cur_free); break; } } #ifdef DEUBG_MEM #define DX void* wtk_vpool_pop(wtk_vpool_t *v) { static int ki=0; void *p; p=wtk_malloc(v->bytes); ++ki; #ifndef DX wtk_debug("new[%d] %p\n",ki,p); #endif return p; } void wtk_vpool_push(wtk_vpool_t *v,void *usr_data) { static int ki=0; ++ki; #ifndef DX wtk_debug("delete[%d] %p\n",ki,usr_data); #else if(ki==259038 || ki==277156) { //exit(0); } #endif wtk_free(usr_data); } #else void* wtk_vpool_pop(wtk_vpool_t *v) { void *p; //wtk_debug("cache[%p] %p\n",v,v->cache); if(v->cache->used>0) { p=wtk_robin_pop(v->cache); }else { //p=wtk_vpool_new_item(v); p=wtk_hoard_pop(&(v->hoard)); } return p; } void wtk_vpool_push(wtk_vpool_t *v,void *usr_data) { //wtk_debug("push[%p] %p/%p\n",v,v->cache,usr_data); if(wtk_robin_is_full(v->cache)) { //wtk_vpool_delete_item(v,usr_data); wtk_hoard_push(&(v->hoard),usr_data); }else { wtk_robin_push(v->cache,usr_data); } } #endif <file_sep>/core/wtk_sqlite.c #include "wtk_sqlite.h" #ifdef USE_SQL wtk_sqlite_t* wtk_sqlite_new(char *fn) { wtk_sqlite_t *s; int ret; //wtk_debug("fn=%s\n",fn); s=calloc(1,sizeof(*s)); ret=wtk_sqlite_init(s,fn); if(ret!=0) { wtk_sqlite_delete(s); s=0; } return s; } int wtk_sqlite_delete(wtk_sqlite_t *s) { wtk_sqlite_clean(s); free(s); return 0; } int wtk_sqlite_set_opt(wtk_sqlite_t *s) { //sqlite3 *db=s->db; int ret; ret=wtk_sqlite_exe_s(s,"PRAGMA cache_size =8192;PRAGMA temp_store = MEMORY;"); //wtk_debug("ret=%d\n",ret); return ret; } int wtk_sqlite_init(wtk_sqlite_t *s,char *fn) { int ret; //#define WIN32 #ifdef WIN32 char *p; #endif s->db=0; s->buf=wtk_strbuf_new(4096,1); #ifdef WIN32 fn=p=gbk_to_utf8(fn); #endif ret=sqlite3_open(fn,&(s->db)); if(ret!=SQLITE_OK){ret=-1;goto end;}; //wtk_sqlite_set_opt(s); end: #ifdef WIN32 if(p){wtk_free(p);} #endif return ret; } int wtk_sqlite_clean(wtk_sqlite_t *s) { if(s->db) { sqlite3_close(s->db); } wtk_strbuf_delete(s->buf); return 0; } int wtk_sqlite_select_str1(wtk_sqlite_t* s,char *sql,int sql_len,char *p,int p_len) { sqlite3_stmt* stmt=0; sqlite3* db=s->db; int ret; char *data; int len; ret=sqlite3_prepare(db,sql,sql_len,&stmt,0); if(ret!=SQLITE_OK){ret=-1;goto end;} if(p_len>0) { ret=sqlite3_bind_text(stmt,1,p,p_len,0); if(ret!=SQLITE_OK){ret=-1;goto end;} } ret=sqlite3_step(stmt); if(ret!=SQLITE_ROW){ret=-1;goto end;} len=sqlite3_column_bytes(stmt,0); data=(char*)sqlite3_column_text(stmt,0); wtk_strbuf_reset(s->buf); wtk_strbuf_push(s->buf,data,len); wtk_strbuf_push_c(s->buf,0); ret=0; end: if(stmt) { sqlite3_finalize(stmt); } return ret; } int wtk_sqlite_select_str(wtk_sqlite_t* s,wtk_array_t *a,char *sql,int sql_len) { sqlite3_stmt* stmt=0; sqlite3* db=s->db; wtk_string_t **str; int ret; char *data; int len; wtk_array_reset(a); ret=sqlite3_prepare(db,sql,sql_len,&stmt,0); if(ret!=SQLITE_OK){ret=-1;goto end;} while(1) { ret=sqlite3_step(stmt); //wtk_debug("%d\n",ret); if(ret!=SQLITE_ROW) { break; } len=sqlite3_column_bytes(stmt,0); data=(char*)sqlite3_column_text(stmt,0); str=(wtk_string_t **)wtk_array_push(a); str[0]=wtk_heap_dup_string(a->heap,data,len); //wtk_strbuf_reset(s->buf); //wtk_strbuf_push(s->buf,data,len); } ret=ret==SQLITE_DONE?0:-1; end: if(stmt) { sqlite3_finalize(stmt); } return ret; } int wtk_sqlite_exe(wtk_sqlite_t* s,char *sql,int sql_len) { sqlite3_stmt* stmt=0; sqlite3* db=s->db; int ret; //print_data(sql,sql_len); ret=sqlite3_prepare(db,sql,sql_len,&stmt,0); if(ret!=SQLITE_OK){ret=-1;goto end;} ret=sqlite3_step(stmt); ret=ret==SQLITE_DONE?0:-1; end: if(stmt) { sqlite3_finalize(stmt); } //wtk_sqlite_print(s); return ret; } int wtk_sqlite_exe2(wtk_sqlite_t* s,char *sql,int sql_len,char *p,int p_len) { sqlite3_stmt* stmt=0; sqlite3* db=s->db; int ret; ret=sqlite3_prepare(db,sql,sql_len,&stmt,0); if(ret!=SQLITE_OK){ret=-1;goto end;} ret=sqlite3_bind_text(stmt,1,p,p_len,0); if(ret!=SQLITE_OK){ret=-1;goto end;} ret=sqlite3_step(stmt); ret=ret==SQLITE_DONE?0:-1; end: if(stmt) { sqlite3_finalize(stmt); } return ret; } int wtk_sqlite_exe3(wtk_sqlite_t *s,wtk_string_t *sql,void *ths,wtk_sqlite_add_param_f add_param,wtk_sqlite_notify_value_f notify) { sqlite3_stmt* stmt=0; sqlite3* db=s->db; sqlite3_value *v; int ret; int i,ncol,index; //wtk_debug("%.*s\n",sql->len,sql->data); ret=sqlite3_prepare(db,sql->data,sql->len,&stmt,0); if(ret!=SQLITE_OK) { //wtk_debug("ret=%d\n",ret); wtk_debug("prepare[%.*s],ret=%d failed.\n",sql->len,sql->data,ret); ret=-1;goto end; } if(add_param) { ret=add_param(ths,stmt); if(ret!=0){goto end;} } index=0; while(1) { ret=sqlite3_step(stmt); //wtk_debug("%d\n",ret); if(ret!=SQLITE_ROW) { break; } ncol=sqlite3_column_count(stmt); for(i=0;i<ncol;++i) { v=sqlite3_column_value(stmt,i); if(v && notify) { notify(ths,index,i,v); } } } ret=ret==SQLITE_DONE?0:-1; end: if(stmt) { sqlite3_finalize(stmt); } return ret; } int wtk_sqlite_exe4(wtk_sqlite_t *s,wtk_string_t *sql,void *ths,wtk_sqlite_add_param_f add_param,wtk_sqlite_notify_value2_f notify) { sqlite3_stmt* stmt=0; sqlite3* db=s->db; sqlite3_value *v; int ret; int i,ncol,index; //wtk_debug("%.*s\n",sql->len,sql->data); ret=sqlite3_prepare(db,sql->data,sql->len,&stmt,0); if(ret!=SQLITE_OK) { //wtk_debug("ret=%d\n",ret); wtk_debug("prepare[%.*s],ret=%d failed.\n",sql->len,sql->data,ret); ret=-1;goto end; } if(add_param) { ret=add_param(ths,stmt); if(ret!=0){goto end;} } index=0; while(1) { ret=sqlite3_step(stmt); //wtk_debug("%d/%d\n",ret,SQLITE_ROW); if(ret!=SQLITE_ROW) { break; } ncol=sqlite3_column_count(stmt); for(i=0;i<ncol;++i) { v=sqlite3_column_value(stmt,i); if(v && notify) { if(notify(ths,index,i,v)==0) { ret=0; goto end; } } } } //wtk_debug("ret=%d\n",ret); //wtk_sqlite_print(s); ret=ret==SQLITE_DONE?0:-1; end: if(stmt) { sqlite3_finalize(stmt); } //wtk_debug("ret=%d\n",ret); return ret; } int wtk_sqlite_begin_transaction(wtk_sqlite_t *s,wtk_string_t *sql) { sqlite3* db=s->db; int ret; //wtk_debug("%.*s\n",sql->len,sql->data); s->trans_stmt=0; ret=sqlite3_prepare(db,sql->data,sql->len,&s->trans_stmt,0); if(ret!=SQLITE_OK) { //wtk_debug("ret=%d\n",ret); wtk_debug("prepare[%.*s],ret=%d failed.\n",sql->len,sql->data,ret); ret=-1;goto end; } ret=sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL,0); if(ret!=SQLITE_OK) { //wtk_debug("ret=%d\n",ret); wtk_debug("begine session [%.*s],ret=%d failed.\n",sql->len,sql->data,ret); ret=-1;goto end; } ret=0; end: if(ret!=0 && s->trans_stmt) { sqlite3_finalize(s->trans_stmt); s->trans_stmt=0; } return ret; } int wtk_sqlite_exe_transaction(wtk_sqlite_t *s,void *ths,wtk_sqlite_add_param_f add_param,wtk_sqlite_notify_value2_f notify) { sqlite3_stmt* stmt=s->trans_stmt; sqlite3_value *v; int ret; int i,ncol,index; //wtk_debug("%.*s\n",sql->len,sql->data); if(add_param) { ret=add_param(ths,stmt); if(ret!=0) { wtk_debug("add param failed\n"); goto end; } } index=0; while(1) { ret=sqlite3_step(stmt); //wtk_debug("%d\n",ret); if(ret!=SQLITE_ROW) { break; } ncol=sqlite3_column_count(stmt); for(i=0;i<ncol;++i) { v=sqlite3_column_value(stmt,i); if(v && notify) { if(notify(ths,index,i,v)==0) { ret=0; goto end; } } } } wtk_debug("ret=%d\n",ret); ret=ret==SQLITE_DONE?0:-1; end: sqlite3_clear_bindings(stmt); sqlite3_reset(stmt); wtk_debug("ret=%d\n",ret); return ret; } int wtk_sqlite_end_transaction(wtk_sqlite_t *s) { sqlite3* db=s->db; sqlite3_exec(db, "END TRANSACTION", NULL, NULL,0); if(s->trans_stmt) { sqlite3_finalize(s->trans_stmt); s->trans_stmt=0; } return 0; } //--------------------- example section -------------------- int wtk_sqlite_add_param_test(void *ths,sqlite3_stmt *stmt) { int ret; char *p="hello"; ret=sqlite3_bind_text(stmt,1,p,strlen(p),0); if(ret!=SQLITE_OK){ret=-1;goto end;} end: return ret; } void wtk_sqlite_add_param_notify_test(void *ths,int index,int col,sqlite3_value *v) { int type; char *p; int n; wtk_debug("[%d,%d]\n",index,col); type=sqlite3_value_type(v); wtk_debug("type=%d\n",type); switch(type) { case SQLITE_INTEGER: wtk_debug("%d\n",sqlite3_value_int(v)); break; case SQLITE_FLOAT: wtk_debug("%f\n",sqlite3_value_double(v)); break; case SQLITE_BLOB: p=(char*)sqlite3_value_blob(v); n=sqlite3_value_bytes(v); wtk_debug("[%.*s]\n",n,p); break; case SQLITE_NULL: break; case SQLITE_TEXT: p=(char*)sqlite3_value_text(v); wtk_debug("[%s]=%d\n",p,(int)strlen(p)); break; default: break; } } void wtk_sqlite_print(wtk_sqlite_t *s) { const char *msg; msg=sqlite3_errmsg(s->db); wtk_debug("err: %s\n",msg?msg:"succeed"); } #endif <file_sep>/core/wtk_strv.h #ifndef WTK_CORE_WTK_STRV_H_ #define WTK_CORE_WTK_STRV_H_ #include "wtk/core/wtk_type.h" #include "wtk_str.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_strv wtk_strv_t; #define wtk_strv_s(s,v) {{s,sizeof(s)-1},{(void*)v}} #define wtk_strv_array_find_s(v,v_len,s) wtk_strv_array_find(v,v_len,s,sizeof(s)-1) struct wtk_strv { wtk_string_t key; union { void *v; char *s; int i; }v; //don't use type for when use this,you must known the value is; }; /** * @brief sort array by key, 0<1<2<3 */ void wtk_strv_array_sort(wtk_strv_t* v,int v_len); /** * @brief search by key use binary search, v must be ordered; */ wtk_strv_t* wtk_strv_array_find(wtk_strv_t *v,int v_len,char *key,int key_bytes); /** * @brief search by key, use increase search element 0,1,2,3 ... */ wtk_strv_t* wtk_strv_array_find2(wtk_strv_t *v,int v_len,char *key,int key_bytes); /** * @brief print strv; */ void wtk_strv_print(wtk_strv_t *v); /** * @brief print strv array; */ void wtk_strv_array_print(wtk_strv_t *v,int v_len); /** * @brief example; */ void wtk_strv_array_test(); #ifdef __cplusplus }; #endif #endif <file_sep>/os/wtk_thread.h #ifndef WTK_OS_WTK_THREAD_H_ #define WTK_OS_WTK_THREAD_H_ #include "wtk/core/wtk_type.h" #include "wtk/os/wtk_sem.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_thread wtk_thread_t; typedef int (*thread_route_handler)(void *data,wtk_thread_t *t); typedef enum { THREAD_STATE_INIT, THREAD_STATE_RUN, THREAD_STATE_EXIT, }wtk_thread_state; struct wtk_thread { wtk_sem_t sem; wtk_thread_state state; #ifdef WIN32 HANDLE handler; DWORD ppid; #else pthread_t handler; pid_t ppid; #endif thread_route_handler route; void *data; void *app_data; //used for attach thread data; char *name; }; int wtk_thread_init(wtk_thread_t *t,thread_route_handler route,void *data); int wtk_thread_clean(wtk_thread_t *t); int wtk_thread_start(wtk_thread_t *t); int wtk_thread_join(wtk_thread_t *t); int wtk_thread_kill(wtk_thread_t *t); void wtk_thread_set_name(wtk_thread_t *t,char *name); typedef int(*wtk_thread_route_f)(void *ths); typedef int(*wtk_thread_create_f)(wtk_thread_route_f route,void *ths); void wtk_thread_g_set_glb_create(wtk_thread_create_f cf); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/8f/8f52ca01f3107935b20e0aab2e90c3424c03058d.svn-base #ifndef WTK_CORE_WTK_VPOOL_H_ #define WTK_CORE_WTK_VPOOL_H_ #include "wtk/core/wtk_bit_heap.h" #include "wtk/core/wtk_hoard.h" #include "wtk/core/wtk_heap.h" #include "wtk/core/wtk_robin.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_vpool wtk_vpool_t; typedef enum { WTK_VPOOL_BITHEAP, WTK_VPOOL_HEAP, WTK_VPOOL_CHEAP, }wtk_vpool_type_t; struct wtk_vpool { union { wtk_heap_t *heap; wtk_bit_heap_t *bitheap; }v; wtk_hoard_t hoard; int bytes; int max; int alloc; int reset_free; wtk_vpool_type_t type; wtk_robin_t *cache; }; wtk_vpool_t* wtk_vpool_new(int bytes,int max_free); wtk_vpool_t* wtk_vpool_new2(int bytes,int max_free,int reset_free); wtk_vpool_t* wtk_vpool_new3(int bytes,int max_free,int reset_free,wtk_vpool_type_t type); wtk_vpool_t* wtk_vpool_new4(int bytes,int max_free,int reset_free,wtk_vpool_type_t type,int max_item); int wtk_vpool_bytes(wtk_vpool_t *v); void wtk_vpool_delete(wtk_vpool_t *v); void wtk_vpool_reset(wtk_vpool_t *v); void* wtk_vpool_pop(wtk_vpool_t *v); void wtk_vpool_push(wtk_vpool_t *v,void *usr_data); #ifdef __cplusplus }; #endif #endif <file_sep>/os/wtk_blockqueue.c #include "wtk_blockqueue.h" int wtk_blockqueue_init(wtk_blockqueue_t *q) { int ret; ret=wtk_lockqueue_init((wtk_lockqueue_t*)q); if(ret!=0){goto end;} ret=wtk_sem_init(&(q->sem),0); end: return ret; } int wtk_blockqueue_clean(wtk_blockqueue_t *q) { wtk_lockqueue_clean((wtk_lockqueue_t*)q); wtk_sem_clean(&(q->sem)); return 0; } int wtk_blockqueue_push(wtk_blockqueue_t *q,wtk_queue_node_t *n) { int ret; ret=wtk_lockqueue_push((wtk_lockqueue_t*)q,n); if(ret!=0){goto end;} //wtk_debug("push time,%d\n",q->length); ret=wtk_sem_inc(&(q->sem)); end: return ret; } int wtk_blockqueue_push_front(wtk_blockqueue_t *q,wtk_queue_node_t *n) { int ret; ret=wtk_lockqueue_push_front((wtk_lockqueue_t*)q,n); if(ret!=0){goto end;} //wtk_debug("push time,%d\n",q->length); ret=wtk_sem_inc(&(q->sem)); end: return ret; } wtk_queue_node_t* wtk_blockqueue_pop(wtk_blockqueue_t *q,int ms,int *is_timeout) { wtk_queue_node_t *n; int ret; n=NULL; //wtk_debug("pop time,%d\n",ms); ret=wtk_sem_acquire(&(q->sem),ms); //wtk_debug("pop ret,%d\n",ret); if(ret==0) { n=wtk_lockqueue_pop((wtk_lockqueue_t*)q); } if(is_timeout) { *is_timeout= ret==0 ? 0 :1; } return n; } int wtk_blockqueue_wake(wtk_blockqueue_t *q) { return wtk_sem_inc(&(q->sem)); } <file_sep>/os/.svn/pristine/6b/6b56ee42785eb384265aaeda3cde9f233eeb06be.svn-base #ifndef WTK_CORE_WTK_PIPEQUEUE_H_ #define WTK_CORE_WTK_PIPEQUEUE_H_ #include "wtk/core/wtk_queue.h" #include "wtk/os/wtk_lockqueue.h" #include "wtk/os/wtk_fd.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_pipequeue wtk_pipequeue_t; struct wtk_pipequeue { WTK_LOCK_QUEUE /* * pipe_fd 0 for read, 1 for write;read is non-blocked; * this is used for single sender and single receiver, * it's not safe with multi-sender and multi-receiver for not lock fd; */ int pipe_fd[2]; }; int wtk_pipequeue_init(wtk_pipequeue_t *q); int wtk_pipequeue_clean(wtk_pipequeue_t *q); int wtk_pipequeue_push(wtk_pipequeue_t *q,wtk_queue_node_t *n); wtk_queue_node_t* wtk_pipequeue_pop(wtk_pipequeue_t *q); int wtk_pipequeue_touch_write(wtk_pipequeue_t* q); int wtk_pipequeue_touch_read(wtk_pipequeue_t* q); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/4d/4d9492193909fc27081b2e2d1e8c6c736cf4c67b.svn-base #include "wtk_strdict.h" #include "wtk/core/wtk_larray.h" wtk_strdict_t* wtk_strdict_new(int hash_hint) { wtk_strdict_t *d; d=(wtk_strdict_t*)wtk_malloc(sizeof(wtk_strdict_t)); d->hash=wtk_str_hash_new(hash_hint); return d; } void wtk_strdict_delete(wtk_strdict_t *d) { wtk_str_hash_delete(d->hash); wtk_free(d); } void wtk_strdict_reset(wtk_strdict_t *d) { wtk_str_hash_reset(d->hash); } wtk_strdict_phn_t* wtk_strdict_get(wtk_strdict_t *d,char *k,int k_bytes) { return (wtk_strdict_phn_t*)wtk_str_hash_find(d->hash,k,k_bytes); } int wtk_strdict_load(wtk_strdict_t *d,wtk_source_t *src) { wtk_strbuf_t *buf; wtk_string_t *k,*v; wtk_heap_t *heap; int nl; int ret; wtk_larray_t *a; wtk_strdict_phn_t *phn; int i; //int cnt=0; a=wtk_larray_new(10,sizeof(void*)); buf=wtk_strbuf_new(64,1); heap=d->hash->heap; while(1) { ret=wtk_source_read_string(src,buf); if(ret!=0){ret=0;goto end;} k=wtk_heap_dup_string(heap,buf->data,buf->pos); wtk_larray_reset(a); while(1) { ret=wtk_source_read_string(src,buf); if(ret!=0){goto end;} v=wtk_heap_dup_string(heap,buf->data,buf->pos); wtk_larray_push2(a,&v); //wtk_debug("[%.*s]=[%.*s]\n",k->len,k->data,v->len,v->data); wtk_source_skip_sp(src,&nl); if(nl){break;} } phn=(wtk_strdict_phn_t*)wtk_heap_malloc(heap,sizeof(wtk_strdict_phn_t)); phn->nph=a->nslot; phn->phns=(wtk_string_t**)wtk_heap_malloc(heap,sizeof(wtk_string_t*)*a->nslot); for(i=0;i<phn->nph;++i) { phn->phns[i]=((wtk_string_t**)a->slot)[i]; } //++cnt; wtk_str_hash_add(d->hash,k->data,k->len,phn); } ret=0; end: //wtk_debug("cnt=%d\n",cnt); wtk_larray_delete(a); wtk_strbuf_delete(buf); return ret; } <file_sep>/core/.svn/pristine/93/938b7911ac6e9bcc8776b4ee7b42db5a79d81a2b.svn-base #ifndef WTK_CORE_CFG_WTK_MAIN_CFG_H_ #define WTK_CORE_CFG_WTK_MAIN_CFG_H_ #include "wtk/core/cfg/wtk_cfg_file.h" #include "wtk/core/wtk_arg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_main_cfg wtk_main_cfg_t; typedef int (*wtk_main_cfg_init_f)(void *cfg); typedef int (*wtk_main_cfg_clean_f)(void *cfg); typedef int (*wtk_main_cfg_update_local_f)(void *cfg,wtk_local_cfg_t *lc); typedef int (*wtk_main_cfg_update_f)(void *cfg); typedef int (*wtk_main_cfg_update2_f)(void *cfg,wtk_source_loader_t *sl); typedef void (*wtk_main_cfg_update_arg_f)(void *cfg,wtk_arg_t *arg); #define wtk_main_cfg_new_type(type,fn) wtk_main_cfg_new(sizeof(CAT(type,_t)), \ (wtk_main_cfg_init_f)CAT(type,_init),\ (wtk_main_cfg_clean_f)CAT(type,_clean),\ (wtk_main_cfg_update_local_f)CAT(type,_update_local), \ (wtk_main_cfg_update_f)CAT(type,_update),fn) #define wtk_main_cfg_new_str_type(type,data,bytes,dn) wtk_main_cfg_new_str(sizeof(CAT(type,_t)), \ (wtk_main_cfg_init_f)CAT(type,_init),\ (wtk_main_cfg_clean_f)CAT(type,_clean),\ (wtk_main_cfg_update_local_f)CAT(type,_update_local), \ (wtk_main_cfg_update_f)CAT(type,_update),data,bytes,dn) #define wtk_main_cfg_new_type2(type,fn,arg) wtk_main_cfg_new6(sizeof(CAT(type,_t)), \ (wtk_main_cfg_init_f)CAT(type,_init),\ (wtk_main_cfg_clean_f)CAT(type,_clean),\ (wtk_main_cfg_update_local_f)CAT(type,_update_local), \ (wtk_main_cfg_update_f)CAT(type,_update),\ (wtk_main_cfg_update_arg_f)CAT(type,_update_arg),fn,arg,0) #define wtk_main_cfg_new_type3(type,fn,section) wtk_main_cfg_new6(sizeof(CAT(type,_t)), \ (wtk_main_cfg_init_f)CAT(type,_init),\ (wtk_main_cfg_clean_f)CAT(type,_clean),\ (wtk_main_cfg_update_local_f)CAT(type,_update_local), \ (wtk_main_cfg_update_f)CAT(type,_update),\ (wtk_main_cfg_update_arg_f)0,fn,0,section) #define wtk_main_cfg_new_type4(type,dir,data,len) wtk_main_cfg_new7(sizeof(CAT(type,_t)), \ (wtk_main_cfg_init_f)CAT(type,_init),\ (wtk_main_cfg_clean_f)CAT(type,_clean),\ (wtk_main_cfg_update_local_f)CAT(type,_update_local), \ (wtk_main_cfg_update_f)CAT(type,_update),dir,1,data,len) struct wtk_main_cfg { wtk_cfg_file_t *cfile; void* cfg; //wtk_xxx_cfg_t, which size if cfg_bytes; int cfg_bytes; wtk_main_cfg_init_f init; wtk_main_cfg_clean_f clean; wtk_main_cfg_update_local_f update_lc; wtk_main_cfg_update_f update; wtk_main_cfg_update2_f update2; //wtk_main_cfg_update_arg_f update_arg; }; wtk_main_cfg_t *wtk_main_cfg_new(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,char *fn); /** * @brief create configure, update configure or not by update_cfg; */ wtk_main_cfg_t *wtk_main_cfg_new2(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,char *fn,int update_cfg); /** * @brief update from argc,argv; */ wtk_main_cfg_t* wtk_main_cfg_new3(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,char *fn,int argc,char **argv); /** * @brief update from arg; */ wtk_main_cfg_t *wtk_main_cfg_new4(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,char *fn,wtk_arg_t *arg); /** *@param cfg_section, if cfg_section is "http:nk", update by nk local cfg; */ wtk_main_cfg_t* wtk_main_cfg_new5(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,char *fn,wtk_arg_t *arg,char *cfg_section); wtk_main_cfg_t* wtk_main_cfg_new6(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update, wtk_main_cfg_update_arg_f update_arg, char *fn,wtk_arg_t *arg,char *cfg_section); wtk_main_cfg_t *wtk_main_cfg_new7(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,wtk_string_t *dir,int update_cfg,char *data,int len); int wtk_main_cfg_delete(wtk_main_cfg_t *cfg); void wtk_main_cfg_update(wtk_main_cfg_t *cfg,int argc,char **argv); int wtk_main_cfg_update_cfg(wtk_main_cfg_t *cfg); int wtk_main_cfg_bytes(wtk_main_cfg_t *cfg); /** * @param section,if section is "httpd:nk",update by nk local cfg; */ int wtk_main_cfg_update_cfg2(wtk_main_cfg_t *cfg,char *section); wtk_main_cfg_t *wtk_main_cfg_new_str(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update,char *data,int bytes,char *dn); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/67/67cc7df1f840e771243037d22fa8ffe35706721b.svn-base #ifndef WTK_CORE_GZ_WTK_GZIP #define WTK_CORE_GZ_WTK_GZIP #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_strbuf.h" #include "miniz.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_gzip wtk_gzip_t; typedef struct { int l; uint32_t crc32; }wtk_gzip_st_t; typedef enum { WTK_GZIP_UNZIP_INIT, WTK_GZIP_UNZIP_FLAG_EXTRA, WTK_GZIP_UNZIP_FLAG_EXTRA_SKIP, WTK_GZIP_UNZIP_FLAG_FNAME, WTK_GZIP_UNZIP_FLAG_FCOMMENT, WTK_GZIP_UNZIP_FLAG_FCRC, WTK_GZIP_UNZIP_RUN, }wtk_gzip_unzip_state_t; struct wtk_gzip { wtk_strbuf_t *buf; wtk_gzip_st_t st; z_stream stream; char *cache; int cache_size; uint8_t hdr_flags; int next_bytes; wtk_gzip_unzip_state_t state; }; wtk_gzip_t* wtk_gzip_new(); void wtk_gzip_delete(wtk_gzip_t *zip); void wtk_gzip_zip_start(wtk_gzip_t *zip); void wtk_gzip_zip_write(wtk_gzip_t *zip,char *data,int bytes,int is_end); void wtk_gzip_unzip_start(wtk_gzip_t *zip); int wtk_gzip_unzip_read(wtk_gzip_t *zip,char *data,int bytes,int is_end); #ifdef __cplusplus }; #endif #endif <file_sep>/core/cfg/wtk_opt.c #include "wtk_opt.h" void wtk_opt_print_usage() { printf("\t-c configure file\n"); printf("\t-s input string\n"); printf("\t-i input file\n"); printf("\t-o output file\n"); } void wtk_opt_update_arg(wtk_opt_t *opt) { wtk_arg_t *arg=opt->arg; wtk_arg_get_str_s(arg,"c",&(opt->cfg_fn)); wtk_arg_get_str_s(arg,"s",&(opt->input_s)); wtk_arg_get_str_s(arg,"i",&(opt->input_fn)); wtk_arg_get_str_s(arg,"o",&(opt->output_fn)); } wtk_opt_t* wtk_opt_new(int argc,char **argv,int cfg_bytes, wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean, wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update_f update ) { wtk_opt_t *opt; int ret=-1; opt=(wtk_opt_t*)wtk_malloc(sizeof(wtk_opt_t)); opt->cfg_fn=NULL; opt->input_fn=NULL; opt->output_fn=NULL; opt->input_s=NULL; opt->output_fn=NULL; opt->arg=NULL; opt->main_cfg=NULL; opt->arg=wtk_arg_new(argc,argv); opt->output=NULL; opt->log=NULL; wtk_opt_update_arg(opt); if(opt->cfg_fn) { opt->main_cfg=wtk_main_cfg_new4(cfg_bytes,init,clean,update_lc,update,opt->cfg_fn,opt->arg); if(!opt->main_cfg) { printf("load configure[%s] failed.\n",opt->cfg_fn); goto end; } } if(opt->output_fn && 0) { opt->output=fopen(opt->output_fn,"w"); if(opt->output) { opt->log=opt->output; }else { opt->log=stdout; } }else { opt->log=stdout; } ret=0; end: if(ret!=0) { wtk_opt_delete(opt); opt=NULL; } return opt; } void wtk_opt_delete(wtk_opt_t *opt) { if(opt->output) { fclose(opt->output); } if(opt->main_cfg) { wtk_main_cfg_delete(opt->main_cfg); } if(opt->arg) { wtk_arg_delete(opt->arg); } wtk_free(opt); } <file_sep>/os/wtk_fd.c #include "wtk_fd.h" #include <errno.h> #ifdef WIN32 #include <winsock2.h> #pragma comment(lib,"Ws2_32.lib") #else #include <sys/types.h> #include <sys/socket.h> #endif int fd_read(int fd, char* data, int len, int* readed) { int ret = 0, index = 0, nLeft = len, count; int step; if (!data) { return -1; } while (nLeft > 0) { step=min(4096,nLeft); #ifdef WIN32 count = _read(fd, &data[index], step); #else count = read(fd, &data[index], step); #endif if (count < step) { if ((count<=0) && (errno != EINTR )) { ret = -1; break; } } index += count; nLeft -= count; } if (readed) { *readed = index; } return ret; } int fd_write(int fd, const char* data, int len, int* writed) { int ret = 0, index = 0, nLeft = len; int step; if (!data) { return -1; } while (nLeft > 0) { step=min(4096,nLeft); //step=nLeft; #ifdef WIN32 ret = _write(fd, &data[index],step); #else ret = write(fd, &data[index],step); #endif //wtk_debug("pid=%d,ret=%d,step=%d,nLeft=%d,len=%d\n",getpid(),ret,step,nLeft,len); if (ret < step) { if ((ret<=0) && (errno != EINTR)) { ret = -1; break; } } index += ret; nLeft -= ret; } if (writed) { *writed = index; } return ret; } int wtk_fd_read(int fd,char* buf,int len) { int readed; readed=0; fd_read(fd,buf,len,&readed); return len==readed ? 0 :-1; } int wtk_fd_write(int fd,char* buf,int len) { int writed=0; fd_write(fd,buf,len,&writed); return len==writed ? 0 : -1; } wtk_string_t* wtk_fd_read_string(int fd) { int32_t read_length; wtk_string_t* s; int ret; s=0; read_length=0; ret=wtk_fd_read(fd,(char*)&read_length,sizeof(read_length)); if(ret!=0 || read_length<=0) { perror(__FUNCTION__); #ifndef WIN32 wtk_debug("read length failed(proc=%d,ret=%d,read_length=%d).\n",getpid(),ret,read_length); #endif goto end; } s=wtk_string_new(read_length); ret=wtk_fd_read(fd,s->data,read_length); if(ret!=0) { #ifndef WIN32 wtk_debug("read string failed (%d,%d-%d).\n",ret,read_length,getpid()); #endif wtk_string_delete(s); s=0; } end: return s; } int wtk_fd_write_string(int fd,char* buf,int len) { int32_t length; int ret; length=len; ret=wtk_fd_write(fd,(char*)&length,sizeof(length)); if(ret!=0){goto end;} ret=wtk_fd_write(fd,buf,len); end: return ret; } int wtk_fd_write_stack(int fd,wtk_stack_t *s) { stack_block_t *b; int ret,count,t; int32_t length; length=s->len; ret=wtk_fd_write(fd,(char*)&length,sizeof(length)); if(ret!=0){goto end;} count=0; for(b=s->pop;b;b=b->next) { t=b->push-b->pop; ret=wtk_fd_write(fd,b->pop,t); if(ret!=0){goto end;} count+=t; } ret=count==length?0:-1; end: return ret; } #ifdef WIN32 wtk_fd_state_t wtk_fd_recv(int fd, char* buf, int len, int* readed) { wtk_fd_state_t s; int ret; int no; ret = recv(fd, buf, len, 0); //print_data(buf,ret); if (ret >= 0) { if (readed){*readed = ret;} s=(ret>0) ? WTK_OK : ((errno == EAGAIN || errno==0) ? WTK_OK : WTK_EOF); } else { if (readed){*readed = 0;} #ifdef WIN32 no=WSAGetLastError(); s=(no==WSAEWOULDBLOCK || no==0) ? WTK_AGAIN : WTK_ERR; #else s = (errno == EAGAIN || errno == EINTR || errno==0) ? WTK_AGAIN : ((errno==EPIPE) ? WTK_EOF : WTK_ERR); #endif } return s; } wtk_fd_state_t wtk_fd_send(int fd, char* buf, int len, int* writed) { wtk_fd_state_t s=WTK_OK; int nLeft = len; int idx = 0; int ret; int err; //print_data(buf,len); //wtk_debug("send %d\n",len); while (nLeft > 0) { ret = send(fd, &(buf[idx]), nLeft, 0); if (ret <= 0) { //s = (errno == EAGAIN || errno == EINTR || errno==0) ? WTK_AGAIN : ((errno==EPIPE) ? WTK_EOF : WTK_ERR); err=WSAGetLastError(); s= (err==WSAEWOULDBLOCK) ? WTK_AGAIN : ((err==WSAESHUTDOWN) ? WTK_EOF : WTK_ERR); //wtk_debug("fd=%d,left=%d,again=%d,err=%d\n",fd,nLeft,s==WTK_AGAIN,err); break; } nLeft -= ret; idx += ret; } if(nLeft==0){s=WTK_OK;} if (writed) { *writed = idx; } return s; } wtk_fd_state_t wtk_fd_recv_blk(int fd, char* buf, int len, int* readed) { wtk_fd_state_t s; int ret; ret = recv(fd, buf, len, 0); #ifdef DEBUG_NK print_data(buf,ret); #endif if (ret >= 0) { #ifdef USE_TCP_QUICKACK int flag = 1; setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, &flag, sizeof(int)); #endif if (readed){*readed = ret;} if(ret==0) { wtk_debug("errno=%d %s ret=%d\n",errno,strerror(errno),ret); } s=(ret>0) ? WTK_OK : ( (errno == EAGAIN || errno == 0 || errno==115) ? WTK_OK : WTK_EOF); } else { if (readed){*readed = 0;} s = (errno == EINTR || errno==115) ? WTK_AGAIN : ((errno==EPIPE) ? WTK_EOF : WTK_ERR); } return s; } #else //#define DEBUG_NK wtk_fd_state_t wtk_fd_recv2(int fd, char* buf, int len) { wtk_fd_state_t state; char *s,*e; int read; s=buf;e=s+len; while(s<e) { state=wtk_fd_recv(fd,s,e-s,&read); if(state!=WTK_OK || read<=0){break;} s+=read; } if(s<e) { state=WTK_ERR; } return state; } wtk_fd_state_t wtk_fd_recv(int fd, char* buf, int len, int* readed) { wtk_fd_state_t s; int ret; ret = recv(fd, buf, len, 0); //print_data(buf,ret); //wtk_debug("errno=%d\n",errno); #ifdef DEBUG_NK print_data(buf,ret); #endif if (ret >= 0) { #ifdef USE_TCP_QUICKACK int flag = 1; setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, &flag, sizeof(int)); #endif if (readed){*readed = ret;} s=(ret>0) ? WTK_OK : ( (errno == EAGAIN || errno == 0) ? WTK_OK : WTK_EOF); //s=(ret>0) ? WTK_OK : ( (errno == EAGAIN) ? WTK_OK : WTK_EOF); } else { if (readed){*readed = 0;} s = (errno == EAGAIN || errno == EINTR) ? WTK_AGAIN : ((errno==EPIPE) ? WTK_EOF : WTK_ERR); } return s; } wtk_fd_state_t wtk_fd_recv_blk(int fd, char* buf, int len, int* readed) { wtk_fd_state_t s; int ret; ret = recv(fd, buf, len, 0); //print_data(buf,ret); //wtk_debug("errno=%d\n",errno); #ifdef DEBUG_NK print_data(buf,ret); #endif if (ret >= 0) { #ifdef USE_TCP_QUICKACK int flag = 1; setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, &flag, sizeof(int)); #endif if (readed){*readed = ret;} //change by pfc123 if(ret==0) { wtk_debug("errno=%d %s ret=%d\n",errno,strerror(errno),ret); } s=(ret>0) ? WTK_OK : ( (errno == EAGAIN || errno == 0 || errno==115) ? WTK_OK : WTK_EOF); //s=(ret>0) ? WTK_OK : WTK_EOF; } else { if (readed){*readed = 0;} //wtk_debug("errno=%d %s\n",errno,strerror(errno)); s = (errno == EINTR || errno==115) ? WTK_AGAIN : ((errno==EPIPE) ? WTK_EOF : WTK_ERR); } return s; } wtk_fd_state_t wtk_fd_send(int fd, char* buf, int len, int* writed) { wtk_fd_state_t s=WTK_OK; int nLeft = len; int idx = 0; int ret; //print_data(buf,len); //wtk_debug("%*.*s\n",len,len,buf); #ifdef DEBUG_NK print_data(buf,len); #endif while (nLeft > 0) { ret = send(fd, &(buf[idx]), nLeft, 0); //wtk_debug("ret=%d/%d\n",ret,nLeft); if (ret <= 0) { //wtk_debug("%d,%d\n",ret,errno); s = (errno == EAGAIN || errno == EINTR ||errno==0) ? WTK_AGAIN : ((errno==EPIPE) ? WTK_EOF : WTK_ERR); break; } // if(ret>0) // { // static char hdr[4]={0,}; // static int hdr_pos=0; // static int len=0; // static int is_hdr=1; // static int pos=0; // char *s,*e; // int i; // // if(idx==0) // { // wtk_debug("================= is_hdr=%d pos=%d len=%d\n",is_hdr,pos,len); // } // s=buf+idx; // e=s+ret; // while(s<e) // { // if(is_hdr) // { // hdr[hdr_pos++]=*s; // ++s; // if(hdr_pos==4) // { // len=*(int*)(hdr); // wtk_debug("=======================> len=%d\n",len); // if(len<0) // { // exit(0); // } // is_hdr=0; // pos=0; // } // }else // { // i=min(e-s,len-pos); // pos+=i; // if(pos==len) // { // is_hdr=1; // hdr_pos=0; // } // s+=i; // } // } // // } // if(ret>0) // { // print_hex(buf+idx,ret); // } nLeft -= ret; idx += ret; } if(nLeft==0){s=WTK_OK;} if (writed) { *writed = idx; } //if(s==WTK_EOF){wtk_debug("state=%d,errno=%d\n",s,errno);} return s; } #endif wtk_fd_state_t wtk_fd_write_nonblock(int fd,const char *data,int bytes,int *writed) { wtk_fd_state_t s; int ret; //wtk_debug("%d: [%.*s]\n",getpid(),bytes,data); #ifdef WIN32 ret=_write(fd,data,bytes); #else ret=write(fd,data,bytes); #endif //wtk_debug("%d: fd=%d,write=%d,errno=%d\n",getpid(),fd,ret,errno); if(ret<0) { //perror(__FUNCTION__); //wtk_debug("errno=%d\n",errno); s = (errno == EAGAIN || errno == EINTR ||errno==0) ? WTK_AGAIN : ((errno==EPIPE) ? WTK_EOF : WTK_ERR); }else if(ret==0) { s=WTK_EOF; }else { s=WTK_OK; } if(writed) { *writed=ret>0?ret:0; } //wtk_debug("s=%d\n",s); return s; } wtk_fd_state_t wtk_fd_read_nonblock(int fd,char *data,int bytes,int *readed) { wtk_fd_state_t s; int ret; #ifdef WIN32 ret=_read(fd,data,bytes); #else ret=read(fd,data,bytes); #endif //wtk_debug("%d: fd=%d,ret=%d,errno=%d\n",getpid(),fd,ret,errno); if(ret<0) { s = (errno == EAGAIN || errno == EINTR ||errno==0) ? WTK_AGAIN : ((errno==EPIPE) ? WTK_EOF : WTK_ERR); }else if(ret==0) { s=WTK_EOF; }else { //wtk_debug("%d: [%.*s]\n",getpid(),bytes,data); s=WTK_OK; } if(readed) { *readed=ret>0?ret:0; } return s; } wtk_fd_state_t wtk_fd_flush_send_stack(int fd,wtk_stack_t *s) { wtk_fd_state_t t; stack_block_t *b; int count,writed; int len,ret; t=WTK_OK; for(b=s->pop,count=0;b;b=b->next) { len=b->push - b->pop; if(len<=0){continue;} t=wtk_fd_send(fd,(char*)b->pop,len,&writed); count+=writed; if(t!=WTK_OK){break;} } ret=wtk_stack_pop(s,0,count); if(ret!=0) { t=WTK_ERR; } return t; } #ifdef WIN32 int wtk_fd_set_nonblock(int fd) { u_long iMode = 1; return ioctlsocket(fd,FIONBIO,&iMode); } int wtk_fd_set_block(int fd) { u_long iMode = 0; return ioctlsocket(fd, FIONBIO, &iMode); } #else int wtk_fd_set_nonblock(int fd) { int opts,ret; ret=-1; opts = fcntl(fd, F_GETFL); if (opts == -1){goto end;} opts = opts | O_NONBLOCK; ret = fcntl(fd, F_SETFL, opts); end: return ret; } int wtk_fd_set_block(int fd) { int opts,ret; ret=-1; opts = fcntl(fd, F_GETFL); if (opts == -1){goto end;} opts = opts ^ O_NONBLOCK; ret = fcntl(fd, F_SETFL, opts); end: return ret; } int wtk_fd_is_block(int fd) { int opts; int ret; opts = fcntl(fd, F_GETFL); ret=opts & O_NONBLOCK; return ret?0:1; } #endif int wtk_fd_set_tcp_client_opt(int fd) { int keepalive = 1, keepalive_time = 3, keepalive_intvl = 3, keepalive_probes = 2; int reuse = 1; int ret; ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*) &reuse, sizeof(reuse)); if (ret != 0) { goto end; } ret = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (char*) (&keepalive), (socklen_t) sizeof(keepalive)); #ifndef WIN32 if (ret != 0) { goto end; } ret = setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void*) (&keepalive_time), (socklen_t) sizeof(keepalive_time)); if (ret != 0) { goto end; } ret = setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void*) (&keepalive_intvl), (socklen_t) sizeof(keepalive_intvl)); if (ret != 0) { goto end; } ret = setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, (void*) (&keepalive_probes), (socklen_t) sizeof(keepalive_probes)); #ifdef USE_TCP_NODELAY { int tcp_nodelay = 1; ret = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void *)&tcp_nodelay, sizeof(int)); } #endif #endif end: return ret; } <file_sep>/core/wtk_median_filter.c #include "wtk_median_filter.h" wtk_median_filter_t* wtk_median_filter_new(int window) { wtk_median_filter_t* m; m=(wtk_median_filter_t*)wtk_malloc(sizeof(wtk_median_filter_t)); m->win=window; m->idx=0; m->v=(short*)wtk_malloc(sizeof(short)*window); m->s=(short*)wtk_malloc(sizeof(short)*window); return m; } void wtk_median_filter_delete(wtk_median_filter_t *m) { wtk_free(m->s); wtk_free(m->v); wtk_free(m); } float wtk_median_short_sort(void *ths,short *src,short *dst) { return *src-*dst; } short wtk_median_update(wtk_median_filter_t *m) { //print_short(m->v,m->win); memcpy(m->s,m->v,sizeof(short)*m->win); wtk_qsort2(m->s,m->win,sizeof(short),(wtk_qsort_cmp_f)wtk_median_short_sort,NULL); //print_short(m->s,m->win); return m->s[m->win/2]; } void wtk_median_filter_feed(wtk_median_filter_t *m,short *v,int n,short *dst) { int i,j; j=0; for(i=0;i<n;++i) { m->v[m->idx++]=v[i]; if(m->idx==m->win) { dst[j++]=wtk_median_update(m); --m->idx; memmove(m->v,m->v+1,sizeof(short)*m->idx); //wtk_debug("v=%d\n",v[j-1]); //exit(0); }else { //dst[j++]=0; } } } void wtk_median_filter_process(short *input,short *output,int len,int win) { wtk_median_filter_t *m; m=wtk_median_filter_new(win); wtk_median_filter_feed(m,input,len,output); wtk_median_filter_delete(m); } <file_sep>/os/.svn/pristine/ed/edddb56f37c43df114abed6175912f75c5c4ecf7.svn-base #ifndef WTK_OS_WTK_LOCKVPOOL #define WTK_OS_WTK_LOCKVPOOL #include "wtk/core/wtk_vpool.h" #include "wtk_lock.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_lockvpool wtk_lockvpool_t; struct wtk_lockvpool { wtk_lock_t lock; wtk_vpool_t *pool; }; wtk_lockvpool_t* wtk_lockvpool_new(int bytes,int max_free); wtk_lockvpool_t* wtk_lockvpool_new2(int bytes,int max_free,int reset_free); void wtk_lockvpool_delete(wtk_lockvpool_t *v); void wtk_lockvpool_reset(wtk_lockvpool_t *v); void* wtk_lockvpool_pop(wtk_lockvpool_t *v); void wtk_lockvpool_push(wtk_lockvpool_t *v,void *usr_data); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/52/5287780e92e3785088c7c4ad1f610ef644d65f95.svn-base #include "wtk_slot.h" wtk_slot_t* wtk_slot_new_h(wtk_heap_t *heap,int nslot,int elem_bytes) { wtk_slot_t *s; s=(wtk_slot_t*)wtk_heap_malloc(heap,sizeof(*s)); s->nslot=nslot; if(nslot>0) { s->slot=(void*)wtk_heap_malloc(heap,elem_bytes*nslot); }else { s->slot=0; } return s; } <file_sep>/core/rbin/wtk_ubin.h #ifndef WTK_CORE_RBIN_WTK_UBIN_H_ #define WTK_CORE_RBIN_WTK_UBIN_H_ #include "wtk/core/wtk_heap.h" #include "wtk/core/wtk_os.h" #include "wtk/core/cfg/wtk_source.h" #include "wtk/core/wtk_str_hash.h" #include "wtk/core/rbin/wtk_rbin.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_ubin wtk_ubin_t; #define WTK_UBIN_ATTR_VALID 0x00 #define WTK_UBIN_ATTR_INVALID 0x01 typedef struct wtk_ubin_item { wtk_string_t *fn; wtk_string_t *data; int seek_pos; char attr; }wtk_ubin_item_t; struct wtk_ubin { char *fn; int item_len; int item_num; wtk_heap_t *heap; wtk_str_hash_t *hash; }; #define wtk_ubin_new_item(b) wtk_heap_malloc((b)->heap,sizeof(wtk_ubin_item_t)) wtk_ubin_t* wtk_ubin_new(unsigned int slot); void wtk_ubin_delete(wtk_ubin_t *b); void wtk_ubin_reset(wtk_ubin_t *b); int wtk_ubin_read(wtk_ubin_t *b,char *fn,int read_data); int wtk_ubin_read_all_data(wtk_ubin_t *b); int wtk_ubin_read_data(wtk_ubin_t *b,wtk_ubin_item_t *item); int wtk_ubin_write_all(wtk_ubin_t *b,char *fn); int wtk_ubin_write_item(wtk_ubin_t *b,FILE *f,wtk_ubin_item_t *item); int wtk_ubin_write_data(wtk_ubin_t *b,FILE *f,wtk_ubin_item_t *item); int wtk_ubin_write_attr(wtk_ubin_t *b,FILE *f,wtk_ubin_item_t *item); wtk_ubin_item_t* wtk_ubin_add_item(wtk_ubin_t *b,wtk_string_t *fn,wtk_string_t *data,char attr); int wtk_ubin_append(wtk_ubin_t *b,wtk_string_t *fn,wtk_string_t *data,char attr); wtk_ubin_item_t* wtk_ubin_find_item(wtk_ubin_t *b,wtk_string_t *fn); #ifdef __cplusplus } #endif #endif <file_sep>/os/wtk_pid.c #include "wtk_pid.h" #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <signal.h> #include <sys/prctl.h> #include "wtk_proc.h" #include "wtk/core/wtk_str.h" int pid_kill(pid_t pid) { int ret; ret=kill(pid,SIGKILL); if(ret==0) { waitpid(pid,0,0); } return ret; } static void proc_process_sig(int sig) { wtk_debug("%d: receive %d signal.\n",getpid(),sig);//magic_proc->name?magic_proc->name:"anon",sig); switch(sig) { case SIGSEGV: wtk_proc_dump_stack(); exit(0); break; case SIGFPE: wtk_proc_dump_stack(); exit(0); break; } } int pid_setup_signal() { int signals[]={SIGPIPE,SIGSEGV,SIGFPE}; int i,count; count=sizeof(signals)/sizeof(int); for(i=0;i<count;++i) { signal(signals[i],proc_process_sig); } return 0; } void pid_daemonize() { signal(SIGTTOU, SIG_IGN); signal(SIGTTIN, SIG_IGN); signal(SIGTSTP, SIG_IGN); if (0 != fork()) exit(0); if (-1 == setsid()) exit(0); signal(SIGHUP, SIG_IGN); if (0 != fork()) exit(0); //if (0 != chdir("/")) exit(0); } void pid_save_file(pid_t pid,char* pf) { char buf[32]; int n; n=sprintf(buf,"%d",pid); file_write_buf(pf,buf,n); } void pid_delete_file(pid_t pid,char* pf) { //char buf[32]; //sprintf(buf,"%d",pid); if(wtk_file_exist(pf)==0) { remove(pf); } } int pid_from_file(char *fn) { int id=-1,n; char *p; if(wtk_file_exist(fn)!=0){goto end;} p=file_read_buf(fn,&n); id=wtk_str_atoi(p,n); wtk_free(p); end: return id; } <file_sep>/os/wtk_log.c #include "wtk_log.h" #include <stdarg.h> #include <time.h> #include "wtk/core/wtk_os.h" wtk_log_t *glb_log=NULL; #if _MSC_VER #define snprintf _snprintf #endif int wtk_log_g_print_time(char *buf) { time_t ct; struct tm xm; struct tm* m; int ret,n; n=0; ret=time(&ct); if(ret==-1){goto end;} #ifdef WIN32 m=localtime(&ct); #else m=localtime_r(&ct,&xm); #endif if(!m){ret=-1;goto end;} n=sprintf(buf,"%04d-%02d-%02d-%02d:%02d:%02d",m->tm_year+1900,m->tm_mon+1,m->tm_mday,m->tm_hour,m->tm_min,m->tm_sec); ret=0; end: return n; } wtk_log_t* wtk_log_new(char *fn) { return wtk_log_new2(fn,LOG_NOTICE); } wtk_log_t* wtk_log_new2(char *fn,int level) { return wtk_log_new3(fn,level,0); } wtk_log_t* wtk_log_new3(char *fn,int level, int daily) { wtk_log_t* l; int ret; l=(wtk_log_t*)wtk_malloc(sizeof(*l)); l->log_level=level; l->log_ts=1; l->daily=daily; l->log_touch=1; ret=wtk_log_init(l,fn); if(ret!=0) { wtk_log_delete(l); l=0; } glb_log=l; return l; } int wtk_log_delete(wtk_log_t *l) { wtk_log_clean(l); wtk_free(l); return 0; } /* get log file */ static FILE * _f(wtk_log_t *l) { char fn[256]; if (l->f == stdout || l->fn[0] == 0) { return stdout; } if (l->daily) { if (l->today != l->t->tm.tm_mday) { snprintf(fn, sizeof(fn), "%s-%04d%02d%02d", l->fn, l->t->tm.tm_year + 1900, l->t->tm.tm_mon + 1, l->t->tm.tm_mday); if (l->f) { fclose(l->f); } l->f = wtk_file_open(fn, "w"); l->today = l->t->tm.tm_mday; } } else { if (l->f == NULL) { snprintf(fn, sizeof(fn), "%s", l->fn); l->f = wtk_file_open(fn, "w"); } } return l->f; } int wtk_log_init(wtk_log_t* l,char* fn) { l->t = wtk_time_new(); l->today = -1; l->f = NULL; l->fn[0] = 0; if (fn) { strncpy(l->fn, fn, sizeof(l->fn)); } l->f = _f(l); wtk_lock_init(&(l->l)); return l->f ? 0 : -1; } int wtk_log_clean(wtk_log_t* l) { int ret; wtk_lock_clean(&(l->l)); if(l->f && (l->f!=stdout)) { ret=fclose(l->f); l->f=0; }else { ret=0; } if(l->t) { wtk_time_delete(l->t); } return ret; } int wtk_log_redirect(wtk_log_t *l,char *fn) { fclose(l->f); l->f=wtk_file_open(fn,"a"); return l->f?0:-1; } int wtk_log_printf(wtk_log_t* l,const char *func,int line,int level,char* fmt,...) { va_list ap; int ret; if(level<l->log_level) { return 0; } //if(!l){return 0;} va_start(ap,fmt); ret=wtk_lock_lock(&(l->l)); if(ret!=0){goto end;} if (l->f == NULL) { goto end; } if(l->log_touch) { wtk_time_update(l->t); } l->f = _f(l); //fprintf(l->f,"%*.*s:%f [%d](%s:%d) ",l->t->log_time.len,l->t->log_time.len,l->t->log_time.data,time_get_ms(),level,func,line); if(l->log_ts) { //wtk_time_update(l->t); fprintf(l->f,"%*.*s [%d](%s:%d) ",l->t->log_time.len,l->t->log_time.len,l->t->log_time.data,level,func,line); } vfprintf(l->f,fmt,ap); fprintf(l->f,"\n"); fflush(l->f); //wtk_debug("ret=%d\n",ret); ret=wtk_lock_unlock(&(l->l)); end: va_end(ap); return 0; } double wtk_log_cur_time(wtk_log_t *l) { return l->t->wtk_cached_time; } //--------------------- test/example section ---------------- void wtk_log_test_g() { wtk_log_t *log; int i=0; log=wtk_log_new("foo.log"); while(1) { wtk_log_log(log,"log %d.",++i); wtk_msleep(500); } wtk_log_delete(log); } <file_sep>/core/.svn/pristine/9a/9ae4bac63812d41d3846b8c9a70861488eac92ba.svn-base #include "wtk_queue3.h" /* void wtk_queue3_init(wtk_queue3_t *q) { q->pop=q->push=0; }*/ int wtk_queue3_len(wtk_queue3_t *q) { wtk_queue_node_t *n=q->pop; int len; len=0; while(n) { ++len; n=n->next; } return len; } void wtk_queue3_push(wtk_queue3_t *q,wtk_queue_node_t *n) { n->prev=q->push; if(q->push) { q->push->next=n; } n->next=0; q->push=n; if(!q->pop) { q->pop=n; } ++q->len; } void wtk_queue3_push_front(wtk_queue3_t *q,wtk_queue_node_t *n) { n->next=q->pop; if(q->pop) { q->pop->prev=n; } n->prev=0; q->pop=n; if(!q->push) { q->push=n; } ++q->len; } void wtk_queue3_insert_to(wtk_queue3_t *q,wtk_queue_node_t *n,wtk_queue_node_t* n2) { if(n==q->push) { wtk_queue3_push(q,n2); }else { n2->prev=n; n2->next=n->next; n2->next->prev=n2->prev->next=n2; ++q->len; } return; } /** * n0->n2->n3 * => n0->n1->n2->n3 * n1 */ void wtk_queue3_insert_before(wtk_queue3_t *q,wtk_queue_node_t *n2,wtk_queue_node_t *n1) { n1->prev=n2->prev; if(n1->prev) { n1->prev->next=n1; }else { q->pop=n1; } n2->prev=n1; n1->next=n2; ++q->len; } wtk_queue_node_t* wtk_queue3_pop(wtk_queue3_t *q) { wtk_queue_node_t* n; n=0; if(!q->pop){goto end;} n=q->pop; q->pop=q->pop->next; if(q->pop) { q->pop->prev=0; }else { q->push=0; } --q->len; end: return n; } wtk_queue_node_t* wtk_queue3_pop_back(wtk_queue3_t *q) { wtk_queue_node_t* n; if(q->len<=0 || !q->push){return 0;} n=q->push; --q->len; q->push=q->push->prev; if(q->push) { q->push->next=NULL; }else { q->pop=NULL; } return n; } void wtk_queue3_remove(wtk_queue3_t *q,wtk_queue_node_t *n) { if(n->prev) { n->prev->next=n->next; }else { q->pop=n->next; } if(n->next) { n->next->prev=n->prev; }else { q->push=n->prev; } n->prev=n->next=0; --q->len; } void wtk_queue3_check(wtk_queue3_t *q) { wtk_queue_node_t *qn; int len=0; for(qn=q->pop;qn;qn=qn->next) { ++len; } if(len!=q->len) { wtk_debug("found bug=%d/%d\n",len,q->len); exit(0); } } void wtk_queue_link2(wtk_queue_t *dst,wtk_queue3_t *src) { wtk_queue_node_t *n=src->pop; if(src->len<=0){return;} if(dst->length==0) { dst->pop=dst->push=0; } n->prev=dst->push; if(dst->push) { dst->push->next=n; } dst->push=src->push; if(!dst->pop) { dst->pop=n; } if(dst->listener) { dst->listener(dst->data); } dst->length+=src->len; } wtk_queue_node_t* wtk_queue3_peek(wtk_queue3_t *q,int index) { wtk_queue_node_t *n=0; int i; if(index>=q->len){goto end;} n=q->pop;i=0; while(i<index) { n=n->next; ++i; } end: return n; } <file_sep>/core/wtk_model.h #ifndef WTK_FISH_LEARN_WTK_MODEL #define WTK_FISH_LEARN_WTK_MODEL #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_heap.h" #include "wtk/core/wtk_str_hash.h" #include "wtk/core/wtk_queue2.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_model wtk_model_t; #define wtk_model_add_listener_s(m,k,ths,n) wtk_model_add_listener(m,k,sizeof(k)-1,ths,n) #define wtk_model_set_i_s(m,k,i) wtk_model_set_i(m,k,sizeof(k)-1,i) #define wtk_model_set_f_s(m,k,f) wtk_model_set_f(m,k,sizeof(k)-1,f); #define wtk_model_set_p_s(m,k,p) wtk_model_set_p(m,k,sizeof(k)-1,p); #define wtk_model_get_item_s(m,k) wtk_model_get_item(m,k,sizeof(k)-1) #define wtk_model_get_data_s(m,k) wtk_model_get_data(m,k,sizeof(k)-1) typedef enum { WTK_MODEL_V_NIL, WTK_MODEL_V_P, WTK_MODEL_V_I, WTK_MODEL_V_F, }wtk_model_item_type_t; typedef struct { wtk_model_item_type_t type; union { void *p; int i; float f; }v; }wtk_model_item_v_t; typedef void(*wtk_model_notify_f)(void *ths,wtk_model_item_v_t *old_value,wtk_model_item_v_t *new_value); typedef void*(*wtk_model_get_data_f)(void *ths,char *k,int k_bytes); typedef void (*wtk_model_touch_f)(void *ths); typedef struct { wtk_queue_node_t q_n; void *ths; wtk_model_notify_f notify; }wtk_model_listener_item_t; typedef struct { // wtk_queue_node_t q_n; wtk_string_t *k; wtk_model_item_v_t v; wtk_queue2_t listener_q; }wtk_model_item_t; struct wtk_model { wtk_str_hash_t *hash; void *data_ths; wtk_model_get_data_f get_data_f; void *touch_ths; wtk_model_touch_f touch_f; }; wtk_model_t* wtk_model_new(int nslot); void wtk_model_delete(wtk_model_t *m); void wtk_model_add_listener(wtk_model_t *m,char *k,int k_bytes,void *ths,wtk_model_notify_f notify); void wtk_model_add_listener2(wtk_model_t *m,wtk_model_item_t *item,void *ths,wtk_model_notify_f notify); wtk_model_item_t* wtk_model_set_i(wtk_model_t *m,char *k,int k_bytes,int i); wtk_model_item_t* wtk_model_set_f(wtk_model_t *m,char *k,int k_bytes,float f); wtk_model_item_t* wtk_model_set_p(wtk_model_t *m,char *k,int k_bytes,void *p); wtk_model_item_t* wtk_model_get_item(wtk_model_t *m,char *k,int k_bytes); void wtk_model_item_set(wtk_model_item_t *item,wtk_model_item_v_t *new_value); void wtk_model_item_set_i(wtk_model_item_t *item,int i); void wtk_model_item_set_f(wtk_model_item_t *item,float f); void wtk_model_item_set_p(wtk_model_item_t *item,void *p); void wtk_model_set_data_get(wtk_model_t *m,void *ths,wtk_model_get_data_f get_data); void* wtk_model_get_data(wtk_model_t *m,char *k,int k_bytes); void wtk_model_set_touch(wtk_model_t *m,void *ths,wtk_model_touch_f touch); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/52/5253188bb3ae6c2a72a6e9f49ef80aeb17c8bc7f.svn-base #include "wtk_gzip.h" void wtk_gzip_zip_finish(wtk_gzip_t *zip); wtk_gzip_t* wtk_gzip_new() { wtk_gzip_t *gz; gz=(wtk_gzip_t*)wtk_malloc(sizeof(wtk_gzip_t)); gz->buf=wtk_strbuf_new(256,1); gz->cache_size=4096; //gz->cache_size=256; gz->cache=(char*)wtk_malloc(gz->cache_size); return gz; } void wtk_gzip_delete(wtk_gzip_t *gz) { wtk_free(gz->cache); wtk_strbuf_delete(gz->buf); wtk_free(gz); } static void storLE32 (uint8_t *p, uint32_t n) { p[0] = n >> 0; p[1] = n >> 8; p[2] = n >> 16; p[3] = n >> 24; } void wtk_gzip_zip_start(wtk_gzip_t *gz) { uint8_t hdr[10] = { 0x1F, 0x8B, /* magic */ 8, /* z method */ 0, /* flags */ 0,0,0,0, /* mtime */ 0, /* xfl */ 0xFF, /* OS */ }; wtk_strbuf_t *buf=gz->buf; z_stream *s=&(gz->stream); int windowBits = -MZ_DEFAULT_WINDOW_BITS; wtk_strbuf_reset(buf); wtk_strbuf_push(buf,(char*)hdr,10); memset(s,0,sizeof(z_stream)); deflateInit2 (s,6,MZ_DEFLATED, windowBits, 6, MZ_DEFAULT_STRATEGY); } void wtk_gzip_zip_write(wtk_gzip_t *gz,char *data,int bytes,int is_end) { wtk_strbuf_t *buf=gz->buf; z_stream *s=&(gz->stream); int st; int v; int b; //wtk_debug("======================> in=%d is_end=%d\n",bytes,is_end); s->next_in=(unsigned char*)data; s->avail_in =bytes; s->next_out = (unsigned char*)gz->cache; s->avail_out = gz->cache_size; b=1; while(b) { st=mz_deflate (s,is_end?MZ_FINISH:MZ_NO_FLUSH);//bytes>0?MZ_NO_FLUSH:MZ_FINISH); //bytes=0; //wtk_debug("st=%d/%d bytes=%d avin=%d avout=%d\n",st,MZ_OK,bytes,s->avail_in,s->avail_out); switch(st) { case MZ_STREAM_END: //fall through b=0; case MZ_OK: //wtk_debug("out=%d b=%d\n",s->avail_out,b); v=gz->cache_size-s->avail_out; //wtk_debug("v=%d\n",v); if(v<gz->cache_size)//s->avail_out>0) { b=0; } if(v>0) { wtk_strbuf_push(buf,gz->cache,v); s->next_out = (unsigned char*)gz->cache; s->avail_out = gz->cache_size; } //s->avail_in=0; //b=0; break; case MZ_BUF_ERROR: wtk_debug("buf error\n"); b=0; break; case MZ_DATA_ERROR: wtk_debug("data error\n"); b=0; break; case MZ_PARAM_ERROR: wtk_debug("param error\n"); b=0; break; case MZ_STREAM_ERROR: wtk_debug("stream error\n"); b=0; break; } } //wtk_debug("size=%d\n",buf->pos); //exit(0); if(is_end) { wtk_gzip_zip_finish(gz); } } void wtk_gzip_zip_finish(wtk_gzip_t *gz) { uint8_t ftr[8]; wtk_strbuf_t *buf=gz->buf; gz->st.l=gz->stream.total_in; gz->st.crc32=gz->stream.crc32; storLE32 (ftr + 0, gz->st.crc32); storLE32 (ftr + 4, gz->st.l); wtk_strbuf_push(buf,(char*)ftr,8); //wtk_debug("size=%d\n",buf->pos); //exit(0); deflateEnd(&(gz->stream)); } void wtk_gzip_unzip_start(wtk_gzip_t *gz) { wtk_strbuf_t *buf=gz->buf; z_stream *s=&(gz->stream); int windowBits = -MZ_DEFAULT_WINDOW_BITS; wtk_strbuf_reset(buf); memset(s,0,sizeof(z_stream)); inflateInit2(s,windowBits); gz->state=WTK_GZIP_UNZIP_INIT; } int wtk_gzip_unzip_read(wtk_gzip_t *gz,char *data,int bytes,int is_end) { wtk_strbuf_t *buf=gz->buf; int n; int ret; z_stream *s=&(gz->stream); int st; int v; int b; //wtk_debug("====================== bytes=%d ==================\n",bytes); switch(gz->state) { case WTK_GZIP_UNZIP_INIT: n=min(10-buf->pos,bytes); wtk_strbuf_push(buf,data,n); if(buf->pos==10) { if(buf->data[0]!=0x1f || buf->data[1]==0x8b) { wtk_debug("not in gz format"); ret=-1; goto end; } if(buf->data[2]!=8) { wtk_debug("unknown z-algorithm: 0x%0hhX", buf->data[2]); ret=-1; goto end; } gz->hdr_flags=buf->data[3]; if (gz->hdr_flags & (1 << 2)) { gz->state=WTK_GZIP_UNZIP_FLAG_EXTRA; }else if(gz->hdr_flags & (1<<3)) { gz->state=WTK_GZIP_UNZIP_FLAG_FNAME; }else if(gz->hdr_flags & (1<<4)) { gz->state=WTK_GZIP_UNZIP_FLAG_FCOMMENT; }else if(gz->hdr_flags & (1<<1)) { gz->state=WTK_GZIP_UNZIP_FLAG_FCRC; }else { gz->state=WTK_GZIP_UNZIP_RUN; } wtk_strbuf_reset(buf); bytes-=n; if(bytes>0) { return wtk_gzip_unzip_read(gz,data+n,bytes,is_end); } } break; case WTK_GZIP_UNZIP_FLAG_EXTRA: n=min(2-buf->pos,bytes); wtk_strbuf_push(buf,data,n); if(buf->pos==2) { gz->state=WTK_GZIP_UNZIP_FLAG_EXTRA_SKIP; gz->next_bytes=(buf->data[1]<<8)+buf->data[0]; wtk_strbuf_reset(buf); bytes-=n; if(bytes>0) { return wtk_gzip_unzip_read(gz,data+n,bytes,is_end); } } break; case WTK_GZIP_UNZIP_FLAG_EXTRA_SKIP: n=min(gz->next_bytes-buf->pos,bytes); wtk_strbuf_push(buf,data,n); if(buf->pos==gz->next_bytes) { if(gz->hdr_flags & (1<<3)) { gz->state=WTK_GZIP_UNZIP_FLAG_FNAME; }else if(gz->hdr_flags & (1<<4)) { gz->state=WTK_GZIP_UNZIP_FLAG_FCOMMENT; }else if(gz->hdr_flags & (1<<1)) { gz->state=WTK_GZIP_UNZIP_FLAG_FCRC; }else { gz->state=WTK_GZIP_UNZIP_RUN; } wtk_strbuf_reset(buf); bytes-=n; if(bytes>0) { return wtk_gzip_unzip_read(gz,data+n,bytes,is_end); } } break; case WTK_GZIP_UNZIP_FLAG_FNAME: for(n=0;n<bytes;++n) { if(data[n]==0) { if(gz->hdr_flags & (1<<4)) { gz->state=WTK_GZIP_UNZIP_FLAG_FCOMMENT; }else if(gz->hdr_flags & (1<<1)) { gz->state=WTK_GZIP_UNZIP_FLAG_FCRC; }else { gz->state=WTK_GZIP_UNZIP_RUN; } wtk_strbuf_reset(buf); ++n; bytes-=n; if(bytes>0) { return wtk_gzip_unzip_read(gz,data+n,bytes,is_end); } break; } } break; case WTK_GZIP_UNZIP_FLAG_FCOMMENT: for(n=0;n<bytes;++n) { if(data[n]==0) { if(gz->hdr_flags & (1<<1)) { gz->state=WTK_GZIP_UNZIP_FLAG_FCRC; }else { gz->state=WTK_GZIP_UNZIP_RUN; } wtk_strbuf_reset(buf); ++n; bytes-=n; if(bytes>0) { return wtk_gzip_unzip_read(gz,data+n,bytes,is_end); } break; } } break; case WTK_GZIP_UNZIP_FLAG_FCRC: n=min(2-buf->pos,bytes); wtk_strbuf_push(buf,data,n); if(buf->pos==2) { gz->state=WTK_GZIP_UNZIP_RUN; wtk_strbuf_reset(buf); bytes-=n; if(bytes>0) { return wtk_gzip_unzip_read(gz,data+n,bytes,is_end); } } break; case WTK_GZIP_UNZIP_RUN: s->next_in=(unsigned char*)data; s->avail_in=bytes; s->next_out = (unsigned char*)gz->cache; s->avail_out = gz->cache_size; b=1; while(b) { st=mz_inflate(s,MZ_SYNC_FLUSH); switch(st) { case MZ_STREAM_END: //fall through b=0; case MZ_OK: //wtk_debug("out=%d b=%d\n",s->avail_out,b); v=gz->cache_size-s->avail_out; //wtk_debug("out=%d out=%d in=%d pos=%d\n",v,s->avail_out,s->avail_in,buf->pos); if(v<gz->cache_size) { b=0; } if(v>0) { wtk_strbuf_push(buf,gz->cache,v); s->next_out = (unsigned char*)gz->cache; s->avail_out = gz->cache_size; } //s->avail_in=0; //b=0; break; case MZ_BUF_ERROR: wtk_debug("buf error\n"); b=0; break; case MZ_DATA_ERROR: wtk_debug("data error\n"); b=0; break; case MZ_PARAM_ERROR: wtk_debug("param error\n"); b=0; break; case MZ_STREAM_ERROR: wtk_debug("stream error\n"); b=0; break; } } //exit(0); break; } ret=0; end: if(is_end) { inflateEnd(s); } return ret; } <file_sep>/core/.svn/pristine/00/00d9f26d89ca3efe684d8e047c08b472eed879b0.svn-base #include "wtk_chnpos_cfg.h" #include "wtk/core/cfg/wtk_source.h" int wtk_chnpos_cfg_init(wtk_chnpos_cfg_t *cfg) { wtk_prune_cfg_init(&(cfg->prune)); cfg->model=NULL; cfg->model_fn=NULL; cfg->use_prune=0; return 0; } int wtk_chnpos_cfg_clean(wtk_chnpos_cfg_t *cfg) { if(cfg->model) { wtk_chnpos_model_delete(cfg->model); } return 0; } int wtk_chnpos_cfg_update_local(wtk_chnpos_cfg_t *cfg,wtk_local_cfg_t *main) { wtk_string_t *v; wtk_local_cfg_t *lc; lc=main; wtk_local_cfg_update_cfg_str(lc,cfg,model_fn,v); wtk_local_cfg_update_cfg_b(lc,cfg,use_prune,v); lc=wtk_local_cfg_find_lc_s(main,"prune"); if(lc) { wtk_prune_cfg_update_local(&(cfg->prune),lc); } return 0; } int wtk_chnpos_cfg_update(wtk_chnpos_cfg_t *cfg) { wtk_prune_cfg_update(&(cfg->prune)); cfg->model=wtk_chnpos_model_new(); wtk_source_load_file(cfg->model,(wtk_source_load_handler_t)wtk_chnpos_model_load,cfg->model_fn); return 0; } int wtk_chnpos_cfg_update2(wtk_chnpos_cfg_t *cfg,wtk_source_loader_t *sl) { int ret; wtk_prune_cfg_update(&(cfg->prune)); cfg->model=wtk_chnpos_model_new(); ret=wtk_source_loader_load(sl,cfg->model,(wtk_source_load_handler_t)wtk_chnpos_model_load,cfg->model_fn); return ret; } <file_sep>/core/.svn/pristine/fe/fe6678aec729f136f89f1db76f823a979be5ff26.svn-base #include "wtk_larray.h" wtk_larray_t* wtk_larray_new(uint32_t n,uint32_t size) { wtk_larray_t* a; a=(wtk_larray_t*)wtk_malloc(sizeof(*a)); a->slot_alloc=n; a->slot_size=size; a->nslot=0; a->slot=wtk_calloc(n,size); return a; } int wtk_larray_delete(wtk_larray_t* a) { wtk_free(a->slot); wtk_free(a); return 0; } int wtk_larray_bytes(wtk_larray_t *a) { int bytes=sizeof(wtk_larray_t); bytes+=a->slot_size*a->slot_alloc; return bytes; } wtk_larray_t* wtk_larray_dup(wtk_larray_t *src) { wtk_larray_t* dst; dst=wtk_larray_new(src->nslot,src->slot_size); dst->nslot=src->nslot; memcpy(dst->slot,src->slot,src->nslot*src->slot_size); return dst; } void wtk_larray_cpy(wtk_larray_t *src,wtk_larray_t *dst) { wtk_larray_reset(dst); if(dst->slot_alloc<src->slot_alloc) { wtk_larray_reset2(dst,src->slot_alloc); } memcpy(dst->slot,src->slot,src->nslot*src->slot_size); dst->nslot=src->nslot; } void wtk_larray_merge(wtk_larray_t *merged,wtk_larray_t *pad) { void *dst; dst=wtk_larray_push_n(merged,pad->nslot); //print_data(dst,4); memcpy(dst,pad->slot,pad->slot_size*pad->nslot); } void wtk_larray_reset(wtk_larray_t *a) { a->nslot=0; } void wtk_larray_reset2(wtk_larray_t *a,int n) { if(a->slot_alloc!=n) { wtk_free(a->slot); a->slot=wtk_calloc(n,a->slot_size); a->slot_alloc=n; } a->nslot=0; } void* wtk_larray_push(wtk_larray_t* a) { return wtk_larray_push_n(a,1); } void* wtk_larray_get(wtk_larray_t *a,int idx) { //wtk_debug("[%p]=%p\n",a->slot,((char*)a->slot)+idx*a->slot_size); return (void*)(((char*)a->slot)+idx*a->slot_size); } void wtk_larray_push2(wtk_larray_t *a,void *src) { void *dst; dst=wtk_larray_push_n(a,1); //print_data(dst,4); memcpy(dst,src,a->slot_size); //print_data(dst,4); //wtk_debug("src:%p,%d\n",src,a->slot_size); } void* wtk_larray_push_n(wtk_larray_t* a,uint32_t n) { uint32_t alloc; void *s; if(a->nslot+n > a->slot_alloc) { alloc=2*max(n,a->slot_alloc); s=wtk_calloc(alloc,a->slot_size); memcpy(s,a->slot,a->slot_size*a->nslot); wtk_free(a->slot); a->slot=s; a->slot_alloc=alloc; } s=(char*)a->slot+a->slot_size*a->nslot; a->nslot+=n; return s; } wtk_flta_t* wtk_flta_new(int n) { wtk_flta_t *f; f=(wtk_flta_t*)wtk_malloc(sizeof(wtk_flta_t)); f->len=n; f->p=(float*)wtk_malloc(sizeof(float)*n); f->pos=0; wtk_flta_zero(f); return f; } void wtk_flta_delete(wtk_flta_t *a) { wtk_free(a->p); wtk_free(a); } void wtk_flta_reset(wtk_flta_t *a) { a->pos=0; } void wtk_flta_zero(wtk_flta_t *a) { memset(a->p,0,a->len*sizeof(float)); } //------------------------------- test/examle section ------------------ void wtk_larray_test_g() { wtk_larray_t *a; a=wtk_larray_new(10,sizeof(int)); *((int*)wtk_larray_push(a))=10; wtk_larray_delete(a); } <file_sep>/core/.svn/pristine/a5/a56dde629fe90f290a11f62e22dac6838c465c08.svn-base #ifndef WTK_CORE_WTK_FKV2 #define WTK_CORE_WTK_FKV2 #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_str_hash.h" #include "wtk/core/wtk_str_encode.h" #include "wtk/core/wtk_strbuf.h" #include "wtk/core/rbin/wtk_rbin2.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_fkv2 wtk_fkv2_t; #define wtk_fkv2_get_s(kv,env,k) wtk_fkv2_get(kv,env,k,sizeof(k)-1) #define wtk_fkv2_has_s(kv,env,k) wtk_fkv2_has(kv,env,k,sizeof(k)-1) /** * python kv2bin2.py */ typedef enum { WTK_FKV2_INT=1, WTK_FKV2_FLOAT, WTK_FKV2_STRING, //WTK_FKV2_LSTRING, }wtk_fkv2_type_t; typedef struct { union { int v; float f; wtk_string_t str; }v; unsigned int offset; unsigned short depth; unsigned short is_end:1; unsigned short is_err:1; }wtk_fkv_env_t; struct wtk_fkv2 { FILE *f; wtk_str_hash_t *char_map; unsigned int max; unsigned int step; unsigned int nslot; unsigned int *slots; unsigned int slot_offset; wtk_strbuf_t *buf; wtk_fkv2_type_t type; int f_of; int f_len; unsigned file_want_close:1; }; wtk_fkv2_t* wtk_fkv2_new2(wtk_rbin2_t *rbin,char *fn); wtk_fkv2_t* wtk_fkv2_new(char *fn); void wtk_fkv2_delete(wtk_fkv2_t* k); void wtk_fkv_env_init(wtk_fkv2_t *k,wtk_fkv_env_t *env); void wtk_fkv_env_print(wtk_fkv_env_t *env); int wtk_fkv2_get(wtk_fkv2_t *kv,wtk_fkv_env_t *env,char *k,int k_bytes); int wtk_fkv2_has(wtk_fkv2_t *kv,wtk_fkv_env_t *env,char *data,int bytes); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/79/79ff3e4e7b3c8ec1a3d179240c0ec36ca6cb64b7.svn-base #ifndef WTK_VITE_PITCH_WTK_PITCH #define WTK_VITE_PITCH_WTK_PITCH #include "wtk/core/cfg/wtk_local_cfg.h" #include "wtk/core/wtk_larray.h" #include "wtk/core/wtk_strbuf.h" #include "wtk_pitch_cfg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_pitch wtk_pitch_t; typedef void(*wtk_pitch_noityf_f)(void *ths,char *data,int bytes); struct wtk_pitch { wtk_pitch_cfg_t *cfg; wtk_flta_t *in; wtk_flta_t *out; wtk_flta_t *in_fifo; wtk_flta_t *out_fifo; wtk_flta_t *fft_worksp; wtk_flta_t *last_phase; wtk_flta_t *sum_phase; wtk_flta_t *output_accum; wtk_flta_t *ana_freq; wtk_flta_t *ana_magn; wtk_flta_t *syn_freq; wtk_flta_t *syn_magn; int rover; wtk_strbuf_t *buf; double f1; double f2; double f3; double f4; void* notify_ths; wtk_pitch_noityf_f notify; }; wtk_pitch_t* wtk_pitch_new(wtk_pitch_cfg_t *cfg); void wtk_pitch_delete(wtk_pitch_t *p); void wtk_pitch_reset(wtk_pitch_t *p); void wtk_pitch_set(wtk_pitch_t *p,void *ths,wtk_pitch_noityf_f notify); /* bytes must be pow 2 */ void wtk_pitch_process(wtk_pitch_t *p,float pitch_shift,char *data,int bytes); int wtk_pitch_convert(wtk_pitch_t *p,float shift,char *in,char *out); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_jsonkv.c #include <ctype.h> #include "wtk_jsonkv.h" #include "wtk/core/wtk_os.h" wtk_jsonkv_t* wtk_jsonkv_new(char *dn) { wtk_jsonkv_t *kv; kv=(wtk_jsonkv_t*)wtk_malloc(sizeof(wtk_jsonkv_t)); kv->json_parser=wtk_json_parser_new(); kv->dn=wtk_strbuf_new(256,1); wtk_strbuf_push(kv->dn,dn,strlen(dn)); kv->buf=wtk_strbuf_new(256,1); kv->tmp=wtk_strbuf_new(1024,1); kv->get_map=NULL; kv->get_map_ths=NULL; wtk_mkdir_p(dn,'/',1); //wtk_debug("%s\n",dn); return kv; } void wtk_jsonkv_delete(wtk_jsonkv_t *kv) { wtk_strbuf_delete(kv->tmp); wtk_strbuf_delete(kv->buf); wtk_strbuf_delete(kv->dn); wtk_json_parser_delete(kv->json_parser); wtk_free(kv); } void wtk_jsonkv_set_dn(wtk_jsonkv_t *kv,char *dn) { wtk_strbuf_reset(kv->dn); wtk_strbuf_push(kv->dn,dn,strlen(dn)); wtk_mkdir_p(dn,'/',1); } void wtk_jsonkv_reset(wtk_jsonkv_t *kv) { wtk_json_parser_reset(kv->json_parser); } typedef enum { WTK_JSONKV_ATTR_INIT, WTK_JSONKV_ATTR_K, }wtk_jsonkv_attr_state_t; char* wtk_jsonkv_get_fn(wtk_jsonkv_t *kv,char *k,int k_bytes) { wtk_strbuf_t *buf=kv->buf; wtk_string_t v; wtk_strbuf_reset(buf); wtk_strbuf_push(buf,kv->dn->data,kv->dn->pos); wtk_strbuf_push_c(buf,'/'); if(kv->get_map) { v=kv->get_map(kv->get_map_ths,k,k_bytes); if(v.len>0) { wtk_strbuf_push(buf,v.data,v.len); }else { wtk_strbuf_push(buf,k,k_bytes); } }else { wtk_strbuf_push(buf,k,k_bytes); } wtk_strbuf_push_s(buf,".json"); wtk_strbuf_push_c(buf,0); return buf->data; } wtk_string_t wtk_jsonkv_get_dat(wtk_jsonkv_t *kv,char *k,int k_bytes) { wtk_strbuf_t *buf=kv->buf; char *fn; int ret; wtk_string_t v; char *data=NULL; int len; wtk_string_set(&(v),0,0); fn=wtk_jsonkv_get_fn(kv,k,k_bytes); ret=wtk_file_exist(fn); if(ret!=0){goto end;} data=file_read_buf(buf->data,&len); if(!data){goto end;} wtk_strbuf_reset(buf); wtk_strbuf_push(buf,data,len); wtk_string_set(&(v),data,len); end: if(data) { wtk_free(data); } return v; } void wtk_jsonkv_set_dat(wtk_jsonkv_t *kv,char *k,int k_bytes,char *v,int v_bytes) { char *fn; fn=wtk_jsonkv_get_fn(kv,k,k_bytes); file_write_buf(fn,v,v_bytes); } void wtk_jsonkv_save_json(wtk_jsonkv_t *kv,char *k,int k_bytes,wtk_json_t *json) { char *fn; wtk_strbuf_t *buf2; fn=wtk_jsonkv_get_fn(kv,k,k_bytes); buf2=wtk_strbuf_new(1024,1); wtk_json_item_print(json->main,buf2); // wtk_debug("[%.*s]=%s\n",k_bytes,k,fn); // wtk_debug("%.*s\n",buf2->pos,buf2->data); // exit(0); file_write_buf(fn,buf2->data,buf2->pos); wtk_strbuf_delete(buf2); } wtk_json_t* wtk_jsonkv_get_json(wtk_jsonkv_t *kv,char *k,int k_bytes) { wtk_json_parser_t *json=kv->json_parser; char *fn; int ret; wtk_string_t v; wtk_json_t *xj=NULL; wtk_string_set(&(v),0,0); wtk_json_parser_reset(json); fn=wtk_jsonkv_get_fn(kv,k,k_bytes); ret=wtk_file_exist(fn); //wtk_debug("%s=%d\n",fn,ret); ///exit(0); if(ret==0) { wtk_json_parser_parse_file(json,fn); }else { //wtk_debug("[%.*s] not found.\n",buf->pos,buf->data); //goto end; json->json->main=wtk_json_new_object(json->json); } if(!json->json->main) { wtk_debug("[%s] null.\n",fn); goto end; } xj=json->json; end: return xj; } wtk_string_t wtk_jsonkv_get(wtk_jsonkv_t *kv,char *k,int k_bytes,char *attr,int attr_bytes) { wtk_json_parser_t *json=kv->json_parser; char *fn; int ret; char *s,*e; wtk_string_t nm; wtk_string_t last_nm; int cnt; wtk_jsonkv_attr_state_t state; wtk_json_item_t *item,*parent; wtk_string_t v; int find; wtk_string_set(&(v),0,0); wtk_json_parser_reset(json); fn=wtk_jsonkv_get_fn(kv,k,k_bytes); ret=wtk_file_exist(fn); if(ret==0) { wtk_json_parser_parse_file(json,fn); }else { //wtk_debug("[%.*s] not found.\n",buf->pos,buf->data); goto end; } if(!json->json->main) { wtk_debug("[%s] null.\n",fn); goto end; } s=attr;e=s+attr_bytes; state=WTK_JSONKV_ATTR_INIT; parent=json->json->main; item=NULL; wtk_string_set(&(last_nm),0,0); wtk_string_set(&(nm),0,0); while(s<e) { cnt=wtk_utf8_bytes(*s); find=0; switch(state) { case WTK_JSONKV_ATTR_INIT: if(cnt==1 && isspace(*s)) { }else { nm.data=s; state=WTK_JSONKV_ATTR_K; if(s+cnt>=e) { find=1; nm.len=cnt; } } break; case WTK_JSONKV_ATTR_K: if(cnt==1 &&(isspace(*s) || *s==':')) { find=1; nm.len=s-nm.data; }else if(s+cnt>=e) { find=1; nm.len=s-nm.data+cnt; } break; } if(find) { if(last_nm.len>0) { //wtk_debug("[%.*s]\n",last_nm.len,last_nm.data) item=wtk_json_obj_get(parent,last_nm.data,last_nm.len); if(!item) { wtk_debug("[%.*s] not found\n",last_nm.len,last_nm.data) goto end; } parent=item; } last_nm=nm; state=WTK_JSONKV_ATTR_INIT; } s+=cnt; } //wtk_json_item_print3(parent); if(nm.len>0) { //wtk_debug("[%.*s]\n",nm.len,nm.data); item=wtk_json_obj_get(parent,nm.data,nm.len); if(!item) { if(nm.len==1 && nm.data[0]=='*') { item=parent; }else { goto end; } } }else { item=parent; } //wtk_json_item_print3(item); if(item->type==WTK_JSON_STRING) { v=*(item->v.str); }else { wtk_json_item_print(item,kv->tmp); wtk_string_set(&(v),kv->tmp->data,kv->tmp->pos); } end: return v; } void wtk_jsonkv_set(wtk_jsonkv_t *kv,char *k,int k_bytes,char *attr,int attr_bytes,char *v,int v_bytes) { wtk_json_parser_t *json=kv->json_parser; char *fn; int ret; char *s,*e; wtk_string_t nm = {0}, vx = {0}; wtk_string_t last_nm; int cnt; wtk_jsonkv_attr_state_t state; wtk_json_item_t *item,*parent; int find; wtk_json_parser_reset(json); fn=wtk_jsonkv_get_fn(kv,k,k_bytes); ret=wtk_file_exist(fn); if(ret==0) { wtk_json_parser_parse_file(json,fn); } s=attr;e=s+attr_bytes; state=WTK_JSONKV_ATTR_INIT; if(!json->json->main) { json->json->main=wtk_json_new_object(json->json); } parent=json->json->main; item=NULL; wtk_string_set(&(last_nm),0,0); while(s<e) { cnt=wtk_utf8_bytes(*s); find=0; switch(state) { case WTK_JSONKV_ATTR_INIT: if(cnt==1 && isspace(*s)) { }else { nm.data=s; state=WTK_JSONKV_ATTR_K; if(s+cnt>=e) { find=1; nm.len=cnt; } } break; case WTK_JSONKV_ATTR_K: if(cnt==1 &&(isspace(*s) || *s==':')) { find=1; nm.len=s-nm.data; }else if(s+cnt>=e) { find=1; nm.len=s-nm.data+cnt; } break; } if(find) { if(last_nm.len>0) { //wtk_debug("[%.*s]\n",last_nm.len,last_nm.data) item=wtk_json_obj_get(parent,last_nm.data,last_nm.len); if(!item) { item=wtk_json_new_object(json->json); wtk_json_obj_add_item2(json->json,parent,last_nm.data,last_nm.len,item); } parent=item; } last_nm=nm; state=WTK_JSONKV_ATTR_INIT; } s+=cnt; } // if(parent) // { // wtk_debug("type=%d\n",parent->type); // } // wtk_debug("nm=%.*s\n",nm.len,nm.data); item=wtk_json_obj_get(parent,nm.data,nm.len); if(item) { wtk_string_set(&(vx),v,v_bytes); item->v.str=&(vx); item->type=WTK_JSON_STRING; }else { wtk_string_set(&(vx),v,v_bytes); wtk_json_obj_add_ref_str(json->json,parent,nm.data,nm.len,&(vx)); } //wtk_json_item_print3(json->json->main); wtk_json_print(json->json,kv->tmp); file_write_buf(fn,kv->tmp->data,kv->tmp->pos); } void wtk_jsonkv_test() { wtk_jsonkv_t *kv; wtk_string_t v; kv=wtk_jsonkv_new("jkv"); wtk_jsonkv_set_sss(kv,"lz","name:sex:你好:hello:我","boy"); wtk_jsonkv_set_sss(kv,"lz","name:sex:我","girl"); v=wtk_jsonkv_get_ss(kv,"lz","name"); wtk_debug("[%.*s]\n",v.len,v.data); v=wtk_jsonkv_get_ss(kv,"lz","name:sex:你好:hello:我"); wtk_debug("[%.*s]\n",v.len,v.data); v=wtk_jsonkv_get_ss(kv,"lz","name:sex:我"); wtk_debug("[%.*s]\n",v.len,v.data); v=wtk_jsonkv_get_ss(kv,"lz",""); wtk_debug("[%.*s]\n",v.len,v.data); wtk_jsonkv_delete(kv); } <file_sep>/core/.svn/pristine/06/061634c5154789fcf4299913f7e67ae4cc63f956.svn-base #ifndef WTK_CORE_TEXT_WTK_TXTPEEK #define WTK_CORE_TEXT_WTK_TXTPEEK #include "wtk/core/wtk_type.h" #include "wtk_txtpeek_cfg.h" #include "wtk/core/wtk_strbuf.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_txtpeek wtk_txtpeek_t; typedef enum { WTK_TXTPEEK_EOF, WTK_TXTPEEK_CHN, WTK_TXTPEEK_ENG, WTK_TXTPEEK_NUM, }wtk_txtpeek_item_type_t; typedef struct { wtk_txtpeek_item_type_t type; wtk_string_t v; }wtk_txtpeek_item_t; struct wtk_txtpeek { wtk_txtpeek_cfg_t *cfg; char *s; char *e; }; wtk_txtpeek_t* wtk_txtpeek_new(wtk_txtpeek_cfg_t *cfg); void wtk_txtpeek_delete(wtk_txtpeek_t *p); void wtk_txtpeek_set(wtk_txtpeek_t *p,char *txt,int bytes); wtk_txtpeek_item_t wtk_txtpeek_next(wtk_txtpeek_t *p); void wtk_txtpeek_process(wtk_txtpeek_t *p,char *txt,int bytes,wtk_strbuf_t *buf); #ifdef __cplusplus }; #endif #endif <file_sep>/os/.svn/pristine/76/7679492037c9c3ebcddb5ecb53f18a0918d58c5d.svn-base #ifndef WTK_OS_WTK_THREAD_POOL_H_ #define WTK_OS_WTK_THREAD_POOL_H_ #include "wtk/os/wtk_thread.h" #include "wtk/os/wtk_blockqueue.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_thread_pool wtk_thread_pool_t; typedef int (*thread_pool_handler)(void *user_data,wtk_queue_node_t *n,wtk_thread_t *thread); typedef int (*wtk_thread_pool_init_f)(void *user_data,wtk_thread_t *thread); typedef int (*wtk_thread_pool_clean_f)(void *user_data,wtk_thread_t *thread); typedef void (*wtk_thread_pool_timeout_f)(void *user_data,wtk_thread_t *thread); struct wtk_thread_pool { int thread_num; wtk_thread_t *threads; wtk_blockqueue_t *queue; thread_pool_handler handler; wtk_thread_pool_init_f init; wtk_thread_pool_clean_f clean; wtk_thread_pool_timeout_f timeout_f; int timeout; void *user_data; unsigned run:1; }; wtk_thread_pool_t *wtk_thread_pool_new(int threads,wtk_blockqueue_t *queue, thread_pool_handler handler,void *user_data); wtk_thread_pool_t *wtk_thread_pool_new2(int threads,wtk_blockqueue_t *queue,wtk_thread_pool_init_f init, wtk_thread_pool_clean_f clean,thread_pool_handler handler,void *user_data); int wtk_thread_pool_bytes(wtk_thread_pool_t *t); int wtk_thread_pool_delete(wtk_thread_pool_t *p); void wtk_thread_pool_set_timeout(wtk_thread_pool_t *p,wtk_thread_pool_timeout_f timeout_f,int timeout); int wtk_thread_pool_start(wtk_thread_pool_t *p); int wtk_thread_pool_join(wtk_thread_pool_t *p); int wtk_thread_pool_stop(wtk_thread_pool_t *p); int wtk_thread_pool_kill(wtk_thread_pool_t *p); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_txtree.h #ifndef WTK_CORE_WTK_TXTREE_H_ #define WTK_CORE_WTK_TXTREE_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_queue2.h" #include "wtk/core/wtk_str.h" #include "wtk/core/wtk_str_encode.h" #include "wtk/core/cfg/wtk_source.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_txtree wtk_txtree_t; #define wtk_tnode_is_text_in_s(p,txt) wtk_tnode_is_text_in(p,txt,sizeof(txt)-1) typedef struct { wtk_queue_node_t q_n; wtk_queue2_t child; //wtk_tonde_t queue; char data[3]; //utf-8; unsigned len:7; unsigned is_leaf:1; }wtk_tnode_t; struct wtk_txtree { wtk_tnode_t *root; wtk_heap_t *heap; }; wtk_txtree_t* wtk_txtree_new(); void wtk_txtree_delete(wtk_txtree_t *tree); wtk_tnode_t* wtk_tnode_find_child(wtk_tnode_t *p,char *data,int bytes); void wtk_txtree_add_text(wtk_txtree_t *t,char *txt,int bytes); /** * @return 0 on failed, 1 for text in, and -1 for match the last word; */ int wtk_tnode_is_text_in(wtk_txtree_t *p,char *txt,int bytes); int wtk_txtree_load(wtk_txtree_t *t,wtk_source_t *src); int wtk_txtree_load_file(wtk_txtree_t *t,char *fn); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/bd/bd767d5e4619211b3364b94b2d69bb577327e1f7.svn-base #include "wtk_txtree.h" #include "wtk/core/cfg/wtk_source.h" void wtk_tnode_print(wtk_tnode_t *n) { wtk_queue_node_t *qn; wtk_tnode_t *n2; wtk_debug("=============== %p:child=%d ===================\n",n,wtk_queue2_len(&(n->child))); if(n->len>0) { printf("%.*s\n",n->len,n->data); }else { printf("root\n"); } for(qn=n->child.pop;qn;qn=qn->next) { n2=data_offset(qn,wtk_tnode_t,q_n); wtk_tnode_print(n2); } } wtk_tnode_t* wtk_txtree_new_node(wtk_txtree_t *t,char *data,int len) { wtk_tnode_t *n; int i; n=(wtk_tnode_t*)wtk_heap_malloc(t->heap,sizeof(wtk_tnode_t)); wtk_queue2_init(&(n->child)); n->is_leaf=0; n->len=len; for(i=0;i<len;++i) { n->data[i]=data[i]; } return n; } wtk_txtree_t* wtk_txtree_new() { wtk_txtree_t *t; t=(wtk_txtree_t*)wtk_malloc(sizeof(*t)); t->heap=wtk_heap_new(4096); t->root=wtk_txtree_new_node(t,0,0); return t; } void wtk_txtree_delete(wtk_txtree_t *t) { wtk_heap_delete(t->heap); wtk_free(t); } wtk_tnode_t* wtk_tnode_find_child(wtk_tnode_t *p,char *data,int bytes) { wtk_queue_node_t *n; wtk_tnode_t *n1; for(n=p->child.pop;n;n=n->next) { n1=data_offset(n,wtk_tnode_t,q_n); if(n1->len==bytes && strncmp(data,n1->data,bytes)==0) { return n1; break; } } return 0; } int wtk_tnode_is_text_in(wtk_txtree_t *t,char *txt,int bytes) { char *s,*e; int n; wtk_tnode_t *parent,*node; parent=t->root; s=txt;e=s+bytes; while(s<e) { n=wtk_utf8_bytes(*s); //wtk_tnonde_print(parent); node=wtk_tnode_find_child(parent,s,n); if(!node) { return 0; } parent=node; //wtk_debug("[%.*s]\n",n,s); s+=n; } return parent->is_leaf?-1:1; } void wtk_txtree_add_text(wtk_txtree_t *t,char *txt,int bytes) { char *s,*e; int n; wtk_tnode_t *parent,*node; parent=t->root; s=txt;e=s+bytes; while(s<e) { n=wtk_utf8_bytes(*s); //wtk_tnonde_print(parent); node=wtk_tnode_find_child(parent,s,n); if(!node) { node=wtk_txtree_new_node(t,s,n); wtk_queue2_push(&(parent->child),&(node->q_n)); } parent=node; //wtk_debug("[%.*s]\n",n,s); s+=n; if(s>=e) { node->is_leaf=1; } } } int wtk_txtree_load(wtk_txtree_t *t,wtk_source_t *src) { wtk_strbuf_t *buf; int ret; //wtk_debug("load src\n"); ret=0; buf=wtk_strbuf_new(256,1); while(1) { ret=wtk_source_read_string(src,buf); //wtk_debug("ret=%d\n",ret); if(ret!=0){ret=0;goto end;} //wtk_debug("%.*s\n",buf->pos,buf->data); wtk_txtree_add_text(t,buf->data,buf->pos); } end: wtk_strbuf_delete(buf); return ret; } int wtk_txtree_load_file(wtk_txtree_t *t,char *fn) { return wtk_source_load_file(t,(wtk_source_load_handler_t)wtk_txtree_load,fn); } <file_sep>/study_wwk/makefile pwd=${shell pwd} out_dir=. core_dir=$(pwd)/core os_dir=$(pwd)/os obj_src_dir=$(pwd)/core $(pwd)/os obj_org_src=${shell find $(obj_src_dir) -name "*.c"} obj_src=${filter-out %wtk_select.c,$(obj_org_src)} objs=${patsubst %.c,%.o,${obj_src}} target=libwwk.a TEST=test CC=gcc CFLAGS=-Wall -Werror -g -O3 LDFLAGS= TEST_LD=-I . -L . -lwwk CFLAGS+= ${TEST_LD} -D USE_TCP_NODELAY -D USE_TCP_QUICKACK -DUSE_SQL all: $(target) echo $(target) $(target): $(objs) $(AR) rcs $@ $^ pre: $(core_dir) $(os_dir) # ../third/sqlite/sqlite3.o: ../third/sqlite/sqlite3.c # ${CC} -I. -g -O3 -Wall -funroll-loops -c -o $@ $<; %.o: %.c $(CC) $(CFLAGS) -c -o $@ $< -I .. $(LDFLAGS) test:test.c $(CC) test.c -o ${TEST} $(TEST_LD) clean: -rm $(objs) ${TEST} <file_sep>/core/wtk_strpool.c #include "wtk_strpool.h" wtk_strpool_t* wtk_strpool_new(int nhint) { wtk_strpool_t *p; p=(wtk_strpool_t*)wtk_malloc(sizeof(*p)); p->hash=wtk_str_hash_new(nhint); return p; } void wtk_strpool_delete(wtk_strpool_t *p) { wtk_str_hash_delete(p->hash); wtk_free(p); } int wtk_strpool_bytes(wtk_strpool_t *p) { return wtk_str_hash_bytes(p->hash)+sizeof(wtk_strpool_t); } void wtk_strpool_reset(wtk_strpool_t *p) { wtk_str_hash_reset(p->hash); } wtk_strpool_item_t* wtk_strpool_find_item2(wtk_strpool_t *p,char *v,int v_len,int insert,int *is_new) { wtk_strpool_item_t *item; item=wtk_str_hash_find(p->hash,v,v_len); if(item || insert==0) { if(is_new) { *is_new=0; } goto end; } item=(wtk_strpool_item_t*)wtk_heap_malloc(p->hash->heap,sizeof(wtk_strpool_item_t)); wtk_heap_fill_string(p->hash->heap,&(item->v),v,v_len); //wtk_debug("[%.*s]\n",item->v.len,item->v.data); item->hook=NULL; wtk_str_hash_add(p->hash,item->v.data,item->v.len,item); if(is_new) { *is_new=1; } end: return item; } wtk_strpool_item_t* wtk_strpool_find_item(wtk_strpool_t *p,char *v,int v_len,int insert) { return wtk_strpool_find_item2(p,v,v_len,insert,NULL); } wtk_string_t* wtk_strpool_find(wtk_strpool_t *p,char *v,int v_len,int insert) { wtk_strpool_item_t *item; wtk_string_t *x=0; item=wtk_strpool_find_item(p,v,v_len,insert); if(!item){goto end;} x=&(item->v); end: return x; } <file_sep>/core/.svn/pristine/47/476f07ccdd7ddf7e1f406aca2c3850eb9b8d131c.svn-base #include "wtk_complex.h" int isinvalid(double f) { return isnan(f) || isinf(f); } void wtk_complex_check(wtk_complex_t *c,int n) { int i; for(i=0;i<n;++i) { if(isinvalid(c[i].a) || isinvalid(c[i].b)) { wtk_debug("v[%d]=%f+%fj\n",i,c[i].a,c[i].b); exit(0); } } } float*** wtk_float_new_p3(int n1,int n2,int n3) { float ***c; int i,j; c=(float***)wtk_calloc(n1,sizeof(float***)); for(i=0;i<n1;++i) { c[i]=(float**)wtk_calloc(n2,sizeof(float*)); for(j=0;j<n2;++j) { c[i][j]=(float*)wtk_calloc(n3,sizeof(float)); } } return c; } double*** wtk_double_new_p3(int n1,int n2,int n3) { double ***c; int i,j; c=(double***)wtk_calloc(n1,sizeof(double***)); for(i=0;i<n1;++i) { c[i]=(double**)wtk_calloc(n2,sizeof(double*)); for(j=0;j<n2;++j) { c[i][j]=(double*)wtk_calloc(n3,sizeof(double)); } } return c; } void wtk_float_p3_set(float ***p,int n1,int n2,int n3,float v) { int i,j,k; float **p2; float *p1; for(i=0;i<n1;++i) { p2=p[i]; for(j=0;j<n2;++j) { p1=p2[j]; for(k=0;k<n3;++k) { p1[k]=v; } } } } void wtk_double_p3_set(double ***p,int n1,int n2,int n3,float v) { int i,j,k; double **p2; double *p1; for(i=0;i<n1;++i) { p2=p[i]; for(j=0;j<n2;++j) { p1=p2[j]; for(k=0;k<n3;++k) { p1[k]=v; } } } } void wtk_float_delete_p3(float ***pf,int n1,int n2) { int i,j; for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { wtk_free(pf[i][j]); } wtk_free(pf[i]); } wtk_free(pf); } void wtk_double_delete_p3(double ***pf,int n1,int n2) { int i,j; for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { wtk_free(pf[i][j]); } wtk_free(pf[i]); } wtk_free(pf); } void wtk_float_delete_p2(float **pf,int n1) { int i; for(i=0;i<n1;++i) { wtk_free(pf[i]); } wtk_free(pf); } void wtk_double_delete_p2(double **pf,int n1) { int i; for(i=0;i<n1;++i) { wtk_free(pf[i]); } wtk_free(pf); } float** wtk_float_new_p2(int n1,int n2) { float **c; int i; c=(float**)wtk_calloc(n1,sizeof(float*)); for(i=0;i<n1;++i) { c[i]=(float*)wtk_calloc(n2,sizeof(float)); } return c; } void wtk_float_p2_zero(float **p,int n1,int n2) { int i,nx; nx=n2*sizeof(float); for(i=0;i<n1;++i) { memset(p[i],0,nx); } } void wtk_double_p2_zero(double **p,int n1,int n2) { int i,nx; nx=n2*sizeof(double); for(i=0;i<n1;++i) { memset(p[i],0,nx); } } double** wtk_double_new_p2(int n1,int n2) { double **c; int i; c=(double**)wtk_calloc(n1,sizeof(double*)); for(i=0;i<n1;++i) { c[i]=(double*)wtk_calloc(n2,sizeof(double)); } return c; } wtk_complex_t** wtk_complex_new_p2(int n1,int n2) { wtk_complex_t **c; int i; c=(wtk_complex_t**)wtk_calloc(n1,sizeof(wtk_complex_t*)); for(i=0;i<n1;++i) { c[i]=(wtk_complex_t*)wtk_calloc(n2,sizeof(wtk_complex_t)); } return c; } wtk_dcomplex_t** wtk_dcomplex_new_p2(int n1,int n2) { wtk_dcomplex_t **c; int i; c=(wtk_dcomplex_t**)wtk_calloc(n1,sizeof(wtk_dcomplex_t*)); for(i=0;i<n1;++i) { c[i]=(wtk_dcomplex_t*)wtk_calloc(n2,sizeof(wtk_dcomplex_t)); } return c; } void wtk_complex_eye(wtk_complex_t **p,int n,wtk_complex_t v) { int i; int nx; nx=n*sizeof(wtk_complex_t); for(i=0;i<n;++i) { memset(p[i],0,nx); p[i][i]=v; } } void wtk_complex_eye3(wtk_complex_t **p,int n) { wtk_complex_t v; v.a=1; v.b=0; wtk_complex_eye(p,n,v); } void wtk_complex_eye2(wtk_complex_t *p,int n) { int i; int nx; wtk_complex_t v={1,0}; nx=n*sizeof(wtk_complex_t); for(i=0;i<n;++i) { memset(p,0,nx); p[i]=v; p+=n; } } void wtk_dcomplex_eye(wtk_dcomplex_t **p,int n,wtk_dcomplex_t v) { int i; int nx; nx=n*sizeof(wtk_dcomplex_t); for(i=0;i<n;++i) { memset(p[i],0,nx); p[i][i]=v; } } void wtk_dcomplex_eye2(wtk_dcomplex_t **p,int n) { wtk_dcomplex_t v={1,0}; wtk_dcomplex_eye(p,n,v); } void wtk_complex_delete_p2(wtk_complex_t **p2,int n1) { int i; for(i=0;i<n1;++i) { wtk_free(p2[i]); } wtk_free(p2); } void wtk_dcomplex_delete_p2(wtk_dcomplex_t **p2,int n1) { int i; for(i=0;i<n1;++i) { wtk_free(p2[i]); } wtk_free(p2); } void wtk_complex_delete_p3(wtk_complex_t ***p3,int n1,int n2) { int i,j; for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { wtk_free(p3[i][j]); } wtk_free(p3[i]); } wtk_free(p3); } wtk_complex_t*** wtk_complex_new_p3(int n1,int n2,int n3) { wtk_complex_t ***c; wtk_complex_t **p; int i,j; c=(wtk_complex_t***)wtk_calloc(n1,sizeof(wtk_complex_t***)); for(i=0;i<n1;++i) { p=c[i]=(wtk_complex_t**)wtk_calloc(n2,sizeof(wtk_complex_t*)); for(j=0;j<n2;++j) { //c[i][j]=(wtk_complex_t*)wtk_calloc(n3,sizeof(wtk_complex_t)); p[j]=(wtk_complex_t*)wtk_calloc(n3,sizeof(wtk_complex_t)); } } return c; } void wtk_complex_zero_p3(wtk_complex_t ***p,int n1,int n2,int n3) { int i,j; int t; wtk_complex_t **p2; t=n3*sizeof(wtk_complex_t); for(i=0;i<n1;++i) { p2=p[i]; for(j=0;j<n2;++j) { memset(p2[j],0,t); } } } void wtk_dcomplex_zero_p3(wtk_dcomplex_t ***p,int n1,int n2,int n3) { int i,j; int t; wtk_dcomplex_t **p2; t=n3*sizeof(wtk_dcomplex_t); for(i=0;i<n1;++i) { p2=p[i]; for(j=0;j<n2;++j) { memset(p2[j],0,t); } } } void wtk_complex_cpy_p2(wtk_complex_t **dst,wtk_complex_t **src,int n1,int n2) { int i; int t; t=n2*sizeof(wtk_complex_t); for(i=0;i<n1;++i) { memcpy(dst[i],src[i],t); } } void wtk_complex_cpy_diag(wtk_complex_t **dst,wtk_complex_t **src,int n1) { int i,j; for(i=0;i<n1;++i) { for(j=i;j<n1;++j) { dst[i][j]=src[i][j]; if(j!=i) { dst[j][i]=src[i][j]; } } } } void wtk_complex_cpy_p3(wtk_complex_t ***dst,wtk_complex_t ***src,int n1,int n2,int n3) { int i,j; int t; t=n3*sizeof(wtk_complex_t); for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { memcpy(dst[i][j],src[i][j],t); } } } void wtk_dcomplex_cpy_p3(wtk_dcomplex_t ***dst,wtk_complex_t ***src,int n1,int n2,int n3) { int i,j,k; //wtk_complex_t **src1,*src2; //wtk_dcomplex_t **dst1,*dst2; for(i=0;i<n1;++i) { //src1=src[i]; for(j=0;j<n2;++j) { //src2=src1[j]; for(k=0;k<n3;++k) { dst[i][j][k].a=src[i][j][k].a; dst[i][j][k].b=src[i][j][k].b; } } } } void wtk_complex_cpy_p4(wtk_complex_t ***dst,wtk_dcomplex_t ***src,int n1,int n2,int n3) { int i,j,k; for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { for(k=0;k<n3;++k) { dst[i][j][k].a=src[i][j][k].a; dst[i][j][k].b=src[i][j][k].b; } } } } void wtk_complex_zero_p2(wtk_complex_t **p,int n1,int n2) { int i,t; t=n2*sizeof(wtk_complex_t); for(i=0;i<n1;++i) { memset(p[i],0,t); } } void wtk_dcomplex_zero_p2(wtk_dcomplex_t **p,int n1,int n2) { int i; int t; t=n2*sizeof(wtk_dcomplex_t); for(i=0;i<n1;++i) { memset(p[i],0,t); } } int wtk_dcomplex_guass_elimination(wtk_dcomplex_t **a,wtk_dcomplex_t **b,int n1,int n2) { int i,j,k; double f; wtk_dcomplex_t *pa,*pb; double fa,fb,fa1,fb1; fb=0; for(i=0;i<n1;++i) { //(a+bi)/(c+di)=(a+bi)(c-di)/(c*c+d*d)=(ac+bd)+i(-ad+bc)/(c*c+d*d) pa=a[i]+i; if(pa->b==0) { if(pa->a==0) { return -1; } fa=1.0/pa->a; pa->a=1; pa->b=0; j=i+1; ++pa; for(;j<n1;++j,++pa) { pa->a*=fa; pa->b*=fa; } pa=b[i]; for(j=0;j<n2;++j,++pa) { pa->a*=fa; pa->b*=fa; } }else { f=(pa->a*pa->a+pa->b*pa->b); if(f==0) { return -1; } fa=pa->a/f; fb=-pa->b/f; pa->a=1; pa->b=0; j=i+1; ++pa; for(;j<n1;++j,++pa) { //d*c=(a+bi)(c+di)=(ac-bd)+i(ad+bc); fa1=pa->a; fb1=pa->b; pa->a=fa1*fa -fb1*fb; pa->b=fa1*fb+fb1*fa; } pa=b[i]; for(j=0;j<n2;++j,++pa) { fa1=pa->a; fb1=pa->b; pa->a=fa1*fa -fb1*fb; pa->b=fa1*fb+fb1*fa; } } for(j=i+1;j<n1;++j) { fa=a[j][i].a; fb=a[j][i].b; if(fb==0) { pa=a[i]+i; pb=a[j]+i; for(k=i;k<n1;++k,++pa,++pb) { pb->a-=pa->a*fa; pb->b-=pa->b*fa; } pa=b[i]; pb=b[j]; for(k=0;k<n2;++k,++pa,++pb) { pb->a-=pa->a*fa; pb->b-=pa->b*fa; } }else { pa=a[i]+i; pb=a[j]+i; for(k=i;k<n1;++k,++pa,++pb) { pb->a-=pa->a*fa -pa->b*fb; pb->b-=pa->a*fb+pa->b*fa; } pa=b[i]; pb=b[j]; for(k=0;k<n2;++k,++pa,++pb) { pb->a-=pa->a*fa -pa->b*fb; pb->b-=pa->a*fb+pa->b*fa; } } } } for(i=n1-1;i>=0;--i) { for(j=0;j<i;++j) { fa=a[j][i].a; fb=a[j][i].b; if(fb==0) { pa=b[i]; pb=b[j]; for(k=0;k<n2;++k,++pa,++pb) { pb->a-=pa->a*fa; pb->b-=pa->b*fa; } }else { pa=b[i]; pb=b[j]; for(k=0;k<n2;++k,++pa,++pb) { pb->a-=pa->a*fa -pa->b*fb; pb->b-=pa->a*fb+pa->b*fa; } } } } return 0; } int wtk_complex_guass_elimination_p1(wtk_complex_t *a,wtk_complex_t *b,int n1,int n2) { int i,j,k; double f; wtk_complex_t *pa,*pb; float fa,fb; float fa1,fb1; for(i=0;i<n1;++i) { pa=a+i*(n1+1); if(pa->b==0) { if(pa->a==0) { return -1; } fa=1.0/pa->a; pa->a=1; j=i+1; ++pa; for(;j<n1;++j,++pa) { pa->a*=fa; pa->b*=fa; } pa=b+i*n2; for(j=0;j<n2;++j,++pa) { pa->a*=fa; pa->b*=fa; } }else { f=(pa->a*pa->a+pa->b*pa->b); if(f==0) { return -1; } fa=pa->a/f; fb=-pa->b/f; pa->a=1; pa->b=0; j=i+1; ++pa; for(;j<n1;++j,++pa) { fa1=pa->a; fb1=pa->b; pa->a=fa1*fa -fb1*fb; pa->b=fa1*fb+fb1*fa; } pa=b+i*n2; for(j=0;j<n2;++j,++pa) { fa1=pa->a; fb1=pa->b; pa->a=fa1*fa -fb1*fb; pa->b=fa1*fb+fb1*fa; } } for(j=i+1;j<n1;++j) { fa=a[j*n1+i].a; fb=a[j*n1+i].b; if(fb==0) { pa=a+i*n1+i; pb=a+j*n1+i; for(k=i;k<n1;++k,++pa,++pb) { pb->a-=pa->a*fa; pb->b-=pa->b*fa; } pa=b+i*n2; pb=b+j*n2; for(k=0;k<n2;++k,++pa,++pb) { pb->a-=pa->a*fa; pb->b-=pa->b*fa; } }else { pa=a+i*n1+i; pb=a+j*n1+i; for(k=i;k<n1;++k,++pa,++pb) { pb->a-=pa->a*fa -pa->b*fb; pb->b-=pa->a*fb+pa->b*fa; } pa=b+i*n2; pb=b+j*n2; for(k=0;k<n2;++k,++pa,++pb) { pb->a-=pa->a*fa -pa->b*fb; pb->b-=pa->a*fb+pa->b*fa; } } } } for(i=n1-1;i>=0;--i) { for(j=0;j<i;++j) { fa=a[j*n1+i].a; fb=a[j*n1+i].b; if(fb==0) { pa=b+i*n2; pb=b+j*n2; for(k=0;k<n2;++k,++pa,++pb) { pb->a-=pa->a*fa; pb->b-=pa->b*fa; } }else { pa=b+i*n2; pb=b+j*n2; for(k=0;k<n2;++k,++pa,++pb) { pb->a-=pa->a*fa -pa->b*fb; pb->b-=pa->a*fb+pa->b*fa; } } } } return 0; } void wtk_complex_guass_elimination(wtk_complex_t **a,wtk_complex_t **b,int n1,int n2) { int i,j,k; double f; wtk_complex_t *pa,*pb; float fa,fb; float fa1,fb1; fb=0; for(i=0;i<n1;++i) { //(a+bi)/(c+di)=(a+bi)(c-di)/(c*c+d*d)=(ac+bd)+i(-ad+bc)/(c*c+d*d) pa=a[i]+i; if(pa->b==0) { fa=1.0/pa->a; pa->a=1; j=i+1; ++pa; for(;j<n1;++j,++pa) { pa->a*=fa; pa->b*=fa; } pa=b[i]; for(j=0;j<n2;++j,++pa) { pa->a*=fa; pa->b*=fa; } }else { f=(pa->a*pa->a+pa->b*pa->b); fa=pa->a/f; fb=-pa->b/f; pa->a=1; pa->b=0; j=i+1; ++pa; for(;j<n1;++j,++pa) { //d*c=(a+bi)(c+di)=(ac-bd)+i(ad+bc); fa1=pa->a; fb1=pa->b; pa->a=fa1*fa -fb1*fb; pa->b=fa1*fb+fb1*fa; } pa=b[i]; for(j=0;j<n2;++j,++pa) { fa1=pa->a; fb1=pa->b; pa->a=fa1*fa -fb1*fb; pa->b=fa1*fb+fb1*fa; } } for(j=i+1;j<n1;++j) { fa=a[j][i].a; fb=a[j][i].b; if(fb==0) { pa=a[i]+i; pb=a[j]+i; for(k=i;k<n1;++k,++pa,++pb) { pb->a-=pa->a*fa; pb->b-=pa->b*fa; } pa=b[i]; pb=b[j]; for(k=0;k<n2;++k,++pa,++pb) { pb->a-=pa->a*fa; pb->b-=pa->b*fa; } }else { pa=a[i]+i; pb=a[j]+i; for(k=i;k<n1;++k,++pa,++pb) { pb->a-=pa->a*fa -pa->b*fb; pb->b-=pa->a*fb+pa->b*fa; } pa=b[i]; pb=b[j]; for(k=0;k<n2;++k,++pa,++pb) { pb->a-=pa->a*fa -pa->b*fb; pb->b-=pa->a*fb+pa->b*fa; } } } } for(i=n1-1;i>=0;--i) { for(j=0;j<i;++j) { fa=a[j][i].a; fb=a[j][i].b; if(fb==0) { pa=b[i]; pb=b[j]; for(k=0;k<n2;++k,++pa,++pb) { pb->a-=pa->a*fa; pb->b-=pa->b*fa; } }else { pa=b[i]; pb=b[j]; for(k=0;k<n2;++k,++pa,++pb) { pb->a-=pa->a*fa -pa->b*fb; pb->b-=pa->a*fb+pa->b*fa; } } } } } void wtk_complex_guass_elimination_raw(wtk_complex_t **a,wtk_complex_t **b,int n1,int n2) { int i,j,k; wtk_complex_t c,d; double f; wtk_complex_t *pa,*pb; for(i=0;i<n1;++i) { //(a+bi)/(c+di)=(a+bi)(c-di)/(c*c+d*d)=(ac+bd)+i(-ad+bc)/(c*c+d*d) pa=a[i]; f=(pa[i].a*pa[i].a+pa[i].b*pa[i].b); c.a=pa[i].a/f; c.b=-pa[i].b/f; for(j=i;j<n1;++j) { //d*c=(a+bi)(c+di)=(ac-bd)+i(ad+bc); d=pa[j]; pa[j].a=d.a*c.a -d.b*c.b; pa[j].b=d.a*c.b+d.b*c.a; } pa=b[i]; for(j=0;j<n2;++j) { d=pa[j]; pa[j].a=d.a*c.a -d.b*c.b; pa[j].b=d.a*c.b+d.b*c.a; } for(j=i+1;j<n1;++j) { c=a[j][i]; pa=a[i]; pb=a[j]; for(k=i;k<n1;++k) { d=pa[k]; pb[k].a-=d.a*c.a -d.b*c.b; pb[k].b-=d.a*c.b+d.b*c.a; } pa=b[i]; pb=b[j]; for(k=0;k<n2;++k) { d=pa[k]; pb[k].a-=d.a*c.a -d.b*c.b; pb[k].b-=d.a*c.b+d.b*c.a; } } } for(i=n1-1;i>=0;--i) { for(j=0;j<i;++j) { c=a[j][i]; pa=b[i]; pb=b[j]; for(k=0;k<n2;++k) { d=pa[k]; pb[k].a-=d.a*c.a -d.b*c.b; pb[k].b-=d.a*c.b+d.b*c.a; } } } } void wtk_complex_p2_scale_add(wtk_complex_t **dst,wtk_complex_t **src,int n1,int n2,float f1) { int i,j; float f2; wtk_complex_t *p1,*p2; f2=1-f1; for(i=0;i<n1;++i) { p1=dst[i]; p2=src[i]; for(j=0;j<n2;++j) { p1[j].a=p1[j].a*f2+f1*p2[j].a; p1[j].b=p1[j].b*f2+f1*p2[j].b; } } } void wtk_complex_p2_cpy(wtk_complex_t **dst,wtk_complex_t **src,int n1,int n2) { int i; int t; t=n2*sizeof(wtk_complex_t); for(i=0;i<n1;++i) { memcpy(dst[i],src[i],t); } } void wtk_complex_p2_cpy2(wtk_dcomplex_t **dst,wtk_complex_t **src,int n1,int n2) { int i,j; for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { dst[i][j].a=src[i][j].a; dst[i][j].b=src[i][j].b; } } } wtk_complex_t**** wtk_complex_new_p4(int n1,int n2,int n3,int n4) { wtk_complex_t ****c; int i,j,k; c=(wtk_complex_t****)wtk_calloc(n1,sizeof(wtk_complex_t****)); for(i=0;i<n1;++i) { c[i]=(wtk_complex_t***)wtk_calloc(n2,sizeof(wtk_complex_t**)); for(j=0;j<n2;++j) { c[i][j]=(wtk_complex_t**)wtk_calloc(n3,sizeof(wtk_complex_t*)); for(k=0;k<n3;++k) { c[i][j][k]=(wtk_complex_t*)wtk_calloc(n4,sizeof(wtk_complex_t)); } } } return c; } wtk_dcomplex_t**** wtk_dcomplex_new_p4(int n1,int n2,int n3,int n4) { wtk_dcomplex_t ****c; int i,j,k; c=(wtk_dcomplex_t****)wtk_calloc(n1,sizeof(wtk_dcomplex_t****)); for(i=0;i<n1;++i) { c[i]=(wtk_dcomplex_t***)wtk_calloc(n2,sizeof(wtk_dcomplex_t**)); for(j=0;j<n2;++j) { c[i][j]=(wtk_dcomplex_t**)wtk_calloc(n3,sizeof(wtk_dcomplex_t*)); for(k=0;k<n3;++k) { c[i][j][k]=(wtk_dcomplex_t*)wtk_calloc(n4,sizeof(wtk_dcomplex_t)); } } } return c; } void wtk_complex_delete_p4(wtk_complex_t ****p,int n1,int n2,int n3) { int i,j,k; for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { for(k=0;k<n3;++k) { wtk_free(p[i][j][k]); } wtk_free(p[i][j]); } wtk_free(p[i]); } wtk_free(p); } float wtk_complex_p2_max_abs(wtk_complex_t **p,int n1,int n2) { float t,maxt; int i,j; maxt=0; for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { t=p[i][j].a*p[i][j].a+p[i][j].b+p[i][j].b; if(t>maxt) { maxt=t; } } } return sqrt(maxt); } float wtk_complex_p2_dist(wtk_complex_t **p1,wtk_complex_t **p2,int n1,int n2) { double t; int i,j; float ta,tb; wtk_complex_t *pp1,*pp2; t=0; for(i=0;i<n1;++i) { pp1=p1[i]; pp2=p2[i]; for(j=0;j<n2;++j) { ta=pp1[j].a-pp2[j].a; tb=pp1[j].b-pp2[j].b; if(isnan(ta) || isnan(tb)) { wtk_debug("ta=%f tb=%f %f/%f %f/%f\n",ta,tb,pp1[j].a,pp1[j].b,pp2[j].a,pp2[j].b); exit(0); } t+=ta*ta+tb*tb; } } return sqrt(t); } #ifdef PI #undef PI #endif #define PI 3.1415926535897932384626433832795 float wtk_complex_p2_angle(wtk_complex_t **p1,wtk_complex_t **p2,int n1,int n2) { double t,ta,tb; int i,j; wtk_complex_t *pp1,*pp2; t=0; ta=tb=0; for(i=0;i<n1;++i) { pp1=p1[i]; pp2=p2[i]; for(j=0;j<n2;++j) { //pp1*pp2 //(a+bi)(c+di)=(ac-bd)+i(ad+bd); ta+=pp1[j].a*pp2[j].a - pp1[j].b*pp2[j].b; tb+=pp1[j].a*pp2[j].b + pp1[j].b*pp2[j].a; t+=pp1[j].a*pp1[j].a; t+=pp1[j].b*pp1[j].b; t+=pp2[j].a*pp2[j].a; t+=pp2[j].b*pp2[j].b; } } t=sqrt(t); wtk_debug("ta=%f tb=%f t=%f\n",ta,tb,t); ta=sqrt(ta*ta+tb*tb); //t=ta/t; wtk_debug("f=%f %f\n",ta/t,acos(ta/t)); t=acos(ta/t)*180/PI; //wtk_debug("ta=%f tb=%f t=%f\n",ta,tb,t); return t; } void wtk_complex_p2_mul(wtk_complex_t **p,int n1,int n2,float f) { int i,j; wtk_complex_t *c; for(i=0;i<n1;++i) { c=p[i]; for(j=0;j<n2;++j) { c[j].a*=f; c[j].b*=f; } } } void wtk_complex_identity(wtk_complex_t *a,int n) { int i; memset(a,0,n*n*sizeof(wtk_complex_t)); for(i=0;i<n;++i) { a[i*n+i].a=1; } } void wtk_dcmplex_p2_mul(wtk_dcomplex_t **p,int n1,int n2,float f) { int i,j; wtk_dcomplex_t *c; for(i=0;i<n1;++i) { c=p[i]; for(j=0;j<n2;++j) { c[j].a*=f; c[j].b*=f; } } } void wtk_complex_print(wtk_complex_t *c,int n) { int i; float a,b; a=b=0; for(i=0;i<n;++i) { //wtk_debug("v[%d]=%.4f+%.4fi\n",i,c[i].a,c[i].b); a+=c[i].a; b+=c[i].b; wtk_debug("v[%d]=%.8f+%.8fi\n",i,c[i].a,c[i].b); //wtk_debug("v[%d]=%e+%ei\n",i,c[i].a,c[i].b); } wtk_debug("tot=%f+%fi\n\n",a,b); } wtk_complex_t wtk_complex_p2_sum(wtk_complex_t **c,int n1,int n2) { int i,j; wtk_complex_t b; float ta,tb; ta=tb=0; for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { ta+=c[i][j].a; tb+=c[i][j].b; } } b.a=ta; b.b=tb; return b; } void wtk_complex_print3(wtk_complex_t **c,int r,int col) { int i,j; float a,b; wtk_debug("------------- complex[%d,%d] --------------\n",r,col); a=b=0; for(i=0;i<r;++i) { for(j=0;j<col;++j) { if(j>0) { printf(" "); } a+=c[i][j].a; b+=c[i][j].b; printf("%f+%fj",c[i][j].a,c[i][j].b); //wtk_debug("v[%d,%d]=%f+j%f\n",i,j,c[i][j].a,c[i][j].b); } printf("\n"); } wtk_debug("--------- tot=%f+%fi ----------\n",a,b); } void wtk_complex_print2(wtk_complex_t *c,int r,int col) { int i,j; int k=0; wtk_dcomplex_t x; float f=1;//10000; int use_e=0; //f=1000; //f=10000; x.a=0; x.b=0; for(i=0;i<r;++i) { for(j=0;j<col;++j) { x.a+=c[k].a; x.b+=c[k].b; if(j>0) { printf("\t"); } if(c[k].b>=0) { if(use_e) { printf("%e + %ei",c[k].a*f,c[k].b*f); }else { printf("%.8f + %.8fi",c[k].a*f,c[k].b*f); } }else { if(use_e) { printf("%e - %ei",c[k].a*f,-c[k].b*f); }else { printf("%.8f + %.8fi",c[k].a*f,c[k].b*f); } } ++k; } printf("\n"); } wtk_debug("tot: %e+i%e\n\n",x.a,x.b); } void wtk_dcomplex_print(wtk_dcomplex_t *c,int n) { double ta,tb; int i; ta=tb=0; for(i=0;i<n;++i) { ta+=c[i].a; tb+=c[i].b; wtk_debug("v[%d]=%.10f+%.10fi\n",i,c[i].a,c[i].b); } wtk_debug("tot=%f+%fi\n",ta,tb); } void wtk_dcomplex_p2_print(wtk_dcomplex_t **c,int n1,int n2) { int i,j; double ta,tb; ta=tb=0; for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { // if(j>0) // { // printf(" "); // } // printf("%e+%e",c[i][j].a,c[i][j].b); wtk_debug("v[%d/%d]=%.10f+%.10fi\n",i,j,c[i][j].a,c[i][j].b); //wtk_debug("v[%d/%d]=%f+%fi\n",i,j,c[i][j].a,c[i][j].b); ta+=c[i][j].a; tb+=c[i][j].b; } //printf("\n"); } wtk_debug("tot=%f+%fi\n",ta,tb); } void wtk_dcomplex_p2_print2(wtk_dcomplex_t **c,int n1,int n2) { int i,j; for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { if(j>0) { printf(" "); } //printf("%e",c[i][j].a); //printf("%e+%e",c[i][j].a,c[i][j].b); //printf("%.4f+%.4f",c[i][j].a,c[i][j].b); printf("%f",c[i][j].a); //wtk_debug("v[%d/%d]=%f+%fi\n",i,j,c[i][j].a,c[i][j].b); //wtk_debug("v[%d/%d]=%f+%fi\n",i,j,c[i][j].a,c[i][j].b); } printf("\n"); //printf(";"); } } void wtk_complex_mult(wtk_complex_t **c,int n1,int n2,float f) { int i,j; wtk_complex_t *pc; for(i=0;i<n1;++i) { pc=c[i]; for(j=0;j<n2;++j) { pc[j].a*=f; pc[j].b*=f; } } } void wtk_complex3_mult(wtk_complex_t ***c,int n1,int n2,int n3,float f) { int i,j,k; wtk_complex_t **cc1,*c1; for(i=0;i<n1;++i) { cc1=c[i]; for(j=0;j<n2;++j) { c1=cc1[j]; for(k=0;k<n3;++k) { c1[k].a*=f; c1[k].b*=f; } } } } void wtk_dcomplex_mult(wtk_dcomplex_t **c,int n1,int n2,float f) { int i,j; wtk_dcomplex_t *pc; for(i=0;i<n1;++i) { pc=c[i]; for(j=0;j<n2;++j) { pc[j].a*=f; pc[j].b*=f; } } } void wtk_dcomplex_print3(wtk_dcomplex_t **c,int r,int col) { int i,j; wtk_debug("==================================\n"); for(i=0;i<r;++i) { for(j=0;j<col;++j) { wtk_debug("v[%d,%d]=%f+j%f\n",i,j,c[i][j].a,c[i][j].b); } } } void wtk_dcomplex_print4(wtk_dcomplex_t **c,int r,int col) { int i,j; wtk_debug("==================================\n"); for(i=0;i<r;++i) { for(j=0;j<col;++j) { if(j>0) { printf(" "); } printf("%f+%fi",c[i][j].a,c[i][j].b); //wtk_debug("v[%d,%d]=%f+j%f\n",i,j,c[i][j].a,c[i][j].b); } printf("\n"); } } void wtk_dcomplex_print2(wtk_dcomplex_t *c,int r,int col) { int i,j; int k=0; wtk_dcomplex_t x; float f=1;//10000; int b=1; //b=0; //f=1000; x.a=0; x.b=0; for(i=0;i<r;++i) { for(j=0;j<col;++j) { x.a+=c[k].a; x.b+=c[k].b; if(j>0) { printf(" "); } if(b) { if(c[k].b>=0) { printf("%.6f + %.6fi",c[k].a*f,c[k].b*f); }else { printf("%.6f - %.6fi",c[k].a*f,-c[k].b*f); } }else { if(c[k].b>=0) { printf("%.6f+%.6fi",c[k].a*f,c[k].b*f); }else { printf("%.6f-%.6fi",c[k].a*f,-c[k].b*f); } } ++k; } if(b) { printf("\n"); }else { printf(";"); } } printf("\n"); wtk_debug("tot: %e+i%e\n\n",x.a,x.b); } wtk_complex_t wtk_complex_div(wtk_complex_t *a,wtk_complex_t *b) { float f; wtk_complex_t c; f=1.0/(b->a*b->a+b->b*b->b); c.a=(a->a*b->a+a->b*b->b)*f;//(xc*xc+xd*xd); c.b=(a->b*b->a-a->a*b->b)*f;//(xc*xc+xd*xd); return c; } wtk_complex_t wtk_complex_mul(wtk_complex_t *a,wtk_complex_t *b) { wtk_complex_t c; //a+bi c+di => ac-bd +i ad+bc c.a=a->a*b->a - a->b*b->b; c.b=a->a*b->b + a->b*b->a; return c; } wtk_dcomplex_t wtk_dcomplex_mul(wtk_dcomplex_t *a,wtk_complex_t *b) { wtk_dcomplex_t c; //a+bi c+di => ac-bd +i ad+bc c.a=a->a*b->a - a->b*b->b; c.b=a->a*b->b + a->b*b->a; return c; } wtk_dcomplex_t wtk_dcomplex_mul2(wtk_dcomplex_t *a,wtk_dcomplex_t *b) { wtk_dcomplex_t c; //a+bi c+di => ac-bd +i ad+bc c.a=a->a*b->a - a->b*b->b; c.b=a->a*b->b + a->b*b->a; return c; } //c+=|a*b| void wtk_complex_add_mul(wtk_complex_t *c,wtk_complex_t *a,wtk_complex_t *b) { //a+bi c+di => ac-bd +i ad+bc c->a+=a->a*b->a - a->b*b->b; c->b+=a->a*b->b + a->b*b->a; } void wtk_complex_sub(wtk_complex_t *a,wtk_complex_t b) { a->a-=b.a; a->b-=b.b; } //a=b*c |1*4|*|4*2| void wtk_complex_matrix_mul(wtk_complex_t *a,wtk_complex_t *b,wtk_complex_t *c,int row,int col,int col2) { int i,j,k; wtk_complex_t *x; wtk_complex_t t; for(i=0;i<row;++i) { x=b+i*row; for(j=0;j<col2;++j) { t.a=t.b=0; for(k=0;k<col;++k) { //x[k] c[k][j] wtk_complex_add_mul(&(t),x+k,c+k*col2+j); } //a[i][j]=t; a[i*col2+j]=t; //wtk_debug("v[%d/%d]=%f/%f\n",i,j,t.a,t.b); //exit(0); } } } /** * A=alpha*A+(1-alpha)*B; */ void wtk_complex_matrix_add(wtk_complex_t **a,wtk_complex_t **b,float alpha,int r,int c) { float alpha2=1-alpha; int i,j; wtk_complex_t *ca,*cb; for(i=0;i<r;++i) { ca=a[i]; cb=b[i]; for(j=0;j<c;++j) { //a[i][j]=a[i][j]*alpha+b[i][j]*alpha2; ca[j].a=ca[j].a*alpha+cb[j].a*alpha2; ca[j].b=ca[j].b*alpha+cb[j].b*alpha2; } } } void wtk_complex_matrix_mul2(wtk_complex_t **a,wtk_complex_t **b,wtk_complex_t **c,int row,int col,int col2) { int i,j,k; float ta,tb; wtk_complex_t *pa; wtk_complex_t *a1,*b1,*c1; for(i=0;i<row;++i) { pa=a[i]; c1=c[i]; for(j=0;j<col2;++j) { ta=tb=0; a1=pa; for(k=0;k<col;++k) { //pa[k]*b[k][j] //(a+bi)*(c+di)=(ac-bd)+i(ad+bc); //ta+=pa[k].a*b[k][j].a - pa[k].b*b[k][j].b; //tb+=pa[k].a*b[k][j].b+pa[k].b*b[k][j].a; b1=b[k]+j; ta+=a1->a*b1->a - a1->b*b1->b; tb+=a1->a*b1->b+a1->b*b1->a; ++a1; } //wtk_debug("i=%d j=%d\n",i,j); c1[j].a=ta; c1[j].b=tb; } } } void wtk_dcomplex_matrix_mul(wtk_dcomplex_t **a,wtk_dcomplex_t **b,wtk_dcomplex_t **c,int row,int col,int col2) { int i,j,k; double ta,tb; wtk_dcomplex_t *pa; for(i=0;i<row;++i) { pa=a[i]; for(j=0;j<col2;++j) { ta=tb=0; for(k=0;k<col;++k) { //pa[k]*b[k][j] //(a+bi)*(c+di)=(ac-bd)+i(ad+bc); ta+=pa[k].a*b[k][j].a - pa[k].b*b[k][j].b; tb+=pa[k].a*b[k][j].b+pa[k].b*b[k][j].a; } c[i][j].a=ta; c[i][j].b=tb; } } } void print_complex(wtk_complex_t *c,int n) { int i; for(i=0;i<n;++i) { wtk_debug("v[%d]=%f+i%f\n",i,c[i].a,c[i].b); } } //a=b*c |1*4|*|4*2| void wtk_complexa_matrix_mul(wtk_complexa_t *a,wtk_complexa_t *b,wtk_complexa_t *c,int row,int col,int col2) { int i,j,k; //wtk_complex_t t; float xa,xb; int idx,idx2; int rowi; for(i=0,rowi=0;i<row;++i,rowi+=row) { //x=b+i*row; for(j=0;j<col2;++j) { xa=xb=0; for(k=0;k<col;++k) { //x[k] c[k][j] //wtk_complex_add_mul(&(t),x+k,c+k*col2+j); idx=rowi+k; idx2=k*col2+j; xa+=b->a[idx]*c->a[idx2] - b->b[idx]*c->b[idx2]; xb+=b->a[idx]*c->b[idx2] + b->b[idx]*c->a[idx2]; } //a[i][j]=t; idx=i*col2+j; a->a[idx]=xa; a->b[idx]=xb; //a[i*col2+j]=t; } } } wtk_complexa_t* wtk_complexa_new(int n) { wtk_complexa_t *ca; ca=(wtk_complexa_t*)wtk_malloc(sizeof(wtk_complexa_t)); ca->a=(float*)wtk_malloc(sizeof(float)*n); ca->b=(float*)wtk_malloc(sizeof(float)*n); ca->n=n; return ca; } void wtk_complexa_delete(wtk_complexa_t *ca) { wtk_free(ca->a); wtk_free(ca->b); wtk_free(ca); } void wtk_complexa_zero(wtk_complexa_t *ca) { memset(ca->a,0,sizeof(float)*ca->n); memset(ca->b,0,sizeof(float)*ca->n); } void wtk_complexa_print(wtk_complexa_t *ca) { int i; for(i=0;i<ca->n;++i) { wtk_debug("v[%d]=%f+%fi\n",i,ca->a[i],ca->b[i]); } } void wtk_complex_inv_2x(wtk_complex_t *a,int r,int c,wtk_complex_t *b) { int i,j,k; wtk_complex_t *pc,*pc2,*pc3,*pc4,*pc5,*pc6,*pc7; double f; double xa,xb; double ta,tb; //if(r!=c){return;} k=r*c; //memset(b,0,sizeof(wtk_complex_t)*k); for(i=0;i<k;++i) { b[i].a=b[i].b=0; } for(i=0,j=0;i<r;++i) //+=(r+1)) { b[j].a=1; //b[j].b=0; j+=r+1; } pc5=a; pc6=b; for(k=0;k<r;++k,pc5+=c,pc6+=c) { pc=a; pc2=b; pc7=pc5+k;//a+k*c+k; //f=1.0/(pc7->a*pc7->a+pc7->b*pc7->b); ta=pc7->a; tb=pc7->b; //wtk_debug("ta=%f/%f\n",ta,tb); f=ta*ta+tb*tb; if(f==0) { f=1e-35; } f=1.0/f;//(ta*ta+tb*tb); if(isnan(f)) { wtk_debug("ta=%f/%f\n",ta,tb); exit(0); } ta*=f; tb*=f; if(isnan(ta)) { wtk_debug("ta=%f/%f\n",ta,f); exit(0); } //wtk_debug("%f/%f\n",pc7->a,pc7->b); //exit(0); for(i=0;i<c;++i) { if(i==k) { pc+=c; pc2+=c; continue; } pc3=a+i*c+k; // pc7=a+k*c+k; // f=1.0/(pc7->a*pc7->a+pc7->b*pc7->b); //xa=(pc3->a*pc7->a+pc3->b*pc7->b)*f; //xb=(pc3->b*pc7->a-pc3->a*pc7->b)*f; xa=(pc3->a*ta+pc3->b*tb); if(isnan(xa)) { wtk_debug("%f/%f/%f/%f\n",ta,pc3->a,tb,pc3->b); exit(0); } xb=(pc3->b*ta-pc3->a*tb); //ratio=wtk_complex_div(a+i*c+k,a+k*c+k); //wtk_debug("xa=%f xb=%f f=%f\n",xa,xb,f); //exit(0); //pc=a+i*c; //pc2=b+i*c; pc3=pc5;//a+k*c; pc4=pc6;//b+k*c; //pc3=pc5;//a+k*c; //pc4=pc6;//b+k*c; for(j=0;j<c;j++) { //a=ratio b=pc3; //wtk_complex_sub(a+i*c+j,wtk_complex_mul(&ratio,a+k*c+j)); pc->a-=xa*pc3->a - xb*pc3->b; if(isnan(pc->a)) { wtk_debug("%f %f/%f/%f/%f\n",pc->a,xa,pc3->a,xb,pc3->b); exit(0); } (pc++)->b-=xa*pc3->b + xb*pc3->a; if(isnan((pc-1)->b)) { wtk_debug("%f\n",pc->b); exit(0); } ++pc3; //wtk_complex_sub(b+i*c+j,wtk_complex_mul(&ratio,b+k*c+j)); pc2->a-=xa*pc4->a - xb*pc4->b; if(isnan(pc2->a)) { wtk_debug("%f\n",pc2->a); exit(0); } (pc2++)->b-=xa*pc4->b + xb*pc4->a; if(isnan((pc2-1)->b)) { wtk_debug("%f\n",pc2->b); exit(0); } //++pc;++pc2; ++pc4; } } } for(i=0;i<r;++i) { pc=a+i*c+i; ta=pc->a; tb=pc->b; f=ta*ta+tb*tb; if(f==0) { f=1e-35; } f=1.0/f;//(ta*ta+tb*tb); if(isnan(f)) { wtk_debug("ta=%f/%f\n",ta,ta); exit(0); } ta*=f; tb*=f; for(j=0,pc2=b+i*c;j<c;++j) { //b[k]=wtk_complex_div(b+k,pc); //b[i*c+j]=wtk_complex_div(b+i*c+j,a+i*c+i); //b[i*c+j]/=a[i*c+i]; //xa=(pc2->a*pc->a+pc2->b*pc->b)*f; //xb=(pc2->b*pc->a-pc2->a*pc->b)*f; xa=(pc2->a*ta + pc2->b*tb); xb=(pc2->b*ta - pc2->a*tb); if(isnan(xa)) { wtk_debug("%f %f/%f/%f/%f\n",xa,pc2->a,ta,pc2->b,tb); exit(0); } pc2->a=xa; (pc2++)->b=xb; //++pc2; } } } void wtk_complex_inv(wtk_complex_t *a,int r,int c,wtk_complex_t *b) { wtk_complex_t *at; int n; n=r*c*sizeof(wtk_complex_t); at=(wtk_complex_t*)wtk_malloc(n); memcpy(at,a,n); wtk_complex_inv_2x(at,r,c,b); wtk_free(at); } void wtk_complex_inv_x(wtk_complex_t *a,int r,int c,wtk_complex_t *b) { int i,j,k; wtk_complex_t *pc,*pc2,*pc3,*pc4,*pc5,*pc6,*pc7; float f; float xa,xb; float ta,tb; //if(r!=c){return;} k=r*c; //memset(b,0,sizeof(wtk_complex_t)*k); for(i=0;i<k;++i) { b[i].a=b[i].b=0; } for(i=0,j=0;i<r;++i) //+=(r+1)) { b[j].a=1; //b[j].b=0; j+=r+1; } pc5=a; pc6=b; for(k=0;k<r;++k,pc5+=c,pc6+=c) { pc=a; pc2=b; pc7=pc5+k;//a+k*c+k; //f=1.0/(pc7->a*pc7->a+pc7->b*pc7->b); ta=pc7->a; tb=pc7->b; f=1.0/(ta*ta+tb*tb); ta*=f; tb*=f; //wtk_debug("%f/%f\n",pc7->a,pc7->b); //exit(0); for(i=0;i<c;++i) { if(i==k) { pc+=c; pc2+=c; continue; } pc3=a+i*c+k; // pc7=a+k*c+k; // f=1.0/(pc7->a*pc7->a+pc7->b*pc7->b); //xa=(pc3->a*pc7->a+pc3->b*pc7->b)*f; //xb=(pc3->b*pc7->a-pc3->a*pc7->b)*f; xa=(pc3->a*ta+pc3->b*tb); xb=(pc3->b*ta-pc3->a*tb); //ratio=wtk_complex_div(a+i*c+k,a+k*c+k); //wtk_debug("xa=%f xb=%f f=%f\n",xa,xb,f); //exit(0); //pc=a+i*c; //pc2=b+i*c; pc3=pc5;//a+k*c; pc4=pc6;//b+k*c; //pc3=pc5;//a+k*c; //pc4=pc6;//b+k*c; for(j=0;j<c;j++) { //a=ratio b=pc3; //wtk_complex_sub(a+i*c+j,wtk_complex_mul(&ratio,a+k*c+j)); pc->a-=xa*pc3->a - xb*pc3->b; (pc++)->b-=xa*pc3->b + xb*pc3->a; ++pc3; //wtk_complex_sub(b+i*c+j,wtk_complex_mul(&ratio,b+k*c+j)); pc2->a-=xa*pc4->a - xb*pc4->b; (pc2++)->b-=xa*pc4->b + xb*pc4->a; //++pc;++pc2; ++pc4; } } } pc2=b; for(i=0;i<r;++i) { pc=a+i*c+i; ta=pc->a; tb=pc->b; f=1.0/(ta*ta+tb*tb);//pc->a*pc->a+pc->b*pc->b); ta*=f; tb*=f; for(j=0;j<c;++j) { //b[k]=wtk_complex_div(b+k,pc); //b[i*c+j]=wtk_complex_div(b+i*c+j,a+i*c+i); //b[i*c+j]/=a[i*c+i]; //xa=(pc2->a*pc->a+pc2->b*pc->b)*f; //xb=(pc2->b*pc->a-pc2->a*pc->b)*f; // xa=(pc2->a*ta + pc2->b*tb); // xb=(pc2->b*ta - pc2->a*tb); // pc2->a=xa; // (pc2++)->b=xb; xa=(pc2->a*ta + pc2->b*tb); pc2->b=(pc2->b*ta - pc2->a*tb); (pc2++)->a=xa; //(pc2++)->b=xb; //++pc2; } } } void wtk_complex_inv2(wtk_complex_t *a,int r,int c,wtk_complex_t *b) { int i,j,k; wtk_complex_t ratio; wtk_complex_t *pc; float f; if(r!=c){return;} k=r*c; for(i=0;i<k;++i) { b[i].a=b[i].b=0; } for(i=0,j=0;i<r;++i) //+=(r+1)) { //b[i].a=1; //b[i].b=0; b[j].a=1; b[j].b=0; j+=r+1; } for(k=0;k<r;++k) { for(i=0;i<c;++i) { if(i==k) { continue; } ratio=wtk_complex_div(a+i*c+k,a+k*c+k); for(j=0;j<c;j++) { wtk_complex_sub(a+i*c+j,wtk_complex_mul(&ratio,a+k*c+j)); wtk_complex_sub(b+i*c+j,wtk_complex_mul(&ratio,b+k*c+j)); } } } for(i=0;i<r;++i) { k=i*c; pc=a+i*c+i; f=1.0/(pc->a*pc->a+pc->b*pc->b); for(j=0;j<c;++j,++k) { //b[k]=wtk_complex_div(b+k,pc); //b[i*c+j]=wtk_complex_div(b+i*c+j,a+i*c+i); //b[i*c+j]/=a[i*c+i]; ratio.a=(b[k].a*pc->a+b[k].b*pc->b)*f; ratio.b=(b[k].b*pc->a-b[k].a*pc->b)*f; b[k]=ratio; } } } //------------------------------------------------------------------ //功能: 采用部分主元的高斯消去法求方阵A的逆矩阵B //入口参数: 输入方阵,输出方阵,方阵阶数 //返回值: true or false //------------------------------------------------------------------- #define N 10 int Gauss(float A[][N], float B[][N], int n) { int i, j, k; float max, temp; float t[N][N]; //临时矩阵 //将A矩阵存放在临时矩阵t[n][n]中 for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { t[i][j] = A[i][j]; } } //初始化B矩阵为单位阵 for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { B[i][j] = (i == j) ? (float)1 : 0; } } for (i = 0; i < n; i++) { //寻找主元 max = t[i][i]; k = i; for (j = i + 1; j < n; j++) { if (fabs(t[j][i]) > fabs(max)) { max = t[j][i]; k = j; } } //如果主元所在行不是第i行,进行行交换 if (k != i) { for (j = 0; j < n; j++) { temp = t[i][j]; t[i][j] = t[k][j]; t[k][j] = temp; //B伴随交换 temp = B[i][j]; B[i][j] = B[k][j]; B[k][j] = temp; } } //判断主元是否为0, 若是, 则矩阵A不是满秩矩阵,不存在逆矩阵 if (t[i][i] == 0) { return -1; } //消去A的第i列除去i行以外的各行元素 temp = t[i][i]; for (j = 0; j < n; j++) { t[i][j] = t[i][j] / temp; //主对角线上的元素变为1 B[i][j] = B[i][j] / temp; //伴随计算 } for (j = 0; j < n; j++) //第0行->第n行 { if (j != i) //不是第i行 { temp = t[j][i]; for (k = 0; k < n; k++) //第j行元素 - i行元素*j列i行元素 { t[j][k] = t[j][k] - t[i][k] * temp; B[j][k] = B[j][k] - B[i][k] * temp; } } } } return 0; } int bcinv(ar,ai,n) int n; double ar[],ai[]; { int *is,*js,i,j,k,l,u,v,w; double p,q,s,t,d,b; is=malloc(n*sizeof(int)); js=malloc(n*sizeof(int)); for (k=0; k<=n-1; k++) { d=0.0; for (i=k; i<=n-1; i++) for (j=k; j<=n-1; j++) { u=i*n+j; p=ar[u]*ar[u]+ai[u]*ai[u]; if (p>d) { d=p; is[k]=i; js[k]=j;} } if (d+1.0==1.0) { free(is); free(js); printf("err**not inv\n"); return(0); } if (is[k]!=k) for (j=0; j<=n-1; j++) { u=k*n+j; v=is[k]*n+j; t=ar[u]; ar[u]=ar[v]; ar[v]=t; t=ai[u]; ai[u]=ai[v]; ai[v]=t; } if (js[k]!=k) for (i=0; i<=n-1; i++) { u=i*n+k; v=i*n+js[k]; t=ar[u]; ar[u]=ar[v]; ar[v]=t; t=ai[u]; ai[u]=ai[v]; ai[v]=t; } l=k*n+k; ar[l]=ar[l]/d; ai[l]=-ai[l]/d; for (j=0; j<=n-1; j++) if (j!=k) { u=k*n+j; p=ar[u]*ar[l]; q=ai[u]*ai[l]; s=(ar[u]+ai[u])*(ar[l]+ai[l]); ar[u]=p-q; ai[u]=s-p-q; } for (i=0; i<=n-1; i++) if (i!=k) { v=i*n+k; for (j=0; j<=n-1; j++) if (j!=k) { u=k*n+j; w=i*n+j; p=ar[u]*ar[v]; q=ai[u]*ai[v]; s=(ar[u]+ai[u])*(ar[v]+ai[v]); t=p-q; b=s-p-q; ar[w]=ar[w]-t; ai[w]=ai[w]-b; } } for (i=0; i<=n-1; i++) if (i!=k) { u=i*n+k; p=ar[u]*ar[l]; q=ai[u]*ai[l]; s=(ar[u]+ai[u])*(ar[l]+ai[l]); ar[u]=q-p; ai[u]=p+q-s; } } for (k=n-1; k>=0; k--) { if (js[k]!=k) for (j=0; j<=n-1; j++) { u=k*n+j; v=js[k]*n+j; t=ar[u]; ar[u]=ar[v]; ar[v]=t; t=ai[u]; ai[u]=ai[v]; ai[v]=t; } if (is[k]!=k) for (i=0; i<=n-1; i++) { u=i*n+k; v=i*n+is[k]; t=ar[u]; ar[u]=ar[v]; ar[v]=t; t=ai[u]; ai[u]=ai[v]; ai[v]=t; } } free(is); free(js); return(1); } int wtk_dcomplex_invx3_x(wtk_dcomplex_t **A, int n, wtk_dcomplex_t **B) { int *is, *js, i, j, k; double p, q, s, t, d, b; wtk_dcomplex_t c; is = malloc(n * sizeof(int)); js = malloc(n * sizeof(int)); for (k = 0; k < n; k++) { d = 0.0; for (i = k; i < n ; i++) { for (j = k; j <n ; j++) { p=A[i][j].a*A[i][j].a+A[i][j].b*A[i][j].b; if (p > d) { d = p; is[k] = i; js[k] = j; } } } if (d + 1.0 == 1.0) { free(is); free(js); return -1; } if (is[k] != k) { for (j = 0; j <n; j++) { c=A[k][j]; A[k][j]=A[is[k]][j]; A[is[k]][j]=c; } } if (js[k] != k) { for (i = 0; i <n; i++) { c=A[i][k]; A[i][k]=A[i][js[k]]; A[i][js[k]]=c; } } A[k][k].a/=d; A[k][k].b/=-d; for (j = 0; j < n; j++) { if (j != k) { p=A[k][j].a*A[k][k].a; q=A[k][j].b*A[k][k].b; s=(A[k][j].a+A[k][j].b)*(A[k][k].a+A[k][k].b); A[k][j].a=p-q; A[k][j].b=s-p-q; } } for (i = 0; i <n ; i++) { if (i != k) { for (j = 0; j < n; j++) { if (j != k) { p=A[k][j].a*A[i][k].a; q=A[k][j].b*A[i][k].b; s=(A[k][j].a+A[k][j].b)*(A[i][k].a+A[i][k].b); t = p - q; b = s - p - q; A[i][j].a-=t; A[i][j].b-=b; } } } } for (i = 0; i < n; i++) { if (i != k) { p=A[i][k].a*A[k][k].a; q=A[i][k].b*A[k][k].b; s=(A[i][k].a+A[i][k].b)*(A[k][k].a+A[k][k].b); A[i][k].a=q-p; A[i][k].b=p+q-s; } } } for (k = n - 1; k >= 0; k--) { if (js[k] != k) { for (j = 0; j < n; j++) { c=A[k][j]; A[k][j]=A[js[k]][j]; A[js[k]][j]=c; } } if (is[k] != k) { for (i = 0; i < n ; i++) { c=A[i][k]; A[i][k]=A[i][is[k]]; A[i][is[k]]=c; } } } for(i=0;i<n;++i) { for(j=0;j<n;++j) { B[i][j]=A[i][j]; } } free(is); free(js); return 0; } int wtk_dcomplex_invx3(wtk_dcomplex_t **a,int n,wtk_dcomplex_t **b) { int i,j,k; wtk_dcomplex_t *pc,*pc2,*pc3,*pc4,*pc5,*pc6; double f,xa,xb,ta,tb; //wtk_debug("============ phr ==========\n"); // wtk_dcomplex_p2_print2(a,n,n); j=sizeof(wtk_dcomplex_t)*n; for(i=0;i<n;++i) { memset(b[i],0,j); b[i][i].a=1; } for(k=0;k<n;++k) { pc5=a[k]; pc6=b[k]; ta=pc5[k].a; tb=pc5[k].b; //wtk_debug("ta=%f/%f\n",ta,tb); f=(ta*ta+tb*tb); if(f==0) { wtk_debug("found err\n"); return -1; } f=1.0/f; ta*=f; tb*=f; //wtk_debug("%f/%f\n",pc7->a,pc7->b); //exit(0); for(i=0;i<n;++i) { if(i==k) { continue; } pc=a[i]; pc2=b[i]; pc3=a[i]+k; xa=(pc3->a*ta+pc3->b*tb); xb=(pc3->b*ta-pc3->a*tb); pc3=pc5;//a+k*c; pc4=pc6;//b+k*c; for(j=0;j<n;j++) { //a=ratio b=pc3; //wtk_complex_sub(a+i*c+j,wtk_complex_mul(&ratio,a+k*c+j)); pc->a-=xa*pc3->a - xb*pc3->b; (pc++)->b-=xa*pc3->b + xb*pc3->a; ++pc3; //wtk_complex_sub(b+i*c+j,wtk_complex_mul(&ratio,b+k*c+j)); pc2->a-=xa*pc4->a - xb*pc4->b; (pc2++)->b-=xa*pc4->b + xb*pc4->a; //++pc;++pc2; ++pc4; } } } for(i=0;i<n;++i) { //pc=a+i*c+i; pc=a[i]+i; ta=pc->a; tb=pc->b; f=(ta*ta+tb*tb); if(f==0) { wtk_debug("found err\n"); return -1; } f=1.0/f; ta*=f; tb*=f; for(j=0,pc2=b[i];j<n;++j) { xa=pc2->a; xb=pc2->b; pc2->a=xa*ta+xb*tb; (pc2++)->b=xb*ta-xa*tb;; } } //wtk_debug("============ phr2 ==========\n"); // wtk_dcomplex_p2_print2(b,n,n); return 0; } int wtk_dcomplex_lu_invx3(wtk_dcomplex_t **a,wtk_dcomplex_t **L,wtk_dcomplex_t **U,wtk_dcomplex_t **l,wtk_dcomplex_t **u,int n,wtk_dcomplex_t **b) { int i,j,k; wtk_dcomplex_t *c1,*c2,*c3; float f,ta,tb,ta1,tb1; c3 = (wtk_dcomplex_t *)malloc(n*sizeof(wtk_dcomplex_t)); for(i=0;i<n;++i) { memset(U[i],0,n); memset(L[i],0,n); L[i][i].a=1; memset(l[i],0,n); l[i][i].a=1; memset(u[i],0,n); } c1 = U[0]; c2 = a[0]; for(i=0;i<n;++i) { c1[i].a = c2[i].a; c1[i].b = c2[i].b; } ta = c1->a; tb = c2->b; f = ta*ta+tb*tb ; if(f==0) { wtk_debug("found err\n"); return -1; } f=1.0/f; ta*=f; tb*=f; c3[0].a=ta; c3[0].b=-tb; for(i=1;i<n;++i) { L[i]->a = a[i]->a*ta+a[i]->b*tb; L[i]->b = a[i]->b*ta-a[i]->a*tb; } for(i=1;i<n;++i) { for(j=i;j<n;++j) { ta=0; tb=0; for(k=0;k<i;++k) { ta += L[i][k].a*U[k][j].a - L[i][k].b*U[k][j].b; tb += L[i][k].b*U[k][j].a + L[i][k].a*U[k][j].b; } U[i][j].a = a[i][j].a-ta; U[i][j].b = a[i][j].b-tb; } ta1 = U[i][i].a; tb1 = U[i][i].b; f = ta1*ta1+tb1*tb1; if(f==0) { wtk_debug("found err\n"); return -1; } f=1.0/f; ta1*=f; tb1*=f; c3[i].a=ta1; c3[i].b=-tb1; for(j=i+1;j<n;++j) { ta=0; tb=0; for(k=0;k<i;++k) { ta +=L[j][k].a*U[k][i].a - L[j][k].b*U[k][i].b; tb +=L[j][k].b*U[k][i].a + L[j][k].a*U[k][i].b; } ta = a[j][i].a-ta; tb = a[j][i].b-tb; L[j][i].a = ta*ta1 + tb*tb1; L[j][i].b = tb*ta1 - ta*tb1; } } wtk_debug("L===\n"); wtk_dcomplex_p2_print2(L,n,n); wtk_debug("U===\n"); wtk_dcomplex_p2_print2(U,n,n); for(i=0;i<n;++i) { for(j=i+1;j<n;++j) { ta=0; tb=0; for(k=i;k<j;++k) { ta += l[k][i].a*L[j][k].a - l[k][i].b*L[j][k].b; tb += l[k][i].a*L[j][k].b + l[k][i].b*L[j][k].a; } l[j][i].a = -ta; l[j][i].b = -tb; } u[i][i].a=c3[i].a; u[i][i].b=c3[i].b; for(j=i-1;j>=0;--j) { ta1=0; tb1=0; for(k=j;k<i+1;++k) { ta1 += U[j][k].a*u[k][i].a - U[j][k].b*u[k][i].b; tb1 += U[j][k].a*u[k][i].b + U[j][k].b*u[k][i].a; } u[j][i].a = -(u[j][j].a*ta1 - u[j][j].b*tb1); u[j][i].b = -(u[j][j].a*tb1 + u[j][j].b*ta1); } } //wtk_debug("%f\n",u[0][0].a); wtk_debug("l===\n"); wtk_dcomplex_p2_print2(l,n,n); wtk_debug("u===\n"); wtk_dcomplex_p2_print2(u,n,n); wtk_dcomplex_matrix_mul(u,l,b,n,n,n); free(c3); return 0; } //a是nx x nx*2维的 int wtk_complex_invx4(wtk_complex_t *input,wtk_dcomplex_t *a,int nx,wtk_complex_t *b,int sym) { int i,j,k; int nx2=nx<<1; wtk_dcomplex_t *dc,*dc2,*dc3,tmp; wtk_dcomplex_t e={1,0},z={0,0}; wtk_complex_t *c,*c2; double mx,fa,fb,fa2,fb2,f; int mi,k2,k3; dc=a; c=input; for(i=0;i<nx;++i) { for(j=0;j<nx;++j,++dc,++c) { dc->a=c->a; dc->b=c->b; if(j==i) { *(dc+nx)=e; }else { *(dc+nx)=z; } } dc+=nx; } for(k=0;k<nx;++k) { dc=a+k*nx2+k; mx=0; mi=k; for(i=k;i<nx;++i) { f=dc->a*dc->a+dc->b*dc->b; if(f>mx) { mx=f; mi=i; } dc+=nx2; } if(mx==0.0) { return -1; } if(mi!=k) { k2=k*nx2+k; k3=mi*nx2+k; for(i=k;i<nx2;++i,++k2,++k3) { tmp=*(a+k2); *(a+k2)=*(a+k3); *(a+k3)=tmp; } } mx=1.0/mx; dc3=a+k*nx2+k; fa=dc3->a*mx; fb=dc3->b*mx; dc2=a+k; for(i=0;i<nx;++i) { if(i==k) { dc2+=nx2; continue; } dc=dc3; fa2=fa*dc2->a+fb*dc2->b; fb2=fa*dc2->b-fb*dc2->a; for(j=k;j<nx2;++j,++dc2,++dc) { dc2->a-=dc->a*fa2-dc->b*fb2; dc2->b-=dc->a*fb2+dc->b*fa2; } dc2+=k; } } if(sym) { dc=dc2=a; c=b; for(i=0,dc2+=nx;i<nx;++i) { fa=dc->a; fb=dc->b; mx=fa*fa+fb*fb; if(mx==0.0) { return -1; } mx=1/mx; fa*=mx; fb*=mx; dc2+=i; c=b+nx*i+i; c2=c+nx; for(j=i;j<nx;++j,++dc2,++c) { c->a=dc2->a*fa+dc2->b*fb; c->b=dc2->b*fa-dc2->a*fb; if(i!=j) { c2->a=c->a; c2->b=-c->b; c2+=nx; } } dc2+=nx; dc+=nx2+1; } return 0; } dc=dc2=a; for(i=0,dc2+=nx;i<nx;++i) { fa=dc->a; fb=dc->b; mx=fa*fa+fb*fb; if(mx==0.0) { return -1; } mx=1/mx; fa*=mx; fb*=mx; for(j=0;j<nx;++j,++dc2,++b) { b->a=dc2->a*fa+dc2->b*fb; b->b=dc2->b*fa-dc2->a*fb; } dc2+=nx; dc+=nx2+1; } return 0; } int wtk_complex_invx3(wtk_complex_t **a,int r,int c,wtk_complex_t **b) { int i,j,k; wtk_complex_t *pc,*pc2,*pc3,*pc4,*pc5,*pc6,*pc7; double f; double xa,xb; double ta,tb; for(i=0;i<r;++i) { memset(b[i],0,sizeof(wtk_complex_t)*c); b[i][i].a=1; } for(k=0;k<r;++k) { pc5=a[k]; pc6=b[k]; pc7=pc5+k;//a+k*c+k; //f=1.0/(pc7->a*pc7->a+pc7->b*pc7->b); ta=pc7->a; tb=pc7->b; //wtk_debug("ta=%f/%f\n",ta,tb); f=(ta*ta+tb*tb); if(f==0) { return -1; } f=1.0/f; ta*=f; tb*=f; //wtk_debug("%f/%f\n",pc7->a,pc7->b); //exit(0); for(i=0;i<c;++i) { if(i==k) { continue; } pc=a[i]; pc2=b[i]; pc3=a[i]+k; // pc7=a+k*c+k; // f=1.0/(pc7->a*pc7->a+pc7->b*pc7->b); //xa=(pc3->a*pc7->a+pc3->b*pc7->b)*f; //xb=(pc3->b*pc7->a-pc3->a*pc7->b)*f; xa=(pc3->a*ta+pc3->b*tb); xb=(pc3->b*ta-pc3->a*tb); //ratio=wtk_complex_div(a+i*c+k,a+k*c+k); //wtk_debug("xa=%f xb=%f f=%f\n",xa,xb,f); //exit(0); //pc=a+i*c; //pc2=b+i*c; pc3=pc5;//a+k*c; pc4=pc6;//b+k*c; //pc3=pc5;//a+k*c; //pc4=pc6;//b+k*c; for(j=0;j<c;j++) { //a=ratio b=pc3; //wtk_complex_sub(a+i*c+j,wtk_complex_mul(&ratio,a+k*c+j)); pc->a-=xa*pc3->a - xb*pc3->b; (pc++)->b-=xa*pc3->b + xb*pc3->a; ++pc3; //wtk_complex_sub(b+i*c+j,wtk_complex_mul(&ratio,b+k*c+j)); pc2->a-=xa*pc4->a - xb*pc4->b; (pc2++)->b-=xa*pc4->b + xb*pc4->a; //++pc;++pc2; ++pc4; } } } for(i=0;i<r;++i) { //pc=a+i*c+i; pc=a[i]+i; ta=pc->a; tb=pc->b; f=(ta*ta+tb*tb); if(f==0) { return -1; } f=1.0/f; ta*=f; tb*=f; for(j=0,pc2=b[i];j<c;++j) { //b[k]=wtk_complex_div(b+k,pc); //b[i*c+j]=wtk_complex_div(b+i*c+j,a+i*c+i); //b[i*c+j]/=a[i*c+i]; //xa=(pc2->a*pc->a+pc2->b*pc->b)*f; //xb=(pc2->b*pc->a-pc2->a*pc->b)*f; xa=(pc2->a*ta + pc2->b*tb); xb=(pc2->b*ta - pc2->a*tb); pc2->a=xa; (pc2++)->b=xb; //++pc2; } } return 0; } int wtk_complex_invx2(wtk_complex_t *a,int r,int c,wtk_complex_t *b) { int i,j,k; wtk_complex_t *pc,*pc2,*pc3,*pc4,*pc5,*pc6,*pc7; double f; double xa,xb; double ta,tb; memset(b,0,sizeof(wtk_complex_t)*r*c); for(i=0,j=0;i<r;++i) //+=(r+1)) { b[j].a=1; //b[j].b=0; j+=r+1; } pc5=a; pc6=b; for(k=0;k<r;++k,pc5+=c,pc6+=c) { pc=a; pc2=b; pc7=pc5+k;//a+k*c+k; //f=1.0/(pc7->a*pc7->a+pc7->b*pc7->b); ta=pc7->a; tb=pc7->b; //wtk_debug("ta=%f/%f\n",ta,tb); f=(ta*ta+tb*tb); if(f==0) { return -1; } f=1.0/f; ta*=f; tb*=f; //wtk_debug("%f/%f\n",pc7->a,pc7->b); //exit(0); for(i=0;i<c;++i) { if(i==k) { pc+=c; pc2+=c; continue; } pc3=a+i*c+k; // pc7=a+k*c+k; // f=1.0/(pc7->a*pc7->a+pc7->b*pc7->b); //xa=(pc3->a*pc7->a+pc3->b*pc7->b)*f; //xb=(pc3->b*pc7->a-pc3->a*pc7->b)*f; xa=(pc3->a*ta+pc3->b*tb); xb=(pc3->b*ta-pc3->a*tb); //ratio=wtk_complex_div(a+i*c+k,a+k*c+k); //wtk_debug("xa=%f xb=%f f=%f\n",xa,xb,f); //exit(0); //pc=a+i*c; //pc2=b+i*c; pc3=pc5;//a+k*c; pc4=pc6;//b+k*c; //pc3=pc5;//a+k*c; //pc4=pc6;//b+k*c; for(j=0;j<c;j++) { //a=ratio b=pc3; //wtk_complex_sub(a+i*c+j,wtk_complex_mul(&ratio,a+k*c+j)); pc->a-=xa*pc3->a - xb*pc3->b; (pc++)->b-=xa*pc3->b + xb*pc3->a; ++pc3; //wtk_complex_sub(b+i*c+j,wtk_complex_mul(&ratio,b+k*c+j)); pc2->a-=xa*pc4->a - xb*pc4->b; (pc2++)->b-=xa*pc4->b + xb*pc4->a; //++pc;++pc2; ++pc4; } } } for(i=0;i<r;++i) { pc=a+i*c+i; ta=pc->a; tb=pc->b; f=(ta*ta+tb*tb); if(f==0) { return -1; } f=1.0/f; ta*=f; tb*=f; for(j=0,pc2=b+i*c;j<c;++j) { //b[k]=wtk_complex_div(b+k,pc); //b[i*c+j]=wtk_complex_div(b+i*c+j,a+i*c+i); //b[i*c+j]/=a[i*c+i]; //xa=(pc2->a*pc->a+pc2->b*pc->b)*f; //xb=(pc2->b*pc->a-pc2->a*pc->b)*f; xa=(pc2->a*ta + pc2->b*tb); xb=(pc2->b*ta - pc2->a*tb); pc2->a=xa; (pc2++)->b=xb; //++pc2; } } return 0; } int wtk_complex_invx(wtk_complex_t *a,int r,int c,wtk_complex_t *b,wtk_complex_t *at) { int n; n=r*c*sizeof(wtk_complex_t); memcpy(at,a,n); return wtk_complex_invx2(at,r,c,b); } int wtk_dcomplex_invx2(wtk_dcomplex_t *a,int r,int c,wtk_dcomplex_t *b) { int i,j,k; wtk_dcomplex_t *pc,*pc2,*pc3,*pc4,*pc5,*pc6,*pc7; double f; double xa,xb; double ta,tb; memset(b,0,sizeof(wtk_dcomplex_t)*r*c); for(i=0,j=0;i<r;++i) //+=(r+1)) { b[j].a=1; //b[j].b=0; j+=r+1; } pc5=a; pc6=b; for(k=0;k<r;++k,pc5+=c,pc6+=c) { pc=a; pc2=b; pc7=pc5+k;//a+k*c+k; //f=1.0/(pc7->a*pc7->a+pc7->b*pc7->b); ta=pc7->a; tb=pc7->b; //wtk_debug("ta=%f/%f\n",ta,tb); f=(ta*ta+tb*tb); if(f==0) { return -1; } f=1.0/f; ta*=f; tb*=f; //wtk_debug("%f/%f\n",pc7->a,pc7->b); //exit(0); for(i=0;i<c;++i) { if(i==k) { pc+=c; pc2+=c; continue; } pc3=a+i*c+k; // pc7=a+k*c+k; // f=1.0/(pc7->a*pc7->a+pc7->b*pc7->b); //xa=(pc3->a*pc7->a+pc3->b*pc7->b)*f; //xb=(pc3->b*pc7->a-pc3->a*pc7->b)*f; xa=(pc3->a*ta+pc3->b*tb); xb=(pc3->b*ta-pc3->a*tb); //ratio=wtk_complex_div(a+i*c+k,a+k*c+k); //wtk_debug("xa=%f xb=%f f=%f\n",xa,xb,f); //exit(0); //pc=a+i*c; //pc2=b+i*c; pc3=pc5;//a+k*c; pc4=pc6;//b+k*c; //pc3=pc5;//a+k*c; //pc4=pc6;//b+k*c; for(j=0;j<c;j++) { //a=ratio b=pc3; //wtk_complex_sub(a+i*c+j,wtk_complex_mul(&ratio,a+k*c+j)); pc->a-=xa*pc3->a - xb*pc3->b; (pc++)->b-=xa*pc3->b + xb*pc3->a; ++pc3; //wtk_complex_sub(b+i*c+j,wtk_complex_mul(&ratio,b+k*c+j)); pc2->a-=xa*pc4->a - xb*pc4->b; (pc2++)->b-=xa*pc4->b + xb*pc4->a; //++pc;++pc2; ++pc4; } } } for(i=0;i<r;++i) { pc=a+i*c+i; ta=pc->a; tb=pc->b; f=(ta*ta+tb*tb); if(f==0) { return -1; } f=1.0/f; ta*=f; tb*=f; for(j=0,pc2=b+i*c;j<c;++j) { //b[k]=wtk_complex_div(b+k,pc); //b[i*c+j]=wtk_complex_div(b+i*c+j,a+i*c+i); //b[i*c+j]/=a[i*c+i]; //xa=(pc2->a*pc->a+pc2->b*pc->b)*f; //xb=(pc2->b*pc->a-pc2->a*pc->b)*f; xa=(pc2->a*ta + pc2->b*tb); xb=(pc2->b*ta - pc2->a*tb); pc2->a=xa; (pc2++)->b=xb; //++pc2; } } return 0; } int wtk_dcomplex_invx(wtk_dcomplex_t *a,int r,int c,wtk_dcomplex_t *b,wtk_dcomplex_t *at) { int n; n=r*c*sizeof(wtk_dcomplex_t); memcpy(at,a,n); return wtk_dcomplex_invx2(at,r,c,b); } void wtk_complex_det(wtk_complex_t *c,int n,char *bit,wtk_dcomplex_t *a,int step) { wtk_dcomplex_t t; wtk_complex_t x; int i,j; int sign; if(step==n-1) { for(i=0;i<n;++i) { if(!bit[i]) { //wtk_debug("step=%d i=%d\n",step,i); c=c+step*n+i; a->a=c->a; a->b=c->b; return; } } wtk_debug("found err\n"); exit(0); return; } sign=1; a->a=0; a->b=0; j=0; for(i=step;i<n;++i) { while(bit[j]) { ++j; } //wtk_debug("j=%d\n",j); bit[j]=1; wtk_complex_det(c,n,bit,&t,step+1); x=c[step*n+j]; //wtk_debug("%f+%fi %f+%fi\n",t.a,t.b,x.a,x.b); if(sign>=0) { a->a+=x.a*t.a-x.b*t.b; a->b+=x.b*t.a+x.a*t.b; }else { a->a-=x.a*t.a-x.b*t.b; a->b-=x.b*t.a+x.a*t.b; } bit[j]=0; sign=-sign; ++j; } } int wtk_complex_invx_and_det(wtk_complex_t *input,wtk_dcomplex_t *a,int nx,wtk_complex_t *b,int sym,double *det) { int i,j,k; int nx2=nx<<1; wtk_dcomplex_t *dc,*dc2,*dc3,tmp; wtk_dcomplex_t e={1,0},z={0,0}; wtk_complex_t *c,*c2; double f,mx,fa,fb,fa2,fb2; int mi,k2,k3; double fa3,fb3; dc=a; c=input; for(i=0;i<nx;++i) { for(j=0;j<nx;++j,++dc,++c) { dc->a=c->a; dc->b=c->b; if(j==i) { *(dc+nx)=e; }else { *(dc+nx)=z; } } dc+=nx; } for(k=0;k<nx;++k) { dc=a+k*nx2+k; mx=0; mi=k; for(i=k;i<nx;++i) { f=dc->a*dc->a+dc->b*dc->b; if(f>mx) { mx=f; mi=i; } dc+=nx2; } if(mx==0.0) { *det=0; return -1; } if(mi!=k) { k2=k*nx2+k; k3=mi*nx2+k; for(i=k;i<nx2;++i,++k2,++k3) { tmp=*(a+k2); *(a+k2)=*(a+k3); *(a+k3)=tmp; } } mx=1.0/mx; dc3=a+k*nx2+k; fa=dc3->a*mx; fb=dc3->b*mx; dc2=a+k; for(i=0;i<nx;++i) { if(i==k) { dc2+=nx2; continue; } dc=dc3; fa2=fa*dc2->a+fb*dc2->b; fb2=fa*dc2->b-fb*dc2->a; for(j=k;j<nx2;++j,++dc2,++dc) { dc2->a-=dc->a*fa2-dc->b*fb2; dc2->b-=dc->a*fb2+dc->b*fa2; } dc2+=k; } } fa3=fb3=0; if(sym) { dc=dc2=a; c=b; for(i=0,dc2+=nx;i<nx;++i) { fa=dc->a; fb=dc->b; mx=fa*fa+fb*fb; if(mx==0.0) { *det=0; return -1; } if(i==0) { fa3=fa; fb3=fb; }else { f=fa3; fa3=fa3*fa-fb3*fb; fb3=f*fb+fb3*fa; } mx=1/mx; fa*=mx; fb*=mx; dc2+=i; c=b+nx*i+i; c2=c+nx; for(j=i;j<nx;++j,++dc2,++c) { c->a=dc2->a*fa+dc2->b*fb; c->b=dc2->b*fa-dc2->a*fb; if(i!=j) { c2->a=c->a; c2->b=-c->b; c2+=nx; } } dc2+=nx; dc+=nx2+1; } *det=sqrt(fa3*fa3+fb3*fb3); return 0; } dc=dc2=a; for(i=0,dc2+=nx;i<nx;++i) { fa=dc->a; fb=dc->b; mx=fa*fa+fb*fb; if(mx==0.0) { return -1; } if(i==0) { fa3=fa; fb3=fb; }else { f=fa3; fa3=fa3*fa-fb3*fb; fb3=f*fb+fb3*fa; } mx=1/mx; fa*=mx; fb*=mx; for(j=0;j<nx;++j,++dc2,++b) { b->a=dc2->a*fa+dc2->b*fb; b->b=dc2->b*fa-dc2->a*fb; } dc2+=nx; dc+=nx2+1; } *det=sqrt(fa3*fa3+fb3*fb3); return 0; } void wtk_dcomplex_det1(wtk_dcomplex_t *c, int n, wtk_dcomplex_t *a) { int i,j,k,n1,n2,n3,mi,mj,flag; double mv,tmp,real,imag; wtk_dcomplex_t ctmp,v,v1; a->a=1; a->b=0; n1=n-1; flag=1; for(k=0;k<n1;++k) { mv = 0.0; mi=mj=k; for(i=k;i<n;++i) { n2=i*n+k; for(j=k;j<n;++j,++n2) { tmp=c[n2].a*c[n2].a+c[n2].b*c[n2].b; if(tmp>mv) { mv=tmp; mi=i; mj=j; } } } if(mv == 0.0) { a->a=a->b=0; return; } if(mi != k) { n2=k*n+k; n3=mi*n+k; for(i=k;i<n;++i,++n2,++n3) { ctmp.a=c[n2].a; ctmp.b=c[n2].b; c[n2].a=c[n3].a; c[n2].b=c[n3].b; c[n3].a=ctmp.a; c[n3].b=ctmp.b; } flag=-flag; } if(mj != k) { for(i=k;i<n;++i) { n2=n*i+k; n3=n*i+mj; ctmp.a=c[n2].a; ctmp.b=c[n2].b; c[n2].a=c[n3].a; c[n2].b=c[n3].b; c[n3].a=ctmp.a; c[n3].b=ctmp.b; } flag=-flag; } n2=k*n+k; mv=1.0/mv; v.a=c[n2].a*mv; v.b=-c[n2].b*mv; for(i=k+1;i<n;++i) { n3=i*n+k; real=v.a*c[n3].a-v.b*c[n3].b; imag=v.a*c[n3].b+v.b*c[n3].a; n2=k*n+k+1; n3=i*n+k+1; for(j=k+1;j<n;++j,++n2,++n3) { v1.a=real*c[n2].a-imag*c[n2].b; v1.b=real*c[n2].b+imag*c[n2].a; c[n3].a-=v1.a; c[n3].b-=v1.b; } } n2=k*n+k; real=a->a; imag=a->b; a->a=real*c[n2].a-imag*c[n2].b; a->b=real*c[n2].b+imag*c[n2].a; } n1=n*n-1; real=a->a; imag=a->b; a->a=flag*(real*c[n1].a-imag*c[n1].b); a->b=flag*(real*c[n1].b+imag*c[n1].a); } double wtk_complex_abs_det(wtk_complex_t *c,int n,char *bit) { wtk_dcomplex_t a; //char *bit; memset(bit,0,n); //bit=wtk_calloc(n,sizeof(char)); wtk_complex_det(c,n,bit,&a,0); //wtk_debug("%e+i%e\n",a.a,a.b); return sqrt(a.a*a.a+a.b*a.b); } double wtk_complex_abs_det1(wtk_complex_t *c,wtk_dcomplex_t *c1,int n) { wtk_dcomplex_t a; int i,k; k=n*n; for(i=0;i<k;++i) { c1[i].a=c[i].a; c1[i].b=c[i].b; } wtk_dcomplex_det1(c1,n, &a); return sqrt(a.a*a.a+a.b*a.b); } void wtk_dcomplex_det(wtk_dcomplex_t *c,int n,char *bit,wtk_dcomplex_t *a,int step) { wtk_dcomplex_t t; wtk_dcomplex_t x; int i,j; int sign; if(step==n-1) { for(i=0;i<n;++i) { if(!bit[i]) { //wtk_debug("step=%d i=%d\n",step,i); c=c+step*n+i; a->a=c->a; a->b=c->b; return; } } wtk_debug("found err\n"); exit(0); return; } sign=1; a->a=0; a->b=0; j=0; for(i=step;i<n;++i) { while(bit[j]) { ++j; } //wtk_debug("j=%d\n",j); bit[j]=1; wtk_dcomplex_det(c,n,bit,&t,step+1); x=c[step*n+j]; //wtk_debug("%f+%fi %f+%fi\n",t.a,t.b,x.a,x.b); if(sign>=0) { a->a+=x.a*t.a-x.b*t.b; a->b+=x.b*t.a+x.a*t.b; }else { a->a-=x.a*t.a-x.b*t.b; a->b-=x.b*t.a+x.a*t.b; } bit[j]=0; sign=-sign; ++j; } } double wtk_dcomplex_abs_det(wtk_dcomplex_t *c,int n,char *bit) { wtk_dcomplex_t a; //char *bit; memset(bit,0,n); //bit=wtk_calloc(n,sizeof(char)); wtk_dcomplex_det(c,n,bit,&a,0); //wtk_debug("%e+i%e\n",a.a,a.b); return sqrt(a.a*a.a+a.b*a.b); } void wtk_complex_p2_print(wtk_complex_t **p,int n1,int n2) { int i,j; for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { wtk_debug("v[%d/%d]=%.12f+%.12fi\n",i,j,p[i][j].a,p[i][j].b); // if(j>0) // { // printf(" "); // } // printf("%f+%fi",p[i][j].a,p[i][j].b); } //printf("\n"); } } void wtk_complex_p2_print2(wtk_complex_t **p,int n1,int n2) { int i,j; double ta,tb; wtk_debug("================ n1=%d n2=%d ===============\n",n1,n2); ta=tb=0; for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { //wtk_debug("v[%d/%d]=%f+%fi\n",i,j,p[i][j].a,p[i][j].b); if(j>0) { printf(" "); } //printf("%e",p[i][j].a); printf("%.4f",p[i][j].a); //printf("%.4f+%.4fi",p[i][j].a,p[i][j].b); ta+=p[i][j].a; tb+=p[i][j].b; } printf("\n"); } wtk_debug("======== tot=%f+%fi ===========\n\n",ta,tb); } void wtk_complex_p2_write(wtk_complex_t **p,int n1,int n2,char *fn) { FILE *f; int i; f=fopen(fn,"wb"); for(i=0;i<n1;++i) { fwrite(p[i],n2*sizeof(wtk_complex_t),1,f); } fclose(f); } void wtk_dcomplex_p2_add_scale(wtk_dcomplex_t **dst,wtk_dcomplex_t **src,float alpha1,float alpha2,int n1,int n2) { int i,j; wtk_dcomplex_t *pdst,*psrc; for(i=0;i<n1;++i) { pdst=dst[i]; psrc=src[i]; for(j=0;j<n2;++j) { pdst[j].a=psrc[j].a*alpha1+alpha2*pdst[j].a; pdst[j].b=psrc[j].b*alpha1+alpha2*pdst[j].b; } } } void wtk_dcomplex_p2_add_scale_c(wtk_complex_t **dst,wtk_complex_t **src,float alpha,int n1,int n2) { int i,j; float alpha2=1-alpha; wtk_complex_t *pdst; wtk_complex_t *psrc; for(i=0;i<n1;++i) { pdst=dst[i]; psrc=src[i]; for(j=0;j<n2;++j) { pdst[j].a=psrc[j].a*alpha+alpha2*pdst[j].a; pdst[j].b=psrc[j].b*alpha+alpha2*pdst[j].b; } } } void wtk_dcomplex_p2_cpy(wtk_dcomplex_t **dst,wtk_dcomplex_t **src,int n1,int n2) { int i; int n; n=n2*sizeof(wtk_dcomplex_t); for(i=0;i<n1;++i) { memcpy(dst[i],src[i],n); } } void wtk_dcomplex_delete_p3(wtk_dcomplex_t ***p3,int n1,int n2) { int i,j; for(i=0;i<n1;++i) { for(j=0;j<n2;++j) { wtk_free(p3[i][j]); } wtk_free(p3[i]); } wtk_free(p3); } wtk_dcomplex_t*** wtk_dcomplex_new_p3(int n1,int n2,int n3) { wtk_dcomplex_t ***c; int i,j; c=(wtk_dcomplex_t***)wtk_calloc(n1,sizeof(wtk_dcomplex_t***)); for(i=0;i<n1;++i) { c[i]=(wtk_dcomplex_t**)wtk_calloc(n2,sizeof(wtk_dcomplex_t*)); for(j=0;j<n2;++j) { c[i][j]=(wtk_dcomplex_t*)wtk_calloc(n3,sizeof(wtk_dcomplex_t)); } } return c; } /** * cos=(x*y)/(|x|*|y|) */ float wtk_complex_distance(wtk_complex_t *a,wtk_complex_t *b,int n) { int i; float fa,fb; float f; f=0; for(i=0;i<n;++i) { fa=a->a-b->a; fb=a->b-b->b; f+=fa*fa+fb*fb; } return sqrt(f); } <file_sep>/core/math/wtk_guassrand.h #ifndef WTK_VITE_MATH_WTK_GUASSRAND_H_ #define WTK_VITE_MATH_WTK_GUASSRAND_H_ #include <math.h> #include "wtk/core/wtk_type.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_guassrand wtk_guassrand_t; struct wtk_guassrand { float V1; float V2; float S; int phase; }; void wtk_guassrand_init(wtk_guassrand_t *r); void wtk_guassrand_clean(wtk_guassrand_t *r); void wtk_guassrand_reset(wtk_guassrand_t *r); float wtk_guassrand_rand(wtk_guassrand_t *r,float mean,float delta); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/5e/5eacefd5c93292307e388188207bdc5a12ef7c29.svn-base #ifndef WTK_CORE_WTK_KCLS #define WTK_CORE_WTK_KCLS #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_heap.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_kcls wtk_kcls_t; typedef struct { wtk_queue_node_t q_n; int idx; float v; }wtk_kcls_value_t; struct wtk_kcls { wtk_queue_node_t q_n; wtk_queue_t item_q; //wtk_cls_value_t float sse; float mean; }; wtk_kcls_t* wtk_kcls_new(wtk_heap_t *heap); wtk_kcls_value_t* wtk_kcls_value_new(wtk_heap_t *heap,int idx,float f); void wtk_kcls_print(wtk_kcls_t *cls); wtk_kcls_t* wtk_kcls_cluster(wtk_kcls_t *cls,wtk_heap_t *heap,float max_sse); void wtk_kcls_select_int(int *v,int n); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/b1/b1e9493d891da14694ed3633f37ef7dff3cc5a94.svn-base #include "wtk_zip_cfg.h" int wtk_zip_cfg_init(wtk_zip_cfg_t *cfg) { cfg->blk_size=1024; cfg->bits=13; return 0; } int wtk_zip_cfg_clean(wtk_zip_cfg_t *cfg) { return 0; } int wtk_zip_cfg_update_local(wtk_zip_cfg_t *cfg,wtk_local_cfg_t *lc) { wtk_string_t *v; wtk_local_cfg_update_cfg_i(lc,cfg,blk_size,v); wtk_local_cfg_update_cfg_i(lc,cfg,bits,v); return 0; } int wtk_zip_cfg_update(wtk_zip_cfg_t *cfg) { return 0; } <file_sep>/core/param/param_serialize.c #include "param_serialize.h" #include "wtk/core/wtk_stack.h" int wtk_param_write_bin(wtk_param_t* param,wtk_stack_t* chars) { int len; int ret; len=param->value.bin.len; ret=wtk_stack_push(chars,(char*)&len,sizeof(len)); if(ret!=0){goto end;} if(len>0) { ret=wtk_stack_push(chars,(char*)param->value.bin.data,len); } end: return ret; } wtk_param_t* wtk_stack_read_bin_param(wtk_stack_t* chars)//,wtk_heap_t *heap) { wtk_param_t* result; int len,ret; result=0; ret=wtk_stack_pop(chars,(char*)&len,sizeof(len)); if(ret!=0){goto end;} result=wtk_param_new_bin(0,len);//,heap); ret=wtk_stack_pop(chars,(char*)result->value.bin.data,len); if(ret!=0) { wtk_param_delete(result); result=0; } end: return result; } wtk_param_t* wtk_stack_read_oct_param(wtk_stack_t* chars)//,wtk_heap_t *heap) { wtk_param_t* result; int len,ret; result=0; ret=wtk_stack_pop(chars,(char*)&len,sizeof(len)); if(ret!=0){goto end;} result=wtk_param_new_oct(0,len);//,heap); ret=wtk_stack_pop(chars,(char*)result->value.bin.data,len); if(ret!=0) { wtk_param_delete(result); result=0; } end: return result; } int wtk_param_write_double(wtk_param_t* param,wtk_stack_t* chars) { return wtk_stack_push(chars,(char*)&(param->value.number),sizeof(param->value.number)); } wtk_param_t* wtk_stack_read_double_param(wtk_stack_t* chars)//,wtk_heap_t *heap) { wtk_param_t* result; double number; int ret; result=0; ret=wtk_stack_pop(chars,(char*)&number,sizeof(number)); if(ret!=0){goto end;} result=wtk_param_new_number(number);//,heap); end: return result; } int wtk_param_write_str(wtk_param_t* param,wtk_stack_t* chars) { int len; int ret; len=param->value.str.len;//strlen(param->value.str.data)+1; ret=wtk_stack_push(chars,(char*)&len,sizeof(len)); if(ret!=0){goto end;} ret=wtk_stack_push(chars,(char*)param->value.str.data,len); end: return ret; } wtk_param_t* wtk_stack_read_str_param(wtk_stack_t* chars) //,wtk_heap_t *heap) { wtk_param_t* result; int len,ret; result=0; ret=wtk_stack_pop(chars,(char*)&len,sizeof(len)); if(ret!=0){goto end;} result=wtk_param_new_str(0,len);//,heap); ret=wtk_stack_pop(chars,result->value.str.data,len); if(ret!=0) { wtk_param_delete(result); result=0; } end: return result; } wtk_param_t* wtk_stack_read_array_param(wtk_stack_t* chars) //,wtk_heap_t *heap) { wtk_param_t *result,*p; int len,ret,i; result=0; ret=wtk_stack_pop(chars,(char*)&len,sizeof(len)); if(ret!=0){goto end;} result=wtk_param_new_array(len);//,heap); for(i=0;i<len;++i) { p=wtk_stack_read_param(chars);//,heap); if(p) { result->value.array.params[i]=p; }else { wtk_param_delete(result); result=0; goto end; } } end: return result; } int wtk_param_write_array(wtk_param_t *param,wtk_stack_t *chars) { int ret=0; int i,len; len=param->value.array.len; ret=wtk_stack_push(chars,(char*)&len,sizeof(len)); if(ret!=0){goto end;} for(i=0;i<len;++i) { ret=wtk_param_write(param->value.array.params[i],chars); if(ret!=0){goto end;} } end: return ret; } int wtk_stack_write_number_param(struct wtk_stack* s,double x) { wtk_param_t v; v.type=WTK_NUMBER; v.value.number=x; return wtk_param_write(&v,s); } int wtk_stack_read_number_param(wtk_stack_t* s,double *x) { wtk_param_t *p; int ret; p=wtk_stack_read_param(s);//,0); if(!p){ret=-1;goto end;} *x=p->value.number; wtk_param_delete(p); ret=0; end: return ret; } int wtk_param_write(wtk_param_t* param,wtk_stack_t* chars) { int ret; char type; if(param) { type=param->type; }else { type=WTK_NIL; } ret=wtk_stack_push(chars,&type,sizeof(type)); if(ret!=0){goto end;} if(!param){goto end;} switch(param->type) { case WTK_NIL: ret=0; break; case WTK_OCT: case WTK_BIN: ret=wtk_param_write_bin(param,chars); break; case WTK_NUMBER: ret=wtk_param_write_double(param,chars); break; case WTK_STRING: ret=wtk_param_write_str(param,chars); break; case WTK_ARRAY: ret=wtk_param_write_array(param,chars); break; } end: return ret; } int wtk_stack_write_params(wtk_stack_t* s,wtk_param_t** params,int count) { int i,ret; ret=0; for(i=0;i<count;++i) { ret=wtk_param_write(params[i],s); if(ret!=0){goto end;} } end: return ret; } wtk_param_t* wtk_stack_read_param(wtk_stack_t* chars)//,wtk_heap_t *heap) { wtk_param_t* result; int ret; char type; result=0; //wtk_debug("len=%d\n",chars->len); ret=wtk_stack_pop(chars,(char*)&type,sizeof(type)); //wtk_debug("ret=%d type=%d len=%d\n",ret,type,chars->len); if(ret!=0){goto end;} switch(type) { case WTK_NIL: result=wtk_param_new(WTK_NIL); break; case WTK_OCT: result=wtk_stack_read_oct_param(chars);//,heap); break; case WTK_BIN: result=wtk_stack_read_bin_param(chars);//,heap); break; case WTK_NUMBER: result=wtk_stack_read_double_param(chars);//,heap); break; case WTK_STRING: result=wtk_stack_read_str_param(chars);//,heap); break; case WTK_ARRAY: result=wtk_stack_read_array_param(chars);//,heap); break; } end: return result; } void wtk_func_param_write(wtk_func_param_t *param,wtk_stack_t *s) { wtk_param_t v; int i; v.type=WTK_NUMBER; v.value.number=param->valid; wtk_param_write(&v,s); for(i=0;i<param->valid;++i) { wtk_param_write(param->params[i],s); } } int wtk_func_param_read(wtk_func_param_t *param,wtk_stack_t *s) { double v; int ret=-1,i; ret=wtk_stack_read_number_param(s,&(v)); if(ret!=0){goto end;} //wtk_debug("%d\n",(int)v); param->valid=(int)v; for(i=0;i<param->valid;++i) { param->params[i]=wtk_stack_read_param(s);//,0); //wtk_debug("%p\n",param->params[i]); //wtk_param_print(param->params[i]); if(!param->params[i]){goto end;} if(param->params[i]->type==WTK_NIL) { wtk_param_delete(param->params[i]); param->params[i]=0; } } ret=0; end: return ret; } void wtk_module_param_write(wtk_module_param_t *param,wtk_stack_t *s) { wtk_stack_write_number_param(s,param->state); if(param->state & WTK_SPEECH_START) { wtk_stack_write_number_param(s,param->audio_tag.type); wtk_stack_write_number_param(s,param->audio_tag.channel); wtk_stack_write_number_param(s,param->audio_tag.samplerate); wtk_stack_write_number_param(s,param->audio_tag.samplesize); wtk_func_param_write(&(param->start),s); } if(param->state & WTK_SPEECH_APPEND) { wtk_func_param_write(&(param->append),s); } if((param->state & WTK_SPEECH_END)) { wtk_func_param_write(&(param->end),s); } } int wtk_module_param_read(wtk_module_param_t *param,wtk_stack_t *s) { double v; int ret; wtk_module_param_reset(param); ret=wtk_stack_read_number_param(s,&(v)); if(ret!=0){goto end;} param->state=(int)v; if(param->state & WTK_SPEECH_START) { ret=wtk_stack_read_number_param(s,&v); if(ret!=0){goto end;} param->audio_tag.type=(int)v; ret=wtk_stack_read_number_param(s,&v); if(ret!=0){goto end;} param->audio_tag.channel=(int)v; ret=wtk_stack_read_number_param(s,&v); if(ret!=0){goto end;} param->audio_tag.samplerate=(int)v; ret=wtk_stack_read_number_param(s,&v); if(ret!=0){goto end;} param->audio_tag.samplesize=(int)v; ret=wtk_func_param_read(&(param->start),s); if(ret!=0){goto end;} }else { param->start.valid=0; } if(param->state & WTK_SPEECH_APPEND) { ret=wtk_func_param_read(&(param->append),s); if(ret!=0){goto end;} }else { param->append.valid=0; } if(param->state & WTK_SPEECH_END) { ret=wtk_func_param_read(&(param->end),s); }else { param->end.valid=0; } end: //wtk_debug("%d\n",ret); if(ret!=0) { wtk_debug("release param...\n"); wtk_module_param_release_param(param); } return ret; } <file_sep>/core/wtk_queue2.c #include "wtk_queue2.h" /* void wtk_queue2_init(wtk_queue2_t *q) { q->pop=q->push=0; }*/ int wtk_queue2_len(wtk_queue2_t *q) { wtk_queue_node_t *n=q->pop; int len; len=0; while(n) { ++len; n=n->next; } return len; } void wtk_queue2_push(wtk_queue2_t *q,wtk_queue_node_t *n) { n->prev=q->push; if(q->push) { q->push->next=n; } n->next=0; q->push=n; if(!q->pop) { q->pop=n; } } void wtk_queue2_touch_node(wtk_queue2_t *q,wtk_queue_node_t *n) { if(n->prev) { n->prev->next=n->next; }else { q->pop=n->next; } if(n->next) { n->next->prev=n->prev; }else { q->push=n->prev; } n->prev=q->push; if(q->push) { q->push->next=n; } q->push=n; n->next=NULL; if(!q->pop) { q->pop=n; } } void wtk_queue2_push_front(wtk_queue2_t *q,wtk_queue_node_t *n) { n->next=q->pop; if(q->pop) { q->pop->prev=n; } n->prev=0; q->pop=n; if(!q->push) { q->push=n; } } void wtk_queue2_insert_to(wtk_queue2_t *q,wtk_queue_node_t *n,wtk_queue_node_t* n2) { if(n==q->push) { wtk_queue2_push(q,n2); }else { n2->prev=n; n2->next=n->next; n2->next->prev=n2->prev->next=n2; } return; } /** * n0->n2->n3 * => n0->n1->n2->n3 * n1 */ void wtk_queue2_insert_before(wtk_queue2_t *q,wtk_queue_node_t *n2,wtk_queue_node_t *n1) { n1->prev=n2->prev; if(n1->prev) { n1->prev->next=n1; }else { q->pop=n1; } n2->prev=n1; n1->next=n2; } wtk_queue_node_t* wtk_queue2_pop(wtk_queue2_t *q) { wtk_queue_node_t* n; n=0; if(!q->pop){goto end;} n=q->pop; q->pop=q->pop->next; if(q->pop) { q->pop->prev=0; }else { q->push=0; } end: return n; } void wtk_queue2_remove(wtk_queue2_t *q,wtk_queue_node_t *n) { if(n->prev) { n->prev->next=n->next; }else { q->pop=n->next; } if(n->next) { n->next->prev=n->prev; }else { q->push=n->prev; } n->prev=n->next=0; } <file_sep>/core/wtk_hash.h #ifndef WTK_CORE_WTK_HASH_H_ #define WTK_CORE_WTK_HASH_H_ #include "wtk/core/wtk_queue.h" #include "wtk/core/wtk_heap.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_hash wtk_hash_t; typedef unsigned int (*wtk_hash_f)(void* v,unsigned int nslot); /** * @return 0 on equal. */ typedef int (*wtk_cmp_f)(void *v,void *k); typedef struct { wtk_queue_node_t q_n; void *v; }wtk_hash_node_t; struct wtk_hash { wtk_heap_t *heap; wtk_queue_t **slot; unsigned int nslot; }; /** * @brief create hash table; */ wtk_hash_t* wtk_hash_new(int nslot); /** * @brief delete hash table; */ int wtk_hash_delete(wtk_hash_t *h); /** * @brief reset hash table; */ int wtk_hash_reset(wtk_hash_t *h); int wtk_hash_bytes(wtk_hash_t *h); /** * @brief add element use hf hash v; */ int wtk_hash_add(wtk_hash_t *h,void *v,wtk_hash_f hf); int wtk_hash_add2(wtk_hash_t *h,unsigned int id,void *v); int wtk_hash_add_node(wtk_hash_t *h,void *v,wtk_hash_node_t *n,wtk_hash_f hf); /** * @brief * hf, hash(k) * cf: cmp(v,k) */ wtk_hash_node_t* wtk_hash_find_node(wtk_hash_t *h,void *k,wtk_hash_f hf,wtk_cmp_f cf); /** * @brief find value by hf,cf; */ void* wtk_hash_find(wtk_hash_t *h,void *k,wtk_hash_f hf,wtk_cmp_f cf); wtk_hash_node_t* wtk_hash_remove(wtk_hash_t *h,void *k,wtk_hash_f hf,wtk_cmp_f cf); /** * @brief elements of hash; */ int wtk_hash_len(wtk_hash_t *h); /*-------------------------------------------------------------------------*/ /** * in handler(void* user_data,void* data),data is an pointer to wtk_hash_node_t. */ /*--------------------------------------------------------------------------*/ int wtk_hash_walk(wtk_hash_t* h,wtk_walk_handler_t handler,void* user_data); void wtk_hash_print(wtk_hash_t *h); //-------------------- iterator section ---------------------- typedef struct { wtk_hash_t *hash; wtk_queue_node_t *cur_n; int next_index; }wtk_hash_it_t; wtk_hash_it_t wtk_hash_iterator(wtk_hash_t *hash); wtk_hash_node_t* wtk_hash_it_next(wtk_hash_it_t *it); //--------------------- hash function ------------------------- unsigned int wtk_hash_intptr(int *v,unsigned int nslot); int wtk_hash_cmp_intptr(int *v1,int *v2); //--------------------- test/example section ------------------- void wtk_hash_test_g(); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/13/137e7708b1db58c8db2ff73158cfbf0e51bf9d30.svn-base #ifndef WTK_FST_REC_WTK_PRUNE #define WTK_FST_REC_WTK_PRUNE #include "wtk/core/wtk_type.h" #include "wtk_prune_cfg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_prune wtk_prune_t; struct wtk_prune { wtk_prune_cfg_t *cfg; float max; float min; int nbin; float bin_width_scale; float min_x; unsigned int *bins; unsigned int count; float thresh; }; wtk_prune_t* wtk_prune_new(wtk_prune_cfg_t *cfg); void wtk_prune_delete(wtk_prune_t *p); void wtk_prune_reset(wtk_prune_t *p); void wtk_prune_add(wtk_prune_t *p,float f); float wtk_prune_get_thresh(wtk_prune_t *p); float wtk_prune_get_thresh2(wtk_prune_t *p,int count); void wtk_prune_update_thresh(wtk_prune_t *p); int wtk_prune_want_prune(wtk_prune_t *p); void wtk_prune_plus(wtk_prune_t *dst,wtk_prune_t *src); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_robin.h #ifndef WTK_CORE_WTK_ROBIN_H_ #define WTK_CORE_WTK_ROBIN_H_ #include "wtk/core/wtk_type.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_robin wtk_robin_t; #define wtk_robin_at(rb,i) ((rb)->r[((rb)->pop+(i))%((rb)->nslot)]) #define wtk_robin_is_full(rb) ((rb)->nslot==(rb)->used) /** * @brief robin is used for save fixed size array; */ struct wtk_robin { int nslot; //slots of robin int pop; //the first valid data slot int used; //length of valid data void **r; }; wtk_robin_t* wtk_robin_new(int n); int wtk_robin_delete(wtk_robin_t* r); void wtk_robin_push(wtk_robin_t* r,void *d); void* wtk_robin_push2(wtk_robin_t *r,void *d); void* wtk_robin_pop(wtk_robin_t *r); void wtk_robin_pop2(wtk_robin_t *r,int n); void wtk_robin_reset(wtk_robin_t *r); void* wtk_robin_next(wtk_robin_t* r); /** * @brief used for window shift */ void wtk_robin_peek_win_array(wtk_robin_t *robin,void **array,int pad_end); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/43/43e5fa5f73cbadc96bddfa1428fc95ed0cec9f4e.svn-base #ifndef WLIB_CORE_WTK_ALLOC_H_ #define WLIB_CORE_WTK_ALLOC_H_ #include <stdlib.h> #include "wtk_type.h" #ifdef USE_MALLOC_H #include <malloc.h> #endif #ifdef __cplusplus extern "C" { #endif #define MEM_INLINE #define WTK_ALIGNMENT ((int)(sizeof(unsigned long))) /* platform word */ #define WTK_ALIGNMENT_BIT (WTK_ALIGNMENT<<3) #ifdef WIN32 #define wtk_align_ptr(ptr, align) \ ((align)>0 ? (void*)(((uintptr_t)(ptr)+(uintptr_t)(align - 1)) & (~((uintptr_t)(align - 1)))) : ptr) #else #define wtk_align_ptr(ptr, align) \ ((align)>0 ? (void*)(((unsigned long)(ptr)+(align - 1)) & (~(align - 1))) : ptr) #endif /* #define wtk_align_ptr(p, a) \ (uint8_t*)(((unsigned int)(p)+(a-1)) & (~(a-1))) */ #define wtk_round(size,align) \ ((align)>0 ? (((size)+((align)-1))&(~((align)-1))) : size) #define wtk_round_8(size) ((((size)&7)==0)? (size) : ((size)+8-((size)&7))) #define wtk_round_16(size) ((((size)&15)==0)? (size) : ((size)+16-((size)&15))) //#define wtk_round_word(size) ((((size)&(WTK_ALIGNMENT_BIT-1))==0)? (size) : ((size)+WTK_ALIGNMENT_BIT-((size)&(WTK_ALIGNMENT_BIT-1)))) #define wtk_round_word(size) wtk_round_16(size) //for old version #define wtk_round8(size) wtk_round_8(size) //#define DEBUG_MEM #ifdef MEM_INLINE #ifdef DEBUG_MEM #define wtk_free(p) wtk_free_debug(p,__FUNCTION__,__LINE__) #define wtk_malloc(n) wtk_malloc_debug(n,__FUNCTION__,__LINE__) #define wtk_calloc(nmem,size) wtk_calloc_debug(nmem,size,__FUNCTION__,__LINE__) #else #define wtk_free(p) free(p) #define wtk_malloc(n) malloc(n) #define wtk_calloc(nmem,size) calloc(nmem,size) #endif #else void wtk_free(void* p); void* wtk_malloc(size_t n); void* wtk_calloc(int elems,int size); #endif char* wtk_data_cpy(char *data,int len); void* wtk_memalign(size_t alignment,size_t size); void print_data(char* data, int len); #ifdef DEBUG_MEM void* wtk_calloc_debug(int elems,int size,const char *f,int line); void* wtk_malloc_debug(size_t n,const char *f,int line); void wtk_free_debug(void *p,const char *f,int line); #endif #ifdef __cplusplus }; #endif #endif <file_sep>/os/.svn/pristine/55/55c7bd35ac4666a41f588d97035ade8070202e3c.svn-base #ifndef WTK_OS_WTK_SEMSHM_H_ #define WTK_OS_WTK_SEMSHM_H_ #include "wtk/core/wtk_type.h" #include <sys/ipc.h> #include <sys/shm.h> #include <unistd.h> #include <semaphore.h> #ifdef __cplusplus extern "C" { #endif typedef struct wtk_semshm wtk_semshm_t; typedef void(*wtk_semshm_read_f)(void *hook,const char *data,int bytes); typedef struct { sem_t readable_sem; //shared allocated in addr; sem_t writeable_sem; //shared allocated in addr; int user_data_len; //bytes of valid user data; }wtk_semshm_shared_t; /* * @brief blocked for read and write; used for one process write and another read; */ struct wtk_semshm { int shm_id; void *addr; //mapped user data; wtk_semshm_shared_t *shared; //shared data for process; char *user_data; //pointer the valid user data; int user_data_bytes; //bytes of allocated user data; }; wtk_semshm_t* wtk_semshm_new(int shm_bytes); int wtk_semshm_delete(wtk_semshm_t *s); /* * @brief will read all shared data; */ int wtk_semshm_read(wtk_semshm_t *s,void *hook,wtk_semshm_read_f read); /** * @brief readable will not; */ int wtk_semshm_readable(wtk_semshm_t *s); /** * @brief write data to semshm, blocked for all data is write to shared memory; */ int wtk_semshm_write(wtk_semshm_t *s,const char *data,int bytes); /** * @brief nattach porcess of current shared memory; */ int wtk_semshm_nattach(wtk_semshm_t *s); /** * @brief notify semshm read, used for wake up read blocked thread. */ void wtk_semshm_wake_read(wtk_semshm_t *s); /** * @brief notify semshm write, used for wake up write blocked thread; */ void wtk_semshm_wake_write(wtk_semshm_t *s); /** * @brief notify semshm read and write; */ void wtk_semshm_wake_rw(wtk_semshm_t *s); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/3c/3ccbb69261ebcce5760f050259822b974a01bb16.svn-base #include "wtk_rbtree.h" wtk_rbtree_t* wtk_rbtree_new() { wtk_rbtree_t* t; t=(wtk_rbtree_t*)wtk_calloc(1,sizeof(wtk_rbtree_t)); t->len=0; return t; } int wtk_rbtree_delete(wtk_rbtree_t* t) { wtk_free(t); return 0; } void wtk_rbtree_init(wtk_rbtree_t *t) { t->root=0; t->len=0; } void wtk_rbnode_insert(wtk_rbnode_t *r,wtk_rbnode_t *n) { wtk_rbnode_t **p; for(;;) { //found node with empty child. p= (n->key < r->key) ? &(r->left) : &(r->right); if(!*p){break;} r=*p; } *p=n; n->parent=r; n->left=n->right=0; wtk_rbnode_red(n); } wtk_rbnode_t* wtk_rbtree_find(wtk_rbtree_t *t,wtk_rbnode_key_t key) { wtk_rbnode_t *p,*n; float v; p=t->root;n=0; while(p) { v=key-p->key; if(v<0) { p=p->left; }else if(v>0) { p=p->right; }else { n=p; break; } } return n; } wtk_rbnode_t* wtk_rbtree_find_like(wtk_rbtree_t *t,wtk_rbnode_key_t key) { wtk_rbnode_t *p,*n,*prev; float v; p=t->root;n=0; prev=p; while(p) { prev=p; v=key-p->key; if(v<0) { p=p->left; }else if(v>0) { p=p->right; }else { n=p; break; } } if(!n) { n=p?p:prev; } return n; } //i do not use macro or offset to make this code be shorter for want it //be clear. void wtk_rbtree_right_rotate(wtk_rbtree_t *t,wtk_rbnode_t *n) { wtk_rbnode_t *l; l=n->left; n->left=l->right; if(l->right){l->right->parent=n;} l->parent=n->parent; if(n->parent) { if(n == n->parent->left) { n->parent->left=l; }else { n->parent->right=l; } }else { t->root=l; } l->right=n; n->parent=l; } void wtk_rbtree_left_rotate(wtk_rbtree_t *t,wtk_rbnode_t *n) { wtk_rbnode_t *r; r=n->right; if(!r){return;} n->right=r->left; if(r->left){r->left->parent=n;} r->parent=n->parent; if(n->parent) { if(n == n->parent->left) { n->parent->left=r; }else { n->parent->right=r; } }else { t->root=r; } r->left=n; n->parent=r; } void wtk_rbtree_insert_fixup(wtk_rbtree_t *t,wtk_rbnode_t *n) { wtk_rbnode_t *p,*pp,*rpp,*lpp; for(p=n->parent;p && wtk_rbnode_is_red(p);p=n->parent) { pp=p->parent; if(!pp){break;} //wtk_debug("pp=%p l=%p r=%p p=%p r=%p:%p\n",pp,pp->left,pp->right,p,t->root,t->root->parent); if(p == pp->left) { rpp=pp->right; if(wtk_rbnode_is_red(rpp)) { wtk_rbnode_black(p); wtk_rbnode_black(rpp); wtk_rbnode_red(pp); n=pp; continue; }else { if(n == p->right) { wtk_rbtree_left_rotate(t,p); p=n; } wtk_rbnode_black(p); wtk_rbnode_red(pp); wtk_rbtree_right_rotate(t,pp); break; } }else { lpp=pp->left; if(wtk_rbnode_is_red(lpp)) { wtk_rbnode_black(p); wtk_rbnode_black(lpp); wtk_rbnode_red(pp); n=pp; continue; }else { if( n == p->left) { wtk_rbtree_right_rotate(t,p); p=n; } wtk_rbnode_black(p); wtk_rbnode_red(pp); wtk_rbtree_left_rotate(t,pp); break; } } } wtk_rbnode_black(t->root); } void wtk_rbtree_insert(wtk_rbtree_t *t,wtk_rbnode_t *n) { //wtk_debug("node=%p\n",n); ++t->len; n->left=n->right=n->parent=0; if(!t->root) { t->root=n; wtk_rbnode_black(n); return; } wtk_rbnode_insert(t->root,n); wtk_rbtree_insert_fixup(t,n); return; } void wtk_rbtree_delete_fixup(wtk_rbtree_t *t,wtk_rbnode_t *n,wtk_rbnode_t *p) { wtk_rbnode_t *rp,*lp; for(;n!=t->root && wtk_rbnode_is_black(n);p=n->parent) { if(n == p->left) { rp=p->right; if(wtk_rbnode_is_red(rp)) { wtk_rbnode_black(rp); wtk_rbnode_red(p); wtk_rbtree_left_rotate(t,p); rp=p->right; } if(!rp || (wtk_rbnode_is_black(rp->left) && wtk_rbnode_is_black(rp->right))) { if(rp){wtk_rbnode_red(rp);} n=p; continue; } if(wtk_rbnode_is_black(rp->right)) { wtk_rbnode_black(rp->left); wtk_rbnode_red(rp); wtk_rbtree_right_rotate(t,rp); rp=p->right; } rp->color=p->color; wtk_rbnode_black(p); wtk_rbnode_black(rp->right); wtk_rbtree_left_rotate(t,p); n=t->root; break; }else { lp = p->left; if(wtk_rbnode_is_red(lp)) { if(lp){wtk_rbnode_black(lp);} wtk_rbnode_red(p); wtk_rbtree_right_rotate(t,p); lp=p->left; } if(!lp || (wtk_rbnode_is_black(lp->left) && wtk_rbnode_is_black(lp->right))) { wtk_rbnode_red(lp); n=p; continue; } if(wtk_rbnode_is_black(lp->left)) { wtk_rbnode_black(lp->right); wtk_rbnode_red(lp); wtk_rbtree_left_rotate(t,lp); lp=p->left; } lp->color=p->color; wtk_rbnode_black(p); wtk_rbnode_black(lp->left); wtk_rbtree_right_rotate(t,p); n=t->root; break; } } wtk_rbnode_black(n); } void wtk_rbtree_remove(wtk_rbtree_t *t,wtk_rbnode_t *n) { wtk_rbnode_t *subst,*tmp,*p; int red; //wtk_debug("root=%p n=%p l=%p r=%p\n",t->root,n,n->left,n->right); --t->len; p=0; if(!n->left) { tmp=n->right; subst=n; }else if(!n->right) { tmp=n->left; subst=n; }else { subst=(wtk_rbnode_t*)wtk_treenode_min((wtk_treenode_t*)n->right); if(subst->left) { tmp=subst->left; }else { tmp=subst->right; } } if(subst == t->root) { t->root=tmp; wtk_rbnode_black(tmp); n->left=n->parent=n->right=0; if(tmp) { tmp->parent=NULL; } return; } red=wtk_rbnode_is_red(subst); if(subst == subst->parent->left) { subst->parent->left=tmp; }else { subst->parent->right=tmp; } if(subst == n) { if(tmp) { tmp->parent=subst->parent; }else { p=subst->parent; } }else { if(subst->parent == n) { if(tmp) { tmp->parent=subst; }else { p=subst; } }else { if(tmp) { tmp->parent=subst->parent; }else { p=subst->parent; } } subst->left=n->left; subst->right=n->right; subst->parent=n->parent; subst->color=n->color; if(n==t->root) { t->root=subst; if(subst && subst->parent) { subst->parent=NULL; } }else { if(n==n->parent->left) { n->parent->left=subst; }else { n->parent->right=subst; } } if(subst->left){subst->left->parent=subst;} if(subst->right){subst->right->parent=subst;} } n->left=n->parent=n->right=0; //printf("subst=%d,tmp=%p,p=%d\n",subst->key,tmp,p->key); //wtk_rbtree_print(t); //wtk_debug("root=%p\n",t->root); if(red){return;} if(tmp) { wtk_rbtree_delete_fixup(t,tmp,tmp->parent); }else { wtk_rbtree_delete_fixup(t,tmp,p); } return; } int wtk_rbnode_valid(void* data,wtk_rbnode_t *n) { int ret; if(!wtk_rbnode_is_red(n)){ret=0;goto end;} ret=-1; if(wtk_rbnode_is_red(n->left)) { printf("left node is red.\n"); goto end; } if(wtk_rbnode_is_red(n->right)) { printf("right node is red.\n"); goto end; } ret=0; end: return ret; } int wtk_rbnode_black_depth(wtk_rbnode_t *n,int n_depth) { int d_left,d_right; if(!n){goto end;} if(wtk_rbnode_is_black(n)) { n_depth += 1; } d_left=wtk_rbnode_black_depth(n->left,0); if(d_left<0){n_depth=-1;goto end;} d_right=wtk_rbnode_black_depth(n->right,0); if(d_right<0){n_depth=-1;goto end;} if(d_left != d_right) { printf("%f(left=%d,right=%d) depth not equal.\n",n->key,d_left,d_right); n_depth=-1; goto end; } n_depth += d_left; end: return n_depth; } int wtk_rbtree_is_valid(wtk_rbtree_t *t) { int ret; int len; if(t->root && t->root->parent) { wtk_debug("found parent\n"); ret=0; goto end; } len=wtk_treenode_len((wtk_treenode_t*)t->root); if(len!=t->len) { //wtk_debug("len[%d/%d] not eq\n",len,t->len); ret=0; goto end; } if(!t->root) { if(t->len==0) { ret=1; }else { ret=0; } goto end; } ret=0; if(wtk_rbnode_is_red(t->root)){goto end;} ret=wtk_treenode_traverse((wtk_treenode_t*)t->root,(WtkTreeNodeTraverseFunc)wtk_rbnode_valid,0); if(ret!=0) { printf("red-black tree color is not right.\n"); goto end; } ret=wtk_rbnode_black_depth(t->root,0); ret=ret > 0 ? 1 : 0; end: if(ret!=1) { exit(0); } return ret; } void wtk_rbnode_print(wtk_rbnode_t *n) { printf("%f(%s:%p)\n",n->key,n->color?"r":"b",(n)); } void wtk_rbtree_print(wtk_rbtree_t *t) { printf("##############################################\n"); wtk_treenode_print((wtk_treenode_t*)t->root,0,(WtkTreeNodePrintFunc)wtk_rbnode_print); printf("##############################################\n"); } int wtk_rbtree_depth(wtk_rbtree_t *t) { return wtk_treenode_depth((wtk_treenode_t*)t->root,0); } <file_sep>/os/wtk_sem.h #ifndef WTK_OS_WTK_SEM_H_ #define WTK_OS_WTK_SEM_H_ #include "wtk/core/wtk_type.h" //#define __USE_XOPEN2K //#define _XOPEN_SOURCE 600 #ifdef __cplusplus extern "C" { #endif #ifndef WIN32 typedef sem_t wtk_sem_t; #define wtk_sem_init(s,c) sem_init(s,0,c) #define wtk_sem_clean(s) sem_destroy(s) #define wtk_sem_tryacquire(s) sem_trywait(s) #define wtk_sem_inc(s) sem_post(s) #ifdef USE_ARM #else /** * @brief create semaphore for shared access; and can be used by processes; * * sem_init; * * sem_open; */ wtk_sem_t* wtk_sem_new_shared(); /** * @brief delete shared semaphore; */ void wtk_sem_delete_shared(wtk_sem_t *s); #endif #else typedef HANDLE wtk_sem_t; int wtk_sem_init(wtk_sem_t *s,int init_count); int wtk_sem_clean(wtk_sem_t *s); #define wtk_sem_inc(s) wtk_sem_release(s,1) #endif int wtk_sem_acquire(wtk_sem_t *s,int ms); int wtk_sem_release(wtk_sem_t *s, int count); int wtk_sem_drain(wtk_sem_t *s); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_time.c #include "wtk_time.h" int wtk_time_is_leap_year(int y) { int leap_year; if((y%400==0) && (y%4==0 && y%100!=0)) { leap_year=1; }else { leap_year=0; } return leap_year; } /** * m=[1,12] */ int wtk_time_month_max_day(int m,int y) { if(m<=7) { if(m%2==1) { return 31; }else { if(m==2) { if(wtk_time_is_leap_year(y)) { return 29; }else { return 28; } }else { return 30; } } }else { if(m%2==0) { return 31; }else { return 30; } } } <file_sep>/core/wtk_str.h #ifndef WTK_STRING_WTK_STR_H_ #define WTK_STRING_WTK_STR_H_ #include "wtk/core/wtk_type.h" #include <stdlib.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif typedef struct wtk_string wtk_string_t; #define is_hex(c) (((c)>='0' && (c)<='9')||((c)>='A' && (c)<='F') || ((c)>='a' && (c)<='f')) #define wtk_string(s) {s,sizeof(s)-1} #define wtk_string_dup(s) wtk_string_dup_data(s,sizeof(s)) #define wtk_string_end(s) ((s)->data+(s)->len) #define wtk_string_set(str,d,bytes) (str)->data=d;(str)->len=bytes; #define wtk_string_set_s(str,data) wtk_string_set(str,data,sizeof(data)-1) #define wtk_string_cmp_s(str,s) wtk_string_cmp(str,s,sizeof(s)-1) #define wtk_string_cmp_s_withstart(str,s) wtk_string_cmp_withstart(str,s,sizeof(s)-1) #define wtk_string_equal_s(str,s) (((str)->len == (sizeof(s)-1)) && (strncmp((str)->data,s,sizeof(s)-1)==0)) #define wtk_str_equal(s1,ns1,s2,ns2) ( (ns1==ns2) && (strncmp(s1,s2,ns1)==0)) #define wtk_str_equal_s(s1,ns1,s2) wtk_str_equal(s1,ns1,s2,sizeof(s2)-1) #define wtk_string_equal(str1,str2) (((str1)->len==(str2)->len) && (strncmp((str1)->data,(str2)->data,(str1)->len)==0)) #define ngx_str3_cmp(m,c0,c1,c2) \ (m[0] == c0 && m[1]==c1 && m[2] == c2) #define ngx_str4_cmp(m,c0,c1,c2,c3) \ (m[0] == c0 && m[1]==c1 && m[2] == c2 && m[3]==c3) #define wtk_string_print(s) printf("%.*s\n",(s)->len,(s)->data) #define wtk_string_str_s(str,s) wtk_string_str(str,s,sizeof(s)-1) #define wtk_str_str_s(str,len,s) wtk_str_str(str,len,s,sizeof(s)-1) #define wtk_str_end_with_s(data,len,suf) wtk_str_end_with(data,len,suf,sizeof(suf)-1) #define wtk_str_start_with_s(data,len,suf) wtk_str_start_with(data,len,suf,sizeof(suf)-1) #define wtk_string_cmp_withstart_s(s,data) wtk_string_cmp_withstart(s,data,sizeof(data)-1) struct wtk_string { char* data; int len; }; wtk_string_t* wtk_string_new(int len); int wtk_string_delete(wtk_string_t *s); wtk_string_t* wtk_string_dup_data(char* data,int len); wtk_string_t* wtk_string_dup_data_pad0(char* data,int len); char* wtk_string_to_str(wtk_string_t *s); int wtk_string_cmp_withstart(wtk_string_t* str, char*s, int bytes); int wtk_str_end_with(char *data,int len,char *suf,int suf_bytes); int wtk_str_start_with(char *data,int len,char *suf,int suf_bytes); int wtk_string_cmp(wtk_string_t *str,char* s,int bytes); int wtk_data_cmp(char *str,int str_bytes,char* s,int bytes); int wtk_string_cmp2(wtk_string_t *str1,wtk_string_t *str2); int wtk_string_is_char_in(wtk_string_t *s,char c); int wtk_string_array_has(wtk_string_t **strs,int n,wtk_string_t *s); unsigned int wtk_string_to_ord(wtk_string_t *str); char* wtk_str_dup(const char* str); int wtk_string_char_count(wtk_string_t *str,char c); int wtk_str_char_count(const char *s,char c); /** * @brief like stdlib:atoi */ long long wtk_str_atoi(char* s,int len); /** * @brief like stdlib:atof */ double wtk_str_atof(char *s,int len); char* wtk_data_dup(const char* data,size_t data_len,size_t alloc_len); char* wtk_data_dup2(char *data,int bytes); char* wtk_data_to_str(char *data,int len); void print_hex(char *data,int len); void print_char(unsigned char *data,int len); /** * @brief print data in readable format; */ void print_data(char* data, int len); void print_short(short *f,int len); void print_short2(short *f,int len); void print_int(int *f,int len); void print_char2(signed char *f,int len); void print_uchar(unsigned char *f,int len); void print_data_f(FILE* f,char* data, int len); void print_data_f2(FILE* f,char* data, int len,int cn); int zero_dispose(void *data); char* str_merge(char* arg1,...); char *wtk_str_found(char *src,char *key,int key_bytes); /** * find the first occurrence of the sub string in src. */ int wtk_string_str(wtk_string_t *str,char *sub,int bytes); char* wtk_str_chr(char* s,int slen,char c); char* wtk_str_rchr(char *s,int len,char c); int wtk_str_str(char *src,int src_len,char *sub,int bytes); int wtk_char_to_hex(char c); uint32_t hash_string_value(char* name); uint32_t hash_string(char* name, uint32_t hash_size); //uint32_t hash_string_value_len(char* data,int len,int hash_size); uint32_t hash_string_value_len_seed(unsigned char* p,int len,int hash_size); #define hash_string_value_len(p,len,slot) hash_string_value_len_seed((unsigned char*)p,len,slot) char* wtk_itoa(int n); //---------------------- string util section -------------------- typedef void (*wtk_str_split_f)(void *ths,char *item,int len,int index); typedef int (*wtk_str_split_is_sep_f)(void *ths,char c); int wtk_str_split(char *data,int len,char sep,void *split_ths,wtk_str_split_f split); int wtk_str_split2(char *data,int len,void *split_ths,wtk_str_split_f split,wtk_str_split_is_sep_f is_sep); void print_float(float *f,int len); void print_float2(float *f,int len); void print_double(double *f,int len); void print_double2(double *f,int len); void print_double3(double *f,int len); int wtk_chnstr_atoi(char *data,int len,int *left); int wtk_chnstr_atoi2(char *data,int len); int wtk_chnstr_atoi3(char *s,int len); int wtk_chnstr_atoi4(char *s,int len); int wtk_str_atoi2(char *data,int len,int *left); int wtk_is_all_digit(char *data,int len); int wtk_num_get_unit(int num); wtk_string_t* wtk_chnstr_itoa(int v); //-------------------- string format parser -------------------------- typedef void(*wtk_str_attr_f)(void *ths,wtk_string_t *k,wtk_string_t *v); /** * [a=1,b,c=d] */ int wtk_str_attr_parse(char *data,int bytes,void *ths,wtk_str_attr_f attr_notify); int wtk_str_attr_parse2(char *data,int bytes,void *ths,wtk_str_attr_f attr_notify,int *consume); void print_hex2(char *data,int len); typedef void(*wtk_str_chnwrd_f)(void *ths,char *data,int len); void wtk_str_parse_chnwrd(char *data,int len,void *ths,wtk_str_chnwrd_f wrd); typedef struct { char *s; char *e; }wtk_str_chnwrd_iter_t; void wtk_str_chnwrd_iter_init(wtk_str_chnwrd_iter_t *iter,char *data,int len); wtk_string_t wtk_str_chnwrd_iter_next(wtk_str_chnwrd_iter_t *iter); typedef struct { char *s; char *e; }wtk_str_spwrd_iter_t; void wtk_str_spwrd_iter_init(wtk_str_spwrd_iter_t *iter,char *data,int len); wtk_string_t wtk_str_spwrd_iter_next(wtk_str_spwrd_iter_t *iter); void float_nan_check(float *f,int len); void wtk_float_print2(float **f,int n1,int n2); #ifdef __cplusplus }; #endif #endif <file_sep>/core/cfg/wtk_source.h #ifndef WTK_MODEL_WTK_SOURCE_H_ #define WTK_MODEL_WTK_SOURCE_H_ #include "wtk/core/wtk_str.h" #include "wtk/core/wtk_strbuf.h" #include "wtk/core/wtk_str_encode.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_source wtk_source_t; typedef struct wtk_source_loader wtk_source_loader_t; typedef int (*wtk_source_get_handler_t)(void*); typedef int (*wtk_source_get_str_f)(void*,char *buf,int bytes); typedef int (*wtk_source_read_str_f)(void*,wtk_strbuf_t *buf); typedef wtk_string_t* (*wtk_source_get_file_f)(void*); typedef int (*wtk_soure_get_file_size_f)(void*); typedef int (*wtk_source_unget_handler_t)(void*,int); typedef int (*wtk_source_load_handler_t)(void *data_ths,wtk_source_t *s); typedef int (*wtk_source_loader_v_t)(void* inst,void *data,wtk_source_load_handler_t loader,char *fn); #define wtk_source_get(s) ((s)->get((s)->data)) //#define wtk_source_get(s) wtk_source_read_char(s) #define wtk_source_unget(s,c) ((s)->unget((s)->data,c)) #define wtk_source_seek_to_s(s,d) wtk_source_seek_to(s,d,sizeof(d)-1) #define wtk_source_seek_to2_s(s,d,b) wtk_source_seek_to2(s,d,sizeof(d)-1,b) typedef struct { FILE *f; unsigned char *buf; unsigned char *valid; unsigned char *cur; unsigned eof:1; int alloc; }wtk_source_file_item_t; struct wtk_source { wtk_source_get_handler_t get; wtk_source_unget_handler_t unget; wtk_source_get_str_f get_str; wtk_source_read_str_f read_str; wtk_source_get_file_f get_file; //wtk_soure_get_file_size_f get_filesize; void *data; unsigned char swap:1; //wtk_strbuf_t *buf; }; struct wtk_source_loader { void *hook; wtk_source_loader_v_t vf; }; void wtk_source_init(wtk_source_t *src); void wtk_swap_short(short *p); void wtk_swap_int32(int *p); int wtk_is_little_endian(); int wtk_file_write_float(FILE *file,float *f,int n,int bin,int swap); int wtk_source_init_file(wtk_source_t *s,char *fn); int wtk_source_clean_file(wtk_source_t *s); int wtk_source_init_file2(wtk_source_t *s,char *fn); int wtk_source_clean_file2(wtk_source_t *s); int wtk_source_init_str(wtk_source_t *s,const char *data,int bytes); void wtk_source_set_str(wtk_source_t *s,const char *data,int bytes); int wtk_source_clean_str(wtk_source_t *s); int wtk_source_init_fd(wtk_source_t *s,FILE *f,int pos); int wtk_source_clean_fd(wtk_source_t *s); /** * @brief input buf b will be reset */ int wtk_source_read_string(wtk_source_t *s,wtk_strbuf_t *b); /** * @brief input buf b will not be reset */ int wtk_source_read_string2(wtk_source_t *s,wtk_strbuf_t *b); int wtk_source_read_string3(wtk_source_t *s,wtk_strbuf_t *b); int wtk_source_read_normal_string(wtk_source_t *s,wtk_strbuf_t *b); int wtk_source_read_wtkstr(wtk_source_t *s,wtk_strbuf_t *b); int wtk_source_read_wtkstr2(wtk_source_t *s,wtk_strbuf_t *b,int bi); int wtk_source_read_line(wtk_source_t *s,wtk_strbuf_t *b); int wtk_source_read_line2(wtk_source_t *s,wtk_strbuf_t *b,int *eof); int wtk_source_skip_sp(wtk_source_t *s,int *nl); int wtk_source_skip_sp2(wtk_source_t *s,int *nl,int *eof); int wtk_source_skip_sp3(wtk_source_t *s,int *nl); int wtk_source_peek(wtk_source_t *s); int wtk_source_fill(wtk_source_t* s,char* data,int len); int wtk_source_read_short(wtk_source_t* s,short* v,int n,int bin); int wtk_source_read_ushort(wtk_source_t* s,unsigned short* v,int n,int bin); int wtk_source_read_int(wtk_source_t *s,int* v,int n,int bin); int wtk_source_atof(wtk_source_t* s,double *v); int wtk_source_atoi(wtk_source_t* s,int* value); int wtk_source_read_double(wtk_source_t *s,double *f,int n); int wtk_source_read_float(wtk_source_t *s,float *f,int n,int bin); int wtk_source_read_char(wtk_source_t *s); int wtk_source_read_utf8_char(wtk_source_t *s,wtk_strbuf_t *buf); int wtk_source_seek_to(wtk_source_t *s,char *data,int len); int wtk_source_seek_to2(wtk_source_t *src,char *data,int len,wtk_strbuf_t *buf); int wtk_source_load_file(void *data,wtk_source_load_handler_t loader,char *fn); int wtk_source_load_file_v(void *hook,void *data,wtk_source_load_handler_t loader,char *fn); void wtk_source_loader_init_file(wtk_source_loader_t *sl); int wtk_source_loader_load(wtk_source_loader_t *l,void *data_ths,wtk_source_load_handler_t loader,char *fn); int wtk_source_loader_file_lines(wtk_source_loader_t *sl,char *fn); wtk_string_t* wtk_source_read_file(wtk_source_t *src); void wtk_source_read_file2(wtk_source_t *src,wtk_strbuf_t *buf); float* wtk_file_read_float(char *fn,int *n); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/35/35bdebef1e6d4268eec12721f3519e691213a8f6.svn-base #include "wtk_gbk.h" #include "gbk.h" unsigned int convert_to_gbk(unsigned int uni_code) { const unsigned short *page = from_uni[(uni_code >> 8) & 0xFF]; return page == NULL ? 0x3F : page[uni_code & 0xFF]; } unsigned int convert_from_gbk(unsigned int gbk_code) { const unsigned short *page = to_uni[(gbk_code >> 8) & 0xFF]; return page == NULL ? 0xFFFE : page[gbk_code & 0xFF]; } size_t utf8_encode(char *s, unsigned int ch) { if (ch < 0x80) { s[0] = (char)ch; return 1; } if (ch <= 0x7FF) { s[1] = (char) ((ch | 0x80) & 0xBF); s[0] = (char) ((ch >> 6) | 0xC0); return 2; } if (ch <= 0xFFFF) { three: s[2] = (char) ((ch | 0x80) & 0xBF); s[1] = (char) (((ch >> 6) | 0x80) & 0xBF); s[0] = (char) ((ch >> 12) | 0xE0); return 3; } if (ch <= 0x1FFFFF) { s[3] = (char) ((ch | 0x80) & 0xBF); s[2] = (char) (((ch >> 6) | 0x80) & 0xBF); s[1] = (char) (((ch >> 12) | 0x80) & 0xBF); s[0] = (char) ((ch >> 18) | 0xF0); return 4; } if (ch <= 0x3FFFFFF) { s[4] = (char) ((ch | 0x80) & 0xBF); s[3] = (char) (((ch >> 6) | 0x80) & 0xBF); s[2] = (char) (((ch >> 12) | 0x80) & 0xBF); s[1] = (char) (((ch >> 18) | 0x80) & 0xBF); s[0] = (char) ((ch >> 24) | 0xF8); return 5; } if (ch <= 0x7FFFFFFF) { s[5] = (char) ((ch | 0x80) & 0xBF); s[4] = (char) (((ch >> 6) | 0x80) & 0xBF); s[3] = (char) (((ch >> 12) | 0x80) & 0xBF); s[2] = (char) (((ch >> 18) | 0x80) & 0xBF); s[1] = (char) (((ch >> 24) | 0x80) & 0xBF); s[0] = (char) ((ch >> 30) | 0xFC); return 6; } /* fallback */ ch = 0xFFFD; goto three; } size_t utf8_decode(const char *s, const char *e, unsigned int *pch) { unsigned int ch; if (s >= e) { *pch = 0; return 0; } ch = (unsigned char)s[0]; if (ch < 0xC0) goto fallback; if (ch < 0xE0) { if (s+1 >= e || (s[1] & 0xC0) != 0x80) goto fallback; *pch = ((ch & 0x1F) << 6) | (s[1] & 0x3F); return 2; } if (ch < 0xF0) { if (s+2 >= e || (s[1] & 0xC0) != 0x80 || (s[2] & 0xC0) != 0x80) goto fallback; *pch = ((ch & 0x0F) << 12) | ((s[1] & 0x3F) << 6) | (s[2] & 0x3F); return 3; } { int count = 0; /* to count number of continuation bytes */ unsigned int res; while ((ch & 0x40) != 0) { /* still have continuation bytes? */ int cc = (unsigned char)s[++count]; if ((cc & 0xC0) != 0x80) /* not a continuation byte? */ goto fallback; /* invalid byte sequence, fallback */ res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */ ch <<= 1; /* to test next bit */ } if (count > 5) goto fallback; /* invalid byte sequence */ res |= ((ch & 0x7F) << (count * 5)); /* add first byte */ return count+1; } fallback: *pch = ch; return 1; } //static void add_utf8char(luaL_Buffer *b, unsigned int ch) { // char buff[UTF_MAX]; // size_t n = utf8_encode(buff, ch); // luaL_addlstring(b, buff, n); //} size_t gbk_decode(const char *s, const char *e, unsigned *pch) { unsigned int ch; if (s >= e) { *pch = 0; return 0; } ch = s[0] & 0xFF; if (ch < 0x7F) { *pch = ch; return 1; } *pch = (ch << 8) | (s[1] & 0xFF); return 2; } size_t gbk_length(const char *s, const char *e) { size_t gbklen = 0; while (s < e) { if ((unsigned char)(*s++) > 0x7F) ++s; ++gbklen; } return gbklen; } void wtk_gbk_buf_add_char(wtk_strbuf_t *buf,unsigned int ch) { if(ch<0x7f) { wtk_strbuf_push_c(buf,ch&0xFF); }else { wtk_strbuf_push_c(buf,(ch>>8)&0xFF); wtk_strbuf_push_c(buf,ch&0xFF); } } char* wtk_utf8_to_gbk(char *s,int len) { unsigned int ch=0; char *e; wtk_strbuf_t *buf; char *v; buf=wtk_strbuf_new(256,1); e=s+len; while (s < e) { s += utf8_decode(s, e, &ch); wtk_gbk_buf_add_char(buf,convert_to_gbk(ch)); } v=wtk_data_to_str(buf->data,buf->pos); wtk_strbuf_delete(buf); return v; } //static int gbk_string_to_utf8(lua_State *L) { // const char *e, *s = check_gbk(L, 1, &e); // luaL_Buffer b; // luaL_buffinit(L, &b); // while (s < e) { // unsigned int ch; // s += gbk_decode(s, e, &ch); // add_utf8char(&b, convert_from_gbk(ch)); // } // luaL_pushresult(&b); // return 1; //} <file_sep>/core/rbin/wtk_flist.c #include <ctype.h> #include "wtk_flist.h" void wtk_flist_feed_start(wtk_flist_t *fl,char c); void wtk_flist_feed_append(wtk_flist_t *fl,char c); void wtk_flist_feed(wtk_flist_t *fl,char *data,int len); wtk_flist_t* wtk_flist_new(char *fn) { wtk_flist_t *fl=0; char *data; int len; data=file_read_buf(fn,&len); if(!data){goto end;} fl=(wtk_flist_t*)wtk_malloc(sizeof(*fl)); fl->heap=wtk_heap_new(4096); fl->buf=wtk_strbuf_new(1024,1); wtk_queue_init(&(fl->queue)); wtk_flist_feed(fl,data,len); end: if(data){free(data);} return fl; } int wtk_flist_delete(wtk_flist_t *fl) { wtk_strbuf_delete(fl->buf); wtk_heap_delete(fl->heap); wtk_free(fl); return 0; } wtk_fitem_t* wtk_flist_append(wtk_flist_t *fl,char *data,int len) { wtk_fitem_t *item; //wtk_debug("%*.*s\n",len,len,data); item=(wtk_fitem_t*)wtk_heap_malloc(fl->heap,sizeof(*item)); item->str=wtk_heap_dup_string(fl->heap,data,len); wtk_queue_push(&(fl->queue),&(item->q_n)); return item; } void wtk_flist_feed_start(wtk_flist_t *fl,char c) { if(!isspace(c) && c!=EOF) { fl->state=WTK_FITEM_APPEND; wtk_strbuf_reset(fl->buf); wtk_flist_feed_append(fl,c); } } void wtk_flist_feed_append(wtk_flist_t *fl,char c) { wtk_fitem_t *item; if(c=='\n' || c==EOF) { wtk_strbuf_push_c(fl->buf,0); item=wtk_flist_append(fl,fl->buf->data,fl->buf->pos); --item->str->len; fl->state=WTK_FITEM_START; }else { wtk_strbuf_push_c(fl->buf,c); } } void wtk_flist_feed_c(wtk_flist_t *fl,char c) { switch(fl->state) { case WTK_FITEM_START: wtk_flist_feed_start(fl,c); break; case WTK_FITEM_APPEND: wtk_flist_feed_append(fl,c); break; } } void wtk_flist_feed(wtk_flist_t *fl,char *data,int len) { char *s,*e; s=data;e=data+len; fl->state=WTK_FITEM_START; while(s<e) { wtk_flist_feed_c(fl,*s); ++s; } wtk_flist_feed_c(fl,EOF); } void wtk_flist_process(char *fn,void *ths,wtk_flist_notify_f notify) { wtk_flist_t *fl; wtk_queue_node_t *qn; wtk_fitem_t *item; int i; fl=wtk_flist_new(fn); for(i=0,qn=fl->queue.pop;qn;qn=qn->next,++i) { item=data_offset2(qn,wtk_fitem_t,q_n); //if(i%100==0) { wtk_debug("process %d/%d\n",i,fl->queue.length); } notify(ths,item->str->data); } wtk_flist_delete(fl); } void wtk_flist_process3(char *fn,void *ths,wtk_flist_notify_f2 notify,int cnt) { wtk_flist_t *fl; wtk_queue_node_t *qn; wtk_fitem_t *item; int i; int step=0; fl=wtk_flist_new(fn); if(!fl)return; for(i=0,qn=fl->queue.pop;qn;qn=qn->next,++i) { if(i<cnt) { continue; } ++step; item=data_offset2(qn,wtk_fitem_t,q_n); notify(ths,item->str->data,i,fl->queue.length); } if(step!=0) { wtk_flist_process3(fn,ths,notify,fl->queue.length); } wtk_flist_delete(fl); } void wtk_flist_process2(char *fn,void *ths,wtk_flist_notify_f2 notify) { wtk_flist_process3(fn,ths,notify,0); } #include "wtk/core/cfg/wtk_source.h" void wtk_flist_process4(char *fn,void *ths,wtk_flist_notify_f notify) { wtk_strbuf_t *buf; wtk_source_t src; int ret; buf=wtk_strbuf_new(256,1); wtk_source_init_file(&(src),fn); while(1) { ret=wtk_source_read_line(&(src),buf); if(ret!=0){break;} if(buf->pos==0) { break; } wtk_strbuf_push_c(buf,0); notify(ths,buf->data); } wtk_source_clean_file(&(src)); wtk_strbuf_delete(buf); } wtk_flist_it_t* wtk_flist_it_new(char *fn) { wtk_flist_it_t *it; it=(wtk_flist_it_t*)wtk_malloc(sizeof(wtk_flist_it_t)); it->buf=wtk_strbuf_new(256,1); wtk_source_init_file(&(it->src),fn); return it; } char* wtk_flist_it_next(wtk_flist_it_t *it) { char *s=NULL; int ret; ret=wtk_source_read_line(&(it->src),it->buf); if(ret!=0){goto end;} if(it->buf->pos==0) { goto end; } wtk_strbuf_push_c(it->buf,0); s=it->buf->data; end: return s; } void wtk_flist_it_delete(wtk_flist_it_t *it) { wtk_source_clean_file(&(it->src)); wtk_strbuf_delete(it->buf); wtk_free(it); } <file_sep>/core/cfg/wtk_cfg_queue.h #ifndef WTK_CORE_CFG_WTK_CFG_QUEUE_H_ #define WTK_CORE_CFG_WTK_CFG_QUEUE_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_queue.h" #include "wtk/core/wtk_str.h" #include "wtk/core/wtk_heap.h" #include "wtk/core/wtk_array.h" #include "wtk/core/wtk_strbuf.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_cfg_queue wtk_cfg_queue_t; struct wtk_local_cfg; #define wtk_cfg_item_is_string(cfg) ((cfg)->type==WTK_CFG_STRING) #define wtk_cfg_item_is_lc(cfg) ((cfg)->type==WTK_CFG_LC) #define wtk_cfg_item_is_array(cfg) ((cfg)->type==WTK_CFG_ARRAY) #define wtk_cfg_queue_find_s(c,k) wtk_cfg_queue_find(c,k,sizeof(k)-1) typedef enum { WTK_CFG_STRING=0, WTK_CFG_LC, WTK_CFG_ARRAY, }wtk_cfg_type_t; typedef struct { wtk_queue_node_t n; wtk_cfg_type_t type; wtk_string_t *key; union { wtk_string_t *str; struct wtk_local_cfg *cfg; wtk_array_t *array; //wtk_string_t* array. }value; }wtk_cfg_item_t; struct wtk_cfg_queue { wtk_queue_t queue; //wtk_cfg_item_t wtk_heap_t *heap; }; wtk_cfg_queue_t* wtk_cfg_queue_new_h(wtk_heap_t *heap); int wtk_cfg_queue_add(wtk_cfg_queue_t *c,wtk_cfg_item_t *item); wtk_cfg_item_t* wtk_cfg_queue_find(wtk_cfg_queue_t *c,char *k,int bytes); void wtk_cfg_queue_remove(wtk_cfg_queue_t *c,wtk_cfg_item_t *item); wtk_cfg_item_t* wtk_cfg_queue_add_string(wtk_cfg_queue_t *cfg,char *k,int kbytes,char *v,int vbytes); wtk_cfg_item_t* wtk_cfg_queue_add_lc(wtk_cfg_queue_t *cfg,char *k,int kbytes,struct wtk_local_cfg *lc); wtk_cfg_item_t* wtk_cfg_queue_add_array(wtk_cfg_queue_t *cfg,char *k,int bytes,wtk_array_t *a); void wtk_cfg_item_print(wtk_cfg_item_t *i); void wtk_cfg_queue_print(wtk_cfg_queue_t *c); void wtk_cfg_queue_to_string(wtk_cfg_queue_t *c,wtk_strbuf_t *buf); #ifdef __cplusplus }; #endif #endif <file_sep>/os/wtk_lockvpool2.c #include "wtk_lockvpool2.h" wtk_lockvpool2_t* wtk_lockvpool2_new(int bytes,int max_free) { wtk_lockvpool2_t *v; v=(wtk_lockvpool2_t*)wtk_malloc(sizeof(wtk_lockvpool2_t)); wtk_lock_init(&(v->lock)); v->pool=wtk_vpool2_new(bytes,max_free); return v; } void wtk_lockvpool2_delete(wtk_lockvpool2_t *v) { wtk_vpool2_delete(v->pool); wtk_lock_clean(&(v->lock)); wtk_free(v); } void wtk_lockvpool2_reset(wtk_lockvpool2_t *v) { wtk_lock_lock(&(v->lock)); wtk_vpool2_reset(v->pool); wtk_lock_unlock(&(v->lock)); } void* wtk_lockvpool2_pop(wtk_lockvpool2_t *v) { void *p; wtk_lock_lock(&(v->lock)); p=wtk_vpool2_pop(v->pool); wtk_lock_unlock(&(v->lock)); return p; } void wtk_lockvpool2_push(wtk_lockvpool2_t *v,void *usr_data) { wtk_lock_lock(&(v->lock)); wtk_vpool2_push(v->pool,usr_data); wtk_lock_unlock(&(v->lock)); } <file_sep>/core/.svn/pristine/0c/0c4ed8bf1c4ff63cc947b1f30727c633dd62a20d.svn-base #ifndef WTK_CORE_WTK_ALAWHDR_H_ #define WTK_CORE_WTK_ALAWHDR_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_strbuf.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_alawhdr wtk_alawhdr_t; struct wtk_alawhdr { #pragma pack(1) char riff_id[4]; //"RIFF" int32_t riff_datasize; // RIFF chunk data size char riff_type[4]; // "WAVE" char fmt_id[4]; // "fmt " int32_t fmt_datasize; // fmt chunk data size int16_t fmt_compression_code; // 1 for PCM int16_t fmt_channels; // 1 or 2 int32_t fmt_sample_rate; // samples per second int32_t fmt_avg_bytes_per_sec; // sample_rate*block_align int16_t fmt_block_align; // number bytes per sample bit_per_sample*channels/8 int16_t fmt_bit_per_sample; // bits of each sample. char fact_id[4]; // "fact" int32_t fact_datasize; // data chunk size. int32_t fact_dependent; char data_id[4]; // "data" int32_t data_datasize; // data chunk size. #pragma pack() }; void wtk_alawhdr_init(wtk_alawhdr_t *hdr); void wtk_alawhdr_set_fmt(wtk_alawhdr_t* header, int channels, int sampleRate, int bytesPerSample); void wtk_alawhdr_set_size(wtk_alawhdr_t* header, int rawDataSize); void wtk_alaw_write(wtk_strbuf_t *buf,char *fn); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_audio_type.h #ifndef WTK_CORE_WTK_AUDIO_TYPE_H_ #define WTK_CORE_WTK_AUDIO_TYPE_H_ #include "wtk/core/wtk_type.h" #include "wtk_str.h" #ifdef __cplusplus extern "C" { #endif typedef enum { AUDIO_WAV=0, AUDIO_MP3=1, AUDIO_OGG=2, //speex AUDIO_FLV=3, AUDIO_TEXT=4, AUDIO_UNKNOWN=5, }wtk_audio_type_t; #define wtk_audio_type_is_audio(a) ((a)>=AUDIO_WAV && (a)<=AUDIO_FLV) wtk_string_t* wtk_audio_type_to_fnstring(wtk_audio_type_t type); wtk_audio_type_t wtk_audio_type_from_string(wtk_string_t *v); /** * @brief returned string is from static segment, so should not be freed; */ wtk_string_t* wtk_audio_type_to_string(wtk_audio_type_t t); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/a2/a294a2a1a7446b994ce18b7ddb8cb20ff72ae217.svn-base #include "wtk_riff.h" #include "wtk/core/wtk_wavfile.h" int wtk_riff_hdr_check(wtk_riff_hdr_t *hdr) { int ret=-1; if(strncmp(hdr->id,"RIFF",4)!=0) { goto end; } if(strncmp(hdr->type,"WAVE",4)!=0) { goto end; } ret=0; end: return ret; } int wtk_riff_fmt_check(wtk_riff_fmt_t *fmt) { int ret=-1; if(strncmp(fmt->id,"fmt ",4)!=0) { goto end; } ret=0; end: return ret; } int wtk_riff_wavhdr_check(wtk_riff_wavhdr_t *hdr) { int ret=-1; //print_data(hdr->id,4); if(strncmp(hdr->id,"data",4)!=0) { goto end; } ret=0; end: return ret; } wtk_riff_t* wtk_riff_new() { wtk_riff_t *w; w=(wtk_riff_t*)wtk_malloc(sizeof(wtk_riff_t)); w->file=NULL; w->data_pos=-1; return w; } void wtk_riff_delete(wtk_riff_t *f) { if(f->file) { wtk_riff_close(f); } wtk_free(f); } int wtk_riff_open(wtk_riff_t *f,char *fn) { int extra; int ret=-1; wtk_riff_close(f); f->file=fopen(fn,"rb"); if(!f->file) { wtk_debug("file open failed:%s\n", fn); goto end; } ret=fread(&(f->riff_hdr),sizeof(wtk_riff_hdr_t),1,f->file); if(ret!=1) { wtk_debug("riff header read failed\n"); ret=-1;goto end; } ret=wtk_riff_hdr_check(&(f->riff_hdr)); if(ret!=0) { wtk_debug("riff header format is wrong.\n"); goto end; } ret=fread(&(f->fmt),sizeof(wtk_riff_fmt_t),1,f->file); if(ret!=1) { wtk_debug("riff fmt read failed.\n"); ret=-1;goto end; } ret=wtk_riff_fmt_check(&(f->fmt)); if(ret!=0) { wtk_debug("riff fmt format is wrong.\n"); goto end; } extra=f->fmt.data_size-16; if(extra>0) { //wtk_debug("extra=%d\n",extra); fseek(f->file,extra,SEEK_CUR); } ret=fread(&(f->wavhdr),sizeof(wtk_riff_wavhdr_t),1,f->file); if(ret!=1) { wtk_debug("wavhdr read failed.\n"); ret=-1;goto end; } ret=wtk_riff_wavhdr_check(&(f->wavhdr)); if(ret!=0) { wtk_debug("wavhdr format is wrong %4s.\n",f->wavhdr.id); goto end; } f->data_pos=ftell(f->file); ret=0; end: return ret; } void wtk_riff_rewind(wtk_riff_t *f) { if(f->file && f->data_pos>=0) { fseek(f->file,f->data_pos,SEEK_SET); } } int wtk_riff_read(wtk_riff_t *f,char *buf,int size) { int ret; ret=fread(buf,1,size,f->file); return ret; } int wtk_riff_close(wtk_riff_t *f) { if(f->file) { fclose(f->file); f->file=NULL; } return 0; } int wtk_riff_copy_wav(wtk_riff_t *r,char *dst,char sep,int want_len) { #define FILE_BUF_SIZE 1024 char buf[FILE_BUF_SIZE]; int ret=-1; int len; int cnt=0; int step; FILE *fin=r->file; wtk_wavfile_t *wavfile = NULL; //wtk_debug("want_len=%d\n",want_len); ret=wtk_mkdir_p(dst,sep,0); if(ret!=0){goto end;} wavfile=wtk_wavfile_new(r->fmt.sample_rate); ret=wtk_wavfile_open(wavfile,dst); if(ret!=0){goto end;} while(cnt<want_len) { step=min(want_len-cnt,FILE_BUF_SIZE); //wtk_debug("step=%d\n",step); ret=fread(buf,1,step,fin); if(ret<0){goto end;} if(ret==0){break;} len=ret; cnt+=len; ret=wtk_wavfile_write(wavfile,buf,len); if(ret!=0){goto end;} } ret=0; end: if(wavfile) { wtk_wavfile_delete(wavfile); } return ret; } int wtk_riff_cpy(char *fn,int s,int e,char *dst) { wtk_riff_t *r; int ret; wtk_debug("copy [%d-%d]\n",s,e); r=wtk_riff_new(); ret=wtk_riff_open(r,fn); if(ret!=0){goto end;} ret=fseek(r->file,s,SEEK_CUR); if(ret<0){goto end;} ret=wtk_riff_copy_wav(r,dst,'/',e-s); end: if(r) { wtk_riff_delete(r); } return ret; } void wtk_riff_print(wtk_riff_t *f) { printf("========== riff =========\n"); printf("%.*s\n",4,f->riff_hdr.id); printf("%.*s\n",4,f->fmt.id); printf("%.*s\n",4,f->wavhdr.id); printf("rate: %d\n",f->fmt.sample_rate); printf("channel: %d\n",f->fmt.channels); printf("compres: %d\n",f->fmt.compression_code); printf("bitpersample: %d\n",f->fmt.bit_per_sample); printf("size: %d\n",f->wavhdr.data_size); } wtk_strbuf_t** wtk_riff_read_channel(char *fn,int *n) { wtk_strbuf_t **bufs=NULL; wtk_riff_t *riff; int ret=-1; char *pv; int chan; int i,len; int bytes_per_sample; riff=wtk_riff_new(); ret=wtk_riff_open(riff,fn); if(ret!=0){goto end;} chan=riff->fmt.channels; bytes_per_sample=riff->fmt.bit_per_sample/8; if(n) { *n=chan; } //wtk_debug("chan=%d bytes_per_samle=%d\n",chan,bytes_per_sample); bufs=(wtk_strbuf_t**)wtk_malloc(sizeof(wtk_strbuf_t*)*chan); for(i=0;i<chan;++i) { bufs[i]=wtk_strbuf_new(10240,1); } len=bytes_per_sample*chan; pv=(char*)wtk_malloc(len); while(1) { ret=wtk_riff_read(riff,(char*)pv,len); if(ret!=len) { ret=0; break; } for(i=0;i<chan;++i) { wtk_strbuf_push(bufs[i],(char*)(pv+i*bytes_per_sample),bytes_per_sample); } } wtk_free(pv); ret=0; end: wtk_riff_delete(riff); return bufs; } int wtk_riff_get_channel(char *fn) { wtk_riff_t *riff; int ret; int x=-1; riff=wtk_riff_new(); ret=wtk_riff_open(riff,fn); if(ret!=0){goto end;} x=riff->fmt.channels; end: wtk_riff_delete(riff); return x; } int wtk_riff_get_samples(char *fn) { wtk_riff_t *riff; int ret; int x=-1; riff=wtk_riff_new(); ret=wtk_riff_open(riff,fn); if(ret!=0){goto end;} x=riff->fmt.bit_per_sample/8; end: wtk_riff_delete(riff); return x; } <file_sep>/core/rbin/wtk_rbin.c #include "wtk_rbin.h" #include <stdlib.h> int wtk_ritem_delete(wtk_ritem_t *i) { if(i->data.len>0) { wtk_free(i->data.data); } wtk_string_delete(i->fn); wtk_free(i); return 0; } void wtk_ritem_print(wtk_ritem_t *i) { print_data(i->fn->data,i->fn->len); printf("data: %d\n",i->data.len); } int wtk_ritem_get(wtk_ritem_t *i) { int c; if(i->pos<i->data.len) { //for EOF check; c=(unsigned char)i->data.data[i->pos]; ++i->pos; }else { //wtk_debug("%*.*s EOF.\n",i->fn->len,i->fn->len,i->fn->data); c=EOF; } //wtk_debug("v[%d/%d]=%x,%x\n",i->pos,i->data.len,c,EOF); return c; } int wtk_ritem_get2(wtk_ritem_t* i,char *buf,int bytes) { int len; len=i->data.len-i->pos; if(len<bytes) { return EOF; } memcpy(buf,i->data.data+i->pos,bytes); i->pos+=bytes; return bytes; } int wtk_ritem_unget(wtk_ritem_t *i,int c) { if(i->pos>0){--i->pos;} return 0; } wtk_rbin_t* wtk_rbin_new() { wtk_rbin_t* rb; rb=(wtk_rbin_t*)wtk_malloc(sizeof(*rb)); wtk_queue_init(&(rb->list)); rb->buf=wtk_strbuf_new(1024,1); rb->fl=0; return rb; } int wtk_rbin_delete(wtk_rbin_t *rb) { wtk_queue_node_t *n,*p; wtk_ritem_t *i; for(n=rb->list.pop;n;n=p) { p=n->next; i=data_offset(n,wtk_ritem_t,q_n); wtk_ritem_delete(i); } if(rb->fl){wtk_flist_delete(rb->fl);} wtk_strbuf_delete(rb->buf); wtk_free(rb); return 0; } int wtk_rbin_read_scp(wtk_rbin_t *rb,char *fn) { rb->fl=wtk_flist_new(fn); return 0; } wtk_ritem_t* wtk_rbin_new_item(wtk_rbin_t *rb,wtk_string_t *fn,char *rfn) { wtk_ritem_t* item; int len; char *data; int ret=-1; //printf("%d:%*.*s#\n",fn->len,fn->len,fn->len,fn->data); item=(wtk_ritem_t*)wtk_malloc(sizeof(*item)); item->fn=wtk_string_dup_data(fn->data,fn->len); item->data.len=0; data=file_read_buf(rfn,&len); if(!data){goto end;} item->data.data=data; item->data.len=len; ret=0; end: if(ret!=0) { wtk_ritem_delete(item); item=0; } return item; } int wtk_rbin_read_dn(wtk_rbin_t *rb,char *res_dn) { wtk_queue_node_t *n; wtk_queue_t *q=&(rb->list); wtk_fitem_t *i; wtk_ritem_t *ri; wtk_strbuf_t *buf=rb->buf; int rlen=strlen(res_dn); int ret=-1; int add_sep; //wtk_debug("%s\n",res_dn); if(rlen>0 && res_dn[rlen-1]!='/') { add_sep=1; }else { add_sep=0; } for(n=rb->fl->queue.pop;n;n=n->next) { i=data_offset(n,wtk_fitem_t,q_n); wtk_strbuf_reset(buf); wtk_strbuf_push(buf,res_dn,rlen); if(add_sep) { //add directory sep; wtk_strbuf_push_c(buf,'/'); } wtk_strbuf_push(buf,i->str->data,i->str->len); wtk_strbuf_push_c(buf,0); //wtk_debug("%s\n",buf->data); ri=wtk_rbin_new_item(rb,i->str,buf->data); if(!ri){goto end;} wtk_queue_push(q,&(ri->q_n)); //hdr_size+=RBIN_INT_SIZE+i->str->len+RBIN_INT_SIZE; } //wtk_debug("%d,hs=%d\n",q->length,hdr_size); ret=0; end: return ret; } #define WTK_RBIN_INT_SIZE 10 void wtk_rbin_write_int_f(wtk_rbin_t *rb,int v,FILE* f) { char buf[WTK_RBIN_INT_SIZE]={0,0}; sprintf(buf,"%d",v); fwrite(buf,sizeof(buf),1,f); } int wtk_rbin_read_int_f(wtk_rbin_t *rb,FILE* f,int *v) { char buf[WTK_RBIN_INT_SIZE]; int ret; ret=fread(buf,sizeof(buf),1,f); if(ret!=1){ret=-1;goto end;} *v=atoi(buf); ret=0; end: return ret; } void wtk_file_write_reverse(FILE* f,char *data,int len) { int i; unsigned char c; //fwrite(data,len,1,f); for(i=0;i<len;++i) { //c=255-((unsigned char)data[i]); c=~((unsigned char)data[i]); fwrite(&c,1,1,f); } } void wtk_rbin_write_data2(wtk_rbin_t *rb,FILE* f,char *data,int len) { int i; unsigned char c; //fwrite(data,len,1,f); for(i=0;i<len;++i) { //c=255-((unsigned char)data[i]); c=~((unsigned char)data[i]); fwrite(&c,1,1,f); } } int wtk_rbin_read_data2(wtk_rbin_t *rb,FILE* f,unsigned char *data,int len) { unsigned char c; int i,ret=0; //fwrite(data,len,1,f); for(i=0;i<len;++i) { ret=fread(&c,1,1,f); if(ret!=1){ret=-1;goto end;} data[i]=~(c); } ret=0; end: return ret; } void wtk_rbin_reverse_data(unsigned char *p,int len) { unsigned char *e; e=p+len; while(p<e) { *p=~*p; ++p; } } void wtk_rbin_write_data(wtk_rbin_t *rb,FILE* f,char *data,int len) { wtk_rbin_reverse_data((unsigned char *)data,len); //skip error check; fwrite(data,len,1,f); wtk_rbin_reverse_data((unsigned char *)data,len); } int wtk_rbin_read_data(wtk_rbin_t *rb,FILE* f,unsigned char *data,int len) { int ret; ret = fread(data,1,len,f); if(ret!=len){ret=-1;goto end;} wtk_rbin_reverse_data(data,len); ret=0; end: return ret; } int wtk_rbin_write(wtk_rbin_t *rb,char *res_dn,char *bin) { wtk_queue_node_t *n; wtk_queue_t *q=&(rb->list); wtk_ritem_t *i; FILE* f=0; int ret=-1; f=fopen(bin,"wb"); if(!f){goto end;} ret=wtk_rbin_read_dn(rb,res_dn); if(ret!=0){goto end;} wtk_rbin_write_int_f(rb,q->length,f); for(n=q->pop;n;n=n->next) { i=data_offset(n,wtk_ritem_t,q_n); wtk_rbin_write_int_f(rb,i->fn->len,f); wtk_rbin_write_data(rb,f,i->fn->data,i->fn->len); //fwrite(i->fn->data,i->fn->len,1,f); wtk_rbin_write_int_f(rb,i->data.len,f); wtk_rbin_write_data(rb,f,i->data.data,i->data.len); } ret=0; end: if(f){fclose(f);} return ret; } int wtk_bin_read_bin(wtk_rbin_t *rb,FILE* f) { wtk_queue_t *q=&(rb->list); wtk_ritem_t *item; int c,v,ret; int i; ret=wtk_rbin_read_int_f(rb,f,&c); if(ret!=0){goto end;} for(i=0;i<c;++i) { ret=wtk_rbin_read_int_f(rb,f,&v); if(ret!=0){goto end;} item=(wtk_ritem_t*)wtk_malloc(sizeof(*item)); item->data.len=0; item->fn=wtk_string_new(v); ret=wtk_rbin_read_data(rb,f,(unsigned char*)item->fn->data,v); if(ret!=0){goto end;} ret=wtk_rbin_read_int_f(rb,f,&v); if(ret!=0){goto end;} item->data.len=v; //wtk_debug("v=%d\n",v); if(v==0) { item->data.data=0; }else { item->data.data=(char*)wtk_malloc(v); } ret=wtk_rbin_read_data(rb,f,(unsigned char*)item->data.data,v); if(ret!=0){goto end;} //wtk_debug("%.*s: %d\n",item->fn->len,item->fn->data,item->data.len); //printf("%d: %*.*s\n",item->fn->len,item->fn->len,item->fn->len,item->fn->data); wtk_queue_push(q,&(item->q_n)); } ret=0; end: return ret; } int wtk_rbin_read(wtk_rbin_t *rb,char *bin) { FILE* f; int ret=-1; f=fopen(bin,"rb"); if(!f) { wtk_debug("%s not exist.\n",bin); goto end; } ret=wtk_bin_read_bin(rb,f); end: if(f){fclose(f);} //wtk_debug("%d\n",ret); return ret; } int wtk_rbin_write_item(wtk_rbin_t *rb,wtk_ritem_t *i,char *dn,int len) { wtk_strbuf_t *buf=rb->buf; wtk_strbuf_reset(buf); wtk_strbuf_push(buf,dn,len); wtk_strbuf_push_s(buf,"/"); wtk_strbuf_push(buf,i->fn->data,i->fn->len); wtk_strbuf_push_c(buf,0); //printf("%s\n",buf->data); return file_write_buf(buf->data,i->data.data,i->data.len); } int wtk_rbin_extract(wtk_rbin_t *rb,char *dn) { wtk_queue_node_t *n; wtk_queue_t *q=&(rb->list); wtk_ritem_t *i; int len=strlen(dn); int ret=-1; if(wtk_file_exist(dn)==0) { wtk_mkdir_p(dn,DIR_SEP,1); } for(n=q->pop;n;n=n->next) { i=data_offset(n,wtk_ritem_t,q_n); ret=wtk_rbin_write_item(rb,i,dn,len); if(ret!=0) { wtk_debug("write %*.*s failed.\n",i->fn->len,i->fn->len,i->fn->data); goto end; } } end: return ret; } wtk_ritem_t* wtk_rbin_find(wtk_rbin_t *rb,char *data,int len) { wtk_queue_node_t *n; wtk_queue_t *q=&(rb->list); wtk_ritem_t *i=0,*x; for(n=q->pop;n;n=n->next) { x=data_offset(n,wtk_ritem_t,q_n); if(wtk_string_cmp(x->fn,data,len)==0) { i=x; break; } } return i; } void wtk_source_init_rbin(wtk_source_t* s,wtk_ritem_t *i) { wtk_source_init(s); i->pos=0; s->data=i; s->get=(wtk_source_get_handler_t)wtk_ritem_get; s->unget=(wtk_source_unget_handler_t)wtk_ritem_unget; s->get_str=(wtk_source_get_str_f)wtk_ritem_get2; //s->swap=0;//wtk_is_little_endian(); s->swap=wtk_is_little_endian(); } int wtk_rbin_load_file(wtk_rbin_t *rb,void *data,wtk_source_load_handler_t loader,char *fn) { wtk_source_t s,*ps=&s; wtk_ritem_t *i; int ret=-1; i=wtk_rbin_find(rb,fn,strlen(fn)); //wtk_debug("fn=%s,i=%p\n",fn,i); if(!i){goto end;} //wtk_ritem_print(i); wtk_source_init_rbin(ps,i); ret=loader(data,ps); end: return ret; } <file_sep>/core/wtk_ringarray.h #ifndef WTK_CORE_WTK_RINGARRAY_H_ #define WTK_CORE_WTK_RINGARRAY_H_ #include "wtk/core/wtk_type.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_ringarray wtk_ringarray_t; /** * @brief ring array is used for save fixed size array, * |1|2|3|4|5| * => push 6 * |2|3|4|5|6| */ struct wtk_ringarray { void *slot; int slot_size; int nslot; int used; }; wtk_ringarray_t* wtk_ringarray_new(int nslot,int slot_size); void wtk_ringarray_delete(wtk_ringarray_t *r); void wtk_ringarray_push(wtk_ringarray_t *r,void *item); //-------------- float ringarray section --------- float wtk_ringarray_mean_value(wtk_ringarray_t *r); void wtk_ringarray_print_float(wtk_ringarray_t *r); //----------- test/example section --------------- void wtk_ringarray_test_g(); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/c9/c95177fb15131cbce1a54c3bb7d1971a5e1c0ee3.svn-base #ifndef CORE_THIN_WTK_STACK_H_ #define CORE_THIN_WTK_STACK_H_ #include "wtk/core/wtk_type.h" #include <stdio.h> #include "wtk_alloc.h" #include "wtk_queue.h" #include "wtk_os.h" #include "wtk_strbuf.h" #ifdef __cplusplus extern "C" { #endif typedef struct stack_block stack_block_t; #define wtk_stack_push_s(s,msg) wtk_stack_push(s,msg,sizeof(msg)-1) struct stack_block { stack_block_t* next; char *pop; char *push; char *end; }; struct wtk_stack { wtk_queue_node_t q; uint32_t last_alloc_size; uint32_t max_size; uint32_t len; float growf; stack_block_t *pop; stack_block_t *push; stack_block_t *end; }; typedef struct wtk_stack wtk_stack_t; /** * @brief allocate stack. */ wtk_stack_t* wtk_stack_new(int init_size,int max_size,float growf); int wtk_stack_bytes(wtk_stack_t *s); /** * @brief init stack. */ int wtk_stack_init(wtk_stack_t *s,int init_size,int max_size,float growf); /** * @brief dispose stack. */ int wtk_stack_delete(wtk_stack_t* s); /** * @brief clean stack. */ int wtk_stack_clean(wtk_stack_t *s); /** * @brief reset stack. */ int wtk_stack_reset(wtk_stack_t *s); /** * @brief push data. */ int wtk_stack_push(wtk_stack_t* s,const char* data,int len); void wtk_stack_push_f(wtk_stack_t *s,const char *fmt,...); /** * @brief push string. */ int wtk_stack_push_string(wtk_stack_t* s,const char* str); /** * @brief pop data * @return 0 if pop len bytes else failed; */ int wtk_stack_pop(wtk_stack_t* s,char* data,int len); /** * @return copied bytes; */ int wtk_stack_pop2(wtk_stack_t* s,char* data,int len); /** * @brief print. */ int wtk_stack_print(wtk_stack_t* s); /** * @brief check stack is valid or not. */ int wtk_stack_is_valid(wtk_stack_t * s); void wtk_stack_merge(wtk_stack_t *s,char* p); void wtk_stack_add(wtk_stack_t *dst,wtk_stack_t *src); void wtk_stack_copy(wtk_stack_t *s,wtk_strbuf_t *to); int wtk_stack_write(wtk_stack_t *s,FILE *f); int wtk_stack_write2(wtk_stack_t *s,char *fn); int wtk_stack_read(wtk_stack_t *s,char *fn); int wtk_stack_write_nbfd(wtk_stack_t *s, int fd); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/a1/a101ac7708804c8e265060478eeedc9e6d524cdc.svn-base #ifndef WTK_CORE_WTK_TREENODE_H_ #define WTK_CORE_WTK_TREENODE_H_ #include "wtk/core/wtk_type.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_treenode wtk_treenode_t; struct wtk_treenode { wtk_treenode_t *left; wtk_treenode_t *right; wtk_treenode_t *parent; }; #define wtk_treenode_left(t) ((t)->left) #define wtk_treenode_right(t) ((t)->right) #define wtk_treenode_parent(t) ((t)->parent) typedef void (*WtkTreeNodePrintFunc)(wtk_treenode_t *n); typedef int (*WtkTreeNodeTraverseFunc)(void *data,wtk_treenode_t *n); /** * @brief return left node of t. */ wtk_treenode_t* wtk_treenode_min(wtk_treenode_t *t); /** * @brief return right node of t. */ wtk_treenode_t* wtk_treenode_max(wtk_treenode_t *t); /** * @brief traverse tree node. */ int wtk_treenode_traverse(wtk_treenode_t *t,WtkTreeNodeTraverseFunc traverse,void *data); /** * @brief print node. */ void wtk_treenode_print(wtk_treenode_t *n,int depth,WtkTreeNodePrintFunc print); /** * @brief get max depth of the tree. */ int wtk_treenode_depth(wtk_treenode_t* n,int depth); int wtk_treenode_len(wtk_treenode_t *n); #ifdef __cplusplus }; #endif #endif <file_sep>/os/tcp/wtk_tcp_listen_cfg.c #include "wtk_tcp_listen_cfg.h" int wtk_tcp_listen_cfg_init(wtk_tcp_listen_cfg_t *cfg) { cfg->port=8080; cfg->backlog=5; cfg->reuse=0; return 0; } int wtk_tcp_listen_cfg_clean(wtk_tcp_listen_cfg_t *cfg) { return 0; } int wtk_tcp_listen_cfg_update_local(wtk_tcp_listen_cfg_t *cfg,wtk_local_cfg_t *lc) { wtk_string_t *v; wtk_local_cfg_update_cfg_i(lc,cfg,port,v); wtk_local_cfg_update_cfg_i(lc,cfg,backlog,v); wtk_local_cfg_update_cfg_b(lc,cfg,reuse,v); return 0; } int wtk_tcp_listen_cfg_update(wtk_tcp_listen_cfg_t *cfg) { return 0; } <file_sep>/core/.svn/pristine/55/55d918ac18494ee105f65f79448d75f7d039f4f1.svn-base #ifndef WTK_CORE_PARSE_WTK_NUMBER_PARSE_H_ #define WTK_CORE_PARSE_WTK_NUMBER_PARSE_H_ #include "wtk/core/wtk_type.h" #ifdef __cplusplus extern "C" { #endif /* * expr=(e|E)[+|-]*[\d]* * dec=(0|[1-9]+).[\d]+ * [+|-]*(dec|[\d]+)expr* * * =>+|-|0|1-9 */ typedef struct wtk_number_parse wtk_number_parse_t; typedef enum { WTK_NUMBER_PARSE_WAIT, WTK_NUMBER_PARSE_V_WAIT_DOT, WTK_NUMBER_PARSE_V_DECIMAL, WTK_NUMBER_PARSE_E_FLAG, WTK_NUMBER_PARSE_E_VALUE, WTK_NUMBER_PARSE_V_VALUE, }wtk_number_parse_state_t; struct wtk_number_parse { char state;//wtk_number_parse_state_t; int nchar; int64_t integer; float decimal; int e; int num_decimal; unsigned char vflag:1; //1=>+; 0=>- unsigned char eflag:1; //1=>+; 0=>- unsigned char has_decimal:1; unsigned char has_e:1; }; void wtk_number_parse_init(wtk_number_parse_t *p); int wtk_number_parse_can_parse(char c); double wtk_number_parse_to_value(wtk_number_parse_t *p); int wtk_number_parse_feed(wtk_number_parse_t *p,char c); double wtk_aton(char *data,int bytes); void test_number_parse(); #ifdef __cplusplus }; #endif #endif <file_sep>/core/segmenter/wtk_segmenter.h #ifndef WTK_SEGMENTER_WTK_SEGMENTER_H_ #define WTK_SEGMENTER_WTK_SEGMENTER_H_ #include "wtk/core/wtk_type.h" #include "wtk_segmenter_cfg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_segmenter wtk_segmenter_t; #define wtk_segmenter_parse_s(seg,data) wtk_segmenter_parse(seg,data,sizeof(data)-1) struct wtk_segmenter { wtk_segmenter_cfg_t *cfg; wtk_fkv2_t *fkv; wtk_heap_t *heap; wtk_strbuf_t *buf; //------------- output word array ------------ wtk_string_t **wrd_array; int wrd_array_n; }; wtk_segmenter_t* wtk_segmenter_new(wtk_segmenter_cfg_t *cfg,wtk_rbin2_t *rbin); void wtk_segmenter_delete(wtk_segmenter_t *seg); void wtk_segmenter_reset(wtk_segmenter_t *seg); int wtk_segmenter_parse(wtk_segmenter_t *seg,char *data,int bytes,wtk_strbuf_t *output_buf); int wtk_segmenter_parse2(wtk_segmenter_t *seg,char *data,int bytes); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/e4/e4ea33e60c45ca942e858b65c82bfda110e9bcae.svn-base #include "wtk_alloc.h" //#define USE_ALIGN char* wtk_data_cpy(char *data,int len) { char *v; v=(char*)wtk_malloc(len); memcpy(v,data,len); return v; } void* wtk_memalign(size_t alignment,size_t size) { #ifdef USE_ALIGN void *p; int err; err = posix_memalign(&p, alignment, size); if(err!=0) { p=0; } return p; #else return wtk_calloc(1,size); #endif } #ifndef MEM_INLINE void wtk_free(void* p) { printf("free: %p\n",p); free(p); } void* wtk_malloc(size_t n) { void* p; p=malloc(n); if(n==8|| n==40) { printf("malloc: %p\n",p); } return p; } void* wtk_calloc(int elems,int size) { void *p; p=calloc(elems,size); if(size==8|| size==40) { printf("calloc: %p\n",p); } return p; } #endif #ifdef DEBUG_MEM #include "wtk/os/wtk_lock.h" wtk_lock_t lock; pid_t pid; void wtk_alloc_init() { static int i=0; if(i==0) { pid=getpid(); wtk_lock_init(&lock); i=1; } } void* wtk_calloc_debug(int elems,int size,const char *f,int line) { void *p; wtk_alloc_init(); p=calloc(elems,size); //make page dirty memset(p,0,elems*size); if(pid==getpid()) { wtk_lock_lock(&(lock)); printf("DM malloc %s:%d %p %d\n",f,line,p,elems*size); fflush(stdout); wtk_lock_unlock(&(lock)); } return p; } void* wtk_malloc_debug(size_t n,const char *f,int line) { void *p; wtk_alloc_init(); p=malloc(n); //make page dirty memset(p,0,n); if(pid==getpid()) { wtk_lock_lock(&(lock)); printf("DM malloc %s:%d %p %d\n",f,line,p,n); fflush(stdout); wtk_lock_unlock(&(lock)); } return p; } void wtk_free_debug(void *p,const char *f,int line) { wtk_alloc_init(); if(pid==getpid()) { wtk_lock_lock(&(lock)); printf("DM free %s:%d %p\n",f,line,p); fflush(stdout); wtk_lock_unlock(&(lock)); } free(p); } #endif <file_sep>/core/.svn/pristine/99/9912798833294c28059ea3cdf3bbaab65f9f676c.svn-base #include "wtk_vector.h" wtk_type_vector_new_imp(double); wtk_type_vector_new_imp(short); wtk_type_vector_newh_imp(short); wtk_type_vector_newh_imp(double); wtk_vector_t* wtk_vector_new_h(wtk_heap_t *h,int size) { wtk_vector_t* v; v=(wtk_vector_t*)wtk_heap_malloc(h,wtk_vector_bytes(size)); wtk_vector_init(v,size); return v; } wtk_int_vector_t* wtk_int_vector_new_h(wtk_heap_t *h,int size) { wtk_int_vector_t *v; v=(wtk_int_vector_t*)wtk_heap_malloc(h,wtk_int_vector_bytes(size)); wtk_vector_init(v,size); return v; } //#include <stdlib.h> //#include <malloc.h> wtk_vector_t *wtk_vector_new(int size) { wtk_vector_t *v; v=(wtk_vector_t*)wtk_calloc(1,wtk_vector_bytes(size)); wtk_vector_init(v,size); return v; } void wtk_vector_delete2(wtk_vector_t *v) { int of; char *p; of=*(((int*)v)-1); p=(char*)v-of; // wtk_debug("p=%p\n",p); wtk_free(p); } wtk_vector_t *wtk_vector_new2(int size) { wtk_vector_t *v; char *p; int of; v=(wtk_vector_t*)wtk_calloc(1,wtk_vector_bytes(size)+8); p=(char*)(v)+4; while(1) { if(((long)(p+4))%8==0) { break; } ++p; } of=(int)(p-(char*)v); //wtk_debug("%p/%p of=%d\n",v,p,of); v=(wtk_vector_t*)p; *(((int*)v)-1)=of; //wtk_vector_delete2(v); //exit(0); //v=(wtk_vector_t*)memalign(4096,wtk_vector_bytes(size)); wtk_vector_init(v,size); return v; } int wtk_vector_bytes2(wtk_vector_t *v) { int n; n=wtk_vector_size(v); return wtk_vector_bytes(n); } void wtk_vector_cpy(wtk_vector_t *src,wtk_vector_t *dst) { int n; n=wtk_vector_size(src); memcpy((char*)(dst+1),(char*)(src+1),n*sizeof(float)); // for(i=1;i<=n;++i) // { // dst[i]=src[i]; // } } void wtk_double_vector_cpy(wtk_double_vector_t *src,wtk_double_vector_t *dst) { int i,n; n=wtk_vector_size(src); for(i=1;i<=n;++i) { dst[i]=src[i]; } } wtk_vector_t *wtk_vector_dup(wtk_vector_t *src) { wtk_vector_t *dst; int n; n=wtk_vector_size(src); dst=wtk_vector_new(n); wtk_vector_cpy(src,dst); return dst; } /* EXPORT->CreateSVector: Shared version */ wtk_svector_t* wtk_svector_newh(wtk_heap_t* heap, int size) { wtk_svector_t* v; void *p; p=(void*)wtk_heap_malloc(heap,wtk_svector_bytes(size)); v=(wtk_svector_t*)((char*)p+sizeof(void*)*2); (*(int*)v)=size; wtk_set_hook((void**)v,0); wtk_set_use((void**)v,0); return v; } wtk_svector_t* wtk_svector_dup(wtk_heap_t* heap, wtk_svector_t *src) { wtk_svector_t *dst; dst=wtk_svector_newh(heap,wtk_vector_size(src)); wtk_vector_cpy(src,dst); return dst; } void wtk_set_use(void **m,int n) { *((int*)(m-1))=n; } int wtk_get_use(void **m) { return *((int*)(m-1)); } void wtk_inc_use(void **m) { ++*((int*)(m-1)); } void wtk_dec_use(void **m) { --*((int*)(m-1)); } void wtk_set_hook(void **m,void *h) { *(m-2)=h; //*((void**)((char*)m-2*sizeof(void*)))=h; } void* wtk_get_hook(void **m) { return *(m-2); } void wtk_vector_zero2(wtk_vector_t *v) { int i,n; n=wtk_vector_size(v); for(i=1;i<=n;++i) { v[i]=0; } } void wtk_vector_zero(wtk_vector_t *v) { int n; n=wtk_vector_size(v); memset(v+1,0,sizeof(float)*n); // for(i=1;i<=n;++i) // { // v[i]=0; // } } void wtk_vector_set_init_value(wtk_vector_t *v,float f) { int i,n; n=wtk_vector_size(v); for(i=1;i<=n;++i) { v[i]=f; } } void wtk_double_vector_zero(wtk_double_vector_t *v) { int i,n; n=wtk_vector_size(v); for(i=1;i<=n;++i) { v[i]=0; } } float wtk_vector_max_abs(wtk_vector_t *v) { float min=10000; float max=-10000; int i,n; n=wtk_vector_size(v); for(i=1;i<n;++i) { if(v[i]>max) { max=v[i]; } if(v[i]<min) { min=v[i]; } } if(min<0) { min=-min; } if(max<0) { max=-max; } if(max>min) { return max; }else { return min; } } float wtk_vector_sum(wtk_vector_t* v) { float sum=0; wtk_vector_t *s,*e; s=v;e=v+wtk_vector_size(v); while((e-s)>=4) { sum+=*(++s); sum+=*(++s); sum+=*(++s); sum+=*(++s); } while(s<e) { sum+=*(++s); } return sum; } float wtk_math_max(float *a,int len) { float max; float *s,*e; max=a[0]; s=a+1; e=s+len-1; while(s<e) { if(*s>max) { max=*s; //wtk_debug("max=%f\n",max); } ++s; } return max; } float wtk_math_max2(float *a,int len) { int i; float max; max=a[0]; for(i=1;i<len;++i) { if(a[i]>max) { max=a[i]; } } return max; } void wtk_vector_print(wtk_vector_t* v) { float t; wtk_debug("========== vector ==========\n"); #ifdef INLINE wtk_vector_do_i(v,t=,;printf("%.3f %s",t,i%10==0?"\n":"")); printf("\n"); /* if(wtk_vector_size(v)!=39) { wtk_debug("found invalid %d.\n",wtk_vector_size(v)); exit(0); } */ //wtk_debug("%d\n",wtk_vector_size(v)); //exit(0); #else wtk_vector_do_i(v,t=,;if(t!=0){printf("v[%d]=%.6f\n",i,t);}); //wtk_vector_do_i(v,t=,;printf("v[%d]=%f\n",i,t)); //wtk_vector_do_i(v,t=,;printf("%f\n",t)); #endif //exit(0); } void wtk_short_vector_print(wtk_short_vector_t* v) { int i,count; count=wtk_short_vector_size(v); for(i=1;i<=count;++i) { printf("%d\n",v[i]); } } void wtk_vector_fix_scale2(wtk_vector_t *v,float scale) { int *pi; int i,n; float f; pi=(int*)(v); n=wtk_vector_size(v); for(i=1;i<=n;++i) { f=v[i]*scale; pi[i]=wtk_float_round(f); //wtk_debug("v[%d]=%d\n",i,pi[i]); } //exit(0); } void wtk_vector_fix_scale(wtk_vector_t *v,float scale) { float f; int *pi,*pe; int n; //int i=0; n=wtk_vector_size(v); pi=((int*)v)+1; pe=pi+n; while(pi<pe) { f=(*((float*)pi))*scale; *pi=wtk_float_round(f); // ++i; // wtk_debug("v[%d]=%d\n",i,*pi); ++pi; } //exit(0); } <file_sep>/core/.svn/pristine/0b/0b1b03e4f395ea8180aabc15172a8486e6f47dc9.svn-base #ifndef WTK_CORE_SEGMENTER_WTK_POSEG_CFG #define WTK_CORE_SEGMENTER_WTK_POSEG_CFG #include "wtk/core/cfg/wtk_local_cfg.h" #include "wtk_chnpos_cfg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_poseg_cfg wtk_poseg_cfg_t; //python py/wtk/kv2bin2.py -i ./res/pos/dict.txt.big -o test.bin -type "float|string" struct wtk_poseg_cfg { wtk_chnpos_cfg_t pos; wtk_array_t *filter; wtk_posdict_t *dict; int def_weight; int max_char; char *dict_fn; unsigned upper:1; unsigned use_dict_bin:1; }; int wtk_poseg_cfg_init(wtk_poseg_cfg_t *cfg); int wtk_poseg_cfg_clean(wtk_poseg_cfg_t *cfg); int wtk_poseg_cfg_update_local(wtk_poseg_cfg_t *cfg,wtk_local_cfg_t *lc); int wtk_poseg_cfg_update(wtk_poseg_cfg_t *cfg); int wtk_poseg_cfg_update2(wtk_poseg_cfg_t *cfg,wtk_source_loader_t *sl); #ifdef __cplusplus }; #endif #endif <file_sep>/os/wtk_rw_lock.c #include "wtk_rw_lock.h" #include "wtk/core/wtk_os.h" void wtk_rw_lock_init(wtk_rw_lock_t *lock) { wtk_lock_init(&(lock->lock)); wtk_lock_init(&(lock->xlock)); lock->r=0; lock->w=0; } void wtk_rw_lock_clean(wtk_rw_lock_t *lock) { wtk_lock_clean(&(lock->lock)); } void wtk_rw_lock_lock_read(wtk_rw_lock_t *lock) { // while(lock->w>0) // { // //sleep check // wtk_msleep(1); // } wtk_lock_lock(&(lock->lock)); } void wtk_rw_lock_unlock_read(wtk_rw_lock_t *lock) { wtk_lock_unlock(&(lock->lock)); } void wtk_rw_lock_inc_read(wtk_rw_lock_t *lock) { ++lock->r; } void wtk_rw_lock_dec_read(wtk_rw_lock_t *lock) { --lock->r; } void wtk_rw_lock_start_write(wtk_rw_lock_t *lock) { //wtk_debug("lock=%p start write r=%d w=%d\n",lock,lock->r,lock->w); while(lock->r>0) { //sleep check //wtk_msleep(1); //usleep(1); sched_yield(); } wtk_lock_lock(&(lock->lock)); ++lock->w; //wtk_lock_unlock(&(lock->lock)); } void wtk_rw_lock_stop_write(wtk_rw_lock_t *lock) { //wtk_debug("lock=%p stop write r=%d w=%d\n",lock,lock->r,lock->w); //wtk_lock_lock(&(lock->lock)); --lock->w; wtk_lock_unlock(&(lock->lock)); } void wtk_rw_lock_start_read(wtk_rw_lock_t *lock) { //wtk_debug("lock=%p start read r=%d w=%d\n",lock,lock->r,lock->w); //wtk_debug("wait write\n"); // while(lock->w>0) // { // //wtk_msleep(1); // //usleep(1); // sched_yield(); // } wtk_lock_lock(&(lock->lock)); wtk_lock_lock(&(lock->xlock)); ++lock->r; wtk_lock_unlock(&(lock->xlock)); wtk_lock_unlock(&(lock->lock)); //wtk_debug("wait write end\n"); } void wtk_rw_lock_stop_read(wtk_rw_lock_t *lock) { //wtk_debug("lock=%p stop read r=%d w=%d\n",lock,lock->r,lock->w); //wtk_lock_lock(&(lock->lock)); wtk_lock_lock(&(lock->xlock)); --lock->r; wtk_lock_unlock(&(lock->xlock)); //wtk_lock_unlock(&(lock->lock)); } <file_sep>/core/.svn/pristine/b9/b9239a01dd0127577ea24ab84f131518fad47f0c.svn-base #include "wtk_rbin2.h" wtk_rbin2_t* wtk_rbin2_new() { wtk_rbin2_t *rb; rb=(wtk_rbin2_t*)wtk_malloc(sizeof(wtk_rbin2_t)); rb->heap=wtk_heap_new(4096); rb->f=NULL; rb->fn=NULL; rb->buf=wtk_strbuf_new(4096,1); rb->version=1; wtk_queue_init(&(rb->list)); return rb; } void wtk_rbin2_delete(wtk_rbin2_t *rb) { wtk_strbuf_delete(rb->buf); if(rb->f) { fclose(rb->f); } wtk_heap_delete(rb->heap); wtk_free(rb); } int wtk_rbin2_add(wtk_rbin2_t *rb,wtk_string_t *name,char *realname) { char *data; int len; int ret=-1; ///wtk_debug("[%s]\n",realname); data=file_read_buf(realname,&len); if(!data){goto end;} wtk_heap_add_large(rb->heap,data,len); wtk_rbin2_add2(rb,name,data,len); ret=0; end: return ret; } wtk_rbin2_item_t* wtk_rbin2_new_item(wtk_rbin2_t *rb) { wtk_rbin2_item_t *item; item=(wtk_rbin2_item_t*)wtk_heap_malloc(rb->heap,sizeof(wtk_rbin2_item_t)); item->fn=NULL; item->data=NULL; item->pos=-1; item->len=item->seek_pos=0; item->buf_pos=0; item->reverse=0; item->rb=rb; return item; } int wtk_rbin2_is_file_reverse(wtk_rbin2_t *rv,char *name,int len) { char *suf[]={ ".lex",".lua",".cfg",".r",".fst",".nlg",".srt",".owl" }; int i,n; if(rv->version==0) { return name[len-1]=='r'?1:0; }else { if(len==3 && strncmp(name,"cfg",3)==0) { return 1; }else if(len==5 && strncmp(name,"./cfg",5)==0) { return 1; } n=sizeof(suf)/sizeof(char*); for(i=0;i<n;++i) { if(wtk_str_end_with(name,len,suf[i],strlen(suf[i]))) { return 1; } } return 0; } } void wtk_rbin2_add2(wtk_rbin2_t *rb,wtk_string_t *name,char *data,int len) { wtk_rbin2_item_t *item; wtk_heap_t *heap=rb->heap; wtk_strbuf_t *buf=rb->buf; wtk_strbuf_reset(buf); wtk_strbuf_push_s(buf,"./"); wtk_strbuf_push(buf,name->data,name->len); //wtk_debug("[%.*s]\n",buf->pos,buf->data); item=wtk_rbin2_new_item(rb); //item->fn=wtk_heap_dup_string(heap,name->data,name->len); item->fn=wtk_heap_dup_string(heap,buf->data,buf->pos); item->data=(wtk_string_t*)wtk_heap_malloc(heap,sizeof(wtk_string_t)); item->reverse=wtk_rbin2_is_file_reverse(rb,name->data,name->len); //wtk_debug("[%.*s]=%d\n",name->len,name->data,item->reverse); //print_data(item->data,4); wtk_string_set((item->data),data,len); wtk_queue_push(&(rb->list),&(item->q_n)); } int wtk_rbin2_write_data(FILE* f,char *data,int len) { int ret; wtk_rbin_reverse_data((unsigned char *)data,len); //skip error check; ret=fwrite(data,len,1,f); wtk_rbin_reverse_data((unsigned char *)data,len); return ret==1?0:-1; } int wtk_rbin2_write(wtk_rbin2_t *rb,char *fn) { wtk_queue_node_t *qn; wtk_rbin2_item_t *item; int ret=-1; FILE *f; int vi; int pos; //wtk_debug("write %s\n",fn); f=fopen(fn,"wb"); if(!f){goto end;} if(rb->version>0) { vi=-rb->version; ret=fwrite(&vi,1,4,f); if(ret!=4){ret=-1;goto end;} pos=4; }else { pos=0; } vi=rb->list.length; ret=fwrite(&vi,1,4,f); if(ret!=4){ret=-1;goto end;} pos+=4; for(qn=rb->list.pop;qn;qn=qn->next) { item=data_offset(qn,wtk_rbin2_item_t,q_n); pos+=4+item->fn->len+4+4; } for(qn=rb->list.pop;qn;qn=qn->next) { item=data_offset(qn,wtk_rbin2_item_t,q_n); vi=item->fn->len; item->pos=pos; pos+=item->data->len; ret=fwrite(&(vi),1,4,f); if(ret!=4){ret=-1;goto end;} ret=wtk_rbin2_write_data(f,item->fn->data,item->fn->len); //ret=fwrite(item->fn->data,item->fn->len,1,f); //wtk_debug("[%.*s] ret=%d\n",item->fn->len,item->fn->data, ret); if(ret!=0){ret=-1;goto end;} vi=item->pos; ret=fwrite(&(vi),1,4,f); if(ret!=4){ret=-1;goto end;} vi=item->data->len; ret=fwrite(&(vi),1,4,f); if(ret!=4){ret=-1;goto end;} } for(qn=rb->list.pop;qn;qn=qn->next) { item=data_offset(qn,wtk_rbin2_item_t,q_n); if(item->data && item->data->len>0) { /* wtk_debug("[%.*s] reverse=%d,fpos=%d,pos=%d,len=%d\n",item->fn->len,item->fn->data, item->reverse,(int)ftell(f),item->pos,item->data->len); */ //print_data(item->data->data,10); if(item->reverse) { ret=wtk_rbin2_write_data(f,item->data->data,item->data->len); //ret=fwrite(item->fn->data,item->fn->len,1,f); //wtk_debug("[%.*s]\n",item->fn->len,item->fn->data); if(ret!=0){ret=-1;goto end;} }else { //wtk_debug("[%.*s] %d/%d\n",item->fn->len,item->fn->data,(int)item->pos,(int)ftell(f)); //print_data(item->data->data,4); ret=fwrite(item->data->data,item->data->len,1,f); if(ret!=1){ret=-1;goto end;} } } } ret=0; end: //wtk_debug("ret=%d\n",ret); if(f) { fclose(f); } return ret; } void wtk_rbin2_load_all(wtk_rbin2_t *rb) { wtk_queue_node_t *qn; wtk_rbin2_item_t *item; for(qn=rb->list.pop;qn;qn=qn->next) { item=data_offset(qn,wtk_rbin2_item_t,q_n); if(!item->data) { wtk_rbin2_load_item(rb,item,1); } } } int wtk_rbin2_read(wtk_rbin2_t *rb,char *fn) { wtk_rbin2_item_t *item; wtk_heap_t *heap; FILE *f; int ret; int i; int n,vi; heap=rb->heap; f=fopen(fn,"rb"); if(!f){ret=-1;goto end;} ret=fread((char*)&(n),4,1,f); if(ret!=1){ret=-1;goto end;} if(n<0) { rb->version=-n; ret=fread((char*)&(n),4,1,f); if(ret!=1){ret=-1;goto end;} }else { rb->version=0; } //wtk_debug("n=%d\n",n); for(i=0;i<n;++i) { item=wtk_rbin2_new_item(rb);//(wtk_rbin2_item_t*)wtk_heap_malloc(heap,sizeof(wtk_rbin2_item_t)); ret=fread((char*)&(vi),4,1,f); if(ret!=1) { ret=-1;goto end; } item->fn=wtk_heap_dup_string(heap,0,vi); ret=fread(item->fn->data,item->fn->len,1,f); //wtk_debug("ret=%d\n",ret); if(ret!=1){ret=-1;goto end;} wtk_rbin_reverse_data((unsigned char*)item->fn->data,item->fn->len); //wtk_debug("[%.*s]\n",item->fn->len,item->fn->data); item->reverse=wtk_rbin2_is_file_reverse(rb,item->fn->data,item->fn->len); ret=fread((char*)&(vi),4,1,f); if(ret!=1){ret=-1;goto end;} item->pos=vi; ret=fread((char*)&(vi),4,1,f); if(ret!=1){ret=-1;goto end;} item->len=vi; //wtk_debug("[%.*s]=%d/%d\n",item->fn->len,item->fn->data,item->pos,item->len); item->data=NULL; wtk_queue_push(&(rb->list),&(item->q_n)); } rb->fn=wtk_heap_dup_str(rb->heap,fn); ret=0; end: if(ret!=0) { if(f) { fclose(f); } }else { rb->f=f; } //wtk_debug("ret=%d,f=%p/%p\n",ret,f,rb->f); return ret; } int wtk_rbin2_read2(wtk_rbin2_t *rb,char *fn,unsigned int seek_pos) { wtk_rbin2_item_t *item; wtk_heap_t *heap; FILE *f; int ret; int i; int n,vi; heap=rb->heap; f=fopen(fn,"rb"); if(!f){ret=-1;goto end;} ret=fseek(f,seek_pos,SEEK_SET); if(ret==-1){goto end;} ret=fread((char*)&(n),4,1,f); if(ret!=1){ret=-1;goto end;} if(n<0) { rb->version=-n; ret=fread((char*)&(n),4,1,f); if(ret!=1){ret=-1;goto end;} }else { rb->version=0; } for(i=0;i<n;++i) { item=wtk_rbin2_new_item(rb);//(wtk_rbin2_item_t*)wtk_heap_malloc(heap,sizeof(wtk_rbin2_item_t)); ret=fread((char*)&(vi),4,1,f); if(ret!=1){ret=-1;goto end;} //wtk_debug("vi=%d\n",vi); item->fn=wtk_heap_dup_string(heap,0,vi); ret=fread(item->fn->data,item->fn->len,1,f); if(ret!=1){ret=-1;goto end;} wtk_rbin_reverse_data((unsigned char*)item->fn->data,item->fn->len); item->reverse=wtk_rbin2_is_file_reverse(rb,item->fn->data,item->fn->len); ret=fread((char*)&(vi),4,1,f); if(ret!=1){ret=-1;goto end;} item->pos=vi+seek_pos; ret=fread((char*)&(vi),4,1,f); if(ret!=1){ret=-1;goto end;} item->len=vi; //wtk_debug("[%.*s]=%d/%d\n",item->fn->len,item->fn->data,item->pos,item->len); item->data=NULL; wtk_queue_push(&(rb->list),&(item->q_n)); } rb->fn=wtk_heap_dup_str(rb->heap,fn); ret=0; end: if(ret!=0) { if(f) { fclose(f); } }else { rb->f=f; } //wtk_debug("ret=%d,f=%p/%p\n",ret,f,rb->f); return ret; } void wtk_rbin2_print(wtk_rbin2_t *rb) { wtk_queue_node_t *qn; wtk_rbin2_item_t *item; int ki; for(ki=0,qn=rb->list.pop;qn;qn=qn->next,++ki) { item=data_offset(qn,wtk_rbin2_item_t,q_n); wtk_debug("rb=%p/%p,v[%d]=[%.*s],pos=%d,len=%d\n",rb,qn,ki,item->fn->len,item->fn->data,item->pos,item->len); } } wtk_rbin2_item_t* wtk_rbin2_get_x(wtk_rbin2_t *rb,char *name,int len) { wtk_queue_node_t *qn; wtk_rbin2_item_t *item; for(qn=rb->list.pop;qn;qn=qn->next) { item=data_offset(qn,wtk_rbin2_item_t,q_n); // if(ki==116) // { // print_data(name,len); // print_data(item->fn->data,item->fn->len); // } if(wtk_string_cmp(item->fn,name,len)==0) { //wtk_debug("[%.*s]=%p\n",len,name,item); return item; } } return NULL; } FILE* wtk_rbin2_get_file(wtk_rbin2_t *rb,char *name) { FILE *f=NULL; wtk_rbin2_item_t *item; int ret; item=wtk_rbin2_get(rb,name,strlen(name)); if(!item){goto end;} f=fopen(rb->fn,"rb"); if(!f){goto end;} ret=fseek(f,item->pos,SEEK_SET); if(ret!=0) { fclose(f); f=NULL; } end: return f; } wtk_rbin2_item_t* wtk_rbin2_get(wtk_rbin2_t *rb,char *name,int len) { wtk_rbin2_item_t *item; wtk_strbuf_t *buf; item=wtk_rbin2_get_x(rb,name,len); if(item){goto end;} buf=wtk_strbuf_new(256,1); wtk_strbuf_real_path(buf,name,len); //wtk_debug("[%.*s]\n",buf->pos,buf->data); item=wtk_rbin2_get_x(rb,buf->data,buf->pos); wtk_strbuf_delete(buf); end: //wtk_debug("[%.*s]=%p\n",len,name,item); return item; } int wtk_rbin2_file_exist(wtk_rbin2_t *rb,char *name,int len) { wtk_rbin2_item_t *item; item=wtk_rbin2_get(rb,name,len); return item?1:0; } wtk_rbin2_item_t* wtk_rbin2_get2(wtk_rbin2_t *rb,char *name,int len) { wtk_rbin2_item_t *item; int ret; //wtk_debug("[%.*s]\n",len,name); item=wtk_rbin2_get(rb,name,len); if(item && !item->data) { ret=wtk_rbin2_load_item(rb,item,1); if(ret!=0) { return NULL; } } return item; } wtk_rbin2_item_t* wtk_rbin2_get3(wtk_rbin2_t *rb,char *name,int len,int use_heap) { wtk_rbin2_item_t *item; int ret; //wtk_debug("[%.*s]\n",len,name); item=wtk_rbin2_get(rb,name,len); if(item && !item->data) { ret=wtk_rbin2_load_item(rb,item,use_heap); if(ret!=0) { wtk_debug("load failed\n"); return NULL; } } return item; } void wtk_rbin2_item_release(wtk_rbin2_item_t *item) { if(item->data) { wtk_free(item->data); item->data=NULL; } } int wtk_rbin2_load_item(wtk_rbin2_t *rb,wtk_rbin2_item_t *item,int use_heap) { FILE *f=rb->f; int ret; //wtk_debug("[%.*s] pos=%d r=%d\n",item->fn->len,item->fn->data,item->pos,item->reverse); if(item->len==0){return 0;} ret=fseek(f,item->pos,SEEK_SET); if(ret!=0) { wtk_debug("seek failed %d f=%p\n",item->pos,f); perror(__FUNCTION__); exit(0); goto end; } if(use_heap) { item->data=wtk_heap_dup_string(rb->heap,0,item->len); }else { item->data=wtk_string_new(item->len); } ret=fread(item->data->data,item->len,1,f); if(ret!=1) { wtk_debug("read failed %d/%d\n",item->len,ret); ret=-1;goto end; } //print_data(item->data->data,10); //wtk_debug("[%.*s]=%d\n",item->fn->len,item->fn->data,item->reverse); //print_hex(item->data->data,4); if(item->reverse) { wtk_rbin_reverse_data((unsigned char*)item->data->data,item->data->len); } ret=0; end: return ret; } void wtk_rbin2_item_clean(wtk_rbin2_item_t *item) { if(item->data) { wtk_string_delete(item->data); item->data=NULL; } } int wtk_rbin2_extract(wtk_rbin2_t *rb,char *dn) { wtk_queue_node_t *qn; wtk_rbin2_item_t *item; int ret=-1; wtk_strbuf_t *buf; //wtk_rbin2_print(rb); if(wtk_file_exist(dn)==0) { wtk_mkdir_p(dn,DIR_SEP,1); } buf=wtk_strbuf_new(1024,1); for(qn=rb->list.pop;qn;qn=qn->next) { item=data_offset(qn,wtk_rbin2_item_t,q_n); if(!item->data) //item->len!=item->data->len) { ret=wtk_rbin2_load_item(rb,item,1); if(ret!=0) { wtk_debug("load [%.*s] failed\n",item->fn->len,item->fn->data); goto end; } } if (!item->data){ //for null file. continue; } wtk_strbuf_reset(buf); wtk_strbuf_push(buf,dn,strlen(dn)); wtk_strbuf_push_c(buf,'/'); wtk_strbuf_push(buf,item->fn->data,item->fn->len); wtk_strbuf_push_c(buf,0); wtk_debug("write [%s]\n",buf->data); file_write_buf(buf->data,item->data->data,item->data->len); } end: wtk_strbuf_delete(buf); return ret; } //------------------ load ------------------ /* int wtk_rbin2_item_get(wtk_rbin2_item_t *i) { if(i->seek_pos<i->data->len) { //for EOF check; return (unsigned char)i->data->data[i->seek_pos++]; }else { return EOF; } } int wtk_rbin2_item_get2(wtk_rbin2_item_t* i,char *buf,int bytes) { int len; len=i->data->len-i->seek_pos; if(len<bytes) { return EOF; } memcpy(buf,i->data->data+i->seek_pos,bytes); i->seek_pos+=bytes; return bytes; } wtk_string_t* wtk_rbin2_item_get3(wtk_rbin2_item_t* i) { return i->data; } int wtk_rbin2_item_unget(wtk_rbin2_item_t *i,int c) { if(i->seek_pos>0){--i->seek_pos;} return 0; }*/ #define wtk_rbin2_item_get_c(i) ((i)->s<(i)->e)?*((i)->s++):EOF int wtk_rbin2_item_get(wtk_rbin2_item_t *i) { return (i->s<i->e)?*(i->s++):EOF; } int wtk_rbin2_item_get2(wtk_rbin2_item_t* i,char *buf,int bytes) { if(i->e-i->s<bytes) { return EOF; } memcpy(buf,i->s,bytes); i->s+=bytes; return bytes; } #define SING_QUOTE '\'' #define DBL_QUOTE '"' #define ESCAPE_CHAR '\\' #include <ctype.h> int wtk_rbin2_read_string(wtk_rbin2_item_t *item,wtk_strbuf_t *buf) { char c; int ret=-1; int n; unsigned char *p; if(item->s>=item->e){goto end;} while(item->s<item->e) { c=*(item->s++); if(c=='\n' || c==' '|| c=='\t' || c=='\r' ) { }else { break; } } if (item->s >= item->e){goto end;} if(c==DBL_QUOTE||c==SING_QUOTE) { p=item->s; while(item->s<item->e && (*item->s++!=c)); n=item->s-p-1; if(n>0) { wtk_strbuf_push(buf,(char*)p,n); } }else { p=item->s-1; while(1) { if(c==ESCAPE_CHAR) { c=*(item->s++); if(c>='0' && c<='7') { n=item->s-p-1; if(n>0) { wtk_strbuf_push(buf,(char*)p,n); } n=c-'0'; c=*(item->s++); n=(n<<3)+c-'0'; c=*(item->s++); n=(n<<3)+c-'0'; c=n; wtk_strbuf_push_c(buf,c); p=item->s; } } //wtk_strbuf_push_c(buf,c); if(item->s>=item->e){break;} c=*(item->s++); if(c==' '||c=='\n' || c=='\r' || c=='\t') { --item->s; break; } } n=item->s-p; if(n>0) { wtk_strbuf_push(buf,(char*)p,n); } } ret=0; end: //wtk_debug("[%.*s]\n",buf->pos,buf->data); //exit(0); return ret; } int wtk_rbin2_read_string3(wtk_rbin2_item_t *item,wtk_strbuf_t *buf) { char c,q; int ret=-1; int n,len; unsigned char *p; if(item->s>=item->e){goto end;} while(item->s<item->e) { c=*(item->s++); if(c=='\n' || c==' '|| c=='\t' || c=='\r' ) { }else { break; } } if(c==DBL_QUOTE||c==SING_QUOTE) { q=c; while(item->s<item->e) { c=*(item->s++); if(c==q) { break; }else { wtk_strbuf_push_c(buf,c); } } }else { p=item->s-1; while(1) { if(c==ESCAPE_CHAR) { c=*(item->s++); if(c>='0' && c<='7') { len=item->s-p-1; if(len>0) { wtk_strbuf_push(buf,(char*)p,len); } n=c-'0'; c=*(item->s++); n=(n<<3)+c-'0'; c=*(item->s++); n=(n<<3)+c-'0'; c=n; p=item->s; } } //wtk_strbuf_push_c(buf,c); if(item->s>=item->e) { len=item->s-p-1; if(len>0) { wtk_strbuf_push(buf,(char*)p,len); } break; } c=*(item->s++); if(c==' '||c=='\n' || c=='\r' ||c=='\t') { len=item->s-p-1; if(len>0) { wtk_strbuf_push(buf,(char*)p,len); } --item->s; break; } } } ret=0; end: //wtk_debug("[%.*s]\n",buf->pos,buf->data); //exit(0); return ret; } int wtk_rbin2_read_string2(wtk_rbin2_item_t *item,wtk_strbuf_t *buf) { int isq,q=0,c,ret,n,i; //char t; ret=-1; c=wtk_rbin2_item_get_c(item); while(c=='\n' || c==' '|| c=='\r' ||c=='\t') { c=wtk_rbin2_item_get_c(item); } if(c==EOF){goto end;} if(c==DBL_QUOTE||c==SING_QUOTE) { isq=1;q=c; c=wtk_rbin2_item_get_c(item); }else { isq=0; } while(1) { //wtk_debug("%d:%c\n",c,c); if(c==EOF){ret=0;goto end;} if(isq) { if(c==q){break;} }else { if(c=='\n' || c==EOF||c==' ' || c=='\t' || c=='\r') { --item->s; break; } } if(c==ESCAPE_CHAR) { c=*(item->s++); if(c>='0' && c<='7') { n=c-'0'; for(i=0;i<2;++i) { c=wtk_rbin2_item_get_c(item); if(c==EOF||c<'0'||c>'7'){goto end;} n=(n<<3)+c-'0'; } c=n; } } wtk_strbuf_push_c(buf,c); c=wtk_rbin2_item_get_c(item); } ret=0; end: return ret; } wtk_string_t* wtk_rbin2_item_get3(wtk_rbin2_item_t* i) { return i->data; } int wtk_rbin2_item_unget(wtk_rbin2_item_t *i,int c) { if(((char*)i->s)>i->data->data) { --i->s; } return 0; } void wtk_source_init_rbin2(wtk_source_t* s,wtk_rbin2_item_t *i) { wtk_source_init(s); i->seek_pos=0; i->s=(unsigned char*)i->data->data; i->e=i->s+i->data->len; s->data=i; s->get=(wtk_source_get_handler_t)wtk_rbin2_item_get; s->unget=(wtk_source_unget_handler_t)wtk_rbin2_item_unget; s->get_str=(wtk_source_get_str_f)wtk_rbin2_item_get2; s->get_file=(wtk_source_get_file_f)wtk_rbin2_item_get3; s->read_str=(wtk_source_read_str_f)wtk_rbin2_read_string; //s->swap=0;//wtk_is_little_endian(); s->swap=wtk_is_little_endian(); } //------------------------------------------------------------- int wtk_rbin2_item_get_x(wtk_rbin2_item_t *i) { wtk_strbuf_t *buf=i->rb->buf; int len; int v; //wtk_debug("get %p pos=%d/%d\n",i,i->buf_pos,buf->pos); if(i->buf_pos==buf->pos) { i->seek_pos+=i->buf_pos; if(i->seek_pos>=i->len) { i->buf_pos=buf->pos=0; return EOF; } buf->pos=0; len=i->len-i->seek_pos; len=min(len,buf->length); //wtk_debug("i=%p/%p %d len=%d/%d\n",i,i->rb,len,i->len,i->seek_pos); buf->pos=fread(buf->data,1,len,i->rb->f); //wtk_debug("buf->pos=%d\n",buf->pos); //print_data(buf->data,buf->pos); if(buf->pos!=len) { return EOF; } if(i->reverse) { wtk_rbin_reverse_data((unsigned char*)buf->data,buf->pos); } i->buf_pos=0; } v=*(((unsigned char*)buf->data)+i->buf_pos); ++i->buf_pos; return v; } int wtk_rbin2_item_get2_x(wtk_rbin2_item_t* i,char *p,int bytes) { wtk_strbuf_t *buf=i->rb->buf; int len,ret; len=buf->pos-i->buf_pos; if(len>=bytes) { memcpy(p,buf->data+i->buf_pos,bytes); i->buf_pos+=bytes; return bytes; }else { if(len>0) { memcpy(p,buf->data+i->buf_pos,len); i->buf_pos+=len; bytes-=len; p+=len; } ret=wtk_rbin2_item_get_x(i); if(ret==EOF){return EOF;} --i->buf_pos; ret=wtk_rbin2_item_get2_x(i,p,bytes); if(ret==EOF){return EOF;} return ret+len; } } int wtk_rbin2_item_unget_x(wtk_rbin2_item_t *i,int c) { if(i->buf_pos>0) { --i->buf_pos; }else { ungetc(c,i->rb->f); } return 0; } void wtk_source_init_rbin2_x(wtk_source_t* s,wtk_rbin2_item_t *i) { fseek(i->rb->f,i->pos,SEEK_SET); wtk_source_init(s); wtk_strbuf_reset(i->rb->buf); i->seek_pos=0; i->buf_pos=0; s->data=i; s->get=(wtk_source_get_handler_t)wtk_rbin2_item_get_x; s->unget=(wtk_source_unget_handler_t)wtk_rbin2_item_unget_x; s->get_str=(wtk_source_get_str_f)wtk_rbin2_item_get2_x; s->get_file=NULL; //s->swap=0;//wtk_is_little_endian(); s->swap=wtk_is_little_endian(); } int wtk_rbin2_load_file(wtk_rbin2_t *rb,void *data,wtk_source_load_handler_t loader,char *fn) { //#define DEBUG_T wtk_source_t s,*ps=&s; wtk_rbin2_item_t *i; int ret=-1; #ifdef DEBUG_T double t; #endif #ifdef DEBUG_T t=time_get_ms(); #endif i=wtk_rbin2_get(rb,fn,strlen(fn)); if(!i) { wtk_debug("[%s] not found\n",fn); goto end; } if(!i->data) { ret=wtk_rbin2_load_item(rb,i,0); if(ret!=0) { wtk_debug("[%s] load failed\n",fn); goto end; } } #ifdef DEBUG_T wtk_debug("time=%f file=%s len=%fKB\n",time_get_ms()-t,fn,i->len*1.0/1024); #endif //wtk_ritem_print(i); wtk_source_init_rbin2(ps,i); ret=loader(data,ps); wtk_rbin2_item_release(i); end: #ifdef DEBUG_T wtk_debug("time=%f file=%s\n",time_get_ms()-t,fn); #endif return ret; } <file_sep>/core/math/wtk_lms.h #ifndef WTK_CORE_MATH_WTK_LMS #define WTK_CORE_MATH_WTK_LMS #include "wtk/core/wtk_type.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_lms wtk_lms_t; struct wtk_lms { int frame_size; float rate; short *x; float *win; }; wtk_lms_t* wtk_lms_new(int frame_size,float rate); void wtk_lms_delete(wtk_lms_t *lms); void wtk_lms_process(wtk_lms_t *lms,short *mic,int mic_len,short *sp,int sp_len); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/03/03efec04c299069aa22b337d65aa7e92779fcb79.svn-base #ifndef WTK_EVAL_TEXT_WTK_TXTPARSER_H_ #define WTK_EVAL_TEXT_WTK_TXTPARSER_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_heap.h" #include "wtk/core/wtk_strbuf.h" #include "wtk/core/wtk_array.h" #include "wtk/core/errno/wtk_eos.h" #include "wtk/core/wtk_str_hash.h" #include "wtk_txtparser_cfg.h" #include "wtk/core/wtk_str_encode.h" #ifdef __cplusplus extern "C" { #endif /* =============================================================== space=[ \r\t\n] digit=[0-9] alpha=[a-zA-Z] purechar = digit | alpha sepchar=. char=purechar | sepchar | -|_ inchar=-|'|:|_ sep=,|;|?|!|" note=space*[tsg]:space*[01]space* word=char[inchar|char]*char*(\(note\))* ============================================================ sent=(space*word[sep|space]+)+ */ #define wtk_txtparser_parse_s(p,s) wtk_txtparser_parse(p,s,sizeof(s)-1) #define wtk_txtparser_set_err_s(p,s) wtk_txtparser_set_err(p,s,sizeof(s)-1) #define wtk_txtparser_add_dot_word_s(p,w) wtk_txtparser_add_dot_word(p,w,sizeof(w)-1) typedef struct wtk_txtparser wtk_txtparser_t; typedef struct wtk_tpword wtk_tpword_t; typedef int (*wtk_txtparser_is_wrd_f)(void *ths,char *wrd,int wrd_bytes); typedef int (*wtk_txtparser_wrd_normalize_f)(void *ths,wtk_strbuf_t *wrd); typedef enum { TP_START, TP_WORD, TP_INCHAR, TP_NOTE_START, TP_NOTE_TOK, TP_NOTE_SEP, TP_NOTE_WAIT_END, }wtk_tp_state_t; struct wtk_tpword { wtk_queue_node_t q_n; wtk_string_t *name; char sep; //separate char; wtk_string_t *sep2; //separate char, for utf8 char cur_sense; char chn_tone; //0,1,2,3,4 for chinese tone; unsigned s:1; //stress unsigned t:1; //tone unsigned g:1; //sense group unsigned s_set:1; unsigned t_set:1; unsigned g_set:1; unsigned end_sep:1; //current word have separate char or not; unsigned use_usr_pron:1; //current word has usr pron or not, if 1, use the pron in refText to eval; }; struct wtk_txtparser { wtk_txtparser_cfg_t *cfg; wtk_eos_t *os; wtk_tp_state_t state; //wtk_str_hash_t *dot_hash; wtk_heap_t *heap; wtk_strbuf_t *buf; wtk_strbuf_t *snt; //save word as ebnf format for fa, like (sil i want an apple sil) wtk_tpword_t *cur; wtk_array_t *wrds; //array of (wtk_tpword_t*) wtk_txtparser_is_wrd_f is_wrd_f; void *is_wrd_data; wtk_txtparser_wrd_normalize_f wrd_normalize_f; void *wrd_normalize_ths; int char_index; unsigned cfg_is_ref:1; //delete cfg or not when delete parser; }; wtk_txtparser_t* wtk_txtparser_new(wtk_eos_t *os); wtk_txtparser_t* wtk_txtparser_new2(wtk_txtparser_cfg_t *cfg,wtk_eos_t *os); int wtk_txtparser_delete(wtk_txtparser_t *p); int wtk_txtparser_reset(wtk_txtparser_t *p); int wtk_txtparser_parse(wtk_txtparser_t *p,char *data,int bytes); void wtk_txtparser_print(wtk_txtparser_t *p); //---------------- private section ----------------------------- /** * @brief add word to wrds list and also push word to snt buffer for ebnf expand. */ void wtk_txtparser_add_word(wtk_txtparser_t *p,char *w,int bytes); /** * @brief add word to wrds list. */ wtk_tpword_t* wtk_txtparse_add_tpword(wtk_txtparser_t *p,char *w,int bytes); /** * @brief set word judge; */ void wtk_txtparser_set_is_wrd_f(wtk_txtparser_t *p,wtk_txtparser_is_wrd_f is_wrd_f,void *ths); /** * @brief word normalize callback */ void wtk_txtparser_set_wrd_normalize_callback(wtk_txtparser_t *p,wtk_txtparser_wrd_normalize_f normalize,void *ths); /** * @brief add dot word */ void wtk_txtparser_add_dot_word(wtk_txtparser_t* p,char *wrd,int wrd_bytes); /** * @brief to string; */ int wtk_txtparser_to_string(wtk_txtparser_t *p,wtk_strbuf_t *buf,int add_note); //------------------------ example section -------------------- void wtk_txtparser_test_g(); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/9d/9d8c1f21830926cceb474cbcae2c8774e1643633.svn-base #include "wtk_sort.h" float wtk_float_cmp(void *ths,float *src,float *dst) { return *src-*dst; } void wtk_qsort_float(float *f,int len) { float t; wtk_qsort(f,f+len-1,sizeof(float),(wtk_qsort_cmp_f)wtk_float_cmp,NULL,&t); } float wtk_double_cmp(void *ths,double *src,double *dst) { return *src-*dst; } void wtk_qsort_double(double *f,int len) { double t; wtk_qsort(f,f+len-1,sizeof(double),(wtk_qsort_cmp_f)wtk_double_cmp,NULL,&t); } void wtk_qsort(void *s,void *e,size_t size,wtk_qsort_cmp_f cmp,void *app_data,void *tmp_elem) { char *x; char *i,*j; float f; if(e<=s){return;} x=(char*)e; i=(char*)s-size; j=(char*)s; while(j<x) { f=cmp(app_data,(void*)j,(void*)x); //wtk_debug("v[%p/%p]=%f\n",j,x,f); if(f<=0) { i+=size; if(j!=i) { memcpy(tmp_elem,i,size); memcpy(i,j,size); memcpy(j,tmp_elem,size); } } j+=size; } i+=size; if(i!=x) { memcpy(tmp_elem,i,size); memcpy(i,x,size); memcpy(x,tmp_elem,size); } wtk_qsort(s,i-size,size,cmp,app_data,tmp_elem); wtk_qsort(i+size,e,size,cmp,app_data,tmp_elem); } void wtk_qsort2(void *base,size_t nmemb,size_t size,wtk_qsort_cmp_f cmp,void *app_data) { void *tmp_elem; tmp_elem=malloc(size); wtk_qsort(base,(void*)((char*)base+(nmemb-1)*size),size,cmp,app_data,tmp_elem); free(tmp_elem); } void wtk_qsort3(void *base,size_t nmemb,size_t size,wtk_qsort_cmp_f cmp,void *app_data,void *tmp_elem) { wtk_qsort(base,(void*)((char*)base+(nmemb-1)*size),size,cmp,app_data,tmp_elem); } void* wtk_inc_search(void *s,void *e,int size,wtk_search_cmp_f cmp,void *usr_data) { void *p=0; int ret; while(s<=e) { ret=cmp(usr_data,s); if(ret==0) { p=s; break; } s=(void*)((char*)s+size); } return p; } void* wtk_binary_search(void *s,void *e,int size,wtk_search_cmp_f cmp,void *usr_data) { void *p; int ret; //wtk_debug("s=%p-%p n=%d\n",s,e,1+(int)((e-s)/sizeof(void*))); if(s<e) { //wtk_debug("%d\n",(int)((((char*)e-(char*)s)/size - 1 )>>1)); p=(void*)( (char*)s+ (( ((char*)e-(char*)s)/size - 1 )>>1)*size); //wtk_debug("s=%p,e=%p,p=%p,size=%#x\n",s,e,p,size); ret=cmp(usr_data,p); if(ret==0) { return p; }else if(ret<0) { return wtk_binary_search(s,(void*)((long)p-size),size,cmp,usr_data); }else { return wtk_binary_search((void*)((long)p+size),e,size,cmp,usr_data); } }else if(s==e) { ret=cmp(usr_data,s); return ret==0?s:0; }else { return 0; } } <file_sep>/core/wtk_bit_heap.c #include "wtk_bit_heap.h" int wtk_bit_heap_clean(wtk_bit_heap_t* heap); /** * @brief initialize element. */ int wtk_bit_heap_init(wtk_bit_heap_t* p,size_t elem_size,size_t elem_min,size_t elem_max,float growf); void heap_block_reset(HeapBlock* block,size_t elem_num) { int bit_len=(elem_num+7)>>3; block->elem_num=elem_num; block->elem_free=elem_num; block->first_free=0; memset(block->bitmap,0,bit_len); if(elem_num&7) { block->bitmap[bit_len-1]|=0xff<<(elem_num&7); } } HeapBlock* heap_block_new(size_t elem_size,size_t elem_num) { size_t size,bit_len; HeapBlock* block; uint8_t* p; bit_len=(elem_num+7)>>3; size=sizeof(HeapBlock)+bit_len;//(elem_num*elem_size); block=(HeapBlock*)wtk_calloc(1,size); p=(uint8_t*)block; block->next=0; block->bitmap=p+sizeof(HeapBlock); heap_block_reset(block,elem_num); //block->data=p+sizeof(HeapBlock)+bit_len; #ifdef USE_bIT_ALIGN bit_len=elem_num*elem_size; if(bit_len <4096) { int ret; ret=posix_memalign((void**)&(block->data),4096,4096); if(ret!=0) { block->data=NULL; } }else { block->data=wtk_calloc(elem_num,elem_size); } #else block->data=wtk_calloc(elem_num,elem_size); #endif return block; } int heap_block_bytes(HeapBlock *blk,int elem_size) { int bytes; bytes=sizeof(HeapBlock); bytes+=blk->elem_num*elem_size; bytes+=(blk->elem_num+7)>>3; return bytes; } void heap_block_delete(HeapBlock* b) { wtk_free(b->data); wtk_free(b); } HeapBlock* heap_block_reorder(HeapBlock* head,size_t elem_free) { HeapBlock *cur,*prev; for(cur=head,prev=0;cur;prev=cur,cur=cur->next) { if(cur->elem_free>=elem_free) { if(prev) { prev->next=cur->next; cur->next=head; } head=cur; break; } } return head; } uint8_t* heap_block_get_elem(HeapBlock* head,size_t elem_size) { size_t index,bitpos,bit_len,pos,i; uint8_t *p; uint8_t c; if(head->elem_free<=0){p=0;goto end;} index=head->first_free; bitpos=head->first_free>>3; head->bitmap[bitpos]|=1<<(head->first_free&7); --head->elem_free; p=head->data+index*elem_size; if(head->elem_free<=0) { head->first_free=head->elem_num; goto end; } bit_len=(head->elem_num+7)>>3; for(i=bitpos;i<bit_len;++i) { if(head->bitmap[i]!=(unsigned)0xFF) { c=~(head->bitmap[i]); pos=7; if(c&0xf){pos-=4;c&=0xf;} if(c&0x33){pos-=2;c&=0x33;} if(c&0x55){pos-=1;} head->first_free=(i<<3)+pos; break; } } end: return p; } //wtk_bit_heap_t* wtk_bit_heap_new(size_t elem_size,size_t elem_min,size_t elem_max,float growf,heap_clean_handler cleaner) wtk_bit_heap_t* wtk_bit_heap_new(size_t elem_size,size_t elem_min,size_t elem_max,float growf) { wtk_bit_heap_t* p; p=(wtk_bit_heap_t*)wtk_malloc(sizeof(wtk_bit_heap_t)); wtk_bit_heap_init(p,elem_size,elem_min,elem_max,growf); return p; } wtk_bit_heap_t* wtk_bit_heap_new2(size_t elem_size) { int n; n=4096/elem_size; return wtk_bit_heap_new(elem_size,n,n,0); } int wtk_bit_heap_init(wtk_bit_heap_t* p,size_t elem_size,size_t elem_min,size_t elem_max,float growf) { p->block_list=0; p->elem_size=elem_size; p->elem_cur=elem_min; p->elem_min=elem_min; p->elem_max=elem_max; p->tot_alloc=0; p->tot_used=0; p->growf=growf; //p->cleaner=cleaner; return 0; } int wtk_bit_heap_delete(wtk_bit_heap_t* heap) { wtk_bit_heap_clean(heap); wtk_free(heap); return 0; } int wtk_bit_heap_clean(wtk_bit_heap_t* heap) { HeapBlock *cur,*next; for(cur=heap->block_list;cur;cur=next) { next=cur->next; heap_block_delete(cur); } heap->tot_used=0; heap->tot_alloc=0; heap->block_list=0; heap->elem_cur=heap->elem_min; return 0; } int wtk_bit_heap_bytes(wtk_bit_heap_t *heap) { int bytes; HeapBlock *p; bytes=sizeof(wtk_bit_heap_t); for(p=heap->block_list;p;p=p->next) { bytes+=heap_block_bytes(p,heap->elem_size); } return bytes; } int wtk_bit_heap_reset(wtk_bit_heap_t* heap) { wtk_bit_heap_clean(heap); return 0; } int wtk_bit_heap_add_block(wtk_bit_heap_t* heap) { HeapBlock* block; size_t num; num=heap->elem_cur*((heap->block_list?heap->growf:0)+1); if(num>heap->elem_max) { num=heap->elem_max; }else if(num<heap->elem_min) { num=heap->elem_min; } heap->elem_cur=num; block=heap_block_new(heap->elem_size,num); block->next=heap->block_list; heap->block_list=block; heap->tot_alloc+=num; return 0; } void* wtk_bit_heap_malloc(wtk_bit_heap_t* heap) { void* p; int ret; p=0; if(heap->tot_alloc==heap->tot_used) { ret=wtk_bit_heap_add_block(heap); if(ret!=0){goto end;} }else if(heap->block_list->elem_free==0) { heap->block_list=heap_block_reorder(heap->block_list,1); } p=heap_block_get_elem(heap->block_list,heap->elem_size); if(p){++heap->tot_used;} end: if(p==0) { printf("get null pointer.\n"); } return p; } void* wtk_bit_heap_zmalloc(wtk_bit_heap_t *heap) { void *p; p=wtk_bit_heap_malloc(heap); if(p) { memset(p,0,heap->elem_size); } return p; } int wtk_bit_heap_free(wtk_bit_heap_t* heap,void* p) { HeapBlock *cur,*pre; int found,ret,index; for(cur=heap->block_list,pre=0;cur;pre=cur,cur=cur->next) { found=(cur->data<=(uint8_t*)p) && ((cur->data+(cur->elem_num)*(heap->elem_size))>(uint8_t*)p); if(found){break;} } if(!cur){ret=-1;goto end;} index=((uint8_t*)p-cur->data)/heap->elem_size; cur->bitmap[index>>3]&=~(1<<(index&7)); if(index<cur->first_free) { cur->first_free=index; } ++cur->elem_free; --heap->tot_used; ret=0; if(cur->elem_free!=cur->elem_num){goto end;} if(cur!=heap->block_list) { pre->next=cur->next; }else { heap->block_list=cur->next; } heap->tot_alloc-=cur->elem_num; heap_block_delete(cur); end: return ret; } int wtk_bit_heap_is_valid(wtk_bit_heap_t *heap) { HeapBlock *b; int f,t; int valid; f=t=0; for(b=heap->block_list;b;b=b->next) { f+=b->elem_free; t+=b->elem_num; } valid=0; if(t!=heap->tot_alloc) { wtk_debug("heap alloc is not equal: (real=%d,want=%d)\n",t,(int)heap->tot_alloc); goto end; } if(f!=(heap->tot_alloc-heap->tot_used)) { wtk_debug("heap free is not equal: (real=%d,want=%d)\n",f,(int)(heap->tot_alloc-heap->tot_used)); goto end; } valid=1; end: return valid; } void wtk_bit_heap_print(wtk_bit_heap_t *heap) { printf("=============== bit heap ============\n"); printf("alloc: %d\n",(int)(heap->tot_alloc)); printf("used: %d\n",(int)(heap->tot_used)); } void wtk_bit_heap_test_g() { typedef struct{ int i; float f; }wtk_foo_t; wtk_bit_heap_t *heap; wtk_foo_t *f; //create bit heap; heap=wtk_bit_heap_new(sizeof(wtk_foo_t),100,4096/sizeof(wtk_foo_t),1); //malloc element; f=wtk_bit_heap_malloc(heap); f->i=0;f->f=10; //free element; wtk_bit_heap_free(heap,f); //dlete bit heap; wtk_bit_heap_delete(heap); } <file_sep>/core/.svn/pristine/d4/d4f0e5070330ef2c942145e739091079c0231cbe.svn-base #ifndef WTK_CORE_WTK_SPLAYTREE_H_ #define WTK_CORE_WTK_SPLAYTREE_H_ #include "wtk/core/wtk_type.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_spnode wtk_spnode_t; typedef struct wtk_splaytree wtk_splaytree_t; struct wtk_spnode { wtk_spnode_t *left; wtk_spnode_t *right; void *value; }; struct wtk_splaytree { wtk_spnode_t *root; }; /** * @brief create splay tree; */ wtk_splaytree_t* wtk_splaytree_new(); /** * @brief init splay tree; */ int wtk_splaytree_init(wtk_splaytree_t* t);//,dispose_handler dispose,void *data); /** * @brief resplay the tree by cmp; */ wtk_spnode_t* wtk_splaytree_splay(wtk_splaytree_t *t,wtk_cmp_handler_t cmp,void *value,int *cmp_ret); /** * @brief find node by cmp; */ wtk_spnode_t* wtk_splaytree_find_node(wtk_splaytree_t *t,wtk_cmp_handler_t cmp,void *value); /** * @brief find node value by cmp; */ void* wtk_splaytree_find(wtk_splaytree_t *t,wtk_cmp_handler_t cmp,void *value); /** * @brief insert node and keep the tree order; */ int wtk_splaytree_insert(wtk_splaytree_t *t, wtk_cmp_handler_t cmp,void *cmp_param,wtk_spnode_t *node); /** * @brief remove node by cmp; */ wtk_spnode_t* wtk_splaytree_remove(wtk_splaytree_t* tree,wtk_cmp_handler_t cmp,void *value); /** * @walk the tree; */ int wtk_splaytree_walk(wtk_splaytree_t* t,wtk_walk_handler_t walk,void *user_data); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/9b/9b2d260850a9b681cb34bae8342bcc8efcacb2d3.svn-base #ifndef WTK_CORE_WTK_SORT_H_ #define WTK_CORE_WTK_SORT_H_ #include "wtk/core/wtk_type.h" #ifdef __cplusplus extern "C" { #endif /** * return src-dst */ typedef float (*wtk_qsort_cmp_f)(void *app_data,void *src,void *dst); /** * return usr_data - dst_data; */ typedef int(*wtk_search_cmp_f)(void *usr_data,void *dst_data); /** * @brief 0<1<2<3 * @param s, the first elem; * @param e, the last elem; * @param size: bytes of element; */ void wtk_qsort(void *s,void *e,size_t size,wtk_qsort_cmp_f cmp,void *app_data,void *tmp_elem); void wtk_qsort2(void *base,size_t nmemb,size_t size,wtk_qsort_cmp_f cmp,void *app_data); void wtk_qsort3(void *base,size_t nmemb,size_t size,wtk_qsort_cmp_f cmp,void *app_data,void *tmp_elem); void wtk_qsort_float(float *f,int len); void wtk_qsort_double(double *f,int len); /** * @brief search by element 0,1,2,3 * @param s, the first elem; * @param e, the last elem; * @param size, bytes of element; */ void* wtk_inc_search(void *s,void *e,int size,wtk_search_cmp_f cmp,void *usr_data); /** * @brief search in order array; * @param s, the first elem; * @param e, the last elem; * @param size, bytes of element; * [s,e] */ void* wtk_binary_search(void *s,void *e,int size,wtk_search_cmp_f cmp,void *usr_data); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_audio_type.c #include "wtk_audio_type.h" wtk_string_t* wtk_audio_type_to_fnstring(wtk_audio_type_t type) { static wtk_string_t fn[]={ wtk_string("wav"), wtk_string("mp3"), wtk_string("ogg"), wtk_string("flv"), wtk_string("data") }; static wtk_audio_type_t at[]={ AUDIO_WAV, AUDIO_MP3, AUDIO_OGG, AUDIO_FLV, }; static int n=sizeof(fn)/sizeof(wtk_string_t)-1; int i; wtk_string_t *name=0; for(i=0;i<n;++i) { if(type==at[i]) { name=&(fn[i]); break; } } if(i==n) { name=&(fn[3]); } return name; } wtk_audio_type_t wtk_audio_type_from_string(wtk_string_t *v) { static wtk_string_t audio[]={ wtk_string("audio/x-wav"), wtk_string("audio/mpeg"), wtk_string("audio/ogg"), wtk_string("audio/flv"), wtk_string("text/plain"), wtk_string("application/x-www-form-urlencoded"), wtk_string("text/xml"), }; static wtk_audio_type_t at[]={ AUDIO_WAV, AUDIO_MP3, AUDIO_OGG, AUDIO_FLV, AUDIO_TEXT, AUDIO_TEXT, AUDIO_TEXT, }; static int n=sizeof(audio)/sizeof(wtk_string_t); int i; wtk_audio_type_t audio_type; for(i=0;i<n;++i) { if(audio[i].len<=v->len && (strncmp(audio[i].data,v->data,audio[i].len)==0)) { audio_type=at[i]; break; } } if(i==n) { audio_type=AUDIO_UNKNOWN; } return audio_type; } wtk_string_t* wtk_audio_type_to_string(wtk_audio_type_t t) { static wtk_string_t audio[]={ wtk_string("audio/x-wav"), wtk_string("audio/mpeg"), wtk_string("audio/ogg"), wtk_string("audio/amr"), wtk_string("audio/flv"), wtk_string("text/plain"), wtk_string(""), wtk_string(""), }; return &(audio[t]); } <file_sep>/core/text/wtk_txtparser.c #include "wtk_txtparser.h" #include <ctype.h> int wtk_txtparser_feed(wtk_txtparser_t *p,char c); int wtk_txtparser_feed_start(wtk_txtparser_t *p,char c); int wtk_txtparser_feed_word(wtk_txtparser_t *p,char c); int wtk_txtparser_feed_inchar(wtk_txtparser_t *p,char c); int wtk_txtparser_feed_note_start(wtk_txtparser_t *p,char c); int wtk_txtparser_feed_note_tok(wtk_txtparser_t *p,char c); int wtk_txtparser_feed_note_sep(wtk_txtparser_t *p,char c); int wtk_txtparser_feed2(wtk_txtparser_t *p, wtk_string_t *str); int wtk_txtparser_feed_start2(wtk_txtparser_t *p, wtk_string_t *str); int wtk_txtparser_feed_word2(wtk_txtparser_t *p, wtk_string_t *str); int wtk_txtparser_feed_inchar2(wtk_txtparser_t *p, wtk_string_t *str); void wtk_tpword_print(wtk_tpword_t *w) { printf("%*.*s\n",w->name->len,w->name->len,w->name->data); printf("s:\t%d\n",w->s); printf("t:\t%d\n",w->t); printf("g:\t%d\n",w->g); printf("chntone:\t%d\n",w->chn_tone); if(w->sep) { printf("sep:\t%c\n",w->sep); } if(w->sep2) { printf("sep2:\t%.*s\n",w->sep2->len,w->sep2->data); } } void wtk_txtparser_init(wtk_txtparser_t *p,wtk_eos_t *os,wtk_txtparser_cfg_t *cfg,int cfg_is_ref) { p->cfg=cfg; p->cfg_is_ref=cfg_is_ref; p->os=os; p->heap=wtk_heap_new(4096); p->buf=wtk_strbuf_new(64,1); p->snt=wtk_strbuf_new(4096,1); //p->dot_hash=wtk_str_hash_new(337); p->is_wrd_f=0; p->is_wrd_data=0; p->wrd_normalize_f=0; p->wrd_normalize_ths=0; //wtk_txtparser_init_dot_hash(p); wtk_txtparser_reset(p); } wtk_txtparser_t* wtk_txtparser_new(wtk_eos_t *os) { wtk_txtparser_t *p; wtk_txtparser_cfg_t *cfg; cfg=(wtk_txtparser_cfg_t*)wtk_malloc(sizeof(*cfg)); wtk_txtparser_cfg_init(cfg); wtk_txtparser_cfg_update(cfg); p=(wtk_txtparser_t*)wtk_malloc(sizeof(*p)); wtk_txtparser_init(p,os,cfg,0); return p; } wtk_txtparser_t* wtk_txtparser_new2(wtk_txtparser_cfg_t *cfg,wtk_eos_t *os) { wtk_txtparser_t *p; p=(wtk_txtparser_t*)wtk_malloc(sizeof(*p)); wtk_txtparser_init(p,os,cfg,1); return p; } int wtk_txtparser_delete(wtk_txtparser_t *p) { if(!p->cfg_is_ref) { wtk_txtparser_cfg_clean(p->cfg); wtk_free(p->cfg); } //wtk_str_hash_delete(p->dot_hash); wtk_strbuf_delete(p->buf); wtk_strbuf_delete(p->snt); wtk_heap_delete(p->heap); wtk_free(p); return 0; } void wtk_txtparser_set_is_wrd_f(wtk_txtparser_t *p,wtk_txtparser_is_wrd_f is_wrd_f,void *is_wrd_data) { p->is_wrd_f=is_wrd_f; p->is_wrd_data=is_wrd_data; } void wtk_txtparser_set_wrd_normalize_callback(wtk_txtparser_t *p,wtk_txtparser_wrd_normalize_f normalize,void *ths) { p->wrd_normalize_f=normalize; p->wrd_normalize_ths=ths; } int wtk_txtparser_reset(wtk_txtparser_t *p) { wtk_heap_reset(p->heap); p->wrds=wtk_array_new_h(p->heap,1024,sizeof(wtk_tpword_t*)); wtk_strbuf_reset(p->buf); p->cur=0; p->state=TP_START; return 0; } void wtk_txtparser_add_dot_word(wtk_txtparser_t* p,char *wrd,int wrd_bytes) { wtk_txtparser_cfg_add_dot_word(p->cfg,wrd,wrd_bytes); } wtk_tpword_t* wtk_txtparser_new_word(wtk_txtparser_t *p) { wtk_tpword_t *w; w=(wtk_tpword_t*)wtk_heap_malloc(p->heap,sizeof(*w)); w->name=0; w->s=w->t=w->g=0; w->s_set=w->t_set=w->g_set=0; w->end_sep=0;w->sep=0; w->use_usr_pron=0; w->chn_tone=0; w->sep2 = 0; return w; } int wtk_txtparser_is_wrd(wtk_txtparser_t *p,char *wrd,int wrd_bytes) { return p->is_wrd_f?p->is_wrd_f(p->is_wrd_data,wrd,wrd_bytes):0; } int wtk_txtparser_normal_buf(wtk_txtparser_t* p,wtk_strbuf_t *buf) { int found; char c; wtk_string_t *v; found=wtk_txtparser_is_wrd(p,buf->data,buf->pos); if(found){goto end;} c=buf->data[buf->pos-1]; if(c=='.') { v=wtk_str_hash_find(p->cfg->dot_hash,buf->data,buf->pos); found=v?1:0; if(!found) { --buf->pos; p->cur->sep='.'; } /*------- jfyuan 20121012 add:start -------- */ /* deal with unnormal case, such as smoking'. */ c = buf->data[buf->pos-1]; if(c=='\'' || c=='-') --buf->pos; /*------- jfyuan 20121012 add:end -------- */ }else if(wtk_txtparser_cfg_is_extchar(p->cfg,c)) { --buf->pos; p->cur->sep=c; } end: return 0; } void wtk_txtparser_set_err(wtk_txtparser_t *p,char *msg,int msg_bytes) { if(p->buf->pos>0) { wtk_strbuf_push_s(p->buf,": "); } wtk_strbuf_push(p->buf,msg,msg_bytes); wtk_strbuf_push_f(p->buf," (index: %d).",p->char_index); if(p->os) { wtk_errno_set(p->os->err,WTK_EVAL_REF_INVALID,p->buf->data,p->buf->pos); }else { wtk_debug("%*.*s\n",p->buf->pos,p->buf->pos,p->buf->data); } } int wtk_txtparser_peek_word(wtk_txtparser_t *p) { wtk_strbuf_t *buf=p->buf; wtk_tpword_t *w=p->cur; int ret=-1; //wtk_debug("pos=%d\n",buf->pos); //print_data(buf->data,buf->pos); if(!w||buf->pos<=0){goto end;} wtk_txtparser_normal_buf(p,buf); //wtk_debug("%*.*s\n",buf->pos,buf->pos,buf->data); if(p->cfg->use_chn_tone) { char t; t=buf->data[buf->pos-1]; //wtk_debug("tone: %c\n",t); if(isdigit(t)) { if(t>'0' && t<='4') { w->chn_tone=t-'0'; } --buf->pos; } } if(p->wrd_normalize_f) { p->wrd_normalize_f(p->wrd_normalize_ths,buf); } if(buf->pos<=0){ret=0;goto end;} //wtk_debug("buf->pos=%d\n",buf->pos); w->name=wtk_heap_dup_string(p->heap,buf->data,buf->pos); if(p->wrds->nslot>0) { wtk_strbuf_push_c(p->snt,' '); } wtk_strbuf_push(p->snt,buf->data,buf->pos); //wtk_debug("%p:g=%d\n",w,w->g); //wtk_tpword_print(w); ((wtk_tpword_t **)wtk_array_push(p->wrds))[0]=w; p->cur=0;ret=0; //wtk_tpword_print(w); end: return ret; } int wtk_txtparser_feed_note_wait_end(wtk_txtparser_t *p,char c) { int ret=0; if(c==')') { p->state=TP_WORD; }else if(c==',') { p->state=TP_NOTE_START; }else if(!isspace(c)) { wtk_txtparser_set_err_s(p,"invalid char in sense end"); ret=-1; } return ret; } int wtk_txtparser_feed_note_sep(wtk_txtparser_t *p,char c) { wtk_tpword_t *w; int ret=0,v; if(c=='0' || c=='1') { w=p->cur; v=c-'0'; switch(w->cur_sense) { case 's': w->s=v; w->s_set=1; break; case 't': w->t=v; w->t_set=1; break; case 'g': w->g=v; w->g_set=1; break; } p->state=TP_NOTE_WAIT_END; }else if(!isspace(c)) { wtk_txtparser_set_err_s(p,"invalid char in sense tok value"); ret=-1; } return ret; } int wtk_txtparser_feed_note_start(wtk_txtparser_t *p,char c) { wtk_tpword_t *w; int ret=0; if(wtk_txtpaser_cfg_is_note(p->cfg,c)) { w=p->cur; w->cur_sense=c; p->state=TP_NOTE_TOK; }else if(!isspace(c)) { wtk_txtparser_set_err_s(p,"invalid char in sense tok"); ret=-1; } return ret; } int wtk_txtparser_feed_note_tok(wtk_txtparser_t *p,char c) { int ret=0; if(c==':') { p->state=TP_NOTE_SEP; }else if(!isspace(c)) { wtk_txtparser_set_err_s(p,"invalid char in sense tok sep"); ret=-1; } return ret; } int wtk_txtparser_feed_start(wtk_txtparser_t *p,char c) { if(wtk_txtparser_cfg_is_schar(p->cfg,c)) { p->state=TP_WORD; p->cur=wtk_txtparser_new_word(p); wtk_strbuf_reset(p->buf); wtk_strbuf_push_c(p->buf,c); } return 0; } int wtk_txtparser_feed_word(wtk_txtparser_t *p,char c) { wtk_strbuf_t* buf=p->buf; int ret=0; if(wtk_txtparser_cfg_is_char(p->cfg,c)) { wtk_strbuf_push_c(buf,c); }else if(wtk_txtparser_cfg_is_inchar(p->cfg,c)) { wtk_strbuf_push_c(buf,c); p->state=TP_INCHAR; }else if(c=='(') { p->state=TP_NOTE_START; }else if(isspace(c)||c==-1) { ret=wtk_txtparser_peek_word(p); p->state=TP_START; }else if(wtk_txtpaser_cfg_is_sep(p->cfg,c)) { p->cur->end_sep=1; p->cur->sep=c; ret=wtk_txtparser_peek_word(p); p->state=TP_START; }else { ret=wtk_txtparser_peek_word(p); p->state=TP_START; //wtk_txtparser_set_err_s(p," word is end by non-char."); //ret=-1; } return ret; } int wtk_txtparser_feed_inchar(wtk_txtparser_t *p,char c) { wtk_strbuf_t* buf=p->buf; int ret=0; if(wtk_txtparser_cfg_is_char(p->cfg,c)) { wtk_strbuf_push_c(buf,c); p->state=TP_WORD; }else if(wtk_txtparser_cfg_is_inchar(p->cfg,c)) { wtk_strbuf_push_c(buf,c); }else { wtk_txtparser_set_err_s(p,"word is end by in-char"); ret=-1; } return ret; } int wtk_txtparser_feed(wtk_txtparser_t *p,char c) { int ret; //printf("%c,%d\n",c,p->state); switch(p->state) { case TP_START: ret=wtk_txtparser_feed_start(p,c); break; case TP_WORD: ret=wtk_txtparser_feed_word(p,c); break; case TP_INCHAR: ret=wtk_txtparser_feed_inchar(p,c); break; case TP_NOTE_START: ret=wtk_txtparser_feed_note_start(p,c); break; case TP_NOTE_TOK: ret=wtk_txtparser_feed_note_tok(p,c); break; case TP_NOTE_SEP: ret=wtk_txtparser_feed_note_sep(p,c); break; case TP_NOTE_WAIT_END: ret=wtk_txtparser_feed_note_wait_end(p,c); break; default: wtk_txtparser_set_err_s(p,"unexpected state"); ret=-1; break; } return ret; } void wtk_txtparser_post_process(wtk_txtparser_t *tp) { wtk_tpword_t **wrds,*wrd; if(tp->wrds->nslot<=0){goto end;} wrds=(wtk_tpword_t**)tp->wrds->slot; wrd=wrds[tp->wrds->nslot-1]; if(!wrd->g_set) { wrd->g=1; } end: return; } int wtk_txtparser_parse(wtk_txtparser_t *tp,char *data,int bytes) { wtk_strbuf_t *snt=tp->snt; char *p=data,*end=data+bytes; int ret=-1; //print_data(data,bytes); tp->char_index=0; wtk_strbuf_reset(snt); wtk_strbuf_push_s(snt,"(sil "); if(tp->cfg->use_utf8) { int cnt; wtk_string_t v; while(p < end) { cnt = wtk_utf8_bytes(*p); wtk_string_set(&(v), p, cnt); //wtk_debug("v = %.*s[%d]\n", v.len, v.data, v.len); ret = wtk_txtparser_feed2(tp, &v); if(0 != ret) { goto end; } p += cnt; } ret = wtk_txtparser_feed(tp, -1); if(0 != ret) { goto end; } ret=tp->wrds->nslot>0?0:-1; if(ret!=0){goto end;} } else { while(p<end) { ret=wtk_txtparser_feed(tp,tolower(*p)); if(ret!=0){goto end;} ++tp->char_index; ++p; } ret=wtk_txtparser_feed(tp,-1); if(ret!=0){goto end;} ret=tp->wrds->nslot>0?0:-1; if(ret!=0){goto end;} wtk_txtparser_post_process(tp); } wtk_strbuf_push_s(snt," sil)"); end: return ret; } wtk_tpword_t* wtk_txtparse_add_tpword(wtk_txtparser_t *p,char *w,int bytes) { wtk_tpword_t *tw; wtk_heap_t *heap=p->heap; tw=wtk_txtparser_new_word(p); tw->name=wtk_heap_dup_string(heap,w,bytes); ((wtk_tpword_t **)wtk_array_push(p->wrds))[0]=tw; return tw; } void wtk_txtparser_add_word(wtk_txtparser_t *p,char *w,int bytes) { wtk_txtparse_add_tpword(p,w,bytes); if(p->wrds->nslot>0) { wtk_strbuf_push_c(p->snt,' '); } wtk_strbuf_push(p->snt,w,bytes); } int wtk_txtparser_to_string(wtk_txtparser_t *p,wtk_strbuf_t *buf,int add_note) { wtk_tpword_t **wrds; wtk_tpword_t *wrd; int i,nwrd; int n; wtk_strbuf_reset(buf); if(!p->wrds){nwrd=0;goto end;} wrds=(wtk_tpword_t**)p->wrds->slot; //wtk_debug("nslot: %d\n",p->wrds->nslot); nwrd=p->wrds->nslot; for(i=0;i<nwrd;++i) { wrd=wrds[i]; if(i>0) { wtk_strbuf_push_s(buf," "); } wtk_strbuf_push(buf,wrd->name->data,wrd->name->len); if(add_note && (wrd->t || wrd->g ||wrd->s)) { n=0; wtk_strbuf_push_s(buf,"("); if(wrd->t) { wtk_strbuf_push_s(buf,"t:1"); ++n; } if(wrd->g) { if(n>0) { wtk_strbuf_push_s(buf,","); } wtk_strbuf_push_s(buf,"g:1"); ++n; } if(wrd->s) { if(n>0) { wtk_strbuf_push_s(buf,","); } wtk_strbuf_push_s(buf,"s:1"); ++n; } wtk_strbuf_push_s(buf,")"); } } end: return nwrd; } void wtk_txtparser_print(wtk_txtparser_t *p) { wtk_tpword_t **wrds; int i; printf("%*.*s\n",p->snt->pos,p->snt->pos,p->snt->data); wrds=(wtk_tpword_t**)p->wrds->slot; for(i=0;i<p->wrds->nslot;++i) { wtk_tpword_print(wrds[i]); } } //------------------ surport utf8 --------------- /* * @auth: jfyuan * @date: 2014-06-10 * @brief: surport the text which is encoded by utf-8 * @see */ /* start word */ int wtk_txtparser_feed_start2(wtk_txtparser_t *p, wtk_string_t *str) { p->state = TP_WORD; p->cur = wtk_txtparser_new_word(p); wtk_strbuf_reset(p->buf); wtk_strbuf_push(p->buf, str->data, str->len); return 0; } /* in char */ int wtk_txtparser_feed_inchar2(wtk_txtparser_t *p, wtk_string_t *str) { wtk_strbuf_t* buf=p->buf; int ret=0; if(wtk_txtparser_cfg_is_char2(p->cfg, str)) { wtk_strbuf_push(buf, str->data, str->len); p->state=TP_WORD; }else if(wtk_txtparser_cfg_is_inchar2(p->cfg, str)) { wtk_strbuf_push(buf, str->data, str->len); }else { wtk_txtparser_set_err_s(p,"word is end by in-char"); ret=-1; } return ret; } int wtk_txtparser_feed_word2(wtk_txtparser_t *p, wtk_string_t *str) { wtk_strbuf_t* buf=p->buf; char c; int ret=0; if(str->len == 1) { c = *(str->data); if(wtk_txtparser_cfg_is_inchar(p->cfg,c)) { wtk_strbuf_push_c(buf,c); p->state=TP_INCHAR; }else if(c=='(') { p->state=TP_NOTE_START; }else if(isspace(c)||c==-1) { ret=wtk_txtparser_peek_word(p); p->state=TP_START; }else if(wtk_txtpaser_cfg_is_sep(p->cfg,c)) { p->cur->end_sep=1; //p->cur->sep=c; p->cur->sep2 = wtk_heap_dup_string(p->heap, str->data, str->len); ret=wtk_txtparser_peek_word(p); p->state=TP_START; }else { ret=wtk_txtparser_peek_word(p); p->state=TP_START; } } else { if(wtk_txtparser_cfg_is_inchar2(p->cfg, str)) { wtk_strbuf_push(buf, str->data, str->len); p->state=TP_INCHAR; } else if(wtk_txtparser_cfg_is_sep2(p->cfg, str)) { p->cur->end_sep = 1; p->cur->sep2 = wtk_heap_dup_string(p->heap, str->data, str->len); ret = wtk_txtparser_peek_word(p); p->state = TP_START; goto end; } wtk_strbuf_push(buf, str->data, str->len); } end: return ret; } int wtk_txtparser_feed2(wtk_txtparser_t *p, wtk_string_t *str) { int ret; char c = *(str->data); //printf("%c,%d\n",c,p->state); switch(p->state) { case TP_START: ret = wtk_txtparser_feed_start2(p, str); break; case TP_WORD: ret = wtk_txtparser_feed_word2(p, str); break; case TP_INCHAR: ret = wtk_txtparser_feed_inchar2(p, str); break; case TP_NOTE_START: ret = wtk_txtparser_feed_note_start(p, c); break; case TP_NOTE_TOK: ret=wtk_txtparser_feed_note_tok(p,c); break; case TP_NOTE_SEP: ret=wtk_txtparser_feed_note_sep(p,c); break; case TP_NOTE_WAIT_END: ret=wtk_txtparser_feed_note_wait_end(p,c); break; default: wtk_txtparser_set_err_s(p,"unexpected state"); ret=-1; break; } return ret; } //------------------------ example section -------------------- void wtk_txtparser_test_g() { wtk_txtparser_t *p; int i; p=wtk_txtparser_new(0); for(i=0;i<10;++i) { wtk_txtparser_parse_s(p,"yes hello. world-check me"); wtk_txtparser_print(p); wtk_txtparser_reset(p); } wtk_txtparser_delete(p); } <file_sep>/core/math/wtk_sfvec.c #include "wtk_sfvec.h" void wtk_sfvec_init(wtk_sfvec_t *v) { wtk_queue3_init(&(v->item_q)); } void wtk_sfvec_add_value(wtk_sfvec_t *v,wtk_svec_item_t *item) { wtk_queue_node_t *qn; wtk_svec_item_t *si; wtk_queue_node_t *prev=NULL; //wtk_debug("%d:%.0f\n",item->i,item->v); for(qn=v->item_q.push;qn;qn=qn->prev) { si=data_offset2(qn,wtk_svec_item_t,q_n); if(si->i<item->i) { prev=qn; break; } } //wtk_debug("prev=%p\n",prev); if(prev) { wtk_queue3_insert_to(&(v->item_q),prev,&(item->q_n)); }else { if(qn) { wtk_queue3_push(&(v->item_q),&(item->q_n)); }else { wtk_queue3_push_front(&(v->item_q),&(item->q_n)); } } //wtk_sfvec_print(v); } void wtk_sfvec_norm(wtk_sfvec_t *v) { wtk_queue_node_t *qn; wtk_svec_item_t *si; float f; f=0; for(qn=v->item_q.pop;qn;qn=qn->next) { si=data_offset2(qn,wtk_svec_item_t,q_n); f+=si->v*si->v; } if(f==0){return;} f=1.0/sqrt(f); for(qn=v->item_q.pop;qn;qn=qn->next) { si=data_offset2(qn,wtk_svec_item_t,q_n); si->v*=f; } } double wtk_sfvec_dist(wtk_sfvec_t *sf1,wtk_sfvec_t *sf) { wtk_queue_node_t *qn,*qn2; wtk_svec_item_t *si,*si2; double f,t; int b; //wtk_sfvec_print(sf1); //wtk_sfvec_print(sf); f=0; for(qn2=sf1->item_q.pop;qn2;qn2=qn2->next) { si2=data_offset2(qn2,wtk_svec_item_t,q_n); t=0; for(qn=sf->item_q.pop;qn;qn=qn->next) { si=data_offset2(qn,wtk_svec_item_t,q_n); //wtk_debug("v[%d]=%d\n",i,si->i); if(si2->i==si->i) { //wtk_debug("v[%d]=%f\n",si->i,si->v); t=si->v; break; }else if(si2->i<si->i) { break; } } //wtk_debug("v[%d]=%f-%f\n",si2->i,si2->v,t); t=si2->v-t; f+=t*t; } for(qn2=sf->item_q.pop;qn2;qn2=qn2->next) { si2=data_offset2(qn2,wtk_svec_item_t,q_n); t=0; b=0; for(qn=sf1->item_q.pop;qn;qn=qn->next) { si=data_offset2(qn,wtk_svec_item_t,q_n); //wtk_debug("v[%d]=%d\n",i,si->i); if(si2->i==si->i) { b=1; break; } } if(b) { continue; } t=si2->v; //wtk_debug("v[%d]=%f\n",si2->i,si2->v); f+=t*t; } //wtk_debug("f=%f\n",f); //exit(0); return f; } void wtk_sfvec_dup(wtk_sfvec_t *src,wtk_sfvec_t *dst,wtk_heap_t *heap) { wtk_queue_node_t *qn; wtk_svec_item_t *si,*ti; wtk_sfvec_init(dst); for(qn=src->item_q.pop;qn;qn=qn->next) { si=data_offset2(qn,wtk_svec_item_t,q_n); //printf("%d:%.3f\n",si->i,si->v); ti=(wtk_svec_item_t*)wtk_heap_malloc(heap,sizeof(wtk_svec_item_t)); ti->i=si->i; ti->v=si->v; wtk_sfvec_add_value(dst,ti); } } void wtk_sfvec_print(wtk_sfvec_t *v) { wtk_queue_node_t *qn; wtk_svec_item_t *si; wtk_debug("============ class %d ====================\n",v->item_q.len); for(qn=v->item_q.pop;qn;qn=qn->next) { si=data_offset2(qn,wtk_svec_item_t,q_n); printf("%d:%.3f\n",si->i,si->v); } } <file_sep>/core/wtk_shash.c #include "wtk_shash.h" wtk_shash_t* wtk_shash_new(int nslot) { wtk_shash_t *hash; hash=(wtk_shash_t*)wtk_malloc(sizeof(wtk_shash_t)); hash->nslot=nslot; hash->slot=(wtk_slist_node_t*)wtk_calloc(nslot,sizeof(wtk_slist_node_t)); hash->used=0; wtk_shash_reset(hash); return hash; } void wtk_shash_delete(wtk_shash_t *h) { wtk_free(h->slot); wtk_free(h); } int wtk_shash_bytes(wtk_shash_t *h) { int b; b=h->nslot*sizeof(wtk_slist_node_t); b+=sizeof(*h); return b; } void wtk_shash_reset(wtk_shash_t *h) { //redesign later if(h->used>0) { if(h->nslot>40960) { wtk_free(h->slot); h->slot=(wtk_slist_node_t*)wtk_calloc(h->nslot,sizeof(wtk_slist_node_t)); }else { memset(h->slot,0,sizeof(wtk_slist_node_t)*h->nslot); } h->used=0; } } void wtk_shash_add(wtk_shash_t *h,unsigned int id,wtk_slist_node_t *q_n) { wtk_slist_node_t *s; unsigned int index; ++h->used; index=id%h->nslot; s=h->slot+index; //wtk_debug("s->prev=%p\n",s->prev); q_n->prev=s->prev; s->prev=q_n; } void wtk_shash_dump2(wtk_shash_t *h,FILE *log) { wtk_slist_node_t *s; int i,n; fprintf(log,"h n\n"); for(i=0;i<h->nslot;i+=1) { s=h->slot+i; n=wtk_slist_len(s); if(n>0) { fprintf(log,"%d %d\n",i,n); } } } void wtk_shash_dump(wtk_shash_t *h,char *fn) { FILE *f; f=fopen(fn,"w"); wtk_shash_dump2(h,f); fclose(f); } <file_sep>/core/.svn/pristine/b9/b9424fa8f3f0149ff6edee26a1002f6e8ba07450.svn-base #include "wtk/core/cfg/wtk_local_cfg.h" wtk_local_cfg_t *wtk_local_cfg_new_h(wtk_heap_t *h) { wtk_local_cfg_t *c; c=(wtk_local_cfg_t*)wtk_heap_zalloc(h,sizeof(*c)); c->cfg=wtk_cfg_queue_new_h(h); c->heap=h; return c; } wtk_local_cfg_t* wtk_local_cfg_find_lc(wtk_local_cfg_t *cfg,char *d,int bytes) { wtk_cfg_item_t *i; wtk_local_cfg_t *lc=0; if(!cfg){goto end;} i=(wtk_cfg_item_t*)wtk_cfg_queue_find(cfg->cfg,d,bytes); if(i && wtk_cfg_item_is_lc(i)){lc=i->value.cfg;goto end;} lc=wtk_local_cfg_find_lc(cfg->parent,d,bytes); end: return lc; } wtk_cfg_item_t* wtk_local_cfg_find_local(wtk_local_cfg_t *cfg,char *d,int bytes) { return (wtk_cfg_item_t*)wtk_cfg_queue_find(cfg->cfg,d,bytes); } wtk_cfg_item_t* wtk_local_cfg_find(wtk_local_cfg_t *cfg,char *d,int bytes) { wtk_cfg_item_t *i; i=(wtk_cfg_item_t*)wtk_cfg_queue_find(cfg->cfg,d,bytes); if(i){goto end;} if(cfg->parent) { i=wtk_local_cfg_find(cfg->parent,d,bytes); }else { i=NULL; } end: return i; } wtk_string_t* wtk_local_cfg_find_string(wtk_local_cfg_t *cfg,char *d,int bytes) { return wtk_local_cfg_find_string2(cfg,d,bytes,1); } wtk_string_t* wtk_local_cfg_find_string2(wtk_local_cfg_t *cfg,char *d,int bytes,int recursive) { wtk_string_t* name=0; wtk_cfg_item_t *i; if(!cfg){goto end;} i=(wtk_cfg_item_t*)wtk_cfg_queue_find(cfg->cfg,d,bytes); if(i && wtk_cfg_item_is_string(i)){name=i->value.str;goto end;} if(recursive) { name=wtk_local_cfg_find_string(cfg->parent,d,bytes); } end: return name; } wtk_array_t* wtk_local_cfg_find_array(wtk_local_cfg_t *cfg,char *d,int bytes) { wtk_array_t* a=0; wtk_cfg_item_t *i; if(!cfg){goto end;} i=(wtk_cfg_item_t*)wtk_cfg_queue_find(cfg->cfg,d,bytes); if(i && wtk_cfg_item_is_array(i)){a=i->value.array;goto end;} a=wtk_local_cfg_find_array(cfg->parent,d,bytes); end: return a; } wtk_array_t* wtk_local_cfg_find_int_array(wtk_local_cfg_t *cfg,char *d,int bytes) { wtk_array_t* a=0,*b=0; wtk_cfg_item_t *i; wtk_string_t **v; int k,j; if(!cfg){goto end;} i=(wtk_cfg_item_t*)wtk_cfg_queue_find(cfg->cfg,d,bytes); if(i && wtk_cfg_item_is_array(i)){b=i->value.array;goto end;} b=wtk_local_cfg_find_array(cfg->parent,d,bytes); if(!b){goto end;} end: if(b) { v=(wtk_string_t**)b->slot; a=wtk_array_new_h(cfg->heap,b->nslot,sizeof(int)); for(k=0;k<b->nslot;++k) { j=atoi(v[k]->data); *((int*)wtk_array_push(a))=j; } } return a; } wtk_array_t* wtk_local_cfg_find_float_array(wtk_local_cfg_t *cfg,char *d,int bytes) { wtk_array_t* a=0,*b=0; wtk_cfg_item_t *i; wtk_string_t **v; int k; float j; if(!cfg){goto end;} i=(wtk_cfg_item_t*)wtk_cfg_queue_find(cfg->cfg,d,bytes); if(i && wtk_cfg_item_is_array(i)){b=i->value.array;goto end;} b=wtk_local_cfg_find_array(cfg->parent,d,bytes); if(!b){goto end;} end: if(b) { v=(wtk_string_t**)b->slot; a=wtk_array_new_h(cfg->heap,b->nslot,sizeof(float)); for(k=0;k<b->nslot;++k) { j=atof(v[k]->data); *((float*)wtk_array_push(a))=j; } } return a; } wtk_cfg_item_t* wtk_local_cfg_add_item(wtk_local_cfg_t *lc,wtk_cfg_item_t *vi) { wtk_cfg_item_t *item; switch(vi->type) { case WTK_CFG_STRING: item=wtk_cfg_queue_add_string(lc->cfg,vi->key->data,vi->key->len,vi->value.str->data,vi->value.str->len); break; case WTK_CFG_LC: item=wtk_cfg_queue_add_lc(lc->cfg,vi->key->data,vi->key->len,vi->value.cfg); break; case WTK_CFG_ARRAY: item=wtk_cfg_queue_add_array(lc->cfg,vi->key->data,vi->key->len,vi->value.array); break; default: item=NULL; break; } return item; } wtk_cfg_item_t* wtk_local_cfg_find_item(wtk_local_cfg_t *lc,wtk_cfg_item_t *vi) { wtk_queue_node_t *qn; wtk_cfg_item_t *item; for(qn=lc->cfg->queue.pop;qn;qn=qn->next) { item=data_offset2(qn,wtk_cfg_item_t,n); if(item->type==vi->type && wtk_string_cmp(vi->key,item->key->data,item->key->len)==0) { return item; } } return NULL; } void wtk_local_cfg_update(wtk_local_cfg_t *lc,wtk_local_cfg_t *custom) { wtk_queue_node_t *qn; wtk_cfg_item_t *item; wtk_cfg_item_t *vi; for(qn=custom->cfg->queue.pop;qn;qn=qn->next) { item=data_offset2(qn,wtk_cfg_item_t,n); vi=wtk_local_cfg_find_item(lc,item); if(vi) { //wtk_debug("set...\n"); switch(item->type) { case WTK_CFG_STRING: vi->value.str=item->value.str; break; case WTK_CFG_LC: wtk_local_cfg_update(vi->value.cfg,item->value.cfg); break; case WTK_CFG_ARRAY: vi->value.array=item->value.array; break; } }else { wtk_local_cfg_add_item(lc,item); } } //exit(0); } /** * @param last_field is set when called,if section is "httpd:nk:port",last_field is set to "port"; * @return NULL if not found; */ wtk_local_cfg_t* wtk_local_cfg_find_section(wtk_local_cfg_t *lc,char *section,int section_bytes,wtk_string_t *last_field) { char *ks,*ke,*ls; int len; ls=ks=section; ke=ks+section_bytes; while(ks<ke) { if(*ks==':') { len=ks-ls; lc=wtk_local_cfg_find_lc(lc,ls,len); //wtk_debug("lc:%*.*s=%p\n",len,len,ls,lc); ls=ks+1; //wtk_local_cfg_print(lc); } ++ks; } if(!lc){goto end;} len=ke-ls; wtk_string_set(last_field,ls,len); end: //wtk_debug("%*.*s=%s\n",n->key.len,n->key.len,n->key.data,v); return lc; } wtk_local_cfg_t* wtk_local_cfg_find_section_lc(wtk_local_cfg_t* lc,char *section,int section_bytes) { wtk_string_t last_field; lc=wtk_local_cfg_find_section(lc,section,section_bytes,&last_field); if(!lc){goto end;} lc=wtk_local_cfg_find_lc(lc,last_field.data,last_field.len); end: return lc; } int wtk_local_cfg_update_hash(wtk_local_cfg_t* lc,wtk_arg_item_t *n,int show) { wtk_string_t last_field; char *v; wtk_string_t *xv; if(n->v.len<=0){return 0;} v=(char*)n->v.data; lc=wtk_local_cfg_find_section(lc,n->k.data,n->k.len,&last_field); if(!lc){goto end;} xv=wtk_local_cfg_find_string(lc,last_field.data,last_field.len); if(xv) { wtk_string_set(xv,v,strlen(v)); if(show) { printf("[cmd] update %.*s=%s\n",n->k.len,n->k.data,v); } }else { wtk_cfg_queue_add_string(lc->cfg,last_field.data,last_field.len,v,strlen(v)); if(show) { printf("[cmd] set %.*s=%s\n",n->k.len,n->k.data,v); } } end: //wtk_debug("%*.*s=%s\n",n->key.len,n->key.len,n->key.data,v); return 0; } int wtk_local_cfg_hook_update(void **hook,wtk_arg_item_t *item) { return wtk_local_cfg_update_hash((wtk_local_cfg_t*)hook[0],item,*(int*)hook[1]); } void wtk_local_cfg_update_arg(wtk_local_cfg_t *lc,wtk_arg_t *arg,int show) { void *hook[2]={lc,&show}; if(show) { printf("================ update ===============\n"); } //wtk_str_hash_walk(arg->hash,(wtk_walk_handler_t)wtk_local_cfg_hook_update,hook); wtk_queue_walk(&(arg->queue),offsetof(wtk_arg_item_t,q_n),(wtk_walk_handler_t)wtk_local_cfg_hook_update,hook); if(show) { printf("=======================================\n\n"); } } void wtk_local_cfg_print(wtk_local_cfg_t *lc) { //printf("################ %*.*s ########################\n",lc->name.len,lc->name.len,lc->name.data); wtk_cfg_queue_print(lc->cfg); //printf("################################################\n"); } void wtk_local_cfg_value_to_string(wtk_local_cfg_t *lc,wtk_strbuf_t *buf) { wtk_cfg_queue_to_string(lc->cfg,buf); } <file_sep>/core/.svn/pristine/9a/9a6c77cc36fdc69ce0e7bad87a062545fb8dd55c.svn-base #include "wtk_matrix.h" #include <math.h> double wtk_fast_exp(double y) { #define EXP_A (1048576/M_LN2) #define EXP_C 60801 union { double d; struct { int j, i; } n; } d2i; d2i.n.j=0; d2i.n.i = EXP_A*(y)+(1072693248-EXP_C); return d2i.d; } float wtk_fast_exp2(float y) { #define EXP_A (1048576/M_LN2) #define EXP_C 60801 union { double d; struct { int j, i; } n; } d2i; d2i.n.j=0; d2i.n.i = EXP_A*(y)+(1072693248-EXP_C); return d2i.d; } wtk_double_matrix_t* wtk_double_matrix_init(char *p,int nrows,int ncols) { int csize; double **m; int i; m=(double**)p; *((int*)p)=nrows; csize=wtk_double_vector_bytes(ncols); p+=wtk_round_word((nrows+1)*sizeof(double*)); for(i=1;i<=nrows;++i,p+=csize) { *((int*)p)=ncols; m[i]=(double*)p; } return m; } wtk_double_matrix_t* wtk_double_matrix_new(int nrows,int ncols) { char *p; p=(char*)wtk_malloc(wtk_double_matrix_bytes(nrows,ncols)); return wtk_double_matrix_init(p,nrows,ncols); } wtk_double_matrix_t* wtk_double_matrix_new_h(wtk_heap_t *heap,int nrows,int ncols) { char *p; p=(char*)wtk_heap_malloc(heap,wtk_double_matrix_bytes(nrows,ncols)); return wtk_double_matrix_init(p,nrows,ncols); } wtk_smatrix_t* wtk_smatrix_newh(wtk_heap_t *h,int nrows,int ncols) { float** m; char *p; int csize,j; p=(char*)wtk_heap_malloc(h,wtk_smatrix_bytes(nrows,ncols))+2*sizeof(void**); m=(float**)((char*)p);//+2*sizeof(void**)); *(int*)m=nrows; csize=wtk_vector_bytes(ncols); p+=(nrows+1)*sizeof(float*); for(j=1;j<=nrows;++j,p+=csize) { *(int*)p=ncols; m[j]=(float*)p; } wtk_set_hook((void**)m,0); wtk_set_use((void**)m,0); return m; } wtk_matrix_t* wtk_matrix_init(char *p,int nrows,int ncols) { float **m; int csize; int i; m=(float**)p; *((int*)p)=nrows; csize=wtk_vector_bytes(ncols); p+=wtk_round_word((nrows+1)*sizeof(float*)); for(i=1;i<=nrows;++i,p+=csize) { *((int*)p)=ncols; m[i]=(float*)p; } return m; } wtk_matrix_t* wtk_matrix_new(int nrows,int ncols) { char *p; p=(char*)wtk_calloc(1,wtk_matrix_bytes(nrows,ncols)); return wtk_matrix_init(p,nrows,ncols); } int wtk_matrix_bytes2(wtk_matrix_t *m) { int r,c; r=wtk_matrix_rows(m); c=wtk_matrix_cols(m); return wtk_matrix_bytes(r,c); } wtk_matrix_t* wtk_matrix_newh(wtk_heap_t* h,int nrows,int ncols) { char *p; p=(char*)wtk_heap_malloc(h,wtk_matrix_bytes(nrows,ncols)); return wtk_matrix_init(p,nrows,ncols); } //0.119 void wtk_matrix_multi2(wtk_matrix_t *m,wtk_matrix_t *a,wtk_matrix_t *b) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int ac=wtk_matrix_cols(a); int i,j,k; double t; float *p; //#define DEBUG_MXY //wtk_debug("rows=%d,cols=%d,ac=%d\n",rows,cols,ac); for(i=1;i<=rows;++i) { p=a[i]; for(j=1;j<=cols;++j) { for(t=0,k=1;k<=ac;++k) { t+=p[k]*b[k][j]; #ifdef DEBUG_MXY wtk_debug("v[%d]=%f*%f/%f\n",k,p[k],b[k][j],t);//,k,j); if(k==10) { //exit(0); } #endif } m[i][j]=t; #ifdef DEBUG_MXY wtk_debug("v[%d][%d]=%f\n",i,j,m[i][j]); exit(0); #endif } } } //0.133 void wtk_matrix_multi1(wtk_matrix_t *m,wtk_matrix_t *a,wtk_matrix_t *b) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int ac=wtk_matrix_cols(a); int i,j,k; for(i=1;i<=rows;++i) { for(j=1;j<=cols;++j) { m[i][j]=0; for(k=1;k<=ac;++k) { m[i][j]+=a[i][k]*b[k][j]; //wtk_debug("%d,%d,%d,%f,%f,%f\n",i,j,k,m[i][j],a[i][k],b[k][j]); } } } } //0.09 void wtk_matrix_multi5(wtk_matrix_t *m,wtk_matrix_t *a,wtk_matrix_t *b) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int ac=wtk_matrix_cols(a); int i,k; float *pa,*pm; register float *tpm,*tpb; register float pak; register float *e; for(i=1;i<=rows;++i) { pa=a[i];pm=m[i]; e=pm+cols; for(k=1;k<=ac;++k) { tpb=b[k];pak=pa[k]; tpm=pm; //wtk_debug("%d/%d=%d\n",i,k,(int)(e-tpm)); if(k==1) { while(tpm<e) { *(++tpm)=pak*(*(++tpb)); } }else { while(tpm<e) { *(++tpm)+=pak*(*(++tpb)); } } } } } #ifdef USE_ASM #include <xmmintrin.h> void wtk_matrix_multi(wtk_matrix_t *m,wtk_matrix_t *a,wtk_matrix_t *b) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int ac=wtk_matrix_cols(a); int i,k; float *pa,*pm; register float *tpm,*tpb; register float pak; register float *e; register __m128 ma; //wtk_debug("m=%p a=%p b=%p\n",m,a,b); //wtk_debug("rows=%d cols=%d\n",rows,cols); for(i=1;i<=rows;++i) { pa=a[i];pm=m[i]+1; e=pm+cols; for(k=1;k<=ac;++k) { tpb=b[k]+1;pak=pa[k]; tpm=pm; //wtk_debug("%d/%d=%d\n",i,k,(int)(e-tpm)); ma=_mm_set_ps(pak,pak,pak,pak); if(k==1) { while(e-tpm>=4) { *((__m128*)tpb)=_mm_mul_ps(ma,*((__m128*)tpb)); tpb+=4; tpm+=4; /* *(((__m128*)tpb)+1)=_mm_mul_ps(ma,*(((__m128*)tpb)+1)); *(((__m128*)tpb)+2)=_mm_mul_ps(ma,*(((__m128*)tpb)+2)); *(((__m128*)tpb)+3)=_mm_mul_ps(ma,*(((__m128*)tpb)+3)); tpb+=16; tpm+=16; */ } while(tpm<e) { *(tpm++)=pak*(*(tpb++)); } }else { while(e-tpm>=4) { *((__m128*)tpm)=_mm_add_ps(_mm_mul_ps(ma,*((__m128*)tpb)),*((__m128*)tpm));//*((__m128*)tpb));//,mb); tpb+=4; tpm+=4; /* *((__m128*)tpm+1)=_mm_add_ps(_mm_mul_ps(ma,*((__m128*)tpb+1)),*((__m128*)tpm+1)); *((__m128*)tpm+2)=_mm_add_ps(_mm_mul_ps(ma,*((__m128*)tpb+2)),*((__m128*)tpm+2)); *((__m128*)tpm+3)=_mm_add_ps(_mm_mul_ps(ma,*((__m128*)tpb+3)),*((__m128*)tpm+3)); tpb+=16; tpm+=16; */ } while(tpm<e) { *(tpm++)+=pak*(*(tpb++)); } } } } } #endif void wtk_matrix_multi(wtk_matrix_t *m,wtk_matrix_t *a,wtk_matrix_t *b) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int ac=wtk_matrix_cols(a); int i,k; float *pa,*pm; register float *tpm,*tpb; register float pak; register float *e; for(i=1;i<=rows;++i) { pa=a[i];pm=m[i]; e=pm+cols; for(k=1;k<=ac;++k) { tpb=b[k];pak=pa[k]; tpm=pm; //wtk_debug("%d/%d=%d\n",i,k,(int)(e-tpm)); if(k==1) { while(e-tpm>=4) { *(++tpm)=pak*(*(++tpb)); *(++tpm)=pak*(*(++tpb)); *(++tpm)=pak*(*(++tpb)); *(++tpm)=pak*(*(++tpb)); } while(tpm<e) { *(++tpm)=pak*(*(++tpb)); } }else { while(e-tpm>=4) { *(++tpm)+=pak*(*(++tpb)); *(++tpm)+=pak*(*(++tpb)); *(++tpm)+=pak*(*(++tpb)); *(++tpm)+=pak*(*(++tpb)); } while(tpm<e) { *(++tpm)+=pak*(*(++tpb)); } } } } } void wtk_matrix_multi4(wtk_matrix_t *m,wtk_matrix_t *a,wtk_matrix_t *b) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int ac=wtk_matrix_cols(a); int i,k; float *pa,*pm; register float *tpm,*tpb; register float pak; register float *e; ////|1*429|*|429*1500|=0; //wtk_debug("rows=%d,cols=%d,ac=%d\n",rows,cols,ac); //wtk_matrix_print(b); //wtk_debug("rows=%d,a=%d\n",rows,ac); for(i=1;i<=rows;++i) { pa=a[i];pm=m[i]; e=pm+cols; for(k=1;k<=ac;++k) { tpb=b[k];pak=pa[k]; //wtk_debug("sf=%d,pb=%d,pa=%d,pm=%d\n",(int)(sizeof(float)),(int)((long)pb%8),(int)((long)pa%8),(int)((long)pm%8)); tpm=pm; while(tpm<e) { if(k==1) { *(++tpm)=pak*(*(++tpb)); }else { *(++tpm)+=pak*(*(++tpb)); } } } } } void wtk_matrix_multi3(wtk_matrix_t *m,wtk_matrix_t *a,wtk_matrix_t *b) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int ac=wtk_matrix_cols(a); int i,j,k; register float *pi,*ai; float t; static int ki=0; //++ki; for(i=1;i<=rows;++i) { pi=m[i];ai=a[i]; for(j=1;j<=cols;++j) { t=0; for(k=1;k<=ac;++k) { t+=ai[k]*b[k][j]; //wtk_debug("%d,%d,%d,%f,%f,%f\n",i,j,k,m[i][j],a[i][k],b[k][j]); if(ki==2) { wtk_debug("v[%d]: %f*%f=%f\n",k,ai[k],b[k][j],t); } } pi[j]=t; if(ki==2) { wtk_debug("t=%f\n",t); exit(0); } } } } void wtk_matrix_add1(wtk_matrix_t *m,wtk_matrix_t *a) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int i,j; for(i=1;i<=rows;++i) { for(j=1;j<=cols;++j) { //wtk_debug("%d,%d,%f,%f\n",i,j,m[i][j],a[i][j]); m[i][j]+=a[i][j]; } } } void wtk_matrix_add(wtk_matrix_t *m,wtk_matrix_t *a) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int i,j; float *pm,*pa; for(i=1;i<=rows;++i) { pm=m[i];pa=a[i]; for(j=1;j<=cols;++j) { //wtk_debug("%d,%d,%f,%f\n",i,j,m[i][j],a[i][j]); pm[j]+=pa[j]; } } } void wtk_matrix_add2(wtk_matrix_t *dst,wtk_matrix_t *src,float f1,float f2) { int rows=wtk_matrix_rows(dst); int cols=wtk_matrix_cols(dst); int i,j; float *pm,*pa; for(i=1;i<=rows;++i) { pm=dst[i];pa=src[i]; for(j=1;j<=cols;++j) { //wtk_debug("%d,%d,%f,%f\n",i,j,m[i][j],a[i][j]); pm[j]=pm[j]*f1+pa[j]*f2; } } } double wtk_matrix_max(wtk_matrix_t *m) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int i,j; double max=-100000.0; for(i=1;i<=rows;++i) { for(j=1;j<=cols;++j) { if(m[i][j]>max) { max=m[i][j]; } } } return max; } double wtk_matrix_min(wtk_matrix_t *m) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int i,j; double min=100000.0; for(i=1;i<=rows;++i) { for(j=1;j<=cols;++j) { if(m[i][j]<min) { min=m[i][j]; } } } return min; } float wtk_matrix_avg(wtk_matrix_t *m) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int i; register float f,v; register float *p,*pe; f=0; for(i=1;i<=rows;++i) { p=m[i]; pe=p+cols; while(p<pe) { v=*(++p); f+=v>=0?v:-v; } } return f/(rows*cols); } double wtk_matrix_max_abs(wtk_matrix_t *m) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int i,j; float max=-100000.0; //float min=10000.0; float *ps,f; for(i=1;i<=rows;++i) { ps=m[i]+1; for(j=1;j<=cols;++j,++ps) { f=*ps; f=f>0?f:-f; if(f>max) { max=f; } } } return max; } void wtk_matrix_add3(wtk_matrix_t *m,wtk_matrix_t *a) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int i; float *pm,*pa; float *p1,*p1e,*p2; for(i=1;i<=rows;++i) { pm=m[i];pa=a[i]; p1=pm; p1e=p1+cols; p2=pa; while(p1<=p1e) { *(++p1)=*(++p2); } } } void wtk_matrix_transpose1(wtk_matrix_t *m,wtk_matrix_t *a) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int i,j; for(i=1;i<=rows;++i) { for(j=1;j<=cols;++j) { m[i][j]=a[j][i]; } } } #define LSMALL (-0.5E10) /* log values < LSMALL are set to LZERO */ void wtk_matrix_scale(wtk_matrix_t *m,float scale) { int r,c; int i,j; r=wtk_matrix_rows(m); c=wtk_matrix_cols(m); for(i=1;i<=r;++i) { for(j=1;j<=c;++j) { if(m[i][j]>LSMALL) { m[i][j]*=scale; } } } } void wtk_matrix_transpose(wtk_matrix_t *dst,wtk_matrix_t *src) { int rows=wtk_matrix_rows(dst); int cols=wtk_matrix_cols(dst); int i,j; float *pm; for(i=1;i<=rows;++i) { pm=dst[i]; for(j=1;j<=cols;++j) { pm[j]=src[j][i]; } } } wtk_matrix_t* wtk_matrix_transpose2(wtk_matrix_t *a) { wtk_matrix_t *b; b=wtk_matrix_new2(wtk_matrix_cols(a),wtk_matrix_rows(a)); wtk_matrix_transpose(b,a); return b; } void wtk_matrix_to_vector(wtk_matrix_t *m,wtk_vector_t *v) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int i,j,k; k=0; for(i=1;i<=rows;++i) { for(j=1;j<=cols;++j) { v[++k]=m[i][j]; } } } void wtk_matrix_print(wtk_matrix_t *m) { int i,rows; int j,cols; //int ki=0; rows=wtk_matrix_rows(m); cols=wtk_matrix_cols(m); for(i=1;i<=rows;++i) { for(j=1;j<=cols;++j) { //if(fabs(m[i][j]-0.003)>0.001) { printf("v[%d][%d]=%.6f\n",i,j,m[i][j]); } } } } void wtk_matrix_print2(wtk_matrix_t *m) { int i,rows; rows=wtk_matrix_rows(m); for(i=1;i<=rows;++i) { wtk_vector_print(m[i]); } } void wtk_double_matrix_cpy(wtk_double_matrix_t *src,wtk_double_matrix_t *dst) { int i,rows; rows=wtk_matrix_rows(src); for(i=1;i<=rows;++i) { wtk_double_vector_cpy(src[i],dst[i]); } } void wtk_matrix_cpy(wtk_matrix_t *src,wtk_matrix_t *dst) { int i,rows; rows=wtk_matrix_rows(src); for(i=1;i<=rows;++i) { wtk_vector_cpy(src[i],dst[i]); } } void wtk_double_matrix_zero(wtk_double_matrix_t *m) { int i,j,nr,nc; nr=wtk_matrix_rows(m); nc=wtk_matrix_cols(m); for(i=1;i<=nr;++i) { for(j=1;j<=nc;++j) { m[i][j]=0; } } } void wtk_matrix_zero(wtk_matrix_t *m) { int i,j,nr,nc; nr=wtk_matrix_rows(m); nc=wtk_matrix_cols(m); for(i=1;i<=nr;++i) { for(j=1;j<=nc;++j) { m[i][j]=0; } } } void wtk_matrix_set_init_value(wtk_matrix_t *m,double f) { int i,j,nr,nc; nr=wtk_matrix_rows(m); nc=wtk_matrix_cols(m); for(i=1;i<=nr;++i) { for(j=1;j<=nc;++j) { m[i][j]=f; } } } /* mat_id -- set A to being closest to identity matrix as possible -- i.e. A[i][j] == 1 if i == j and 0 otherwise */ void wtk_double_matrix_init_identity(wtk_double_matrix_t *A) { int i,size; wtk_double_matrix_zero(A); size=min(wtk_matrix_rows(A),wtk_matrix_cols(A)); for(i=1;i<=size;++i) { A[i][i]=1.0; } } int wtk_matrix_16_bytes(int r,int col) { return sizeof(float*)*(r+1)+16+(sizeof(float)*(col+1)+16)*r; /* int bytes; bytes=sizeof(float*)*(r+1)+16+(sizeof(float)*(col+1)+16)*r; { int i,t; t=s+sizeof(float*)*(r+1); for(i=0;i<r;++i) { t=wtk_round(t+sizeof(float),16); wtk_debug("t=%d/%d\n",t,t%16); if(t%16 !=0 ) { exit(0); } t+=sizeof(float)*col; } wtk_debug("t=%d/%d r=%d/%d bytes=%d %d\n",t,s+bytes,r,col,bytes,t-s); if(s+bytes<t) { exit(0); } } //exit(0); return bytes; */ } void wtk_matrix_16_check() { int i,t,s,r,col,bytes; r=13; col=26; for(s=0;s<16;++s) { bytes=wtk_matrix_16_bytes(r,col); wtk_debug("====== end %d ==========\n",s); t=s+sizeof(float*)*(r+1); for(i=0;i<r;++i) { t=wtk_round(t+sizeof(float),16); wtk_debug("t=%d/%d\n",t,t%16); if(t%16 !=0 ) { exit(0); } t+=sizeof(float)*col; } wtk_debug("t=%d/%d r=%d/%d bytes=%d %d\n",t,s+bytes,r,col,bytes,t-s); if(s+bytes<t) { exit(0); } } exit(0); } wtk_matrix_t* wtk_matrix_new2(int r,int col) { char *p; float **m; int i; int bytes; int col_bytes; bytes=wtk_matrix_16_bytes(r,col); p=wtk_malloc(bytes); m=(float**)p; *((int*)p)=r; p+=sizeof(float*)*(r+1); col_bytes=sizeof(float)*(col+1); for(i=1;i<=r;++i) { //wtk_debug("%p\n",wtk_align_ptr(p+sizeof(float),16)); #ifdef WIN32 p = (char*)wtk_align_ptr(p + sizeof(float), 16) - sizeof(float); #else p = wtk_align_ptr(p + sizeof(float), 16) - sizeof(float); #endif //wtk_debug("p=%p=m=%p\n",p,p+sizeof(float)); *((int*)p)=col; m[i]=(float*)p; //wtk_debug("v[%d]=%p:%p\n",i,m,p); //wtk_debug("v[%d]=%p/%p\n",i,m,&(m[i][1])); /* if(((long)(&(m[1][1])))%16!=0) { wtk_debug("[%ld]=%p\n",((long)(m[1]+1))%16,p); exit(0); }*/ p+=col_bytes; } return m; } wtk_int_matrix_t* wtk_int_matrix_new(int r,int c) { int **i; char *p; int j; int col_bytes; p=wtk_malloc((r+1)*sizeof(int*)+16+((c+1)*sizeof(int)+16)*r); i=(int**)p; *((int*)p)=r; p+=sizeof(int*)*(r+1); col_bytes=sizeof(int)*(c+1); for(j=1;j<=r;++j) { #ifdef WIN32 p = (char*)wtk_align_ptr(p + sizeof(float), 16) - sizeof(float); #else p = wtk_align_ptr(p + sizeof(float), 16) - sizeof(float); #endif *((int*)p)=c; i[j]=(int*)p; p+=col_bytes; } return i; } void wtk_int_matrix_print(wtk_int_matrix_t *m) { int row,col; int i,j; row=wtk_matrix_rows(m); col=wtk_matrix_cols(m); //wtk_debug("row=%d col=%d\n",row,col); for(i=1;i<=row;++i) { for(j=1;j<=col;++j) { printf("v[%d][%d]=%d\n",i,j,m[i][j]); } } } void wtk_matrix_set_random(wtk_matrix_t *m,wtk_matrix_random_f random) { int rows=wtk_matrix_rows(m); int cols=wtk_matrix_cols(m); int i,j; for(i=1;i<=rows;++i) { for(j=1;j<=cols;++j) { m[i][j]=random(); } } // for(j=1;j<=cols;++j) // { // for(i=1;i<=rows;++i) // { // // { // m[i][j]=random(); // } // } // } } void wtk_matrix_sigmoid(wtk_matrix_t *m) { int i,j,nr,nc; float f; nr=wtk_matrix_rows(m); nc=wtk_matrix_cols(m); for(i=1;i<=nr;++i) { for(j=1;j<=nc;++j) { f=m[i][j]; if(f>50){f=50;} if(f<-50){f=-50;} f=-f; m[i][j]=1/(1+FAST_EXP(f)); } } } void wtk_matrix_softmax(wtk_matrix_t *m) { // int i,j,nr,nc; // float f; // double sum=0; // // nr=wtk_matrix_rows(m); // nc=wtk_matrix_cols(m); // for(i=1;i<=nr;++i) // { // for(j=rnn->voc_size+1;j<=nc;++j) // { // f=m[i][j]; // if(f>50){f=50;} // if(f<-50){f=-50;} // f=FAST_EXP(f); // m[i][j]=f; // sum+=f; // } // } // sum=1.0/sum; // for(i=1;i<=nr;++i) // { // for(j=rnn->voc_size+1;j<=nc;++j) // { // m[i][j]*=sum; // } // } } void wtk_vector_mult_matrix_2(wtk_vector_t *dst,wtk_vector_t *src,wtk_matrix_t *m) { int n=wtk_vector_size(src); int n2=wtk_vector_size(dst); int i,j; double f; for(i=1;i<=n2;++i) { f=0; for(j=1;j<=n;++j) { f+=(src[j])*(m[j][i]); } dst[i]=f; } } void wtk_vector_mult_matrix_4(wtk_vector_t *dst,wtk_vector_t *src,wtk_matrix_t *m) { register float f; register float *pdst,*pdst_end; register float *pm; float *psrc,*psrc_end; float *ppdst; int i; wtk_vector_zero(dst); psrc=src+1; psrc_end=psrc+wtk_vector_size(src); ppdst=dst+1; pdst_end=ppdst+wtk_vector_size(dst); i=1; while(psrc<psrc_end) { f=*(psrc++); if(f!=0) { pdst=ppdst; pm=m[i]+1; //wtk_debug("pm=%p\n",pm); while(pdst<pdst_end-8) { *(pdst++)+=f*(*(pm++)); *(pdst++)+=f*(*(pm++)); *(pdst++)+=f*(*(pm++)); *(pdst++)+=f*(*(pm++)); *(pdst++)+=f*(*(pm++)); *(pdst++)+=f*(*(pm++)); *(pdst++)+=f*(*(pm++)); *(pdst++)+=f*(*(pm++)); } while(pdst<pdst_end) { *(pdst++)+=f*(*(pm++)); } } ++i; } } /* #include <xmmintrin.h> void wtk_vector_mult_matrix(wtk_vector_t *dst,wtk_vector_t *src,wtk_matrix_t *m) { float f; float *pdst,*pdst_end; float *pm; float *psrc,*psrc_end; float *ppdst; float **pmx; __m128 mf; float *pdst_end2; wtk_vector_zero(dst); psrc=src+1; psrc_end=psrc+wtk_vector_size(src); ppdst=dst+1; pdst_end=ppdst+wtk_vector_size(dst); pdst_end2=psrc_end-8; pmx=m; while(psrc<psrc_end) { f=*(psrc++); if(f==0) { continue; } pdst=ppdst; pm=(*(++pmx))+1; //wtk_debug("pm=%p\n",pm); mf=_mm_set_ps(f,f,f,f); while(pdst<pdst_end2) { // ma=_mm_load_ps(pm); // mb=_mm_mul_ps(mf,ma); // ma=_mm_load_ps(pdst); // ma=_mm_add_ps(ma,mb); // _mm_store_ps(pdst,ma); *((__m128*)pdst)=_mm_add_ps(_mm_mul_ps(mf,*(__m128*)pm),*(__m128*)pdst); //wtk_debug("%.12f/%.12f/%.12f/%.12f\n",pdst[0],pdst[1],pdst[2],pdst[3]); pdst+=4; pm+=4; *((__m128*)pdst)=_mm_add_ps(_mm_mul_ps(mf,*(__m128*)pm),*(__m128*)pdst); //wtk_debug("%.12f/%.12f/%.12f/%.12f\n",pdst[0],pdst[1],pdst[2],pdst[3]); pdst+=4; pm+=4; } while(pdst<pdst_end) { *(pdst++)+=f*(*(pm++)); } } } */ void wtk_vector_mult_matrix(wtk_vector_t *dst,wtk_vector_t *src,wtk_matrix_t *m) { float f; float *pdst,*pdst_end; float *pm; float *psrc,*psrc_end; float *ppdst; float **pmx; wtk_vector_zero(dst); psrc=src+1; psrc_end=psrc+wtk_vector_size(src); ppdst=dst+1; pdst_end=ppdst+wtk_vector_size(dst); pmx=m; while(psrc<psrc_end) { f=*(psrc++); if(f==0) { continue; } pdst=ppdst; pm=(*(++pmx))+1; while(pdst<pdst_end) { *(pdst++)+=f*(*(pm++)); } } } void wtk_vector_mult_matrix_5(wtk_vector_t *dst,wtk_vector_t *src,wtk_matrix_t *m) { // register float f; // register float *pdst,*pdst_end; // register float *pm; float f; float *pdst,*pdst_end; float *pm; float *psrc,*psrc_end,*pdst_end2; float *ppdst; float **pmx; wtk_vector_zero(dst); psrc=src+1; psrc_end=psrc+wtk_vector_size(src); ppdst=dst+1; pdst_end=ppdst+wtk_vector_size(dst); pdst_end2=pdst_end-8; pmx=m; while(psrc<psrc_end) { f=*(psrc++); pdst=ppdst; pm=(*(++pmx))+1; while(pdst<pdst_end2) { pdst[0]+=f*pm[0]; pdst[1]+=f*pm[1]; pdst[2]+=f*pm[2]; pdst[3]+=f*pm[3]; pdst[4]+=f*pm[4]; pdst[5]+=f*pm[5]; pdst[6]+=f*pm[6]; pdst[7]+=f*pm[7]; pdst+=8; pm+=8; } while(pdst<pdst_end) { *(pdst++)+=f*(*(pm++)); } } } void wtk_vector_mult_matrix_3(wtk_vector_t *dst,wtk_vector_t *src,wtk_matrix_t *m) { register float f; register float *pdst,*pdst_end; register float *pm; float *psrc; float *ppdst; int i; int n; wtk_vector_zero(dst); n=wtk_vector_size(src); ppdst=dst+1; pdst_end=ppdst+wtk_vector_size(dst); for(i=1,psrc=src+1;i<=n;++i) { f=*(psrc++); if(f!=0) { pdst=ppdst; pm=m[i]+1; //wtk_debug("pm=%p\n",pm); while(pdst<pdst_end) { *(pdst++)+=f*(*(pm++)); } } } } /** * [s,e) */ void wtk_vector_mult_matrix2(wtk_vector_t *dst,wtk_vector_t *src,wtk_matrix_t *m,int s,int e) { int n=wtk_vector_size(src); //int n2=wtk_vector_size(dst); int i,j; float f; float *pf; for(i=s;i<e;++i) { f=0; for(j=1,pf=src+1;j<=n;++j) { f+=*(pf++) * m[j][i]; } dst[i]=f; } } /** * |dst * src| *|src*1|=|dst*1| */ void wtk_vector_mult_matrix_rev_2(wtk_vector_t *dst,wtk_vector_t *src,wtk_matrix_t *m,int add) { int n,n2; int i; double f; float *pm; float *psrc; float *ppsrc; float *psrc_end; float *psrc_end2; float *pdst; n=wtk_vector_size(src); n2=wtk_vector_size(dst); if(add) { ppsrc=src+1; psrc_end=ppsrc+n; psrc_end2=psrc_end-8; pdst=dst+1; for(i=1;i<=n2;++i) { f=0; psrc=ppsrc; pm=m[i]+1; while(psrc<psrc_end2) { f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); } while(psrc<psrc_end) { f+=(*(pm++))*(*(psrc++)); } //dst[i]=f; *(pdst++)+=f; } }else { ppsrc=src+1; psrc_end=ppsrc+n; psrc_end2=psrc_end-8; pdst=dst+1; for(i=1;i<=n2;++i) { f=0; psrc=ppsrc; pm=m[i]+1; while(psrc<psrc_end2) { f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); f+=(*(pm++))*(*(psrc++)); } while(psrc<psrc_end) { f+=(*(pm++))*(*(psrc++)); } //dst[i]=f; *(pdst++)=f; } } } void wtk_vector_mult_matrix_rev(wtk_vector_t *dst,wtk_vector_t *src,wtk_matrix_t *m,int add) { int n,n2; int i,j; double f; n=wtk_vector_size(src); n2=wtk_vector_size(dst); for(i=1;i<=n2;++i) { f=0; for(j=1;j<=n;++j) { f+=m[i][j]*src[j]; if(i==1) { //wtk_debug("v[%d/%d]=%.12f/%.12f/%.12f\n",i,j,m[i][j],src[j],f); } } if(i==1) { //wtk_debug("v[%d]=%.12f/%.12f\n",i,dst[i],f); } if(add) { dst[i]+=f; }else { dst[i]=f; } } } void wtk_vector_mult_matrix_rev2(wtk_vector_t *dst,wtk_vector_t *src,wtk_matrix_t *m,int s,int e) { int n2; int i,j; double f; n2=wtk_vector_size(dst); for(i=1;i<=n2;++i) { f=0; for(j=s;j<e;++j) { f+=m[i][j]*src[j]; if(i==1) { //wtk_debug("v[%d/%d]=%.12f/%.12f/%.12f\n",j,i,f,m[i][j],src[j]); } } dst[i]=f; } } <file_sep>/core/.svn/pristine/c6/c61d704599199309a7449cea430066400a51bd78.svn-base #include "wtk_zip.h" #include <math.h> #define WTK_ZIP_END_SYM 256 wtk_zip_t* wtk_zip_new(wtk_zip_cfg_t *cfg) { wtk_zip_t *z; z=(wtk_zip_t*)wtk_malloc(sizeof(wtk_zip_t)); z->cfg=cfg; z->buf=wtk_strbuf_new(1024,1); z->len=pow(2,cfg->bits);//4096;//8192;//4096;//2^12 0/255 z->item=wtk_malloc(sizeof(wtk_zip_item_t)*z->len); wtk_zip_reset(z); return z; } void wtk_zip_delete(wtk_zip_t *z) { wtk_free(z->item); wtk_strbuf_delete(z->buf); wtk_free(z); } void wtk_zip_reset(wtk_zip_t *z) { wtk_zip_item_t *item; int i; z->use=0; z->prev_item=NULL; z->nxt_idx=WTK_ZIP_END_SYM+1; z->cnt=0; z->cache_v=0; z->cache_bit=32; wtk_strbuf_reset(z->buf); for(i=0,item=z->item;i<z->len;++i,++item) { wtk_queue2_init(&(item->next_q)); if(i>255) { item->c=0; item->used=0; item->prev=0; }else { item->c=i; item->used=1; item->prev=0; } } } unsigned int zip_bit_map[]={ 0, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff }; void wtk_zip_write_short(wtk_zip_t *z,unsigned short v) { unsigned int vx; int bits; bits=z->cfg->bits-z->cache_bit; if(bits<0) { //index 32-z->cache_bit z->cache_v+=v<<(32-z->cache_bit);//-bits); z->cache_bit-=z->cfg->bits; }else { //index 32-z->cache_bit //wtk_debug("bits=%d/%d/%d\n",bits,32-z->cache_bit,z->cache_bit); //低位在前 vx=v&zip_bit_map[z->cache_bit]; vx=(vx)<<(32-z->cache_bit); z->cache_v+=vx;//v>>(z->cfg->bits-z->cache_bit); //wtk_debug("v[%d]=[%#x]\n",z->cnt,z->cache_v); ++z->cnt; wtk_strbuf_push(z->buf,(char*)&(z->cache_v),4); //wtk_debug("bits=%d\n",bits); if(bits>0) { //wtk_debug("vx=%#x\n",vx); v=v>>z->cache_bit; //v-=(v>>bits)<<bits; z->cache_v= v;// <<(32-bits); z->cache_bit=32-bits; }else { z->cache_v=0; z->cache_bit=32; } } // if((32-z->cache_bit+z->buf->pos*8) != z->cnt*z->cfg->bits) // { // wtk_debug("found bug %d %d %d %d/%d\n",z->cnt,z->buf->pos,z->cache_bit,z->cnt*z->cfg->bits,32-z->cache_bit+z->buf->pos*8); // exit(0); // } } void wtk_zip_feed_end(wtk_zip_t *z) { unsigned short v; if(z->prev_item) { v=z->prev_item-z->item; wtk_zip_write_short(z,v); } wtk_zip_write_short(z,WTK_ZIP_END_SYM); //wtk_debug("cb=%d %d\n",z->cache_bit,z->cache_v); if(z->cache_bit>0) { //wtk_debug("v[%d]=[%#x]\n",z->cnt,z->cache_v); ++z->cnt; wtk_strbuf_push(z->buf,(char*)&(z->cache_v),4); } } void wtk_zip_feed(wtk_zip_t *z,char *data,int len) { wtk_zip_item_t *item; wtk_queue_node_t *qn; unsigned char *s,*e,c; int b; unsigned short v; static int kx=0; if(len<=0){return;} //wtk_debug("%.*s\n",len,data); s=(unsigned char*)data;e=s+len; if(!z->use) { c=*(s++); //wtk_debug("%#x\n",c); z->prev_item=z->item+c; z->use=1; ++kx; } while(s<e) { ++kx; c=*(s++); //wtk_debug("%c\n",c); b=0; if(z->prev_item) { for(qn=z->prev_item->next_q.pop;qn;qn=qn->next) { item=data_offset2(qn,wtk_zip_item_t,q_n); if(item->c==c) { z->prev_item=item; b=1; break; } } } if(b==0) { if((z->nxt_idx>=z->len)) { v=z->prev_item-z->item; wtk_zip_write_short(z,v); //wtk_debug("found bug %d/%d\n",v,len); //exit(0); }else { v=z->prev_item-z->item; //wtk_debug("v=%d / %d\n",v,z->nxt_idx); wtk_zip_write_short(z,v); v=z->nxt_idx++; item=z->item+v; item->used=1; item->c=c; item->prev=z->prev_item-z->item; wtk_queue2_push(&(z->prev_item->next_q),&(item->q_n)); } z->prev_item=z->item+c; } //exit(0); } } int wtk_zip_write_file(wtk_zip_t *z,char *fn) { wtk_zip_item_t *item; int ret=-1; FILE *f; int i; unsigned char c; unsigned short v; f=fopen(fn,"wb"); if(!f){goto end;} ret=fwrite("WZF1",4,1,f); if(ret!=1){ret=-1;goto end;} c=z->cfg->bits; ret=fwrite(&c,1,1,f); if(ret!=1){ret=-1;goto end;} v=z->nxt_idx-WTK_ZIP_END_SYM-1; ret=fwrite(&(v),1,2,f); if(ret!=2){ret=-1;goto end;} //wtk_debug("nxt=%d\n",z->nxt_idx); for(i=WTK_ZIP_END_SYM+1,item=z->item+i;i<z->nxt_idx;++i,++item) { ret=fwrite(&(item->prev),1,2,f); if(ret!=2){goto end;} ret=fwrite(&(item->c),1,1,f); if(ret!=1){goto end;} } ret=fwrite(z->buf->data,1,z->buf->pos,f); if(ret!=z->buf->pos){ret=-1;goto end;} end: if(f) { fclose(f); } return ret; } int wtk_zip_file(wtk_zip_t *z,char *ifn,char *ofn) { #define BUF_SIZE 4096 char buf[BUF_SIZE]; int ret=-1; FILE *f; f=fopen(ifn,"rb"); if(!f){goto end;} while(1) { ret=fread(buf,1,BUF_SIZE,f); if(ret<=0){goto end;} wtk_zip_feed(z,buf,ret); if(ret<BUF_SIZE) { break; } } wtk_zip_feed_end(z); wtk_zip_write_file(z,ofn); ret=0; end: if(f) { fclose(f); } return ret; } <file_sep>/os/.svn/pristine/3f/3fd45db71e0e034152b9799e9d8bcad2e094fd75.svn-base #ifndef WTK_OS_DTP_WTK_DTP_CFG_H_ #define WTK_OS_DTP_WTK_DTP_CFG_H_ #include "wtk/core/cfg/wtk_local_cfg.h" #include "wtk/os/wtk_cpu.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_dtp_cfg wtk_dtp_cfg_t; struct wtk_dtp_cfg { int min; int max; int timeout; }; int wtk_dtp_cfg_init(wtk_dtp_cfg_t *cfg); int wtk_dtp_cfg_clean(wtk_dtp_cfg_t *cfg); int wtk_dtp_cfg_update_local(wtk_dtp_cfg_t *cfg,wtk_local_cfg_t *lc); int wtk_dtp_cfg_update(wtk_dtp_cfg_t *cfg); #ifdef __cplusplus }; #endif #endif <file_sep>/core/rbin/wtk_rbin2.h #ifndef WTK_CORE_RBIN_WTK_RBIN2_H_ #define WTK_CORE_RBIN_WTK_RBIN2_H_ #include "wtk/core/rbin/wtk_rbin.h" #include "wtk/core/wtk_heap.h" #include "wtk/core/wtk_os.h" #include "wtk/core/cfg/wtk_source.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_rbin2 wtk_rbin2_t; #define wtk_rbin2_get_s(rb,name) wtk_rbin2_get(rb,name,sizeof(name)-1) #define wtk_rbin2_get2_s(rb,name) wtk_rbin2_get2(rb,name,sizeof(name)-1) typedef struct { wtk_queue_node_t q_n; wtk_rbin2_t *rb; wtk_string_t *fn; //file name; wtk_string_t *data; int pos; //file pos; int len; //data len unsigned char *s; unsigned char *e; int seek_pos; //file pos; int buf_pos; //buf pos; unsigned reverse:1; }wtk_rbin2_item_t; struct wtk_rbin2 { wtk_queue_t list; wtk_heap_t *heap; FILE *f; char *fn; wtk_strbuf_t *buf; int version; }; wtk_rbin2_t* wtk_rbin2_new(); void wtk_rbin2_delete(wtk_rbin2_t *rb); //-------------------- write -------------------------------- int wtk_rbin2_add(wtk_rbin2_t *rb,wtk_string_t *name,char *realname); void wtk_rbin2_add2(wtk_rbin2_t *rb,wtk_string_t *name,char *data,int len); int wtk_rbin2_write(wtk_rbin2_t *rb,char *fn); //------------------ read ------------------------- int wtk_rbin2_read(wtk_rbin2_t *rb,char *fn); int wtk_rbin2_read2(wtk_rbin2_t *rb,char *fn,unsigned int seek_pos); int wtk_rbin2_extract(wtk_rbin2_t *rb,char *dn); FILE* wtk_rbin2_get_file(wtk_rbin2_t *rb,char *name); wtk_rbin2_item_t* wtk_rbin2_get(wtk_rbin2_t *rb,char *name,int len); wtk_rbin2_item_t* wtk_rbin2_get2(wtk_rbin2_t *rb,char *name,int len); wtk_rbin2_item_t* wtk_rbin2_get3(wtk_rbin2_t *rb,char *name,int len,int use_heap); int wtk_rbin2_load_item(wtk_rbin2_t *rb,wtk_rbin2_item_t *item,int use_heap); void wtk_rbin2_item_clean(wtk_rbin2_item_t *item); void wtk_rbin2_print(wtk_rbin2_t *rb); int wtk_rbin2_load_file(wtk_rbin2_t *rb,void *data,wtk_source_load_handler_t loader,char *fn); void wtk_source_init_rbin2(wtk_source_t* s,wtk_rbin2_item_t *i); void wtk_source_init_rbin2_x(wtk_source_t* s,wtk_rbin2_item_t *i); int wtk_rbin2_file_exist(wtk_rbin2_t *rb,char *name,int len); #ifdef __cplusplus }; #endif #endif <file_sep>/os/.svn/pristine/49/49178db00f14d6aa9c5c44a44f63b0c031aae2b9.svn-base #ifndef WTK_OS_DAEMON_WTK_DAEMON_H_ #define WTK_OS_DAEMON_WTK_DAEMON_H_ #include "wtk/os/wtk_proc.h" #include "wtk/os/wtk_pid.h" #include "wtk/os/wtk_sem.h" #include "wtk/os/wtk_log.h" #include "wtk_daemon_cfg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_daemon wtk_daemon_t; typedef int(*wtk_daemon_start_f)(void *usr_data); typedef int(*wtk_daemon_stop_f)(void *usr_data); typedef int(*wtk_daemon_join_f)(void *usr_data); #define wtk_daemon_new_type(cfg,log,usr_data,type) wtk_daemon_new(cfg,log,usr_data,\ (wtk_daemon_start_f)CAT(type,_start),\ (wtk_daemon_stop_f)CAT(type,_stop),\ (wtk_daemon_join_f)CAT(type,_join)) struct wtk_daemon { wtk_daemon_cfg_t *cfg; wtk_log_t *log; wtk_sem_t stop_sem; pid_t master_pid; pid_t worker_pid; wtk_daemon_start_f start; wtk_daemon_stop_f stop; wtk_daemon_join_f join; void *usr_data; volatile unsigned run:1; }; /** * @brief: * start: usually start server thread route; * stop: send stop hint to server thread route; * join: wait server thread route to be end; */ wtk_daemon_t* wtk_daemon_new(wtk_daemon_cfg_t *cfg, wtk_log_t *log, void *usr_data, wtk_daemon_start_f start, wtk_daemon_stop_f stop, wtk_daemon_join_f join); void wtk_daemon_delete(wtk_daemon_t *d); int wtk_daemon_run(wtk_daemon_t *d); //==================== Test Section ================== int wtk_daemon_test(int argc,char **argv); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/af/afd51bb0374c3c8f3401920e1367774c9e44ec9f.svn-base #ifndef WTK_CORE_WTK_FRING #define WTK_CORE_WTK_FRING #include "wtk/core/wtk_type.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_fring wtk_fring_t; #define wtk_fring_at(r,i) ((r)->f[((r)->first+(i))%((r)->nslot)]) struct wtk_fring { float *f; int first; int used; int nslot; float tot_v; }; wtk_fring_t* wtk_fring_new(int n); void wtk_fring_delete(wtk_fring_t *r); void wtk_fring_reset(wtk_fring_t *r); void wtk_fring_push(wtk_fring_t *r,float f); float wtk_fring_pop(wtk_fring_t* r); void wtk_fring_pop2(wtk_fring_t *r,int n); void wtk_fring_pop3(wtk_fring_t *r,int n); void wtk_fring_print(wtk_fring_t *r); #ifdef __cplusplus }; #endif #endif <file_sep>/core/math/wtk_vector.h #ifndef WTK_MATH_WTK_VECTOR_H_ #define WTK_MATH_WTK_VECTOR_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_heap.h" #include "wtk/core/wtk_alloc.h" #ifdef __cplusplus extern "C" { #endif /** * v=[ 0, 1 , 2, 3 , ... ,n ] * size v[0] v[1] v[2] ... v[n] */ //#define wtk_vector_type_bytes(size,type) ((size+1)*sizeof(type)) #define wtk_vector_type_bytes(size,type) (wtk_round((size+1)*sizeof(type),8)) #define wtk_vector_bytes(size) wtk_vector_type_bytes(size,float) #define wtk_double_vector_bytes(size) wtk_vector_type_bytes(size,double) #define wtk_svector_bytes(size) ((size+1)*sizeof(float)+2*sizeof(void*)) #define wtk_int_vector_bytes(size) wtk_vector_type_bytes(size,int) #define wtk_vector_size(v) (*(int*)(v)) #define wtk_short_vector_size(v) (*(short*)v) #define wtk_vector_init(v,size) (*((int*)v)=size) //((int)(v[0])) #define wtk_type_vector(type) CAT(CAT(wtk_,type),_vector_t) #define wtk_type_vector_new_dec(t) wtk_type_vector(t)* CAT(CAT(wtk_,t),_vector_new)(int size) #define wtk_type_vector_new_imp(t) \ wtk_type_vector_new_dec(t) \ { \ wtk_type_vector(t)* v; \ \ v=(wtk_type_vector(t)*)wtk_malloc(wtk_vector_type_bytes(size,t)); \ if(sizeof(t)>=sizeof(int)) \ { \ *((int*)v)=size; \ }\ {\ *((short*)v)=size;\ }\ return v; \ } #define wtk_type_vector_newh_dec(t) wtk_type_vector(t)* CAT(CAT(wtk_,t),_vector_newh)(wtk_heap_t *h,int size) #define wtk_type_vector_newh_imp(t) \ wtk_type_vector_newh_dec(t) \ { \ wtk_type_vector(t)* v; \ \ v=(wtk_type_vector(t)*)wtk_heap_malloc(h,wtk_vector_type_bytes(size,t)); \ if(sizeof(t)>=sizeof(int)) \ { \ *((int*)v)=size; \ }\ {\ *((short*)v)=size;\ }\ return v; \ } #define wtk_vector_do_p(v,pre,after) \ { \ wtk_vector *s,*e;\ s=v;e=v+wtk_vector_size(v);\ while((e-s)>=4)\ {\ pre *(++s) after;\ pre *(++s) after;\ pre *(++s) after;\ pre *(++s) after;\ }\ while(s<e)\ {\ pre *(++s) after; \ }\ } #define wtk_vector_do_i(v,pre,after) \ { \ int i,size; \ i=1;size=wtk_vector_size(v);\ for(i=1;i<=(size-4);)\ {\ pre v[i] after;++i;\ pre v[i] after;++i;\ pre v[i] after;++i;\ pre v[i] after;++i;\ }\ for(;i<=size;++i)\ {\ pre v[i] after;\ }\ } #define wtk_vector_do_i_step(v,pre,after,step) \ { \ int i,size; \ i=1;size=wtk_vector_size(v);\ for(i=1;i<=(size-step);)\ {\ pre v[i] after;++i;\ pre v[i] after;++i;\ pre v[i] after;++i;\ pre v[i] after;++i;\ }\ for(;i<=size;++i)\ {\ pre v[i] after;\ }\ } #define wtk_vector_delete(v) wtk_free(v) typedef float wtk_vector; typedef double wtk_double_vector_t; typedef int wtk_int_vector_t; typedef wtk_vector wtk_vector_t; typedef short wtk_short_vector_t; /* Shared versions */ typedef wtk_vector_t wtk_svector_t; /* shared vector[1..size] */ wtk_type_vector_new_dec(double); wtk_type_vector_new_dec(short); wtk_type_vector_newh_dec(short); wtk_type_vector_newh_dec(double); wtk_vector_t* wtk_vector_new_h(wtk_heap_t *heap,int size); wtk_int_vector_t* wtk_int_vector_new_h(wtk_heap_t *heap,int size); wtk_vector_t* wtk_vector_new(int size); int wtk_vector_bytes2(wtk_vector_t *v); wtk_vector_t *wtk_vector_dup(wtk_vector_t *src); void wtk_vector_cpy(wtk_vector_t *src,wtk_vector_t *dst); void wtk_double_vector_cpy(wtk_double_vector_t *src,wtk_double_vector_t *dst); void wtk_vector_zero(wtk_vector_t *v); void wtk_double_vector_zero(wtk_double_vector_t *v); float wtk_vector_sum(wtk_vector_t* v); void wtk_vector_print(wtk_vector_t* v); void wtk_short_vector_print(wtk_short_vector_t* v); wtk_svector_t* wtk_svector_newh(wtk_heap_t* heap, int size); wtk_svector_t* wtk_svector_dup(wtk_heap_t* heap, wtk_svector_t *src); void wtk_set_use(void **m,int n); int wtk_get_use(void **m); void wtk_inc_use(void **m); void wtk_dec_use(void **m); void wtk_set_hook(void **m,void *h); void* wtk_get_hook(void **m); float wtk_math_max(float *a,int len); float wtk_vector_max_abs(wtk_vector_t *v); void wtk_vector_fix_scale(wtk_vector_t *v,float scale); void wtk_vector_set_init_value(wtk_vector_t *v,float f); wtk_vector_t *wtk_vector_new2(int size); void wtk_vector_delete2(wtk_vector_t *v); #ifdef __cplusplus }; #endif #endif <file_sep>/core/fft/wtk_rfft.c #include "wtk_rfft.h" #include "math.h" #ifdef PI #undef PI #endif #define PI 3.1415926535897932384626433832795 #define SQRT2 1.41421356237309514547462185873883 int wtk_rfft_next_pow (long x) { --x; int p = 0; while ((x & ~0xFFFFL) != 0) { p += 16; x >>= 16; } while ((x & ~0xFL) != 0) { p += 4; x >>= 4; } while (x > 0) { ++p; x >>= 1; } return (p); } void wtk_rfft_init_br_lut(wtk_rfft_t *f) { int len=1<<f->nbr_bits; int i,bit,idx; f->br_lut=(int*)wtk_malloc(len*sizeof(int)); f->br_lut[0]=0; idx=0; for(i=1;i<len;++i) { bit=len>>1; while (((idx ^= bit) & bit) == 0) { bit >>= 1; } f->br_lut[i] = idx; } } int wtk_rfft_get_trigo_level_index(int level) { return ((1L << (level - 1)) - 4); } void wtk_rfft_init_trigo_lut(wtk_rfft_t *fft) { int len; int level,i; float *fp; double f; if(fft->nbr_bits<=3) { return; } len=(1<<(fft->nbr_bits-1))-4; //wtk_debug("len=%d\n",len); fft->trigo_lut=(float*)wtk_malloc(len*sizeof(float)); //wtk_debug("fp=%p/%p\n",fft->trigo_lut,fft->trigo_lut+len); for(level=3;level<fft->nbr_bits;++level) { len=1L << (level - 1); i=wtk_rfft_get_trigo_level_index(level); fp=fft->trigo_lut+i; //wtk_debug("i=%d fp=%p\n",i,fp); f=PI/(len<<1); for(i=0;i<len;++i) { fp[i]=cos(i*f); } } } void wtk_oscsincos_init(wtk_oscsincos_t *t) { t->pos_cos=1; t->pos_sin=0; t->step_cos=1; t->step_sin=0; } void wtk_oscsincos_set_step(wtk_oscsincos_t *t,double angle_rad) { t->step_cos=cos(angle_rad); t->step_sin=sin(angle_rad); } void wtk_oscsincos_step(wtk_oscsincos_t *t) { float c,s; c=t->pos_cos; s=t->pos_sin; t->pos_cos=c*t->step_cos-s*t->step_sin; t->pos_sin=c*t->step_sin+s*t->step_cos; } void wtk_oscsincos_clean_buffers(wtk_oscsincos_t *t) { t->pos_cos=1; t->pos_sin=0; } void wtk_rfft_init_trigo_osc(wtk_rfft_t *f) { int nbr_osc=f->nbr_bits-TRIGO_BD_LIMIT; int i; wtk_oscsincos_t *t; int len; double mul; if(nbr_osc<=0){return;} f->trigo_osc=(wtk_oscsincos_t*)wtk_malloc(nbr_osc *sizeof(wtk_oscsincos_t)); for(i=0;i<nbr_osc;++i) { t=f->trigo_osc+i; wtk_oscsincos_init(t); len = 1L << (TRIGO_BD_LIMIT + i); mul = (0.5 * PI) / len; wtk_oscsincos_set_step(t,mul); } } wtk_rfft_t* wtk_rfft_new(int len) { wtk_rfft_t *f; f=(wtk_rfft_t*)wtk_malloc(sizeof(wtk_rfft_t)); f->win=pow(2.0,(int)ceil(log(len)/log(2.0))); //f->win=pow(2.0,(int)(log(len)/log(2.0)+0.5)); len=f->len=f->win*2; f->nbr_bits=wtk_rfft_next_pow(len); //wtk_debug("win=%d/%d bits=%d\n",f->win,f->len,f->nbr_bits); f->br_lut=NULL; f->trigo_lut=NULL; f->buffer=(float*)wtk_malloc(sizeof(float)*len); f->trigo_osc=NULL; wtk_rfft_init_br_lut(f); wtk_rfft_init_trigo_lut(f); wtk_rfft_init_trigo_osc(f); return f; } void wtk_rfft_delete(wtk_rfft_t *rf) { if(rf->trigo_osc) { wtk_free(rf->trigo_osc); } if(rf->trigo_lut) { wtk_free(rf->trigo_lut); } if(rf->br_lut) { wtk_free(rf->br_lut); } wtk_free(rf->buffer); wtk_free(rf); } void wtk_rfft_compute_direct_pass_1_2(wtk_rfft_t *r,float *df,float *x) { int *bit_rev_lut_ptr=r->br_lut; int coef_index=0; int rev_index_0,rev_index_1,rev_index_2,rev_index_3; float *df2; float sf_0,sf_2; do { rev_index_0 = bit_rev_lut_ptr [coef_index]; rev_index_1 = bit_rev_lut_ptr [coef_index + 1]; rev_index_2 = bit_rev_lut_ptr [coef_index + 2]; rev_index_3 = bit_rev_lut_ptr [coef_index + 3]; df2 = df + coef_index; df2 [1] = x [rev_index_0] - x [rev_index_1]; df2 [3] = x [rev_index_2] - x [rev_index_3]; sf_0 = x [rev_index_0] + x [rev_index_1]; sf_2 = x [rev_index_2] + x [rev_index_3]; df2 [0] = sf_0 + sf_2; df2 [2] = sf_0 - sf_2; coef_index += 4; }while(coef_index<r->len); } void wtk_rfft_compute_direct_pass_3(wtk_rfft_t *r,float *df,float *sf) { double sqrt2_2=SQRT2 * 0.5; long coef_index = 0; float v; do { df [coef_index] = sf [coef_index] + sf [coef_index + 4]; df [coef_index + 4] = sf [coef_index] - sf [coef_index + 4]; df [coef_index + 2] = sf [coef_index + 2]; df [coef_index + 6] = sf [coef_index + 6]; v = (sf [coef_index + 5] - sf [coef_index + 7]) * sqrt2_2; df [coef_index + 1] = sf [coef_index + 1] + v; df [coef_index + 3] = sf [coef_index + 1] - v; v = (sf [coef_index + 5] + sf [coef_index + 7]) * sqrt2_2; df [coef_index + 5] = v + sf [coef_index + 3]; df [coef_index + 7] = v - sf [coef_index + 3]; coef_index += 8; } while (coef_index < r->len); } void wtk_rfft_compute_direct_pass_n_lut2(wtk_rfft_t *r,float *df,float *sf,int pass) { int nbr_coef = 1 << pass; int h_nbr_coef = nbr_coef >> 1; int d_nbr_coef = nbr_coef << 1; //int coef_index = 0; float *cos_ptr=r->trigo_lut+wtk_rfft_get_trigo_level_index(pass); float *sf1r,*sf2r,*dfr,*dfi; float *sf1i,*sf2i; float c,s,v1,v2,v3; int i; //int ki=0; float *sf1e; sf1r=sf; sf1e=sf1r+r->len; dfr=df; do { //++ki; sf2r=sf1r+nbr_coef; dfi=dfr+nbr_coef; // Extreme coefficients are always real dfr[0]=sf1r[0]+sf2r[0]; dfr[h_nbr_coef]=sf1r[h_nbr_coef]; dfi[0]=sf1r[0]-sf2r[0]; dfi[h_nbr_coef]=sf2r[h_nbr_coef]; sf1i = sf1r + h_nbr_coef; sf2i = sf1i + nbr_coef; for (i = 1; i < h_nbr_coef; ++ i) { c = cos_ptr [i]; // cos (i*PI/nbr_coef); s = cos_ptr [h_nbr_coef - i]; // sin (i*PI/nbr_coef); v1 = sf2r [i] * c - sf2i [i] * s; v2 = sf2r [i] * s + sf2i [i] * c; v3=sf1r[i]; dfr [i] =v3+v1;// sf1r [i] + v1; dfi [-i] =v3-v1;// sf1r [i] - v1; // dfr [nbr_coef - i] = v3=sf1i[i]; dfi [i] =v2+v3;// v2 + sf1i [i]; dfi [nbr_coef - i] =v2-v3;// v2 - sf1i [i]; } sf1r+=d_nbr_coef; dfr+=d_nbr_coef; }while(sf1r<sf1e); //wtk_debug("ki=%d\n",ki); //print_float(df,256); //exit(0); } void wtk_rfft_compute_direct_pass_n_lut(wtk_rfft_t *r,float *df,float *sf,int pass) { int nbr_coef = 1 << pass; int h_nbr_coef = nbr_coef >> 1; int d_nbr_coef = nbr_coef << 1; int coef_index = 0; float *cos_ptr=r->trigo_lut+wtk_rfft_get_trigo_level_index(pass); register float *sf1r,*sf2r,*dfr,*dfi; register float *sf1i,*sf2i; register float c,s,v1;//,v2; int i,j,k; do { sf1r = sf + coef_index; sf2r = sf1r + nbr_coef; dfr = df + coef_index; dfi = dfr + nbr_coef; // Extreme coefficients are always real dfr [0] = sf1r [0] + sf2r [0]; dfr [h_nbr_coef] = sf1r [h_nbr_coef]; dfi [0] = sf1r [0] - sf2r [0]; // dfr [nbr_coef] = dfi [h_nbr_coef] = sf2r [h_nbr_coef]; // Others are conjugate complex numbers sf1i = sf1r + h_nbr_coef; sf2i = sf1i + nbr_coef; for (i = 1,j=h_nbr_coef-i,k=nbr_coef - i; i < h_nbr_coef; ++i,--j,--k) { c = cos_ptr [i]; // cos (i*PI/nbr_coef); s = cos_ptr [j]; // sin (i*PI/nbr_coef); v1 = sf2r [i] * c - sf2i [i] * s; dfr [i] = sf1r [i] + v1; dfi [-i] = sf1r [i] - v1; // dfr [nbr_coef - i] = v1 = sf2r [i] * s + sf2i [i] * c; dfi [i] = v1 + sf1i [i]; dfi [k] = v1 - sf1i [i]; } coef_index += d_nbr_coef; //wtk_debug("d_nbr_coef=%d h_nbr_coef=%d nbr_coef=%d\n",d_nbr_coef,h_nbr_coef,nbr_coef); //exit(0); } while (coef_index < r->len); } void wtk_rfft_compute_direct_pass_n_lut3(wtk_rfft_t *r,float *df,float *sf,int pass) { int nbr_coef = 1 << pass; int h_nbr_coef = nbr_coef >> 1; int d_nbr_coef = nbr_coef << 1; int coef_index = 0; float *cos_ptr=r->trigo_lut+wtk_rfft_get_trigo_level_index(pass); float *sf1r,*sf2r,*dfr,*dfi; float *sf1i,*sf2i; float c,s,v; int i; do { sf1r = sf + coef_index; sf2r = sf1r + nbr_coef; dfr = df + coef_index; dfi = dfr + nbr_coef; // Extreme coefficients are always real dfr [0] = sf1r [0] + sf2r [0]; dfr [h_nbr_coef] = sf1r [h_nbr_coef]; dfi [0] = sf1r [0] - sf2r [0]; // dfr [nbr_coef] = dfi [h_nbr_coef] = sf2r [h_nbr_coef]; // Others are conjugate complex numbers sf1i = sf1r + h_nbr_coef; sf2i = sf1i + nbr_coef; for (i = 1; i < h_nbr_coef; ++ i) { c = cos_ptr [i]; // cos (i*PI/nbr_coef); s = cos_ptr [h_nbr_coef - i]; // sin (i*PI/nbr_coef); v = sf2r [i] * c - sf2i [i] * s; dfr [i] = sf1r [i] + v; dfi [-i] = sf1r [i] - v; // dfr [nbr_coef - i] = v = sf2r [i] * s + sf2i [i] * c; dfi [i] = v + sf1i [i]; dfi [nbr_coef - i] = v - sf1i [i]; } coef_index += d_nbr_coef; //wtk_debug("d_nbr_coef=%d h_nbr_coef=%d nbr_coef=%d\n",d_nbr_coef,h_nbr_coef,nbr_coef); //exit(0); } while (coef_index < r->len); } void wtk_rfft_compute_direct_pass_n_osc(wtk_rfft_t *r,float *df,float *sf,int pass) { const long nbr_coef = 1 << pass; const long h_nbr_coef = nbr_coef >> 1; const long d_nbr_coef = nbr_coef << 1; long coef_index = 0; wtk_oscsincos_t *osc=r->trigo_osc+pass - (TRIGO_BD_LIMIT + 1); float *sf1r,*sf2r,*dfr,*dfi; float *sf1i,*sf2i; float c,s,v; int i; do { sf1r = sf + coef_index; sf2r = sf1r + nbr_coef; dfr = df + coef_index; dfi = dfr + nbr_coef; wtk_oscsincos_clean_buffers(osc); // Extreme coefficients are always real dfr [0] = sf1r [0] + sf2r [0]; dfi [0] = sf1r [0] - sf2r [0]; // dfr [nbr_coef] = dfr [h_nbr_coef] = sf1r [h_nbr_coef]; dfi [h_nbr_coef] = sf2r [h_nbr_coef]; // Others are conjugate complex numbers sf1i = sf1r + h_nbr_coef; sf2i = sf1i + nbr_coef; for (i = 1; i < h_nbr_coef; ++ i) { wtk_oscsincos_step(osc); c=osc->pos_cos; s=osc->pos_sin; v = sf2r [i] * c - sf2i [i] * s; dfr [i] = sf1r [i] + v; dfi [-i] = sf1r [i] - v; // dfr [nbr_coef - i] = v = sf2r [i] * s + sf2i [i] * c; dfi [i] = v + sf1i [i]; dfi [nbr_coef - i] = v - sf1i [i]; } coef_index += d_nbr_coef; } while (coef_index < r->len); } void wtk_rfft_compute_direct_pass_n(wtk_rfft_t *rfft,float *df,float *sf,int pass) { //wtk_debug("i=%d/%d\n",pass,TRIGO_BD_LIMIT); if (pass <= TRIGO_BD_LIMIT) { wtk_rfft_compute_direct_pass_n_lut (rfft,df, sf, pass); } else { //wtk_debug("...................\n"); wtk_rfft_compute_direct_pass_n_osc (rfft,df, sf, pass); } } void wtk_rfft_compute_fft_general(wtk_rfft_t *rfft,float *f,float *x) { float *sf,*df; int i; float *tf; if((rfft->nbr_bits&1)!=0) { //wtk_debug("-------------- 1 -----------\n"); df=rfft->buffer; sf=f; }else { //wtk_debug("-------------- 2 -----------\n"); df=f; sf=rfft->buffer; } //exit(0); wtk_rfft_compute_direct_pass_1_2(rfft,df,x); //wtk_debug("%f/%f/%f\n",df[0],df[16],df[31]); wtk_rfft_compute_direct_pass_3(rfft,sf,df); //wtk_debug("%f/%f/%f\n",sf[0],sf[16],sf[31]); for(i=3;i<rfft->nbr_bits;++i) { wtk_rfft_compute_direct_pass_n(rfft,df,sf,i); //wtk_debug("v[%d]=%f/%f/%f\n",i,f[0],f[rfft->len/2],f[rfft->len-1]); // if(i==4) // { // exit(0); // } tf=df; df=sf; sf=tf; } //exit(0); } /* ============================================================================== Name: do_fft Description: Compute the FFT of the array. Input parameters: - x: pointer on the source array (time). Output parameters: - f: pointer on the destination array (frequencies). f [0...length(x)/2] = real values, f [length(x)/2+1...length(x)-1] = negative imaginary values of coefficents 1...length(x)/2-1. Throws: Nothing for comples value(win): 0: v[0] 0 1: v[1] v[1+win] 2: v[2] v[2+win] .. win: v[win] 0 win+1 v[win-1] -v[win-1] ============================================================================== */ void wtk_rfft_process_fft(wtk_rfft_t *rf,float *f,float *x) { float b_0,b_2; //wtk_debug("nbits=%d len=%d\n",rf->nbr_bits,rf->len); if(rf->nbr_bits>2) { wtk_rfft_compute_fft_general(rf,f,x); }else if(rf->nbr_bits==2) { f [1] = x [0] - x [2]; f [3] = x [1] - x [3]; b_0 = x [0] + x [2]; b_2 = x [1] + x [3]; f [0] = b_0 + b_2; f [2] = b_0 - b_2; }else if(rf->nbr_bits==1) { f [0] = x [0] + x [1]; f [1] = x [0] - x [1]; }else { f[0]=x[0]; } } void wtk_rfft_compute_inverse_pass_n_lut(wtk_rfft_t *rfft,float *df,float *sf,int pass) { const long nbr_coef = 1 << pass; const long h_nbr_coef = nbr_coef >> 1; const long d_nbr_coef = nbr_coef << 1; long coef_index = 0; float *cos_ptr=rfft->trigo_lut+wtk_rfft_get_trigo_level_index(pass); float *sfr,*sfi,*df1r,*df2r; float *df1i,*df2i; float c,s,vr,vi; int i; do { sfr = sf + coef_index; sfi = sfr + nbr_coef; df1r = df + coef_index; df2r = df1r + nbr_coef; // Extreme coefficients are always real df1r [0] = sfr [0] + sfi [0]; // + sfr [nbr_coef] df2r [0] = sfr [0] - sfi [0]; // - sfr [nbr_coef] df1r [h_nbr_coef] = sfr [h_nbr_coef] * 2; df2r [h_nbr_coef] = sfi [h_nbr_coef] * 2; // Others are conjugate complex numbers df1i = df1r + h_nbr_coef; df2i = df1i + nbr_coef; for (i = 1; i < h_nbr_coef; ++ i) { df1r [i] = sfr [i] + sfi [-i]; // + sfr [nbr_coef - i] df1i [i] = sfi [i] - sfi [nbr_coef - i]; c = cos_ptr [i]; // cos (i*PI/nbr_coef); s = cos_ptr [h_nbr_coef - i]; // sin (i*PI/nbr_coef); vr = sfr [i] - sfi [-i]; // - sfr [nbr_coef - i] vi = sfi [i] + sfi [nbr_coef - i]; df2r [i] = vr * c + vi * s; df2i [i] = vi * c - vr * s; } coef_index += d_nbr_coef; } while (coef_index < rfft->len); } void wtk_rfft_compute_inverse_pass_n_osc(wtk_rfft_t *rfft,float *df,float *sf,int pass) { int nbr_coef = 1 << pass; int h_nbr_coef = nbr_coef >> 1; int d_nbr_coef = nbr_coef << 1; int coef_index = 0; wtk_oscsincos_t *osc=rfft->trigo_osc+pass - (TRIGO_BD_LIMIT + 1); float *sfr,*sfi,*df1r,*df2r; float *df1i,*df2i; float c,s,vr,vi; int i; do { sfr = sf + coef_index; sfi = sfr + nbr_coef; df1r = df + coef_index; df2r = df1r + nbr_coef; wtk_oscsincos_clean_buffers(osc); // Extreme coefficients are always real df1r [0] = sfr [0] + sfi [0]; // + sfr [nbr_coef] df2r [0] = sfr [0] - sfi [0]; // - sfr [nbr_coef] df1r [h_nbr_coef] = sfr [h_nbr_coef] * 2; df2r [h_nbr_coef] = sfi [h_nbr_coef] * 2; // Others are conjugate complex numbers df1i = df1r + h_nbr_coef; df2i = df1i + nbr_coef; for (i = 1; i < h_nbr_coef; ++ i) { df1r [i] = sfr [i] + sfi [-i]; // + sfr [nbr_coef - i] df1i [i] = sfi [i] - sfi [nbr_coef - i]; wtk_oscsincos_step(osc); c=osc->pos_cos; s=osc->pos_sin; vr = sfr [i] - sfi [-i]; // - sfr [nbr_coef - i] vi = sfi [i] + sfi [nbr_coef - i]; df2r [i] = vr * c + vi * s; df2i [i] = vi * c - vr * s; } coef_index += d_nbr_coef; } while (coef_index < rfft->len); } void wtk_rfft_compute_inverse_pass_3(wtk_rfft_t *rfft,float *df,float *sf) { float sqrt2_2=SQRT2 * 0.5; int coef_index = 0; float vr,vi; do { df [coef_index] = sf [coef_index] + sf [coef_index + 4]; df [coef_index + 4] = sf [coef_index] - sf [coef_index + 4]; df [coef_index + 2] = sf [coef_index + 2] * 2; df [coef_index + 6] = sf [coef_index + 6] * 2; df [coef_index + 1] = sf [coef_index + 1] + sf [coef_index + 3]; df [coef_index + 3] = sf [coef_index + 5] - sf [coef_index + 7]; vr = sf [coef_index + 1] - sf [coef_index + 3]; vi = sf [coef_index + 5] + sf [coef_index + 7]; df [coef_index + 5] = (vr + vi) * sqrt2_2; df [coef_index + 7] = (vi - vr) * sqrt2_2; coef_index += 8; } while (coef_index < rfft->len); } void wtk_rfft_compute_inverse_pass_1_2(wtk_rfft_t *rfft,float *x,float *sf) { int * bit_rev_lut_ptr =rfft->br_lut; float * sf2 = sf; int coef_index = 0; float b_0,b_2,b_1,b_3; do { { b_0 = sf2 [0] + sf2 [2]; b_2 = sf2 [0] - sf2 [2]; b_1 = sf2 [1] * 2; b_3 = sf2 [3] * 2; x [bit_rev_lut_ptr [0]] = b_0 + b_1; x [bit_rev_lut_ptr [1]] = b_0 - b_1; x [bit_rev_lut_ptr [2]] = b_2 + b_3; x [bit_rev_lut_ptr [3]] = b_2 - b_3; } { b_0 = sf2 [4] + sf2 [6]; b_2 = sf2 [4] - sf2 [6]; b_1 = sf2 [5] * 2; b_3 = sf2 [7] * 2; x [bit_rev_lut_ptr [4]] = b_0 + b_1; x [bit_rev_lut_ptr [5]] = b_0 - b_1; x [bit_rev_lut_ptr [6]] = b_2 + b_3; x [bit_rev_lut_ptr [7]] = b_2 - b_3; } sf2 += 8; coef_index += 8; bit_rev_lut_ptr += 8; } while (coef_index < rfft->len); } void wtk_rfft_compute_inverse_pass_n(wtk_rfft_t *rfft,float *df,float *sf,int pass) { if (pass <= TRIGO_BD_LIMIT) { wtk_rfft_compute_inverse_pass_n_lut (rfft,df, sf, pass); } else { wtk_rfft_compute_inverse_pass_n_osc (rfft,df, sf, pass); } } void wtk_rfft_compute_ifft_general(wtk_rfft_t *rfft,float *f,float *x) { float *sf=f; float *df; float *df_temp; int pass; float *temp_ptr; if (rfft->nbr_bits & 1) { df = rfft->buffer; df_temp = x; }else { df = x; df_temp = rfft->buffer; } for (pass = rfft->nbr_bits - 1; pass >= 3; -- pass) { wtk_rfft_compute_inverse_pass_n (rfft,df, sf, pass); if (pass < rfft->nbr_bits - 1) { temp_ptr = df; df = sf; sf = temp_ptr; } else { sf = df; df = df_temp; } } wtk_rfft_compute_inverse_pass_3 (rfft,df, sf); wtk_rfft_compute_inverse_pass_1_2 (rfft,x, df); } /* ============================================================================== Name: do_ifft Description: Compute the inverse FFT of the array. Note that data must be post-scaled: IFFT (FFT (x)) = x * length (x). Input parameters: - f: pointer on the source array (frequencies). f [0...length(x)/2] = real values f [length(x)/2+1...length(x)-1] = negative imaginary values of coefficents 1...length(x)/2-1. Output parameters: - x: pointer on the destination array (time). Throws: Nothing ============================================================================== */ void wtk_rfft_process_ifft(wtk_rfft_t *rf,float *f,float *x) { #define USE_X float b_0,b_2; #ifdef USE_X register float t; register float *p1; float *pe,*pe2; #else int i; #endif // General case if (rf->nbr_bits > 2) { wtk_rfft_compute_ifft_general(rf,f, x); #ifdef USE_X t=1.0/rf->len; p1=x; pe=p1+rf->len; pe2=p1+((rf->len>>3)<<3); while(p1<pe2) { p1[0]*=t; p1[1]*=t; p1[2]*=t; p1[3]*=t; p1[4]*=t; p1[5]*=t; p1[6]*=t; p1[7]*=t; p1+=8; } while(p1<pe) { *(p1++)*=t; } #else for(i=0;i<rf->len;++i) { x[i]/=rf->len; } #endif } // 4-point IFFT else if (rf->nbr_bits == 2) { b_0 = f [0] + f [2]; b_2 = f [0] - f [2]; x [0] = (b_0 + f [1] * 2)/4; x [2] = (b_0 - f [1] * 2)/4; x [1] = (b_2 + f [3] * 2)/4; x [3] = (b_2 - f [3] * 2)/4; } // 2-point IFFT else if (rf->nbr_bits == 1) { x [0] = (f [0] + f [1])/2; x [1] = (f [0] - f [1])/2; } // 1-point IFFT else { x [0] = f [0]; } } //fft -ref_fft void wtk_xcorr_freq_mult(float *fft1,float *fft2,float *xy,int fft_size) { int i; float t; int nx; float x1,x2; nx=fft_size<<1; x1=fft1[0]*fft2[0]; t=abs(x1); if(t==0){t=1;} xy[0]=x1/(t*nx); for(i=1;i<fft_size;i++) { //do the multiplication: (a+jb)(c+jd)* = (a+jb)*(c-jd)=(ac+bd)+j(bc-ad); x1=fft1[i]*fft2[i]+fft1[i+fft_size]*fft2[i+fft_size]; x2=fft1[i+fft_size]*fft2[i]-fft1[i]*fft2[i+fft_size]; t=sqrt(x1*x1+x2*x2); if(t==0){t=1;} t=1.0/(t*nx); xy[i]=x1*t;///(t*nx); xy[i+fft_size]=x2*t;///(t*nx); } x1=fft1[fft_size]*fft2[fft_size]; t=abs(x1); if(t==0){t=1;} xy[fft_size]=x1/(t*nx); } int wtk_xcorr_find_best_value(float *xcorr_value,int nx,int margin) { int i,j; float f; float max=-1e10; int idx=0; //vs=wtk_larray_new(n/4,sizeof(float)); //ps=wtk_larray_new(n/4,sizeof(int)); //finding the maximums //I don't consider the delay=0 a maximum, as it has a discontinuity always. f=xcorr_value[nx-1]; if(f>xcorr_value[nx-2] && f>xcorr_value[0]) { idx=margin; //wtk_debug("v[%d]=%f\n",x,f); max=f; } for(i=nx-margin-1,j=0;i<(nx-1);++i,++j) { f=xcorr_value[i]; //wtk_debug("v[%d]=%f\n",i,f); if(f>xcorr_value[i-1] && f>xcorr_value[i+1] && f>max) { //wtk_debug("v[%d]=%f\n",j,f); idx=j; max=f; } } f=xcorr_value[0]; if(f>xcorr_value[1] && f>xcorr_value[nx-1] && f>max) { idx=margin+1; max=f; //wtk_debug("v[%d]=%f\n",x,f); } for(i=1;i<margin;++i) { f=xcorr_value[i]; if(f>xcorr_value[i-1] && f>xcorr_value[i+1] && f>max) { idx=i+margin+1; max=f; } } idx-=(margin+1); //wtk_debug("idx=%d max=%f\n",idx,max); //exit(0); //wtk_debug("max=%f idx=%d\n",max,idx); return idx; } void wtk_xcorr_find_nbest_values(wtk_larray_t *vs,wtk_larray_t *ps,float *xcorr_value,int nx,int margin,int *delays,float *values,int nbest) { int win=5; int i,j,k=-1; int n; float f; int v=-1; int b; //wtk_larray_t *vs; //wtk_larray_t *ps; float *pvs; int *pps; int x; n=2*margin-1; wtk_larray_reset(vs); wtk_larray_reset(ps); //vs=wtk_larray_new(n/4,sizeof(float)); //ps=wtk_larray_new(n/4,sizeof(int)); //finding the maximums //I don't consider the delay=0 a maximum, as it has a discontinuity always. f=xcorr_value[nx-1]; if(f>xcorr_value[nx-2] && f>xcorr_value[0]) { wtk_larray_push2(vs,&(f)); x=margin; wtk_larray_push2(ps,&(x)); //wtk_debug("v[%d]=%f\n",0,f); } for(i=nx-margin-1,j=0;i<(nx-1);++i,++j) { f=xcorr_value[i]; //wtk_debug("v[%d]=%f\n",i,f); if(f>xcorr_value[i-1] && f>xcorr_value[i+1]) { wtk_larray_push2(vs,&(f)); wtk_larray_push2(ps,&(j)); //wtk_debug("v[%d]=%f\n",j-(margin+1),f); } } f=xcorr_value[0]; if(f>xcorr_value[1] && f>xcorr_value[nx-1]) { wtk_larray_push2(vs,&(f)); x=margin+1; wtk_larray_push2(ps,&(x)); //wtk_debug("v[%d]=%f\n",0,f); } for(i=1;i<margin;++i) { f=xcorr_value[i]; if(f>xcorr_value[i-1] && f>xcorr_value[i+1]) { wtk_larray_push2(vs,&(f)); x=i+margin+1; wtk_larray_push2(ps,&(x)); //wtk_debug("v[%d]=%f\n",i,f); } } //wtk_debug("n=%d/%d\n",n,n/4); n=vs->nslot; pvs=(float*)vs->slot; pps=(int*)ps->slot; //wtk_debug("max=%d n=%d\n",max,n); delays[0]=margin+1; if(values) { values[0]=0; } for(i=0;i<nbest;++i) { f=-1; for(j=0;j<n;++j) { if(pvs[j]>f) { f=pvs[j]; v=pps[j]; k=j; } } //wtk_debug("f=%f v=%d\n",f,v); if(f!=-1) { x=1; for(j=0;j<i;++j) { b=v-delays[j]; if(b<win && b>-win) { x=0; pvs[k]=-1; } } //wtk_debug("x=%d\n",x); if(x==0) { --i; }else { delays[i]=v; if(values) { values[i]=f; } pvs[k]=-1; } }else { //we didn't find any more maximums, we repeat the first delay and value (it's a way to put null) delays[i]=delays[0]; if(values) { values[i]=values[0]; } } } for(j=0;j<nbest;++j) { //wtk_debug("v[%d]=%d\n",i,delays[j]); delays[j]-=margin+1; //wtk_debug("v[%d/%d]=%d/%f\n",j,max,delays[j],values[j]); } //wtk_larray_delete(vs); //wtk_larray_delete(ps); } int wtk_rfft_xcorr2(char *mic,int mic_len,char *sp,int sp_len) { float f; f=wtk_rfft_xcorr3(mic,mic_len,sp,sp_len,800,NULL); if(f>0) { return (int)(f+0.5); }else { return (int)(f-0.5); } } void wtk_rfft_find_max_value2(float x1,float y1,float x2,float y2,float x3,float y3) { float a,b,c; float idx,v; a=(y1-y2-(x1-x2)*(y1-y3)/(x1-x3))/(x1*x1-x2*x2-(x1-x2)*(x1+x3)); b=((y1-y3)-a*(x1*x1-x3*x3))/(x1-x3); c=y1-a*x1*x1-b*x1; wtk_debug("a=%f b=%f c=%f\n",a,b,c); wtk_debug("%f/%f/%f\n",a*x1*x1+b*x1+c,a*x2*x2+b*x2+c,a*x3*x3+b*x3+c); idx=-b/(2*a); v=c-b*b/(4*a); wtk_debug("v[%f]=%f/%f\n",idx,v,a*idx*idx+b*idx+c); exit(0); } float wtk_rfft_find_max_value(float x1,float y1,float x2,float y2,float x3,float y3,float *max_v) { float a,b,c; float idx; a=(y1-y2-(x1-x2)*(y1-y3)/(x1-x3))/(x1*x1-x2*x2-(x1-x2)*(x1+x3)); b=((y1-y3)-a*(x1*x1-x3*x3))/(x1-x3); c=y1-a*x1*x1-b*x1; idx=-b/(2*a); if(max_v) { *max_v=c-b*b/(4*a); } //wtk_debug("v[%f]=%f\n",idx,v); return idx; } float wtk_rfft_find_best_value(float *x1,int len,int margin,float *max_v) { int idx; float ft; int i; int win=len/2; float fidx; int j=0; if(margin>win) { margin=win; } //wtk_debug("margin=%d\n",margin); idx=0; ft=x1[0]; for(i=1;i<margin;++i) { if(x1[i]>ft) { idx=i; ft=x1[i]; } } //print_float(x1,20); //print_float(x1+len-20,20); //wtk_debug("idx=%d %e\n", idx,ft); for(i=len-margin,j=-margin;i<len;++i,++j) { if(x1[i]>ft) { idx=j; ft=x1[i]; } } //wtk_debug("idx=%d %e\n", idx,ft); // wtk_debug("idx=%d %e\n",idx,ft); // wtk_debug("margin=%d\n",margin); // print_float(x1,10); // print_float(x1+rfft->len-10,10); //wtk_debug("idx[%d]=%f\n",idx,ft); //wtk_debug("idx=%d f=%f len=%d/%d\n",idx,ft,rfft->win,rfft->len); // if(len>3) // { // //寻找中间值 // if(idx>win) // { // v[0]=idx-len; // v[1]=x1[idx]; // v[2]=idx-1-len; // v[3]=x1[idx-1]; // if((idx+1)<len) // { // v[4]=idx+1-len; // v[5]=x1[idx+1]; // }else // { // v[4]=idx-2-len; // v[5]=x1[idx-2]; // } // fidx=wtk_rfft_find_max_value(v[0],v[1],v[2],v[3],v[4],v[5],max_v); // //fidx-=rfft->len; // }else // { // v[0]=idx; // v[1]=x1[idx]; // wtk_debug("%f=%e\n",v[0],v[1]); // if(idx<=0) // { // v[2]=idx+2; // v[3]=x1[idx+2]; // }else // { // v[2]=idx-1; // v[3]=x1[idx-1]; // } // v[4]=idx+1; // v[5]=x1[idx+1]; // fidx=wtk_rfft_find_max_value(v[0],v[1],v[2],v[3],v[4],v[5],max_v); // } // wtk_debug("fidx=%f\n",fidx); // }else { if(max_v) { *max_v=ft;//x1[idx]; } fidx=idx; } return fidx; } float wtk_rfft_xcorr3(char *mic,int mic_len,char *sp,int sp_len,int margin,float *max_v) { int len; wtk_rfft_t *rfft; float *x1; float *x2; float *x3; int i; short *smc,*ssp; float ft; double x; float fidx; //wtk_debug("mic=%d sp=%d\n",mic_len,sp_len); len=min(mic_len/2,sp_len/2); rfft=wtk_rfft_new(len); smc=(short*)mic; ssp=(short*)sp; x1=(float*)wtk_calloc(rfft->len,sizeof(float)); x2=(float*)wtk_calloc(rfft->len,sizeof(float)); x3=(float*)wtk_calloc(rfft->len,sizeof(float)); x=6.283185307/(len-1); for(i=0;i<len;++i) { ft=0.54 - 0.46*cos(x*i); //ft=1; x1[i]=smc[i]*ft; x2[i]=ssp[i]*ft; } wtk_rfft_process_fft(rfft,x3,x1);//x3 mic fft; wtk_rfft_process_fft(rfft,x1,x2);//x1 sp fft; wtk_xcorr_freq_mult(x3,x1,x2,rfft->win); wtk_rfft_process_ifft(rfft,x2,x1); fidx=wtk_rfft_find_best_value(x1,rfft->len,margin,max_v); //wtk_debug("idx=%f f=%f len=%d/%d\n",fidx,ft,rfft->win,rfft->len); wtk_free(x1); wtk_free(x2); wtk_free(x3); wtk_rfft_delete(rfft); return fidx; } int wtk_rfft_xcorr(char *mic,int mic_len,char *sp,int sp_len) { #define NBEST 4 int idx; int delays[NBEST]; int v; int i; wtk_rfft_nbest_xcorr(mic,mic_len,sp,sp_len,min(mic_len,sp_len)/2,delays,NBEST); wtk_debug("----------------------------\n"); for(i=0;i<NBEST;++i) { wtk_debug("v[%d]=%d\n",i,delays[i]); } idx=delays[0]; for(i=0;i<NBEST-1;++i) { //wtk_debug("v[%d]=%d\n",i,delays[i]); v=delays[i]-delays[i+1]; v=abs(v); if(v<80) { idx=delays[i]; break; } } return idx; } void wtk_rfft_nbest_xcorr2(char *mic,int mic_len,char *sp,int sp_len,int *delays,int nbest) { wtk_rfft_nbest_xcorr(mic,mic_len,sp,sp_len,min(mic_len,sp_len)/2,delays,nbest); } //#define DUEBG_XV void wtk_rfft_nbest_xcorr_int(int *mic,int mic_len,int *sp,int sp_len,int margin,int *delays,int nbest) { float *p1,*p2; int i; p1=(float*)wtk_calloc(mic_len,sizeof(float)); p2=(float*)wtk_calloc(sp_len,sizeof(float)); for(i=0;i<mic_len;++i) { p1[i]=mic[i]; } for(i=0;i<sp_len;++i) { p2[i]=sp[i]; } wtk_rfft_nbest_xcorr_float(p1,mic_len,p2,sp_len,margin,delays,nbest); wtk_free(p1); wtk_free(p2); } void wtk_rfft_nbest_xcorr_float(float *mic,int mic_len,float *sp,int sp_len,int margin,int *delays,int nbest) { int len; wtk_rfft_t *rfft; float *x1; float *x2; float *x3; int i; short *smc,*ssp; wtk_larray_t *vs,*ps; float ft; double x; #ifdef DUEBG_XV float values[10]; #else float *values=NULL; #endif //wtk_debug("mic=%d sp=%d\n",mic_len,sp_len); len=min(mic_len/2,sp_len/2); rfft=wtk_rfft_new(len); smc=(short*)mic; ssp=(short*)sp; x1=(float*)wtk_calloc(rfft->len,sizeof(float)); x2=(float*)wtk_calloc(rfft->len,sizeof(float)); x3=(float*)wtk_calloc(rfft->len,sizeof(float)); x=6.283185307/(len-1); for(i=0;i<len;++i) { ft=0.54 - 0.46*cos(x*i); x1[i]=smc[i]*ft; x2[i]=ssp[i]*ft; } wtk_rfft_process_fft(rfft,x3,x1);//x3 mic fft; wtk_rfft_process_fft(rfft,x1,x2);//x1 sp fft; wtk_xcorr_freq_mult(x3,x1,x2,rfft->win); wtk_rfft_process_ifft(rfft,x2,x1); vs=wtk_larray_new(rfft->win/3,sizeof(float)); ps=wtk_larray_new(vs->nslot,sizeof(int)); wtk_xcorr_find_nbest_values(vs,ps,x1,rfft->len,margin,delays,values,nbest); // i=wtk_xcorr_find_best_value(x1,rfft->len,margin); // wtk_debug("i=%d\n",i); #ifdef DUEBG_XV for(i=0;i<nbest;++i) { wtk_debug("v[%d]=%d/%f\n",i,delays[i],values[i]); } #endif wtk_larray_delete(vs); wtk_larray_delete(ps); wtk_free(x1); wtk_free(x2); wtk_free(x3); wtk_rfft_delete(rfft); } void wtk_rfft_nbest_xcorr(char *mic,int mic_len,char *sp,int sp_len,int margin,int *delays,int nbest) { #define DUEBG_XV int len; wtk_rfft_t *rfft; float *x1; float *x2; float *x3; int i; short *smc,*ssp; wtk_larray_t *vs,*ps; float ft; double x; #ifdef DUEBG_XV float values[64]; #else float *values=NULL; #endif //wtk_debug("mic=%d sp=%d\n",mic_len,sp_len); len=min(mic_len/2,sp_len/2); rfft=wtk_rfft_new(len); smc=(short*)mic; ssp=(short*)sp; x1=(float*)wtk_calloc(rfft->len,sizeof(float)); x2=(float*)wtk_calloc(rfft->len,sizeof(float)); x3=(float*)wtk_calloc(rfft->len,sizeof(float)); x=6.283185307/(len-1); for(i=0;i<len;++i) { ft=0.54 - 0.46*cos(x*i); x1[i]=smc[i]*ft; x2[i]=ssp[i]*ft; } wtk_rfft_process_fft(rfft,x3,x1);//x3 mic fft; wtk_rfft_process_fft(rfft,x1,x2);//x1 sp fft; wtk_xcorr_freq_mult(x3,x1,x2,rfft->win); wtk_rfft_process_ifft(rfft,x2,x1); vs=wtk_larray_new(rfft->win/3,sizeof(float)); ps=wtk_larray_new(vs->nslot,sizeof(int)); wtk_xcorr_find_nbest_values(vs,ps,x1,rfft->len,margin,delays,values,nbest); // i=wtk_xcorr_find_best_value(x1,rfft->len,margin); // wtk_debug("i=%d\n",i); #ifdef DUEBG_XV for(i=0;i<nbest;++i) { wtk_debug("v[%d]=%d/%e\n",i,delays[i],values[i]); } #endif wtk_larray_delete(vs); wtk_larray_delete(ps); wtk_free(x1); wtk_free(x2); wtk_free(x3); wtk_rfft_delete(rfft); } int wtk_int_max(int *delay,int n) { int v; int i; v=delay[0]; for(i=1;i<n;++i) { if(delay[i]>v) { v=delay[i]; } } return v; } int wtk_int_min(int *delay,int n) { int v; int i; v=delay[0]; for(i=1;i<n;++i) { if(delay[i]<v) { v=delay[i]; } } return v; } void wtk_rfft_nbest_xcorr3(int channel,char **mic,int mic_len,char *sp,int sp_len,int *delays) { int len; wtk_rfft_t *rfft; float **x1; float *x2; float *x3; int i,j; short **smc,*ssp; float ft; double x; int margin; //wtk_debug("mic=%d sp=%d\n",mic_len,sp_len); len=min(mic_len/2,sp_len/2); margin=min(len,600); rfft=wtk_rfft_new(len); smc=(short**)mic; ssp=(short*)sp; x1=(float**)wtk_malloc(sizeof(float*)*channel); for(i=0;i<channel;++i) { x1[i]=(float*)wtk_calloc(rfft->len,sizeof(float)); } x2=(float*)wtk_calloc(rfft->len,sizeof(float)); x3=(float*)wtk_calloc(rfft->len,sizeof(float)); x=6.283185307/(len-1); for(i=0;i<len;++i) { ft=0.54 - 0.46*cos(x*i); for(j=0;j<channel;++j) { x1[j][i]=smc[j][i]*ft; } x2[i]=ssp[i]*ft; } wtk_rfft_process_fft(rfft,x3,x2);//x1 sp fft; for(i=0;i<channel;++i) { wtk_rfft_process_fft(rfft,x2,x1[i]);//mic fft wtk_xcorr_freq_mult(x2,x3,x1[i],rfft->win); //sp fft wtk_rfft_process_ifft(rfft,x1[i],x2); //wtk_xcorr_find_nbest_values(); ft=wtk_rfft_find_best_value(x2,rfft->len,margin,NULL); delays[i]=ft>0?((int)(ft+0.5)):((int)(ft-0.5)); //wtk_debug("ft=%f/%d\n",ft,delays[i]); wtk_free(x1[i]); } wtk_free(x1); wtk_free(x2); wtk_free(x3); wtk_rfft_delete(rfft); } void wtk_rfft_nbest_xcorr4(int channel,char **mic,int mic_len,char *sp,int sp_len,int nbest,int *nbest_delays) { int len; wtk_rfft_t *rfft; float **x1; float *x2; float *x3; int i,j; short **smc,*ssp; float ft; double x; int margin; wtk_larray_t *ps; wtk_larray_t *vs; //wtk_debug("mic=%d sp=%d\n",mic_len,sp_len); len=min(mic_len/2,sp_len/2); margin=min(len,3200); rfft=wtk_rfft_new(len); ps=wtk_larray_new(rfft->win/3,sizeof(int)); vs=wtk_larray_new(rfft->win/3,sizeof(float)); smc=(short**)mic; ssp=(short*)sp; x1=(float**)wtk_malloc(sizeof(float*)*channel); for(i=0;i<channel;++i) { x1[i]=(float*)wtk_calloc(rfft->len,sizeof(float)); } x2=(float*)wtk_calloc(rfft->len,sizeof(float)); x3=(float*)wtk_calloc(rfft->len,sizeof(float)); x=6.283185307/(len-1); for(i=0;i<len;++i) { ft=0.54 - 0.46*cos(x*i); for(j=0;j<channel;++j) { x1[j][i]=smc[j][i]*ft; } x2[i]=ssp[i]*ft; } wtk_rfft_process_fft(rfft,x3,x2);//x1 sp fft; for(i=0;i<channel;++i) { wtk_rfft_process_fft(rfft,x2,x1[i]);//mic fft wtk_xcorr_freq_mult(x2,x3,x1[i],rfft->win); //sp fft wtk_rfft_process_ifft(rfft,x1[i],x2); //wtk_xcorr_find_nbest_values(); //delays[i]=wtk_xcorr_find_best_value(x2,rfft->len,margin); //wtk_debug("v[%d]=%d\n",i,delays[i]); //exit(0); wtk_xcorr_find_nbest_values(vs,ps,x2,rfft->len,margin,nbest_delays+i*nbest,NULL,nbest); //print_float(vx,nbest); wtk_free(x1[i]); } wtk_larray_delete(ps); wtk_larray_delete(vs); wtk_free(x1); wtk_free(x2); wtk_free(x3); wtk_rfft_delete(rfft); } void wtk_rfft_nbest_xcorr_mult_channel(int channel,char **mic,int mic_len,char *sp,int sp_len,int *delays) { wtk_rfft_nbest_xcorr4(channel,mic,mic_len,sp,sp_len,1,delays); } void wtk_rfft_nbest_xcorr_mult_channel2(int channel,char **mic,int mic_len,char *sp,int sp_len,int nbest,int *delays) { wtk_heap_t *heap; wtk_kcls_t *cls; wtk_kcls_value_t *vx; float max_sse=3; int *nbest_delay; int i; nbest_delay=(int*)wtk_malloc(sizeof(int)*channel*nbest); wtk_rfft_nbest_xcorr4(channel,mic,mic_len,sp,sp_len,nbest,nbest_delay); heap=wtk_heap_new(4096); cls=wtk_kcls_new(heap); for(i=0;i<channel;++i) { print_int(nbest_delay+i*nbest,nbest); vx=wtk_kcls_value_new(heap,i,nbest_delay[i*nbest]); wtk_queue_push(&(cls->item_q),&(vx->q_n)); } cls=wtk_kcls_cluster(cls,heap,max_sse); wtk_kcls_print(cls); wtk_heap_delete(heap); exit(0); wtk_free(nbest_delay); } void wtk_rfft_mult(register float *fft1,register float *fft2,register float *xy,int win) { int i; register float *fp1,*fp2,*fpx; //do the multiplication: (a+jb)(c+jd)=(ac-bd)+j(bc+ad); xy[0]=fft1[0]*fft2[0]; fp1=fft1+win; fp2=fft2+win; fpx=xy+win; //wtk_debug("v[0]=%f\n",xy[0]); for(i=1;i<win;++i) { //a=fft1[i] b=fp1[i] //c=fft2[i] d=fp2[i] xy[i]=fft1[i]*fft2[i]-fp1[i]*fp2[i]; fpx[i]=fp1[i]*fft2[i]+fft1[i]*fp2[i]; //wtk_debug("%f+%f %f+%f\n",fft1[i],fp1[i],fft2[i],fp2[i]); //wtk_debug("v[%d]=%f+%f\n",i,xy[i],fpx[i]); //exit(0); } xy[win]=fft1[win]*fft2[win]; } //do the multiplication: (a+jb)'(c+jd) =(a-jb)(c+jd)=(ac+bd)+j(ad-bc); void wtk_rfft_mult2(register float *fft1,register float *fft2,float *xy,int win) { int i; register float *fp1,*fp2,*fpx; xy[0]=fft1[0]*fft2[0]; fp1=fft1+win; fp2=fft2+win; fpx=xy+win; for(i=1;i<win;++i) { //a=fft1[i] b=fp1[i] //c=fft2[i] d=fp2[i] xy[i]=fft1[i]*fft2[i]+fp1[i]*fp2[i]; fpx[i]=fft1[i]*fp2[i]-fp1[i]*fft2[i]; } xy[win]=fft1[win]*fft2[win]; } //do the multiplication: (a+jb).conj(c+jd) =(a+jb)(c-jd)=(ac+bd)+j(-ad+bc); void wtk_rfft_mult3(register float *fft1,register float *fft2,float *xy,int win) { int i; register float *fp1,*fp2,*fpx; xy[0]=fft1[0]*fft2[0]; fp1=fft1+win; fp2=fft2+win; fpx=xy+win; for(i=1;i<win;++i) { //a=fft1[i] b=fp1[i] //c=fft2[i] d=fp2[i] xy[i]=fft1[i]*fft2[i]+fp1[i]*fp2[i]; fpx[i]=-fft1[i]*fp2[i]+fp1[i]*fft2[i]; } xy[win]=fft1[win]*fft2[win]; } void wtk_rfft_set_value(float *f,int n,int idx,wtk_complex_t c) { int win; if(idx==0) { f[0]=c.a; }else { win=n>>1; if(idx<win) { f[idx]=c.a; f[idx+win]=-c.b; }else if(idx==win) { f[idx]=c.a; }else { f[n-idx]=c.a; f[n-idx+win]=c.b; } } } void wtk_rfft_set_value2(float *f,int n,int idx,float a,float b) { int win; if(idx==0) { f[0]=a; }else { win=n>>1; if(idx<win) { f[idx]=a; f[idx+win]=-b; }else if(idx==win) { f[idx]=a; }else { f[n-idx]=a; f[n-idx+win]=b; } } } wtk_complex_t wtk_rfft_get_value(float *f,int n,int idx) { wtk_complex_t c; int win; if(idx==0) { c.a=f[0]; c.b=0; }else { win=n>>1; if(idx<win) { c.a=f[idx]; c.b=-f[idx+win]; }else if(idx==win) { c.a=f[idx]; c.b=0; }else { c.a=f[n-idx]; c.b=f[n-idx+win]; } } return c; } void wtk_rfft_print_fft(float *f,int n) { int i; int win=n/2; double ta,tb; ta=tb=0; printf("----------------- fft --------------------------\n"); ta+=f[0]; wtk_debug("v[%d]=%.6f+%.6fi\n",0,f[0],0.0); for(i=1;i<win;++i) { ta+=f[i]; tb+=-f[i+win]; wtk_debug("v[%d]=%.6f+%.6fi\n",i,f[i],-f[i+win]); } wtk_debug("v[%d]=%.6f+%.6fi\n",win,f[win],0.0); ta+=f[win]; for(i=win+1;i<n;++i) { ta+=f[n-i]; tb+=f[n-i+win]; wtk_debug("v[%d]=%.6f+%.6fi\n",i,f[n-i],f[n-i+win]); //exit(0); } wtk_debug("tot=%f+%f\n",ta,tb); //exit(0); } <file_sep>/os/.svn/pristine/29/29146d6749270e4f6491e71b36ddc027342ac688.svn-base #ifndef WTK_OS_DTP_WTK_DTP_H_ #define WTK_OS_DTP_WTK_DTP_H_ #include "wtk/core/wtk_type.h" #include "wtk/os/wtk_thread.h" #include "wtk/os/wtk_blockqueue.h" #include "wtk_dtp_cfg.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_dtp wtk_dtp_t; typedef void*(*wtk_dtp_inst_new_f)(void *ths); typedef void(*wtk_dtp_inst_delete_f)(void *inst); typedef void(*wtk_dtp_inst_process_f)(void *ths,void *inst,wtk_queue_node_t *n); typedef struct { void *ths; wtk_dtp_inst_new_f inst_new; wtk_dtp_inst_delete_f inst_delete; wtk_dtp_inst_process_f inst_process; }wtk_dtp_handler_t; typedef struct { wtk_thread_t thread; wtk_queue_node_t q_n; void *inst; wtk_dtp_t *dtp; }wtk_dtp_route_t; struct wtk_dtp { wtk_dtp_cfg_t *cfg; wtk_dtp_handler_t *handler; wtk_heap_t *heap; wtk_queue_t thread_q; //wtk_dtp_route_t wtk_blockqueue_t input_q; unsigned run:1; }; wtk_dtp_t* wtk_dtp_new(wtk_dtp_cfg_t *cfg,wtk_dtp_handler_t *h); void wtk_dtp_delete(wtk_dtp_t *dtp); void wtk_dtp_push(wtk_dtp_t *dtp,wtk_queue_node_t *n); void wtk_dtp_join(wtk_dtp_t *dtp); void wtk_dtp_stop(wtk_dtp_t *dtp); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_base64.h #ifndef WTK_CORE_WTK_BASE64 #define WTK_CORE_WTK_BASE64 #include "wtk_type.h" #ifdef __cplusplus extern "C" { #endif char* wtk_base64_encode(char* data,int len); char* wtk_base64_encode_url(char* data,int len); char* wtk_base64_decode(const char* base64,int len); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_label.h #ifndef WTK_MODEL_WTK_LABEL_H_ #define WTK_MODEL_WTK_LABEL_H_ #include "wtk/core/wtk_str.h" #include "wtk/core/wtk_str_hash.h" #include "wtk/core/wtk_queue3.h" #ifdef __cplusplus extern "C" { #endif #define wtk_label_find_s(l,s,i) wtk_label_find(l,s,sizeof(s)-1,i) typedef struct wtk_label wtk_label_t; typedef struct wtk_label_node wtk_label_node_t; struct wtk_label_node { wtk_label_node_t *next; }; typedef struct { wtk_label_node_t q_n; wtk_string_t* name; void *data; }wtk_name_t; struct wtk_label { wtk_heap_t *heap; wtk_label_node_t **slot; int nslot; }; wtk_label_t* wtk_label_new(int hint); int wtk_label_delete(wtk_label_t *l); int wtk_label_bytes(wtk_label_t *l); int wtk_label_init(wtk_label_t* l,int hint); int wtk_label_clean(wtk_label_t *l); int wtk_label_reset(wtk_label_t *l); wtk_name_t* wtk_label_find(wtk_label_t *l,char *s,int sl,int insert); wtk_string_t* wtk_label_find2(wtk_label_t *l,char *s,int sl,int insert); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_kcls.c #include "wtk_kcls.h" wtk_kcls_value_t* wtk_kcls_value_new(wtk_heap_t *heap,int idx,float f) { wtk_kcls_value_t *v; v=(wtk_kcls_value_t*)wtk_heap_malloc(heap,sizeof(wtk_kcls_value_t)); v->idx=idx; v->v=f; return v; } wtk_kcls_t* wtk_kcls_new(wtk_heap_t *heap) { wtk_kcls_t *cls; cls=(wtk_kcls_t*)wtk_heap_malloc(heap,sizeof(wtk_kcls_t)); wtk_queue_init(&(cls->item_q)); cls->sse=0; cls->mean=0; return cls; } wtk_kcls_t* wtk_kcls_pop(wtk_kcls_t *cls,wtk_heap_t *heap) { wtk_kcls_t *vi; wtk_queue_node_t *qn; wtk_kcls_value_t *v; vi=wtk_kcls_new(heap); qn=wtk_queue_pop(&(cls->item_q)); v=data_offset2(qn,wtk_kcls_value_t,q_n); vi->mean=v->v; wtk_queue_push(&(vi->item_q),qn); return vi; } void wtk_kcls_print(wtk_kcls_t *cls) { wtk_queue_node_t *qn; wtk_kcls_value_t *vx; wtk_debug("============ sse=%f mean=%f ==========\n",cls->sse,cls->mean); for(qn=cls->item_q.pop;qn;qn=qn->next) { vx=(wtk_kcls_value_t*)data_offset2(qn,wtk_kcls_value_t,q_n); wtk_debug("v[%d]=%f\n",vx->idx,vx->v); } } void wtk_kcls_update_sse(wtk_kcls_t *item) { wtk_queue_node_t *qn; wtk_kcls_value_t *vx; float f,f2; f=0; for(qn=item->item_q.pop;qn;qn=qn->next) { vx=(wtk_kcls_value_t*)data_offset2(qn,wtk_kcls_value_t,q_n); f+=vx->v; //wtk_debug("v[%d]=%f\n",vx->idx,vx->v); } item->mean=f/item->item_q.length; f=0; for(qn=item->item_q.pop;qn;qn=qn->next) { vx=(wtk_kcls_value_t*)data_offset2(qn,wtk_kcls_value_t,q_n); f2=vx->v-item->mean; f+=f2*f2; } item->sse=f; //wtk_debug("============ sse=%f ===========\n",item->sse); } void wtk_kcls_insert(wtk_queue_t *q,wtk_kcls_t *item) { wtk_queue_node_t *qn; wtk_kcls_t *vi; for(qn=q->pop;qn;qn=qn->next) { vi=data_offset2(qn,wtk_kcls_t,q_n); //wtk_debug("sse=%f/%f\n",item->sse,vi->sse); if(vi->sse<=item->sse) { //wtk_debug("============= insert %f len=%d ===========\n",item->sse,item->item_q.length); wtk_queue_insert_before(q,qn,&(item->q_n)); return; } } wtk_queue_push(q,&(item->q_n)); } void wtk_kcls_cluster_process(wtk_queue_t *qt,wtk_heap_t *heap,float min_sse) { wtk_kcls_t *item1,*item2,*item; wtk_queue_node_t *qn; wtk_kcls_value_t *vx; float f1,f2; float m1,m2; wtk_queue_t q; qn=wtk_queue_pop(qt); item=data_offset2(qn,wtk_kcls_t,q_n); //wtk_debug("len=%d sse=%f\n",item->item_q.length,item->sse); if(item->item_q.length<2 || item->sse/item->item_q.length<min_sse) { wtk_queue_push_front(qt,qn); return; } item1=wtk_kcls_pop(item,heap); item2=wtk_kcls_pop(item,heap); m1=item1->mean; m2=item2->mean; while(1) { qn=wtk_queue_pop(&(item->item_q)); if(!qn){break;} vx=data_offset2(qn,wtk_kcls_value_t,q_n); f1=(vx->v-m1);//item1->mean); f1*=f1; f2=(vx->v-m2);//item2->mean); f2*=f2; if(f1<f2) { item1->mean=(item1->mean*item1->item_q.length+vx->v)/(item1->item_q.length+1); wtk_queue_push(&(item1->item_q),qn); }else { item2->mean=(item2->mean*item2->item_q.length+vx->v)/(item2->item_q.length+1); wtk_queue_push(&(item2->item_q),qn); } } q=item1->item_q; wtk_queue_link(&(q),&(item2->item_q)); wtk_queue_init(&(item1->item_q)); wtk_queue_init(&(item2->item_q)); m1=item1->mean; m2=item2->mean; while(1) { qn=wtk_queue_pop(&(q)); if(!qn){break;} vx=data_offset2(qn,wtk_kcls_value_t,q_n); f1=(vx->v-m1);//item1->mean); f1*=f1; f2=(vx->v-m2);//item2->mean); f2*=f2; if(f1<f2) { wtk_queue_push(&(item1->item_q),qn); }else { wtk_queue_push(&(item2->item_q),qn); } } wtk_kcls_update_sse(item1); wtk_kcls_update_sse(item2); wtk_kcls_insert(qt,item1); wtk_kcls_insert(qt,item2); } wtk_kcls_t* wtk_kcls_cluster(wtk_kcls_t *cls,wtk_heap_t *heap,float max_sse) { int nx; wtk_queue_node_t *qn; wtk_queue_t q; wtk_queue_init(&(q)); wtk_queue_push(&(q),&(cls->q_n)); cls->sse=max_sse*cls->item_q.length+1; do { nx=q.length; wtk_kcls_cluster_process(&(q),heap,max_sse); //wtk_debug("============nx=%d =======\n",nx); }while(nx!=q.length); qn=wtk_queue_pop(&(q)); if(qn) { cls=data_offset2(qn,wtk_kcls_t,q_n); return cls; }else { return NULL; } } void wtk_kcls_select_int(int *v,int n) { wtk_heap_t *heap; wtk_kcls_t *cls; wtk_kcls_value_t *vx; int i; float max_sse=2; heap=wtk_heap_new(4096); cls=wtk_kcls_new(heap); for(i=0;i<n;++i) { vx=wtk_kcls_value_new(heap,i,v[i]); wtk_queue_push(&(cls->item_q),&(vx->q_n)); } cls=wtk_kcls_cluster(cls,heap,max_sse); wtk_kcls_print(cls); wtk_heap_delete(heap); } <file_sep>/core/.svn/pristine/8e/8e52c0570c9d6b77c756a64d839635f0e92f1616.svn-base #ifndef WTK_CORE_FFT_WTK_QSTFT #define WTK_CORE_FFT_WTK_QSTFT #include "wtk/core/wtk_type.h" #include "wtk_qstft_cfg.h" #include "wtk_stft.h" #include "wtk/core/wtk_robin.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_qstft wtk_qstft_t; typedef enum { WTK_QSTFT_INIT, WTK_QSTFT_UPDATE, }wtk_qstft_state_t; typedef void(*wtk_qstft_notify_f)(void *ths,wtk_complex_t ***XX,int is_end); typedef void(*wtk_qstft_delete_msg_f)(void *ths,wtk_stft_msg_t *msg); struct wtk_qstft { wtk_qstft_cfg_t *cfg; wtk_stft_cfg_t *stft_cfg; wtk_qstft_state_t state; wtk_robin_t *robin; float *winf; float *wint; wtk_complex_t ***XX;//|channel*channel*nbin| wtk_complex_t **xx; float *wei; int max_ind; void *notify_ths; wtk_qstft_notify_f notify; void *delete_msg_ths; wtk_qstft_delete_msg_f delete_msg; }; wtk_qstft_t* wtk_qstft_new(wtk_qstft_cfg_t *cfg,wtk_stft_cfg_t *stft_cfg); void wtk_qstft_delete(wtk_qstft_t *qf); void wtk_qstft_reset(wtk_qstft_t *qf); void wtk_qstft_set_notify(wtk_qstft_t *qf,void *ths,wtk_qstft_notify_f notify); void wtk_qstft_set_delete_msg(wtk_qstft_t *qf,void *ths,wtk_qstft_delete_msg_f delete_msg); void wtk_qstft_feed(wtk_qstft_t *qf,wtk_stft_msg_t *msg,int len,int is_end); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/17/178abb8f2a9a47e7ca2b228bdda7c9d0f9709d38.svn-base #ifndef WTK_DLG_AUDIO_DSB_WTK_RFFT #define WTK_DLG_AUDIO_DSB_WTK_RFFT #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_larray.h" #include "wtk/core/wtk_str.h" #include "wtk/core/math/wtk_mat.h" #include "wtk/core/math/wtk_math.h" #include "wtk/core/wtk_complex.h" #include "wtk/core/wtk_kcls.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_rfft wtk_rfft_t; #define TRIGO_BD_LIMIT 12 typedef struct { float pos_cos;// Current phase expressed with sin and cos. [-1 ; 1] float pos_sin;// - float step_cos;// Phase increment per step, [-1 ; 1] float step_sin;// - }wtk_oscsincos_t; struct wtk_rfft { int win; int len; int nbr_bits; int *br_lut; float *trigo_lut; float *buffer; wtk_oscsincos_t *trigo_osc; }; int wtk_rfft_next_pow (long x); /** * len=length(data)/2; */ wtk_rfft_t* wtk_rfft_new(int len); void wtk_rfft_delete(wtk_rfft_t *rf); void wtk_rfft_process_fft(wtk_rfft_t *rf,float *f,float *x); void wtk_rfft_process_ifft(wtk_rfft_t *rf,float *f,float *x); /** * fft2 在 fft1 中的位置与偏移; */ //fft,ref_fft void wtk_xcorr_freq_mult(float *fft1,float *fft2,float *xy,int fft_size); //vs values float array //ps values int array void wtk_xcorr_find_nbest_values(wtk_larray_t *vs,wtk_larray_t *ps,float *xcorr_value,int nx,int margin,int *delays,float *values,int nbest); void wtk_rfft_nbest_xcorr_int(int *mic,int mic_len,int *sp,int sp_len,int margin,int *delays,int nbest); void wtk_rfft_nbest_xcorr_float(float *mic,int mic_len,float *sp,int sp_len,int margin,int *delays,int nbest); void wtk_rfft_nbest_xcorr(char *mic,int mic_len,char *sp,int sp_len,int margin,int *delays,int nbest); void wtk_rfft_nbest_xcorr2(char *mic,int mic_len,char *sp,int sp_len,int *delays,int nbest); void wtk_rfft_nbest_xcorr3(int channel,char **mic,int mic_len,char *sp,int sp_len,int *delays); void wtk_rfft_nbest_xcorr4(int channel,char **mic,int mic_len,char *sp,int sp_len,int nbest,int *nbest_delays); void wtk_rfft_nbest_xcorr_mult_channel(int channel,char **mic,int mic_len,char *sp,int sp_len,int *delays); int wtk_rfft_xcorr(char *mic,int mic_len,char *sp,int sp_len); int wtk_rfft_xcorr2(char *mic,int mic_len,char *sp,int sp_len); float wtk_rfft_xcorr3(char *mic,int mic_len,char *sp,int sp_len,int margin,float *max_v); void wtk_rfft_print_fft(float *f,int n); wtk_complex_t wtk_rfft_get_value(float *f,int n,int idx); void wtk_rfft_set_value(float *f,int n,int idx,wtk_complex_t c); void wtk_rfft_set_value2(float *f,int n,int idx,float a,float b); int wtk_int_max(int *delay,int n); int wtk_int_min(int *delay,int n); //do the multiplication: (a+jb)(c+jd) = (ac-bd)+j(bc+ad); void wtk_rfft_mult(float *fft1,float *fft2,float *xy,int win); //do the multiplication: (a+jb)'(c+jd) =(a-jb)(c+jd)=(ac+bd)+j(ad-bc); void wtk_rfft_mult2(float *fft1,float *fft2,float *xy,int win); //do the multiplication: (a+jb).conj(c+jd) =(a+jb)(c-jd)=(ac+bd)+j(-ad+bc); void wtk_rfft_mult3(register float *fft1,register float *fft2,float *xy,int win); #ifdef __cplusplus }; #endif #endif <file_sep>/os/ps/wtk_psys.c #include <sys/types.h> #include <sys/wait.h> #include "wtk_psys.h" #include "wtk/core/wtk_os.h" #include <sys/prctl.h> int wtk_psys_init(wtk_psys_t *s,char *cmd) { int ret; s->parent_write_fd[0]=-1; s->parent_write_fd[1]=-1; s->parent_read_fd[0]=-1; s->parent_read_fd[1]=-1; ret=pipe(s->parent_read_fd); if(ret!=0){goto end;} ret=pipe(s->parent_write_fd); if(ret!=0){goto end;} s->pid=fork(); if(s->pid<0){ret=-1;goto end;} if(s->pid==0) { //child; //wtk_debug("pid=%d:%d\n",getppid(),getpid()); // prctl(PR_SET_PDEATHSIG,SIGUSR1); close(s->parent_write_fd[1]); close(s->parent_read_fd[0]); dup2(s->parent_write_fd[0],0); dup2(s->parent_read_fd[1],1); //wtk_debug("run exit %s ...\n",cmd); // ret=system(cmd); //perror(__FUNCTION__); ret=execl(cmd,cmd,NULL); if(ret==-1) { close(s->parent_write_fd[0]); close(s->parent_read_fd[1]); close(0); close(1); exit(1); } close(s->parent_write_fd[0]); close(s->parent_read_fd[1]); close(0); close(1); //wait for parent to kill to make valgrind happy. while(1) { wtk_msleep(100000); //getchar(); } exit(0); }else { //parent; close(s->parent_write_fd[0]); s->parent_write_fd[0]=-1; close(s->parent_read_fd[1]); s->parent_read_fd[1]=-1; } end: return ret; } void wtk_psys_clean(wtk_psys_t *s) { //wtk_debug("pid=%d:%d:%d\n",getppid(),getpid(),s->pid); if(s->parent_write_fd[0]>0) { close(s->parent_write_fd[0]); } if(s->parent_write_fd[1]>0) { close(s->parent_write_fd[1]); } if(s->parent_read_fd[0]>0) { close(s->parent_read_fd[0]); } if(s->parent_read_fd[1]>0) { close(s->parent_read_fd[1]); } if(s->pid>0) { //wtk_debug("kill ...\n"); if(kill(s->pid,0)==0) { kill(s->pid,SIGKILL); } waitpid(s->pid,0,0); //wtk_debug("kill ... end\n"); } } int wtk_psys_write(wtk_psys_t *sys,char *data,int bytes) { //print_data(data,bytes); return write(sys->parent_write_fd[1],data,bytes); } int wtk_psys_read(wtk_psys_t *sys,char *data,int bytes) { return read(sys->parent_read_fd[0],data,bytes); } <file_sep>/os/wtk_shm.c #include "wtk_shm.h" wtk_shm_t* wtk_shm_new(int bytes) { wtk_shm_t *s=0; int id; id=shmget(IPC_PRIVATE,bytes,IPC_CREAT|0600); if(id==-1){goto end;} s=(wtk_shm_t*)wtk_malloc(sizeof(*s)); s->id=id; s->addr=(char*)shmat(id,0,0); if(s->addr==(void*)-1) { s->addr=0; wtk_shm_delete(s); s=0; } end: return s; } void wtk_shm_delete(wtk_shm_t *s) { if(s->addr) { shmdt(s->addr); } shmctl(s->id,IPC_RMID,0); wtk_free(s); } <file_sep>/core/segmenter/wtk_poseg.h #ifndef WTK_CORE_SEGMENTER_WTK_POSEG #define WTK_CORE_SEGMENTER_WTK_POSEG #include "wtk/core/wtk_type.h" #include "wtk_poseg_cfg.h" #include "wtk_chnpos.h" #include "wtk/core/wtk_fkv2.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_poseg wtk_poseg_t; struct wtk_poseg { wtk_poseg_cfg_t *cfg; wtk_chnpos_t *chnpos; wtk_heap_t *heap; wtk_array_t *input; wtk_string_t **wrds; wtk_string_t **pos; int nwrd; }; wtk_poseg_t* wtk_poseg_new(wtk_poseg_cfg_t *cfg); void wtk_poseg_delete(wtk_poseg_t *seg); void wtk_poseg_reset(wtk_poseg_t *seg); void wtk_poseg_process(wtk_poseg_t *seg,char *data,int bytes); void wtk_poseg_print_output(wtk_poseg_t *seg); #ifdef __cplusplus }; #endif #endif <file_sep>/os/wtk_thread_pool.c #include "wtk_thread_pool.h" wtk_thread_pool_t *wtk_thread_pool_new(int threads,wtk_blockqueue_t *queue, thread_pool_handler handler,void *user_data) { return wtk_thread_pool_new2(threads,queue,NULL,NULL,handler,user_data); } wtk_thread_pool_t *wtk_thread_pool_new2(int threads,wtk_blockqueue_t *queue,wtk_thread_pool_init_f init, wtk_thread_pool_clean_f clean,thread_pool_handler handler,void *user_data) { wtk_thread_pool_t *t; t=(wtk_thread_pool_t*)wtk_malloc(sizeof(*t)); t->thread_num=threads; t->threads=(wtk_thread_t*)wtk_calloc(threads,sizeof(wtk_thread_t)); t->queue=queue; t->handler=handler; t->init=init; t->clean=clean; t->user_data=user_data; t->timeout=-1; t->timeout_f=0; return t; } int wtk_thread_pool_bytes(wtk_thread_pool_t *t) { return sizeof(*t)+sizeof(wtk_thread_t)*t->thread_num; } int wtk_thread_pool_delete(wtk_thread_pool_t *p) { int i; for(i=0;i<p->thread_num;++i) { //wtk_thread_join(&p->threads[i]); wtk_thread_clean((&p->threads[i])); } wtk_free(p->threads); wtk_free(p); return 0; } void wtk_thread_pool_set_timeout(wtk_thread_pool_t *p,wtk_thread_pool_timeout_f timeout_f,int timeout) { p->timeout_f=timeout_f; p->timeout=timeout; } int wtk_thread_pool_run(wtk_thread_pool_t *p,wtk_thread_t *t) { wtk_blockqueue_t* q; wtk_queue_node_t *n; thread_pool_handler handler; void *user_data; int ret; int is_timeout; q=(p->queue); handler=p->handler; user_data=p->user_data; //wtk_debug("thread[%d] is on.\n",t->ppid); if(p->init) { p->init(p->user_data,t); } while(p->run) { n=wtk_blockqueue_pop(q,p->timeout,&is_timeout); //wtk_debug("pid: %d,tid=%d\n",getpid(),t->ppid); if(!n) { if(is_timeout) { if(p->timeout_f) { p->timeout_f(p->user_data,t); } continue; } break; } ret=handler(user_data,n,t); if(ret!=0){break;} } #ifndef WIN32 //wtk_debug("thread %d run=%d goto exit.\n",t->ppid,p->run); #endif if(p->clean) { p->clean(p->user_data,t); } return 0; } int wtk_thread_pool_start(wtk_thread_pool_t *p) { wtk_thread_t *t; int i,ret; p->run=1;ret=0; for(i=0;i<p->thread_num;++i) { t=&(p->threads[i]); ret=wtk_thread_init(t,(thread_route_handler)wtk_thread_pool_run,p); if(ret!=0) { perror(__FUNCTION__); wtk_debug("create thread pool failed.\n"); break; } ret=wtk_thread_start(t); if(ret!=0) { perror(__FUNCTION__); wtk_debug("create thread pool failed.\n"); break; } } return ret; } int wtk_thread_pool_join(wtk_thread_pool_t *p) { wtk_thread_t *t; int i,ret; ret=0; for(i=0;i<p->thread_num;++i) { t=&(p->threads[i]); ret=wtk_thread_join(t); } return ret; } int wtk_thread_pool_stop(wtk_thread_pool_t *p) { int i; p->run=0; for(i=0;i<p->thread_num;++i) { wtk_blockqueue_wake((p->queue)); } for(i=0;i<p->thread_num;++i) { wtk_thread_join(&(p->threads[i])); } return 0; } int wtk_thread_pool_kill(wtk_thread_pool_t *p) { int i; p->run=0; for(i=0;i<p->thread_num;++i) { wtk_thread_kill(&(p->threads[i])); } return 0; } <file_sep>/core/.svn/pristine/fb/fb15693d74baf2c8b4b83c334bf22830f4f9df3e.svn-base #ifndef WTK_EVAL_ERRNO_WTK_EOS_H_ #define WTK_EVAL_ERRNO_WTK_EOS_H_ #include "wtk_errno.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_eos wtk_eos_t; //#define wtk_eos_set_err(e,no,...) wtk_errno_set((e)->err,no,__VA_ARGS__) struct wtk_eos { wtk_errno_t *err; }; wtk_eos_t* wtk_eos_new(); int wtk_eos_delete(wtk_eos_t *o); int wtk_eos_reset(wtk_eos_t *o); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_time.h #ifndef WTK_CORE_WTK_TIME_H_ #define WTK_CORE_WTK_TIME_H_ #include <time.h> #include "wtk/core/wtk_type.h" #ifdef __cplusplus extern "C" { #endif int wtk_time_is_leap_year(int y); /** * m=[1,12] */ int wtk_time_month_max_day(int m,int y); #ifdef __cplusplus }; #endif #endif <file_sep>/core/.svn/pristine/02/02d7b99751aa9ac75fe33012ad9961e7c39166e4.svn-base #include "wtk_phndict.h" #include "wtk/core/wtk_larray.h" #include <ctype.h> void wtk_phndict_add_wrd(wtk_phndict_t *dict,wtk_phndict_wrd_t *wrd) { //wtk_debug("[%.*s]\n",wrd->wrd->len,wrd->wrd->data); wtk_str_hash_add(dict->hash,wrd->wrd->data,wrd->wrd->len,wrd); } int wtk_phndict_load(wtk_phndict_t *dict,wtk_source_t *src) { wtk_strpool_xitem_t *xi; wtk_str_spwrd_iter_t iter; wtk_string_t v; wtk_strbuf_t *buf; int ret; wtk_larray_t *a; wtk_phndict_wrd_t *wrd; wtk_heap_t *heap=dict->hash->heap; int n; int idx; int xnew; idx=0; a=wtk_larray_new(10,sizeof(wtk_strpool_xitem_t*)); buf=wtk_strbuf_new(256,1); while(1) { ret=wtk_source_read_line(src,buf); if(ret!=0 || buf->pos==0){ret=0;goto end;} //wtk_debug("[%.*s]\n",buf->pos,buf->data); wrd=NULL; wtk_larray_reset(a); wtk_str_spwrd_iter_init(&iter,buf->data,buf->pos); while(1) { v=wtk_str_spwrd_iter_next(&(iter)); if(v.len==0){break;} //wtk_debug("[%.*s]\n",v.len,v.data); if(wrd) { xnew=0; if(isdigit(v.data[v.len-1])) { xi=(wtk_strpool_xitem_t*)wtk_strpool_find_item2(dict->pool,v.data,v.len-1,1,&xnew); if(xnew) { xi->hook.i=idx; ++idx; //wtk_debug("idx=%d\n",idx); } wtk_larray_push2(a,&xi); xi=(wtk_strpool_xitem_t*)wtk_strpool_find_item2(dict->pool,v.data+v.len-1,1,1,&xnew); if(xnew) { xi->hook.i=idx; ++idx; //wtk_debug("idx=%d\n",idx); } wtk_larray_push2(a,&xi); }else { xi=(wtk_strpool_xitem_t*)wtk_strpool_find_item2(dict->pool,v.data,v.len,1,&xnew); if(xnew) { xi->hook.i=idx; ++idx; //wtk_debug("idx=%d\n",idx); } wtk_larray_push2(a,&xi); } }else { wrd=(wtk_phndict_wrd_t*)wtk_heap_malloc(heap,sizeof(wtk_phndict_wrd_t)); wrd->wrd=wtk_heap_dup_string(heap,v.data,v.len); wrd->nphn=0; wrd->phns=NULL; } } //wtk_debug("n=%d\n",a->nslot); wrd->nphn=a->nslot; n=sizeof(wtk_strpool_xitem_t*)*a->nslot; wrd->phns=(wtk_strpool_xitem_t**)wtk_heap_malloc(heap,n); memcpy(wrd->phns,a->slot,n); wtk_phndict_add_wrd(dict,wrd); //exit(0); } ret=0; end: wtk_debug("idx=%d\n",idx); //exit(0); dict->nphn=idx; wtk_larray_delete(a); wtk_strbuf_delete(buf); return ret; } wtk_phndict_t* wtk_phndict_new(char *fn) { wtk_phndict_t *phn; unsigned long long lines; phn=(wtk_phndict_t*)wtk_malloc(sizeof(wtk_phndict_t)); phn->pool=wtk_strpool_new(101); lines=wtk_file_lines(fn); lines=lines*2+1; phn->hash=wtk_str_hash_new(lines); wtk_source_load_file(phn,(wtk_source_load_handler_t)wtk_phndict_load,fn); return phn; } void wtk_phndict_delete(wtk_phndict_t *phn) { if(phn->hash) { wtk_str_hash_delete(phn->hash); } wtk_strpool_delete(phn->pool); wtk_free(phn); } wtk_phndict_wrd_t* wtk_phndict_find(wtk_phndict_t *dict,char *wrd,int bytes) { return (wtk_phndict_wrd_t*)wtk_str_hash_find(dict->hash,wrd,bytes); } void wtk_phndict_wrd_print(wtk_phndict_wrd_t *wrd) { int i; wtk_debug("================ word =================\n"); printf("WORD: %.*s\n",wrd->wrd->len,wrd->wrd->data); for(i=0;i<wrd->nphn;++i) { printf("v[%d]=%.*s\n",i,wrd->phns[i]->v.len,wrd->phns[i]->v.data); } } <file_sep>/core/cfg/wtk_cfg_file.c #include "wtk_cfg_file.h" #include "wtk/core/wtk_os.h" #include <ctype.h> int wtk_cfg_file_feed_expr_value_tok_end(wtk_cfg_file_t *cfg,char c); int wtk_cfg_file_feed_expr_value_start(wtk_cfg_file_t *cfg,char c); int wtk_cfg_file_feed_expr_value_tok_start(wtk_cfg_file_t *cfg,char c); int wtk_cfg_file_feed_expr_tok_start(wtk_cfg_file_t* cfg,char c); int wtk_cfg_file_feed_expr_start(wtk_cfg_file_t* cfg,char c); int wtk_cfg_file_feed_string(wtk_cfg_file_t *c,char *d,int bytes); wtk_cfg_if_item_t* wtk_cfg_file_get_last_if_item(wtk_cfg_file_t *cfg); wtk_cfg_if_cond_t* wtk_cfg_file_get_last_if_cond(wtk_cfg_file_t *cfg); wtk_cfg_if_cond_t* wtk_cfg_file_pop_item_cond(wtk_cfg_file_t *cfg); void wtk_cfg_file_pop_condition(wtk_cfg_file_t *cfg); int wtk_cfg_file_init(wtk_cfg_file_t *f) { f->main=wtk_local_cfg_new_h(f->heap); f->cur=f->main; wtk_string_set_s(&(f->main->name),"main"); wtk_queue_push(&(f->cfg_queue),&(f->main->q_n)); f->scope=0; f->included=0; f->escaped=0; return 0; } wtk_cfg_file_t* wtk_cfg_file_new_fn(char *fn) { return wtk_cfg_file_new_fn2(fn,1); } wtk_cfg_file_t* wtk_cfg_file_new_fn2(char *fn,int add_pwd) { wtk_cfg_file_t *cfg=0; char *data=0; int len,ret; wtk_string_t *v=0; ret=0; data=file_read_buf(fn,&len); if(!data){goto end;} cfg=wtk_cfg_file_new(); if(add_pwd) { v=wtk_dir_name(fn,'/'); if(v->len>0) { wtk_cfg_file_add_var_ks(cfg,"pwd",v->data,v->len); }else { wtk_cfg_file_add_var_s_s(cfg,"pwd","."); } } ret=wtk_cfg_file_feed(cfg,data,len); if(v) { wtk_string_delete(v); } end: if(data){free(data);} if(ret!=0) { wtk_cfg_file_delete(cfg); cfg=0; } return cfg; } wtk_cfg_file_t* wtk_cfg_file_new_fn3(wtk_string_t *dir,char *data,int len,int add_pwd) { wtk_cfg_file_t *cfg=0; int ret; // wtk_string_t *v=0; ret=0; if(!data){goto end;} cfg=wtk_cfg_file_new(); if(add_pwd) { wtk_cfg_file_add_var_ks(cfg,"pwd",dir->data,dir->len); } ret=wtk_cfg_file_feed(cfg,data,len); end: if(ret!=0) { wtk_cfg_file_delete(cfg); cfg=0; } return cfg; } wtk_cfg_file_t *wtk_cfg_file_new() { return wtk_cfg_file_new_ex(2048,4096); } wtk_cfg_file_t *wtk_cfg_file_new_ex(int buf_size,int heap_size) { wtk_cfg_file_t *f; f=(wtk_cfg_file_t*)wtk_malloc(sizeof(*f)); wtk_queue_init(&(f->cfg_queue)); f->heap=wtk_heap_new(heap_size); f->tok=wtk_strbuf_new(buf_size,1); f->value=wtk_strbuf_new(buf_size,1); f->var=wtk_strbuf_new(buf_size,1); //f->comment=wtk_strbuf_new(buf_size,1); f->quoted=0; f->included=0; f->rbin=NULL; wtk_queue_init(&(f->if_q)); wtk_cfg_file_init(f); return f; } int wtk_cfg_file_bytes2(wtk_cfg_file_t *cfg) { return sizeof(*cfg)+wtk_strbuf_bytes(cfg->tok)+wtk_strbuf_bytes(cfg->value)+wtk_strbuf_bytes(cfg->var)+wtk_heap_bytes(cfg->heap); } int wtk_cfg_file_bytes(wtk_cfg_file_t *c) { int bytes; bytes=sizeof(wtk_cfg_file_t); bytes+=wtk_heap_bytes(c->heap); bytes+=wtk_strbuf_bytes(c->tok); bytes+=wtk_strbuf_bytes(c->value); bytes+=wtk_strbuf_bytes(c->var); return bytes; } int wtk_cfg_file_reset(wtk_cfg_file_t *cfg) { wtk_queue_init(&(cfg->cfg_queue)); wtk_heap_reset(cfg->heap); cfg->quoted=0; cfg->included=0; return wtk_cfg_file_init(cfg); } int wtk_cfg_file_delete(wtk_cfg_file_t *c) { wtk_heap_delete(c->heap); wtk_strbuf_delete(c->tok); wtk_strbuf_delete(c->value); wtk_strbuf_delete(c->var); //wtk_strbuf_delete(c->comment); wtk_free(c); return 0; } void wtk_cfg_file_set_rbin(wtk_cfg_file_t *cfile,wtk_rbin2_t *rbin) { cfile->rbin=rbin; } int wtk_cfg_file_add_var(wtk_cfg_file_t *cfg,char *k,int kbytes,char *v,int vbytes) { wtk_cfg_queue_add_string(cfg->main->cfg,k,kbytes,v,vbytes); return 0; } /* space=[ \r\t\n] digit=[0-9] alpha=[a-zA-Z] char=digit|alpha tok= char+ var=${tok} expr= tok space*=space* value space*; value= tok | {space* expr* space*} */ #define is_value(c) (isalnum((c))||(c==':')||c=='/'||c=='\\'||c=='_'||c=='-'||c=='.') #define is_char(c) (isalnum((c))||(c==':')||c=='_'||c=='.'||c=='-'||c=='/'||c=='@') int wtk_cfg_file_process_include(wtk_cfg_file_t *cfg) { int ret=-1; char *data; wtk_string_t *v; wtk_cfg_item_t *pth,*item; int n; wtk_cfg_queue_t *cq; wtk_rbin2_item_t *ritem=NULL; wtk_cfg_if_item_t* fi; fi=wtk_cfg_file_get_last_if_item(cfg); if(fi && fi->valid==0) { //wtk_debug("[%.*s]\n",cfg->value->pos,cfg->value->data); cfg->state=CF_EXPR_START; return 0; } wtk_strbuf_push_c(cfg->value,0); cfg->included=0; if(cfg->rbin) { ritem=wtk_rbin2_get3(cfg->rbin,cfg->value->data,strlen(cfg->value->data),0); if(ritem) { data=ritem->data->data; n=ritem->data->len; }else { data=NULL; } }else { data=file_read_buf(cfg->value->data,&n); } if(!data) { wtk_debug("%s not found.\n",cfg->value->data); goto end; } cfg->state=CF_EXPR_START; cq=cfg->cur->cfg; pth=wtk_cfg_queue_find_s(cq,"pwd"); if(pth) { wtk_cfg_queue_remove(cq,pth); } v=wtk_dir_name(cfg->value->data,'/'); if(!v){goto end;} wtk_cfg_queue_add_string(cq,"pwd",3,v->data,v->len); wtk_string_delete(v); ret=wtk_cfg_file_feed_string(cfg,data,n); if(cfg->rbin) { if(ritem) { wtk_rbin2_item_clean(ritem); } }else { wtk_free(data); } if(ret!=0){goto end;} item=wtk_cfg_queue_find_s(cq,"pwd"); if(item) { wtk_cfg_queue_remove(cq,item); } if(pth) { wtk_cfg_queue_add(cq,pth); } cfg->state=CF_EXPR_START; end: return ret; } int wtk_cfg_file_feed_expr_value_tok_end(wtk_cfg_file_t *cfg,char c) { int ret=0; if(c==';') { //wtk_strbuf_push_c(cfg->value,0); if(cfg->included) { ret=wtk_cfg_file_process_include(cfg); }else { wtk_cfg_if_item_t* item; item=wtk_cfg_file_get_last_if_item(cfg); //wtk_debug("[%.*s]=[%.*s] item=%p/%d\n",cfg->tok->pos,cfg->tok->data,cfg->value->pos,cfg->value->data,item,item?item->valid:0); if(!item || item->valid) { //wtk_debug("[%.*s]=[%.*s]\n",cfg->tok->pos,cfg->tok->data,cfg->value->pos,cfg->value->data); wtk_cfg_queue_add_string(cfg->cur->cfg,cfg->tok->data,cfg->tok->pos,cfg->value->data,cfg->value->pos); } cfg->state=CF_EXPR_START; } }else if(!isspace(c)) { wtk_debug("expect \";\"\n"); ret=-1; } return ret; } void wtk_cfg_file_set_state(wtk_cfg_file_t *cfg,wtk_cfg_file_state_t state) { cfg->state=state; cfg->quoted=0; cfg->escaped=0; cfg->sub_state=-1; } int wtk_cfg_file_feed_array_tok_end(wtk_cfg_file_t *cfg,char c) { int ret=0; //wtk_debug("[%c]\n",c); if(c==',') { wtk_cfg_file_set_state(cfg,CFG_ARRAY_START); }else if (c==']') { wtk_cfg_file_set_state(cfg,CF_EXPR_START); }else if(!isspace(c)) { wtk_debug("expect array tok like \",\" or \"]\",buf found[%c]\n",c); ret=-1; } return ret; } int wtk_cfg_file_feed_array_tok_start(wtk_cfg_file_t *cfg,char c) { wtk_string_t *s; int ret=0; //wtk_debug("c=[%c]\n",c); if(cfg->escaped) { wtk_strbuf_push_c(cfg->value,c); cfg->escaped=0; return 0; } if(cfg->quoted) { if(c==cfg->quoted_char) { s=wtk_heap_dup_string(cfg->heap,cfg->value->data,cfg->value->pos+1); --s->len; s->data[s->len]=0; ((wtk_string_t**)wtk_array_push(cfg->array))[0]=s; //wtk_debug("[%.*s]\n",s->len,s->data); //cfg->state=CFG_ARRAY_TOK_END; wtk_cfg_file_set_state(cfg,CFG_ARRAY_TOK_END); }else { if(c=='\\') { cfg->escaped=1; }else { wtk_strbuf_push_c(cfg->value,c); } } }else { if(isspace(c)||c==','||c==']') { if(cfg->value->pos>0) { s=wtk_heap_dup_string(cfg->heap,cfg->value->data,cfg->value->pos+1); --s->len; s->data[s->len]=0; ((wtk_string_t**)wtk_array_push(cfg->array))[0]=s; } //cfg->state=CFG_ARRAY_TOK_END; wtk_cfg_file_set_state(cfg,CFG_ARRAY_TOK_END); if(!isspace(c)) { ret=wtk_cfg_file_feed_array_tok_end(cfg,c); } }else if(c=='$') { cfg->var_cache_state=CFG_ARRAY_TOK_START; //cfg->state=CF_VAR_START; wtk_cfg_file_set_state(cfg,CF_VAR_START); }else { if(cfg->value->pos==0 && (c=='\'' || c=='"')) { cfg->quoted=1; cfg->quoted_char=c; }else { wtk_strbuf_push_c(cfg->value,c); } } } return ret; } int wtk_cfg_file_feed_array_start(wtk_cfg_file_t *cfg,char c) { int ret; if(!isspace(c)) { //cfg->state=CFG_ARRAY_TOK_START; wtk_strbuf_reset(cfg->value); //cfg->quoted=0; wtk_cfg_file_set_state(cfg,CFG_ARRAY_TOK_START); ret=wtk_cfg_file_feed_array_tok_start(cfg,c); }else { ret=0; } return ret; } int wtk_cfg_file_feed_expr_value_start(wtk_cfg_file_t *cfg,char c) { wtk_heap_t *h=cfg->heap; wtk_local_cfg_t *lc; int ret=0; if(c=='{') { wtk_cfg_item_t* item; item=wtk_cfg_queue_find(cfg->cur->cfg,cfg->tok->data,cfg->tok->pos); if(item && item->type==WTK_CFG_LC) { lc=item->value.cfg; }else { lc=wtk_local_cfg_new_h(h); wtk_cfg_queue_add_lc(cfg->cur->cfg,cfg->tok->data,cfg->tok->pos,lc); wtk_queue_push(&(cfg->cfg_queue),&(lc->q_n)); lc->parent=cfg->cur; } cfg->cur=lc; cfg->state=CF_EXPR_START; ++cfg->scope; ret=wtk_cfg_file_feed_expr_start(cfg,c); }else if(c=='[') { cfg->state=CFG_ARRAY_START; cfg->array=wtk_array_new_h(cfg->heap,5,sizeof(wtk_string_t*)); wtk_cfg_queue_add_array(cfg->cur->cfg,cfg->tok->data,cfg->tok->pos,cfg->array); }else if(is_char(c)||c=='$'||c=='"') { cfg->state=CF_EXPR_VALUE_TOK_START; wtk_strbuf_reset(cfg->value); cfg->quoted=c=='"'; if(cfg->quoted) { cfg->quoted_char=c; }else { ret=wtk_cfg_file_feed_expr_value_tok_start(cfg,c); } }else if(!isspace(c)) { wtk_debug("expect expr value start %c.\n",c); ret=-1; } return ret; } int wtk_cfg_file_feed_var_tok_start(wtk_cfg_file_t *cfg,char c) { int ret=0; wtk_string_t *n; if(is_char(c)) { wtk_strbuf_push_c(cfg->var,c); }else if(c=='}') { n=wtk_local_cfg_find_string(cfg->cur,cfg->var->data,cfg->var->pos); if(n) { wtk_strbuf_push(cfg->value,n->data,n->len); cfg->state=cfg->var_cache_state; //cfg->state=CF_EXPR_VALUE_TOK_START; }else { wtk_debug("var %*.*s not found.\n",cfg->var->pos,cfg->var->pos,cfg->var->data); ret=-1; } }else if(!isspace(c)) { wtk_debug("expect expr tok start.\n"); ret=-1; } return ret; } int wtk_cfg_file_feed_var_tok(wtk_cfg_file_t *cfg,char c) { int ret; if(!isspace(c)) { cfg->state=CF_VAR_TOK_START; wtk_strbuf_reset(cfg->var); ret=wtk_cfg_file_feed_var_tok_start(cfg,c); }else { ret=0; } return ret; } int wtk_cfg_file_feed_var_start(wtk_cfg_file_t *cfg,char c) { int ret; if(c=='{') { cfg->state=CF_VAR_TOK; ret=0; }else { wtk_debug("expect var { start.\n"); ret=-1; } return ret; } int wtk_cfg_file_feed_escape_x2(wtk_cfg_file_t *cfg,char c) { int ret; int v; v=wtk_char_to_hex(c); if(v==-1) { ret=-1; }else { cfg->escape_char=(cfg->escape_char<<4)+v; wtk_strbuf_push_c(cfg->value,cfg->escape_char); cfg->state=CF_EXPR_VALUE_TOK_START; ret=0; } return ret; } int wtk_cfg_file_feed_escape_x1(wtk_cfg_file_t *cfg,char c) { int ret; int v; v=wtk_char_to_hex(c); if(v==-1) { ret=-1; }else { cfg->escape_char=v; cfg->state=CFG_ESCAPE_X2; ret=0; } return ret; } int wtk_cfg_file_feed_escape_o2(wtk_cfg_file_t *cfg,char c) { int ret; if(c>='0' && c<='7') { cfg->escape_char=(cfg->escape_char<<3)+c-'0'; wtk_strbuf_push_c(cfg->value,cfg->escape_char); cfg->state=CF_EXPR_VALUE_TOK_START; ret=0; }else { ret=-1; } return ret; } int wtk_cfg_file_feed_escape_o1(wtk_cfg_file_t *cfg,char c) { int ret; if(c>='0' && c<='7') { cfg->escape_char=(cfg->escape_char<<3)+c-'0'; cfg->state=CFG_ESCAPE_O2; ret=0; }else { ret=-1; } return ret; } int wtk_cfg_file_feed_escape_start(wtk_cfg_file_t *cfg,char c) { if(c=='x'||c=='X') { cfg->escape_char=0; cfg->state=CFG_ESCAPE_X1; }else if(c>='0' && c<='7') { cfg->escape_char=c-'0'; cfg->state=CFG_ESCAPE_O1; }else { switch(c) { case 't': wtk_strbuf_push_c(cfg->value,'\t'); break; case 'n': wtk_strbuf_push_c(cfg->value,'\n'); break; case 'r': wtk_strbuf_push_c(cfg->value,'\r'); break; case '\'': wtk_strbuf_push_c(cfg->value,'\''); break; case '\"': wtk_strbuf_push_c(cfg->value,'\"'); break; case '\\': wtk_strbuf_push_c(cfg->value,'\\'); break; default: wtk_strbuf_push_c(cfg->value,c); break; } cfg->state=CF_EXPR_VALUE_TOK_START; } return 0; } int wtk_cfg_file_feed_expr_value_tok_start(wtk_cfg_file_t *cfg,char c) { int ret=0; if(c=='\\') { cfg->state=CFG_ESCAPE_START; return 0; } if(cfg->quoted) { if(c==cfg->quoted_char) { cfg->quoted=0; cfg->state=CF_EXPR_VALUE_TOK_END; }else { wtk_strbuf_push_c(cfg->value,c); } return 0; } if(is_value(c)) { wtk_strbuf_push_c(cfg->value,c); }else if(c==';') { cfg->state=CF_EXPR_VALUE_TOK_END; ret=wtk_cfg_file_feed_expr_value_tok_end(cfg,c); }else if(c=='$') { cfg->var_cache_state=CF_EXPR_VALUE_TOK_START; cfg->state=CF_VAR_START; }else { wtk_debug("expect var value %c end.\n",c); ret=-1; } return ret; } void wtk_cfg_file_push_condition(wtk_cfg_file_t *cfg) { wtk_heap_t *heap=cfg->heap; wtk_cfg_if_item_t *item; item=(wtk_cfg_if_item_t*)wtk_heap_malloc(heap,sizeof(wtk_cfg_if_item_t)); item->_or=0; item->valid=1; wtk_queue_init(&(item->cond)); wtk_queue_push(&(cfg->if_q),&(item->q_n)); } void wtk_cfg_file_pop_condition(wtk_cfg_file_t *cfg) { wtk_queue_pop(&(cfg->if_q)); } wtk_cfg_if_item_t* wtk_cfg_file_get_last_if_item(wtk_cfg_file_t *cfg) { if(cfg->if_q.length>0) { return (wtk_cfg_if_item_t*)data_offset2(cfg->if_q.push,wtk_cfg_if_item_t,q_n); }else { return NULL; } } wtk_cfg_if_cond_t* wtk_cfg_file_get_last_if_cond(wtk_cfg_file_t *cfg) { wtk_cfg_if_item_t *item; item=wtk_cfg_file_get_last_if_item(cfg); return (wtk_cfg_if_cond_t*)data_offset2(item->cond.push,wtk_cfg_if_cond_t,q_n); } wtk_cfg_if_cond_t* wtk_cfg_file_pop_item_cond(wtk_cfg_file_t *cfg) { wtk_heap_t *heap=cfg->heap; wtk_cfg_if_cond_t *cond; wtk_cfg_if_item_t *item; item=data_offset2(cfg->if_q.push,wtk_cfg_if_item_t,q_n); cond=(wtk_cfg_if_cond_t*)wtk_heap_malloc(heap,sizeof(wtk_cfg_if_cond_t)); cond->k=NULL; cond->v=NULL; wtk_queue_push(&(item->cond),&(cond->q_n)); return cond; } #include "wtk/core/wtk_str_parser.h" wtk_string_t* wtk_cfg_file_get_var(wtk_cfg_file_t *cfg,char *k,int k_len) { wtk_cfg_item_t *item; item=wtk_cfg_queue_find(cfg->cur->cfg,k,k_len); if(item && item->type==WTK_CFG_STRING) { return item->value.str; }else { return NULL; } } char* wtk_cfg_file_str_expand(wtk_cfg_file_t *cfg,char *s,int len) { wtk_string_parser2_t *p; p=wtk_string_parser2_new(); wtk_string_parser2_set(p,cfg,(wtk_string_parser2_get_var_f)wtk_cfg_file_get_var); wtk_string_parser2_process(p,s,len); //wtk_debug("[%.*s]\n",p->buf->pos,p->buf->data); //exit(0); if(p->buf->pos>0) { s=wtk_data_to_str(p->buf->data,p->buf->pos); }else { s=NULL; } wtk_string_parser2_delete(p); return s; } void wtk_cfg_file_update_last_if(wtk_cfg_file_t *cfg) { wtk_cfg_if_item_t *item; wtk_cfg_if_cond_t *cond; wtk_queue_node_t *qn; wtk_cfg_item_t *ci; char *s; int ret; item=wtk_cfg_file_get_last_if_item(cfg); if(item->_or) { item->valid=0; for(qn=item->cond.pop;qn;qn=qn->next) { cond=data_offset2(qn,wtk_cfg_if_cond_t,q_n); //wtk_debug("[%.*s]\n",cond->k->len,cond->k->data); ci=wtk_local_cfg_find(cfg->cur,cond->k->data,cond->k->len); //wtk_debug("ci=%p\n",ci); if(ci) { if(!cond->v) { item->valid=1; goto end; }else if(ci->type==WTK_CFG_STRING && wtk_string_cmp(cond->v,ci->value.str->data,ci->value.str->len)==0) { item->valid=1; goto end; } }else if(cond->k->data[0]=='#') { s=wtk_cfg_file_str_expand(cfg,cond->k->data+1,cond->k->len-1); if(s) { ret=wtk_file_exist(s); //wtk_debug("[%s]=%d\n",s,ret); wtk_free(s); }else { ret=-1; } if(ret==0) { item->valid=1; goto end; } //exit(0); } } }else { item->valid=1; for(qn=item->cond.pop;qn;qn=qn->next) { cond=data_offset2(qn,wtk_cfg_if_cond_t,q_n); //wtk_debug("[%.*s]\n",cond->k->len,cond->k->data); ci=wtk_local_cfg_find(cfg->cur,cond->k->data,cond->k->len); //wtk_debug("ci=%p\n",ci); if(!ci) { //wtk_debug("[%.*s]\n",cond->k->len,cond->k->data); if(cond->k->data[0]=='#') { s=wtk_cfg_file_str_expand(cfg,cond->k->data+1,cond->k->len-1); if(s) { ret=wtk_file_exist(s); //wtk_debug("[%s]=%d\n",s,ret); wtk_free(s); }else { ret=-1; } //wtk_debug("[%.*s]=%d\n",cond->k->len,cond->k->data,ret); }else { ret=-1; } if(ret!=0) { item->valid=0; goto end; } }else if(cond->v) { if(ci->type!=WTK_CFG_STRING) { item->valid=0; goto end; }else if(wtk_string_cmp(cond->v,ci->value.str->data,ci->value.str->len)!=0) { item->valid=0; goto end; } } } } end: return; } int wtk_cfg_file_feed_if(wtk_cfg_file_t* cfg,char c) { enum { WTK_CFG_IF_INIT=0, WTK_CFG_IF_KEY, WTK_CFG_IF_VALUE, }; wtk_strbuf_t *buf=cfg->tok; wtk_cfg_if_item_t *item; wtk_cfg_if_cond_t *cond; wtk_heap_t *heap=cfg->heap; if(cfg->sub_state==-1) { cfg->sub_state=WTK_CFG_IF_INIT; } switch(cfg->sub_state) { case WTK_CFG_IF_INIT: if(!isspace(c)) { wtk_strbuf_reset(buf); wtk_strbuf_push_c(buf,c); cfg->sub_state=WTK_CFG_IF_KEY; } break; case WTK_CFG_IF_KEY: if(c=='=') { cond=wtk_cfg_file_pop_item_cond(cfg); //wtk_debug("[%.*s]\n",buf->pos,buf->data); cond->k=wtk_heap_dup_string(heap,buf->data,buf->pos); cfg->sub_state=WTK_CFG_IF_VALUE; wtk_strbuf_reset(buf); }else if(isspace(c)) { //wtk_debug("[%.*s]\n",buf->pos,buf->data); if(wtk_str_equal_s(buf->data,buf->pos,"or")) { item=wtk_cfg_file_get_last_if_item(cfg); item->_or=1; }else if(wtk_str_equal_s(buf->data,buf->pos,"and")) { item=wtk_cfg_file_get_last_if_item(cfg); item->_or=0; }else if(wtk_str_equal_s(buf->data,buf->pos,"then")) { wtk_cfg_file_update_last_if(cfg); wtk_cfg_file_set_state(cfg,CF_EXPR_START); }else { cond=wtk_cfg_file_pop_item_cond(cfg); //wtk_debug("[%.*s]\n",buf->pos,buf->data); cond->k=wtk_heap_dup_string(heap,buf->data,buf->pos); } wtk_strbuf_reset(buf); cfg->sub_state=WTK_CFG_IF_INIT; }else { wtk_strbuf_push_c(buf,c); } break; case WTK_CFG_IF_VALUE: if(isspace(c)) { //wtk_debug("[%.*s]\n",buf->pos,buf->data); if(buf->data[0]=='"' && buf->data[buf->pos-1]=='\"') { wtk_strbuf_pop(buf,NULL,1); buf->pos-=1; } //wtk_debug("[%.*s]\n",buf->pos,buf->data); cond=wtk_cfg_file_get_last_if_cond(cfg); cond->v=wtk_heap_dup_string(heap,buf->data,buf->pos); cfg->sub_state=WTK_CFG_IF_INIT; wtk_strbuf_reset(buf); }else { wtk_strbuf_push_c(buf,c); } break; } return 0; } int wtk_cfg_file_feed_expr_tok_start(wtk_cfg_file_t* cfg,char c) { wtk_cfg_if_item_t *item; int ret=0; if(cfg->quoted) { if(c!=cfg->quoted_char) { wtk_strbuf_push_c(cfg->tok,c); }else { cfg->quoted=0; cfg->state=CF_EXPR_TOK_WAIT_EQ; } }else { if(is_char(c)) { wtk_strbuf_push_c(cfg->tok,c); }else if(c=='=') { cfg->state=CF_EXPR_VALUE_START; //ret=wtk_cfg_file_feed_expr_value_start(cfg,c); }else if(!isspace(c)) { ret=-1; }else if(cfg->tok->pos>0) { if(wtk_str_equal_s(cfg->tok->data,cfg->tok->pos,"if")) { //wtk_debug("[%.*s]\n",cfg->tok->pos,cfg->tok->data); wtk_cfg_file_push_condition(cfg); wtk_strbuf_reset(cfg->tok); //cfg->state=CFG_EXPR_IF; wtk_cfg_file_set_state(cfg,CFG_EXPR_IF); }else if(wtk_str_equal_s(cfg->tok->data,cfg->tok->pos,"else")) { //wtk_debug("[%.*s]\n",cfg->tok->pos,cfg->tok->data); item=wtk_cfg_file_get_last_if_item(cfg); item->valid=!item->valid; wtk_strbuf_reset(cfg->tok); wtk_cfg_file_set_state(cfg,CF_EXPR_START); }else if(wtk_str_equal_s(cfg->tok->data,cfg->tok->pos,"end")) { wtk_cfg_file_pop_condition(cfg); wtk_strbuf_reset(cfg->tok); wtk_cfg_file_set_state(cfg,CF_EXPR_START); } } } return ret; } int wtk_cfg_file_feed_expr_tok_wait_eq(wtk_cfg_file_t* cfg,char c) { if(c=='=') { cfg->state=CF_EXPR_VALUE_START; } return 0; } int wtk_cfg_file_feed_comment(wtk_cfg_file_t *cfg,char c) { int len=sizeof("include")-1; wtk_strbuf_t *buf; if(c=='\n') { //wtk_strbuf_reset(cfg->tok); cfg->state=CF_EXPR_START; }else { buf=cfg->tok; if(buf->pos<len) { wtk_strbuf_push_c(buf,c); if(buf->pos==len) { if(strncmp(buf->data,"include",buf->pos)==0) { cfg->state=CF_EXPR_VALUE_START; cfg->included=1; } } } } return 0; } int wtk_cfg_file_feed_expr_start(wtk_cfg_file_t* cfg,char c) { int ret=0; #ifdef WIN32 if(is_char((unsigned char)c) ||c=='"' ||c=='\'') #else if(is_char(c) ||c=='"' ||c=='\'') #endif { cfg->state=CF_EXPR_TOK_START; wtk_strbuf_reset(cfg->tok); if(c=='"' ||c=='\'') { cfg->quoted=1; cfg->quoted_char=c; }else { ret=wtk_cfg_file_feed_expr_tok_start(cfg,c); } }else if(c=='}') { if(cfg->scope<=0) { ret=-1; }else { --cfg->scope; cfg->cur=cfg->cur->parent; } }else if(c=='#') { cfg->state=CFG_COMMENT; wtk_strbuf_reset(cfg->tok); }else { //wtk_debug("c=%c\n",c); ret=0; } return ret; } int wtk_cfg_file_feed_fn(wtk_cfg_file_t* cfg,char *fn) { char *data=0; int len,ret=-1; data=file_read_buf(fn,&len); if(!data){goto end;} //print_data(data,len); ret=wtk_cfg_file_feed(cfg,data,len); end: if(data){free(data);} return ret; } int wtk_cfg_file_feed_string(wtk_cfg_file_t *c,char *d,int bytes) { char *s=d,*e=d+bytes; int ret=-1; while(s<e) { //printf("%c",*s); //wtk_debug("[%c]:%d\n",*s,c->state); switch(c->state) { case CF_EXPR_START: ret=wtk_cfg_file_feed_expr_start(c,*s); break; case CF_EXPR_TOK_START: ret=wtk_cfg_file_feed_expr_tok_start(c,*s); break; case CF_EXPR_TOK_WAIT_EQ: ret=wtk_cfg_file_feed_expr_tok_wait_eq(c,*s); break; case CF_EXPR_VALUE_START: ret=wtk_cfg_file_feed_expr_value_start(c,*s); break; case CFG_ESCAPE_START: ret=wtk_cfg_file_feed_escape_start(c,*s); break; case CFG_ESCAPE_X1: ret=wtk_cfg_file_feed_escape_x1(c,*s); break; case CFG_ESCAPE_X2: ret=wtk_cfg_file_feed_escape_x2(c,*s); break; case CFG_ESCAPE_O1: ret=wtk_cfg_file_feed_escape_o1(c,*s); break; case CFG_ESCAPE_O2: ret=wtk_cfg_file_feed_escape_o2(c,*s); break; case CF_EXPR_VALUE_TOK_START: ret=wtk_cfg_file_feed_expr_value_tok_start(c,*s); break; case CF_EXPR_VALUE_TOK_END: ret=wtk_cfg_file_feed_expr_value_tok_end(c,*s); break; case CF_VAR_START: ret=wtk_cfg_file_feed_var_start(c,*s); break; case CF_VAR_TOK: ret=wtk_cfg_file_feed_var_tok(c,*s); break; case CF_VAR_TOK_START: ret=wtk_cfg_file_feed_var_tok_start(c,*s); break; case CFG_ARRAY_START: ret=wtk_cfg_file_feed_array_start(c,*s); break; case CFG_ARRAY_TOK_START: ret=wtk_cfg_file_feed_array_tok_start(c,*s); break; case CFG_ARRAY_TOK_END: ret=wtk_cfg_file_feed_array_tok_end(c,*s); break; case CFG_COMMENT: ret=wtk_cfg_file_feed_comment(c,*s); break; case CFG_EXPR_IF: ret=wtk_cfg_file_feed_if(c,*s); break; default: ret=-1; break; } if(ret!=0) { print_data(d,s-d); break; } ++s; } //wtk_cfg_file_print(c); return ret; } int wtk_cfg_file_feed(wtk_cfg_file_t *c,char *d,int bytes) { int ret; //wtk_debug("%*.*s\n",bytes,bytes,d); c->state=CF_EXPR_START; c->cur=c->main; ret=wtk_cfg_file_feed_string(c,d,bytes); return ret; } void wtk_cfg_file_print(wtk_cfg_file_t *c) { /* wtk_queue_node_t *n; wtk_local_cfg_t *lc; for(n=c->cfg_queue.pop;n;n=n->next) { lc=data_offset(n,wtk_local_cfg_t,q_n); wtk_local_cfg_print(lc); } */ wtk_local_cfg_print(c->main); } <file_sep>/core/math/wtk_imat.c #include <math.h> #include "wtk_imat.h" wtk_imat_t* wtk_imat_new(int row,int col) { int **i=0; int *ip; int n; int col_bytes; char *pdata; ip=wtk_calloc(1,wtk_imat_bytes(row,col)); //set row col; *(int*)ip=row; ++ip; *(int*)ip=col; i=(int**)(ip); //set index; col_bytes=col*sizeof(int); pdata=(char*)i+sizeof(int*)*(row+1); for(n=1;n<=row;++n,pdata+=col_bytes) { i[n]=(int*)(pdata-sizeof(int)); } return i; } void wtk_imat_delete(wtk_imat_t *m) { wtk_free((char*)m-sizeof(int)); } void wtk_imat_reset(wtk_imat_t *m) { char *data; data=wtk_imat_data(m); memset(data,0,sizeof(int)*wtk_imat_row(m)*wtk_imat_col(m)); } double wtk_imat_euclid_distance2(wtk_imat_t *m1,wtk_imat_t *m2) { int i,j; int N,M; int t; double d=0; N=wtk_imat_row(m1); M=wtk_imat_col(m1); for(i=1;i<=N;++i) { for(j=1;j<=M;++j) { t=m1[i][j]-m2[i][j]; d+=t*t; } } return sqrt(d); } double wtk_imat_euclid_distance(wtk_imat_t *m1,wtk_imat_t *m2) { int N,M; int t; double d; int *p1,*p2,*p1e; N=wtk_imat_row(m1); M=wtk_imat_col(m1); p1=(int*)wtk_imat_data(m1); p2=(int*)wtk_imat_data(m2); N*=M; d=0; p1e=p1+N; while(p1<p1e) { t=*p1++-*p2++; d+=t*t; } return sqrt(d); } double wtk_imat_cos2(wtk_imat_t *m1,wtk_imat_t *m2) { int i,j; int N,M; int t; double d=0,a=0,b=0; N=wtk_imat_row(m1); M=wtk_imat_col(m1); for(i=1;i<=N;++i) { for(j=1;j<=M;++j) { t=m1[i][j]*m2[i][j]; d+=t*t; t=m1[i][j]; a+=t*t; t=m2[i][j]; b+=t*t; } } wtk_debug("d=%f,a=%f,b=%f\n",d,a,b); d=d/(sqrt(a)*sqrt(b)); return d; } double wtk_imat_cos(wtk_imat_t *m1,wtk_imat_t *m2) { int N,M; int *p1,*p2,*p1e; double d,a,b; int t1,t2; N=wtk_imat_row(m1); M=wtk_imat_col(m1); p1=(int*)wtk_imat_data(m1); p2=(int*)wtk_imat_data(m2); N*=M; d=a=b=0; p1e=p1+N; while(p1<p1e) { t1=*p1++; t2=*p2++; if(t1!=0 && t2!=0) { //wtk_debug("t1=%d,t2=%d\n",t1,t2); //wtk_debug("d=%f,a=%f,b=%f\n",d,a,b); d+=t1*t2; //wtk_debug("d=%f\n",d); } if(t1!=0) { a+=t1*t1; //wtk_debug("a=%f\n",a); } if(t2!=0) { b+=t2*t2; //wtk_debug("b=%f\n",a); } } //wtk_debug("d=%f,a=%f,b=%f\n",d,a,b); d=d/(sqrt(a)*sqrt(b)); return d; } void wtk_imat_print(wtk_imat_t *m) { int i,j; int N,M; N=wtk_imat_row(m); M=wtk_imat_col(m); for(i=1;i<=N;++i) { printf("%d:\t",i); for(j=1;j<=M;++j) { if(j>1) { printf(" "); } printf("[%d]",m[i][j]); } printf("\n"); } } //---------------- float matrix section ----------------- wtk_fmat_t* wtk_fmat_new(int row,int col) { float **i=0,*pf; int *ip; int n; int col_bytes; char *pdata; int j; ip=wtk_calloc(1,wtk_fmat_bytes(row,col)); //set row col; *(int*)ip=row; ++ip; *(int*)ip=col; i=(float**)(ip); //set index; col_bytes=col*sizeof(float); pdata=(char*)i+sizeof(float*)*(row+1); for(n=1;n<=row;++n,pdata+=col_bytes) { pf=i[n]=(float*)(pdata-sizeof(float)); for(j=1;j<col;++j) { pf[j]=0; } } return i; } void wtk_fmat_delete(wtk_fmat_t *m) { wtk_free((char*)m-sizeof(int)); } void wtk_fmat_print(wtk_fmat_t *m) { int i,j; int N,M; N=wtk_imat_row(m); M=wtk_imat_col(m); for(i=1;i<=N;++i) { printf("%d:\t",i); for(j=1;j<=M;++j) { if(j>1) { printf(" "); } printf("[%f]",m[i][j]); } printf("\n"); } } <file_sep>/core/cfg/wtk_cfg_file.h #ifndef WTK_CFG_WTK_CFG_FILE_H_ #define WTK_CFG_WTK_CFG_FILE_H_ #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_heap.h" #include "wtk/core/wtk_str_hash.h" #include "wtk/core/wtk_queue.h" #include "wtk/core/rbin/wtk_rbin2.h" #include "wtk_source.h" #include "wtk_local_cfg.h" #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif typedef struct wtk_cfg_file wtk_cfg_file_t; #define wtk_cfg_file_add_var_s(cfg,k,kbytes,v) wtk_cfg_file_add_var(cfg,k,kbytes,v,sizeof(v)-1) #define wtk_cfg_file_add_var_s_s(cfg,k,v) wtk_cfg_file_add_var_s(cfg,k,sizeof(k)-1,v) #define wtk_cfg_file_add_var_ks(cfg,k,v,vlen) wtk_cfg_file_add_var(cfg,k,sizeof(k)-1,v,vlen) #define wtk_cfg_file_feed_s(cfg,data) wtk_cfg_file_feed(cfg,data,sizeof(data)-1) typedef enum { CF_EXPR_START, CF_EXPR_TOK_START, CF_EXPR_TOK_WAIT_EQ, CF_EXPR_VALUE_START, CF_EXPR_VALUE_TOK_START, CF_EXPR_VALUE_TOK_END, CF_VAR_START, CF_VAR_TOK, CF_VAR_TOK_START, CFG_ARRAY_START, CFG_ARRAY_TOK_START, CFG_ARRAY_TOK_END, CFG_COMMENT, CFG_ESCAPE_START, CFG_ESCAPE_X1, CFG_ESCAPE_X2, CFG_ESCAPE_O1, CFG_ESCAPE_O2, CFG_EXPR_IF, }wtk_cfg_file_state_t; typedef struct { wtk_queue_node_t q_n; wtk_string_t *k; wtk_string_t *v; }wtk_cfg_if_cond_t; typedef struct { wtk_queue_node_t q_n; wtk_queue_t cond; unsigned _or:1; unsigned valid:1; }wtk_cfg_if_item_t; struct wtk_cfg_file { wtk_queue_t cfg_queue; wtk_rbin2_t *rbin; wtk_heap_t *heap; wtk_local_cfg_t *main; //main configure; wtk_local_cfg_t *cur; wtk_cfg_file_state_t state; wtk_cfg_file_state_t var_cache_state; int sub_state; wtk_strbuf_t *tok; wtk_strbuf_t *value; wtk_strbuf_t *var; wtk_queue_t if_q; //wtk_strbuf_t *comment; //comment; wtk_array_t *array; int scope; char quoted_char; unsigned char escape_char; unsigned escaped:1; unsigned quoted:1; unsigned included:1; }; void wtk_cfg_file_set_rbin(wtk_cfg_file_t *cfile,wtk_rbin2_t *rbin); wtk_cfg_file_t* wtk_cfg_file_new_fn(char *fn); wtk_cfg_file_t* wtk_cfg_file_new_fn2(char *fn,int add_pwd); wtk_cfg_file_t* wtk_cfg_file_new_fn3(wtk_string_t *dir,char *data,int len,int add_pwd); wtk_cfg_file_t *wtk_cfg_file_new(); int wtk_cfg_file_bytes(wtk_cfg_file_t *cfg); /** * @param buf_size bytes of buf used by cfg; * @param heap_size block of heap used by cfg; */ wtk_cfg_file_t *wtk_cfg_file_new_ex(int buf_size,int heap_size); int wtk_cfg_file_reset(wtk_cfg_file_t *cfg); int wtk_cfg_file_delete(wtk_cfg_file_t *c); int wtk_cfg_file_feed_fn(wtk_cfg_file_t* cfg,char *fn); int wtk_cfg_file_feed(wtk_cfg_file_t *c,char *d,int bytes); /** * v is end with 0. vbytes not with include 0 */ int wtk_cfg_file_add_var(wtk_cfg_file_t *cfg,char *k,int kbytes,char *v,int vlen); void wtk_cfg_file_print(wtk_cfg_file_t *c); #ifdef __cplusplus }; #endif #endif <file_sep>/core/math/wtk_clsvec_cfg.c #include "wtk_clsvec_cfg.h" int wtk_clsvec_cfg_init(wtk_clsvec_cfg_t *cfg) { cfg->use_idx=0; return 0; } int wtk_clsvec_cfg_clean(wtk_clsvec_cfg_t *cfg) { return 0; } int wtk_clsvec_cfg_update_local(wtk_clsvec_cfg_t *cfg,wtk_local_cfg_t *lc) { wtk_string_t *v; wtk_local_cfg_update_cfg_b(lc,cfg,use_idx,v); return 0; } int wtk_clsvec_cfg_update(wtk_clsvec_cfg_t *cfg) { return 0; } <file_sep>/core/.svn/pristine/7b/7b0ed7161307c39cd0eeae199c73b17105c8d3b2.svn-base #include "wtk_model.h" wtk_model_t* wtk_model_new(int nslot) { wtk_model_t *m; m=(wtk_model_t*)wtk_malloc(sizeof(wtk_model_t)); m->hash=wtk_str_hash_new(nslot); m->data_ths=NULL; m->get_data_f=NULL; m->touch_f=NULL; m->touch_ths=NULL; return m; } void wtk_model_delete(wtk_model_t *m) { wtk_str_hash_delete(m->hash); wtk_free(m); } void wtk_model_set_data_get(wtk_model_t *m,void *ths,wtk_model_get_data_f get_data) { m->data_ths=ths; m->get_data_f=get_data; } void wtk_model_set_touch(wtk_model_t *m,void *ths,wtk_model_touch_f touch) { m->touch_ths=ths; m->touch_f=touch; } void* wtk_model_get_data(wtk_model_t *m,char *k,int k_bytes) { return m->get_data_f(m->data_ths,k,k_bytes); } wtk_model_item_t* wtk_model_get_item(wtk_model_t *m,char *k,int k_bytes) { hash_str_node_t *node; wtk_heap_t *heap=m->hash->heap; wtk_model_item_t *item; node=wtk_str_hash_find_node(m->hash,k,k_bytes,NULL); if(!node) { item=(wtk_model_item_t*)wtk_heap_malloc(heap,sizeof(wtk_model_item_t)); item->k=wtk_heap_dup_string(heap,k,k_bytes); item->v.type=WTK_MODEL_V_NIL; item->v.v.i=0; wtk_queue2_init(&(item->listener_q)); wtk_str_hash_add(m->hash,item->k->data,item->k->len,item); }else { item=node->value; } return item; } void wtk_model_add_listener(wtk_model_t *m,char *k,int k_bytes,void *ths,wtk_model_notify_f notify) { wtk_model_item_t* item; item=wtk_model_get_item(m,k,k_bytes); wtk_model_add_listener2(m,item,ths,notify); } void wtk_model_add_listener2(wtk_model_t *m,wtk_model_item_t *item,void *ths,wtk_model_notify_f notify) { wtk_heap_t *heap=m->hash->heap; wtk_model_listener_item_t *li; li=(wtk_model_listener_item_t*)wtk_heap_malloc(heap,sizeof(wtk_model_listener_item_t)); li->notify=notify; li->ths=ths; wtk_queue2_push(&(item->listener_q),&(li->q_n)); } void wtk_model_item_set(wtk_model_item_t *item,wtk_model_item_v_t *new_value) { wtk_queue_node_t *qn; wtk_model_listener_item_t *li; wtk_model_item_v_t *old_value; if(item->v.type==WTK_MODEL_V_NIL) { old_value=NULL; }else { old_value=&(item->v); } for(qn=item->listener_q.pop;qn;qn=qn->next) { li=data_offset2(qn,wtk_model_listener_item_t,q_n); li->notify(li->ths,old_value,new_value); } item->v=*new_value; } void wtk_model_item_set_i(wtk_model_item_t *item,int i) { wtk_model_item_v_t v = {0}; if(item->v.v.i==i) { return; } v.type=WTK_MODEL_V_I; v.v.i=i; wtk_model_item_set(item,&v); } void wtk_model_item_set_f(wtk_model_item_t *item,float f) { wtk_model_item_v_t v = {0}; if(item->v.v.f==f) { return; } v.type=WTK_MODEL_V_F; v.v.f=f; wtk_model_item_set(item,&v); } void wtk_model_item_set_p(wtk_model_item_t *item,void *p) { wtk_model_item_v_t v = {0}; v.type=WTK_MODEL_V_I; v.v.p=p; wtk_model_item_set(item,&v); } wtk_model_item_t* wtk_model_set_i(wtk_model_t *m,char *k,int k_bytes,int i) { wtk_model_item_t *item; wtk_model_item_v_t v; v.type=WTK_MODEL_V_I; v.v.i=i; item=wtk_model_get_item(m,k,k_bytes); wtk_model_item_set(item,&v); return item; } wtk_model_item_t* wtk_model_set_f(wtk_model_t *m,char *k,int k_bytes,float f) { wtk_model_item_t *item; wtk_model_item_v_t v; v.type=WTK_MODEL_V_F; v.v.f=f; item=wtk_model_get_item(m,k,k_bytes); wtk_model_item_set(item,&v); return item; } wtk_model_item_t* wtk_model_set_p(wtk_model_t *m,char *k,int k_bytes,void *p) { wtk_model_item_t *item; wtk_model_item_v_t v; v.type=WTK_MODEL_V_P; v.v.p=p; item=wtk_model_get_item(m,k,k_bytes); wtk_model_item_set(item,&v); return item; } <file_sep>/core/.svn/pristine/3a/3a251e50b8771b0a57482ef236dac0cd8111c459.svn-base #include "wtk_mbin_cfg.h" #include "wtk/core/cfg/wtk_source.h" wtk_mbin_cfg_t* wtk_mbin_cfg_new(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update2_f update,char *bin_fn,char *cfg_fn,wtk_local_cfg_t *custom) { wtk_mbin_cfg_t *cfg; wtk_rbin2_item_t *item; int ret; wtk_source_loader_t sl; cfg=(wtk_mbin_cfg_t*)wtk_malloc(sizeof(wtk_mbin_cfg_t)); cfg->cfg=(void*)wtk_calloc(1,cfg_bytes); cfg->init=init; cfg->clean=clean; cfg->update_lc=update_lc; cfg->update=update; cfg->rbin=wtk_rbin2_new(); ret=wtk_rbin2_read(cfg->rbin,bin_fn); if(ret!=0) { wtk_debug("read [%s:%s] failed.",bin_fn,cfg_fn); goto end; } //wtk_debug("f=%p\n",cfg->rbin->f); item=wtk_rbin2_get2(cfg->rbin,cfg_fn,strlen(cfg_fn)); if(!item) { wtk_debug("read [%s:%s] failed.",bin_fn,cfg_fn); ret=-1;goto end; } cfg->cfile=wtk_cfg_file_new(); wtk_cfg_file_set_rbin(cfg->cfile,cfg->rbin); //wtk_debug("f=%p\n",cfg->rbin->f); wtk_cfg_file_add_var_ks(cfg->cfile,"pwd",".",1); ret=wtk_cfg_file_feed(cfg->cfile,item->data->data,item->data->len); if(ret!=0){goto end;} ret=cfg->init(cfg->cfg); if(ret!=0){goto end;} //wtk_debug("update lc\n"); if(custom) { wtk_local_cfg_update(cfg->cfile->main,custom); //wtk_local_cfg_print(cfg->cfile->main); } //exit(0); ret=cfg->update_lc(cfg->cfg,cfg->cfile->main); if(ret!=0){goto end;} sl.hook=cfg->rbin; sl.vf=(wtk_source_loader_v_t)wtk_rbin2_load_file; cfg->sl=sl; ret=cfg->update(cfg->cfg,&sl); end: //wtk_debug("ret=%d\n",ret); //wtk_debug("f=%p\n",cfg->rbin->f); if(ret!=0) { wtk_mbin_cfg_delete(cfg); cfg=NULL; ret=0; } return cfg; } wtk_mbin_cfg_t* wtk_mbin_cfg_new2(int seek_pos,int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update2_f update,char *bin_fn,char *cfg_fn) { wtk_mbin_cfg_t *cfg; wtk_rbin2_item_t *item; int ret; wtk_source_loader_t sl; cfg=(wtk_mbin_cfg_t*)wtk_malloc(sizeof(wtk_mbin_cfg_t)); cfg->cfg=(void*)wtk_calloc(1,cfg_bytes); cfg->init=init; cfg->clean=clean; cfg->update_lc=update_lc; cfg->update=update; cfg->rbin=wtk_rbin2_new(); ret=wtk_rbin2_read2(cfg->rbin,bin_fn,seek_pos); if(ret!=0) { //wtk_debug("read failed\n"); goto end; } //wtk_debug("f=%p\n",cfg->rbin->f); item=wtk_rbin2_get2(cfg->rbin,cfg_fn,strlen(cfg_fn)); if(!item){ret=-1;goto end;} cfg->cfile=wtk_cfg_file_new(); //wtk_debug("f=%p\n",cfg->rbin->f); wtk_cfg_file_add_var_ks(cfg->cfile,"pwd",".",1); ret=wtk_cfg_file_feed(cfg->cfile,item->data->data,item->data->len); if(ret!=0){goto end;} ret=cfg->init(cfg->cfg); if(ret!=0){goto end;} //wtk_debug("update lc\n"); ret=cfg->update_lc(cfg->cfg,cfg->cfile->main); if(ret!=0){goto end;} sl.hook=cfg->rbin; sl.vf=(wtk_source_loader_v_t)wtk_rbin2_load_file; cfg->sl=sl; ret=cfg->update(cfg->cfg,&sl); end: //wtk_debug("ret=%d\n",ret); //wtk_debug("f=%p\n",cfg->rbin->f); if(ret!=0) { wtk_mbin_cfg_delete(cfg); cfg=NULL; ret=0; } return cfg; } void wtk_mbin_cfg_delete(wtk_mbin_cfg_t *cfg) { cfg->clean(cfg->cfg); wtk_free(cfg->cfg); if (cfg->cfile){ wtk_cfg_file_delete(cfg->cfile); } wtk_rbin2_delete(cfg->rbin); wtk_free(cfg); } #include "wtk/core/rbin/wtk_rbin.h" wtk_main_cfg_t *wtk_main_cfg_new_bin(int cfg_bytes,wtk_main_cfg_init_f init, wtk_main_cfg_clean_f clean,wtk_main_cfg_update_local_f update_lc, wtk_main_cfg_update2_f update,char *bin_fn,char *cfg_fn) { wtk_main_cfg_t *cfg; wtk_rbin_t *rbin; wtk_ritem_t *item; wtk_cfg_file_t *cf=0; void *xcfg; int ret=-1; wtk_source_loader_t sl; cfg=(wtk_main_cfg_t*)wtk_calloc(1,sizeof(*cfg)); cfg->init=init; cfg->clean=clean; cfg->update_lc=update_lc; cfg->update=0; cfg->update2=update; rbin=wtk_rbin_new(); ret=wtk_rbin_read(rbin,bin_fn); if(ret!=0){goto end;} item=wtk_rbin_find(rbin,cfg_fn,strlen(cfg_fn)); if(!item){goto end;} cf=wtk_cfg_file_new(); wtk_cfg_file_add_var_ks(cf,"pwd",".",1); ret=wtk_cfg_file_feed(cf,item->data.data,item->data.len); if(ret!=0){goto end;} cfg->cfile=cf; xcfg=(void*)calloc(1,cfg_bytes); ret=cfg->init(xcfg); if(ret!=0){goto end;} ret=cfg->update_lc(xcfg,cfg->cfile->main); if(ret!=0){goto end;} sl.hook=rbin; sl.vf=(wtk_source_loader_v_t)wtk_rbin_load_file; ret=cfg->update2(xcfg,&sl); if(ret!=0){goto end;} cfg->cfg_bytes=cfg_bytes; cfg->cfg=xcfg; cf=0; ret=0; end: if(cf) { wtk_cfg_file_delete(cf); } wtk_rbin_delete(rbin); if(ret!=0) { wtk_free(cfg); cfg=0; } return cfg; } <file_sep>/core/.svn/pristine/5d/5d2f0e3ebe99fa675ed7a6e165c9225cdcac96f5.svn-base #ifndef WTK_CORE_WTK_KDICT #define WTK_CORE_WTK_KDICT #include "wtk/core/wtk_type.h" #include "wtk/core/wtk_str_hash.h" #include "wtk/core/cfg/wtk_source.h" #include "wtk_strpool.h" #ifdef __cplusplus extern "C" { #endif typedef struct wtk_kdict wtk_kdict_t; typedef void* (*wtk_kdict_parse_value_f)(void *ths,wtk_kdict_t *d,wtk_string_t *k,char *v,int v_bytes); #define wtk_kdict_get_s(d,k) wtk_kdict_get(d,k,sizeof(k)-1) struct wtk_kdict { wtk_strpool_t *pool; wtk_str_hash_t *hash; void* parse_ths; wtk_kdict_parse_value_f parse_f; }; wtk_kdict_t* wtk_kdict_new(wtk_strpool_t *pool,int hint,void *ths,wtk_kdict_parse_value_f parse_f); void wtk_kdict_delete(wtk_kdict_t *d); int wtk_kdict_bytes(wtk_kdict_t *d); int wtk_kdict_load(wtk_kdict_t *d,wtk_source_t *src); int wtk_kdict_load_file(wtk_kdict_t *d,char *fn); void* wtk_kdict_get(wtk_kdict_t *d,char *k,int k_bytes); #ifdef __cplusplus }; #endif #endif <file_sep>/core/wtk_qarray.c #include "wtk_qarray.h" wtk_qarray_t* wtk_qarray_new(wtk_heap_t *heap,int use_sort) { wtk_qarray_t *a; a=(wtk_qarray_t*)wtk_heap_malloc(heap,sizeof(wtk_qarray_t)); a->heap=heap; a->use_sort=use_sort; wtk_queue_init(&(a->q)); return a; } wtk_qarray_item_t* wtk_qarray_add_item(wtk_qarray_t *a,int idx) { wtk_qarray_item_t *item,*t; wtk_queue_node_t *qn,*nxt; item=(wtk_qarray_item_t*)wtk_heap_malloc(a->heap,sizeof(wtk_qarray_item_t)); item->idx=idx; if(a->use_sort) { for(nxt=NULL,qn=a->q.pop;qn;qn=qn->next) { t=data_offset(qn,wtk_qarray_item_t,q_n); if(idx>=t->idx) { nxt=qn; break; } } if(nxt) { wtk_queue_insert_before(&(a->q),nxt,&(item->q_n)); }else { wtk_queue_push(&(a->q),&(item->q_n)); } }else { wtk_queue_push(&(a->q),&(item->q_n)); } return item; } wtk_qarray_item_t* wtk_qarray_find(wtk_qarray_t *a,int idx) { wtk_queue_node_t *qn; wtk_qarray_item_t *item; for(qn=a->q.pop;qn;qn=qn->next) { item=data_offset(qn,wtk_qarray_item_t,q_n); if(item->idx==idx) { return item; } } return NULL; } void wtk_qarray_add_p(wtk_qarray_t *a,int idx,void *ths) { wtk_qarray_item_t *item; item=wtk_qarray_add_item(a,idx); item->v.p=ths; } void wtk_qarray_append_p(wtk_qarray_t *a,void *ths) { wtk_qarray_add_p(a,a->q.length,ths); } void* wtk_qarray_get_p(wtk_qarray_t *a,int idx) { wtk_qarray_item_t *item; item=wtk_qarray_find(a,idx); return item->v.p; }
b25d7e7600146273e5ab3c18efffe8eb87c42c5b
[ "C", "Makefile" ]
170
C
DWtiangu/wwk
cac92116c0e2489d230b0f75a6aeb59b6b65c157
8bd3e656218d5400482a9c850cceb0b32b380eb1
refs/heads/master
<file_sep>import React from 'react'; import '../assets/styles/NavBar.sass'; const NavBar = () => { return ( <div className="title"> <h1>Titleeee</h1> </div> ) } export default NavBar;
e2f17a4227b361258d4559826a044d71b2166051
[ "JavaScript" ]
1
JavaScript
gon-za/test-futbol-palacio
2220440ba7f4e1441c9e51653a56345908b7e8c0
5e89b26752a855affc3cb67d93318cb68e3cce1c
refs/heads/master
<file_sep>#include <iostream> #include "include/vision.h" using namespace std; //These are so far the best parameters for find circles as well as tolerances for certain //algorithim decisions for radius filtering and rectangle circle pattern detection. //Don't change these unless you ask Jason first. static double dp = 1; static double minDist = 80; static double param1 = 40; static double param2 = 30; static double minRadius = 5; static double maxRadius = 100; static int radTolerance = 10; static int distTolerance = 40; static int intTolerance = 50; int main(){ Vision *v = new Vision(dp, minDist, param1, param2, minRadius, maxRadius, radTolerance, distTolerance, intTolerance); while(true){ if(v->checkBoard()){ cout << "Found board!" << endl; v->analyzeBoard(); } } delete v; return 0; } <file_sep># Simon-Says Vision Algorithm for MRDC iRobotics, FA2017-SP2018 It's been a long time since I've looked at this code, but it was written to detect when buttons would light up in a four-circle grid. The code was written in C++ and mainly utilized the OpenCV library. The main detection algorithm was finished and working, but the rest remains unfinished. <file_sep>#ifndef VISION_H #define VISION_H #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <iostream> #include <math.h> #include <queue> #include <map> #include <string> #include <unordered_map> using std::string; using std::cout; using std::endl; using namespace cv; class Vision{ public: /* * Default Constructor, initializes private variables. Default values are visible in .cpp files, they aren't very good. */ Vision(); Vision(double dp, double minDist, double param1, double param2, double minRadius, double maxRadius, int radTolerance, int distTolerance, int intTolerance); /* * Destructor, deletes private variables that need to be deleted */ ~Vision(); /* * Streams video to window on display, * later instead of streaming on the pi, * this will be sent to our receiving display, * whether it be VR or a laptop * * Needs to spawn another process so this can keep happening * while we do other stuff to the video. This should * also be sent over with gstreamer to our receiving display */ void streamVideo(); /* * Checks on screen if we are at the simon says board * * Returns 1 if we are at the board, 0 otherwise */ int checkBoard(); /* * Analyzes the video during the simon says game * Push 1 if top left, 2 if top right, * 3 if bottom left, 4 if bottom right. * Do nothing or push 0 if it cannot determine which one it is */ void analyzeBoard(); void analyzeBoard(string fileName); void drawCircles(); int readImage(string fileName); /* * Rotates around in a circular direction */ void panArena(); int checkBoard(string fileName); /* * Follows moving objects with camera */ void followMovement(); private: void filterRadius(); int findRectangle(); int findPair(std::pair<Vec3f, Vec3f> xPair, std::pair<Vec3f, Vec3f> yPair); size_t findCircles(); std::queue<int> presses; //Queue to hold our presses std::vector<Vec3f> circles; Mat frame; //Holds the frame Mat Mat grayFrame; VideoCapture *capture; //Holds the capture /* * Opens video stream for object, running in Mat video * * Returns 1 if successful, 0 otherwise */ int openCapture(); /* * Reads capture into Mat video */ int readCapture(); double dp_; double minDist_; double param1_; double param2_; double minRadius_; double maxRadius_; int radTolerance_; int distTolerance_; int intTolerance_; }; #endif <file_sep>#include "vision.h" Vision::Vision(){ //Default values for vision object. These have been optimized. If we find optimized values, put them here. dp_ = 1; //Refer to OpenCV docs. minDist_ = 80; //Minimum distance between consecutive circles. param1_ = 40; //Refer to OpenCV docs. param2_ = 30; //Refer to OpenCV docs. minRadius_ = 5; //Minimum radius for circle detection. maxRadius_ = 100; //Maximum radius for circle detection. radTolerance_ = 10; //Radius tolerance for radius filtering for circles. distTolerance_ = 40; //Distance tolerance when determining rectangle of circles. intTolerance_ = 50; capture = NULL; if(!this->openCapture()){ //Opens capture cout << "Problem with vision construction. Error with capture." << endl; } if(!this->readCapture()){ //Reads capture into video mat variable cout << "Problem with vision construction. Error with reading capture into video." << endl; } } Vision::Vision(double dp, double minDist, double param1, double param2, double minRadius, double maxRadius, int radTolerance, int distTolerance, int intTolerance){ //Values for vision object. This constructor is mainly used for testing optimal parameters. Put optimized ones in default constructor. //Refer to default constructor for attribute descriptions. dp_ = dp; minDist_ = minDist; param1_ = param1; param2_ = param2; minRadius_ = minRadius; maxRadius_ = maxRadius; radTolerance_ = radTolerance; distTolerance_ = distTolerance; intTolerance_ = intTolerance; capture = NULL; if(!this->openCapture()){ //Opens capture cout << "Problem with vision construction. Error with capture." << endl; } if(!this->readCapture()){ //Reads capture into video mat variable cout << "Problem with vision construction. Error with reading capture into video." << endl; } } Vision::~Vision(){ //Frees capture. Nothing much to do here. delete(capture); cout << "Freed capture." << endl; } int Vision::openCapture(){ capture = new VideoCapture(0); //Dynamically allocate video capture for device 0. That 0 is where the picamera resides, don't change. if(!capture->isOpened()){ //Check if capture opened successfully. cout << "Opening capture failed." << endl; return 0; //Unsuccessful. } cout << "Capture successfully opened." << endl; return 1; //Successful. } int Vision::readCapture(){ //Reads capture into video mat variable. If capture is not there, read image from file. if(!capture->read(frame)){ //Check if capture is read into video successfully. cout << "Capture could not be read to video." << endl; return 0; //Unsuccessful } cout << "Capture read to video." << endl; return 1; //Successful } int Vision::readImage(string fileName){ //Reads image from file. This is for test cases. frame = imread(fileName, CV_LOAD_IMAGE_COLOR); //Reads from file based on fileName. if(!frame.data){ //Check if capture is read into video successfully. cout << "Could not read image from file." << endl; return 0; //Unsuccessful } cout << "Read image from file." << endl; return 1; //Successful } void Vision::streamVideo(){ //TODO: Install software and test this. The giant block comment is literally copied from stack overflow. I have done nothing with it yet. /* Open pipeline using gstreamer * * sender cmd: * * gst-launch-1.0 -v v4l2src \ * ! video/x-raw,format=YUY2,width=640,height=480 \ * ! jpegenc \ * ! rtpjpegpay \ * ! udpsink host=127.0.0.1 port=5000 */ /* * receiver cmd: * * gst-launch-1.0 -v udpsrc port=5000 \ * ! application/x-trp, media=video, clock-rate=90000, encoding-name=JPEG, payload=26 \ * ! rtpjpegdepay \ * ! jpegdec \ * ! xvimagesink sync=0 */ /* VideoCapture cap("v4l2src ! video/x-raw, format=BGR, width=640, height=480, framerate=30/1 ! appsink" , CAP_GSTREAMER); VideoWriter out("appsrc ! videoconvert ! video/x-raw, format=YUY2, width=640, height=480, framerate=30/1 ! jpegenc ! rtpjpegpasy ! udpsink host=127.0.0.1 port=5000", CAP_GSTREAMER, 0, 30 Size(640,480), true); if(!cap.isOpened() || !out.isOpened()){ cout << "VideoCapture of VideoWriter not opened." << endl; exit(-1); } Mat frame; while(true){ cap.read(frame); if(frame.empty()){ break; } out.write(frame); } */ } int Vision::checkBoard(string fileName){ //Function for checkBoard on a still image, not a live feed. if(!readImage(fileName)){ //If there's a problem reading the image, leave function with "-1" error. return -1; } size_t size = findCircles(); //Grab circle vector size. //If less than 4 circles, then it cannot be the board. Any more circles greater than 15 makes the Pi3 run very slow during drawing. if(size >= 4 && size <= 20){ //The amount of circles must be a reasonable amount for radius filtering, rectangle detection, and drawing. filterRadius(); //Filters out unnecessary circles with radii too far off from the mode. if(findRectangle()){ return 1; } drawCircles(); //Draws the circles on the regular frame mat variable. } imshow("GrayFrame", grayFrame); //Show the gray image on screen. imshow("Frame", frame); //Show the regular image on screen. waitKey(100); //Wait 100 ms. Required but the time can vary. Try to keep it above 30 ms. return 0; } size_t Vision::findCircles(){ cvtColor(frame, grayFrame, CV_BGR2GRAY); GaussianBlur(grayFrame, grayFrame, Size(9,9), 2, 2); HoughCircles(grayFrame, circles, CV_HOUGH_GRADIENT, dp_, minDist_, param1_, param2_, minRadius_, maxRadius_); return circles.size(); } int Vision::checkBoard(){ //IMPORTANT NOTE: THIS WHOLE FUNCTION RUNS IN A "while(true)" LOOP IN MAIN.CPP // //This function checks if we are actually at the Simon Say's board. For that to be true, there must be a few conditions: //1. There must be four circles that form a pseudo rectangle within a certain offset tolerance, distTolerance_. //2. The radius of all of the circles must be within a certain radiance tolerance, radTolerance_. if(!readCapture()){ //If there's a problem reading the capture into video, leave this function with "-1" error. return -1; //Big error. } size_t size = findCircles(); //Grab circle vector size. //If less than 4 circles, then it cannot be the board. Any more circles greater than 15 makes the Pi3 run very slow during drawing. if(size >= 4 && size <= 20){ //The amount of circles must be a reasonable amount for radius filtering, rectangle detection, and drawing. filterRadius(); //Filters out unnecessary circles with radii too far off from the mode. if(findRectangle()){ //If we found the pseudo rectangle. return 1; //Found the board! } drawCircles(); //Draws the circles on the regular video mat variable. Used for debugging or if operator wants to see. } imshow("GrayFrame", grayFrame); //Show the gray video on screen. imshow("Frame", frame); //Show the regular video on screen. waitKey(100); //Wait 100 ms. Required but the time can vary. Try to keep it above 30 ms. return 0; //Didn't find the board. } int Vision::findRectangle(){ //This function determines if there are four common circles arranged in a rectangle formation. if(circles.size() < 4){ //If we don't have enough circles to work with. return 0; //Unsuccessful } std::vector<std::pair<Vec3f, Vec3f>> xMatch; std::vector<std::pair<Vec3f, Vec3f>> yMatch; std::pair<Vec3f, Vec3f> xPair; std::pair<Vec3f, Vec3f> yPair; //This part looks for x-coordinate and y-coordinate pairs. for(auto outerIt : circles){ for(auto innerIt : circles){ if(innerIt != outerIt){ if(abs(outerIt[0] - innerIt[0]) <= distTolerance_ && abs(outerIt[2] - innerIt[2] <= radTolerance_)){ xPair = std::make_pair(outerIt, innerIt); xMatch.push_back(xPair); } if(abs(outerIt[1] - innerIt[1]) <= distTolerance_ && abs(outerIt[2] - innerIt[2] <= radTolerance_)){ yPair = std::make_pair(outerIt, innerIt); yMatch.push_back(yPair); } } } } std::vector<std::pair<Vec3f, Vec3f>>::iterator xIt; std::vector<std::pair<Vec3f, Vec3f>>::iterator yIt; for(xIt = xMatch.begin(); xIt != xMatch.end(); xIt++){ for(yIt = yMatch.begin(); yIt != yMatch.end(); yIt++){ if(findPair(*xIt, *yIt)){ circles.clear(); circles.push_back(xIt->first); circles.push_back(xIt->second); circles.push_back(yIt->first); circles.push_back(yIt->second); return 1; //Found rectangle! } } } return 0; //No rectangle } int Vision::findPair(std::pair<Vec3f, Vec3f> xPair, std::pair<Vec3f, Vec3f> yPair){ if((abs(xPair.first[0] - yPair.first[0]) <= distTolerance_ && abs(xPair.second[1] - yPair.second[1]) <= distTolerance_) || (abs(xPair.first[0] - yPair.second[0]) <= distTolerance_ && abs(xPair.second[1] - yPair.first[1]) <= distTolerance_)){ return 1; //Found pair } return 0; } void Vision::drawCircles(){ //This function draws circles on the frame mat variable. size_t size = circles.size(); //Get size of circles vector. int radius = 0; //Radius of circle. for(size_t i = 0; i < size; i++){ //Loop through all circles. Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); //Get center point radius = cvRound(circles[i][2]); //Get radius. circle(frame, center, 3, Scalar(0,255,0), -1, 8, 0); //Draw center dot in green. Go to OpenCV Docs for params. circle(frame, center, radius, Scalar(0,0,255), 3, 8, 0); //Draw circumference in red. Go to OpenCV Docs for params. } } void Vision::filterRadius(){ //If looking at runtime for this, which please don't, the size of "n" will never exceed "15" currently. //This function will filter out circles from circles vector that don't have a radius //within the radTolerance of the mode radius. If this confuses you, ask Jason. std::map<int, int> buckets; //Buckets to hold the count of a certain radius appearing in circles vector //NOTE: init[2] contains the radius for a particular circle in the circles vector. //This part initializes the buckets. for(auto init : circles){ //Go through the circles and fill categories for buckets. if(buckets.find(init[2]) == buckets.end()){ //If there is currently no category for a particular radius. buckets.insert(std::pair<int, int>(init[2], 0)); //Insert a bucket for that radius, start it at 0. } } //This part increments the buckets. for(auto outerIt : circles){ //Pick a particular circle. for(auto innerIt : circles){ //Go through all the circles. if(outerIt != innerIt){ //Make sure we aren't comparing the same circle. if(abs(outerIt[2] - innerIt[2]) <= radTolerance_){ //If the difference of two circle radii is <= the tolerance. buckets.at(outerIt[2])++; //Increment the bucket size. } } } } std::vector<int> highestRads; //Holds the mode of the circle radii. There can be more than one. //This part just pushes on the first radius to start out for comparisons. std::map<int, int>::iterator it = buckets.begin(); //Get the first bucket. highestRads.push_back((*it).first); //Push back the first radius. int highestRadFreq = (*it).first; //Set the running highest mode frequency. //This part finds the mode. There can be multiple modes. for(auto mapIt : buckets){ //Go through all buckets if(mapIt.second > highestRadFreq){ //If one of the buckets beats the running highest frequency. highestRads.clear(); //Clear the highestRads vector. highestRads.push_back(mapIt.first); //Push back the new highest radius. highestRadFreq = mapIt.second; //Updated the running highest frequency. } else if(mapIt.second == highestRadFreq){ //If one of the buckets is the same as the running highest frequency. highestRads.push_back(mapIt.first); //Add it to the list of modes. } } std::vector<Vec3f> newCircles; //This is a temporary container to hold our filtered circles vector. //This part does the actual filtering and puts the appropriate circles in the newCircles container. for(auto radsIt : highestRads){ //Go through all the highest modes. std::vector<Vec3f>::iterator circlesIt; //I didn't use autos because it got complicated. for(circlesIt = circles.begin(); circlesIt != circles.end(); circlesIt++){ //Go through our original circles vector. if(abs(radsIt - (*circlesIt)[2]) <= radTolerance_){ //If it falls within the radTolerance of this particular mode. newCircles.push_back(*circlesIt); //It's an appropriate circle, keep it. } } } circles.clear(); //Clear our old circles vector just in case. circles = newCircles; //Update circles with our filtered circles we decided to keep. } void Vision::analyzeBoard(string fileName){ Mat gameBoard; if(!readImage(fileName)){ //We might not want to recapture this, might want to stay on the original one. return; } cvtColor(frame, gameBoard, CV_BGR2GRAY); for(size_t i = 0; i < circles.size(); i++){ Rect r(circles[i][0], circles[i][1], circles[i][2] * 2, circles[i][2] * 2); if(r.x >= 0 && r.y >= 0 && r.width + r.x < frame.cols && r.height + r.y < frame.rows){ Mat roi(frame, r); Scalar avgIntensity = mean(roi); cout << avgIntensity.val[0] << endl; } } } void Vision::analyzeBoard(){ //Must run for live video feed. Unsure if its useful for testing on images. //TODO: Implement same for still image. int size = circles.size(); int *intMap = new int[size]; for(int i = 0; i < size; i++){ intMap[i] = -1; } while(true){ Mat gameBoard; if(!readCapture()){ //We might not want to recapture this, might want to stay on the original one. return; } cvtColor(frame, gameBoard, CV_BGR2GRAY); for(int i = 0; i < size; i++){ Rect r(circles[i][0], circles[i][1], circles[i][2] * 2, circles[i][2] * 2); if(r.x >= 0 && r.y >= 0 && r.width + r.x < frame.cols && r.height + r.y < frame.rows){ Mat roi(frame, r); Scalar avgIntensity = mean(roi); cout << avgIntensity.val[0] << endl; if(intMap[i] == -1){ intMap[i] = avgIntensity.val[0]; } else{ int prevIntensity = intMap[i]; if(abs(prevIntensity - avgIntensity.val[0]) <= intTolerance_){ intMap[i] = avgIntensity.val[0]; } else{ cout << "Button lit up at: " << circles[i] << endl; //Do something } } } } } } void Vision::panArena(){ } void Vision::followMovement(){ } <file_sep>EXENAME = main OBJS = main.o vision.o CXX = g++ CXXFLAGS = -c -g -O0 -Wall -Wextra -pedantic LD = g++ LDFLAGS = -lpng -lpthread -lm OPENCV = $(shell pkg-config --libs --static opencv) all : $(EXENAME) $(EXENAME) : $(OBJS) $(LD) $(OPENCV) $(OBJS) $(LDFLAGS) -o $(EXENAME) main.o : main.cpp include/vision.h $(CXX) $(CXXFLAGS) main.cpp vision.o : include/vision.cpp include/vision.h $(CXX) $(CXXFLAGS) include/vision.cpp test : tests.o vision.o $(LD) tests.o $(LDFLAGS) -o test tests.o : tests/tests.cpp include/vision.h $(CXX) $(CXXFLAGS) tests/tests.cpp clean : -rm -f *.o $(EXENAME) test
2cb0d52768a16a415fb054b15b2d32c87807f579
[ "Markdown", "Makefile", "C++" ]
5
C++
JRaether16/Robotics
849fd4e3852acec0197d1baa2359e970a36079a8
50068bde179f274cc157a938a255fc1ac565c8c7
refs/heads/master
<file_sep>stock_dictionary = {'GM' => 'General Motors', 'CAT' => 'Caterpillar', 'EK' => 'Eastman Kodak'} # puts stock_dictionary purchases = [ [ 'GM', 100, '10-sep-2001', 48 ], [ 'CAT', 100, '1-apr-1999', 24 ], [ 'EK', 200, '1-jul-1998', 56 ] ] # puts purchases results_array = [] for array in purchases shares = array[1] price = array[3] result = shares * price results_array << result # puts results_array end # Display Company names with total stock purchase puts stock_dictionary['GM'].concat(" #{results_array.at(0)}") puts stock_dictionary['CAT'].concat(" #{results_array.at(1)}") puts stock_dictionary['EK'].concat(" #{results_array.at(2)}") #still must list stock tickers with totals
4f7243f1fddbb3759c25fcf0902bcc47c3ce6962
[ "Ruby" ]
1
Ruby
clmassie1/hashes
7b1c9e8e87f4a275c1af2ac5f16cf82ff35798bd
b6ad51fd6f779f22b46cb78793adafba377744d1
refs/heads/master
<repo_name>hyun6ik/Spring-myBoard<file_sep>/mythymeleaf/src/main/java/com/example/mythymeleaf/controller/BoardApiController.java package com.example.mythymeleaf.controller; import com.example.mythymeleaf.domain.Board; import com.example.mythymeleaf.repository.BoardRepository; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import org.thymeleaf.util.StringUtils; import java.util.List; @RestController @RequestMapping("/api") @RequiredArgsConstructor public class BoardApiController { private final BoardRepository boardRepository; @GetMapping("/boards") List<Board> all(@RequestParam(required = false, defaultValue = "") String title, @RequestParam(required=false, defaultValue = "") String content) { if(StringUtils.isEmpty(title) && StringUtils.isEmpty(content)) { return boardRepository.findAll(); } else{ return boardRepository.findByTitleOrContent(title,content); } } @PostMapping("/boards") Board newBoard(@RequestBody Board newBoard){ return boardRepository.save(newBoard); } @GetMapping("/boards/{id}") Board one(@PathVariable Long id){ return boardRepository.findById(id).orElse(null); } @PutMapping("/boards/{id}") Board replaceBoard(@RequestBody Board newBoard, @PathVariable Long id){ return boardRepository.findById(id) .map(board ->{ board.setTitle(newBoard.getTitle()); board.setContent(newBoard.getContent()); return boardRepository.save(board); }) .orElseGet(() ->{ newBoard.setId(id); return boardRepository.save(newBoard); }); } @DeleteMapping("/boards/{id}") void deleteBoard(@PathVariable Long id){ boardRepository.deleteById(id); } } <file_sep>/README.md # Spring-myBoard Spring Boot을 이용해 웹 페이지 제작 Spring Security, JPA를 이용해 보안 설정과 데이터 다루기 <file_sep>/mythymeleaf/settings.gradle rootProject.name = 'mythymeleaf'
f37116cd48e0dc19ed2120347bf64cdf3077ed15
[ "Markdown", "Java", "Gradle" ]
3
Java
hyun6ik/Spring-myBoard
37da8c1e6b06d6830dd5599a31b42b6a8970d6a8
2efb056621a34630ce8112a1d657048ad8c52f1d
refs/heads/master
<file_sep>package raftkv import ( "labgob" "labrpc" // "log" "raft" "sync" "fmt" "time" ) const Debug = 0 func DPrintf(format string, a ...interface{}) (n int, err error) { if Debug > 0 { fmt.Printf(format, a...) } return } type Op struct { // Your definitions here. // Field names must start with capital letters, // otherwise RPC will break. OpType string Key string Value string ClerkId int64 Cntr int } type Client struct { // keep info about each client cntr int reply string executed int } type OpLogEntry struct { operation Op result string } type KVServer struct { mu sync.Mutex me int rf *raft.Raft applyCh chan raft.ApplyMsg maxraftstate int // snapshot if log grows this big // added clients map[int64]*Client logs []OpLogEntry db map[string]string killCh chan rune conditions []*sync.Cond } func (kv *KVServer) Get(args *GetArgs, reply *GetReply) { DPrintf("Getting %v\n", args) // Your code here. kv.mu.Lock() _, ok := kv.clients[args.ClerkId] // no such client before if !ok { kv.clients[args.ClerkId] = &Client { cntr: args.Cntr, reply: "", executed: -1, } } // ignore request with small count if kv.clients[args.ClerkId].cntr > args.Cntr { kv.mu.Unlock() return } else { // update counter kv.clients[args.ClerkId].cntr = args.Cntr // if the command is already executed if kv.clients[args.ClerkId].cntr == kv.clients[args.ClerkId].executed { // ConstructReply(args, reply, c.reply) reply.WrongLeader = false reply.Err = OK reply.Value = kv.clients[args.ClerkId].reply kv.mu.Unlock() return } else { // ask raft to commit new Op operation := Op { OpType: GET, Key: args.Key, // Value? ClerkId:args.ClerkId, Cntr: args.Cntr, } index, _, isLeader := kv.rf.Start(operation) if !isLeader { // this raft peer is not the leader reply.WrongLeader = true kv.mu.Unlock() return } else { // create condition variable for this index to wait for if len(kv.conditions) < index { kv.conditions = append(kv.conditions, make([]*sync.Cond, index - len(kv.conditions))...) } if kv.conditions[index-1] == nil { m := sync.Mutex{} kv.conditions[index-1] = sync.NewCond(&m) } kv.conditions[index-1].L.Lock() kv.mu.Unlock() kv.conditions[index-1].Wait() // the log at this index is committed kv.conditions[index-1].L.Unlock() if operation == kv.logs[index-1].operation { // ConstructReply(args, reply, kv.logs[index-1].result) reply.WrongLeader = false reply.Err = OK reply.Value = kv.logs[index-1].result DPrintf("P%d GET(commit) %v, dict:%v\n", kv.me, args, kv.db) return } else { reply.WrongLeader = true return } } } } } func (kv *KVServer) PutAppend(args *PutAppendArgs, reply *PutAppendReply) { DPrintf("P%d got PutAppending %v\n", kv.me, args) // Your code here. kv.mu.Lock() _, ok := kv.clients[args.ClerkId] // no such client before if !ok { kv.clients[args.ClerkId] = &Client { cntr: args.Cntr, reply: "", executed: -1, } } // ignore request with small count if kv.clients[args.ClerkId].cntr > args.Cntr { kv.mu.Unlock() return } else { // update counter kv.clients[args.ClerkId].cntr = args.Cntr // if the command is already executed if kv.clients[args.ClerkId].cntr == kv.clients[args.ClerkId].executed { kv.mu.Unlock() reply.WrongLeader = false reply.Err = OK return } else { // ask raft to commit new Op operation := Op { OpType: args.Op, Key: args.Key, Value: args.Value, ClerkId:args.ClerkId, Cntr: args.Cntr, } index, _, isLeader := kv.rf.Start(operation) if !isLeader { // this raft peer is not the leader reply.WrongLeader = true kv.mu.Unlock() DPrintf("P%d Not leader for PutAppending %v\n", kv.me, args) return } else { DPrintf("P%d(%v) leader K:%v,V:%v,C:%v,cntr:%v \n", kv.me, args.Op,args.Key, args.Value, args.ClerkId, args.Cntr) // create condition variable for this index to wait for if len(kv.conditions) < index { kv.conditions = append(kv.conditions, make([]*sync.Cond, index - len(kv.conditions))...) } if kv.conditions[index-1] == nil { m := sync.Mutex{} kv.conditions[index-1] = sync.NewCond(&m) } kv.conditions[index-1].L.Lock() kv.mu.Unlock() kv.conditions[index-1].Wait() // the log at this index is committed kv.conditions[index-1].L.Unlock() if operation == kv.logs[index-1].operation { reply.WrongLeader = false reply.Err = OK DPrintf("P%d %v(commit) %v, dict:%v\n", kv.me, args.Op, args, kv.db) return } else { reply.WrongLeader = true return } } } } } // // the tester calls Kill() when a KVServer instance won't // be needed again. you are not required to do anything // in Kill(), but it might be convenient to (for example) // turn off debug output from this instance. // func (kv *KVServer) Kill() { kv.rf.Kill() // Your code here, if desired. close(kv.killCh) } // // servers[] contains the ports of the set of // servers that will cooperate via Raft to // form the fault-tolerant key/value service. // me is the index of the current server in servers[]. // the k/v server should store snapshots through the underlying Raft // implementation, which should call persister.SaveStateAndSnapshot() to // atomically save the Raft state along with the snapshot. // the k/v server should snapshot when Raft's saved state exceeds maxraftstate bytes, // in order to allow Raft to garbage-collect its log. if maxraftstate is -1, // you don't need to snapshot. // StartKVServer() must return quickly, so it should start goroutines // for any long-running work. // func StartKVServer(servers []*labrpc.ClientEnd, me int, persister *raft.Persister, maxraftstate int) *KVServer { // call labgob.Register on structures you want // Go's RPC library to marshall/unmarshall. labgob.Register(Op{}) kv := new(KVServer) kv.me = me kv.maxraftstate = maxraftstate // You may need initialization code here. kv.applyCh = make(chan raft.ApplyMsg) kv.rf = raft.Make(servers, me, persister, kv.applyCh) // You may need initialization code here. kv.clients = make(map[int64]*Client) kv.db = make(map[string]string) kv.killCh = make(chan rune) go kv.ApplyChHandler() return kv } // Handles new ApplyCh responses func (kv *KVServer) ApplyChHandler() { var result string var operation Op for { select { case <-kv.killCh: return case msg := <- kv.applyCh: kv.mu.Lock() operation = msg.Command.(Op) cid, counter := operation.ClerkId, operation.Cntr // if the log is not executed, so that each request is executed only once _, ok := kv.clients[cid] if !ok { kv.clients[cid] = &Client { cntr: counter, reply: "", executed: -1, } } if kv.clients[cid].executed < counter { switch operation.OpType{ case GET: result, _ = kv.db[operation.Key] case PUT: kv.db[operation.Key] = operation.Value case APPEND: result, _ = kv.db[operation.Key] kv.db[operation.Key] = result + operation.Value } kv.clients[cid].executed = counter // update most recent reply counter if kv.clients[cid].cntr <= counter { kv.clients[cid].cntr = counter kv.clients[cid].reply = result } } else { // this command was already executed, find out its value for i:=len(kv.logs)-1; i>=0;i-- { if kv.logs[i].operation.ClerkId == cid && kv.logs[i].operation.Cntr == counter { result = kv.logs[i].result break } } } idx := msg.CommandIndex if idx > len(kv.logs) { // append it to the log it's new kv.logs = append(kv.logs, OpLogEntry{ operation: operation, result: result, }) } else { fmt.Printf("3 Should not be here") } kv.mu.Unlock() // if someone is waiting, wake up if len(kv.conditions) >= idx && kv.conditions[idx-1] != nil { kv.conditions[idx-1].Broadcast() } default: time.Sleep(20 * time.Millisecond) } } } <file_sep># 6.824 (Spring 2018) Labs for MIT-6.824 Distributed Systems (in progress) <file_sep>package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry // rf.GetState() (term, isLeader) // ask a Raft for its current term, and whether it thinks it is leader // ApplyMsg // each time a new entry is committed to the log, each Raft peer // should send an ApplyMsg to the service (or tester) // in the same server. // import ( //"fmt" "labrpc" "math/rand" "sync" "time" ) import "bytes" import "labgob" // // as each Raft peer becomes aware that successive log entries are // committed, the peer should send an ApplyMsg to the service (or // tester) on the same server, via the applyCh passed to Make(). set // CommandValid to true to indicate that the ApplyMsg contains a newly // committed log entry. // // in Lab 3 you'll want to send other kinds of messages (e.g., // snapshots) on the applyCh; at that point you can add fields to // ApplyMsg, but set CommandValid to false for these other uses. // type ApplyMsg struct { CommandValid bool Command interface{} CommandIndex int } // // A Go object implementing a single Raft peer. // type Raft struct { mu sync.Mutex // Lock to protect shared access to this peer's state peers []*labrpc.ClientEnd // RPC end points of all peers persister *Persister // Object to hold this peer's persisted state me int // this peer's index into peers[] // Your data here (2A, 2B, 2C). // Look at the paper's Figure 2 for a description of what // state a Raft server must maintain. currentTerm int votedFor int // current leader leaderId int // channel to send command applyCh chan ApplyMsg // channel to for signals to restart timeout followCh chan rune // random generator ran *rand.Rand // channel for killing the process killCh chan struct{} // log stuff log []LogEntry lastApplied int commitIndex int applyMu sync.Mutex } // return currentTerm and whether this server // believes it is the leader. func (rf *Raft) GetState() (int, bool) { var term int var isleader bool // Your code here (2A). // locking here to make sure that term and isleader are consistent rf.mu.Lock() term = rf.currentTerm isleader = rf.leaderId == rf.me rf.mu.Unlock() return term, isleader } // // save Raft's persistent state to stable storage, // where it can later be retrieved after a crash and restart. // see paper's Figure 2 for a description of what should be persistent. // // *** must be called with rf locked *** // func (rf *Raft) persist() { w := new(bytes.Buffer) e := labgob.NewEncoder(w) e.Encode(rf.currentTerm) e.Encode(rf.votedFor) e.Encode(len(rf.log)) e.Encode(rf.log) data := w.Bytes() rf.persister.SaveRaftState(data) } // // restore previously persisted state. // // *** must be called with rf locked *** // func (rf *Raft) readPersist(data []byte) { if data == nil || len(data) < 1 { // bootstrap without any state? return } r := bytes.NewBuffer(data) d := labgob.NewDecoder(r) var stateCurrentTerm int var stateVotedFor int var stateLogLen int if d.Decode(&stateCurrentTerm) != nil || d.Decode(&stateVotedFor) != nil || d.Decode(&stateLogLen) != nil { // fmt.Println("Error reading persist data") } else { rf.currentTerm = stateCurrentTerm rf.votedFor = stateVotedFor tmp := make([]LogEntry, stateLogLen) if d.Decode(&tmp) != nil { // fmt.Println("Error reading persist logs") } else { rf.log = tmp } } } // // example RequestVote RPC arguments structure. // field names must start with capital letters! // type RequestVoteArgs struct { // Your data here (2A, 2B). Term int CandidateId int LastLogIndex int LastLogTerm int } // // example RequestVote RPC reply structure. // field names must start with capital letters! // type RequestVoteReply struct { // Your data here (2A). Term int VoteGranted bool } type LogEntry struct { Term int // Index int Operations interface{} } type AppendEntriesArgs struct { // leader's term Term int LeaderId int PrevLogIndex int PrevLogTerm int // new entries to append after prev log Entries []LogEntry // leader's commit index LeaderCommit int } type AppendEntriesReply struct { Term int Success bool LastIndexOfTerm int } // // RequestVote RPC handler. // func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) { rf.mu.Lock() reply.VoteGranted = false // check if the request is new if args.Term > rf.currentTerm || (args.Term == rf.currentTerm && (rf.votedFor == -1 || rf.votedFor == args.CandidateId)) { // clear leader Id and vote if the message comes from a newer term if args.Term > rf.currentTerm { rf.leaderId = -1 rf.votedFor = -1 } // update terms no matter endorsing the request or not rf.currentTerm = args.Term // check if this candidate has up-to-date logs // i.e. the leader election restraints in Ch 5.4 if (len(rf.log) == 0) || (args.LastLogTerm > rf.log[len(rf.log)-1].Term) || (args.LastLogTerm == rf.log[len(rf.log)-1].Term && args.LastLogIndex >= len(rf.log) - 1) { // enforse the request rf.votedFor = args.CandidateId reply.VoteGranted = true // fmt.Printf("\tP%d votes P%d in T%d\n", rf.me, args.CandidateId, args.Term) go func() { rf.followCh <- 1 }() } else if args.Term > rf.currentTerm{ go func() { rf.followCh <- 1 }() } else { } } else { } // bring the candidate up to date reply.Term = rf.currentTerm rf.persist() rf.mu.Unlock() return } // Applier for Raft instances // Apply the log entries up to the input index // this makes sure that entries are applied in order // and each entry is applied exactly once func (rf *Raft) ApplyLog(end int) { rf.applyMu.Lock() if end > rf.lastApplied { for i:=rf.lastApplied+1; i <= end; i++ { applymsg := ApplyMsg{ CommandValid: true, Command: rf.log[i].Operations, CommandIndex: i+1} rf.applyCh <- applymsg } rf.lastApplied = end } rf.applyMu.Unlock() return } func (rf *Raft) AppendEntries(args *AppendEntriesArgs, reply *AppendEntriesReply) { rf.mu.Lock() reply.LastIndexOfTerm = -1 if args.Term >= rf.currentTerm { // restart timeout go func() { rf.followCh <- 1 }() // up-to-date heartbeat rf.currentTerm = args.Term rf.leaderId = args.LeaderId // implicitly vote for the current leader rf.votedFor = args.LeaderId // check entries i.e. if PrevLogIndex and PrevLogTerm match // if match, update accordingly, else still reply false if args.PrevLogIndex < len(rf.log) && (args.PrevLogIndex == -1 || rf.log[args.PrevLogIndex].Term == args.PrevLogTerm) { // success HB, i.e. matching previous log entry // follow exactly from Figure 2. if len(rf.log) <= args.PrevLogIndex + 1 + len(args.Entries) { rf.log = rf.log[:args.PrevLogIndex+1] rf.log = append(rf.log, args.Entries...) } else { for i:=0; i < len(args.Entries); i++ { j := i + 1 + args.PrevLogIndex if rf.log[j].Term != args.Entries[i].Term { rf.log = rf.log[:j] rf.log = append(rf.log, args.Entries[i:]...) } } } // fmt.Printf("P%d T%d: updates log from %d to %d from leader %d\n", rf.me, rf.currentTerm, args.PrevLogIndex, len(rf.log) - 1, rf.leaderId) if len(rf.log) > 0{ // fmt.Printf("P%d T%d: log sanity, index %d is %v T%d\n", rf.me, rf.currentTerm, len(rf.log)-1, rf.log[len(rf.log)-1].Operations, rf.log[len(rf.log)-1].Term) } else { // fmt.Printf("P%d T%d: log sanity, empty log\n", rf.me, rf.currentTerm) } // update commit index toCommit := args.LeaderCommit // taking the minimum here, since the logs that the leader sent // may not include up to leaderCommit if toCommit > args.PrevLogIndex + len(args.Entries) { toCommit = args.PrevLogIndex + len(args.Entries) } if rf.commitIndex < toCommit { // fmt.Printf("P%d T%d: commit index uptate from %d to %d\n", rf.me, rf.currentTerm, rf.commitIndex, toCommit) rf.commitIndex = toCommit } go rf.ApplyLog(rf.commitIndex) reply.Success = true } else { // optimization: find out latest index of the log of this term start := args.PrevLogIndex if start > len(rf.log) - 1 { start = len(rf.log) - 1 } for i:=start; i>=0; i-- { if rf.log[i].Term == args.PrevLogTerm { reply.LastIndexOfTerm = i } else if rf.log[i].Term < args.PrevLogTerm { break } } reply.Term = rf.currentTerm reply.Success = false // fmt.Printf("P%d T%d: unsuc HB, prev log indx:%d, term %d\n", rf.me, rf.currentTerm, args.PrevLogIndex, args.PrevLogTerm) } } else { reply.Term = rf.currentTerm reply.Success = false } rf.persist() rf.mu.Unlock() return } // // example code to send a RequestVote RPC to a server. // server is the index of the target server in rf.peers[]. // expects RPC arguments in args. // fills in *reply with RPC reply, so caller should // pass &reply. // the types of the args and reply passed to Call() must be // the same as the types of the arguments declared in the // handler function (including whether they are pointers). // // The labrpc package simulates a lossy network, in which servers // may be unreachable, and in which requests and replies may be lost. // Call() sends a request and waits for a reply. If a reply arrives // within a timeout interval, Call() returns true; otherwise // Call() returns false. Thus Call() may not return for a while. // A false return can be caused by a dead server, a live server that // can't be reached, a lost request, or a lost reply. // // Call() is guaranteed to return (perhaps after a delay) *except* if the // handler function on the server side does not return. Thus there // is no need to implement your own timeouts around Call(). // // look at the comments in ../labrpc/labrpc.go for more details. // // if you're having trouble getting RPC to work, check that you've // capitalized all field names in structs passed over RPC, and // that the caller passes the address of the reply struct with &, not // the struct itself. // func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool { ok := rf.peers[server].Call("Raft.RequestVote", args, reply) if ok { } return ok } func (rf *Raft) sendAppendEntries(server int, args *AppendEntriesArgs, reply *AppendEntriesReply) bool { ok := rf.peers[server].Call("Raft.AppendEntries", args, reply) if ok { } return ok } // // the service using Raft (e.g. a k/v server) wants to start // agreement on the next command to be appended to Raft's log. if this // server isn't the leader, returns false. otherwise start the // agreement and return immediately. there is no guarantee that this // command will ever be committed to the Raft log, since the leader // may fail or lose an election. even if the Raft instance has been killed, // this function should return gracefully. // // the first return value is the index that the command will appear at // if it's ever committed. the second return value is the current // term. the third return value is true if this server believes it is // the leader. // func (rf *Raft) Start(command interface{}) (int, int, bool) { index := -1 term := -1 // Your code here (2B). rf.mu.Lock() isLeader := rf.me == rf.leaderId if isLeader { // fmt.Printf("P%dT%d start command %v at index %d\n", rf.me, rf.currentTerm, command, len(rf.log)) // do everything with true index, i.e. 0-based index = len(rf.log) term = rf.currentTerm newLog := LogEntry{ Term: term, // index is implicit from array index Operations: command, } // append the new command to leader's log rf.log = append(rf.log, newLog) rf.persist() } rf.mu.Unlock() // communicate with service using 1-based index return index+1, term, isLeader } // // the tester calls Kill() when a Raft instance won't // be needed again. you are not required to do anything // in Kill(), but it might be convenient to (for example) // turn off debug output from this instance. // func (rf *Raft) Kill() { // Your code here, if desired. // fmt.Printf("Killing P%d\n", rf.me) close(rf.killCh) return } // // the service or tester wants to create a Raft server. the ports // of all the Raft servers (including this one) are in peers[]. this // server's port is peers[me]. all the servers' peers[] arrays // have the same order. persister is a place for this server to // save its persistent state, and also initially holds the most // recent saved state, if any. applyCh is a channel on which the // tester or service expects Raft to send ApplyMsg messages. // Make() must return quickly, so it should start goroutines // for any long-running work. // func Make(peers []*labrpc.ClientEnd, me int, persister *Persister, applyCh chan ApplyMsg) *Raft { rf := &Raft{} rf.peers = peers rf.persister = persister rf.me = me rf.leaderId = -1 rf.votedFor = -1 // log stuff // log array is initially empty // using 1-based index for communication rf.lastApplied = -1 rf.commitIndex = -1 // Your initialization code here (2A, 2B, 2C). rf.applyCh = applyCh rf.followCh = make(chan rune) rf.killCh = make(chan struct{}) // random generator seed := time.Now().UnixNano() rf.ran = rand.New(rand.NewSource(seed)) // initialize from state persisted before a crash rf.readPersist(persister.ReadRaftState()) // start the consensus procedure go func() { rf.follower() }() return rf } func (rf *Raft) follower() { for { select { // recv'd some some present infomation from some peer case <-rf.killCh: // fmt.Printf("P%d killed in follower\n", rf.me) return case <-rf.followCh: // time out period should be randomized // choose interval to be 300 ms ~ 500 ms, with 100 ms as HB frequency case <-time.After(time.Duration(300+rf.ran.Intn(100)) * time.Millisecond): // fmt.Printf("P%d T%d timed out\n", rf.me, rf.currentTerm) // timeout, become candidate rf.candidate() } } } func (rf *Raft) candidate() { // need to read channel first n := len(rf.peers) var rvArgs RequestVoteArgs for { rf.mu.Lock() // make sure no newer message is heard before becoming candidate select { case <-rf.killCh: // fmt.Printf("P%d killed in candidate\n", rf.me) rf.mu.Unlock() return case <-rf.followCh: rf.mu.Unlock() return default: // become candidate for the new term rf.currentTerm++ rf.votedFor = rf.me // fmt.Printf("P%d(candidate) enters T%d and voted for itself\n", rf.me, rf.currentTerm) rvArgs = RequestVoteArgs{ Term: rf.currentTerm, CandidateId: rf.me, // 0-based index, -1 if there's no log LastLogIndex: len(rf.log) - 1, } // set lastlogterm, differentiate the initial case where there is no log if rvArgs.LastLogIndex == -1 { // initial term is 0 rvArgs.LastLogTerm = -1 } else { rvArgs.LastLogTerm = rf.log[rvArgs.LastLogIndex].Term } } rf.mu.Unlock() // make RequestVote RPCs // wait for n/2 acknowledgements (leader election) ackCntr := 0 // mutex for the counter and condition channel of Acks var ackMu sync.Mutex ackCh := make(chan struct{}) for i := 0; i < n; i++ { if i == rf.me { continue } go func(i int) { rvReply := &RequestVoteReply{} if rf.sendRequestVote(i, &rvArgs, rvReply) { // if granted, increment count by decrement wait count if rvReply.VoteGranted { ackMu.Lock() ackCntr++ if ackCntr == n/2 { // received enough votes, notify by closing one end of channel close(ackCh) } ackMu.Unlock() } else { // update term and // send messge to channel to make server back to follower rf.mu.Lock() // only consider message with newer term as up-to-date message from peer if rvReply.Term > rf.currentTerm { rf.currentTerm = rvReply.Term rf.votedFor = -1 rf.leaderId = -1 go func() { // add back-to-follower token rf.followCh <- 1 }() } rf.mu.Unlock() } } }(i) } select { // received enough votes, become leader for the current candidate term case <-ackCh: rf.leader(rvArgs.Term) return // received an up-to-date message, go back to follower case <-rf.followCh: return // election timeout, rerun candidate in a newer term // timeout using 300-500ms as in follwer, with HB frequency around 100ms case <-time.After(time.Duration(300+rf.ran.Intn(100)) * time.Millisecond): } } } func (rf *Raft) leader(term int) { // update leader ID rf.mu.Lock() if term == rf.currentTerm { rf.leaderId = rf.me } else { rf.mu.Unlock() return } log_len := len(rf.log) rf.mu.Unlock() n := len(rf.peers) nextIndex := make([]int, n) matchIndex := make([]int, n) // set itself as leader, making sure the leader hasn't received a newer message for i := 0; i < n; i++ { // use 0-based index, -1 means no log is replicated yet nextIndex[i] = log_len matchIndex[i] = -1 } // fmt.Printf("P%d T%d: becomes leader, finishes initialization\n", rf.me, term) // each loop will send Heartbeats to all other processes for { // Check leadership and send HeartBeat msgs rf.mu.Lock() if rf.currentTerm != term { rf.mu.Unlock() return } for i := 0; i < n; i++ { // no need to send heartbeat msg to itself if i == rf.me { continue } // construct per-server append entries argument prevlgterm := 0 // if the log array is not empty if nextIndex[i] > 0 { // the log right before the new log entries prevlgterm = rf.log[nextIndex[i]-1].Term } // AppendEntries argument for server i aeArgs := AppendEntriesArgs{ Term: term, LeaderId: rf.me, PrevLogIndex: nextIndex[i] - 1, PrevLogTerm: prevlgterm, Entries: rf.log[nextIndex[i] : len(rf.log)], LeaderCommit: rf.commitIndex, } go func(i int, arg AppendEntriesArgs) { aeReply := &AppendEntriesReply{} if rf.sendAppendEntries(i, &arg, aeReply) { rf.mu.Lock() // check leadership if rf.currentTerm != term { rf.mu.Unlock() return } if !aeReply.Success { // fail because there is a higher term if aeReply.Term > term { if aeReply.Term > rf.currentTerm { // enter new term, clear leader and voting rf.currentTerm = aeReply.Term rf.leaderId = -1 rf.votedFor = -1 go func() { rf.followCh <- 1 }() } } else { // fail because the nextIndex does not match // a successful AppendEntries will have nextIndex[i] - 1 = matchIndex[i] // optimization, follower will return the most recent index that matched prevTerm if nextIndex[i]-1 > matchIndex[i] { iot := aeReply.LastIndexOfTerm if iot >= 0 && rf.log[iot].Term == arg.PrevLogTerm { if iot > matchIndex[i] { nextIndex[i] = iot } else { // fmt.Printf("2: Should not be here") } } else { var j int if aeReply.LastIndexOfTerm == -1 { j = arg.PrevLogIndex - 1 } else { // fmt.Printf("3: Should not be here") j = iot - 1 } for ; j >=0; j-- { if rf.log[j].Term < arg.PrevLogTerm { if j > matchIndex[i] { nextIndex[i] = j break } else { // fmt.Printf("1: Should not be here") nextIndex[i] = matchIndex[i] + 1 break } } } if j == -1 { nextIndex[i] = 0 } } } } } else { // successful AppendEntries, we know that the entries are replicated on server i if arg.PrevLogIndex+len(arg.Entries) > matchIndex[i] { matchIndex[i] = arg.PrevLogIndex + len(arg.Entries) nextIndex[i] = matchIndex[i] + 1 } } rf.mu.Unlock() } }(i, aeArgs) } // update leader's commitIndex according to current estimate of // replicas match indexes using 0-based indexes if len(rf.log)-1 > rf.commitIndex { // counting backwards, starting from the highest index for index := len(rf.log) - 1; index > rf.commitIndex && rf.log[index].Term == term; index-- { count := 0 for i := 0; i < n && count < n/2+1; i++ { if matchIndex[i] >= index || i == rf.me { count++ } } // found the highest committed log index if count >= n/2+1 { rf.commitIndex = index // fmt.Printf("P%dT%d: leader commits index %d\n",rf.me, rf.currentTerm, rf.commitIndex) // fmt.Printf("\t sanity: Ops:%v, Term %d\n", rf.log[index].Operations, rf.log[index].Term) break } } } go rf.ApplyLog(rf.commitIndex) rf.mu.Unlock() select { // return from leader will go back to follower case <-rf.killCh: // fmt.Printf("P%d killed in leader\n", rf.me) return case <-rf.followCh: return case <-time.After(100 * time.Millisecond): } } } <file_sep>package raftkv import "labrpc" import "crypto/rand" import "math/big" // import "fmt" import "time" import "sync" type Clerk struct { servers []*labrpc.ClientEnd // You will have to modify this struct. // "uniquely" identifies the Clerk clerkId int64 // serial number for each command cntr int mu sync.Mutex leaderId int } func nrand() int64 { max := big.NewInt(int64(1) << 62) bigx, _ := rand.Int(rand.Reader, max) x := bigx.Int64() return x } func MakeClerk(servers []*labrpc.ClientEnd) *Clerk { ck := new(Clerk) ck.servers = servers // You'll have to add code here. ck.clerkId = nrand() ck.leaderId = 0 return ck } // // fetch the current value for a key. // returns "" if the key does not exist. // keeps trying forever in the face of all other errors. // // you can send an RPC with code like this: // ok := ck.servers[i].Call("KVServer.Get", &args, &reply) // // the types of args and reply (including whether they are pointers) // must match the declared types of the RPC handler function's // arguments. and reply must be passed as a pointer. // func (ck *Clerk) Get(key string) string { // You will have to modify this function. ck.mu.Lock() // assign unique identifier of each operation args := GetArgs{ Key: key, ClerkId: ck.clerkId, Cntr: ck.cntr, } ck.cntr++ ck.mu.Unlock() // request each server if previous one does not work for i,n := ck.leaderId,len(ck.servers); ;i = (i+1)%n { reply := GetReply{} c := make(chan rune) go func(sid int, rpl *GetReply) { if ck.servers[i].Call("KVServer.Get", &args, rpl) { c <- 1 } else { c <- 0 } }(i, &reply) select { case r := <-c: if r == 1 && !reply.WrongLeader { switch reply.Err { case OK: return reply.Value case ErrNoKey: return "" default: //fmt.Printf("1 Should not be here \n") } } // in steady state: should be 100ms + 2msg delay + process speed case <-time.After(400 * time.Millisecond): } } return "" } // // shared by Put and Append. // // you can send an RPC with code like this: // ok := ck.servers[i].Call("KVServer.PutAppend", &args, &reply) // // the types of args and reply (including whether they are pointers) // must match the declared types of the RPC handler function's // arguments. and reply must be passed as a pointer. // func (ck *Clerk) PutAppend(key string, value string, op string) { // You will have to modify this function. ck.mu.Lock() // assign unique identifier of each operation args := PutAppendArgs{ Key: key, Value: value, Op: op, ClerkId: ck.clerkId, Cntr: ck.cntr, } ck.cntr++ ck.mu.Unlock() for i,n := ck.leaderId,len(ck.servers); ;i = (i+1)%n { //fmt.Printf("Ask leader %v\n", i) reply := PutAppendReply{} c := make(chan rune) go func(sid int, rpl *PutAppendReply, ch *chan rune) { if ck.servers[i].Call("KVServer.PutAppend", &args, rpl) { c <- 1 } else { c <- 0 } }(i, &reply, &c) select { case r := <-c: // //fmt.Printf("got r%v", r) if r == 1 && !reply.WrongLeader { //fmt.Printf("P%d committed %v\n", i, args) switch reply.Err { case OK: return default: //fmt.Printf("2 Should not be here \n") } } // time.Sleep(5*time.Millisecond) // in steady state: should be 100ms + 2msg delay + process speed case <-time.After(400 * time.Millisecond): //fmt.Printf("Waiting in PutAppend\n") } } return } func (ck *Clerk) Put(key string, value string) { ck.PutAppend(key, value, "Put") } func (ck *Clerk) Append(key string, value string) { ck.PutAppend(key, value, "Append") }
9ad318ade81c320b0ab0ec6164722a948bc60018
[ "Markdown", "Go" ]
4
Go
cy-b/6.824
74dce6214551abd1fb0f9facb25f479d942e2959
8a2d9ef4f8d0d45af33494841802b3079c5285ec
refs/heads/main
<file_sep>/* eslint-disable no-unused-expressions */ import { test, expect } from 'vitest'; import { computed, defineComponent, ref } from 'vue'; import flushPromises from 'flush-promises'; import waitForExpect from 'wait-for-expect'; import { mount } from './helpers/mount'; import { useClient, useMutation, useQuery } from '../src/index'; import { LikePostMutation, MutationWithNetworkError, MutationWithParseError, MutationWithGqlError, PostsQuery, } from './mocks/queries'; test('runs mutations', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute } = useMutation<{ likePost: { id: number; title: string } }>(LikePostMutation); return { data, execute }; }, template: ` <div> <div v-if="data"> <p>{{ data.likePost.title }}</p> </div> <button @click="execute()"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(0); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('p')?.textContent).toContain('Awesome Post'); }); }); test('passes variables via execute method', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute } = useMutation(LikePostMutation); return { data, execute }; }, template: ` <div> <div v-if="data"> <p>{{ data.likePost.id }}</p> </div> <button @click="execute({ id: 123 })"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(0); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('p')?.textContent).toBe('123'); }); }); test('handles parse errors', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute, error } = useMutation(MutationWithParseError); return { data, execute, error }; }, template: ` <div> <div v-if="data"> <p>{{ data.likePost.id }}</p> </div> <p id="error" v-if="error">{{ error.message }}</p> <button @click="execute()"></button> </div>`, }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { expect(document.querySelector('#error')?.textContent).toMatch(/is not valid JSON/); }); }); test('handles mutation errors', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute, error } = useMutation(MutationWithGqlError); return { data, execute, error }; }, template: ` <div> <div v-if="data"> <p>{{ data.likePost.id }}</p> </div> <p id="error" v-if="error">{{ error.message }}</p> <button @click="execute()"></button> </div>`, }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { expect(document.querySelector('#error')?.textContent).toContain('Not authenticated'); }); }); test('handles network errors', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute, error } = useMutation(MutationWithNetworkError); return { data, execute, error }; }, template: ` <div> <div v-if="data"> <p>{{ data.likePost.id }}</p> </div> <p id="error" v-if="error">{{ error.message }}</p> <button @click="execute()"></button> </div>`, }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { expect(document.querySelector('#error')?.textContent).toContain('Failed to connect'); }); }); test('Fails if provider was not resolved', async () => { try { mount({ setup() { const { data, execute } = useMutation(LikePostMutation); return { data, execute }; }, template: ` <div> <div v-if="data"> <p>{{ data.likePost.message }}</p> </div> <button @click="execute()"></button> </div>`, }); } catch (err) { await waitForExpect(() => { expect((err as Error).message).toContain('Cannot detect villus Client'); }); } }); test('runs mutations with custom headers per mutation', async () => { const ctx = { 'SOME-AUTH-HEADER': 'OH YEA', }; mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute } = useMutation(LikePostMutation, { context: computed(() => { return { headers: ctx, }; }), }); return { data, execute }; }, template: ` <div> <div v-if="data"> <p>{{ data.likePost.id }}</p> </div> <button @click="execute()"></button> </div>`, }); await flushPromises(); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledWith( 'https://test.com/graphql', expect.objectContaining({ url: 'https://test.com/graphql', body: expect.anything(), method: 'POST', headers: expect.objectContaining(ctx), }), ); }); }); test('clears cache of previous queries which has the same tag', async () => { let refetch!: () => void; let mutate!: () => void; mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const query = useQuery({ query: PostsQuery, tags: ['test'] }); const mutation = useMutation(LikePostMutation, { clearCacheTags: ['test'], }); refetch = query.execute; mutate = mutation.execute; return { data: query.data }; }, template: ` <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); await refetch(); await flushPromises(); // cache was used. await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); await mutate(); await flushPromises(); // mutation was executed await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(2); }); // cache was evicted. await refetch(); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(3); }); }); test('refetch tagged queries that has the same tag', async () => { let mutate!: () => void; mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const query = useQuery({ query: PostsQuery, tags: ['test'] }); const mutation = useMutation(LikePostMutation, { refetchTags: ['test'], }); mutate = mutation.execute; return { data: query.data }; }, template: ` <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); await mutate(); await flushPromises(); // mutation was executed and also the query await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(3); }); }); test('unmounted queries do not refetch', async () => { let mutate!: () => void; const show = ref(true); const Query = defineComponent({ setup() { const query = useQuery({ query: PostsQuery, tags: ['test'] }); return { data: query.data }; }, template: '<div></div>', }); mount({ components: { Query, }, setup() { useClient({ url: 'https://test.com/graphql', }); const mutation = useMutation(LikePostMutation, { refetchTags: ['test'], }); mutate = mutation.execute; return { show }; }, template: `<Query v-if="show"></Query>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); show.value = false; await flushPromises(); await mutate(); await flushPromises(); // mutation was executed but not the query await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(2); }); }); test('onData option hook is called when mutation get data', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); type Post = { id: number; title: string }; const post = ref<Post>(); const { execute } = useMutation<{ likePost: Post }>(LikePostMutation, { onData: data => (post.value = data.likePost), }); return { execute, post }; }, template: ` <div> <div v-if="post"> <p>{{ post.title }}</p> </div> <button @click="execute()"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(0); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('p')?.textContent).toContain('Awesome Post'); }); }); test('onError option hook is called when mutation get error', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const error = ref<string>(); const { data, execute } = useMutation(MutationWithNetworkError, { onError: err => (error.value = err.message), }); return { data, execute, error }; }, template: ` <div> <div v-if="data"> <p>{{ data.likePost.id }}</p> </div> <p id="error" v-if="error">{{ error }}</p> <button @click="execute()"></button> </div>`, }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { expect(document.querySelector('#error')?.textContent).toContain('Failed to connect'); }); }); <file_sep>import { ClientPlugin } from './types'; export function definePlugin(fn: ClientPlugin) { return fn; } <file_sep>--- layout: ../../layouts/PageLayout.astro title: Plugins description: Learn how villus plugins work order: 6 --- import DocTip from '@/components/DocTip.vue'; # Plugins villus is very flexible and versatile, and as such you will need to write quite a few plugins of your own for various purposes, whether to add special headers, transform the body to a specific format or encoding, or even change the `fetch` function used. Something you might not be aware of is that villus is pre-configured with a couple of plugins that are necessary to execute queries, the default plugins are: - [`fetch`](/plugins/fetch): used to execute queries on the network (actual fetching) - [`cache`](/plugins/cache): an in-memory simple cache that comes with villus by default, and supports all cache policies - [`dedup`](/plugins/dedup): removes any duplicate pending queries Furthermore, villus exposes the default plugins as `defaultPlugins` function. To add plugins to villus client you need to pass a `use` array containing the plugins you would like to have ```vue <script setup> import { useClient, defaultPlugins } from 'villus'; useClient({ url: '/graphql', use: [...defaultPlugins()], // if not provided `defaultPlugins` will be used }); </script> ``` In addition to the default plugins, villus also offers the following plugins but they are not enabled by default: - [`batch`](/plugins/batch): used instead of `fetch` to execute queries in batches on the network - [`multipart`](/plugins/multipart): Adds File upload support - [`handleSubscriptions`](/plugins/handle-subscriptions): Adds GraphQL subscriptions support ## Plugins under the hood Under the hood, plugins are simple callbacks that run through various life-cycles of the operation execution, the main features of villus plugins compared to other libraries are: - All plugins can be synchronous or asynchronous - They will be executed in the same order they are defined in - Each plugin can set anything about the current operations fetch options, like `url` or `body` or `headers` (ex: adding auth token to headers) - Each plugin can choose to set the operation result at any time without stopping other plugins (ex: cache plugins) - Each plugin can choose to end the operation with a specific result while skipping other plugins by setting the terminate signal (ex: fetch and batch plugins) - Each plugin can execute a callback that's synchronous or asynchronous after the query is executed (ex: cache plugin) A villus plugin has a type called `ClientPlugin` and it looks like this in TypeScript: ```typescript type OperationType = 'query' | 'mutation' | 'subscription'; type AfterQueryCallback = (result: OperationResult) => void | Promise<void>; interface FetchOptions extends RequestInit { url?: string; } interface AfterQueryContext { response?: ParsedResponse<unknown>; // The fetch operation response except it contains a parsed `body` property } interface ClientPluginContext { useResult: (result: OperationResult<unknown>, terminate?: boolean) => void; // used to signal that the plugin found a result for the operation afterQuery: (cb: AfterQueryCallback, ctx: AfterQueryContext) => void; // Registers a callback to do something after the query is finished and the pipeline is done operation: { query: DocumentNode | string; // The query/mutation to be executed variables: Record<string, any>; // The query variables cachePolicy: CachePolicy; // The cache policy for this operation key: number; // a unique key to identify this operation (useful for cache) type: OperationType; // the operation type: `query` or `mutation` or `subscription` }; opContext: FetchOptions; // The current operation context, contains stuff like `headers`, `body` and `url` and other fetch options response?: ParsedResponse<unknown>; // The fetch operation response except it contains a parsed `body` property } type ClientPlugin = ({ useResult, operation }: ClientPluginContext) => void | Promise<void>; ``` The following sections will explain the purpose of each item in the context ### useResult() The `useResult` function allows your plugin to resolve a value for the GraphQL operation. Plugins like `fetch`, `batch`, and `cache` make use of this as each of them are responsible for setting a response value for the GraphQL operation. #### Non-terminating Results There are two types of `useResult` calls, the first being a **non-terminating** resolution, meaning that while your plugin found a value, it still wants other plugins to continue executing: ```js useResult(response); // Other plugins will still execute ``` This is useful for the `cache` plugin with the `cache-and-network` policy as it may decide to resolve an operation earlier (if found in cache) and leave the pipeline of plugins unaffected because it still needs to make a network request to fetch the fresh result. #### Terminating Results The other type is a **terminating** resolution, meaning your plugin has decided to take over the pipeline and stop executing all others. This is useful with the `cache` plugin because with the `cache-first` policy, it doesn't want any requests to go through. ```js useResult(response, true); // Stops all plugins after it ``` <DocTip> Calling `useResult` multiple times in the pipeline (by multiple plugins) won't have an effect on the end result as the very first `useResult` call will set the operation response, and any subsequent calls are ignored. </DocTip> ### afterQuery() The `afterQuery` function allows you to run a callback after the query is finished, the callback receives the GraphQL response as the first argument. For example, the `cache` plugin makes use of this to cache the operation response, here is a snippet of what happens in the `cache` plugin: ```js function cachePlugin({ afterQuery, useResult, operation }) { // ... afterQuery(result => { // Set the cache result after query is resolved setCacheResult(operation, result); }); // ... } ``` Additionally, you can have access to the actual response returned by the `fetch` API, the second argument is an object that contains the `response` property: ```js function somePlugin({ afterQuery, useResult, operation }) { // ... afterQuery((result, { response }) => { // do something with the response console.log(response); }); // ... } ``` ### operation The `operation` field contains useful information about the GraphQL operation being executed. | Field | Type | Description | | ----------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- | | query | `string \| DocumentNode` | The query/mutation being executed | | variables | `Record<string, any>` | The query variables passed with the operation | | cachePolicy | `'cache-first' \| 'network-only' \| 'cache-and-network' \| 'cache-only'` | The cache policy for this operation, which is useful if you are building a custom cache plugin | | key | `number` | A unique identifier to use for this operation, useful for cache and dedup plugins | | type | `'query' \| 'mutation' \| 'subscription'` | The operation type | ### opContext The `opContext` field is the `fetch` options that will be passed to the `fetch` or `batch` plugins or your custom plugin that makes the actual request, it has the same shape as [`RequestInit` interface](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#Parameters). This is particularly useful if you are building a `fetch` plugin or some kind of authentication plugin with headers or cookies. Here are a few useful snippets: ```js function myPlugin({ opContext, operation }) { // Add auth headers opContext.headers.Authorization = 'Bearer <token>'; // Encode additional information in the body opContext.body = JSON.stringify({ query: operation.query, variables: operation.variables, mutationKey: 39933 }); // Change the URL dynamically opContext.url = '/other/graphql'; } ``` <DocTip> All plugins are processed in the same order they were added in, and as you can imagine the order of these plugins is critical as some plugins may override options for others and some may resolve the value too early. So keep the order in mind when defining the plugins </DocTip> ## Plugin Configuration You might want to create a configurable plugin to publish or re-use in various ways. `villus` doesn't offer any API for that but good old higher-order functions can be used to achieve that: ```js function myPluginWithConfig({ prefix }) { return ({ opContext, operation }) => { // Add auth headers with configurable prefix opContext.headers.Authorization = `${prefix} <token>`; }; } ``` ## TypeScript Support While `villus` exports the `ClientPlugin` type, you can use the `definePlugin` helper to get automatic types for your plugins: ```typescript import { definePlugin } from 'villus'; // opContext will be automatically typed const myPlugin = definePlugin(({ opContext }) => { opContext.headers.Authorization = 'Bearer <token>'; }); const myPluginWithConfig = (config: { prefix: string }) => { // opContext will be automatically typed return definePlugin(({ opContext }) => { // Add auth headers with configurable prefix opContext.headers.Authorization = `${config.prefix} <token>`; }); }; ``` ## Example - Adding Authorization Headers You likely have an authentication header you would like to add to your queries to be able to execute protected queries/mutations. A very common header is `Authorization` header which contains an auth token. Here is a snippet that shows how to add such headers to your queries: ```js function authPlugin({ opContext }) { opContext.headers.Authorization = 'Bearer <token>'; } // later in your setup import { useClient, defaultPlugins } from 'villus'; useClient({ url: '/graphql', use: [authPlugin, ...defaultPlugins()], // add the auth plugin alongside the default plugins }); ``` And that's it, ## Example - Persistent Cache You might want to create a custom cache especially since the villus default cache plugin does not persist when the page is reloaded or when the client is destroyed, this is because villus default cache is a simple object in memory that keeps track of queries during runtime and each time the page is reloaded or when the client is initialized, it will start with a new object each time. This is convenient for most cases but you might want to leverage a more permanent cache solution. In our example we will use `localStorage` as our storage to cache queries, you are free to use anything else as storage like [`indexedDB`](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) which should offer more powerful capabilities and flexibility. Here is an example of such a cache: ```js function localStorageCache({ afterQuery, useResult, operation }) { // avoid caching mutations or subscriptions, also avoid caching queries with `network-only` policy if (operation.type !== 'query' || operation.cachePolicy === 'network-only') { return; } // Set the cache result after query is resolved // Using the `operation.key` is very handy here, it is a unique value that identifies this operation // The key is calculated from the query itself and it's variables afterQuery(result => { localStorage.setItem(operation.key, result); }); // Get cached item const cachedResult = localStorage.getItem(operation.key); // if exists in cache, terminate with result if (cachedResult) { // The first argument of `useResult` is the final value of the operation // The second argument is optional, it allows the plugin to terminate the operation // and stop all other plugins from executing, the last plugin must terminate with `true` return useResult(cachedResult, true); } } // later in your setup import { useClient, fetch } from 'villus'; useClient({ url: '/graphql', use: [localStorageCache, fetch()], // add the local storage plugin along with the fetch plugin }); ``` In the previous sample, our cache plugin does not handle `cache-and-network` policy because it terminates the operation once it finds a cached value in local storage. To simply support it you could check if the cache policy is `cache-first` which doesn't require any cache invalidations/update after resolving the value. So you need to terminate the operation conditionally if the policy is `cache-first` or not. ```js // ... // Terminate operation only if the cache policy is cache-first return useResult(cachedResult, operation.cachePolicy === 'cache-first'); ``` For reference you may look at the implementation of the [`cache` plugin](https://github.com/logaretm/villus/blob/main/packages/villus/src/cache.ts) ## Example - Response Headers You might want to do something after response headers, for example refreshing a user's token after each response to keep them signed in. You can do so by using the plugin context's `response` property which is set after either `fetch` or `batch` plugins are done executing. To make sure you access the response, you need to do so in the `afterQuery` callback: ```vue <script setup> let token = `TOKEN`; function authPluginWithRefresh({ opContext, afterQuery }) { opContext.headers.Authorization = `Bearer $<token>`; afterQuery((result, { response }) => { // if no response, then the fetch plugin failed with a fatal error if (!response) { return; } // Update the access token token = response.headers['access-token']; }); } // later in your setup import { useClient, defaultPlugins } from 'villus'; useClient({ url: '/graphql', use: [authPluginWithRefresh, ...defaultPlugins()], // add the auth plugin alongside the default plugins }); </script> ``` <DocTip type="danger"> It is important that you don't use ES6 destructing if you plan to use the `response` property as it will be set after the query is executed, destructing it at the function level will always yield `undefined`. </DocTip> ## Example - Global Error Handler If you are using an error reporting or bug tracking service like [`Sentry`](https://sentry.io/), it can become tedious to handle each query and mutation errors all over your app. It would be useful to handle most of the errors in a global handler while leaving the specific errors (e.g: validation) to the component that used that query/mutation. In this example, a global error handler is created where it reports all 500 (and unknown) errors to Sentry. ```ts import { captureException } from '@sentry/browser'; /** * Reports unknown errors to Sentry to avoid having to do that everywhere. */ const sentryReportPlugin = definePlugin(({ operation, afterQuery }) => { afterQuery(({ error }, { response }) => { // collect some information about the query that failed const operationContext = { query: operation.query, type: operation.type, variables: operation.variables, }; if ((response?.status || 200) >= 500) { captureException(error, { contexts: { info: { description: 'received 500 response code from API', }, operation: operationContext, }, }); } // Other kinds of error codes should be handled by the consuming component if (error && isUnknownError(error)) { captureException(error, { contexts: { operation: operationContext, }, }); } // Notify user about the error // ... }); }); ``` <file_sep>--- layout: ../../layouts/PageLayout.astro title: useQuery() description: API reference for the useQuery composable function order: 1 --- import DocTip from '@/components/DocTip.vue'; # useQuery() The `useQuery` function allows you to execute GraphQL queries, it requires a `Provider` or `useClient` to be called in the component tree, so make sure to [set that up](/guide/setup) before using `useQuery` The `useQuery` function returns the following properties and functions: | Property | Type | Description | | ---------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | data | `Ref<any/null>` | The GraphQL query result's `data` | | error | `Ref<CombinedError>` | Any errors encountered during query execution | | execute | `({cachePolicy: CachePolicy}) => Promise<OperationResult<TData>>` | Executes the query and returns the operation result containing `data` and `error` values | | isDone | `Ref<boolean>` | Set to true when the query is executed at least once, never resets to `false` | | isFetching | `Ref<boolean>` | Set to true when the query is executing either by calling `execute` explicitly or by watch effect due to reactive variables or queries | There might be undocumented properties, such properties are no intended for public use and should be ignored. ## Usage ```vue <script setup> import { useQuery } from 'villus'; const Todos = ` query Todos { todos { text } } `; // without variables const { data, error } = useQuery({ query: Todos, }); const FindTodo = ` query FindTodo($id: ID!) { todo (id: $id) { text } } `; // with variables const { data, error } = useQuery({ query: FindTodo, variables: { id: 1 }, }); </script> ``` ### Query Options These are the full object fields that the `useQuery` function accepts: | Property | Type | Required | Description | | ------------ | -------------------------------------------------------------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | query | `string` or `DocumentNode` or `Ref<string>` | **Yes** | The query to be executed | | variables | `object` or `Ref<object>` | **No** | The query variables | | cachePolicy | A `string` with those possible values `cache-and-network` or `network-only` or `cache-first` | **No** | The cache policy to execute the query with, defaults to the value configured with the provided client | | fetchOnMount | `boolean` | **No** | If the query **should be** executed on `mounted`, default is `true` | | context | `{ headers: Record<string, string> }` | **No** | A object to be merged with the fetch options, currently accepts `headers`. The `context` can be a reactive `ref` or `computed ref`. | | paused | `boolean` or `Ref<boolean>` or `(variables?: TVars) => boolean` | **No** | When `true` it will pause executing the query when the variables change. If it is a reactive or a function and it changes back to `false` it will re-execute the query automatically if no execution was already in progress. | | skip | `Ref<boolean>` or `(variables?: TVars) => boolean` | **No** | When `true` any execution calls will be prevented. Similar to `paused`, except it doesn't trigger any automatic executions when it changes. | | tags | `string[]` | **No** | Tags the query for cache clearing or refetching. | This signature allows you to tweak the `fetchOnMount` and `cachePolicy` behaviors for the query, Here is an example: ```vue <script setup> import { useQuery } from 'villus'; const FindTodo = ` query FindTodo($id: ID!) { todo (id: $id) { text } } `; const { data, error } = useQuery({ query: FindTodo, // query variables: { id: 1 }, // variables fetchOnMount: false, cachePolicy: 'network-only', }); </script> ``` ## Reactivity The `useQuery` works well with reactive arguments with some limitations ### Reactive Queries You can create reactive queries using `Ref` or `Computed` with the recommended being `Computed` as it is unlikely you will be explicitly changing the query value. By default `useQuery` detects whenever a `query` argument is reactive and watches it for changes, when a change is triggered it will re-fetch the query automatically. ```vue <script setup> import { computed, ref } from 'vue'; import { useQuery } from 'villus'; // computed id that will be used to compute the query const id = ref(1); // Create a computed query const FetchTodo = computed(() => { return `query FetchTodo { todo (id: ${id.value}) { text } } `; }); const { data } = useQuery({ query: FetchTodo, }); // later on, changing the `id` ref will automatically refetch the query because it is computed id.value = 2; </script> ``` This works the same if you are using `graphql-tag` and returning `ASTs` for your queries. But it's unlikely you will be switching between two different queries. <DocTip type="danger" title="reactive() Support"> Note that reactive objects created with `reactive()` are not considered reactive queries, only `Ref` and `ComputedRef` are accepted. </DocTip> ### Reactive Variables You can also create reactive variables and `useQuery` will detect them and will be watching them for changes, once a change is detected it will re-fetch the query. You can create reactive variables with both `ref` or `reactive` and their derivatives. Here is a quick sample with `reactive`: ```vue <script setup> import { reactive } from 'vue'; import { useQuery } from 'villus'; const variables = reactive({ id: 123, }); const { data } = useQuery({ query: `query FetchTodo ($id: ID!) { todo (id: $id) { text } } `, variables, }); </script> ``` This also works with [ref()](https://v3.vuejs.org/api/refs-api.html#ref) ```vue <script setup> import { ref } from 'vue'; import { useQuery } from 'villus'; const variables = ref({ id: 123, }); const FetchTodo = ` query FetchTodo ($id: ID!) { todo (id: $id) { text } } `; const { data } = useQuery({ query: FetchTodo, variables, }); </script> ``` You can pause variable watching by [checking the guide](/guide/queries#disabling-re-fetching). For more information on `useQuery`, [check the queries guide](/guide/queries) <file_sep>import { vi } from 'vitest'; import fetch from 'node-fetch'; let fetchSpy: any; export const fetchMock = { setup() { global.fetch = fetch as any; fetchSpy = vi.spyOn(global, 'fetch').mockImplementation(fetch as any); }, teardown() { fetchSpy.mockRestore(); }, }; <file_sep>import { createApp } from 'vue'; export function mount(component: Record<string, any>) { const app = createApp(component); app.config.warnHandler = () => { // Do nothing }; app.config.errorHandler = err => { if ((err as Error).message === 'data is not defined') { return; } if (/Cannot detect villus Client/.test((err as Error).message)) { return; } if (/No subscription forwarder was set/.test((err as Error).message)) { return; } // eslint-disable-next-line no-console console.error(err); }; document.body.innerHTML = `<div id="app"></div>`; return app.mount('#app'); } <file_sep># `shared` The shared modules/types between the various villus packages <file_sep>--- layout: ../../layouts/PageLayout.astro title: Application Setup order: 2 --- # Application Setup To start querying GraphQL endpoints, you need to setup a client for that endpoint. **villus** exposes multiple functions and components that allow you to create GraphQL clients for your endpoints. You don't need to create a client for each component, any of these methods makes the villus client available for all the child components. So you only need to do this once for your application. ## Composition API The `useClient` composition API function allows your components to define a GraphQL endpoint that all children of that component will query against. To create a GraphQL client with the composition API: ```vue[App.vue] <script setup> import { useClient } from 'villus'; useClient({ url: '/graphql', // your endpoint. }); </script> ``` Internally it uses `provide/inject` API to inject the client into your components or composable functions. You can find the full options the `useClient` accepts in the [API reference](/api/client) ## Vue Plugin You can use `createClient` function result as a Vue plugin that conveniently adds a `villus` client to your app root. ```js[main.js] import { createClient } from 'villus'; import { createApp } from 'vue'; const app = createApp({...}); // Creates a villus client instance const client = createClient({ url: '/graphql', // your endpoint. }); // Makes the villus client available to your app app.use(client); ``` ## Multiple Providers While uncommon, there are no limitations on how many endpoints you can use within your app, you can use as many clients as you like, and that allows you to query different GraphQL APIs within the same app without hassle. To do that you will need to create a parent component for each client: ```vue <script setup> // ComponentA useClient({ url: '{GITHUB_API_ENDPOINT}', }); </script> <script setup> // ComponentB useClient({ url: '{MY_API}', }); </script> ``` ## Next Steps Now that you have successfully set up the GraphQL client, you can start to [query](/guide/queries) and [execute mutations](/guide/mutations) on your GraphQL APIs. <file_sep># Change Log All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. # [3.1.0](https://github.com/logaretm/villus/compare/v3.0.0...v3.1.0) (2023-04-04) **Note:** Version bump only for package villus-docs # [3.0.0](https://github.com/logaretm/villus/compare/v2.2.1...v3.0.0) (2023-03-20) **Note:** Version bump only for package villus-docs <file_sep>export { createClient, defaultPlugins, setActiveClient, getActiveClient, ClientOptions, Client } from './client'; export { useClient } from './useClient'; export { useQuery, QueryApi, BaseQueryApi, QueryCompositeOptions, QueryExecutionOpts, DataHookHandler, ErrorHookHandler, } from './useQuery'; export { useMutation, MutationResult, MutationApi } from './useMutation'; export { useSubscription, Reducer } from './useSubscription'; export { handleSubscriptions, SubscriptionForwarder } from './handleSubscriptions'; export { fetch } from './fetch'; export { cache } from './cache'; export { dedup } from './dedup'; export { definePlugin } from './helpers'; export { CombinedError } from './utils/error'; export { getQueryKey } from './utils/query'; export * from './types'; export { VILLUS_CLIENT } from './symbols'; export * from '../../shared/src/types'; export { parseResponse, mergeFetchOpts, makeFetchOptions } from '../../shared/src/network'; export { normalizeQuery } from '../../shared/src/utils'; <file_sep>--- layout: ../../layouts/PageLayout.astro title: Client --- # Client API Reference This is a detailed document of the villus client ## API Reference ### createClient() The `createClient` function exported by `villus` package allows you to create raw villus client instances to be used freely without being attached to components/composable functions. Here are the options that `createClient` accepts: | Option | Description | | ----------- | -------------------------------------------------------------------------------------------------------------------------------------- | | url | The URL of the GraphQL API service | | use | An array of [plugins](/api/guide/plugins) to be used on this client. By default the `cache`, `fetch`, and `dedup` plugins are present. | | cachePolicy | The global cache policy to be used for queries, possible values are: `cache-and-network`, `network-only`, or `cache-first` | ```js const client = createClient({ // opts ... }); ``` ### useClient() The `useClient` function exported by `villus` package allows you to create a villus client that can be injected into your components using `useQuery` or `useMutation` or `useSubscription`. It accepts the same options as [createClient()](#createclient). ```js useClient({ // createClient() opts... }); ``` ## Using The Client Manually You don't have to use any of the functions/components to make use of `villus`. You can still use the core client manually to run arbitrary GraphQL queries and still get most of the benefits like caching queries and batching requests. ```js import { createClient } from 'villus'; const client = createClient({ url: '/graphql', }); ``` ### Client as Vue Plugin The `villus` client also doubles as a Vue plugin that you can use to inject the client to your application, it is similar to calling `useClient` but injects the `villus` client at the app level rather than the component-tree level. ```js import { createClient } from 'villus'; import { createApp } from 'vue'; const app = createApp({...}); const client = createClient({ url: '/graphql', // your endpoint. }); // Makes the villus client available to your app app.use(client); ``` ### Queries First, you'll need to build the client instance, which can be done using `createClient` function exported by `villus`: Then you can run queries, mutations, or subscriptions using any of their corresponding methods. You can execute queries using `executeQuery` method on the client instance: ```js import { createClient } from 'villus'; const client = createClient({ url: '/graphql', }); client .executeQuery({ query: 'your query', variables: { // any variables }, }) .then(response => { // process the response }); ``` You can also specify a custom cache policy per query execution by passing a `cachePolicy` property, by default it will follow whatever policy configured in the `createClient` function. ```js{13} import { createClient } from 'villus'; const client = createClient({ url: '/graphql', }); client .executeQuery({ query: 'your query', variables: { // any variables }, cachePolicy: 'network-only', }) .then(response => { // process the response }); ``` ### Mutations You can execute mutations using `executeMutation` method on the client instance: ```js import { createClient } from 'villus'; const client = createClient({ url: '/graphql', }); client .executeMutation({ query: 'your query', variables: { // any variables }, }) .then(response => { // process the response }); ``` import DocTip from '@/components/DocTip.vue'; <DocTip> You can make use of `async/await` as `executeQuery` and `executeMutation` both return a native Promise. </DocTip> ### Subscriptions Subscriptions are trickier because they are more **event-driven**, so you cannot wait for them to execute like queries or mutations. Because of this, the `executeSubscription` method returns an **Observable** that allows you to respond to incoming data. The `useSubscription` function offers an abstraction for dealing with subscriptions but you can still execute your own arbitrary subscriptions without resorting to either: ```js import { createClient, handleSubscriptions, defaultPlugins } from 'villus'; import { SubscriptionClient } from 'subscriptions-transport-ws'; const subscriptionClient = new SubscriptionClient('ws://localhost:4001/graphql', {}); const subscriptionForwarder = operation => subscriptionClient.request(op), const client = createClient({ url: 'http://localhost:4000/graphql', use: [handleSubscriptions(subscriptionForwarder), ...defaultPlugins()], }); const observable = await client.executeSubscription({ query: 'your subscription query', variables: { // any variables }, }); observable.subscribe({ next(response) { // handle incoming data }, // eslint-disable-next-line error(err) { // Handle errors }, }); ``` <DocTip type="danger"> Don't forget to configure the `handleSubscriptions` plugin with a subscription forwarder, which is a function that returns an observable. </DocTip> <file_sep>import { Ref } from 'vue'; import type { ExecutionResult } from 'graphql'; import { CombinedError } from './utils/error'; import { ParsedResponse, FetchOptions, Operation, QueryVariables } from '../../shared/src'; export interface OperationResult<TData = any> { data: TData | null; error: CombinedError | null; } export type CachePolicy = 'cache-and-network' | 'network-only' | 'cache-first' | 'cache-only'; export type StandardOperationResult<TData = any> = ExecutionResult<TData>; export type MaybePromise<T> = T | Promise<T>; export interface ObserverLike<T> { next: (value: T) => void; error: (err: any) => void; complete: () => void; } export interface Unsubscribable { unsubscribe: () => void; } /** An abstract observable interface conforming to: https://github.com/tc39/proposal-observable */ export interface ObservableLike<T> { subscribe(observer: ObserverLike<T>): Unsubscribable; } export type MaybeRef<T> = T | Ref<T>; export type MaybeLazyOrRef<T> = MaybeRef<T> | (() => T); export type OperationType = 'query' | 'mutation' | 'subscription'; export type AfterQueryCallback = ( result: OperationResult, ctx: { response?: ParsedResponse<unknown> }, ) => void | Promise<void>; export interface QueryOperation<TData, TVars> extends Operation<TData, TVars> { type: 'query'; cachePolicy?: CachePolicy; tags?: string[]; } export interface MutationOperation<TData, TVars> extends Operation<TData, TVars> { type: 'mutation'; clearCacheTags?: string[]; } export interface SubscriptionOperation<TData, TVars> extends Operation<TData, TVars> { type: 'subscription'; } export type OperationWithCachePolicy<TData, TVars> = | QueryOperation<TData, TVars> | MutationOperation<TData, TVars> | SubscriptionOperation<TData, TVars>; export type ClientPluginOperation = OperationWithCachePolicy<unknown, QueryVariables> & { key: number; }; export interface QueryExecutionContext { headers: Record<string, string>; } export interface ClientPluginContext { useResult: (result: OperationResult<unknown>, terminate?: boolean) => void; afterQuery: (cb: AfterQueryCallback) => void; operation: ClientPluginOperation; opContext: FetchOptions; response?: ParsedResponse<unknown>; } export type ClientPlugin = ({ useResult, operation }: ClientPluginContext) => void | Promise<void>; export type QueryPredicateOrSignal<TVars = QueryVariables> = boolean | Ref<boolean> | ((variables: TVars) => boolean); <file_sep>--- layout: ../../layouts/PageLayout.astro title: File Uploads description: Using the multipart plugin for file uploads order: 5 --- import DocTip from '@/components/DocTip.vue'; # File Uploads Villus has support for file uploads but it is not configured out of the box, So you would need to manually import it and configure it with `villus` client. The multipart plugin is available as its own package under the name `@villus/multipart` ## Basic File Upload First, add the plugin to your dependencies using `yarn` or `npm`: ```bash yarn add @villus/multipart # Or npm install @villus/multipart ``` Then import the `multipart` plugin from `villus` and make sure it is before the `fetch` plugin: ```vue <script setup> import { useClient, fetch } from 'villus'; import { multipart } from '@villus/multipart'; useClient({ url: 'https://test.com/graphql', use: [multipart(), fetch()], }); </script> ``` And that's it, Now you can use files in your queries/mutations: ```vue <template> <div> <input type="file" name="upload" id="" @change="upload" /> </div> </template> <script setup> import { useClient, useMutation, fetch } from 'villus'; import { multipart } from '@villus/multipart'; useClient({ url: 'http://localhost:9000/graphql', use: [multipart(), fetch()], }); const SingleUpload = ` mutation SingleUpload ($file: Upload!) { singleUpload(file: $file) { id path mimetype filename } } `; const { execute } = useMutation(SingleUpload); async function upload(e) { const { data, error } = await execute({ file: e.target.files[0], }); console.log(data, error); } </script> ``` <DocTip type="danger"> Note that the `multipart` plugin currently is not supported by the `batch` plugin, you can only use it with `fetch` and your custom fetchers if applicable. </DocTip> ## Options At this moment the multipart plugin doesn't have any options to customize ## Code You can check the [source code for the `multipart` plugin](https://github.com/logaretm/villus/blob/main/packages/multipart/src/index.ts) and use it as a reference to build your own <file_sep>--- layout: ../../layouts/PageLayout.astro title: GraphQL Code Generator Workflow description: How to use GraphQL code generator with villus order: 7 --- # GraphQL Code Generator Workflow `villus` is built with TypeScript in its core, you can provide typings for your fetched queries and their variables. Providing typings manually for your queries and variables can be as straightforward as this: ```ts import { useQuery } from 'villus'; interface PostsQuery { posts: { id: number; title: string; }; } interface PostsVariables { first?: number; after?: number; } const { data } = useQuery<PostsQuery, PostsVariables>({ query: `{ posts { id title } }`, variables: { // variables are now typed as PostsVariables }, }); data.value; // is now typed as PostsQuery type! ``` However, it can be very tedious (and will be hard to maintain) as your schema evolves with time. This is why it is better to automatically generate them with [GraphQL code generator](https://graphql-code-generator.com/). ## Automatically Generating Types The [GraphQL code generator](https://graphql-code-generator.com/) tool allows you to configure automation to generate the TypeScript definitions for your schema, queries, mutations, and their variables. Make to read their [documentation](https://graphql-code-generator.com/docs/getting-started/index) to get familiar with the setup and tools you will need, this guide will focus on the relevant parts of `villus`. ### Using Generated Queries Once you've got everything setup, you will be able to import your queries and their type definitions along with their variables as well, the following is a snippet of such a setup: ```ts import { useQuery } from 'villus'; import { Posts, PostsQuery, PostsQueryVariables } from '@/graphql/Posts.gql'; const { data } = useQuery<PostsQuery, PostsQueryVariables>({ query: Posts variables: { // variables are now typed as PostsQueryVariables }, }); data.value; // is now typed as PostsQuery type! ``` ### Using Typed Document There is a nice plugin for the code generator called [Typed Document Node](https://graphql-code-generator.com/docs/plugins/typed-document-node/) that instead of generating just types for your queries, it generates a `TypedDocumentNode` that has both the type information of your queries/mutations and their variables, so you don't need to import the query type each time you use villus. After setting up the plugin and generating the required files you can now import the new `TypedDocumented` for your queries, here is a sample: ```ts import { useQuery } from 'villus'; import { PostsDocument } from '@/graphql/Posts'; const { data } = useQuery({ query: PostsDocument variables: { // variables are now typed as PostsQueryVariables }, }); data.value; // is now typed as PostsQuery type! ``` This reduces the noise you have to import into your file and allows your code to be more concise. ## Demo Here is a live example of a project with the complete setup of the mentioned tools in a Nuxt app: import Codesandbox from "@/components/Codesandbox.vue"; <Codesandbox title="Villus + Nuxt + TypedDocument Plugin" id="villus-nuxt-typeddocument-plugin-qewsn" /> <file_sep>import { graphql, rest } from 'msw'; function makePost(id: number, title = 'Awesome Post') { return { id, title: `${id} ${title}` }; } export const handlers: any[] = [ // Handles a "GetUserInfo" query graphql.query('Posts', (req, res, ctx) => { return res( ctx.data({ posts: new Array(5).fill(0).map((_, idx) => makePost(idx + 1)), }), ); }), graphql.query('Post', (req, res, ctx) => { return res( ctx.data({ post: makePost(req.variables.id), }), ); }), graphql.query('QueryParseError', (req, res) => { return res(res => { res.headers.set('content-type', 'text/html'); res.body = '<div></div>'; return res; }); }), graphql.query('QueryNetworkError', (req, res) => { return res.networkError('Failed to connect'); }), graphql.query('QueryError', (req, res, ctx) => { return res( ctx.errors([ { message: 'Not authenticated', errorType: 'AuthenticationError', }, ]), ); }), graphql.query('ErrorWith500', (req, res, ctx) => { return res( ctx.status(500), ctx.errors([ { message: 'Not authenticated', errorType: 'AuthenticationError', }, ]), ); }), graphql.mutation('LikePost', (req, res, ctx) => { return res(ctx.data({ likePost: makePost(req.variables.id || 1) })); }), graphql.mutation('MutationError', (req, res, ctx) => { return res( ctx.errors([ { message: 'Not authenticated', errorType: 'AuthenticationError', }, ]), ); }), graphql.mutation('MutationParseError', (req, res) => { return res(res => { res.headers.set('content-type', 'text/html'); res.body = '<div></div>'; return res; }); }), graphql.mutation('MutationNetworkError', (req, res) => { return res.networkError('Failed to connect'); }), // Handles Batched requests rest.post('https://test.com/graphql', async (req, res, ctx) => { if (!Array.isArray(req.body)) { throw new Error('Unknown operation'); } const responses = await Promise.all( req.body.map(async op => { const partReq = { ...req, body: op }; const handler = handlers.find(h => h.test(partReq)); if (!handler) { return Promise.reject(new Error(`Cannot handle operation ${op}`)); } return handler.run(partReq); }), ); const batchedResponse = responses.map(d => { return JSON.parse(d?.response?.body) || {}; }); return res(ctx.json(batchedResponse)); }), ]; <file_sep>import { GraphQLError } from 'graphql'; import { ClientPlugin } from './types'; import { makeFetchOptions, resolveGlobalFetch, parseResponse } from '../../shared/src'; import { CombinedError } from './utils'; interface FetchPluginOpts { fetch?: (typeof window)['fetch']; } export function fetch(opts?: FetchPluginOpts): ClientPlugin { const fetch = opts?.fetch || resolveGlobalFetch(); if (!fetch) { throw new Error('Could not resolve a fetch() method, you should provide one.'); } return async function fetchPlugin(ctx) { const { useResult, opContext, operation } = ctx; const fetchOpts = makeFetchOptions(operation, opContext); let response; try { response = await fetch(opContext.url as string, fetchOpts).then(parseResponse); } catch (err) { return useResult( { data: null, error: new CombinedError({ response, networkError: err as any }), }, true, ); } // Set the response on the context ctx.response = response; const data = response.body?.data; if (!response.ok || !response.body) { // It is possible than a non-200 response is returned with errors, it should be treated as GraphQL error const ctorOptions: { response: typeof response; graphqlErrors?: GraphQLError[]; networkError?: Error } = { response, }; if (response.body?.errors) { ctorOptions.graphqlErrors = response.body.errors; } else { ctorOptions.networkError = new Error(response.statusText); } return useResult( { data, error: new CombinedError(ctorOptions), }, true, ); } useResult( { data, error: response.body.errors ? new CombinedError({ response, graphqlErrors: response.body.errors }) : null, }, true, ); }; } <file_sep>import { GraphQLError } from 'graphql'; // https://github.com/FormidableLabs/urql/blob/master/src/utils/error.ts const generateErrorMessage = (networkError?: Error, graphqlErrors?: GraphQLError[]) => { let error = ''; if (networkError !== undefined) { return (error = `[Network] ${networkError.message}`); } if (graphqlErrors !== undefined) { graphqlErrors.forEach(err => { error += `[GraphQL] ${err.message}\n`; }); } return error.trim(); }; function normalizeGqlError(error: any): GraphQLError { if (typeof error === 'string') { return new GraphQLError(error); } if (typeof error === 'object' && error.message) { return new GraphQLError( error.message, error.nodes, error.source, error.positions, error.path, error, error.extensions || {}, ); } return error as any; } export class CombinedError extends Error { public name: 'CombinedError'; public message: string; public response: any; public networkError?: Error; public graphqlErrors?: GraphQLError[]; constructor({ response, networkError, graphqlErrors, }: { response: any; networkError?: Error; graphqlErrors?: Array<string | GraphQLError | Error>; }) { const gqlErrors = graphqlErrors?.map(normalizeGqlError); const message = generateErrorMessage(networkError, gqlErrors); super(message); this.name = 'CombinedError'; this.response = response; this.message = message; this.networkError = networkError; this.graphqlErrors = gqlErrors; } get isGraphQLError(): boolean { return !!(this.graphqlErrors && this.graphqlErrors.length); } toString() { return this.message; } } <file_sep>import { GraphQLError } from 'graphql'; import { ClientPluginContext, CombinedError, ClientPluginOperation, definePlugin, fetch as fetchPlugin } from 'villus'; import { GraphQLResponse, makeFetchOptions, mergeFetchOpts, ParsedResponse, parseResponse, resolveGlobalFetch, } from '../../shared/src'; interface BatchOptions { fetch?: typeof fetch; timeout: number; maxOperationCount: number; exclude?: (op: ClientPluginOperation, ctx: ClientPluginContext) => boolean; } type BatchedGraphQLResponse = GraphQLResponse<unknown>[]; const defaultOpts = (): BatchOptions => ({ fetch: resolveGlobalFetch(), timeout: 10, maxOperationCount: 10, }); export function batch(opts?: Partial<BatchOptions>) { const { fetch, timeout, maxOperationCount } = { ...defaultOpts(), ...(opts || {}) }; const fetchPluginInstance = fetchPlugin({ fetch }); let operations: { resolveOp: (r: any, opIdx: number, err?: Error) => void; body: string }[] = []; let scheduledConsume: any; return definePlugin(function batchPlugin(ctx) { const { useResult, opContext, operation } = ctx; if (opts?.exclude?.(ctx.operation, ctx)) { return fetchPluginInstance(ctx); } async function consume() { const pending = operations; const body = `[${operations.map(o => o.body).join(',')}]`; const fetchOpts = mergeFetchOpts(opContext, { headers: {}, body }); operations = []; if (!fetch) { throw new Error('Could not resolve fetch, please provide a fetch function'); } let response: ParsedResponse<unknown>; try { response = await fetch(opContext.url as string, fetchOpts).then(parseResponse); ctx.response = response; const resInit: Partial<Response> = { ok: response.ok, status: response.status, statusText: response.statusText, headers: response.headers, }; pending.forEach(function unBatchResult(o, oIdx) { const opResult = (response.body as unknown as BatchedGraphQLResponse | null)?.[oIdx]; // the server returned a non-json response or an empty one if (!opResult) { o.resolveOp( { ...resInit, body: response.body, }, oIdx, new Error('Received empty response for this operation from server'), ); return; } o.resolveOp( { body: opResult, ...resInit, }, oIdx, ); }); } catch (err) { // This usually mean a network fetch error which is limited to DNS lookup errors // or the user may not be connected to the internet, so it's safe to assume no data is in the response pending.forEach(function unBatchErrorResult(o, oIdx) { o.resolveOp(undefined, oIdx, err as Error); }); } } return new Promise(resolve => { if (scheduledConsume) { clearTimeout(scheduledConsume); } if (operations.length >= maxOperationCount) { // consume the old array consume(); } if (!opContext.body) { opContext.body = makeFetchOptions(operation, opContext).body; } operations.push({ resolveOp: (response: ParsedResponse<unknown>, opIdx, err) => { resolve(undefined); // Handle DNS errors if (err) { useResult( { data: null, error: new CombinedError({ response, networkError: err, }), }, true, ); return; } const data = response.body?.data || null; if (!response.ok || !response.body) { const error = buildErrorObject(response, opIdx); useResult( { data, error, }, true, ); return; } useResult( { data, error: response.body.errors ? new CombinedError({ response, graphqlErrors: response.body.errors }) : null, }, true, ); }, body: opContext.body as string, }); scheduledConsume = setTimeout(consume, timeout); }); }); } function buildErrorObject(response: ParsedResponse<unknown>, opIdx: number) { // It is possible than a non-200 response is returned with errors, it should be treated as GraphQL error const ctorOptions: { response: typeof response; graphqlErrors?: GraphQLError[]; networkError?: Error } = { response, }; if (Array.isArray(response.body)) { const opResponse = response.body[opIdx]; ctorOptions.graphqlErrors = opResponse?.errors; } else if (response.body?.errors) { ctorOptions.graphqlErrors = response.body.errors; } else { ctorOptions.networkError = new Error(response.statusText); } return new CombinedError(ctorOptions); } <file_sep>/* eslint-disable no-unused-expressions */ import flushPromises from 'flush-promises'; import { test, expect } from 'vitest'; import { multipart } from '../src/index'; import { mount } from '../../villus/test/helpers/mount'; import { useClient, useMutation, fetch } from '../../villus/src'; const content = { hello: 'world' }; const file = new File([new Blob([JSON.stringify(content, null, 2)], { type: 'application/json' })], 'index.ts'); test('handles single file uploads', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [multipart(), fetch()], }); const { data, error, execute } = useMutation( 'mutation Upload ($file: Upload!) { singleUpload (file: $file) { path } }', ); async function upload() { await execute({ file, }); } return { data, error, upload }; }, template: ` <div> <div v-if="data"> <p>{{ data.singleUpload.path }}</p> </div> <p>{{error }}</p> <button @click="upload()"></button> </div>`, }); await flushPromises(); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); expect(global.fetch).toHaveBeenCalledWith( 'https://test.com/graphql', expect.objectContaining({ url: 'https://test.com/graphql', body: expect.any(FormData), method: 'POST', headers: expect.objectContaining({}), }), ); }); <file_sep>import { ref, Ref, onMounted, unref, onBeforeUnmount, watch, isRef, getCurrentInstance, computed } from 'vue'; import { Unsubscribable, OperationResult, MaybeRef, StandardOperationResult, QueryPredicateOrSignal, MaybeLazyOrRef, } from './types'; import { CombinedError, isWatchable, unravel, unwrap, debounceAsync, isEqual } from './utils'; import { Operation, QueryVariables } from '../../shared/src'; import { Client, resolveClient } from './client'; interface SubscriptionCompositeOptions<TData, TVars, TResult = TData> { query: MaybeRef<Operation<TData, TVars>['query']>; variables?: MaybeLazyOrRef<TVars>; skip?: QueryPredicateOrSignal<TVars>; paused?: QueryPredicateOrSignal<TVars>; client?: Client; initialData?: TResult; } export type Reducer<TData = any, TResult = TData> = (value: OperationResult<TData>, prev: TResult | null) => TResult; export const defaultReducer: Reducer = val => val.data; export function useSubscription<TData = any, TResult = TData, TVars = QueryVariables>( opts: SubscriptionCompositeOptions<TData, TVars, TResult>, reduce: Reducer<TData, TResult> = defaultReducer, ) { const client = opts.client ?? resolveClient(); const { query, variables, paused, skip } = opts; const data = ref<TResult | null>(opts?.initialData ?? reduce({ data: null, error: null }, null)); const error: Ref<CombinedError | null> = ref(null); const isPaused = computed(() => unravel(paused, variables as TVars)); const isFetching = ref(true); function handleResponse(result: OperationResult<TData>) { data.value = reduce(result, data.value as TResult) as any; error.value = result.error; } /** * if can not getCurrentInstance, the func use outside of setup, cannot get onMounted * when outside of setup initObserver immediately. */ let observer: Unsubscribable | undefined; const subscribe = debounceAsync(async function subscribe() { unsubscribe(); if (shouldSkip()) { return; } isFetching.value = true; const result = await client.executeSubscription<TData, TVars>({ query: unref(query), variables: unwrap(variables), }); observer = result.subscribe({ next(result) { if (isPaused.value) { return; } const response = transformResult(result); isFetching.value = false; handleResponse(response); }, // eslint-disable-next-line complete() {}, error(err) { if (isPaused.value) { return; } const response = { data: null, error: new CombinedError({ networkError: err, response: null }) }; isFetching.value = false; return handleResponse(response); }, }); return observer; }); function unsubscribe() { observer?.unsubscribe(); observer = undefined; } const vm = getCurrentInstance(); if (!isPaused.value && !shouldSkip()) { vm ? onMounted(subscribe) : subscribe(); } // TODO: if outside of setup, it should be recommend manually pause it(or some action else) vm && onBeforeUnmount(unsubscribe); function shouldSkip() { return unravel(skip, unwrap(variables) || {}); } if (isWatchable(paused)) { watch(paused, val => { if (!val) { subscribe(); } }); } if (isRef(query)) { watch(query, subscribe); } if (isWatchable(variables)) { watch(variables, (value, oldValue) => { if (!isEqual(value, oldValue)) { subscribe(); } }); } if (isWatchable(skip)) { watch(shouldSkip, (value, oldValue) => { if (value === oldValue) { return; } value ? unsubscribe() : subscribe(); }); } return { data, error, paused: isPaused, isFetching }; } /** * Transforms the result from a standard operation result to villus result */ function transformResult<TData>(result: StandardOperationResult<TData>): OperationResult<TData> { if (!result.errors) { return { data: result.data || null, error: null }; } return { data: result.data || null, error: new CombinedError({ graphqlErrors: [...result.errors], response: null }), }; } <file_sep>--- layout: ../../layouts/PageLayout.astro title: Dedup Plugin description: How the default dedup plugin works in villus order: 3 --- import DocTip from '@/components/DocTip.vue'; # Dedup Plugin The dedup plugin removes any duplicate pending queries from executing which means you can safely run the same queries at the same time without worrying about excessive requests. The dedup plugin only applies its caching logic to queries. Mutations and subscriptions are excluded from the deduplication process. ```vue <script setup> import { useClient, dedup, fetch } from 'villus'; useClient({ use: [dedup(), fetch()], }); </script> ``` <DocTip> The dedup plugin is one of the default plugins that are pre-configured with any villus client unless specified otherwise </DocTip> ## Options At this moment the dedup plugin doesn't have any options to customize ## Code You can check the [source code for the `dedup` plugin](https://github.com/logaretm/villus/blob/main/packages/villus/src/dedup.ts) and use it as a reference to build your own <file_sep>--- layout: ../../layouts/PageLayout.astro title: Mutations description: Learn how to run GraphQL mutations order: 4 --- # Mutations ## Mutations Basics **villus** offers a `useMutation` function that is very similar to its **[querying](/queries.md)** counterpart but with few distinct differences: - It **does not** accept a `variables` option. - It **does not** execute automatically, you have to explicitly call `execute`. - Cache policies do not apply to mutations as mutations represent user actions and will always use `network-only` policy. Here is an example of the `useMutation` function: ```vue <template> <div> <div v-if="data"> <p>{{ data.likePost.message }}</p> </div> <button @click="execute()">Submit</button> </div> </template> <script setup> import { useMutation } from 'villus'; const LikePost = ` mutation { likePost (id: 123) { message } } `; const { data, execute } = useMutation(LikePost); </script> ``` ## Passing Variables Since the `useMutation` function does not accept a `variables` property you can pass them to the `execute` function: ```vue <script setup> const LikePost = ` mutation LikePost ($id: ID!) { likePost (id: $id) { message } } `; const { data, execute } = useMutation(LikePost); function onSubmit() { const variables = { id: 123, }; execute(variables); } </script> ``` ## Clearing Tagged Queries Cache To clear [tagged queries'](/guide/queries#tagged-queries) cache, you can specify a `clearCacheTags` option when calling `useMutation` composable: ```vue <script setup> const CreatePost = ` mutation CreatePost ($title: String!) { createPost (title: $title) { id } } `; const GetPosts = ` query GetPosts { posts { id title } } `; const { data } = useQuery(GetPosts, { tags: ['all_posts'], }); const { execute } = useMutation(CreatePost, { clearCacheTags: ['all_posts'], }); function onSubmit() { execute({ title: 'hello there', }); } </script> ``` This will clear all the cache entries for any queries tagged with `all_posts` when using `useQuery`. The next time they are fetched they will go straight to the network and fetch the fresh data from the server. ## Refetching queries after a mutation Aside from clearing the cache for tagged queries, you can also refetch them. By specifying `refetchTags` option when calling `useMutation` composable: ```vue <script setup> const CreatePost = ` mutation CreatePost ($title: String!) { createPost (title: $title) { id } } `; const GetPosts = ` query GetPosts { posts { id title } } `; const { data } = useQuery(GetPosts, { tags: ['all_posts'], }); const { execute } = useMutation(CreatePost, { refetchTags: ['all_posts'], }); function onSubmit() { execute({ title: 'hello there', }); } </script> ``` After the mutation execution completes, it will trigger a refetch for all queries tagged with `all_posts` tag. Note that `refetchTags` also clear the cache if present for those tagged queries, so the refetch will always override the network policy and the cached results. ## Handling Errors You can handle errors by either grabbing the `error` ref returned from the `useMutation` function or by checking the result of the `execute` promise, the latter is preferable as it makes more sense in most situations. The `execute` function doesn't throw and collects all encountered errors into a `CombinedError` instance that contains any GraphQL or network errors encountered. ```vue <script setup> const LikePost = ` mutation LikePost ($id: ID!) { likePost (id: $id) { message } } `; const { data, execute } = useMutation(LikePost); const variables = { id: 123, }; function onSubmit() { execute(variables).then(result => { if (result.error) { // Do something } }); } </script> ``` ## Event hooks useMutation returns event hooks allowing you to execute code when a specific event occurs. ### onData This is called whenever a new result is available. ```vue <script setup> import { useMutation } from 'villus'; const { data, execute } = useMutation(LikePost, { onData: (data) => { // Do something console.log(data) }, }); </script> ``` ### onError It is triggered when an error occurs. ```vue <script setup> import { useMutation } from 'villus'; const { data, execute } = useMutation(LikePost, { onError: (error) => { // Handle the error console.log(error) }, }); </script> ``` There are more things you can do with mutations, like displaying progress for users. Check the API documentation for [useMutation](/api/use-mutation). <file_sep>import { defineConfig } from 'astro/config'; import remarkGfm from 'remark-gfm'; import mdx from '@astrojs/mdx'; import sitemap from '@astrojs/sitemap'; import vue from '@astrojs/vue'; import highlight from './highlight'; // https://astro.build/config export default defineConfig({ site: process.env.NODE_ENV === 'production' ? 'https://villus.logaretm.com' : 'http://localhost:3000', integrations: [ vue(), sitemap(), mdx({ remarkPlugins: [remarkGfm, highlight], }), ], }); <file_sep>export * from './common'; export * from './error'; export * from './query'; <file_sep>import { ClientPlugin, OperationResult } from './types'; export function dedup(): ClientPlugin { // Holds references to pending operations const pendingLookup: Partial<Record<number, Promise<OperationResult>>> = {}; return function dedupPlugin(ctx) { // Don't dedup mutations or subscriptions if (ctx.operation.type !== 'query') { return; } // extract the original useResult function const { useResult } = ctx; // Clean up pending queries after they are resolved ctx.afterQuery(() => { delete pendingLookup[ctx.operation.key]; }); // If pending, re-route the result to it const existingOp = pendingLookup[ctx.operation.key]; if (existingOp) { return existingOp.then(result => { useResult(result, true); }); } // Hold a resolve fn reference let resolveOp: (value: OperationResult) => void; // Create a pending operation promise and add it to lookup pendingLookup[ctx.operation.key] = new Promise<any>(resolve => { resolveOp = resolve; }); // resolve the promise once the result are set via another plugin ctx.useResult = function (...args: [any, any]) { useResult(...args); resolveOp(args[0]); }; }; } <file_sep>import { definePlugin } from 'villus'; import { extractFiles } from 'extract-files'; import { normalizeQuery } from '../../shared/src'; export function multipart() { return definePlugin(function multipartPlugin(context) { const { operation, opContext } = context; const { files, clone: variables } = extractFiles({ ...(operation?.variables || {}) }); if (!files.size) { return; } // cleanup content-type if ((opContext.headers as any)['content-type'] === 'application/json') { delete (opContext.headers as any)['content-type']; } const body = new FormData(); body.append('operations', JSON.stringify({ query: normalizeQuery(operation.query), variables })); const map: Record<number, string[]> = {}; let i = 0; files.forEach(paths => { map[++i] = paths.map(path => `variables.${path}`); }); body.append('map', JSON.stringify(map)); i = 0; files.forEach((_, file) => { body.append(`${++i}`, file as Blob, (file as File).name); }); opContext.body = body; }); } <file_sep>--- layout: ../../layouts/PageLayout.astro title: Overview order: 1 --- # Introduction villus is a minimal [GraphQL](https://graphql.org/) client for Vue.js, exposing components to build highly customizable GraphQL projects. You can use this in small projects or large complex applications. I use GraphQL In most of the apps I build, but more often than not I end up only using the bare-bones **ApolloLink** without the extra whistles provided by the **ApolloClient**. I often even just use a bare `fetch` to run my GraphQL queries as I prefer to handle caching and persisting on my own when building complex PWA apps. Also, the fact that Apollo Client sometimes throws obscure non-standard GraphQL errors doesn't help. To solve this, I needed a bare-bones GraphQL client for Vue.js, but with small quality of life defaults out of the box, like caching. Keeping it simple means it gets to be flexible, lightweight, and can be scaled to handle more complex challenges. This library is inspired by [URQL](https://github.com/FormidableLabs/urql), and forked from my past contribution to the `vue-gql` library before a different direction was decided for it. ## Features - 📦 **Minimal:** Its all you need to query GQL APIs - 🦐 **Tiny:** Very small footprint - 🗄 **Caching:** Simple and convenient query caching by default - 💪 **TypeScript**: Written in Typescript - 💚 Minimal Vue.js Components - 🖇 Composition API support ## Compatibility This library relies on the `fetch` web API to run queries, you can use `unfetch` (client-side) or `node-fetch` (server-side) to use as a polyfill. ## Alternatives ### [VueApollo](https://github.com/vue/vue-apollo) **VueApollo** Is probably the most complete Vue GraphQL client out there and is the official one for apollo, like **villus** it exposes components to work with queries and mutations. It builds upon the **ApolloClient** ecosystem. Use it if you find **villus** lacking for your use-case. <file_sep>import stringify from 'fast-json-stable-stringify'; import { Operation, normalizeQuery } from '../../../shared/src'; export function hash(x: string) { let h, i, l; for (h = 5381 | 0, i = 0, l = x.length | 0; i < l; i++) { h = (h << 5) + h + x.charCodeAt(i); } return h >>> 0; } export function getQueryKey(operation: Operation<any, any>, ...components: string[]) { const variables = operation.variables ? stringify(operation.variables) : ''; const query = normalizeQuery(operation.query); return hash(`${query}${variables}${components.join('')}`); } <file_sep>import { InjectionKey } from 'vue'; import { Client } from './client'; export const VILLUS_CLIENT: InjectionKey<Client> = Symbol('villus.client'); <file_sep>import { isRef, onMounted, Ref, ref, unref, watch, getCurrentInstance, onBeforeUnmount } from 'vue'; import stringify from 'fast-json-stable-stringify'; import { CachePolicy, MaybeLazyOrRef, MaybeRef, OperationResult, QueryExecutionContext, QueryPredicateOrSignal, } from './types'; import { hash, CombinedError, unwrap, isWatchable, unravel, useCallback } from './utils'; import { Operation, QueryVariables } from '../../shared/src'; import { Client, resolveClient } from './client'; export interface QueryCompositeOptions<TData, TVars> { query: MaybeRef<Operation<TData, TVars>['query']>; variables?: MaybeLazyOrRef<TVars>; context?: MaybeRef<QueryExecutionContext>; cachePolicy?: CachePolicy; fetchOnMount?: boolean; client?: Client; paused?: QueryPredicateOrSignal<TVars>; skip?: QueryPredicateOrSignal<TVars>; tags?: string[]; onData?: (data: TData) => void; onError?: (err: CombinedError) => void; } export interface QueryExecutionOpts<TVars> { cachePolicy: CachePolicy; variables: TVars; } export type DataHookHandler<TData> = (data: TData) => unknown; export type ErrorHookHandler = (error: CombinedError) => unknown; type UnregisterHookFn = () => void; export interface BaseQueryApi<TData = any, TVars = QueryVariables> { data: Ref<TData | null>; isFetching: Ref<boolean>; isDone: Ref<boolean>; error: Ref<CombinedError | null>; onData(handler: DataHookHandler<TData>): UnregisterHookFn; onError(handler: ErrorHookHandler): UnregisterHookFn; execute( overrideOpts?: Partial<QueryExecutionOpts<TVars>>, ): Promise<{ data: TData | null; error: CombinedError | null }>; } export interface QueryApi<TData, TVars> extends BaseQueryApi<TData, TVars> { then(onFulfilled: (value: BaseQueryApi<TData, TVars>) => any): Promise<BaseQueryApi<TData, TVars>>; } function useQuery<TData = any, TVars = QueryVariables>( opts: QueryCompositeOptions<TData, TVars>, ): QueryApi<TData, TVars> { const client = opts?.client ?? resolveClient(); if (opts.tags) { const id = client.registerTaggedQuery(opts.tags, async () => { await execute(); }); onBeforeUnmount(() => { client.unregisterTaggedQuery(id); }); } const { query, variables, cachePolicy, fetchOnMount, paused, skip, onData: dataHook, onError: errorHook, } = normalizeOptions(opts); let currentFetchOnMount = fetchOnMount; const data: Ref<TData | null> = ref(null); const isFetching = ref<boolean>(fetchOnMount ?? false); const isDone = ref(false); const isStale = ref(true); const error: Ref<CombinedError | null> = ref(null); const { on: onData, run: executeDataHooks } = useCallback<DataHookHandler<TData>>(); const { on: onError, run: executeErrorHooks } = useCallback<ErrorHookHandler>(); if (dataHook) { onData(dataHook); } if (errorHook) { onError(errorHook); } // This is to prevent state mutation for racing requests, basically favoring the very last one let lastPendingOperation: Promise<OperationResult<TData>> | undefined; const isCurrentlyPaused = () => unravel(paused, (variables || {}) as TVars); function onResultChanged(result: OperationResult<TData>) { if (result.data) { executeDataHooks(result.data); } if (result.error) { executeErrorHooks(result.error); } data.value = result.data as TData; error.value = result.error; } async function execute(overrideOpts?: Partial<QueryExecutionOpts<TVars>>) { const vars = unwrap(variables) || ({} as TVars); // result won't change if execution is skipped if (unravel(skip, vars)) { isFetching.value = false; return { data: data.value, error: error.value, }; } isFetching.value = true; const pendingExecution = client.executeQuery<TData, TVars>( { query: isRef(query) ? query.value : query, variables: unwrap(overrideOpts?.variables || vars), cachePolicy: overrideOpts?.cachePolicy || cachePolicy, tags: opts?.tags, }, unref(opts?.context), onResultChanged, ); lastPendingOperation = pendingExecution; const res = await pendingExecution; // Avoid state mutation if the pendingExecution isn't the last pending operation if (pendingExecution !== lastPendingOperation) { // we still return this result to preserve the integrity of "execute" calls return { data: res.data as TData, error: res.error }; } onResultChanged(res); isDone.value = true; isFetching.value = false; isStale.value = false; lastPendingOperation = undefined; return { data: data.value, error: error.value }; } function executeIfNotPaused() { const isPaused = isCurrentlyPaused(); if (!isPaused) { execute(); } } if (isRef(query)) { watch(query, executeIfNotPaused); } if (isWatchable<boolean>(paused)) { watch( () => !isCurrentlyPaused(), shouldExecute => { if (shouldExecute && isStale.value) { execute(); } }, ); } function initVarWatchers() { let oldCache: number; if (!variables || !isWatchable(variables)) { return; } watch( () => unwrap(variables), newValue => { const id = hash(stringify(newValue)); // prevents duplicate queries. if (id === oldCache) { return; } oldCache = id; isStale.value = true; executeIfNotPaused(); }, { deep: true }, ); } initVarWatchers(); const api = { data, isFetching, isDone, error, execute, onData, onError }; /** * if can not getCurrentInstance, the func use outside of setup, cannot get onMounted * when outside of setup and fetchOnMount is true, execute immediately, but a little confused * todo: maybe better to add a new param decide execute immediately, but it's ok also now */ const vm = getCurrentInstance(); if (currentFetchOnMount) { if (!paused || !isCurrentlyPaused()) { vm ? onMounted(() => execute()) : execute(); } } return { ...api, async then(onFulfilled: (value: BaseQueryApi<TData, TVars>) => any): Promise<BaseQueryApi<TData, TVars>> { currentFetchOnMount = false; await api.execute(); return onFulfilled(api); }, }; } function normalizeOptions<TData, TVars>( opts: Partial<QueryCompositeOptions<TData, TVars>>, ): QueryCompositeOptions<TData, TVars> { const defaultOpts = { variables: {} as TVars, fetchOnMount: true, }; return { ...defaultOpts, ...opts, query: opts.query as NonNullable<(typeof opts)['query']>, }; } export { useQuery }; <file_sep>import { FetchOptions, GraphQLResponse, ParsedResponse, Operation, QueryVariables } from './types'; import { normalizeQuery } from './utils'; export async function parseResponse<TData>(response: Response): Promise<ParsedResponse<TData>> { let json: GraphQLResponse<TData>; const responseData = { ok: response.ok, statusText: response.statusText, status: response.status, headers: response.headers, }; try { json = await response.json(); } catch (err) { return { ...responseData, statusText: (err as Error).message, body: null, }; } return { ...responseData, body: json, }; } export function resolveGlobalFetch(): typeof fetch | undefined { if (typeof window !== 'undefined' && 'fetch' in window && window.fetch) { return window.fetch.bind(window); } if (typeof global !== 'undefined' && 'fetch' in global) { return (global as any).fetch; } if (typeof self !== 'undefined' && 'fetch' in self) { return self.fetch; } return undefined; } export const DEFAULT_FETCH_OPTS = { method: 'POST', headers: { 'content-type': 'application/json', }, } as const; export function mergeFetchOpts(lhs: FetchOptions, rhs: FetchOptions) { return { ...lhs, ...rhs, method: rhs.method || lhs.method || DEFAULT_FETCH_OPTS.method, headers: { ...(lhs.headers || {}), ...(rhs.headers || {}), }, }; } export function makeFetchOptions({ query, variables }: Operation<unknown, QueryVariables>, opts: FetchOptions) { const normalizedQuery = normalizeQuery(query); if (!normalizedQuery) { throw new Error('A query must be provided.'); } return mergeFetchOpts({ body: JSON.stringify({ query: normalizedQuery, variables }) } as any, opts); } <file_sep>export default { appURL: process.env.NODE_ENV === 'production' ? 'https://villus.logaretm.com' : 'http://localhost:3000', algolia: { apiKey: '434db5d5d2794ec2818d4665d631a15b', appId: '1SMG3JU76L', indexName: 'villus', }, } as const; <file_sep>import flushPromises from 'flush-promises'; import { test, expect, vi } from 'vitest'; import gql from 'graphql-tag'; import { mount } from './helpers/mount'; import { makeObservable, tick } from './helpers/observer'; import { defaultPlugins, handleSubscriptions, useClient, useSubscription } from '../src/index'; import { computed, ref } from 'vue'; import { print } from 'graphql'; import { createClient } from 'graphql-ws'; vi.useFakeTimers(); interface Message { id: number; message: string; } test('Default reducer', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [handleSubscriptions(() => makeObservable()), ...defaultPlugins()], }); const { data } = useSubscription<Message>({ query: `subscription { newMessages }` }); return { messages: data }; }, template: ` <div> <div v-if="messages"> <span>{{ messages.id }}</span> </div> </div> `, }); await flushPromises(); vi.advanceTimersByTime(501); await flushPromises(); expect(document.querySelector('span')?.textContent).toBe('4'); }); test('Re-executes subscriptions if query changes', async () => { const unSubSpy = vi.fn(); const subSpy = vi.fn(() => ({ subscribe() { return { unsubscribe: unSubSpy, }; }, })); const id = ref(0); mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [handleSubscriptions(subSpy), ...defaultPlugins()], }); const query = computed(() => { return `subscription (id: ${id.value}) { newMessages }`; }); const { data } = useSubscription<Message>({ query }); return { messages: data }; }, template: `<div></div>`, }); await flushPromises(); expect(subSpy).toHaveBeenCalledTimes(1); expect(unSubSpy).not.toHaveBeenCalled(); id.value++; await flushPromises(); expect(unSubSpy).toHaveBeenCalledTimes(1); expect(subSpy).toHaveBeenCalledTimes(2); }); test('Re-executes subscriptions if variables changes', async () => { const unSubSpy = vi.fn(); const subSpy = vi.fn(() => ({ subscribe() { return { unsubscribe: unSubSpy, }; }, })); const id = ref(0); mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [handleSubscriptions(subSpy), ...defaultPlugins()], }); const variables = computed(() => { return { id: id.value, }; }); const { data } = useSubscription<Message>({ query: `subscription { newMessages }`, variables }); return { messages: data }; }, template: `<div></div>`, }); await flushPromises(); expect(subSpy).toHaveBeenCalledTimes(1); expect(unSubSpy).not.toHaveBeenCalled(); id.value++; await flushPromises(); expect(unSubSpy).toHaveBeenCalledTimes(1); expect(subSpy).toHaveBeenCalledTimes(2); }); test('Handles subscriptions with a custom reducer', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [handleSubscriptions(() => makeObservable()), ...defaultPlugins()], }); const { data } = useSubscription<Message, string[]>( { query: `subscription { newMessages }` }, (response, oldMessages) => { if (!response.data || !oldMessages) { return oldMessages || []; } return [...oldMessages, response.data.message]; }, ); return { messages: data }; }, template: ` <div> <ul v-for="message in messages"> <li>{{ message.id }}</li> </ul> </div> `, }); await flushPromises(); vi.advanceTimersByTime(501); await flushPromises(); expect(document.querySelectorAll('li')).toHaveLength(5); }); test('Handles observer errors', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [handleSubscriptions(() => makeObservable(true)), ...defaultPlugins()], }); function reduce(response: any, oldMessages: string[] | null): string[] { if (!response.data || !oldMessages) { return oldMessages || []; } return [...oldMessages, response.data.message]; } const { data, error } = useSubscription({ query: `subscription { newMessages }` }, reduce); return { messages: data, error }; }, template: ` <div> <ul v-for="message in messages"> <li>{{ message.id }}</li> </ul> <p id="error" v-if="error">{{ error.message }}</p> </div> `, }); await flushPromises(); vi.advanceTimersByTime(150); await flushPromises(); expect(document.querySelector('#error')?.textContent).toContain('oops!'); }); test('Pauses and resumes subscriptions', async () => { const paused = ref(false); mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [handleSubscriptions(() => makeObservable()), ...defaultPlugins()], }); function reduce(response: any, oldMessages: string[] | null) { if (!response.data || !oldMessages) { return oldMessages || []; } return [...oldMessages, response.data.message]; } const { data, paused: isPaused } = useSubscription({ query: `subscription { newMessages }`, paused }, reduce); return { messages: data, isPaused }; }, template: ` <div> <ul v-for="message in messages"> <li>{{ message.id }}</li> </ul> <span id="status">{{ isPaused }}</span> </div> `, }); await flushPromises(); vi.advanceTimersByTime(201); // pauses subscription expect(document.querySelector('#status')?.textContent).toBe('false'); paused.value = true; await flushPromises(); expect(document.querySelectorAll('li')).toHaveLength(2); expect(document.querySelector('#status')?.textContent).toBe('true'); paused.value = false; await flushPromises(); vi.advanceTimersByTime(201); await flushPromises(); expect(document.querySelectorAll('li')).toHaveLength(4); expect(document.querySelector('#status')?.textContent).toBe('false'); }); test('Can pause subscriptions initially', async () => { const paused = ref(true); mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [handleSubscriptions(() => makeObservable()), ...defaultPlugins()], }); function reduce(response: any, oldMessages: string[] | null) { if (!response.data || !oldMessages) { return oldMessages || []; } return [...oldMessages, response.data.message]; } const { data, paused: isPaused } = useSubscription({ query: `subscription { newMessages }`, paused }, reduce); return { messages: data, isPaused }; }, template: ` <div> <ul v-for="message in messages"> <li>{{ message.id }}</li> </ul> <span id="status">{{ isPaused }}</span> </div> `, }); await flushPromises(); vi.advanceTimersByTime(201); // pauses subscription expect(document.querySelector('#status')?.textContent).toBe('true'); vi.advanceTimersByTime(201); expect(document.querySelectorAll('li')).toHaveLength(0); paused.value = false; await flushPromises(); expect(document.querySelector('#status')?.textContent).toBe('false'); vi.advanceTimersByTime(201); await flushPromises(); expect(document.querySelectorAll('li')).toHaveLength(2); }); test('Skips subscribing if skip is true', async () => { const unSubSpy = vi.fn(); const subSpy = vi.fn(() => ({ subscribe() { return { unsubscribe: unSubSpy, }; }, })); const id = ref(0); mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [handleSubscriptions(subSpy), ...defaultPlugins()], }); const query = `subscription (id) { newMessages }`; const { data } = useSubscription<Message>({ query, variables: () => ({ id: id.value }), skip: ({ id }) => !id }); return { messages: data }; }, template: `<div></div>`, }); await flushPromises(); expect(subSpy).not.toHaveBeenCalled(); expect(unSubSpy).not.toHaveBeenCalled(); id.value++; await flushPromises(); expect(subSpy).toHaveBeenCalledTimes(1); expect(unSubSpy).toHaveBeenCalledTimes(0); id.value--; await flushPromises(); expect(subSpy).toHaveBeenCalledTimes(1); expect(unSubSpy).toHaveBeenCalledTimes(1); }); test('Fails if provider was not resolved', () => { try { mount({ setup() { const { data, error } = useSubscription({ query: `subscription { newMessages }` }); return { messages: data, error }; }, template: ` <div> <ul v-for="message in messages"> <li>{{ message.id }}</li> </ul> <p id="error" v-if="errors">{{ error.message }}</p> </div> `, }); } catch (err) { expect((err as Error).message).toContain('Cannot detect villus Client'); } }); test('Fails if subscription forwarder was not set', () => { try { mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [handleSubscriptions(null as any)], }); const { data, error } = useSubscription({ query: `subscription { newMessages }` }); return { messages: data, error }; }, template: ` <div> <ul v-for="message in messages"> <li>{{ message.id }}</li> </ul> <p id="error" v-if="error">{{ error.message }}</p> </div> `, }); } catch (err) { expect((err as Error).message).toContain('No subscription forwarder was set'); } }); test('handles subscription errors', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [handleSubscriptions(() => makeObservable(false, true)), ...defaultPlugins()], }); const { data, error } = useSubscription<Message>({ query: `subscription { newMessages }` }); return { messages: data.value, error }; }, template: ` <div> <div v-if="messages && !error"> <span>{{ messages.id }}</span> </div> <span id="error" v-if="error">{{ error }}</span> </div> `, }); await flushPromises(); await tick(1); await flushPromises(); expect(document.querySelector('#error')?.textContent).toBeTruthy(); }); test('normalizes subscription queries', async () => { const spy = vi.fn(); mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [ handleSubscriptions(op => { spy(op.query); return makeObservable(); }), ...defaultPlugins(), ], }); const { data, error } = useSubscription<Message>({ query: gql` subscription { newMessages } `, variables: { id: 2 }, }); return { messages: data.value, error }; }, template: ` <div> <div v-if="messages && !error"> <span>{{ messages.id }}</span> </div> <span id="error" v-if="error">{{ error }}</span> </div> `, }); await flushPromises(); await tick(1); await flushPromises(); expect(spy).toHaveBeenCalledTimes(1); expect(spy).toHaveBeenLastCalledWith( print(gql` subscription { newMessages } `), ); }); test('ensure type compatability with graphql-ws', async () => { const wsClient = createClient({ url: 'ws://localhost:9005/graphql', }); const subscriptionForwarder = handleSubscriptions(operation => { return { subscribe: obs => { wsClient.subscribe( { query: operation.query, variables: operation.variables, }, obs, ); return { unsubscribe: () => { // No OP }, }; }, }; }); expect(subscriptionForwarder).toBeTruthy(); useClient({ url: 'https://test.com/graphql', use: [subscriptionForwarder], }); }); test('Allows providing initial data', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [handleSubscriptions(() => makeObservable()), ...defaultPlugins()], }); const { data } = useSubscription<Message>({ query: `subscription { newMessages }`, initialData: { id: 1, message: 'initial' }, }); return { data }; }, template: ` <div> <span>{{ data.message }}</span> </div> `, }); await flushPromises(); expect(document.querySelector('span')?.textContent).toBe('initial'); vi.advanceTimersByTime(101); await flushPromises(); expect(document.querySelector('span')?.textContent).toBe('New message'); }); test('isFetching is set to true until initial data is received', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [handleSubscriptions(() => makeObservable()), ...defaultPlugins()], }); const { isFetching } = useSubscription<Message>({ query: `subscription { newMessages }`, }); return { isFetching }; }, template: ` <div> <span>{{ isFetching }}</span> </div> `, }); await flushPromises(); expect(document.querySelector('span')?.textContent).toBe('true'); vi.advanceTimersByTime(101); await flushPromises(); expect(document.querySelector('span')?.textContent).toBe('false'); }); <file_sep>/** * Slugifies a given string */ export function slugify(str) { // eslint-disable-next-line no-useless-escape const slug = str.replace(/\s|\.|\?|\!|'/g, '-').toLowerCase(); return slug; } <file_sep>import path, { dirname } from 'path'; import { fileURLToPath } from 'url'; import typescript from '@rollup/plugin-typescript'; import replace from 'rollup-plugin-replace'; import commonjs from 'rollup-plugin-commonjs'; import resolve from 'rollup-plugin-node-resolve'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const formatNameMap = { villus: 'Villus', batch: 'VillusBatch', multipart: 'VillusMultipart', }; const pkgNameMap = { villus: 'villus', batch: 'batch', multipart: 'multipart', }; const pkgBannerMap = { villus: 'villus', batch: '@villus/batch', multipart: '@villus/multipart', }; const pkgExternals = { villus: ['vue', 'graphql'], multipart: ['extract-files', 'villus'], batch: ['villus', 'graphql'], }; const pkgGlobals = { villus: { vue: 'Vue', graphql: 'graphql', }, multipart: { 'extract-files': 'ExtractFiles', villus: 'Villus', }, batch: { villus: 'Villus', graphql: 'graphql', }, }; const formatMap = { es: 'esm', umd: '', }; async function createConfig(pkg, format) { const tsPlugin = typescript({ declarationDir: path.resolve(__dirname, `../packages/${pkg}/dist`), }); // An import assertion in a dynamic import const { default: info } = await import(path.resolve(__dirname, `../packages/${pkg}/package.json`), { assert: { type: 'json', }, }); const { version } = info; const config = { input: { input: path.resolve(__dirname, `../packages/${pkg}/src/index.ts`), external: pkgExternals[pkg], plugins: [ tsPlugin, resolve({ dedupe: ['fast-json-stable-stringify'], }), commonjs(), replace({ __VERSION__: version }), ], }, output: { banner: `/** * ${pkgBannerMap[pkg]} v${version} * (c) ${new Date().getFullYear()} <NAME> * @license MIT */`, format, name: format === 'umd' ? formatNameMap[pkg] : undefined, globals: pkgGlobals[pkg], }, }; config.bundleName = `${pkgNameMap[pkg]}${formatMap[format] ? '.' + formatMap[format] : ''}.js`; // if (options.env) { // config.input.plugins.unshift( // replace({ // 'process.env.NODE_ENV': JSON.stringify(options.env) // }) // ); // } return config; } export { formatNameMap, pkgNameMap, formatMap, createConfig }; <file_sep>import type { TypedDocumentNode, DocumentTypeDecoration } from '@graphql-typed-document-node/core'; import { DocumentNode, print } from 'graphql'; /** * Normalizes a query string or object to a string. */ export function normalizeQuery( query: string | DocumentNode | TypedDocumentNode | DocumentTypeDecoration<any, any>, ): string | null { if (typeof query === 'string') { return query; } // Supports typed document strings in 3.2 if (query && query instanceof String) { return query.toString(); } if (query && 'kind' in query) { return print(query); } return null; } <file_sep>import { ref, Ref, unref, nextTick } from 'vue'; import { MaybeRef, OperationResult, QueryExecutionContext } from './types'; import { CombinedError } from './utils'; import { Operation, QueryVariables } from '../../shared/src'; import { Client, resolveClient } from './client'; interface MutationExecutionOptions<TData> { context: MaybeRef<QueryExecutionContext>; client?: Client; clearCacheTags?: string[]; refetchTags?: string[]; onData?: (data: TData) => void; onError?: (err: CombinedError) => void; } export interface MutationResult<TData> { data: TData | null; error: CombinedError | null; } export interface MutationApi<TData, TVars> { data: Ref<TData | null>; isFetching: Ref<boolean>; isDone: Ref<boolean>; error: Ref<CombinedError | null>; execute(vars?: TVars): Promise<MutationResult<TData>>; } export function useMutation<TData = any, TVars = QueryVariables>( query: Operation<TData, TVars>['query'], opts?: Partial<MutationExecutionOptions<TData>>, ): MutationApi<TData, TVars> { const client = opts?.client ?? resolveClient(); const data: Ref<TData | null> = ref(null); const isFetching = ref(false); const isDone = ref(false); const error: Ref<CombinedError | null> = ref(null); // This is to prevent state mutation for racing requests, basically favoring the very last one let lastPendingOperation: Promise<OperationResult<TData>> | undefined; async function execute(variables?: TVars): Promise<MutationResult<TData>> { isFetching.value = true; const vars = variables || {}; const pendingExecution = client.executeMutation<TData, TVars>( { query, variables: vars as TVars, // FIXME: fix this casting clearCacheTags: [...(opts?.clearCacheTags || []), ...(opts?.refetchTags || [])], }, unref(opts?.context), ); lastPendingOperation = pendingExecution; const res = await pendingExecution; nextTick(() => { if (opts?.refetchTags) { client.refetchTaggedQueries(opts.refetchTags); } }); // Avoid state mutation if the pendingExecution isn't the last pending operation if (pendingExecution !== lastPendingOperation) { // we still return this result to preserve the integrity of "execute" calls return { data: res.data as TData, error: res.error }; } if (res.data) opts?.onData?.(res.data); if (res.error) opts?.onError?.(res.error); data.value = res.data; error.value = res.error; isDone.value = true; isFetching.value = false; lastPendingOperation = undefined; return { data: data.value, error: error.value }; } return { data, isFetching, isDone, error, execute }; } <file_sep>import { normalizeQuery } from '../../shared/src/utils'; import { ClientPlugin, ClientPluginOperation, ObservableLike, StandardOperationResult, MaybePromise } from './types'; export type SubscriptionForwarder<TData = any> = ( operation: ClientPluginOperation & { query: string }, ) => MaybePromise<ObservableLike<StandardOperationResult<TData>>>; export function handleSubscriptions(forwarder: SubscriptionForwarder): ClientPlugin { const forward = forwarder; return async function subscriptionsHandlerPlugin({ operation, useResult }) { if (operation.type !== 'subscription') { return; } if (!forward) { throw new Error('No subscription forwarder was set.'); } const normalizedQuery = normalizeQuery(operation.query); if (!normalizedQuery) { throw new Error('A query must be provided.'); } const result = await forward({ ...operation, query: normalizedQuery }); useResult(result as any, true); }; } <file_sep>import { MarkdownInstance } from 'astro'; export function generateMetaTags({ title, description, image, url, keywords }: any) { return [ { name: 'description', content: description, }, { name: 'og:description', property: 'og:description', content: description, }, { name: 'og:title', property: 'og:title', content: title, }, url ? { name: 'og:url', property: 'og:url', content: url, } : undefined, image ? { name: 'og:image', property: 'og:image', content: image, } : undefined, image ? { name: 'image', property: 'image', content: image, } : undefined, { name: 'twitter:card', content: 'summary_large_image', }, { name: 'twitter:title', property: 'twitter:title', content: title, }, { name: 'twitter:description', property: 'twitter:description', content: description, }, image ? { name: 'twitter:image', property: 'twitter:image', content: image, } : undefined, keywords ? { name: 'keywords', property: 'keywords', content: Array.isArray(keywords) ? keywords.join(', ') : keywords, } : undefined, ].filter(Boolean); } export function generateLinks({ url }) { return [ { hid: 'canonical', rel: 'canonical', href: url, }, ]; } export interface Frontmatter { title: string; order: number; } export function buildMenu(pages: MarkdownInstance<Frontmatter>[]) { return [...pages.sort((a, b) => a.frontmatter.order - b.frontmatter.order)].map(p => { return { title: p.frontmatter.title, order: p.frontmatter.order, path: p.url, }; }); } <file_sep>import { OperationResult, ClientPlugin, ClientPluginContext, ClientPluginOperation } from './types'; import { arrayToExistHash } from './utils'; interface ResultCache { [k: string]: { result: OperationResult; tags?: string[] }; } export function cache(): ClientPlugin & { clearCache(tags?: string | string[]): void } { let resultCache: ResultCache = {}; function setCacheResult({ key, tags }: ClientPluginOperation & { type: 'query' }, result: OperationResult) { resultCache[key] = { result, tags }; } function getCachedResult({ key }: ClientPluginOperation): OperationResult | undefined { return resultCache[key]?.result; } function clearCache(tags?: string | string[]) { if (!tags) { resultCache = {}; return; } const tagArray = Array.isArray(tags) ? tags : [tags]; if (!tagArray.length) { return; } const tagsLookup = arrayToExistHash(tagArray); // clears cache keys one by one Object.keys(resultCache).forEach(key => { const cacheItem = resultCache[key]; if (!cacheItem.tags) { return; } const tagExists = cacheItem.tags.some(t => tagsLookup[t]); if (tagExists) { delete resultCache[key]; } }); } function cachePlugin({ afterQuery, useResult, operation }: ClientPluginContext) { if (operation.type === 'mutation' && operation.clearCacheTags?.length) { afterQuery(result => { // only after successful operation if (result.data) { clearCache(operation.clearCacheTags); } }); return; } if (operation.type !== 'query' || operation.cachePolicy === 'network-only') { return; } // Set the cache result after query is resolved afterQuery(result => { setCacheResult(operation, result); }); // Get cached item const cachedResult = getCachedResult(operation); if (operation.cachePolicy === 'cache-only') { return useResult(cachedResult || { data: null, error: null }, true); } // if exists in cache, terminate with result if (cachedResult) { return useResult(cachedResult, operation.cachePolicy === 'cache-first'); } } cachePlugin.clearCache = clearCache; return cachePlugin; } <file_sep>import type { TypedDocumentNode, DocumentTypeDecoration } from '@graphql-typed-document-node/core'; import { DocumentNode } from 'graphql'; export interface GraphQLResponse<TData> { data: TData; errors: any; } export interface FetchOptions extends RequestInit { url?: string; headers: NonNullable<Record<string, string>>; } export interface ParsedResponse<TData> { ok: boolean; status: number; statusText: string; headers: Headers; body: GraphQLResponse<TData> | null; } export interface Operation<TData, TVars> { query: string | DocumentNode | TypedDocumentNode<TData, TVars> | DocumentTypeDecoration<TData, TVars>; variables?: TVars; } export type QueryVariables = Record<string, any>; <file_sep>import { createApp } from 'vue'; import { test, expect, vi } from 'vitest'; import flushPromises from 'flush-promises'; import { defaultPlugins } from '../src/client'; import { createClient, useQuery } from '../src/index'; import { ClientPlugin } from '../src/types'; import { PostsQuery } from './mocks/queries'; import waitForExpect from 'wait-for-expect'; test('fails if a fetcher was not provided', () => { (global as any).fetch = undefined; expect(() => { // @ts-expect-error Checking for run-time error createClient({ fetch: null }); }).toThrow(/Could not resolve/); }); test('fails if executes an non-provided query', async () => { try { const client = createClient({ url: '', }); await client.executeQuery({ query: null as any }); } catch (err) { expect((err as Error).message).toMatch(/A query must be provide/); } }); test('supports async plugins', async () => { const auth: ClientPlugin = async ({ opContext }) => { (opContext.headers as any).Authorization = 'Bearer {TOKEN}'; }; const client = createClient({ url: 'https://test.com/graphql', use: [auth, ...defaultPlugins()], }); const { data } = await client.executeQuery({ query: PostsQuery }); expect(data).toBeDefined(); }); test('throws if no plugins set the result for the operation', async () => { const client = createClient({ url: 'https://test.com/graphql', use: [], }); await expect(client.executeQuery({ query: PostsQuery })).rejects.toThrow( 'Operation result was not set by any plugin, make sure you have default plugins configured or review documentation', ); }); test('plugins can use the response', async () => { const spy = vi.fn(); const plugin: ClientPlugin = async ({ afterQuery }) => { afterQuery((_, { response }) => { spy(response?.headers.get('content-type')); }); }; const client = createClient({ url: 'https://test.com/graphql', use: [plugin, ...defaultPlugins()], }); await client.executeQuery({ query: PostsQuery }); expect(spy).toHaveBeenCalledWith('application/json'); }); test('works as a Vue plugin', async () => { const app = createApp({ setup() { const { data, error } = useQuery({ query: PostsQuery }); return { data, error }; }, template: `<div>' <div>{{ error }}</div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> </div>`, }); app.use( createClient({ url: 'https://test.com/graphql', }), ); document.body.innerHTML = `<div id="app"></div>`; app.mount('#app'); await flushPromises(); await waitForExpect(() => { expect(document.querySelectorAll('li').length).toBe(5); }); }); <file_sep># Change Log ## 3.2.0 ### Minor Changes - 559556d: feat: expose normalize query and add batching exclusion filter All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. # [3.1.0](https://github.com/logaretm/villus/compare/v3.0.0...v3.1.0) (2023-04-04) ### Features - support typed document strings ([62e5c56](https://github.com/logaretm/villus/commit/62e5c56db55ae6659b75470a3173285fed601ce7)) # [3.0.0](https://github.com/logaretm/villus/compare/v2.2.1...v3.0.0) (2023-03-20) ### Features - added data and error hooks ([8ba12ae](https://github.com/logaretm/villus/commit/8ba12aeadc1aa45169cd0f77c03ec0660740d32a)) - added subscription initial data and isFetching ([7edd698](https://github.com/logaretm/villus/commit/7edd69864bed7c9923ca28f36a1b8404e4c86424)) - **breaking:** change the reducer signature in subscriptions ([f7b3893](https://github.com/logaretm/villus/commit/f7b3893c898c538cc1f156d9638a51f5c3ba0ef8)) - expose hook handler types ([3e16cdc](https://github.com/logaretm/villus/commit/3e16cdc4cc5bb845a8476ce90239627cd7fb41e8)) ## [2.2.1](https://github.com/logaretm/villus/compare/v2.2.0...v2.2.1) (2023-03-09) ### Bug Fixes - subscriptions enhancements ([b88190b](https://github.com/logaretm/villus/commit/b88190b8528d6d9dfd7aad7514647cce6f2b4bff)) # [2.2.0](https://github.com/logaretm/villus/compare/v2.1.1...v2.2.0) (2023-03-03) ### Features - add onSuccess and onError hooks in useQuery function ([151b928](https://github.com/logaretm/villus/commit/151b928f14147051a530845f362655db67d7bb4d)) - **useQuery:** add tests ([2e3152a](https://github.com/logaretm/villus/commit/2e3152a7a5e2056100968f7b2ea893a0a11329e3)) ## [2.1.1](https://github.com/logaretm/villus/compare/v2.1.0...v2.1.1) (2023-02-08) ### Bug Fixes - ensure subscription queries are normalized closes [#188](https://github.com/logaretm/villus/issues/188) ([7a50249](https://github.com/logaretm/villus/commit/7a502495c17b8b34dc6edd6ecc5fc5620bb279c0)) - require observerlike props closes [#186](https://github.com/logaretm/villus/issues/186) closes [#154](https://github.com/logaretm/villus/issues/154) ([0c91f11](https://github.com/logaretm/villus/commit/0c91f11d44da84195636327f908a265769d72cb6)) # [2.1.0](https://github.com/logaretm/villus/compare/v2.0.2...v2.1.0) (2022-12-30) ### Features - added a mechanism to clear all cache closes [#84](https://github.com/logaretm/villus/issues/84) ([c78dfd2](https://github.com/logaretm/villus/commit/c78dfd21fbeea97ee36666f252b15b0fde235006)) - added refetching tagged queries ([18e04b9](https://github.com/logaretm/villus/commit/18e04b95e6a1efd4cedf1e77f1178033bf56508b)) - implement tag based eviction closes [#147](https://github.com/logaretm/villus/issues/147) ([9139f7e](https://github.com/logaretm/villus/commit/9139f7e5c945f053cfe5eb3d3ceb3fb717492976)) - write docs on clearing cache ([4e8e156](https://github.com/logaretm/villus/commit/4e8e1567eaa68a553c927eb15ba0fa6c350d961b)) ## [2.0.2](https://github.com/logaretm/villus/compare/v2.0.1...v2.0.2) (2022-12-28) ### Bug Fixes - **types:** ensure mutation data and error are nullable closes [#182](https://github.com/logaretm/villus/issues/182) ([#183](https://github.com/logaretm/villus/issues/183)) ([25b6e5c](https://github.com/logaretm/villus/commit/25b6e5c8b8831b697748e2dba5c8ca7b41dfd004)) ## [2.0.1](https://github.com/logaretm/villus/compare/v1.2.5...v2.0.1) (2022-10-23) **Note:** Version bump only for package villus # [2.0.0](https://github.com/logaretm/villus/compare/v1.2.5...v2.0.0) (2022-08-07) ### Bug Fixes - handle internal injections for vue 2.7 ([163242e](https://github.com/logaretm/villus/commit/163242e8e6395c3ddfb9e0d14f799101cb86db64)) ### Features - add waitFor ([e1a5aee](https://github.com/logaretm/villus/commit/e1a5aee9cd0f52e1feadb957153326189efa30fb)) - deprecate variable watching API in useQuery ([cbeef72](https://github.com/logaretm/villus/commit/cbeef721137ab75a1b09975abed23481644a3578)) - normalize the skip and pause behaviors ([3ba3576](https://github.com/logaretm/villus/commit/3ba357657ebaac868a24bdbb6f93493545afb0da)) ## [1.2.5](https://github.com/logaretm/villus/compare/v1.2.4...v1.2.5) (2022-07-31) **Note:** Version bump only for package villus ## [1.2.4](https://github.com/logaretm/villus/compare/v1.2.3...v1.2.4) (2022-07-11) ### Features - export GQL response types ([e1d75f5](https://github.com/logaretm/villus/commit/e1d75f5a75b34c16665e6513553a8c502c20dc80)) ## [1.2.3](https://github.com/logaretm/villus/compare/v1.2.2...v1.2.3) (2022-07-03) **Note:** Version bump only for package villus ## [1.2.2](https://github.com/logaretm/villus/compare/v1.2.1...v1.2.2) (2022-06-13) **Note:** Version bump only for package villus ## [1.2.1](https://github.com/logaretm/villus/compare/v1.2.0...v1.2.1) (2022-06-03) ### Bug Fixes - ensure isFetching is false after a query was skipped ([659820a](https://github.com/logaretm/villus/commit/659820acb2a5fcaf98b8ec90282a7f8179601fe8)) # [1.2.0](https://github.com/logaretm/villus/compare/v1.1.0...v1.2.0) (2022-05-30) ### Bug Fixes - query variables import path ([6a05aee](https://github.com/logaretm/villus/commit/6a05aeeb8dbee1a1aa84fb46f6d13a7346a2e222)) ### Features - added query skip argument ([9b0ba85](https://github.com/logaretm/villus/commit/9b0ba8591546ef8d17f66cd0dbbad1229902dfb4)) - allow lazy variables to be passed in to queries ([980673b](https://github.com/logaretm/villus/commit/980673b347f49f56312f60bb0367fe1aca13c2e4)) # [1.1.0](https://github.com/logaretm/villus/compare/v1.0.1...v1.1.0) (2022-04-23) ### Bug Fixes - add export types for villus.d.ts ([#155](https://github.com/logaretm/villus/issues/155)) ([ca2a6b2](https://github.com/logaretm/villus/commit/ca2a6b290b5fec2262cc65c4baf71716c4282501)) ### Features - enable useQuery etc function outside of setup and outside component ([#156](https://github.com/logaretm/villus/issues/156)) ([14335b3](https://github.com/logaretm/villus/commit/14335b31a8713c03b6573561d1c1fbdc1e84c731)) ## [1.0.1](https://github.com/logaretm/villus/compare/v1.0.0...v1.0.1) (2021-11-06) **Note:** Version bump only for package villus # [1.0.0](https://github.com/logaretm/villus/compare/v1.0.0-rc.21...v1.0.0) (2021-10-18) ### Features - add `paused` for subscriptions init object ([#143](https://github.com/logaretm/villus/issues/143)) ([9cfa418](https://github.com/logaretm/villus/commit/9cfa4188e0679aa72d1c00a7ea40fd39c58f8a06)) - added slot typing ([1aec7e7](https://github.com/logaretm/villus/commit/1aec7e727a2b2dee2a3f58708307c91198609f78)) # [1.0.0-rc.21](https://github.com/logaretm/villus/compare/v1.0.0-rc.20...v1.0.0-rc.21) (2021-08-26) **Note:** Version bump only for package villus # [1.0.0-rc.20](https://github.com/logaretm/villus/compare/v1.0.0-rc.19...v1.0.0-rc.20) (2021-08-07) **Note:** Version bump only for package villus # [1.0.0-rc.19](https://github.com/logaretm/villus/compare/v1.0.0-rc.18...v1.0.0-rc.19) (2021-07-25) ### Features - update the reactive result for cache-and-network policy closes [#76](https://github.com/logaretm/villus/issues/76) ([23cd60b](https://github.com/logaretm/villus/commit/23cd60ba3646b95514af37cd3f174e21f2151867)) # [1.0.0-rc.18](https://github.com/logaretm/villus/compare/v1.0.0-rc.17...v1.0.0-rc.18) (2021-06-29) ### Bug Fixes - added TData to client execute variants closes [#128](https://github.com/logaretm/villus/issues/128) ([80426e2](https://github.com/logaretm/villus/commit/80426e21c98301d9896f814e94c106a1374cd385)) # [1.0.0-rc.17](https://github.com/logaretm/villus/compare/v1.0.0-rc.16...v1.0.0-rc.17) (2021-05-12) **Note:** Version bump only for package villus # [1.0.0-rc.16](https://github.com/logaretm/villus/compare/v1.0.0-rc.15...v1.0.0-rc.16) (2021-04-15) **Note:** Version bump only for package villus # [1.0.0-rc.15](https://github.com/logaretm/villus/compare/v1.0.0-rc.14...v1.0.0-rc.15) (2021-03-06) ### Bug Fixes - explose villus public types closes [#105](https://github.com/logaretm/villus/issues/105) ([a9b62de](https://github.com/logaretm/villus/commit/a9b62de2e24fba25c26cbf3527606d6f258a8b4c)) - used correct import of type ([608018a](https://github.com/logaretm/villus/commit/608018a6fad13cd2626cf3cc9609e28d5dc472b4)) # [1.0.0-rc.14](https://github.com/logaretm/villus/compare/v1.0.0-rc.13...v1.0.0-rc.14) (2021-03-04) ### Bug Fixes - handle multiple executions state integrity ([43d936b](https://github.com/logaretm/villus/commit/43d936b91a407af0e3e83a1f1a1c81dbb00d0806)) # [1.0.0-rc.13](https://github.com/logaretm/villus/compare/v1.0.0-rc.12...v1.0.0-rc.13) (2021-02-27) ### Bug Fixes - ensure fetch recongizes partial error responses ([6c0a6fa](https://github.com/logaretm/villus/commit/6c0a6fa81a57131c9c23758435a1143f3fafd33d)) # [1.0.0-rc.12](https://github.com/logaretm/villus/compare/v1.0.0-beta.0...v1.0.0-rc.12) (2021-02-16) ### Bug Fixes - effect conditions for Query and Subscription components ([20f6803](https://github.com/logaretm/villus/commit/20f68035861916dffadbe11ea5a55739cc1e9ac8)) - ensure executeopts arg is optional ([f3f4bca](https://github.com/logaretm/villus/commit/f3f4bca64121938d22329ed70f5d6dceb1693121)) - expose villus client symbol for testing ([141bf97](https://github.com/logaretm/villus/commit/141bf9717250894d58a71ce3dd8a28160677b229)) - fetchonMounted typo ([09c3de4](https://github.com/logaretm/villus/commit/09c3de457e4a4b30742e5f315b1241b0961681fb)) - handle non 200 error responses closes [#49](https://github.com/logaretm/villus/issues/49) ([0950fa8](https://github.com/logaretm/villus/commit/0950fa8a82060a02871d4eb027841eb0ecb31f96)) - only resubscribe if the query/vars change closes [#94](https://github.com/logaretm/villus/issues/94) ([739b75e](https://github.com/logaretm/villus/commit/739b75e8e140fa418011672ba081bf10a4611237)) - prevent running the query onMounted when suspended closes [#56](https://github.com/logaretm/villus/issues/56) ([27385b6](https://github.com/logaretm/villus/commit/27385b66e196a43e6ab64800183a693939f5320a)) - remove invalid import ([3bfdaf7](https://github.com/logaretm/villus/commit/3bfdaf77028549c22705f0a702bb84a4dcd1d66f)) - safe access to the provides property ([73efd25](https://github.com/logaretm/villus/commit/73efd25399988ea3615e208fff16ef8fbcd5d7e1)) - type import path ([9c7c12c](https://github.com/logaretm/villus/commit/9c7c12ce0bbf8f1cf2d88b6b1b2d56a1b21299ba)) - type the patched useResult ([31fe56b](https://github.com/logaretm/villus/commit/31fe56b89f9f8d02c48c02beec4227618cc6f2d8)) - typing of operation in fetch plugin ([2dc8173](https://github.com/logaretm/villus/commit/2dc81738c784f00373a95d70bd75a38a3e35d62d)) - use QueryVariables as default type for subscription forwarder [#93](https://github.com/logaretm/villus/issues/93) ([3791251](https://github.com/logaretm/villus/commit/37912514ce7f5fe1123d0f2c46c95963c67203ef)) - use standard execution result for subscription forwarder closes [#93](https://github.com/logaretm/villus/issues/93) ([9ced480](https://github.com/logaretm/villus/commit/9ced480d387edb8d1d8893cc88d3ae0e856a897c)) ### Features - add install method to client ([#83](https://github.com/logaretm/villus/issues/83)) ([397bbdb](https://github.com/logaretm/villus/commit/397bbdb612a4bacfd5f3b9242d48b2ec94ccde14)) - added context per query basis closes [#96](https://github.com/logaretm/villus/issues/96) ([8248b06](https://github.com/logaretm/villus/commit/8248b06674a4bf2757f0025740d7b775945acc09)) - added dedup test ([8b12141](https://github.com/logaretm/villus/commit/8b1214155b0bd8c4ff1c89734af8ba1d6e2838f1)) - allow adding other hash items to the query key helper ([5d18e8a](https://github.com/logaretm/villus/commit/5d18e8a7c3016cc9adef0bacfe43076878654a73)) - avoid deduping mutations and subscriptions ([3bb9642](https://github.com/logaretm/villus/commit/3bb9642990b8fac1352964c965b6483ad0626655)) - changed the signature of provider and useClient ([b4fa6d9](https://github.com/logaretm/villus/commit/b4fa6d953a4997554497253bf520d401c571d4b2)) - enhance suspense query suspense API and allow override query vars ([c38e574](https://github.com/logaretm/villus/commit/c38e574a12801cf8e15b05c37637bc62b1cae9b4)) - export plugins types ([598a65f](https://github.com/logaretm/villus/commit/598a65fec909ae273aa2bb588e0d9e3d306dee88)) - expose getQueryKey helper ([26548d5](https://github.com/logaretm/villus/commit/26548d575d579bd1cff44c7cbacc93c07e06fee8)) - expose new definePlugin type helper ([6f79a97](https://github.com/logaretm/villus/commit/6f79a97b040f132cdbea97a7e6050043f21b2195)) - implement dedup plugin ([eb0f0a3](https://github.com/logaretm/villus/commit/eb0f0a36947aec6a5cf02a0b395acfe32f63f1d8)) - implement response context closes [#62](https://github.com/logaretm/villus/issues/62) ([04cae29](https://github.com/logaretm/villus/commit/04cae29a8ba6163127a6da4985e37585084763ce)) - initial isFetching ([#74](https://github.com/logaretm/villus/issues/74)) ([ea043da](https://github.com/logaretm/villus/commit/ea043da2a4d25c81e772c2a8b9a8c9ddf33e6680)) - re-execute subscriptions closes [#79](https://github.com/logaretm/villus/issues/79) ([0ec4680](https://github.com/logaretm/villus/commit/0ec46802c80788531a7b84c516eac9d879b076e8)) - re-implement subscriptions as a plugin ([e5e790a](https://github.com/logaretm/villus/commit/e5e790a404eb0cc27a9320999c03484e8bf575d5)) - remove initialIsFetching and sync it with fetchOnMount ([a1e75c4](https://github.com/logaretm/villus/commit/a1e75c4aeb800a2e22e123bb1c75271258ff09dc)) - rename lazy to fetchOnMount ([68b937e](https://github.com/logaretm/villus/commit/68b937ebfc91037494be33a67f643c22e11b5064)) - rename pause and resume for queries to be more explicit ([ca9cf1e](https://github.com/logaretm/villus/commit/ca9cf1eb93aeff8a40cc9d85465e45089990d412)) - rename pause prop to paused and watch its effect ([fca32d4](https://github.com/logaretm/villus/commit/fca32d4e03f57312340ca0cea6d6697eef21280a)) - rename suspend prop to suspended for consistency ([06eaecd](https://github.com/logaretm/villus/commit/06eaecd8a5ac02f82d015511c8fb80db79150deb)) - support typed document node ([9c166f6](https://github.com/logaretm/villus/commit/9c166f6bffa589ec580d8e8d6f2729ab17a662c0)) - updated graphql dep closes [#65](https://github.com/logaretm/villus/issues/65) ([ef4be0a](https://github.com/logaretm/villus/commit/ef4be0afb8cba12a57c5cc128b999f570898fa69)) - upgrade Vue and provide a workaround for [#72](https://github.com/logaretm/villus/issues/72) ([6127f37](https://github.com/logaretm/villus/commit/6127f379adf743b691f48f9bc6d044553f9771b5)) - **breaking:** signature updates ([#70](https://github.com/logaretm/villus/issues/70)) ([47937e8](https://github.com/logaretm/villus/commit/47937e8437cae6e78769dc7b0abfa2f4c41f5996)) - updated query component prop names ([d0fc40d](https://github.com/logaretm/villus/commit/d0fc40d7376c6e8cd3d7cfb02b03198e7e7d11f9)) - use defineComponent helper with subscription ([ef7c16a](https://github.com/logaretm/villus/commit/ef7c16a4948b407f36523b037d58db41d9f50302)) - use the defineComponent helper with Mutation component ([eb72067](https://github.com/logaretm/villus/commit/eb7206783e898b710463c87f0cb2a2e880c659e9)) - use the defineComponent helper with Query component and omit redudencies ([d00e25b](https://github.com/logaretm/villus/commit/d00e25b8d924434ab44602d65788a2d4a9da5bda)) # [1.0.0-rc.11](https://github.com/logaretm/villus/compare/villus@1.0.0-rc.10...villus@1.0.0-rc.11) (2021-01-20) ### Bug Fixes - only resubscribe if the query/vars change closes [#94](https://github.com/logaretm/villus/issues/94) ([739b75e](https://github.com/logaretm/villus/commit/739b75e8e140fa418011672ba081bf10a4611237)) - use QueryVariables as default type for subscription forwarder [#93](https://github.com/logaretm/villus/issues/93) ([3791251](https://github.com/logaretm/villus/commit/37912514ce7f5fe1123d0f2c46c95963c67203ef)) - use standard execution result for subscription forwarder closes [#93](https://github.com/logaretm/villus/issues/93) ([9ced480](https://github.com/logaretm/villus/commit/9ced480d387edb8d1d8893cc88d3ae0e856a897c)) # [1.0.0-rc.10](https://github.com/logaretm/villus/compare/villus@1.0.0-rc.9...villus@1.0.0-rc.10) (2021-01-17) ### Bug Fixes - ensure executeopts arg is optional ([f3f4bca](https://github.com/logaretm/villus/commit/f3f4bca64121938d22329ed70f5d6dceb1693121)) # [1.0.0-rc.9](https://github.com/logaretm/villus/compare/villus@1.0.0-rc.8...villus@1.0.0-rc.9) (2021-01-15) ### Features - enhance suspense query suspense API and allow override query vars ([c38e574](https://github.com/logaretm/villus/commit/c38e574a12801cf8e15b05c37637bc62b1cae9b4)) # [1.0.0-rc.8](https://github.com/logaretm/villus/compare/villus@1.0.0-rc.7...villus@1.0.0-rc.8) (2021-01-05) ### Bug Fixes - expose villus client symbol for testing ([141bf97](https://github.com/logaretm/villus/commit/141bf9717250894d58a71ce3dd8a28160677b229)) # [1.0.0-rc.7](https://github.com/logaretm/villus/compare/villus@1.0.0-rc.6...villus@1.0.0-rc.7) (2021-01-02) ### Features - remove initialIsFetching and sync it with fetchOnMount ([a1e75c4](https://github.com/logaretm/villus/commit/a1e75c4aeb800a2e22e123bb1c75271258ff09dc)) # [1.0.0-rc.6](https://github.com/logaretm/villus/compare/villus@1.0.0-rc.5...villus@1.0.0-rc.6) (2020-11-26) ### Features - add install method to client ([#83](https://github.com/logaretm/villus/issues/83)) ([397bbdb](https://github.com/logaretm/villus/commit/397bbdb612a4bacfd5f3b9242d48b2ec94ccde14)) # [1.0.0-rc.5](https://github.com/logaretm/villus/compare/villus@1.0.0-rc.4...villus@1.0.0-rc.5) (2020-11-25) ### Bug Fixes - remove invalid import ([3bfdaf7](https://github.com/logaretm/villus/commit/3bfdaf77028549c22705f0a702bb84a4dcd1d66f)) ### Features - allow adding other hash items to the query key helper ([5d18e8a](https://github.com/logaretm/villus/commit/5d18e8a7c3016cc9adef0bacfe43076878654a73)) - expose getQueryKey helper ([26548d5](https://github.com/logaretm/villus/commit/26548d575d579bd1cff44c7cbacc93c07e06fee8)) - re-execute subscriptions closes [#79](https://github.com/logaretm/villus/issues/79) ([0ec4680](https://github.com/logaretm/villus/commit/0ec46802c80788531a7b84c516eac9d879b076e8)) # [1.0.0-rc.4](https://github.com/logaretm/villus/compare/villus@1.0.0-rc.3...villus@1.0.0-rc.4) (2020-11-01) ### Features - expose new definePlugin type helper ([6f79a97](https://github.com/logaretm/villus/commit/6f79a97b040f132cdbea97a7e6050043f21b2195)) # [1.0.0-rc.3](https://github.com/logaretm/villus/compare/villus@1.0.0-rc.2...villus@1.0.0-rc.3) (2020-10-28) ### Features - initial isFetching ([#74](https://github.com/logaretm/villus/issues/74)) ([ea043da](https://github.com/logaretm/villus/commit/ea043da2a4d25c81e772c2a8b9a8c9ddf33e6680)) # [1.0.0-rc.2](https://github.com/logaretm/villus/compare/villus@1.0.0-rc.1...villus@1.0.0-rc.2) (2020-10-27) ### Bug Fixes - safe access to the provides property ([73efd25](https://github.com/logaretm/villus/commit/73efd25399988ea3615e208fff16ef8fbcd5d7e1)) # [1.0.0-rc.1](https://github.com/logaretm/villus/compare/villus@1.0.0-rc.0...villus@1.0.0-rc.1) (2020-10-26) ### Features - upgrade Vue and provide a workaround for [#72](https://github.com/logaretm/villus/issues/72) ([6127f37](https://github.com/logaretm/villus/commit/6127f379adf743b691f48f9bc6d044553f9771b5)) # [1.0.0-rc.0](https://github.com/logaretm/villus/compare/villus@1.0.0-beta.8...villus@1.0.0-rc.0) (2020-10-22) ### Features - **breaking:** signature updates ([#70](https://github.com/logaretm/villus/issues/70)) ([47937e8](https://github.com/logaretm/villus/commit/47937e8437cae6e78769dc7b0abfa2f4c41f5996)) # [1.0.0-beta.8](https://github.com/logaretm/villus/compare/villus@1.0.0-beta.7...villus@1.0.0-beta.8) (2020-10-21) ### Bug Fixes - type import path ([9c7c12c](https://github.com/logaretm/villus/commit/9c7c12ce0bbf8f1cf2d88b6b1b2d56a1b21299ba)) - type the patched useResult ([31fe56b](https://github.com/logaretm/villus/commit/31fe56b89f9f8d02c48c02beec4227618cc6f2d8)) ### Features - added dedup test ([8b12141](https://github.com/logaretm/villus/commit/8b1214155b0bd8c4ff1c89734af8ba1d6e2838f1)) - avoid deduping mutations and subscriptions ([3bb9642](https://github.com/logaretm/villus/commit/3bb9642990b8fac1352964c965b6483ad0626655)) - implement dedup plugin ([eb0f0a3](https://github.com/logaretm/villus/commit/eb0f0a36947aec6a5cf02a0b395acfe32f63f1d8)) - implement response context closes [#62](https://github.com/logaretm/villus/issues/62) ([04cae29](https://github.com/logaretm/villus/commit/04cae29a8ba6163127a6da4985e37585084763ce)) - updated graphql dep closes [#65](https://github.com/logaretm/villus/issues/65) ([ef4be0a](https://github.com/logaretm/villus/commit/ef4be0afb8cba12a57c5cc128b999f570898fa69)) # [1.0.0-beta.7](https://github.com/logaretm/villus/compare/villus@1.0.0-beta.6...villus@1.0.0-beta.7) (2020-10-19) ### Bug Fixes - typing of operation in fetch plugin ([2dc8173](https://github.com/logaretm/villus/commit/2dc81738c784f00373a95d70bd75a38a3e35d62d)) ### Features - support typed document node ([9c166f6](https://github.com/logaretm/villus/commit/9c166f6bffa589ec580d8e8d6f2729ab17a662c0)) # [1.0.0-beta.6](https://github.com/logaretm/villus/compare/villus@1.0.0-beta.5...villus@1.0.0-beta.6) (2020-10-09) ### Bug Fixes - prevent running the query onMounted when suspended closes [#56](https://github.com/logaretm/villus/issues/56) ([27385b6](https://github.com/logaretm/villus/commit/27385b66e196a43e6ab64800183a693939f5320a)) # [1.0.0-beta.5](https://github.com/logaretm/villus/compare/villus@1.0.0-beta.4...villus@1.0.0-beta.5) (2020-10-09) ### Bug Fixes - fetchonMounted typo ([09c3de4](https://github.com/logaretm/villus/commit/09c3de457e4a4b30742e5f315b1241b0961681fb)) # [1.0.0-beta.4](https://github.com/logaretm/villus/compare/villus@1.0.0-beta.3...villus@1.0.0-beta.4) (2020-10-07) ### Bug Fixes - effect conditions for Query and Subscription components ([20f6803](https://github.com/logaretm/villus/commit/20f68035861916dffadbe11ea5a55739cc1e9ac8)) ### Features - re-implement subscriptions as a plugin ([e5e790a](https://github.com/logaretm/villus/commit/e5e790a404eb0cc27a9320999c03484e8bf575d5)) - rename lazy to fetchOnMount ([68b937e](https://github.com/logaretm/villus/commit/68b937ebfc91037494be33a67f643c22e11b5064)) - rename pause and resume for queries to be more explicit ([ca9cf1e](https://github.com/logaretm/villus/commit/ca9cf1eb93aeff8a40cc9d85465e45089990d412)) - rename pause prop to paused and watch its effect ([fca32d4](https://github.com/logaretm/villus/commit/fca32d4e03f57312340ca0cea6d6697eef21280a)) - rename suspend prop to suspended for consistency ([06eaecd](https://github.com/logaretm/villus/commit/06eaecd8a5ac02f82d015511c8fb80db79150deb)) - updated query component prop names ([d0fc40d](https://github.com/logaretm/villus/commit/d0fc40d7376c6e8cd3d7cfb02b03198e7e7d11f9)) - use defineComponent helper with subscription ([ef7c16a](https://github.com/logaretm/villus/commit/ef7c16a4948b407f36523b037d58db41d9f50302)) - use the defineComponent helper with Mutation component ([eb72067](https://github.com/logaretm/villus/commit/eb7206783e898b710463c87f0cb2a2e880c659e9)) - use the defineComponent helper with Query component and omit redudencies ([d00e25b](https://github.com/logaretm/villus/commit/d00e25b8d924434ab44602d65788a2d4a9da5bda)) # [1.0.0-beta.3](https://github.com/logaretm/villus/compare/villus@1.0.0-beta.2...villus@1.0.0-beta.3) (2020-10-05) **Note:** Version bump only for package villus # [1.0.0-beta.2](https://github.com/logaretm/villus/compare/villus@1.0.0-beta.1...villus@1.0.0-beta.2) (2020-10-02) **Note:** Version bump only for package villus # 1.0.0-beta.1 (2020-09-30) ### Breaking Changes - deprecate the `context` and `fetch` options in favor of [custom plugins API](https://villus.logaretm.com/villus/guide/plugins) - deprecate the exported `batch` fetcher in favor of [`@villus/batch` plugin](https://villus.logaretm.com/villus/plugins/batch) - changed the signature of provider and useClient ([b4fa6d9](https://github.com/logaretm/villus/commit/b4fa6d953a4997554497253bf520d401c571d4b2)) due to conflicts with TypeScript typings ### Bug Fixes - handle non 200 error responses closes [#49](https://github.com/logaretm/villus/issues/49) ([0950fa8](https://github.com/logaretm/villus/commit/0950fa8a82060a02871d4eb027841eb0ecb31f96)) ### Features #### Plugins API A large chunk of villus code has been re-written from scratch to use a pipeline-like operation transformers (plugins) similair to what apollo client and urql are doing with much less jargon and complexity, they are just a simple middleware performing operations on GraphQL queries as they go out or after execution. [Check the documentation here](https://villus.logaretm.com/villus/guide/plugins) #### `multipart` plugin The `multipart` plugin will enable support for graphql file upload, [check the documentation and examples here](https://villus.logaretm.com/villus/plugins/multipart) <file_sep>--- layout: ../../layouts/PageLayout.astro title: Subscriptions description: Learn how to run GraphQL subscriptions order: 5 --- import DocTip from '@/components/DocTip.vue'; # Subscriptions `villus` handles subscriptions with the `useSubscription` function. To add support for subscriptions you need to add the `handleSubscriptions` plugin to the `useClient` plugin list, which in turn will call your subscription client. The plugin expects an a function that returns an object that follows the [observable spec](https://github.com/tc39/proposal-observable) to be returned, this function is called a **subscription forwarder**. You can use [`graphql-ws`](https://github.com/enisdenjo/graphql-ws) package for your subscriptions implemented with websockets protocol, so one way to build your subscription forwarder is like this: ```vue <script setup> import { useClient } from 'villus'; import { createClient } from 'graphql-ws'; const wsClient = createClient({ url: 'ws://localhost:9005/graphql', }); const subscriptionsHandler = handleSubscriptions(operation => { return { subscribe: obs => { wsClient.subscribe( { query: operation.query, variables: operation.variables, }, obs ); return { unsubscribe: () => { // No OP }, }; }, }; }); const client = useClient({ url: 'http://localhost:4000/graphql', // Install the subscriptions handler use: [subscriptionsHandler, ...defaultPlugins()], }); </script> ``` ## Executing Subscriptions The `useSubscription` function has a similar API as it exposes a `data` property that you can watch ```vue <template> <ul> <li v-for="message in messages">{{ message }}</li> </ul> </template> <script setup> import { watch, ref } from 'vue'; import { useSubscription } from 'villus'; const NewMessages = ` subscription NewMessages { newMessages { id from message } } `; const messages = ref([]); useSubscription({ query: NewMessages }, ({ data, error }) => { // do stuff with incoming data if (data) { messages.value.push(...data.newMessages); } // Handler errors if (error) { } }); </script> ``` ## Passing Variables You can pass variables to subscriptions by passing an object containing both `query` and `variables` as the first argument: ```vue <script setup> import { useSubscription } from 'villus'; const NewMessages = ` subscription ConversationMessages ($id: ID!) { conversation(id: $id) { id from message } } `; const { data } = useSubscription({ query: NewMessages, variables: { id: 1 }, }); </script> ``` ## Handling Subscription Data The previous examples are not very useful, as usually you would like to be able to use the `data` as a continuous value rather than a reference to the last received value, that is why you can pass a custom mapper or a reducer as the second argument to the `useSubscription` function. This callback function receives the new result from the subscription as the first argument, and the reduced data if available as the second argument. You can use it as either a mapper or a reducer depending on what you return from the function. to understand the difference between a mapper and a reducer check the next couple of examples. ### Mapping data In the following example, the passed function only extracts the `lastMessage` field out from the response data. That means it only returns a mapped version of the last result recieved. ```vue{19-22} <script setup> import { useSubscription } from 'villus'; const LastMessage = ` subscription LastMessage { lastMessage { id from message } } `; // rename data to be more descriptive of its usage const { data: lastMessage } = useSubscription( { query: LastMessage, }, ({ data }) => { // remember that data can be null return data?.lastMessage; } ); // anywhere lastMessage.value; // { id: 1, from: 'someone', message: 'hello' } </script> ``` This is useful for subscriptions that represent a live state for something on your API. You are not limited to mapping the results in a specific way, for example if you want to return a boolean, you can do so: ```vue{17-19} <script setup> import { useSubscription } from 'villus'; const UnreadMessages = ` subscription UnreadMessages { unreadMessages { id } } `; // rename data to be more descriptive of its usage const { data: hasUnread } = useSubscription( { query: UnreadMessages, }, ({ data }) => { return data?.unreadMessages.length > 1 } ); // anywhere hasUnread.value; // true or false </script> ``` So it is completely is up to you how to map the data and make them useful to your needs. ### Reducing data The reducer is a subscription handler that aggregates past and future results into a single value. The aggregated value will become the `data` returned from `useSubscription`. Here is the last example with a custom reducer: ```vue{19-29} <script setup> import { useSubscription } from 'villus'; const NewMessages = ` subscription NewMessages { newMessages { id from message } } `; // rename data to make it more clear const { data: messages } = useSubscription( { query: NewMessages, }, ({ data, error }, oldValue) => { // old value is nullable oldValue = oldValue || []; // in case of error just return the last value if (!data || error) { return oldValue; } // combine old and incoming messages return [...oldValue, response.data.newMessages]; } ); messages.value; // { id, from, message }[] </script> ``` The function here acts as a reducer for the incoming data, whenever a new response is received it will be passed to `reduceMessages` function as the second argument, the first argument will be the previous value. This makes it more compact than having to declare state or watching over the data yourself. <DocTip> Keep in mind that initially, we have `null` for the initial value so we needed to provide a fallback for that. </DocTip> ## Pausing subscriptions Similar to queries, subscriptions could also be paused by passing a `paused` value to `useSubscription`. ```vue <script setup> import { ref } from 'vue'; import { useSubscription } from 'villus'; const NewMessages = ` subscription ConversationMessages ($id: ID!) { conversation(id: $id) { id from message } } `; const paused = ref(false); const { data } = useSubscription({ query: NewMessages, variables: { id: 1 }, paused, }); // pause the subscription paused.value = true; // resume the subscription paused.value = false; </script> ``` Note that pausing or unpausing doesn't sever the established connection (if websocket implementation is used), all it does is ignore the incoming values. <file_sep>--- layout: ../../layouts/PageLayout.astro title: Fetch Plugin description: The plugin that executes your queries order: 1 --- import DocTip from '@/components/DocTip.vue'; # Fetch Plugin The fetch plugin is both a very simple plugin and a critical one to villus inner workings. Because villus is built using a pipeline of plugins that perform some processing on a GraphQL operation. The fetch plugin is the one that executes your queries and mutations against the GraphQL API which is why it is very important to either have a `fetch` or `batch` plugin, or any similar plugins you may write on your own. <DocTip> The fetch plugin is one of the default plugins that are pre-configured with any villus client unless specified otherwise </DocTip> ## Options You can customize a few aspects of the `fetch` plugin: ```vue <script setup> import { useClient, fetch } from 'villus'; const fetchPlugin = fetch({ // plugin options... }); useClient({ use: [fetchPlugin], }); </script> ``` The available options are: | Option | Type | Description | | ------ | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | fetch | `typeof window.fetch` | Pass this option if you plan to be specific about the `fetch` polyfill that will be used, by default it tries to find `window.fetch` on the browser or `global.fetch` on Node.js depending on the execution environment | ## Code You can check the [source code for the `fetch` plugin](https://github.com/logaretm/villus/blob/main/packages/villus/src/fetch.ts) and use it as a reference to build your own <file_sep>--- layout: ../../layouts/PageLayout.astro title: Query Batching Plugin description: Learn how to run batch multiple GraphQL queries order: 4 --- import DocTip from '@/components/DocTip.vue'; # Query Batching Villus has support for query batching but it is not configured out of the box, this is because not all GraphQL implementations support query-batching. So you would need to manually import it and configure it with `villus` client. The batch plugin is available as its own package under the name `@villus/batch` ## Basic Batching First, add the plugin to your dependencies using `yarn` or `npm`: ```bash yarn add @villus/batch # Or npm install @villus/batch ``` Then import the `batch` plugin from `villus` and pass it at the very end of the `plugins` array in client configuration: ```vue <script setup> import { useClient } from 'villus'; import { batch } from '@villus/batch'; useClient({ url: 'https://test.com/graphql', use: [batch()], }); </script> ``` <DocTip type="danger"> Careful not to use `batch` with the default `fetch` plugin, both of them act as a fetcher and there can only be 1 fetcher plugin for `villus` at any given time. </DocTip> And that's it, all your nested components that use `useQuery` or `useMutation` will automatically be batched together in a single request: ```vue <template> <div> <ul v-if="postsWithTitle"> <li v-for="post in postsWithTitle.posts" :key="post.id">{{ post.title }}</li> </ul> <ul v-if="postsWithId"> <li v-for="post in postsWithId.posts" :key="post.id">{{ post.title }}</li> </ul> </div> </template> <script setup> import { useQuery } from 'villus'; // Both will be sent in a single request const firstQuery = useQuery('{ posts { title } }'); const secondQuery = useQuery('{ posts { id } }'); </script> ``` ## Batching timeout Batching is done by waiting for a specific time which is `10ms` by default since the last executed query, and all queries executed within this time window will be batched together. You can configure that time window by passing a `timeout` option to the `batch` function configuration: ```vue{7} <script setup> import { useClient } from 'villus'; import { batch } from '@villus/batch'; useClient({ url: 'https://test.com/graphql', use: [batch({ timeout: 50 })], }); </script> ``` This will add a `50ms` time window between queries to be batched together. ## Batched operations limit You can also introduce a limit on how many operations can be executed in a batch. Usually, it is a good idea to make sure you don't include a lot of operations in a single batch which could have an inverse effect on performance since the total execution time now depends on all the operations being executed. You can configure the batch limit by passing a `maxOperationCount` option to the `batch` function configuration: ```vue{7} <script setup> import { useClient } from 'villus'; import { batch } from '@villus/batch'; useClient({ url: 'https://test.com/graphql', use: [batch({ maxOperationCount: 5 })], }); </script> ``` By default, it is `10`. ## Excluding certain operations You can also exclude certain operations from being batched by passing an `exclude` option to the `batch` function configuration: ```vue{7,8} <script setup> import { useClient } from 'villus'; import { batch } from '@villus/batch'; useClient({ url: 'https://test.com/graphql', // Exclude all queries named "Posts" use: [batch({ exclude: ({ query }) => /query Posts/.test(query) })], }); </script> ``` ## Options You can customize a few aspects of the `batch` plugin: The available options are: | Option | Type | Description | | ----------------- | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | fetch | `typeof window.fetch` | Pass this option if you plan to be specific about the `fetch` polyfill that will be used, by default it tries to find `window.fetch` on the browser or `global.fetch` on Node.js depending on the execution environment | | timeout | `number` | The number of milliseconds to wait for before executing the batched queries | | maxOperationCount | `number` | The maximum number of operations to be included in a single batch | | exclude | `(operation: ClientPluginOperation, ctx: PluginContext) => boolean` | If returns true, the operation won't be batched and will be fetched in a single non-batched request | ## Code You can check the [source code for the `batch` plugin](https://github.com/logaretm/villus/blob/main/packages/batch/src/index.ts) and use it as a reference to build your own <file_sep>import { isReactive, isRef, Ref, unref, nextTick } from 'vue'; import { MaybeLazyOrRef, QueryPredicateOrSignal, MaybeRef } from '../types'; import stringify from 'fast-json-stable-stringify'; import { QueryVariables } from '../../../shared/src'; export function unravel<TVars = QueryVariables>( signal: QueryPredicateOrSignal<TVars> | undefined, vars: MaybeRef<TVars>, ) { if (isRef(signal)) { return signal.value; } if (typeof signal === 'function') { return signal(unref(vars)); } return signal; } export function unwrap<TValue>(val: MaybeLazyOrRef<TValue>) { if (isRef(val)) { return unref(val); } // TODO: typescript bug to fix here return typeof val === 'function' ? (val as any)() : val; } export function isWatchable<T>(val: unknown): val is Ref<T> { return isRef(val) || isReactive(val) || typeof val === 'function'; } export function arrayToExistHash<T extends string | number>(items: T[]): Record<string, boolean> { return items.reduce( (acc, item) => { acc[String(item)] = true; return acc; }, {} as Record<string, boolean>, ); } export function debounceAsync<TFunction extends (...args: any) => Promise<any>, TResult = ReturnType<TFunction>>( inner: TFunction, ): (...args: Parameters<TFunction>) => Promise<TResult> { let resolves: any[] = []; let ticking = false; return function (...args: Parameters<TFunction>) { if (!ticking) { nextTick(() => { const result = inner(...(args as any)); resolves.forEach(r => r(result)); resolves = []; ticking = false; }); ticking = true; } return new Promise<TResult>(resolve => resolves.push(resolve)); }; } export function isEqual(lhs: unknown, rhs: unknown) { return stringify(lhs) === stringify(rhs); } export function useCallback<THandler extends (...a: any[]) => any>() { const hooks: Set<THandler> = new Set(); function on(handler: THandler) { hooks.add(handler); return () => { hooks.delete(handler); }; } async function run(...args: Parameters<THandler>) { for (const hook of hooks) { await hook(...args); } } return { on, run, }; } <file_sep># Change Log ## 3.2.0 ### Patch Changes - Updated dependencies [559556d] - villus@3.2.0 All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. # [3.1.0](https://github.com/logaretm/villus/compare/v3.0.0...v3.1.0) (2023-04-04) **Note:** Version bump only for package @villus/multipart # [3.0.0](https://github.com/logaretm/villus/compare/v2.2.1...v3.0.0) (2023-03-20) ### Bug Fixes - reference packages ([c6622cb](https://github.com/logaretm/villus/commit/c6622cbdc237faf8fc7581cb6cdbb969912f15d7)) ## [2.2.1](https://github.com/logaretm/villus/compare/v2.2.0...v2.2.1) (2023-03-09) **Note:** Version bump only for package @villus/multipart # [2.2.0](https://github.com/logaretm/villus/compare/v2.1.1...v2.2.0) (2023-03-03) **Note:** Version bump only for package @villus/multipart ## [2.1.1](https://github.com/logaretm/villus/compare/v2.1.0...v2.1.1) (2023-02-08) **Note:** Version bump only for package @villus/multipart # [2.1.0](https://github.com/logaretm/villus/compare/v2.0.2...v2.1.0) (2022-12-30) **Note:** Version bump only for package @villus/multipart ## [2.0.2](https://github.com/logaretm/villus/compare/v2.0.1...v2.0.2) (2022-12-28) **Note:** Version bump only for package @villus/multipart ## [2.0.1](https://github.com/logaretm/villus/compare/v1.2.5...v2.0.1) (2022-10-23) **Note:** Version bump only for package @villus/multipart # [2.0.0](https://github.com/logaretm/villus/compare/v1.2.5...v2.0.0) (2022-08-07) **Note:** Version bump only for package @villus/multipart ## [1.2.5](https://github.com/logaretm/villus/compare/v1.2.4...v1.2.5) (2022-07-31) **Note:** Version bump only for package @villus/multipart ## [1.2.4](https://github.com/logaretm/villus/compare/v1.2.3...v1.2.4) (2022-07-11) **Note:** Version bump only for package @villus/multipart ## [1.2.3](https://github.com/logaretm/villus/compare/v1.2.2...v1.2.3) (2022-07-03) **Note:** Version bump only for package @villus/multipart ## [1.2.2](https://github.com/logaretm/villus/compare/v1.2.1...v1.2.2) (2022-06-13) **Note:** Version bump only for package @villus/multipart ## [1.2.1](https://github.com/logaretm/villus/compare/v1.2.0...v1.2.1) (2022-06-03) **Note:** Version bump only for package @villus/multipart # [1.2.0](https://github.com/logaretm/villus/compare/v1.1.0...v1.2.0) (2022-05-30) **Note:** Version bump only for package @villus/multipart # [1.1.0](https://github.com/logaretm/villus/compare/v1.0.1...v1.1.0) (2022-04-23) **Note:** Version bump only for package @villus/multipart ## [1.0.1](https://github.com/logaretm/villus/compare/v1.0.0...v1.0.1) (2021-11-06) **Note:** Version bump only for package @villus/multipart # [1.0.0](https://github.com/logaretm/villus/compare/v1.0.0-rc.21...v1.0.0) (2021-10-18) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.21](https://github.com/logaretm/villus/compare/v1.0.0-rc.20...v1.0.0-rc.21) (2021-08-26) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.20](https://github.com/logaretm/villus/compare/v1.0.0-rc.19...v1.0.0-rc.20) (2021-08-07) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.19](https://github.com/logaretm/villus/compare/v1.0.0-rc.18...v1.0.0-rc.19) (2021-07-25) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.18](https://github.com/logaretm/villus/compare/v1.0.0-rc.17...v1.0.0-rc.18) (2021-06-29) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.17](https://github.com/logaretm/villus/compare/v1.0.0-rc.16...v1.0.0-rc.17) (2021-05-12) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.16](https://github.com/logaretm/villus/compare/v1.0.0-rc.15...v1.0.0-rc.16) (2021-04-15) ### Bug Fixes - normalize the multipart queries closes [#112](https://github.com/logaretm/villus/issues/112) ([#113](https://github.com/logaretm/villus/issues/113)) ([c54fd0e](https://github.com/logaretm/villus/commit/c54fd0e80f8d05a4a115630e8b7c83bd2c58a5f3)) # [1.0.0-rc.15](https://github.com/logaretm/villus/compare/v1.0.0-rc.14...v1.0.0-rc.15) (2021-03-06) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.14](https://github.com/logaretm/villus/compare/v1.0.0-rc.13...v1.0.0-rc.14) (2021-03-04) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.13](https://github.com/logaretm/villus/compare/v1.0.0-rc.12...v1.0.0-rc.13) (2021-02-27) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.12](https://github.com/logaretm/villus/compare/v1.0.0-beta.0...v1.0.0-rc.12) (2021-02-16) ### Features - added basic implementation of multipart fetcher ([bca5ee8](https://github.com/logaretm/villus/commit/bca5ee857a0c9583850d4f23e673c3467321044f)) - use the public plugin API and add villus to multipart deps ([77fb90f](https://github.com/logaretm/villus/commit/77fb90f71e400b3000dd18ffbfa7f355365c5c01)) # [1.0.0-rc.7](https://github.com/logaretm/villus/compare/@villus/multipart@1.0.0-rc.6...@villus/multipart@1.0.0-rc.7) (2021-01-20) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.6](https://github.com/logaretm/villus/compare/@villus/multipart@1.0.0-rc.5...@villus/multipart@1.0.0-rc.6) (2021-01-17) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.5](https://github.com/logaretm/villus/compare/@villus/multipart@1.0.0-rc.4...@villus/multipart@1.0.0-rc.5) (2021-01-15) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.4](https://github.com/logaretm/villus/compare/@villus/multipart@1.0.0-rc.3...@villus/multipart@1.0.0-rc.4) (2021-01-05) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.3](https://github.com/logaretm/villus/compare/@villus/multipart@1.0.0-rc.2...@villus/multipart@1.0.0-rc.3) (2021-01-02) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.2](https://github.com/logaretm/villus/compare/@villus/multipart@1.0.0-rc.1...@villus/multipart@1.0.0-rc.2) (2020-11-26) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.1](https://github.com/logaretm/villus/compare/@villus/multipart@1.0.0-rc.0...@villus/multipart@1.0.0-rc.1) (2020-11-25) **Note:** Version bump only for package @villus/multipart # [1.0.0-rc.0](https://github.com/logaretm/villus/compare/@villus/multipart@1.0.0-beta.2...@villus/multipart@1.0.0-rc.0) (2020-11-01) ### Features - use the public plugin API and add villus to multipart deps ([77fb90f](https://github.com/logaretm/villus/commit/77fb90f71e400b3000dd18ffbfa7f355365c5c01)) # [1.0.0-beta.2](https://github.com/logaretm/villus/compare/@villus/multipart@1.0.0-beta.1...@villus/multipart@1.0.0-beta.2) (2020-10-19) **Note:** Version bump only for package @villus/multipart # 1.0.0-beta.1 (2020-09-30) ### Features - added basic implementation of multipart fetcher ([bca5ee8](https://github.com/logaretm/villus/commit/bca5ee857a0c9583850d4f23e673c3467321044f)) <file_sep>import path, { dirname } from 'path'; import { fileURLToPath } from 'url'; import fs from 'fs-extra'; import { rollup } from 'rollup'; import chalk from 'chalk'; import * as Terser from 'terser'; import { createConfig } from './config.mjs'; import { reportSize } from './info.mjs'; import { generateDts } from './generate-dts.mjs'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); async function minify({ code, pkg, bundleName }) { const pkgout = path.join(__dirname, `../packages/${pkg}/dist`); const output = await Terser.minify(code, { compress: true, mangle: true, }); const fileName = bundleName.replace(/\.js$/, '.min.js'); const filePath = `${pkgout}/${fileName}`; fs.outputFileSync(filePath, output.code); const stats = reportSize({ code: output.code, path: filePath }); console.log(`${chalk.green('Output File:')} ${fileName} ${stats}`); } async function build(pkg) { console.log(chalk.magenta(`Generating bundle for ${pkg}`)); const pkgout = path.join(__dirname, `../packages/${pkg}/dist`); for (const format of ['es', 'umd']) { const { input, output, bundleName } = await createConfig(pkg, format); const bundle = await rollup(input); const { output: [{ code }], } = await bundle.generate(output); const outputPath = path.join(pkgout, bundleName); fs.outputFileSync(outputPath, code); const stats = reportSize({ code, path: outputPath }); // eslint-disable-next-line console.log(`${chalk.green('Output File:')} ${bundleName} ${stats}`); if (format === 'umd') { await minify({ bundleName, pkg, code }); } } await generateDts(pkg); console.log(`${chalk.magenta('✅ Bundled ' + pkg)}`); return true; } (async function Bundle() { for (const pkg of ['villus', 'batch', 'multipart']) { await build(pkg); } })(); <file_sep>#!/usr/bin/env sh # abort on errors set -e cd docs yarn generate cd dist git init git add -A git commit -m 'deploy' git push -f <EMAIL>:logaretm/villus.git master:gh-pages cd -<file_sep>--- layout: ../layouts/HomeLayout.astro title: villus description: A small and fast GraphQL client for Vue.js home: true features: - title: ⚡️ Fast details: Small API footprint with tiny bundle size < 4kb to make your apps load faster - title: 📦 Cache-Ready details: Reasonable caching behavior out of the box which can be adjusted per query - title: 👕 TypeScript details: Written in TypeScript and supports Typed query Responses and variables - title: ☢️ Reactive details: Write reactive queries/variables with the composition API - title: 🚟 Suspense API details: Supports the <Suspense /> component API out of the box --- ## Sponsors Thanks for the following companies and individuals who are supporting villus <br /> <a href="https://github.com/sponsors/logaretm"> <img src="https://sponsors.logaretm.com/sponsors.svg" /> </a> <br /> <br /> You can also help this project and my other projects by donating one time or by sponsoring via the following link <br /> <div class="flex items-center justify-center"> <sponsor-button></sponsor-button> </div> <br /> ## Quick Start First, install `villus` yarn ```sh yarn add villus graphql ``` npm ```sh npm install villus graphql --save ``` ### Usage Configure the GraphQL client for your root component: ```vue <script setup> import { useClient } from 'villus'; useClient({ url: 'http://localhost:3002/graphql', }); </script> ``` Then you can use `useQuery` in any child component: ```vue <template> <div> <div v-if="data"> <pre>{{ data }}</pre> </div> </div> </template> <script setup> import { useQuery } from 'villus'; const { data } = useQuery({ query: '{ posts { title } }', }); </script> ``` <file_sep>/* eslint-disable no-unused-expressions */ import flushPromises from 'flush-promises'; import { test, expect, vi, beforeEach, afterEach, describe } from 'vitest'; import { rest } from 'msw'; import { server } from '../../villus/test/mocks/server'; import { batch } from '../src/index'; import { mount } from '../../villus/test/helpers/mount'; import { useClient, useQuery, definePlugin, normalizeQuery } from 'villus'; import waitForExpect from 'wait-for-expect'; import { PostQuery, PostQueryWithDescription, PostsQuery, QueryErrorWith500, QueryWithNetworkError, } from 'villus/test/mocks/queries'; beforeEach(() => { vi.useFakeTimers(); }); afterEach(() => { vi.useRealTimers(); }); describe('batch plugin', () => { test('batches queries with batcher', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [batch()], }); const firstQuery = useQuery({ query: PostsQuery }); const secondQuery = useQuery({ query: PostQuery }); return { postsWithTitle: firstQuery.data, postsWithId: secondQuery.data }; }, template: ` <div> <ul v-if="postsWithTitle" id="multi"> <li v-for="post in postsWithTitle.posts" :key="post.id">{{ post.title }}</li> </ul> <p v-if="postsWithId" id="single">{{ postsWithId.post.title }}</p> </div>`, }); vi.advanceTimersByTime(100); await flushPromises(); // wait-for-expect uses timers under the hood, so we need to reset here vi.useRealTimers(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('#multi')?.children).toHaveLength(5); expect(document.querySelector('#single')?.textContent).toContain('Awesome'); }); }); test('results with non-200 code will be evaluated separately', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [batch()], }); const firstQuery = useQuery({ query: PostsQuery }); const secondQuery = useQuery({ query: QueryErrorWith500 }); return { postsWithTitle: firstQuery.data, secondQueryError: secondQuery.error }; }, template: ` <div> <ul v-if="postsWithTitle" id="multi"> <li v-for="post in postsWithTitle.posts" :key="post.id">{{ post.title }}</li> </ul> <p v-if="secondQueryError" id="error">{{ secondQueryError.message }}</p> </div>`, }); vi.advanceTimersByTime(100); await flushPromises(); // wait-for-expect uses timers under the hood, so we need to reset here vi.useRealTimers(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('#multi')?.children).toHaveLength(5); expect(document.querySelector('#error')?.textContent).toContain('Not authenticated'); }); }); test('null json responses should be handled', async () => { server.use( rest.post('https://test.com/graphql', async (req, res, ctx) => { return res(ctx.status(200), ctx.json(null)); }), ); mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [batch()], }); const firstQuery = useQuery({ query: PostsQuery }); return { error: firstQuery.error }; }, template: ` <div> <p v-if="error" id="error">{{ error.message }}</p> </div>`, }); vi.advanceTimersByTime(100); await flushPromises(); // wait-for-expect uses timers under the hood, so we need to reset here vi.useRealTimers(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('#error')?.textContent).toContain('empty response'); }); server.resetHandlers(); }); test('handles network errors', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [batch()], }); const { error } = useQuery({ query: QueryWithNetworkError }); return { error }; }, template: ` <div> <p id="error" v-if="error">{{ error.message }}</p> </div>`, }); vi.advanceTimersByTime(100); await flushPromises(); // wait-for-expect uses timers under the hood, so we need to reset here vi.useRealTimers(); await waitForExpect(() => { expect(document.querySelector('#error')?.textContent).toContain('Failed to connect'); }); }); test('can set batched queries limit with maxOperationCount', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [ batch({ maxOperationCount: 2, }), ], }); useQuery({ query: PostsQuery }); useQuery({ query: PostQuery }); useQuery({ query: PostQuery, variables: { id: 1 } }); useQuery({ query: PostQuery, variables: { id: 2 } }); useQuery({ query: PostQuery, variables: { id: 3 } }); return {}; }, template: `<div></div>`, }); vi.advanceTimersByTime(100); await flushPromises(); vi.useRealTimers(); await waitForExpect(() => { // we've set the limit to 2, so 5 queries will be executed over 3 HTTP calls expect(fetch).toHaveBeenCalledTimes(3); }); }); // #166 test('can set fetch options', async () => { const headerPlugin = definePlugin(({ opContext }) => { opContext.headers['X-CUSTOM-HEADER'] = 'TEST'; opContext.credentials = 'include'; }); mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [headerPlugin, batch()], }); useQuery({ query: PostsQuery }); return {}; }, template: `<div></div>`, }); await flushPromises(); vi.advanceTimersByTime(100); await flushPromises(); // wait-for-expect uses timers under the hood, so we need to reset here vi.useRealTimers(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenLastCalledWith( expect.any(String), expect.objectContaining({ credentials: 'include', headers: expect.objectContaining({ 'X-CUSTOM-HEADER': 'TEST', }), }), ); }); }); test('certain operations can be un-batched', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [ batch({ exclude: op => { const query = normalizeQuery(op.query); return /query Posts/.test(query || ''); }, }), ], }); useQuery({ query: PostsQuery }); useQuery({ query: PostQuery }); useQuery({ query: PostQueryWithDescription }); return {}; }, template: `<div></div>`, }); vi.advanceTimersByTime(100); await flushPromises(); vi.useRealTimers(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(2); }); }); }); <file_sep>--- layout: ../../layouts/PageLayout.astro title: Cache Plugin description: How the default cache works in villus order: 2 --- import DocTip from '@/components/DocTip.vue'; # Cache Plugin The cache plugin is a simple in-memory cache that clears whenever the page reloads or when the client is destroyed. The cache plugin only applies it's caching logic to queries, as mutations require a fresh response from the server. The cache plugin handles all the cache policies in villus: - `cache-first`: If found in cache return it, otherwise fetch it from the network - `network-only`: Always fetch from the network and do not cache it - `cache-and-network`: If found in cache return it, then fetch a fresh result from the network and update current data (reactive). if not found in cache it will fetch it from the network and cache it - `cache-only`: If found in cache return it, otherwise returns an empty response without errors ```vue <script setup> import { useClient, cache, fetch } from 'villus'; useClient({ use: [cache(), fetch()], }); </script> ``` <DocTip> The cache plugin is one of the default plugins that are pre-configured with any villus client unless specified otherwise </DocTip> ## Options At this moment the cache plugin doesn't have any options to customize ## Clearing cache You can clear the cache for all queries using `clearCache()` present on the cachePlugin instance. You can export the cache plugin to make it accessible to other parts of your code like so: ```ts import { useClient, cache, fetch } from 'villus'; export const cachePlugin = cache(); useClient({ use: [cachePlugin, fetch()], }); ``` Then you can import it and clear it whenever it makes sense in your logic: ```ts import { cachePlugin } from '../client'; // anywhere in your code cachePlugin.clearCache(); ``` ## Code You can check the [source code for the `cache` plugin](https://github.com/logaretm/villus/blob/main/packages/villus/src/cache.ts) and use it as a reference to build your own <file_sep>import { getCurrentInstance, provide } from 'vue'; import { createClient, ClientOptions } from './client'; import { VILLUS_CLIENT } from './symbols'; export function useClient(opts: ClientOptions) { const client = createClient(opts); if (getCurrentInstance()) { provide(VILLUS_CLIENT, client); } return client; } <file_sep>--- layout: ../../layouts/PageLayout.astro title: Queries with Pinia description: Using queries in a Pinia state store order: 3 --- # Queries in a state store There are multiple ways you can query in a state store. For example, [Pinia](https://pinia.vuejs.org/) allows you to define stores as smaller setup functions. This allows you to use `useQuery` or `useMutation` features directly in your store as state or actions. The following example showcases a store created using `useQuery` where it fetches the data from the API and shows a loading state as well. <iframe src="https://stackblitz.com/edit/vitejs-vite-ipujmr?embed=1&file=src/components/Pets.vue&view=preview" style="width: 100%; height: 500px; border: 0; border-radius: 4px; overflow: hidden" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" loading="lazy" class="mt-8" ></iframe> <file_sep>--- layout: ../../layouts/PageLayout.astro title: Basic Query description: Using `useQuery` in a Vue app to execute queries order: 1 --- # Query Example This is a simple example of how to run queries along with reactive variables <p class="codepen" data-height="625" data-theme-id="light" data-default-tab="js,result" data-user="logaretm" data-slug-hash="eYZbevO" style="height: 625px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="Basic Queries"> <span>See the Pen <a href="https://codepen.io/logaretm/pen/eYZbevO"> Basic Queries</a> by <NAME> (<a href="https://codepen.io/logaretm">@logaretm</a>) on <a href="https://codepen.io">CodePen</a>.</span> </p> <script async src="https://static.codepen.io/assets/embed/ei.js"></script> <file_sep>import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { setupFiles: ['./packages/villus/test/setup.ts'], environment: 'jsdom', coverage: { reporter: ['text', 'json', 'html'], exclude: ['packages/**/dist/**', '**/test/**', '**/*.d.ts'], }, }, }); <file_sep>--- layout: ../../layouts/PageLayout.astro title: Migration Guide description: Migrating from villus 2.x to 3.0 order: 9 --- # Migration Guide ## From 2.x to 3.0 3.0 contains very few breaking changes. ### useSubscription() reducer arguments For better TypeScript detection with TypedDocuments and more versastility with the reducer function, the argument order has been flipped. - So instead of getting the previous value as the first argument, you will get the new subscription result instead. - The second argument will recieve the previous reduced value. This makes the reducer more flexible as it can now be used as either a callback for when incoming data is received or a mapper if you only plan to use the last result or map it to a different value, or a reducer that combines the previous and incoming values if applicable. Here is how to migrate: ```diff - function reduceMessages(old, incoming) { + function reduceMessages(incoming, old) { // reduce values } ``` ### onSuccess query hook renamed For consistency, the recently introduced `onSuccess` option on `useQuery` has been renamed to `onData` to be more consistent with other naming conventions. Here is how to migrate: ```diff import { useQuery } from 'villus'; useQuery({ query: GetPostById, variables, - onSuccess: data => console.log(data), + onData: data => console.log(data), }); ``` <file_sep>import { arrayToExistHash, getQueryKey } from './utils'; import { cache } from './cache'; import { fetch } from './fetch'; import { dedup } from './dedup'; import { DEFAULT_FETCH_OPTS, FetchOptions, Operation, QueryVariables } from '../../shared/src'; import { OperationResult, CachePolicy, ClientPlugin, ClientPluginContext, OperationType, AfterQueryCallback, ObservableLike, OperationWithCachePolicy, StandardOperationResult, QueryExecutionContext, QueryOperation, MutationOperation, SubscriptionOperation, ClientPluginOperation, } from './types'; import { VILLUS_CLIENT } from './symbols'; import { App, getCurrentInstance, inject, InjectionKey } from 'vue'; export interface ClientOptions { url: string; cachePolicy?: CachePolicy; use?: ClientPlugin[]; } /** * setActiveClient should be called to solve problem outside setup */ // eslint-disable-next-line no-use-before-define let activeClient: Client | undefined; /** * Sets or unsets the active client * * @param client - villus client instance */ export const setActiveClient = (client: Client | undefined) => (activeClient = client); /** * Get the currently active client if there is any. */ export const getActiveClient = () => { const vm = getCurrentInstance() as any; if (!vm) { return activeClient; } return vm.provides?.[VILLUS_CLIENT as any] || inject(VILLUS_CLIENT, activeClient); }; type OnResultChangedCallback<TData> = (result: OperationResult<TData>) => unknown; export const defaultPlugins = () => [cache(), dedup(), fetch()]; interface TaggedQueryEntry { id: symbol; refetch(): Promise<void>; tags: string[]; } export class Client { public install: (app: App) => void = () => undefined; private url: string; private defaultCachePolicy: CachePolicy; private plugins: ClientPlugin[]; private taggedQueries: TaggedQueryEntry[]; public constructor(opts: ClientOptions) { this.url = opts.url; this.defaultCachePolicy = opts.cachePolicy || 'cache-first'; this.plugins = opts.use || [...defaultPlugins()]; this.taggedQueries = []; } /** * Executes an operation and returns a normalized response. */ private async execute<TData, TVars>( operation: Operation<TData, TVars> | OperationWithCachePolicy<TData, TVars>, type: OperationType, queryContext?: QueryExecutionContext, onResultChanged?: OnResultChangedCallback<TData>, ): Promise<OperationResult<TData>> { let result: OperationResult<TData> | undefined; const opContext: FetchOptions = { url: this.url, ...DEFAULT_FETCH_OPTS, headers: { ...DEFAULT_FETCH_OPTS.headers, ...(queryContext?.headers || {}) }, }; let terminateSignal = false; const afterQuery: AfterQueryCallback[] = []; const context: ClientPluginContext = { useResult(pluginResult, terminate) { if (terminate) { terminateSignal = true; } // this means the `useResult` was called multiple times if (result) { onResultChanged?.(pluginResult as OperationResult<TData>); } result = pluginResult as OperationResult<TData>; }, afterQuery(cb) { afterQuery.push(cb); }, operation: { ...operation, key: getQueryKey(operation), type, cachePolicy: ('cachePolicy' in operation ? operation.cachePolicy : this.defaultCachePolicy) || this.defaultCachePolicy, } as ClientPluginOperation, opContext, }; let lastI = 0; for (let i = 0; i < this.plugins.length; i++) { const plugin = this.plugins[i]; await plugin(context); if (result) { lastI = i; break; } } return new Promise((resolve, reject) => { if (!result) { reject( new Error( 'Operation result was not set by any plugin, make sure you have default plugins configured or review documentation', ), ); return; } resolve(result); (async () => { if (!terminateSignal) { for (let i = lastI + 1; i < this.plugins.length; i++) { const plugin = this.plugins[i]; await plugin(context); } } const afterQueryCtx = { response: context.response }; for (let i = 0; i < afterQuery.length; i++) { const afterCb = afterQuery[i]; await afterCb(result as OperationResult<TData>, afterQueryCtx); } })(); }); } public async executeQuery<TData = any, TVars = QueryVariables>( operation: Omit<QueryOperation<TData, TVars>, 'type'>, queryContext?: QueryExecutionContext, onResultChanged?: OnResultChangedCallback<TData>, ): Promise<OperationResult<TData>> { return this.execute<TData, TVars>(operation, 'query', queryContext, onResultChanged); } public async executeMutation<TData = any, TVars = QueryVariables>( operation: Omit<MutationOperation<TData, TVars>, 'type'>, queryContext?: QueryExecutionContext, ): Promise<OperationResult<TData>> { return this.execute<TData, TVars>(operation, 'mutation', queryContext); } public async executeSubscription<TData = any, TVars = QueryVariables>( operation: Omit<SubscriptionOperation<TData, TVars>, 'type'>, ) { const result = await this.execute<TData, TVars>(operation, 'subscription'); return result as unknown as ObservableLike<StandardOperationResult<TData>>; } public registerTaggedQuery(tags: string[], refetch: () => Promise<void>): symbol { const id = Symbol('Tagged query'); this.taggedQueries.push({ id, tags, refetch }); return id; } public unregisterTaggedQuery(id: symbol) { const idx = this.taggedQueries.findIndex(tq => tq.id === id); if (idx === -1) { return; } this.taggedQueries.splice(idx, 1); } public async refetchTaggedQueries(tags: string[]) { const tagsLookup = arrayToExistHash(tags); const queries = this.taggedQueries.filter(tq => { return tq.tags.some(t => tagsLookup[t]); }); return Promise.all(queries.map(q => q.refetch())).then(() => undefined); } } export function createClient(opts: ClientOptions) { const client = new Client(opts); client.install = (app: App) => { // this allows useQuery() etc useFunctions to get client outside of a component setup after setActiveClient(client); app.provide(VILLUS_CLIENT, client); }; return client; } function resolveInternalInjection<T>(vm: any, symbol: InjectionKey<T>) { // Vue 2 uses `proxy._provided` while Vue 3 has `provides` // Vue 2.7's proxy property might be a bug but thats the IRL situation. return vm?.proxy?._provided?.[symbol as any] || vm?._provided?.[symbol as any] || vm?.provides?.[symbol as any]; } export function resolveClient(): Client { const vm = getCurrentInstance() as any; // Uses same component provide as its own injections // Due to changes in https://github.com/vuejs/vue-next/pull/2424 let client = vm && inject(VILLUS_CLIENT, resolveInternalInjection(vm, VILLUS_CLIENT)); if (client) setActiveClient(client); client = getActiveClient(); if (client === null || client === undefined) { throw new Error( 'Cannot detect villus Client, did you forget to call `useClient`? Alternatively, you can explicitly pass a client as the `manualClient` argument.', ); } return client; } <file_sep>--- layout: ../../layouts/PageLayout.astro title: Writing Tests description: Recommendations and examples for writing tests order: 8 --- # Writing Tests villus does not have any special treatment when it comes to writing unit and integration tests, but this topic can be confusing. In this guide, you will find some recommendations and examples on how to write unit tests for components using `villus`. ## Testing tools and methodology It is recommended that you use either [Vue Test Utils (VTU)](https://next.vue-test-utils.vuejs.org/) or [testing library](https://testing-library.com/docs/vue-testing-library/intro/) to write your tests. The following examples in this guide will use VTU. We will follow an example where we implement a posts list component unit test. Here is the component code in question: ```vue <template> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id"> {{ post.title }} </li> </ul> </template> <script setup> import { defineComponent } from 'vue'; import { useQuery } from 'villus'; const { data } = useQuery({ query: ` query Posts { posts { id title } } `, }); </script> ``` ## Setting up Global Injections All the queries and mutations you use in your application components rely on the `provide/inject` API. Typically you would have an `App.vue` component setup where you would [setup your villus client](/guide/setup). In unit tests, you don't usually mount the entire app hierarchy as you are only interested in testing a specific component, hence why it's called "unit test". That means you need to provide the client setup injection to your component, this can be done using [VTU global mounting options](https://next.vue-test-utils.vuejs.org/api/#global). ```js import { createClient, VILLUS_CLIENT } from 'villus'; import { mount } from '@vue/test-utils'; import PostsList from '@/components/PostsList.vue'; test('it lists the blog posts', async () => { const wrapper = mount(PostsList, { global: { provide: { [VILLUS_CLIENT]: createClient({ url: 'http://test/graphql', }), }, }, }); // TODO: Write assertions }); ``` Note that since `villus` uses ES6 symbols to identify the villus client object. This is why the `VILLUS_CLIENT` is exported to you, so you can freely inject the villus client manually when needed. It might be worthwhile to refactor the above snippet to some test helper since you will be doing that a lot in your tests. ## Mocking Network Requests The next step would be to mock the response the component expects from the API. This can be done in two different ways: - Mock the `fetch` function and have it return the response - Use an advanced mocking library like [mswjs](https://mswjs.io/) to mock an API server While the former can be simpler, It is recommended to go with the mswjs approach as it allows you to test GraphQL error responses and it allows you to test your component in an environment that's much closer to real-world. This guide won't focus on how to do either of these methods, but it is recommended to go with mswjs. ## Writing Assertions Assuming you've set up your network request-mocked environment, the next step would be writing the actual assertion to make sure the component does its job. Here is some assertions that test if the component fetches the data when mounted and displays the posts returned from the API: ```js import { createClient, VILLUS_CLIENT } from 'villus'; import { mount } from '@vue/test-utils'; import waitForExpect from 'wait-for-expect'; import PostsList from '@/components/PostsList.vue'; test('it lists the blog posts', async () => { const wrapper = mount(PostsList, { global: { provide: { [VILLUS_CLIENT]: createClient({ url: 'http://test/graphql', }), }, }, }); await waitForExpect(() => { expect(wrapper.findAll('li').length).toBeGreaterThan(0); }); }); ``` Notice the use of [wait-for-expect](https://www.npmjs.com/package/wait-for-expect) module to allow us to retry the assertions until they are met or until they fail after a max number of retries. This is very useful because the time needed to wait for the components to mount and fetch from your mocked API is unknown. <file_sep>import { vi, afterAll } from 'vitest'; let interval: any; export function makeObservable(throws = false, simulateError = false) { let counter = 0; const observable = { subscribe({ next, error }: { error: (err: Error) => any; next: (value: any) => any }) { interval = setInterval(() => { if (throws) { error(new Error('oops!')); return; } if (!simulateError) { next({ data: { message: 'New message', id: counter++ } }); return; } next({ errors: [new Error('sadge')], data: null }); }, 100); return { unsubscribe() { clearTimeout(interval); }, }; }, }; return observable; } afterAll(() => { clearTimeout(interval); }); export function tick(ticks = 1) { vi.advanceTimersByTime(ticks * 100 + 1); } <file_sep>--- layout: ../../layouts/PageLayout.astro title: useMutation() description: API reference for the useMutation composable function order: 2 --- ## useMutation() The `useMutation` function allows you to execute GraphQL mutations, it requires a `Provider` or `useClient` to be called in the component tree, so make sure to [set that up](/guide/setup) before using `useMutation` The `useMutation` function returns the following properties and functions: | Property | Type | Description | | ---------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------- | | data | `Ref<any/null>` | The GraphQL mutation result's `data` | | error | `Ref<CombinedError>` | Any errors encountered during mutation execution | | execute | `(variables: object) => Promise<OperationResult<TData>>` | Executes the mutation and returns the operation result containing `data` and `error` values | | isDone | `Ref<boolean>` | Set to true when the mutation is executed at least once, never resets to `false` | | isFetching | `Ref<boolean>` | Set to true when the mutation is executing by calling `execute` explicitly | ## Mutation Options Aside from the mutation itself, the `useMutation` function accepts an optional second argument containing these options: | Property | Type | Required | Description | | -------------- | ------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------- | | context | `{ headers: Record<string, string> }` | **No** | A object to be merged with the fetch options, currently accepts `headers`. The `context` can be a reactive `ref` or `computed ref`. | | clearCacheTags | `string[]` | **No** | Passing this will clear the tagged queries cache if they have any of the tags specified | | refetchTags | `string[]` | **No** | Passing this will clear the tagged queries cache and will trigger a refetch if those queries have any one of the tags specified | ## Signature and Usage You can use `useMutation` like this: ```vue <script setup> import { useMutation } from 'villus'; const LikePost = ` mutation { likePost (id: 123) { message } } `; const { data, execute } = useMutation(LikePost); </script> ``` `useMutation` is very simple and doesn't accept any other arguments, just the mutation. ## Reactivity `useMutation` does not accept reactive queries or variables, so it is your responsibility to unwrap any reactive values passed to it For more information on `useMutation`, [check the mutations guide](/guide/mutations)/ <file_sep>--- layout: ../../layouts/PageLayout.astro title: Handle Subscriptions Plugin description: The plugin that executes your subscriptions order: 6 --- # Handle Subscriptions Plugin Subscriptions are very different from queries or mutations, as it is considered a constant stream of events or data. Because of this, it requires special handling, `villus` implements the subscription support as a plugin for added flexibility and streamlining of the query execution process regardless of its type. ## Options The `handleSubscriptions` plugin requires only one option, a **subscription forwarder**, which is just a function that returns an observable. ```vue <script setup> import { useClient, handleSubscriptions, defaultPlugins } from 'villus'; import { createClient } from 'graphql-ws'; const wsClient = createClient({ url: 'ws://localhost:9005/graphql', }); const subscriptionsHandler = handleSubscriptions(operation => { return { subscribe: obs => { wsClient.subscribe( { query: operation.query, variables: operation.variables, }, obs ); return { unsubscribe: () => { // No OP }, }; }, }; }); // in your setup const client = useClient({ url: 'http://localhost:4000/graphql', // Install the subscriptions handler use: [subscriptionsHandler, ...defaultPlugins()], }); </script> ``` ## Code You can check the [source code for the `handleSubscriptions` plugin](https://github.com/logaretm/villus/blob/main/packages/villus/src/handleSubscriptions.ts) and use it as a reference to build your own <file_sep>--- layout: ../../layouts/PageLayout.astro title: Queries description: Learn how to run GraphQL queries order: 3 --- import DocTip from '@/components/DocTip.vue'; import DocBadge from '@/components/DocBadge.vue'; # Queries You can query GraphQL APIs with the `useQuery` composition function after you've setup the [GraphQL Client](/setup.md). ## Queries Basics The `useQuery` function is a composable function that provides query state and various helper methods for managing the query. To execute a query the `useQuery` accepts a GraphQL query as the first argument. The `query` property is a `string` containing the query body or a `DocumentNode` (AST) created by `graphql-tag`. ```vue <template> <div> <ul v-if="data"> <li v-for="todo in data.todos">{{ todo.text }}</li> </ul> </div> </template> <script setup> import { useQuery } from 'villus'; const GetTodos = ` GetTodos { todos { id title } } `; const { data } = useQuery({ query: GetTodos, }); </script> ``` ## With [graphql-tag](https://github.com/apollographql/graphql-tag) You can use `graphql-tag` to compile your queries or load them with the `graphql-tag/loader`. This is an example with the `useQuery` function: ```vue <script setup> import { gql } from 'graphql-tag'; const GetTodos = gql` GetTodos { todos { id title } } `; const { data } = useQuery({ query: GetTodos, }); </script> ``` If you are using **webpack** you can configure the loader `graphql-tag/loader` and use `import/require`: ```vue <script setup> import { Todos } from '@/graphql/todos.gql'; const { data } = useQuery({ query: Todos, }); </script> ``` ## Query Variables You can pass variables to your queries as the second argument of `useQuery`: ```vue <script setup> const FetchTodo = ` query FetchTodo ($id: ID!) { todo (id: $id) { text } } `; const { data } = useQuery({ query: GetTodos, variables: { id: 123 }, }); </script> ``` However, if you want to re-fetch the query whenever the variables change, then this is where the composition API shines. You can pass a [reactive object](https://v3.vuejs.org/api/basic-reactivity.html#reactive) containing your variables and the query will automatically execute with the new variables value: ```vue <script setup> import { reactive } from 'vue'; import { useQuery } from 'villus'; const variables = reactive({ id: 123, }); const { data } = useQuery({ query: `query FetchTodo ($id: ID!) { todo (id: $id) { text } } `, variables, }); </script> ``` This also works with [reactive Refs](https://v3.vuejs.org/api/refs-api.html#ref) ```vue <script setup> import { ref } from 'vue'; import { useQuery } from 'villus'; const variables = ref({ id: 123, }); const FetchTodo = ` query FetchTodo ($id: ID!) { todo (id: $id) { text } } `; const { data } = useQuery({ query: FetchTodo, variables, }); </script> ``` This is only one way to re-fetch queries because `villus` is built with composable API first you will find many ways to re-fetch your queries no matter how complex your requirements are. ## Re-fetching Queries Sometimes you want to re-fetch the query or run it after some action, the `execute` function that is returned from the `useQuery` function. When called it re-executes the query. This example executes the query after the button has been clicked, note that the query is still fetched initially. Here is a snippet for calling `execute` with `useQuery`: ```vue <script> import { useQuery } from 'villus'; const { data, execute } = useQuery({ // ... }); // call execute whenever you want the query to re-fetch execute(); </script> ``` This can be very useful in situations where you have complex logic that triggers a refetch, which means `watch` and `watchEffect` play well with the `execute` function: ```vue <script setup> import { watch } from 'vue'; import { useQuery } from 'villus'; const GetTodos = ` GetTodos { todos { id title } } `; const { data, execute } = useQuery({ query: GetTodos, }); watch(someComputedProp, () => execute()); </script> ``` ## Reactive Queries Vue is all about reactivity to achieve better DX, and villus follows this philosophy as well. You are not only limited to reactive variables, you can also have reactive queries. In other words, queries created with `ref` or `computed` are recognized as reactive queries and will be watched automatically and re-fetched whenever the query changes. ```vue <script setup> import { computed, ref } from 'vue'; import { useQuery } from 'villus'; // computed id that will be used to compute the query const id = ref(1); // Create a computed query const FetchTodo = computed(() => { return `query FetchTodo { todo (id: ${id.value}) { text } } `; }); const { data } = useQuery({ query: FetchTodo, }); // later on, changing the `id` ref will automatically refetch the query because it is computed id.value = 2; </script> ``` Reactive queries are very flexible and one of the many advantages of using the composition API. ### Disabling Re-fetching You can disable the automatic refetch behavior by passing a `paused` getter function to the `useQuery` function. The getter should return a boolean. ```vue <script setup> import { ref } from 'vue'; import { useQuery } from 'villus'; const GetPostById = ` query getPost ($id: ID!) { post (id: $id) { id title } } `; // Create a reactive variables object const variables = ref({ id: 123 }); const { data } = useQuery({ query: GetPostById, variables, paused: () => !variables.id, // Don't re-fetch automatically unless the id is present }); </script> ``` The previous example can be also re-written as shown below, since the `paused` function receives the current variables as an argument. ```vue <script setup> import { useQuery } from 'villus'; const { data } = useQuery({ query: GetPostById, variables, // Don't re-fetch automatically unless the id is present paused: ({ id }) => !id, }); </script> ``` This is useful if you want to build variable guards to make sure you don't pass invalid values to your GraphQL servers. In addition to passing a function, you can also pass reactive refs or a plain boolean: ```vue <script setup> const { data } = useQuery({ query: GetPostById, variables, // computed or `ref` paused: computed(() => !variables.id), }); const { data, execute } = useQuery({ query: GetPostById, variables, // boolean, this query is now "lazy" and you have to trigger executions manually with `execute`. paused: true, }); function runQuery() { // won't be stopped execute(); } </script> ``` Whenever the `paused` is a reactive value and it changes to `false`, the query will be re-executed automatically so you can also use `paused` to wait for when some condition is met before the query is executed. For example, maybe you have a query that depends on another and would like to make sure not to fetch the second one unless the first one was fetched. ```vue <script setup> const Post = ` query GetPost ($postId: ID!) { post (id: $postId) { id title } } `; const Comments = ` query Comments ($postId: ID!) { post (id: $postId) { comments { body } } } `; const variables = { postId: 1 }; const { data: postData } = useQuery({ query: Post, variables, }); const { data } = useQuery({ query: Comments, variables, // Causes the query to wait for the post to be found and fetched. paused: () => !!postData.value.post, }); </script> ``` ## Skipping Queries You can also skip executing queries by providing a `skip` argument to the query options. This can be particularly useful if you want to prevent fetching or refetching a query if a variable value is invalid. This may seem similar to `paused` except it doesn't stop query or variables watching and it prevents all executions, even manual ones with `execute`. Also, it doesn't re-fetch automatically whenever it is set back to `false`. In the following example, we skip the query unless the user has entered enough characters for the search terms. ```vue <template> <div> <input v-model="searchTerm" type="search" placeholder="Enter search terms" /> <ul v-if="data"> <li v-for="post in data.searchPosts" :key="post.id">{{ post.title }}</li> </ul> <p v-if="isFetching">Searching...</p> </div> </template> <script setup> import { computed } from 'vue'; import { useQuery } from 'villus'; const SearchPosts = ` query SearchPosts($term: String!) { searchPosts (term: $term) { id title } } `; const searchTerm = ref(''); // Skip the query if the search term has less than 3 characters. const shouldSkip = computed(() => { return searchTerm.value && searchTerm.value.length >= 3; }); const { data, isFetching } = useQuery({ query: SearchPosts, skip: shouldSkip, variables: computed(() => { return { term: searchTerm.value, }; }), }); </script> ``` You can also pass a function instead of a reactive variable, this function receives the current variables as an argument. ```vue <template> <div> <input v-model="searchTerm" type="search" placeholder="Enter search terms" /> <ul v-if="data"> <li v-for="post in data.searchPosts" :key="post.id">{{ post.title }}</li> </ul> <p v-if="isFetching">Searching...</p> </div> </template> <script setup> import { computed, ref } from 'vue'; import { useQuery } from 'villus'; const SearchPosts = ` query SearchPosts($term: String!) { searchPosts (term: $term) { id title } } `; const searchTerm = ref(''); const { data, isFetching } = useQuery({ query: SearchPosts, skip: ({ term }) => { return term && term.length >= 3; }, variables: computed(() => { return { term: searchTerm.value, }; }), }); </script> ``` Of course, you could've used `paused` for the previous example, but because `paused` stops watching the query variables it means your query won't trigger whenever the user type something into the search terms. Also, it wouldn't work correctly if you call `execute` manually with a watcher because `paused` doesn't stop manual executions. This makes `skip` ideal for situations where you want to keep the reactivity of the query while also ignoring certain executions of it. ## Fetching on Mounted By default queries are executed when the component is mounted. You can configure this behavior by setting the `fetchOnMount` option: ```vue <script setup> import { useQuery } from 'villus'; const GetPosts = ` query GetPosts { posts { id title } } `; const { data } = useQuery({ query: GetPosts, // disables query fetching on mounted fetchOnMount: false, }); </script> ``` <DocTip type="warn" title="Pausing and Skipping with fetchOnMount"> Note that this behavior is subject to `paused` or `skip` being set. Meaning if a query is paused or skipped it won't fetch when the component is mounted. </DocTip> ## Caching Queries are **cached in memory**, the uniqueness criteria is the query name, body, and its variables. Meaning if the same query is run with the same variables it will be fetched from the cache by default and will not hit the network. **Cache is deleted after the user closes/refreshes the page.** By default the client uses `cache-first` policy to handle queries, the full list of available policies are: - `cache-first`: If found in cache return it, otherwise fetch it from the network - `network-only`: Always fetch from the network and do not cache it - `cache-and-network`: If found in cache return it, then fetch a fresh result from the network and update current data (reactive). if not found in cache, it will fetch it from the network and cache it - `cache-only`: If found in cache return it, otherwise returns `null` for both `data` and `errors` You can specify a different strategy on different levels: ### On the client level You can set the default policy on the client level when you are [building the GraphQL client](/client.md) by passing `cachePolicy` option to either: ```vue{6} <script setup> import { useClient } from 'villus'; useClient({ url: '/graphql', // Your endpoint cachePolicy: 'network-only', }); </script> ``` This will make all the child-components using `useQuery` use the `network-only` policy by default. ### On the query level You can pass the `cachePolicy` property to the `useQuery` function to set the default caching policy for that query: <DocTip> Note the usage of a different signature here for the `useQuery` function, what you have seen so far is the "short-hand" but when you need to modify the query behavior you will need to use the full or extended options. The main difference is that this signature only accepts exactly 1 argument containing the query options, you can find more information about the available options in the [API reference page](/api/use-query). </DocTip> ```vue <script setup> import { useQuery } from 'villus'; const GetPosts = ` query GetPosts { posts { id title } } `; const { data } = useQuery({ query: GetPosts, cachePolicy: 'network-only', }); </script> ``` ### On each `execute` call level You can also set the caching policy for a single `execute` call by passing it to the `execute` function provided by the slot props or the `useQuery` function. Here is a snippet for doing so with the `useQuery` function: ```vue <script setup> import { useQuery } from 'villus'; const GetPosts = ` query GetPosts { posts { id title } } `; const { execute, data } = useQuery({ query: GetPosts, }); // use this in template or whatever. function runWithPolicy() { execute({ cachePolicy: 'network-only' }); } </script> ``` You can build your own cache layer and plugins for villus, check the [Plugins Guide](/plugins) ## Query tags <DocBadge title="2.1.0" /> You can tag the queries with an array of strings. These tags have a couple of uses: - You can clear the cache for those tagged queries and also allow mutations to auto-clear the queries' cache that has any of the same tags. - You can refetch all of tagged queries after a mutation that has any of the same tags. You can specify tags by passing `tags` to the query options when first calling `useQuery` composable: ```vue <script setup> import { useQuery } from 'villus'; const GetPosts = ` query GetPosts { posts { id title } } `; const { execute, data } = useQuery({ query: GetPosts, tags: ['all_posts'], }); </script> ``` The previous snippet tags the query with `all_posts` tag. Meaning any mutation that has `clearCacheTags` with the same value will clear this query's cache. So next time it is refetched, the query will be go to the network, skipping the cache entirely. To see how mutations can be configured to clear tagged queries or refetch them, check the [mutation's guide](/guide/mutations#clearing-tagged-queries-cache). You can manually clear the entire cache or any specific cache tags, read more in the [cache plugin page](/plugins/cache). ## Suspense <DocTip type="danger" title="Vue 3"> This feature is only available with Vue 3 at the moment </DocTip> You can use `useQuery` with the `Suspense` API component shipped in Vue 3.x. To utilize the suspense feature, you need to `await` the `useQuery` function and it returns the exact same API after executing the query: ```vue[Listing.vue] <template> <ul> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> </template> <script setup> import { useQuery } from 'villus'; const GetPosts = ` query GetPosts { posts { id title } } `; const { data } = await useQuery({ query: GetPosts, }); </script> ``` Then you can suspend the `Listing.vue` component like this: ```vue <template> <div> <Suspense> <template #default> <Listing /> </template> <template #fallback> <span>Loading...</span> </template> </Suspense> </div> </template> <script setup> import Listing from '@/components/Listing.vue'; </script> ``` ## Fetching Indication It is very common to display an indication for pending queries in your UI so your users know that something is being done, the `useQuery` composition function exposes a `isFetching` boolean ref that you can use to display such indicators. ```vue <template> <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> <p v-if="isFetching">Loading...</p> </div> </template> <script setup> import { useQuery } from 'villus'; const GetPosts = ` query GetPosts { posts { id title } } `; const { data, isFetching } = useQuery({ query: GetPosts, }); </script> ``` Whenever a re-fetch is triggered, or the query was executed again, the `isFetching` property will update accordingly so you don't have to keep it in sync, nor will you have to create your own boolean refs for indications. <DocTip title="Initial isFetching value"> The default value for `isFetching` is `true` if `fetchOnMount` is enabled, otherwise it will default to `false`. </DocTip> ## Event hooks useQuery returns event hooks allowing you to execute code when a specific event occurs. ### onData This is called whenever a new result is available. ```vue <script setup> import { useQuery } from 'villus'; const { onData } = useQuery({ query: GetPostById, variables, }); onData(data => { // Do something console.log(data); }); </script> ``` You can also register multiple callbacks, if you need to. ```ts onData(data => { // Do one thing }); onData(data => { // Do another }); ``` You can unregister any callback by calling the function returned from calling `onData`. ```vue <script setup> import { useQuery } from 'villus'; const { onData } = useQuery({ query: GetPostById, variables, }); const stop = onData(data => { // Do something console.log(data); }); // removes the callback and will no longer execute stop(); </script> ``` `useQuery` also accepts `onData` option if you are only interested in registering one callback: ```ts import { useQuery } from 'villus'; useQuery({ query: GetPostById, variables, onData: data => console.log(data), }); ``` ### onError only triggered when an error occurs. ```vue <script setup> import { useQuery } from 'villus'; const { onError } = useQuery({ query: GetPostById, variables, }); onError(error => { // Handle the error }); </script> ``` You can also register multiple callbacks, if you need to. ```ts onError(error => { // Do one thing }); onError(error => { // Do another }); ``` You can unregister any callback by calling the function returned from calling `onError`. ```vue <script setup> import { useQuery } from 'villus'; const { onError } = useQuery({ query: GetPostById, variables, }); const stop = onError(error => { // Do something }); // removes the callback and will no longer execute stop(); </script> ``` `useQuery` also accepts `onError` option if you are only interested in registering one callback: ```vue <script setup> import { useQuery } from 'villus'; useQuery({ query: GetPostById, variables, onError: err => { console.log(err); }, }); </script> ``` <file_sep>export const PostsQuery = `query Posts { posts { id title } }`; export const PostsQueryWithDescription = `query Posts { posts { id title description } }`; export const PostQuery = `query Post ($id: Int) { post (id: $id) { id title } }`; export const PostQueryWithDescription = `query Post ($id: Int) { post (id: $id) { id title description } }`; export const QueryWithGqlError = `query QueryError { posts { id title } }`; export const QueryWithParseError = `query QueryParseError { posts { id title } }`; export const QueryWithNetworkError = `query QueryNetworkError { posts { id title } }`; export const QueryErrorWith500 = `query ErrorWith500 { posts { id title } }`; export const LikePostMutation = `mutation LikePost ($id: Int!) { likePost (id: $id) { id title } }`; export const MutationWithNetworkError = `mutation MutationNetworkError ($id: Int!) { likePost (id: $id) { id title } }`; export const MutationWithGqlError = `mutation MutationError ($id: Int!) { likePost (id: $id) { id title } }`; export const MutationWithParseError = `mutation MutationParseError ($id: Int!) { likePost (id: $id) { id title } }`; <file_sep># villus <p align="center"> <img width="80%" src="https://raw.githubusercontent.com/logaretm/villus/main/logo.png"> </p> <p align="center"> <a target="_blank" href="https://www.npmjs.com/package/villus"> <img src="https://img.shields.io/npm/v/villus.svg?label=&color=05bda8"> </a> <a target="_blank" href="https://npm-stat.com/charts.html?package=villus"> <img src="https://img.shields.io/npm/dm/villus.svg?color=05bd6d&label="> </a> <a href="https://villus.logaretm.com/" target="_blank"> <img src="https://img.shields.io/badge/-docs%20and%20demos-009f53"> </a> <a href="https://github.com/sponsors/logaretm"> <img src="https://img.shields.io/badge/-%E2%99%A5%20Sponsors-ec5cc6"> </a> </p> <h6 align="center">Villus is a finger-like structures in the small intestine. They help to absorb digested food.</h6> A small and fast GraphQL client for **Vue.js** This is forked from my previous work at [vue-gql](https://github.com/baianat/vue-gql) before they decide to go for a different direction with this library. <p align="center"> <a href="https://github.com/sponsors/logaretm"> <img src='https://sponsors.logaretm.com/sponsors.svg'> </a> </p> <br> You can also help this this project and my other projects by donating one time or by sponsoring. ## Features - 📦 **Minimal:** Its all you need to query GQL APIs - 🦐 **Tiny:** Very small footprint - 🗄 **Caching:** Simple and convenient query caching by default - 👕 **TypeScript:** Written in Typescript and Supports GraphQL TS tooling - 🖇 **Composable:** Built for the Composition API - ⚡️ **Suspense:** Supports the `<Suspense>` API - 🔌 **Plugins:** Use existing plugins and create custom ones ## Why use this GraphQL is just a simple HTTP request. This library is meant to be a tiny client without all the bells and whistles attached to Apollo and its ecosystem which subsequently means it is faster across the board due to it's smaller bundle size and reduced overhead. `villus` offers simple strategies to cache and batch, dedup your GraphQL requests. `villus` also supports file uploads and subscriptions without compromising bundle size through plugins. If you are looking for a more full-featured client use [vue-apollo](https://github.com/vuejs/vue-apollo), it has everything you need. You can read more about it in the [announcement post](https://logaretm.com/blog/2020-01-11-announcing-villus/). ## Documentation You can find the [documentation here](https://villus.logaretm.com/) ## Quick Start First install `villus`: ```bash yarn add villus graphql # or npm npm install villus graphql --save ``` Or because villus is so simple, you can use it via CDN: ```html <!-- Import Vue 3 --> <script src="https://unpkg.com/vue@3.0.2/dist/vue.global.js"></script> <!-- Villus --> <script src="https://unpkg.com/villus@latest/dist/villus.min.js"></script> ``` ### Usage Configure the GraphQL client for your root component: ```vue[App.vue] <script setup> import { useClient } from 'villus'; useClient({ url: 'http://localhost:3002/graphql', }); </script> ``` Then you can use `useQuery` in any child component: ```vue <template> <div> <div v-if="data"> <pre>{{ data }}</pre> </div> </div> </template> <script setup> import { useQuery } from 'villus'; const AllPosts = ` query AllPosts { posts { title } } `; const { data } = useQuery({ query: AllPosts, }); </script> ``` `villus` makes frequent tasks such as re-fetching, caching, deduplication, mutations, and subscriptions a breeze. It has even built-in `Suspense` support with Vue 3! Consult the [documentation](https://villus.logaretm.com) for more use-cases and examples. ## Compatibility This library relies on the `fetch` web API to run queries, you can use [`unfetch`](https://github.com/developit/unfetch) (client-side) or [`node-fetch`](https://www.npmjs.com/package/node-fetch) (server-side) to use as a polyfill. This library is compatible with Vue 3.0+ or 2.7+ ## Examples Live examples can be found [here](https://villus.logaretm.com/examples/basic-query) ## License MIT <file_sep>--- layout: ../../layouts/PageLayout.astro title: useSubscription() description: API reference for the useSubscription composable function order: 3 --- ## useSubscription() The `useSubscription` function allows you to execute GraphQL subscriptions, it requires a `Provider` or `useClient` to be configured in the component tree with a subscription forwarder configured, so make sure to [set that up](/guide/subscriptions) before using `useSubscription`. The `useSubscription` function returns the following properties and functions: | Property | Type | Description | | -------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------ | | data | `Ref<any/null>` | The GraphQL subscription result's `data` | | error | `Ref<CombinedError>` | Any errors encountered during subscription execution | | paused | `ComputedRef<boolean>` | True if the subscription is paused or inactive. This is readonly, and you should control it by the passed `paused` value. | ## Usage The `useSubscription` function accepts two arguments, the first being the operation object which contains the following properties: | Property | Type | Required | Description | | --------- | --------------------------------------------------------- | --------- | ------------------------------- | | query | `string` or `DocumentNode` or `Ref<string>` | **Yes** | The subscription to be executed | | variables | `object` or `Ref<object>` | **No** | The subscription variables | | paused | `boolean`, `Ref<boolean>` or `({ variables }) => boolean` | **No** | If the subscription should be paused, if `true` any incoming values will be ignored by the reducer | The second argument is what is called a `Reducer` which allows you to aggregate subscription results. For more information about that, [check the subscription guide](/guide/subscriptions). Here is a full example of the usage: ```vue <script setup> import { useSubscription } from 'villus'; function messagesReducer(oldValue, response) { oldValue = oldValue || []; if (!response.data || response.errors) { return oldValue; } return [...oldValue, response.data.newMessages]; } const NewMessages = ` subscription NewMessages { newMessages { id from message } } `; const { data } = useSubscription( { query: NewMessages, }, messagesReducer ); </script> ``` ## Reactivity Subscriptions are fired once and continuously keep emitting results. Because of that, `useSubscription` doesn't accept any reactive queries or variables you may pass. For more information about subscriptions, you can check [the subscription guide](/guide/subscriptions). <file_sep>/* eslint-disable no-unused-expressions */ import { ref, computed, reactive } from 'vue'; import { test, expect, describe, vi } from 'vitest'; import gql from 'graphql-tag'; import { server } from './mocks/server'; import flushPromises from 'flush-promises'; import waitForExpect from 'wait-for-expect'; import { mount } from './helpers/mount'; import { useClient, useQuery, cache as cachePlugin, fetch as fetchPlugin, CombinedError } from '../src/index'; import { PostsQuery, QueryWithGqlError, QueryWithParseError, QueryWithNetworkError, QueryErrorWith500, PostQuery, PostsQueryWithDescription, } from './mocks/queries'; import { graphql } from 'msw'; import { DocumentTypeDecoration } from '@graphql-typed-document-node/core'; interface Post { id: number; title: string; } describe('useQuery()', () => { test('executes hook queries on mounted', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, error } = useQuery<{ posts: Post[] }>({ query: PostsQuery, }); return { data, error }; }, template: ` <div>' <div>{{ error }}</div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelectorAll('li').length).toBe(5); }); }); test('accepts tagged queries', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data } = useQuery({ query: gql` query Posts { posts { id title } } `, }); return { data }; }, template: ` <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelectorAll('li').length).toBe(5); }); }); test('accepts typed document strings', async () => { class TypedDocumentString<TResult, TVariables> extends String implements DocumentTypeDecoration<TResult, TVariables> { __apiType?: DocumentTypeDecoration<TResult, TVariables>['__apiType']; constructor( private value: string, public __meta__?: { hash: string }, ) { super(value); } toString(): string & DocumentTypeDecoration<TResult, TVariables> { return this.value; } } mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data } = useQuery({ query: new TypedDocumentString(` query Posts { posts { id title } } `), }); return { data }; }, template: ` <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelectorAll('li').length).toBe(5); }); }); test('caches queries by default', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute } = useQuery({ query: PostsQuery }); return { data, execute }; }, template: ` <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> <button @click="execute()"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); // cache was used. await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); }); test('clears all cache by calling `clearCache` on the cache plugin', async () => { const cache = cachePlugin(); mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [cache, fetchPlugin()], }); const { data, execute } = useQuery({ query: PostsQuery }); return { data, execute }; }, template: ` <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> <button @click="execute()"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); // cache was used. await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); cache.clearCache(); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); // cache was evicted. await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(2); }); }); test('clears specific queries cache by calling `clearCache` on the cache plugin', async () => { const cache = cachePlugin(); mount({ setup() { useClient({ url: 'https://test.com/graphql', use: [cache, fetchPlugin()], }); const { data, execute } = useQuery({ query: PostsQuery, tags: ['posts'] }); return { data, execute }; }, template: ` <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> <button @click="execute()"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); // cache was used. await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); cache.clearCache('posts'); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); // cache was evicted. await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(2); }); }); test('re-runs reactive queries automatically', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const id = ref(12); const query = computed(() => { return `query Post { post (id: ${id.value}) { id title } }`; }); const { data } = useQuery({ query, }); return { data, id }; }, template: ` <div> <button @click="id = 13"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { // fetch was triggered a second time, due to variable change. expect(fetch).toHaveBeenCalledTimes(2); }); }); test('cache policy can be overridden with execute function', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute } = useQuery({ query: PostsQuery }); return { data, execute }; }, template: ` <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> <button @click="execute({ cachePolicy: 'cache-and-network' })"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { // fetch was triggered a second time. expect(fetch).toHaveBeenCalledTimes(2); }); }); test('cache policy can be overridden with cachePolicy option', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute } = useQuery({ query: PostsQuery, cachePolicy: 'cache-and-network', }); return { data, execute }; }, template: ` <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> <button @click="execute()"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { // fetch was triggered a second time. expect(fetch).toHaveBeenCalledTimes(2); }); }); test('variables are watched by default if refs', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const variables = ref({ id: 12, }); const { data } = useQuery({ query: PostQuery, variables, }); return { data, variables }; }, template: ` <div> <div v-if="data"> <h1>{{ data.post.title }}</h1> </div> <button @click="variables.id = 13"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('h1')?.textContent).toContain('12'); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); // fetch was triggered a second time, due to variable change. await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(2); expect(document.querySelector('h1')?.textContent).toContain('13'); }); }); test('variables are watched by default if a getter', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const variables = ref({ id: 12, }); const { data } = useQuery({ query: PostQuery, variables: () => variables.value, }); return { data, variables }; }, template: ` <div> <div v-if="data"> <h1>{{ data.post.title }}</h1> </div> <button @click="variables.id = 13"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('h1')?.textContent).toContain('12'); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); // fetch was triggered a second time, due to variable change. await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(2); expect(document.querySelector('h1')?.textContent).toContain('13'); }); }); test('variables are watched by default if reactive', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const variables = reactive({ id: 12, }); const { data } = useQuery({ query: PostQuery, variables }); return { data, variables }; }, template: ` <div> <div v-if="data"> <h1>{{ data.post.title }}</h1> </div> <button @click="variables.id = 13"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('h1')?.textContent).toContain('12'); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { // fetch was triggered a second time, due to variable change. expect(fetch).toHaveBeenCalledTimes(2); expect(document.querySelector('h1')?.textContent).toContain('13'); }); }); test('cached variables are matched by equality not reference', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const variables = ref({ id: 12, }); const { data } = useQuery({ query: PostQuery, variables, }); function updateRef() { variables.value = { id: 12 }; } return { data, variables, updateRef }; }, template: ` <div> <div v-if="data"> <h1>{{ data.post.title }}</h1> </div> <button @click="updateRef"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('h1')?.textContent).toContain('12'); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { // fetch was triggered a second time, due to variable change. expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('h1')?.textContent).toContain('12'); }); }); test('can skip execution given a skip ref', async () => { const skip = ref(false); const variables = ref({ id: 12 }); mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute, isFetching } = useQuery({ query: PostQuery, variables, skip, }); return { data, execute, isFetching }; }, template: ` <div> <div v-if="data"> <h1>{{ data.post.title }}</h1> </div> <span id="fetching">{{ isFetching }}</span> <button @click="execute"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('h1')?.textContent).toContain('12'); }); variables.value = { id: 13 }; skip.value = true; await flushPromises(); expect(fetch).toHaveBeenCalledTimes(1); // data didn't change expect(document.querySelector('h1')?.textContent).toContain('12'); // explicit execution won't work either document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('h1')?.textContent).toContain('12'); expect(document.querySelector('#fetching')?.textContent).toBe('false'); skip.value = false; document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); expect(fetch).toHaveBeenCalledTimes(2); // fetch was triggered a second time, due to variable change. await waitForExpect(() => { expect(document.querySelector('h1')?.textContent).toContain('13'); }); }); test('can skip execution given a skip getter', async () => { const skip = ref(false); const variables = ref({ id: 12 }); mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute, isFetching } = useQuery({ query: PostQuery, variables, skip: () => skip.value, }); return { data, execute, isFetching }; }, template: ` <div> <div v-if="data"> <h1>{{ data.post.title }}</h1> </div> <span id="fetching">{{ isFetching }}</span> <button @click="execute"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('h1')?.textContent).toContain('12'); }); variables.value = { id: 13 }; skip.value = true; await flushPromises(); expect(fetch).toHaveBeenCalledTimes(1); // data didn't change expect(document.querySelector('h1')?.textContent).toContain('12'); // explicit execution won't work either document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('h1')?.textContent).toContain('12'); expect(document.querySelector('#fetching')?.textContent).toBe('false'); skip.value = false; document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); expect(fetch).toHaveBeenCalledTimes(2); // fetch was triggered a second time, due to variable change. await waitForExpect(() => { expect(document.querySelector('h1')?.textContent).toContain('13'); }); }); test('can pause execution given a pause ref', async () => { const paused = ref(false); const variables = ref({ id: 12 }); mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute, isFetching } = useQuery({ query: PostQuery, variables, paused, }); return { data, execute, isFetching }; }, template: ` <div> <div v-if="data"> <h1>{{ data.post.title }}</h1> </div> <span id="fetching">{{ isFetching }}</span> <button @click="execute"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('h1')?.textContent).toContain('12'); }); variables.value = { id: 13 }; paused.value = true; await flushPromises(); expect(fetch).toHaveBeenCalledTimes(1); // data didn't change expect(document.querySelector('h1')?.textContent).toContain('12'); // explicit execution still works document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); expect(fetch).toHaveBeenCalledTimes(2); await waitForExpect(() => { expect(document.querySelector('h1')?.textContent).toContain('13'); expect(document.querySelector('#fetching')?.textContent).toBe('false'); }); variables.value = { id: 14 }; await flushPromises(); // changing back to `false` will trigger an additional fetch paused.value = false; await flushPromises(); expect(fetch).toHaveBeenCalledTimes(3); // fetch was triggered a second time, due to variable change. await waitForExpect(() => { expect(document.querySelector('h1')?.textContent).toContain('14'); }); }); test('can pause execution given a pause getter', async () => { const paused = ref(false); const variables = ref({ id: 12 }); mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute, isFetching } = useQuery({ query: PostQuery, variables, paused: () => paused.value, }); return { data, execute, isFetching }; }, template: ` <div> <div v-if="data"> <h1>{{ data.post.title }}</h1> </div> <span id="fetching">{{ isFetching }}</span> <button @click="execute"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('h1')?.textContent).toContain('12'); }); paused.value = true; variables.value = { id: 13 }; await flushPromises(); expect(fetch).toHaveBeenCalledTimes(1); // data didn't change expect(document.querySelector('h1')?.textContent).toContain('12'); // explicit execution will work document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); expect(fetch).toHaveBeenCalledTimes(2); await waitForExpect(() => { expect(document.querySelector('h1')?.textContent).toContain('13'); expect(document.querySelector('#fetching')?.textContent).toBe('false'); }); variables.value = { id: 14 }; await flushPromises(); paused.value = false; // will trigger an additional fetch await flushPromises(); expect(fetch).toHaveBeenCalledTimes(3); // fetch was triggered a second time, due to variable change. await waitForExpect(() => { expect(document.querySelector('h1')?.textContent).toContain('14'); }); }); test('variables prop arrangement does not trigger queries', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const variables = ref({ id: 12, type: 'test', }); const { data } = useQuery({ query: PostQuery, variables, }); return { data, variables }; }, template: ` <div> <div v-if="data"> <h1>{{ data.post.title }}</h1> </div> <button @click="variables = { type: 'test', id: 12 }"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('h1')?.textContent).toContain('12'); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); }); test('can be suspended', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); }, components: { Listing: { async setup() { const { data } = await useQuery({ query: PostsQuery }); return { data }; }, template: ` <ul> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> `, }, }, template: ` <div> <Suspense> <Listing /> <template #fallback> <span>Loading...</span> </template> </Suspense> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelectorAll('li').length).toBe(5); }); }); test('Handles query errors', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, error } = useQuery({ query: QueryWithGqlError, }); return { data, error }; }, template: ` <div> <div v-if="data"> <h1>It shouldn't work!</h1> </div> <p id="error" v-if="error">{{ error.message }}</p> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelector('#error')?.textContent).toMatch(/Not authenticated/); }); }); test('Handles parse errors', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, error } = useQuery({ query: QueryWithParseError, }); return { data, error }; }, template: ` <div> <div v-if="data"> <h1>It shouldn't work!</h1> </div> <p id="error" v-if="error">{{ error.message }}</p> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelector('#error')?.textContent).toMatch(/is not valid JSON/); }); }); test('Handles network errors', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, error } = useQuery({ query: QueryWithNetworkError, }); return { data, error }; }, template: ` <div> <div v-if="data"> <h1>It shouldn't work!</h1> </div> <p id="error" v-if="error">{{ error.message }}</p> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelector('#error')?.textContent).toMatch(/Failed to connect/); }); }); test('Fails if provider was not resolved', () => { try { mount({ setup() { const { data, error } = useQuery({ query: `{ posts { id title } }` }); return { messages: data, error }; }, template: ` <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> </div> `, }); } catch (err) { expect((err as Error).message).toContain('Cannot detect villus Client'); } }); test('Errors can be separated by type', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, error } = useQuery({ query: QueryWithNetworkError, }); return { data, error }; }, template: ` <div> <div v-if="data"> <h1>It shouldn't work!</h1> </div> <p id="error" v-if="error">{{ error.isGraphQLError ? 'GraphQL' : 'Network' }}</p> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelector('#error')?.textContent).toBe('Network'); }); }); // # 49 test('Errors can have non 200 response code', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, error } = useQuery({ query: QueryErrorWith500, }); return { data, error }; }, template: ` <div> <div v-if="data"> <h1>It shouldn't work!</h1> </div> <p id="error" v-if="error">{{ error.isGraphQLError ? 'GraphQL' : 'Network' }}</p> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelector('#error')?.textContent).toBe('GraphQL'); }); }); test('cache-only policy returns null results if not found', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', cachePolicy: 'cache-only', }); const { data, execute } = useQuery({ query: PostsQuery }); return { data, execute }; }, template: ` <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(0); expect(document.querySelector('ul')).toBeNull(); }); }); test('cache-only policy returns results if found in cache', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute } = useQuery({ query: PostsQuery }); return { data, execute }; }, template: ` <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> <button @click="execute({ cachePolicy: 'cache-only' })"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(1); }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { // cache was used. expect(fetch).toHaveBeenCalledTimes(1); expect(document.querySelector('ul')?.children).toHaveLength(5); }); }); test('dedups duplicate queries', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); useQuery({ query: PostsQuery }); useQuery({ query: PostsQuery }); useQuery({ query: PostsQuery }); useQuery({ query: PostsQueryWithDescription }); useQuery({ query: PostsQueryWithDescription }); return {}; }, template: `<div></div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledTimes(2); // only 2 unique queries were executed }); }); test('isFetching should start with true if fetchOnMount is true', async () => { const spy = vi.fn(); mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { isFetching } = useQuery({ query: PostsQuery, }); spy(isFetching.value); return { isFetching, }; }, template: `<div id="el">{{ isFetching }}</div>`, }); await flushPromises(); await waitForExpect(() => { expect(spy).toHaveBeenCalledWith(true); }); }); test('isFetching should start with false if fetchOnMount is false', async () => { const spy = vi.fn(); mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { isFetching } = useQuery({ query: PostsQuery, fetchOnMount: false, }); spy(isFetching.value); return { isFetching, }; }, template: `<div id="el">{{ isFetching }}</div>`, }); await flushPromises(); await waitForExpect(() => { expect(spy).toHaveBeenCalledWith(false); }); }); test('additional context can be provided per query', async () => { const ctx = { 'SOME-AUTH-HEADER': 'OH YEA', }; mount({ setup() { useClient({ url: 'https://test.com/graphql', }); useQuery({ query: PostsQuery, context: { headers: ctx, }, }); return {}; }, template: `<div></div>`, }); await flushPromises(); await waitForExpect(() => { expect(fetch).toHaveBeenCalledWith( 'https://test.com/graphql', expect.objectContaining({ url: 'https://test.com/graphql', body: expect.anything(), method: 'POST', headers: expect.objectContaining(ctx), }), ); }); }); test('cache-and-network updates the reactive data', async () => { const posts = [{ id: 1, title: 'First post' }]; server.use( graphql.query('Posts', (req, res, ctx) => { return res( ctx.data({ posts, }), ); }), ); mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { data, execute } = useQuery({ query: PostsQuery, cachePolicy: 'cache-and-network', }); return { data, execute }; }, template: ` <div> <ul v-if="data"> <li v-for="post in data.posts" :key="post.id">{{ post.title }}</li> </ul> <button @click="execute()"></button> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelectorAll('li')).toHaveLength(1); }); posts.push({ id: 2, title: 'Second post' }); document.querySelector('button')?.dispatchEvent(new Event('click')); await flushPromises(); await waitForExpect(() => { expect(document.querySelectorAll('li')).toHaveLength(2); }); server.resetHandlers(); }); test('onData option hook is called when query get data', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const posts = ref<Post[]>(); const { error } = useQuery<{ posts: Post[] }>({ query: PostsQuery, onData: data => (posts.value = data.posts), }); return { error, posts }; }, template: ` <div>' <div>{{ error }}</div> <ul v-if="posts"> <li v-for="post in posts" :key="post.id">{{ post.title }}</li> </ul> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelectorAll('li').length).toBe(5); }); }); test('onError hook is called when query get error', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const errorMessage = ref<string>(); const { data } = useQuery({ query: QueryWithGqlError, onError: err => (errorMessage.value = err.message), }); return { data, errorMessage }; }, template: ` <div> <div v-if="data"> <h1>It shouldn't work!</h1> </div> <p id="error" v-if="errorMessage">{{ errorMessage }}</p> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelector('#error')?.textContent).toMatch(/Not authenticated/); }); }); test('onData option hook is not called when query get error', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const posts = ref<Post[]>(); const { error } = useQuery({ query: QueryWithGqlError, onData: data => (posts.value = data.posts), }); return { error, posts }; }, template: ` <div>' <div>{{ error }}</div> <ul v-if="posts"> <li v-for="post in posts" :key="post.id">{{ post.title }}</li> </ul> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelectorAll('li').length).toBe(0); }); }); test('onError hook is not called when query get data', async () => { mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const errorMessage = ref<string>(); const { data } = useQuery<{ posts: Post[] }>({ query: PostsQuery, onError: err => (errorMessage.value = err.message), }); return { data, errorMessage }; }, template: ` <div> <div v-if="data"> <h1>It shouldn't work!</h1> </div> <p id="error" v-if="errorMessage">{{ errorMessage }}</p> </div>`, }); await flushPromises(); await waitForExpect(() => { expect(document.querySelector('#error')?.textContent).toBeUndefined(); }); }); test('can have multiple onData hooks', async () => { const spies = [vi.fn(), vi.fn()] as const; const errorSpy = vi.fn(); mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { onData, onError } = useQuery<{ posts: Post[] }>({ query: PostsQuery, }); onData(spies[0]); onData(spies[1]); onError(errorSpy); }, template: `<div></div>`, }); await flushPromises(); await waitForExpect(() => { expect(spies[0]).toHaveBeenCalledWith( expect.objectContaining({ posts: expect.any(Array), }), ); expect(spies[1]).toHaveBeenCalledWith( expect.objectContaining({ posts: expect.any(Array), }), ); expect(errorSpy).not.toHaveBeenCalled(); }); }); test('can have multiple onError hooks', async () => { const spies = [vi.fn(), vi.fn()] as const; const dataSpy = vi.fn(); mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { onError, onData } = useQuery({ query: QueryWithGqlError, }); onError(spies[0]); onError(spies[1]); onData(dataSpy); }, template: `<div></div>`, }); await flushPromises(); await waitForExpect(() => { expect(spies[0]).toHaveBeenCalledWith(expect.any(CombinedError)); expect(spies[1]).toHaveBeenCalledWith(expect.any(CombinedError)); expect(dataSpy).not.toHaveBeenCalled(); }); }); test('can unregister data hooks', async () => { const spies = [vi.fn(), vi.fn()] as const; mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { onData } = useQuery<{ posts: Post[] }>({ query: PostsQuery, }); onData(spies[0]); const unregister = onData(spies[1]); unregister(); }, template: `<div></div>`, }); await flushPromises(); await waitForExpect(() => { expect(spies[0]).toHaveBeenCalledWith( expect.objectContaining({ posts: expect.any(Array), }), ); expect(spies[1]).not.toHaveBeenCalled(); }); }); test('can unregister onError hooks', async () => { const spies = [vi.fn(), vi.fn()] as const; mount({ setup() { useClient({ url: 'https://test.com/graphql', }); const { onError } = useQuery({ query: QueryWithGqlError, }); onError(spies[0]); const unregister = onError(spies[1]); unregister(); }, template: `<div></div>`, }); await flushPromises(); await waitForExpect(() => { expect(spies[0]).toHaveBeenCalledWith(expect.any(CombinedError)); expect(spies[1]).not.toHaveBeenCalled(); }); }); }); <file_sep>--- layout: ../../layouts/PageLayout.astro title: Query with Suspense description: Using the new Suspense feature in Vue 3 order: 2 --- # Query with Suspense This is an example that utilizes Vue 3's `<Suspense />` component with `useQuery` <p class="codepen" data-height="602" data-theme-id="light" data-default-tab="js,result" data-user="logaretm" data-slug-hash="xxVmPJg" style="height: 602px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="Query with Suspense"> <span>See the Pen <a href="https://codepen.io/logaretm/pen/xxVmPJg"> Query with Suspense</a> by <NAME> (<a href="https://codepen.io/logaretm">@logaretm</a>) on <a href="https://codepen.io">CodePen</a>.</span> </p> <script async src="https://static.codepen.io/assets/embed/ei.js"></script>
9c46c65e527d09a893e9fffd9047afedefd9093b
[ "Markdown", "TypeScript", "JavaScript", "Shell" ]
69
TypeScript
logaretm/villus
06b69a8c53cec80c523e2a6bdd73d17d0c6c6069
a73a486da326641ad7de41cbae6177e8cb0720d2
refs/heads/master
<repo_name>cayetanobv/python-metar<file_sep>/test_metar_decode_short.py #!/usr/bin/env python # # This is a minimal sample script showing how the individual data # are accessed from the decoded report. To produce the standard text # summary of a report, the string() method of the Metar object. # # The parsed data are stored as attributes of a Metar object. # Individual attributes are either strings. instances of one of the # metar.Datatypes classes, or lists of tuples of these scalars. # Here's a summary, adapted from the comments in the Metar.Metar.__init__() # method: # # Attribute Comments [data type] # -------------- -------------------- # code original METAR code [string] # type METAR (routine) or SPECI (special) [string] # mod AUTO (automatic) or COR (corrected) [string] # station_id 4-character ICAO station code [string] # time observation time [datetime] # cycle observation cycle (0-23) [int] # wind_dir wind direction [direction] # wind_speed wind speed [speed] # wind_gust wind gust speed [speed] # wind_dir_from beginning of range for win dir [direction] # wind_dir_to end of range for wind dir [direction] # vis visibility [distance] # vis_dir visibility direction [direction] # max_vis visibility [distance] # max_vis_dir visibility direction [direction] # temp temperature (C) [temperature] # dewpt dew point (C) [temperature] # press barometric pressure [pressure] # runway runway visibility [list of tuples...] # name [string] # low [distance] # high [distance] # weather present weather [list of tuples...] # intensity [string] # description [string] # precipitation [string] # obscuration [string] # other [string] # recent recent weather [list of tuples...] # sky sky conditions [list of tuples...] # cover [string] # height [distance] # cloud [string] # windshear runways w/ wind shear [list of strings] # # press_sea_level sea-level pressure [pressure] # wind_speed_peak peak wind speed in last hour [speed] # wind_dir_peak direction of peak wind speed in last hour [direction] # max_temp_6hr max temp in last 6 hours [temperature] # min_temp_6hr min temp in last 6 hours [temperature] # max_temp_24hr max temp in last 24 hours [temperature] # min_temp_24hr min temp in last 24 hours [temperature] # precip_1hr precipitation over the last hour [precipitation] # precip_3hr precipitation over the last 3 hours [precipitation] # precip_6hr precipitation over the last 6 hours [precipitation] # precip_24hr precipitation over the last 24 hours [precipitation] # # _remarks remarks [list of strings] # _unparsed unparsed remarks [list of strings] # # The metar.Datatypes classes (temperature, pressure, precipitation, # speed, direction) describe an observation and its units. They provide # value() and string() methods to that return numerical and string # representations of the data in any of a number of supported units. # # (You're going to have to study the source code for more details, # like the available methods and supported unit conversions for the # metar.Datatypes objects, etc..) # In particular, look at the Metar.string() # method, and the functions it calls. # # Feb 4, 2005 # <NAME> # from metar.Metar import Metar # A sample METAR report #code = "METAR KEWR 111851Z VRB03G19KT 2SM R04R/3000VP6000FT TSRA BR FEW015 BKN040CB BKN065 OVC200 22/22 A2987 RMK AO2 PK WND 29028/1817 WSHFT 1812 TSB05RAB22 SLP114 FRQ LTGICCCCG TS OHD AND NW-N-E MOV NE P0013 T02270215" #code = 'METAR TFFF 151430Z AUTO 08016KT 050V110 9999 SCT032 BKN038 BKN044' #code = 'METAR SVVA 092200Z 36004KT 9999 -DZ BKN016' #code = 'METAR CYPY 120000Z AUTO 27008KT 9SM BKN090 OVC110 13/M00 A3001 RMK SLP171' #code='METAR SVVA 092200Z 36004KT 9999 -DZ BKN016 30/21 Q1011' #code = 'METAR LCPH 120000Z 01008KT FEW020 22/18' #code = 'METAR LBBG 120000Z 05004MPS 9999 FEW033 19/17 Q1015 NOSIG' #code = ' METAR LCPH 120000Z 01008KT 9999 FEW020 22/18 Q1013' #code = 'SPECI YSNF 220000Z 22017G28KT 9999 FEW024 SCT300 18/11 Q1021' #code = 'METAR OYRN 220100Z 36004KT CAVOK 29/26 Q1005' #code = 'METAR SPIM 120000Z 29006KT 9999 OVC010 16/13 Q1013 NOSIG RMK PP000 SLP171' #code='METAR TNCM 220100Z 06010KT 9999 VCSH SCT017TCU 29/24 Q1016 A3001 NOSI G' #code ='METAR ETSI 220020Z AUTO 30006KT 6000 // ////// 12/11 Q1017 ///' #code='METAR EBLB 220125Z AUTO 34011KT 3600 SCT002/// BKN004/// BKN006/// 09/09 Q1021 AMB' #code='METAR CYYF 220200Z VRB02KT 15SM SKC 20/11 A2983 RMK SLP102 DENSITY ALT 2000FT' #code='METAR VTCT 220000Z 19003KT 9999 BKN015 OVC100 25/23 Q1010 A2983 RMK/RWY03 INFO A' #code= 'METAR CZBF 220100Z 20005KT 170V230 15SM FEW100 OVC250 19/15 A2973 RMK AC2CS6 SLP068 DENSITY ALT 800FT' #code = 'METAR SVMG 220100Z /////KT 9999 TS FEW010 CB/NE 28/25 Q1012 TEMPO' #code = 'METAR FKKD 220000Z 00000KT 9999 TS BKN013 FEW016CB 25/24 Q1014 TEMPO 4000 -TSRA' #code='METAR OMDW 220000Z 09006KT 2500 BR NSC 26/25 Q1004 BECMG 0800 BCFG' #code='METAR LCEN 302350Z 28008KT CAVOK 17/09 Q1016 NOSIG' #code='SPECI CZCP 302353Z AUTO 11016KT 2 3/4SM OVC005 OVC015 OVC020 M03/ A2989 RMK ICG PAST HR' #code='METAR VANP 302340Z 00000KT 3500 HZ NSC 21/18 Q1014 TEMPO 3000 HZ/BR' #code='METAR SEGU 010000Z 22009KT 9999 SCT023 BKN100 26/20 Q1009 RMK A2983 NOSIG' #code='METAR SEQM 010000Z 12007KT CAVOK 16/03 Q1024 NOSIG RMK A3024' #code='SPECI CZCP 302355Z AUTO 11017KT 2 3/4SM OVC004 OVC020 M03/ A2989 RMK ICG PAST HR' #code='METAR LCEN 302350Z 28008KT CAVOK 17/09 Q1016 NOSIG' #code='METAR VABB 310040Z 08008KT 3000 HZ NSC 25/18 Q1011 NOSIG=' #code='METAR COR VABB 310040Z 08008KT 3000 HZ NSC 25/18 Q1011 NOSIG=' #code='METAR LEMD 222200Z 35007KT 310V020 CAVOK 27/10 Q1015 NOSIG=' #code='METAR UMMM 151230Z 08004MPS 9999 FEW025 OVC100 07/00 Q1041 R12/CLRD60 NOSIG RMK QFE760' #code='METAR UMMS 151230Z 01002MPS 010V070 CAVOK 09/00 Q1042 R13/CLRD// NOSIG' # code='METAR EYKA 151250Z 10007KT 060V130 CAVOK 09/00 Q1042 R08/090095' #code='METAR UMMS 151230Z 01002MPS 010V070 CAVOK 09/00 Q1042 R88CLRD95 NOSIG' #code='METAR UMMS 151230Z 01002MPS 010V070 CAVOK 09/00 Q1042 R24CLRD93 NOSIG' #code='METAR UMMS 151230Z 01002MPS 010V070 CAVOK 09/00 Q1042 R99/421594 NOSIG' #code='METAR UMMS 151230Z 01002MPS 010V070 CAVOK 09/00 Q1042 R99/SNOCLO NOSIG' #code='METAR LTAJ 151220Z 24012KT 9999 SCT040 BKN100 14/04 Q1017 TEMPO Q1019 TEMPO 27015G25KT -TSRA' code='SPECI KBTV 151208Z 36007KT 1SM R15/P6000FT -SN BR BKN006 OVC019 M01/M03 A2965' print "-----------------------------------------------------------------------" print "METAR: ",code print "-----------------------------------------------------------------------" # Initialize a Metar object with the coded report obs = Metar(code) print obs.string() print obs.json() #print obs.string().split('\n') metar_header = {} metar_header['ICAO_code'] = obs.station_id metar_header['origin_time'] = obs.time.isoformat(' ') metar_header['origin_date'] = obs.time.day metar_header['origin_hours'] = obs.time.isoformat()[11:13] metar_header['origin_minutes'] = obs.time.isoformat()[14:16] print metar_header
561446b4478384121a7ac7a8255d9e8d9f6f5187
[ "Python" ]
1
Python
cayetanobv/python-metar
9daa0a30fb342b47e21bb97aefc4c106fa7cc746
af033d66ac4da4ac895fd1e96208a43ff26d0b10
refs/heads/master
<repo_name>enzococca/Tilgjengelighet<file_sep>/FAKT_Dokumentasjon/_modules/AttributeForm.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>AttributeForm &#8212; Tilgjengelig For Alle 0.1 documentation</title> <link rel="stylesheet" href="../_static/alabaster.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="stylesheet" href="../_static/custom.css" type="text/css" /> <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" /> </head><body> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <h1>Source code for AttributeForm</h1><div class="highlight"><pre> <span></span><span class="kn">import</span> <span class="nn">operator</span> <div class="viewcode-block" id="AttributeForm"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm">[docs]</a><span class="k">class</span> <span class="nc">AttributeForm</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Saves attributes and assosiated gui widgets&quot;&quot;&quot;</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">attribute</span><span class="p">,</span> <span class="n">comboBox</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">lineEdit</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">comboBoxText</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Constructor</span> <span class="sd"> :param attribute: The name of the attribute in layer</span> <span class="sd"> :type attribute: str</span> <span class="sd"> :param comboBox: The associated comboBox</span> <span class="sd"> :type comboBox: QComboBox</span> <span class="sd"> :param lineEdit: The associated lineEdit</span> <span class="sd"> :type lineEdit: QLineEdit</span> <span class="sd"> :param comboBoxText: Alternative text for combobox</span> <span class="sd"> :type comboBoxText: dict</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="bp">self</span><span class="o">.</span><span class="n">attribute</span> <span class="o">=</span> <span class="n">attribute</span> <span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span> <span class="o">=</span> <span class="n">comboBox</span> <span class="bp">self</span><span class="o">.</span><span class="n">lineEdit</span> <span class="o">=</span> <span class="n">lineEdit</span> <span class="bp">self</span><span class="o">.</span><span class="n">label</span> <span class="o">=</span> <span class="n">label</span> <span class="bp">self</span><span class="o">.</span><span class="n">alt_comboboxText</span> <span class="o">=</span> <span class="n">comboBoxText</span> <span class="bp">self</span><span class="o">.</span><span class="n">opperatorDict</span> <span class="o">=</span> <span class="p">{</span><span class="sa">u</span><span class="s1">&#39;=&#39;</span> <span class="p">:</span> <span class="s1">&#39;PropertyIsEqualTo&#39;</span><span class="p">,</span> <span class="sa">u</span><span class="s1">&#39;&lt;&#39;</span> <span class="p">:</span> <span class="s1">&#39;PropertyIsLessThan&#39;</span><span class="p">,</span> <span class="sa">u</span><span class="s1">&#39;&gt;&#39;</span> <span class="p">:</span> <span class="s1">&#39;PropertyIsGreaterThan&#39;</span><span class="p">,</span> <span class="sa">u</span><span class="s1">&#39;&lt;=&#39;</span> <span class="p">:</span> <span class="s1">&#39;PropertyIsLessThanOrEqualTo&#39;</span><span class="p">,</span> <span class="sa">u</span><span class="s1">&#39;&gt;=&#39;</span> <span class="p">:</span> <span class="s1">&#39;PropertyIsGreaterThanOrEqualTo&#39;</span><span class="p">}</span> <span class="c1">#attribute.opperator(), attribute.valueReference(), attribute.value()</span> <div class="viewcode-block" id="AttributeForm.opperator"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.opperator">[docs]</a> <span class="k">def</span> <span class="nf">opperator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;</span> <span class="sd"> :returns: the opperator for attriubutt qury</span> <span class="sd"> :rtype: QString, None</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span><span class="o">.</span><span class="n">currentText</span><span class="p">()</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">opperatorDict</span><span class="p">:</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">opperatorDict</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span><span class="o">.</span><span class="n">currentText</span><span class="p">()]</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">opperatorDict</span><span class="p">[</span><span class="sa">u</span><span class="s1">&#39;=&#39;</span><span class="p">]</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="kc">None</span></div> <div class="viewcode-block" id="AttributeForm.valueReference"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.valueReference">[docs]</a> <span class="k">def</span> <span class="nf">valueReference</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Returns the objekt attribute</span> <span class="sd"> </span> <span class="sd"> :returns: name of object attribute in database</span> <span class="sd"> :rtype: str</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">attribute</span></div> <div class="viewcode-block" id="AttributeForm.value"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.value">[docs]</a> <span class="k">def</span> <span class="nf">value</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;returns the value constraint, if alternative combobox is set, return that value, if lineedit, ruturn value freom line edit, else return from combobox</span> <span class="sd"> </span> <span class="sd"> :returns: the value constraint</span> <span class="sd"> :rtype: str</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">alt_comboboxText</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">alt_comboboxText</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span><span class="o">.</span><span class="n">currentText</span><span class="p">()]</span> <span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">lineEdit</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">lineEdit</span><span class="o">.</span><span class="n">text</span><span class="p">()</span> <span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span><span class="o">.</span><span class="n">currentText</span><span class="p">()</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="kc">None</span></div> <div class="viewcode-block" id="AttributeForm.setComboBox"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.setComboBox">[docs]</a> <span class="k">def</span> <span class="nf">setComboBox</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">comboBox</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Assigning comboBox</span> <span class="sd"> :param comboBox: combobox assisiated to attribute</span> <span class="sd"> :type comboBox: QComboBox</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span> <span class="o">=</span> <span class="n">comboBox</span></div> <div class="viewcode-block" id="AttributeForm.setLineEdit"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.setLineEdit">[docs]</a> <span class="k">def</span> <span class="nf">setLineEdit</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">lineEdit</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Assigning lineEdit</span> <span class="sd"> :param lineEdit: Linedit assisiated to attribute</span> <span class="sd"> :type lineEdit: QLineEdit</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="bp">self</span><span class="o">.</span><span class="n">lineEdit</span> <span class="o">=</span> <span class="n">lineEdit</span></div> <div class="viewcode-block" id="AttributeForm.getComboBox"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.getComboBox">[docs]</a> <span class="k">def</span> <span class="nf">getComboBox</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot; Returns the assosiated combobox widget</span> <span class="sd"> :returns: returns the associated comboBox</span> <span class="sd"> :rtype: QComboBox</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span></div> <div class="viewcode-block" id="AttributeForm.getLineEdit"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.getLineEdit">[docs]</a> <span class="k">def</span> <span class="nf">getLineEdit</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Returns the assosiated lineEdit widget if any</span> <span class="sd"> :returns: returns the associated lineEdit</span> <span class="sd"> :rtype: QLineEdit</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">lineEdit</span></div> <div class="viewcode-block" id="AttributeForm.getLabel"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.getLabel">[docs]</a> <span class="k">def</span> <span class="nf">getLabel</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Returns the assisiated label widget if any</span> <span class="sd"> :returns: returns the associated label</span> <span class="sd"> :rtype: QLabel</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">label</span></div> <div class="viewcode-block" id="AttributeForm.getAttribute"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.getAttribute">[docs]</a> <span class="k">def</span> <span class="nf">getAttribute</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Returns the assosiated attriubte name</span> <span class="sd"> :returns: returns the associated attribute name</span> <span class="sd"> :rtype: str</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">attribute</span></div> <div class="viewcode-block" id="AttributeForm.getComboBoxCurrentText"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.getComboBoxCurrentText">[docs]</a> <span class="k">def</span> <span class="nf">getComboBoxCurrentText</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Returns the assosoated combobox text</span> <span class="sd"> :returns: returns the associated comboBox text, return None if no combobox is availeble</span> <span class="sd"> :rtype: QString</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">alt_comboboxText</span><span class="p">:</span> <span class="c1">#If AttributForm has alternative text, return alternative text</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">alt_comboboxText</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span><span class="o">.</span><span class="n">currentText</span><span class="p">()]</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span><span class="o">.</span><span class="n">currentText</span><span class="p">()</span> <span class="k">return</span> <span class="kc">None</span></div> <div class="viewcode-block" id="AttributeForm.getLineEditText"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.getLineEditText">[docs]</a> <span class="k">def</span> <span class="nf">getLineEditText</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Returns the lineEdit text</span> <span class="sd"> :returns: returns the lineEdit text, return None if no lineEdit is availeble</span> <span class="sd"> :rtype: QString</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">lineEdit</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">lineEdit</span><span class="o">.</span><span class="n">text</span><span class="p">()</span> <span class="k">return</span> <span class="kc">None</span></div> <div class="viewcode-block" id="AttributeForm.setLineEditText"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.setLineEditText">[docs]</a> <span class="k">def</span> <span class="nf">setLineEditText</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">string</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Sett text in AttributeForm lineEdit</span> <span class="sd"> :param string: String to set in lineEdit</span> <span class="sd"> :type string: str</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">lineEdit</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">lineEdit</span><span class="o">.</span><span class="n">setText</span><span class="p">(</span><span class="n">string</span><span class="p">)</span></div> <div class="viewcode-block" id="AttributeForm.valudeValid"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.valudeValid">[docs]</a> <span class="k">def</span> <span class="nf">valudeValid</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;checks if the attribute is valid and search ready</span> <span class="sd"> :returns: True if attrivute is valid, false if not</span> <span class="sd"> :rtype: boolean</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">lineEdit</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">opperator</span><span class="p">()</span> <span class="o">!=</span> <span class="s1">&#39;PropertyIsEqualTo&#39;</span> <span class="ow">and</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">getLineEditText</span><span class="p">())</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> <span class="c1">#opperator chosen, but no value</span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;IsValid 1&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="kc">False</span> <span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">opperator</span><span class="p">()</span> <span class="o">==</span> <span class="s1">&#39;PropertyIsEqualTo&#39;</span> <span class="ow">and</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">getLineEditText</span><span class="p">())</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span> <span class="c1">#value chosen, bu no opperator</span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;IsValid 2&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="kc">False</span> <span class="k">elif</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">getLineEditText</span><span class="p">())</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;len: </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">getLineEditText</span><span class="p">())))</span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;IsValid 3&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">is_number</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">getLineEditText</span><span class="p">())</span> <span class="c1">#Valu not a number</span> <span class="k">else</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;attribute is valid&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="kc">True</span></div> <div class="viewcode-block" id="AttributeForm.reset"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.reset">[docs]</a> <span class="k">def</span> <span class="nf">reset</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Resets form to defult&quot;&quot;&quot;</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">comboBox</span><span class="o">.</span><span class="n">setCurrentIndex</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">lineEdit</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">lineEdit</span><span class="o">.</span><span class="n">setText</span><span class="p">(</span><span class="s2">&quot;&quot;</span><span class="p">)</span></div> <div class="viewcode-block" id="AttributeForm.is_number"><a class="viewcode-back" href="../code.html#AttributeForm.AttributeForm.is_number">[docs]</a> <span class="k">def</span> <span class="nf">is_number</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">s</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Sett text in AttributeForm lineEdit</span> <span class="sd"> :param s: string to be change for being a number</span> <span class="sd"> :type s: str</span> <span class="sd"> :returns: tru if s is number, false if s in not a number</span> <span class="sd"> :rtype: boolean</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;s: </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">s</span><span class="p">))</span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;type: </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="n">s</span><span class="p">)))</span> <span class="k">try</span><span class="p">:</span> <span class="nb">float</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="k">return</span> <span class="kc">True</span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span> <span class="k">return</span> <span class="kc">False</span></div></div> </pre></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"><div class="relations"> <h3>Related Topics</h3> <ul> <li><a href="../FAKT_Dokumentasjon.html">Documentation overview</a><ul> <li><a href="index.html">Module code</a><ul> </ul></li> </ul></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer"> &copy;2018, <NAME>. | Powered by <a href="http://sphinx-doc.org/">Sphinx 1.7.4</a> &amp; <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.10</a> </div> </body> </html><file_sep>/FAKT_Dokumentasjon/_sources/code.rst.txt FAKT - Automatisk Generert Dokumantasjon ======================================== Tilgjengelighet --------------- .. automodule:: Tilgjengelighet :members: :undoc-members: :show-inheritance: AttributeForm ------------- .. automodule:: AttributeForm :members: :undoc-members: :show-inheritance: SavedSearch ----------- .. automodule:: SavedSearch :members: :undoc-members: :show-inheritance:<file_sep>/Tilgjengelighet.py # -*- coding: utf-8 -*- """ /*************************************************************************** Tilgjengelighet A QGIS plugin My Tilgjengelighet assignment ------------------- begin : 2017-08-21 git sha : $Format:%H$ copyright : (C) 2017 by <NAME> email : <EMAIL> ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ """ import sys import os import io import urllib import urllib.parse import random import tempfile import string import datetime import operator import codecs import time from qgis.core import * #QgsDataSourceURI, QgsMapLayerRegistry, QgsVectorLayer, QgsExpression, QgsFeatureRequest, QgsVectorFileWriter, QgsLayerTreeLayer, QgsLayerTreeGroup, QgsMapLayer, QgsProject, QgsFeature, QGis from PyQt4.QtCore import * #QSettings, QTranslator, qVersion, QCoreApplication, QPyNullVariant, QDateTime, QThread, pyqtSignal, Qt, QRect, QSize, QFileInfo from PyQt4.QtGui import * #QAction, QIcon, QDockWidget, QGridLayout, QLineEdit, QTableWidget, QTableWidgetItem, QMessageBox, QApplication, QHBoxLayout, QVBoxLayout, QAbstractItemView, QListWidgetItem, QAbstractItemView, QFileDialog, QLabel, QPixmap, QIcon from PyQt4.QtNetwork import QHttp from qgis.gui import QgsRubberBand, QgsMessageBar from osgeo import gdal from osgeo import ogr from functools import partial # Initialize Qt resources from file resources.py import resources_rc # Import the code for the dialog from Tilgjengelighet_dialog import TilgjengelighetDialog from tabledialog import TableDialog from infowidgetdialog import infoWidgetDialog from AttributeForm import AttributeForm #Storing user made attribute information from SavedSearch import SavedSearch #Save search choises for later use #from xytools from xytools.field_chooser import FieldChooserDialog from xytools.exportlayerdialog import exportLayerDialog from xytools import utils #from OpenLayers plugin from openlayers_plugin.openlayers_layer import OpenlayersLayer from openlayers_plugin.weblayers.weblayer_registry import WebLayerTypeRegistry from openlayers_plugin.weblayers.weblayer_registry import WebLayerTypeRegistry from openlayers_plugin.weblayers.google_maps import OlGooglePhysicalLayer, OlGoogleStreetsLayer, OlGoogleHybridLayer, OlGoogleSatelliteLayer from openlayers_plugin.weblayers.osm import OlOpenStreetMapLayer, OlOSMHumanitarianDataModelLayer from openlayers_plugin.weblayers.osm_thunderforest import OlOpenCycleMapLayer, OlOCMLandscapeLayer, OlOCMPublicTransportLayer, OlOCMOutdoorstLayer, OlOCMTransportDarkLayer, OlOCMSpinalMapLayer, OlOCMPioneerLayer, OlOCMMobileAtlasLayer, OlOCMNeighbourhoodLayer from openlayers_plugin.weblayers.bing_maps import OlBingRoadLayer, OlBingAerialLayer, OlBingAerialLabelledLayer from openlayers_plugin.weblayers.apple_maps import OlAppleiPhotoMapLayer from openlayers_plugin.weblayers.osm_stamen import OlOSMStamenTonerLayer, OlOSMStamenTonerLiteLayer, OlOSMStamenWatercolorLayer, OlOSMStamenTerrainLayer from openlayers_plugin.weblayers.wikimedia_maps import WikimediaLabelledLayer, WikimediaUnLabelledLayer class Tilgjengelighet: """QGIS Plugin Implementation.""" def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface #Accsess to QGIS interface self.canvas = self.iface.mapCanvas() #Access to QGIS canvas self.settings = QSettings() #Access to QGIS settings # initialize locale locale = QSettings().value('locale/userLocale')[0:2] self.plugin_dir = os.path.dirname(__file__) #Plugin path self.locale_path = os.path.join( self.plugin_dir, 'i18n', 'Tilgjengelighet_{}.qm'.format(locale)) if os.path.exists(self.locale_path): self.translator = QTranslator() self.translator.load(self.locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Kartverket Tilgjengelighet') self.toolbar = self.iface.addToolBar(u'Tilgjengelighet') self.toolbar.setObjectName(u'Tilgjengelighet') #Settnings self.settings.setValue("/Qgis/dockAttributeTable", True) #Get attribute table at bottom of screen #self.settings.setValue("/Qgis/attributeTableBehaviour", "1") #Show Selected Features #Layer and attributes self.current_layer = None #The last searched layer self.current_attributes = None #The attributes for current search layer self.search_history = {} #history of all search self.rubberHighlight = None #Marking the object currently visulised in infoWidget self.unspecified = u"" #unspecified attributes self.infoWidget = None #Lists of feature types for tettested and friluft, key equeals name of tabs self.feature_type_tettsted = { u"HC-Parkering" : u'TettstedHCparkering', u"Inngang" : u'TettstedInngangBygg', u'Parkeringsområde' : u'TettstedParkeringsområde', u"Vei" : u'TettstedVei', u"Sittegruppe" : u"TettstedSittegruppe" } #use this to get featuretype based on current tab self.feature_type_friluft = { u'Baderampe' : u'FriluftBaderampe', u'Fiskeplass' : u'FriluftFiskeplassBrygge', u'Turvei' : u'FriluftTurvei', u'HC-Parkeringsplass' : u'FriluftHCparkering', u'Parkeringsområde' : u'FriluftParkeringsområde', u'Friluftsområder' : u'FriluftFriluftsområde', u'Gapahuk' : u'FriluftGapahuk', u'Grill-/Bålplass' : u'FriluftGrillBålplass', u'Sittegruppe' : u'FriluftSittegruppe', u'Toalett' : u'FriluftToalett', u'Skiløype' : u'FriluftSkiløype'} #Path to combobox values self.path_kommuner = self.plugin_dir + r"\kommuner_2018.txt" self.path_tilgjenglighetsvurdering = self.plugin_dir + r"\combobox_values\tilgjengvurdering.txt" self.path_more_less = self.plugin_dir + r'\combobox_values\mer_mindre.txt' self.path_boolean = self.plugin_dir + r'\combobox_values\boolean.txt' self.path_dortype = self.plugin_dir + r"\combobox_values\dortype.txt" self.path_dorapner = self.plugin_dir + r"\combobox_values\dorapner.txt" self.path_kontrast = self.plugin_dir + r"\combobox_values\kontrast.txt" self.path_handlist = self.plugin_dir + r"\combobox_values\handlist.txt" self.path_ledelinje = self.plugin_dir + r"\combobox_values\ledelinje.txt" self.path_byggfunksjon = self.plugin_dir + r"\combobox_values\tettstedInngangByggningstype.txt" self.path_gatetype = self.plugin_dir + r'\combobox_values\tettstedVeiGatetype.txt' self.path_dekke_tettsted = self.plugin_dir + r"\combobox_values\tettstedDekke.txt" self.path_dekketilstand = self.plugin_dir + r"\combobox_values\dekkeTilstand.txt" self.path_dekke_friluft = self.plugin_dir + r'\combobox_values\friluftDekke.txt' self.path_spesialFotrutetype = self.plugin_dir + r'\combobox_values\spesialFotrutetype.txt' self.path_belysning = self.plugin_dir + r'\combobox_values\belysning.txt' self.path_frihoyde = self.plugin_dir + r'\combobox_values\frihoyde.txt' self.path_plasstype = self.plugin_dir + r'\combobox_values\friluftPlasstype.txt' self.path_byggtype = self.plugin_dir + r'\combobox_values\byggtype.txt' #Open Layers, background layers self._olLayerTypeRegistry = WebLayerTypeRegistry(self) self._ol_layer = None self._ol_layer_id = None #self._ol_layers = {} # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('Tilgjengelighet', message) def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ # Create the dialog (after translation) and keep reference self.dlg = TilgjengelighetDialog() #main dialig icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu( self.menu, action) self.iface.addPluginToWebMenu( self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/Tilgjengelighet/icon.png' self.add_action( icon_path, text=self.tr(u'Kartverkets Tilgjengelighets database'), callback=self.run, parent=self.iface.mainWindow()) ### main window ### #Set Icons main tab self.dlg.tabWidget_main.setTabIcon(0, QIcon(":/plugins/Tilgjengelighet/icons/friluft.png")) self.dlg.tabWidget_main.setTabIcon(1, QIcon(":/plugins/Tilgjengelighet/icons/tettsted.png")) #change search name based on tab self.dlg.tabWidget_main.currentChanged.connect(self.change_search_name) #change search name based on tab self.dlg.tabWidget_friluft.currentChanged.connect(self.change_search_name) self.dlg.tabWidget_tettsted.currentChanged.connect(self.change_search_name) #Connect pushbuttons self.dlg.pushButton_filtrer.clicked.connect(self.filtrer) #Connect pushbytton filtrer action self.dlg.pushButton_reset.clicked.connect(self.reset) #resett all choses made by user ### table window ### ## NB: Table window changed to attribute table # self.dock = TableDialog(self.iface.mainWindow()) # self.dock.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) #select entire row in table # self.dock.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) #Making table unediteble # self.iface.addDockWidget( Qt.BottomDockWidgetArea , self.dock ) #adding seartch result Widget # self.dock.close() #Start pløugin without this dialog ### Export window ### self.export_layer = exportLayerDialog() self.export_layer.pushButton_bla.clicked.connect(self.OpenBrowser) self.export_layer.pushButton_lagre.clicked.connect(self.lagre_lag) self.export_layer.pushButton_lagre.clicked.connect(lambda x: self.export_layer.close()) #close winwo when you have saved layer self.export_layer.pushButton_avbryt.clicked.connect(lambda x: self.export_layer.close()) ### Fill gui ### self.fill_fylker() #fill fylker combobox self.fylke_valgt() #Filling up kommune combobox #set combobox functions self.dlg.comboBox_fylker.currentIndexChanged.connect(self.fylke_valgt) #Filling cityes from county self.dlg.comboBox_fylker.currentIndexChanged.connect(self.change_search_name) #setting search name based on fylke self.dlg.comboBox_kommuner.currentIndexChanged.connect(self.change_search_name) #setting search name based on komune #Assign fylker and kommuner to AttributeForm self.fylker = AttributeForm("fylker", self.dlg.label_fylke) self.fylker.setComboBox(self.dlg.comboBox_fylker) self.kommuner = AttributeForm("komune", self.dlg.label_kommune) self.kommuner.setComboBox(self.dlg.comboBox_kommuner) #Create attributes object tettsted self.assign_combobox_inngang() self.assign_combobox_vei() self.assign_combobox_hc_parkering() self.assign_combobox_parkeringsomraade() self.assign_combobox_sittegruppe_tettsted() #Create attributes object friluft (Needs futher methods for filling rest of friluft) self.assign_combobox_baderampe() self.assign_combobox_fiskeplass() self.assign_combobox_turvei() self.assign_combobox_hc_parkering_friluft() self.assign_combobox_parkeringsomraade_friluft() self.assign_combobox_friluftomrader() self.assign_combobox_gapahuk() self.assign_combobox_grillbalplass() self.assign_combobox_sittegruppe() self.assign_combobox_toalett() self.assign_combobox_ski() #Dictionarys for all attributes in different object type. Key equals name of tab self.attributes_tettsted = { u"HC-Parkering" : self.attributes_hcparkering_tettsted, u"Inngang" : self.attributes_inngang, u'Parkeringsområde' : self.attributes_pomrade_tettsted, u"Vei" : self.attributes_vei, u"Sittegruppe" : self.attributes_sittegruppe_tettsted} self.attributes_friluft = { u"Baderampe" : self.attributes_baderampe, u"Fiskeplass" : self.attributes_fiskeplass, u"Turvei" : self.attributes_turvei, u"HC-Parkeringsplass" : self.attributes_hcparkering_friluft, u"Parkeringsområde" : self.attributes_pomrade_friluft, u"Friluftsområder" : self.attributes_friluftsomrader, u"Gapahuk" : self.attributes_gapahuk, u"Grill-/Bålplass" : self.attributes_balplass, u"Sittegruppe" : self.attributes_sittegruppe, u"Toalett" : self.attributes_toalett, u"Skiløype" : self.attributes_ski } self.change_search_name() #Initiate a search name self.openLayer_background_init() #Activate open layers def create_infoWidget(self): ### info window ### self.infoWidget = infoWidgetDialog(self.iface.mainWindow()) self.iface.addDockWidget( Qt.LeftDockWidgetArea , self.infoWidget) self.infoWidget.setAllowedAreas(Qt.LeftDockWidgetArea) self.infoWidget.setFloating(False) self.infoWidget.setFeatures(QDockWidget.DockWidgetClosable | QDockWidget.DockWidgetMovable) #self.infoWidget.pushButton_filtrer.clicked.connect(lambda x: self.dlg.show()) #open main window self.infoWidget.pushButton_filtrer.clicked.connect(self.get_previus_search_activeLayer) #setting main window to match search for active layer self.infoWidget.pushButton_next.clicked.connect(self.infoWidget_next) #itterate the selected objekts self.infoWidget.pushButton_prev.clicked.connect(self.infoWidget_prev) self.infoWidget.pushButton_tabell.clicked.connect(self.show_tabell) #open tableWiddget #TEST #pixmap_red = QPixmap(self.plugin_dir + "\symboler\rullestol-red.png") #self.infoWidget.pushButton_filtrer.clicked.connect(lambda: self.infoWidget.label_icon.setPixmap(pixmap_red)) # Set tools an icons self.selectPolygon = QAction(QIcon(":/plugins/Tilgjengelighet/icons/Select_polygon.gif"), QCoreApplication.translate("MyPlugin", "Polygon"), self.iface.mainWindow()) #Change therese icons self.selectPoint = QAction(QIcon(":/plugins/Tilgjengelighet/icons/Select_point_1.gif"), QCoreApplication.translate("MyPlugin", u"Punkt/Frihånd"), self.iface.mainWindow()) #Change therese icons self.selectPolygon.triggered.connect(lambda x: self.iface.actionSelectPolygon().trigger()) #select objects by polygon self.selectPoint.triggered.connect(lambda x: self.iface.actionSelectFreehand().trigger()) #select objects by freehand self.infoWidget.toolButton_velgikart.addAction(self.selectPolygon) self.infoWidget.toolButton_velgikart.addAction(self.selectPoint) self.exportExcel = QAction(QIcon(":/plugins/Tilgjengelighet/icons/black-ms-excel-16.png"), QCoreApplication.translate("MyPlugin", "Excel"), self.iface.mainWindow()) #Change therese icons self.exportImage = QAction(QIcon(":/plugins/Tilgjengelighet/icons/Export_map.gif"), QCoreApplication.translate("MyPlugin", "Bilde"), self.iface.mainWindow()) #Change therese icons self.exportExcel.triggered.connect(self.excelSave) #export tp excel self.exportImage.triggered.connect(self.imageSave) #ecport image self.infoWidget.toolButton_eksporter.addAction(self.exportExcel) self.infoWidget.toolButton_eksporter.addAction(self.exportImage) #self.addOLmenu() self.infoWidget.toolButton_map.setMenu(self._olMenu) ############################# Assign widget to attributeform and fill comboboxes ################################# def assign_combobox_inngang(self): """Assigning a AttributeForm object to each option in inngang""" avstandHC = AttributeForm("avstandHC", "app:avstandHC", comboBox=self.dlg.comboBox_avstand_hc, lineEdit=self.dlg.lineEdit_avstand_hc) ank_stigning = AttributeForm("stigningAdkomstvei", "app:stigningAdkomstvei", comboBox=self.dlg.comboBox_ank_stigning, lineEdit=self.dlg.lineEdit_ank_stigning) byggningstype = AttributeForm("byggningsfunksjon", "app:byggningsfunksjon", comboBox=self.dlg.comboBox_byggningstype) rampe = AttributeForm("rampe", "app:rampe", comboBox=self.dlg.comboBox_rampe) trapp_inngang = AttributeForm("trapp", "app:trapp", comboBox=self.dlg.comboBox_inngang_trapp) trapp_kontrast_inngang = AttributeForm("trappKontrast", "app:trapp/app:Trapp/app:trappKontrast", self.dlg.comboBox_inngang_konstrast_trapp, label=self.dlg.label_tettsted_inngang_trapp_kontrast) dortype = AttributeForm(u"dørtype", u"app:dørtype", comboBox=self.dlg.comboBox_dortype) dorapner = AttributeForm(u"døråpner", u"app:døråpner", comboBox=self.dlg.comboBox_dorapner) man_hoyde = AttributeForm(u"manøverknappHøyde", u"app:manøverknappHøyde", comboBox=self.dlg.comboBox_man_hoyde, lineEdit=self.dlg.lineEdit_man_hoyde) dorbredde = AttributeForm("breddeInngang", "app:breddeInngang", comboBox=self.dlg.comboBox_dorbredde, lineEdit=self.dlg.lineEdit_dorbredde) terskel = AttributeForm(u"terskelHøyde", u"app:terskelHøyde", comboBox=self.dlg.comboBox_terskel, lineEdit=self.dlg.lineEdit_terskel) kontrast = AttributeForm("kontrastInngang", "app:kontrastInngang", comboBox=self.dlg.comboBox_kontrast) rampe_stigning = AttributeForm("rampeStigning", "app:rampe/app:Rampe/app:rampeStigning", comboBox=self.dlg.comboBox_rmp_stigning, lineEdit=self.dlg.lineEdit_rmp_stigning, label=self.dlg.label_rmp_stigning) rampe_bredde = AttributeForm("rampeBredde", "app:rampe/app:Rampe/app:rampeBredde", comboBox=self.dlg.comboBox_rmp_bredde, lineEdit=self.dlg.lineEdit_rmp_bredde, label=self.dlg.label_rmp_bredde) handlist = AttributeForm(u"håndlist", u"app:rampe/app:Rampe/app:håndlist", comboBox=self.dlg.comboBox_handliste, label=self.dlg.label_handliste) handlist1 = AttributeForm(u"håndlistHøydeØvre", u"app:rampe/app:Rampe/app:håndlistHøydeØvre", comboBox=self.dlg.comboBox_hand1, lineEdit=self.dlg.lineEdit_hand1, label=self.dlg.label_hand1) handlist2 = AttributeForm(u"håndlistHøydeNedre", u"app:rampe/app:Rampe/app:håndlistHøydeNedre", comboBox=self.dlg.comboBox_hand2, lineEdit=self.dlg.lineEdit_hand2, label=self.dlg.label_hand2) rmp_tilgjengelig = AttributeForm("rampeTilgjengelig", "app:rampe/app:Rampe/app:rampeTilgjengelig", comboBox=self.dlg.comboBox_rmp_tilgjengelig, label=self.dlg.label_rmp_tilgjengelig) manuellRullestol = AttributeForm("tilgjengvurderingRulleAuto", "app:tilgjengvurderingRulleAuto", comboBox=self.dlg.comboBox_manuell_rullestol) elektriskRullestol = AttributeForm("tilgjengvurderingElRull", "app:tilgjengvurderingElRull", comboBox=self.dlg.comboBox_el_rullestol) synshemmet = AttributeForm("tilgjengvurderingSyn", "app:tilgjengvurderingSyn", comboBox=self.dlg.comboBox_syn) rampelengde = AttributeForm("rampeLengde", "app:rampe/app:Rampe/app:rampeLengde", comboBox=self.dlg.comboBox_rampe_lengde_inngang, lineEdit=self.dlg.lineEdit_rampe_lengde_inngang, label=self.dlg.label_rampe_lengde_inngang) self.attributes_inngang = [avstandHC, ank_stigning, byggningstype, rampe, trapp_inngang, trapp_kontrast_inngang, dortype, dorapner, man_hoyde, dorbredde, terskel, kontrast, rampe_stigning, rampe_bredde, handlist, handlist1, handlist2, rmp_tilgjengelig, manuellRullestol, elektriskRullestol, synshemmet, rampelengde] self.attributes_inngang_gui = [byggningstype, dortype, dorapner, kontrast, handlist, rmp_tilgjengelig, manuellRullestol, elektriskRullestol, synshemmet] self.attributes_inngang_mer_mindre = [avstandHC, ank_stigning, man_hoyde, dorbredde, terskel, rampe_stigning, rampe_bredde, handlist1, handlist2, rampelengde] self.attributes_rampe = [rampe_stigning, rampe_bredde, handlist, handlist1, handlist2, rampelengde, rmp_tilgjengelig] #fill combobox path = ":/plugins/Tilgjengelighet/" #Mey not need this for attributt in self.attributes_inngang_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(rampe.getComboBox(), self.path_boolean) self.fill_combobox(trapp_inngang.getComboBox(), self.path_boolean) self.fill_combobox(trapp_kontrast_inngang.getComboBox(), self.path_kontrast) self.fill_combobox(byggningstype.getComboBox(), self.path_byggfunksjon) self.fill_combobox(dortype.getComboBox(), self.path_dortype) self.fill_combobox(dorapner.getComboBox(), self.path_dorapner) self.fill_combobox(kontrast.getComboBox(), self.path_kontrast) self.fill_combobox(handlist.getComboBox(), self.path_handlist) self.fill_combobox(rmp_tilgjengelig.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(manuellRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(elektriskRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(synshemmet.getComboBox(), self.path_tilgjenglighetsvurdering) #Set what to be hidden in form and conditions for showing parts self.hide_show_gui(self.attributes_rampe, self.dlg.comboBox_rampe.currentText() == u"Ja", [self.dlg.label_rampe_boxs, self.dlg.line_inngang_rampe, self.dlg.line]) self.dlg.comboBox_rampe.currentIndexChanged.connect(lambda: self.hide_show_gui(self.attributes_rampe, self.dlg.comboBox_rampe.currentText() == u"Ja", [self.dlg.label_rampe_boxs, self.dlg.line_inngang_rampe, self.dlg.line])) self.hide_show_gui([trapp_kontrast_inngang], self.dlg.comboBox_inngang_trapp.currentText() == "Ja") self.dlg.comboBox_inngang_trapp.currentIndexChanged.connect(lambda: self.hide_show_gui([trapp_kontrast_inngang], self.dlg.comboBox_inngang_trapp.currentText() == "Ja")) #self.dlg.comboBox_rampe.currentIndexChanged.connect(self.hide_show_rampe) def assign_combobox_vei(self): """Assigning a AttributeForm object to each option in vei""" gatetype = AttributeForm("gatetype", "app:gatetype", self.dlg.comboBox_gatetype) nedsenkning1 = AttributeForm("nedsenk1", "app:nedsenk1", self.dlg.comboBox_nedsenkning1, self.dlg.lineEdit_nedsenkning1, label=self.dlg.label_nedsenkning1) nedsenkning2 = AttributeForm("nedsenk2", "app:nedsenk2", self.dlg.comboBox_nedsenkning2, self.dlg.lineEdit_nedsenkning2, label=self.dlg.label_nedsenkning2) trapp_vei = AttributeForm("trapp", "app:trapp", self.dlg.comboBox_tettsted_vei_trapp) trapp_kontrast = AttributeForm("trappKontrast", "app:trapp/app:Trapp/app:trappKontrast", self.dlg.comboBox_tettsted_vei_konstrast_trapp, label=self.dlg.label_vei_trapp_kontrast) dekke_vei_tettsted = AttributeForm("dekke", "app:dekke", self.dlg.comboBox_dekke_vei_tettsted) dekkeTilstand_vei_tettsted = AttributeForm("dekkeTilstand", "app:dekkeTilstand", self.dlg.comboBox_dekkeTilstand_vei_tettsted) bredde = AttributeForm("bredde", "app:bredde", self.dlg.comboBox_bredde, self.dlg.lineEdit_bredde) stigning = AttributeForm("stigning", "app:stigning", self.dlg.comboBox_stigning, self.dlg.lineEdit_stigning) tverfall = AttributeForm("tverrfall", "app:tverrfall", self.dlg.comboBox_tverfall, self.dlg.lineEdit_tverfall) ledelinje = AttributeForm("ledelinje", "app:ledelinje", self.dlg.comboBox_vei_ledelinje) ledelinjeKontrast = AttributeForm("ledelinjeKontrast", "app:ledelinjeKontrast", self.dlg.comboBox_vei_ledelinjeKontrast, label=self.dlg.label_vei_ledelinjeKontrast) lyssignal = AttributeForm("lyssignal", "app:lyssignal", self.dlg.comboBox_lyssignal) lydsignal = AttributeForm("lydsignal", "app:lydsignal", self.dlg.comboBox_lydsignal) moteplass = AttributeForm(u"møteplass", u"app:møteplass", self.dlg.comboBox_moteplass) manuell_rullestol_vei = AttributeForm("tilgjengvurderingRulleAuto", "app:tilgjengvurderingRulleAuto", self.dlg.comboBox_manuell_rullestol_vei) electrisk_rullestol_vei = AttributeForm("tilgjengvurderingElRull", "app:tilgjengvurderingElRull", self.dlg.comboBox_electrisk_rullestol_vei) syn_vei = AttributeForm("tilgjengvurderingSyn", "app:tilgjengvurderingSyn", self.dlg.comboBox_syn_vei) self.attributes_vei = [gatetype, nedsenkning1, nedsenkning2, trapp_vei, trapp_kontrast, dekke_vei_tettsted, dekkeTilstand_vei_tettsted, bredde, stigning, tverfall, ledelinje, ledelinjeKontrast, manuell_rullestol_vei, electrisk_rullestol_vei, syn_vei, lyssignal, lydsignal, moteplass] attributes_vei_gui = [gatetype, dekke_vei_tettsted, dekkeTilstand_vei_tettsted, ledelinje, ledelinjeKontrast, manuell_rullestol_vei, electrisk_rullestol_vei, syn_vei] attributes_vei_mer_mindre = [nedsenkning1,nedsenkning2,bredde,stigning,tverfall] attributes_nedsenkning = [nedsenkning1, nedsenkning2] #fill combobox for attributt in attributes_vei_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(gatetype.getComboBox(), self.path_gatetype) self.fill_combobox(dekke_vei_tettsted.getComboBox(), self.path_dekke_tettsted) self.fill_combobox(dekkeTilstand_vei_tettsted.getComboBox(), self.path_dekketilstand) self.fill_combobox(ledelinje.getComboBox(), self.path_ledelinje) self.fill_combobox(ledelinjeKontrast.getComboBox(), self.path_kontrast) self.fill_combobox(lyssignal.getComboBox(), self.path_boolean) self.fill_combobox(lydsignal.getComboBox(), self.path_boolean) self.fill_combobox(moteplass.getComboBox(), self.path_boolean) self.fill_combobox(trapp_vei.getComboBox(), self.path_boolean) self.fill_combobox(trapp_kontrast.getComboBox(), self.path_kontrast) self.fill_combobox(manuell_rullestol_vei.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(electrisk_rullestol_vei.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(syn_vei.getComboBox(), self.path_tilgjenglighetsvurdering) #Set what to be hidden in form and conditions for showing parts self.hide_show_gui(attributes_nedsenkning, self.dlg.comboBox_gatetype.currentText() == "Gangfelt") self.dlg.comboBox_gatetype.currentIndexChanged.connect(lambda: self.hide_show_gui(attributes_nedsenkning, self.dlg.comboBox_gatetype.currentText() == "Gangfelt")) self.hide_show_gui([dekkeTilstand_vei_tettsted], dekkeTilstand_vei_tettsted.getComboBox().currentText() != self.unspecified, [self.dlg.label_vei_dekkeTilstand]) self.dlg.comboBox_dekke_vei_tettsted.currentIndexChanged.connect(lambda: self.hide_show_gui([dekkeTilstand_vei_tettsted], self.dlg.comboBox_dekke_vei_tettsted.currentText() != self.unspecified, [self.dlg.label_vei_dekkeTilstand])) self.hide_show_gui([ledelinjeKontrast], (self.dlg.comboBox_vei_ledelinje.currentText() != self.unspecified and self.dlg.comboBox_vei_ledelinje.currentText() != "Ingen")) self.dlg.comboBox_vei_ledelinje.currentIndexChanged.connect(lambda: self.hide_show_gui([ledelinjeKontrast], (self.dlg.comboBox_vei_ledelinje.currentText() != self.unspecified and self.dlg.comboBox_vei_ledelinje.currentText() != "Ingen"))) self.hide_show_gui([trapp_kontrast], trapp_vei.getComboBox().currentText() == "Ja") trapp_vei.getComboBox().currentIndexChanged.connect(lambda: self.hide_show_gui([trapp_kontrast], trapp_vei.getComboBox().currentText() == "Ja")) def assign_combobox_hc_parkering(self): """Assigning a AttributeForm object to each option in hc parkering""" avstandServicebygg = AttributeForm("avstandServicebygg", "app:avstandServicebygg", self.dlg.comboBox_avstandServicebygg, self.dlg.lineEdit_avstandServicebygg) overbygg = AttributeForm("overbygg", "app:overbygg", self.dlg.comboBox_overbygg) skiltet = AttributeForm("skiltet", "app:skiltet", self.dlg.comboBox_skiltet) merket = AttributeForm("merket", "app:merket", self.dlg.comboBox_merket) gatelangsparkering = AttributeForm("gatelangsParkering", "app:gatelangsParkering", self.dlg.comboBox_gatelangsparkering) tryggOvergang = AttributeForm("tryggOvergang", "app:tryggOvergang", self.dlg.comboBox_tryggOvergang) bredde_hcp_merke = AttributeForm("bredde", "app:bredde", self.dlg.comboBox_bredde_hcp_merke, self.dlg.lineEdit_bredde_hcp_merke, label=self.dlg.label_bredde_hcp_merke) lengde_hcp_merke = AttributeForm("lengde", "app:lengde", self.dlg.comboBox_lengde_hcp_merke, self.dlg.lineEdit_lengde_hcp_merke, label=self.dlg.label_lengde_hcp_merke) manuell_rullestol_hcparkering = AttributeForm("tilgjengvurderingRulleAuto", "app:tilgjengvurderingRulleAuto", self.dlg.comboBox_manuell_rullestol_hcparkering) self.attributes_hcparkering_tettsted = [avstandServicebygg, overbygg, skiltet, merket, bredde_hcp_merke, lengde_hcp_merke, gatelangsparkering, manuell_rullestol_hcparkering, tryggOvergang] attributes_hcparkering_gui = [manuell_rullestol_hcparkering] attributes_hcparkering_mer_mindre = [avstandServicebygg, bredde_hcp_merke, lengde_hcp_merke] #fill combobox for attributt in attributes_hcparkering_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(overbygg.getComboBox(), self.path_boolean) self.fill_combobox(skiltet.getComboBox(), self.path_boolean) self.fill_combobox(merket.getComboBox(), self.path_boolean) self.fill_combobox(gatelangsparkering.getComboBox(), self.path_boolean) self.fill_combobox(tryggOvergang.getComboBox(), self.path_boolean) tryggOvergang self.fill_combobox(manuell_rullestol_hcparkering.getComboBox(), self.path_tilgjenglighetsvurdering) #Set what to be hidden in form and conditions for showing parts self.hide_show_gui([bredde_hcp_merke, lengde_hcp_merke], self.dlg.comboBox_merket.currentText() == "Ja") self.dlg.comboBox_merket.currentIndexChanged.connect(lambda: self.hide_show_gui([bredde_hcp_merke, lengde_hcp_merke], self.dlg.comboBox_merket.currentText() == "Ja")) def assign_combobox_parkeringsomraade(self): """Assigning a AttributeForm object to each option in parkeringsområde""" overbygg_pomrade = AttributeForm("overbygg", "app:overbygg", self.dlg.comboBox_overbygg_pomrade) kapasitetPersonbiler = AttributeForm("kapasitetPersonbiler", "app:kapasitetPersonbiler", self.dlg.comboBox_kapasitetPersonbiler, self.dlg.lineEdit_kapasitetPersonbiler) kapasitetUU = AttributeForm("antallUU", "app:antallUU", self.dlg.comboBox_kapasitetUU, self.dlg.lineEdit_kapasitetUU) dekke_pomrade = AttributeForm("dekke", "app:dekke", self.dlg.comboBox_dekke_pomrade) dekkeTilstand_pomrade = AttributeForm("dekkeTilstand", "app:dekkeTilstand", self.dlg.comboBox_dekkeTilstand_pomrade, label=self.dlg.label_dekkeTilstand_pomrade) manuell_rullestol_pomrade = AttributeForm("tilgjengvurderingRulleAuto", "app:tilgjengvurderingRulleAuto", self.dlg.comboBox_manuell_rullestol_pomrade) self.attributes_pomrade_tettsted = [overbygg_pomrade, kapasitetPersonbiler, kapasitetUU, dekke_pomrade, dekkeTilstand_pomrade, manuell_rullestol_pomrade] attributes_pomrade_gui = [dekke_pomrade, dekkeTilstand_pomrade, manuell_rullestol_pomrade] attributes_pomrade_mer_mindre = [kapasitetPersonbiler, kapasitetUU] #fill combobox for attributt in attributes_pomrade_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(overbygg_pomrade.getComboBox(), self.path_boolean) self.fill_combobox(dekke_pomrade.getComboBox(), self.path_dekke_tettsted) self.fill_combobox(dekkeTilstand_pomrade.getComboBox(), self.path_dekketilstand) self.fill_combobox(manuell_rullestol_pomrade.getComboBox(), self.path_tilgjenglighetsvurdering) #Hide gui self.hide_show_gui([dekkeTilstand_pomrade], self.dlg.comboBox_dekke_pomrade.currentText() != self.unspecified) self.dlg.comboBox_dekke_pomrade.currentIndexChanged.connect(lambda: self.hide_show_gui([dekkeTilstand_pomrade], self.dlg.comboBox_dekke_pomrade.currentText() != self.unspecified)) def assign_combobox_sittegruppe_tettsted(self): """Assigning an AttributeForm object to each option in Sittegruppe""" dekke = AttributeForm("dekke", "app:dekke", self.dlg.comboBox_sittegruppe_dekke_tettsted) dekkeTilstand = AttributeForm("dekkeTilstand", "app:dekkeTilstand", self.dlg.comboBox_sittegruppe_dekkeTilstand_tettsted, label=self.dlg.label_sittegruppe_dekkeTilstand_tettsted) helning = AttributeForm("helning", "app:helning", self.dlg.comboBox_sittegruppe_helning_tettsted, self.dlg.lineEdit_sittegruppe_helning_tettsted) bordhoyde = AttributeForm(u"høydeBord", u"app:høydeBord", self.dlg.comboBox_sittegruppe_hoyde_tettsted, self.dlg.lineEdit_hoyde_sittegruppe_tettsted) bordutsikt = AttributeForm("utstikkBord", "app:utstikkBord", self.dlg.comboBox_sittegruppe_utsikt_tettsted, self.dlg.lineEdit_sittegruppe_utsikt_tettsted) manuellRullestol = AttributeForm("tilgjengvurderingRulleAuto", "app:tilgjengvurderingRulleAuto", self.dlg.comboBox_sittegruppe_manuell_rullestol_tettsted) #Nye attributter 2019 benkhoyde = AttributeForm("høydeBenk", "app:høydeBenk", self.dlg.comboBox_sittegruppe_hoyde_benk_tettsted, self.dlg.lineEdit_sittegruppe_hoyde_benk_tettsted) armlene = AttributeForm("armlene", "app:armlene", self.dlg.comboBox_sittegruppe_armlene_tettsted) #Boolean ryggstotte = AttributeForm(u"ryggstøtte", u"app:ryggstøtte", self.dlg.comboBox_sittegruppe_ryggstotte_tettsted) #Boolean adkomstkant = AttributeForm("adkomstKant", "app:adkomstKant", self.dlg.comboBox_sittegruppe_adkomst_kant_tettsted, self.dlg.lineEdit_sittegruppe_adkomst_kant_tettsted) #float adkomst_tilgjenglig = AttributeForm("adkomstTilgjengelig", "app:adkomstTilgjengelig", self.dlg.comboBox_sittegruppe_adkomst_tilgjengleig_tettsted) #Boolean self.attributes_sittegruppe_tettsted = [dekke, dekkeTilstand, helning, bordhoyde, bordutsikt, manuellRullestol, benkhoyde, armlene, ryggstotte, adkomstkant, adkomst_tilgjenglig] attributes_mer_mindre = [helning, bordhoyde, bordutsikt, benkhoyde, adkomstkant] #fill combobox for attributt in attributes_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(dekke.getComboBox(), self.path_dekke_friluft) self.fill_combobox(dekkeTilstand.getComboBox(), self.path_dekketilstand) self.fill_combobox(manuellRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(armlene.getComboBox(), self.path_boolean) self.fill_combobox(ryggstotte.getComboBox(), self.path_boolean) self.fill_combobox(adkomst_tilgjenglig.getComboBox(), self.path_boolean) #Hide GUI self.hide_show_gui([dekkeTilstand], self.dlg.comboBox_sittegruppe_dekke_tettsted.currentText() != self.unspecified) self.dlg.comboBox_sittegruppe_dekke_tettsted.currentIndexChanged.connect(lambda: self.hide_show_gui([dekkeTilstand], self.dlg.comboBox_sittegruppe_dekke_tettsted.currentText() != self.unspecified)) def assign_combobox_baderampe(self): """Assigning a AttributeForm object to each option in Baderampe""" rampeBredde = AttributeForm(u"rampeBredde", u"app:rampe/app:Rampe/app:rampeBredde", self.dlg.comboBox_baderampe_rampeBredde, self.dlg.lineEdit_baderampe_rampeBredde) rampeStigning = AttributeForm(u"rampeStigning", u"app:rampe/app:Rampe/app:rampeStigning", self.dlg.comboBox_baderampe_rampeStigning, self.dlg.lineEdit_baderampe_rampeStigning) handlist = AttributeForm(u"håndlist", u"app:rampe/app:Rampe/app:håndlist", self.dlg.comboBox_baderampe_handliste) handlistHoyde1 = AttributeForm(u"håndlistHøydeØvre", u"app:rampe/app:Rampe/app:håndlistHøydeØvre", self.dlg.comboBox_baderampe_handlistHoyde1, self.dlg.lineEdit_baderampe_handlistHoyde1) handlistHoyde2 = AttributeForm(u"håndlistHøydeNedre", u"app:rampe/app:Rampe/app:håndlistHøydeNedre", self.dlg.comboBox_baderampe_handlistHoyde2, self.dlg.lineEdit_baderampe_handlistHoyde2) rampeLengde = AttributeForm(u"rampeLengde", u"app:rampe/app:Rampe/app:rampeLengde", self.dlg.comboBox_baderampe_lengde, self.dlg.lineEdit_baderampe_lengde, label=self.dlg.label_baderampe_lengde) rampeTilgjengelig = AttributeForm(u"rampeTilgjengelig", u"app:rampe/app:Rampe/app:rampeTilgjengelig", self.dlg.comboBox_baderampe_rampeTilgjengelig) tilgjengvurderingRullestol = AttributeForm(u"tilgjengvurderingRulleAuto", u"app:tilgjengvurderingRulleAuto", self.dlg.comboBox_baderampe_tilgjengvurderingRullestol) tilgjengvurderingSyn = AttributeForm(u"tilgjengvurderingSyn", u"app:tilgjengvurderingSyn", self.dlg.comboBox_baderampe_tilgjengvurderingSyn) self.attributes_baderampe = [rampeBredde, rampeStigning, handlist, handlistHoyde1, handlistHoyde2, rampeLengde, rampeTilgjengelig, tilgjengvurderingRullestol, tilgjengvurderingSyn] attributes_mer_mindre = [rampeBredde, rampeStigning, handlistHoyde1, handlistHoyde2, rampeLengde] #Fill combobox for attributt in attributes_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(handlist.getComboBox(), self.path_handlist) self.fill_combobox(rampeTilgjengelig.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(tilgjengvurderingRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(tilgjengvurderingSyn.getComboBox(), self.path_tilgjenglighetsvurdering) def assign_combobox_fiskeplass(self): """Assigning a AttributeForm object to each option in Baderampe""" rampe = AttributeForm(u"rampe", u"app:rampe", self.dlg.comboBox_fiskeplass_rampe, label=self.dlg.label_fiskeplass_rampe) dekke = AttributeForm(u"dekke", u"app:dekke", self.dlg.comboBox_fiskeplass_dekke) plankeavstand = AttributeForm(u"plankeavstand", u"app:plankeavstand", self.dlg.comboBox_fiskeplass_plankeavstand, self.dlg.lineEdit_fiskeplass_plankeavstand, label=self.dlg.label_fiskeplass_plankeavstand) dekkeTilstand = AttributeForm(u"dekkeTilstand", u"app:dekkeTilstand", self.dlg.comboBox_fiskeplass_dekke_tilstand, label=self.dlg.label_fiskeplass_dekke_tilstand) diameter = AttributeForm(u"diameter", u"app:diameter", self.dlg.comboBox_fiskeplass_snusirkel, self.dlg.lineEdit_fiskeplass_snusirkel) rekkverk = AttributeForm(u"rekkverk", u"app:rekkverk", self.dlg.comboBox_fiskeplass_rekkverk) stoppkant = AttributeForm(u"stoppkant", u"app:stoppkant", self.dlg.comboBox_fiskeplass_stoppkant) stoppkantHoyde = AttributeForm(u"stoppkantHøyde", u"app:stoppkantHøyde", self.dlg.comboBox_fiskeplass_stoppkant_hoyde, self.dlg.lineEdit_fiskeplass_stoppkant_hoyde, label=self.dlg.label_fiskeplass_stoppkant_hoyde) rampeBredde = AttributeForm(u"rampeBredde", u"app:rampe/app:Rampe/app:rampeBredde", self.dlg.comboBox_fiskeplass_rampe_bredde, self.dlg.lineEdit_fiskeplass_rampe_bredde, label=self.dlg.label_fiskeplass_rampe_bredde) rampeStigning = AttributeForm(u"rampeStigning", u"app:rampe/app:Rampe/app:rampeStigning", self.dlg.comboBox_fiskeplass_rampe_stigning, self.dlg.lineEdit_fiskeplass_rampe_stigning, label=self.dlg.label_fiskeplass_rampe_stigning) handlist = AttributeForm(u"håndlist", u"app:rampe/app:Rampe/app:håndlist", self.dlg.comboBox_fiskeplass_handliste, label=self.dlg.label_fiskeplass_handliste) handlistHoyde1 = AttributeForm(u"håndlistHøyde1", u"app:rampe/app:Rampe/app:håndlistHøyde1", self.dlg.comboBox_fiskeplass_handlist1, self.dlg.lineEdit_fiskeplass_handlist1, label=self.dlg.label_fiskeplass_handlist1) handlistHoyde2 = AttributeForm(u"håndlistHøyde2", u"app:rampe/app:Rampe/app:håndlistHøyde2", self.dlg.comboBox_fiskeplass_handlist2, self.dlg.lineEdit_fiskeplass_handlist2, label=self.dlg.label_fiskeplass_handlist2) rampeLengde = AttributeForm(u"rampeLengde", u"app:rampe/app:Rampe/app:rampeLengde", self.dlg.comboBox_fiskeplass_lengde, self.dlg.lineEdit_fiskeplass_lengde, label=self.dlg.label_fiskeplass_lengde) rampeTilgjengelig = AttributeForm(u"rampeTilgjengelig", u"app:rampe/app:Rampe/app:rampeTilgjengelig", self.dlg.comboBox_fiskeplass_rampe_tilgjengelig, label=self.dlg.label_fiskeplass_rampe_tilgjengelig) tilgjengvurderingRullestol = AttributeForm(u"tilgjengvurderingRulleAuto", u"app:tilgjengvurderingRulleAuto", self.dlg.comboBox_fiskeplass_manuell_rullestol) tilgjengvurderingElRullestol = AttributeForm(u"tilgjengvurderingElRullestol", u"app:tilgjengvurderingElRullestol", self.dlg.comboBox_fiskeplass_el_rullestol) tilgjengvurderingSyn = AttributeForm(u"tilgjengvurderingSyn", u"app:tilgjengvurderingSyn", self.dlg.comboBox_fiskeplass_syn) self.attributes_fiskeplass = [rampe, dekke, plankeavstand, dekkeTilstand, diameter, rekkverk, stoppkant, stoppkantHoyde, rampeBredde, rampeStigning, handlist, handlistHoyde1, handlistHoyde2, rampeLengde, rampeTilgjengelig, tilgjengvurderingRullestol, tilgjengvurderingElRullestol, tilgjengvurderingSyn] attributes_mer_mindre = [plankeavstand, diameter, stoppkantHoyde, rampeBredde, rampeStigning, handlistHoyde1, handlistHoyde2, rampeLengde] attributes_rampe = [rampeBredde, rampeStigning, handlist, handlistHoyde1, handlistHoyde2, rampeLengde, rampeTilgjengelig] #Fill combobox for attributt in attributes_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(rampe.getComboBox(), self.path_boolean) self.fill_combobox(dekke.getComboBox(), self.path_dekke_friluft) self.fill_combobox(dekkeTilstand.getComboBox(), self.path_dekketilstand) self.fill_combobox(rekkverk.getComboBox(), self.path_boolean) self.fill_combobox(stoppkant.getComboBox(), self.path_boolean) self.fill_combobox(handlist.getComboBox(), self.path_handlist) self.fill_combobox(rampeTilgjengelig.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(tilgjengvurderingRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(tilgjengvurderingElRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(tilgjengvurderingSyn.getComboBox(), self.path_tilgjenglighetsvurdering) #Set what to be hidden in form and conditions for showing parts self.hide_show_gui(attributes_rampe, self.dlg.comboBox_fiskeplass_rampe.currentText() == u"Ja", [self.dlg.label_fiskeplass_rampe, self.dlg.line_fiskeplass_rampe, self.dlg.line_fiskeplass]) self.dlg.comboBox_fiskeplass_rampe.currentIndexChanged.connect(lambda: self.hide_show_gui(attributes_rampe, self.dlg.comboBox_fiskeplass_rampe.currentText() == u"Ja", [self.dlg.label_fiskeplass_rampe, self.dlg.line_fiskeplass_rampe, self.dlg.line_fiskeplass])) self.hide_show_gui([dekkeTilstand], self.dlg.comboBox_fiskeplass_dekke.currentText() != self.unspecified) self.dlg.comboBox_fiskeplass_dekke.currentIndexChanged.connect(lambda: self.hide_show_gui([dekkeTilstand], self.dlg.comboBox_fiskeplass_dekke.currentText() != self.unspecified)) self.hide_show_gui([plankeavstand], self.dlg.comboBox_fiskeplass_dekke.currentText() == "Tre") self.dlg.comboBox_fiskeplass_dekke.currentIndexChanged.connect(lambda: self.hide_show_gui([plankeavstand], self.dlg.comboBox_fiskeplass_dekke.currentText() == "Tre")) self.hide_show_gui([stoppkantHoyde], self.dlg.comboBox_fiskeplass_stoppkant.currentText() == u"Ja") self.dlg.comboBox_fiskeplass_stoppkant.currentIndexChanged.connect(lambda: self.hide_show_gui([stoppkantHoyde], self.dlg.comboBox_fiskeplass_stoppkant.currentText() == u"Ja")) def assign_combobox_turvei(self): """Assigning a AttributeForm object to each option in Turvei""" spesialFotrutetype = AttributeForm(u"spesialFotrutetype", u"spesialFotrutetype", self.dlg.comboBox_turvei_spesialFotrutetype) dekke = AttributeForm(u"dekke", u"dekke", self.dlg.comboBox_turvei_dekke) dekkeTilstand = AttributeForm(u"dekkeTilstand", u"dekkeTilstand", self.dlg.comboBox_turvei_dekkeTilstand, label=self.dlg.label_turvei_dekketilstand) plankeavstand = AttributeForm(u"plankeavstand", u"plankeavstand", self.dlg.comboBox_turvei_plankeavstand, self.dlg.lineEdit_turvei_plankeavstand, label=self.dlg.label_turvei_plankeavstand) bredde = AttributeForm(u"bredde", u"bredde", self.dlg.comboBox_turvei_bredde, self.dlg.lineEdit_turvei_bredde) stigning = AttributeForm(u"stigning", u"stigning", self.dlg.comboBox_turvei_stigning, self.dlg.lineEdit_turvei_stigning) tverfall = AttributeForm(u"tverrfall", u"tverrfall", self.dlg.comboBox_turvei_tverfall, self.dlg.lineEdit_turvei_tverfall) sperrebom = AttributeForm(u"sperrebom", u"sperrebom", self.dlg.comboBox_turvei_sperrebom) sperrebom_tilgjengelig = AttributeForm(u"sperrebomTilgjengelig", u"sperrebomTilgjengelig", self.dlg.comboBox_turvei_sperrebom_tilgjengelig, label=self.dlg.label_turvei_sperrebom_tilgjengelig) ledelinje = AttributeForm(u"ledelinje", u"ledelinje", self.dlg.comboBox_turvei_ledelinje) ledelinjeKontrakst = AttributeForm(u"ledelinjeKontrast", u"ledelinjeKontrast", self.dlg.comboBox_turvei_ledelinjeKontrast, label=self.dlg.label_turvei_ledelinjeKontrast) belysning = AttributeForm(u"belysning", u"belysning", self.dlg.comboBox_turvei_belysning) frihoyde = AttributeForm(u"friHøyde", u"friHøyde", self.dlg.comboBox_turvei_frihoyde) moteplass = AttributeForm(u"møteHvileplass", u"møteHvileplass", self.dlg.comboBox_turvei_moteplass) tilgjengvurderingRullestol = AttributeForm(u"tilgjengvurderingRulleAuto", u"tilgjengvurderingRulleAuto", self.dlg.comboBox_turvei_manuell_rullestol) tilgjengvurderingElRullestol = AttributeForm(u"tilgjengvurderingElRullestol", u"tilgjengvurderingElRullestol", self.dlg.comboBox_turvei_electrisk_rullestol) tilgjengvurderingSyn = AttributeForm(u"tilgjengvurderingSyn", u"tilgjengvurderingSyn", self.dlg.comboBox_turvei_syn) self.attributes_turvei = [spesialFotrutetype, dekke, dekkeTilstand, bredde, stigning, tverfall, sperrebom, ledelinje, ledelinjeKontrakst, belysning, frihoyde, sperrebom_tilgjengelig, moteplass, plankeavstand, tilgjengvurderingRullestol, tilgjengvurderingElRullestol, tilgjengvurderingSyn] attributes_mer_mindre = [bredde, stigning, tverfall, plankeavstand] #Fill combobox for attributt in attributes_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(spesialFotrutetype.getComboBox(), self.path_spesialFotrutetype) self.fill_combobox(dekke.getComboBox(), self.path_dekke_friluft) self.fill_combobox(dekkeTilstand.getComboBox(), self.path_dekketilstand) self.fill_combobox(sperrebom.getComboBox(), self.path_boolean) self.fill_combobox(sperrebom_tilgjengelig.getComboBox(), self.path_boolean) self.fill_combobox(ledelinje.getComboBox(), self.path_ledelinje) self.fill_combobox(ledelinjeKontrakst.getComboBox(), self.path_kontrast) self.fill_combobox(belysning.getComboBox(), self.path_belysning) self.fill_combobox(frihoyde.getComboBox(), self.path_frihoyde) self.fill_combobox(moteplass.getComboBox(), self.path_boolean) self.fill_combobox(tilgjengvurderingRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(tilgjengvurderingElRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(tilgjengvurderingSyn.getComboBox(), self.path_tilgjenglighetsvurdering) #Hide/show GUI self.hide_show_gui([dekkeTilstand], self.dlg.comboBox_turvei_dekke.currentText() != self.unspecified) self.dlg.comboBox_turvei_dekke.currentIndexChanged.connect(lambda: self.hide_show_gui([dekkeTilstand], self.dlg.comboBox_turvei_dekke.currentText() != self.unspecified)) self.hide_show_gui([plankeavstand], self.dlg.comboBox_turvei_dekke.currentText() == "Tre") self.dlg.comboBox_turvei_dekke.currentIndexChanged.connect(lambda: self.hide_show_gui([plankeavstand], self.dlg.comboBox_turvei_dekke.currentText() == "Tre")) self.hide_show_gui([sperrebom_tilgjengelig], self.dlg.comboBox_turvei_sperrebom.currentText() == "Ja") self.dlg.comboBox_turvei_sperrebom.currentIndexChanged.connect(lambda: self.hide_show_gui([sperrebom_tilgjengelig], self.dlg.comboBox_turvei_sperrebom.currentText() == "Ja")) self.hide_show_gui([ledelinjeKontrakst], (self.dlg.comboBox_turvei_ledelinje.currentText() != self.unspecified and self.dlg.comboBox_turvei_ledelinje.currentText() != "Ingen")) self.dlg.comboBox_turvei_ledelinje.currentIndexChanged.connect(lambda: self.hide_show_gui([ledelinjeKontrakst], (self.dlg.comboBox_turvei_ledelinje.currentText() != self.unspecified and self.dlg.comboBox_turvei_ledelinje.currentText() != "Ingen"))) def assign_combobox_hc_parkering_friluft(self): """Assigning a AttributeForm object to each option in hc parkering friluft""" avstand_fasilitet = AttributeForm("avstandFasilitet", "app:avstandFasilitet", self.dlg.comboBox_friluft_hcpark_avstand_fasilitet, self.dlg.lineEdit_friluft_hcpark_avstand_fasilitet) skiltet = AttributeForm("skiltet", "app:skiltet", self.dlg.comboBox_hcpark_friluft_skiltet) merket = AttributeForm("merket", "app:merket", self.dlg.comboBox_hcpark_friluft_merket) bredde_hcp_merke = AttributeForm("bredde", "app:bredde", self.dlg.comboBox_hcpark_friluft_bredde, self.dlg.lineEdit_hcpark_friluft_bredde, label=self.dlg.label_hcpark_friluft_bredde) lengde_hcp_merke = AttributeForm("lengde", "app:lengde", self.dlg.comboBox_hcpark_friluft_lengde, self.dlg.lineEdit_hcpark_friluft_lengde, label=self.dlg.label_hcpark_friluft_lengde) manuell_rullestol_hcparkering = AttributeForm("tilgjengvurderingRulleAuto", "app:tilgjengvurderingRulleAuto", self.dlg.comboBox_hcpark_friluft_manuell_rullestol) self.attributes_hcparkering_friluft = [avstand_fasilitet, skiltet, merket, bredde_hcp_merke, lengde_hcp_merke, manuell_rullestol_hcparkering] attributes_hcparkering_mer_mindre = [avstand_fasilitet, bredde_hcp_merke, lengde_hcp_merke] #fill combobox for attributt in attributes_hcparkering_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(skiltet.getComboBox(), self.path_boolean) self.fill_combobox(merket.getComboBox(), self.path_boolean) self.fill_combobox(manuell_rullestol_hcparkering.getComboBox(), self.path_tilgjenglighetsvurdering) #Set what to be hidden in form and conditions for showing parts self.hide_show_gui([bredde_hcp_merke, lengde_hcp_merke], self.dlg.comboBox_hcpark_friluft_merket.currentText() == "Ja") self.dlg.comboBox_hcpark_friluft_merket.currentIndexChanged.connect(lambda: self.hide_show_gui([bredde_hcp_merke, lengde_hcp_merke], self.dlg.comboBox_hcpark_friluft_merket.currentText() == "Ja")) def assign_combobox_parkeringsomraade_friluft(self): """Assigning a AttributeForm object to each option in parkeringsområde_friluft""" kapasitetPersonbiler = AttributeForm("kapasitetPersonbiler", "app:kapasitetPersonbiler", self.dlg.comboBox_pomrade_friluft_kapasitetPersonbiler, self.dlg.lineEdit_pomrade_friluft_kapasitetPersonbiler) kapasitetUU = AttributeForm("antallUU", "app:antallUU", self.dlg.comboBox_pomrade_friluft_kapasitetUU, self.dlg.lineEdit_pomrade_friluft_kapasitetUU) dekke_pomrade = AttributeForm("dekke", "app:dekke", self.dlg.comboBox_pomrade_friluft_pomrade) dekkeTilstand_pomrade = AttributeForm("dekkeTilstand", "app:dekkeTilstand", self.dlg.comboBox_pomrade_friluft_dekkeTilstand, label=self.dlg.label_pomrade_friluft_dekkeTilstand) manuell_rullestol_pomrade = AttributeForm("tilgjengvurderingRulleAuto", "app:tilgjengvurderingRulleAuto", self.dlg.comboBox_pomrade_friluft_manuell_rullestol) self.attributes_pomrade_friluft = [kapasitetPersonbiler, kapasitetUU, dekke_pomrade, dekkeTilstand_pomrade, manuell_rullestol_pomrade] attributes_pomrade_gui = [dekke_pomrade, dekkeTilstand_pomrade, manuell_rullestol_pomrade] attributes_pomrade_mer_mindre = [kapasitetPersonbiler, kapasitetUU] #fill combobox for attributt in attributes_pomrade_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(dekke_pomrade.getComboBox(), self.path_dekke_friluft) self.fill_combobox(dekkeTilstand_pomrade.getComboBox(), self.path_dekketilstand) self.fill_combobox(manuell_rullestol_pomrade.getComboBox(), self.path_tilgjenglighetsvurdering) #Hide gui self.hide_show_gui([dekkeTilstand_pomrade], self.dlg.comboBox_pomrade_friluft_pomrade.currentText() != self.unspecified) self.dlg.comboBox_pomrade_friluft_pomrade.currentIndexChanged.connect(lambda: self.hide_show_gui([dekkeTilstand_pomrade], self.dlg.comboBox_pomrade_friluft_pomrade.currentText() != self.unspecified)) def assign_combobox_friluftomrader(self): """Assign a AttributeForm object to each option in friluftsområder""" navn = AttributeForm("navn", "app:navn", lineEdit=self.dlg.lineEdit_friluftsomrader_navn) naturbasenummber = AttributeForm("naturbaseId", "app:naturbaseId", lineEdit=self.dlg.lineEdit_friluftsomrader_naturbasenummer) self.attributes_friluftsomrader = [navn, naturbasenummber] def assign_combobox_gapahuk(self): """Assigning a AttributeForm object to each option in gapahuk""" rampe = AttributeForm("rampe", "app:rampe", self.dlg.comboBox_gapahuk_rampe) bredde = AttributeForm("breddeInngang", "app:breddeInngang", self.dlg.comboBox_gapahuk_bredde, self.dlg.lineEdit_gapahuk_bredde) hoyde = AttributeForm(u"høydeInngang", u"app:høydeInngang", self.dlg.comboBox_gapahuk_hoyde, self.dlg.lineEdit_gapahuk_hoyde) terskel = AttributeForm(u"terskelhøyde", u"app:terskelhøyde", self.dlg.comboBox_gapahuk_terskelhoyde, self.dlg.lineEdit_gapahuk_terskelhoyde) kontrast = AttributeForm("kontrastInngang", "app:kontrastInngang", self.dlg.comboBox_gapahuk_kontrast) snusirkel = AttributeForm("diameter", "app:diameter", self.dlg.comboBox_gapahuk_snusirkel, self.dlg.lineEdit_gapahuk_snusirkel) dekke = AttributeForm("dekke", "app:dekke", self.dlg.comboBox_gapahuk_dekke) dekkeTilstand = AttributeForm("dekkeTilstand", "app:dekkeTilstand", self.dlg.comboBox_gapahuk_dekke_tilstand, label=self.dlg.label_gapahuk_dekke_tilstand) rampe_stigning = AttributeForm("rampeStigning", "app:rampe/app:Rampe/app:rampeStigning", self.dlg.comboBox_gapahuk_rmp_stigning, self.dlg.lineEdit_gapahuk_rmp_stigning, label=self.dlg.label_gapahuk_rmp_stigning) rampe_bredde = AttributeForm("rampeBredde", "app:rampe/app:Rampe/app:rampeBredde", self.dlg.comboBox_gapahuk_rmp_bredde, self.dlg.lineEdit_gapahuk_rmp_bredde, label=self.dlg.label_gapahuk_rmp_bredde) handlist = AttributeForm(u"håndlist", u"app:rampe/app:Rampe/app:håndlist", self.dlg.comboBox_handlist_handliste, label=self.dlg.label_gapahuk_handliste) handlist1 = AttributeForm(u"håndlistHøydeØvre", u"app:rampe/app:Rampe/app:håndlistHøydeØvre", self.dlg.comboBox_gapahuk_hand1, self.dlg.lineEdit_gapahuk_hand1, label=self.dlg.label_gapahuk_hand1) handlist2 = AttributeForm(u"håndlistHøydeNedre", u"app:håndlistHøydeNedre", self.dlg.comboBox_gapahuk_hand2, self.dlg.lineEdit_gapahuk_hand2, label=self.dlg.label_gapahuk_hand2) rampeLengde = AttributeForm(u"rampeLengde", u"app:rampe/app:Rampe/app:rampeLengde", self.dlg.comboBox_gapahuk_lengde, self.dlg.lineEdit_gapahuk_lengde, label=self.dlg.label_gapahuk_lengde) rmp_tilgjengelig = AttributeForm("rampeTilgjengelig", "app:rampe/app:Rampe/app:rampeTilgjengelig", self.dlg.comboBox_gapahuk_rmp_tilgjengelig, label=self.dlg.label_gapahuk_rmp_tilgjengelig) manuellRullestol = AttributeForm("tilgjengvurderingRulleAuto", "app:tilgjengvurderingRulleAuto", self.dlg.comboBox_gapahuk_manuell_rullestol) elektriskRullestol = AttributeForm("tilgjengvurderingElRullestol", "app:tilgjengvurderingElRullestol", self.dlg.comboBox_gapahuk_el_rullestol) synshemmet = AttributeForm("tilgjengvurderingSyn", "app:tilgjengvurderingSyn", self.dlg.comboBox_gapahuk_syn) self.attributes_gapahuk = [rampe, bredde, hoyde, terskel, kontrast, snusirkel, dekke, dekkeTilstand, rampe_stigning, rampe_bredde, rampeLengde, handlist, handlist1, handlist2, rmp_tilgjengelig, manuellRullestol, elektriskRullestol, synshemmet] attributes_mer_mindre = [bredde, hoyde, terskel, snusirkel, rampe_stigning, rampe_bredde, handlist1, handlist2, rampeLengde] attributes_rampe = [rampe_stigning, rampe_bredde, handlist, handlist1, handlist2, rampeLengde, rmp_tilgjengelig] #fill combobox for attributt in attributes_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(rampe.getComboBox(), self.path_boolean) self.fill_combobox(kontrast.getComboBox(), self.path_kontrast) self.fill_combobox(dekke.getComboBox(), self.path_dekke_friluft) self.fill_combobox(dekkeTilstand.getComboBox(), self.path_dekketilstand) self.fill_combobox(handlist.getComboBox(), self.path_handlist) self.fill_combobox(rmp_tilgjengelig.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(manuellRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(elektriskRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(synshemmet.getComboBox(), self.path_tilgjenglighetsvurdering) #Set what to be hidden in form and conditions for showing parts self.hide_show_gui(attributes_rampe, self.dlg.comboBox_gapahuk_rampe.currentText() == u"Ja", [self.dlg.label_gapahuk_rampe_title, self.dlg.line_gapahuk_title_line, self.dlg.line_gapahuk_divider]) self.dlg.comboBox_gapahuk_rampe.currentIndexChanged.connect(lambda: self.hide_show_gui(attributes_rampe, self.dlg.comboBox_gapahuk_rampe.currentText() == u"Ja", [self.dlg.label_gapahuk_rampe_title, self.dlg.line_gapahuk_title_line, self.dlg.line_gapahuk_divider])) self.hide_show_gui([dekkeTilstand], self.dlg.comboBox_gapahuk_dekke.currentText() != self.unspecified) self.dlg.comboBox_gapahuk_dekke.currentIndexChanged.connect(lambda: self.hide_show_gui([dekkeTilstand], self.dlg.comboBox_gapahuk_dekke.currentText() != self.unspecified)) def assign_combobox_grillbalplass(self): """Assigning an AttributeForm object to each option grill-/bålplass""" plasstype = AttributeForm("plasstype", "app:plasstype", self.dlg.comboBox_balplass_plasstype) dekke = AttributeForm("dekke", "app:dekke", self.dlg.comboBox_balplass_dekke) dekkeTilstand = AttributeForm("dekkeTilstand", "app:dekkeTilstand", self.dlg.comboBox_balplass_dekketilstand, label=self.dlg.label_balplass_dekketilstand) helning = AttributeForm("helning", "app:helning", self.dlg.comboBox_balplass_helning, self.dlg.lineEdit_balplass_helning) manuellRullestol = AttributeForm("tilgjengvurderingRulleAuto", "app:tilgjengvurderingRulleAuto", self.dlg.comboBox_balplass_manuell_rullestol) self.attributes_balplass = [plasstype, dekke, dekkeTilstand, helning, manuellRullestol] self.fill_combobox(plasstype.getComboBox(), self.path_plasstype) self.fill_combobox(dekke.getComboBox(), self.path_dekke_friluft) self.fill_combobox(dekkeTilstand.getComboBox(), self.path_dekketilstand) self.fill_combobox(helning.getComboBox(), self.path_more_less) self.fill_combobox(manuellRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.hide_show_gui([dekkeTilstand], self.dlg.comboBox_balplass_dekke.currentText() != self.unspecified) self.dlg.comboBox_balplass_dekke.currentIndexChanged.connect(lambda: self.hide_show_gui([dekkeTilstand], self.dlg.comboBox_balplass_dekke.currentText() != self.unspecified)) def assign_combobox_sittegruppe(self): """Assigning an AttributeForm object to each option in Sittegruppe""" dekke = AttributeForm("dekke", "app:dekke", self.dlg.comboBox_sittegruppe_dekke) dekkeTilstand = AttributeForm("dekkeTilstand", "app:dekkeTilstand", self.dlg.comboBox_sittegruppe_dekkeTilstand, label=self.dlg.label_sittegruppe_dekkeTilstand) helning = AttributeForm("helning", "app:helning", self.dlg.comboBox_sittegruppe_helning, self.dlg.lineEdit_sittegruppe_helning) bordhoyde = AttributeForm(u"høydeBord", u"app:høydeBord", self.dlg.comboBox_sittegruppe_hoyde, self.dlg.lineEdit_hoyde_sittegruppe) bordutsikt = AttributeForm("utstikkBord", "app:utstikkBord", self.dlg.comboBox_sittegruppe_utsikt, self.dlg.lineEdit_sittegruppe_utsikt) manuellRullestol = AttributeForm("tilgjengvurderingRulleAuto", "app:tilgjengvurderingRulleAuto", self.dlg.comboBox_sittegruppe_manuell_rullestol) #Nye attributter 2019 benkhoyde = AttributeForm("høydeBenk", "app:høydeBenk", self.dlg.comboBox_sittegruppe_hoyde_benk, self.dlg.lineEdit_sittegruppe_hoyde_benk) armlene = AttributeForm("armlene", "app:armlene", self.dlg.comboBox_sittegruppe_armlene) #Boolean ryggstotte = AttributeForm(u"ryggstøtte", u"app:ryggstøtte", self.dlg.comboBox_sittegruppe_ryggstotte) #Boolean adkomstkant = AttributeForm("adkomstKant", "app:adkomstKant", self.dlg.comboBox_sittegruppe_adkomst_kant, self.dlg.lineEdit_sittegruppe_adkomst_kant) #float adkomst_tilgjenglig = AttributeForm("adkomstTilgjengelig", "app:adkomstTilgjengelig", self.dlg.comboBox_sittegruppe_adkomst_tilgjengleig) #Boolean self.attributes_sittegruppe = [dekke, dekkeTilstand, helning, bordhoyde, bordutsikt, manuellRullestol, benkhoyde, armlene, ryggstotte, adkomstkant, adkomst_tilgjenglig] attributes_mer_mindre = [helning, bordhoyde, bordutsikt, benkhoyde, adkomstkant] #fill combobox for attributt in attributes_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(dekke.getComboBox(), self.path_dekke_friluft) self.fill_combobox(dekkeTilstand.getComboBox(), self.path_dekketilstand) self.fill_combobox(manuellRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(armlene.getComboBox(), self.path_boolean) self.fill_combobox(ryggstotte.getComboBox(), self.path_boolean) self.fill_combobox(adkomst_tilgjenglig.getComboBox(), self.path_boolean) #Hide GUI self.hide_show_gui([dekkeTilstand], self.dlg.comboBox_sittegruppe_dekke.currentText() != self.unspecified) self.dlg.comboBox_sittegruppe_dekke.currentIndexChanged.connect(lambda: self.hide_show_gui([dekkeTilstand], self.dlg.comboBox_sittegruppe_dekke.currentText() != self.unspecified)) def assign_combobox_toalett(self): """Assigning an AttributeForm object to each option in Sittegruppe""" byggtype = AttributeForm("byggtype", "app:byggtype", self.dlg.comboBox_toalett_byggtype) rampe = AttributeForm("rampe", "app:rampe", self.dlg.comboBox_toalett_rampe) trapp_toalett = AttributeForm("trapp", "app:trapp", self.dlg.comboBox_toalett_trapp) trapp_kontrast = AttributeForm("trappKontrast", "app:trapp/app:Trapp/app:trappKontrast", self.dlg.comboBox_toalett_konstrast_trapp, label=self.dlg.label_toalett_trapp_Kontrast) dortype = AttributeForm(u"dørtype", u"app:dørtype", self.dlg.comboBox_toalett_dortype) dorapner = AttributeForm(u"døråpner", u"app:døråpner", self.dlg.comboBox_toalett_dorapner) dorbredde = AttributeForm("breddeInngang", "app:breddeInngang", self.dlg.comboBox_toalett_bredde, self.dlg.lineEdit_toalett_bredde) terskel = AttributeForm(u"terskelhøyde", u"app:terskelhøyde", self.dlg.comboBox_toalett_terskel, self.dlg.lineEdit_toalett_terskel) kontrast = AttributeForm("kontrastInngang", "app:kontrastInngang", self.dlg.comboBox_toalett_kontrast) belysning = AttributeForm("belysningInne", "app:belysningInne", self.dlg.comboBox_toalett_belysning) snusirkel = AttributeForm("diameter", "app:diameter", self.dlg.comboBox_toalett_snusirkel, self.dlg.lineEdit_toalett_snusirkel) rampe_stigning = AttributeForm("rampeStigning", "app:rampe/app:Rampe/app:rampeStigning", self.dlg.comboBox_toalett_rmp_stigning, self.dlg.lineEdit_toalett_rmp_stigning, label=self.dlg.label_lineEdit_toalett_rmp_stigning) rampe_bredde = AttributeForm("rampeBredde", "app:rampe/app:Rampe/app:rampeBredde", self.dlg.comboBox_toalett_rmp_bredde, self.dlg.lineEdit_toalett_rmp_bredde, label=self.dlg.label_toalett_rmp_bredde) handlist = AttributeForm(u"håndlist", u"app:rampe/app:Rampe/app:håndlist", self.dlg.comboBox_toalett_handliste, label=self.dlg.label_toalett_handliste) handlist1 = AttributeForm(u"håndlistHøydeØvre", u"app:rampe/app:Rampe/app:håndlistHøydeØvre", self.dlg.comboBox_toalett_hand1, self.dlg.lineEdit_toalett_hand1, label=self.dlg.label_toalett_hand1) handlist2 = AttributeForm(u"håndlistHøydeNedre", u"app:rampe/app:Rampe/app:håndlistHøydeNedre", self.dlg.comboBox_toalett_hand2, self.dlg.lineEdit_toalett_hand2, label=self.dlg.label_toalett_hand2) rampeLengde = AttributeForm(u"rampeLengde", u"app:rampe/app:Rampe/app:rampeLengde", self.dlg.comboBox_toalett_lengde, self.dlg.lineEdit_toalett_lengde, label=self.dlg.label_toalett_lengde) rmp_tilgjengelig = AttributeForm("rampeTilgjengelig", "app:rampe/app:Rampe/app:rampeTilgjengelig", self.dlg.comboBox_toalett_rmp_tilgjengelig, label=self.dlg.label_toalett_rmp_tilgjengelig) omkledning = AttributeForm("omkledningTilgjengelig", "app:omkledningTilgjengelig", self.dlg.comboBox_toalett_omkledning, label=self.dlg.label_toalett_omkledning) sesrvant = AttributeForm("servantTilgjengelig", "app:servantTilgjengelig", self.dlg.comboBox_toalett_servant) wc = AttributeForm("wcTilgjengelig", "app:wcTilgjengelig", self.dlg.comboBox_toalett_wc, label=self.dlg.label_toalett_wc) manuellRullestol = AttributeForm("tilgjengvurderingRulleAuto", "app:tilgjengvurderingRulleAuto", self.dlg.comboBox_toalett_manuell_rullestol) elektriskRullestol = AttributeForm("tilgjengvurderingElRullestol", "app:tilgjengvurderingElRullestol", self.dlg.comboBox_toalett_el_rullestol) synshemmet = AttributeForm("tilgjengvurderingSyn", "app:tilgjengvurderingSyn", self.dlg.comboBox_toalett_syn) self.attributes_toalett = [byggtype, rampe, trapp_toalett, trapp_kontrast, dortype, dorapner, dorbredde, terskel, kontrast, belysning, snusirkel, rampe_stigning, rampe_bredde, handlist, handlist1, handlist2, rampeLengde, rmp_tilgjengelig, omkledning, sesrvant, wc, manuellRullestol, elektriskRullestol, synshemmet] attributes_mer_mindre = [dorbredde, terskel, snusirkel, rampe_stigning, rampe_bredde, handlist1, handlist2, rampeLengde] attributes_rampe = [rampe_stigning, rampe_bredde, handlist, handlist1, handlist2, rampeLengde, rmp_tilgjengelig] #fill combobox for attributt in attributes_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(byggtype.getComboBox(), self.path_byggtype) self.fill_combobox(rampe.getComboBox(), self.path_boolean) self.fill_combobox(dortype.getComboBox(), self.path_dortype) self.fill_combobox(dorapner.getComboBox(), self.path_dorapner) self.fill_combobox(kontrast.getComboBox(), self.path_kontrast) self.fill_combobox(belysning.getComboBox(), self.path_boolean) self.fill_combobox(trapp_toalett.getComboBox(), self.path_boolean) self.fill_combobox(trapp_kontrast.getComboBox(), self.path_kontrast) self.fill_combobox(handlist.getComboBox(), self.path_handlist) self.fill_combobox(rmp_tilgjengelig.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(omkledning.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(sesrvant.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(wc.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(manuellRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(elektriskRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(synshemmet.getComboBox(), self.path_tilgjenglighetsvurdering) #Set what to be hidden in form and conditions for showing parts self.hide_show_gui(attributes_rampe, self.dlg.comboBox_toalett_rampe.currentText() == u"Ja", [self.dlg.label_toalett_rampe_title, self.dlg.line_toalett_rampe, self.dlg.line_toalett_dividing]) self.dlg.comboBox_toalett_rampe.currentIndexChanged.connect(lambda: self.hide_show_gui(attributes_rampe, self.dlg.comboBox_toalett_rampe.currentText() == u"Ja", [self.dlg.label_toalett_rampe_title, self.dlg.line_toalett_rampe, self.dlg.line_toalett_dividing])) self.hide_show_gui([omkledning], self.dlg.comboBox_toalett_byggtype.currentText() != "Toalett") self.dlg.comboBox_toalett_byggtype.currentIndexChanged.connect(lambda: self.hide_show_gui([omkledning], self.dlg.comboBox_toalett_byggtype.currentText() != "Toalett")) self.hide_show_gui([wc], self.dlg.comboBox_toalett_byggtype.currentText() != "Omkledning") self.dlg.comboBox_toalett_byggtype.currentIndexChanged.connect(lambda: self.hide_show_gui([wc], self.dlg.comboBox_toalett_byggtype.currentText() != "Omkledning")) self.hide_show_gui([trapp_kontrast], trapp_toalett.getComboBox().currentText() == "Ja") trapp_toalett.getComboBox().currentIndexChanged.connect(lambda: self.hide_show_gui([trapp_kontrast], trapp_toalett.getComboBox().currentText() == "Ja")) #self.dlg.comboBox_rampe.currentIndexChanged.connect(self.hide_show_rampe) def assign_combobox_ski(self): """Assigning an AttributeForm object to each option in Skiløype""" hcpark = AttributeForm(u"avstandHC", "app:avstandHC", self.dlg.comboBox_ski_hcpark, self.dlg.lineEdit_ski_hcpark) dobbelspor = AttributeForm(u"dobbelSpor", "app:dobbelSpor", self.dlg.comboBox_ski_dobbelspor) belysning = AttributeForm(u"belysning", "app:belysning", self.dlg.comboBox_ski_belysning) bredde = AttributeForm(u"bredde", "app:bredde", self.dlg.comboBox_ski_bredde, self.dlg.lineEdit_ski_bredde) stigning = AttributeForm(u"stigning", "app:stigning", self.dlg.comboBox_ski_stigning, self.dlg.lineEdit_ski_stigning) tverfall = AttributeForm(u"tverrfall", "app:tverrfall", self.dlg.comboBox_ski_tverfall, self.dlg.lineEdit_ski_tverfall) frihoyde = AttributeForm(u"friHøyde", "app:friHøyde", self.dlg.comboBox_ski_frihoyde) manuellRullestol = AttributeForm(u"tilgjengvurderingRulleMan", "app:tilgjengvurderingRulleMan", self.dlg.comboBox_ski_manuell_rullestol) synshemmed = AttributeForm(u"tilgjengvurderingSyn", "app:tilgjengvurderingSyn", self.dlg.comboBox_ski_synshemmed) self.attributes_ski = [hcpark, dobbelspor, belysning, bredde, stigning, tverfall, frihoyde, manuellRullestol, synshemmed] attributes_mer_mindre = [hcpark, bredde, stigning, tverfall] #fill combobox for attributt in attributes_mer_mindre: self.fill_combobox(attributt.getComboBox(), self.path_more_less) self.fill_combobox(dobbelspor.getComboBox(), self.path_boolean) self.fill_combobox(belysning.getComboBox(), self.path_belysning) self.fill_combobox(frihoyde.getComboBox(), self.path_frihoyde) self.fill_combobox(manuellRullestol.getComboBox(), self.path_tilgjenglighetsvurdering) self.fill_combobox(synshemmed.getComboBox(), self.path_tilgjenglighetsvurdering) ################################# Automate tools #################################### def resolve(name, basepath=None): if not basepath: basepath = os.path.dirname(os.path.realpath(__file__)) return os.path.join(basepath, name) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginWebMenu( self.tr(u'&Kartverket Tilgjengelighet'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def get_temppath(self, filename): """Creating a temperarly path for a temperary file :param filename: String name for file :type filename: str, QString :returns: string of full path :rtype: str """ tmpdir = os.path.join(tempfile.gettempdir(),'Tilgjengelighet') if not os.path.exists(tmpdir): os.makedirs(tmpdir) tmpfile= os.path.join(tmpdir, filename) return tmpfile def to_unicode(self, in_string): """Transforme string to unicode :param in_string: String to transforme :returns: unicode verson of string :rtype: unicode """ if isinstance(in_string,str): out_string = in_string.decode('utf-8') elif isinstance(in_string,unicode): out_string = in_string else: raise TypeError('not stringy') return out_string def nanInt(self, number): """Transforme strign number to int, if not a number, return None :param number: Number to transform to int :returns: int version of string :rtype: int, None """ try: return int(number) except TypeError: return None return None def hide_show_gui(self, attributeForms, condition, extra = None): """Shows parts of GUI if conditions are meat, hids it if not :param attributeForms: A list of witch attributes to hide in GUI :type attributeForms: list<AttributeForm> :param condition: The condition to show GUI parts :type condition: boolean :param extra: include if gui consists of more than attributes that needs to be showed/hidden :type extra: list<QtWidgets> """ #Itterate throu alle attributes that need to be hidden or showd for attribute in attributeForms: attribute.getComboBox().setVisible(condition) if attribute.getLineEdit(): attribute.getLineEdit().setVisible(condition) if attribute.getLabel(): attribute.getLabel().setVisible(condition) if extra: #Hide/Show additional widgets for widget in extra: widget.setVisible(condition) def fill_combobox(self, combobox, filename): """Fikks combobox with lines from filename :param combobox: The combobox to be filled :type combobox: QComboBox :param filename: name of file with info to be filled in combobox :type filename: str, QString """ combobox.clear() #Clear possible information in combobox combobox.addItem(self.unspecified) #Include an empty, unspesifised field for combobox with open(filename, 'r') as file: for line in file: combobox.addItem(self.to_unicode(line).rstrip('\n')) #Add line to combobox def fill_infoWidget(self, attributes): """Filling infowidget with attributes name and no value. Also ajustes size of infowidget :param attributes: List of gui attriibutes :type attributes: list<AttributeForms> """ for i in range(0, len(attributes)): #print("fill_infoWidget loop 1: {}".format(i)) self.infoWidget.gridLayout.itemAtPosition(i, 0).widget().setText(attributes[i].getAttribute()) #Sets attribute name self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText("-") #Set sign for no value #Show line in case the line is hidden self.infoWidget.gridLayout.itemAtPosition(i, 0).widget().setVisible(True) self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setVisible(True) for i in range(len(attributes), self.infoWidget.gridLayout.rowCount()): #Hides rows that are not used self.infoWidget.gridLayout.itemAtPosition(i, 0).widget().setVisible(False) self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setVisible(False) def fill_fylker(self): """Fill up the combobox fylker with fylker from komm.txt""" self.dlg.comboBox_fylker.clear() self.dlg.comboBox_fylker.addItem("Norge") #Option for not chosing a single county filename = self.path_kommuner #Inititate dictionarys for fylke and kommune self.komm_dict_nr = {} self.komm_dict_nm = {} self.fylke_dict = {} with io.open(filename, 'r', encoding='utf-8') as f: for line in f: komm_nr, kommune, fylke = line.rstrip('\n').split(("\t")) #remove linebreak, spilt on tab #translate text to unicode komm_nr = self.to_unicode(komm_nr) kommune = self.to_unicode(kommune) fylke = self.to_unicode(fylke) #Fill dictionarys self.komm_dict_nr[komm_nr] = kommune self.komm_dict_nm[kommune] = komm_nr #If fylke is not in combobox, add fylke and list to fylke_dict if not fylke in self.fylke_dict: self.fylke_dict[fylke] = [] self.dlg.comboBox_fylker.addItem(fylke) self.fylke_dict[fylke].append(komm_nr) #add kommune numbers to fylke list in fylke dict def url_encode(self, url): replace_list ={'<' : '%3C', '>' : '%3E', ' ' : '%20', '"' : '%22'} for x in replace_list: url = url.replace(x, replace_list[x]) return url ############################ Actions ################################## def get_previus_search_activeLayer(self): """Open filtering window set to preweus choises""" activeLayer = self.iface.activeLayer() #if self.search_history[activeLayer.name()]: if activeLayer is not None and activeLayer.name() in self.search_history: #Check that actice layers is in search history try: pre_search = self.search_history[activeLayer.name()] #Get previus search for key, value in pre_search.attributes.iteritems(): #key: AttributeForm, value[0]: combobox index, value[1]; lineEdit text if key.getComboBox(): key.getComboBox().setCurrentIndex(int(value[0])) #Set combobx to given index if value[1]: #if attribute has lineEdit and text key.getLineEdit().setText(value[1]) #Fill lineEdit with given text self.dlg.tabWidget_main.setCurrentIndex(pre_search.tabIndex_main) #set main tab to given index self.dlg.tabWidget_friluft.setCurrentIndex(pre_search.tabIndex_friluft) #Set friluft tab to given index self.dlg.tabWidget_tettsted.setCurrentIndex(pre_search.tabIndex_tettsted) #Set tettsted tab to given index self.dlg.lineEdit_search_name.setText(self.layer_name) #Sett search name to given text self.change_search_name() self.dlg.show() #Open filtrer window except KeyError: raise else: self.dlg.show() def fylke_valgt(self): """Fill up kommune combobox with kommune in chosen fylke""" fylke = self.dlg.comboBox_fylker.currentText() self.dlg.comboBox_kommuner.clear() #Clear combobox to fill with new values self.dlg.comboBox_kommuner.addItem(self.unspecified) #Add unspesified value if fylke != "Norge": #If value other that Norge was chosen try: for kommune_nr in self.fylke_dict[fylke]: #Fill combobx with all values given county self.dlg.comboBox_kommuner.addItem(self.komm_dict_nr[kommune_nr]) #Get kommune name from kommune nummber except Exception as e: print(str(e)) else: #No spesific county chosen, add all kommuner filename = self.path_kommuner try: with io.open(filename, 'r', encoding='utf-8') as f: for line in f: komm_nr, komune, fylke = line.rstrip('\n').split(("\t")) self.dlg.comboBox_kommuner.addItem(self.komm_dict_nr[komm_nr]) except Exception as e: print(str(e)) def kommune_valgt(self): """Alter the name on seach after a kommune is chosen""" if self.dlg.comboBox_kommuner.currentText() != "": #A kommune is chocen self.dlg.lineEdit_search_name.setText(self.dlg.lineEdit_search_name.text() + ": " + self.dlg.comboBox_kommuner.currentText()) #Set searchname with name of kommune as ending else: self.dlg.lineEdit_search_name.setText(self.dlg.lineEdit_search_name.text() + ": " + self.dlg.comboBox_fylker.currentText()) #Set searchname with name of county as ending def change_search_name(self): """Changes the name of search based on current tab and fyle and kommune""" self.dlg.lineEdit_search_name.setText(self.dlg.tabWidget_main.tabText(self.dlg.tabWidget_main.currentIndex())) if self.dlg.tabWidget_main.tabText(self.dlg.tabWidget_main.currentIndex()) == "Friluft": #If main tab is in friluft self.dlg.lineEdit_search_name.setText(self.dlg.lineEdit_search_name.text() + " " + self.dlg.tabWidget_friluft.tabText(self.dlg.tabWidget_friluft.currentIndex())) else: #if main tab is in tettsted self.dlg.lineEdit_search_name.setText(self.dlg.lineEdit_search_name.text() + " " + self.dlg.tabWidget_tettsted.tabText(self.dlg.tabWidget_tettsted.currentIndex())) self.kommune_valgt() # if self.dlg.comboBox_kommuner.currentText() != "": # self.dlg.lineEdit_search_name.setText(self.dlg.lineEdit_search_name.text() + ": " + self.dlg.comboBox_kommuner.currentText()) # else: # self.dlg.lineEdit_search_name.setText(self.dlg.lineEdit_search_name.text() + ": " + self.dlg.comboBox_fylker.currentText()) def save_search(self): """"Saves the search to search history so it can set choises in GUI bac to preveus desisions""" self.search_history[self.layer_name] = SavedSearch(self.layer_name, self.current_layer, self.dlg.tabWidget_main.currentIndex(), self.dlg.tabWidget_friluft.currentIndex(), self.dlg.tabWidget_tettsted.currentIndex()) #saves search tab index, layer name and layer referense for attribute in self.current_attributes: #Stores the choises made in current form self.search_history[self.layer_name].add_attribute(attribute, self.nanInt(attribute.getComboBoxIndex()), attribute.getLineEditText()) #Attributes are stored as key in dictionary, index and tex are stored as value self.search_history[self.layer_name].add_attribute(self.fylker, self.nanInt(self.fylker.getComboBoxIndex()), None) #stores the choises of fylke and kommune self.search_history[self.layer_name].add_attribute(self.kommuner, self.nanInt(self.kommuner.getComboBoxIndex()), None) def show_tabell(self): """Shows or hide tableWidget""" if self.infoWidget.pushButton_tabell.isChecked(): #If pushbutton tabell is check, open attributetable, if not, close attributetable #self.iface.showAttributeTable(self.iface.activeLayer()) self.iface.mainWindow().findChild( QAction, 'mActionOpenTable' ).trigger() else: attrTables = [d for d in QApplication.instance().allWidgets() if d.objectName() == u'QgsAttributeTableDialog' or d.objectName() == u'AttributeTable'] for x in attrTables: x.close() def create_filter(self, opperator, valueReference, value): """creates FE based on input, made to take less space in other method create_filtherencoding :param opperator: opperator for FE :type opperator: str :param valueReference: name of attribute for FE :type valueReference: str :param value: value for FE :type value: str """ constraint = u"<fes:{0}><fes:ValueReference>{1}</fes:ValueReference><fes:Literal>{2}</fes:Literal></fes:{0}>".format(opperator,valueReference,value) return constraint def create_filtherencoding(self, attributeList, tilgjDB): """creates FE based on user choices :param attributeList: list of all attriubtes for filterencoding :type attributeList: list<AttributeForms> :returns: FilterEncoding :rtype: str """ fylke = self.dlg.comboBox_fylker.currentText() kommune = self.dlg.comboBox_kommuner.currentText() constraint = [] query = "" if fylke != "Norge" and kommune == self.unspecified: #County is chosen, not kommune for kommune_nr in range(0, len(self.fylke_dict[fylke])): #itterate all kommune numbers in fylke valueReference = "app:kommune" if len(self.fylke_dict[fylke][kommune_nr]) < 4: #Syntax demands 4 numbers in kommune number value = "0" + self.fylke_dict[fylke][kommune_nr] else: value = self.fylke_dict[fylke][kommune_nr] query += "<fes:PropertyIsEqualTo><fes:ValueReference>{0}</fes:ValueReference><fes:Literal>{1}</fes:Literal></fes:PropertyIsEqualTo>".format(valueReference,value) #Input values to FE if len(self.fylke_dict[fylke]) > 1: #Oslo only has 1 kommune, and can't use 'OR' opperators query = "<Or>{0}</Or>".format(query) #Add string within 'OR' to include all kommune numbers elif kommune != self.unspecified: #Kommune is chosen valueReference = "app:kommune" if len(self.komm_dict_nm[kommune]) < 4: #Syntax demands 4 numbers in kommune number value = "0" + self.komm_dict_nm[kommune] else: value = self.komm_dict_nm[kommune] query += "<fes:PropertyIsEqualTo><fes:ValueReference>{0}</fes:ValueReference><fes:Literal>{1}</fes:Literal></fes:PropertyIsEqualTo>".format(valueReference,value) #Input values to FE if len(query) > 0: #A fylke or kommune is chocen constraint.append(query) for attribute in attributeList: #Itterate all attributes in search if (attribute.getComboBox() is not None and attribute.getComboBoxCurrentText() != self.unspecified and attribute.getComboBox().isVisible()) or (attribute.getComboBox() is None and attribute.getLineEditText() is not self.unspecified): #Combobox value defined, or lineEdit text defined valueReference = attribute.getLocation() #Get valueReference value = attribute.value() #Get FE value value = value.replace(" ", "%20") #make the space in value url encoded (Need url endcoded spaces) opperator = attribute.opperator() #Get FE opperator constraint.append(self.create_filter(opperator, valueReference, value)) #Add contraint to list of constraints #print("valueReference: {0}\nvalue: {1}\nopperator: {2}".format(valueReference, value, opperator)) query = "" filterString = "" if len(constraint) > 1: #More than one constraint, contraint must be withing 'AND' for q in constraint: query += q #Create constraint string filterString = u'<fes:Filter xmlns:app="http://skjema.geonorge.no/SOSI/produktspesifikasjon/Tilgjengelighet{0}/1.2"><And>{1}</And></fes:Filter>'.format(tilgjDB, query) return ("FILTER=" + self.to_unicode(filterString)) #return ("FILTER=" + urllib.parse.quote_plus(self.to_unicode(filterString))) elif len(constraint) == 1: #One constraint, contraint can't be withing And filterString = u'<fes:Filter xmlns:app="http://skjema.geonorge.no/SOSI/produktspesifikasjon/Tilgjengelighet{0}/1.2">{1}</fes:Filter>'.format(tilgjDB, self.to_unicode(constraint[0])) return ("FILTER=" + self.to_unicode(filterString)) #return ("FILTER=" + urllib.parse.quote_plus(self.to_unicode(filterString))) return filterString #return empty filsterString (without "Filter=") def filtrer(self): """Makes FE and layer based on choises from user an current tab""" #if self.current_layer is not None: #Remove selection for previus search layer # self.current_layer.removeSelection() #Need more adjustment, what to do if layer is deleted self.layer_name = self.dlg.lineEdit_search_name.text() #gives search layer a name print("Main tab: {}".format(self.dlg.tabWidget_main.currentIndex())) if self.dlg.tabWidget_main.tabText(self.dlg.tabWidget_main.currentIndex()) == "Friluft":#if self.dlg.tabWidget_main.currentIndex() < 1: #Maintab is set at friluft, gets values for friluft print("friluft") tilgjDB = "friluft" featuretype = self.feature_type_friluft[self.dlg.tabWidget_friluft.tabText(self.dlg.tabWidget_friluft.currentIndex())] #gets feature type based on freaturetype tab in friluft self.current_attributes = self.attributes_friluft[self.dlg.tabWidget_friluft.tabText(self.dlg.tabWidget_friluft.currentIndex())] #gets attributes based on freaturetype tab in friluft infoWidget_title = self.dlg.tabWidget_friluft.tabText(self.dlg.tabWidget_friluft.currentIndex()) #gets infowidget title based on freaturetype tab in friluft else: #Main tab is set at tettsted, gets values for tettsted print("tettsted") tilgjDB = "tettsted" featuretype = self.feature_type_tettsted[self.dlg.tabWidget_tettsted.tabText(self.dlg.tabWidget_tettsted.currentIndex())] #gets feature type based on freaturetype tab in tettsted self.current_attributes = self.attributes_tettsted[self.dlg.tabWidget_tettsted.tabText(self.dlg.tabWidget_tettsted.currentIndex())] #gets attributes based on freaturetype tab in tettsted infoWidget_title = self.dlg.tabWidget_tettsted.tabText(self.dlg.tabWidget_tettsted.currentIndex()) #gets infowidget title based on freaturetype tab in tettsted #srsName = "urn:ogc:def:crs:EPSG::3034" #Denne er like dårlig som de andre som begynner med 30 #srsName = "urn:ogc:def:crs:EPSG::3575" # Denne gjør at ingen objecter blir funnet srsName = "urn:ogc:def:crs:EPSG::3857" #This seams to work!! :D #srsName = "EPSG:900913" #måtte velge koodssystem selv, fikk feilmelding når bakgrunskart ble valgt #srsName = "urn:ogc:def:crs:EPSG::4326" #Lik den orginale #srsName ="urn:ogc:def:crs:EPSG::3047" #Lik den forrige #srsName = "urn:ogc:def:crs:EPSG::3045" #Lik den forrige #srsName = "urn:ogc:def:crs:EPSG::3044" #Enda værre, punktene ute i vann, zoomer ut stopper ikke å laste #srsName = "urn:ogc:def:crs:EPSG::3035" #Veldig feil, punktene stemte ikke overens med bakgrunskartet #srsName = "urn:ogc:def:crs:EPSG::25835" #Samme som den andre #srsName = "urn:ogc:def:crs:EPSG::25833" #Mer eller mindre det samme som den forige #srsName = "urn:ogc:def:crs:EPSG::25832" #Næremre, men ikke helt #srsName = "urn:ogc:def:crs:EPSG::4258" #Den jeg alltid har brukt #Create url url = u"http://wfs.geonorge.no/skwms1/wfs.tilgjengelighet_{0}?service=WFS&request=GetFeature&version=2.0.0&srsName={2}&typeNames=app:{1}&".format(tilgjDB, featuretype, srsName) #print("url: {}".format(url)) #Create FE filter_encoding = self.create_filtherencoding(self.current_attributes, tilgjDB.capitalize())#= "FILTER=<fes:Filter><fes:PropertyIsEqualTo><fes:ValueReference>app:kommune</fes:ValueReference><fes:Literal>0301</fes:Literal></fes:PropertyIsEqualTo></fes:Filter>" URL_FE = url + filter_encoding print("Plane Text: {}".format(URL_FE)) URL_FE = self.url_encode(URL_FE) print("Encoded Text: {}".format(URL_FE)) #URL_FE = 'http://wfs.geonorge.no/skwms1/wfs.tilgjengelighet_tettsted?service=WFS&request=GetFeature&version=2.0.0&srsName=urn:ogc:def:crs:EPSG::3857&typeNames=app:TettstedInngangBygg&FILTER=%3Cfes:Filter%20xmlns:app=%22http://skjema.geonorge.no/SOSI/produktspesifikasjon/TilgjengelighetTettsted/1.2%22%3E%3Cfes:PropertyIsGreaterThan%3E%3Cfes:ValueReference%3Eapp:rampe/app:Rampe/app:rampeLengde%3C/fes:ValueReference%3E%3Cfes:Literal%3E800%3C/fes:Literal%3E%3C/fes:PropertyIsGreaterThan%3E%3C/fes:Filter%3E' #URL_FE = urllib.parse.quote_plus(url + filter_encoding) #print("FE: {}".format(filter_encoding)) #print("URL_FE: {}".format(URL_FE)) #Create new layer new_layer = QgsVectorLayer(URL_FE, self.layer_name, "ogr") #new_layer = QgsVectorLayer(url + filter_encoding, self.layer_name, "ogr") #print(u"url: {}".format(url)) #print(u"FE: {}".format(filter_encoding)) if new_layer.isValid(): #If new layer is valid/contains objekcts, add to canvas existing_layers = self.iface.legendInterface().layers() for name in self.search_history: if name == new_layer.name(): layer_id = self.search_history[name].get_id() if layer_id in QgsMapLayerRegistry.instance().mapLayers(): self.search_history[name].get_layer().removeSelection() QgsMapLayerRegistry.instance().removeMapLayers([layer_id]) del self.search_history[name] break QgsMapLayerRegistry.instance().addMapLayer(new_layer) #Add new layer self.current_layer = new_layer #Sett current layer self.current_id = new_layer.id() self.save_search() #Store search attributes self.current_layer.selectionChanged.connect(self.selectedObjects) #Filling infoWidget when objects are selected self.feature_ids = [f.id() for f in self.current_layer.getFeatures()] print("len feature_ids: {}".format(len(self.feature_ids))) #Zoom to layer canvasCrs = self.canvasCrs() if canvasCrs != self.current_layer.crs(): #If the crs of the canvas differ from the layer, the zoom vil be wrong coordTrans = QgsCoordinateTransform(canvasCrs, self.current_layer.crs()) extMap = self.canvas.extent() extMap = coordTrans.transform(extMap, QgsCoordinateTransform.ForwardTransform) if QGis.QGIS_VERSION_INT >= 20300: self.canvas.setDestinationCrs(self.current_layer.crs()) elif QGis.QGIS_VERSION_INT >= 10900: self.canvas.mapRenderer().setDestinationCrs(self.current_layer.crs()) else: self.canvas.mapRenderer().setDestinationSrs(self.current_layer.crs()) self.canvas.freeze(False) self.canvas.setMapUnits(self.current_layer.crs().mapUnits()) self.canvas.setExtent(self.current_layer.extent()) self.canvas.zoomOut() #inititate new infowidget if self.infoWidget is None: self.create_infoWidget() self.fill_infoWidget(self.current_attributes) self.infoWidget.label_typeSok.setText(infoWidget_title) self.selectedObjects() self.infoWidget.show() #Close old atribute table attrTables = [d for d in QApplication.instance().allWidgets() if d.objectName() == u'QgsAttributeTableDialog' or d.objectName() == u'AttributeTable'] for x in attrTables: x.close() self.show_tabell() #Show or hide new attribute table if self.rubberHighlight is not None: #removing previus single highlight self.canvas.scene().removeItem(self.rubberHighlight) self.save_search() #Store search attributes self.dlg.close() #closing main window for easyer visualisation of results else: self.show_message("Ingen objekter funnet", msg_title="layer not valid", msg_type=QMessageBox.Warning) #Messeage if layer is not valid/not objects was found #self.show_message("WFS client currently down", msg_title="WFS-Client down", msg_type=QMessageBox.Warning) #self.infoWidget.show() #self.show_tabell() #self.dlg.close() #print(u"URL: {0}\n FE: {1}".format(url, filter_encoding)) print(u"FilterEnd") ############################## Selection and info of Objects ################################################ def selectedObjects(self): """changing number of selected objects in infowidget and settning current selected object :param selFeatures: Selected features of layer """ if self.current_id in QgsMapLayerRegistry.instance().mapLayers(): self.selection = self.current_layer.selectedFeatures() #Set selected features #self.number_of_objects = len(selFeatures) #number of objects selected self.cur_sel_obj = 1 #Current selected object if len(self.selection) > 0: self.number_of_objects = len(self.selection) else: self.number_of_objects = len(self.feature_ids) self.obj_info() #Fill infowidget with info on current selected object self.highlightSelected() #highligt current selected object viewd in infowidget def no_object_selected(self): self.number_of_objects = len(self.feature_ids) self.current_viewed_object = 0 self.obj_info() def highlightSelected(self): """Highlights the object viewed in infowidget""" if self.rubberHighlight is not None: self.canvas.scene().removeItem(self.rubberHighlight) #remove previus rubberband self.canvas.refresh() #if len(self.selection) > 0: #objects selected is more than 0 self.rubberHighlight = QgsRubberBand(self.canvas,QGis.Polygon) #create new rubberband self.rubberHighlight.setBorderColor(QColor(255,0,0)) #Set birder color for new rubberband (red) self.rubberHighlight.setFillColor(QColor(255,0,0,255)) #set fill color for new rubberband (red) #self.rubberHighlight.setLineStyle(Qt.PenStyle(Qt.DotLine)) self.rubberHighlight.setWidth(4) #Set widht of new rubberband if len(self.selection) > 0: self.rubberHighlight.setToGeometry(self.selection[self.cur_sel_obj-1].geometry(), self.current_layer) #set geometry of rubberband equal to current selected object else: iterator = self.current_layer.getFeatures(QgsFeatureRequest().setFilterFid(self.feature_ids[self.cur_sel_obj-1])) feature = next(iterator) self.rubberHighlight.setToGeometry(feature.geometry(), self.current_layer) self.rubberHighlight.show() #Show rubberband def infoWidget_next(self): """shows next object in infoWidget""" if self.current_id in QgsMapLayerRegistry.instance().mapLayers(): try: self.cur_sel_obj+=1 if self.cur_sel_obj > self.number_of_objects: #when exiding objects, go back to first self.cur_sel_obj = 1 self.obj_info() #Fill infowidget with new info self.highlightSelected() #set new rubberband to highlight new object except AttributeError as e: pass def infoWidget_prev(self): """shows previus object in infoWidget""" if self.current_id in QgsMapLayerRegistry.instance().mapLayers(): try: self.cur_sel_obj-=1 if self.cur_sel_obj <= 0: #when exiding objects, go to last self.cur_sel_obj = self.number_of_objects self.obj_info() #Fill infowidget with new info self.highlightSelected() #set new rubberband to highlight new object except AttributeError as e: pass def obj_info(self): """Fills infowidget with info of current object""" self.infoWidget.label_object_number.setText("{0}/{1}".format(self.cur_sel_obj, self.number_of_objects)) #Show current object, and number of objects selected for i in range(0, len(self.current_attributes)): try: if len(self.selection) > 0: value = self.selection[self.cur_sel_obj-1][self.to_unicode(self.current_attributes[i].getAttribute())] #Get attribute value of current selected objects for else: #print("cur_sel_obj: {}".format(self.cur_sel_obj)) #print("length feature_ids: {}".format(len(self.feature_ids))) iterator = self.current_layer.getFeatures(QgsFeatureRequest().setFilterFid(self.feature_ids[self.cur_sel_obj-1])) feature = next(iterator) attributes = feature.attributes() idx = self.current_layer.fieldNameIndex(self.current_attributes[i].getAttribute()) value = attributes[idx] try: #insert valu to infowidget if isinstance(value, (int, float, long)): self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText(str(value)) #make value str elif isinstance(value, (QPyNullVariant)): #No value self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText("-") else: self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText(value) except Exception as e: self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText("-") #No value except KeyError as e: #attribute not in layer do to no value in any objects pass # self.infoWidget.label_object_number.setText("{0}/{1}".format(self.cur_sel_obj+1, self.number_of_objects)) #Show current object, and number of objects selected # if len(self.selection) > 0: # for i in range(0, len(self.current_attributes)): # try: # value = self.selection[self.cur_sel_obj][self.to_unicode(self.current_attributes[i].getAttribute())] #Get attribute value of current selected objects for # try: #insert valu to infowidget # if isinstance(value, (int, float, long)): # self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText(str(value)) #make value str # elif isinstance(value, (QPyNullVariant)): #No value # self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText("-") # else: # self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText(value) # except Exception as e: # self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText("-") #No value # except KeyError as e: #attribute not in layer do to no value in any objects # pass # else: #No objects chocen, set value to "-" # print("Print features in current_layer") # print(', '.join(str(f.id()) for f in self.current_layer.getFeatures())) # for i in range(0, len(self.current_attributes)): # request = QgsFeatureRequest().setFilterFid(i) # iterator = self.current_layer.getFeatures(QgsFeatureRequest().setFilterFid(i)) # try: # feature = next(iterator) # except StopIteration: # print('No feature with id {} found in dataset').format(i) # raise # for i in range(0, len(self.current_attributes)): # request = QgsFeatureRequest().setFilterFid(i) # iterator = self.current_layer.getFeatures(QgsFeatureRequest().setFilterFid(i)) # feature = next(iterator) # #feature = self.current_layer.getFeatures(request).next() # attributes = feature.attributes() # idx = self.current_layer.fieldNameIndex(self.current_attributes[i].getAttribute()) # value = attributes[idx] # try: # if isinstance(value, (int, float, long)): # self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText(str(value)) #make value str # elif isinstance(value, (QPyNullVariant)): #No value # self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText("-") # else: # self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText(value) # except Exception as e: # self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText("-") #No value #for i in range(0, len(self.current_attributes)): # self.infoWidget.gridLayout.itemAtPosition(i, 1).widget().setText("-") def canvasReleaseEvent(self, event): #Unfinished, the goal of this is to provide info of an object by clicking in the canvas. does however get the same effect with freehand selection layer = self.current_layer features = QgsMapToolIdentify(self.canvas).identify(event.x(), event.y(), [layer], QgsMapToolIdentify.TopDownStopAtFirst) if len(features) > 0: #here you get the selected feature feature = features[0].mFeature #And here you get the attribute's value feature_name = feature['gml_id'] x = event.pos().x() y = event.pos().y() point = self.canvas.getCoordinateTransform().toMapCoordinates(x, y) print("gml_id: {}".format(feature_name)) def show_message(self, msg_text, msg_title=None, msg_info=None, msg_details=None, msg_type=None): """Show the user a message :param msg_text: the tekst to show the user :type msg_text: str :param msg_title: the title of the message box :type msg_title: str :param msg_info: additional info for the user :type msg_info: str :param msg_details: details for the user :type msg_details: str :param msg_type: the type of message :type msg_type: QMessageBox.Icon """ msg = QMessageBox() msg.setText(self.to_unicode(msg_text)) if msg_title is not None: msg.setWindowTitle(msg_title) if msg_info is not None: msg.setInformativeText(msg_info) if msg_details is not None: msg.setDetailedText(msg_details) if msg_type is not None: msg.setIcon(msg_type) msg.setStandardButtons(QMessageBox.Ok) retval = msg.exec_() print(("value of pressed message box button:", retval)) def savePath(self, saveType, saveExtension): #find savepath """Find the save path :param saveType: The type of file to be saved :type saveType: str :param saveExtension: File extention (e.g .xls .png) :type saveExtension: str :returns: direktory path and file namle :rtype: (str,str) """ dirPath = self.settings.value("/Tilgjengelighet/savePath", ".", type=str) #Open file expoorer and save file (filename, filter) = QFileDialog.getSaveFileNameAndFilter(self.iface.mainWindow(), "Please save {0} file as...".format(saveType), dirPath, "{0} files (*{1})".format(saveType, saveExtension), "Filter list for selecting files from a dialog box") fn, fileExtension = os.path.splitext(unicode(filename)) if len(fn) == 0: # user choose cancel return None, None self.settings.setValue("/Tilgjengelighet/savePath", QFileInfo(filename).absolutePath()) if fileExtension != saveExtension: #set file extention to filename filename = filename + saveExtension return dirPath, filename #return path to save folder and filname def imageSave(self): """saves a screenshot of canvas""" dirPath, filename = self.savePath("Image", ".png") if dirPath is None: #user chose cansel return size = self.canvas.size() image = QImage(size, QImage.Format_RGB32) painter = QPainter(image) settings = self.canvas.mapSettings() job = QgsMapRendererCustomPainterJob(settings, painter) job.renderSynchronously() painter.end() image.save(filename) #filename1 + ".png")#'C:\\Users\\kaspa_000\\OneDrive\\Documents\\Skole-KaspArno\\Master\\tests\\newimageTest3.png') def open_export_layer_dialog(self): #Not currently in use """opens the excport gui""" self.export_layer.show() def OpenBrowser(self): #Not currently in use """Opens broeser to save file""" filename1 = QFileDialog.getSaveFileName() self.export_layer.lineEdit.setText(filename1) def lagre_lag(self): #Not currently in use """Saves layer as exported""" QgsVectorFileWriter.writeAsVectorFormat(self.iface.activeLayer(), self.export_layer.lineEdit.text(), "utf-8", None, self.export_layer.comboBox.currentText()) def reset(self): """Resets the gui back to default""" all_attributes = [] #add all attributes to list for attributeList in self.attributes_tettsted: all_attributes.extend(self.attributes_tettsted[attributeList]) for attributeList in self.attributes_friluft: all_attributes.extend(self.attributes_friluft[attributeList]) for attribute in all_attributes: attribute.reset() #resets attribute value ###############################################Xy-tools##################################################### def excelSave(self): """obtaind from xytools, Saves features to excel format @author: <NAME> """ if self.current_layer == None or self.current_id not in QgsMapLayerRegistry.instance().mapLayers(): QMessageBox.warning(self.iface.mainWindow(), u"Finner ingen lag å eksportere", u"Fant ingen lag til å exsportere til xls") return #if self.iface.activeLayer(): # self.currentLayerChanged(self.iface.activeLayer()) #else: # QMessageBox.warning(self.iface.mainWindow(), "No active layer", "Please make an vector layer active before saving it to excel file.") # return fieldNames = utils.fieldNames(self.current_layer) dlg = FieldChooserDialog(fieldNames) names = [] while len(names) == 0: dlg.show() if dlg.exec_() == 0: return names = dlg.getSelectedFields() if len(names) == 0: QMessageBox.warning(self.iface.mainWindow(), "Ingen felt valgt", "Vennligst velg minst ett felt.")#"No fields selected", "Please select at least one field.") dirPath, filename = self.savePath("Excel", ".xls") if dirPath == None: #User chose cancel return try: from xytools.providers import excel except: QMessageBox.warning(self.iface.mainWindow(), "Unable to load Python module", "There is a problem with loading a python module which is needed to read/write Excel files. Please see documentation/help how to install python xlw and xlrd libraries.") return xlw = excel.Writer(filename) #self.layer = self.iface.activeLayer() selection = None if self.current_layer.selectedFeatureCount() > 0: if QMessageBox.question(self.iface.mainWindow(), "Eksporter Til Excel", (u"Du har et utvalg i dette laget. Bare eksporter dette utvalget?\n" u"Klikk Ja for å eksportere bare utvalg, klikk Nei for å eksportere alle rader."),#("You have a selection in this layer. Only export this selection?\n" "Click Yes to export selection only, click No to export all rows."), QMessageBox.No, QMessageBox.Yes) == QMessageBox.Yes: selection = self.current_layer.selectedFeaturesIds() feature = QgsFeature(); xlw.writeAttributeRow(0, names) rowNr = 1 if QGis.QGIS_VERSION_INT < 10900: prov = self.current_layer.dataProvider() prov.select(prov.attributeIndexes()) while prov.nextFeature(feature): # attribute values, either for all or only for selection if selection == None or feature.id() in selection: values = feature.attributeMap().values() rowValues = [] for field in names: rowValues.append(values[field]) xlw.writeAttributeRow(rowNr, values) rowNr += 1 else: prov = self.current_layer.getFeatures() while prov.nextFeature(feature): # attribute values, either for all or only for selection if selection == None or feature.id() in selection: values = [] for field in names: values.append(feature.attribute(field)) xlw.writeAttributeRow(rowNr, values) rowNr += 1 xlw.saveFile() QMessageBox.information(self.iface.mainWindow(), u"Vellykket", u"Vellykket lagret som xls-fil") #"Success", "Successfully saved as xls file") ########################### Open Lyaers Plugin ########################################## def openLayer_background_init(self): """The folowing code has been taken out from OpenLayers Plugin writen by Sourcepole""" self._olMenu = QMenu("OpenLayers plugin") self._olLayerTypeRegistry.register(OlOpenStreetMapLayer()) self._olLayerTypeRegistry.register(OlOpenCycleMapLayer()) self._olLayerTypeRegistry.register(OlOCMLandscapeLayer()) self._olLayerTypeRegistry.register(OlOCMPublicTransportLayer()) # ID 8-10 was Yahoo self._olLayerTypeRegistry.register(OlOSMHumanitarianDataModelLayer()) self._olLayerTypeRegistry.register(OlBingRoadLayer()) self._olLayerTypeRegistry.register(OlBingAerialLayer()) self._olLayerTypeRegistry.register(OlBingAerialLabelledLayer()) # Order from here on is free. Layers 0-14 should keep order for # compatibility with OL Plugin < 2.3 self._olLayerTypeRegistry.register(OlOSMStamenTonerLayer()) self._olLayerTypeRegistry.register(OlOSMStamenTonerLiteLayer()) self._olLayerTypeRegistry.register(OlOSMStamenWatercolorLayer()) self._olLayerTypeRegistry.register(OlOSMStamenTerrainLayer()) self._olLayerTypeRegistry.register(OlAppleiPhotoMapLayer()) self._olLayerTypeRegistry.register(WikimediaLabelledLayer()) self._olLayerTypeRegistry.register(WikimediaUnLabelledLayer()) for group in self._olLayerTypeRegistry.groups(): #print("group: ", group) groupMenu = group.menu() for layer in self._olLayerTypeRegistry.groupLayerTypes(group): #print("layer: ", layer) layer.addMenuEntry(groupMenu, self.iface.mainWindow()) self._olMenu.addMenu(groupMenu) def addLayer(self, layerType): """The folowing code has been taken out from OpenLayers Plugin writen by Sourcepole""" if layerType.hasGdalTMS(): # create GDAL TMS layer layer = self.createGdalTmsLayer(layerType, layerType.displayName) else: # create OpenlayersLayer layer = OpenlayersLayer(self.iface, self._olLayerTypeRegistry) layer.setLayerName(layerType.displayName) layer.setLayerType(layerType) if layer.isValid(): #if len(self._ol_layers) > 0: if self._ol_layer_id in QgsMapLayerRegistry.instance().mapLayers(): QgsMapLayerRegistry.instance().removeMapLayers( [self._ol_layer_id] ) # if self._ol_layers[0].id() in QgsMapLayerRegistry.instance().mapLayers(): # QgsMapLayerRegistry.instance().removeMapLayers( [self._ol_layers[0].id()] ) # self._ol_layers.remove(self._ol_layers[0]) coordRefSys = layerType.coordRefSys(self.canvasCrs()) self.setMapCrs(coordRefSys) QgsMapLayerRegistry.instance().addMapLayer(layer, False) #self._ol_layers += [layer] self._ol_layer = layer self._ol_layer_id = layer.id() # last added layer is new reference self.setReferenceLayer(layer) if not layerType.hasGdalTMS(): msg = "Printing and rotating of Javascript API " \ "based layers is currently not supported!" self.iface.messageBar().pushMessage( "OpenLayers Plugin", msg, level=QgsMessageBar.WARNING, duration=5) #Set background mat at bacground root = QgsProject.instance().layerTreeRoot() root.insertLayer(-1, layer) def setReferenceLayer(self, layer): """The folowing code has been taken out from OpenLayers Plugin writen by Sourcepole""" self.layer = layer def createGdalTmsLayer(self, layerType, name): """The folowing code has been taken out from OpenLayers Plugin writen by Sourcepole""" # create GDAL TMS layer with XML string as datasource layer = QgsRasterLayer(layerType.gdalTMSConfig(), name) layer.setCustomProperty('ol_layer_type', layerType.layerTypeName) return layer def canvasCrs(self): """The folowing code has been taken out from OpenLayers Plugin writen by Sourcepole""" mapCanvas = self.iface.mapCanvas() if QGis.QGIS_VERSION_INT >= 20300: #crs = mapCanvas.mapRenderer().destinationCrs() crs = mapCanvas.mapSettings().destinationCrs() elif QGis.QGIS_VERSION_INT >= 10900: crs = mapCanvas.mapRenderer().destinationCrs() else: crs = mapCanvas.mapRenderer().destinationSrs() return crs def setMapCrs(self, coordRefSys): """The folowing code has been taken out from OpenLayers Plugin writen by Sourcepole""" mapCanvas = self.canvas # self.iface.mapCanvas() # On the fly if QGis.QGIS_VERSION_INT >= 20300: #mapCanvas.setCrsTransformEnabled(True) pass else: #mapCanvas.mapRenderer().setProjectionsEnabled(True) pass canvasCrs = self.canvasCrs() if canvasCrs != coordRefSys: coordTrans = QgsCoordinateTransform(canvasCrs, coordRefSys) extMap = mapCanvas.extent() extMap = coordTrans.transform(extMap, QgsCoordinateTransform.ForwardTransform) if QGis.QGIS_VERSION_INT >= 20300: mapCanvas.setDestinationCrs(coordRefSys) pass elif QGis.QGIS_VERSION_INT >= 10900: mapCanvas.mapRenderer().setDestinationCrs(coordRefSys) pass else: mapCanvas.mapRenderer().setDestinationSrs(coordRefSys) pass mapCanvas.freeze(False) mapCanvas.setMapUnits(coordRefSys.mapUnits()) #mapCanvas.setExtent(extMap) ########################################################################### def run(self): #reloadPlugin('Tilgjengelighet') """Run method that performs all the real work""" self.dlg.show() result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass <file_sep>/README.md A QGIS plugin to make easyer access to a database from kartverket, made as part for a master thiesis<file_sep>/FAKT_Dokumentasjon/_sources/project.rst.txt Filtrering og Analyse av Kartverkets Tilgjengelighetsdatabase ============================================================= Dette prosjektet er gjort i sammarbeid med Statens kartver som en del av min master avhandling. Tilleggsfunksjonen har som hensikt å gjøre det enklere å få tilgang til Kartverkets database for tilgjengelighet. Den er laget som en plugin til QGIS, slik at alle fylker har mulighet til å bruke den uten å betale for lisenser English: This project is made in association with the Norwegian Mapping Authority as a part of my master thesis. The application is ment to make it easyer to access the Norwegian Mapping Authority database for universal design. It is made within QGIS so all countys in Norway can get access to the application without paying any license. Innstalasjon ------------ Dersom tilleggsfunksjonen er tilgjengelig i plugin mangaer, kan du åpne pluginmanager of søke etter tilgjengleighet. Klikk på tilleggsfunksjonen og installer Dersom tilleggsfunksjonen ikke er tilgjengleig i plugin manger, kan den lastes ned fra https://github.com/KaspArno/Tilgjengelighet. Unzip filen, og legge mappen i :/.qgis2/python/plugins. Sørg for at mappen heter Tilgjengelighet, og ikke git-Tilgjengelighet eller noe annet, og at alle filene og undermappene ligger i denne mappen, og ikke i noen undermapper. Du burde nå kunne finne tilleggsfunksjonen i plugin manager. English: If the plugin is availeble in plugin manager, then open plugin manager and search for tilgjengelighet. Click on the plugin and install. If the plugin is not availeble in plugin manager, then you can download it from https://github.com/KaspArno/Tilgjengelighet. Download the file and unzip it in :/.qgis2/python/plugins. Make sure the folders name is Tilgjengelighet, and not git-Tilgjengleighet, ant that all files and dubfolders in in this filder. You should now be able to find it in plugin manager.<file_sep>/AttributeForm.py import operator class AttributeForm(object): """Saves attributes and assosiated gui widgets""" def __init__(self, attribute, location, comboBox=None, lineEdit=None, comboBoxText=None, label=None): """Constructor :param attribute: The name of the attribute in layer :type attribute: str :param comboBox: The associated comboBox :type comboBox: QComboBox :param lineEdit: The associated lineEdit :type lineEdit: QLineEdit :param comboBoxText: Alternative text for combobox :type comboBoxText: dict """ self.attribute = attribute self.location= location self.comboBox = comboBox self.lineEdit = lineEdit self.label = label self.alt_comboboxText = comboBoxText self.opperatorDict = {u'=' : 'PropertyIsEqualTo', u'<' : 'PropertyIsLessThan', u'>' : 'PropertyIsGreaterThan', u'<=' : 'PropertyIsLessThanOrEqualTo', u'>=' : 'PropertyIsGreaterThanOrEqualTo'} #attribute.opperator(), attribute.valueReference(), attribute.value() def opperator(self): """ :returns: the opperator for attriubutt qury :rtype: QString, None """ if self.comboBox is not None: if self.comboBox.currentText() in self.opperatorDict: return self.opperatorDict[self.comboBox.currentText()] else: return self.opperatorDict[u'='] else: return self.opperatorDict[u'='] def valueReference(self): """Returns the objekt attribute :returns: name of object attribute in database :rtype: str """ return self.attribute def getLocation(self): """returns the location of the object :returns: location of attribute :rtype: str """ return self.location def value(self): """returns the value constraint, if alternative combobox is set, return that value, if lineedit, ruturn value freom line edit, else return from combobox :returns: the value constraint :rtype: str """ if self.alt_comboboxText is not None: return self.alt_comboboxText[self.comboBox.currentText()] elif self.lineEdit is not None: return self.lineEdit.text() elif self.comboBox is not None: return self.comboBox.currentText() else: return None def setComboBox(self, comboBox): """Assigning comboBox :param comboBox: combobox assisiated to attribute :type comboBox: QComboBox """ self.comboBox = comboBox def setLineEdit(self, lineEdit): """Assigning lineEdit :param lineEdit: Linedit assisiated to attribute :type lineEdit: QLineEdit """ self.lineEdit = lineEdit def getComboBox(self): """ Returns the assosiated combobox widget :returns: returns the associated comboBox :rtype: QComboBox """ return self.comboBox def getComboBoxIndex(self): """ Returns the current index of combobox, retuns None if no combox :returns: returns the associated combobox index :rtype: int, None """ if self.comboBox: return self.comboBox.currentIndex() return None def getLineEdit(self): """Returns the assosiated lineEdit widget if any :returns: returns the associated lineEdit :rtype: QLineEdit """ return self.lineEdit def getLabel(self): """Returns the assisiated label widget if any :returns: returns the associated label :rtype: QLabel """ return self.label def getAttribute(self): """Returns the assosiated attriubte name :returns: returns the associated attribute name :rtype: str """ return self.attribute def getComboBoxCurrentText(self): """Returns the assosoated combobox text :returns: returns the associated comboBox text, return None if no combobox is availeble :rtype: QString """ if self.comboBox is not None: if self.alt_comboboxText: #If AttributForm has alternative text, return alternative text return self.alt_comboboxText[self.comboBox.currentText()] return self.comboBox.currentText() return None def getLineEditText(self): """Returns the lineEdit text :returns: returns the lineEdit text, return None if no lineEdit is availeble :rtype: QString """ if self.lineEdit is not None: return self.lineEdit.text() return None def setLineEditText(self, string): """Sett text in AttributeForm lineEdit :param string: String to set in lineEdit :type string: str """ if self.lineEdit is not None: self.lineEdit.setText(string) def valudeValid(self): """checks if the attribute is valid and search ready :returns: True if attrivute is valid, false if not :rtype: boolean """ if self.lineEdit is not None: if self.opperator() != 'PropertyIsEqualTo' and len(self.getLineEditText()) == 0: #opperator chosen, but no value print("IsValid 1") return False elif self.opperator() == 'PropertyIsEqualTo' and len(self.getLineEditText()) > 0: #value chosen, bu no opperator print("IsValid 2") return False elif len(self.getLineEditText()) > 0: print("len: {}".format(len(self.getLineEditText()))) print("IsValid 3") return self.is_number(self.getLineEditText()) #Valu not a number else: print("attribute is valid") return True def reset(self): """Resets form to defult""" if self.comboBox: self.comboBox.setCurrentIndex(0) if self.lineEdit: self.lineEdit.setText("") def is_number(self, s): """Sett text in AttributeForm lineEdit :param s: string to be change for being a number :type s: str :returns: tru if s is number, false if s in not a number :rtype: boolean """ print("s: {}".format(s)) print("type: {}".format(type(s))) try: float(s) return True except ValueError: return False<file_sep>/infowidgetdialog.py import os from PyQt4 import QtCore, QtGui, uic FORM_CLASS, _ = uic.loadUiType(os.path.join( os.path.dirname(__file__), 'ui/infoWidget.ui')) class infoWidgetDialog(QtGui.QDockWidget, FORM_CLASS): def __init__(self, parent=None): super(infoWidgetDialog, self).__init__(parent) #QtGui.QDockWidget.__init__(self) #self.ui = testDock() self.setupUi(self) <file_sep>/FAKT_Dokumentasjon/_sources/FAKT_Dokumentasjon.rst.txt .. Filtrering og Analyse av Kartverkets Tilgjengelighetsdatabase file, created by sphinx-quickstart on Tue May 22 14:11:46 2018. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Velkommen til Filtrering og Analyse av Kartverkets Tilgjengelighetsdatabase's dokumentasjon! ============================================================================================ .. toctree:: :maxdepth: 2 :caption: Innhold: project code Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` <file_sep>/SavedSearch.py class SavedSearch(object): """Class made to save the choises made by user on a previus search""" def __init__(self, search_name, layer, tabIndex_main, tabIndex_friluft, tabIndex_tettsted): """Constructor :param search_name: The name of the search made (layer name) :type search_name: str :param layer: The layer or result from search :type layer: QgsVectorLayer :param tabIndex_main: Main tab index at search :type tabIndex_main: int :param tabIndex_friluft: friluft tab index at search :type tabIndex_friluft: int :param tabIndex_tettsted: tettsted tab index at search :type tabIndex_tettsted: int """ self.search_name = search_name #Name of layer self.layer = layer #Layer self.layer_id = self.layer.id() #self.lineEdit_seach = lineEdit_seach self.tabIndex_main = tabIndex_main #Main tab index self.tabIndex_friluft = tabIndex_friluft #Friluft tab index self.tabIndex_tettsted = tabIndex_tettsted #Tettsted tab index self.attributes = {} #attributes used in search (combobx index and lineEdit text stored in list as dictionary valu, AttributeForm is stored as Key) def add_attribute(self, attribute, current_index, current_lineText): """Add attribute with current index for combobx and current text for lineText Attributes are stored in dictionarys as key, while value is list of combobox indes and lintEdtid text :param attribute: one attribute from filter interface :type attribute: AttributeForm :param current_index: index of combobx at search :type current_index: int :param current_lineText: text of lineEdit at search :type current_lineText: str """ self.attributes[attribute] = [current_index, current_lineText] def get_attributes(self): """Returns dictionary of attributes :returns: dictionary of attributes :rtype: list<AttributeForm> """ return self.attributes def get_layer(self): """Returns layer :returns: layer :rtype: QgsMapLayer """ return self.layer def get_id(self): """Returns layer id :returns: layer.id() :rtype: String """ return self.layer_id<file_sep>/FAKT_Dokumentasjon/_modules/SavedSearch.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>SavedSearch &#8212; Tilgjengelig For Alle 0.1 documentation</title> <link rel="stylesheet" href="../_static/alabaster.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="stylesheet" href="../_static/custom.css" type="text/css" /> <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" /> </head><body> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <h1>Source code for SavedSearch</h1><div class="highlight"><pre> <div class="viewcode-block" id="SavedSearch"><a class="viewcode-back" href="../code.html#SavedSearch.SavedSearch">[docs]</a><span></span><span class="k">class</span> <span class="nc">SavedSearch</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Class made to save the choises made by user on a previus search&quot;&quot;&quot;</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">search_name</span><span class="p">,</span> <span class="n">layer</span><span class="p">,</span> <span class="n">tabIndex_main</span><span class="p">,</span> <span class="n">tabIndex_friluft</span><span class="p">,</span> <span class="n">tabIndex_tettsted</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Constructor</span> <span class="sd"> :param search_name: The name of the search made (layer name)</span> <span class="sd"> :type search_name: str</span> <span class="sd"> :param layer: The layer or result from search</span> <span class="sd"> :type layer: QgsVectorLayer</span> <span class="sd"> :param tabIndex_main: Main tab index at search</span> <span class="sd"> :type tabIndex_main: int</span> <span class="sd"> :param tabIndex_friluft: friluft tab index at search</span> <span class="sd"> :type tabIndex_friluft: int</span> <span class="sd"> :param tabIndex_tettsted: tettsted tab index at search</span> <span class="sd"> :type tabIndex_tettsted: int</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="bp">self</span><span class="o">.</span><span class="n">search_name</span> <span class="o">=</span> <span class="n">search_name</span> <span class="c1">#Name of layer</span> <span class="bp">self</span><span class="o">.</span><span class="n">layer</span> <span class="o">=</span> <span class="n">layer</span> <span class="c1">#Layer</span> <span class="c1">#self.lineEdit_seach = lineEdit_seach</span> <span class="bp">self</span><span class="o">.</span><span class="n">tabIndex_main</span> <span class="o">=</span> <span class="n">tabIndex_main</span> <span class="c1">#Main tab index</span> <span class="bp">self</span><span class="o">.</span><span class="n">tabIndex_friluft</span> <span class="o">=</span> <span class="n">tabIndex_friluft</span> <span class="c1">#Friluft tab index</span> <span class="bp">self</span><span class="o">.</span><span class="n">tabIndex_tettsted</span> <span class="o">=</span> <span class="n">tabIndex_tettsted</span> <span class="c1">#Tettsted tab index</span> <span class="bp">self</span><span class="o">.</span><span class="n">attributes</span> <span class="o">=</span> <span class="p">{}</span> <span class="c1">#attributes used in search (combobx index and lineEdit text stored in list as dictionary valu, AttributeForm is stored as Key)</span> <div class="viewcode-block" id="SavedSearch.add_attribute"><a class="viewcode-back" href="../code.html#SavedSearch.SavedSearch.add_attribute">[docs]</a> <span class="k">def</span> <span class="nf">add_attribute</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">attribute</span><span class="p">,</span> <span class="n">current_index</span><span class="p">,</span> <span class="n">current_lineText</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Add attribute with current index for combobx and current text for lineText Attributes are stored in dictionarys as key, while value is list of combobox indes and lintEdtid text</span> <span class="sd"> </span> <span class="sd"> :param attribute: one attribute from filter interface</span> <span class="sd"> :type attribute: AttributeForm</span> <span class="sd"> :param current_index: index of combobx at search</span> <span class="sd"> :type current_index: int</span> <span class="sd"> :param current_lineText: text of lineEdit at search</span> <span class="sd"> :type current_lineText: str</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="bp">self</span><span class="o">.</span><span class="n">attributes</span><span class="p">[</span><span class="n">attribute</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="n">current_index</span><span class="p">,</span> <span class="n">current_lineText</span><span class="p">]</span></div> <div class="viewcode-block" id="SavedSearch.get_attributes"><a class="viewcode-back" href="../code.html#SavedSearch.SavedSearch.get_attributes">[docs]</a> <span class="k">def</span> <span class="nf">get_attributes</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Returns dictionary of attributes</span> <span class="sd"> </span> <span class="sd"> :returns: dictionary of attributes</span> <span class="sd"> :rtype: list&lt;AttributeForm&gt;</span> <span class="sd"> &quot;&quot;&quot;</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">attributes</span></div></div> </pre></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"><div class="relations"> <h3>Related Topics</h3> <ul> <li><a href="../FAKT_Dokumentasjon.html">Documentation overview</a><ul> <li><a href="index.html">Module code</a><ul> </ul></li> </ul></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer"> &copy;2018, <NAME>. | Powered by <a href="http://sphinx-doc.org/">Sphinx 1.7.4</a> &amp; <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.10</a> </div> </body> </html>
c6a9f96af07c9f922a4b05671f7dc3e6077bae17
[ "Markdown", "Python", "HTML", "reStructuredText" ]
10
HTML
enzococca/Tilgjengelighet
c0da54d78da5135fcb6528e71598040591f16c2d
2a15b099e45f3e5508a8d7be90361370213f81f4
refs/heads/main
<repo_name>JGHernandez7/c-sharp-practice<file_sep>/stringReverse.cs using System; public class ReverseString { public static void Main() { string[] s = "to the moon and back".Split(' '); string temp = ""; for (int i = s.Length - 1; i >= 0; i--) temp += s[i] + " "; Console.Write("Reversed String: "); Console.Write(temp.Substring(0, temp.Length - 1)); } }<file_sep>/README.md # c-sharp-practice Practicing C# problems. <file_sep>/combineStrings.cs using System; class CombineStrings { private static string combine(string a, string b) { string result = ""; for (int i = 0; i < (a.Length > b.Length ? a.Length : b.Length); i++) { if (i < a.Length) { result += a[i]; } if (i < b.Length) { result += b[i]; } } return result; } public static void Main(string[] args) { Console.WriteLine(combine("Guadalupe", "Hernandez")); Console.WriteLine(combine("Hernandez", "0000000")); } }
0631925a649f23d2f98b9e37874e6455d9657d60
[ "Markdown", "C#" ]
3
C#
JGHernandez7/c-sharp-practice
ec4befdb7816a67777647834d809ee63c5001ed9
ddfda5d95bb43632ca1d8d165c17a9436c6346dd
refs/heads/master
<repo_name>maxwell-oroark/component-library<file_sep>/lib/index.js import Grid from './elements/Grid'; module.exports = { Grid }; <file_sep>/lib/elements/Grid.js import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; const GridItem = styled.div` width: ${({gridItemWidth}) => gridItemWidth }; height:${({gridItemHeight}) => gridItemHeight }; color: ${({gridItemColor}) => gridItemColor }; background-color: ${({ backgroundColor }) => backgroundColor }; ` const GridContainer = styled.div` display: grid; grid-template-columns: ${({ columns }) => "1fr ".repeat(columns) }; grid-template-rows: ${({ rows }) => "1fr ".repeat(rows) }; width: ${({ width }) => width }; height: ${({ height }) => height }; padding: ${({ padding }) => padding }; margin: ${({ margin }) => margin }; height: ${({ border }) => border }; ` const Grid = (props) => { return ( <GridContainer { ...props }> { props.children.map( ( gridItem, i) => ( <GridItem gridItemHeight={ props.gridItemHeight } gridItemWidth={ props.gridItemWidth } backgroundColor={ props.gridItemBackgroundColor } gridItemColor={ props.gridItemColor } key={ `container-${i}` } > { gridItem } </GridItem> )) } </GridContainer> ) } Grid.propTypes = { gridItems: PropTypes.array.isRequired, gridTemplateColumns: PropTypes.string.isRequired, gridTemplateRows: PropTypes.string.isRequired }; export default Grid; <file_sep>/README.md # Simple React CSS Grid ## Simple Usage This grid component seeks to leverage the new CSS grid specification in a lightweight and manageable way. By eschewing most of the features and functionality of CSS grid, we can get up and running quickly and predictably. ``` <Grid columns={3} rows={2} height={"500px"} width={"500px"}> gridItemHeight={"200px"} gridItemWidth={"200px"} { gridItems.map( item => ( <Item itemTitle={item.title} itemDescription={item.description} /> ) } </Grid> ```
c975ba55c0a71b62ad092566afa0813e07c7a7de
[ "JavaScript", "Markdown" ]
3
JavaScript
maxwell-oroark/component-library
1a45b28b70eac15e75d2c7d60039ee1f2e95895c
ed10b564b0b24f690259de30bf3fe4d48006d1b4
refs/heads/main
<file_sep>list = [1,3,5,10,20] k = 3 #poziciya c = 5 list.insert(k,c) print(list) <file_sep>try: string = '1' number = 1 print(string + number) except TypeError: print('error') list1 = [1,2,3,4] try: for i in range(10): print(list1[i]) except IndexError: print('Vyvyshli za gran spiska!')<file_sep># isem znak 4isla phone="0558573883" email="<EMAIL>" password="<PASSWORD>" check_input=input ("phone or email: ") #vybiraem 4to vvodit if check_input=="phone": phone_check=input("vvedite telefon:" ) #vvodim telefon password_check=input("vvedite parol:") if phone_check == phone and password_check == password: print("Vy vosli v sistemu!") else: print(" Vy vveli ne verno") elif check_input == "email": email_check = input("vvedite email:") # vvodim emal password_check = input("vvedite parol:") if email_check == email and password_check == password: print("Vy vosli v sistemu!") else: print(" Vy vveli ne verno") i<file_sep> # Дан список строк(письма пришедшие на почту). Требуется написать: функцию которая будет # записывать строки в файл, каждая новая строка начинается с новой строки, функцию которая # будет считывать содержимое файла, все строки которые относятся к спаму, следует записывать # в новый файл(пример: строка начинается: «Buy right now!», «Sales», строки которые содержат # имя пользователя – «Emma» , но не содержатся слова с мольбами о помощи нужно добавить в # другой файл, строки где содержатся слова “help” или “SOS” или начинаются с “Dear” нужно # добавить в другой файл. Добавление файлов и создание начальных функций закончено! strings = ['hello Emma, how are u?', 'Dear Emma, please fix production', 'SALES lining sales','buy right now dont lose your chance', 'Emma help me please','Emma SOS production is down'] def write_to(): with open('mail.txt','w') as file1: for mail in strings: file1.write(mail.lower() + '\n') write_to() def mail_check(): with open('mail.txt') as file1: f1 = file1.readlines() for spam in f1: if spam.startswith('buy right now!') or spam.startswith('sales'): file2 = open('spam.txt','a') file2.write(spam+ '\n') elif spam.startswith('dear') or 'sos' in spam or 'help' in spam: file3 = open('work.txt','a') file3.write(spam+ '\n') else: file4 = open('my_mail.txt', 'a') file4.write(spam+ '\n') print(mail_check()) mail_box = [] <file_sep>number1=5.2222 number2=5 number3='5' number4=number1>number2 print(type(number1),type(number2),type(number3),number4)<file_sep>string1 = 'localization' if len(string1)>10: str_len = str(len(string1)-2) result = string1[0]+str_len+string1[len(string1)-1] print(result) else: print(string1) # <file_sep># find gipotenuza pre a and b import math a= int(input()) b= int(input()) result=(a**2)+(b**2) # isem sum kvadratov square=math.sqrt(result) # nahodim kvadratnyi koren' print(square ) <file_sep>a=float(input()) b=float(input()) if a<b: print(a) else: print(b)<file_sep>num_list = [1,-2,3,-4] i = 0 while i < len(num_list): if num_list[i] > 0: print(num_list[i]) i += 1<file_sep>user_name = "Maksim" password = "<PASSWORD>" i = 0 while i < 5: login = input("Введите имя пользователя:") check_passord = input ("Введите пароль:") if login == user_name and check_passord == password: print("Вы вошди в систему!") break else: print("Вы ввели неверные данные!") i = i + 1 <file_sep>numbers = [1,3,5,4,6,2,8,9,7] prime_numbers = [] non_prime_numbers = [] i = 0 while i < len(numbers): if numbers[i] % 2 == 0: prime_numbers.append(numbers[i]) else: non_prime_numbers.append(numbers[i]) i += 1 print(f'Obshii spisok {numbers}') print(f'4etnye 4islami: {prime_numbers}') print(f'Ne4etnye 4isla: {non_prime_numbers}') <file_sep>import random product_list = ['asus','acer','iphone','samsung','intel hd', 'nvidia','adata','kingston','macbook','xiomi', 'iMac','amd','apacer'] def register(login,password,check_password): register_list = [] if password == check_password: code = random.sample([1,2,3,4,5,6,7,8,9,0],4) register_list.append(login) register_list.append(password) return register_list else: return 'Nepravelnye dannie' user = (register('user','123456','123456')) username = user[0] password = user[1] print(username,password) def check_login(login,password): if username == login and password == password: print('Vy voshli v sistemu!') else: print('Nepravelnye dannye!') check_login('user','123456') def write_to(): file1 = open('product_list.txt', 'w') for product in product_list: file1.write(product + '\n') write_to() #5 def write_product(product_list): with open('product_list.txt', 'w') as file1: for product in product_list: file1.write(product + '\n') write_product(product_list) def sort_list(product_list): with open('product_list.txt', 'w') as file2: f2 = file2.readlines() for product in f2: if product == 'asus' or product == 'acer' or product == 'macbook' or product == 'iMac': file1 = open('computers.txt','w') file1.write(product) elif product == 'iphone' or product == 'samsung': file2 = open('phones.txt,', 'w') file2.write(product) elif product == 'intel_hd' or product == 'nvidia' or product == 'amd': file3 = open('video cart.txt', 'w') file3.write(product) elif product == 'adata' or product == 'kingston' or product == 'apacer': file4 = open('jestkii_diski.txt', 'w') file4.write(product) sort_list(product_list) <file_sep>#ishem znak 4isla number=int(input()) if number>0: # esli 4islo >0 print(1) elif number<0: #esli 4islo <0 print(-1) else: print(0) #4islo==0<file_sep>username_list = [] password_list = [] i = 1 while i <= 2: username = input('Vvedite imya polzovatelya:') password = input('<PASSWORD>:') username_list.append(username) password_list.append(password) print(f'Polzovatel pod nomerom {i} zaregistripovan') i = i + 1 print(username_list) print(password_list)<file_sep>def millionaire(): answer_list = ['shekspir','pushkik','bunin','bulgakov'] true_answer = 'bulgakov' print('Otvette na vopros: Kto napisal Master i Margarita?') print('Varianty otvetov:',answer_list) help = input('Nujny varianty podskazki?') if help == 'da': poll = input('U vas 3 podskazki: 50/50,zvonok drugu,pomosh zala') if poll == '5050': for i in range(2): if answer_list[i] != true_answer: answer_list.remove(answer_list[i]) print(answer_list) my_answer = input('Vvedite svoi otvet:') if my_answer == true_answer: return 'Pravelnyi otvet' else: 'Vy otvetili ne verno' elif poll == 'pomosh zala': help_list = [] for i in range(6): help_list = input('Vvedite pomosh zala:') help_list.append(true_answer) print(help_list) my_answer = input('vvedite svoi otvet:') if my_answer == true_answer: return 'Vy pobedili' else: return 'Ne verniy otvet' elif poll == 'Zvonok drugu:': call_answer = input('Vvedite otvet na vopros:') print(call_answer) my_answer = input('Vvedite svoi otvet:') if my_answer == true_answer: return'Vypobedili' else: return 'Ne verno' else: print('Vvedite da ili net') print(millionaire())<file_sep>products = ['bread','meat','egg','cheese'] file1 = open('products.txt','w') for product in products: file1.write(product+'\n') file1.close() file2= open('products.txt') var = file2.readlines() print(var) <file_sep>def relation_to_Luke(name): if name == 'Darv': return 'Luke, I am your father' elif name == 'Leila': return ' Luke, i am your sister' elif name == 'Han': return ' Luke, i am your brother' print(relation_to_Luke('Leila'))<file_sep>w = int(input('Vvedite kolli4estvo kg: ')) if 1<= w <= 100: if w % 2 == 0 and w > 2: print("ravnie doli!") else: print('Vyvyshli s ramki')<file_sep>list1 = [1,1,1,1,1,2,2,3,3,5,5,6] print(list1) def count_list(number): j=0 for list_number in list1: if list_number == number: j+=1 print(j) count_list(1) <file_sep>day_plan = ['eat','walk','study','sleep'] plan_len = len(day_plan) i = 0 # s4et4ik while i < plan_len: action = input('Vvedite plan deistviya:') if action in day_plan: act_index = day_plan.index(action) # nahodim index nashego deistviya if act_index == 0: # deistvie v preoritete day_plan.remove(action) # delo sdelano vy4erkivaem iz deistviya i += 1 else: print('Ne zaplanirovannye dela') else: print('Vy eto ne planirovali!') print(f'ostavshiesya dela{day_plan}') <file_sep># prog imeet spisoki vyvodit spisok iz 3 elementov;1go ,3go i vtorogo s konca list1 = ['1','2','3','4','5'] print(list1[0]) print(list1[2]) list_len = len(list1) print(list1[list_len-2]) <file_sep>n=int(input()) print(n//10%10)<file_sep># 22. В форме интернет-магазина пользователю нужно ввести свой номер телефона. # Номер телефона состоит из 10 цифр, однако некоторые пользователи вводят его в формате # +996558588086, некоторые - 996550588086, а некоторые и вовсе вводят только 9 цифр (без первой) 558588086. # Вам необходимо привести номер к стандарту +996558588086 phone = input() if phone.startswith('996'): phone = '+'+ phone print(phone) elif phone.startswith('+996'): print(phone) elif not phone.startswith('+996') and not phone.startswith('0') and len(phone) < 9: phone = '+996'+phone print(phone) else: print('Vvedite pravelnye dannye!') <file_sep>name = '<NAME>' print(name[::-1])<file_sep>text = 'privit Zarina,kak dela?' check = text.find('Zarina') if check >0: print('Klassno') elif check<0: print('nado porabotat')<file_sep>number_list = [1,2,3,4,5,6] k= 5 # poziciya number_list.pop(k) print(number_list)<file_sep>perviy = 5 * (2**2) result = x * (2**y) # perevodim v functiyu!!!!!!!!!!!!!!!!!!!!!!! print(result)<file_sep># skidki na tovar price1=int(input()) price2=int(input()) maximum=max(price1,price2) # modul' max print(maximum)<file_sep>string = 'hhhhello' h_lfind = string.find('h') h_rfind = string.rfind('h') string<file_sep>taxi_za_4as = 10 ojidanie = 0 oplata = ojidanie + taxi_za_4as proezd = int(input("k oplate:")) if ojidanie >= 0: ojidanie = taxi_za_4as - oplata plata = ojidanie + taxi_za_4as print(plata) elif ojidanie: print(proezd) <file_sep>mail = "dhhhhhhhhhhhhhhhhhhhjkl Sales lknnnnnnnnnnn" spam ="Sales" sending = False if spam not in mail: sending = True print(sending) else: print("Eto spam!", sending) <file_sep> file1 = open('test.txt','a') file1.write('student') for number in [1,-2,3,-4]: if number > 0: print(number)<file_sep>def open_file(filename,text): with open(filename,'a') as file2: file2.write(text.capitalize()) strings = ['hello Emma, how are u?', 'Dear Emma, please fix production', 'SALES lining sales','buy right now dont lose your chance', 'Emma help me please','Emma SOS production is down' 'Sales nike boots hurry up',''] def write_to(strings:list): with open('email.txt','w') as file1: for mail in strings: file1.write(mail.lower()+'\n') def open_file(filename,text): with open(filename,'a') as file2: file2.write(text.capitalize()) write_to(strings) def sort(): with open('email.txt') as file3: mail_list = file3.readlines() for mail in mail_list: if mail.startswith('sales') or mail.startswith('buy right now'): open_file('spam.txt',mail) elif mail.startswith('dear') or 'help' in mail or 'sos' in mail: open_file('work.txt',mail) else: open_file('emma.txt',mail) sort()<file_sep># in eto sravnivanie po4ti kak == sentence = 'hello' print('hello' in sentence) <file_sep>x=float(input()) x_int=int(x) print(x_int) result=x-x_int print(int(result*10)) <file_sep># find digits of number number=int(input()) hund=number//100 #find hundreds print(hund) tens=number//10%10 #find tens print(tens) digits=number%100%10 #find digit print(digits) print(hund+tens+digits) <file_sep>list = [1,2,3,4] test_list = list1 test_list.reverse() print(list) <file_sep>list = ['table','chair','sofa','couch'] list.remove('table') print(list) <file_sep>dictionary = {'name': 'Zarina','email': 'gmail.com'} perchase = ['email'] for item in dictionary: print(dictionary[item])<file_sep>product_list = ['bread','cheese','egg','meat'] # buterbrod 0+1 # biphsteks 2+3 # gamburger 0+2+3 # 4isburger 0+1+2+3 cook_list = [] print('U vas imeyutsya takie produkty:', product_list) product = input('Vozmte product:') i = 0 while product != '0' and i <= len(product_list): if product in product_list: cook_list.append(product) else: print('Ispolzuyte producty s tarelki!') product = input('Vozmit product:') i += 1 j = 0 butter = ['bread', 'cheese'] biff = ['meat', 'egg'] ham = [' bread', 'egg', 'meat'] ch_ham = [' bread', 'cheese', 'egg', 'meat'] #product1 =[] #product2= [] #product13 =[] #product4 = [] if len(cook_list) == len(butter): j = 0 while j < len(cook_list): if cook_list[j] in butter: j += 1 else: print('vy dali mne ne vernyi product:') break if j == len(butter): print('Vy mojete prigotovit buter') elif len(cook_list) == len(ham): j = 0 while j < len(cook_list): if cook_list[j] in biff: j += 1 else: print('vy dali mne ne vernyi product:') break if j == len(biff): print('Vy mojete prigotovit buter') elif len(cook_list) == len(cook_list): j = 0 while j < len(cook_list): if cook_list[j] in ham: j += 1 else: print('vy dali mne ne vernyi product:') break if j == len(ham): print('Vy mojete prigotovit buter') elif len(cook_list) == len(cook_list): j = 0 while j < len(cook_list): if cook_list[j] in ch_ham: j += 1 else: print('vy dali mne ne vernyi product:') break if j == len(ch_ham): print('Vy mojete prigotovit buter')<file_sep>products = {'gucci boots': 10000, 'channel': 20000, 'adidas boots': 8000, 'nike sport-suit': 23000, 'gucci sport-suit': 24000, 'Lonsdale suit': 8000, 'nike boots': 9000, 'dior chest': 10000, 'raben waist': 15000, 'wedding dress': 500000} user = 'user' password = '<PASSWORD>' def check_login(login, password): if len(login) < 20 and user == login and password == password and not password.isalpha() and not password.isdigit(): print('Vy voshli v sistemu!') else: print('Nepravelnye dannye!') check_login('user', 'user123456') def counter(money, price): if money > price: money = money - price return money else: return 'Ne dostatochno sredst!' def cart(): cart_list = [] for i in range(3): product = input('Vvedite nazvanie tovara: ') if product in products: cart_list.append(product) return cart_list test_cart = cart() def wallet(money): test_cart1 = [] for line in test_cart: if money >= products[line]: money = counter(money, products[line]) test_cart1.append(line) return {'4to ya hotel kupit:':test_cart1, 'Konechniy vybor:': test_cart, 'Sdacha:':money} print(wallet(50000))<file_sep>import random file1 = open('players.txt','w') for i in range(4): cost = random(2,11) + random.randint(2,11) check = input(f'Vasha ruka: {cost} Nujna eshe karta? Da ili net') if check == 'da': cost = cost + random.randint(2,11) elif check == 'Net': cost = cost else: print('Otvet to4no') cards.append (cost) print(cards) i = 0 while i < len(cards): if cards [i] > 21: cards [i] = 0 i +=1 max_cost= max(cards) max_index = cards.index(max_cost) winner = players_list[max_index] print(f'Vstre4aite pobeditelya!{winner}') <file_sep>course=(input()) Example=(input()) Day1=input("Started day:12.10.20") print("Course:",course) print("Lesson 1: Introduction") print("Lesson 2:", Example) print(Day1) <file_sep>login=input('input you login: ') password=input("input you password: ") repeat_password=input("input you password: ") if password==<PASSWORD>: print("Try again") else: print("Welcome")<file_sep>money = int(input("Vvedite vasu summu:")) boots = 3000 wear = 4500 scarf = 900 product = input("Vvedite tovar dlya pokupki (boots wear scarf)") if product == "boots": if money >= boots: print("spasibo") else: print("Nedostato4no sredtv") elif product == "wear": if money >= wear: print("spasibo") else: print("Nedostato4no sredtv") elif product == "scarf": if money >= scarf: print("spasibo") else: print("Nedostato4no sredtv")<file_sep>i = 1 while True: print(i) i += 1 if i == 1000000000: print('Vy vyigrali mln') break<file_sep>import reguests def send_simple_message(): return requests.post( "https://api.mailgun.net/v3/sandboxcfcfbe65c9814d799bb34688336e685c.mailgun.org/messages", auth=("api", "<PASSWORD>"), data={"from": "<EMAIL>", "to": ["<EMAIL>"], "subject": "Hello", "text": "Testing some Mailgun awesomness!"}) send_simple_message()<file_sep>student_list = ['zarina','emir','bayza', 'nazira'] current_list = [] i = 0 student_len = len(student_list) come_in = 1 while come_in != '0': come_in = input('vvedite imya studenta:') if come_in not in current_list: #prishedshii if come_in in student_list: # proveryaem current_list.append(come_in) # dobavim studenta print('prishel') else: print('takogo studenta net') else: print('student uje prishol') print(current_list)<file_sep> def translator(en_word): if en_word == 'dog': print('sobaka') elif en_word == 'kat': print('koshka') translator('dog') <file_sep>sum_km = 10 wait = 2 path = int(input('Put:')) cost = 40 wait_status = input('Voditel ojidaet:') come_status = input('Klient jdet:') i = 1 while come_status != 'True': cost = cost + wait i = i + 1 come_status = input('Klient jdet:') cost = cost + (path * sum_km) print(cost)<file_sep>login=input() result=len(login)>20 print(result)<file_sep>a=5 b=4 if a>b: print("nape4atai a:", a) else: print("nape4ataei b",b)<file_sep># ogoggo shop list1 = [' acer', 'acus', 'lenovo', "sony"] list2 = [ 13,12,14,17] max_of_list2 = max(list2) # naibolshee 4islo pokupok index_list2 = list2.index(max_of_list2) # nahodim poziciyu elementa max_of_list2 print(f'noutbuk: {list1[index_list2]} pokupali: {max_of_list2} raz') <file_sep>user_db = '' password_db = '' def register(username,password,repeat_password): if password == repeat_password: user_db = username password_db = password return user_db,password_db else: return 'Paroli ne sovpadaut!' print(register('zarina','123456','1234567')) <file_sep>sentence="lets escape" ban_word= "escape" if ban_word in sentence: print("Not allowed to access") else: print("Allowed to access")<file_sep># string = '<NAME>' for line in string.split(): print(line)<file_sep>string = 'sdobrymutrombishkek' if string.istitle() and len(string)<10: string = string.upper() print(string) elif string.istitle() and len(string)<10: string = string.lower() print(string) elif len(string)>10: string= string.capitalize() print(string) <file_sep>money = int(input("VVedite vasu summu")) product_price = 3000 if money > product_price: result = money - product_price print(" Vasa sda4a", result) elif money == product_price: print(" Spasibo za pokupku!") else: print( "U vas ne dostato4no sredstv")<file_sep># string = '<NAME>' check = string.split() count = string.count(' ') print(check) print(count+1)<file_sep>list1 = [1,2,3,4] def change_list(mode,number): if mode == 'remove': list1.remove(number) elif mode == 'add' and number in list1: list.append(number) else: print('Vy vveli nevernie dannie') change_list('remove',1) change_list('add',1) print(list1) <file_sep>number=int(input()) if number% 2==0: print("Yes") else: print("No")<file_sep>username=input( "Full name:") len_username=len(username) if len_username<20: print("May enter:") else: print("May not enter") <file_sep>bmw = 20 merc = 18 fit = 9 fuel = int(input("Запрвьте авто:")) i =0 while i <3: auto = input("Введите наименования авто для тестирования:") result= 0 final = 0 path = 240 if auto == "bmw": result = path / 100 result = bmw * result # кол литров расхода поезки на Ы-К final = fuel - result if final >0: print(f'После поездки остаток:{final} литров') else: result = 100 // bmw # расход 1 литров на км result = result * fuel path = path - result print(f"(Вам осалось ехать: {round(path)}км ") elif auto == "merc": result = path / 100 result = merc * result # кол литров расхода поезки на Ы-К final = fuel - result if final > 0: print(f"(После поездки остаток: {final} литров") else: result = 100 // merc # расход 1 литров на км result = result * fuel path = path - result print(f"(Вам осалось ехать: {round(path)}км") elif auto == "fit": result = path / 100 result = fit * result # кол литров расхода поезки на Ы-К final = fuel - result if final > 0: print(f"После поездки остаток: (round{final}) литров") else: result = 100 // fit # расход 1 литров на км result = result * fuel path = path - result print(f"(Вам осалось ехать: {path} км") <file_sep>hour_salary = 70 salary = 0 # na4alnaya zaplata work = int(input("VVedite koli4estvo 4asov:")) work_day = 8 if work > 1 and work <= 24: if work > work_day: check = work - work_day salary = (work_day * hour_salary) + ((check * hour_salary)*2) print(f"Vasha zarplata z segodnya: {salary}$") else: salary = hour_salary * work print(f"Vasha ZP za segodnya: {salary}") else: print(" Vresh!") <file_sep>new_list = [1,2,3, "red", "yellow", "green"] new_list.append("test-append") print(new_list )<file_sep>username = 'user' password = '<PASSWORD>' def login(login,check_password): if username == login and password == check_password: print('Vy voshli v sistemu!') else: print('Ne vernye dannye') login('user','<PASSWORD>') # eto vyzov funciyu bez nee ne vozmojno zaiti <file_sep>time = int(input()) breakfast = False lunch = False dinner = False if 0<=time<24: if 8<=time<12: breakfast = True print(f"Zaftrak!{breakfast}", lunch, dinner) elif 12<=time<16: lunch = True dinner = True print(f"Ugin! {lunch}", dinner, breakfast) else: print("My ne rabotaem") else: print("Vy s drugoi planety") <file_sep>new_list = ['Peperroni', 'Havali', 'Meat', 'Checken'] new_list.remove("Peperroni") # udalyaet opredelennyi elemet new_list.pop() # udalyaet posledniy element new_list.pop(1) #udalyaet poziciyu elementa print(new_list)<file_sep>string = 'emir','zarina','baizak','nazira' string = string.replace('emir','vanya') print(string) <file_sep>x=5.9 x_int=int(x) print(x_int)ф result=x-x_int print(result) print(int(result*10)) <file_sep>list = ['yellow', 'red', 'brawn', 'green'] i = 0 while i < len(list): if i % 2 == 0: print(f'$etnyi index{i}:', list[i]) i += 1 <file_sep>string = '122' print(len(string)) number = '122' str_number = str(number) print(str_number)<file_sep>number1=int(input()) number2=int(input()) check=number1!=number2 print(type(check)) print(check)<file_sep>def translator(): print("Vyberite kak perevoditsya koshka: [{'cat','dog'}]") answer = input('Vvedite otvet:') if answer == 'kat': print('pravilno!') else: print('Ne pravilno!') translator() <file_sep>score_list = [] score = 1 while score != 0: score = int(input('vvedite ocenku rebenka:')) if 0 < score <= 5: score_list.append(score_list) if score == 5: print('molodec!') elif score == 4: print('neploho') if score == 3: print('staraisya!') elif score == 2: print('poluchish') elif score == 1: print(';(((((') else: print('Nepravilnaya ocenka') print(score_list) summary = sum(score_list) print(summary/len(score_list))<file_sep>path = 240 v= int(input("Vvedite ob'em benzobaka:")) result = path /100 fuel = v - (result*12) if fuel >1: print(f"Vy doehali do mesta nazna4eniya u vas ostalos': {round(fuel)} litr(a) benzina") else: result = 100/12 result1 = result * v print(f" u vas zakon4itsya benzin na {round(result)} kilometre!") <file_sep>def max_number(number1,number2,number3): max1= max(number1,number2) max2= max(max1,number3) print(max2) max_number(5,4,3) def min_number(number1,number2,number3): min1= min(number1,number2) min2= min(min1,number3) print(min2) min_number(5,4,3) <file_sep>numbers = [1,2,3,4,5,6] for number1 in range(1,4): for number2 in range(1,4): print(f'Pervoe 4islo= {number1}, Vtoroe 4islo = {number2}')<file_sep>numbers = [1,'red', 2,3,'yellow', 12.4,[7, 11.5]] int_list = [] float_list = [] str_list = [] i = 0 while i < len(numbers): if isinstance(numbers[i], str): str_list.append(numbers[i]) elif isinstance(numbers[i],float): float_list.append(numbers[i]) else: int_list.append(numbers[i]) i += 1 print(f'Obshii spisok{numbers}') print(f'Spisok soderjasii stroki:{str_list}') print(f'Spisok soderjasii celye 4isla:{int_list}') print(f'Spisok soderjasii drobnye 4isla:{float_list}')<file_sep>list1 = [1,2,3,4,5,6] def change_list(mode,number): if mode == 'remove': list1.remove(number) elif mode == 'add' and number in list1: list1.append(number) elif mode == 'pop': list1.pop(number) else: print('Vy vveli nevernie mod') change_list('remove',1) change_list('add',1) change_list('pop',2) print(list1)<file_sep># vhod v sistemu ispol'zuya logi4eskiy I login="username" password="<PASSWORD>" login1=input("Vvedite imya pol'zovayelya:" ) password1=input("vvedite parol:") if login1==login and password==password: print("Vy vosli v sistemu") else: print(" Ne udalos voiti. Proverte pojaluysta!")<file_sep>password= input("Put your password:") len_password=len(password) if len_password>=8: print("ok") else: print("not") <file_sep>colours = ["red", "yellow","green", "blue"] i = 0 while i < len(colours): print(f'Krug cikla {i}', colours[i]) i += 1
9c08f3ff53e54b1cf6c39ceca9fc204d1573538c
[ "Python" ]
83
Python
zarina494/fisrt_git_lesson
169fc205b3a99a84f1041d578c4c120555162a66
5538a3294dbb497cda8b3b18a51a870413514649
refs/heads/master
<file_sep>//! # Equality constraints for types //! //! `is_type` gives the trait `Is<X>` which acts like an equality constraint. //! //! There's also functions to move between these two equivalent types, //! as Rust will still not realise these types are //! //! The constraint `X : Is<Y>` requires that `X` == `Y`. //! //! The idea was stolen from //! [this comment on equality constraints in where clauses] which //! contains an example use case. //! //! [this comment on equality constraints in where clauses]: //! https://github.com/rust-lang/rust/issues/20041#issuecomment-414551783 //! //! Note that `into_val` and `from_val` are basically `into` and `from`, //! but for this trait to work universally we need a universal instance, //! which one can't define on `Into` or `From`. pub trait Is { type Type; fn into_val(self) -> Self::Type; fn into_ref(&self) -> &Self::Type; fn into_mut_ref(&mut self) -> &mut Self::Type; fn from_val(x : Self::Type) -> Self; fn from_ref(x : &Self::Type) -> &Self; fn from_mut_ref(x : &mut Self::Type) -> &mut Self; } impl<T> Is for T { type Type = T; fn into_val(self) -> Self::Type { self } fn into_ref(&self) -> &Self::Type { self } fn into_mut_ref(&mut self) -> &mut Self::Type { self } fn from_val(x : Self::Type) -> Self { x } fn from_ref(x : &Self::Type) -> &Self { x } fn from_mut_ref(x : &mut Self::Type) -> &mut Self { x } } <file_sep>[package] name = "is_type" version = "0.2.0" authors = ["<NAME> <<EMAIL>>"] edition = "2018" description = "Equality constraints for types" license = "MIT/Apache-2.0" repository = "https://github.com/clintonmead/is_type"
291089a31c9260f01a3cf9c147dbdb0b85e4ad51
[ "TOML", "Rust" ]
2
Rust
clintonmead/is_type
39f4bb2789db25ce1ec5682166ac56472b45856a
89d68002e345032362490e3ad67cd6048f582659
refs/heads/master
<file_sep>/** * @file vidutil.c Video utility functions * * Copyright (C) 2017 Creytiv.com */ #include <re.h> #include <rem.h> #include <baresip.h> #include "core.h" /** * Calculate the RTP timestamp from Presentation Time Stamp (PTS) * or Decoding Time Stamp (DTS) and framerate. * * @note The calculated RTP Timestamp may NOT wrap around. * * @param pts Presentation Time Stamp (PTS) * @param fps Framerate in [frames per second] * * @return Extended RTP Timestamp */ uint64_t video_calc_rtp_timestamp(int64_t pts, double fps) { uint64_t rtp_ts; if (!fps) return 0; rtp_ts = ((uint64_t)VIDEO_SRATE * pts) / fps; return rtp_ts; } /** * Calculate the timestamp in seconds from the RTP timestamp. * * @param rtp_ts RTP Timestamp * * @return Timestamp in seconds */ double video_calc_seconds(uint64_t rtp_ts) { double timestamp; /* convert from RTP clockrate to seconds */ timestamp = (double)rtp_ts / (double)VIDEO_SRATE; return timestamp; } /** * Convert a video timestamp to seconds * * @param timestamp Timestamp in VIDEO_TIMEBASE units * * @return Timestamp in seconds */ double video_timestamp_to_seconds(uint64_t timestamp) { return (double)timestamp / (double)VIDEO_TIMEBASE; }
29c89154f0e9d0e49ace716b53174a9b36d0e92c
[ "C" ]
1
C
RobGries/baresip_410c
7326389ab96392f5f9d4d8844798741a2ada277b
64cc6233a830f9531ec543b9ee50afc887945464
refs/heads/Master
<repo_name>Zhu-Zhenhua/MNSIM_Python<file_sep>/MNSIM/Mapping_Model/Behavior_mapping.py #!/usr/bin/python # -*-coding:utf-8-*- import torch import sys import os import math import configparser as cp work_path = os.path.dirname(os.getcwd()) # print("ok", work_path) sys.path.append(work_path) from MNSIM.Hardware_Model import * from MNSIM.Hardware_Model.Tile import tile from MNSIM.Interface.interface import * class behavior_mapping(tile): def __init__(self, NetStruct, SimConfig_path): self.SimConfig_path = SimConfig_path tile.__init__(self, SimConfig_path) bm_config = cp.ConfigParser() bm_config.read(SimConfig_path, encoding='UTF-8') self.xbar_polarity = int(bm_config.get('Process element level', 'Xbar_Polarity')) self.net_structure = NetStruct self.arch_config = SimConfig_path self.total_layer_num = len(self.net_structure) self.tile_list = [] self.kernel_length = self.total_layer_num*[0] self.sliding_times = self.total_layer_num*[0] self.output_channel = self.total_layer_num*[0] self.weight_precision = self.total_layer_num*[8] self.activation_precision = self.total_layer_num*[8] self.operations = self.total_layer_num*[0] self.PE_num = self.total_layer_num*[0] self.tile_num = self.total_layer_num * [0] for i in range(self.total_layer_num): self.tile_list.append([]) self.arch_area = self.total_layer_num*[0] self.arch_xbar_area = self.total_layer_num*[0] self.arch_ADC_area = self.total_layer_num*[0] self.arch_DAC_area = self.total_layer_num*[0] self.arch_digital_area = self.total_layer_num*[0] self.arch_adder_area = self.total_layer_num*[0] self.arch_shiftreg_area = self.total_layer_num*[0] self.arch_input_demux_area = self.total_layer_num*[0] self.arch_output_mux_area = self.total_layer_num*[0] self.arch_total_area = 0 self.arch_total_xbar_area = 0 self.arch_total_ADC_area = 0 self.arch_total_DAC_area = 0 self.arch_total_digital_area = 0 self.arch_total_adder_area = 0 self.arch_total_shiftreg_area = 0 self.arch_total_input_demux_area = 0 self.arch_total_output_mux_area = 0 self.arch_utilization = self.total_layer_num*[0] self.arch_total_utilization = 0 self.arch_latency = self.total_layer_num * [0] self.arch_xbar_latency = self.total_layer_num * [0] self.arch_ADC_latency = self.total_layer_num * [0] self.arch_DAC_latency = self.total_layer_num * [0] self.arch_digital_latency = self.total_layer_num * [0] self.arch_adder_latency = self.total_layer_num * [0] self.arch_shiftreg_latency = self.total_layer_num * [0] self.arch_input_demux_latency = self.total_layer_num * [0] self.arch_output_mux_latency = self.total_layer_num * [0] self.arch_total_latency = 0 self.arch_total_xbar_latency = 0 self.arch_total_ADC_latency = 0 self.arch_total_DAC_latency = 0 self.arch_total_digital_latency = 0 self.arch_total_adder_latency = 0 self.arch_total_shiftreg_latency = 0 self.arch_total_input_demux_latency = 0 self.arch_total_output_mux_latency = 0 self.arch_power = self.total_layer_num * [0] self.arch_xbar_power = self.total_layer_num * [0] self.arch_ADC_power = self.total_layer_num * [0] self.arch_DAC_power = self.total_layer_num * [0] self.arch_digital_power = self.total_layer_num * [0] self.arch_adder_power = self.total_layer_num * [0] self.arch_shiftreg_power = self.total_layer_num * [0] self.arch_input_demux_power = self.total_layer_num * [0] self.arch_output_mux_power = self.total_layer_num * [0] self.arch_total_power = 0 self.arch_total_xbar_power = 0 self.arch_total_ADC_power = 0 self.arch_total_DAC_power = 0 self.arch_total_digital_power = 0 self.arch_total_adder_power = 0 self.arch_total_shiftreg_power = 0 self.arch_total_input_demux_power = 0 self.arch_total_output_mux_power = 0 self.arch_energy = self.total_layer_num * [0] self.arch_xbar_energy = self.total_layer_num * [0] self.arch_ADC_energy = self.total_layer_num * [0] self.arch_DAC_energy = self.total_layer_num * [0] self.arch_digital_energy = self.total_layer_num * [0] self.arch_adder_energy = self.total_layer_num * [0] self.arch_shiftreg_energy = self.total_layer_num * [0] self.arch_input_demux_energy = self.total_layer_num * [0] self.arch_output_mux_energy = self.total_layer_num * [0] self.arch_total_energy = 0 self.arch_total_xbar_energy = 0 self.arch_total_ADC_energy = 0 self.arch_total_DAC_energy = 0 self.arch_total_digital_energy = 0 self.arch_total_adder_energy = 0 self.arch_total_shiftreg_energy = 0 self.arch_total_input_demux_energy = 0 self.arch_total_output_mux_energy = 0 self.arch_energy_efficiency = 0 def config_behavior_mapping(self): for layer_id in range(len(self.net_structure)): layer_dict = self.net_structure[layer_id][0][0] layer_type = layer_dict['type'] if layer_type =='conv' or layer_type=='pooling': inputsize = list(map(int, layer_dict['Inputsize'])) inputsize = inputsize[0]*inputsize[1] outputsize = list(map(int, layer_dict['Outputsize'])) outputsize = outputsize[0]*outputsize[1] kernelsize = int(layer_dict['Kernelsize']) stride = int(layer_dict['Stride']) inputchannel = int(layer_dict['Inputchannel']) self.output_channel[layer_id] = int(layer_dict['Outputchannel']) self.sliding_times[layer_id] = outputsize else: assert layer_type == 'fc', "Layer type must be conv or fc" inputsize = 1 outputsize = int(layer_dict['Outfeature']) kernelsize = 1 inputchannel = int(layer_dict['Infeature']) self.output_channel[layer_id] = int(layer_dict['Outfeature']) self.sliding_times[layer_id] = 1 self.kernel_length[layer_id] = kernelsize ** 2 * inputchannel # The length of the kernel data if self.xbar_polarity == 1: self.weight_precision[layer_id] = int(layer_dict['Weightbit']) else: assert self.xbar_polarity == 2, "Crossbar polarity must be 1 or 2" self.weight_precision[layer_id] = int(layer_dict['Weightbit']) - 1 self.activation_precision[layer_id] = int(layer_dict['Inputbit']) inputchannel_xbar = min(self.xbar_row // (kernelsize**2), inputchannel) # The input channel number stored in one crossbar if self.output_channel[layer_id]>self.xbar_column: outputchannel_xbar = self.xbar_column else: outputchannel_xbar = self.output_channel[layer_id] # The output channel number stored in one crossbar PE_bitwidth = math.floor(math.log2(self.device_level))*self.group_num # The bitwidth of one PE can represent self.operations[layer_id] = self.sliding_times[layer_id] * \ self.kernel_length[layer_id] * \ self.output_channel[layer_id] * 2 # The number of operations self.PE_num[layer_id] = math.ceil(inputchannel/inputchannel_xbar) * \ math.ceil(self.output_channel[layer_id]/outputchannel_xbar) * \ math.ceil(self.weight_precision[layer_id]/PE_bitwidth) # The PE number used for this layer self.tile_num[layer_id] = math.ceil(self.PE_num[layer_id] / (self.tile_PE_total_num)) # The tile number used for this layer xbar_used_length = inputchannel_xbar * (kernelsize**2) # The number of used row (length of the used cells in one column) # Mapping procedure start: tile_index = 0 current_PE_num = 0 read_column = [] read_row = [] kernel_length_2bsplit = self.kernel_length[layer_id] while kernel_length_2bsplit > 0: if kernel_length_2bsplit < xbar_used_length: temp_length = kernel_length_2bsplit else: temp_length = xbar_used_length kernel_length_2bsplit -= temp_length channel_width_2bsplit = self.output_channel[layer_id] while channel_width_2bsplit > 0: if channel_width_2bsplit < outputchannel_xbar: temp_width = channel_width_2bsplit else: temp_width = outputchannel_xbar channel_width_2bsplit -= temp_width weight_precision_2bsplit = self.weight_precision[layer_id] while weight_precision_2bsplit > 0: if weight_precision_2bsplit < PE_bitwidth: temp_bitwidth = weight_precision_2bsplit else: temp_bitwidth = PE_bitwidth weight_precision_2bsplit -= temp_bitwidth current_PE_num += 1 temp_occupied_group = math.ceil(temp_bitwidth/math.floor(math.log2(self.device_level))) read_row.append(temp_occupied_group*[temp_length]) read_column.append(temp_occupied_group*[temp_width]) if current_PE_num == self.tile_PE_total_num or \ ((kernel_length_2bsplit==0)&(channel_width_2bsplit==0)&(weight_precision_2bsplit==0)): # print("yes") __temp_tile = tile(self.SimConfig_path) self.tile_list[layer_id].append(__temp_tile) self.tile_list[layer_id][tile_index].tile_read_config( layer_num=layer_id, activation_precision=self.activation_precision[layer_id], sliding_times=self.sliding_times[layer_id], read_row=read_row, read_column=read_column ) tile_index += 1 current_PE_num = 0 read_column = [] read_row = [] # print(layer_id,':',self.PE_num[layer_id],self.tile_num[layer_id],tile_index) def behavior_mapping_area(self): # Notice: before calculating area, config_behavior_mapping must be executed # unit: um^2 self.calculate_tile_area() for i in range(self.total_layer_num): self.arch_area[i] = self.tile_area * self.tile_num[i] self.arch_xbar_area[i] = self.tile_xbar_area * self.tile_num[i] self.arch_ADC_area[i] = self.tile_ADC_area * self.tile_num[i] self.arch_DAC_area[i] = self.tile_DAC_area * self.tile_num[i] self.arch_digital_area[i] = self.tile_digital_area * self.tile_num[i] self.arch_adder_area[i] = self.tile_adder_area * self.tile_num[i] self.arch_shiftreg_area[i] = self.tile_shiftreg_area * self.tile_num[i] self.arch_input_demux_area[i] = self.tile_input_demux_area * self.tile_num[i] self.arch_output_mux_area[i] = self.tile_output_mux_area * self.tile_num[i] self.arch_total_area = sum(self.arch_area) self.arch_total_xbar_area = sum(self.arch_xbar_area) self.arch_total_ADC_area = sum(self.arch_ADC_area) self.arch_total_DAC_area = sum(self.arch_DAC_area) self.arch_total_digital_area = sum(self.arch_digital_area) self.arch_total_adder_area = sum(self.arch_adder_area) self.arch_total_shiftreg_area = sum(self.arch_shiftreg_area) self.arch_total_input_demux_area = sum(self.arch_input_demux_area) self.arch_total_output_mux_area = sum(self.arch_output_mux_area) def behavior_mapping_utilization(self): # Notice: before calculating utilization, config_behavior_mapping must be executed for i in range(self.total_layer_num): for j in range(self.tile_num[i]): self.arch_utilization[i] += self.tile_list[i][j].tile_utilization self.arch_total_utilization += self.tile_list[i][j].tile_utilization self.arch_utilization[i] /= self.tile_num[i] self.arch_total_utilization /= sum(self.tile_num) def behavior_mapping_latency(self): # Notice: before calculating latency, config_behavior_mapping must be executed # unit: ns # TODO: add arch level adder tree estimation for i in range(self.total_layer_num): temp_latency = 0 latency_index = 0 for j in range(self.tile_num[i]): self.tile_list[i][j].calculate_tile_read_latency() if self.tile_list[i][j].tile_read_latency > temp_latency: latency_index = j self.arch_latency[i] = self.tile_list[i][latency_index].tile_read_latency self.arch_xbar_latency[i] = self.tile_list[i][latency_index].tile_xbar_read_latency self.arch_ADC_latency[i] = self.tile_list[i][latency_index].tile_ADC_read_latency self.arch_DAC_latency[i] = self.tile_list[i][latency_index].tile_DAC_read_latency self.arch_digital_latency[i] = self.tile_list[i][latency_index].tile_digital_read_latency self.arch_adder_latency[i] = self.tile_list[i][latency_index].tile_adder_read_latency self.arch_shiftreg_latency[i] = self.tile_list[i][latency_index].tile_shiftreg_read_latency self.arch_input_demux_latency[i] = self.tile_list[i][latency_index].tile_input_demux_read_latency self.arch_output_mux_latency[i] = self.tile_list[i][latency_index].tile_output_mux_read_latency self.arch_total_latency = sum(self.arch_latency) self.arch_total_xbar_latency = sum(self.arch_xbar_latency) self.arch_total_ADC_latency = sum(self.arch_ADC_latency) self.arch_total_DAC_latency = sum(self.arch_DAC_latency) self.arch_total_digital_latency = sum(self.arch_digital_latency) self.arch_total_adder_latency = sum(self.arch_adder_latency) self.arch_total_shiftreg_latency = sum(self.arch_shiftreg_latency) self.arch_total_input_demux_latency = sum(self.arch_input_demux_latency) self.arch_total_output_mux_latency = sum(self.arch_output_mux_latency) def behavior_mapping_power(self): # Notice: before calculating power, config_behavior_mapping must be executed # unit: W # TODO: add arch level adder tree estimation for i in range(self.total_layer_num): for j in range(self.tile_num[i]): self.tile_list[i][j].calculate_tile_read_power() self.arch_power[i] += self.tile_list[i][j].tile_read_power self.arch_xbar_power[i] += self.tile_list[i][j].tile_xbar_read_power self.arch_ADC_power[i] += self.tile_list[i][j].tile_ADC_read_power self.arch_DAC_power[i] += self.tile_list[i][j].tile_DAC_read_power self.arch_digital_power[i] += self.tile_list[i][j].tile_digital_read_power self.arch_adder_power[i] += self.tile_list[i][j].tile_adder_read_power self.arch_shiftreg_power[i] += self.tile_list[i][j].tile_shiftreg_read_power self.arch_input_demux_power[i] += self.tile_list[i][j].tile_input_demux_read_power self.arch_output_mux_power[i] += self.tile_list[i][j].tile_output_mux_read_power self.arch_total_power = sum(self.arch_power) self.arch_total_xbar_power = sum(self.arch_xbar_power) self.arch_total_ADC_power = sum(self.arch_ADC_power) self.arch_total_DAC_power = sum(self.arch_DAC_power) self.arch_total_digital_power = sum(self.arch_digital_power) self.arch_total_adder_power = sum(self.arch_adder_power) self.arch_total_shiftreg_power = sum(self.arch_shiftreg_power) self.arch_total_input_demux_power = sum(self.arch_input_demux_power) self.arch_total_output_mux_power = sum(self.arch_output_mux_power) def behavior_mapping_energy(self): # Notice: before calculating energy, config_behavior_mapping must be executed # unit: nJ # TODO: add arch level adder tree estimation for i in range(self.total_layer_num): for j in range(self.tile_num[i]): self.tile_list[i][j].calculate_tile_read_energy() self.arch_energy[i] += self.tile_list[i][j].tile_read_energy self.arch_xbar_energy[i] += self.tile_list[i][j].tile_xbar_read_energy self.arch_ADC_energy[i] += self.tile_list[i][j].tile_ADC_read_energy self.arch_DAC_energy[i] += self.tile_list[i][j].tile_DAC_read_energy self.arch_digital_energy[i] += self.tile_list[i][j].tile_digital_read_energy self.arch_adder_energy[i] += self.tile_list[i][j].tile_adder_read_energy self.arch_shiftreg_energy[i] += self.tile_list[i][j].tile_shiftreg_read_energy self.arch_input_demux_energy[i] += self.tile_list[i][j].tile_input_demux_read_energy self.arch_output_mux_energy[i] += self.tile_list[i][j].tile_output_mux_read_energy self.arch_total_energy = sum(self.arch_energy) self.arch_total_xbar_energy = sum(self.arch_xbar_energy) self.arch_total_ADC_energy = sum(self.arch_ADC_energy) self.arch_total_DAC_energy = sum(self.arch_DAC_energy) self.arch_total_digital_energy = sum(self.arch_digital_energy) self.arch_total_adder_energy = sum(self.arch_adder_energy) self.arch_total_shiftreg_energy = sum(self.arch_shiftreg_energy) self.arch_total_input_demux_energy = sum(self.arch_input_demux_energy) self.arch_total_output_mux_energy = sum(self.arch_output_mux_energy) self.arch_energy_efficiency = sum(self.operations)/self.arch_total_energy #unit: GOPs/W def behavior_mapping_output(self, module_information = 1, layer_information = 1): # module_information: 1: print module information # layer_information: 1: print hardware performance of each layer print("=====================================") print("CNN model information:") print("Layer number:", self.total_layer_num) for i in range(len(self.net_structure)): layer = self.net_structure[i][0][0] print(" Layer", i, ":", layer['type']) if layer['type'] == 'conv': print(" |----Input Size:", layer['Inputsize']) print(" |----Input Precision:", layer['Inputbit']) print(" |----Kernel Size:", layer['Kernelsize']) print(" |----Weight Precision:", layer['Weightbit']) print(" |----Input Channel:", layer['Inputchannel']) print(" |----Stride:", layer['Stride']) print(" |----Output Size:", layer['Outputsize']) print(" |----Output Channel:", layer['Outputchannel']) # print(" |----Operations:", self.operations[i]) elif layer['type'] == 'fc': print(" |----Input Size:", layer['Infeature']) print(" |----Input Precision:", layer['Inputbit']) print(" |----Weight Precision:", layer['Weightbit']) print(" |----Output Size:", layer['Outfeature']) # print(" |----Operations:", self.operations[i]) elif layer['type'] == 'pooling': print(" |----Input Size:", layer['Inputsize']) print(" |----Input Precision:", layer['Inputbit']) print(" |----Kernel Size:", layer['Kernelsize']) print(" |----Weight Precision:", layer['Weightbit']) print(" |----Input Channel:", layer['Inputchannel']) print(" |----Stride:", layer['Stride']) print(" |----Output Size:", layer['Outputsize']) print(" |----Output Channel:", layer['Outputchannel']) # print(" |----Operations:", self.operations[i]) print("======================================") print("Hardware performance finished!") print("Tile number:", sum(self.tile_num)) print("Resource utilization:", self.arch_total_utilization) print("Hardware area:", self.arch_total_area, "um^2") if module_information: print(" crossbar area:", self.arch_total_xbar_area, "um^2") print(" DAC area:", self.arch_total_DAC_area, "um^2") print(" ADC area:", self.arch_total_ADC_area, "um^2") print(" digital part area:", self.arch_total_digital_area, "um^2") print(" |---adder area:", self.arch_total_adder_area, "um^2") print(" |---shift-reg area:", self.arch_total_shiftreg_area, "um^2") print(" |---input_demux area:", self.arch_total_input_demux_area, "um^2") print(" |---output_mux area:", self.arch_total_output_mux_area, "um^2") print("Hardware power:", self.arch_total_power, "W") if module_information: print(" crossbar power:", self.arch_total_xbar_power, "W") print(" DAC power:", self.arch_total_DAC_power, "W") print(" ADC power:", self.arch_total_ADC_power, "W") print(" digital part power:", self.arch_total_digital_power, "W") print(" |---adder power:", self.arch_total_adder_power, "W") print(" |---shift-reg power:", self.arch_total_shiftreg_power, "W") print(" |---input_demux power:", self.arch_total_input_demux_power, "W") print(" |---output_mux power:", self.arch_total_output_mux_power, "W") print("Hardware energy:", self.arch_total_energy, "nJ") if module_information: print(" crossbar energy:", self.arch_total_xbar_energy, "nJ") print(" DAC energy:", self.arch_total_DAC_energy, "nJ") print(" ADC energy:", self.arch_total_ADC_energy, "nJ") print(" digital part energy:", self.arch_total_digital_energy, "nJ") print(" |---adder energy:", self.arch_total_adder_energy, "nJ") print(" |---shift-reg energy:", self.arch_total_shiftreg_energy, "nJ") print(" |---input_demux energy:", self.arch_total_input_demux_energy, "nJ") print(" |---output_mux energy:", self.arch_total_output_mux_energy, "nJ") if layer_information: for i in range(self.total_layer_num): print("Layer", i, ":") print(" Operations:", self.operations[i]) print(" Tile number:", self.tile_num[i]) print(" Tile utilization:", self.arch_utilization[i]) print(" Hardware area:", self.arch_area[i]) print(" Hardware power:", self.arch_power[i]) print(" Hardware latency:", self.arch_latency[i]) print(" Hardware energy:", self.arch_energy[i]) print(" Crossbar energy:", self.arch_xbar_energy[i]) print(" ADC energy:", self.arch_ADC_energy[i]) print("total operations:",sum(self.operations)) print("Hardware energy efficiency:", self.arch_energy_efficiency, " GOPs/W") if __name__ == '__main__': test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "SimConfig.ini") test_weights_file_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "alexnet_channels_bit/alexnet_16_5_params.pth") __TestInterface = TrainTestInterface('alexnet_16_5', 'MNSIM.Interface.cifar10', test_SimConfig_path, test_weights_file_path, 'cpu') structure_file = __TestInterface.get_structure() _bm = behavior_mapping(structure_file, test_SimConfig_path) _bm.config_behavior_mapping() _bm.behavior_mapping_area() _bm.behavior_mapping_utilization() _bm.behavior_mapping_latency() _bm.behavior_mapping_power() _bm.behavior_mapping_energy() _bm.behavior_mapping_output(1,1) <file_sep>/MNSIM/Hardware_Model/Reg.py #!/usr/bin/python #-*-coding:utf-8-*- import configparser as cp import os import math test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"SimConfig.ini") #Default SimConfig file path: MNSIM_Python/SimConfig.ini class reg(object): def __init__(self, SimConfig_path, bitwidth = None): # frequency unit: MHz reg_config = cp.ConfigParser() reg_config.read(SimConfig_path, encoding='UTF-8') self.reg_tech = int(reg_config.get('Digital module', 'Reg_Tech')) if self.reg_tech <= 0: self.reg_tech = 65 self.reg_area = float(reg_config.get('Digital module', 'Reg_Area')) self.reg_power = float(reg_config.get('Digital module', 'Reg_Power')) if bitwidth is None: self.bitwidth = 8 else: self.bitwidth = bitwidth assert self.bitwidth > 0 self.reg_frequency =float(reg_config.get('Digital module', 'Digital_Frequency')) if self.reg_frequency is None: self.reg_frequency = 100 assert self.reg_frequency > 0 self.reg_latency = 1.0/self.reg_frequency self.calculate_reg_power() self.reg_energy = 0 # print("reg configuration is loaded") def calculate_reg_area(self): # unit: um^2 if self.reg_area == 0: reg_area_dict = { 4: 1.4256, 8: 1.4256, 16:1.4256 } if self.bitwidth <= 4: self.reg_area = reg_area_dict[4]*pow((self.reg_tech/65),2) elif self.bitwidth <= 8: self.reg_area = reg_area_dict[8]*pow((self.reg_tech/65),2) else: self.reg_area = reg_area_dict[16]*pow((self.reg_tech/65),2) def calculate_reg_power(self): # unit: W if self.reg_power == 0: reg_power_dict = { 4: 18.8e-9, 8: 18.8e-9, 16: 18.8e-9 } if self.bitwidth <= 4: self.reg_power = reg_power_dict[4]*pow((self.reg_tech/65),2) elif self.bitwidth <= 8: self.reg_power = reg_power_dict[8]*pow((self.reg_tech/65),2) else: self.reg_power = reg_power_dict[16]*pow((self.reg_tech/65),2) def calculate_reg_energy(self): assert self.reg_power >= 0 assert self.reg_latency >= 0 self.reg_energy = self.reg_latency * self.reg_power def reg_output(self): print("reg_area:", self.reg_area, "um^2") print("reg_bitwidth:", self.bitwidth, "bit") print("reg_power:", self.reg_power, "W") print("reg_latency:", self.reg_latency, "ns") print("reg_energy:", self.reg_energy, "nJ") def reg_test(): print("load file:",test_SimConfig_path) _reg = reg(test_SimConfig_path) _reg.calculate_reg_area() _reg.calculate_reg_power() _reg.calculate_reg_energy() _reg.reg_output() if __name__ == '__main__': reg_test()<file_sep>/MNSIM/Latency_Model/Pooling_latency.py #!/usr/bin/python # -*-coding:utf-8-*- import torch import sys import os import math import configparser as cp work_path = os.path.dirname(os.getcwd()) sys.path.append(work_path) from MNSIM.Hardware_Model.Buffer import buffer from MNSIM.Hardware_Model.Pooling import Pooling from MNSIM.Interface.interface import * class pooling_latency_analysis(): def __init__(self, SimConfig_path, indata=0, rdata=0, outprecision = 8, default_inbuf_size = 16, default_outbuf_size = 4, default_inchannel = 64, default_size = 9): # indata: volume of input data (for pooling) (Byte) # rdata: volume of data from buffer to iReg (Byte) # default_inbuf_size: the default PE-level input buffer size (unit: KB) # default_outbuf_size: the default Tile-level output buffer size (unit: KB) self.pooling = Pooling(SimConfig_path=SimConfig_path) self.inbuf = buffer(SimConfig_path=SimConfig_path, buf_level=1, default_buf_size=default_inbuf_size) self.inbuf.calculate_buf_write_latency(indata) self.inbuf_wlatency = self.inbuf.buf_wlatency # unit: ns self.inbuf.calculate_buf_read_latency(rdata) self.inbuf_rlatency = self.inbuf.buf_rlatency self.pooling.calculate_Pooling_latency(inchannel=default_inchannel, insize=default_size) self.digital_latency = self.pooling.Pooling_latency self.outbuf = buffer(SimConfig_path=SimConfig_path, buf_level=2, default_buf_size=default_outbuf_size) self.outbuf.calculate_buf_write_latency(wdata=(default_inchannel * outprecision / 8)) self.outbuf_rlatency = 0 self.outbuf_wlatency = self.outbuf.buf_wlatency self.pooling_latency = self.inbuf_wlatency + self.inbuf_rlatency + self.digital_latency + self.outbuf_rlatency + self.outbuf_wlatency # Todo: Add the parameter into config file # Todo: update pooling latency estimation def update_pooling_latency(self,indata=0, rdata=0): # update the latency computing when indata and rdata change self.inbuf.calculate_buf_write_latency(indata) self.inbuf_wlatency = self.inbuf.buf_wlatency # unit: ns self.inbuf.calculate_buf_read_latency(rdata) self.inbuf_rlatency = self.inbuf.buf_rlatency self.pooling_latency = self.inbuf_wlatency + self.inbuf_rlatency + self.digital_latency + self.outbuf_rlatency + self.outbuf_wlatency if __name__ == '__main__': test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "SimConfig.ini") _test = pooling_latency_analysis(test_SimConfig_path, 8, 4) print(_test) <file_sep>/MNSIM/Interface/synthesize.py #-*-coding:utf-8-*- import argparse from importlib import import_module import torch parser = argparse.ArgumentParser() parser.add_argument('-g', '--gpu', help = 'select gpu') parser.add_argument('-d', '--dataset', help = 'select dataset') parser.add_argument('-n', '--net', help = 'select net') parser.add_argument('-t', '--train', help = 'select train') parser.add_argument('-p', '--prefix', help = 'select prefix') parser.add_argument('-m', '--mode', help = 'select mode', choices = ['train', 'test']) parser.add_argument('-w', '--weight', help = 'weight file') args = parser.parse_args() assert args.gpu assert args.dataset assert args.net assert args.train assert args.mode if args.mode == 'train': if args.prefix == None: args.prefix = args.dataset.split('.')[-1] + '_' + args.net elif args.mode == 'test': assert args.weight else: assert 0 print(f'args is {args}') # dataloader dataset_module = import_module(f'MNSIM.Interface.{args.dataset}') train_loader, test_loader = dataset_module.get_dataloader() # net net_module = import_module('MNSIM.Interface.network') if args.dataset.endswith('cifar10'): num_classes = 10 elif args.dataset.endswith('cifar100'): num_classes = 100 else: assert 0, f'unknown dataset' net = net_module.get_net(cate = args.net, num_classes = num_classes) # train train_module = import_module(f'MNSIM.Interface.{args.train}') device = torch.device(f'cuda:{args.gpu}' if torch.cuda.is_available() else 'cpu') print(f'run on device {device}') # weights if args.weight is not None: print(f'load weights, {args.weight}') net.load_change_weights(torch.load(args.weight, map_location=device)) # net.load_state_dict(torch.load(args.weight)) if args.mode == 'train': train_module.train_net(net, train_loader, test_loader, device, args.prefix) if args.mode == 'test': assert args.weight # net.load_change_weights(torch.load(args.weight)) train_module.eval_net(net, test_loader, 0, device) <file_sep>/SimConfig.ini ######## Hardware Configuration ##### [Device level] Device_Tech = 45 # tech unit: nm Device_Area = 1.44 # Suppress variations of analog resistive memory for neuromorphic computing by localizing Vo formation # area unit: um^2 Read_Level = 2 # Read_Voltage = 0,0.5 # read voltage unit: V Write_Level = 2 # Write_Voltage = 0,3 # write voltage unit: V Read_Latency = 3.16 # read latency unit: ns, 3.16 NTHU ISSCC19 Write_Latency = 10 # write latency unit: ns Device_Level = 4 Device_Resistance = 1e7,10000,5000,3333 #1.2e6,4e4 # resistence unit: ohm, the item number in this tuple is bit_level # from HRS to LRS Device_Variation = 5 # x% of ideal resistance Device_SAF = 9,1 # X% of Stuck-At-HRS and Stuck-At-LRS [Crossbar level] Xbar_Size = 256,256 # (Row, Column) Cell_Type = 1T1R # cell type option: 1T1R, 0T1R Transistor_Tech = 65 # transistor technology unit: nm Wire_Resistance = -1 # wire resistance option: value (unit: ohm) or Default (-1) Wire_Capacity = -1 # wire capacity option: value (unit: fF) or Default (-1) Load_Resistance = -1 # load resistance (unit:ohm) or Default (-1) Area_Calculation = 0 # different area calculation methods: 0: use device area for computing; 1: use device tech for computing [Interface level] DAC_Choice = 2 # DAC choice option: -1: User defined, 1~7: four default configurations DAC_Area = 0 # DAC area option: 0: default configurations, x: unit um^2 DAC_Precision = 0 # DAC precision option: 0: default configurations, x: unit bit DAC_Power = 0 # DAC power option: 0: default configurations, x: unit W DAC_Sample_Rate = 0 # DAC sample rate option: 0: default configurations, x: GSamples/s ADC_Choice = 3 # ADC choice option: -1: User defined, 1~7: four default configurations ADC_Area = 0 # ADC area option: 0: default configurations, x: unit um^2 ADC_Precision = 0 # ADC precision option: 0: default configurations, x: unit bit ADC_Power = 0 # ADC power option: 0: default configurations, x: unit W, 静态功耗 ADC_Sample_Rate = 0 # ADC sample rate option: 0: default configurations, x: Samples/s ADC_Interval_Thres = -1 # ADC sample interval threshold option: -1 default configurations, x: a list with the length of 2^Precision. unit: V [Process element level] Xbar_Polarity = 2 # polarity 1: one xbar for both pos and neg; polarity 2: one pos xbar and one neg xbar #Multiplex_Xbar_Num = 0,0 # will be supported in the latter version # number of crossbars use one group of ADDA (x,y): 0:default configuration (1x2), x,y: user defined -> TODO Sub_Position = 0 # 0: the subtraction of pos and neg xbar is performed in the analog domain; 1: in the digital domain (sub after ADC quantization) Group_Num = 8 # number of crossbar groups DAC_Num = 64 # number of DAC in each group: 0: default configuration, x: user defined ADC_Num = 4 # number of ADC in each group: 0: default configuration, x: user defined PE_inBuf_Size = 0 # the input buffer size in each PE: 0: default configuration, x: user defined PE_inBuf_Area = 0 # PE input buffer area option: 0: default configurations, x: um^2 Tile_outBuf_Size = 0 Tile_outBuf_Area = 0 DFU_Buf_Size = 0 DFU_Buf_Area = 0 [Digital module] Digital_Frequency = 500 # digital part frequency unit: MHz Adder_Tech = 45 # adder technology unit: nm Adder_Area = 0 # adder area option: 0:default configurations x: unit um^2 Adder_Power = 0 # adder power option: 0:default configurations x: unit W ShiftReg_Tech = 65 # shiftreg technology unit: nm ShiftReg_Area = 0 # shiftreg area option: 0:default configurations x: unit um^2 ShiftReg_Power = 0 # shiftreg power option: 0:default configurations x: unit W Reg_Tech = 45 # shiftreg technology unit: nm Reg_Area = 0 # shiftreg area option: 0:default configurations x: unit um^2 Reg_Power = 0 # shiftreg power option: 0:default configurations x: unit W JointModule_Tech = 45 # JointModule technology unit: nm JointModule_Area = 0 # jointmodule area option: 0:default configurations x: unit um^2 JointModule_Power = 0 # jointmodule power option: 0:default configurations x: unit W [Tile level] PE_Num = 2,2 # number of PEs in each tile (x,y): 0,0: default configuration (4x4), x,y: user defined Pooling_shape = 3,3 # Pooling Kernel size of the hardware actually suppoert (x,y): 0,0:default configuration (3x3), x,y: user defined Pooling_unit_num = 64 # the Pooling unit in a tile. 0: default configuration, x: user defined Pooling_Tech = 65 # technology for pooling unit used, unit is nm. 0: default configuration, x: user defined Pooling_area = 0 # area for total Pooling part in the tile: 0: default configuration, x: user defined Tile_Adder_Num = 0 # number of adders in each tile: 0: default configuration, x: user defined Tile_Adder_Level = 0 # max adder level in each tile: 0: default configuration, x: user defined Tile_ShiftReg_Num = 0 # number of shiftregs in each tile: 0: default configuration, x: user defined Tile_ShiftReg_Level = 0 # max shiftreg level in each tile: 0: default configuration, x: user defined Inter_Tile_Bandwidth = 20 # inter tile bandwidth, unit: Gbps Intra_Tile_Bandwidth = 1024 # intra tile bandwidth (inter PE), unit: Gbps Tile_outBuf_Size = 0 # the output buffer size in each Tile: 0: default configuration, x: user defined Tile_outBuf_Area = 0 # Tile output buffer area option: 0: default configurations, x: um^2 DFU_Buf_Size = 0 # the buffer size in Data Forwarding Unit of each Tile: 0: default configuration, x: user defined DFU_Buf_Area = 0 # DFU buffer area option: 0: default configurations, x: um^2 [Architecture level] Buffer_Choice = 1 # buffer choice option: 0: User defined, 1: SRAM, 2:DRAM, 3:RRAM Buffer_Technology = 90 # buffer technology option: 0: default configurations, x:nm Buffer_ReadPower = 0 # buffer read power option: 0: default configurations, x:mW Buffer_WritePower = 0 # buffer read power option: 0: default configurations, x:mW Buffer_Bitwidth = 64 # buffer bitwidth option: 0: default configurations, x:bit LUT_Capacity = 1 # LUT capacity unit: Mb LUT_Area = 0 # LUT are option: 0: default configurations, x: mm^2 LUT_Power = 0 # LUT power option: 0: default configurations, x:mW LUT_Bandwidth = 0 # LUT bandwidth option: 0: default configurations, x:Mb/s Tile_Connection = 2 # Option: 0, 1, 2, 3 Tile_Num = 64,64 # number of Tiles in accelerator (x,y): 0,0: default configuration (8x8), x,y: user defined ########### Algorithm Configuration ################ [Algorithm Configuration] Weight_Polarity = 1 # 1 or 2 Simulation_Level = 0 # 0: Behavior, do not consider specific weight values; 1: Estimation, consider the specific weight values NoC_enable = 0 # 0: not call booksim to simulate the NoC part; 1: Call booksim to simulate NoC part <file_sep>/MNSIM/Hardware_Model/__init__.py # #!/usr/bin/python # #-*-coding:utf-8-*- # from .Device import device # from .Adder import adder # from .ShiftReg import shiftreg # from .ADC import ADC # from .DAC import DAC # from .Crossbar import crossbar # from .PE import ProcessElement # from .Bank import tile<file_sep>/MNSIM/Hardware_Model/Device.py #!/usr/bin/python #-*-coding:utf-8-*- import configparser as cp import os import math test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"SimConfig.ini") # Default SimConfig file path: MNSIM_Python/SimConfig.ini class device(object): def __init__(self, SimConfig_path): device_config = cp.ConfigParser() device_config.read(SimConfig_path, encoding='UTF-8') self.device_tech = float(device_config.get('Device level', 'Device_Tech')) self.device_area = float(device_config.get('Device level', 'Device_Area')) self.device_read_voltage_level = int(device_config.get('Device level', 'Read_Level')) assert self.device_read_voltage_level >= 0, "Read voltage level < 0" self.device_read_voltage = list(map(float, device_config.get('Device level', 'Read_Voltage').split(','))) assert self.device_read_voltage_level == len(self.device_read_voltage), "Read voltage setting error" self.device_write_voltage_level = int(device_config.get('Device level', 'Write_Level')) assert self.device_write_voltage_level >= 0, "Write voltage level < 0" self.device_write_voltage = list(map(float, device_config.get('Device level', 'Write_Voltage').split(','))) assert self.device_write_voltage_level == len(self.device_write_voltage), "Write voltage setting error" self.device_read_latency = float(device_config.get('Device level', 'Read_Latency')) self.device_write_latency = float(device_config.get('Device level', 'Write_Latency')) self.device_level = int(device_config.get('Device level', 'Device_Level')) assert self.device_level >= 0, "NVM resistance level < 0" self.device_resistance = list(map(float, device_config.get('Device level', 'Device_Resistance').split(','))) assert self.device_level == len(self.device_resistance), "NVM resistance setting error" self.decice_variation = float(device_config.get('Device level', 'Device_Variation')) # Device variation is defined as \Delta R / R self.device_read_power = 0 self.device_write_power = 0 # print("Device configuration is loaded") def calculate_device_read_power(self, R = None, V = None): # R is the resistance of memristor, None means use default resistance (Sqrt(R_on*R_off)) if R is None: # R = math.sqrt(float(self.device_resistance[0])*float(self.device_resistance[-1])) # R = float(self.device_resistance[-1]) #worst case estimation # R = 0.75*float(self.device_resistance[0]) + 0.25*float(self.device_resistance[-1]) R = (float(self.device_resistance[0])*float(self.device_resistance[-1]))/\ (float(self.device_resistance[-1])*0.67+float(self.device_resistance[0])*0.33) assert R > 0, "Resistance <= 0" if V is None: # V = math.sqrt((self.device_read_voltage[0]**2 + self.device_read_voltage[-1]**2)/2) # V = self.device_read_voltage[-1] #worst case estimation V = math.sqrt(0.9*(self.device_read_voltage[0]**2) + 0.1*(self.device_read_voltage[-1]**2)) assert V >= 0, "Voltage < 0" self.device_read_power = V ** 2 / R def calculate_device_write_power(self, R = None, V = None): # R is the resistance of memristor, None means use default resistance (Sqrt(R_on*R_off)) if R is None: R = math.sqrt(float(self.device_resistance[0])*float(self.device_resistance[-1])) assert R > 0, "Resistance <= 0" if V is None: V = (self.device_write_voltage[0] + self.device_write_voltage[-1])/2 assert V >= 0, "Voltage < 0" self.device_write_power = V ** 2 / R def device_output(self): print("device_tech:", self.device_tech, "nm") print("read_voltage:", self.device_read_voltage, "V") print("write_voltage:", self.device_write_voltage, "V") print("read_latency:", self.device_read_latency, "ns") print("write_latency:", self.device_write_latency, "ns") print("device_level", self.device_level) print("device_resistance:", self.device_resistance, "(ohm)") print("device_variation:", self.decice_variation, "%") print("device_read_power:", self.device_read_power, "W") print("device_write_power:", self.device_write_power, "W") def device_test(): print("load file:",test_SimConfig_path) _device = device(test_SimConfig_path) _device.calculate_device_read_power() _device.calculate_device_write_power() _device.device_output() if __name__ == '__main__': device_test()<file_sep>/MNSIM/Hardware_Model/Tile.py #!/usr/bin/python # -*-coding:utf-8-*- import configparser as cp import os import math from numpy import * import numpy as np from MNSIM.Hardware_Model.PE import ProcessElement from MNSIM.Hardware_Model.Adder import adder from MNSIM.Hardware_Model.Buffer import buffer from MNSIM.Hardware_Model.ShiftReg import shiftreg from MNSIM.Hardware_Model.Reg import reg from MNSIM.Hardware_Model.JointModule import JointModule from MNSIM.Hardware_Model.Pooling import Pooling test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"SimConfig.ini") # Default SimConfig file path: MNSIM_Python/SimConfig.ini class tile(ProcessElement): def __init__(self, SimConfig_path): # layer_num is a list with the size of 1xPE_num ProcessElement.__init__(self, SimConfig_path) tile_config = cp.ConfigParser() tile_config.read(SimConfig_path, encoding='UTF-8') self.tile_PE_num = list(map(int, tile_config.get('Tile level', 'PE_Num').split(','))) if self.tile_PE_num[0] == 0: self.tile_PE_num[0] = 4 self.tile_PE_num[1] = 4 assert self.tile_PE_num[0] > 0, "PE number in one PE < 0" assert self.tile_PE_num[1] > 0, "PE number in one PE < 0" self.tile_PE_total_num = self.tile_PE_num[0] * self.tile_PE_num[1] self.tile_simulation_level = int(tile_config.get('Algorithm Configuration', 'Simulation_Level')) self.tile_PE_list = [] self.tile_PE_enable = [] for i in range(self.tile_PE_num[0]): self.tile_PE_list.append([]) self.tile_PE_enable.append([]) for j in range(self.tile_PE_num[1]): __PE = ProcessElement(SimConfig_path) self.tile_PE_list[i].append(__PE) self.tile_PE_enable[i].append(0) self.layer_type = 'conv' self.tile_layer_num = 0 self.tile_activation_precision = 0 self.tile_sliding_times = 0 self.tile_adder_num = 0 self.tile_shiftreg_num = 0 self.tile_jointmodule_num = 0 self.tile_adder = adder(SimConfig_path) self.tile_shiftreg = shiftreg(SimConfig_path) self.tile_iReg = reg(SimConfig_path) self.tile_oReg = reg(SimConfig_path) self.tile_jointmodule = JointModule(SimConfig_path) self.tile_buffer = buffer(SimConfig_path) self.tile_pooling = Pooling(SimConfig_path) self.tile_utilization = 0 self.num_occupied_PE = 0 self.tile_area = 0 self.tile_xbar_area = 0 self.tile_ADC_area = 0 self.tile_DAC_area = 0 self.tile_digital_area = 0 self.tile_adder_area = 0 self.tile_shiftreg_area = 0 self.tile_iReg_area = 0 self.tile_oReg_area = 0 self.tile_input_demux_area = 0 self.tile_output_mux_area = 0 self.tile_jointmodule_area = 0 self.tile_pooling_area = 0 self.tile_buffer_area = 0 self.tile_read_power = 0 self.tile_xbar_read_power = 0 self.tile_ADC_read_power = 0 self.tile_DAC_read_power = 0 self.tile_digital_read_power = 0 self.tile_adder_read_power = 0 self.tile_shiftreg_read_power = 0 self.tile_iReg_read_power = 0 self.tile_oReg_read_power = 0 self.tile_input_demux_read_power = 0 self.tile_output_mux_read_power = 0 self.tile_jointmodule_read_power = 0 self.tile_pooling_read_power = 0 self.tile_buffer_read_power = 0 self.tile_buffer_r_read_power = 0 self.tile_buffer_w_read_power = 0 self.tile_write_power = 0 self.tile_xbar_write_power = 0 self.tile_ADC_write_power = 0 self.tile_DAC_write_power = 0 self.tile_digital_write_power = 0 self.tile_adder_write_power = 0 self.tile_shiftreg_write_power = 0 self.tile_iReg_write_power = 0 self.tile_input_demux_write_power = 0 self.tile_output_mux_write_power = 0 self.tile_jointmodule_write_power = 0 self.tile_read_latency = 0 self.tile_xbar_read_latency = 0 self.tile_ADC_read_latency = 0 self.tile_DAC_read_latency = 0 self.tile_digital_read_latency = 0 self.tile_adder_read_latency = 0 self.tile_shiftreg_read_latency = 0 self.tile_iReg_read_latency = 0 self.tile_input_demux_read_latency = 0 self.tile_output_mux_read_latency = 0 self.tile_jointmodule_read_latency = 0 # self.tile_layer_read_latency = {0:0} self.tile_write_latency = 0 self.tile_xbar_write_latency = 0 self.tile_ADC_write_latency = 0 self.tile_DAC_write_latency = 0 self.tile_digital_write_latency = 0 self.tile_adder_write_latency = 0 self.tile_shiftreg_write_latency = 0 self.tile_iReg_write_latency = 0 self.tile_input_demux_write_latency = 0 self.tile_output_mux_write_latency = 0 self.tile_jointmodule_write_latency = 0 # self.tile_layer_write_latency = {0:0} self.tile_read_energy = 0 self.tile_xbar_read_energy = 0 self.tile_ADC_read_energy = 0 self.tile_DAC_read_energy = 0 self.tile_digital_read_energy = 0 self.tile_adder_read_energy = 0 self.tile_shiftreg_read_energy = 0 self.tile_iReg_read_energy = 0 self.tile_input_demux_read_energy = 0 self.tile_output_mux_read_energy = 0 self.tile_jointmodule_read_energy = 0 self.tile_write_energy = 0 self.tile_xbar_write_energy = 0 self.tile_ADC_write_energy = 0 self.tile_DAC_write_energy = 0 self.tile_digital_write_energy = 0 self.tile_adder_write_energy = 0 self.tile_shiftreg_write_energy = 0 self.tile_iReg_write_energy = 0 self.tile_input_demux_write_energy = 0 self.tile_output_mux_write_energy = 0 self.tile_jointmodule_write_energy = 0 # print("tile configuration is loaded") self.calculate_intra_PE_connection() def calculate_intra_PE_connection(self): # default configuration: H-tree structure index = self.tile_PE_total_num temp_num = 0 while index/2 >= 1: temp_num += int(index/2) + index%2 index = int(index/2) temp_num *= self.tile_PE_list[0][0].PE_ADC_num self.tile_adder_num = temp_num self.tile_shiftreg_num = temp_num self.tile_jointmodule_num = temp_num def update_tile_buf_size(self, SimConfig_path, default_buf_size = 16): self.tile_buffer = buffer(SimConfig_path=SimConfig_path, default_buf_size=default_buf_size) def calculate_tile_area(self, SimConfig_path=None, default_inbuf_size = 16, default_outbuf_size = 4): # unit: um^2 self.tile_area = 0 self.tile_xbar_area = 0 self.tile_ADC_area = 0 self.tile_DAC_area = 0 self.tile_input_demux_area = 0 self.tile_output_mux_area = 0 self.tile_shiftreg_area = 0 self.tile_iReg_area = 0 self.tile_oReg_area = 0 self.tile_adder_area = 0 self.tile_buffer_area = 0 self.tile_digital_area = 0 self.tile_adder.calculate_adder_area() self.tile_shiftreg.calculate_shiftreg_area() self.tile_iReg.calculate_reg_area() self.tile_oReg.calculate_reg_area() self.tile_jointmodule.calculate_jointmodule_area() self.tile_buffer = buffer(SimConfig_path=SimConfig_path,buf_level=2,default_buf_size=default_outbuf_size) self.tile_buffer.calculate_buf_area() self.tile_pooling.calculate_Pooling_area() for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): self.tile_PE_list[i][j].calculate_PE_area(SimConfig_path=SimConfig_path, default_inbuf_size = default_inbuf_size) self.tile_xbar_area += self.tile_PE_list[i][j].PE_xbar_area self.tile_ADC_area += self.tile_PE_list[i][j].PE_ADC_area self.tile_DAC_area += self.tile_PE_list[i][j].PE_DAC_area # self.tile_digital_area += self.tile_PE_list[i][j].PE_digital_area self.tile_input_demux_area += self.tile_PE_list[i][j].PE_input_demux_area self.tile_output_mux_area += self.tile_PE_list[i][j].PE_output_mux_area self.tile_shiftreg_area += self.tile_PE_list[i][j].PE_shiftreg_area self.tile_iReg_area += self.tile_PE_list[i][j].PE_iReg_area self.tile_oReg_area += self.tile_PE_list[i][j].PE_oReg_area self.tile_adder_area += self.tile_PE_list[i][j].PE_adder_area self.tile_buffer_area += self.tile_PE_list[i][j].PE_inbuf_area # self.tile_adder_area += self.tile_adder_num * self.tile_adder.adder_area # self.tile_shiftreg_area += self.tile_shiftreg_num * self.tile_shiftreg.shiftreg_area self.tile_jointmodule_area = self.tile_jointmodule_num * self.tile_jointmodule.jointmodule_area self.tile_digital_area = self.tile_input_demux_area + self.tile_output_mux_area + self.tile_adder_area \ + self.tile_shiftreg_area + self.tile_jointmodule_area + self.tile_iReg_area + self.tile_oReg_area self.tile_pooling_area = self.tile_pooling.Pooling_area self.tile_buffer_area += self.tile_buffer.buf_area self.tile_area = self.tile_xbar_area + self.tile_ADC_area + self.tile_DAC_area + self.tile_digital_area + self.tile_buffer_area+self.tile_pooling_area def calculate_tile_read_power_fast(self, max_column=0, max_row=0, max_PE=0, max_group=0, layer_type=None, SimConfig_path=None, default_inbuf_size = 16, default_outbuf_size = 4): # max_column: maximum used column in one crossbar in this tile # max_row: maximum used row in one crossbar in this tile # max_PE: maximum used PE in this tile # max_group: maximum used groups in one PE # unit: W # coarse but fast estimation self.tile_read_power = 0 self.tile_xbar_read_power = 0 self.tile_ADC_read_power = 0 self.tile_DAC_read_power = 0 self.tile_digital_read_power = 0 self.tile_adder_read_power = 0 self.tile_shiftreg_read_power = 0 self.tile_iReg_read_power = 0 self.tile_oReg_read_power = 0 self.tile_input_demux_read_power = 0 self.tile_output_mux_read_power = 0 self.tile_jointmodule_read_power = 0 self.tile_pooling_read_power = 0 self.tile_buffer_read_power = 0 self.tile_buffer_r_read_power = 0 self.tile_buffer_w_read_power = 0 self.tile_buffer = buffer(SimConfig_path=SimConfig_path, buf_level=2, default_buf_size=default_outbuf_size) if layer_type == 'pooling': self.tile_pooling.calculate_Pooling_power() self.tile_pooling_read_power = self.tile_pooling.Pooling_power elif layer_type == 'conv' or layer_type == 'fc': self.calculate_PE_read_power_fast(max_column=max_column, max_row=max_row, max_group=max_group, SimConfig_path=SimConfig_path, default_inbuf_size = default_inbuf_size) self.tile_xbar_read_power = max_PE * self.PE_xbar_read_power self.tile_ADC_read_power = max_PE * self.PE_ADC_read_power self.tile_DAC_read_power = max_PE * self.PE_DAC_read_power self.tile_adder_read_power = max_PE * self.PE_adder_read_power self.tile_shiftreg_read_power = max_PE * self.PE_shiftreg_read_power self.tile_iReg_read_power = max_PE * self.PE_iReg_read_power self.tile_oReg_read_power = max_PE * self.PE_oReg_read_power self.tile_input_demux_read_power = max_PE * self.input_demux_read_power self.tile_output_mux_read_power = max_PE * self.output_mux_read_power self.tile_jointmodule_read_power = (max_PE-1)*math.ceil(max_column/self.output_mux)*self.tile_jointmodule.jointmodule_power self.tile_digital_read_power = self.tile_adder_read_power+self.tile_shiftreg_read_power+\ self.tile_input_demux_read_power+self.tile_output_mux_read_power+self.tile_jointmodule_read_power self.tile_buffer_r_read_power = max_PE * self.PE_inbuf_read_rpower self.tile_buffer_w_read_power = max_PE * self.PE_inbuf_read_wpower self.tile_buffer.calculate_buf_read_power() self.tile_buffer.calculate_buf_write_power() self.tile_buffer_r_read_power += self.tile_buffer.buf_rpower * 1e-3 self.tile_buffer_w_read_power += self.tile_buffer.buf_wpower * 1e-3 self.tile_buffer_read_power = self.tile_buffer_r_read_power + self.tile_buffer_w_read_power self.tile_digital_read_power = self.tile_adder_read_power+self.tile_shiftreg_read_power+self.tile_iReg_read_power+self.tile_oReg_read_power+\ self.tile_input_demux_read_power+self.tile_output_mux_read_power+self.tile_jointmodule_read_power self.tile_read_power = self.tile_xbar_read_power+self.tile_ADC_read_power+self.tile_DAC_read_power+\ self.tile_digital_read_power+self.tile_pooling_read_power+self.tile_buffer_read_power def tile_read_config(self, layer_num = 0, activation_precision = 0, sliding_times = 0, read_row = None, read_column = None, read_matrix = None, read_vector = None): # read_row and read_column are 2D lists with the size of (#occupied_PE x #occupied groups) # read_matrix is a 3D list of matrices, with the size of (#occupied_PE x #occupied groups x Xbar_Polarity) # read_vector is a 2D list of vectors, with the size of (#occupied_PE x #occupied groups) self.tile_layer_num = layer_num self.tile_activation_precision = activation_precision self.tile_sliding_times = sliding_times self.tile_utilization = 0 self.num_occupied_PE = 0 if self.tile_simulation_level == 0: if (read_row is None) or (read_column is None): self.num_occupied_group = self.tile_PE_total_num for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): # temp_index = i*self.tile_PE_num[0] + self.tile_PE_num[1] self.tile_PE_list[i][j].PE_read_config() self.tile_PE_enable[i][j] = 1 self.tile_utilization += self.tile_PE_list[i][j].PE_utilization else: assert len(read_row) == len(read_column), "read_row and read_column must be equal in length" self.num_occupied_PE = len(read_row) assert self.num_occupied_PE <= self.tile_PE_total_num, "The length of read_row exceeds the PE number in one tile" for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): temp_index = i * self.tile_PE_num[0] + j if temp_index < self.num_occupied_PE: self.tile_PE_list[i][j].PE_read_config(read_row = read_row[temp_index], read_column = read_column[temp_index]) self.tile_PE_enable[i][j] = 1 self.tile_utilization += self.tile_PE_list[i][j].PE_utilization else: self.tile_PE_enable[i][j] = 0 else: if read_matrix is None: self.num_occupied_group = self.tile_PE_total_num for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): self.tile_PE_list[i][j].PE_read_config() self.tile_PE_enable[i][j] = 1 self.tile_utilization += self.tile_PE_list[i][j].PE_utilization else: if read_vector is None: self.num_occupied_PE = len(read_matrix) assert self.num_occupied_PE <= self.tile_PE_total_num, "The number of read_matrix exceeds the PE number in one tile" for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): temp_index = i * self.tile_PE_num[0] + j if temp_index < self.num_occupied_PE: self.tile_PE_list[i][j].PE_read_config(read_matrix = read_matrix[temp_index]) self.tile_PE_enable[i][j] = 1 self.tile_utilization += self.tile_PE_list[i][j].PE_utilization else: self.tile_PE_enable[i][j] = 0 else: assert len(read_matrix) == len(read_vector), "The number of read_matrix and read_vector must be equal" self.num_occupied_PE = len(read_matrix) for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): temp_index = i * self.tile_PE_num[0] + j if temp_index < self.num_occupied_PE: self.tile_PE_list[i][j].PE_read_config(read_matrix = read_matrix[temp_index], read_vector = read_vector[temp_index]) self.tile_PE_enable[i][j] = 1 self.tile_utilization += self.tile_PE_list[i][j].PE_utilization else: self.tile_PE_enable[i][j] = 0 self.tile_utilization /= self.tile_PE_total_num '''def tile_write_config(self, write_row = None, write_column = None, write_matrix = None, write_vector = None): # write_row and write_column are 2D lists with the size of (#occupied_PE x #occupied groups) # write_matrix is a 3D list of matrices, with the size of (#occupied_PE x #occupied groups x Xbar_Polarity) # write_vector is a 2D list of vectors, with the size of (#occupied_PE x #occupied groups) self.tile_utilization = 0 if self.tile_simulation_level == 0: if (write_row is None) or (write_column is None): self.num_occupied_PE = self.tile_PE_total_num for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): # temp_index = i*self.tile_PE_num[0] + self.tile_PE_num[1] self.tile_PE_list[i][j].PE_write_config() self.tile_PE_enable[i][j] = 1 self.tile_utilization += self.tile_PE_list[i][j].PE_utilization else: assert len(write_row) == len(write_column), "write_row and write_column must be equal in length" self.num_occupied_PE = len(write_row) assert self.num_occupied_PE <= self.tile_PE_total_num, "The length of write_row exceeds the PE number in one tile" for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): temp_index = i * self.tile_PE_num[0] + self.tile_PE_num[1] if temp_index < self.num_occupied_PE: self.tile_PE_list[i][j].PE_write_config(write_row = write_row[temp_index], write_column = write_column[temp_index]) self.tile_PE_enable[i][j] = 1 self.tile_utilization += self.tile_PE_list[i][j].PE_utilization else: self.tile_PE_enable[i][j] = 0 else: if write_matrix is None: self.num_occupied_PE = self.tile_PE_total_num for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): self.tile_PE_list[i][j].PE_write_config() self.tile_PE_enable[i][j] = 1 self.tile_utilization += self.tile_PE_list[i][j].PE_utilization else: if write_vector is None: self.num_occupied_PE = len(write_matrix) assert self.num_occupied_PE <= self.tile_PE_total_num, "The number of write_matrix exceeds the PE number in one tile" for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): temp_index = i * self.tile_PE_num[0] + self.tile_PE_num[1] if temp_index < self.num_occupied_PE: self.tile_PE_list[i][j].PE_write_config(write_matrix = write_matrix[temp_index]) self.tile_PE_enable[i][j] = 1 self.tile_utilization += self.tile_PE_list[i][j].PE_utilization else: self.tile_PE_enable[i][j] = 0 else: assert len(write_matrix) == len(write_vector), "The number of write_matrix and write_vector must be equal" self.num_occupied_PE = len(write_matrix) for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): temp_index = i * self.tile_PE_num[0] + self.tile_PE_num[1] if temp_index < self.num_occupied_PE: self.tile_PE_list[i][j].PE_write_config(write_matrix = write_matrix[temp_index], write_vector = write_vector[temp_index]) self.tile_PE_enable[i][j] = 1 self.tile_utilization += self.tile_PE_list[i][j].PE_utilization else: self.tile_PE_enable[i][j] = 0 self.tile_utilization /= self.tile_PE_total_num''' '''def calculate_tile_read_latency(self): # Notice: before calculating latency, tile_read_config must be executed # unit: ns self.tile_read_latency = 0 self.tile_xbar_read_latency = 0 self.tile_ADC_read_latency = 0 self.tile_DAC_read_latency = 0 self.tile_digital_read_latency = 0 self.tile_adder_read_latency = 0 self.tile_shiftreg_read_latency = 0 self.tile_input_demux_read_latency = 0 self.tile_output_mux_read_latency = 0 if self.num_occupied_PE != 0: temp_latency = 0 for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): if self.tile_PE_enable[i][j] == 1: self.tile_PE_list[i][j].calculate_PE_read_latency() if self.tile_PE_list[i][j].PE_read_latency > temp_latency: temp_latency = self.tile_PE_list[i][j].PE_read_latency self.tile_xbar_read_latency = self.tile_PE_list[i][j].PE_xbar_read_latency self.tile_ADC_read_latency = self.tile_PE_list[i][j].PE_ADC_read_latency self.tile_DAC_read_latency = self.tile_PE_list[i][j].PE_DAC_read_latency self.tile_digital_read_latency = self.tile_PE_list[i][j].PE_digital_read_latency self.tile_shiftreg_read_latency = self.tile_PE_list[i][j].PE_shiftreg_read_latency self.tile_adder_read_latency = self.tile_PE_list[i][j].PE_adder_read_latency self.tile_input_demux_read_latency = self.tile_PE_list[i][j].input_demux_read_latency self.tile_output_mux_read_latency = self.tile_PE_list[i][j].output_mux_read_latency level = math.ceil(math.log2(self.num_occupied_PE)) multiple_time = math.ceil(self.tile_activation_precision / self.tile_PE_list[0][0].DAC_precision) \ * self.tile_sliding_times # self.tile_shiftreg_read_latency = multiple_time * (self.tile_shiftreg_read_latency + self.tile_shiftreg.shiftreg_latency) # self.tile_adder_read_latency = multiple_time * (level * self.tile_adder.adder_latency + self.tile_adder_read_latency) self.tile_xbar_read_latency *= multiple_time self.tile_ADC_read_latency *= multiple_time self.tile_DAC_read_latency *= multiple_time self.tile_input_demux_read_latency *= multiple_time self.tile_output_mux_read_latency *= multiple_time self.tile_jointmodule_read_latency = self.tile_sliding_times * level * self.tile_jointmodule.jointmodule_latency self.tile_digital_read_latency = multiple_time * (self.tile_digital_read_latency + self.tile_shiftreg.shiftreg_latency + level * self.tile_adder.adder_latency)\ + self.tile_jointmodule_read_latency self.tile_read_latency = self.tile_xbar_read_latency + self.tile_ADC_read_latency \ + self.tile_DAC_read_latency + self.tile_digital_read_latency def calculate_tile_write_latency(self): # Notice: before calculating latency, tile_write_config must be executed # unit: ns self.tile_write_latency = 0 self.tile_xbar_write_latency = 0 self.tile_ADC_write_latency = 0 self.tile_DAC_write_latency = 0 self.tile_digital_write_latency = 0 self.tile_adder_write_latency = 0 self.tile_shiftreg_write_latency = 0 self.tile_input_demux_write_latency = 0 self.tile_output_mux_write_latency = 0 if self.num_occupied_PE != 0: temp_latency = 0 for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): if self.tile_PE_enable[i][j] == 1: self.tile_PE_list[i][j].calculate_PE_write_latency() if self.tile_PE_list[i][j].PE_write_latency > temp_latency: temp_latency = self.tile_PE_list[i][j].PE_write_latency self.tile_xbar_write_latency = self.tile_PE_list[i][j].PE_xbar_write_latency self.tile_ADC_write_latency = self.tile_PE_list[i][j].PE_ADC_write_latency self.tile_DAC_write_latency = self.tile_PE_list[i][j].PE_DAC_write_latency self.tile_digital_write_latency = self.tile_PE_list[i][j].PE_digital_write_latency self.tile_input_demux_write_latency = self.tile_PE_list[i][j].input_demux_write_latency self.tile_output_mux_write_latency = 0 self.tile_shiftreg_write_latency = 0 self.tile_adder_write_latency = 0 self.tile_jointmodule_write_latency = 0 self.tile_write_latency = self.tile_xbar_write_latency + self.tile_ADC_write_latency \ + self.tile_DAC_write_latency + self.tile_digital_write_latency''' def calculate_tile_read_power(self): # unit: W # Notice: before calculating power, tile_read_config must be executed self.tile_read_power = 0 self.tile_xbar_read_power = 0 self.tile_ADC_read_power = 0 self.tile_DAC_read_power = 0 self.tile_digital_read_power = 0 self.tile_adder_read_power = 0 self.tile_shiftreg_read_power = 0 self.tile_iReg_read_power = 0 self.tile_input_demux_read_power = 0 self.tile_output_mux_read_power = 0 self.tile_buffer_read_power = 0 self.tile_buffer_r_read_power = 0 self.tile_buffer_w_read_power = 0 max_occupied_column = 0 if self.num_occupied_PE != 0: for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): if self.tile_PE_enable[i][j] == 1: self.tile_PE_list[i][j].calculate_PE_read_power() self.tile_xbar_read_power += self.tile_PE_list[i][j].PE_xbar_read_power self.tile_ADC_read_power += self.tile_PE_list[i][j].PE_ADC_read_power self.tile_DAC_read_power += self.tile_PE_list[i][j].PE_DAC_read_power self.tile_adder_read_power += self.tile_PE_list[i][j].PE_adder_read_power self.tile_shiftreg_read_power += self.tile_PE_list[i][j].PE_shiftreg_read_power self.tile_iReg_read_power += self.tile_PE_list[i][j].PE_iReg_read_power self.tile_input_demux_read_power += self.tile_PE_list[i][j].input_demux_read_power self.tile_output_mux_read_power += self.tile_PE_list[i][j].output_mux_read_power # self.tile_digital_read_power += self.tile_PE_list[i][j].PE_digital_read_power if self.tile_PE_list[i][j].PE_max_occupied_column > max_occupied_column: max_occupied_column = self.tile_PE_list[i][j].PE_max_occupied_column # TODO: more accurate estimation of adder/shiftreg number max_occupied_column = min(max_occupied_column, self.tile_PE_list[0][0].PE_ADC_num) # self.tile_adder_read_power = (self.num_occupied_PE - 1) * max_occupied_column * self.tile_adder.adder_power # self.tile_shiftreg_read_power = (self.num_occupied_PE - 1) * max_occupied_column * self.tile_shiftreg.shiftreg_power self.tile_jointmodule_read_power = (self.num_occupied_PE - 1) * math.ceil(max_occupied_column/self.output_mux) * self.tile_jointmodule.jointmodule_power self.tile_digital_read_power = self.tile_adder_read_power + self.tile_shiftreg_read_power + self.tile_iReg_read_power \ + self.tile_input_demux_read_power + self.tile_output_mux_read_power + self.tile_jointmodule_read_power self.tile_buffer.calculate_buf_read_power() self.tile_buffer.calculate_buf_write_power() self.tile_buffer_r_read_power = self.tile_buffer.buf_rpower * 1e-3 self.tile_buffer_w_read_power = self.tile_buffer.buf_wpower * 1e-3 self.tile_buffer_read_power = self.tile_buffer_r_read_power + self.tile_buffer_w_read_power self.tile_read_power = self.tile_xbar_read_power + self.tile_ADC_read_power + self.tile_DAC_read_power \ + self.tile_digital_read_power \ + self.tile_buffer_read_power '''def calculate_tile_write_power(self): # unit: W # Notice: before calculating power, tile_write_config must be executed self.tile_write_power = 0 self.tile_xbar_write_power = 0 self.tile_ADC_write_power = 0 self.tile_DAC_write_power = 0 self.tile_digital_write_power = 0 self.tile_adder_write_power = 0 self.tile_shiftreg_write_power = 0 self.tile_input_demux_write_power = 0 self.tile_output_mux_write_power = 0 if self.num_occupied_PE != 0: for i in range(self.tile_PE_num[0]): for j in range(self.tile_PE_num[1]): if self.tile_PE_enable[i][j] == 1: self.tile_PE_list[i][j].calculate_PE_write_power() self.tile_xbar_write_power += self.tile_PE_list[i][j].PE_xbar_read_power self.tile_ADC_write_power += self.tile_PE_list[i][j].PE_ADC_write_power self.tile_DAC_write_power += self.tile_PE_list[i][j].PE_DAC_write_power self.tile_digital_write_power += self.tile_PE_list[i][j].PE_digital_write_power self.tile_adder_write_power += self.tile_PE_list[i][j].PE_adder_write_power self.tile_shiftreg_write_power += self.tile_PE_list[i][j].PE_shiftreg_write_power self.tile_input_demux_write_power += self.tile_PE_list[i][j].input_demux_write_power self.tile_output_mux_write_power += self.tile_PE_list[i][j].output_mux_write_power self.tile_write_power = self.tile_xbar_write_power + self.tile_ADC_write_power + self.tile_DAC_write_power \ + self.tile_digital_write_power \ + (self.buffer.dynamic_buf_wpower + self.buffer.leakage_power) * 1e-3 def calculate_tile_read_energy(self): # unit: nJ # Notice: before calculating energy, tile_read_config and calculate_tile_read_power must be executed self.tile_read_energy = 0 self.tile_xbar_read_energy = 0 self.tile_ADC_read_energy = 0 self.tile_DAC_read_energy = 0 self.tile_digital_read_energy = 0 self.tile_adder_read_energy = 0 self.tile_shiftreg_read_energy = 0 self.tile_input_demux_read_energy = 0 self.tile_output_mux_read_energy = 0 if self.num_occupied_PE != 0: self.tile_xbar_read_energy = self.tile_xbar_read_power * self.tile_xbar_read_latency self.tile_ADC_read_energy = self.tile_ADC_read_power * self.tile_ADC_read_latency self.tile_DAC_read_energy = self.tile_DAC_read_power * self.tile_DAC_read_latency #TODO: correct the adder and shiftreg energy calculation self.tile_adder_read_energy = self.tile_adder_read_power * self.tile_adder_read_latency self.tile_shiftreg_read_energy = self.tile_shiftreg_read_power * self.tile_shiftreg_read_latency self.tile_jointmodule_read_energy = self.tile_jointmodule_read_power * self.tile_jointmodule_read_latency self.tile_input_demux_read_energy = self.tile_input_demux_read_power * self.tile_input_demux_read_latency self.tile_output_mux_read_energy = self.tile_output_mux_read_power * self.tile_output_mux_read_latency self.tile_digital_read_energy = self.tile_adder_read_energy + self.tile_shiftreg_read_energy \ + self.tile_input_demux_read_energy + self.tile_output_mux_read_energy + self.tile_jointmodule_read_energy self.tile_read_energy = self.tile_xbar_read_energy + self.tile_ADC_read_energy \ + self.tile_DAC_read_energy + self.tile_digital_read_energy + self.tile_buffer.buf_renergy def calculate_tile_write_energy(self): # unit: nJ # Notice: before calculating energy, tile_write_config and calculate_tile_write_power must be executed self.tile_write_energy = 0 self.tile_xbar_write_energy = 0 self.tile_ADC_write_energy = 0 self.tile_DAC_write_energy = 0 self.tile_digital_write_energy = 0 self.tile_adder_write_energy = 0 self.tile_shiftreg_write_energy = 0 self.tile_input_demux_write_energy = 0 self.tile_output_mux_write_energy = 0 if self.num_occupied_PE != 0: self.tile_xbar_write_energy = self.tile_xbar_write_power * self.tile_xbar_write_latency self.tile_ADC_write_energy = self.tile_ADC_write_power * self.tile_ADC_write_latency self.tile_DAC_write_energy = self.tile_DAC_write_power * self.tile_DAC_write_latency # TODO: correct the adder and shiftreg energy calculation self.tile_adder_write_energy = self.tile_adder_write_power * self.tile_adder_write_latency self.tile_shiftreg_write_energy = self.tile_shiftreg_write_power * self.tile_shiftreg_write_latency self.tile_input_demux_write_energy = self.tile_input_demux_write_power * self.tile_input_demux_write_latency self.tile_output_mux_write_energy = self.tile_output_mux_write_power * self.tile_output_mux_write_latency self.tile_digital_write_energy = self.tile_adder_write_energy + self.tile_shiftreg_write_energy \ + self.tile_input_demux_write_energy + self.tile_output_mux_write_energy self.tile_write_energy = self.tile_xbar_write_energy + self.tile_ADC_write_energy \ + self.tile_DAC_write_energy + self.tile_digital_write_energy + self.tile_buffer.buf_wenergy''' def tile_output(self): self.tile_PE_list[0][0].PE_output() print("-------------------------tile Configurations-------------------------") print("total PE number in one tile:", self.tile_PE_total_num, "(", self.tile_PE_num, ")") print("total adder number in one tile:", self.tile_adder_num) # print(" the level of adders is:", self.tile_adder_level) print("total shift-reg number in one tile:", self.tile_shiftreg_num) # print(" the level of shift-reg is:", self.tile_shiftreg_level) print("----------------------tile Area Simulation Results-------------------") print("tile area:", self.tile_area, "um^2") print(" crossbar area:", self.tile_xbar_area, "um^2") print(" DAC area:", self.tile_DAC_area, "um^2") print(" ADC area:", self.tile_ADC_area, "um^2") print(" digital part area:", self.tile_digital_area, "um^2") print(" |---adder area:", self.tile_adder_area, "um^2") print(" |---shift-reg area:", self.tile_shiftreg_area, "um^2") print(" |---input_demux area:", self.tile_input_demux_area, "um^2") print(" |---output_mux area:", self.tile_output_mux_area, "um^2") print(" |---JointModule area:", self.tile_jointmodule_area, "um^2") print("--------------------tile Latency Simulation Results------------------") print("tile read latency:", self.tile_read_latency, "ns") print(" crossbar read latency:", self.tile_xbar_read_latency, "ns") print(" DAC read latency:", self.tile_DAC_read_latency, "ns") print(" ADC read latency:", self.tile_ADC_read_latency, "ns") print(" digital part read latency:", self.tile_digital_read_latency, "ns") print(" |---adder read latency:", self.tile_adder_read_latency, "ns") print(" |---shift-reg read latency:", self.tile_shiftreg_read_latency, "ns") print(" |---input demux read latency:", self.tile_input_demux_read_latency, "ns") print(" |---output mux read latency:", self.tile_output_mux_read_latency, "ns") print(" |---JointModule read latency:", self.tile_jointmodule_read_latency, "ns") print("tile write latency:", self.tile_write_latency, "ns") print(" crossbar write latency:", self.tile_xbar_write_latency, "ns") print(" DAC write latency:", self.tile_DAC_write_latency, "ns") print(" ADC write latency:", self.tile_ADC_write_latency, "ns") print(" digital part write latency:", self.tile_digital_write_latency, "ns") print(" |---adder write latency:", self.tile_adder_write_latency, "ns") print(" |---shift-reg write latency:", self.tile_shiftreg_write_latency, "ns") print(" |---input demux write latency:", self.tile_input_demux_write_latency, "ns") print(" |---output mux write latency:", self.tile_output_mux_write_latency, "ns") print(" |---JointModule write latency:", self.tile_jointmodule_write_latency, "ns") print("--------------------tile Power Simulation Results-------------------") print("tile read power:", self.tile_read_power, "W") print(" crossbar read power:", self.tile_xbar_read_power, "W") print(" DAC read power:", self.tile_DAC_read_power, "W") print(" ADC read power:", self.tile_ADC_read_power, "W") print(" digital part read power:", self.tile_digital_read_power, "W") print(" |---adder read power:", self.tile_adder_read_power, "W") print(" |---shift-reg read power:", self.tile_shiftreg_read_power, "W") print(" |---input demux read power:", self.tile_input_demux_read_power, "W") print(" |---output mux read power:", self.tile_output_mux_read_power, "W") print(" |---JointModule read power:", self.tile_jointmodule_read_power, "W") print(" buffer read power:", (self.buffer.dynamic_buf_rpower + self.buffer.leakage_power) * 1e-3, "W") print("tile write power:", self.tile_write_power, "W") print(" crossbar write power:", self.tile_xbar_write_power, "W") print(" DAC write power:", self.tile_DAC_write_power, "W") print(" ADC write power:", self.tile_ADC_write_power, "W") print(" digital part write power:", self.tile_digital_write_power, "W") print(" |---adder write power:", self.tile_adder_write_power, "W") print(" |---shift-reg write power:", self.tile_shiftreg_write_power, "W") print(" |---input demux write power:", self.tile_input_demux_write_power, "W") print(" |---output mux write power:", self.tile_output_mux_write_power, "W") print(" |---JointModule write power:", self.tile_jointmodule_write_power, "W") print(" buffer write power:", (self.buffer.dynamic_buf_wpower + self.buffer.leakage_power) * 1e-3, "W") print("------------------Energy Simulation Results----------------------") print("tile read energy:", self.tile_read_energy, "nJ") print(" crossbar read energy:", self.tile_xbar_read_energy, "nJ") print(" DAC read energy:", self.tile_DAC_read_energy, "nJ") print(" ADC read energy:", self.tile_ADC_read_energy, "nJ") print(" digital part read energy:", self.tile_digital_read_energy, "nJ") print(" |---adder read energy:", self.tile_adder_read_energy, "nJ") print(" |---shift-reg read energy:", self.tile_shiftreg_read_energy, "nJ") print(" |---input demux read energy:", self.tile_input_demux_read_energy, "nJ") print(" |---output mux read energy:", self.tile_output_mux_read_energy, "nJ") print(" |---JointModule read energy:", self.tile_jointmodule_read_energy, "nJ") print("tile write energy:", self.tile_write_energy, "nJ") print(" crossbar write energy:", self.tile_xbar_write_energy, "nJ") print(" DAC write energy:", self.tile_DAC_write_energy, "nJ") print(" ADC write energy:", self.tile_ADC_write_energy, "nJ") print(" digital part write energy:", self.tile_digital_write_energy, "nJ") print(" |---adder write energy:", self.tile_adder_write_energy, "nJ") print(" |---shift-reg write energy:", self.tile_shiftreg_write_energy, "nJ") print(" |---input demux write energy:", self.tile_input_demux_write_energy, "nJ") print(" |---output mux write energy:", self.tile_output_mux_write_energy, "nJ") print(" |---JointModule write energy:", self.tile_jointmodule_write_energy, "nJ") print("-----------------------------------------------------------------") def tile_test(): print("load file:", test_SimConfig_path) _tile = tile(test_SimConfig_path) print(_tile.xbar_column) _tile0 = _tile _tile0.tile_read_config() _tile0.tile_write_config() _tile0.calculate_tile_area() _tile0.calculate_tile_read_latency() _tile0.calculate_tile_write_latency() _tile0.calculate_tile_read_power() _tile0.calculate_tile_write_power() _tile0.calculate_tile_read_energy() _tile0.calculate_tile_write_energy() _tile0.tile_output() if __name__ == '__main__': tile_test()<file_sep>/MNSIM/Hardware_Model/ADC.py #!/usr/bin/python #-*-coding:utf-8-*- import configparser as cp import os import math test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"SimConfig.ini") #Default SimConfig file path: MNSIM_Python/SimConfig.ini class ADC(object): def __init__(self, SimConfig_path): ADC_config = cp.ConfigParser() ADC_config.read(SimConfig_path, encoding='UTF-8') self.ADC_choice = int(ADC_config.get('Interface level', 'ADC_Choice')) self.ADC_area = float(ADC_config.get('Interface level', 'ADC_Area')) self.ADC_precision = int(ADC_config.get('Interface level', 'ADC_Precision')) self.ADC_power = float(ADC_config.get('Interface level', 'ADC_Power')) self.ADC_sample_rate = float(ADC_config.get('Interface level', 'ADC_Sample_Rate')) self.ADC_latency = 0 self.ADC_energy = 0 self.ADC_interval = list(map(int, ADC_config.get('Interface level', 'ADC_Interval_Thres').split(','))) # print("ADC configuration is loaded") # self.calculate_ADC_area() self.calculate_ADC_precision() # self.calculate_ADC_power() self.calculate_ADC_sample_rate() # self.calculate_ADC_energy() def calculate_ADC_area(self): #unit: um^2 ADC_area_dict = {1: 1600, #reference: A 10b 1.5GS/s Pipelined-SAR ADC with Background Second-Stage Common-Mode Regulation and Offset Calibration in 14nm CMOS FinFET 2: 1200, #reference: ISAAC: A Convolutional Neural Network Accelerator with In-Situ Analog Arithmetic in Crossbars 3: 1650, #reference: A >3GHz ERBW 1.1GS/s 8b Two-Step SAR ADC with Recursive-Weight DAC 4: 580, #reference: Area-Efficient 1GS/s 6b SAR ADC with Charge-Injection-Cell-Based DAC 5: 1650, #ASPDAC1 6: 1650, #ASPDAC2 7: 500 #ASPDAC3 } if self.ADC_choice != -1: assert self.ADC_choice in [1,2,3,4,5,6,7] self.ADC_area = ADC_area_dict[self.ADC_choice] def calculate_ADC_precision(self): ADC_precision_dict = {1: 10, #reference: A 10b 1.5GS/s Pipelined-SAR ADC with Background Second-Stage Common-Mode Regulation and Offset Calibration in 14nm CMOS FinFET 2: 8, #reference: ISAAC: A Convolutional Neural Network Accelerator with In-Situ Analog Arithmetic in Crossbars 3: 8, #reference: A >3GHz ERBW 1.1GS/s 8b Two-Step SAR ADC with Recursive-Weight DAC 4: 6, #reference: Area-Efficient 1GS/s 6b SAR ADC with Charge-Injection-Cell-Based DAC 5: 8, #ASPDAC1 6: 6, #ASPDAC2 7: 4 #ASPDAC3 } if self.ADC_choice != -1: assert self.ADC_choice in [1,2,3,4,5,6,7] self.ADC_precision = ADC_precision_dict[self.ADC_choice] def calculate_ADC_power(self): #unit: W ADC_power_dict = {1: 6.92*1e-3, #reference: A 10b 1.5GS/s Pipelined-SAR ADC with Background Second-Stage Common-Mode Regulation and Offset Calibration in 14nm CMOS FinFET 2: 2*1e-3, #reference: ISAAC: A Convolutional Neural Network Accelerator with In-Situ Analog Arithmetic in Crossbars 3: 4*1e-3, #reference: A >3GHz ERBW 1.1GS/s 8b Two-Step SAR ADC with Recursive-Weight DAC 4: 1.26*1e-3, #reference: Area-Efficient 1GS/s 6b SAR ADC with Charge-Injection-Cell-Based DAC 5: 4e-3, #ASPDAC1 6: 1.26e-3, #ASPDAC2 7: 0.7e-3 #ASPDAC3 } if self.ADC_choice != -1: assert self.ADC_choice in [1,2,3,4,5,6,7] self.ADC_power = ADC_power_dict[self.ADC_choice] def calculate_ADC_sample_rate(self): #unit: GSamples/s ADC_sample_rate_dict = {1: 1.5, #reference: A 10b 1.5GS/s Pipelined-SAR ADC with Background Second-Stage Common-Mode Regulation and Offset Calibration in 14nm CMOS FinFET 2: 1.28, #reference: ISAAC: A Convolutional Neural Network Accelerator with In-Situ Analog Arithmetic in Crossbars 3: 1.1, #reference: A >3GHz ERBW 1.1GS/s 8b Two-Step SAR ADC with Recursive-Weight DAC 4: 1, #reference: Area-Efficient 1GS/s 6b SAR ADC with Charge-Injection-Cell-Based DAC 5: 1.1, #ASPDAC1 6: 1, #ASPDAC2 7:1 #ASPDAC3 } if self.ADC_choice != -1: assert self.ADC_choice in [1,2,3,4,5,6,7] self.ADC_sample_rate = ADC_sample_rate_dict[self.ADC_choice] def calculate_ADC_latency(self): # unit: ns self.ADC_latency = 1 / self.ADC_sample_rate * (self.ADC_precision + 2) def calculate_ADC_energy(self): #unit: nJ self.ADC_energy = self.ADC_latency * self.ADC_power def config_ADC_interval(self, SimConfig_path, WL_num = 0): if self.ADC_interval[0] == -1: #User defined ADC_config = cp.ConfigParser() ADC_config.read(SimConfig_path, encoding='UTF-8') self.ADC_interval = (2**self.ADC_precision-1) * [0.0] V_in = list(map(float, ADC_config.get('Device level', 'Read_Voltage').split(','))) R = list(map(float, ADC_config.get('Device level', 'Device_Resistance').split(','))) # Rs = math.sqrt(R[0]*R[-1]) Rs = float(ADC_config.get('Crossbar level', 'Load_Resistance')) if Rs == -1: Rs = math.sqrt(R[0] * R[-1]) assert Rs > 0, "Load resistance must be > 0" step = math.ceil(WL_num/(2**self.ADC_precision)) temp = step V_max = WL_num*V_in[-1]/R[-1]*Rs for i in range(len(self.ADC_interval)): if temp < WL_num+1: self.ADC_interval[i] = 0.5 * ((temp-1)*V_in[-1]/R[-1]*Rs+(WL_num-temp+1)*V_in[0]/R[-1]*Rs+ temp*V_in[-1]/R[-1]*Rs+(WL_num-temp)*V_in[0]/R[0]*Rs) temp += step else: self.ADC_interval[i] = V_max # print(self.ADC_interval) def calculate_sensing_results(self, V_in): # Notice: before calculating sensing results, config_ADC_interval must be calculated start = 0 end = 2**self.ADC_precision-2 V_out = 0 temp = 0 if V_in < self.ADC_interval[0]: V_out = 0 elif V_in > self.ADC_interval[-1]: V_out = 2**self.ADC_precision -1 else: while start < end: temp = int(1/2*(start+end)) if temp == start: V_out = temp + 1 break if V_in > self.ADC_interval[temp]: start = temp V_out = temp else: end = temp V_out = temp return V_out def ADC_output(self): if self.ADC_choice == -1: print("ADC_choice: User defined") else: print("ADC_choice:", self.ADC_choice) print("ADC_area:", self.ADC_area, "um^2") print("ADC_precision:", self.ADC_precision, "bit") print("ADC_power:", self.ADC_power, "W") print("ADC_sample_rate:", self.ADC_sample_rate, "Gbit/s") print("ADC_latency:", self.ADC_latency, "ns") print("ADC_energy:", self.ADC_energy, "nJ") def ADC_test(): print("load file:",test_SimConfig_path) _ADC = ADC(test_SimConfig_path) _ADC.calculate_ADC_area() _ADC.calculate_ADC_power() _ADC.calculate_ADC_sample_rate() _ADC.calculate_ADC_latency() _ADC.calculate_ADC_energy() _ADC.config_ADC_interval(test_SimConfig_path,256) result = _ADC.calculate_sensing_results(100) _ADC.ADC_output() if __name__ == '__main__': ADC_test()<file_sep>/MNSIM/Accuracy_Model/Weight_update.py import sys import os import math import random import configparser as cp import numpy as np from MNSIM.Hardware_Model import * from MNSIM.Hardware_Model.Crossbar import crossbar from MNSIM.Interface.interface import * def weight_update(SimConfig_path, weight, is_SAF=0, is_Variation=0, is_Rratio=0): # print("Hardware config file is loaded:", SimConfig_path) wu_config = cp.ConfigParser() wu_config.read(SimConfig_path, encoding='UTF-8') SAF_dist = list(map(int, wu_config.get('Device level', 'Device_SAF').split(','))) variation = float(wu_config.get('Device level', 'Device_Variation')) device_level = int(wu_config.get('Device level', 'Device_Level')) assert device_level >= 0, "NVM resistance level < 0" device_resistance = np.array(list(map(float, wu_config.get('Device level', 'Device_Resistance').split(',')))) assert device_level == len(device_resistance), "NVM resistance setting error" # assume the resistance distribution of MLC is linear max_value = 2 ** math.floor(math.log2(device_level)) - 1 interval = 0 for i in range(len(device_resistance) - 1): interval += 1 / device_resistance[i + 1] - 1 / device_resistance[i] interval /= len(device_resistance) - 1 unit_conduntance = max_value/(1/device_resistance[-1]) for i in range(len(weight)): if weight[i] is not None: for label, value in weight[i].items(): # print(value.shape) if (is_Rratio|is_Variation): for j in range(len(device_resistance)): temp_resistance = 0 if(is_Variation): temp_resistance = np.random.normal(loc=0, scale=device_resistance[j] * variation / 100) value = np.where(value == j, 1/(device_resistance[j]+temp_resistance)*unit_conduntance, value) if (is_SAF): SAF = np.random.random_sample(value.shape) value = np.where(SAF < float(SAF_dist[0] / 100), 0, value) value = np.where(SAF > 1 - float(SAF_dist[-1] / 100), max_value, value) # print(value) weight[i].update({label: value.astype(float)}) return weight if __name__ == '__main__': SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "SimConfig.ini") weights_file_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"cifar10_lenet_params.pth") __TestInterface = TrainTestInterface('lenet', 'MNSIM.Interface.cifar10', SimConfig_path, weights_file_path, 0) structure_file = __TestInterface.get_structure() weight = __TestInterface.get_net_bits() weight_2 = weight_update(SimConfig_path, weight, is_Variation=0,is_SAF=0,is_Rratio=1) # weight_2 = _test.non_ideal_analyzer() # print(weight_2[0]['split0_weight0_positive'].dtype) weight = __TestInterface.get_net_bits() # print(weight_2-weight) print(__TestInterface.set_net_bits_evaluate(weight_2)) <file_sep>/MNSIM/Latency_Model/PE_latency.py #!/usr/bin/python # -*-coding:utf-8-*- import torch import sys import os import math import configparser as cp work_path = os.path.dirname(os.getcwd()) sys.path.append(work_path) from MNSIM.Hardware_Model.PE import ProcessElement from MNSIM.Hardware_Model.Buffer import buffer from MNSIM.Interface.interface import * class PE_latency_analysis(): def __init__(self, SimConfig_path, read_row=0, read_column=0, indata=0, rdata=0, inprecision = 8, default_buf_size = 16): # read_row: activated WL number in crossbar # read_column: activated BL number in crossbar # indata: volume of input data (for PE) (Byte) # rdata: volume of data from buffer to iReg (Byte) # outdata: volume of output data (for PE) (Byte) # inprecision: input data precision of each Xbar # default_buf_size: default input buffer size (KB) PEl_config = cp.ConfigParser() PEl_config.read(SimConfig_path, encoding='UTF-8') self.inbuf = buffer(SimConfig_path=SimConfig_path, buf_level=1, default_buf_size=default_buf_size) self.PE = ProcessElement(SimConfig_path) self.inbuf.calculate_buf_write_latency(indata) self.PE_buf_wlatency = self.inbuf.buf_wlatency # unit: ns self.digital_period = 1/float(PEl_config.get('Digital module', 'Digital_Frequency'))*1e3 self.inbuf.calculate_buf_read_latency(rdata) self.PE_buf_rlatency = self.inbuf.buf_rlatency multiple_time = math.ceil(inprecision/self.PE.DAC_precision) * math.ceil(read_row/self.PE.PE_group_DAC_num) *\ math.ceil(read_column/self.PE.PE_group_ADC_num) self.PE.calculate_xbar_read_latency() Transistor_Tech = int(PEl_config.get('Crossbar level', 'Transistor_Tech')) XBar_size = list(map(float, PEl_config.get('Crossbar level', 'Xbar_Size').split(','))) DAC_num = int(PEl_config.get('Process element level', 'DAC_Num')) ADC_num = int(PEl_config.get('Process element level', 'ADC_Num')) Row = XBar_size[0] Column = XBar_size[1] # ns (using NVSim) decoderLatency_dict = { 1:0.27933 # 1:8, technology 65nm } decoder1_8 = decoderLatency_dict[1] Row_per_DAC = math.ceil(Row/DAC_num) m = 1 while Row_per_DAC > 0: Row_per_DAC = Row_per_DAC // 8 m += 1 self.decoderLatency = m * decoder1_8 # ns muxLatency_dict = { 1:32.744/1000 } mux8_1 = muxLatency_dict[1] m = 1 Column_per_ADC = math.ceil(Column / ADC_num) while Column_per_ADC > 0: Column_per_ADC = Column_per_ADC // 8 m += 1 self.muxLatency = m * mux8_1 self.xbar_latency = multiple_time * self.PE.xbar_read_latency self.PE.calculate_DAC_latency() self.DAC_latency = multiple_time * self.PE.DAC_latency self.PE.calculate_ADC_latency() self.ADC_latency = multiple_time * self.PE.ADC_latency self.iReg_latency = math.ceil(read_row/self.PE.PE_group_DAC_num)*math.ceil(read_column/self.PE.PE_group_ADC_num)*self.digital_period+\ multiple_time*self.digital_period # write and read self.shiftreg_latency = multiple_time * self.digital_period self.input_demux_latency = multiple_time*self.decoderLatency self.adder_latency = math.ceil(read_column/self.PE.PE_group_ADC_num)*math.ceil(math.log2(self.PE.group_num))*self.digital_period self.output_mux_latency = multiple_time*self.muxLatency self.computing_latency = self.DAC_latency+self.xbar_latency+self.ADC_latency self.oReg_latency = math.ceil(read_column/self.PE.PE_group_ADC_num)*self.digital_period self.PE_digital_latency = self.iReg_latency + self.shiftreg_latency + self.input_demux_latency + \ self.adder_latency + self.output_mux_latency + self.oReg_latency self.PE_latency = self.PE_buf_wlatency + self.PE_buf_rlatency + self.computing_latency + self.PE_digital_latency def update_PE_latency(self, indata=0, rdata=0): # update the latency computing when indata and rdata change self.inbuf.calculate_buf_write_latency(indata) self.PE_buf_wlatency = self.inbuf.buf_wlatency self.inbuf.calculate_buf_read_latency(rdata) self.PE_buf_rlatency = self.inbuf.buf_rlatency self.PE_latency = self.PE_buf_wlatency + self.PE_buf_rlatency + self.computing_latency + self.PE_digital_latency if __name__ == '__main__': test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "SimConfig.ini") _test = PE_latency_analysis(test_SimConfig_path, 100,100,32,96) print(_test) <file_sep>/MNSIM/Hardware_Model/Crossbar.py #!/usr/bin/python #-*-coding:utf-8-*- import configparser as cp import os import math from MNSIM.Hardware_Model.Device import device import numpy as np test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"SimConfig.ini") # Default SimConfig file path: MNSIM_Python/SimConfig.ini class crossbar(device): def __init__(self, SimConfig_path): device.__init__(self,SimConfig_path) xbar_config = cp.ConfigParser() xbar_config.read(SimConfig_path, encoding='UTF-8') self.xbar_size = list(map(int, xbar_config.get('Crossbar level', 'Xbar_Size').split(','))) self.xbar_row = int(self.xbar_size[0]) self.xbar_column = int(self.xbar_size[1]) self.cell_type = xbar_config.get('Crossbar level', 'Cell_Type') self.transistor_tech = int(xbar_config.get('Crossbar level', 'Transistor_Tech')) self.wire_resistance = float(xbar_config.get('Crossbar level', 'Wire_Resistance')) self.wire_capacity = float(xbar_config.get('Crossbar level', 'Wire_Capacity')) self.area_calculation_method = int(xbar_config.get('Crossbar level', 'Area_Calculation')) self.xbar_area = 0 self.xbar_simulation_level = int(xbar_config.get('Algorithm Configuration', 'Simulation_Level')) self.xbar_load_resistance = float(xbar_config.get('Crossbar level', 'Load_Resistance')) if self.xbar_load_resistance == -1: self.xbar_load_resistance = math.sqrt(self.device_resistance[0] * self.device_resistance[-1]) assert self.xbar_load_resistance >0, "Load resistance must be > 0" self.xbar_write_matrix = np.zeros((self.xbar_row,self.xbar_column))# * 1/self.device_resistance[-1] self.xbar_write_vector = np.zeros((self.xbar_row,1)) self.xbar_read_matrix = np.zeros((self.xbar_row, self.xbar_column))# * 1/self.device_resistance[-1] self.xbar_read_vector = np.zeros((self.xbar_row, 1)) self.xbar_read_power = 0 self.xbar_read_latency = 0 self.xbar_write_power = 0 self.xbar_write_latency = 0 self.xbar_read_energy = 0 self.xbar_write_energy = 0 self.xbar_num_write_row = 0 self.xbar_num_write_column = 0 self.xbar_num_read_row = 0 self.xbar_num_read_column = 0 self.xbar_utilization = 0 # print("Crossbar configuration is loaded") def xbar_write_config(self, write_row = None, write_column = None, write_matrix = None, write_vector = None): # write_row and write_column are the sizes of occupied parts in crossbars # write_matrix: the target weight matrix of the write operation, write_vector: the vector of write voltages if self.xbar_simulation_level == 0: # behavior level simulation if write_row is None: self.xbar_num_write_row = self.xbar_row else: assert write_row >= 0, "Num of occupied row (write) < 0" self.xbar_num_write_row = write_row if write_column is None: self.xbar_num_write_column = self.xbar_column else: assert write_column >= 0, "Num of occupied column (write) < 0" self.xbar_num_write_column = write_column else: # estimation level simulation if write_matrix is None or len(write_matrix) == 0 or ((len(write_matrix)>0) & (len(write_matrix[0])==0)): self.xbar_write_matrix = 1/math.sqrt(float(self.device_resistance[0])*float(self.device_resistance[-1])) \ * np.ones((self.xbar_row,self.xbar_column)) self.xbar_num_write_column = self.xbar_column self.xbar_num_write_row = self.xbar_row else: for i in range(len(write_matrix)): for j in range(len(write_matrix[0])): assert int(write_matrix[i][j]) < self.device_level, "Weight value (write) exceeds the resistance range" self.xbar_write_matrix[i][j] = 1/self.device_resistance[int(write_matrix[i][j])] self.xbar_num_write_row = len(write_matrix) self.xbar_num_write_column = len(write_matrix[0]) if write_vector is None or len(write_vector) == 0 or ((len(write_vector)>0) & (len(write_vector[0])==0)): self.xbar_write_vector = math.sqrt((self.device_write_voltage[0]*self.device_write_voltage[-1])) \ * np.ones((self.xbar_row,1)) else: for i in range(len(write_vector)): assert int(write_vector[i][0]) < self.device_write_voltage_level, "Write voltage value is out of range" self.xbar_write_vector[i][0] = self.device_write_voltage[int(write_vector[i][0])] self.xbar_utilization = self.xbar_num_write_column * self.xbar_num_write_row / (self.xbar_row*self.xbar_column) def xbar_read_config(self, read_row = None, read_column = None, read_matrix = None, read_vector = None): # read_row and read_column are the sizes of occupied parts in crossbars # read_matrix: the weight matrix stored in the crossbar, read_vector: read voltage vector (activation input) if self.xbar_simulation_level == 0: # behavior level simulation if read_row is None: self.xbar_num_read_row = self.xbar_row else: assert read_row >= 0, "Num of occupied row (read) < 0" self.xbar_num_read_row = read_row if read_column is None: self.xbar_num_read_column = self.xbar_column else: assert read_column >= 0, "Num of occupied column (read) < 0" self.xbar_num_read_column = read_column else: # estimation level simulation if read_matrix is None or len(read_matrix) == 0 or ((len(read_matrix)>0) & (len(read_matrix[0])==0)): self.xbar_read_matrix = 1/math.sqrt(float(self.device_resistance[0])*float(self.device_resistance[-1])) \ * np.ones((self.xbar_row,self.xbar_column)) self.xbar_num_read_column = self.xbar_column self.xbar_num_read_row = self.xbar_row else: for i in range(len(read_matrix)): for j in range(len(read_matrix[0])): assert int(read_matrix[i][j]) < self.device_level, "Weight value (read) exceeds the resistance range" self.xbar_read_matrix[i][j] = 1/self.device_resistance[int(read_matrix[i][j])] self.xbar_num_read_row = len(read_matrix) self.xbar_num_read_column = len(read_matrix[0]) if read_vector is None or len(read_vector) == 0 or ((len(read_vector)>0) & (len(read_vector[0])==0)): # self.xbar_read_vector = math.sqrt((self.device_read_voltage[0]*self.device_read_voltage[-1])) \ # * np.ones((self.xbar_row,1)) self.xbar_read_vector = math.sqrt((self.device_read_voltage[0]**2 + self.device_read_voltage[-1]**2)/2) * np.ones((self.xbar_row,1)) # self.xbar_read_vector = self.device_read_voltage[-1] * np.ones((self.xbar_row,1)) else: for i in range(len(read_vector)): assert int(read_vector[i][0]) < self.device_read_voltage_level, "Vector value exceeds the input voltage range" self.xbar_read_vector[i][0] = self.device_read_voltage[int(read_vector[i][0])] self.xbar_utilization = self.xbar_num_read_row * self.xbar_num_read_column / (self.xbar_row * self.xbar_column) def calculate_xbar_area(self): # Area unit: um^2 if self.area_calculation_method == 0: area_factor = 1 self.xbar_area = area_factor * self.xbar_row * self.xbar_column * self.device_area else: WL_ratio = 3 # WL_ratio is the technology parameter W/L of the transistor if self.cell_type[0] == '0': self.xbar_area = 4 * self.xbar_row * self.xbar_column * self.device_tech**2 * 1e-6 else: self.xbar_area = 3 * (WL_ratio + 1) * self.xbar_row * self.xbar_column * self.device_tech**2 * 1e-6 def calculate_wire_resistance(self): #unit: ohm if self.wire_resistance < 0: self.wire_resistance = 2.82 #ref: Overcoming the challenges of crossbar resistive memory architectures #TODO: Update the wire resistance calculation according to different technology sizes def calculate_wire_capacity(self): #unit: fF if self.wire_capacity < 0: self.wire_capacity = 1 #TODO: Update the wire capacity calculation according to different technology sizes def calculate_xbar_read_latency(self): # unit: ns self.calculate_wire_resistance() self.calculate_wire_capacity() if self.cell_type == '0T1R': size = self.xbar_row*self.xbar_column / 1024 / 8 # KB wire_latency = 0.001 * (0.0002 * size ** 2 + 5 * 10 ** -6 * size + 4 * 10 ** -14) # ns else: size = self.xbar_row * self.xbar_column / 1024 / 8 # KB wire_latency = 0.001 * (0.0002 * size ** 2 + 5 * 10 ** -6 * size + 4 * 10 ** -14) # ns # wire_latency = 0.5 * self.wire_resistance * self.wire_capacity * self.xbar_row 1e3 #TODO: Update the calculation formula considering the branches self.xbar_read_latency = self.device_read_latency + wire_latency def calculate_xbar_write_latency(self): # Notice: before calculating write latency, xbar_write_config must be executed self.xbar_write_latency = self.device_write_latency * self.xbar_num_write_row # self.xbar_write_latency = self.device_write_latency * min(math.ceil(num_write_row/num_multi_row), num_write_column)\ # * min(num_multi_row, num_write_row) #unit: ns #Assuming that the write operation of cells in one row can be performed concurrently def calculate_xbar_read_power(self): # unit: W # cal_mode: 0: simple estimation, 1: detailed simulation # Notice: before calculating power, xbar_read_config must be executed # self.xbar_read_config(read_matrix,read_vector) self.xbar_read_power = 0 #Assuming that in 0T1R structure, the read power of unselected cell is 1/4 of the selected cells' read power if self.xbar_simulation_level == 0: assert self.xbar_utilization <= 1, "Crossbar usage utilization rate > 1" self.calculate_device_read_power() self.xbar_read_power += self.xbar_num_read_row * self.xbar_num_read_column * self.device_read_power if self.cell_type[0] =='0': self.calculate_device_read_power(self.device_resistance[0]) self.xbar_read_power += 0.25 * self.xbar_num_read_row * (self.xbar_column - self.xbar_num_read_column) \ * self.device_read_power else: temp_v2 = self.xbar_read_vector * self.xbar_read_vector self.xbar_read_power += (self.xbar_read_matrix.T.dot(temp_v2)).sum() if self.cell_type[0] == '0': temp_matrix = np.ones((self.xbar_num_read_row, self.xbar_column-self.xbar_num_read_column)) / self.device_resistance[0] # print("temp_matrix",temp_matrix.T) # print("temp_vector",temp_v2[0:self.xbar_num_read_column]) # print("unused power", 0.25* (temp_matrix.T.dot(temp_v2[0:self.xbar_num_read_column])).sum()) self.xbar_read_power += 0.25* (temp_matrix.T.dot(temp_v2[0:self.xbar_num_read_column])).sum() def calculate_xbar_write_power(self): # unit: W # cal_mode: 0: simple estimation, 1: detailed simulation # Notice: before calculating power, xbar_write_config must be executed # TODO: consider the write power of unselected cells # self.xbar_write_config(write_matrix, write_vector) self.xbar_write_power = 0 # Assuming that the write operation of cells in one row can be performed concurrently if self.xbar_simulation_level == 0: self.calculate_device_write_power() self.xbar_write_power = self.xbar_num_write_column * self.device_write_power else: temp_v2 = self.xbar_write_vector * self.xbar_write_vector assert self.xbar_num_write_row>0, "xbar_num_write_row is 0, consider use the write_config function" self.xbar_write_power = (self.xbar_write_matrix.T.dot(temp_v2)).sum() / self.xbar_num_write_row def calculate_xbar_read_energy(self): #unit: nJ self.xbar_read_energy = self.xbar_read_power * self.xbar_read_latency def calculate_xbar_write_energy(self): #unit: nJ self.xbar_write_energy = self.xbar_write_power * self.device_write_latency #Do not consider the wire power in write operation def xbar_output(self): device.device_output(self) print("crossbar_size:", self.xbar_size) print("cell_type:", self.cell_type) print("transistor_tech:", self.transistor_tech, "nm") print("wire_resistance:", self.wire_resistance, "ohm") print("wire_capacity:", self.wire_capacity, "fF") print("crossbar_area", self.xbar_area, "um^2") print("load_resistance", self.xbar_load_resistance, "ohm") print("crossbar_utilization_rate", self.xbar_utilization) print("crossbar_read_power:", self.xbar_read_power, "W") print("crossbar_read_latency:", self.xbar_read_latency, "ns") print("crossbar_read_energy:", self.xbar_read_energy, "nJ") print("crossbar_write_power:", self.xbar_write_power, "W") print("crossbar_write_latency:", self.xbar_write_latency, "ns") print("crossbar_write_energy:", self.xbar_write_energy, "nJ") def xbar_test(): print("load file:",test_SimConfig_path) _xbar = crossbar(test_SimConfig_path) print('------------') _xbar.xbar_read_config() _xbar.calculate_xbar_area() _xbar.calculate_xbar_read_latency() _xbar.calculate_xbar_read_power() _xbar.calculate_xbar_read_energy() _xbar.xbar_output() if __name__ == '__main__': xbar_test() <file_sep>/MNSIM/Latency_Model/Model_latency.py #!/usr/bin/python # -*-coding:utf-8-*- import sys import os import configparser as cp work_path = os.path.dirname(os.getcwd()) sys.path.append(work_path) import numpy as np import pandas as pd from MNSIM.Interface.interface import * from MNSIM.Mapping_Model.Tile_connection_graph import TCG from MNSIM.Latency_Model.Tile_latency import tile_latency_analysis from MNSIM.Latency_Model.Pooling_latency import pooling_latency_analysis from MNSIM.NoC.interconnect_estimation import interconnect_estimation from MNSIM.Hardware_Model.Buffer import buffer def merge_interval(interval): if len(interval) == 0: return [] result = [] interval.sort() lower_bound = interval[0][0] upper_bound = interval[0][1] for index in range(1, len(interval)): if interval[index][0] > upper_bound: result.append([lower_bound, upper_bound]) lower_bound = interval[index][0] upper_bound = interval[index][1] else: if interval[index][1] > upper_bound: upper_bound = interval[index][1] result.append([lower_bound, upper_bound]) return result def Search(value, data): pos = 0 if value > data[-1]: return len(data) while (value > data[pos]): pos += 1 return pos def Split_map(padding, outputsize, multiple): # 对下一层进行划分 base = outputsize // multiple res = outputsize - base * multiple split = [] # split the outputsize if multiple == 1: split.append(outputsize) else: for i in range(multiple): if i < res: split.append(base + 1) else: split.append(base) return split def inoutsize_conversion(kernelsize, padding, stride, outputsize): # calculate the input size according to the output size return kernelsize+(outputsize-1)*stride-2*padding class Model_latency(): def __init__(self, NetStruct, SimConfig_path, multiple=None, TCG_mapping=None): modelL_config = cp.ConfigParser() modelL_config.read(SimConfig_path, encoding='UTF-8') NoC_Compute = int(modelL_config.get('Algorithm Configuration', 'NoC_enable')) self.inter_tile_bandwidth = float(modelL_config.get('Tile level', 'Inter_Tile_Bandwidth')) self.NetStruct = NetStruct if multiple is None: multiple = [1] * len(self.NetStruct) if TCG_mapping is None: TCG_mapping = TCG(NetStruct, SimConfig_path, multiple) self.graph = TCG_mapping self.graph.mapping_net() self.graph.calculate_transfer_distance() self.begin_time = [] self.finish_time = [] self.layer_tile_latency = [] if NoC_Compute == 1: self.Noc_latency = interconnect_estimation() else: self.Noc_latency = [0] * len(self.NetStruct) self.SimConfig_path = SimConfig_path self.compute_interval = [] self.occupancy = [] self.multiple = multiple self.buffer_latency = [] self.buffer_r_latency = [] self.buffer_w_latency = [] self.inbuffer_latency = [] # PE level input buffer latency self.outbuffer_latency = [] # Tile level output buffer latency self.computing_latency = [] self.DAC_latency = [] self.xbar_latency = [] self.ADC_latency = [] self.digital_latency = [] self.iReg_latency = [] self.input_demux_latency = [] self.output_mux_latency = [] self.shiftreg_latency = [] self.adder_latency = [] self.oReg_latency = [] self.jointmodule_latency = [] self.pooling_latency = [] self.intra_tile_latency = [] self.inter_tile_latency = [] self.tile_merge_latency = [] self.tile_transfer_latency = [] self.total_buffer_latency = [] self.total_computing_latency = [] self.total_DAC_latency = [] self.total_xbar_latency = [] self.total_ADC_latency = [] self.total_digital_latency = [] self.total_intra_tile_latency = [] self.total_inter_tile_latency = [] self.total_tile_merge_latency = [] self.total_tile_transfer_latency = [] self.total_iReg_latency = [] self.total_oReg_latency = [] self.total_input_demux_latency = [] self.total_output_mux_latency = [] self.total_shiftreg_latency = [] self.total_adder_latency = [] self.total_jointmodule_latency = [] self.total_pooling_latency = [] self.total_buffer_r_latency = [] self.total_buffer_w_latency = [] self.layer_type = [] self.layer_split = [] self.pre_max_time = 0 def layer_latency_initial(self): self.begin_time.append([]) self.finish_time.append([]) self.compute_interval.append([]) self.buffer_latency.append([]) self.computing_latency.append([]) self.DAC_latency.append([]) self.xbar_latency.append([]) self.ADC_latency.append([]) self.buffer_r_latency.append([]) self.buffer_w_latency.append([]) self.inbuffer_latency.append([]) self.outbuffer_latency.append([]) self.iReg_latency.append([]) self.input_demux_latency.append([]) self.output_mux_latency.append([]) self.shiftreg_latency.append([]) self.adder_latency.append([]) self.oReg_latency.append([]) self.jointmodule_latency.append([]) self.pooling_latency.append([]) self.digital_latency.append([]) self.intra_tile_latency.append([]) self.inter_tile_latency.append([]) self.tile_merge_latency.append([]) self.tile_transfer_latency.append([]) def Judge(self, last_layer_id ,last_layer_pos, current_layer_id): # calculate the position of the most time consuming output of the input layer (used in replicate mode) layer_dict = self.NetStruct[current_layer_id][0][0] # print(current_layer_id) if layer_dict['type'] is not 'pooling': assert layer_dict['type'] == 'conv', "only conv layer could be judged" kernelsize = int(layer_dict['Kernelsize']) last_split = self.layer_split[last_layer_id] input_size = list(map(int, layer_dict['Inputsize']))[1] Row = (last_layer_pos+1) // input_size last_column = (last_layer_pos+1) % input_size # begin from 0 m = 0 pos = 0 while last_column > last_split[m]: last_column -= last_split[m] m += 1 if (last_column - kernelsize >= 0) or (m == 0): return last_layer_pos else: for i in range(m): pos += last_split[m] # get the last data point in each multiple return pos - 1 + Row * input_size def pipe_result_update(self, layer_type='conv', begin_time=0, compute_time=0, layer_id=0, temp_tile_latency=None, temp_pooling_latency = None, global_buf = None, merge_time=0, transfer_time=0, output_size=0): if layer_type == 'conv': self.begin_time[layer_id].append(begin_time) self.finish_time[layer_id].append(compute_time) self.compute_interval[layer_id].append([begin_time, compute_time]) self.buffer_latency[layer_id].append(temp_tile_latency.tile_buf_wlatency + temp_tile_latency.tile_buf_rlatency + temp_tile_latency.PE_buf_rlatency + temp_tile_latency.PE_buf_wlatency) self.computing_latency[layer_id].append(temp_tile_latency.computing_latency) self.DAC_latency[layer_id].append(temp_tile_latency.DAC_latency) self.xbar_latency[layer_id].append(temp_tile_latency.xbar_latency) self.ADC_latency[layer_id].append(temp_tile_latency.ADC_latency) self.buffer_r_latency[layer_id].append(temp_tile_latency.tile_buf_rlatency+temp_tile_latency.PE_buf_rlatency) self.buffer_w_latency[layer_id].append(temp_tile_latency.tile_buf_wlatency+temp_tile_latency.PE_buf_wlatency) self.iReg_latency[layer_id].append(temp_tile_latency.iReg_latency) self.input_demux_latency[layer_id].append(temp_tile_latency.input_demux_latency) self.output_mux_latency[layer_id].append(temp_tile_latency.output_mux_latency) self.shiftreg_latency[layer_id].append(temp_tile_latency.shiftreg_latency) self.adder_latency[layer_id].append(temp_tile_latency.adder_latency) self.oReg_latency[layer_id].append(temp_tile_latency.oReg_latency) self.jointmodule_latency[layer_id].append(temp_tile_latency.jointmodule_latency) self.digital_latency[layer_id].append(temp_tile_latency.iReg_latency + temp_tile_latency.input_demux_latency + temp_tile_latency.output_mux_latency + temp_tile_latency.shiftreg_latency + temp_tile_latency.adder_latency + temp_tile_latency.oReg_latency + temp_tile_latency.jointmodule_latency) self.pooling_latency[layer_id].append(0) self.intra_tile_latency[layer_id].append(temp_tile_latency.transfer_latency) self.inter_tile_latency[layer_id].append(merge_time + transfer_time) self.tile_merge_latency[layer_id].append(merge_time) self.tile_transfer_latency[layer_id].append(transfer_time) elif layer_type == 'fc': self.begin_time[layer_id] = output_size * [begin_time] self.finish_time[layer_id] = output_size * [compute_time] self.compute_interval[layer_id].append([begin_time, compute_time]) self.buffer_latency[layer_id].append(temp_tile_latency.tile_buf_wlatency + temp_tile_latency.tile_buf_rlatency + temp_tile_latency.PE_buf_rlatency + temp_tile_latency.PE_buf_wlatency) self.computing_latency[layer_id].append(temp_tile_latency.computing_latency) self.DAC_latency[layer_id].append(temp_tile_latency.DAC_latency) self.xbar_latency[layer_id].append(temp_tile_latency.xbar_latency) self.ADC_latency[layer_id].append(temp_tile_latency.ADC_latency) self.buffer_r_latency[layer_id].append(temp_tile_latency.tile_buf_rlatency+temp_tile_latency.PE_buf_rlatency) self.buffer_w_latency[layer_id].append(temp_tile_latency.tile_buf_wlatency+temp_tile_latency.PE_buf_wlatency) self.iReg_latency[layer_id].append(temp_tile_latency.iReg_latency) self.input_demux_latency[layer_id].append(temp_tile_latency.input_demux_latency) self.output_mux_latency[layer_id].append(temp_tile_latency.output_mux_latency) self.shiftreg_latency[layer_id].append(temp_tile_latency.shiftreg_latency) self.adder_latency[layer_id].append(temp_tile_latency.adder_latency) self.oReg_latency[layer_id].append(temp_tile_latency.oReg_latency) self.jointmodule_latency[layer_id].append(temp_tile_latency.jointmodule_latency) self.digital_latency[layer_id].append(temp_tile_latency.iReg_latency + temp_tile_latency.input_demux_latency + temp_tile_latency.output_mux_latency + temp_tile_latency.shiftreg_latency + temp_tile_latency.adder_latency + temp_tile_latency.oReg_latency + temp_tile_latency.jointmodule_latency) self.pooling_latency[layer_id].append(0) self.intra_tile_latency[layer_id].append(temp_tile_latency.transfer_latency) self.inter_tile_latency[layer_id].append(merge_time + transfer_time) self.tile_merge_latency[layer_id].append(merge_time) self.tile_transfer_latency[layer_id].append(transfer_time) elif layer_type == 'pooling': self.begin_time[layer_id].append(begin_time) self.finish_time[layer_id].append(compute_time) self.compute_interval[layer_id].append([begin_time, compute_time]) self.buffer_latency[layer_id].append(temp_pooling_latency.inbuf_wlatency + temp_pooling_latency.inbuf_rlatency + temp_pooling_latency.outbuf_wlatency + temp_pooling_latency.outbuf_rlatency) self.computing_latency[layer_id].append(0) self.DAC_latency[layer_id].append(0) self.xbar_latency[layer_id].append(0) self.ADC_latency[layer_id].append(0) self.buffer_r_latency[layer_id].append(temp_pooling_latency.inbuf_rlatency + temp_pooling_latency.outbuf_rlatency) self.buffer_w_latency[layer_id].append(temp_pooling_latency.inbuf_wlatency + temp_pooling_latency.outbuf_wlatency) self.iReg_latency[layer_id].append(0) self.input_demux_latency[layer_id].append(0) self.output_mux_latency[layer_id].append(0) self.shiftreg_latency[layer_id].append(0) self.adder_latency[layer_id].append(0) self.oReg_latency[layer_id].append(0) self.jointmodule_latency[layer_id].append(0) self.digital_latency[layer_id].append(0) self.pooling_latency[layer_id].append(temp_pooling_latency.digital_latency) self.intra_tile_latency[layer_id].append(0) self.inter_tile_latency[layer_id].append(merge_time + transfer_time) self.tile_merge_latency[layer_id].append(merge_time) self.tile_transfer_latency[layer_id].append(transfer_time) elif layer_type == 'element_sum': self.begin_time[layer_id].append(begin_time) self.finish_time[layer_id].append(compute_time) self.compute_interval[layer_id].append([begin_time, compute_time]) self.buffer_latency[layer_id].append(global_buf.buf_rlatency+global_buf.buf_wlatency) self.computing_latency[layer_id].append(0) self.DAC_latency[layer_id].append(0) self.xbar_latency[layer_id].append(0) self.ADC_latency[layer_id].append(0) self.buffer_r_latency[layer_id].append(global_buf.buf_rlatency) self.buffer_w_latency[layer_id].append(global_buf.buf_wlatency) self.iReg_latency[layer_id].append(0) self.input_demux_latency[layer_id].append(0) self.output_mux_latency[layer_id].append(0) self.shiftreg_latency[layer_id].append(0) self.adder_latency[layer_id].append(0) self.oReg_latency[layer_id].append(0) self.jointmodule_latency[layer_id].append(0) self.digital_latency[layer_id].append(10) self.pooling_latency[layer_id].append(0) self.intra_tile_latency[layer_id].append(0) self.inter_tile_latency[layer_id].append(merge_time + transfer_time) self.tile_merge_latency[layer_id].append(merge_time) self.tile_transfer_latency[layer_id].append(transfer_time) def calculate_model_latency_nopipe(self): for layer_id in range(len(self.NetStruct)): layer_dict = self.NetStruct[layer_id][0][0] if layer_id == 0: # for the first layer, first layer must be conv layer self.layer_latency_initial() output_size = list(map(int, layer_dict['Outputsize'])) input_size = list(map(int, layer_dict['Inputsize'])) kernelsize = int(layer_dict['Kernelsize']) stride = int(layer_dict['Stride']) inputchannel = int(layer_dict['Inputchannel']) outputchannel = int(layer_dict['Outputchannel']) padding = int(layer_dict['Padding']) inputbit = int(layer_dict['Inputbit']) outputbit = int(layer_dict['outputbit']) # print(self.graph.layer_tileinfo[layer_id]['max_row']) input_channel_PE = self.graph.layer_tileinfo[layer_id]['max_row'] / (kernelsize ** 2) # the input channel number each PE processes temp_tile_latency = tile_latency_analysis(SimConfig_path=self.SimConfig_path, read_row=self.graph.layer_tileinfo[layer_id]['max_row'], read_column=self.graph.layer_tileinfo[layer_id]['max_column'], indata=0, rdata=0, inprecision=inputbit, PE_num=self.graph.layer_tileinfo[layer_id]['max_PE'], default_inbuf_size=self.graph.max_inbuf_size, default_outbuf_size=self.graph.max_outbuf_size ) temp_tile_latency.outbuf.calculate_buf_read_latency(rdata = (self.graph.layer_tileinfo[layer_id]['max_column']* outputbit*self.graph.layer_tileinfo[layer_id]['max_PE']/8)) temp_tile_latency.tile_buf_rlatency = temp_tile_latency.outbuf.buf_rlatency merge_time = temp_tile_latency.tile_buf_rlatency+self.graph.inLayer_distance[0][layer_id] * \ (temp_tile_latency.digital_period +self.graph.layer_tileinfo[layer_id]['max_column'] * self.graph.layer_tileinfo[layer_id]['max_PE'] * outputbit / self.inter_tile_bandwidth) # Todo: update merge time (adder tree) and transfer data volume transfer_time = self.graph.transLayer_distance[0][layer_id] * ( outputchannel * outputbit / self.inter_tile_bandwidth) # Todo: update transfer data volume for i in range(output_size[0]): for j in range(output_size[1]): if (i == 0) & (j == 0): # the first output indata = input_channel_PE * ( input_size[1] * max(kernelsize - padding - 1, 0) + max(kernelsize - padding, 0)) * inputbit / 8 # fill the line buffer rdata = self.graph.layer_tileinfo[layer_id]['max_row'] * inputbit / 8 # from the line buffer to the input reg temp_tile_latency.update_tile_latency(indata=indata, rdata=rdata) compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time begin_time = 0 self.pipe_result_update('conv', begin_time, compute_time, layer_id, temp_tile_latency, merge_time, transfer_time) elif j == 0: indata = input_channel_PE * stride * max(kernelsize - padding, 0) * inputbit / 8 # line feed in line buffer rdata = self.graph.layer_tileinfo[layer_id]['max_row'] * inputbit / 8 # from the line buffer to the input reg temp_tile_latency.update_tile_latency(indata=indata, rdata=rdata) begin_time = self.finish_time[0][(i - 1) * output_size[1] + output_size[1] - 1] compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time + \ begin_time self.pipe_result_update('conv', begin_time, compute_time, layer_id, temp_tile_latency, merge_time, transfer_time) else: indata = input_channel_PE * stride ** 2 * inputbit / 8 # write new input data to line buffer rdata = stride * kernelsize * input_channel_PE * inputbit / 8 temp_tile_latency.update_tile_latency(indata=indata, rdata=rdata) begin_time = self.finish_time[0][i * output_size[1] + j - 1] compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time + \ begin_time self.pipe_result_update('conv', begin_time, compute_time, layer_id, temp_tile_latency, merge_time, transfer_time) else: if layer_dict['type'] == 'conv': self.layer_latency_initial() output_size = list(map(int, layer_dict['Outputsize'])) input_size = list(map(int, layer_dict['Inputsize'])) kernelsize = int(layer_dict['Kernelsize']) stride = int(layer_dict['Stride']) inputchannel = int(layer_dict['Inputchannel']) outputchannel = int(layer_dict['Outputchannel']) padding = int(layer_dict['Padding']) inputbit = int(layer_dict['Inputbit']) outputbit = int(layer_dict['outputbit']) # print(self.graph.layer_tileinfo[layer_id]['max_row']) input_channel_PE = self.graph.layer_tileinfo[layer_id]['max_row'] / (kernelsize ** 2) # the input channel number each PE processes temp_tile_latency = tile_latency_analysis(SimConfig_path=self.SimConfig_path, read_row=self.graph.layer_tileinfo[layer_id]['max_row'], read_column=self.graph.layer_tileinfo[layer_id][ 'max_column'], indata=0, rdata=0, inprecision=inputbit, PE_num=self.graph.layer_tileinfo[layer_id]['max_PE'], default_inbuf_size=self.graph.max_inbuf_size, default_outbuf_size=self.graph.max_outbuf_size ) temp_tile_latency.outbuf.calculate_buf_read_latency(rdata=(self.graph.layer_tileinfo[layer_id]['max_column'] * outputbit * self.graph.layer_tileinfo[layer_id]['max_PE'] / 8)) temp_tile_latency.tile_buf_rlatency = temp_tile_latency.outbuf.buf_rlatency merge_time = temp_tile_latency.tile_buf_rlatency + self.graph.inLayer_distance[0][layer_id] * \ (temp_tile_latency.digital_period + self.graph.layer_tileinfo[layer_id]['max_column'] * self.graph.layer_tileinfo[layer_id]['max_PE'] * outputbit / self.inter_tile_bandwidth) # Todo: update merge time (adder tree) and transfer data volume transfer_time = self.graph.transLayer_distance[0][layer_id] * (outputchannel * outputbit / self.inter_tile_bandwidth) # Todo: update transfer data volume for i in range(output_size[0]): for j in range(output_size[1]): if kernelsize > 1: last_layer_pos = (min(max(kernelsize-padding,1) + stride * i, input_size[0]) - 1) * \ input_size[1] + min(max(kernelsize-padding,1) + stride * j, input_size[1]) - 1 else: last_layer_pos = i*stride*input_size[1]+j*stride if last_layer_pos > len(self.finish_time[layer_id - 1]) - 1: print("pos error", i, j) if (i == 0) & (j == 0): # the first output indata = input_channel_PE * (input_size[1] * max(kernelsize - padding - 1, 0) + max( kernelsize - padding, 0)) * inputbit / 8 # fill the line buffer rdata = self.graph.layer_tileinfo[layer_id]['max_row'] * inputbit / 8 # from the line buffer to the input reg temp_tile_latency.update_tile_latency(indata=indata, rdata=rdata) temp_Inputindex = self.graph.layer_tileinfo[layer_id]['Inputindex'] last_layer_finish_time = 0 # the finish time of all the required input data (in all input layers) for idx in temp_Inputindex: tmp_time = self.finish_time[layer_id + idx][-1] if tmp_time > last_layer_finish_time: last_layer_finish_time = tmp_time begin_time = last_layer_finish_time compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time + \ begin_time # consider the input data generation time self.pipe_result_update('conv', begin_time, compute_time, layer_id, temp_tile_latency, merge_time, transfer_time) elif j == 0: indata = input_channel_PE * stride * max(kernelsize - padding, 0) * inputbit / 8 # line feed in line buffer rdata = self.graph.layer_tileinfo[layer_id]['max_row'] * inputbit / 8 # from the line buffer to the input reg temp_tile_latency.update_tile_latency(indata=indata, rdata=rdata) begin_time = self.finish_time[layer_id][(i - 1) * output_size[1] + output_size[1] - 1] # max (the required input data generation time, previous point computation complete time) compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time + \ begin_time self.pipe_result_update('conv', begin_time, compute_time, layer_id, temp_tile_latency, merge_time, transfer_time) else: indata = input_channel_PE * stride ** 2 * inputbit / 8 # write new input data to line buffer rdata = stride * kernelsize * input_channel_PE * inputbit / 8 temp_tile_latency.update_tile_latency(indata=indata, rdata=rdata) begin_time = self.finish_time[layer_id][i * output_size[1] + j - 1] # max (the required input data generation time, previous point computation complete time) compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time + \ begin_time self.pipe_result_update('conv', begin_time, compute_time, layer_id, temp_tile_latency, merge_time, transfer_time) elif layer_dict['type'] == 'fc': output_size = int(layer_dict['Outfeature']) input_size = int(layer_dict['Infeature']) inputbit = int(layer_dict['Inputbit']) outputbit = int(layer_dict['outputbit']) self.layer_latency_initial() indata = self.graph.layer_tileinfo[layer_id]['max_row'] * inputbit / 8 rdata = indata temp_tile_latency = tile_latency_analysis(SimConfig_path=self.SimConfig_path, read_row=self.graph.layer_tileinfo[layer_id]['max_row'], read_column=self.graph.layer_tileinfo[layer_id]['max_column'], indata=indata, rdata=rdata, inprecision=inputbit, PE_num=self.graph.layer_tileinfo[layer_id]['max_PE'], default_inbuf_size=self.graph.max_inbuf_size, default_outbuf_size=self.graph.max_outbuf_size ) temp_tile_latency.outbuf.calculate_buf_read_latency(rdata=(self.graph.layer_tileinfo[layer_id]['max_column'] * outputbit * self.graph.layer_tileinfo[layer_id]['max_PE'] / 8)) temp_tile_latency.tile_buf_rlatency = temp_tile_latency.outbuf.buf_rlatency merge_time = temp_tile_latency.tile_buf_rlatency + self.graph.inLayer_distance[0][layer_id] * \ (temp_tile_latency.digital_period + self.graph.layer_tileinfo[layer_id]['max_column'] * self.graph.layer_tileinfo[layer_id]['max_PE'] * outputbit / self.inter_tile_bandwidth) # Todo: update merge time (adder tree) and transfer data volume transfer_time = self.graph.transLayer_distance[0][layer_id] * ( output_size * outputbit / self.inter_tile_bandwidth) max_prelayer_time = 0 temp_Inputindex = self.graph.layer_tileinfo[layer_id]['Inputindex'] for idx in temp_Inputindex: tmp_time = self.finish_time[layer_id+idx][-1] if tmp_time > max_prelayer_time: max_prelayer_time = tmp_time begin_time = max_prelayer_time compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time + begin_time self.pipe_result_update(layer_type='fc', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_tile_latency=temp_tile_latency, merge_time=merge_time, transfer_time=transfer_time, output_size=output_size) elif layer_dict['type'] == 'pooling': self.layer_latency_initial() output_size = list(map(int, layer_dict['Outputsize'])) input_size = list(map(int, layer_dict['Inputsize'])) kernelsize = int(layer_dict['Kernelsize']) stride = int(layer_dict['Stride']) inputchannel = int(layer_dict['Inputchannel']) outputchannel = int(layer_dict['Outputchannel']) padding = int(layer_dict['Padding']) inputbit = int(layer_dict['Inputbit']) outputbit = int(layer_dict['outputbit']) temp_pooling_latency = pooling_latency_analysis(SimConfig_path=self.SimConfig_path, indata=0, rdata=0, outprecision = outputbit, default_inbuf_size = self.graph.max_inbuf_size, default_outbuf_size = self.graph.max_outbuf_size, default_inchannel = inputchannel, default_size = (kernelsize**2)) temp_pooling_latency.outbuf.calculate_buf_read_latency(rdata=(outputchannel*outputbit/8)) temp_pooling_latency.outbuf_rlatency = temp_pooling_latency.outbuf.buf_rlatency merge_time = temp_pooling_latency.outbuf_rlatency # Todo: update merge time of pooling tile transfer_time = self.graph.transLayer_distance[0][layer_id] * ( outputchannel * outputbit / self.inter_tile_bandwidth) # Todo: update transfer data volume for i in range(output_size[0]): for j in range(output_size[1]): if (i == 0) & (j == 0): # the first output indata = inputchannel * (input_size[1] * max(kernelsize - padding - 1, 0) + max( kernelsize - padding, 0)) * inputbit / 8 # fill the line buffer rdata = inputchannel * kernelsize ** 2 * inputbit / 8 # from the line buffer to the input reg temp_pooling_latency.update_pooling_latency(indata=indata,rdata=rdata) temp_Inputindex = self.graph.layer_tileinfo[layer_id]['Inputindex'] max_prelayer_time = 0 # the maximum time of the required input data (in all input layers) for idx in temp_Inputindex: tmp_time = self.finish_time[layer_id + idx][-1] if tmp_time > max_prelayer_time: max_prelayer_time = tmp_time begin_time = max_prelayer_time compute_time = temp_pooling_latency.pooling_latency + merge_time + transfer_time + \ begin_time self.pipe_result_update(layer_type='pooling', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_pooling_latency=temp_pooling_latency,merge_time=merge_time,transfer_time=transfer_time) elif j == 0: indata = inputchannel * stride * max(kernelsize - padding, 0) * inputbit / 8 # line feed in line buffer rdata = inputchannel * kernelsize ** 2 * inputbit / 8 # from the line buffer to the input reg temp_pooling_latency.update_pooling_latency(indata=indata, rdata=rdata) begin_time = self.finish_time[layer_id][(i - 1) * output_size[1] + output_size[1] - 1] compute_time = temp_pooling_latency.pooling_latency + merge_time + transfer_time + \ begin_time self.pipe_result_update(layer_type='pooling', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_pooling_latency=temp_pooling_latency,merge_time=merge_time,transfer_time=transfer_time) else: indata = inputchannel * stride ** 2 * inputbit / 8 # write new input data to line buffer rdata = stride * kernelsize * inputchannel * inputbit / 8 temp_pooling_latency.update_pooling_latency(indata=indata, rdata=rdata) begin_time = self.finish_time[layer_id][i * output_size[1] + j - 1] compute_time = temp_pooling_latency.pooling_latency + merge_time + transfer_time + \ begin_time self.pipe_result_update(layer_type='pooling', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_pooling_latency=temp_pooling_latency,merge_time=merge_time,transfer_time=transfer_time) elif layer_dict['type'] == 'element_sum': self.layer_latency_initial() Inputindex_list = list(map(int, layer_dict['Inputindex'])) assert len(Inputindex_list) > 1, "the number of element_sum's previous layers must > 1" idx = 0 previous_layer_dict = self.NetStruct[layer_id + Inputindex_list[0]][0][0] while previous_layer_dict['type'] == 'element_sum': idx = idx + 1 previous_layer_dict = self.NetStruct[layer_id + Inputindex_list[idx]][0][0] output_size = list(map(int, previous_layer_dict['Outputsize'])) input_size = list(map(int, previous_layer_dict['Outputsize'])) self.layer_split.append([input_size[1]]) kernelsize = int(previous_layer_dict['Kernelsize']) inputchannel = int(previous_layer_dict['Outputchannel']) outputchannel = int(previous_layer_dict['Outputchannel']) inputbit = int(previous_layer_dict['outputbit']) outputbit = int(previous_layer_dict['outputbit']) merge_time = 0 transfer_time = self.graph.transLayer_distance[0][layer_id]*(outputchannel*outputbit/self.inter_tile_bandwidth) global_buf = buffer(SimConfig_path=self.SimConfig_path,buf_level=2,default_buf_size=self.graph.global_buf_size) global_buf.calculate_buf_read_latency(rdata=(len(Inputindex_list)*inputbit*inputchannel/8)) global_buf.calculate_buf_write_latency(wdata=(len(Inputindex_list)*inputbit*inputchannel/8)) for i in range(output_size[0]): for j in range(output_size[1]): max_prelayer_time = 0 # the maximum time of the required input data (in all input layers) for idx in Inputindex_list: tmp_time = self.finish_time[layer_id+idx][i*input_size[1]+j] if tmp_time > max_prelayer_time: max_prelayer_time = tmp_time begin_time = max_prelayer_time compute_time = 10+merge_time+transfer_time+begin_time+global_buf.buf_rlatency+global_buf.buf_wlatency self.pre_max_time = compute_time self.pipe_result_update(layer_type='element_sum', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, global_buf=global_buf, merge_time=merge_time, transfer_time=transfer_time) self.compute_interval[layer_id] = merge_interval(self.compute_interval[layer_id]) temp_runtime = 0 for l in range(len(self.compute_interval[layer_id])): temp_runtime += (self.compute_interval[layer_id][l][1] - self.compute_interval[layer_id][l][0]) self.occupancy.append(temp_runtime / (max(self.finish_time[layer_id]) - min(self.begin_time[layer_id]))) self.total_buffer_latency.append(sum(self.buffer_latency[layer_id])) self.total_computing_latency.append(sum(self.computing_latency[layer_id])) self.total_DAC_latency.append(sum(self.DAC_latency[layer_id])) self.total_xbar_latency.append(sum(self.xbar_latency[layer_id])) self.total_ADC_latency.append(sum(self.ADC_latency[layer_id])) self.total_digital_latency.append(sum(self.digital_latency[layer_id])) self.total_inter_tile_latency.append(sum(self.inter_tile_latency[layer_id])) self.total_intra_tile_latency.append(sum(self.intra_tile_latency[layer_id])) self.total_tile_merge_latency.append(sum(self.tile_merge_latency[layer_id])) self.total_tile_transfer_latency.append(sum(self.tile_transfer_latency[layer_id])) self.total_iReg_latency.append(sum(self.iReg_latency[layer_id])) self.total_oReg_latency.append(sum(self.oReg_latency[layer_id])) self.total_input_demux_latency.append(sum(self.input_demux_latency[layer_id])) self.total_output_mux_latency.append(sum(self.output_mux_latency[layer_id])) self.total_shiftreg_latency.append(sum(self.shiftreg_latency[layer_id])) self.total_adder_latency.append(sum(self.adder_latency[layer_id])) self.total_jointmodule_latency.append(sum(self.jointmodule_latency[layer_id])) self.total_pooling_latency.append(sum(self.pooling_latency[layer_id])) self.total_buffer_r_latency.append(sum(self.buffer_r_latency[layer_id])) self.total_buffer_w_latency.append(sum(self.buffer_w_latency[layer_id])) def Latency_stall_calculate(self): ''' should be used after the calculate_model ''' Linebuffer_Size = 2048 # Bytes OutputBuffer_Size = 32 * 1024 # Bytes layer_occu = [] for layer_id in range(len(self.NetStruct)): layer_dict = self.NetStruct[layer_id][0][0] self.layer_type.append(layer_dict['type']) if (self.occupancy[layer_id] == 1) and (layer_dict['type'] == 'conv'): # if ((self.occupancy[layer_id] == 1) and (layer_dict['type'] == 'conv')) or (layer_dict['type'] == 'pooling'): layer_occu.append(layer_id) ''' check the consecuive of the layer ''' if len(layer_occu) is 0: return print(layer_occu) layer_stall = [] start = layer_occu[0] end = start for i in range(len(layer_occu) - 1): if layer_occu[i + 1] == layer_occu[i] + 1: end = layer_occu[i + 1] else: if start < end: layer_stall.append([start, end]) start = layer_occu[i + 1] end = start if end > start: layer_stall.append([start, end]) if len(layer_stall) == 0: print("No need to be stalled") return else: # print(layer_stall) for i in range(len(layer_stall)): for layer_id in range(layer_stall[i][1], layer_stall[i][0], -1): layer_dict = self.NetStruct[layer_id][0][0] output_size = list(map(int, layer_dict['Outputsize'])) input_size = list(map(int, layer_dict['Inputsize'])) kernelsize = int(layer_dict['Kernelsize']) stride = int(layer_dict['Stride']) inputchannel = int(layer_dict['Inputchannel']) outputchannel = int(layer_dict['Outputchannel']) padding = int(layer_dict['Padding']) inputbit = int(layer_dict['Inputbit']) outputbit = int(layer_dict['outputbit']) input_channel_PE = self.graph.layer_tileinfo[layer_id]['max_row'] / (kernelsize ** 2) ''' get the point number of this layer and then go back to the previous layer ''' # TODO: update the tile usage of this tile_num = self.graph.layer_tileinfo[layer_id]['tilenum'] pre_point = 0 cur_point = 0 res = 0 if layer_dict['type'] == 'conv': storage_capacity = Linebuffer_Size / input_channel_PE + OutputBuffer_Size * tile_num / outputchannel else: storage_capacity = Linebuffer_Size / inputchannel + OutputBuffer_Size * tile_num / outputchannel # print("Storage is: ", storage_capacity) for cur_point in range(len(self.begin_time[layer_id])): cur_row = cur_point // output_size[1] # begin from 0 cur_column = cur_point - cur_row * output_size[1] # begin from 0 used_point = (stride * cur_row - padding) * input_size[1] + \ (cur_column * stride - padding) * stride pre_point = Search(self.begin_time[layer_id][cur_point], self.begin_time[layer_id - 1]) # begin from 1 res = storage_capacity - (pre_point + cur_point - used_point) # print(res) if res <= 0: print("You need to stall the Pipeline on Layer %d" % (layer_id - 1)) break # update the stall time if res > 0: print("No need to be stalled") continue else: pre_point = pre_point - 1 # print(pre_point) while (pre_point < input_size[0] * input_size[1]): delta = self.begin_time[layer_id][cur_point] - self.begin_time[layer_id - 1][pre_point] assert delta > 0, "delta is not 0, something error" # self.begin_time[layer_id - 1][pre_point] = self.begin_time[layer_id][cur_point] consumption = stride ** 2 for num in range(consumption): self.begin_time[layer_id - 1][pre_point + num] += delta self.finish_time[layer_id - 1][pre_point + num] += delta pre_point += consumption cur_point += 1 interval = [] for i in range(len(self.begin_time[layer_id - 1])): interval.append([self.begin_time[layer_id - 1][i], self.finish_time[layer_id - 1][i]]) stall_interval = merge_interval(interval) self.compute_interval[layer_id - 1] = stall_interval print("++++++++++++++++++++++++++++++++") print("updated: ", self.begin_time[layer_id - 1]) print(" ", self.finish_time[layer_id - 1]) print(" ", self.compute_interval[layer_id - 1]) print(len(stall_interval)) return def model_latency_output(self, module_information=1, layer_information=1): print(' ') if (layer_information): for i in range(len(self.begin_time)): print("Layer", i, " type:", self.NetStruct[i][0][0]['type']) # print("start time: ", self.begin_time[i]) # print("finish time:", self.finish_time[i]) # print("Time interval of working:", self.compute_interval[i]) print("Occupancy:", self.occupancy[i]) # # print(self.xbar_latency[i]) total_latency = self.total_buffer_latency[i] + self.total_computing_latency[i] + \ self.total_digital_latency[i] + self.total_intra_tile_latency[i] + \ self.total_inter_tile_latency[i] if (module_information): print("Buffer latency of layer", i, ":", self.total_buffer_latency[i], '(', "%.2f" % (100 * self.total_buffer_latency[i] / total_latency), '%)') print(" read buffer latency of layer", i, ":", self.total_buffer_r_latency[i], '(', "%.2f" % (100 * self.total_buffer_r_latency[i] / total_latency), '%)') print(" write buffer latency of layer", i, ":", self.total_buffer_w_latency[i], '(', "%.2f" % (100 * self.total_buffer_w_latency[i] / total_latency), '%)') print("Computing latency of layer", i, ":", self.total_computing_latency[i], '(', "%.2f" % (100 * self.total_computing_latency[i] / total_latency), '%)') print(" DAC latency of layer", i, ":", self.total_DAC_latency[i], '(', "%.2f" % (100 * self.total_DAC_latency[i] / total_latency), '%)') print(" ADC latency of layer", i, ":", self.total_ADC_latency[i], '(', "%.2f" % (100 * self.total_ADC_latency[i] / total_latency), '%)') print(" xbar latency of layer", i, ":", self.total_xbar_latency[i], '(', "%.2f" % (100 * self.total_xbar_latency[i] / total_latency), '%)') print("Digital part latency of layer", i, ":", self.total_digital_latency[i], '(', "%.2f" % (100 * self.total_digital_latency[i] / total_latency), '%)') print(" iReg latency of layer", i, ":", self.total_iReg_latency[i], '(', "%.2f" % (100 * self.total_iReg_latency[i] / total_latency), '%)') print(" oReg latency of layer", i, ":", self.total_oReg_latency[i], '(', "%.2f" % (100 * self.total_oReg_latency[i] / total_latency), '%)') print(" input demux latency of layer", i, ":", self.total_input_demux_latency[i], '(', "%.2f" % (100 * self.total_input_demux_latency[i] / total_latency), '%)') print(" output mux latency of layer", i, ":", self.total_output_mux_latency[i], '(', "%.2f" % (100 * self.total_output_mux_latency[i] / total_latency), '%)') print(" shiftreg latency of layer", i, ":", self.total_shiftreg_latency[i], '(', "%.2f" % (100 * self.total_shiftreg_latency[i] / total_latency), '%)') print(" adder latency of layer", i, ":", self.total_adder_latency[i], '(', "%.2f" % (100 * self.total_adder_latency[i] / total_latency), '%)') print(" Jointmodule latency of layer", i, ":", self.total_jointmodule_latency[i], '(', "%.2f" % (100 * self.total_jointmodule_latency[i] / total_latency), '%)') print("Pooling module latency of layer", i, ":", self.total_pooling_latency[i], '(', "%.2f" % (100 * self.total_pooling_latency[i] / total_latency), '%)') print("Intra tile communication latency of layer", i, ":", self.total_intra_tile_latency[i], '(', "%.2f" % (100 * self.total_intra_tile_latency[i] / total_latency), '%)') print("Inter tile communication latency of layer", i, ":", self.total_inter_tile_latency[i], '(', "%.2f" % (100 * self.total_inter_tile_latency[i] / total_latency), '%)') print(" One layer merge latency of layer", i, ":", self.total_tile_merge_latency[i], '(', "%.2f" % (100 * self.total_tile_merge_latency[i] / total_latency), '%)') print(" Inter tile transfer latency of layer", i, ":", self.total_tile_transfer_latency[i], '(', "%.2f" % (100 * self.total_tile_transfer_latency[i] / total_latency), '%)') print('----------------------------------------------') # print("Latency simulation finished!") print("Entire latency:", max(max(self.finish_time)), "ns") def calculate_model_latency(self, mode=0): ''' merge the latency_0 and latency_1 :param mode: 0: fill in input data row by row, 1: fill in input data kerlenl size by kernel size (column direction) :return: ''' for layer_id in range(len(self.NetStruct)): layer_dict = self.NetStruct[layer_id][0][0] if layer_id == 0: # for the first layer, first layer must be conv layer self.layer_latency_initial() output_size = list(map(int, layer_dict['Outputsize'])) input_size = list(map(int, layer_dict['Inputsize'])) kernelsize = int(layer_dict['Kernelsize']) stride = int(layer_dict['Stride']) inputchannel = int(layer_dict['Inputchannel']) outputchannel = int(layer_dict['Outputchannel']) padding = int(layer_dict['Padding']) inputbit = int(layer_dict['Inputbit']) outputbit = int(layer_dict['outputbit']) input_channel_PE = self.graph.layer_tileinfo[layer_id]['max_row'] / (kernelsize ** 2) # the input channel number each PE processes temp_tile_latency = tile_latency_analysis(SimConfig_path=self.SimConfig_path, read_row=self.graph.layer_tileinfo[layer_id]['max_row'], read_column=self.graph.layer_tileinfo[layer_id]['max_column'], indata=0, rdata=0, inprecision=inputbit, PE_num=self.graph.layer_tileinfo[layer_id]['max_PE'], default_inbuf_size=self.graph.max_inbuf_size, default_outbuf_size=self.graph.max_outbuf_size ) temp_tile_latency.outbuf.calculate_buf_read_latency(rdata = (self.graph.layer_tileinfo[layer_id]['max_column']* outputbit*self.graph.layer_tileinfo[layer_id]['max_PE']/8)) temp_tile_latency.tile_buf_rlatency = temp_tile_latency.outbuf.buf_rlatency merge_time = temp_tile_latency.tile_buf_rlatency+self.graph.inLayer_distance[0][layer_id] * \ (temp_tile_latency.digital_period +self.graph.layer_tileinfo[layer_id]['max_column'] * self.graph.layer_tileinfo[layer_id]['max_PE'] * outputbit / self.inter_tile_bandwidth) # Todo: update merge time (adder tree) and transfer data volume transfer_time = self.graph.transLayer_distance[0][layer_id] * ( outputchannel * outputbit / self.inter_tile_bandwidth) cur_multiple = self.multiple[layer_id] split_size = Split_map(padding=padding, outputsize=output_size[1], multiple=cur_multiple) self.layer_split.append(split_size) max_time = [0] * cur_multiple # Todo: update transfer data volume for i in range(output_size[0]): for m in range(cur_multiple): for j in range(split_size[m]): self.pre_max_time = max_time[m] if (i == 0) & (j == 0): # the first output if mode == 0: if cur_multiple == 1: indata = input_channel_PE * (input_size[1] * max(kernelsize - padding - 1, 0) + max(kernelsize - padding, 0)) * inputbit / 8 elif m == 0: temp_insize = inoutsize_conversion(kernelsize=kernelsize, padding=padding/2, stride=stride, outputsize=split_size[m]) # only one padding column indata = input_channel_PE * (temp_insize * max(kernelsize - padding - 1, 0) + max(kernelsize - padding, 0)) * inputbit / 8 elif m == cur_multiple-1: temp_insize = inoutsize_conversion(kernelsize=kernelsize, padding=padding/2, stride=stride, outputsize=split_size[m]) # only one padding column indata = input_channel_PE * (temp_insize * max(kernelsize - padding - 1, 0) + kernelsize) * inputbit / 8 else: temp_insize = inoutsize_conversion(kernelsize=kernelsize, padding=0, stride=stride, outputsize=split_size[m]) # only one padding column indata = input_channel_PE * (temp_insize * max(kernelsize - padding - 1, 0) + kernelsize) * inputbit / 8 else: if cur_multiple == 1: indata = input_channel_PE * (max(kernelsize - padding, 0)**2) * inputbit / 8 elif m == 0: indata = input_channel_PE * (max(kernelsize - padding, 0)**2) * inputbit / 8 else: indata = input_channel_PE * (max(kernelsize-padding,0)*kernelsize) * inputbit / 8 # fill the line buffer rdata = self.graph.layer_tileinfo[layer_id]['max_row'] * inputbit / 8 temp_tile_latency.update_tile_latency(indata=indata, rdata=rdata) compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time begin_time = 0 self.pipe_result_update(layer_type='conv', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_tile_latency=temp_tile_latency, merge_time=merge_time, transfer_time=transfer_time) max_time[m] = compute_time elif j == 0: if mode == 0: if cur_multiple == 1: indata = input_channel_PE * (input_size[1]*(stride-1)+max(kernelsize-padding,0)) * inputbit / 8 elif m == 0: temp_insize = inoutsize_conversion(kernelsize=kernelsize, padding=padding/2, stride=stride, outputsize=split_size[m]) # only one padding column indata = input_channel_PE * (temp_insize*(stride-1)+max(kernelsize - padding, 0)) * inputbit / 8 elif m == cur_multiple-1: temp_insize = inoutsize_conversion(kernelsize=kernelsize, padding=padding/2, stride=stride, outputsize=split_size[m]) # only one padding column indata = input_channel_PE * (temp_insize * (stride-1) + kernelsize) * inputbit / 8 else: temp_insize = inoutsize_conversion(kernelsize=kernelsize, padding=0, stride=stride, outputsize=split_size[m]) # only one padding column indata = input_channel_PE * (temp_insize * (stride-1) + kernelsize) * inputbit / 8 else: if cur_multiple == 1: indata = input_channel_PE * stride * max(kernelsize-padding,0) * inputbit / 8 elif m == 0: indata = input_channel_PE * stride * max(kernelsize-padding,0) * inputbit /8 else: indata = input_channel_PE * stride * kernelsize * inputbit / 8 rdata = self.graph.layer_tileinfo[layer_id]['max_row'] * inputbit / 8 temp_tile_latency.update_tile_latency(indata=indata, rdata=rdata) # TODO: Check begin_time = self.pre_max_time compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time + begin_time self.pipe_result_update(layer_type='conv', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_tile_latency=temp_tile_latency, merge_time=merge_time, transfer_time=transfer_time) max_time[m] = compute_time else: # ignore the last several columns with padding if mode == 0: indata = input_channel_PE * stride * inputbit /8 else: if i == 0: indata = input_channel_PE * stride * kernelsize * inputbit / 8 else: indata = input_channel_PE * stride **2 * inputbit / 8 rdata = stride * kernelsize * input_channel_PE * inputbit / 8 temp_tile_latency.update_tile_latency(indata=indata, rdata=rdata) begin_time = self.pre_max_time compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time + begin_time self.pipe_result_update(layer_type='conv', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_tile_latency=temp_tile_latency, merge_time=merge_time, transfer_time=transfer_time) max_time[m] = compute_time else: if layer_dict['type'] is 'conv': self.layer_latency_initial() output_size = list(map(int, layer_dict['Outputsize'])) input_size = list(map(int, layer_dict['Inputsize'])) kernelsize = int(layer_dict['Kernelsize']) stride = int(layer_dict['Stride']) inputchannel = int(layer_dict['Inputchannel']) outputchannel = int(layer_dict['Outputchannel']) padding = int(layer_dict['Padding']) inputbit = int(layer_dict['Inputbit']) outputbit = int(layer_dict['outputbit']) input_channel_PE = self.graph.layer_tileinfo[layer_id]['max_row'] / (kernelsize ** 2) # the input channel number each PE processes temp_tile_latency = tile_latency_analysis(SimConfig_path=self.SimConfig_path, read_row=self.graph.layer_tileinfo[layer_id]['max_row'], read_column=self.graph.layer_tileinfo[layer_id][ 'max_column'], indata=0, rdata=0, inprecision=inputbit, PE_num=self.graph.layer_tileinfo[layer_id]['max_PE'], default_inbuf_size=self.graph.max_inbuf_size, default_outbuf_size=self.graph.max_outbuf_size ) temp_tile_latency.outbuf.calculate_buf_read_latency(rdata=(self.graph.layer_tileinfo[layer_id]['max_column'] * outputbit * self.graph.layer_tileinfo[layer_id]['max_PE'] / 8)) temp_tile_latency.tile_buf_rlatency = temp_tile_latency.outbuf.buf_rlatency merge_time = temp_tile_latency.tile_buf_rlatency + self.graph.inLayer_distance[0][layer_id] * \ (temp_tile_latency.digital_period + self.graph.layer_tileinfo[layer_id]['max_column'] * self.graph.layer_tileinfo[layer_id]['max_PE'] * outputbit / self.inter_tile_bandwidth) # Todo: update merge time (adder tree) and transfer data volume transfer_time = self.graph.transLayer_distance[0][layer_id] * (outputchannel * outputbit / self.inter_tile_bandwidth) ''' get the multiple for the conv layer ''' cur_multiple = self.multiple[layer_id] split_size = Split_map(padding=padding, outputsize=output_size[1], multiple=cur_multiple) self.layer_split.append(split_size) max_time = [0] * cur_multiple for i in range(output_size[0]): for m in range(cur_multiple): for j in range(split_size[m]): self.pre_max_time = max_time[m] if kernelsize > 1: last_layer_pos = (min(max(kernelsize-padding,1) + stride * i, input_size[0]) - 1) * \ input_size[1] + min(max(kernelsize-padding,1) + stride * j, input_size[1]) - 1 else: last_layer_pos = i*stride*input_size[1]+j*stride # if last_layer_pos > len(self.finish_time[layer_id - 1]) - 1: # print("pos error", i, j) if (i == 0) & (j == 0): ''' the first output ''' if mode == 0: if cur_multiple == 1: indata = input_channel_PE * (input_size[1] * max(kernelsize - padding - 1, 0) + max(kernelsize - padding, 0)) * inputbit / 8 elif m == 0: temp_insize = inoutsize_conversion(kernelsize=kernelsize,padding=padding / 2, stride=stride, outputsize=split_size[m]) # only one padding column indata = input_channel_PE * (temp_insize * max(kernelsize - padding - 1, 0) + max(kernelsize - padding, 0)) * inputbit / 8 elif m == cur_multiple - 1: temp_insize = inoutsize_conversion(kernelsize=kernelsize,padding=padding / 2, stride=stride, outputsize=split_size[m]) # only one padding column indata = input_channel_PE * (temp_insize * max(kernelsize - padding - 1, 0) + kernelsize) * inputbit / 8 else: temp_insize = inoutsize_conversion(kernelsize=kernelsize, padding=0,stride=stride, outputsize=split_size[m]) # only one padding column indata = input_channel_PE * (temp_insize * max(kernelsize - padding - 1, 0) + kernelsize) * inputbit / 8 else: if cur_multiple == 1: indata = input_channel_PE * ( max(kernelsize - padding, 0) ** 2) * inputbit / 8 elif m == 0: indata = input_channel_PE * ( max(kernelsize - padding, 0) ** 2) * inputbit / 8 else: indata = input_channel_PE * ( max(kernelsize - padding, 0) * kernelsize) * inputbit / 8 rdata = self.graph.layer_tileinfo[layer_id]['max_row'] * inputbit / 8 temp_tile_latency.update_tile_latency(indata=indata, rdata=rdata) temp_Inputindex = self.graph.layer_tileinfo[layer_id]['Inputindex'] max_prelayer_time = 0 # the maximum time of the required input data (in all input layers) for idx in temp_Inputindex: if cur_multiple == 1: tmp_time = self.finish_time[layer_id + idx][last_layer_pos] else: updated_last_layer_pos = self.Judge(last_layer_id=(layer_id+idx),last_layer_pos=last_layer_pos,current_layer_id=layer_id) tmp_time = self.finish_time[layer_id + idx][updated_last_layer_pos] if tmp_time > max_prelayer_time: max_prelayer_time = tmp_time begin_time = max(max_prelayer_time, self.pre_max_time) compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time + begin_time self.pipe_result_update(layer_type='conv', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_tile_latency=temp_tile_latency, merge_time=merge_time, transfer_time=transfer_time) max_time[m] = compute_time elif j == 0: if mode == 0: if cur_multiple == 1: indata = input_channel_PE * (input_size[1] * (stride - 1) + max(kernelsize - padding,0)) * inputbit / 8 elif m == 0: temp_insize = inoutsize_conversion(kernelsize=kernelsize,padding=padding / 2, stride=stride, outputsize=split_size[m]) # only one padding column indata = input_channel_PE * (temp_insize * (stride - 1) + max(kernelsize - padding, 0)) * inputbit / 8 elif m == cur_multiple - 1: temp_insize = inoutsize_conversion(kernelsize=kernelsize,padding=padding / 2, stride=stride, outputsize=split_size[m]) # only one padding column indata = input_channel_PE * (temp_insize * (stride - 1) + kernelsize) * inputbit / 8 else: temp_insize = inoutsize_conversion(kernelsize=kernelsize, padding=0,stride=stride, outputsize=split_size[m]) # only one padding column indata = input_channel_PE * (temp_insize * (stride - 1) + kernelsize) * inputbit / 8 else: if cur_multiple == 1: indata = input_channel_PE * stride * max(kernelsize - padding,0) * inputbit / 8 elif m == 0: indata = input_channel_PE * stride * max(kernelsize - padding,0) * inputbit / 8 else: indata = input_channel_PE * stride * kernelsize * inputbit / 8 rdata = self.graph.layer_tileinfo[layer_id]['max_row'] * inputbit / 8 temp_tile_latency.update_tile_latency(indata=indata, rdata=rdata) temp_Inputindex = self.graph.layer_tileinfo[layer_id]['Inputindex'] max_prelayer_time = 0 # the maximum time of the required input data (in all input layers) for idx in temp_Inputindex: if cur_multiple == 1: tmp_time = self.finish_time[layer_id + idx][last_layer_pos] else: updated_last_layer_pos = self.Judge(last_layer_id=(layer_id + idx), last_layer_pos=last_layer_pos, current_layer_id=layer_id) tmp_time = self.finish_time[layer_id + idx][updated_last_layer_pos] if tmp_time > max_prelayer_time: max_prelayer_time = tmp_time begin_time = max(max_prelayer_time, self.pre_max_time) compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time + begin_time self.pipe_result_update(layer_type='conv', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_tile_latency=temp_tile_latency, merge_time=merge_time, transfer_time=transfer_time) max_time[m] = compute_time else: if mode == 0: indata = input_channel_PE * stride * inputbit / 8 else: if i ==0: indata = input_channel_PE * stride * kernelsize * inputbit / 8 else: indata = input_channel_PE * stride**2 * inputbit / 8 rdata = stride * kernelsize * input_channel_PE * inputbit / 8 temp_tile_latency.update_tile_latency(indata=indata, rdata=rdata) temp_Inputindex = self.graph.layer_tileinfo[layer_id]['Inputindex'] max_prelayer_time = 0 # the maximum time of the required input data (in all input layers) for idx in temp_Inputindex: if cur_multiple == 1: tmp_time = self.finish_time[layer_id + idx][last_layer_pos] else: updated_last_layer_pos = self.Judge(last_layer_id=(layer_id + idx), last_layer_pos=last_layer_pos, current_layer_id=layer_id) tmp_time = self.finish_time[layer_id + idx][updated_last_layer_pos] if tmp_time > max_prelayer_time: max_prelayer_time = tmp_time begin_time = max(max_prelayer_time, self.pre_max_time) compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time + begin_time self.pipe_result_update(layer_type='conv', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_tile_latency=temp_tile_latency, merge_time=merge_time, transfer_time=transfer_time) max_time[m] = compute_time else: cur_multiple = self.multiple[layer_id] assert cur_multiple == 1, "Only the conv layer can be multipled" if layer_dict['type'] == 'fc': output_size = int(layer_dict['Outfeature']) input_size = int(layer_dict['Infeature']) self.layer_split.append([input_size]) inputbit = int(layer_dict['Inputbit']) outputbit = int(layer_dict['outputbit']) self.layer_latency_initial() indata = self.graph.layer_tileinfo[layer_id]['max_row'] * inputbit / 8 rdata = indata temp_tile_latency = tile_latency_analysis(SimConfig_path=self.SimConfig_path, read_row=self.graph.layer_tileinfo[layer_id]['max_row'], read_column=self.graph.layer_tileinfo[layer_id]['max_column'], indata=indata, rdata=rdata, inprecision=inputbit, PE_num=self.graph.layer_tileinfo[layer_id]['max_PE'], default_inbuf_size=self.graph.max_inbuf_size, default_outbuf_size=self.graph.max_outbuf_size ) temp_tile_latency.outbuf.calculate_buf_read_latency(rdata=(self.graph.layer_tileinfo[layer_id]['max_column'] * outputbit * self.graph.layer_tileinfo[layer_id]['max_PE'] / 8)) temp_tile_latency.tile_buf_rlatency = temp_tile_latency.outbuf.buf_rlatency merge_time = temp_tile_latency.tile_buf_rlatency + self.graph.inLayer_distance[0][layer_id] * \ (temp_tile_latency.digital_period + self.graph.layer_tileinfo[layer_id]['max_column'] * self.graph.layer_tileinfo[layer_id]['max_PE'] * outputbit / self.inter_tile_bandwidth) # Todo: update merge time (adder tree) and transfer data volume transfer_time = self.graph.transLayer_distance[0][layer_id] * ( output_size * outputbit / self.inter_tile_bandwidth) temp_Inputindex = self.graph.layer_tileinfo[layer_id]['Inputindex'] max_prelayer_time = 0 for idx in temp_Inputindex: tmp_time = self.finish_time[layer_id+idx][-1] if tmp_time > max_prelayer_time: max_prelayer_time = tmp_time begin_time = max_prelayer_time compute_time = temp_tile_latency.tile_latency + merge_time + transfer_time + begin_time self.pipe_result_update(layer_type='fc', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_tile_latency=temp_tile_latency, merge_time=merge_time, transfer_time=transfer_time, output_size=output_size) elif layer_dict['type'] == 'pooling': self.layer_latency_initial() output_size = list(map(int, layer_dict['Outputsize'])) input_size = list(map(int, layer_dict['Inputsize'])) self.layer_split.append([input_size[1]]) kernelsize = int(layer_dict['Kernelsize']) stride = int(layer_dict['Stride']) inputchannel = int(layer_dict['Inputchannel']) outputchannel = int(layer_dict['Outputchannel']) padding = int(layer_dict['Padding']) inputbit = int(layer_dict['Inputbit']) outputbit = int(layer_dict['outputbit']) temp_pooling_latency = pooling_latency_analysis(SimConfig_path=self.SimConfig_path, indata=0, rdata=0, outprecision = outputbit, default_inbuf_size = self.graph.max_inbuf_size, default_outbuf_size = self.graph.max_outbuf_size, default_inchannel = inputchannel, default_size = (kernelsize**2)) temp_pooling_latency.outbuf.calculate_buf_read_latency(rdata=(outputchannel*outputbit/8)) temp_pooling_latency.outbuf_rlatency = temp_pooling_latency.outbuf.buf_rlatency merge_time = temp_pooling_latency.outbuf_rlatency # Todo: update merge time of pooling tile transfer_time = self.graph.transLayer_distance[0][layer_id] * ( outputchannel * outputbit / self.inter_tile_bandwidth) # Todo: update transfer data volume self.pre_max_time = 0 for i in range(output_size[0]): for j in range(output_size[1]): last_layer_pos = (min(max(kernelsize - padding, 1) + stride * i, input_size[0]) - 1) * \ input_size[1] + min(max(kernelsize - padding, 1) + stride * j, input_size[1]) - 1 if (i==0) & (j==0): if mode == 0: indata = inputchannel * (input_size[1] * max(kernelsize-padding-1,0)+max(kernelsize-padding,0))*inputbit/8 else: indata = inputchannel * (max(kernelsize-padding,0)**2)*inputbit/8 rdata = inputchannel * kernelsize ** 2 * inputbit / 8 temp_pooling_latency.update_pooling_latency(indata=indata,rdata=rdata) temp_Inputindex = self.graph.layer_tileinfo[layer_id]['Inputindex'] max_prelayer_time = 0 # the maximum time of the required input data (in all input layers) for idx in temp_Inputindex: tmp_time = self.finish_time[layer_id + idx][last_layer_pos] if tmp_time > max_prelayer_time: max_prelayer_time = tmp_time begin_time = max(max_prelayer_time, self.pre_max_time) compute_time = temp_pooling_latency.pooling_latency + merge_time + transfer_time + begin_time self.pre_max_time = compute_time self.pipe_result_update(layer_type='pooling', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_pooling_latency=temp_pooling_latency,merge_time=merge_time,transfer_time=transfer_time) elif j==0: if mode == 0: indata = inputchannel * (input_size[1] * (stride - 1) + max(kernelsize - padding, 0)) * inputbit/8 else: indata = inputchannel * stride * max(kernelsize - padding, 0) * inputbit / 8 rdata = inputchannel * kernelsize ** 2 * inputbit / 8 temp_pooling_latency.update_pooling_latency(indata=indata, rdata=rdata) temp_Inputindex = self.graph.layer_tileinfo[layer_id]['Inputindex'] max_prelayer_time = 0 for idx in temp_Inputindex: tmp_time = self.finish_time[layer_id + idx][last_layer_pos] if tmp_time > max_prelayer_time: max_prelayer_time = tmp_time begin_time = max(max_prelayer_time, self.pre_max_time) compute_time = temp_pooling_latency.pooling_latency + merge_time + transfer_time + begin_time self.pre_max_time = compute_time self.pipe_result_update(layer_type='pooling', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_pooling_latency=temp_pooling_latency,merge_time=merge_time, transfer_time=transfer_time) else: if mode == 0: indata = inputchannel * stride * inputbit / 8 else: indata = inputchannel * stride **2 * inputbit / 8 rdata = stride * kernelsize * inputchannel * inputbit / 8 temp_pooling_latency.update_pooling_latency(indata=indata, rdata=rdata) temp_Inputindex = self.graph.layer_tileinfo[layer_id]['Inputindex'] max_prelayer_time = 0 for idx in temp_Inputindex: tmp_time = self.finish_time[layer_id + idx][last_layer_pos] if tmp_time > max_prelayer_time: max_prelayer_time = tmp_time begin_time = max(max_prelayer_time, self.pre_max_time) compute_time = temp_pooling_latency.pooling_latency + merge_time + transfer_time + begin_time self.pre_max_time = compute_time self.pipe_result_update(layer_type='pooling', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, temp_pooling_latency=temp_pooling_latency, merge_time=merge_time, transfer_time=transfer_time) elif layer_dict['type'] == 'element_sum': self.layer_latency_initial() Inputindex_list = list(map(int, layer_dict['Inputindex'])) assert len(Inputindex_list) > 1, "the number of element_sum's previous layers must > 1" idx = 0 previous_layer_dict = self.NetStruct[layer_id + Inputindex_list[0]][0][0] while previous_layer_dict['type'] == 'element_sum': idx = idx + 1 previous_layer_dict = self.NetStruct[layer_id + Inputindex_list[idx]][0][0] output_size = list(map(int, previous_layer_dict['Outputsize'])) input_size = list(map(int, previous_layer_dict['Outputsize'])) self.layer_split.append([input_size[1]]) kernelsize = int(previous_layer_dict['Kernelsize']) inputchannel = int(previous_layer_dict['Outputchannel']) outputchannel = int(previous_layer_dict['Outputchannel']) inputbit = int(previous_layer_dict['outputbit']) outputbit = int(previous_layer_dict['outputbit']) merge_time = 0 transfer_time = self.graph.transLayer_distance[0][layer_id]*(outputchannel*outputbit/self.inter_tile_bandwidth) global_buf = buffer(SimConfig_path=self.SimConfig_path,buf_level=2,default_buf_size=self.graph.global_buf_size) global_buf.calculate_buf_read_latency(rdata=(len(Inputindex_list)*inputbit*inputchannel/8)) global_buf.calculate_buf_write_latency(wdata=(len(Inputindex_list)*inputbit*inputchannel/8)) self.pre_max_time = 0 for i in range(output_size[0]): for j in range(output_size[1]): max_prelayer_time = 0 # the maximum time of the required input data (in all input layers) for idx in Inputindex_list: tmp_time = self.finish_time[layer_id+idx][i*input_size[1]+j] if tmp_time > max_prelayer_time: max_prelayer_time = tmp_time begin_time = max(max_prelayer_time, self.pre_max_time) compute_time = 10+merge_time+transfer_time+begin_time+global_buf.buf_rlatency+global_buf.buf_wlatency self.pre_max_time = compute_time self.pipe_result_update(layer_type='element_sum', begin_time=begin_time, compute_time=compute_time, layer_id=layer_id, global_buf=global_buf, merge_time=merge_time, transfer_time=transfer_time) self.compute_interval[layer_id] = merge_interval(self.compute_interval[layer_id]) temp_runtime = 0 for l in range(len(self.compute_interval[layer_id])): temp_runtime += (self.compute_interval[layer_id][l][1] - self.compute_interval[layer_id][l][0]) self.occupancy.append(temp_runtime / (max(self.finish_time[layer_id]) - min(self.begin_time[layer_id]))) self.total_buffer_latency.append(sum(self.buffer_latency[layer_id])) self.total_computing_latency.append(sum(self.computing_latency[layer_id])) self.total_DAC_latency.append(sum(self.DAC_latency[layer_id])) self.total_xbar_latency.append(sum(self.xbar_latency[layer_id])) self.total_ADC_latency.append(sum(self.ADC_latency[layer_id])) self.total_digital_latency.append(sum(self.digital_latency[layer_id])) self.total_inter_tile_latency.append(sum(self.inter_tile_latency[layer_id])) self.total_intra_tile_latency.append(sum(self.intra_tile_latency[layer_id])) self.total_tile_merge_latency.append(sum(self.tile_merge_latency[layer_id])) self.total_tile_transfer_latency.append(sum(self.tile_transfer_latency[layer_id])) self.total_iReg_latency.append(sum(self.iReg_latency[layer_id])) self.total_oReg_latency.append(sum(self.oReg_latency[layer_id])) self.total_input_demux_latency.append(sum(self.input_demux_latency[layer_id])) self.total_output_mux_latency.append(sum(self.output_mux_latency[layer_id])) self.total_shiftreg_latency.append(sum(self.shiftreg_latency[layer_id])) self.total_adder_latency.append(sum(self.adder_latency[layer_id])) self.total_jointmodule_latency.append(sum(self.jointmodule_latency[layer_id])) self.total_pooling_latency.append(sum(self.pooling_latency[layer_id])) self.total_buffer_r_latency.append(sum(self.buffer_r_latency[layer_id])) self.total_buffer_w_latency.append(sum(self.buffer_w_latency[layer_id])) if __name__ == '__main__': test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "SimConfig.ini") test_weights_file_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "alexnet_params.pth") __TestInterface = TrainTestInterface('alexnet', 'MNSIM.Interface.cifar10', test_SimConfig_path, test_weights_file_path) structure_file = __TestInterface.get_structure() test = Model_latency(structure_file, test_SimConfig_path) tile = 0 test.calculate_model_latency(mode=2) test.model_latency_output() <file_sep>/MNSIM/Hardware_Model/JointModule.py #!/usr/bin/python #-*-coding:utf-8-*- import configparser as cp import os import math test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"SimConfig.ini") #Default SimConfig file path: MNSIM_Python/SimConfig.ini class JointModule(object): def __init__(self, SimConfig_path, max_bitwidth = None): # frequency unit: MHz jointmodule_config = cp.ConfigParser() jointmodule_config.read(SimConfig_path, encoding='UTF-8') self.jointmodule_tech = int(jointmodule_config.get('Digital module', 'JointModule_Tech')) if self.jointmodule_tech <= 0: self.jointmodule_tech = 65 self.jointmodule_area = float(jointmodule_config.get('Digital module', 'JointModule_Area')) self.jointmodule_power = float(jointmodule_config.get('Digital module', 'JointModule_Power')) if max_bitwidth is None: self.jointmodule_bit = 8 else: self.jointmodule_bit = max_bitwidth assert self.jointmodule_bit > 0 self.jointmodule_frequency = float(jointmodule_config.get('Digital module', 'Digital_Frequency')) if self.jointmodule_frequency == 0: self.jointmodule_frequency = 100 assert self.jointmodule_frequency > 0 self.jointmodule_latency = 1.0 / self.jointmodule_frequency self.adder_energy = 0 self.calculate_jointmodule_power() def calculate_jointmodule_power(self): # unit: W if self.jointmodule_power == 0: jointmodule_power_dict = {4: 1.39e-4, 8: 2.64e-4, 12: 3.67e-4, 16: 4.97e-4 } if self.jointmodule_bit <= 4: self.jointmodule_power = jointmodule_power_dict[4]*pow((self.jointmodule_tech/65),2) elif self.jointmodule_bit <= 8: self.jointmodule_power = jointmodule_power_dict[8] * pow((self.jointmodule_tech / 65), 2) elif self.jointmodule_bit <= 12: self.jointmodule_power = jointmodule_power_dict[12] * pow((self.jointmodule_tech / 65), 2) else: self.jointmodule_power = jointmodule_power_dict[16] * pow((self.jointmodule_tech / 65), 2) def calculate_jointmodule_area(self): # unit: um^2 if self.jointmodule_area == 0: jointmodule_area_dict = {4: 182.88, 8: 353.76, 12: 385.44, 16: 512.16 } if self.jointmodule_bit <= 4: self.jointmodule_area = jointmodule_area_dict[4]*pow((self.jointmodule_tech/65),2) elif self.jointmodule_bit <= 8: self.jointmodule_area = jointmodule_area_dict[8] * pow((self.jointmodule_tech / 65), 2) elif self.jointmodule_bit <= 12: self.jointmodule_area = jointmodule_area_dict[12] * pow((self.jointmodule_tech / 65), 2) else: self.jointmodule_area = jointmodule_area_dict[16] * pow((self.jointmodule_tech / 65), 2) def calculate_jointmodule_energy(self): assert self.jointmodule_power >= 0 assert self.jointmodule_latency >= 0 self.jointmodule_energy = self.jointmodule_latency * self.jointmodule_power def jointmodule_output(self): print("jointmodule_area:", self.jointmodule_area, "um^2") print("jointmodule_bitwidth:", self.jointmodule_bit, "bit") print("jointmodule_power:", self.jointmodule_power, "W") print("jointmodule_latency:", self.jointmodule_latency, "ns") print("jointmodule_energy:", self.jointmodule_energy, "nJ") def jointmodule_test(): print("load file:",test_SimConfig_path) _jointmodule = JointModule(test_SimConfig_path) _jointmodule.calculate_jointmodule_area() _jointmodule.calculate_jointmodule_power() _jointmodule.calculate_jointmodule_energy() _jointmodule.jointmodule_output() if __name__ == '__main__': jointmodule_test()<file_sep>/MNSIM/Interface/train.py #-*-coding:utf-8-*- import os import time import torch import torch.nn as nn import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler from tensorboardX import SummaryWriter tensorboard_writer = None MOMENTUM = 0.9 WEIGHT_DECAY = 0.0005 GAMMA = 0.01 lr = 0.05 MILESTONES = [30, 60] EPOCHS = 90 TRAIN_PARAMETER = '''\ # TRAIN_PARAMETER ## loss CrossEntropyLoss ## optimizer SGD: base_lr %f momentum %f weight_decay %f ## lr_policy MultiStepLR: milestones [%s] gamma %f epochs %d '''%( lr, MOMENTUM, WEIGHT_DECAY, ','.join([str(v) for v in MILESTONES]), GAMMA, EPOCHS, ) def train_net(net, train_loader, test_loader, device, prefix): global tensorboard_writer tensorboard_writer = SummaryWriter(log_dir = os.path.join(os.path.dirname(__file__), f'runs/{prefix}')) # set net on gpu net.to(device) # loss and optimizer criterion = nn.CrossEntropyLoss() # scale's lr and weight_decay set to 0 optimizer = optim.SGD([{'params': net.parameters(), 'lr': lr, 'weight_decay': WEIGHT_DECAY}], momentum = MOMENTUM) # optimizer = optim.SGD(net.parameters(), lr = lr, weight_decay = WEIGHT_DECAY, momentum = MOMENTUM) scheduler = lr_scheduler.MultiStepLR(optimizer, milestones = MILESTONES, gamma = GAMMA) # test init # eval_net(net, test_loader, 0, device) # epochs for epoch in range(EPOCHS): # train net.train() for i, (images, labels) in enumerate(train_loader): net.zero_grad() images = images.to(device) labels = labels.to(device) outputs = net(images, 'FIX_TRAIN') loss = criterion(outputs, labels) loss.backward() optimizer.step() print(f'epoch {epoch+1:3d}, {i:3d}|{len(train_loader):3d}, loss: {loss.item():2.4f}', end = '\r') tensorboard_writer.add_scalars('train_loss', {'train_loss': loss.item()}, epoch * len(train_loader) + i) eval_net(net, test_loader, epoch + 1, device) torch.save(net.state_dict(), os.path.join(os.path.dirname(__file__), f'zoo/{prefix}_params.pth')) scheduler.step() def eval_net(net, test_loader, epoch, device): # set net on gpu net.to(device) net.eval() test_correct = 0 test_total = 0 with torch.no_grad(): for i, (images, labels) in enumerate(test_loader): images = images.to(device) test_total += labels.size(0) outputs = net(images, 'FIX_TRAIN') # outputs = net(images, 'SINGLE_FIX_TEST') # predicted labels = labels.to(device) _, predicted = torch.max(outputs, 1) test_correct += (predicted == labels).sum().item() print('%s After epoch %d, accuracy is %2.4f' % \ (time.asctime(time.localtime(time.time())), epoch, test_correct / test_total)) if tensorboard_writer != None: tensorboard_writer.add_scalars('test_acc', {'test_acc': test_correct / test_total}, epoch) return test_correct / test_total if __name__ == '__main__': print(TRAIN_PARAMETER) <file_sep>/MNSIM/Hardware_Model/Adder.py #!/usr/bin/python #-*-coding:utf-8-*- import configparser as cp import os import math test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"SimConfig.ini") #Default SimConfig file path: MNSIM_Python/SimConfig.ini class adder(object): def __init__(self, SimConfig_path, bitwidth = None): # frequency unit: MHz adder_config = cp.ConfigParser() adder_config.read(SimConfig_path, encoding='UTF-8') self.adder_tech = int(adder_config.get('Digital module', 'Adder_Tech')) self.adder_area = float(adder_config.get('Digital module', 'Adder_Area')) self.adder_power = float(adder_config.get('Digital module', 'Adder_Power')) if bitwidth is None: self.adder_bitwidth = 8 else: self.adder_bitwidth = bitwidth assert self.adder_bitwidth > 0 self.adder_frequency = float(adder_config.get('Digital module', 'Digital_Frequency')) if self.adder_frequency is None: self.adder_frequency = 100 assert self.adder_frequency > 0 self.adder_latency = 1.0/self.adder_frequency self.adder_energy = 0 self.calculate_adder_power() def calculate_adder_area(self): # unit: um^2 if self.adder_area == 0: adder_area_dict = {130: 10*14*130*130/1e6, #ref: Implementation of an Efficient 14-Transistor Full Adder (.18μm technology) Using DTMOS 2.5e-9 65: 1.42,#10*14*65*65/1e6, 55: 10*14*55*55/1e6, 45: 10*14*45*45/1e6, 28: 10*14*28*28/1e6 } # TODO: add circuits simulation results if self.adder_tech <= 28: self.adder_area = adder_area_dict[28] * self.adder_bitwidth elif self.adder_tech <= 45: self.adder_area = adder_area_dict[45] * self.adder_bitwidth elif self.adder_tech <= 55: self.adder_area = adder_area_dict[55] * self.adder_bitwidth elif self.adder_tech <= 65: self.adder_area = adder_area_dict[65] * self.adder_bitwidth else: self.adder_area = adder_area_dict[130] * self.adder_bitwidth def calculate_adder_power(self): # unit: W if self.adder_power == 0: adder_power_dict = {130: 2.5e-9, 65: 3e-7, 55: 2.5e-9, 45: 2.5e-9, 28: 2.5e-9 } # TODO: add circuits simulation results if self.adder_tech <= 28: self.adder_power = adder_power_dict[28] * self.adder_bitwidth elif self.adder_tech <= 45: self.adder_power = adder_power_dict[45] * self.adder_bitwidth elif self.adder_tech <= 55: self.adder_power = adder_power_dict[55] * self.adder_bitwidth elif self.adder_tech <= 65: self.adder_power = adder_power_dict[65] * self.adder_bitwidth else: self.adder_power = adder_power_dict[130] * self.adder_bitwidth def calculate_adder_energy(self): assert self.adder_power >= 0 assert self.adder_latency >= 0 self.adder_energy = self.adder_latency * self.adder_power def adder_output(self): print("adder_area:", self.adder_area, "um^2") print("adder_bitwidth:", self.adder_bitwidth, "bit") print("adder_power:", self.adder_power, "W") print("adder_latency:", self.adder_latency, "ns") print("adder_energy:", self.adder_energy, "nJ") def adder_test(): print("load file:",test_SimConfig_path) _adder = adder(test_SimConfig_path) _adder.calculate_adder_area() _adder.calculate_adder_power() _adder.calculate_adder_energy() _adder.adder_output() if __name__ == '__main__': adder_test()<file_sep>/MNSIM/Accuracy_Model/Crossbar_accuracy.py import sys import os import math import random import configparser as cp import numpy as np from MNSIM.Hardware_Model import * from MNSIM.Hardware_Model.Crossbar import crossbar test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"SimConfig.ini") class crossbar_accuracy(): def __init__(self, SimConfig_path): self.SimConfig_path = SimConfig_path xbar = crossbar(SimConfig_path) print("Hardware config file is loaded:", SimConfig_path) ca_config = cp.ConfigParser() ca_config.read(SimConfig_path, encoding='UTF-8') self.SAF = list(map(int, ca_config.get('Device level', 'Device_SAF').split(','))) self.read_voltage = xbar.device_read_voltage print(self.read_voltage) # print(self.SAF) self.Load_Resistance = int(ca_config.get('Crossbar level', 'Load_Resistance')) # TODO : change in crossbar.py if self.Load_Resistance == -1: self.Load_Resistance = 2e8 self.wire_resistance = xbar.wire_resistance # if self.standard_wire_resistance == 0: # self.wire_conduction = 0 # else: # self.wire_conduction = 1/self.standard_wire_resistance self.cell_type = xbar.cell_type self.standard_cell_resistance = xbar.device_resistance self.device_bit_level = xbar.device_bit_level self.decice_variation = xbar.decice_variation self.real_matrix = [] self.row = 0 self.column = 0 print(self.row) print(self.column) self.enable_matrix = [] def SAF_effect(self): bound1 = self.SAF[0]*0.01 bound2 = self.SAF[1]*0.01 + bound1 for i in range(self.row): temp = [] for j in range(self.column): num = random.uniform(0,1) if num <= bound1: temp.append(-1) # LRS elif num <= bound2: temp.append(-2) # HRS else: temp.append(1) self.enable_matrix.append(temp) def matrix_accuracy(self, read_matrix): ''' matrix is full of 0,1,2... ''' # real_matrix = [] self.column = len(read_matrix[0]) self.row = len(read_matrix) self.SAF_effect() print(read_matrix) for i in range(self.row): temp = [] for j in range(self.column): if self.enable_matrix[i][j] == 1: resistance = self.standard_cell_resistance[read_matrix[i][j]] temp_resistance = random.uniform(resistance*(1-0.01*self.decice_variation), resistance*(1+0.01*self.decice_variation)) elif self.enable_matrix[i][j] == -1: temp_resistance = self.standard_cell_resistance[-1] else: temp_resistance = self.standard_cell_resistance[0] temp_resistance += self.wire_resistance*(self.row + j - i + 1) temp.append(1/temp_resistance) self.real_matrix.append(temp) def vector_accuracy(self, read_vector): ''' consider the effect of the ADC ''' self.real_vector = [] for j in range(self.column): voltage = 0 for i in range(self.row): temp_voltage = self.read_voltage[read_vector[i]] print(temp_voltage) voltage += temp_voltage * self.Load_Resistance / (self.Load_Resistance + 1/self.real_matrix[i][j]) self.real_vector.append(voltage) def Xbar_accuracy_output(self): print("--------------Accuracy model--------------") print("the real_matrix_weight of the crossbar is:\n") for i in range(self.row): print(self.real_matrix[i]) print("the real vector of the output is:", self.real_vector) print(self.enable_matrix) def Xbar_accuracy_test(): print("load file:", test_SimConfig_path) _xbar_accuracy = crossbar_accuracy(test_SimConfig_path) print('------------') _xbar_accuracy.matrix_accuracy(read_matrix=[ [1,0,1,1], [0,0,1,0], [1,0,1,0] ]) _xbar_accuracy.vector_accuracy(read_vector=[0,0,1]) _xbar_accuracy.Xbar_accuracy_output() if __name__ == '__main__': Xbar_accuracy_test() <file_sep>/MNSIM/Energy_Model/Model_energy.py #!/usr/bin/python # -*-coding:utf-8-*- import sys import os import configparser as cp work_path = os.path.dirname(os.getcwd()) sys.path.append(work_path) import numpy as np import pandas as pd from MNSIM.Interface.interface import * from MNSIM.Mapping_Model.Tile_connection_graph import TCG from MNSIM.Hardware_Model.Tile import tile from MNSIM.Power_Model.Model_inference_power import Model_inference_power from MNSIM.Latency_Model.Model_latency import Model_latency from MNSIM.Hardware_Model.Buffer import buffer from MNSIM.Hardware_Model.Adder import adder class Model_energy(): def __init__(self,NetStruct,SimConfig_path,model_power=None, model_latency=None,multiple=None,TCG_mapping=None): self.NetStruct = NetStruct self.SimConfig_path = SimConfig_path modelL_config = cp.ConfigParser() modelL_config.read(self.SimConfig_path, encoding='UTF-8') NoC_Compute = int(modelL_config.get('Algorithm Configuration', 'NoC_enable')) if multiple is None: multiple = [1] * len(self.NetStruct) if TCG_mapping is None: TCG_mapping = TCG(NetStruct, SimConfig_path, multiple) self.graph = TCG_mapping self.total_layer_num = self.graph.layer_num if model_latency is None: self.model_latency = Model_latency(NetStruct,SimConfig_path,multiple,TCG_mapping) self.model_latency.calculate_model_latency(mode=2) else: self.model_latency = model_latency if model_power is None: self.model_power = Model_inference_power(NetStruct,SimConfig_path,multiple,TCG_mapping) else: self.model_power = model_power self.arch_energy = self.total_layer_num * [0] self.arch_xbar_energy = self.total_layer_num * [0] self.arch_ADC_energy = self.total_layer_num * [0] self.arch_DAC_energy = self.total_layer_num * [0] self.arch_digital_energy = self.total_layer_num * [0] self.arch_adder_energy = self.total_layer_num * [0] self.arch_shiftreg_energy = self.total_layer_num * [0] self.arch_iReg_energy = self.total_layer_num * [0] self.arch_oReg_energy = self.total_layer_num * [0] self.arch_input_demux_energy = self.total_layer_num * [0] self.arch_output_mux_energy = self.total_layer_num * [0] self.arch_jointmodule_energy = self.total_layer_num * [0] self.arch_buf_energy = self.total_layer_num * [0] self.arch_buf_r_energy = self.total_layer_num * [0] self.arch_buf_w_energy = self.total_layer_num * [0] self.arch_pooling_energy = self.total_layer_num * [0] self.arch_total_energy = 0 self.arch_total_xbar_energy = 0 self.arch_total_ADC_energy = 0 self.arch_total_DAC_energy = 0 self.arch_total_digital_energy = 0 self.arch_total_adder_energy = 0 self.arch_total_shiftreg_energy = 0 self.arch_total_iReg_energy = 0 self.arch_total_input_demux_energy = 0 self.arch_total_jointmodule_energy = 0 self.arch_total_buf_energy = 0 self.arch_total_buf_r_energy = 0 self.arch_total_buf_w_energy = 0 self.arch_total_output_mux_energy = 0 self.arch_total_pooling_energy = 0 if NoC_Compute == 1: path = os.getcwd() + '/Final_Results/' data = pd.read_csv(path + 'Energy.csv') self.arch_Noc_energy = float(data.columns[0].split(' ')[-2]) * 1e-3 else: self.arch_Noc_energy = 0 # print("**********************************") # print(self.arch_Noc_energy) self.calculate_model_energy() def calculate_model_energy(self): #print(self.model_latency.total_buffer_r_latency) self.global_buf = buffer(SimConfig_path=self.SimConfig_path,buf_level=1, default_buf_size=self.graph.global_buf_size) self.global_buf.calculate_buf_read_power() self.global_buf.calculate_buf_write_power() self.global_add = adder(SimConfig_path=self.SimConfig_path, bitwidth=self.graph.global_adder_bitwidth) self.global_add.calculate_adder_power() for i in range(self.total_layer_num): tile_num = self.graph.layer_tileinfo[i]['tilenum'] self.arch_xbar_energy[i] = self.model_power.arch_xbar_power[i]*self.model_latency.total_xbar_latency[i] self.arch_ADC_energy[i] = self.model_power.arch_ADC_power[i]*self.model_latency.total_ADC_latency[i] self.arch_DAC_energy[i] = self.model_power.arch_DAC_power[i]*self.model_latency.total_DAC_latency[i] self.arch_adder_energy[i] = self.model_power.arch_adder_power[i]*self.model_latency.total_adder_latency[i] self.arch_shiftreg_energy[i] = self.model_power.arch_shiftreg_power[i]*self.model_latency.total_shiftreg_latency[i] self.arch_iReg_energy[i] = self.model_power.arch_iReg_power[i]*self.model_latency.total_iReg_latency[i] self.arch_oReg_energy[i] = self.model_power.arch_oReg_power[i]*self.model_latency.total_oReg_latency[i] self.arch_input_demux_energy[i] = self.model_power.arch_input_demux_power[i]*self.model_latency.total_input_demux_latency[i] self.arch_output_mux_energy[i] = self.model_power.arch_output_mux_power[i]*self.model_latency.total_output_mux_latency[i] self.arch_jointmodule_energy[i] = self.model_power.arch_jointmodule_power[i]*self.model_latency.total_jointmodule_latency[i] self.arch_buf_r_energy[i] = self.model_power.arch_buf_r_power[i]*self.model_latency.total_buffer_r_latency[i] self.arch_buf_w_energy[i] = self.model_power.arch_buf_w_power[i]*self.model_latency.total_buffer_w_latency[i] self.arch_buf_energy[i] = self.arch_buf_r_energy[i] + self.arch_buf_w_energy[i] self.arch_pooling_energy[i] = self.model_power.arch_pooling_power[i]*self.model_latency.total_pooling_latency[i] self.arch_digital_energy[i] = self.arch_shiftreg_energy[i]+self.arch_iReg_energy[i]+self.arch_oReg_energy[i]+\ self.arch_input_demux_energy[i]+self.arch_output_mux_energy[i]+self.arch_jointmodule_energy[i] self.arch_energy[i] = self.arch_xbar_energy[i]+self.arch_ADC_energy[i]+self.arch_DAC_energy[i]+\ self.arch_digital_energy[i]+self.arch_buf_energy[i]+self.arch_pooling_energy[i] self.arch_total_energy = sum(self.arch_energy) + self.arch_Noc_energy self.arch_total_xbar_energy = sum(self.arch_xbar_energy) self.arch_total_ADC_energy = sum(self.arch_ADC_energy) self.arch_total_DAC_energy = sum(self.arch_DAC_energy) self.arch_total_digital_energy = sum(self.arch_digital_energy)+\ self.global_add.adder_power*self.graph.global_adder_num*self.global_add.adder_latency self.arch_total_adder_energy = sum(self.arch_adder_energy)+\ self.global_add.adder_power*self.graph.global_adder_num*self.global_add.adder_latency self.arch_total_shiftreg_energy = sum(self.arch_shiftreg_energy) self.arch_total_iReg_energy = sum(self.arch_iReg_energy) self.arch_total_input_demux_energy = sum(self.arch_input_demux_energy) self.arch_total_output_mux_energy = sum(self.arch_output_mux_energy) self.arch_total_jointmodule_energy = sum(self.arch_jointmodule_energy) self.arch_total_buf_energy = sum(self.arch_buf_energy) + self.global_buf.buf_rpower*1e-3*self.global_buf.buf_rlatency \ + self.global_buf.buf_wpower*1e-3*self.global_buf.buf_wlatency self.arch_total_buf_r_energy = sum(self.arch_buf_r_energy) + self.global_buf.buf_rpower*1e-3*self.global_buf.buf_rlatency self.arch_total_buf_w_energy = sum(self.arch_buf_w_energy) + self.global_buf.buf_wpower*1e-3*self.global_buf.buf_wlatency self.arch_total_pooling_energy = sum(self.arch_pooling_energy) def model_energy_output(self, module_information = 1, layer_information = 1): print("Hardware energy:", self.arch_total_energy, "nJ") if module_information: print(" crossbar energy:", self.arch_total_xbar_energy, "nJ") print(" DAC energy:", self.arch_total_DAC_energy, "nJ") print(" ADC energy:", self.arch_total_ADC_energy, "nJ") print(" Buffer energy:", self.arch_total_buf_energy, "nJ") print(" |---read buffer energy:", self.arch_total_buf_r_energy, "nJ") print(" |---write buffer energy:", self.arch_total_buf_w_energy, "nJ") print(" Pooling energy:", self.arch_total_pooling_energy, "nJ") print(" Other digital part energy:", self.arch_total_digital_energy, "nJ") print(" |---adder energy:", self.arch_total_adder_energy, "nJ") print(" |---output-shift-reg energy:", self.arch_total_shiftreg_energy, "nJ") print(" |---input-reg energy:", self.arch_total_iReg_energy, "nJ") print(" |---input_demux energy:", self.arch_total_input_demux_energy, "nJ") print(" |---output_mux energy:", self.arch_total_output_mux_energy, "nJ") print(" |---joint_module energy:", self.arch_total_jointmodule_energy, "nJ") print(" NoC part energy:", self.arch_Noc_energy, "nJ") if layer_information: for i in range(self.total_layer_num): print("Layer", i, ":") print(" Hardware energy:", self.arch_energy[i], "nJ") if __name__ == '__main__': test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "SimConfig.ini") test_weights_file_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "vgg8_params.pth") __TestInterface = TrainTestInterface('vgg8_128_9', 'MNSIM.Interface.cifar10', test_SimConfig_path, test_weights_file_path) structure_file = __TestInterface.get_structure() __TCG_mapping = TCG(structure_file, test_SimConfig_path) __energy = Model_energy(NetStruct=structure_file,SimConfig_path=test_SimConfig_path,TCG_mapping=__TCG_mapping) __energy.model_energy_output(1,1)<file_sep>/MNSIM/Hardware_Model/DAC.py #!/usr/bin/python #-*-coding:utf-8-*- import configparser as cp import os import math test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"SimConfig.ini") #Default SimConfig file path: MNSIM_Python/SimConfig.ini class DAC(object): def __init__(self, SimConfig_path): DAC_config = cp.ConfigParser() DAC_config.read(SimConfig_path, encoding='UTF-8') self.DAC_choice = int(DAC_config.get('Interface level', 'DAC_Choice')) self.DAC_area = float(DAC_config.get('Interface level', 'DAC_Area')) self.DAC_precision = int(DAC_config.get('Interface level', 'DAC_Precision')) self.DAC_power = float(DAC_config.get('Interface level', 'DAC_Power')) self.DAC_sample_rate = float(DAC_config.get('Interface level', 'DAC_Sample_Rate')) self.DAC_energy = 0 self.DAC_latency = 0 # print("DAC configuration is loaded") # self.calculate_DAC_area() self.calculate_DAC_precision() # self.calculate_DAC_power() self.calculate_DAC_sample_rate() # self.calculate_DAC_energy() def calculate_DAC_area(self): #unit: um^2 #Data reference: ISAAC: A Convolutional Neural Network Accelerator with In-Situ Analog Arithmetic in Crossbars DAC_area_dict = {1: 0.166, #1-bit 2: 0.332, #2-bit 3: 0.664, #3-bit 4: 1.328, #4-bit 5: 5.312, #6-bit 6: 21.248 #8-bit } if self.DAC_choice != -1: assert self.DAC_choice in [1,2,3,4,5,6] self.DAC_area = DAC_area_dict[self.DAC_choice] def calculate_DAC_precision(self): #Data reference: ISAAC: A Convolutional Neural Network Accelerator with In-Situ Analog Arithmetic in Crossbars DAC_precision_dict = {1: 1, #1-bit 2: 2, #2-bit 3: 3, #3-bit 4: 4, #4-bit 5: 6, #6-bit 6: 8 #8-bit } if self.DAC_choice != -1: assert self.DAC_choice in [1,2,3,4,5,6] self.DAC_precision = DAC_precision_dict[self.DAC_choice] def calculate_DAC_power(self): #unit: W #Data reference: ISAAC: A Convolutional Neural Network Accelerator with In-Situ Analog Arithmetic in Crossbars DAC_power_dict = {1: 0.0039*1e-3, #1-bit 2: 0.0078*1e-3, #2-bit 3: 0.0156*1e-3, #3-bit 4: 0.0312*1e-3, #4-bit 5: 0.1248*1e-3, #6-bit 6: 0.4992 #8-bit } if self.DAC_choice != -1: assert self.DAC_choice in [1,2,3,4,5,6] self.DAC_power = DAC_power_dict[self.DAC_choice] def calculate_DAC_sample_rate(self): # unit: GSamples/s if self.DAC_choice != -1: self.DAC_sample_rate = 1 def calculate_DAC_latency(self): # unit: ns self.DAC_latency = 1 / self.DAC_sample_rate * (self.DAC_precision + 2) def calculate_DAC_energy(self): #unit: nJ self.DAC_energy = self.DAC_latency * self.DAC_power def DAC_output(self): if self.DAC_choice == -1: print("DAC_choice: User defined") else: print("DAC_choice:", self.DAC_choice) print("DAC_area:", self.DAC_area, "um^2") print("DAC_precision:", self.DAC_precision, "bit") print("DAC_power:", self.DAC_power, "W") print("DAC_sample_rate:", self.DAC_sample_rate, "Gbit/s") print("DAC_energy:", self.DAC_energy, "nJ") print("DAC_latency:", self.DAC_latency, "ns") def DAC_test(): print("load file:",test_SimConfig_path) _DAC = DAC(test_SimConfig_path) _DAC.calculate_DAC_area() _DAC.calculate_DAC_power() _DAC.calculate_DAC_sample_rate() _DAC.calculate_DAC_latency() _DAC.calculate_DAC_energy() _DAC.DAC_output() if __name__ == '__main__': DAC_test()<file_sep>/MNSIM/Hardware_Model/Pooling.py #!/usr/bin/python #-*-coding:utf-8-*- import configparser as cp import os import math test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"SimConfig.ini") class Pooling(object): def __init__(self, SimConfig_path): Pooling_config = cp.ConfigParser() Pooling_config.read(SimConfig_path, encoding='UTF-8') # self.Pooling_choice = Pooling_config.get() self.Pooling_unit_num = int(Pooling_config.get('Tile level', 'Pooling_unit_num')) if self.Pooling_unit_num == 0: self.Pooling_unit_num = 64 self.Pooling_Tech = int(Pooling_config.get('Tile level', 'Pooling_Tech')) if self.Pooling_Tech == 0: self.Pooling_Tech = 65 self.Pooling_area = float(Pooling_config.get('Tile level', 'Pooling_area')) self.Pooling_power = 0 self.Pooling_energy = 0 self.Pooling_area = 0 self.Pooling_latency = 0 self.Pooling_shape = list(map(int, Pooling_config.get('Tile level', 'Pooling_shape').split(','))) assert len(self.Pooling_shape) == 2, "Input of Pooling shape is illegal" self.Pooling_size = self.Pooling_shape[0] * self.Pooling_shape[1] if self.Pooling_size == 0: self.Pooling_size = 9 def calculate_Pooling_area(self): # unit um^2 Technology & pooling size & unit num Pooling_area_dict = { 65: { 9: { 64: 91917.1562 } } } if self.Pooling_Tech in [65]: if self.Pooling_size in [9]: ''' 线性插值 ''' self.Pooling_area = Pooling_area_dict[self.Pooling_Tech][self.Pooling_size][self.Pooling_unit_num]*self.Pooling_unit_num/64 else: self.Pooling_area = Pooling_area_dict[65][9][64] * pow((self.Pooling_Tech/65),2)*self.Pooling_unit_num/64 def calculate_Pooling_power(self): # Unit : W Pooling_power_dict = { 65: { 9: { 64: 3.082*1e-3 } } } if self.Pooling_Tech in [65]: if self.Pooling_size in [9]: ''' 线性插值 ''' self.Pooling_power = Pooling_power_dict[self.Pooling_Tech][self.Pooling_size][self.Pooling_unit_num] else: self.Pooling_power = Pooling_power_dict[65][9][64] * pow((self.Pooling_Tech/65),2) def calculate_Pooling_latency(self, inchannel = 64, insize = 9): # Unit: ns Pooling_latency_dict = { 65: { 9: { 64: 100 } } } self.Pooling_latency = 100*math.ceil(inchannel/self.Pooling_unit_num)*math.ceil(insize/self.Pooling_size) # if self.Pooling_Tech in [65]: # if self.Pooling_size in [9]: # ''' 线性插值 ''' # self.Pooling_latency = Pooling_latency_dict[self.Pooling_Tech][self.Pooling_size][self.Pooling_unit_num]*math.ceil(inchannel/self.Pooling_unit_num) def calculate_Pooling_energy(self): #unit mW self.Pooling_energy = self.Pooling_power * self.Pooling_latency def Pooling_output(self): # if self.Pooling_choice == -1: # print("ADC_choice: User defined") # else: # print("default configuration") print("Pooling_shape: %d x %d" %(self.Pooling_shape[0], self.Pooling_shape[1])) print("Pooling_area:", self.Pooling_area, "um^2") print("Pooling_power:", self.Pooling_power, "W") print("Pooling_latency:", self.Pooling_latency, "ns") print("Pooling_energy:", self.Pooling_energy, "nJ") def Pooling_test(): print("load file:", test_SimConfig_path) _Pooling = Pooling(test_SimConfig_path) _Pooling.calculate_Pooling_area() _Pooling.calculate_Pooling_power() _Pooling.calculate_Pooling_latency() _Pooling.calculate_Pooling_energy() _Pooling.Pooling_output() if __name__ == '__main__': Pooling_test() <file_sep>/MNSIM/Hardware_Model/PE.py #!/usr/bin/python # -*-coding:utf-8-*- import configparser as cp import os import math from numpy import * import numpy as np from MNSIM.Hardware_Model.Crossbar import crossbar from MNSIM.Hardware_Model.DAC import DAC from MNSIM.Hardware_Model.ADC import ADC from MNSIM.Hardware_Model.Adder import adder from MNSIM.Hardware_Model.ShiftReg import shiftreg from MNSIM.Hardware_Model.Reg import reg from MNSIM.Hardware_Model.Buffer import buffer test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"SimConfig.ini") # Default SimConfig file path: MNSIM_Python/SimConfig.ini class ProcessElement(crossbar, DAC, ADC): def __init__(self, SimConfig_path): crossbar.__init__(self, SimConfig_path) DAC.__init__(self, SimConfig_path) ADC.__init__(self, SimConfig_path) PE_config = cp.ConfigParser() PE_config.read(SimConfig_path, encoding='UTF-8') self.sub_position = 0 __xbar_polarity = int(PE_config.get('Process element level', 'Xbar_Polarity')) # self.PE_multiplex_xbar_num = list( # map(int, PE_config.get('Process element level', 'Multiplex_Xbar_Num').split(','))) if __xbar_polarity == 1: self.PE_multiplex_xbar_num = [1,1] else: assert __xbar_polarity == 2, "Crossbar polarity must be 1 or 2" self.PE_multiplex_xbar_num = [1,2] self.sub_position = int(PE_config.get('Process element level', 'Sub_Position')) self.group_num = int(PE_config.get('Process element level', 'Group_Num')) if self.group_num == 0: self.group_num = 1 self.num_occupied_group = 0 self.PE_xbar_num = self.group_num * self.PE_multiplex_xbar_num[0] * self.PE_multiplex_xbar_num[1] # self.polarity = PE_config.get('Algorithm Configuration', 'Weight_Polarity') # if self.polarity == 2: # assert self.PE_xbar_num[1]%2 == 0 self.PE_simulation_level = int(PE_config.get('Algorithm Configuration', 'Simulation_Level')) self.PE_xbar_list = [] self.PE_xbar_enable = [] for i in range(self.group_num): self.PE_xbar_list.append([]) self.PE_xbar_enable.append([]) for j in range(self.PE_multiplex_xbar_num[0] * self.PE_multiplex_xbar_num[1]): __xbar = crossbar(SimConfig_path) self.PE_xbar_list[i].append(__xbar) self.PE_xbar_enable[i].append(0) self.PE_group_ADC_num = int(PE_config.get('Process element level', 'ADC_Num')) self.PE_group_DAC_num = int(PE_config.get('Process element level', 'DAC_Num')) self.PE_ADC_num = 0 self.PE_DAC_num = 0 self.input_demux = 0 self.input_demux_power = 0 self.input_demux_area = 0 self.output_mux = 0 self.output_mux_power = 0 self.output_mux_area = 0 self.calculate_ADC_num() self.calculate_DAC_num() self.PE_adder = adder(SimConfig_path) self.PE_adder_num = 0 self.PE_shiftreg = shiftreg(SimConfig_path) self.PE_iReg = reg(SimConfig_path) self.PE_oReg = reg(SimConfig_path) self.PE_utilization = 0 self.PE_max_occupied_column = 0 self.PE_area = 0 self.PE_xbar_area = 0 self.PE_ADC_area = 0 self.PE_DAC_area = 0 self.PE_adder_area = 0 self.PE_shiftreg_area = 0 self.PE_iReg_area = 0 self.PE_oReg_area = 0 self.PE_input_demux_area = 0 self.PE_output_mux_area = 0 self.PE_digital_area = 0 self.PE_inbuf_area = 0 self.PE_read_power = 0 self.PE_xbar_read_power = 0 self.PE_ADC_read_power = 0 self.PE_DAC_read_power = 0 self.PE_adder_read_power = 0 self.PE_shiftreg_read_power = 0 self.PE_iReg_read_power = 0 self.PE_oReg_read_power = 0 self.input_demux_read_power = 0 self.output_mux_read_power = 0 self.PE_digital_read_power = 0 self.PE_inbuf_read_rpower = 0 self.PE_inbuf_read_wpower = 0 self.PE_inbuf_read_power = 0 self.PE_write_power = 0 self.PE_xbar_write_power = 0 self.PE_ADC_write_power = 0 self.PE_DAC_write_power = 0 self.PE_adder_write_power = 0 self.PE_shiftreg_write_power = 0 self.PE_iReg_write_power = 0 self.input_demux_write_power = 0 self.output_mux_write_power = 0 self.PE_digital_write_power = 0 self.PE_read_latency = 0 self.PE_xbar_read_latency = 0 self.PE_ADC_read_latency = 0 self.PE_DAC_read_latency = 0 self.PE_adder_read_latency = 0 self.PE_shiftreg_read_latency = 0 self.PE_iReg_read_latency = 0 self.input_demux_read_latency = 0 self.output_mux_read_latency = 0 self.PE_digital_read_latency = 0 self.PE_write_latency = 0 self.PE_xbar_write_latency = 0 self.PE_ADC_write_latency = 0 self.PE_DAC_write_latency = 0 self.PE_adder_write_latency = 0 self.PE_shiftreg_write_latency = 0 self.PE_iReg_write_latency = 0 self.input_demux_write_latency = 0 self.output_mux_write_latency = 0 self.PE_digital_write_latency = 0 self.PE_read_energy = 0 self.PE_xbar_read_energy = 0 self.PE_ADC_read_energy = 0 self.PE_DAC_read_energy = 0 self.PE_adder_read_energy = 0 self.PE_shiftreg_read_energy = 0 self.PE_iReg_read_energy = 0 self.input_demux_read_energy = 0 self.output_mux_read_energy = 0 self.PE_digital_read_energy = 0 self.PE_write_energy = 0 self.PE_xbar_write_energy = 0 self.PE_ADC_write_energy = 0 self.PE_DAC_write_energy = 0 self.PE_adder_write_energy = 0 self.PE_shiftreg_write_energy = 0 self.PE_iReg_write_energy = 0 self.input_demux_write_energy = 0 self.output_mux_write_energy = 0 self.PE_digital_write_energy = 0 self.calculate_inter_PE_connection() def calculate_ADC_num(self): self.calculate_xbar_area() self.calculate_ADC_area() if self.PE_group_ADC_num == 0: self.PE_group_ADC_num = min((self.sub_position+1) * math.ceil(math.sqrt(self.xbar_area)*self.PE_multiplex_xbar_num[1]/math.sqrt(self.ADC_area)), self.xbar_column) else: assert self.PE_group_ADC_num > 0, "ADC number in one group < 0" self.PE_ADC_num = self.group_num * self.PE_group_ADC_num # self.output_mux = math.ceil(self.xbar_column*self.PE_multiplex_xbar_num[1]/self.PE_group_ADC_num) self.output_mux = math.ceil(self.xbar_column/self.PE_group_ADC_num * (self.sub_position+1)) assert self.output_mux > 0 def calculate_DAC_num(self): self.calculate_xbar_area() self.calculate_DAC_area() if self.PE_group_DAC_num == 0: self.PE_group_DAC_num = min(math.ceil(math.sqrt(self.xbar_area) * self.PE_multiplex_xbar_num[0] / math.sqrt(self.DAC_area)), self.xbar_row) else: assert self.PE_group_DAC_num > 0, "DAC number in one group < 0" self.PE_DAC_num = self.group_num * self.PE_group_DAC_num self.input_demux = math.ceil(self.xbar_row*self.PE_multiplex_xbar_num[0]/self.PE_group_DAC_num) assert self.input_demux > 0 def calculate_demux_area(self): transistor_area = 10* self.transistor_tech * self.transistor_tech / 1000000 demux_area_dict = {2: 8*transistor_area, # 2-1: 8 transistors 4: 24*transistor_area, # 4-1: 3 * 2-1 8: 72*transistor_area, 16: 216*transistor_area, 32: 648*transistor_area, 64: 1944*transistor_area } # unit: um^2 # TODO: add circuits simulation results if self.input_demux <= 2: self.input_demux_area = demux_area_dict[2] elif self.input_demux<=4: self.input_demux_area = demux_area_dict[4] elif self.input_demux<=8: self.input_demux_area = demux_area_dict[8] elif self.input_demux<=16: self.input_demux_area = demux_area_dict[16] elif self.input_demux<=32: self.input_demux_area = demux_area_dict[32] else: self.input_demux_area = demux_area_dict[64] def calculate_mux_area(self): transistor_area = 10* self.transistor_tech * self.transistor_tech / 1000000 mux_area_dict = {2: 8*transistor_area, 4: 24*transistor_area, 8: 72*transistor_area, 16: 216*transistor_area, 32: 648*transistor_area, 64: 1944*transistor_area } # unit: um^2 # TODO: add circuits simulation results if self.output_mux <= 2: self.output_mux_area = mux_area_dict[2] elif self.output_mux <= 4: self.output_mux_area = mux_area_dict[4] elif self.output_mux <= 8: self.output_mux_area = mux_area_dict[8] elif self.output_mux <= 16: self.output_mux_area = mux_area_dict[16] elif self.output_mux <= 32: self.output_mux_area = mux_area_dict[32] else: self.output_mux_area = mux_area_dict[64] def calculate_inter_PE_connection(self): temp = self.group_num self.PE_adder_num = 0 while temp/2 >= 1: self.PE_adder_num += int(temp/2) temp = int(temp/2) + temp%2 def PE_read_config(self, read_row = None, read_column = None, read_matrix = None, read_vector = None): # read_row and read_column are lists with the length of #occupied groups # read_matrix is a 2D list of matrices. The size of the list is (#occupied groups x Xbar_Polarity) # read_vector is a list of vectors with the length of #occupied groups self.PE_utilization = 0 if self.PE_simulation_level == 0: if (read_row is None) or (read_column is None): self.num_occupied_group = self.group_num for i in range(self.group_num): if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_list[i][0].xbar_read_config() self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization else: self.PE_xbar_list[i][0].xbar_read_config() self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization self.PE_xbar_list[i][1].xbar_read_config() self.PE_xbar_enable[i][1] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization else: assert len(read_row) == len(read_column), "read_row and read_column must be equal in length" self.num_occupied_group = len(read_row) assert self.num_occupied_group <= self.group_num, "The length of read_row exceeds the group number in one PE" for i in range(self.group_num): if i < self.num_occupied_group: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_list[i][0].xbar_read_config(read_row = read_row[i], read_column = read_column[i]) self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization else: self.PE_xbar_list[i][0].xbar_read_config(read_row=read_row[i], read_column=read_column[i]) self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization self.PE_xbar_list[i][1].xbar_read_config(read_row=read_row[i], read_column=read_column[i]) self.PE_xbar_enable[i][1] = 1 self.PE_utilization += self.PE_xbar_list[i][1].xbar_utilization else: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_enable[i][0] = 0 else: self.PE_xbar_enable[i][0] = 0 self.PE_xbar_enable[i][1] = 0 else: if read_matrix is None: self.num_occupied_group = self.group_num for i in range(self.group_num): if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_list[i][0].xbar_read_config() self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization else: self.PE_xbar_list[i][0].xbar_read_config() self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization self.PE_xbar_list[i][1].xbar_read_config() self.PE_xbar_enable[i][1] = 1 self.PE_utilization += self.PE_xbar_list[i][1].xbar_utilization else: if read_vector is None: self.num_occupied_group = len(read_matrix) assert self.num_occupied_group <= self.group_num, "The number of read_matrix exceeds the group number in one PE" for i in range(self.group_num): if i < self.num_occupied_group: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_list[i][0].xbar_read_config(read_matrix=read_matrix[i][0]) self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization else: self.PE_xbar_list[i][0].xbar_read_config(read_matrix=read_matrix[i][0]) self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization self.PE_xbar_list[i][1].xbar_read_config(read_matrix=read_matrix[i][1]) self.PE_xbar_enable[i][1] = 1 self.PE_utilization += self.PE_xbar_list[i][1].xbar_utilization else: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_enable[i][0] = 0 else: self.PE_xbar_enable[i][0] = 0 self.PE_xbar_enable[i][1] = 0 else: assert len(read_matrix) == len(read_vector), "The number of read_matrix and read_vector must be equal" self.num_occupied_group = len(read_matrix) assert self.num_occupied_group <= self.group_num, "The number of read_matrix/read_vector exceeds the group number in one PE" for i in range(self.group_num): if i < self.num_occupied_group: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_list[i][0].xbar_read_config(read_matrix = read_matrix[i][0], read_vector = read_vector[i]) self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization else: self.PE_xbar_list[i][0].xbar_read_config(read_matrix = read_matrix[i][0], read_vector = read_vector[i]) self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization self.PE_xbar_list[i][1].xbar_read_config(read_matrix = read_matrix[i][1], read_vector = read_vector[i]) self.PE_xbar_enable[i][1] = 1 self.PE_utilization += self.PE_xbar_list[i][1].xbar_utilization else: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_enable[i][0] = 0 else: self.PE_xbar_enable[i][0] = 0 self.PE_xbar_enable[i][1] = 0 self.PE_utilization /= (self.group_num * self.PE_multiplex_xbar_num[1]) def PE_write_config(self, write_row=None, write_column=None, write_matrix=None, write_vector=None): # write_row and write_column are array with the length of #occupied groups # write_matrix is a 2D array of matrices. The size of the list is (#occupied groups x Xbar_Polarity) # write_vector is a array of vector with the length of #occupied groups if self.PE_simulation_level == 0: if (write_row is None) or (write_column is None): self.num_occupied_group = self.group_num for i in range(self.group_num): if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_list[i][0].xbar_write_config() self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization else: self.PE_xbar_list[i][0].xbar_write_config() self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization self.PE_xbar_list[i][1].xbar_write_config() self.PE_xbar_enable[i][1] = 1 self.PE_utilization += self.PE_xbar_list[i][1].xbar_utilization else: assert len(write_row) == len(write_column), "write_row and write_column must be equal in length" self.num_occupied_group = len(write_row) assert self.num_occupied_group <= self.group_num, "The length of write_row exceeds the group number in one PE" for i in range(self.group_num): if i < self.num_occupied_group: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_list[i][0].xbar_write_config(write_row=write_row[i], write_column=write_column[i]) self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization else: self.PE_xbar_list[i][0].xbar_write_config(write_row=write_row[i], write_column=write_column[i]) self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization self.PE_xbar_list[i][1].xbar_write_config(write_row=write_row[i], write_column=write_column[i]) self.PE_xbar_enable[i][1] = 1 self.PE_utilization += self.PE_xbar_list[i][1].xbar_utilization else: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_enable[i][0] = 0 else: self.PE_xbar_enable[i][0] = 0 self.PE_xbar_enable[i][1] = 0 else: if write_matrix is None: self.num_occupied_group = self.group_num for i in range(self.group_num): if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_list[i][0].xbar_write_config() self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization else: self.PE_xbar_list[i][0].xbar_write_config() self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization self.PE_xbar_list[i][1].xbar_write_config() self.PE_xbar_enable[i][1] = 1 self.PE_utilization += self.PE_xbar_list[i][1].xbar_utilization else: if write_vector is None: self.num_occupied_group = len(write_matrix) assert self.num_occupied_group <= self.group_num, "The number of write_matrix exceeds the group number in one PE" for i in range(self.group_num): if i < self.num_occupied_group: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_list[i][0].xbar_write_config(write_matrix=write_matrix[i][0]) self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization else: self.PE_xbar_list[i][0].xbar_write_config(write_matrix=write_matrix[i][0]) self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization self.PE_xbar_list[i][1].xbar_write_config(write_matrix=write_matrix[i][1]) self.PE_xbar_enable[i][1] = 1 self.PE_utilization += self.PE_xbar_list[i][1].xbar_utilization else: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_enable[i][0] = 0 else: self.PE_xbar_enable[i][0] = 0 self.PE_xbar_enable[i][1] = 0 else: assert len(write_matrix) == len(write_vector), "The number of write_matrix and write_vector must be equal" self.num_occupied_group = len(write_matrix) assert self.num_occupied_group <= self.group_num, "The number of write_matrix/write_vector exceeds the group number in one PE" for i in range(self.group_num): if i < self.num_occupied_group: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_list[i][0].xbar_write_config(write_matrix=write_matrix[i][0], write_vector=write_vector[i]) self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization else: self.PE_xbar_list[i][0].xbar_write_config(write_matrix=write_matrix[i][0], write_vector=write_vector[i]) self.PE_xbar_enable[i][0] = 1 self.PE_utilization += self.PE_xbar_list[i][0].xbar_utilization self.PE_xbar_list[i][1].xbar_write_config(write_matrix=write_matrix[i][1], write_vector=write_vector[i]) self.PE_xbar_enable[i][1] = 1 self.PE_utilization += self.PE_xbar_list[i][1].xbar_utilization else: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_enable[i][0] = 0 else: self.PE_xbar_enable[i][0] = 0 self.PE_xbar_enable[i][1] = 0 self.PE_utilization /= (self.group_num * self.PE_multiplex_xbar_num[1]) def calculate_PE_area(self, SimConfig_path=None, default_inbuf_size = 16): # unit: um^2 self.inbuf = buffer(SimConfig_path=SimConfig_path,buf_level=1,default_buf_size=default_inbuf_size) self.inbuf.calculate_buf_area() self.calculate_xbar_area() self.calculate_demux_area() self.calculate_mux_area() self.calculate_DAC_area() self.calculate_ADC_area() self.PE_adder.calculate_adder_area() self.PE_shiftreg.calculate_shiftreg_area() self.PE_iReg.calculate_reg_area() self.PE_oReg.calculate_reg_area() self.PE_xbar_area = self.PE_xbar_num*self.xbar_area self.PE_ADC_area = self.ADC_area*self.PE_ADC_num self.PE_DAC_area = self.DAC_area*self.PE_DAC_num self.PE_adder_area = self.PE_group_ADC_num*self.PE_adder_num*self.PE_adder.adder_area self.PE_shiftreg_area = self.PE_ADC_num*self.PE_shiftreg.shiftreg_area self.PE_iReg_area = self.PE_DAC_num*self.PE_iReg.reg_area self.PE_oReg_area = self.PE_ADC_num*self.PE_oReg.reg_area self.PE_input_demux_area = self.input_demux_area*self.PE_DAC_num self.PE_output_mux_area = self.output_mux_area*self.PE_ADC_num self.PE_digital_area = self.PE_adder_area + self.PE_shiftreg_area + self.PE_input_demux_area + \ self.PE_output_mux_area + self.PE_iReg_area + self.PE_oReg_area self.PE_inbuf_area = self.inbuf.buf_area self.PE_area = self.PE_xbar_area + self.PE_ADC_area + self.PE_DAC_area + self.PE_digital_area + self.PE_inbuf_area '''def calculate_PE_read_latency(self): # Notice: before calculating latency, PE_read_config must be executed # unit: ns self.PE_xbar_read_latency = 0 self.calculate_xbar_read_latency() self.calculate_DAC_sample_rate() self.calculate_ADC_sample_rate() max_multiple_time = 0 for i in range(self.group_num): if self.PE_xbar_enable[i][0] == 1: multiple_time = math.ceil(self.PE_xbar_list[i][0].xbar_num_read_row/self.PE_group_DAC_num)\ * math.ceil(self.PE_xbar_list[i][0].xbar_num_read_column/self.PE_group_ADC_num) if multiple_time > max_multiple_time: max_multiple_time = multiple_time self.PE_xbar_read_latency = max_multiple_time * self.xbar_read_latency self.PE_ADC_read_latency = max_multiple_time * 1 / self.ADC_sample_rate * (self.ADC_precision + 2) self.PE_DAC_read_latency = max_multiple_time * 1 / self.DAC_sample_rate * (self.DAC_precision + 2) # TODO: check the ADDA latency formalution # TODO: Add the mux/demux latency self.input_demux_read_latency = 0 self.output_mux_read_latency = 0 self.PE_adder_read_latency = max_multiple_time * self.PE_adder.adder_latency * math.ceil(math.log2(self.group_num)) self.PE_shiftreg_read_latency = max_multiple_time * self.PE_shiftreg.shiftreg_latency self.PE_digital_read_latency = self.input_demux_read_latency + self.output_mux_read_latency\ + self.PE_adder_read_latency + self.PE_shiftreg_read_latency # TODO: PipeLine optimization # ignore the latency of MUX and DEMUX self.PE_read_latency = self.PE_xbar_read_latency + self.PE_ADC_read_latency\ + self.PE_DAC_read_latency + self.PE_digital_read_latency def calculate_PE_write_latency(self): # Notice: before calculating latency, PE_write_config must be executed # unit: ns self.PE_xbar_write_latency = 0 self.calculate_DAC_sample_rate() max_write_row = 0 for i in range(self.group_num): if self.PE_xbar_enable[i][0] == 1: write_row = self.PE_xbar_list[i][0].xbar_num_write_row if write_row > max_write_row: max_write_row = write_row self.PE_xbar_list[i][0].calculate_xbar_write_latency() if self.PE_xbar_list[i][0].xbar_write_latency > self.PE_xbar_write_latency: self.PE_xbar_write_latency = self.PE_xbar_list[i][0].xbar_write_latency self.PE_DAC_write_latency = max_write_row * 1 / self.DAC_sample_rate * self.DAC_precision self.PE_ADC_write_latency = 0 # TODO: Add the demux latency self.input_demux_write_latency = 0 self.output_mux_write_latency = 0 self.PE_adder_write_latency = 0 self.PE_shiftreg_write_latency = 0 self.PE_digital_write_latency = self.input_demux_write_latency + self.output_mux_write_latency \ + self.PE_adder_write_latency + self.PE_shiftreg_write_latency # TODO: PipeLine optimization self.PE_write_latency = self.PE_xbar_write_latency + self.PE_ADC_write_latency\ + self.PE_DAC_write_latency + self.PE_digital_write_latency''' def calculate_demux_power(self): transistor_power = 10*1.2/1e9 demux_power_dict = {2: 8*transistor_power, 4: 24*transistor_power, 8: 72*transistor_power, 16: 216*transistor_power, 32: 648*transistor_power, 64: 1944*transistor_power } # unit: W # TODO: add circuits simulation results if self.input_demux <= 2: self.input_demux_power = demux_power_dict[2] elif self.input_demux<=4: self.input_demux_power = demux_power_dict[4] elif self.input_demux<=8: self.input_demux_power = demux_power_dict[8] elif self.input_demux<=16: self.input_demux_power = demux_power_dict[16] elif self.input_demux<=32: self.input_demux_power = demux_power_dict[32] else: self.input_demux_power = demux_power_dict[64] def calculate_mux_power(self): transistor_power = 10*1.2/1e9 mux_power_dict = {2: 8*transistor_power, 4: 24*transistor_power, 8: 72*transistor_power, 16: 216*transistor_power, 32: 648*transistor_power, 64: 1944*transistor_power } # unit: W # TODO: add circuits simulation results if self.output_mux <= 2: self.output_mux_power = mux_power_dict[2] elif self.output_mux <= 4: self.output_mux_power = mux_power_dict[4] elif self.output_mux <= 8: self.output_mux_power = mux_power_dict[8] elif self.output_mux <= 16: self.output_mux_power = mux_power_dict[16] elif self.output_mux <= 32: self.output_mux_power = mux_power_dict[32] else: self.output_mux_power = mux_power_dict[64] def calculate_PE_read_power_fast(self, max_column=0, max_row=0, max_group=0, SimConfig_path=None, default_inbuf_size = 16): # unit: W # coarse but fast estimation # max_column: maximum used column in one crossbar in this tile # max_row: maximum used row in one crossbar in this tile # max_group: maximum used groups in one PE self.inbuf = buffer(SimConfig_path=SimConfig_path, buf_level=1, default_buf_size=default_inbuf_size) self.inbuf.calculate_buf_read_power() self.inbuf.calculate_buf_write_power() self.calculate_DAC_power() self.calculate_ADC_power() self.calculate_demux_power() self.calculate_mux_power() self.PE_shiftreg.calculate_shiftreg_power() self.PE_iReg.calculate_reg_power() self.PE_oReg.calculate_reg_power() self.PE_adder.calculate_adder_power() self.PE_read_power = 0 self.PE_xbar_read_power = 0 self.PE_ADC_read_power = 0 self.PE_DAC_read_power = 0 self.PE_adder_read_power = 0 self.PE_shiftreg_read_power = 0 self.PE_iReg_read_power = 0 self.PE_oReg_read_power = 0 self.input_demux_read_power = 0 self.output_mux_read_power = 0 self.PE_digital_read_power = 0 self.xbar_read_config(read_row=max_row, read_column=max_column) self.calculate_xbar_read_power() self.PE_xbar_read_power = self.PE_multiplex_xbar_num[1]*max_group*self.xbar_read_power/self.input_demux/self.output_mux self.PE_DAC_read_power = max_group*math.ceil(max_row/self.input_demux) * self.DAC_power self.PE_ADC_read_power = max_group*math.ceil(max_column/self.output_mux) * self.ADC_power self.input_demux_read_power = max_group*math.ceil(max_row/self.input_demux) * self.input_demux_power self.output_mux_read_power = max_group*math.ceil(max_column/self.output_mux) * self.output_mux_power self.PE_adder_read_power = (max_group - 1) * math.ceil(max_column/self.output_mux) * self.PE_adder.adder_power self.PE_shiftreg_read_power = max_group * math.ceil(max_column/self.output_mux) * self.PE_shiftreg.shiftreg_power self.PE_iReg_read_power = max_group * math.ceil(max_row/self.input_demux) * self.PE_iReg.reg_power self.PE_oReg_read_power = max_group * math.ceil(max_column / self.output_mux) * self.PE_oReg.reg_power self.PE_digital_read_power = self.input_demux_read_power + self.output_mux_read_power + self.PE_adder_read_power + self.PE_shiftreg_read_power + self.PE_iReg_read_power + self.PE_oReg_read_power self.PE_inbuf_read_rpower = self.inbuf.buf_rpower*1e-3 self.PE_inbuf_read_wpower = self.inbuf.buf_wpower * 1e-3 self.PE_inbuf_read_power = self.PE_inbuf_read_rpower + self.PE_inbuf_read_wpower self.PE_read_power = self.PE_xbar_read_power + self.PE_DAC_read_power + self.PE_ADC_read_power + self.PE_digital_read_power + self.PE_inbuf_read_power def calculate_PE_read_power(self): # unit: W # Notice: before calculating latency, PE_read_config must be executed self.calculate_DAC_power() self.calculate_ADC_power() self.calculate_demux_power() self.calculate_mux_power() self.PE_shiftreg.calculate_shiftreg_power() self.PE_iReg.calculate_reg_power() self.PE_read_power = 0 self.PE_xbar_read_power = 0 self.PE_ADC_read_power = 0 self.PE_DAC_read_power = 0 self.PE_adder_read_power = 0 self.PE_shiftreg_read_power = 0 self.PE_iReg_read_power = 0 self.input_demux_read_power = 0 self.output_mux_read_power = 0 self.PE_digital_read_power = 0 self.PE_max_occupied_column = 0 if self.num_occupied_group != 0: for i in range(self.group_num): if self.PE_xbar_enable[i][0] == 1: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_list[i][0].calculate_xbar_read_power() self.PE_xbar_read_power += self.PE_xbar_list[i][0].xbar_read_power/self.input_demux/self.output_mux else: self.PE_xbar_list[i][0].calculate_xbar_read_power() self.PE_xbar_read_power += self.PE_xbar_list[i][0].xbar_read_power/self.input_demux/self.output_mux self.PE_xbar_list[i][1].calculate_xbar_read_power() self.PE_xbar_read_power += self.PE_xbar_list[i][1].xbar_read_power/self.input_demux/self.output_mux self.PE_DAC_read_power += math.ceil(self.PE_xbar_list[i][0].xbar_num_read_row/self.input_demux)*self.DAC_power self.PE_ADC_read_power += math.ceil(self.PE_xbar_list[i][0].xbar_num_read_column/self.output_mux)*self.ADC_power self.PE_iReg_read_power += math.ceil(self.PE_xbar_list[i][0].xbar_num_read_row/self.input_demux)*self.PE_iReg.shiftreg_power self.input_demux_read_power += math.ceil(self.PE_xbar_list[i][0].xbar_num_read_row/self.input_demux)*self.input_demux_power self.output_mux_read_power += math.ceil(self.PE_xbar_list[i][0].xbar_num_read_column/self.output_mux)*self.output_mux_power if self.PE_xbar_list[i][0].xbar_num_read_column > self.PE_max_occupied_column: # find the most occupied column of each group in one PE self.PE_max_occupied_column = self.PE_xbar_list[i][0].xbar_num_read_column # PE_max_read_column = min(self.PE_max_occupied_column, self.PE_group_ADC_num) self.PE_adder_read_power = (self.num_occupied_group-1)*(self.PE_max_occupied_column/self.output_mux)*self.PE_adder.adder_power self.PE_shiftreg_read_power = (self.num_occupied_group)*(self.PE_max_occupied_column/self.output_mux)*self.PE_shiftreg.shiftreg_power self.PE_digital_read_power = self.input_demux_read_power + self.output_mux_read_power + self.PE_adder_read_power + self.PE_shiftreg_read_power + self.PE_iReg_read_power self.PE_read_power = self.PE_xbar_read_power + self.PE_DAC_read_power + self.PE_ADC_read_power + self.PE_digital_read_power '''def calculate_PE_write_power(self): # unit: W # Notice: before calculating latency, PE_write_config must be executed self.calculate_DAC_power() self.calculate_ADC_power() self.calculate_demux_power() self.calculate_mux_power() self.PE_write_power = 0 self.PE_xbar_write_power = 0 self.PE_ADC_write_power = 0 self.PE_DAC_write_power = 0 self.PE_adder_write_power = 0 self.PE_shiftreg_write_power = 0 self.input_demux_write_power = 0 self.output_mux_write_power = 0 self.PE_digital_write_power = 0 if self.num_occupied_group != 0: for i in range(self.group_num): if self.PE_xbar_enable[i][0] == 1: if self.PE_multiplex_xbar_num[1] == 1: self.PE_xbar_list[i][0].calculate_xbar_write_power() self.PE_xbar_write_power += self.PE_xbar_list[i][0].xbar_write_power else: self.PE_xbar_list[i][0].calculate_xbar_write_power() self.PE_xbar_write_power += self.PE_xbar_list[i][0].xbar_write_power self.PE_xbar_list[i][1].calculate_xbar_write_power() self.PE_xbar_write_power += self.PE_xbar_list[i][1].xbar_write_power self.PE_DAC_write_power += math.ceil(self.PE_xbar_list[i][0].xbar_num_write_row/self.input_demux)*self.DAC_power self.PE_ADC_write_power += 0 # Assume ADCs are idle in write process self.input_demux_write_power += math.ceil(self.PE_xbar_list[i][0].xbar_num_write_row/self.input_demux)*self.input_demux_power self.PE_digital_write_power = self.input_demux_write_power + self.output_mux_read_power + self.PE_adder_read_power + self.PE_shiftreg_read_power self.PE_write_power = self.PE_xbar_write_power + self.PE_DAC_write_power + self.PE_ADC_write_power + self.PE_digital_write_power def calculate_PE_read_energy(self): # unit: nJ # Notice: before calculating energy, PE_read_config and calculate_PE_read_power must be executed self.PE_xbar_read_energy = self.PE_xbar_read_latency * self.PE_xbar_read_power self.PE_DAC_read_energy = self.PE_DAC_read_latency * self.PE_DAC_read_power self.PE_ADC_read_energy = self.PE_ADC_read_latency * self.PE_ADC_read_power self.PE_adder_read_energy = self.PE_adder_read_power * self.PE_adder_read_latency self.PE_shiftreg_read_energy = self.PE_shiftreg_read_power * self.PE_shiftreg_read_latency self.input_demux_read_energy = self.input_demux_read_power * self.input_demux_read_latency self.output_mux_read_energy = self.output_mux_read_power * self.output_mux_read_latency self.PE_digital_read_energy = self.PE_adder_read_energy + self.PE_shiftreg_read_energy + self.input_demux_read_energy + self.output_mux_read_energy self.PE_read_energy = self.PE_xbar_read_energy + self.PE_DAC_read_energy + \ self.PE_ADC_read_energy + self.PE_digital_read_energy def calculate_PE_write_energy(self): # unit: nJ # Notice: before calculating energy, PE_write_config and calculate_PE_write_power must be executed self.PE_xbar_write_energy = self.PE_xbar_write_latency * self.PE_xbar_write_power self.PE_DAC_write_energy = self.PE_DAC_write_latency * self.PE_DAC_write_power self.PE_ADC_write_energy = self.PE_ADC_write_latency * self.PE_ADC_write_power self.PE_adder_write_energy = self.PE_adder_write_power * self.PE_adder_write_latency self.PE_shiftreg_write_energy = self.PE_shiftreg_write_power * self.PE_shiftreg_write_latency self.input_demux_write_energy = self.input_demux_write_power * self.input_demux_write_latency self.output_mux_write_energy = self.output_mux_write_latency * self.output_mux_write_power self.PE_digital_write_energy = self.PE_adder_write_energy + self.PE_shiftreg_write_energy + self.input_demux_write_energy + self.output_mux_write_energy self.PE_write_energy = self.PE_xbar_write_energy + self.PE_DAC_write_energy + \ self.PE_ADC_write_energy + self.PE_digital_write_energy''' def PE_output(self): print("---------------------Crossbar Configurations-----------------------") crossbar.xbar_output(self) print("------------------------DAC Configurations-------------------------") DAC.DAC_output(self) print("------------------------ADC Configurations-------------------------") ADC.ADC_output(self) print("-------------------------PE Configurations-------------------------") print("total crossbar number in one PE:", self.PE_xbar_num) print(" the number of crossbars sharing a set of interfaces:",self.PE_multiplex_xbar_num) print("total utilization rate:", self.PE_utilization) print("total DAC number in one PE:", self.PE_DAC_num) print(" the number of DAC in one set of interfaces:", self.PE_group_DAC_num) print("total ADC number in one PE:", self.PE_ADC_num) print(" the number of ADC in one set of interfaces:", self.PE_group_ADC_num) print("---------------------PE Area Simulation Results--------------------") print("PE area:", self.PE_area, "um^2") print(" crossbar area:", self.PE_xbar_area, "um^2") print(" DAC area:", self.PE_DAC_area, "um^2") print(" ADC area:", self.PE_ADC_area, "um^2") print(" digital part area:", self.PE_digital_area, "um^2") print(" |---adder area:", self.PE_adder_area, "um^2") print(" |---shift-reg area:", self.PE_shiftreg_area, "um^2") print(" |---input_demux area:", self.PE_input_demux_area, "um^2") print(" |---output_mux area:", self.PE_output_mux_area, "um^2") print("--------------------PE Latency Simulation Results-----------------") print("PE read latency:", self.PE_read_latency, "ns") print(" crossbar read latency:", self.PE_xbar_read_latency, "ns") print(" DAC read latency:", self.PE_DAC_read_latency, "ns") print(" ADC read latency:", self.PE_ADC_read_latency, "ns") print(" digital part read latency:", self.PE_digital_read_latency, "ns") print("PE write latency:", self.PE_write_latency, "ns") print(" crossbar write latency:", self.PE_xbar_write_latency, "ns") print(" DAC write latency:", self.PE_DAC_write_latency, "ns") print(" ADC write latency:", self.PE_ADC_write_latency, "ns") print(" digital part write latency:", self.PE_digital_write_latency, "ns") print("--------------------PE Power Simulation Results-------------------") print("PE read power:", self.PE_read_power, "W") print(" crossbar read power:", self.PE_xbar_read_power, "W") print(" DAC read power:", self.PE_DAC_read_power, "W") print(" ADC read power:", self.PE_ADC_read_power, "W") print(" digital part read power:", self.PE_digital_read_power, "W") print(" |---adder power:", self.PE_adder_read_power, "W") print(" |---shift-reg power:", self.PE_shiftreg_read_power, "W") print(" |---input_demux power:", self.input_demux_read_power, "W") print(" |---output_mux power:", self.output_mux_read_power, "W") print("PE write power:", self.PE_write_power, "W") print(" crossbar write power:", self.PE_xbar_write_power, "W") print(" DAC write power:", self.PE_DAC_write_power, "W") print(" ADC write power:", self.PE_ADC_write_power, "W") print(" digital part write power:", self.PE_digital_write_power, "W") print("------------------PE Energy Simulation Results--------------------") print("PE read energy:", self.PE_read_energy, "nJ") print(" crossbar read energy:", self.PE_xbar_read_energy, "nJ") print(" DAC read energy:", self.PE_DAC_read_energy, "nJ") print(" ADC read energy:", self.PE_ADC_read_energy, "nJ") print(" digital part read energy:", self.PE_digital_read_energy, "nJ") print("PE write energy:", self.PE_write_energy, "nJ") print(" crossbar write energy:", self.PE_xbar_write_energy, "nJ") print(" DAC write energy:", self.PE_DAC_write_energy, "nJ") print(" ADC write energy:", self.PE_ADC_write_energy, "nJ") print(" digital part write energy:", self.PE_digital_write_energy, "nJ") print("-----------------------------------------------------------------") def PE_test(): print("load file:",test_SimConfig_path) _PE = ProcessElement(test_SimConfig_path) _PE.calculate_PE_area() _PE.calculate_PE_area() _PE.PE_read_config() _PE.calculate_PE_read_power() _PE.calculate_PE_read_latency() _PE.calculate_PE_read_energy() _PE.PE_output() if __name__ == '__main__': PE_test()<file_sep>/MNSIM/Area_Model/Model_Area.py #!/usr/bin/python # -*-coding:utf-8-*- import sys import os import configparser as cp work_path = os.path.dirname(os.getcwd()) sys.path.append(work_path) import numpy as np from MNSIM.Interface.interface import * from MNSIM.Mapping_Model.Tile_connection_graph import TCG import pandas as pd from MNSIM.Hardware_Model.Tile import tile from MNSIM.Hardware_Model.Buffer import buffer from MNSIM.Hardware_Model.Adder import adder import math class Model_area(): def __init__(self, NetStruct, SimConfig_path, multiple=None, TCG_mapping=None): self.NetStruct = NetStruct self.SimConfig_path = SimConfig_path # modelL_config = cp.ConfigParser() # modelL_config.read(self.SimConfig_path, encoding='UTF-8') # NoC_Compute = int(modelL_config.get('Algorithm Configuration', 'NoC_enable')) if multiple is None: multiple = [1] * len(self.NetStruct) if TCG_mapping is None: TCG_mapping = TCG(NetStruct,SimConfig_path,multiple) self.graph = TCG_mapping self.total_layer_num = self.graph.layer_num self.arch_area = self.total_layer_num * [0] self.arch_xbar_area = self.total_layer_num * [0] self.arch_ADC_area = self.total_layer_num * [0] self.arch_DAC_area = self.total_layer_num * [0] self.arch_digital_area = self.total_layer_num * [0] self.arch_adder_area = self.total_layer_num * [0] self.arch_shiftreg_area = self.total_layer_num * [0] self.arch_iReg_area = self.total_layer_num * [0] self.arch_oReg_area = self.total_layer_num * [0] self.arch_input_demux_area = self.total_layer_num * [0] self.arch_output_mux_area = self.total_layer_num * [0] self.arch_jointmodule_area = self.total_layer_num * [0] self.arch_buf_area = self.total_layer_num * [0] self.arch_pooling_area = self.total_layer_num * [0] self.arch_total_area = 0 self.arch_total_xbar_area = 0 self.arch_total_ADC_area = 0 self.arch_total_DAC_area = 0 self.arch_total_digital_area = 0 self.arch_total_adder_area = 0 self.arch_total_shiftreg_area = 0 self.arch_total_iReg_area = 0 self.arch_total_oReg_area = 0 self.arch_total_input_demux_area = 0 self.arch_total_jointmodule_area = 0 self.arch_total_buf_area = 0 self.arch_total_output_mux_area = 0 self.arch_total_pooling_area = 0 self.arch_xbar_utilization = self.total_layer_num * [0] self.arch_DAC_utilization = self.total_layer_num * [0] self.arch_ADC_utilization = self.total_layer_num * [0] self.arch_total_xbar_utilization = 0 self.arch_total_DAC_utilization = 0 self.arch_total_ADC_utilization = 0 # print(data.columns) # if NoC_Compute == 1: # path = os.getcwd() + '/Final_Results/' # data = pd.read_csv(path + 'area.csv') # self.arch_Noc_area = float(data.columns[0].split(' ')[-2]) # else: # self.arch_Noc_area = 0 self.calculate_model_area() def calculate_model_area(self): #Todo: Noc area self.graph.tile.calculate_tile_area(SimConfig_path=self.SimConfig_path, default_inbuf_size = self.graph.max_inbuf_size, default_outbuf_size = self.graph.max_outbuf_size) self.global_buf = buffer(SimConfig_path=self.SimConfig_path,buf_level=1,default_buf_size=self.graph.global_buf_size) self.global_buf.calculate_buf_area() self.global_add = adder(SimConfig_path=self.SimConfig_path,bitwidth=self.graph.global_adder_bitwidth) self.global_add.calculate_adder_area() self.tile = tile(SimConfig_path=self.SimConfig_path) self.tile_xbar_num = self.tile.tile_PE_total_num*self.tile.group_num*self.tile.xbar_column*self.tile.xbar_row self.tile_DAC_num = self.tile.tile_PE_total_num*self.tile.group_num*self.tile.xbar_row self.tile_ADC_num = self.tile.tile_PE_total_num*self.tile.group_num*self.tile.xbar_column total_tile_num = 0 used_total_xbar_num = 0 used_total_DAC_num = 0 used_total_ADC_num = 0 # not the real DAC/ADC num, but it reflects the DAC/ADC num for i in range(self.total_layer_num): layer_dict = self.NetStruct[i][0][0] tile_num = self.graph.layer_tileinfo[i]['tilenum'] self.arch_area[i] = self.graph.tile.tile_area * tile_num self.arch_xbar_area[i] = self.graph.tile.tile_xbar_area * tile_num self.arch_ADC_area[i] = self.graph.tile.tile_ADC_area * tile_num self.arch_DAC_area[i] = self.graph.tile.tile_DAC_area * tile_num self.arch_digital_area[i] = self.graph.tile.tile_digital_area * tile_num self.arch_adder_area[i] = self.graph.tile.tile_adder_area * tile_num self.arch_shiftreg_area[i] = self.graph.tile.tile_shiftreg_area * tile_num self.arch_iReg_area[i] = self.graph.tile.tile_iReg_area * tile_num self.arch_oReg_area[i] = self.graph.tile.tile_oReg_area * tile_num self.arch_input_demux_area[i] = self.graph.tile.tile_input_demux_area * tile_num self.arch_output_mux_area[i] = self.graph.tile.tile_output_mux_area * tile_num self.arch_jointmodule_area[i] = self.graph.tile.tile_jointmodule_area * tile_num self.arch_buf_area[i] = self.graph.tile.tile_buffer_area * tile_num self.arch_pooling_area[i] = self.graph.tile.tile_pooling_area * tile_num if self.graph.layer_tileinfo[i]['type'] == 'conv': # only consider the utilization rate of conv layer and fc layer total_tile_num += tile_num used_xbar_num = self.graph.layer_tileinfo[i]['x_width']*self.graph.layer_tileinfo[i]['y_height'] used_DAC_num = self.graph.layer_tileinfo[i]['y_height']*self.graph.layer_tileinfo[i]['weight_precision']*math.ceil(int(layer_dict['Outputchannel']) / self.tile.xbar_column) used_ADC_num = self.graph.layer_tileinfo[i]['x_width']*self.graph.layer_tileinfo[i]['my'] self.arch_xbar_utilization[i] = used_xbar_num/(tile_num*self.tile_xbar_num) self.arch_DAC_utilization[i] = used_DAC_num/(tile_num*self.tile_DAC_num) self.arch_ADC_utilization[i] = used_ADC_num/(tile_num*self.tile_ADC_num) used_total_xbar_num += used_xbar_num used_total_DAC_num += used_DAC_num used_total_ADC_num += used_ADC_num if self.graph.layer_tileinfo[i]['type'] == 'fc': # only consider the utilization rate of conv layer and fc layer total_tile_num += tile_num used_xbar_num = self.graph.layer_tileinfo[i]['x_width']*self.graph.layer_tileinfo[i]['y_height'] used_DAC_num = self.graph.layer_tileinfo[i]['y_height']*self.graph.layer_tileinfo[i]['weight_precision']*math.ceil(int(layer_dict['Outfeature']) / self.tile.xbar_column) used_ADC_num = self.graph.layer_tileinfo[i]['x_width']*self.graph.layer_tileinfo[i]['my'] self.arch_xbar_utilization[i] = used_xbar_num/(tile_num*self.tile_xbar_num) self.arch_DAC_utilization[i] = used_DAC_num/(tile_num*self.tile_DAC_num) self.arch_ADC_utilization[i] = used_ADC_num/(tile_num*self.tile_ADC_num) used_total_xbar_num += used_xbar_num used_total_DAC_num += used_DAC_num used_total_ADC_num += used_ADC_num self.arch_total_area = sum(self.arch_area) self.arch_total_xbar_area = sum(self.arch_xbar_area) self.arch_total_ADC_area = sum(self.arch_ADC_area) self.arch_total_DAC_area = sum(self.arch_DAC_area) self.arch_total_digital_area = sum(self.arch_digital_area)+self.global_add.adder_area*self.graph.global_adder_num self.arch_total_adder_area = sum(self.arch_adder_area)+self.global_add.adder_area*self.graph.global_adder_num self.arch_total_shiftreg_area = sum(self.arch_shiftreg_area) self.arch_total_iReg_area = sum(self.arch_iReg_area) self.arch_total_oReg_area = sum(self.arch_oReg_area) self.arch_total_input_demux_area = sum(self.arch_input_demux_area) self.arch_total_output_mux_area = sum(self.arch_output_mux_area) self.arch_total_jointmodule_area = sum(self.arch_jointmodule_area) self.arch_total_buf_area = sum(self.arch_buf_area)+self.global_buf.buf_area self.arch_total_pooling_area = sum(self.arch_pooling_area) self.arch_total_xbar_utilization = used_total_xbar_num/(total_tile_num*self.tile_xbar_num) self.arch_total_DAC_utilization = used_total_DAC_num/(total_tile_num*self.tile_DAC_num) self.arch_total_ADC_utilization = used_total_ADC_num/(total_tile_num*self.tile_ADC_num) def model_area_output(self, module_information = 1, layer_information = 1): print("Hardware area:", self.arch_total_area, "um^2") if module_information: print(" crossbar area:", self.arch_total_xbar_area, "um^2") print(" DAC area:", self.arch_total_DAC_area, "um^2") print(" ADC area:", self.arch_total_ADC_area, "um^2") print(" Buffer area:", self.arch_total_buf_area, "um^2") print(" Pooling area:", self.arch_total_pooling_area, "um^2") print(" Other digital part area:", self.arch_total_digital_area, "um^2") print(" |---adder area:", self.arch_total_adder_area, "um^2") print(" |---output-shift-reg area:", self.arch_total_shiftreg_area, "um^2") print(" |---input-reg area:", self.arch_total_iReg_area, "um^2") print(" |---output-reg area:", self.arch_total_oReg_area, "um^2") print(" |---input_demux area:", self.arch_total_input_demux_area, "um^2") print(" |---output_mux area:", self.arch_total_output_mux_area, "um^2") print(" |---joint_module area:", self.arch_total_jointmodule_area, "um^2") print(" crossbar utilization rate: ", self.arch_total_xbar_utilization*100, "%",sep='') print(" DAC utilization rate: ", self.arch_total_DAC_utilization*100, "%",sep='') print(" ADC utilization rate: ", self.arch_total_ADC_utilization*100, "%",sep='') # print(" NoC part area:", self.arch_Noc_area, "um^2") if layer_information: for i in range(self.total_layer_num): print("Layer", i, ":") layer_dict = self.NetStruct[i][0][0] if layer_dict['type'] == 'element_sum': print(" Hardware area (global accumulator):", self.global_add.adder_area*self.graph.global_adder_num+self.global_buf.buf_area, "um^2") else: print(" Hardware area:", self.arch_area[i], "um^2") if layer_dict['type'] == 'conv' or layer_dict['type'] == 'fc': print(" crossbar utilization rate: ", self.arch_xbar_utilization[i]*100, "%",sep='') print(" DAC utilization rate: ", self.arch_DAC_utilization[i]*100, "%",sep='') print(" ADC utilization rate: ", self.arch_ADC_utilization[i]*100, "%",sep='') if __name__ == '__main__': test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "SimConfig.ini") test_weights_file_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "vgg8_params.pth") __TestInterface = TrainTestInterface('vgg8_128_9', 'MNSIM.Interface.cifar10', test_SimConfig_path, test_weights_file_path) structure_file = __TestInterface.get_structure() __TCG_mapping = TCG(structure_file, test_SimConfig_path) __area = Model_area(NetStruct=structure_file,SimConfig_path=test_SimConfig_path,TCG_mapping=__TCG_mapping) __area.model_area_output(1,1)<file_sep>/MNSIM/Interface/quantize.py #-*-coding:utf-8-*- import collections import copy import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Function # last_activation_scale, last_weight_scale for activation and weight scale in last calculation # last_activation_bit, last_weight_bit for activation and weight bit last time last_activation_scale = None last_weight_scale = None last_activation_bit = None last_weight_bit = None # quantize Function class QuantizeFunction(Function): @staticmethod def forward(ctx, input, qbit, mode, last_value = None, training = None): global last_weight_scale global last_activation_scale global last_weight_bit global last_activation_bit # last_value change only when training if mode == 'weight': last_weight_bit = qbit scale = torch.max(torch.abs(input)).item() elif mode == 'activation': last_activation_bit = qbit if training: ratio = 0.707 tmp = last_value.item() if tmp <= 0: tmp = 3 * torch.std(input).item() + torch.abs(torch.mean(input)).item() else: # tmp = ratio * tmp + (1 - ratio) * torch.max(torch.abs(input)).item() tmp = ratio * tmp + (1 - ratio) * \ (3 * torch.std(input).item() + torch.abs(torch.mean(input)).item()) last_value.data[0] = tmp scale = last_value.data[0] else: assert 0, f'not support {mode}' # transfer thres = 2 ** (qbit - 1) - 1 output = input / scale output = torch.clamp(torch.round(output * thres), 0 - thres, thres - 0) output = output * scale / thres if mode == 'weight': last_weight_scale = scale / thres elif mode == 'activation': last_activation_scale = scale / thres else: assert 0, f'not support {mode}' return output @staticmethod def backward(ctx, grad_output): return grad_output, None, None, None, None Quantize = QuantizeFunction.apply # AB = 1 # N = 512 # Q = 10 # # METHOD = 'TRADITION' # # METHOD = 'FIX_TRAIN' # # METHOD = 'SINGLE_FIX_TEST' # METHOD = '' # quantize layer, include conv and fc without bias class QuantizeLayer(nn.Module): def __init__(self, hardware_config, layer_config, quantize_config): super(QuantizeLayer, self).__init__() # load hardware layer and quantize config in setting self.hardware_config = copy.deepcopy(hardware_config) self.layer_config = copy.deepcopy(layer_config) self.quantize_config = copy.deepcopy(quantize_config) # split weights if self.layer_config['type'] == 'conv': assert 'in_channels' in self.layer_config.keys() channel_N = (self.hardware_config['xbar_size'] // (self.layer_config['kernel_size'] ** 2)) complete_bar_num = self.layer_config['in_channels'] // channel_N residual_col_num = self.layer_config['in_channels'] % channel_N in_channels_list = [] if residual_col_num > 0: in_channels_list = [channel_N] * complete_bar_num + [residual_col_num] else: in_channels_list = [channel_N] * complete_bar_num # generate Module List assert 'out_channels' in self.layer_config.keys() assert 'kernel_size' in self.layer_config.keys() if 'stride' not in self.layer_config.keys(): self.layer_config['stride'] = 1 if 'padding' not in self.layer_config.keys(): self.layer_config['padding'] = 0 self.layer_list = nn.ModuleList([nn.Conv2d( i, self.layer_config['out_channels'], self.layer_config['kernel_size'], stride = self.layer_config['stride'], padding = self.layer_config['padding'], dilation = 1, groups = 1, bias = False ) for i in in_channels_list]) self.split_input = channel_N elif self.layer_config['type'] == 'fc': assert 'in_features' in self.layer_config.keys() complete_bar_num = self.layer_config['in_features'] // self.hardware_config['xbar_size'] residual_col_num = self.layer_config['in_features'] % self.hardware_config['xbar_size'] if residual_col_num > 0: in_features_list = [self.hardware_config['xbar_size']] * complete_bar_num + [residual_col_num] else: in_features_list = [self.hardware_config['xbar_size']] * complete_bar_num # generate Module List assert 'out_features' in self.layer_config.keys() self.layer_list = nn.ModuleList([nn.Linear(i, self.layer_config['out_features'], False) for i in in_features_list]) self.split_input = self.hardware_config['xbar_size'] else: assert 0, f'not support {self.layer_config["type"]}' # self.last_value = nn.Parameter(torch.ones(1)) self.register_buffer('last_value', (-1) * torch.ones(1)) # self.last_value[0] = 1 # self.bit_scale_list = nn.Parameter(torch.FloatTensor([[9,1],[9,1],[9,1]])) self.register_buffer('bit_scale_list', torch.FloatTensor([ [quantize_config['activation_bit'], -1], [quantize_config['weight_bit'], -1], [quantize_config['activation_bit'], -1] ])) # self.bit_scale_list[0, 0] = 9 # self.bit_scale_list[0, 1] = 1 # self.bit_scale_list[1, 0] = 9 # self.bit_scale_list[1, 1] = 1 # self.bit_scale_list[2, 0] = 9 # self.bit_scale_list[2, 1] = 1 # layer information self.layer_info = None def structure_forward(self, input): # TRADITION input_shape = input.shape input_list = torch.split(input, self.split_input, dim = 1) output = None for i in range(len(self.layer_list)): if i == 0: output = self.layer_list[i](input_list[i]) else: output.add_(self.layer_list[i](input_list[i])) output_shape = output.shape # layer_info self.layer_info = collections.OrderedDict() if self.layer_config['type'] == 'conv': self.layer_info['type'] = 'conv' self.layer_info['Inputchannel'] = int(input_shape[1]) self.layer_info['Inputsize'] = list(input_shape[2:]) self.layer_info['Kernelsize'] = self.layer_config['kernel_size'] self.layer_info['Stride'] = self.layer_config['stride'] self.layer_info['Padding'] = self.layer_config['padding'] self.layer_info['Outputchannel'] = int(output_shape[1]) self.layer_info['Outputsize'] = list(output_shape[2:]) elif self.layer_config['type'] == 'fc': self.layer_info['type'] = 'fc' self.layer_info['Infeature'] = int(input_shape[1]) self.layer_info['Outfeature'] = int(output_shape[1]) else: assert 0, f'not support {self.layer_config["type"]}' self.layer_info['Inputbit'] = int(self.bit_scale_list[0,0].item()) self.layer_info['Weightbit'] = int(self.quantize_config['weight_bit']) self.layer_info['outputbit'] = int(self.quantize_config['activation_bit']) self.layer_info['row_split_num'] = len(self.layer_list) self.layer_info['weight_cycle'] = math.ceil((self.quantize_config['weight_bit'] - 1) / (self.hardware_config['weight_bit'])) if 'input_index' in self.layer_config: self.layer_info['Inputindex'] = self.layer_config['input_index'] else: self.layer_info['Inputindex'] = [-1] self.layer_info['Outputindex'] = [1] return output def forward(self, input, method = 'SINGLE_FIX_TEST', adc_action = 'SCALE'): METHOD = method # float method if METHOD == 'TRADITION': input_list = torch.split(input, self.split_input, dim = 1) output = None for i in range(len(self.layer_list)): if i == 0: output = self.layer_list[i](input_list[i]) else: output.add_(self.layer_list[i](input_list[i])) return output # fix training if METHOD == 'FIX_TRAIN': weight = torch.cat([l.weight for l in self.layer_list], dim = 1) # quantize weight global last_weight_scale global last_activation_scale global last_weight_bit global last_activation_bit # last activation bit and scale self.bit_scale_list.data[0, 0] = last_activation_bit self.bit_scale_list.data[0, 1] = last_activation_scale weight = Quantize(weight, self.quantize_config['weight_bit'], 'weight', None, None) # weight bit and scale self.bit_scale_list.data[1, 0] = last_weight_bit self.bit_scale_list.data[1, 1] = last_weight_scale if self.layer_config['type'] == 'conv': output = F.conv2d( input, weight, None, \ self.layer_config['stride'], self.layer_config['padding'], 1, 1 ) elif self.layer_config['type'] == 'fc': output = F.linear(input, weight, None) else: assert 0, f'not support {self.layer_config["type"]}' output = Quantize(output, self.quantize_config['activation_bit'], 'activation', self.last_value, self.training) # output activation bit and scale self.bit_scale_list.data[2, 0] = last_activation_bit self.bit_scale_list.data[2, 1] = last_activation_scale return output if METHOD == 'SINGLE_FIX_TEST': assert self.training == False bit_weights = self.get_bit_weights() output = self.set_weights_forward(input, bit_weights, adc_action) return output assert 0, f'not support {METHOD}' def get_bit_weights(self): # weight_bit = int(self.bit_scale_list[1, 0].item()) weight_bit = self.quantize_config['weight_bit'] weight_scale = self.bit_scale_list[1, 1].item() assert weight_bit != 0 and weight_scale != 0, f'weight bit and scale should be given by the params' bit_weights = collections.OrderedDict() for layer_num, l in enumerate(self.layer_list): # assert (weight_bit - 1) % self.hardware_config['weight_bit'] == 0, generate weight cycle weight_cycle = math.ceil((weight_bit - 1) / self.hardware_config['weight_bit']) # transfer part weight thres = 2 ** (weight_bit - 1) - 1 weight_digit = torch.clamp(torch.round(l.weight / weight_scale), 0 - thres, thres - 0) # split weight into bit sign_weight = torch.sign(weight_digit) weight_digit = torch.abs(weight_digit) base = 1 step = 2 ** self.hardware_config['weight_bit'] for j in range(weight_cycle): tmp = torch.fmod(weight_digit, base * step) - torch.fmod(weight_digit, base) tmp = torch.mul(sign_weight, tmp) tmp = copy.deepcopy((tmp / base).detach().cpu().numpy()) bit_weights[f'split{layer_num}_weight{j}_positive'] = np.where(tmp > 0, tmp, 0) bit_weights[f'split{layer_num}_weight{j}_negative'] = np.where(tmp < 0, -tmp, 0) base = base * step return bit_weights def set_weights_forward(self, input, bit_weights, adc_action): assert self.training == False output = None input_list = torch.split(input, self.split_input, dim = 1) scale = self.last_value.item() # weight_bit = int(self.bit_scale_list[1, 0].item()) weight_bit = self.quantize_config['weight_bit'] weight_scale = self.bit_scale_list[1, 1].item() for layer_num, l in enumerate(self.layer_list): # assert (weight_bit - 1) % self.hardware_config['weight_bit'] == 0, generate weight cycle weight_cycle = math.ceil((weight_bit - 1) / self.hardware_config['weight_bit']) weight_container = [] base = 1 step = 2 ** self.hardware_config['weight_bit'] for j in range(weight_cycle): tmp = bit_weights[f'split{layer_num}_weight{j}_positive'] - bit_weights[f'split{layer_num}_weight{j}_negative'] tmp = torch.from_numpy(tmp) weight_container.append(tmp.to(device = input.device, dtype = input.dtype)) base = base * step activation_in_bit = int(self.bit_scale_list[0, 0].item()) activation_in_scale = self.bit_scale_list[0, 1].item() thres = 2 ** (activation_in_bit - 1) - 1 activation_in_digit = torch.clamp(torch.round(input_list[layer_num] / activation_in_scale), 0 - thres, thres - 0) # assert (activation_in_bit - 1) % self.hardware_config['input_bit'] == 0, generate activation_in cycle activation_in_cycle = math.ceil((activation_in_bit - 1) / self.hardware_config['input_bit']) # split activation into bit sign_activation_in = torch.sign(activation_in_digit) activation_in_digit = torch.abs(activation_in_digit) base = 1 step = 2 ** self.hardware_config['input_bit'] activation_in_container = [] for i in range(activation_in_cycle): tmp = torch.fmod(activation_in_digit, base * step) - torch.fmod(activation_in_digit, base) activation_in_container.append(torch.mul(sign_activation_in, tmp) / base) base = base * step # calculation and add point_shift = math.floor(self.quantize_config['point_shift'] + 0.5 * math.log2(len(self.layer_list))) Q = self.hardware_config['quantize_bit'] for i in range(activation_in_cycle): for j in range(weight_cycle): tmp = None if self.layer_config['type'] == 'conv': tmp = F.conv2d( activation_in_container[i], weight_container[j], None, \ self.layer_config['stride'], self.layer_config['padding'], 1, 1 ) elif self.layer_config['type'] == 'fc': tmp = F.linear(activation_in_container[i], weight_container[j], None) else: assert 0, f'not support {self.layer_config["type"]}' if adc_action == 'SCALE': tmp = tmp * weight_scale * activation_in_scale tmp = tmp / scale * (2 ** ((activation_in_cycle - 1) * self.hardware_config['input_bit'] + \ (weight_cycle - 1) * self.hardware_config['weight_bit'])) transfer_point = point_shift + (Q - 1) tmp = tmp * (2 ** transfer_point) tmp = torch.clamp(torch.round(tmp), 1 - 2 ** (Q - 1), 2 ** (Q - 1) - 1) tmp = tmp / (2 ** transfer_point) elif adc_action == 'FIX': # fix scale range fix_scale_range = (2 ** self.hardware_config['input_bit'] - 1) * \ (2 ** self.hardware_config['weight_bit'] - 1) * \ self.hardware_config['xbar_size'] tmp = tmp / fix_scale_range * (2 ** (Q - 1)) tmp = torch.clamp(torch.round(tmp), 1 - 2 ** (Q - 1), 2 ** (Q - 1) - 1) tmp = tmp * fix_scale_range / (2 ** (Q - 1)) tmp = tmp * weight_scale * activation_in_scale tmp = tmp / scale * (2 ** ((activation_in_cycle - 1) * self.hardware_config['input_bit'] + \ (weight_cycle - 1) * self.hardware_config['weight_bit'])) else: assert 0, f'can not support {adc_action}' # scale scale_point = (activation_in_cycle - 1 - i) * self.hardware_config['input_bit'] + \ (weight_cycle - 1 - j) * self.hardware_config['weight_bit'] tmp = tmp / (2 ** scale_point) # add if torch.is_tensor(output): output = output + tmp else: output = tmp # quantize output activation_out_bit = int(self.bit_scale_list[0, 0].item()) activation_out_scale = self.bit_scale_list[0, 1].item() thres = 2 ** (activation_out_bit - 1) - 1 output = torch.clamp(torch.round(output * thres), 0 - thres, thres - 0) output = output * scale / thres return output def extra_repr(self): return str(self.hardware_config) + ' ' + str(self.layer_config) + ' ' + str(self.quantize_config) QuantizeLayerStr = ['conv', 'fc'] class ViewLayer(nn.Module): def __init__(self): super(ViewLayer, self).__init__() def forward(self, x): return x.view(x.size(0), -1) class EleSumLayer(nn.Module): def __init__(self): super(EleSumLayer, self).__init__() def forward(self, x): return x[0] + x[1] class StraightLayer(nn.Module): def __init__(self, hardware_config, layer_config, quantize_config): super(StraightLayer, self).__init__() # load hardware layer and quantize config in setting self.hardware_config = copy.deepcopy(hardware_config) self.layer_config = copy.deepcopy(layer_config) self.quantize_config = copy.deepcopy(quantize_config) # generate layer if self.layer_config['type'] == 'pooling': assert 'kernel_size' in self.layer_config.keys() assert 'stride' in self.layer_config.keys() if 'padding' not in self.layer_config.keys(): self.layer_config['padding'] = 0 if self.layer_config['mode'] == 'AVE': self.layer = nn.AvgPool2d( kernel_size = self.layer_config['kernel_size'], \ stride = self.layer_config['stride'], \ padding = self.layer_config['padding'] ) elif self.layer_config['mode'] == 'MAX': self.layer = nn.MaxPool2d( kernel_size = self.layer_config['kernel_size'], \ stride = self.layer_config['stride'], \ padding = self.layer_config['padding'] ) else: assert 0, f'not support {self.layer_config["mode"]}' elif self.layer_config['type'] == 'relu': self.layer = nn.ReLU() elif self.layer_config['type'] == 'view': self.layer = ViewLayer() elif self.layer_config['type'] == 'bn': self.layer = nn.BatchNorm2d(self.layer_config['features']) elif self.layer_config['type'] == 'dropout': self.layer = nn.Dropout() elif self.layer_config['type'] == 'element_sum': self.layer = EleSumLayer() else: assert 0, f'not support {self.layer_config["type"]}' # self.last_value = nn.Parameter(torch.ones(1)) self.register_buffer('last_value', torch.ones(1)) # self.last_value[0] = 1 self.layer_info = None def structure_forward(self, input): if self.layer_config['type'] != 'element_sum': # generate input shape and output shape self.input_shape = input.shape output = self.layer.forward(input) self.output_shape = output.shape # generate layer_info self.layer_info = collections.OrderedDict() if self.layer_config['type'] == 'pooling': self.layer_info['type'] = 'pooling' self.layer_info['Inputchannel'] = int(self.input_shape[1]) self.layer_info['Inputsize'] = list(self.input_shape)[2:] self.layer_info['Kernelsize'] = self.layer_config['kernel_size'] self.layer_info['Stride'] = self.layer_config['stride'] self.layer_info['Padding'] = self.layer_config['padding'] self.layer_info['Outputchannel'] = int(self.output_shape[1]) self.layer_info['Outputsize'] = list(self.output_shape)[2:] elif self.layer_config['type'] == 'relu': self.layer_info['type'] = 'relu' elif self.layer_config['type'] == 'view': self.layer_info['type'] = 'view' elif self.layer_config['type'] == 'bn': self.layer_info['type'] = 'bn' self.layer_info['features'] = self.layer_config['features'] elif self.layer_config['type'] == 'dropout': self.layer_info['type'] = 'dropout' else: assert 0, f'not support {self.layer_config["type"]}' else: self.input_shape = (input[0].shape, input[1].shape) output = self.layer.forward(input) self.output_shape = output.shape self.layer_info = collections.OrderedDict() self.layer_info['type'] = 'element_sum' self.layer_info['Inputbit'] = self.quantize_config['activation_bit'] self.layer_info['Weightbit'] = self.quantize_config['weight_bit'] self.layer_info['outputbit'] = self.quantize_config['activation_bit'] if 'input_index' in self.layer_config: self.layer_info['Inputindex'] = self.layer_config['input_index'] else: self.layer_info['Inputindex'] = [-1] self.layer_info['Outputindex'] = [1] return output def forward(self, input, method = 'SINGLE_FIX_TEST', adc_action = 'SCALE'): # DOES NOT use method and adc_action, for unifying with QuantizeLayer METHOD = method # float method if METHOD == 'TRADITION': output = self.layer(input) return output # fix training and single fix test if METHOD == 'FIX_TRAIN' or METHOD == 'SINGLE_FIX_TEST': output = self.layer(input) if self.layer_config['type'] in ["bn", "element_sum"]: output = Quantize(output, self.quantize_config['activation_bit'], 'activation', self.last_value, self.training) return output assert 0, f'not support {METHOD}' def get_bit_weights(self): return None def extra_repr(self): return str(self.hardware_config) + ' ' + str(self.layer_config) + ' ' + str(self.quantize_config) StraightLayerStr = ['pooling', 'relu', 'view', 'bn', 'dropout', 'element_sum'] <file_sep>/README.md # MNSIM_Python **Citation Information**: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, MNSIM 2.0: A Behavior-Level Modeling Tool for Memristor-based Neuromorphic Computing Systems, in Great Lakes Symposium on VLSI (GLSVLSI), 2020. <NAME><sup>1*</sup>, <NAME><sup>1</sup>, <NAME><sup>1</sup>, <NAME><sup>2</sup>, <NAME><sup>6</sup>, <NAME><sup>2</sup>, <NAME><sup>3</sup>, <NAME><sup>4</sup>, <NAME><sup>2, 5</sup>, <NAME><sup>6</sup>, <NAME><sup>3</sup>, <NAME><sup>1*</sup>, and <NAME><sup>1</sup> <sup>1</sup>Tsinghua University, <sup>2</sup>Alibaba Group, <sup>3</sup>University of Notre Dame, <sup>4</sup>Institute of Computing Technology, Chinese Academy of Sciences, <sup>5</sup>University of California, Santa Barbara, <sup>6</sup>Arizona State University <sup>*</sup><EMAIL>, <EMAIL> MNSIM_Python version 1.0 is still a beta version. If you have any questions and suggestions about MNSIM_Python please contact us via e-mail. We hope that MNSIM_Python can be helpful to your research work, and sincerely invite every PIM researcher to add your ideas to MNSIM_Python to enlarge its function. For more information about MNSIM_Python, please refer to the MNSIM_manual.pdf <file_sep>/MNSIM/Interface/interface.py #-*-coding:utf-8-*- import collections import configparser import copy import math import os import copy from importlib import import_module import numpy as np import torch class TrainTestInterface(object): def __init__(self, network_module, dataset_module, SimConfig_path, weights_file = None, device = None, extra_define = None): # network_module = 'lenet' # dataset_module = 'cifar10' # weights_file = './zoo/cifar10_lenet_train_params.pth' # load net, dataset, and weights self.network_module = network_module self.dataset_module = dataset_module self.weights_file = weights_file self.test_loader = None # load simconfig ## xbar_size, input_bit, weight_bit, quantize_bit xbar_config = configparser.ConfigParser() xbar_config.read(SimConfig_path, encoding = 'UTF-8') self.hardware_config = collections.OrderedDict() # xbar_size xbar_size = list(map(int, xbar_config.get('Crossbar level', 'Xbar_Size').split(','))) self.xbar_row = xbar_size[0] self.xbar_column = xbar_size[1] self.hardware_config['xbar_size'] = xbar_size[0] # xbar bit self.xbar_bit = int(xbar_config.get('Device level', 'Device_Level')) self.hardware_config['weight_bit'] = math.floor(math.log2(self.xbar_bit)) # input bit and ADC bit ADC_choice = int(xbar_config.get('Interface level', 'ADC_Choice')) DAC_choice = int(xbar_config.get('Interface level', 'DAC_Choice')) temp_DAC_bit = int(xbar_config.get('Interface level', 'DAC_Precision')) temp_ADC_bit = int(xbar_config.get('Interface level', 'ADC_Precision')) ADC_precision_dict = { -1: temp_ADC_bit, 1: 10, # reference: A 10b 1.5GS/s Pipelined-SAR ADC with Background Second-Stage Common-Mode Regulation and Offset Calibration in 14nm CMOS FinFET 2: 8, # reference: ISAAC: A Convolutional Neural Network Accelerator with In-Situ Analog Arithmetic in Crossbars 3: 8, # reference: A >3GHz ERBW 1.1GS/s 8b Two-Step SAR ADC with Recursive-Weight DAC 4: 6, # reference: Area-Efficient 1GS/s 6b SAR ADC with Charge-Injection-Cell-Based DAC 5: 8, # ASPDAC1 6: 6, # ASPDAC2 7: 4 # ASPDAC3 } DAC_precision_dict = { -1: temp_DAC_bit, 1: 1, # 1-bit 2: 2, # 2-bit 3: 3, # 3-bit 4: 4, # 4-bit 5: 6, # 6-bit 6: 8 # 8-bit } self.input_bit = DAC_precision_dict[DAC_choice] self.quantize_bit = ADC_precision_dict[ADC_choice] self.hardware_config['input_bit'] = self.input_bit self.hardware_config['quantize_bit'] = self.quantize_bit # group num self.pe_group_num = int(xbar_config.get('Process element level', 'Group_Num')) self.tile_size = list(map(int, xbar_config.get('Tile level', 'PE_Num').split(','))) self.tile_row = self.tile_size[0] self.tile_column = self.tile_size[1] # net and weights if device != None: self.device = torch.device(f'cuda:{device}' if torch.cuda.is_available() else 'cpu') else: self.device = torch.device('cpu') print(f'run on device {self.device}') if dataset_module.endswith('cifar10'): num_classes = 10 elif dataset_module.endswith('cifar100'): num_classes = 100 else: assert 0, f'unknown dataset' if extra_define != None: self.hardware_config['input_bit'] = extra_define['dac_res'] self.hardware_config['quantize_bit'] = extra_define['adc_res'] self.hardware_config['xbar_size'] = extra_define['xbar_size'] self.net = import_module('MNSIM.Interface.network').get_net(self.hardware_config, cate = self.network_module, num_classes = num_classes) if weights_file is not None: print(f'load weights from {weights_file}') self.net.load_change_weights(torch.load(weights_file, map_location=self.device)) def origin_evaluate(self, method = 'SINGLE_FIX_TEST', adc_action = 'SCALE'): if self.test_loader == None: self.test_loader = import_module(self.dataset_module).get_dataloader()[1] self.net.to(self.device) self.net.eval() test_correct = 0 test_total = 0 with torch.no_grad(): for i, (images, labels) in enumerate(self.test_loader): if i > 10: break images = images.to(self.device) test_total += labels.size(0) outputs = self.net(images, method, adc_action) # predicted labels = labels.to(self.device) _, predicted = torch.max(outputs, 1) test_correct += (predicted == labels).sum().item() return test_correct / test_total def get_net_bits(self): net_bit_weights = self.net.get_weights() return net_bit_weights def set_net_bits_evaluate(self, net_bit_weights, adc_action = 'SCALE'): if self.test_loader == None: self.test_loader = import_module(self.dataset_module).get_dataloader()[1] self.net.to(self.device) self.net.eval() test_correct = 0 test_total = 0 with torch.no_grad(): for i, (images, labels) in enumerate(self.test_loader): if i > 10: break images = images.to(self.device) test_total += labels.size(0) outputs = self.net.set_weights_forward(images, net_bit_weights, adc_action) # predicted labels = labels.to(self.device) _, predicted = torch.max(outputs, 1) test_correct += (predicted == labels).sum().item() return test_correct / test_total def get_structure(self): net_bit_weights = self.net.get_weights() net_structure_info = self.net.get_structure() # print(net_structure_info) assert len(net_bit_weights) == len(net_structure_info) # set relative index to absolute index absolute_index = [None] * len(net_structure_info) absolute_count = 0 for i in range(len(net_structure_info)): if not (len(net_structure_info[i]['Outputindex']) == 1 and net_structure_info[i]['Outputindex'][0] == 1): raise Exception('duplicate output') if net_structure_info[i]['type'] in ['conv', 'pooling', 'element_sum', 'fc']: absolute_index[i] = absolute_count absolute_count = absolute_count + 1 else: if not len(net_structure_info[i]['Inputindex']) == 1: raise Exception('duplicate input index') absolute_index[i] = absolute_index[i + net_structure_info[i]['Inputindex'][0]] graph = list() for i in range(len(net_structure_info)): if net_structure_info[i]['type'] in ['conv', 'pooling', 'element_sum', 'fc']: # layer num, layer type layer_num = absolute_index[i] layer_type = net_structure_info[i]['type'] # layer input layer_input = list(map(lambda x: (absolute_index[i + x] if i + x != -1 else -1), net_structure_info[i]['Inputindex'])) # layer output layer_output = list() for tmp_i in range(len(net_structure_info)): if net_structure_info[tmp_i]['type'] in ['conv', 'pooling', 'element_sum', 'fc']: tmp_layer_num = absolute_index[tmp_i] tmp_layer_input = list(map(lambda x: (absolute_index[tmp_i + x] if tmp_i + x != -1 else -1), net_structure_info[tmp_i]['Inputindex'])) if layer_num in tmp_layer_input: layer_output.append(tmp_layer_num) graph.append((layer_num, layer_type, layer_input, layer_output)) # add to net array net_array = [] for layer_num, (layer_bit_weights, layer_structure_info) in enumerate(zip(net_bit_weights, net_structure_info)): # change layer structure info layer_structure_info = copy.deepcopy(layer_structure_info) layer_count = absolute_index[layer_num] layer_structure_info['Layerindex'] = graph[layer_count][0] layer_structure_info['Inputindex'] = list(map(lambda x: x - graph[layer_count][0], graph[layer_count][2])) layer_structure_info['Outputindex'] = list(map(lambda x: x - graph[layer_count][0], graph[layer_count][3])) # add for element_sum and pooling if layer_bit_weights == None: if layer_structure_info['type'] in ['element_sum', 'pooling']: net_array.append([(layer_structure_info, None)]) continue assert len(layer_bit_weights.keys()) == layer_structure_info['row_split_num'] * layer_structure_info['weight_cycle'] * 2 # split for i in range(layer_structure_info['row_split_num']): for j in range(layer_structure_info['weight_cycle']): layer_bit_weights[f'split{i}_weight{j}_positive'] = mysplit(layer_bit_weights[f'split{i}_weight{j}_positive'], self.xbar_column) layer_bit_weights[f'split{i}_weight{j}_negative'] = mysplit(layer_bit_weights[f'split{i}_weight{j}_negative'], self.xbar_column) # generate pe array xbar_array = [] for i in range(layer_structure_info['row_split_num']): L = len(layer_bit_weights[f'split{i}_weight{0}_positive']) for j in range(L): pe_array = [] for s in range(layer_structure_info['weight_cycle']): pe_array.append([layer_bit_weights[f'split{i}_weight{s}_positive'][j].astype(np.uint8), layer_bit_weights[f'split{i}_weight{s}_negative'][j].astype(np.uint8)]) xbar_array.append(pe_array) # store in xbar_array total_array = [] L = math.ceil(len(xbar_array) / (self.tile_row * self.tile_column)) for i in range(L): tile_array = [] for h in range(self.tile_row): for w in range(self.tile_column): serial_number = i * self.tile_row * self.tile_column + h * self.tile_column + w if serial_number < len(xbar_array): tile_array.append(xbar_array[serial_number]) total_array.append((layer_structure_info, tile_array)) net_array.append(total_array) # test index # graph = map(lambda x: x[0][0],net_array) # graph = list(map(lambda x: f'l: {x["Layerindex"]}, t: {x["type"]}, i: {x["Inputindex"]}, o: {x["Outputindex"]}', graph)) # graph = '\n'.join(graph) return net_array def mysplit(array, length): # reshape array = np.reshape(array, (array.shape[0], -1)) # split on output assert array.shape[0] > 0 tmp_index = [] for i in range(1, array.shape[0]): if i % length == 0: tmp_index.append(i) return np.split(array, tmp_index, axis = 0) if __name__ == '__main__': test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "SimConfig.ini") __TestInterface = TrainTestInterface('vgg8', 'MNSIM.Interface.cifar10', test_SimConfig_path, './MNSIM/Interface/zoo/cifar10_vgg8_params.pth', '7') print(__TestInterface.origin_evaluate(method='SINGLE_FIX_TEST')) print(__TestInterface.set_net_bits_evaluate(__TestInterface.get_net_bits())) structure_info = __TestInterface.get_structure() <file_sep>/MNSIM/Hardware_Model/ShiftReg.py #!/usr/bin/python #-*-coding:utf-8-*- import configparser as cp import os import math test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())),"SimConfig.ini") #Default SimConfig file path: MNSIM_Python/SimConfig.ini class shiftreg(object): def __init__(self, SimConfig_path, max_shiftbase = None): # frequency unit: MHz shiftreg_config = cp.ConfigParser() shiftreg_config.read(SimConfig_path, encoding='UTF-8') self.shiftreg_tech = int(shiftreg_config.get('Digital module', 'ShiftReg_Tech')) if self.shiftreg_tech <= 0: self.shiftreg_tech = 65 self.shiftreg_area = float(shiftreg_config.get('Digital module', 'ShiftReg_Area')) self.shiftreg_power = float(shiftreg_config.get('Digital module', 'ShiftReg_Power')) if max_shiftbase is None: self.max_shiftbase = 16 else: self.max_shiftbase = max_shiftbase assert self.max_shiftbase > 0 self.shiftreg_frequency =float(shiftreg_config.get('Digital module', 'Digital_Frequency')) if self.shiftreg_frequency is None: self.shiftreg_frequency = 100 assert self.shiftreg_frequency > 0 self.shiftreg_latency = 1.0/self.shiftreg_frequency self.calculate_shiftreg_power() self.shiftreg_energy = 0 # print("shiftreg configuration is loaded") def calculate_shiftreg_area(self): # unit: um^2 if self.shiftreg_area == 0: shiftreg_area_dict = { 4: 1.42,#228.96, 8: 1.42,#217.44, 16:1.42#230.40 } if self.max_shiftbase <= 4: self.shiftreg_area = shiftreg_area_dict[4]*pow((self.shiftreg_tech/65),2) elif self.max_shiftbase <= 8: self.shiftreg_area = shiftreg_area_dict[8]*pow((self.shiftreg_tech/65),2) else: self.shiftreg_area = shiftreg_area_dict[16]*pow((self.shiftreg_tech/65),2) def calculate_shiftreg_power(self): # unit: W if self.shiftreg_power == 0: shiftreg_power_dict = { 4: 8.1e-7,#2.13e-4, 8: 8.1e-7,#1.97e-4, 16: 8.1e-7#1.24e-4 } if self.max_shiftbase <= 4: self.shiftreg_power = shiftreg_power_dict[4]*pow((self.shiftreg_tech/65),2) elif self.max_shiftbase <= 8: self.shiftreg_power = shiftreg_power_dict[8]*pow((self.shiftreg_tech/65),2) else: self.shiftreg_power = shiftreg_power_dict[16]*pow((self.shiftreg_tech/65),2) def calculate_shiftreg_energy(self): assert self.shiftreg_power >= 0 assert self.shiftreg_latency >= 0 self.shiftreg_energy = self.shiftreg_latency * self.shiftreg_power def shiftreg_output(self): print("shiftreg_area:", self.shiftreg_area, "um^2") print("shiftreg_bitwidth:", self.max_shiftbase, "bit") print("shiftreg_power:", self.shiftreg_power, "W") print("shiftreg_latency:", self.shiftreg_latency, "ns") print("shiftreg_energy:", self.shiftreg_energy, "nJ") def shiftreg_test(): print("load file:",test_SimConfig_path) _shiftreg = shiftreg(test_SimConfig_path) _shiftreg.calculate_shiftreg_area() _shiftreg.calculate_shiftreg_power() _shiftreg.calculate_shiftreg_energy() _shiftreg.shiftreg_output() if __name__ == '__main__': shiftreg_test()<file_sep>/MNSIM/Power_Model/Model_inference_power.py #!/usr/bin/python # -*-coding:utf-8-*- import sys import os import configparser as cp work_path = os.path.dirname(os.getcwd()) sys.path.append(work_path) import numpy as np from MNSIM.Interface.interface import * from MNSIM.Mapping_Model.Tile_connection_graph import TCG from MNSIM.Hardware_Model.Tile import tile from MNSIM.Hardware_Model.Buffer import buffer from MNSIM.Hardware_Model.Adder import adder class Model_inference_power(): def __init__(self, NetStruct, SimConfig_path, multiple=None, TCG_mapping=None): self.NetStruct = NetStruct self.SimConfig_path = SimConfig_path if multiple is None: multiple = [1] * len(self.NetStruct) if TCG_mapping is None: TCG_mapping = TCG(NetStruct,SimConfig_path,multiple) self.graph = TCG_mapping self.total_layer_num = self.graph.layer_num self.arch_power = self.total_layer_num * [0] self.arch_xbar_power = self.total_layer_num * [0] self.arch_ADC_power = self.total_layer_num * [0] self.arch_DAC_power = self.total_layer_num * [0] self.arch_digital_power = self.total_layer_num * [0] self.arch_adder_power = self.total_layer_num * [0] self.arch_shiftreg_power = self.total_layer_num * [0] self.arch_iReg_power = self.total_layer_num * [0] self.arch_oReg_power = self.total_layer_num * [0] self.arch_input_demux_power = self.total_layer_num * [0] self.arch_output_mux_power = self.total_layer_num * [0] self.arch_jointmodule_power = self.total_layer_num * [0] self.arch_buf_power = self.total_layer_num * [0] self.arch_buf_r_power = self.total_layer_num * [0] self.arch_buf_w_power = self.total_layer_num * [0] self.arch_pooling_power = self.total_layer_num * [0] self.arch_total_power = 0 self.arch_total_xbar_power = 0 self.arch_total_ADC_power = 0 self.arch_total_DAC_power = 0 self.arch_total_digital_power = 0 self.arch_total_adder_power = 0 self.arch_total_shiftreg_power = 0 self.arch_total_iReg_power = 0 self.arch_total_oReg_power = 0 self.arch_total_input_demux_power = 0 self.arch_total_jointmodule_power = 0 self.arch_total_buf_power = 0 self.arch_total_buf_r_power = 0 self.arch_total_buf_w_power = 0 self.arch_total_output_mux_power = 0 self.arch_total_pooling_power = 0 self.calculate_model_power() def calculate_model_power(self): self.global_buf = buffer(SimConfig_path=self.SimConfig_path, buf_level=1, default_buf_size=self.graph.global_buf_size) self.global_buf.calculate_buf_read_power() self.global_buf.calculate_buf_write_power() self.global_add = adder(SimConfig_path=self.SimConfig_path, bitwidth=self.graph.global_adder_bitwidth) self.global_add.calculate_adder_power() for i in range(self.total_layer_num): tile_num = self.graph.layer_tileinfo[i]['tilenum'] max_column = self.graph.layer_tileinfo[i]['max_column'] max_row = self.graph.layer_tileinfo[i]['max_row'] max_PE = self.graph.layer_tileinfo[i]['max_PE'] max_group = self.graph.layer_tileinfo[i]['max_group'] layer_type = self.graph.net[i][0][0]['type'] self.graph.tile.calculate_tile_read_power_fast(max_column=max_column,max_row=max_row,max_PE=max_PE,max_group=max_group,layer_type=layer_type, SimConfig_path=self.SimConfig_path,default_inbuf_size=self.graph.max_inbuf_size, default_outbuf_size=self.graph.max_outbuf_size) self.arch_power[i] = self.graph.tile.tile_read_power * tile_num self.arch_xbar_power[i] = self.graph.tile.tile_xbar_read_power * tile_num self.arch_ADC_power[i] = self.graph.tile.tile_ADC_read_power * tile_num self.arch_DAC_power[i] = self.graph.tile.tile_DAC_read_power * tile_num self.arch_digital_power[i] = self.graph.tile.tile_digital_read_power * tile_num self.arch_adder_power[i] = self.graph.tile.tile_adder_read_power * tile_num self.arch_shiftreg_power[i] = self.graph.tile.tile_shiftreg_read_power * tile_num self.arch_iReg_power[i] = self.graph.tile.tile_iReg_read_power * tile_num self.arch_oReg_power[i] = self.graph.tile.tile_oReg_read_power * tile_num self.arch_input_demux_power[i] = self.graph.tile.tile_input_demux_read_power * tile_num self.arch_output_mux_power[i] = self.graph.tile.tile_output_mux_read_power * tile_num self.arch_jointmodule_power[i] = self.graph.tile.tile_jointmodule_read_power * tile_num self.arch_buf_power[i] = self.graph.tile.tile_buffer_read_power * tile_num self.arch_buf_r_power[i] = self.graph.tile.tile_buffer_r_read_power * tile_num self.arch_buf_w_power[i] = self.graph.tile.tile_buffer_w_read_power * tile_num self.arch_pooling_power[i] = self.graph.tile.tile_pooling_read_power * tile_num self.arch_total_power = sum(self.arch_power) self.arch_total_xbar_power = sum(self.arch_xbar_power) self.arch_total_ADC_power = sum(self.arch_ADC_power) self.arch_total_DAC_power = sum(self.arch_DAC_power) self.arch_total_digital_power = sum(self.arch_digital_power)+self.global_add.adder_power*self.graph.global_adder_num self.arch_total_adder_power = sum(self.arch_adder_power)+self.global_add.adder_power*self.graph.global_adder_num self.arch_total_shiftreg_power = sum(self.arch_shiftreg_power) self.arch_total_iReg_power = sum(self.arch_iReg_power) self.arch_total_oReg_power = sum(self.arch_oReg_power) self.arch_total_input_demux_power = sum(self.arch_input_demux_power) self.arch_total_output_mux_power = sum(self.arch_output_mux_power) self.arch_total_jointmodule_power = sum(self.arch_jointmodule_power) self.arch_total_buf_power = sum(self.arch_buf_power)+(self.global_buf.buf_wpower+self.global_buf.buf_rpower)*1e-3 self.arch_total_buf_r_power = sum(self.arch_buf_r_power)+self.global_buf.buf_rpower*1e-3 self.arch_total_buf_w_power = sum(self.arch_buf_w_power)+self.global_buf.buf_wpower*1e-3 self.arch_total_pooling_power = sum(self.arch_pooling_power) def model_power_output(self, module_information = 1, layer_information = 1): print("Hardware power:", self.arch_total_power, "W") if module_information: print(" crossbar power:", self.arch_total_xbar_power, "W") print(" DAC power:", self.arch_total_DAC_power, "W") print(" ADC power:", self.arch_total_ADC_power, "W") print(" Buffer power:", self.arch_total_buf_power, "W") print(" |---read buffer power:", self.arch_total_buf_r_power, "W") print(" |---write buffer power:", self.arch_total_buf_w_power, "W") print(" Pooling power:", self.arch_total_pooling_power, "W") print(" Other digital part power:", self.arch_total_digital_power, "W") print(" |---adder power:", self.arch_total_adder_power, "W") print(" |---output-shift-reg power:", self.arch_total_shiftreg_power, "W") print(" |---input-reg power:", self.arch_total_iReg_power, "W") print(" |---output-reg power:", self.arch_total_oReg_power, "W") print(" |---input_demux power:", self.arch_total_input_demux_power, "W") print(" |---output_mux power:", self.arch_total_output_mux_power, "W") print(" |---joint_module power:", self.arch_total_jointmodule_power, "W") if layer_information: for i in range(self.total_layer_num): print("Layer", i, ":") layer_dict = self.NetStruct[i][0][0] if layer_dict['type'] == 'element_sum': print(" Hardware power (global accumulator):", self.global_add.adder_power*self.graph.global_adder_num +self.global_buf.buf_wpower*1e-3+self.global_buf.buf_rpower*1e-3, "W") else: print(" Hardware power:", self.arch_power[i], "W") if __name__ == '__main__': test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "SimConfig.ini") test_weights_file_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "vgg8_params.pth") __TestInterface = TrainTestInterface('vgg8_128_9', 'MNSIM.Interface.cifar10', test_SimConfig_path, test_weights_file_path, 'cpu') structure_file = __TestInterface.get_structure() __TCG_mapping = TCG(structure_file, test_SimConfig_path) __power = Model_inference_power(NetStruct=structure_file,SimConfig_path=test_SimConfig_path,TCG_mapping=__TCG_mapping) __power.model_power_output(1,1)<file_sep>/MNSIM/Mapping_Model/Tile_connection_graph.py #!/usr/bin/python # -*-coding:utf-8-*- import torch import sys import os import math import configparser as cp work_path = os.path.dirname(os.getcwd()) sys.path.append(work_path) from MNSIM.Hardware_Model import * from MNSIM.Hardware_Model.Crossbar import crossbar from MNSIM.Hardware_Model.Tile import tile from MNSIM.Interface.interface import * import collections import pandas as pd class PE_node(): # Obsolete in the current version def __init__(self, PE_id=0, ltype='conv', lnum=0): # PE_id: the id of PE node, ltype: layer type of this PE, lnum: layer number of this PE self.id = PE_id self.type = ltype self.lnum = lnum self.inMerge_list = [] self.outMerge = 0 def set_inMerge(self, Merge_id): if Merge_id not in self.inMerge_list: self.inMerge_list.append(Merge_id) self.inMerge_list.sort() def set_outMerge(self, Merge_id): self.outMerge = Merge_id class Merge_node(): # Obsolete in the current version def __init__(self, Merge_id=0, mtype=0, lnum=0): # Merge_id: the id of Merge node, mtype: merge type (0: add, 1: concat, 2: pooling) self.id = Merge_id self.type = mtype self.lnum = lnum self.inPE_list = [] self.outPE_list = [] self.inMerge_list = [] self.outMerge_list = [] def set_inPE(self, PE_id): if PE_id not in self.inPE_list: self.inPE_list.append(PE_id) self.inPE_list.sort() def set_outPE(self, PE_id): if PE_id not in self.outPE_list: self.outPE_list.append(PE_id) self.outPE_list.sort() def set_inMerge(self, Merge_id): if Merge_id not in self.inMerge_list: self.inMerge_list.append(Merge_id) self.inMerge_list.sort() def set_outMerge(self, Merge_id): if Merge_id not in self.outMerge_list: self.outMerge_list.append(Merge_id) self.outMerge_list.sort() def generate_normal_matrix(row, column): matrix = np.zeros([row, column]) start = 0 for i in range(row): for j in range(column): matrix[i][j] = start start += 1 return matrix def generate_snake_matrix(row, column): matrix = np.zeros([row, column]) start = 0 for i in range(row): for j in range(column): if i % 2: matrix[i][column - j - 1] = start else: matrix[i][j] = start start += 1 return matrix def generate_hui_matrix(row, column): matrix = np.zeros([row, column]) state = 0 stride = 1 step = 0 start = 0 dl = 0 ru = 0 i = 0 j = 0 for x in range(row * column): if x == 0: matrix[i][j] = start else: if state == 0: j += 1 matrix[i][j] = start state = 1 elif state == 1: if dl == 0: i += 1 matrix[i][j] = start step += 1 if step == stride: dl = 1 step = 0 elif dl == 1: j -= 1 matrix[i][j] = start step += 1 if step == stride: dl = 0 step = 0 stride += 1 state = 2 elif state == 2: i += 1 matrix[i][j] = start state = 3 elif state == 3: if ru == 0: j += 1 matrix[i][j] = start step += 1 if step == stride: ru = 1 step = 0 elif ru == 1: i -= 1 matrix[i][j] = start step += 1 if step == stride: ru = 0 step = 0 stride += 1 state = 0 start += 1 return matrix def generate_zigzag_matrix(row, column): matrix = np.zeros([row, column]) state = 0 stride = 1 step = 0 i = 0 j = 0 start = 0 for x in range(row * column): if x == 0: matrix[i][j] = start else: if state == 0: if j < column - 1: j += 1 matrix[i][j] = start else: i += 1 matrix[i][j] = start state = 1 elif state == 1: i += 1 j -= 1 matrix[i][j] = start step += 1 if i == row - 1: state = 2 stride -= 1 step = 0 elif step == stride: state = 2 stride += 1 step = 0 elif state == 2: if i < row - 1: i += 1 matrix[i][j] = start else: j += 1 matrix[i][j] = start state = 3 elif state == 3: j += 1 i -= 1 matrix[i][j] = start step += 1 if j == column - 1: state = 0 stride -= 1 step = 0 elif step == stride: state = 0 stride += 1 step = 0 start += 1 return matrix class TCG(): def __init__(self, NetStruct, SimConfig_path, disable_pipeline = False, multiple=None): # NetStruct: layer structure, SimConfig_path: Hardware config path, multiple: allocate more resources for some layers TCG_config = cp.ConfigParser() TCG_config.read(SimConfig_path, encoding='UTF-8') if multiple is None: multiple = [1] * len(NetStruct) self.tile = tile(SimConfig_path) self.net = NetStruct self.layer_num = len(self.net) self.layer_tileinfo = [] self.xbar_polarity = int(TCG_config.get('Process element level', 'Xbar_Polarity')) self.tile_connection = int(TCG_config.get('Architecture level', 'Tile_Connection')) self.tile_num = list(map(int, TCG_config.get('Architecture level', 'Tile_Num').split(','))) if self.tile_num[0] == 0: self.tile_num[0] = 8 self.tile_num[1] = 8 assert self.tile_num[0] > 0, "Tile number < 0" assert self.tile_num[1] > 0, "Tile number < 0" self.tile_total_num = self.tile_num[0] * self.tile_num[1] self.mapping_order = -1 * np.ones(self.tile_num) self.mapping_result = -1 * np.ones(self.tile_num) start_tileid = 0 # the start tile id # self.trans_time = np.ones([1, self.layer_num]) self.max_inbuf_size = 0 # the maximum input buffer size of each PE, unit: KB self.max_outbuf_size = 0 # the maximum output buffer size of each tile, unit: KB self.global_buf_size = 0 # the global buffer size for accumulator self.global_data_size = 0 self.global_adder_num = 0 # the global adder number in accumulator self.global_adder_bitwidth = 8 num = [] for layer_id in range(self.layer_num): layer_dict = self.net[layer_id][0][0] tmp_tileinfo = collections.OrderedDict() layer_type = layer_dict['type'] if self.xbar_polarity == 1: weight_precision = int(layer_dict['Weightbit']) else: assert self.xbar_polarity == 2, "Crossbar polarity must be 1 or 2" weight_precision = int(layer_dict['Weightbit']) - 1 tmp_tileinfo['weight_precision'] = weight_precision tmp_tileinfo['startid'] = start_tileid input_size = 0 inputchannel = 0 outputchannel = 0 data_inbuf = 0 data_outbuf = 0 if layer_type == 'conv': tmp_tileinfo['type'] = 'conv' tmp_tileinfo['mx'] = math.ceil(weight_precision / self.tile.group_num) * \ math.ceil(int(layer_dict['Outputchannel']) / self.tile.xbar_column) # mx: PE number in x-axis tmp_tileinfo['x_width'] = int(layer_dict['Outputchannel']) * weight_precision # width of kernels tmp_tileinfo['my'] = math.ceil(int(layer_dict['Inputchannel']) / (self.tile.xbar_row // (int(layer_dict['Kernelsize']) ** 2))) # my: PE number in y-axis tmp_tileinfo['y_height'] = int(layer_dict['Inputchannel']) * (int(layer_dict['Kernelsize']) ** 2) # height of kernels tmp_tileinfo['max_group'] = min(weight_precision, self.tile.group_num) # max_group: maximum used groups in one PE of this layer tmp_tileinfo['max_row'] = min((self.tile.xbar_row // (int(layer_dict['Kernelsize']) ** 2)), int(layer_dict['Inputchannel'])) * (int(layer_dict['Kernelsize']) ** 2) # max_row: maximum used row in one crossbar of this layer tmp_tileinfo['max_column'] = min(int(layer_dict['Outputchannel']), self.tile.xbar_column) # max_column: maximum used column in one crossbar of this layer if 'Inputindex' not in layer_dict.keys(): tmp_tileinfo['Inputindex'] = [-1] else: tmp_tileinfo['Inputindex'] = list(map(int, layer_dict['Inputindex'])) # Inputindex: the relative index of the input layers of this layer if 'Outputindex' not in layer_dict.keys(): tmp_tileinfo['Outputindex'] = [1] else: tmp_tileinfo['Outputindex'] = list(map(int, layer_dict['Outputindex'])) # Outputindex: the relative index of the output layers of this layer if len(tmp_tileinfo['Outputindex']) == 1: tmp_tileinfo['is_branchin'] = -1 else: tmp_tileinfo['is_branchin'] = 1 # is_branchin: if this layer is the input layer of a branch tmp_tileinfo['is_branchout'] = 1 # is_branchout: if this layer is the output layer of a branch (the next layer is element_sum) for i in tmp_tileinfo['Outputindex']: tmp_layer = self.net[i+layer_id][0][0] if tmp_layer['type'] != 'element_sum': tmp_tileinfo['is_branchout'] = -1 input_size_list = list(map(int, layer_dict['Inputsize'])) input_size = input_size_list[0] * input_size_list[1] inputchannel = int(layer_dict['Inputchannel']) if not disable_pipeline: data_inbuf = input_size_list[1]*int(layer_dict['Kernelsize'])*inputchannel*int(layer_dict['Inputbit'])/8 else: data_inbuf = input_size*inputchannel*int(layer_dict['Inputbit'])/8 # TODO: non-square convolution outputchannel = int(layer_dict['Outputchannel']) data_outbuf = outputchannel*int(layer_dict['outputbit'])/8 # buffer_size: unit Byte elif layer_type == 'fc': tmp_tileinfo['type'] = 'fc' tmp_tileinfo['mx'] = math.ceil(weight_precision / self.tile.group_num) * \ math.ceil(int(layer_dict['Outfeature']) / self.tile.xbar_column) # mx: PE number in x-axis tmp_tileinfo['x_width'] = int(layer_dict['Outfeature']) * weight_precision # width of kernels tmp_tileinfo['my'] = math.ceil(int(layer_dict['Infeature']) / self.tile.xbar_row) # my: PE number in y-axis tmp_tileinfo['y_height'] = int(layer_dict['Infeature']) # height of kernels tmp_tileinfo['max_group'] = min(weight_precision, self.tile.group_num) # max_group: maximum used groups in one PE of this layer tmp_tileinfo['max_row'] = min(int(layer_dict['Infeature']), self.tile.xbar_row) # max_row: maximum used row in one crossbar of this layer tmp_tileinfo['max_column'] = min(int(layer_dict['Outfeature']), self.tile.xbar_column) # max_row: maximum used column in one crossbar of this layer if 'Inputindex' not in layer_dict.keys(): tmp_tileinfo['Inputindex'] = [-1] else: tmp_tileinfo['Inputindex'] = list(map(int, layer_dict['Inputindex'])) # Inputindex: the relative index of the input layers of this layer if 'Outputindex' not in layer_dict.keys(): tmp_tileinfo['Outputindex'] = [1] else: tmp_tileinfo['Outputindex'] = list(map(int, layer_dict['Outputindex'])) # Outputindex: the relative index of the output layers of this layer if len(tmp_tileinfo['Outputindex']) == 1: tmp_tileinfo['is_branchin'] = -1 else: tmp_tileinfo['is_branchin'] = 1 tmp_tileinfo['is_branchout'] = 1 # is_branchout: if this layer is the output layer of a branch (the next layer is element_sum) for i in tmp_tileinfo['Outputindex']: if (i+layer_id) < self.layer_num: tmp_layer = self.net[i + layer_id][0][0] if tmp_layer['type'] != 'element_sum': tmp_tileinfo['is_branchout'] = -1 # is_branchin: if this layer is the input layer of a branch input_size = int(layer_dict['Infeature']) inputchannel = 1 data_inbuf = input_size*inputchannel*int(layer_dict['Inputbit'])/8 data_outbuf = int(layer_dict['Outfeature'])*int(layer_dict['outputbit'])/8 # buffer_size: unit Byte elif layer_type == 'pooling': tmp_tileinfo['type'] = 'pooling' tmp_tileinfo['mx'] = 1 tmp_tileinfo['my'] = 1 tmp_tileinfo['x_width'] = 0 tmp_tileinfo['y_height'] = 0 tmp_tileinfo['max_row'] = 0 tmp_tileinfo['max_column'] = 0 tmp_tileinfo['max_group'] = 0 if 'Inputindex' not in layer_dict.keys(): tmp_tileinfo['Inputindex'] = [-1] else: tmp_tileinfo['Inputindex'] = list(map(int, layer_dict['Inputindex'])) # Inputindex: the relative index of the input layers of this layer if 'Outputindex' not in layer_dict.keys(): tmp_tileinfo['Outputindex'] = [1] else: tmp_tileinfo['Outputindex'] = list(map(int, layer_dict['Outputindex'])) # Outputindex: the relative index of the output layers of this layer if len(tmp_tileinfo['Outputindex']) == 1: tmp_tileinfo['is_branchin'] = -1 else: tmp_tileinfo['is_branchin'] = 1 # is_branchin: if this layer is the input layer of a branch tmp_tileinfo['is_branchout'] = 1 # is_branchout: if this layer is the output layer of a branch (the next layer is element_sum) for i in tmp_tileinfo['Outputindex']: tmp_layer = self.net[i + layer_id][0][0] if tmp_layer['type'] != 'element_sum': tmp_tileinfo['is_branchout'] = -1 input_size_list = list(map(int, layer_dict['Inputsize'])) input_size = input_size_list[0] * input_size_list[1] inputchannel = int(layer_dict['Inputchannel']) data_inbuf = 0 data_outbuf = 0 # assume the buffer size depends on the conv/fc layers elif layer_type == 'element_sum': tmp_tileinfo['type'] = 'element_sum' tmp_tileinfo['mx'] = 0 tmp_tileinfo['my'] = 0 tmp_tileinfo['x_width'] = 0 tmp_tileinfo['y_height'] = 0 tmp_tileinfo['max_row'] = 0 tmp_tileinfo['max_column'] = 0 tmp_tileinfo['max_group'] = 0 if 'Outputindex' not in layer_dict.keys(): tmp_tileinfo['Outputindex'] = [1] else: tmp_tileinfo['Outputindex'] = list(map(int, layer_dict['Outputindex'])) # Outputindex: the relative index of the output layers of this layer if len(tmp_tileinfo['Outputindex']) == 1: tmp_tileinfo['is_branchin'] = -1 else: tmp_tileinfo['is_branchin'] = 1 tmp_tileinfo['is_branchout'] = -1 # is_branchin: if this layer is the input layer of a branch Inputindex_list = list(map(int, layer_dict['Inputindex'])) tmp_tileinfo['Inputindex'] = Inputindex_list assert len(Inputindex_list)>1, "the number of element_sum's previous layers must > 1" idx = 0 previous_layer_dict = self.net[layer_id + Inputindex_list[0]][0][0] while previous_layer_dict['type'] == 'element_sum': idx = idx+1 previous_layer_dict = self.net[layer_id + Inputindex_list[idx]][0][0] tmp_tileinfo['datanum_branchout'] = previous_layer_dict['Outputchannel'] #*\ # the data number of each branch output, assume the output of each branch contains one output point tmp_tileinfo['bit_branchout'] = previous_layer_dict['outputbit'] # the data precision of each branch output (bit) data_size = tmp_tileinfo['datanum_branchout']*tmp_tileinfo['bit_branchout']*len(Inputindex_list)/8 # unit: Byte self.global_data_size = self.global_data_size + data_size self.global_buf_size = self.global_buf_size + math.pow(2,math.ceil(math.log(data_size,2)))/1024 # unit: KB self.global_adder_num = self.global_adder_num + previous_layer_dict['Outputchannel']*len(Inputindex_list)//2 if tmp_tileinfo['bit_branchout']>self.global_adder_bitwidth: self.global_adder_bitwidth = tmp_tileinfo['bit_branchout'] # self.trans_time[0][layer_id] = 0 # if layer_id < self.layer_num - 1: # for next_id in tmp_tileinfo['Outputindex']: # next_layer_dict = self.net[layer_id + next_id][0][0] # if next_layer_dict['type'] == 'conv' or next_layer_dict['type'] == 'pooling': # self.trans_time[0][layer_id] = int(layer_dict['Outputsize'][1]) * \ # max(int(next_layer_dict['Kernelsize']) - int( # next_layer_dict['Padding']) - 1, 0) + \ # max(int(next_layer_dict['Kernelsize']) - int( # next_layer_dict['Padding']) - 1, 0) # # The amount of data that the previous layer needs to calculate before the next layer starts # elif next_layer_dict['type'] == 'fc': # self.trans_time[0][layer_id] = 1 tmp_tileinfo['PEnum'] = tmp_tileinfo['mx'] * tmp_tileinfo['my'] * multiple[layer_id] num.append(tmp_tileinfo['PEnum']) tmp_tileinfo['tilenum'] = math.ceil(tmp_tileinfo['PEnum'] / self.tile.tile_PE_total_num) tmp_tileinfo['max_PE'] = min(tmp_tileinfo['PEnum'], self.tile.tile_PE_total_num) start_tileid += tmp_tileinfo['tilenum'] self.layer_tileinfo.append(tmp_tileinfo) inputbit = int(layer_dict['Inputbit']) if tmp_tileinfo['type'] == 'conv' or tmp_tileinfo['type'] == 'fc': tmp_inbuf_size = math.pow(2,math.ceil(math.log(data_inbuf / tmp_tileinfo['PEnum'],2)))/1024 tmp_outbuf_size = math.pow(2,math.ceil(math.log(data_outbuf*2 / tmp_tileinfo['tilenum'],2)))/1024 # 2: ping-pong else: tmp_inbuf_size = 0 tmp_outbuf_size = 0 # unit: KB, restricted in 2^M KB if tmp_inbuf_size > self.max_inbuf_size: self.max_inbuf_size = tmp_inbuf_size if tmp_outbuf_size > self.max_outbuf_size: self.max_outbuf_size = tmp_outbuf_size # data.append(input_size * inputchannel * inputbit) # res = pd.DataFrame(num) # res.to_csv('MNSIM/NoC/to_interconnect/num_tiles_per_layer.csv', index=False, header=False) # demo = pd.DataFrame(data) # demo.to_csv('MNSIM/NoC/to_interconnect/ip_activation.csv', index=False, header=False) # self.tile.update_tile_buf_size(SimConfig_path, self.max_inbuf_size) self.used_tile_num = start_tileid assert self.used_tile_num <= self.tile_total_num, "Tile number is not enough" self.inLayer_distance = np.zeros([1, self.layer_num]) self.transLayer_distance = np.zeros([1, self.layer_num]) self.aggregate_arg = np.zeros([self.layer_num, 2]) def mapping_matrix_gen(self): if self.tile_connection == 0: self.mapping_order = generate_normal_matrix(self.mapping_order.shape[0], self.mapping_order.shape[1]) elif self.tile_connection == 1: self.mapping_order = generate_snake_matrix(self.mapping_order.shape[0], self.mapping_order.shape[1]) elif self.tile_connection == 2: self.mapping_order = generate_hui_matrix(self.mapping_order.shape[0], self.mapping_order.shape[1]) elif self.tile_connection == 3: self.mapping_order = generate_zigzag_matrix(self.mapping_order.shape[0], self.mapping_order.shape[1]) def mapping_net(self): self.mapping_matrix_gen() for i in range(self.mapping_order.shape[0]): for j in range(self.mapping_order.shape[1]): if self.mapping_order[i][j] < self.used_tile_num: for layer_id in range(self.layer_num - 1): if self.layer_tileinfo[layer_id]['type'] in ['conv','pooling','fc']: # only allocate tile for conv layers, pooling layers, and fc layers if ((self.mapping_order[i][j] >= self.layer_tileinfo[layer_id]['startid']) & (self.mapping_order[i][j] < self.layer_tileinfo[layer_id + 1]['startid'])): self.mapping_result[i][j] = layer_id break elif self.mapping_order[i][j] >= self.layer_tileinfo[self.layer_num - 1]['startid']: self.mapping_result[i][j] = self.layer_num - 1 def calculate_transfer_distance(self): for layer_id in range(self.layer_num - 1): # Determine the aggregate node for layer 0~N-1 if self.layer_tileinfo[layer_id]['is_branchout'] == 1: # for the layer which is a output layer of one branch and the next layer is element_sum if self.layer_tileinfo[layer_id]['type'] in ['conv', 'pooling', 'fc']: src_pos = np.argwhere(self.mapping_result == layer_id) if len(src_pos) == 1: self.inLayer_distance[0][layer_id] = 0 self.aggregate_arg[layer_id] = src_pos[0] self.transLayer_distance[0][layer_id] = abs(src_pos[0][0]-1/2*self.tile_num[0]) + src_pos[0][1] # TODO: transfer distance update between computing array and element sum array else: mindis_total = 1000 for A in range(len(src_pos)): tmp_transLayer_distance = abs(src_pos[A][0]-1/2*self.tile_num[0]) + src_pos[A][1] maxdis_in = 0 for i in range(len(src_pos)): if i != A: dis_in = abs(src_pos[A][0] - src_pos[i][0]) + abs(src_pos[A][1] - src_pos[i][1]) if dis_in > maxdis_in: maxdis_in = dis_in if (maxdis_in+tmp_transLayer_distance)<mindis_total: self.inLayer_distance[0][layer_id] = maxdis_in self.transLayer_distance[0][layer_id] = tmp_transLayer_distance self.aggregate_arg[layer_id] = src_pos[A] mindis_total = maxdis_in+tmp_transLayer_distance else: if self.layer_tileinfo[layer_id]['type'] in ['conv', 'pooling', 'fc']: src_pos = np.argwhere(self.mapping_result == layer_id) if len(src_pos) == 1: self.inLayer_distance[0][layer_id] = 0 self.aggregate_arg[layer_id] = src_pos[0] maxdis = 0 for idx in self.layer_tileinfo[layer_id]['Outputindex']: dst_pos = np.argwhere(self.mapping_result == (layer_id + idx)) for i in range(len(dst_pos)): dis = abs(src_pos[0][0] - dst_pos[i][0]) + abs(src_pos[0][1] - dst_pos[i][1]) if dis > maxdis: maxdis = dis self.transLayer_distance[0][layer_id] = maxdis else: mindis_total = 1000 for A in range(len(src_pos)): maxdis_in = 0 maxdis_out = 0 for i in range(len(src_pos)): if i != A: dis_in = abs(src_pos[A][0] - src_pos[i][0]) + abs(src_pos[A][1] - src_pos[i][1]) if dis_in > maxdis_in: maxdis_in = dis_in for idx in self.layer_tileinfo[layer_id]['Outputindex']: dst_pos = np.argwhere(self.mapping_result == (layer_id + idx)) for j in range(len(dst_pos)): dis_out = abs(src_pos[A][0] - dst_pos[j][0]) + abs(src_pos[A][1] - dst_pos[j][1]) if dis_out > maxdis_out: maxdis_out = dis_out tempdis = maxdis_in + maxdis_out if tempdis < mindis_total: self.inLayer_distance[0][layer_id] = maxdis_in self.transLayer_distance[0][layer_id] = maxdis_out self.aggregate_arg[layer_id] = src_pos[A] mindis_total = tempdis elif self.layer_tileinfo[layer_id]['type'] == 'element_sum': maxdis_out = 0 for idx in self.layer_tileinfo[layer_id]['Outputindex']: dst_pos = np.argwhere(self.mapping_result == (layer_id + idx)) for j in range(len(dst_pos)): dis_out = abs(dst_pos[0][0]-1/2*self.tile_num[0]) + dst_pos[0][1] if dis_out > maxdis_out: maxdis_out = dis_out self.inLayer_distance[0][layer_id] = 0 self.transLayer_distance[0][layer_id] = maxdis_out final_pos = np.argwhere(self.mapping_result == self.layer_num - 1) # Determine the aggregate node for layer N (output layer) mindis = 1000 for i in range(len(final_pos)): maxdis = 0 for j in range(len(final_pos)): if j != i: dis = abs(final_pos[i][0] - final_pos[j][0]) + abs(final_pos[i][1] - final_pos[j][1]) if dis > maxdis: maxdis = dis if maxdis < mindis: mindis = maxdis self.inLayer_distance[0][self.layer_num - 1] = mindis self.aggregate_arg[self.layer_num - 1] = final_pos[i] self.transLayer_distance[0][self.layer_num - 1] = 0 # self.total_distance = sum(sum(self.trans_time * (self.inLayer_distance + self.transLayer_distance))) if __name__ == '__main__': test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "SimConfig.ini") test_weights_file_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "vgg8_params.pth") __TestInterface = TrainTestInterface('vgg8_128_9', 'MNSIM.Interface.cifar10', test_SimConfig_path, test_weights_file_path, 'cpu') structure_file = __TestInterface.get_structure() test = TCG(structure_file, test_SimConfig_path) test.mapping_net() test.calculate_transfer_distance() # print(test.total_distance) <file_sep>/MNSIM/Latency_Model/Tile_latency.py #!/usr/bin/python # -*-coding:utf-8-*- import torch import sys import os import math import configparser as cp work_path = os.path.dirname(os.getcwd()) sys.path.append(work_path) from MNSIM.Interface.interface import * from MNSIM.Latency_Model.PE_latency import PE_latency_analysis from MNSIM.Hardware_Model.Buffer import buffer class tile_latency_analysis(PE_latency_analysis): def __init__(self, SimConfig_path, read_row=0, read_column=0, indata=0, rdata=0, inprecision = 8, PE_num=0, default_inbuf_size = 16, default_outbuf_size =4): # read_row: activated WL number in crossbar # read_column: activated BL number in crossbar # indata: volume of input data (for PE) (Byte) # rdata: volume of data from buffer to iReg (Byte) # outdata: volume of output data (for PE) (Byte) # inprecision: input data precision of each Xbar # PE_num: used PE_number in one tile # default_inbuf_size: the default PE-level input buffer size (unit: KB) # default_outbuf_size: the default Tile-level output buffer size (unit: KB) PE_latency_analysis.__init__(self, SimConfig_path, read_row=read_row, read_column=read_column, indata=indata, rdata=rdata, inprecision=inprecision, default_buf_size = default_inbuf_size) tilel_config = cp.ConfigParser() tilel_config.read(SimConfig_path, encoding='UTF-8') self.intra_tile_bandwidth = float(tilel_config.get('Tile level', 'Intra_Tile_Bandwidth')) merge_time = math.ceil(math.log2(PE_num)) self.tile_PE_num = list(map(int, tilel_config.get('Tile level', 'PE_Num').split(','))) if self.tile_PE_num[0] == 0: self.tile_PE_num[0] = 4 self.tile_PE_num[1] = 4 assert self.tile_PE_num[0] > 0, "PE number in one PE < 0" assert self.tile_PE_num[1] > 0, "PE number in one PE < 0" self.tile_PE_total_num = self.tile_PE_num[0] * self.tile_PE_num[1] assert PE_num <= self.tile_PE_total_num, "PE number exceeds the range" self.outbuf = buffer(SimConfig_path=SimConfig_path, buf_level=2, default_buf_size=default_outbuf_size) total_level = math.ceil(math.log2(self.tile_PE_total_num)) self.jointmodule_latency = merge_time * self.digital_period self.transfer_latency = (total_level*(self.PE.ADC_precision+merge_time)-merge_time*(merge_time+1)/2)\ *read_column/self.intra_tile_bandwidth self.outbuf.calculate_buf_write_latency(wdata=((self.PE.ADC_precision + merge_time)*read_column*PE_num/8)) self.tile_buf_rlatency = 0 self.tile_buf_wlatency = self.outbuf.buf_wlatency # do not consider self.tile_latency = self.PE_latency + self.jointmodule_latency + self.transfer_latency + self.tile_buf_wlatency def update_tile_latency(self, indata = 0, rdata = 0): self.update_PE_latency(indata=indata,rdata=rdata) self.tile_latency = self.PE_latency + self.jointmodule_latency + self.transfer_latency + self.tile_buf_wlatency if __name__ == '__main__': test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "SimConfig.ini") _test = tile_latency_analysis(test_SimConfig_path, 100, 100, 32, 96, 8, 8) print(_test)<file_sep>/MNSIM/Interface/cifar100.py #-*-coding:utf-8-*- # import multiprocessing # multiprocessing.set_start_method('spawn', True) import os import torch.utils.data as Data import torchvision import torchvision.transforms as Transforms TRAIN_BATCH_SIZE = 128 TRAIN_NUM_WORKERS = 0 TEST_BATCH_SIZE = 100 TEST_NUM_WORKERS = 0 def get_dataloader(): train_dataset = torchvision.datasets.CIFAR100( root = os.path.join(os.path.dirname(__file__), "cifar100"), download = True, train = True, transform = Transforms.Compose([ Transforms.Pad(padding = 4), Transforms.RandomCrop(32), Transforms.RandomHorizontalFlip(), Transforms.ToTensor(), ]) ) train_loader = Data.DataLoader( dataset = train_dataset, batch_size = TRAIN_BATCH_SIZE, shuffle = True, num_workers = TRAIN_NUM_WORKERS, drop_last = True, ) test_dataset = torchvision.datasets.CIFAR100( root = os.path.join(os.path.dirname(__file__), "cifar100"), download = True, train = False, transform = Transforms.Compose([ Transforms.ToTensor(), ]) ) test_loader = Data.DataLoader( dataset = test_dataset, batch_size = TEST_BATCH_SIZE, shuffle = False, num_workers = TEST_NUM_WORKERS, drop_last = False, ) return train_loader, test_loader if __name__ == '__main__': train_loader, test_loader = get_dataloader() print(len(train_loader)) print(len(test_loader)) print('this is the cifar100 dataset, output shape is 32x32x3')<file_sep>/MNSIM/Interface/network.py #-*-coding:utf-8-*- import collections import copy import re import sys import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from MNSIM.Interface import quantize class NetworkGraph(nn.Module): def __init__(self, hardware_config, layer_config_list, quantize_config_list, input_index_list, input_params): super(NetworkGraph, self).__init__() # same length for layer_config_list , quantize_config_list and input_index_list assert len(layer_config_list) == len(quantize_config_list) assert len(layer_config_list) == len(input_index_list) # layer list self.layer_list = nn.ModuleList() # add layer to layer list by layer_config, quantize_config, and input_index for layer_config, quantize_config in zip(layer_config_list, quantize_config_list): assert 'type' in layer_config.keys() if layer_config['type'] in quantize.QuantizeLayerStr: layer = quantize.QuantizeLayer(hardware_config, layer_config, quantize_config) elif layer_config['type'] in quantize.StraightLayerStr: layer = quantize.StraightLayer(hardware_config, layer_config, quantize_config) else: assert 0, f'not support {layer_config["type"]}' self.layer_list.append(layer) # save input_index_list, input_index is a list self.input_index_list = copy.deepcopy(input_index_list) self.input_params = copy.deepcopy(input_params) def forward(self, x, method = 'SINGLE_FIX_TEST', adc_action = 'SCALE'): # input fix information quantize.last_activation_scale = self.input_params['activation_scale'] quantize.last_activation_bit = self.input_params['activation_bit'] # forward tensor_list = [x] for i, layer in enumerate(self.layer_list): # find the input tensor input_index = self.input_index_list[i] assert len(input_index) in [1, 2] if len(input_index) == 1: tensor_list.append(layer.forward(tensor_list[input_index[0] + i + 1], method, adc_action)) else: tensor_list.append( layer.forward([ tensor_list[input_index[0] + i + 1], tensor_list[input_index[1] + i + 1], ], method, adc_action, ) ) return tensor_list[-1] def get_weights(self): net_bit_weights = [] for layer in self.layer_list: net_bit_weights.append(layer.get_bit_weights()) return net_bit_weights def set_weights_forward(self, x, net_bit_weights, adc_action = 'SCALE'): # input fix information quantize.last_activation_scale = self.input_params['activation_scale'] quantize.last_activation_bit = self.input_params['activation_bit'] # filter None net_bit_weights = list(filter(lambda x:x!=None, net_bit_weights)) # forward tensor_list = [x] count = 0 for i, layer in enumerate(self.layer_list): # find the input tensor input_index = self.input_index_list[i] assert len(input_index) in [1, 2] if isinstance(layer, quantize.QuantizeLayer): tensor_list.append(layer.set_weights_forward(tensor_list[input_index[0] + i + 1], net_bit_weights[count], adc_action)) # tensor_list.append(layer.forward(tensor_list[input_index[0] + i + 1], 'SINGLE_FIX_TEST', adc_action)) count = count + 1 else: if len(input_index) == 1: tensor_list.append(layer.forward(tensor_list[input_index[0] + i + 1], 'FIX_TRAIN', None)) else: tensor_list.append( layer.forward([ tensor_list[input_index[0] + i + 1], tensor_list[input_index[1] + i + 1], ], 'FIX_TRAIN', None, ) ) return tensor_list[-1] def get_structure(self): # forward structure x = torch.zeros(self.input_params['input_shape']) self.to(x.device) self.eval() tensor_list = [x] for i, layer in enumerate(self.layer_list): # find the input tensor input_index = self.input_index_list[i] assert len(input_index) in [1, 2] # print(tensor_list[input_index[0]+i+1].shape) if len(input_index) == 1: tensor_list.append(layer.structure_forward(tensor_list[input_index[0] + i + 1])) else: tensor_list.append( layer.structure_forward([ tensor_list[input_index[0] + i + 1], tensor_list[input_index[1] + i + 1], ], ) ) # structure information, stored as list net_info = [] for layer in self.layer_list: net_info.append(layer.layer_info) return net_info def load_change_weights(self, state_dict): # input is a state dict, weights # concat all layer_list weights keys_map = collections.OrderedDict() for key in state_dict.keys(): tmp_key = re.sub('\.layer_list\.\d+\.weight$', '', key) if tmp_key not in keys_map.keys(): keys_map[tmp_key] = [key] else: keys_map[tmp_key].append(key) # concat and split tmp_state_dict = collections.OrderedDict() for tmp_key, key_list in keys_map.items(): if len(key_list) == 1 and tmp_key == key_list[0]: # print('origin weights') tmp_state_dict[tmp_key] = state_dict[key_list[0]] else: # print(f'transfer weights {tmp_key}') # get layer info layer_config = None hardware_config = None for i in range(len(self.layer_list)): name = f'layer_list.{i}' if name == tmp_key: layer_config = self.layer_list[i].layer_config hardware_config = self.layer_list[i].hardware_config assert layer_config, 'layer must have layer config' assert hardware_config, 'layer must have hardware config' # concat weights total_weights = torch.cat([state_dict[key] for key in key_list], dim = 1) # split weights if layer_config['type'] == 'conv': split_len = (hardware_config['xbar_size'] // (layer_config['kernel_size'] ** 2)) elif layer_config['type'] == 'fc': split_len = hardware_config['xbar_size'] else: assert 0, f'not support {layer_config["type"]}' weights_list = torch.split(total_weights, split_len, dim = 1) # load weights for i, weights in enumerate(weights_list): tmp_state_dict[tmp_key + f'.layer_list.{i}.weight'] = weights # load weights self.load_state_dict(tmp_state_dict) def get_net(hardware_config = None, cate = 'lenet', num_classes = 10): # initial config if hardware_config == None: hardware_config = {'xbar_size': 512, 'input_bit': 2, 'weight_bit': 1, 'quantize_bit': 10} # hardware_config = {'xbar_size': 256, 'input_bit': 1, 'weight_bit': 1, 'quantize_bit': 8} # layer_config_list, quantize_config_list, and input_index_list layer_config_list = [] quantize_config_list = [] input_index_list = [] # layer by layer assert cate in ['lenet', 'vgg16', 'vgg8', 'alexnet', 'resnet18'] if cate.startswith('lenet'): layer_config_list.append({'type': 'conv', 'in_channels': 3, 'out_channels': 6, 'kernel_size': 5}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) layer_config_list.append({'type': 'conv', 'in_channels': 6, 'out_channels': 16, 'kernel_size': 5}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) layer_config_list.append({'type': 'conv', 'in_channels': 16, 'out_channels': 120, 'kernel_size': 5}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'view'}) layer_config_list.append({'type': 'fc', 'in_features': 120, 'out_features': 84}) layer_config_list.append({'type': 'dropout'}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'fc', 'in_features': 84, 'out_features': num_classes}) elif cate.startswith('vgg16'): layer_config_list.append({'type': 'conv', 'in_channels': 3, 'out_channels': 64, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 64, 'out_channels': 64, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) layer_config_list.append({'type': 'conv', 'in_channels': 64, 'out_channels': 128, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 128, 'out_channels': 128, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) layer_config_list.append({'type': 'conv', 'in_channels': 128, 'out_channels': 256, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 256, 'out_channels': 256, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 256, 'out_channels': 256, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) layer_config_list.append({'type': 'conv', 'in_channels': 256, 'out_channels': 512, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 512, 'out_channels': 512, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 512, 'out_channels': 512, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) layer_config_list.append({'type': 'conv', 'in_channels': 512, 'out_channels': 512, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 512, 'out_channels': 512, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 512, 'out_channels': 512, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'view'}) layer_config_list.append({'type': 'fc', 'in_features': 2048, 'out_features': num_classes}) # layer_config_list.append({'type': 'dropout'}) # layer_config_list.append({'type': 'relu'}) # layer_config_list.append({'type': 'fc', 'in_features': 512, 'out_features': num_classes}) # layer_config_list.append({'type': 'dropout'}) # layer_config_list.append({'type': 'relu'}) # layer_config_list.append({'type': 'fc', 'in_features': 4096, 'out_features': num_classes}) elif cate.startswith('vgg8'): layer_config_list.append({'type': 'conv', 'in_channels': 3, 'out_channels': 128, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 128, 'out_channels': 128, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) layer_config_list.append({'type': 'conv', 'in_channels': 128, 'out_channels': 256, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 256, 'out_channels': 256, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) layer_config_list.append({'type': 'conv', 'in_channels': 256, 'out_channels': 512, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 512, 'out_channels': 512, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) layer_config_list.append({'type': 'conv', 'in_channels': 512, 'out_channels': 1024, 'kernel_size': 3, 'padding': 0}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) layer_config_list.append({'type': 'view'}) layer_config_list.append({'type': 'fc', 'in_features': 1024, 'out_features': num_classes}) elif cate.startswith('alexnet'): layer_config_list.append({'type': 'conv', 'in_channels': 3, 'out_channels': 64, 'kernel_size': 3, 'padding': 1, 'stride': 2}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) layer_config_list.append({'type': 'conv', 'in_channels': 64, 'out_channels': 192, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) layer_config_list.append({'type': 'conv', 'in_channels': 192, 'out_channels': 384, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 384, 'out_channels': 256, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 256, 'out_channels': 256, 'kernel_size': 3, 'padding': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) layer_config_list.append({'type': 'view'}) layer_config_list.append({'type': 'fc', 'in_features': 1024, 'out_features': 512}) layer_config_list.append({'type': 'dropout'}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'fc', 'in_features': 512, 'out_features': num_classes}) elif cate.startswith('resnet18'): layer_config_list.append({'type': 'conv', 'in_channels': 3, 'out_channels': 64, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'pooling', 'mode': 'MAX', 'kernel_size': 2, 'stride': 2}) # block 1 layer_config_list.append({'type': 'conv', 'in_channels': 64, 'out_channels': 64, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 64, 'out_channels': 64, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'element_sum', 'input_index': [-1, -4]}) layer_config_list.append({'type': 'relu'}) # block 2 layer_config_list.append({'type': 'conv', 'in_channels': 64, 'out_channels': 64, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 64, 'out_channels': 64, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'element_sum', 'input_index': [-1, -4]}) layer_config_list.append({'type': 'relu'}) # block 3 layer_config_list.append({'type': 'conv', 'in_channels': 64, 'out_channels': 128, 'kernel_size': 3, 'padding': 1, 'stride': 2}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 128, 'out_channels': 128, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'conv', 'in_channels': 64, 'out_channels': 128, 'kernel_size': 3, 'padding': 1, 'stride': 2, 'input_index': [-4]}) layer_config_list.append({'type': 'element_sum', 'input_index': [-1, -2]}) layer_config_list.append({'type': 'relu'}) # block 4 layer_config_list.append({'type': 'conv', 'in_channels': 128, 'out_channels': 128, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 128, 'out_channels': 128, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'element_sum', 'input_index': [-1, -4]}) layer_config_list.append({'type': 'relu'}) # block 5 layer_config_list.append({'type': 'conv', 'in_channels': 128, 'out_channels': 256, 'kernel_size': 3, 'padding': 1, 'stride': 2}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 256, 'out_channels': 256, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'conv', 'in_channels': 128, 'out_channels': 256, 'kernel_size': 3, 'padding': 1, 'stride': 2, 'input_index': [-4]}) layer_config_list.append({'type': 'element_sum', 'input_index': [-1, -2]}) layer_config_list.append({'type': 'relu'}) # block 6 layer_config_list.append({'type': 'conv', 'in_channels': 256, 'out_channels': 256, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 256, 'out_channels': 256, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'element_sum', 'input_index': [-1, -4]}) layer_config_list.append({'type': 'relu'}) # block 7 layer_config_list.append({'type': 'conv', 'in_channels': 256, 'out_channels': 512, 'kernel_size': 3, 'padding': 1, 'stride': 2}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 512, 'out_channels': 512, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'conv', 'in_channels': 256, 'out_channels': 512, 'kernel_size': 3, 'padding': 1, 'stride': 2, 'input_index': [-4]}) layer_config_list.append({'type': 'element_sum', 'input_index': [-1, -2]}) layer_config_list.append({'type': 'relu'}) # block 8 layer_config_list.append({'type': 'conv', 'in_channels': 512, 'out_channels': 512, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'conv', 'in_channels': 512, 'out_channels': 512, 'kernel_size': 3, 'padding': 1, 'stride': 1}) layer_config_list.append({'type': 'element_sum', 'input_index': [-1, -4]}) layer_config_list.append({'type': 'relu'}) # output layer_config_list.append({'type': 'view'}) layer_config_list.append({'type': 'fc', 'in_features': 2048, 'out_features': 512}) layer_config_list.append({'type': 'dropout'}) layer_config_list.append({'type': 'relu'}) layer_config_list.append({'type': 'fc', 'in_features': 512, 'out_features': num_classes}) else: assert 0, f'not support {cate}' for i in range(len(layer_config_list)): quantize_config_list.append({'weight_bit': 9, 'activation_bit': 9, 'point_shift': -2}) if 'input_index' in layer_config_list[i]: input_index_list.append(layer_config_list[i]['input_index']) else: input_index_list.append([-1]) input_params = {'activation_scale': 1. / 255., 'activation_bit': 9, 'input_shape': (1, 3, 32, 32)} # add bn for every conv L = len(layer_config_list) for i in range(L-1, -1, -1): if layer_config_list[i]['type'] == 'conv': # continue layer_config_list.insert(i+1, {'type': 'bn', 'features': layer_config_list[i]['out_channels']}) quantize_config_list.insert(i+1, {'weight_bit': 9, 'activation_bit': 9, 'point_shift': -2}) input_index_list.insert(i+1, [-1]) for j in range(i + 2, len(layer_config_list), 1): for relative_input_index in range(len(input_index_list[j])): if j + input_index_list[j][relative_input_index] < i + 1: input_index_list[j][relative_input_index] -= 1 # print(layer_config_list) # print(quantize_config_list) # print(input_index_list) # generate net net = NetworkGraph(hardware_config, layer_config_list, quantize_config_list, input_index_list, input_params) return net if __name__ == '__main__': assert len(sys.argv) == 3 net = get_net(cate = sys.argv[1], num_classes = int(sys.argv[2])) print(net) for name, param in net.named_parameters(): print(name, type(param.data), param.size()) print(f'this is network input shape {net.input_params["input_shape"]},output shape {net.layer_list[-1].layer_config["out_features"]}') <file_sep>/main.py #!/usr/bin/python # -*-coding:utf-8-*- import torch import sys import os import math import argparse import numpy as np import torch import collections import configparser from importlib import import_module from MNSIM.Interface.interface import * from MNSIM.Accuracy_Model.Weight_update import weight_update from MNSIM.Mapping_Model.Behavior_mapping import behavior_mapping from MNSIM.Mapping_Model.Tile_connection_graph import TCG from MNSIM.Latency_Model.Model_latency import Model_latency from MNSIM.Area_Model.Model_Area import Model_area from MNSIM.Power_Model.Model_inference_power import Model_inference_power from MNSIM.Energy_Model.Model_energy import Model_energy def Data_clean(): path = os.getcwd() NoC_file = path + '/MNSIM/NoC/' inj_file = 'inj_dir' log_file = 'log' res_file = 'Final_Results' files = os.listdir(NoC_file) for file in files: if file == inj_file: for target in os.listdir(NoC_file + inj_file): os.remove(NoC_file + inj_file + '/' + target) elif file == log_file: for target in os.listdir(NoC_file + log_file): os.remove(NoC_file + log_file + '/' + target) elif file == res_file: for target in os.listdir(NoC_file + res_file): os.remove(NoC_file + res_file + '/' + target) else: continue print("Removed unnecessary file.") def main(): # home_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) # print("home path", home_path) # if __name__=='__main__': # home_path = os.path.dirname(os.path.dirname(os.getcwd())) # print(1) # else: home_path = os.getcwd() # print(home_path) SimConfig_path = os.path.join(home_path, "SimConfig.ini") weights_file_path = os.path.join(home_path, "cifar10_vgg8_params.pth") # print(SimConfig_path) parser = argparse.ArgumentParser(description='MNSIM example') parser.add_argument("-AutoDelete", "--file_auto_delete", default=True, help="Whether delete the unnecessary files automatically") # parser.add_argument("-NoC", "--NoC_computation", default=False, # help="Whether call booksim to compute the NoC part") parser.add_argument("-HWdes", "--hardware_description", default=SimConfig_path, help="Hardware description file location & name, default:/MNSIM_Python/SimConfig.ini") parser.add_argument("-Weights", "--weights", default=weights_file_path, help="NN model weights file location & name, default:/MNSIM_Python/cifar10_vgg8_params.pth") parser.add_argument("-NN", "--NN", default='vgg8', help="NN model description (name), default: vgg8") parser.add_argument("-DisHW", "--disable_hardware_modeling", action='store_true', default=False, help="Disable hardware modeling, default: false") parser.add_argument("-DisAccu", "--disable_accuracy_simulation", action='store_true', default=False, help="Disable accuracy simulation, default: false") parser.add_argument("-SAF", "--enable_SAF", action='store_true', default=False, help="Enable simulate SAF, default: false") parser.add_argument("-Var", "--enable_variation", action='store_true', default=False, help="Enable simulate variation, default: false") parser.add_argument("-Rratio", "--enable_R_ratio", action='store_true', default=False, help="Enable simulate the effect of R ratio, default: false") parser.add_argument("-FixRange", "--enable_fixed_Qrange", action='store_true', default=False, help="Enable fixed quantization range (max value), default: false") parser.add_argument("-DisPipe", "--disable_inner_pipeline", action='store_true', default=False, help="Disable inner layer pipeline in latency modeling, default: false") parser.add_argument("-D", "--device", default=0, help="Determine hardware device for simulation, default: CPU") parser.add_argument("-DisModOut", "--disable_module_output", action='store_true', default=False, help="Disable module simulation results output, default: false") parser.add_argument("-DisLayOut", "--disable_layer_output", action='store_true', default=False, help="Disable layer-wise simulation results output, default: false") args = parser.parse_args() if args.file_auto_delete: print("use the root mode by 'sudo -s'") Data_clean() else: print("You should make sure that the files are removed which may cause confusions") print("Hardware description file location:", args.hardware_description) print("Software model file location:", args.weights) print("Whether perform hardware simulation:", not (args.disable_hardware_modeling)) print("Whether perform accuracy simulation:", not (args.disable_accuracy_simulation)) print("Whether consider SAFs:", args.enable_SAF) print("Whether consider variations:", args.enable_variation) if args.enable_fixed_Qrange: print("Quantization range: fixed range (depends on the maximum value)") else: print("Quantization range: dynamic range (depends on the data distribution)") # __TestInterface = TrainTestInterface(args.NN, 'MNSIM.Interface.cifar10', args.hardware_description, # args.weights, args.device) __TestInterface = TrainTestInterface(network_module=args.NN, dataset_module='MNSIM.Interface.cifar10', SimConfig_path=args.hardware_description, weights_file=args.weights, device=args.device) structure_file = __TestInterface.get_structure() # weight = __TestInterface.get_net_bits() # print(structure_file) # print(__TestInterface.origin_evaluate(method = 'FIX_TRAIN', adc_action = 'SCALE')) # print(__TestInterface.set_net_bits_evaluate(weight, adc_action = 'SCALE')) TCG_mapping = TCG(structure_file, args.hardware_description, args.disable_inner_pipeline) # print(TCG_mapping.max_inbuf_size) # print(TCG_mapping.max_outbuf_size) if not (args.disable_hardware_modeling): __latency = Model_latency(NetStruct=structure_file, SimConfig_path=args.hardware_description, TCG_mapping=TCG_mapping) if not (args.disable_inner_pipeline): __latency.calculate_model_latency(mode=1) # __latency.calculate_model_latency_nopipe() else: __latency.calculate_model_latency_nopipe() print("========================Latency Results=================================") __latency.model_latency_output(not (args.disable_module_output), not (args.disable_layer_output)) __area = Model_area(NetStruct=structure_file, SimConfig_path=args.hardware_description, TCG_mapping=TCG_mapping) print("========================Area Results=================================") __area.model_area_output(not (args.disable_module_output), not (args.disable_layer_output)) __power = Model_inference_power(NetStruct=structure_file, SimConfig_path=args.hardware_description, TCG_mapping=TCG_mapping) print("========================Power Results=================================") __power.model_power_output(not (args.disable_module_output), not (args.disable_layer_output)) __energy = Model_energy(NetStruct=structure_file, SimConfig_path=args.hardware_description, TCG_mapping=TCG_mapping, model_latency=__latency, model_power=__power) print("========================Energy Results=================================") __energy.model_energy_output(not (args.disable_module_output), not (args.disable_layer_output)) if not (args.disable_accuracy_simulation): print("======================================") print("Accuracy simulation will take a few minutes on GPU") weight = __TestInterface.get_net_bits() weight_2 = weight_update(args.hardware_description, weight, is_Variation=args.enable_variation, is_SAF=args.enable_SAF, is_Rratio=args.enable_R_ratio) if not (args.enable_fixed_Qrange): print("Original accuracy:", __TestInterface.origin_evaluate(method='FIX_TRAIN', adc_action='SCALE')) print("PIM-based computing accuracy:", __TestInterface.set_net_bits_evaluate(weight_2, adc_action='SCALE')) else: print("Original accuracy:", __TestInterface.origin_evaluate(method='FIX_TRAIN', adc_action='FIX')) print("PIM-based computing accuracy:", __TestInterface.set_net_bits_evaluate(weight_2, adc_action='FIX')) # print(structure_file) if __name__ == '__main__': # Data_clean() main() <file_sep>/MNSIM/Hardware_Model/Buffer.py #!/usr/bin/python # -*-coding:utf-8-*- import configparser as cp import os import math test_SimConfig_path = os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), "SimConfig.ini") # Default SimConfig file path: MNSIM_Python/SimConfig.ini class buffer(object): def __init__(self, SimConfig_path, buf_level = 1, default_buf_size = 16): # buf_level: 1: PE input buffer, 2: tile output buffer, 3: DFU buffer buf_config = cp.ConfigParser() buf_config.read(SimConfig_path, encoding='UTF-8') self.buf_choice = int(buf_config.get('Architecture level', 'Buffer_Choice')) # unit: nm self.buf_Tech = int(buf_config.get('Architecture level', 'Buffer_Technology')) if self.buf_Tech == 0: self.buf_Tech = 65 # buffer size unit: KB if buf_level == 1: self.buf_Size = float(buf_config.get('Process element level', 'PE_inBuf_Size')) elif buf_level == 2: self.buf_Size = float(buf_config.get('Process element level', 'Tile_outBuf_Size')) else: self.buf_Size = float(buf_config.get('Process element level', 'DFU_Buf_Size')) if self.buf_Size == 0: self.buf_Size = default_buf_size self.buf_bitwidth = int(buf_config.get('Architecture level', 'Buffer_Bitwidth')) if self.buf_bitwidth == 0: self.buf_bitwidth = 256 # bit self.index = 0 if self.buf_Tech >= 90: if self.buf_Size <= 2: if self.buf_bitwidth <= 64: self.index = 0 elif self.buf_bitwidth <= 128: self.index = 1 elif self.buf_bitwidth <= 256: self.index = 2 else: self.index = 3 elif self.buf_Size <= 4: if self.buf_bitwidth <= 64: self.index = 4 elif self.buf_bitwidth <= 128: self.index = 5 elif self.buf_bitwidth <= 256: self.index = 6 else: self.index = 7 elif self.buf_Size <= 8: if self.buf_bitwidth <= 64: self.index = 8 elif self.buf_bitwidth <= 128: self.index = 9 elif self.buf_bitwidth <= 256: self.index = 10 else: self.index = 11 elif self.buf_Size <= 16: if self.buf_bitwidth <= 64: self.index = 12 elif self.buf_bitwidth <= 128: self.index = 13 elif self.buf_bitwidth <= 256: self.index = 14 else: self.index = 15 elif self.buf_Size <= 32: if self.buf_bitwidth <= 64: self.index = 16 elif self.buf_bitwidth <= 128: self.index = 17 elif self.buf_bitwidth <= 256: self.index = 18 else: self.index = 19 elif self.buf_Size <= 64: if self.buf_bitwidth <= 64: self.index = 20 elif self.buf_bitwidth <= 128: self.index = 21 elif self.buf_bitwidth <= 256: self.index = 22 else: self.index = 23 elif self.buf_Size <= 128: if self.buf_bitwidth <= 64: self.index = 24 elif self.buf_bitwidth <= 128: self.index = 25 elif self.buf_bitwidth <= 256: self.index = 26 else: self.index = 27 elif self.buf_Size <= 256: if self.buf_bitwidth <= 64: self.index = 28 elif self.buf_bitwidth <= 128: self.index = 29 elif self.buf_bitwidth <= 256: self.index = 30 else: self.index = 31 else: if self.buf_bitwidth <= 64: self.index = 32 elif self.buf_bitwidth <= 128: self.index = 33 elif self.buf_bitwidth <= 256: self.index = 34 else: self.index = 35 elif self.buf_Tech >= 65: if self.buf_Size <= 2: if self.buf_bitwidth <= 64: self.index = 0+36 elif self.buf_bitwidth <= 128: self.index = 1+36 elif self.buf_bitwidth <= 256: self.index = 2+36 else: self.index = 3+36 elif self.buf_Size <= 4: if self.buf_bitwidth <= 64: self.index = 4+36 elif self.buf_bitwidth <= 128: self.index = 5+36 elif self.buf_bitwidth <= 256: self.index = 6+36 else: self.index = 7+36 elif self.buf_Size <= 8: if self.buf_bitwidth <= 64: self.index = 8+36 elif self.buf_bitwidth <= 128: self.index = 9+36 elif self.buf_bitwidth <= 256: self.index = 10+36 else: self.index = 11+36 elif self.buf_Size <= 16: if self.buf_bitwidth <= 64: self.index = 12+36 elif self.buf_bitwidth <= 128: self.index = 13+36 elif self.buf_bitwidth <= 256: self.index = 14+36 else: self.index = 15+36 elif self.buf_Size <= 32: if self.buf_bitwidth <= 64: self.index = 16+36 elif self.buf_bitwidth <= 128: self.index = 17+36 elif self.buf_bitwidth <= 256: self.index = 18+36 else: self.index = 19+36 elif self.buf_Size <= 64: if self.buf_bitwidth <= 64: self.index = 20+36 elif self.buf_bitwidth <= 128: self.index = 21+36 elif self.buf_bitwidth <= 256: self.index = 22+36 else: self.index = 23+36 elif self.buf_Size <= 128: if self.buf_bitwidth <= 64: self.index = 24+36 elif self.buf_bitwidth <= 128: self.index = 25+36 elif self.buf_bitwidth <= 256: self.index = 26+36 else: self.index = 27+36 elif self.buf_Size <= 256: if self.buf_bitwidth <= 64: self.index = 28+36 elif self.buf_bitwidth <= 128: self.index = 29+36 elif self.buf_bitwidth <= 256: self.index = 30+36 else: self.index = 31+36 else: if self.buf_bitwidth <= 64: self.index = 32+36 elif self.buf_bitwidth <= 128: self.index = 33+36 elif self.buf_bitwidth <= 256: self.index = 34+36 else: self.index = 35+36 else: if self.buf_Size <= 2: if self.buf_bitwidth <= 64: self.index = 0+72 elif self.buf_bitwidth <= 128: self.index = 1+72 elif self.buf_bitwidth <= 256: self.index = 2+72 else: self.index = 3+72 elif self.buf_Size <= 4: if self.buf_bitwidth <= 64: self.index = 4+72 elif self.buf_bitwidth <= 128: self.index = 5+72 elif self.buf_bitwidth <= 256: self.index = 6+72 else: self.index = 7+72 elif self.buf_Size <= 8: if self.buf_bitwidth <= 64: self.index = 8+72 elif self.buf_bitwidth <= 128: self.index = 9+72 elif self.buf_bitwidth <= 256: self.index = 10+72 else: self.index = 11+72 elif self.buf_Size <= 16: if self.buf_bitwidth <= 64: self.index = 12+72 elif self.buf_bitwidth <= 128: self.index = 13+72 elif self.buf_bitwidth <= 256: self.index = 14+72 else: self.index = 15+72 elif self.buf_Size <= 32: if self.buf_bitwidth <= 64: self.index = 16+72 elif self.buf_bitwidth <= 128: self.index = 17+72 elif self.buf_bitwidth <= 256: self.index = 18+72 else: self.index = 19+72 elif self.buf_Size <= 64: if self.buf_bitwidth <= 64: self.index = 20+72 elif self.buf_bitwidth <= 128: self.index = 21+72 elif self.buf_bitwidth <= 256: self.index = 22+72 else: self.index = 23+72 elif self.buf_Size <= 128: if self.buf_bitwidth <= 64: self.index = 24+72 elif self.buf_bitwidth <= 128: self.index = 25+72 elif self.buf_bitwidth <= 256: self.index = 26+72 else: self.index = 27+72 elif self.buf_Size <= 256: if self.buf_bitwidth <= 64: self.index = 28+72 elif self.buf_bitwidth <= 128: self.index = 29+72 elif self.buf_bitwidth <= 256: self.index = 30+72 else: self.index = 31+72 else: if self.buf_bitwidth <= 64: self.index = 32+72 elif self.buf_bitwidth <= 128: self.index = 33+72 elif self.buf_bitwidth <= 256: self.index = 34+72 else: self.index = 35+72 if buf_level == 1: self.buf_area = float(buf_config.get('Process element level', 'PE_inBuf_Area')) elif buf_level == 2: self.buf_area = float(buf_config.get('Process element level', 'Tile_outBuf_Area')) else: self.buf_area = float(buf_config.get('Process element level', 'DFU_Buf_Area')) if self.buf_area == 0: self.calculate_buf_area() # TODO: 读取文件里的rpower和wpower是否合理 self.buf_rpower = float(buf_config.get('Architecture level', 'Buffer_ReadPower')) self.buf_wpower = float(buf_config.get('Architecture level', 'Buffer_WritePower')) #self.buf_frequency = float(buf_config.get('Architecture level', 'Buffer_Frequency')) self.buf_renergy = 0 self.buf_rlatency = 0 # self.calculate_buf_read_latency() self.buf_wenergy = 0 self.buf_wlatency = 0 # self.calculate_buf_write_energy() self.dynamic_buf_rpower = 0 self.dynamic_buf_wpower = 0 self.leakage_power = 0 sram_cycle = [0.429117, 0.516288, 0.516288, -1, 0.493667, 0.513399, 0.513399, 0.731628, 0.545851, 0.545851, 0.545851, 0.73042, 0.888161, 0.888161, 0.888161, 0.880783, 0.970756, 0.970756, 0.970756, 1.77142, 1.8639, 1.8639, 1.8639, 1.8639, 2.03915, 2.03915, 2.03915, 2.03915, 5.06442, 5.06442, 5.06442, 5.06442, 5.06442, 5.06442, 5.43619, 5.43619, 0.294314, 0.354413, 0.348287, -1, 0.371007, 0.371007, 0.36528, 0.555128, 0.40418, 0.40418, 0.398423, 0.576657, 0.61696, 0.61696, 0.61696, 0.611204, 0.685607, 0.685607, 0.685607, 1.28541, 1.36208, 1.36208, 1.36208, 1.36208, 1.50531, 1.50531, 1.50531, 1.50531, 3.66005, 3.85607, 3.85607, 3.85607, 3.85607, 3.85607, 4.16804, 4.16804, 0.161935, 0.218222, 0.214715, -1, 0.220376, 0.220376, 0.217178, 0.388917, 0.240058, 0.240058, 0.398597, 0.394621, 0.419332, 0.419332, 0.419332, 0.416098, 0.459782, 0.459782, 0.459782, 1.0329, 1.08402, 1.08402, 1.08402, 1.08402, 1.17245, 1.17245, 1.17245, 1.17245, 0.546324, 0.729275, 3.45785, 3.45784, 1.17245, 3.45784, 3.45784, 3.6791 ] # uniit: ns self.buf_cycle = 20#sram_cycle[self.index] assert self.buf_cycle != -1, "Error: No available for 2KB SRAM buffer with 512-bit bus bitwidth" sram_leakage_power = [1.006428, 1.136656, 1.253224, -1, 1.95684, 2.15962, 2.28782, 2.62008, 4.1222, 4.18056, 4.3319, 4.55214, 8.86342, 9.07178, 9.65236, 11.29236, 17.46566, 17.73578, 18.44038, 19.29436, 32.1096, 32.4554, 33.348, 35.5564, 63.688, 64.1578, 65.2978, 68.0018, 121.8756, 122.4862, 126.032, 127.5844, 243.484, 244.982, 245.722, 250.266, 4.33154, 4.5899, 5.99122, -1, 7.75758, 8.25868, 9.76298, 14.09702, 14.98076, 15.5835, 17.29178, 20.9042, 26.6168, 27.3042, 29.192, 34.5, 52.3788, 53.2686, 55.5624, 58.7496, 96.3408, 97.4886, 100.408, 107.6106, 191.03, 192.5814, 196.3112, 205.136, 367.718, 367.692, 372.76, 384.374, 730.276, 735.414, 737.946, 752.802, 3.06844, 3.22544, 4.1977, -1, 5.51418, 5.85956, 6.90244, 9.92618, 10.65116, 11.06626, 11.4876, 14.86772, 19.25676, 19.72618, 21.0248, 24.6852, 37.9354, 38.5436, 40.1206, 42.1506, 69.7894, 70.5706, 72.5732, 77.5184, 138.4138, 139.4718, 142.0298, 148.0884, 299.266, 299.666, 269.828, 277.794, 551.922, 532.732, 539.688, 544.616] # unit:mW self.leakage_power = sram_leakage_power[self.index] assert self.leakage_power != -1, "Error: No available for 2KB SRAM buffer with 512-bit bus bitwidth" def calculate_buf_area(self): ''' the buf_choice is about sram or dram, the area increases as linear. :return: ''' # unit: um^2 # todo: Add DRAM parameters if self.buf_Size == 0: self.buf_area = 0 else: sram_area = [0.0405803,0.0944387,0.170796,-1,0.0686947,0.129533,0.21469158,0.544121685,0.156974886,0.199132286,0.301779123,0.629568, 0.616313686,0.781358547,1.190747266,2.277664127,1.060004216,1.271763571,1.774928364,3.368257932,1.974404875,2.239130702,2.897282324,4.503881809, 3.583918894,3.942740844,4.787940384,6.782865957,6.974574682,7.387286214,8.510494573,11.13794477,14.22112082,15.77955259,15.1903479,18.56649221, 0.069914533,0.13213,0.266413,-1,0.117554,0.172761,0.319445,0.885538,0.185984,0.253431,0.424684,0.98738, 0.321651,0.407856,0.621693,1.18947,0.552979,0.663547,0.92629, 1.75898,1.02955,1.16829,1.51204,2.35122, 1.86953,2.05688,2.49820595,3.532879835,4.110732386,3.853902632,4.440562411,5.812866337,7.345004718,8.232069955,7.924741251,9.68755797, 0.026389593,0.049106366,0.099338763,-1,0.043660718,0.064295773,0.119224229,0.333979075,0.06910098,0.094371317,0.177026169,0.372578216, 0.12167763,0.154207863,0.234897385,0.426436442,0.209317302,0.251074,0.350283787,0.664606538,0.389828369,0.442063443,0.571793236,0.88844989, 0.707812758,0.779322414,0.945248378,1.335949489,1.692348078,1.758800264,1.680181012,2.198122156,2.972110865,3.116036246,3.763339813,3.665484947] self.buf_area = sram_area[self.index]*1e6 assert self.buf_area != -1, "Error: No available for 2KB SRAM buffer with 512-bit bus bitwidth" def calculate_buf_read_power(self): ''' buf_choice buf_Size buf_Tech :return: ''' # unit: mW # todo: Add DRAM parameters if self.buf_Size == 0: self.buf_rpower = 0 else: sram_dynamic_read_energy = [0.0075695,0.0204901,0.0374838,-1,0.00854257,0.0227852,0.041063,0.12054,0.018382,0.0275777,0.0484019,0.127604, 0.044837,0.0706276,0.131809,0.295237,0.0618356,0.0943086,0.169224,0.411876,0.103042,0.14809,0.247932,0.485822, 0.156421,0.21497,0.342013,0.634498,0.27502,0.358447,0.535426,0.927837,0.356492,0.508902,0.795817,1.29724,0.00823002, 0.0183766,0.0407038,-1,0.0120839,0.0211627,0.0454619,0.137905,0.0158937,0.026906,0.0551001,0.147335,0.0248548,0.0394126, 0.0739843,0.166219,0.0349618,0.053362,0.0956746,0.232081,0.0583935,0.0838554,0.140319,0.274961,0.0905117,0.123634,0.19553, 0.361147,0.131652,0.206955,0.307099,0.52924,0.205608,0.291566,0.462242,0.746234,0.00366611,0.00805114,0.0174977,-1,0.00545155, 0.00929243,0.0195678,0.0587335,0.00717156,0.0118251,0.0272345,0.0628241,0.0113831,0.0175339,0.0321178,0.0709932,0.0160867, 0.0238524,0.0416899,0.0996046,0.0272693,0.0380164,0.0618288,0.118533,0.0426012,0.0565679,0.0868665,0.156594,0.0624646, 0.097861,0.138328,0.231921,0.0933836,0.131128,0.210481,0.330414] # unit: nJ dynamic_read_energy = sram_dynamic_read_energy[self.index] assert dynamic_read_energy != -1, "Error: No available for 2KB SRAM buffer with 512-bit bus bitwidth" self.dynamic_buf_rpower = dynamic_read_energy/self.buf_cycle*1e3 #self.dynamic_buf_rpower = 0 self.buf_rpower = self.dynamic_buf_rpower + self.leakage_power def calculate_buf_write_power(self): # unit: mW # todo: Add DRAM parameters if self.buf_Size == 0: self.buf_wpower = 0 else: sram_dynamic_write_energy = [0.0131361,0.0223358,0.0422325,-1,0.0199484,0.0271014,0.0516509,0.130038,0.0211344,0.0368348, 0.0706683,0.14878,0.0437094,0.0779207,0.155944,0.345919,0.0601423,0.109611,0.218248,0.460145,0.08827501, 0.144703,0.278356,0.583869,0.116896,0.209321,0.404114,0.8321,0.162096,0.279398,0.524128,1.05204,0.243037, 0.429853,0.775468,1.54815,0.00983737,0.0198855,0.0427535,-1,0.0129198,0.0243774,0.0516229,0.142004, 0.0177355,0.0335322,0.0694838,0.159657,0.0237539,0.0430962,0.0872368,0.194986,0.0330736,0.0610694,0.122573, 0.258586,0.0450215,0.0800791,0.155734,0.328758,0.0643685,0.116708,0.22704,0.469528,0.0950392,0.154668,0.293248, 0.592261,0.133284,0.23928,0.435794,0.873636,0.00431575,0.00864673,0.0182943,-1,0.00571403,0.0105917,0.0221228, 0.0603267,0.00778673,0.0145317,0.0298331,0.0679341,0.010522,0.0187642,0.0375312,0.0831368,0.0145269,0.0264935, 0.0527328,0.110431,0.0199489,0.0348969,0.067111,0.140623,0.0282674,0.0506538,0.0977918,0.201198,0.0595076,0.108967, 0.1265,0.253771,0.0789223,0.102461,0.198653,0.374836] # unit: nJ dynamic_write_energy = sram_dynamic_write_energy[self.index] assert dynamic_write_energy != -1, "Error: No available for 2KB SRAM buffer with 512-bit bus bitwidth" self.dynamic_buf_wpower = dynamic_write_energy / self.buf_cycle * 1e3 #self.dynamic_buf_wpower = 0 self.buf_wpower = self.dynamic_buf_wpower + self.leakage_power def calculate_buf_read_latency(self, rdata=0): # unit: ns, Byte(data) self.buf_rlatency = math.ceil(rdata*8/self.buf_bitwidth)*self.buf_cycle def calculate_buf_write_latency(self, wdata=0): # unit: ns, Byte(data) self.buf_wlatency = math.ceil(wdata*8/self.buf_bitwidth)*self.buf_cycle def calculate_buf_read_energy(self, rdata=0): # unit: nJ sram_dynamic_read_energy = [0.0075695, 0.0204901, 0.0374838, -1, 0.00854257, 0.0227852, 0.041063, 0.12054, 0.018382, 0.0275777, 0.0484019, 0.127604, 0.044837, 0.0706276, 0.131809, 0.295237, 0.0618356, 0.0943086, 0.169224, 0.411876, 0.103042, 0.14809, 0.247932, 0.485822, 0.156421, 0.21497, 0.342013, 0.634498, 0.27502, 0.358447, 0.535426, 0.927837, 0.356492, 0.508902, 0.795817, 1.29724, 0.00823002, 0.0183766, 0.0407038, -1, 0.0120839, 0.0211627, 0.0454619, 0.137905, 0.0158937, 0.026906, 0.0551001, 0.147335, 0.0248548, 0.0394126, 0.0739843, 0.166219, 0.0349618, 0.053362, 0.0956746, 0.232081, 0.0583935, 0.0838554, 0.140319, 0.274961, 0.0905117, 0.123634, 0.19553, 0.361147, 0.131652, 0.206955, 0.307099, 0.52924, 0.205608, 0.291566, 0.462242, 0.746234, 0.00366611, 0.00805114, 0.0174977, -1, 0.00545155, 0.00929243, 0.0195678, 0.0587335, 0.00717156, 0.0118251, 0.0272345, 0.0628241, 0.0113831, 0.0175339, 0.0321178, 0.0709932, 0.0160867, 0.0238524, 0.0416899, 0.0996046, 0.0272693, 0.0380164, 0.0618288, 0.118533, 0.0426012, 0.0565679, 0.0868665, 0.156594, 0.0624646, 0.097861, 0.138328, 0.231921, 0.0933836, 0.131128, 0.210481, 0.330414] # unit: nJ dynamic_read_energy = sram_dynamic_read_energy[self.index] assert dynamic_read_energy != -1, "Error: No available for 2KB SRAM buffer with 512-bit bus bitwidth" self.buf_renergy = (dynamic_read_energy+self.buf_cycle*self.leakage_power/1e3)*math.ceil(rdata*8/self.buf_bitwidth) def calculate_buf_write_energy(self, wdata=0): # unit: nJ sram_dynamic_write_energy = [0.0131361, 0.0223358, 0.0422325, -1, 0.0199484, 0.0271014, 0.0516509, 0.130038, 0.0211344, 0.0368348, 0.0706683, 0.14878, 0.0437094, 0.0779207, 0.155944, 0.345919, 0.0601423, 0.109611, 0.218248, 0.460145, 0.08827501, 0.144703, 0.278356, 0.583869, 0.116896, 0.209321, 0.404114, 0.8321, 0.162096, 0.279398, 0.524128, 1.05204, 0.243037, 0.429853, 0.775468, 1.54815, 0.00983737, 0.0198855, 0.0427535, -1, 0.0129198, 0.0243774, 0.0516229, 0.142004, 0.0177355, 0.0335322, 0.0694838, 0.159657, 0.0237539, 0.0430962, 0.0872368, 0.194986, 0.0330736, 0.0610694, 0.122573, 0.258586, 0.0450215, 0.0800791, 0.155734, 0.328758, 0.0643685, 0.116708, 0.22704, 0.469528, 0.0950392, 0.154668, 0.293248, 0.592261, 0.133284, 0.23928, 0.435794, 0.873636, 0.00431575, 0.00864673, 0.0182943, -1, 0.00571403, 0.0105917, 0.0221228, 0.0603267, 0.00778673, 0.0145317, 0.0298331, 0.0679341, 0.010522, 0.0187642, 0.0375312, 0.0831368, 0.0145269, 0.0264935, 0.0527328, 0.110431, 0.0199489, 0.0348969, 0.067111, 0.140623, 0.0282674, 0.0506538, 0.0977918, 0.201198, 0.0595076, 0.108967, 0.1265, 0.253771, 0.0789223, 0.102461, 0.198653, 0.374836] # unit: nJ dynamic_write_energy = sram_dynamic_write_energy[self.index] assert dynamic_write_energy != -1, "Error: No available for 2KB SRAM buffer with 512-bit bus bitwidth" self.buf_wenergy = (dynamic_write_energy + self.buf_cycle * self.leakage_power / 1e3) * math.ceil( wdata * 8 / self.buf_bitwidth) def buf_output(self): if self.buf_choice == -1: print("buf_choice: User defined") else: print("buf_choice:", self.buf_choice) print("buf_Size:", self.buf_Size, "bytes") print("buf_Tech:", self.buf_Tech, "nm") print("buf_area:", self.buf_area, "um^2") print("buf_read_power:", self.buf_rpower, "W") print("buf_dynamic_rpower:", self.dynamic_buf_rpower, "mW") print("buf_read_energy:", self.buf_renergy, "nJ") print("buf_read_latency:", self.buf_rlatency, "ns") print("buf_write_power:", self.buf_wpower, "W") print("buf_dynamic_wpower:", self.dynamic_buf_wpower, "mW") print("buf_write_energy:", self.buf_wenergy, "nJ") print("buf_leakage_power:", self.leakage_power, "mW") print("buf_write_latency:", self.buf_wlatency, "ns") def buf_test(): print("load file:", test_SimConfig_path) _buf = buffer(test_SimConfig_path) _buf.calculate_buf_area() _buf.calculate_buf_read_power() _buf.calculate_buf_read_latency() _buf.calculate_buf_read_energy() _buf.calculate_buf_write_power() _buf.calculate_buf_write_latency() _buf.calculate_buf_write_energy() _buf.buf_output() if __name__ == '__main__': buf_test()
334a56435c432d7d152bed26840bc0365da0322f
[ "Markdown", "Python", "INI" ]
33
Python
Zhu-Zhenhua/MNSIM_Python
7642c52c80c26a8e02a665dca9ada2db1a15d220
0abb288c97c4e4121a7021e9e2866bcf63c58132
refs/heads/main
<repo_name>BeSketens/carwash<file_sep>/client.lua carwashStations = { {26.5906, -1392.0261, 28.3634}, {167.1034, -1719.4704, 28.4}, {-74.5693, 6427.8715, 30.5}, {-699.6325, -932.7043, 18.1}, {1362.5385, 3592.1274, 34.0} } Citizen.CreateThread(function() Citizen.Wait(0) for i = 1, #carwashStations do local coords = carwashStations[i] addBlip("Carwash",coords[1],coords[2],coords[3]) end while true do local interval = 1 if IsPedInAnyVehicle(PlayerPedId(), false) then local pedPosition = GetEntityCoords(PlayerPedId()) for i = 1, #carwashStations do cwCoords = carwashStations[i] local distance = GetDistanceBetweenCoords(pedPosition, cwCoords[1], cwCoords[2], cwCoords[3], true) if distance <= 45 then DrawMarker(25, cwCoords[1], cwCoords[2], cwCoords[3], 0.0, 0.0, 0.0, 0.0, 180.0, 0.0, 4.5, 4.5, 0, 0, 255, 0, 255, false, false, 2, true, nil, false) local veh = GetVehiclePedIsIn(PlayerPedId(), false) if distance < 2 and GetPedInVehicleSeat(veh, -1) then AddTextEntry("HELP", 'Appuyez sur ~INPUT_PICKUP~ pour laver votre véhicule') DisplayHelpTextThisFrame('HELP', false) if IsControlJustPressed(1, 38) then SetVehicleDirtLevel(veh, 0.0) end end end end else interval = 1000 end Wait(interval) end end) ----- Functions ------ function addBlip(name, x, y, z) local blip = AddBlipForCoord(x,y,z) SetBlipSprite(blip, 100) SetBlipColour(blip, 25) SetBlipAsShortRange(blip, true) BeginTextCommandSetBlipName('STRING') AddTextComponentString(name) EndTextCommandSetBlipName(blip) SetBlipDisplay(blip, 2) end<file_sep>/README.md # carwash Script carwash non-esx pour le moment. Possède 5 lieux différents, les marqueurs n'aparaissent qu'à 45m de distance de l'un des lieux possible Performances : -> à pieds ~ statique : 0.00 ms -> à pieds ~ mobile : atteint rarement 0.01 ms -> en voiture : entre 0.02 et 0.03 ms -> dans la portée d'apparition du marker : 0.03 ms -> affichage de l'option pour nettoyer : 0.04 ms
dfb62e1b6ce9526dc5a0454a0858772a16ca33da
[ "Markdown", "Lua" ]
2
Lua
BeSketens/carwash
97466576b5c24bf0e5b4c585cae610ee79dbad2d
b77f2e374ed45f941d66d91776f055179a1431a8
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> /* */ typedef struct Pairs{ float fahrenheit; float celsius; }pair; /* */ typedef struct _list{ pair *previous; pair *next; }details; /* */ typedef struct List{ pair *first; details *details; pair *last; int number_of_pairs; }list_of_pairs; /* */ void temperature_one(int step, int times, float initial_value, char scale); list_of_pairs *temperature_two(list_of_pairs *t, int step, int times, float initial_value, char scale); /* */ int main() { temperature_one(10, 10, 10, 'F'); temperature_one(10, 10, -12.22, 'C'); list_of_pairs *list; list = NULL; list = temperature_two(list, 10, 10, 10, 'F'); return 0; } /* */ void temperature_one(int step, int times, float initial_value, char input_scale) { int c; float formula; for(c = 0 ;c < times; c++) { if(input_scale=='F'){ formula = 5.0/9 * (initial_value - 32); } else if(input_scale == 'C'){ formula = 32 + 9.0/5.0*initial_value; } else{ break; } printf("%6.1f, %6.1f\n", initial_value, formula); initial_value += step; } } /* */ list_of_pairs *temperature_two(list_of_pairs *t, int step, int times, float initial_value, char input_scale){ int c; float formula; pair *tmp_pair; details *tmp_details; tmp_pair = NULL; t = malloc(sizeof(list_of_pairs)); t->first = NULL; t->details->previous = NULL; t->details->next = NULL; t->last = NULL; for(c = 0 ;c < times; c++) { tmp_pair = malloc(sizeof(pair)); if(t->first == NULL){ t->first = tmp_pair; t->last == tmp_pair; } /* */ if(input_scale=='F'){ formula = 5.0/9 * (initial_value - 32); } else if(input_scale == 'C'){ formula = 32 + 9.0/5.0*initial_value; } else{ t->first = NULL; t->last = NULL; free(tmp_pair); free(t); t = NULL; break; } /* */ t->number_of_pairs = c; initial_value += step; } return t; }
a0359bec573700253a88af3c870ce0bbd1cb5c8c
[ "C" ]
1
C
metajemo/Basic_C_Course
e8c3a164569abb2f1f6575fbb120578dd2a59019
e35948f395ad3f3a1f4b2ed892793630599a3ea1
refs/heads/master
<file_sep>package com.stackroute.websocketspringboot.config; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @Configuration //enables message broker and by default spring uses STOMP as a message broker. @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { /*enables a simple memory-based message broker to carry the messages back to the client on destinations prefixed with /chat i.e. url will be http://localhost:8080/app */ @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.setApplicationDestinationPrefixes("/app"); registry.enableSimpleBroker("/chat"); } /* enables STOMP support and registers stomp end points at /broadcasting i.e. url will be http://localhost:8080/socket */ @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/broadcasting").setAllowedOrigins("http://localhost:4200").withSockJS(); } } <file_sep>package com.stackroute.websocketspringboot.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import java.text.SimpleDateFormat; import java.util.Date; @Controller public class WebSocketController { private final SimpMessagingTemplate messagingTemplate; @Autowired public WebSocketController(SimpMessagingTemplate messagingTemplate) { this.messagingTemplate = messagingTemplate; } /*This is to map the message headed for the url /message. So, the client should send the message at /message as per our WebSocket config */ @MessageMapping("/send/message") //Message mapping in web socket is same as Request mapping in rest controller public void processMessageFromClient(String message) { this.messagingTemplate.convertAndSend("/chat",new SimpleDateFormat("HH:mm:ss") .format(new Date())+" "+ message); } }
526e6d13176f96a49b8821981b6b1b09a2b9ac76
[ "Java" ]
2
Java
raju-kr50/POC_Websocket
5f58b334e48f63860749734476c87e62846d045c
7003c46bfbb92c4fbc4c923ccf2bb3b91f7c3b44
refs/heads/main
<repo_name>cypherpoll-0/netflix-clone<file_sep>/src/components/player/styles/player.js import styled from 'styled-components/macro' export const Container = styled.div``; export const Overlay = styled.div` display: flex; flex-direction: column; justify-content: center; position: fixed; top: 0; bottom: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); margin: 0 20px; `; export const Inner = styled.div` position: relative; width: 100%; max-width: 900px; margin: auto; video { height: 100%; width: 100%; } `; export const Close = styled.button` position: absolute; right: 15px; top: 15px; width: 22px; height: 22px; opacity: 0.3; background-color: transparent; border: 0; cursor: pointer; &:hover { opacity: 1; } &:before, &:after { position: absolute; left: 10px; top: 0; content: ' '; height: 22px; width: 2px; background-color: #333; } &:before { transform: rotate(45deg); } &:after { transform: rotate(-45deg); } `; export const Button = styled.button` box-shadow: 0 0.6vw 1vw -0.4vw rgba(0,0,0,0.35); background-color: #e6e6e6; color: #000; border-width: 0; font-weight: bold; padding: 10px 20px; border-radius: 5px; max-width: 130px; font-size: 20px; margin-top: 30px; transition: background-color 0.2s; cursor: pointer; &:hover { background-color: #ff1e1e; color: white; } `; <file_sep>/src/lib/firebase.prod.js import Firebase from 'firebase/app' import 'firebase/firestore' import 'firebase/auth' const config = { apiKey: "<KEY>", authDomain: "netflix-clone-92e2a.firebaseapp.com", projectId: "netflix-clone-92e2a", storageBucket: "netflix-clone-92e2a.appspot.com", messagingSenderId: "516747497015", appId: "1:516747497015:web:92a8a48cc05e0e990db9b2" } const firebase = Firebase.initializeApp(config) export { firebase };
e4c996215774cdf954a6f3df21e2812dd1f76cba
[ "JavaScript" ]
2
JavaScript
cypherpoll-0/netflix-clone
e523b2a36f13df8c9e64c383ffe8866c1d6e26ee
8460fa4c97d29b0a10bc23c4fb0153ab852df1b4
refs/heads/master
<file_sep>module Amakanize class AuthorName class << self # @return [Array<Amakan::Filters::BaseFilter>] def filters @filters ||= [ ::Amakanize::Filters::HtmlUnescapeFilter.new, ::Amakanize::Filters::NormalizationFilter.new, ::Amakanize::Filters::HyphenMinusNormalizationFilter.new, ::Amakanize::Filters::ParenthesesDeletionFilter.new, ::Amakanize::Filters::RoleNameDeletionFilter.new, ::Amakanize::Filters::TrailingAuthorNamePayloadDeletionFilter.new, ::Amakanize::Filters::SpaceDeletionFilter.new, ] end end # @param raw [String] def initialize(raw) @raw = raw end # @note Override def to_s self.class.filters.inject(@raw) do |result, filter| filter.call(result) end end end end <file_sep>module Amakanize module Filters class RoleNameDeletionFilter < BaseFilter ROLE_NAMES = %w( 原作 原案 漫画 ) # @note Override # @param string [String] e.g. `"漫画:ハノカゲ"` # @return [String] e.g. `"ハノカゲ"` def call(string) string.gsub(%r<\A#{::Regexp.union(ROLE_NAMES)}[:/]>, "").gsub(%r<[:/]#{::Regexp.union(ROLE_NAMES)}\z>, "") end end end end <file_sep>module Amakanize module Filters class TrailingSurroundingHyphensDeletionFilter < BaseFilter # @note Override # @param string [String] e.g. `"艦隊これくしょん -艦これ- 島風 つむじ風の少女"` # @return [String] e.g. `"艦隊これくしょん"` def call(string) string.gsub(/\s*-.+-.*/, "") end end end end <file_sep>module Amakanize module Filters class ParenthesesDeletionFilter < BaseFilter # @note Override # @param string [String] e.g. `"ぽんかん(8)"` # @return [String] e.g. `"ぽんかん8"` def call(string) string.gsub(/\((\d+)\)/, '\1') end end end end <file_sep>module Amakanize module Filters class BaseFilter # @param string [String] # @return [String] def call(string) raise ::NotImplementedError end end end end <file_sep>require "amakanize/author_name" require "amakanize/author_names" require "amakanize/filters/base_filter" require "amakanize/filters/angle_brackets_after_word_normalization_filter" require "amakanize/filters/dash_between_alphabets_normalization_filter" require "amakanize/filters/html_unescape_filter" require "amakanize/filters/hyphen_minus_normalization_filter" require "amakanize/filters/normalization_filter" require "amakanize/filters/obvious_volume_number_deletion_filter" require "amakanize/filters/parentheses_deletion_filter" require "amakanize/filters/role_name_deletion_filter" require "amakanize/filters/space_deletion_filter" require "amakanize/filters/spaces_between_exclamations_deletion_filter" require "amakanize/filters/strip_filter" require "amakanize/filters/trailing_author_name_payload_deletion_filter" require "amakanize/filters/trailing_dash_deletion_filter" require "amakanize/filters/trailing_parentheses_deletion_filter" require "amakanize/filters/trailing_series_name_payload_deletion_filter" require "amakanize/filters/trailing_surrounding_hyphens_deletion_filter" require "amakanize/filters/trailing_volume_number_deletion_filter" require "amakanize/series_name" require "amakanize/version" module Amakanize PATTERN_OF_NUMERIC_CHARACTER = /[\diIvVxX1-9①②③④⑤⑥⑦⑧⑨⑩〇一二三四五六七八九十百千万零壱弍参肆伍陸漆捌玖壹貳參拾佰仟萬]/ end <file_sep>require "active_support" module Amakanize module Filters class NormalizationFilter < BaseFilter # @note Override # @param string [String] e.g. `"ぽんかん(8)"`, `"ぽんかん⑧"` # @return [String] e.g. `"ぽんかん(8)"`, `"ぽんかん8"` def call(string) ::ActiveSupport::Multibyte::Unicode.normalize(string) end end end end <file_sep>module Amakanize module Filters class SpacesBetweenExclamationsDeletionFilter < BaseFilter # @note Override # @param string [String] e.g. `"ばくおん! !"` # @return [String] e.g. `"ばくおん!!"` def call(string) string.gsub(/!\s+!/, "!!") end end end end <file_sep>module Amakanize module Filters class DashBetweenAlhabetsNormalizationFilter < BaseFilter # @note Override # @param string [String] e.g. `"D.Grayーman"` # @return [String] e.g. `"D.Gray-man"` def call(string) string.gsub(/(\w)ー(\w)/, '\1-\2') end end end end <file_sep>module Amakanize module Filters class SpaceDeletionFilter < BaseFilter # @note Override # @param string [String] e.g. `"渡 航"` # @return [String] e.g. `"渡航"` def call(string) string.gsub(/\s+/, "") end end end end <file_sep>## 0.2.0 - Fix author name separator ## 0.1.12 - Support 第N版 ## 0.1.11 - Improve volume detection for アニウッド大通り ## 0.1.10 - Detect obvious volume number in product title ## 0.1.9 - Normalize hyphen with hyphen/minus ## 0.1.8 - Normalize hyphen between alphabets in series name ## 0.1.7 - Remove trailing surrounding hyphens and payload on series name ## 0.1.6 - Remove trailing dash and payload on series name ## 0.1.5 - Remove spaces between exclamations for 「ばくおん! !」 ## 0.1.4 - Add more author name separator - Remove suffix role name ## 0.1.3 - Remove trailing 原作・原案・漫画 of author name ## 0.1.2 - Add AuthorNames class ## 0.1.1 - Support x and X as roman numeric ## 0.1.0 - Support roman numerals on series name - Support 第N巻 on series name - Normalize series name ## 0.0.4 - Normalize all characters ## 0.0.3 - Remove space from author name ## 0.0.2 - Remove parentheses of numericals in author name - Remove role name from author name - Remove trailing payload from author name - Strip author name - Unescape HTML in author name ## 0.0.1 - 1st release :tada: <file_sep>module Amakanize module Filters class AngleBracketsAfterWordNormalizationFilter < BaseFilter # @note Override # @param string [String] e.g. `"IS〈インフィニット・ストラトス〉 1 (オーバーラップ文庫)"` # @return [String] e.g. `"IS<インフィニット・ストラトス> 1 (オーバーラップ文庫)"` def call(string) string.gsub(/([[:alnum:]])[〈《](.+?)[〉》]/, '\1<\2>') end end end end <file_sep>module Amakanize module Filters class ObviousVolumeNumberDeletionFilter < BaseFilter # @note Override # @param string [String] e.g. `"刀語 第十一話 毒刀・鍍"`, `"アニウッド大通り 1: アニメ監督一家物語"` # @return [String] e.g. `"刀語"`, `"アニウッド大通り"` def call(string) string.gsub(/\s*第?#{Amakanize::PATTERN_OF_NUMERIC_CHARACTER}+(?:話|巻|版).*/, "") .gsub(/\s+第?#{Amakanize::PATTERN_OF_NUMERIC_CHARACTER}+(?:話|巻|版)?:\s+.*/, "") end end end end <file_sep>module Amakanize module Filters class TrailingVolumeNumberDeletionFilter < BaseFilter # @note Override # @param string [String] e.g. `"やはり俺の青春ラブコメはまちがっている。4"` # @return [String] e.g. `"やはり俺の青春ラブコメはまちがっている。"` def call(string) string.gsub(/\s*第?#{Amakanize::PATTERN_OF_NUMERIC_CHARACTER}+(?:話|巻|版)?\z/, "") end end end end <file_sep>RSpec.describe Amakanize::SeriesName do let(:series_name) do described_class.new(raw) end describe "#to_s" do subject do series_name.to_s end { "IS〈インフィニット・ストラトス〉 1 (オーバーラップ文庫)" => "IS<インフィニット・ストラトス>", "IS<インフィニット・ストラトス>9 (オーバーラップ文庫)" => "IS<インフィニット・ストラトス>", "聖剣使いの禁呪詠唱〈ワールドブレイク〉 (GA文庫)" => "聖剣使いの禁呪詠唱<ワールドブレイク>", "聖剣使いの禁呪詠唱<ワールドブレイク> 4 (GA文庫)" => "聖剣使いの禁呪詠唱<ワールドブレイク>", "聖剣使いの禁呪詠唱《ワールドブレイク》10 (GA文庫)" => "聖剣使いの禁呪詠唱<ワールドブレイク>", "JavaScript 第6版" => "JavaScript", "D.Gray-man 25 (ジャンプコミックス)" => "D.Gray-man", "D.Gray‐man (4) (ジャンプ・コミックス)" => "D.Gray-man", "D.Grayーman 10 (ジャンプコミックス)" => "D.Gray-man", "To LOVEる -とらぶる- ダークネス" => "To LOVEる", "To LOVEる -とらぶる-" => "To LOVEる", "アド・アストラ 1 ─スキピオとハンニバル─ (ヤングジャンプコミックス・ウルトラ)" => "アド・アストラ", "アド・アストラ 2―スキピオとハンニバル (ヤングジャンプコミックス・ウルトラ)" => "アド・アストラ", "アニウッド大通り 1: アニメ監督一家物語" => "アニウッド大通り", "なれる!SE 2週間でわかる?SE入門 (電撃文庫)" => "なれる!SE 2週間でわかる?SE入門", "ばくおん! ! (7)(ヤングチャンピオン烈コミックス)" => "ばくおん!!", "やはり俺の青春ラブコメはまちがっている。4" => "やはり俺の青春ラブコメはまちがっている。", "ラブライブ! School idol diary ~星空凛~" => "ラブライブ! School idol diary", "僕だけがいない街 (1) (カドカワコミックス・エース)" => "僕だけがいない街", "冴えない彼女の育てかた (9)" => "冴えない彼女の育てかた", "刀語 第十一話 毒刀・鍍 (ドクトウ・メッキ) (講談社BOX)" => "刀語", "東京レイヴンズEX1party in nest" => "東京レイヴンズEX1party in nest", "白騎士物語-episode.0-ドグマ戦記" => "白騎士物語", "神さまのいない日曜日VII (富士見ファンタジア文庫)" => "神さまのいない日曜日", "艦隊これくしょん -艦これ- 島風 つむじ風の少女" => "艦隊これくしょん", "達人伝 -9万里を風に乗り-(3) (アクションコミックス)" => "達人伝", "魔法使いの嫁 4巻" => "魔法使いの嫁", "魔法使いの嫁 第4巻" => "魔法使いの嫁", "魔法使いの嫁 通常版 4 (BLADE COMICS)" => "魔法使いの嫁", }.each do |book_name, expected_series_name| context "with #{book_name.inspect}" do let(:raw) do book_name end it { is_expected.to eq expected_series_name } end end end end <file_sep>module Amakanize module Filters class TrailingDashDeletionFilter < BaseFilter TOKENS = %w( ̃ ̰ ̴ ‒ – — ― ⁓ 〜 〰 ˜ ˷ ~ ~ ∼ ─ ) # @note Override # @param string [String] e.g. `"アド・アストラ 1 ─スキピオとハンニバル─"` # @return [String] e.g. `"アド・アストラ 1"` def call(string) string.gsub(/\s*#{::Regexp.union(TOKENS)}.*/, "") end end end end <file_sep>module Amakanize module Filters class TrailingParenthesesDeletionFilter < BaseFilter # @note Override # @param string [String] e.g. `"魔法使いの嫁 通常版 4 (BLADE COMICS)"` # @return [String] e.g. `"魔法使いの嫁 通常版 4"` def call(string) string.gsub(/\s*[\((〈《【「『【[\[〔{\{«‹〘〚].*/, "").gsub(/\s*~.+~\z/, "") end end end end <file_sep>module Amakanize module Filters class TrailingSeriesNamePayloadDeletionFilter < BaseFilter PAYLOADS = %w( 通常版 ) # @note Override # @param string [String] e.g. `"魔法使いの嫁 通常版"` # @return [String] e.g. `"魔法使いの嫁"` def call(string) string.gsub(/\s+#{::Regexp.union(PAYLOADS)}\z/, "") end end end end <file_sep>require "cgi" module Amakanize module Filters class HtmlUnescapeFilter < BaseFilter # @note Override # @param string [String] e.g. `"&lt;ハノカゲ&gt;"` # @return [String] e.g. `"ハノカゲ"` def call(string) ::CGI.unescapeHTML(string) end end end end <file_sep>module Amakanize module Filters class StripFilter < BaseFilter # @note Override # @param string [String] e.g. `"  ハノカゲ  "` # @return [String] e.g. `"ハノカゲ"` def call(string) string.strip end end end end <file_sep>module Amakanize module Filters class HyphenMinusNormalizationFilter < BaseFilter # @note Override # @note Replace U+2010 (hyphen) with U+002D (hyphen/minus) # @param string [String] e.g. `"D.Gray‐man"` # @return [String] e.g. `"D.Gray-man"` def call(string) string.gsub("‐", "-") end end end end
cf0188aa9363be9b59c000c6db0ef8f510079bf1
[ "Markdown", "Ruby" ]
21
Ruby
iwazer/amakanize
1f9d3d33875b4c21c1030875d4cbc8bea8e5411f
8c9ef045b6c8148a153e11ad721404d1fb9a6026
refs/heads/master
<file_sep>package oauth import ( "net/http" "golang.org/x/oauth2" ) // Oauth 授权接口 type Oauth interface { Authorize() string Callback(code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error) Client(token *oauth2.Token) *http.Client } <file_sep># oauth ## 实现的平台 - Github <file_sep>module github.com/wychl/oauth go 1.14 require ( github.com/gin-gonic/gin v1.6.3 github.com/rs/xid v1.2.1 golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d ) <file_sep>package main import ( "net/http" "os" "github.com/wychl/oauth" "github.com/gin-gonic/gin" "golang.org/x/oauth2" "golang.org/x/oauth2/github" ) var conf = &oauth2.Config{ ClientID: os.Getenv("CLIENT_ID"), ClientSecret: os.Getenv("CLIENT_SECRET"), Endpoint: github.Endpoint, RedirectURL: os.Getenv("REDIRECT_URL"), Scopes: []string{}, } var oathClient oauth.Oauth = oauth.New(conf) func main() { router := gin.Default() router.GET("/auth", auth) router.GET("/token", token) http.ListenAndServe(":9999", router) } func auth(c *gin.Context) { uri := oathClient.Authorize() c.Redirect(http.StatusSeeOther, uri) } func token(c *gin.Context) { code := c.Query("code") state := c.Query("state") var ( token *oauth2.Token err error ) token, err = oathClient.Callback(code, oauth2.SetAuthURLParam("state", state)) if err != nil { c.JSON(http.StatusUnauthorized, map[string]interface{}{ "code": 1, "resp": err, }) return } c.JSON(http.StatusOK, token) } // authorize http://localhost:9999/auth <file_sep>package oauth import ( "context" "net/http" "time" "github.com/rs/xid" "golang.org/x/oauth2" ) // Github oauth impl type Github struct { conf *oauth2.Config } var _ Oauth = &Github{} // New Oauth instance func New(conf *oauth2.Config) *Github { return &Github{ conf: conf, } } // Authorize Oauth Impl func (o *Github) Authorize() string { state := xid.New().String() return o.conf.AuthCodeURL(state, oauth2.AccessTypeOffline) } // Callback Oauth Impl func (o *Github) Callback(code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error) { ctx := context.Background() httpClient := &http.Client{Timeout: 2 * time.Second} ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient) return o.conf.Exchange(ctx, code, opts...) } // Client Oauth Impl func (o *Github) Client(token *oauth2.Token) *http.Client { return o.conf.Client(context.Background(), token) }
011e3e8092c34888d5996491c772e23df78162e6
[ "Markdown", "Go Module", "Go" ]
5
Go
wychl/oauth
ada663c1702038660a79110b7cb41097e5fac4ec
8b00d42f6aae91e1bdf0848e7e9ab929e3b285b0
refs/heads/master
<repo_name>metaflow/ohmyzsh<file_sep>/themes/meta.zsh-theme # Git-centric variationurs at most once. ZSH_THEME_GIT_PROMPT_ADDED="%{$fg[green]%}+" ZSH_THEME_GIT_PROMPT_MODIFIED="%{$fg[magenta]%}!" ZSH_THEME_GIT_PROMPT_DELETED="%{$fg[red]%}-" ZSH_THEME_GIT_PROMPT_RENAMED="%{$fg[blue]%}>" ZSH_THEME_GIT_PROMPT_UNMERGED="%{$fg[cyan]%}#" ZSH_THEME_GIT_PROMPT_UNTRACKED="%{$fg[yellow]%}?" ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg[yellow]%}" ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%} " ZSH_THEME_GIT_PROMPT_DIRTY="%{$fg[green]%}%{$fg[yellow]%}*%{$fg[green]%}%{$reset_color%}" ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg[green]%}" function citc_prompt_info() { local working_dir=`pwd` if [[ $working_dir == "/google/src/cloud/$USER/"* ]]; then path_array=(${(ps:/:)${working_dir}}) printf "%%{$fg[yellow]%%}(%s)%%{$reset_color%%}" $path_array[5] fi } return_code_enabled="%(?..%{$fg_bold[red]%}%? )%{$reset_color%}" return_code_disabled="" return_code=$return_code_enabled local user_color='green' test $UID -eq 0 && user_color='red' PROMPT='${return_code} %T %{$fg[$user_color]%}%~%{$reset_color%} $(git_prompt_info)$(citc_prompt_info)'\ '%(!.#.) ' # PROMPT2='%{$fg[red]%}\ %{$reset_color%}' # RPS1='${return_code}'
3d6fa984e0a03267535afbf0d0b2fb07fc725f8a
[ "Shell" ]
1
Shell
metaflow/ohmyzsh
6104322f90abf3ac9c73dd832334b5ca1077d5fb
bcb129b79d087853dedaba0064cecc96d58be933
refs/heads/main
<file_sep>using AttackTypeDefine; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using DG.Tweening; public class AnimCtrl : MonoBehaviour { #region System Functions public Vector2[] AnimPerArray; public Vector2[] AnimSkillPerArray; public UI_JoyStick joyStickInst; FinalSkillBtn FinalSkillInst; AnimatorManger AnimMgr; Animator _Anim; public Animator Anim => (_Anim); int _CurAnimAttackIndex = 1; int MinAnimAttackIndex = 1; int MaxAnimAttackIndex = 3; bool IsReady = true; Sword SwordInst; Camera Cam; eSkillType SkillTypes; bool _IsPlaying; public bool IsPlaying => (_IsPlaying); string CurrAnimname; string AttackPre = "Base Layer.Attack"; string SkillPre = "Base Layer.Skill"; string SkillPrePath = "Skills/"; private void Awake() { AnimMgr = gameObject.AddComponent<AnimatorManger>(); } private void Start() { _Anim = GetComponent<Animator>(); AnimMgr.OnStart(this); FinalSkillInst = joyStickInst.FinalSkillBtnInst; Cam = Camera.main; var weaponGo = GlobalHelper.FindGOByName(gameObject, "greatesword"); if (null != weaponGo) { SwordInst = weaponGo.GetComponent<Sword>(); SwordInst.OnStart(this); } joyStickInst.FinalSkillBtnInst.PressDown.AddListener((a) => FinalSkillBegin(a)); joyStickInst.FinalSkillBtnInst.OnDragEvent.AddListener((a) => OnFinalSkillDrag(a)); joyStickInst.FinalSkillBtnInst.PressUp.AddListener((a) => OnFinalSkillEnd(a)); LoadFinalSkillArrow(); } private void Update() { UpdateSkillInput(); } #endregion #region Cast Attack void UpdateSkillInput() { #if UNITY_EDITOR if (Input.GetKeyDown(KeyCode.K)) { CastSkill(eSkillType.eAttack); } #else #endif } void CastSkill(eSkillType type) { if (!IsReady) { return; } SkillTypes = type; if (type == eSkillType.eSkill1) { CurrAnimname = SkillPre + ((int)SkillTypes).ToString(); } else if (type == eSkillType.eAttack) { //Debug.Log("Animate Control : CastSkill"); if (_CurAnimAttackIndex > MaxAnimAttackIndex) { _CurAnimAttackIndex = MinAnimAttackIndex; } CurrAnimname = AttackPre + _CurAnimAttackIndex.ToString(); } //Debug.Log(CurrAnimname); AnimMgr.StartAnimation(CurrAnimname, CastSkillReady, CastSkillBegin, CastSkillEnd, CastSkillEnd1); } void CastSkillReady() { IsReady = true; //Debug.Log("CastSkillReady"); } void CastSkillBegin() { _IsPlaying = true; var item = Vector2.zero; if (SkillTypes == eSkillType.eAttack) { IsReady = false; //load animateor //calculate current index of attack item = AnimPerArray[_CurAnimAttackIndex - 1]; SwordInst.OnStartWeaponCtrl(Anim, item.x, item.y); //Debug.Log(_CurAnimAttackIndex); if (_CurAnimAttackIndex == MinAnimAttackIndex) { //Debug.Log("START Reset"); StartCoroutine("AttackPeriod"); } else if (_CurAnimAttackIndex == MaxAnimAttackIndex) { StopCoroutine("AttackPeriod"); } _CurAnimAttackIndex++; // Load Effects // make rules about how to combine your effect with the animation. var path = SkillPrePath + (1000 + _CurAnimAttackIndex - 1).ToString(); var SkillPrefab = GlobalHelper.InstantiateMyPrefab(path, transform.position - Vector3.up* 0.5f, Quaternion.identity ); var SkillInfo = SkillPrefab.GetComponent<SIAction_SkillInfo>(); SkillInfo.SetOwner(gameObject); //attack more times } else if (SkillTypes == eSkillType.eSkill1) { item = AnimSkillPerArray[(int)(SkillTypes - 1)]; SwordInst.OnStartWeaponCtrl(Anim, item.x, item.y); } } void CastSkillEnd() { _IsPlaying = false; if (SkillTypes == eSkillType.eAttack) { if (_CurAnimAttackIndex > MaxAnimAttackIndex) { _CurAnimAttackIndex = MinAnimAttackIndex; } //_CurAnimAttackIndex = MinAnimAttackIndex; } } void CastSkillEnd1() { /* if (_CurAnimAttackIndex <= 1) { return; } var item = AnimPerArray[_CurAnimAttackIndex - 2]; SwordInst.OnStartWeaponCtrl(Anim, item.x, item.y); */ } IEnumerator AttackPeriod() { yield return new WaitForSeconds(2.0f); _CurAnimAttackIndex = MinAnimAttackIndex; Debug.Log("Reset"); } #endregion #region Final Skill Vector3 FinalSkillDir; bool IsUsingAbility = false; bool IsFinishFinalSkill = false; public float FinalSkillDis = 1.0f; public void OnModifyFSvalue(int value) { //increase vage value joyStickInst.OnModifyFSV(value); } public void FinalSkillBegin(PointerEventData data) { if (IsUsingAbility) { return; } IsFinishFinalSkill = true ; IsUsingAbility = true; Time.timeScale = 0.1f; _GroundArrow.SetActive(true); var dir = FinalSkillInst.Dir.x* Cam.transform.right + FinalSkillInst.Dir.y * Cam.transform.forward; dir.y = 0f; if (dir == Vector3.zero) { dir = transform.forward; } _GroundArrow.transform.forward = dir; } public void OnFinalSkillDrag(PointerEventData data) { if (!IsFinishFinalSkill) { return; } FinalSkillDir = FinalSkillInst.Dir.x * Cam.transform.right + FinalSkillInst.Dir.y * Cam.transform.forward; FinalSkillDir.y = 0f; if (FinalSkillDir == Vector3.zero) { FinalSkillDir = transform.forward; } _GroundArrow.transform.forward = FinalSkillDir; } public void OnFinalSkillEnd(PointerEventData data) { if (!IsFinishFinalSkill) { return; } Time.timeScale = 1f; OnModifyFSvalue(-100); _GroundArrow.SetActive(false); FinalSkillDir = Vector3.zero; //play the skill animation CastSkill(eSkillType.eSkill1); var FinalPos = transform.position + _GroundArrow.transform.forward * FinalSkillDis; transform.DOMove(FinalPos, 0.7f).OnComplete(() => { IsUsingAbility = false; IsFinishFinalSkill = false; }); transform.DOLookAt(FinalPos,0.35f); } #endregion #region Load Arrow private GameObject _GroundArrow; public GameObject GroundArrow => (_GroundArrow); void LoadFinalSkillArrow() { var obj = Resources.Load("Weapons/GrounArrow"); _GroundArrow = Instantiate(obj, transform.position,transform.rotation) as GameObject; _GroundArrow.transform.parent = transform; _GroundArrow.transform.localPosition = Vector3.zero; _GroundArrow.transform.localRotation = Quaternion.identity; _GroundArrow.transform.localScale = Vector3.one; _GroundArrow.SetActive(false); } #endregion } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SIAction_Destruction : SIAction_BaseAction { public override void TrigActor() { base.TrigActor(); Destroy(gameObject); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class FinalSkillBtn : CommonJoyButton { public Color NormalColor; public Color DisableColor; public CanvasGroup CanvasGPInst; public void SetFinalSkillState(bool on) { CanvasGPInst.blocksRaycasts = on; // make the btn unfunction ImageBackGround.color = on == true ? NormalColor : DisableColor; ImageHandle.color = on == true ? NormalColor : DisableColor; // two lines above are same function as below /* if (on) { ImageBackGround.color = NormalColor; ImageHandle.color = NormalColor; } else { ImageBackGround.color = DisableColor; ImageHandle.color = DisableColor; } */ } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using AttackTypeDefine; public class AnimatorManger : MonoBehaviour { NotifySkill SkillReadyInst; AnimCtrl AnimInst; StateMachine StateInst; public void OnStart(AnimCtrl animinst) { AnimInst = animinst; StateInst = AnimInst.Anim.GetBehaviour<StateMachine>(); } public void StartAnimation(string AnimName, NotifySkill SkillReady, NotifySkill SkillBegin, NotifySkill SkillEnd, NotifySkill SkillEnd1) { AnimInst.Anim.SetTrigger(AnimName); SkillReadyInst = SkillReady; //clear all call back StateInst.ClearAllCallBacks(); StateInst.RegisterCallBack(eTrigSkillState.eTrigBegin, SkillBegin); StateInst.RegisterCallBack(eTrigSkillState.eTrigEnd, () => { //Call Back the next one if (null != SkillEnd1) { SkillEnd1(); } this.InvokeNextFrame(() => { StateInst.RegisterCallBack(eTrigSkillState.eTrigEnd, SkillEnd); }); }); } void EventSkillReady() { SkillReadyInst(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SkeletonActor : MonoBehaviour { Animator Anim; private void Start() { Anim = GetComponent<Animator>(); } public void GetHit() { Anim.SetTrigger("Base Layer.GetHit"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestSphereMgr : MonoBehaviour { #region Parameters public Vector3 Areasize; public int SphereNum; public GameObject SpherePrefab; List<SphereCtrl> SphereList; public Transform PlayerInst; public static TestSphereMgr Inst =>(_inst); private static TestSphereMgr _inst; private void Awake() { SphereList = new List<SphereCtrl>(); _inst = this; for (var i = 0; i < SphereNum; i++) { Add(); } } #endregion SphereCtrl CreateSphere() { var pos = transform.position + 0.5f * new Vector3 ( Random.Range(Areasize.x*-1, Areasize.x), 0, Random.Range(Areasize.x * -1, Areasize.z) ); var sphere = Instantiate(SpherePrefab,pos,Quaternion.identity); return sphere.GetComponent<SphereCtrl>(); } void Add() { var sphere = CreateSphere(); SphereList.Add(sphere); sphere.OnStart(PlayerInst); } public void Remove(SphereCtrl obj) { if (null == obj) { Debug.Log("Fatal Error: Iput pam is illegal"); return; } if (SphereList.Contains(obj)) { var tmp = SphereList.Remove(obj); Destroy(obj.gameObject); } } private void OnDrawGizmos() //define a range { Gizmos.color = Color.red; Gizmos.DrawWireCube(transform.position, Areasize); } } <file_sep>using UnityEngine; using AttackTypeDefine; using System.Collections.Generic; public class StateMachine : StateMachineBehaviour { bool IsLastTransition; bool IsCurTransition; AnimatorStateInfo LastStateInfo; Dictionary<eTrigSkillState,List<NotifySkill>> SkillDic = new Dictionary<eTrigSkillState, List<NotifySkill>>(); public override void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { IsCurTransition = animator.IsInTransition(layerIndex); // Check which is the current animator if (!IsCurTransition) { if (stateInfo.normalizedTime % 1.0f < LastStateInfo.normalizedTime % 1.0f) { //CastSkillEnd TriggerAction(eTrigSkillState.eTrigEnd); } } if (IsCurTransition && !IsLastTransition) // Curr is combining but not Last { //CastSkillBegin TriggerAction(eTrigSkillState.eTrigBegin); } if (!IsCurTransition && IsLastTransition) { //CastSkillEnd TriggerAction(eTrigSkillState.eTrigEnd); } IsLastTransition = IsCurTransition; LastStateInfo = stateInfo; } void TriggerAction(eTrigSkillState state) { if (SkillDic.ContainsKey(state)) { var list = SkillDic[state]; while (list.Count >0 ) { var ns = list[0]; list.Remove(ns); ns(); } } } public void RegisterCallBack(eTrigSkillState state, NotifySkill action) { List<NotifySkill> list; if (SkillDic.ContainsKey(state)) { list = SkillDic[state]; list.Add(action); } else { list = new List<NotifySkill>(); list.Add(action); SkillDic.Add(state, list); } } public void ClearAllCallBacks() { if (null == SkillDic) { return; } List<NotifySkill> list; for (var i = eTrigSkillState.eTrigBegin; i <= eTrigSkillState.eTrigEnd; i++) { if (SkillDic.ContainsKey(i)) { list = SkillDic[i]; list.Clear(); //Debug.Log("Clear"); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { public float Speed; public float Duration; private bool IsTriggered = false; float StartTime = 0f; // Start is called before the first frame update public void OnStart() { IsTriggered = true; StartTime = Time.time; } // Update is called once per frame void Update() { if (!IsTriggered) { return; } if (Time.time - StartTime > Duration) { Destroy(gameObject); } else { transform.position += transform.forward * Time.deltaTime * Speed; } } private void OnTriggerEnter(Collider other) { if (other.gameObject.GetComponent<Movement>() != null) { //Player Hurt Animation //destroy bullet Destroy(gameObject); } } } <file_sep>using System.Collections; using UnityEngine; using UnityEngine.UI; public class RewriteCoroutine : MonoBehaviour { public Text _uiText; static RewriteCoroutine _inst; private void Awake() { _inst = this; } // Start is called before the first frame update public void MyStart() { var test01 = Test01(); var test02 = Test02(); CoroutineManager.Inst.MyStartCoroutine(test01); CoroutineManager.Inst.MyStartCoroutine(test02); } // Update is called once per frame void Update() { CoroutineManager.Inst.UpdateCoroutine(); } static IEnumerator Test01() { //Debug.Log("start test 01"); _inst._uiText.text += "start test 01\n\n"; yield return new IWaitForSeconds(5); //Debug.Log("after 5 seconds"); _inst._uiText.text += "after 5 seconds\n\n"; yield return new IWaitForSeconds(5); //Debug.Log("after 10 seconds"); _inst._uiText.text += "after 10 seconds\n\nthe end"; } static IEnumerator Test02() { //Debug.Log("start test 02"); _inst._uiText.text += "start test 02\n\n"; yield return new IWaitForFrames(500); //Debug.Log("after 500 frames"); _inst._uiText.text += "after 500 frames\n\n"; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UI_JoyStick : MonoBehaviour { private void Start() { FinalSkillBtnInst.SetFinalSkillState(ShowFinalSkillBtn); } #region JoyStick public CommonJoyButton CommonBtn; public Vector3 Dir => (CommonBtn.Dir); #endregion #region Rage Slide public Slider SliderInst; public Image HighLight1; public Image HighLight2; public bool ShowFinalSkillBtn => (SliderInst.value >= 100); public void OnModifyFSV(int value) { var RageValue = SliderInst.value; SliderInst.value += value; HighLight2.enabled = false; HighLight1.enabled = false; if (SliderInst.value >= 200) { HighLight2.enabled = true; HighLight1.enabled = true; } else if (SliderInst.value >= 100) { HighLight1.enabled = true; } FinalSkillBtnInst.SetFinalSkillState(ShowFinalSkillBtn); } #endregion #region Final Skill public FinalSkillBtn FinalSkillBtnInst; #endregion } <file_sep>using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; using AttackTypeDefine; public class CommonJoyButton : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler { #region System private void Awake() { PressDown = new GameBtnEvent(); OnDragEvent = new GameBtnEvent(); PressUp = new GameBtnEvent(); } #endregion #region Joy Stick Event Callback public Image ImageBackGround; public Image ImageHandle; public Vector3 HandleOriginPoint; public GameBtnEvent PressDown; public GameBtnEvent OnDragEvent; public GameBtnEvent PressUp; public float MaxRadius; protected Vector3 _Dir; public Vector3 Dir => _Dir; Vector3 PointDownPos; int FingerID = int.MinValue; public void OnPointerDown(PointerEventData eventData) { if ((FingerID = eventData.pointerId) < -1) { return; } ImageBackGround.transform.position = PointDownPos = eventData.position; PressDown?.Invoke(eventData); } public void OnDrag(PointerEventData eventData) { if ((FingerID = eventData.pointerId) < -1) { return; } //get distance var distance = (eventData.position - (Vector2)PointDownPos); //Max and Min of the radus Mathf.Clamp(Value,Min, Max) var radius = Mathf.Clamp(Vector3.Magnitude(distance), 0, MaxRadius); var tmp = radius * distance.normalized; var localPos = new Vector2() { x = tmp.x, y = tmp.y }; ImageHandle.transform.localPosition = localPos; _Dir = ImageHandle.transform.localPosition.normalized; OnDragEvent?.Invoke(eventData); } public void OnPointerUp(PointerEventData eventData) { if ((FingerID = eventData.pointerId) < -1) { return; } //Vector3 origin; //origin = new Vector3(250, -320, 0); ImageBackGround.transform.localPosition = HandleOriginPoint; ImageHandle.transform.localPosition = Vector3.zero; _Dir = Vector3.zero; PressUp?.Invoke(eventData); } #endregion } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class CoroutineManager : MonoBehaviour { private static CoroutineManager _inst; public static CoroutineManager Inst => _inst; private void Awake() { _inst = this; } private LinkedList<IEnumerator> coroutineList = new LinkedList<IEnumerator>(); public void MyStartCoroutine(IEnumerator ie) { coroutineList.AddLast(ie); } public void MyStopCoroutine (IEnumerator ie) { try { coroutineList.Remove(ie); } catch (Exception e) { Debug.LogError(e.ToString()); } } public void UpdateCoroutine() { var node = coroutineList.First; while(node != null) { IEnumerator ie = node.Value; bool ret = true; if(ie.Current is IWait) { var iwait = (IWait)ie.Current; if(iwait.Tick()) { ret = ie.MoveNext(); } } else { ret = ie.MoveNext(); } if(!ret) { coroutineList.Remove(node); } node = node.Next; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Tur1 : MonoBehaviour { public Animator Anim; private void Awake() { } public void Attack() { Anim.SetTrigger("Base Layer.Attack"); } public void Jump() { Anim.SetTrigger("Base Layer.Jump"); } public void Idle() { Anim.SetTrigger("Base Layer.Idle"); } } <file_sep>using UnityEngine; public class IWaitForSeconds : IWait { float _Seconds; public IWaitForSeconds (float seconds) { _Seconds = seconds; } public bool Tick() { _Seconds -= Time.deltaTime; return _Seconds < 0f; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SIAction_SpawnWorld : SIAction_BaseAction { SIAction_DataStore se; public GameObject EffectSpawnInst; public string SocketName; public float EffectDestroyDelay; public Vector3 Offset; public Vector3 OffRot; GameObject Owner; public override void TrigActor() { se = GetComponent<SIAction_DataStore>(); Owner = se.Owner; //find the object on the sword var socket = GlobalHelper.FindGOByName(Owner, SocketName); if (socket == null) { socket = Owner; } //spawn effect var effect = Instantiate(EffectSpawnInst); var des = effect.GetComponent<SIAction_Destruction>(); if (null != des) { des.Duration = EffectDestroyDelay; des.OnStart(); } // let the effect follow the position of sword effect.transform.position = socket.transform.position; effect.transform.Translate(Offset, Space.Self); effect.transform.rotation = socket.transform.rotation; effect.transform.Rotate(OffRot, Space.Self); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; public class SphereCtrl : MonoBehaviour { public float Speed; public float Duration; bool IsTrigger = false; float StartTime = 0f; string BulletPath = "Turs/Tur4/Bullet"; public float MinWait; public float MaxWait; Transform PlayerInst; public void OnStart(Transform player) { PlayerInst = player; StartCoroutine(FireBullet()); } IEnumerator FireBullet() { while (!IsTrigger) { var dur = Random.Range(MinWait, MaxWait); yield return new WaitForSeconds(dur); //Play a short animate transform.DOShakeScale(1,1,2); transform.GetComponent<MeshRenderer>().material.DOColor( new Color( Random.Range(0f,1f), Random.Range(0f, 1f), Random.Range(0f, 1f) ) ,1f); //End of the animate yield return new WaitForSeconds(1.0f); //Onload the Bullet var obj = Resources.Load(BulletPath); var bullet = Instantiate(obj, transform.position, Quaternion.identity) as GameObject; bullet.transform.forward = (PlayerInst.position - transform.position).normalized; // get the direction var bulletCtrl = bullet.GetComponent<Bullet>(); bulletCtrl.OnStart(); } } private void Update() { if (IsTrigger) { if (Time.time - StartTime > Duration) { StopAllCoroutines(); TestSphereMgr.Inst.Remove(this); return; } else { transform.position += Vector3.up * Time.deltaTime * Speed; } } } // Start is called before the first frame update private void OnTriggerEnter(Collider other) { //Debug.Log("HIT"); TriggerSphereUpside(); } void TriggerSphereUpside() { IsTrigger = true; StartTime = Time.time; } } <file_sep>using System.Collections; using UnityEngine; public static class UnityEngineExtension { public delegate void CallBack(); public static void InvokeNextFrame(this MonoBehaviour _mb, CallBack callback) { _mb.StartCoroutine(ProcessNextFrame(callback)); } private static IEnumerator ProcessNextFrame(CallBack callback) { yield return null; callback(); } } <file_sep>using UnityEngine; public class CollisionTrigger : MonoBehaviour { private void OnCollisionEnter(Collision collision) { Debug.Log(collision.gameObject.name); } private void Update() { transform.rotation *= Quaternion.Euler(0f, 20f * Time.deltaTime, 0f); } private void OnTriggerEnter(Collider other) { Debug.Log(other.gameObject.name); } private void OnTriggerStay(Collider other) { } private void OnTriggerExit(Collider other) { } } <file_sep>using UnityEngine; public class GlobalHelper : MonoBehaviour { public static GameObject FindGOByName(GameObject target, string targetname) { if (null == target) { return null; } GameObject resultGo = null; if (target.name.Equals(targetname) == true) { return target; } for (var i = 0; i < target.transform.childCount; i++) { var child = target.transform.GetChild(i).gameObject; if (child.name.Equals(targetname) == true) { return child; } else { if (child.transform.childCount > 0) { resultGo = FindGOByName(child, targetname); if (null != resultGo) { return resultGo; } } } } return null; } // find the gameobject in hierarchy public static GameObject InstantiateMyPrefab(string path, Vector3 pos, Quaternion rot ) { var obj = Resources.Load(path); var go = Object.Instantiate(obj) as GameObject; go.name = obj.name; //rename it, becasue when you instantiate it, it will have a prefix as clone go.transform.position = pos; go.transform.rotation = rot; go.transform.localScale = Vector3.one; return go; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using AttackTypeDefine; public class SIAction_SkillInfo : SIAction_BaseAction { [HideInInspector] public eSkillBindType SkillBindType; [HideInInspector] public string ObjName; public override void TrigActor() { Destroy(gameObject); } public void SetOwner(GameObject Owner) { SIAction_DataStore[] ses = gameObject.GetComponentsInChildren<SIAction_DataStore>(); for (var i = 0; i < ses.Length; i++) { ses[i].Owner = Owner; } } } <file_sep>using UnityEngine; using AttackTypeDefine; public class SIAction_BaseAction : MonoBehaviour { public eTrigType TrigType; public float Duration; float StartTime = 0f; bool IsTriggered = false; void Start() { if (TrigType == eTrigType.eAuto) { StartTime = Time.time; IsTriggered = true; } } public void OnStart() { if (TrigType == eTrigType.eCondition) { StartTime = Time.time; IsTriggered = true; } } // Update is called once per frame void Update() { if (!IsTriggered) { return; } if (Time.time - StartTime >= Duration) { IsTriggered = false; TrigActor(); } } public virtual void TrigActor() { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Movement : MonoBehaviour { #region System Functon void Start() { AnimCtrlInst = GetComponent<AnimCtrl>(); Cam = Camera.main; } // Update is called once per frame void Update() { if (CanMove()) { SetPlayerAnimMoveParameter(); } } #endregion #region Player Animation Controller private AnimCtrl AnimCtrlInst; public Animator Anim; public CharacterController CharCtrl; public float MoveSpeed; public UI_JoyStick JoyStick; float horizontal; float vertical; float speed; float s1; float s2; Camera Cam; bool CanMove() { if (AnimCtrlInst.IsPlaying) { return false; } else { return true; } } void SetPlayerAnimMoveParameter() { #if UNITY_EDITOR horizontal = Input.GetAxis("Horizontal"); vertical = Input.GetAxis("Vertical"); s1 = Mathf.Sqrt(horizontal * horizontal + vertical * vertical); s2 = null != JoyStick ? JoyStick.Dir.magnitude : 0; // if JoyStick != null s2 = JoyStick.Dir.magnitude else s2 = 0 speed = s1 > s2 ? s1 : s2; //if current input is keyboard s1>s2 else current input is joystick s2 > s1 if (s2 > s1) //joystick input { horizontal = JoyStick.Dir.x; vertical = JoyStick.Dir.y; } #else speed = JoyStick.Dir.magnitude; #endif Anim.SetFloat("IdleAndRun",speed); if (speed > 0.01f) { PlayerControlMovement(horizontal, vertical); } } void PlayerControlMovement(float x , float z) { var dir = x * Cam.transform.right + z * Cam.transform.forward; dir.y = 0f; transform.forward = dir; CharCtrl.Move(MoveSpeed * Time.deltaTime * dir); } #endregion } <file_sep>using System; using UnityEngine.Events; using UnityEngine.EventSystems; namespace AttackTypeDefine { public delegate void NotifySkill(); public enum eSkillBindType { eEffectWorld, eEffectOwner, eDamageOwner, } public enum eTrigType { eAuto = 0, eCondition, } public enum eSkillType { eAttack = 0, eSkill1, } public enum eTrigSkillState { eTrigBegin, eTrigEnd, } public class GameEvent : UnityEvent { }; public class GameBtnEvent : UnityEvent <PointerEventData> { }; }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Sword : MonoBehaviour { //Turning On and Off the Sword Collision box according to the percentage of character's attack animation. BoxCollider BC; Animator Anim; float StartPer; float EndPer; float CurrPer; float LastPer; AnimatorStateInfo StateInfo; AnimCtrl AnimCtrlInst; public int RageValue = 30; public void OnStart(AnimCtrl AC) { AnimCtrlInst = AC; } private void Start() { BC = GetComponent<BoxCollider>(); BC.enabled = false; //conceal the object } #region Functions public void OnStartWeaponCtrl(Animator _Anim, float Startpercentage, float Endpercentage) { StartPer = Startpercentage; EndPer = Endpercentage; Anim = _Anim; StopAllCoroutines(); // detect the percentage of the current animation StartCoroutine(WaitToPlayAnim()); } IEnumerator WaitToPlayAnim() { CurrPer = StateInfo.normalizedTime % 1.0f; while (true) { StateInfo = Anim.GetCurrentAnimatorStateInfo(0); CurrPer = StateInfo.normalizedTime % 1.0f; if (CurrPer >= StartPer && LastPer < StartPer) { BC.enabled = true; } else if(CurrPer > EndPer && LastPer <= EndPer) { BC.enabled = false; break; } LastPer = CurrPer; yield return null; } } private void OnTriggerEnter(Collider other) { var enemyActor = other.gameObject.GetComponent<SkeletonActor>(); if (enemyActor != null) { Debug.Log("Hit"); enemyActor.GetHit(); //player increase rage value AnimCtrlInst.OnModifyFSvalue(RageValue); } } #endregion } <file_sep>using System; using System.Collections.Generic; namespace FlatKit.StylizedSurface { public static class Tooltips { public static Dictionary<String, String> map = new Dictionary<string, string> { {"Color Shaded", "The dark part of cel shaded objects."}, {"Center X", "World-space X coordinate of the middle gradient point."}, }; } }<file_sep>namespace AttackTypeDefine { public class PointEventData { } }<file_sep>public interface IWait { bool Tick(); }<file_sep>public class IWaitForFrames : IWait { float _Frames; public IWaitForFrames(int frames) { _Frames = frames; } public bool Tick() { _Frames -= 1; return _Frames < 0; } }
1fb03ef5ac678e23e31e000d69315edaed3d8863
[ "C#" ]
28
C#
ChihhaoFeng/3D_Mobile_Game
371fa42455e328aba6063ef88d98f8e573a14da8
fa432bc5cfb78be3ae92fecbdc6640149028da3a
refs/heads/master
<file_sep>class ReservationsController < ApplicationController respond_to :json def create @reservation = Reservation.new(reservation_params) @reservation.save respond_with(@reservation) end def destroy reservation = Reservation.find(params[:id]) reservation.destroy respond_with(reservation) end def update reservation = Reservation.find(params[:id]) reservation.update_attributes(reservation_params) respond_with(reservation) end private def reservation_params params.require(:reservation).permit(:start_time, :end_time, :table_id) end end <file_sep>class Reservation < ActiveRecord::Base belongs_to :table validates :start_time, :end_time, presence: true validate :date_range, :date_overlap def date_range if self.start_time && self.end_time errors.add( :end_time, "Invalid date range") if self.start_time > self.end_time end end def date_overlap if self.new_record? overlap = Reservation.where("? < end_time AND ? > start_time AND ? = table_id", self.start_time, self.end_time, self.table_id) else overlap = Reservation.where("? < end_time AND ? > start_time AND ? = table_id AND id !=?", self.start_time, self.end_time, self.table_id, self.id) end if overlap.size > 0 errors.add(:start_time, "") errors.add(:end_time, "Date range overlaps with these events") end end end <file_sep>FactoryGirl.define do factory :table do end factory :reservation do start_time Time.now end_time Time.now + 4.hours association :table end end <file_sep>object @table attributes :id child :reservations do attributes :id, :table_id node(:start_time) { |r|(r.start_time).strftime("%Y/%m/%d %l:%M:%S")} node(:end_time) { |r|(r.end_time).strftime("%Y/%m/%d %l:%M:%S")} end<file_sep>Reserve::Application.routes.draw do root 'application#index' resources :tables resources :reservations end <file_sep>json.id @reservation.id #json.start_time @reservation.start_time.strftime("from %I:%M%p, %d %a") #json.end_time @reservation.end_time.strftime("to %I:%M%p, %d %a") <file_sep>class TablesController < ApplicationController respond_to :json, :html def index respond_with(Table.all) end def show @table = Table.includes(:reservations).find(params[:id]) end end <file_sep>require 'rails_helper' describe Reservation do it "has a valid factory" do expect(build(:reservation)).to be_valid end it "is invalid without a end_time" do expect(build(:reservation, end_time: nil)).to be_invalid end it "is invalid if end_time less then start_time" do expect(build(:reservation, end_time: Time.now - 8.hours)).to be_invalid end describe "time ranges" do before :each do create(:reservation) end context "valid if" do it "A occurs entirely B after" do expect(build(:reservation, start_time: Time.now + 8.hours, end_time: Time.now + 10.hours, table_id: 1)).to be_valid end it "B occurs entirely after A" do expect(build(:reservation, start_time: Time.now - 10.hours, end_time: Time.now - 8.hours, table_id: 1)).to be_valid end end context "invalid if" do it "A surrounds B" do expect(build(:reservation, start_time: Time.now - 5.hours, end_time: Time.now + 5.hours, table_id: 1)).to be_invalid end it "B surrounds A" do expect(build(:reservation, start_time: Time.now + 1.hours, end_time: Time.now + 2.hours, table_id: 1)).to be_invalid end it "A partially overlaps B" do expect(build(:reservation, start_time: Time.now - 2.hours, end_time: Time.now + 2.hours, table_id: 1)).to be_invalid end it "A partially overlaps B after" do expect(build(:reservation, start_time: Time.now + 2.hours, end_time: Time.now + 8.hours, table_id: 1)).to be_invalid end end context "valid with different association" do it "A partially overlaps B after" do expect(build(:reservation, start_time: Time.now + 2.hours, end_time: Time.now + 8.hours)).to be_valid end end end end <file_sep>object @reservation attributes :id, :table_id node(:start_time) { |r|(r.start_time).strftime("%Y/%m/%d %l:%M:%S")} node(:end_time) { |r|(r.end_time).strftime("%Y/%m/%d %l:%M:%S")}
97ab358b8bedbfcf0fde96295fc53a8efa39c541
[ "Ruby" ]
9
Ruby
arabyniuk/reservation
a6bca2bdb690223364b9ee34dfbe937890c51b8e
d49e3c42c06c448643610ecc0598ebd83f2bd9c9
refs/heads/master
<file_sep>window.addEventListener('load', () => { let label = document.querySelector('.label'); let planet__container = document.querySelector('.planet__container'); let xOld = 0; let positionElement = -150; planet__container.addEventListener('mousemove', moveLabel); planet__container.addEventListener('click', moveLabel); planet__container.addEventListener('touch', moveLabel); function moveLabel (e) { let xNew = e.screenX; if (xNew > xOld) { positionElement += 4; if (positionElement >= 285) { positionElement = 285; } else { label.style.left = `-${positionElement}px`; } } else { positionElement -= 4 if (positionElement <= 30) { positionElement = 30; } else { label.style.left = `-${positionElement}px`; } } xOld = e.screenX; } });
306e75e2389e3026efaa4fc42c406a9eed64bb4e
[ "JavaScript" ]
1
JavaScript
belocer/planet
2e6ef2234fc1a5ee80902d250e06533fc7c6894c
f2fa0268e24daadd8e9dbb18bb3737253e1aaba5
refs/heads/master
<file_sep># This is a basic tutoril on how to multiply two vectors in PyTorch. # One of the coolest things in PyTorch is that allows the manipulation of vectors/tensors using numpy subverting Torch's methods. # This is a cool feature because good old numpy is extremely easy to use! import torch import numpy as np # Done using good old numpy a=np.random.rand(3,5) #initialize a numpy vector b=np.zeros((5,10)) # initialize another vector b+=0.1 c=a.dot(b) # Multiply just as you would in numpy print(c) # This can also be done using Torch as follows - x = torch.Tensor(5, 3) x = torch.rand(5,3) y= torch.Tensor(3, 10) y= torch.rand(3,10) k=x.numpy() l=y.numpy() z=k.dot(l) print(z) <file_sep># Pytorch-Tutorials **A collection of basic tutorials in Pytorch** Introduction to deep learning based on PyTorch framework. These tutorials are direct ports of Newmu's [Theano Tutorials](https://github.com/Newmu/Theano-Tutorials), and nlintz's [Tensorflow-tutorials](https://github.com/nlintz/TensorFlow-Tutorials)
11a1bf15cdba51f54d68aebfd4f3e66d44231fa7
[ "Markdown", "Python" ]
2
Python
arihantjain15/Pytorch-Tutorials
3afa6172d292a00ebb5176487e7c77b672a8ec38
87b36f5ef789c720d6d269b423c68a34732c4660
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Assignment4.Models { public class Restaurant { //defining the model attributes [Required] public int RestaurantRank { get; set; } [Required] public string RestaurantName { get; set; } public string? FavoriteDish { get; set; } = "It's All Tasty"; //sentence here makes it default [Required] public string? Address { get; set; } [DataType(DataType.PhoneNumber)] public long? RestaurantPhone { get; set; } public string? WebsiteLink { get; set; } = "Coming Soon"; //defining list instance public static Restaurant[] GetRestaurants() { Restaurant rank1 = new Restaurant { RestaurantRank = 1, RestaurantName = "<NAME>", FavoriteDish = "Souvlaki", Address = "1000 N. University", RestaurantPhone = 8013334565, WebsiteLink = "pitapitusa.com" }; Restaurant rank2 = new Restaurant { RestaurantRank = 2, RestaurantName = "Noodles and Company", //leave favorite dish blank Address = "1100 N. University", RestaurantPhone = 8014447867, WebsiteLink = "www.noodles.com" }; Restaurant rank3 = new Restaurant { RestaurantRank = 3, RestaurantName = "Mo'Bettahs", FavoriteDish = "Teriyaki Chicken", Address = "2000 N. University", RestaurantPhone = 8013764865, //leave Website Blank }; Restaurant rank4 = new Restaurant { RestaurantRank = 4, RestaurantName = "Cupbop", FavoriteDish = "Combo Bop", Address = "800 N. University", RestaurantPhone = 8019037865, WebsiteLink = "cupbop.com" }; Restaurant rank5 = new Restaurant { RestaurantRank = 1, RestaurantName = "<NAME>", FavoriteDish = "Chicken Burrito", Address = "900 N. University", RestaurantPhone = 8013989565, WebsiteLink = "www.costavida.com" }; return new Restaurant[] { rank1, rank2, rank3, rank4, rank5 }; } } public class RestaurantSuggestion { //defining the model attributes [Required] public string SuggestorName { get; set; } [Required] public string RestaurantName { get; set; } [Required] public string FavoriteDish { get; set; } = "It's All Tasty"; //sentence here makes it default //requiring and making datatype phonenumber, the validation is in the HTML [DataType(DataType.PhoneNumber)] [Required] public long? RestaurantPhone { get; set; } } } <file_sep>using Assignment4.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace Assignment4.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } //Index and passing list of restaurant information public IActionResult Index() { List<string> restaurantList = new List<string>(); foreach (Restaurant r in Restaurant.GetRestaurants()) { restaurantList.Add(string.Format($"#{r.RestaurantRank}: Name: {r.RestaurantName}, " + $"My Favorite Dish: {r.FavoriteDish}, Address: {r.Address}, Phone: {r.RestaurantPhone}, Website: {r.WebsiteLink}")); } return View(restaurantList); } //submit suggestions before post [HttpGet] public IActionResult SubmitSuggestions() { return View(); } //Suggestion Submittion Application [HttpPost] public IActionResult SubmitSuggestions(RestaurantSuggestion restaurantLists) { TempStorage.AddApplication(restaurantLists); //Debug.WriteLine("Name: " + appResponse.Name); return View("Confirmation", restaurantLists); //"Confirmation", appResponse } //View New Restaurant Suggestions public IActionResult ViewSuggestions() { return View(TempStorage.RestaurantLists); } //Privacy Page public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Assignment4.Models { public class TempStorage { private static List<RestaurantSuggestion> restaurantLists = new List<RestaurantSuggestion>(); public static IEnumerable<RestaurantSuggestion> RestaurantLists => restaurantLists; public static void AddApplication(RestaurantSuggestion restaurantList) { restaurantLists.Add(restaurantList); } } }
424e9c6dd25e8d1ad991f145f3fa69d1c7584818
[ "C#" ]
3
C#
JAW1/Assignment4
5a73f37538b6e2036f659f589c2ead466e9cc780
27d6e2d9150f8fb35f2097fa6e15271bfe24aa80
refs/heads/main
<repo_name>NicolasAuber/Udacity_Enron<file_sep>/poi_id.py #!/usr/bin/python ######################## ### Import Libraries ### ######################## # Standard libraries import sys import time import pickle import numpy as np import pandas as pd import pprint import matplotlib.pyplot as plt import seaborn as sns # Specific functions sys.path.append("./tools/") from feature_format import featureFormat, targetFeatureSplit from tester import dump_classifier_and_data, test_classifier # Machine learning libraries from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC from sklearn import tree, ensemble, neighbors from sklearn.preprocessing import MinMaxScaler from sklearn.feature_selection import SelectKBest, chi2 from sklearn.model_selection import train_test_split, GridSearchCV from sklearn import decomposition from sklearn.pipeline import Pipeline # Displays the version of some libraries print("python: ", sys.version) print("numpy: ", np.__version__) print("pandas: ", pd.__version__) print("seaborn: ", sns.__version__) t0 = time.time() ######################## ### Data Exploration ### ######################## # Loads the dictionary containing the dataset with open("final_project_dataset.pkl", "rb") as data_file: data_dict = pickle.load(data_file) # As already seen during Udacity Intro To Machine Learning course, there are 2 entries that are not employees. # They are removed from the dataset. no_employees_list = ['TOTAL', 'THE TRAVEL AGENCY IN THE PARK'] for item in no_employees_list: data_dict.pop(item) # Enron employees employees_list = list(data_dict.keys()) print("Number of Enron employees: ", len(employees_list)) pprint.pprint(employees_list) # Features for each Enron employee features_list = list(data_dict['LAY KENNETH L'].keys()) print("Number of features: ", len(features_list)) pprint.pprint(features_list) # Let's remove 'email_address' feature and re-order the features manually features_list = ['poi', 'from_messages', 'to_messages', 'from_this_person_to_poi', 'from_poi_to_this_person', 'shared_receipt_with_poi', 'salary','bonus','long_term_incentive','deferred_income','deferral_payments','loan_advances','other','expenses','director_fees','total_payments', 'exercised_stock_options','restricted_stock','restricted_stock_deferred','total_stock_value'] print("Number of features: ", len(features_list)) data = featureFormat(data_dict, features_list, remove_NaN=False, remove_all_zeroes=False, remove_any_zeroes=False, sort_keys = False) df = pd.DataFrame(data, index=employees_list, columns=features_list) print(df.info()) print(df.head()) print("Total: ", df['poi'].count()) print("Number of POI: ", df[df['poi']==True]['poi'].count()) print("Number of non POI: ", df[df['poi']==False]['poi'].count()) print("###") #df = df[df['salary'].notnull()] #df = df[df['bonus'].notnull()] df1 = df[df['from_messages'].notnull()] print(df1.count()) print("###") print("Total: ", df1['poi'].count()) print("Number of POI: ", df1[df1['poi']==True]['poi'].count()) print("Number of non POI: ", df1[df1['poi']==False]['poi'].count()) # Checks if some employees have only NaN values df[df.isnull().sum(axis=1)==len(features_list)-1].index[:] df['salary'].plot.hist(bins=20) plt.show() df['to_messages'].plot.hist(bins=20) plt.show() # Displays a scatter plot for 2 features distinguishing the POI and non POI def plotGraph(feature1, feature2): x_poi = df[df['poi']==True][feature1].tolist() x_npoi = df[df['poi']==False][feature1].tolist() y_poi = df[df['poi']==True][feature2].tolist() y_npoi = df[df['poi']==False][feature2].tolist() plt.scatter(x_poi, y_poi, color='r', label = 'poi') plt.scatter(x_npoi, y_npoi, color='b', label = 'non poi') plt.xlabel(feature1) plt.ylabel(feature2) plt.legend() plt.show() # Scatter plot 'salary' vs 'bonus'. Prints remarkable values plotGraph('salary', 'bonus') print(df.loc[(df['salary'] > 500000) | (df['bonus'] > 4000000),['poi','salary','bonus']]) # Scatter plot 'total_payments' vs 'total_stock_value'. Prints remarkable values plotGraph('total_payments', 'total_stock_value') print(df.loc[df['total_stock_value'] > 10000000,['poi','total_payments','total_stock_value']]) # Scatter plot 'from_messages' vs 'to_messages'. Prints remarkable values plotGraph('from_messages', 'to_messages') print(df.loc[(df['to_messages'] > 5000) | (df['from_messages'] > 5000),['poi','from_messages','to_messages']]) # Creates new email features focusing on ratios. df['ratio_from_poi']= df['from_this_person_to_poi'] / df['from_messages'] df['ratio_to_poi']= df['from_poi_to_this_person'] / df['to_messages'] df['ratio_shared_poi']= df['shared_receipt_with_poi'] / df['to_messages'] # Scatter plot 'ratio_from_poi' vs 'ratio_to_poi'. Prints remarkable values plotGraph('ratio_from_poi', 'ratio_to_poi') print(df.loc[(df['ratio_from_poi'] > 0.8) | (df['ratio_to_poi'] > 0.15),['poi','ratio_from_poi','ratio_to_poi']]) ######################### ### Feature Selection ### ######################### ### Task 1: Select what features you'll use. ### features_list is a list of strings, each of which is a feature name. ### The first feature must be "poi". # Defines the features with too many NaN values and removes these features for col in df.columns: if df[col].count() < 81: features_list.remove(col) print("Number of features: ", len(features_list)) pprint.pprint(features_list) ################ ### Outliers ### ################ ### Task 2: Remove outliers # Removes the outliers from the Enron dataset outliers_list = ['<NAME>', '<NAME>','LOCKHART EUGENE E'] for item in outliers_list: data_dict.pop(item) ''' # Removes the employees with NaN email features. THIS IS NOT USED. employees_list = list(data_dict.keys()) for employee in employees_list: if data_dict[employee]['from_messages'] == "NaN": data_dict.pop(employee) ''' # Enron employees employees_list = list(data_dict.keys()) print("Number of employees: ", len(employees_list)) # Creates the dataset my_dataset = data_dict #################### ### New Features ### #################### ### Task 3: Create new feature(s) # Calculates the ratio between 2 values. NaN for any of the 2 values will result in null values. def calcRatio(poi_messages, all_messages): ratio = 0. if poi_messages == "NaN" or all_messages == "NaN": ratio = 0. else: ratio = float(poi_messages) / float(all_messages) return ratio # Generates new features in the dataset for name in data_dict: data_dict[name]['ratio_to_poi'] = calcRatio(data_dict[name]['from_this_person_to_poi'],data_dict[name]['from_messages']) data_dict[name]['ratio_from_poi'] = calcRatio(data_dict[name]['from_poi_to_this_person'],data_dict[name]['to_messages']) data_dict[name]['ratio_shared_poi'] = calcRatio(data_dict[name]['shared_receipt_with_poi'],data_dict[name]['to_messages']) print ("###") print ("Feature selection analysis on email features") print ("###") # Creates a list of email features features_email_list = ['poi', 'from_this_person_to_poi','from_poi_to_this_person','shared_receipt_with_poi','from_messages','to_messages', 'ratio_from_poi','ratio_to_poi','ratio_shared_poi'] # Evaluates the performance of the classifier clf = tree.DecisionTreeClassifier() test_classifier(clf, my_dataset, features_email_list) # Displays the importance of features print("Features importance for email features:") for importance, feature in sorted(zip(clf.feature_importances_, features_email_list[1:]),reverse=True): print ('{}: {:.3}'.format(feature, importance)) print ("###") print ("Univariate feature selection analysis") print ("###") # Extracts the labels and features used by the POI classifier data = featureFormat(data_dict, features_list,remove_all_zeroes=True) labels, features = targetFeatureSplit(data) features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=0.3, random_state=42) # Creates a pipeline of two steps. pipe = Pipeline([('sel', SelectKBest()), ('clf', tree.DecisionTreeClassifier())]) ### Parameters k = [1,2,3,4,5] max_depth = [2,4,6] min_samples_split = [2,10,20] # Creates Parameter Space parameters = [{'sel__k':k}, {'clf__max_depth':max_depth, 'clf__min_samples_split':min_samples_split}] # Conducts Parameter Optmization With Pipeline # Creating a grid search object clf = GridSearchCV(pipe, parameters, scoring='recall', cv=5) # Fits the grid search clf.fit(features_train, labels_train) # Prints the Best Parameters print('Best score:', clf.best_score_) print('Best estimator:', clf.best_estimator_) print ("###") print ("Feature selection") print ("###") # Adds the newly selected email features to the list of features append_feature_list = ['ratio_from_poi','ratio_to_poi'] for feature in append_feature_list: features_list.append(feature) # Removes the non selected email features from the list of features remove_feature_list = ['from_this_person_to_poi','from_poi_to_this_person','from_messages'] for feature in remove_feature_list: features_list.remove(feature) ################### ### Classifiers ### ################### print ("###########") print ("Classifiers") print ("###########") ### Task 4: Try a varity of classifiers ### Please name your classifier clf for easy export below. ### Note that if you want to do PCA or other multi-stage operations, ### you'll need to use Pipelines. For more info: ### http://scikit-learn.org/stable/modules/pipeline.html # List of classifiers classifiers = [GaussianNB(), tree.DecisionTreeClassifier(), ensemble.AdaBoostClassifier(), ensemble.RandomForestClassifier(), neighbors.KNeighborsClassifier(), SVC(gamma='auto')] # Evaluates the performance for each classifier for classifier in classifiers: clf = classifier test_classifier(clf, my_dataset, features_list) ######################## ### Algorithm Tuning ### ######################## ### Task 5: Tune your classifier to achieve better than .3 precision and recall ### using our testing script. Check the tester.py script in the final project ### folder for details on the evaluation method, especially the test_classifier ### function. Because of the small size of the dataset, the script uses ### stratified shuffle split cross validation. For more info: ### http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedShuffleSplit.html # Extracts the labels and features data = featureFormat(data_dict, features_list,remove_all_zeroes=True) labels, features = targetFeatureSplit(data) features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=0.3, random_state=42) ''' ### THIS IS NOT USED scaler = MinMaxScaler() rescaled_data = scaler.fit_transform(data) rescaled_labels, rescaled_features = targetFeatureSplit(rescaled_data) features_train, features_test, labels_train, labels_test = train_test_split(rescaled_features, rescaled_labels, test_size=0.3, random_state=42) ''' ################################ ### Pipeline: Scaler/PCA/KNN ### ################################ print ("#############") print ("Pipeline: KNN") print ("#############") # Creates an standardscaler object scaler = MinMaxScaler() # Creates a pca object pca = decomposition.PCA() # Creates a DecisionTreeClassifier knn = neighbors.KNeighborsClassifier() # Creates a pipeline of three steps. First, standardizing the data. # Second, tranforms the data with PCA. # Third, trains a Decision Tree Classifier on the data. pipe = Pipeline(steps=[('scaler', scaler), ('pca', pca), ('knn', knn)]) # Creates Parameter Space # Creating a list of a sequence of integers from 1 to the number of features + 1 n_components = list(range(1,len(features_list),1)) # Creates lists of parameter for KNN Classifier n_neighbors = list(range(1,10)) # Creates a dictionary of all the parameter options # Note that we can access the parameters of steps of a pipeline by using '__’ parameters = dict(pca__n_components=n_components, knn__n_neighbors=n_neighbors, ) # Conducts Parameter Optmization With Pipeline # Creating a grid search object clf = GridSearchCV(pipe, parameters, scoring='recall', cv=5) # Fits the grid search clf.fit(features_train, labels_train) # Prints the Best Parameters print('Best n_neighbors:', clf.best_estimator_.get_params()['knn__n_neighbors']) print('Best number of components:', clf.best_estimator_.get_params()['pca__n_components']) print(clf.best_estimator_.get_params()['knn']) ############################# ### Classifier Tuning: DT ### ############################# print ("#####################") print ("Classifier Tuning: DT") print ("#####################") ### GridSearchCV DT criterion = ['gini', 'entropy'] max_depth = [2,4,6,8,10,15,20,50] min_samples_split = [2,10,20,30,40] parameters = {'criterion':criterion, 'max_depth':max_depth, 'min_samples_split':min_samples_split} clf = GridSearchCV(tree.DecisionTreeClassifier(), parameters, scoring='recall', cv=5) clf.fit(features_train, labels_train) # Viewing The Best Parameters print('Best criterion:', clf.best_estimator_.get_params()['criterion']) print('Best max_depth:', clf.best_estimator_.get_params()['max_depth']) print('Best min_samples_split:', clf.best_estimator_.get_params()['min_samples_split']) ''' ############################# ### Classifier Tuning: AB ### ############################# print ("#####################") print ("Classifier Tuning: AB") print ("#####################") ### GridSearchCV AdaBoost parameters = {"n_estimators": np.arange(10,300,10), "learning_rate": [0.01, 0.05, 0.1, 1] } # run grid search clf = GridSearchCV(ensemble.AdaBoostClassifier(), parameters, scoring='recall', cv=5) clf.fit(features_train, labels_train) # Viewing The Best Parameters print('') print('Best n_estimators:', clf.best_estimator_.get_params()['n_estimators']) print('Best learning_rate:', clf.best_estimator_.get_params()['learning_rate']) ############################## ### Classifier Tuning: KNN ### ############################## print ("######################") print ("Classifier Tuning: KNN") print ("######################") ### GridSearchCV KNN parameters = {'n_neighbors': list(range(1,10))} # run grid search clf = GridSearchCV(neighbors.KNeighborsClassifier(), parameters, scoring='recall', cv=5) clf.fit(features_train, labels_train) # Viewing The Best Parameters print('') print('Best n_neighbors:', clf.best_estimator_.get_params()['n_neighbors']) ''' ############################ ### Optimized Classifier ### ############################ print ("####################") print ("Optimized Classifier") print ("####################") clf = tree.DecisionTreeClassifier(criterion='entropy',max_depth=6,min_samples_split=2) test_classifier(clf, my_dataset, features_list) # Prints the feature importance print("Features importance:") for importance, feature in sorted(zip(clf.feature_importances_, features_list[1:]),reverse=True)[:5]: print ('{}: importance = {:.3}'.format(feature, importance)) ''' pipe = Pipeline([('sel', SelectKBest(k=5)), ('clf', tree.DecisionTreeClassifier(criterion='gini',max_depth=None,min_samples_split=2))]) test_classifier(pipe, my_dataset, features_list) features_list = ['poi','other','ratio_to_poi'] clf = tree.DecisionTreeClassifier(criterion='entropy',max_depth=6,min_samples_split=2) test_classifier(clf, my_dataset, features_list) clf = ensemble.AdaBoostClassifier(learning_rate=1,n_estimators=20) test_classifier(clf, my_dataset, features_list) clf = neighbors.KNeighborsClassifier(n_neighbors=1) test_classifier(clf, my_dataset, features_list) ''' ################################################## ### Dump Classifier, Dataset and Features List ### ################################################## ### Task 6: Dump your classifier, dataset, and features_list so anyone can ### check your results. You do not need to change anything below, but make sure ### that the version of poi_id.py that you submit can be run on its own and ### generates the necessary .pkl files for validating your results. dump_classifier_and_data(clf, my_dataset, features_list) print ("Total elapsed time:", round(time.time()-t0, 3), "s")
95ce0e3f20b9778bbf4c560c9f34ce40f3ad8aa9
[ "Python" ]
1
Python
NicolasAuber/Udacity_Enron
4f294e2ee07d0e837d86b7ea7f3808ec49124161
dc2abfd5b1013c88a988deee096b93a89e9a2781
refs/heads/main
<file_sep>a = 6502 b = 8086 c = a; a = b; b = c print(a,b)<file_sep>a = 6502 b = 8086 a = a + b; b = a - b; a = a - b print(a,b)
56e34a31425e24a5174a835ab3bb5965068d437f
[ "Lua" ]
2
Lua
VadimSVV/Other
e6d0da666d797a012dc6a9d9f80cb40516b87f86
b89cf2e452a1eef1d9bed51101a18e0485ecc0db
refs/heads/master
<repo_name>mercma/stuff<file_sep>/pluginconfig.py """ Configuration information specific to Plug-in """ class CircusPluginConfig(CircusBaseConfig): def __init__(self): self._name = '' self._cmd = None self._use = '' self._singleton = True self._copy_env = True self._copy_path = True self._close_child_stderr = False self._close_child_stdout = False self._priority = 1 @property def use(self): return self._name @use.setter def use(self, value): self._use = str(value) <file_sep>/arbiterconfig.py """ Configuration information specific to arbiter """ from distutils.util import strtobool from circus.wconfig.baseconfig import CircusBaseConfig class CircusArbiterConfig(CircusBaseConfig): def __init__(self): super(CircusArbiterConfig, self).__init__() self._name = '' self._cmd = None self._endpoint = None self._pubsub_endpoint = None self._check_delay = 1 self._prereload_fn = None self._statsd = False self._stats_endpoint = None self._papa_endpoint = None self._multicast_endpoint = None self._plugins = None self._sockets = None self._warmup_delay = 0 self._httpd = None self._loop = None self._httpd_host = 'localhost' self._httpd_port = 8080 self._debug = False self._debug_gc = False self._ssh_server = None self._pidfile = None self._loglevel = None self._logoutput = None self._loggerconfig = None self._fqdn_prefix = None self._umask = None self._endpoint_owner = None self._singleton = True self._copy_env = True self._copy_path = True self._close_child_stderr = False self._close_child_stdout = False self._priority = 1 @property def endpoint(self): return self._name @endpoint.setter def endpoint(self, value): self._use = str(value) @property def pubsub_endpoint(self): return self._pubsub_endpoint @pubsub_endpoint.setter def pubsub_endpoint(self, value): self._pubsub_endpoint = str(value) @property def check_delay(self): return self._check_delay @check_delay.setter def check_delay(self, value): self._check_delay = int(value) @property def prereload_fn(self): return self._prereload_fn @prereload_fn.setter def prereload_fn(self): self._prereload_fn = str(value) @property def statsd(self): return self._statsd @statsd.setter def statsd(self, value): self._statsd = strtobool(str(value)) @property def stats_endpoint(self): return self._stats_endpoint @stats_endpoint.setter def stats_endpoint(self, value): self._stats_endpoint = str(value) @property def papa_endpoint(self): return self._papa_endpoint @papa_endpoint.setter def papa_endpoint(self, value): self._papa_endpoint = str(value) @property def multicast_endpoint(self): return self._multicast_endpoint @multicast_endpoint.setter def multicast_endpoint(self, value): self._multicast_endpoint = value @property def plugins(self): return self._plugins @plugins.setter def plugins(self, value): self._plugins = value @property def sockets(self): return self._sockets @sockets.setter def sockets(self, value): self._sockets = value @property def warmup_delay(self): return self._warmup_delay @warmup_delay.setter def warmup_delay(self, value): self._warmup_delay = int(value) @property def httpd(self): return self._httpd @httpd.setter def httpd(self, value): self._httpd = str(value) @property def loop(self): return self._loop @loop.setter def loop(self, value): self._loop = value @property def httpd_host(self): return self._httpd_host @httpd_host.setter def httpd_host(self, value): self._httpd_host = str(value) @property def httpd_port(self): return self._httpd_port @httpd_port.setter def httpd_port(self, value): self._httpd_port = int(value) @property def debug(self): return self._debug @debug.setter def debug(self, value): self._debug = strtobool(str(value)) @property def debug_gc(self): return self._debug_gc @debug_gc.setter def debug_gc(self, value): self._debug_gc = strtobool(str(value)) @property def ssh_server(self): return self._ssh_server @ssh_server.setter def ssh_server(self, value): self._ssh_server = str(value) @property def pidfile(self): return self._pidfile @pidfile.setter def pidfile(self, value): self._pidfile = str(value) @property def loglevel(self): return self._loglevel @loglevel.setter def loglevel(self, value): self._loglevel = value @property def logoutput(self): return self._logoutput @logoutput.setter def logoutput(self, value): self._logoutput = str(value) @property def fqdn_prefix(self): return self._fqdn_prefix @fqnd_prefix.setter def fqdn_prefix(self, value): self._fqdn_prefix = str(value) @property def umask(self): return self._umask @umask.setter def umask(self, value): self._umask = value @property def endpoint_owner(self): return self._endpoint_owner @endpoint_owner.setter def endpoint_owner(self, value): self._endpoint_owner = str(value) <file_sep>/metatest.py class MetaEnum(type): def __contains__(cls, value): for k,v in cls.__dict__.items(): if(type(v) is property): if (k == value): return True return False #return x in range(cls.k) class BaseEnum(metaclass=MetaEnum): def __init__(self): self._name = 'BaseEnum.name' @property def name(self): return self._name @name.setter def name(self, value): self._name = value class MyEnum(BaseEnum): def __init__(self): super(MyEnum, self).__init__() self._name = 'MyEnum.name' self._subname = 'MyEnum.subname' @property def subname(self): return self._subname @subname.setter def subname(self, value): self._subname = value baseenum = BaseEnum() myenum = MyEnum() print('name in baseenum %s' % baseenum.name) baseenum.name = 'BaseEnum.name.changed' print('name in baseenum %s' % baseenum.name) print('name in myenum %s' % myenum.name) myenum.name = 'MyEnum.name.changed' print('name in myenum %s' % myenum.name) print('subname in myenum %s' % myenum.subname) print('name in BaseEnum %s' % ('name' in BaseEnum)) print('name in MyEnum %s' % ('name' in MyEnum)) print('name in baseenum %s' % ('name' in baseenum)) <file_sep>/metaconfig.py #from future.utils import with_metaclass class MetaConfig(type): def __contains__(cls, value): print('__contains') for k,v in cls.__dict__.items(): if (type(v) is property): if (k == value): return True return False <file_sep>/baseconfig.py """ Configuration properties common to everything: Arbiter, Watcher, Plugin, etc """ class CircusBaseConfig(object): def __init__(self): self._name = '' self._cmd = None self._singleton = False self._copy_env = False self._copy_path = False self._close_child_stderr = False self._close_child_stdout = False self._priority = 0 self._ssh_server = None def __getitem__(self, value): return getattr(self, value) def __setitem__(self, key, value): setattr(self, key, value) @classmethod def __contains__(cls, value): for mcls in cls.__mro__: for k,v in mcls.__dict__.items(): if (type(v) is property): if (k == value): return True return False def pop(self, value): return getattr(self, value) def keys(self): wkeys = [] for k, v in self.__dict__.items(): if (type(v) is property): wkeys.add[k] return wkeys @property def name(self): return self._name @name.setter def name(self, value): self._name = value @property def cmd(self): return self._cmd @cmd.setter def cmd(self, value): self._cmd = str(value) @property def singleton(self): return bool(self._singleton) @singleton.setter def singleton(self, value): self._singleton = strtobool(str(value)) @property def copy_env(self): return bool(self._copy_env) @copy_env.setter def copy_env(self, value): self._copy_env = strtobool(str(value)) @property def priority(self): return self._priority @priority.setter def priority(self, value): self._priority = int(value) @property def ssh_server(self): return self._ssh_server @ssh_server.setter def ssh_server(self, value): self._ssh_server = str(value) <file_sep>/basetest.py from circus.wconfig.baseconfig import CircusBaseConfig from circus.wconfig.sockconfig import CircusSockConfig from circus.wconfig.watcherconfig import CircusWatcherConfig if __name__ == "__main__": a = CircusBaseConfig() b = CircusSockConfig() c = CircusWatcherConfig() print('a:%s:%s' % (a.name, a['name'])) print('b:%s:%s' % (b.name, b['name'])) print('c:%s' % c.name) a['name'] = 'basetest' if 'name' in a: print('name in a') if 'name' in b: print('name in b') <file_sep>/clstest.py from pprint import pprint from distutils.util import strtobool from circus.wconfig.baseconfig import CircusBaseConfig class MetaConfig(type): @classmethod def __contains__(cls, value): for k,v in cls.__dict__.items(): if (type(v) is property): if (k == value): return True return False #class Base(object): # pass class BaseConfig(object): def __init__(self): self._name = 'Base.name' def __getitem__(self, value): return getattr(self, value) def __setitem__(self, key, value): setattr(self, key, value) @classmethod def __contains__(cls, value): for mcls in cls.__mro__: for k,v in mcls.__dict__.items(): if (type(v) is property): if (k == value): return True return False @property def name(self): return self._name @name.setter def name(self, value): self._name = value class SubConfig(BaseConfig): def __init__(self): super(SubConfig, self).__init__() self._name = 'SubConfig.name' self._sub = 'SubConfig.sub' @property def sub(self): return self._sub if __name__ == "__main__": a = BaseConfig() b = SubConfig() print('name' in a) print('name' in b) a['name'] = 'test.name' a.name = 'new' b.name = 'subnew' print('base %s' % a.name) print('sub %s:%s' % (b.name, b.sub)) <file_sep>/sockconfig.py from circus.wconfig.baseconfig import CircusBaseConfig class CircusSockConfig(CircusBaseConfig): def __init__(self): super(CircusSockConfig, self).__init__() self._name = 'Sock' self._socket = 'socket' @property def socket(self): return self._socket @socket.setter def socket(self, value): self._socket = str(value) <file_sep>/test.py import signal import sys from distutils.util import strtobool # TODO: validate values for all properties class Test(object): def __init__(self): self._env = None #self._env = '' self._singleton = False self._max_age = 0 def __getitem__(self, value): print("__getitem__(%s):" % value) print("type(%s):" % type(value)) #sys.exit(1) #return "test" return getattr(self, value) def __setitem__(self, key, value): return setattr(self, key, value) @classmethod def __contains__(cls, value): for mcls in cls: for k,v in Test.__dict__.items(): if (type(v) is property): if (k == value): return True return False def keys(self): wkeys = [] for k, v in self.__dict__.items(): if(type(v) is property): wkeys.add[k] return wkeys @property def env(self): return self._env @env.setter def env(self, value): self._env = value @property def singleton(self): return bool(self._singleton) @singleton.setter def singleton(self, value): self._singleton = strtobool(str(value)) @property def max_age(self): return self._max_age @max_age.setter def max_age(self, value): self._max_age = int(value) if __name__ == "__main__": a = Test() for k,v in Test.__dict__.items(): if (type(v) is property): print("%s:%s" % (k, getattr(a, k))) #print("a['singleton']:%s" % a['singleton']) #a['singleton'] = True #print("a['singleton']:%s" % a['singleton']) #print('singleton:%s' % a.singleton) #print('if singleton in a') if 'singleton' in a: print('singleton is in a') else: print('singleton not int a') <file_sep>/processhandler.py import os import re from configparser import ConfigParser from circus.plugins import CircusPlugin from circus import logger class ProcessHandler(CircusPlugin): name = 'processhandler' def __init__(self, *args, **config): super(ProcessHandler, self).__init__(*args, **config) self.configfile = config.get('configfile') def _handle_action_add(self): logger.debug('_handle_action_add') # read the config file config = ConfigParser(allow_no_value = True) config.read(self.configfile) # the section in the config file is # [watcher:<self.watcher_name>] watcher_section = "watcher:{0}".format(self.watcher_name) # get the options for the 'add'ed process watcher_msg = self.call("options", name=self.watcher_name) # configparser needs to have the '%' symbol escaped # for the *_stream.timestamp options for k,v in watcher_msg.get('options').items(): match = re.search('time_format$', k) if match: result = re.sub("%", "%%", v) watcher_msg.get('options')[k] = result # add the config section to the file config[watcher_section] = watcher_msg.get('options') # remove any 'empty' keys empty_keys = [k for k,v in config[watcher_section].items() if not v] for k in empty_keys: config[watcher_section].pop(k, None) # write the updated configuration file with open(self.configfile,'w') as configfile: config.write(configfile) def _handle_action_remove(self): logger.debug('_handle_action_remove') # read the config file config = ConfigParser(allow_no_value = True) config.read(self.configfile) # the section in the config file is # [watcher:<self.watcher_name>] watcher_section = "watcher:{0}".format(self.watcher_name) #remove the section from the config file #del config[self.watcher_name] config.pop(watcher_section, None) #config.popitem(self.watcher_name) with open(self.configfile, 'w') as configfile: config.write(configfile) def handle_init(self): pass def handle_stop(self): pass def handle_recv(self, data): self.watcher_name, self.action, self.msg = self.split_data(data) logger.debug('[watcher:%s] action:\'%s\'' % (self.watcher_name, self.action)) #self.msg_dict = self.load_message(self.msg) if (self.action == 'add'): self._handle_action_add() if (self.action == 'remove'): self._handle_action_remove() if (self.action == 'updated'): self._handle_action_add() <file_sep>/WatcherConfiguration.py import collections # TODO: validate values for all properties class WatcherConfiguration(object): def __init__(self): self._name = None self._cmd = None self._args = None self._numprocesses = 1 self._working_dir = None self._shell = False self._uid = None self._gid = None self._send_hup = False self._stop_signal = 'SIGHUP' self._stop_children = True self._env = None self._stdout_stream = None self._stderr_stream = None self._priority = 0 self._singleton = False self._use_sockets = False self._on_demand = False self._copy_env = False self._copy_path = False self._max_age = 0 self._max_age_variance = 0 self._respawn = True self._virutalenv = None self._stdin_socket = None self._close_child_stdin = True self._close_child_stdout = False self._close_child_stderr = False @property def name(self): return self._name @name.setter def name(self, value): if (isinstance(value, str)): self._name = value else: raise ValueError('name must be a string') @property def cmd(self): return self._cmd @cmd.setter def cmd(self, value): if (type(value) is str): self._cmd = value else: raise ValueError('cmd must be a string') @property def args(self): return self._args @args.setter def args(self, value): if (type(value) is str): self._args = value else: raise ValueError('args must be a string') @property def numprocesses(self): return self._numprocesses @numprocesses.setter def numprocesses(self, value): if (type(value) is int): self._numprocesses = value else: raise ValueError('numprocesses must be an integer') @property def working_dir(self): return self._working_dir @working_dir.setter def working_dir(self, value): if (type(value) is str): self._working_dir = value else: raise ValueError('working_dir must be a string') @property def shell(self): return self._shell @shell.setter def shell(self, value): if (type(value) is bool): self._shell = value else: raise ValueError('shell must be a boolean') @property def uid(self): return self._uid @uid.setter def uid(self, value): if (type(value) is int): self._uid = value else: raise ValueError('uid must be an integer') @property def gid(self): return self._gid @gid.setter def gid(self, value): if (type(value) is int): self._gid = value else: raise ValueError('gid must be an integer') @property def send_hup(self): return self._send_hup @send_hup.setter def send_hup(self, value): if (type(value) is bool): self._send_hup = value else: raise ValueError('send_hup must be an boolean') @property def stop_signal(self): return self._stop_signal @stop_signal.setter def stop_signal(self, value): #TODO: create a signel validation self._stop_signal = value @property def stop_children(self): return self._stop_children @stop_children.setter def stop_children(self, value): if (type(value) is bool): self._stop_children = value else: raise ValueError('stop_children must be boolean') @property def env(self): return self._env @env.setter def env(self, value): self._env = value # TODO: need to get all the rlimits @property def stdout_stream(self): return self._stdout_stream @stdout_stream.setter def stdout_stream(self, value): #TODO: validate the items() #if (isinstance(dictionay, dict)): if (type(value) is dict): if (type(self._stdout_stream) is not dict): self._stdout_stream = dict() for k, v in value.items(): self._stdout_stream[k] = v else: raise ValueError('stdout_stream must be a dict') @property def stderr_stream(self): return self._stderr_stream @stderr_stream.setter def stderr_stream(self, value): if (type(value) is dict): print(type(self._stderr_stream)) if (type(self._stderr_stream) is not dict): print('make it a dict!!') self._stderr_stream = dict() for k, v in value.items(): self._stdout_stream[k] = v else: raise ValueError('stderr_stream must be a dict') @property def priority(self): return self._priority @priority.setter def priority(self, value): if (type(value) is int): self._priority = value else: raise ValueError('priority must be an integer') @property def singleton(self): return self._singleton @singleton.setter def singleton(self, value): if (type(value) is bool): self._singleton = value else: raise ValueError('singleton must be a boolean') @property def use_sockets(self): return self._use_sockets @use_sockets.setter def use_sockets(self, value): if (type(value) is bool): self._use_sockets = value else: raise ValueError('use_sockets must be a boolean') @property def on_demand(self): return self._on_demand @on_demand.setter def on_demand(self, value): if (type(value) is bool): self._on_demand = value else: raise ValueError('on_demand must be a boolean') @property def copy_env(self): return self._copy_env @copy_env.setter def copy_env(self, value): if (type(value is bool)): self._copy_env = value else: raise ValueError('copy_env must be a boolean') @property def copy_path(self): return self._copy_path @copy_path.setter def copy_path(self, value): if (type(value is bool)): self._copy_path = value else: raise ValueError('on_path must be a boolean') @property def max_age(self): return self._max_age @max_age.setter def max_age(self, value): if (type(value) is int): self._max_age = value else: raise ValueError('max_age must be an integer') @property def max_age_variance(self): return self._max_age_variance @max_age_variance.setter def max_age_variance(self, value): if (type(value) is int): self._max_age_variance = value else: raise ValueError('max_age_variance must be an integer') # TODO: need to get all the hooks # TODO: need to figure out what to do with options @property def respawn(self): return self._respawn @respawn.setter def respawn(self, value): if (type(value) is bool): self._respawn = value else: raise ValueError('respawn must be a boolean') @property def virutalenv(self): return self._virtualenv @virutalenv.setter def virutalenv(self, value): if (type(value) is str): self._virtualenv = value else: raise ValueError('virutualenv need to be a string path') @property def stdin_socket(self): return self._stdin_socket @stdin_socket.setter def stdin_socket(self, value): #TODO: what does this value need to be? pass @property def close_child_stdin(self): return self._close_child_stdin @close_child_stdin.setter def close_child_stdin(self, value): if (type(value) is bool): self._close_child_stdin = value else: raise ValueError('close_stdin_child must be a boolean') @property def close_child_stdout(self): return self._close_child_stdout @close_child_stdout.setter def close_child_stdout(self, value): if (type(value) is bool): self._close_child_stdout = value else: raise ValueError('close_child_stdout must be a boolean') @property def close_child_stderr(self): return self._close_child_stderr @close_child_stderr.setter def close_child_stderr(self, value): if (type(value) is bool): self._close_child_stdout = value else: raise ValueError('close_child_stderr must be a boolean') if __name__ == "__main__": a = WatcherConfiguration() a.send_hup = True print("%s" % a.send_hup) try: a.stdout_stream = 11 print("%s:%s" % (type(a.stdout_stream), a.stdout_stream)) except ValueError as e: print(str(e)) pass try: a.stdout_stream = { 'class': 'FileOutputStream', 'filename': '/Users/mercma/output.log' } print("%s:%s" % (type(a.stdout_stream), a.stdout_stream)) except ValueError as e: print(str(e)) pass try: a.stdout_stream = 10 print("%s:%s" % (type(a.stdout_stream), a.stdout_stream)) except ValueError as e: print(str(e)) pass
be0e8dc15c903b0887844562748be2acfeec5a4c
[ "Python" ]
11
Python
mercma/stuff
d7925760aaaf29543f8289fa0c4fc4d049342166
64b5e7ce64617092e31c7a611fdee8a49b6ff65a
refs/heads/main
<file_sep>import cv2 import numpy as np import PySimpleGUI as sg import time from playsound import playsound as play sg.theme("LightGreen") layout = [ [sg.Text("STUD-bot v1", size=(60, 1), justification="center")], [sg.Image(filename="", key="-IMAGE-")], [ sg.Text('Max break Time in Minutes', size=(10, 1)), sg.Slider( (1, 30), 0, 1, orientation="h", size=(40, 15), key="-MAX BREAK TIME-", ), ], [ sg.Text("Eye Aspect Ratio", size=(10, 1)), sg.Slider( (0, 100), 0, 1, orientation="h", size=(40, 15), key="-EYE_AR_THRESH-", ) ], [ sg.Text("Consequitive frames", size=(10, 1), ), sg.Slider( (0, 60), 0, 1, orientation="h", size=(40, 15), key="-EYE_AR_CONSEC_FRAMES-", ) ], [sg.Button("Exit", size=(10, 1))], ] window = sg.Window("Stud-bot", layout, location=(800, 400)) net = cv2.dnn.readNet("yolov3.weights","yolov3.cfg") classes = [] with open("coco.names","r") as f: classes = [line.strip() for line in f.readlines()] layer_names = net.getLayerNames() outputlayers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] colors= np.random.uniform(0,255,size=(len(classes),3)) from scipy.spatial import distance as dist from imutils.video import VideoStream from imutils import face_utils from threading import Thread import numpy as np import playsound import argparse import imutils import time import dlib import cv2 def sound_alarm(path): # play an alarm sound playsound.playsound(path) def eye_aspect_ratio(eye): # compute the euclidean distances between the two sets of # vertical eye landmarks (x, y)-coordinates A = dist.euclidean(eye[1], eye[5]) B = dist.euclidean(eye[2], eye[4]) # compute the euclidean distance between the horizontal # eye landmark (x, y)-coordinates C = dist.euclidean(eye[0], eye[3]) # compute the eye aspect ratio ear = (A + B) / (2.0 * C) # return the eye aspect ratio return ear args = {"shape_predictor": "shape_predictor_68_face_landmarks.dat", "alarm": "alarm.wav", "webcam": 0} EYE_AR_THRESH = 0.3 EYE_AR_CONSEC_FRAMES = 15 COUNTER = 0 ALARM_ON = False print("[INFO] loading facial landmark predictor...") detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(args["shape_predictor"]) (lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"] (rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"] print("[INFO] starting video stream thread...") vs = VideoStream(src=args["webcam"]).start() time.sleep(1.0) frame_id=0 font = cv2.FONT_HERSHEY_PLAIN starting_time = time.time() break_time=0 while True: person_detected=False frame_start_time=time.time() event, values = window.read(timeout=20) if event == "Exit" or event == sg.WIN_CLOSED: break EYE_AR_THRESH = values["-EYE_AR_THRESH-"]/100 EYE_AR_CONSEC_FRAMES = values["-EYE_AR_CONSEC_FRAMES-"] frame_id += 1 frame = vs.read() frame = imutils.resize(frame, width=450) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) height, width, channels = frame.shape rects = detector(gray, 0) blob = cv2.dnn.blobFromImage(frame, 0.00392, (320, 320), (0, 0, 0), True, crop=False) # reduce 416 to 320 net.setInput(blob) outs = net.forward(outputlayers) class_ids = [] confidences = [] boxes = [] for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.3: center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) x = int(center_x - w / 2) y = int(center_y - h / 2) boxes.append([x, y, w, h]) confidences.append( float(confidence)) class_ids.append(class_id) indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.4, 0.6) for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) if(label=='person'): person_detected=True if (label == "cell phone"): play('alarm.wav') confidence = confidences[i] color = colors[class_ids[i]] cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2) cv2.putText(frame, label + " " + str(round(confidence, 2)), (x, y + 30), font, 1, (255, 255, 255), 2) for rect in rects: shape = predictor(gray, rect) shape = face_utils.shape_to_np(shape) leftEye = shape[lStart:lEnd] rightEye = shape[rStart:rEnd] leftEAR = eye_aspect_ratio(leftEye) rightEAR = eye_aspect_ratio(rightEye) ear = (leftEAR + rightEAR) / 2.0 leftEyeHull = cv2.convexHull(leftEye) rightEyeHull = cv2.convexHull(rightEye) cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1) cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1) if ear < EYE_AR_THRESH: COUNTER += 1 if COUNTER >= EYE_AR_CONSEC_FRAMES: if not ALARM_ON: ALARM_ON = True play(args["alarm"]) cv2.putText(frame, "DROWSINESS ALERT!", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) else: COUNTER = 0 ALARM_ON = False cv2.putText(frame, "EAR: {:.2f}".format(ear), (300, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) elapsed_time = time.time() - starting_time fps = frame_id / elapsed_time cv2.putText(frame, "FPS:" + str(round(fps, 2)), (10, 50), font, 2, (0, 0, 0), 1) #cv2.imshow("Frame", frame) #key = cv2.waitKey(1) & 0xFF if (person_detected==False): break_time+=time.time()-frame_start_time cv2.putText(frame, "Break Time" + str(break_time//60)+":"+str(round(break_time%60,2)), (10, 100), font, 2, (0, 0, 0), 1) if break_time>values["-MAX BREAK TIME-"]*60: play('alarm.wav') else: break_time=0 imgbytes = cv2.imencode(".png", frame)[1].tobytes() window["-IMAGE-"].update(data=imgbytes) #if key == ord("q"): # break cv2.destroyAllWindows() window.close() vs.stop()<file_sep>from flask import Flask, jsonify, request import time from playsound import playsound # from pydub import AudioSegment # from pydub.playback import play app = Flask(__name__) urls = {} blacklisted = frozenset(["www.youtube.com", "www.facebook.com", "www.instagram.com"]) def url_strip(url): if "http://" in url or "https://" in url: url = url.replace("https://", '').replace("http://", '').replace('\"', '') if "/" in url: url = url.split('/', 1)[0] return url @app.route('/send_url', methods=['POST']) def send_url(): resp_json = request.get_data() params = resp_json.decode() url = params.replace("url=", "") url = url_strip(url) if url in blacklisted: playsound('alarm.wav') print(url) # song = AudioSegment.from_mp3("audio.mp3") # play(song) urls[url] = urls.get(url, 0) + 1 print(urls) return jsonify({'message': 'success!'}), 200 app.run(host='0.0.0.0', port=5000) <file_sep>import os from multiprocessing import Pool processes = ('UI2.py', 'extension.py') def run_process(process): os.system('python {}'.format(process)) if __name__ == '__main__': pool = Pool(processes=2) pool.map(run_process, processes)<file_sep> # STUD-bot Repository for the project of Study concentration BOT Features: 1. Drowsiness detection : Using the Dlib library and using the 6 facial landmarks of the eye using a threshold while calculating the Eye Aspect Ratio 2. Mobile Phone Detection: Using YoloV3 pretrained on MS-COCO. Pretrained model with weights from Pjreddie Darknet. 3. Website Alert: Flask server with chrome extensionm that gives us an alert when ever a preflagged website is visited. 4. Break Timer: Setting a timer for breaks whenever user in not detected in fromnt of laptop. Members: 1. <NAME> https://github.com/aishik-rakshit 2. <NAME> https://github.com/anuraagm19 3. <NAME> https://github.com/astroturk
5782330971adb9f500af37c082a45e745181b05a
[ "Markdown", "Python" ]
4
Python
simrit1/STUD-bot
d0b8c665d27f6f42c8c0acd18773a4b94ae9e241
2cfc05f7dcdf1986562b9cdfaf6491dc12a42acc
refs/heads/master
<repo_name>Chimaobi-Johnson/marvis_store<file_sep>/routes/store.js const express = require('express'); const router = express.Router(); router.get('/', (req, res) => { res.render('store', { pageTitle: 'Marvis Store', path: '/store' }); }); router.get('/dashboard', (req, res) => { res.render('store/dashboard', { pageTitle: 'Marvis Store - Dashboard', path: '/store/dashboard' }); }); module.exports = router; <file_sep>/controllers/admin.js const crypto = require('crypto'); const bcrypt = require('bcryptjs'); const User = require('../model/User'); const { validationResult } = require('express-validator/check'); exports.getDashboard = (req, res) => { res.render('admin', { pageTitle: 'Admin', path: '/admin', user: req.user }); } exports.getUsers = (req, res) => { User.find().then(users => { res.render('admin/users', { pageTitle: 'All Users', path: '/admin/users', users: users }); }).catch(err => { res.status(500).render('admin/users', { pageTitle: 'All Users', path: '/admin/users', users: null }); }) } exports.getAddUser = (req, res) => { let flashMsg = req.flash('regAdminSuccess'); if (flashMsg.length > 0) { flashMsg = flashMsg[0]; } else { flashMsg = null; } res.render('admin/addUser', { pageTitle: 'Add Users', path: '/admin/user/add', flashMessage: flashMsg, errorMessage: null, oldInput: { firstName: '', lastName: '', gender: '', email: '', password: '', address: '', country: '', role: '', image: '', confirmPassword: '' } }); } exports.getEditUser = (req, res) => { let flashMsg = req.flash('userUpdateSuccess'); if (flashMsg.length > 0) { flashMsg = flashMsg[0]; } else { flashMsg = null; } User.findById(req.params.id).then(user => { if(!user) { res.render('admin/editUser', { pageTitle: 'Edit Users', path: '/admin/user/edit/:id', flashMessage: flashMsg, errorMessage: 'User not found', oldInput: { firstName: '', lastName: '', gender: '', email: '', password: '', address: '', country: '', role: '', image: '', confirmPassword: '' } }); } res.render('admin/editUser', { pageTitle: 'Edit Users', path: '/admin/user/edit/:id', flashMessage: flashMsg, errorMessage: null, oldInput: { firstName: user.firstName, lastName: user.lastName, gender: user.gender, email: user.email, password: <PASSWORD>, address: user.address, country: user.country, role: user.role, image: user.image, confirmPassword: user.confirmPassword } }); }) } exports.getProducts = (req, res) => { res.render('admin/products', { pageTitle: 'All Products', path: '/admin/products', user: req.user }); } exports.getAccounts = (req, res) => { res.render('admin/accounts', { pageTitle: 'Accounts', path: '/admin/accounts', user: req.user }); } exports.getPosts = (req, res) => { res.render('admin/posts', { pageTitle: 'All Posts', path: '/admin/posts', user: req.user }); } exports.getComments = (req, res) => { res.render('admin/comments', { pageTitle: 'All Comments', path: '/admin/comments', user: req.user }); } exports.addUser = (req, res) => { const { firstName, lastName, gender, email, address, country, role, image, password } = req.body; console.log(req.body) const errors = validationResult(req); if (!errors.isEmpty()) { console.log(errors.array()); return res.status(422).render('admin/addUser', { path: '/admin/user/add', pageTitle: 'Add User', flashMessage: null, errorMessage: errors.array()[0].msg, oldInput: { firstName, lastName, gender, email, password, address, country, role, image, confirmPassword: req.body.confirmPassword }, validationErrors: errors.array() }); } bcrypt .hash(password, 12) .then(hashedPassword => { const user = new User({ firstName, lastName, gender, email, address, country, role, image, password: <PASSWORD>, cart: { items: [] } }); return user.save(); }) .then(result => { req.flash('regAdminSuccess', 'User registered successfully') res.redirect('/admin/user/add'); }) .catch(err => { console.log(err) const error = new Error(err); error.httpStatusCode = 500; return next(error); }); } exports.updateUser = (req, res) => { const { firstName, lastName, gender, email, address, country, role, image, password } = req.body; console.log(req.params) User.updateOne({_id: req.params.id }, { ...req.body }) .then(user => { console.log(user) res.render('admin/editUser', { pageTitle: 'Update Users', path: '/admin/user/edit/:id', flashMessage: flashMsg, errorMessage: null, oldInput: { firstName: user.firstName, lastName: user.lastName, gender: user.gender, email: user.email, password: <PASSWORD>, address: user.address, country: user.country, role: user.role, image: user.image, confirmPassword: <PASSWORD> } }); }).catch(err => { console.log(err); }) }<file_sep>/routes/auth.js const express = require('express'); const { check } = require('express-validator'); const authController = require('../controllers/auth'); const { validateRegisterForm } = require('../validators/validators'); const router = express.Router(); router.get('/login', authController.getLogin); router.post('/login', authController.login); router.post('/logout', authController.logout); router.get('/register', authController.getRegister); router.post('/register', validateRegisterForm, authController.register); module.exports = router;<file_sep>/config/keys.js module.exports = { MONGO_URI: 'mongodb+srv://CharlieJohnson:<EMAIL>/marvis_store', SESSION_SECRET: '<KEY>' }<file_sep>/routes/admin.js // const path = require('path'); const express = require('express'); const adminController = require('../controllers/admin'); const { validateRegisterForm } = require('../validators/validators'); const router = express.Router(); router.get('/', adminController.getDashboard); router.get('/users', adminController.getUsers); router.get('/user/add', adminController.getAddUser); router.get('/user/edit/:id', adminController.getEditUser); router.get('/products', adminController.getProducts); router.get('/accounts', adminController.getAccounts); router.get('/posts', adminController.getPosts); router.get('/comments', adminController.getComments); router.post('/user/add', validateRegisterForm, adminController.addUser); router.post('/user/update', validateRegisterForm, adminController.updateUser); module.exports = router; <file_sep>/controllers/auth.js const crypto = require('crypto'); const bcrypt = require('bcryptjs'); const User = require('../model/User'); const { validationResult } = require('express-validator/check'); exports.getLogin = (req, res, next) => { let message = req.flash('regSuccess'); if (message.length > 0) { message = message[0]; } else { message = null; } res.render('store/login', { pageTitle: 'Marvis Store - Login', path: '/store/login', message: message, errorMessage: null }); } exports.login = (req, res, next) => { const { email, password } = req.body; User.findOne({ email: email }) .then(user => { if (!user) { return res.status(422).render('store/login', { path: '/login', pageTitle: 'Login', message: null, errorMessage: 'Invalid email or password.', oldInput: { email: email, password: <PASSWORD> }, validationErrors: [] }); } bcrypt.compare(password, user.password) .then(doMatch => { if (doMatch) { req.session.isLoggedIn = true; req.session.user = user; return req.session.save(err => { if(req.session.user.role === 'suscriber') { res.redirect('/'); } else { res.redirect('/admin'); } }); } return res.status(422).render('store/login', { path: '/login', pageTitle: 'Login', message: null, errorMessage: 'Invalid email or password.', oldInput: { email: email, password: <PASSWORD> }, validationErrors: [] }); }) .catch(err => { console.log(err); res.redirect('/login'); }); }) .catch(err => { const error = new Error(err); error.httpStatusCode = 500; return next(error); }); } exports.getRegister = (req, res, next) => { let message = req.flash('error'); if (message.length > 0) { message = message[0]; } else { message = null; } res.render('store/register', { path: '/register', pageTitle: 'Register', errorMessage: message, oldInput: { email: '', password: '', confirmPassword: '' }, validationErrors: [] }); } exports.register = (req, res, next) => { const { firstName, lastName, gender, email, password } = req.body; const errors = validationResult(req); if (!errors.isEmpty()) { console.log(errors.array()); return res.status(422).render('store/register', { path: '/register', pageTitle: 'Register', errorMessage: errors.array()[0].msg, oldInput: { firstName, lastName, gender, email, password, confirmPassword: <PASSWORD> }, validationErrors: errors.array() }); } bcrypt .hash(password, 12) .then(hashedPassword => { const user = new User({ firstName, lastName, gender, email, password: <PASSWORD>, cart: { items: [] } }); return user.save(); }) .then(result => { req.flash('regSuccess', 'Registeration successful. You can now login with your details.') res.redirect('/login'); }) .catch(err => { console.log(err) const error = new Error(err); error.httpStatusCode = 500; return next(error); }); }; exports.logout = (req, res, next) => { req.session.destroy(err => { console.log(err); res.redirect('/'); }); } <file_sep>/public/scripts/scripts.js const showMenuDropdown = (menu) => { const result = document.getElementById(menu).style.transform; if(result === 'scaleY(0)') { document.getElementById(menu).style.transform = 'scaleY(1)' } else { document.getElementById(menu).style.transform = 'scaleY(0)' } }<file_sep>/model/User.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new Schema({ image: { type: String }, imageId: { type: String }, firstName: { type: String, required: true }, lastName: { type: String, required: true }, gender: { type: String, required: true }, email: { type: String, unique: true, required: true }, password: { type: String, required: true }, address: String, country: String, role: { type: String, default: 'suscriber' }, resetToken: String, resetTokenExpiration: Date, posts: [ { type: Schema.Types.ObjectId, ref: 'Post' } ], cart: { items: [ { productId: { type: Schema.Types.ObjectId, ref: 'Product', required: true }, quantity: { type: Number, required: true } } ] } }); module.exports = mongoose.model('User', userSchema);
605a5667d75a2983e2789b7c94937dc8a0e3076d
[ "JavaScript" ]
8
JavaScript
Chimaobi-Johnson/marvis_store
02c2bfb109f4c0ef8696222e4ceb23da982e63ac
52512fa97ac5fa405ae5fc4f9743268f3edfb1bd
refs/heads/master
<repo_name>TeresaNgo-gh/Module1<file_sep>/README.md # Module1 The goal of this game is to destroy each pickup in the air. The user will instantiate a projectile using the slingshot and, like in Mission Demolition, will launch the projectile to collect items. However, instead of knocking down a castle or reaching a goal, the user will destroy each and every pickup to get to the next stage. This is similar to Roll-a-Ball. There are four levels to this game, and each level getting slightly harder. Once all the levels have been completed, the game displays "You Win!" My goal in creating this project was to combine a few different features from the games we've created this semester. I wanted to make something new, but also similar to what we've done by using previous game elements and features. <file_sep>/Assets/Scripts/Counter.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Counter : MonoBehaviour{ public int numOfPickups; static public bool goalMet = false; void Update(){ numOfPickups = GameObject.FindGameObjectsWithTag("Pickup").Length; if (numOfPickups ==0){ Counter.goalMet = true; } } } <file_sep>/Assets/Scripts/CollectPickups.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CollectPickups : MonoBehaviour{ public void OnCollisionEnter(Collision coll){ GameObject collidedWith = coll.gameObject; if(collidedWith.tag == "Pickup"){ Destroy(collidedWith); } } }
9383561b600cfe5c7bf548cbf06952cac7390bb7
[ "Markdown", "C#" ]
3
Markdown
TeresaNgo-gh/Module1
811896446ad5d9f38639349fd513242e45860f93
ea28eab7db8c4b6e4239af521df9522944803ce2
refs/heads/master
<repo_name>qw110946/rnGank<file_sep>/src/common/theme/index.js import normal from "./normal"; import night from "./night"; import { Distribution } from "../util"; const theme = Distribution( { normal, night }, {} ); export const setTheme = (...args) => theme.setType(...args); export default theme.data; <file_sep>/src/common/i18n/en.js export default { randomRecommendation: "RandomRecommend", languge: "Languge", theme: "Theme", setting: "Setting", all: "All", welfare: "Welfare", android: "Android", ios: "iOS", leisureVideo: "LeisureVideo", // Leisure expand: "Expand", // Expand web: "Web", blindRecommend: "BlindRecommend", // Blind recommend app: "app", secondsAgo: "Seconds ago", minutesAgo: "Minutes ago", hoursAgo: "hours ago", daysAgo: "days ago", unknown: "Unknown", leisure: "Leisure", skill: "Technology", dayNew: "Daily updated", chinese: "中文", japanese: "日本語", english: "English", mainColor: "Main color", normalMode: "Normal", nightMode: "Night", blue: "Blue", red: "Red", black: "Black", loading: "loading", loadFailure: "Load Failure", retry: "Retry" }; <file_sep>/src/logics/appointType/reducer.js import { APPOINT_TYPE } from "~/common/actionTypes"; import { gankio } from "~/common/Api"; import { PULLUPLOAD } from "../../components/pullUploading"; import { arrayUnique } from "../selector"; const dataState = { loaded: false, // 初次加载 refreshLoading: false, // 下拉 loading: false, //上拉 error: false, data: [], limit: 30, page: 1 }; const initState = { [gankio.type.ALL]: { ...dataState }, [gankio.type.FULI]: { ...dataState, limit: 15 }, [gankio.type.ANDROID]: { ...dataState }, [gankio.type.IOS]: { ...dataState }, [gankio.type.WEB]: { ...dataState }, [gankio.type.LEISUREVIDEO]: { ...dataState }, // 休息视频 [gankio.type.EXPAND]: { ...dataState }, // 拓展资源 [gankio.type.BLINDRECOMMEND]: { ...dataState }, // 瞎推荐 [gankio.type.APP]: { ...dataState } }; function appointType(state = initState, action = {}) { const { dataType, data, loadType } = action.payload || {}; const isRefreshRequest = loadType === APPOINT_TYPE.REFRESH; switch (action.type) { case APPOINT_TYPE.REQUEST: return { ...state, [dataType]: { ...state[dataType], loading: PULLUPLOAD.ING } }; break; case APPOINT_TYPE.REFRESH: return { ...state, [dataType]: { ...state[dataType], refreshLoading: true, loading: false, page: 1 } }; break; case APPOINT_TYPE.SUCCESS: return { ...state, [dataType]: { ...state[dataType], data: arrayUnique( isRefreshRequest ? data : [...state[dataType].data, ...data] ), refreshLoading: isRefreshRequest ? false : state[dataType].refreshLoading, // loading: isRefreshRequest? state[dataType].loading: PULLUPLOAD.ING, loading: isRefreshRequest ? PULLUPLOAD.ING : PULLUPLOAD.ING, loaded: true, page: state[dataType].page + 1 } }; break; case APPOINT_TYPE.FAILURE: return { ...state, [dataType]: { ...state[dataType], refreshLoading: isRefreshRequest ? false : state[dataType].refreshLoading, loading: isRefreshRequest ? state[dataType].loading : PULLUPLOAD.FAILURE, error: true } }; break; default: return state; } } export default appointType; <file_sep>/src/logics/userSetting/views/drawerScreen.js import React, { Component, PureComponent } from "react"; import { View, Text, StyleSheet } from "react-native"; import { connect } from "react-redux"; import { Icon } from "react-native-elements"; import { FONT_SIZE, SPACING, adaptUnits } from "~/common/constants"; import i18n from "~/common/i18n"; import theme from "~/common/theme"; import DrawerNavigateHeader from "~/components/drawerNavigateHeader"; import Button from "~/components/button"; import * as userSettingAction from "../action"; class userSetiingDrawerScreen extends Component { static navigationOptions = ({ navigation, screenProps: { i18n, theme } }) => ({ drawerLabel: i18n.setting, drawerIcon: ({ focused, tintColor }) => ( <Icon name="settings" type="material-community" color={focused ? tintColor : "#000"} /> ) }); constructor(props) { super(props); this.languges = { zh: "chinese", jp: "japanese", en: "english" }; this.languges = { zh: "chinese", jp: "japanese", en: "english" }; this.themes = { normal: "normalMode", night: "nightMode" }; this.mainColors = { black: "#383838", blue: "#2196f3", red: "#B22222" //2F4F4F }; } render() { const { mainColor, bgColor, navigation, themeName, languge, setUserSetting } = this.props; const { languges, themes, mainColors } = this; const titleColor = theme.lightText.color || "#666"; const TextColor = theme.text.color || "#000"; const iconColor = theme.lightText.color || mainColor; const langugeOptions = Object.keys(languges).map(v => ( <CheckView key={v} text={i18n[languges[v]]} textColor={TextColor} iconColor={iconColor} onPress={setUserSetting} params={{ languge: v }} active={v === languge} /> )); const themeOptions = Object.keys(themes).map(v => ( <CheckView key={v} text={i18n[themes[v]]} textColor={TextColor} iconColor={iconColor} onPress={setUserSetting} params={{ themeName: v }} active={v === themeName} /> )); const mainColorOptions = Object.keys(mainColors).map(v => ( <CheckView key={v} text={i18n[v]} textColor={mainColors[v] === "#383838" ? TextColor : mainColors[v]} iconColor={iconColor} onPress={setUserSetting} params={{ mainColor: mainColors[v] }} active={mainColors[v] === mainColor} /> )); return ( <View style={[ styles.container, { backgroundColor: bgColor }, theme.container ]} > <DrawerNavigateHeader title={i18n.setting} navigation={navigation} style={[{ backgroundColor: mainColor }, theme.headerStyle]} /> <Title text={i18n.languge} textColor={titleColor} /> {langugeOptions} <Title text={i18n.theme} textColor={titleColor} /> {themeOptions} <Title text={i18n.mainColor} textColor={titleColor} /> {mainColorOptions} </View> ); } } const Title = ({ text, textColor }) => ( <View style={styles.titleWrap}> <Text style={[styles.titleText, { color: textColor }]}>{text}</Text> </View> ); class CheckView extends PureComponent { constructor() { super(); this._onPress = this._onPress.bind(this); } _onPress() { const { onPress = () => {} } = this.props; let { params = [] } = this.props; params = Array.isArray(params) ? params : [params]; onPress(...params); } render() { const { text, textColor, active, iconColor } = this.props; return ( <Button onPress={this._onPress}> <View style={styles.CheckViewWrap}> <Text style={[styles.CheckViewText, { color: textColor }]}> {text} </Text> {active && ( <Icon name="md-checkmark-circle-outline" // md-checkbox-outline type="ionicon" size={adaptUnits(30, "H")} color={iconColor} /> )} </View> </Button> ); } } const styles = StyleSheet.create({ container: { flex: 1 }, titleWrap: { padding: SPACING * 1.5, paddingBottom: SPACING * 0.8 // paddingRight: SPACING, }, titleText: { fontSize: FONT_SIZE.XS, color: "#666" }, CheckViewWrap: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", paddingLeft: SPACING * 2, paddingRight: SPACING * 2, height: adaptUnits(80, "H") // paddingTop: SPACING * 0.8, // paddingBottom: SPACING * 0.8, }, CheckViewText: { fontSize: FONT_SIZE.NR, color: "#000" } }); export default connect( ({ userSetting }) => { return { mainColor: userSetting.mainColor, bgColor: userSetting.bgColor, languge: userSetting.languge, themeName: userSetting.themeName // data: random, }; }, { ...userSettingAction } )(userSetiingDrawerScreen); <file_sep>/src/components/loadingView.js import React, { PureComponent } from "react"; import { StyleSheet, View, Text } from "react-native"; import Spinkit from "react-native-spinkit"; import { Icon } from "react-native-elements"; import * as Animatable from "react-native-animatable"; import { adaptUnits, FONT_SIZE } from "~/common/constants"; // import { parseColorToRgba } from "~/common/util"; import Button from "~/components/button"; class LoadingView extends PureComponent { loadingType = ` Bounce, Wave, ThreeBounce, Circle, 9CubeGrid, WanderingCubes, Pulse, ChasingDots, FadingCircleAlt` .replace(/[\r\n\s]/gi, "") .split(","); render() { const { style = {}, loadingStyle = {}, infoIconName, infoIconType = "ionicon", fullScreen = false, text, textColor = "#444", textSize = FONT_SIZE.SM, textAlign = "bottom", // right btnText, btnTextColor = "#fff", btnBackgroundColor, btnOnPress = () => {}, _ref = () => {} } = this.props; let { loadingType = "1", color = "#000", iconColor = color, size = adaptUnits(40, "F") } = this.props; let compView; // const iconColor = color; loadingType = parseInt(loadingType); // 附加样式 const addStyle = { container: {}, loadingContainer: { flexDirection: textAlign === "bottom" ? "column" : "row" } }; // 全屏 if (fullScreen) { addStyle.container = { height: "100%" }; addStyle.loadingContainer = { ...addStyle.loadingContainer, marginTop: adaptUnits(-300, "H") }; } // if(color.length <= 7) { // color = parseColorToRgba(color, 1, {R: -33, G: -15, B: 0}); // } if (!infoIconName) { compView = ( <View style={[ styles.loadingContainer, addStyle.loadingContainer, loadingStyle ]} > <Spinkit color={color} size={size} type={this.loadingType[loadingType - 1]} /> {text && ( <Text style={[ styles.loadingText, { color: textColor, fontSize: textSize } ]} > {text} </Text> )} </View> ); } else { (size = adaptUnits(18, "F")), (compView = ( <View style={[ styles.infoContainer, addStyle.loadingContainer, loadingStyle ]} > <Icon size={size} color={iconColor} type={infoIconType} name={infoIconName} /> {text && ( <Text style={[ styles.infoText, { color: textColor, fontSize: textSize } ]} > {text} </Text> )} {btnText && ( <Button style={[ styles.btnWrap, { backgroundColor: btnBackgroundColor || color } ]} onPress={btnOnPress} > <Text style={[{ color: btnTextColor, fontSize: textSize }]}> {btnText} </Text> </Button> )} </View> )); } return ( <Animatable.View style={[styles.container, addStyle.container, style]} ref={_ref} > {compView} </Animatable.View> ); } } const styles = StyleSheet.create({ container: { width: "100%", justifyContent: "center", alignItems: "center", backgroundColor: "rgba(255,255,255, 0)" }, loadingContainer: { alignItems: "center" }, loadingText: { marginTop: adaptUnits(15, "H"), paddingBottom: adaptUnits(25, "W") }, infoContainer: { // flexDirection: 'row', alignItems: "center", // justifyContent: 'center', paddingTop: adaptUnits(25, "W"), paddingBottom: adaptUnits(25, "W") }, infoText: { marginLeft: adaptUnits(10, "W") }, btnWrap: { marginLeft: adaptUnits(10, "W"), paddingLeft: adaptUnits(10, "W"), paddingRight: adaptUnits(10, "W"), paddingTop: adaptUnits(5, "W"), paddingBottom: adaptUnits(5, "W"), borderRadius: 3 } }); export default LoadingView; <file_sep>/src/logics/select.js export const getRandomLimit = (state, type) => state.random[type].limit; export const getRandomLoading = (state, type) => state.random[type].loading; export const getAppointType = (state, type) => state.appointType[type]; export const getUserSetting = (state, type) => state.userSetting;<file_sep>/src/components/FlatList.js import React, { Component } from "react"; import { ScrollView, FlatList, RefreshControl } from "react-native"; import { ScrollViewFooter, PULLUPLOAD } from "./pullUploading"; import theme from "~/common/theme"; class MyFlatList extends Component { constructor() { super(); this.ScrollViewFooter = this.ScrollViewFooter.bind(this); } renderScrollComponent(props) { // if (this._isNestedWithSameOrientation()) { // return <View {...props} />; // } else if (props.onRefresh) { if (props.onRefresh) { // invariant( // typeof props.refreshing === 'boolean', // '`refreshing` prop must be set as a boolean in order to use `onRefresh`, but got `' + // JSON.stringify(props.refreshing) + // '`', // ); return ( <ScrollView {...props} refreshControl={ <RefreshControl progressBackgroundColor={props.progressBackgroundColor} colors={[props.refreshComponentColor]} refreshing={props.refreshing} onRefresh={props.onRefresh} progressViewOffset={props.progressViewOffset} /> } /> ); } else { return <ScrollView {...props} />; } } // infoIconName="ios-alert" // color={theme.blackText.color || mainColor} // iconColor={theme.lightText.color || mainColor} // btnBackgroundColor={theme.blackText.color || mainColor} // text="加载失败了" // textAlign="left" // btnText="重试" // textColor={theme.lightText.color || '#444'} // btnOnPress={this._onEndReached} ScrollViewFooter(props = {}) { const { data, mainColor, onEndReached } = this.props; const state = this.props.pullUpLoading; return ( <ScrollViewFooter state={state} mainColor={theme.blackText.color || mainColor} retry={onEndReached} iconColor={theme.lightText.color || mainColor} textColor={theme.lightText.color || "#444"} {...props} /> ); } render() { const { // style, // data, // renderItem, // keyExtractor, // onEndReached onRefresh, refreshing, mainColor } = this.props; return ( <FlatList // style={ style } // data={ data } // renderItem={ renderItem } // keyExtractor={ keyExtractor } // onEndReached={ onEndReached } // refreshing={ refreshing } // onRefresh={ onRefresh } renderScrollComponent={this.renderScrollComponent} refreshComponentColor={mainColor} onEndReachedThreshold={0.05} ListFooterComponent={this.ScrollViewFooter()} {...this.props} /> ); } } export default MyFlatList; <file_sep>/index.js import Root from "./src/Root"; import React, { Component } from "react"; import { AppRegistry } from "react-native"; AppRegistry.registerComponent("rnGank", () => Root); <file_sep>/src/logics/store.js import { createStore, applyMiddleware, compose } from "redux"; import createSagaMiddleware from "redux-saga"; import logger from "redux-logger"; import reducers from "./reducers"; import { DEV } from "~/common/constants"; import rootSaga from "../logics/rootSaga"; const sagaMiddleware = createSagaMiddleware(); let middleware = [sagaMiddleware]; if (DEV) { middleware = [...middleware, logger]; } const enhancer = compose(applyMiddleware(...middleware)); const store = createStore(reducers, undefined, enhancer); export default store; sagaMiddleware.run(rootSaga); <file_sep>/src/navigations/drawerNavigator/footer.js import React, { Component, PureComponent } from "react"; import { StyleSheet, Text, View, Image, ScrollView } from "react-native"; import { Icon } from "react-native-elements"; import { adaptUnits, FONT_SIZE, SCREENS } from "~/common/constants"; import theme from "~/common/theme"; import MyButton from "../../components/button"; class MyIcon extends PureComponent { render() { return ( <Icon raised component={_props => ( <MyButton {..._props} noAction onPress={this.props.onPress} /> )} containerStyle={[styles.icon, { backgroundColor: "#FA8072" }]} size={adaptUnits(15, "F")} color="#fff" // #F4A460 type="material-community" name="puzzle" {...this.props} /> ); } } class DrawerNavigatorFooter extends Component { constructor() { super(); this._gotoSetting = this._gotoSetting.bind(this); } _gotoSetting() { this.props.onItemPress({ route: { routeName: SCREENS.D.SETTING }, focused: false }); } render() { return ( <View style={[styles.container, theme.drawerFooterContainerStyle]}> {/* 主题 */} {/* <MyIcon containerStyle={[styles.icon, {backgroundColor: "#FA8072"}]} // #F4A460 name="puzzle" onPress={()=>console.log(1)} /> */} {/* 设置 */} <MyIcon raised containerStyle={[styles.icon, { backgroundColor: "#4682B4" }]} name="settings" onPress={this._gotoSetting} /> </View> ); } } const styles = StyleSheet.create({ container: { flexDirection: "row", justifyContent: "flex-end", alignItems: "center", paddingHorizontal: adaptUnits(18, "W"), width: "100%", height: adaptUnits(100, "H"), borderColor: "#ddd", borderTopWidth: adaptUnits(1, "H") }, icon: { margin: 0, marginHorizontal: adaptUnits(10, "W"), borderRadius: 50 } }); export default DrawerNavigatorFooter; <file_sep>/src/logics/selector.js import { createSelector } from "reselect"; import Immutable from "immutable"; import { arrayUnique as _arrayUnique } from "~/common/util"; export const propsDiff = createSelector( prevProps => prevProps, nextProps => nextProps, (prevProps, nextProps) => { prevProps = Immutable.fromJS(this.props); nextProps = Immutable.fromJS(nextProps); return !Immutable.is(prevProps, nextProps); } ); export const arrayUnique = createSelector( arr => arr, arr => _arrayUnique(arr, v => v._id) ); <file_sep>/README.md # rnGank rnGank是又一个react native开发的gank.io的App。 目前只完成android端,感谢 [http://gank.io](http://gank.io) 提供 API。 ### 功能 - [x] 每日最新,随机推荐,技术,休闲界面 - [x] 数据加载loading, 上拉下拉加载, 加载失败重试 - [x] 实现自己的分配器( 主要用在 切换色调,语言,主题上 没用别的库 - [x] 切换主色调, 语言, 主题(夜间模式 - [x] 本地保存用户设置(主色调等等 ### 运行 yarn add or npm i react-native run-android ### 界面 <img width="290" style="display: inline-block" src="https://github.com/qw110946/rnGank/blob/master/src/others/imgs/r1.gif"/><img width="290" style="display: inline-block" src="https://github.com/qw110946/rnGank/blob/master/src/others/imgs/r2.gif"/><img width="290" style="display: inline-block" src="https://github.com/qw110946/rnGank/blob/master/src/others/imgs/r3.gif"/><img width="290" style="display: inline-block" src="https://github.com/qw110946/rnGank/blob/master/src/others/imgs/r4.gif"/><img width="290" style="display: inline-block" src="https://github.com/qw110946/rnGank/blob/master/src/others/imgs/r5.gif"/><img width="290" style="display: inline-block" src="https://github.com/qw110946/rnGank/blob/master/src/others/imgs/r6.gif"/> ### 下载 [v1.2](https://github.com/qw110946/rnGank/releases/download/v1.2/rnGank-v1.2.apk) ### 感谢 * [http://gank.io](http://gank.io) * [所有开源的人](https://github.com/)( 用了一堆库<file_sep>/src/logics/random/saga.js import { call, put, all, takeLatest, select } from "redux-saga/effects"; import { fetchRandomDataSuccess, fetchRandomDataFailure } from "./action"; import { RANDOM } from "~/common/actionTypes"; import { Console } from "~/common/util"; import Api, { gankio } from "~/common/Api"; // import { PULLUPLOAD } from "~/components/pullUploading"; import { getRandomLimit } from "../select"; function* randomData(action) { const { dataType, loadType } = action.payload; let response; let results; try { const limit = yield select(getRandomLimit, dataType); response = yield call(Api.fetchRandomData, dataType, limit); if (response.status !== 200 || response.data.error) { yield put(fetchRandomDataFailure(dataType, response, "")); } results = response.data.results; yield put(fetchRandomDataSuccess(loadType, dataType, results)); } catch (err) { Console.log(err); yield put(fetchRandomDataFailure(dataType, response, err)); } } export default function* randomDataWatch() { const sagas = Object.keys(gankio.type) .map(v => { const type = gankio.type[v]; return [ takeLatest(`${RANDOM.REQUEST}_${type}`, randomData), takeLatest(`${RANDOM.REFRESH}_${type}`, randomData) ]; }) .reduce((a, b) => [...a, ...b], []); yield all(sagas); } <file_sep>/src/common/Api.js import axios from 'axios'; import { Console } from './util'; // gank.io const gankio = { domain: 'http://gank.io/', type: { ALL: 'all', FULI: '福利', ANDROID: 'Android', IOS: 'iOS', LEISUREVIDEO: '休息视频', // Leisure EXPAND: '拓展资源',// Expand WEB: '前端', BLINDRECOMMEND: '瞎推荐', // Blind recommend APP: 'App', }, }; const contentType = { json: 'application/json', form: 'application/x-www-form-urlencoded', }; const request = options => { Console.log(options.url); return axios(options); } class Api { // 随机数据 fetchRandomData(type, limit) { return request({ method:'get', url: `${gankio.domain}api/random/data/${type}/${limit}`, headers: { 'content-type': contentType.json }, }) } // 每日数据 fetchAppointDayData(year, month, day) { return request({ method:'get', url: `${gankio.domain}api/day/${year}/${month}/${day}`, headers: { 'content-type': contentType.json }, }) } // 指定数据 fetchAppointTypeData(type, limit, page) { return request({ method:'get', url: `${gankio.domain}api/data/${type}/${limit}/${page}`, headers: { 'content-type': contentType.json }, }) } // 搜索 fetchSearchTypeData(query, type, limit, page) { return request({ method:'get', url: `${gankio.domain}api/search/${query}/listview/category/${type}/count/${limit}/page/${page}`, headers: { 'content-type': contentType.json }, }) } } export default new Api(); export { gankio, };<file_sep>/src/logics/rootSaga.js import { all } from 'redux-saga/effects'; import random from './random/saga'; import appointType from './appointType/saga'; import userSetting from './userSetting/saga'; export default function* rootSaga() { yield all([ random(), appointType(), userSetting(), ]) }<file_sep>/src/common/actionTypes.js import { defineAction } from 'redux-define'; import { SUCCESS, FAILURE, REQUEST, REFRESH, LOCAL_LOAD, APPNAME } from './constants'; const namespace = APPNAME; const GANK = defineAction('GANK', [], namespace); // 随机数据 export const RANDOM = defineAction('RANDOM', [REQUEST, SUCCESS, FAILURE, REFRESH], GANK); // 指定数据 export const APPOINT_TYPE = defineAction('APPOINT_TYPE', [SUCCESS, FAILURE, REQUEST, REFRESH], GANK); // 每日数据 export const APPOINT_DAY = defineAction('APPOINT_DAY', [SUCCESS, FAILURE, REQUEST, REFRESH], GANK); // 搜索数据 export const SEARCH_TYPE = defineAction('APPOINT_DAY', [SUCCESS, FAILURE, REQUEST, REFRESH], GANK); // 设置 export const USER_SETTING = defineAction('USER_SETTING', [SUCCESS, FAILURE, REQUEST, LOCAL_LOAD], GANK); <file_sep>/src/logics/appointType/action.js import { APPOINT_TYPE } from "~/common/actionTypes"; export function fetchAppointTypeData(dataType, loadType) { return { type: `${APPOINT_TYPE.REQUEST}_${dataType}`, payload: { dataType, loadType } }; } export function refreshAppointTypeData(dataType, loadType) { return { type: `${APPOINT_TYPE.REFRESH}_${dataType}`, payload: { dataType, loadType } }; } export function fetchAppointTypeDataSuccess(loadType, dataType, data) { return { type: APPOINT_TYPE.SUCCESS, payload: { dataType, loadType, data } }; } export function fetchAppointTypeDataFailure(dataType, res, err) { return { type: APPOINT_TYPE.FAILURE, payload: { dataType, res, err } }; } <file_sep>/src/common/i18n/jp.js export default { randomRecommendation: "ランダムに推薦", // 無作為推薦 languge: "Languge", theme: "テーマ", setting: "設定", all: "すべて", welfare: "おやつ", android: "Android", ios: "iOS", leisureVideo: "レジャービデオ", // Leisure expand: "開拓の資源", // Expand web: "ウェブ", blindRecommend: "やたらに推薦", // Blind recommend app: "アプリ", secondsAgo: "秒前", minutesAgo: "分前", hoursAgo: "時間前", daysAgo: "日前", unknown: "知らない", leisure: "余暇", skill: "技術", dayNew: "毎日最新の", chinese: "中文", japanese: "日本語", english: "English", mainColor: "主な色調", normalMode: "普通", nightMode: "夜間", blue: "青色", red: "赤色", black: "黒色", black: "黑色", loading: "ローディング", loadFailure: "ロード失敗", retry: "リトライ" }; <file_sep>/src/logics/appointType/saga.js import { call, put, all, takeLatest, select } from "redux-saga/effects"; import { fetchAppointTypeDataSuccess, fetchAppointTypeDataFailure } from "./action"; import { APPOINT_TYPE } from "~/common/actionTypes"; import { Console } from "~/common/util"; import Api, { gankio } from "~/common/Api"; import { getAppointType } from "../select"; function* appointTypeData(action) { const { dataType, loadType } = action.payload; let results; let response; try { const { page, limit } = yield select(getAppointType, dataType); response = yield call(Api.fetchAppointTypeData, dataType, limit, page); if (response.status !== 200 || response.data.error) { yield put(fetchAppointTypeDataFailure(dataType, response, "")); } results = response.data.results; yield put(fetchAppointTypeDataSuccess(loadType, dataType, results)); } catch (err) { Console.error(err); yield put(fetchAppointTypeDataFailure(dataType, response, err)); } } export default function* appointTypeDataWatch() { const sagas = Object.keys(gankio.type) .map(v => { const type = gankio.type[v]; return [ takeLatest(`${APPOINT_TYPE.REQUEST}_${type}`, appointTypeData), takeLatest(`${APPOINT_TYPE.REFRESH}_${type}`, appointTypeData) ]; }) .reduce((a, b) => [...a, ...b], []); yield all(sagas); } <file_sep>/src/components/gankRenderItems/android.js import React, { PureComponent } from "react"; import { View, Text, Platform, StyleSheet, Image } from "react-native"; import { Badge, Avatar } from "react-native-elements"; import { adaptUnits, SPACING, SCREEN_WIDTH, FONT_SIZE, SCREENS } from "~/common/constants"; import Button from "../../components/button"; import { timeMsg, cutstr, randomColor } from "~/common/util"; // import Lightbox from 'react-native-lightbox'; import i18n, { getLanguge } from "~/common/i18n"; import theme from "~/common/theme"; const WIDTH = SCREEN_WIDTH - SPACING * 2; const BORDER_RADIUS = 5; export default class Android extends PureComponent { constructor() { super(); this._onPress = this._onPress.bind(this); this.randomColor = randomColor(); } _onPress() { const { navigation, url } = this.props; let { desc } = this.props; desc = desc || i18n.unknown; desc = cutstr(desc, 25); navigation.navigate(SCREENS.S.WEBVIEW, { url, title: desc }); } render() { const { source = "", type = "", mainColor = "", url = "", desc = "" } = this.props; let { publishedAt = "", who } = this.props; who = who || i18n.unknown; publishedAt = timeMsg(publishedAt, { getLanguge, i18n }, "-"); who = cutstr(who, 10); return ( <View style={styles.container}> <View style={[ styles.insideContainer, styles.raised, theme.gankContainerStyle ]} > <Button noAction onPress={this._onPress}> <View style={[styles.TopWrap]}> <Avatar small rounded title={who[0]} overlayContainerStyle={{ backgroundColor: theme.gankIconStyle.color || this.randomColor }} /> <Text style={[ styles.title, { color: theme.gankTextStyle.color || "#000" } ]} > {desc} </Text> </View> <View style={[styles.bottomWrap, theme.gankBottomContainerStyle]}> <Text style={[ { fontSize: FONT_SIZE.XXXS }, { color: theme.gankTextStyle.color || "#000" } ]} > 发布者: <Text style={{ fontSize: FONT_SIZE.XS }}>{who}</Text> </Text> <View style={styles.bottomRightWrap}> <Badge value={type} containerStyle={[ styles.bottomRightBadge, { backgroundColor: theme.gankBadgeStyle.color || mainColor } ]} textStyle={styles.bottomRightBadgeText} /> <Text style={[ styles.bottomRightTime, { color: theme.gankTextStyle.color || "#000" } ]} > {publishedAt} </Text> </View> </View> </Button> </View> </View> ); } } const styles = StyleSheet.create({ container: { width: "100%", padding: SPACING, paddingTop: SPACING / 2, paddingBottom: SPACING / 2 }, insideContainer: { width: WIDTH, borderRadius: BORDER_RADIUS, backgroundColor: "#fff" }, raised: { ...Platform.select({ ios: { shadowColor: "rgba(0,0,0, 0.4)", shadowOffset: { height: 1, width: 1 }, shadowOpacity: 1, shadowRadius: 1 }, android: { shadowColor: "rgba(0,0,0, 0.05)", shadowOpacity: 0.1, shadowRadius: StyleSheet.hairlineWidth, shadowOffset: { height: StyleSheet.hairlineWidth - 0.2 }, elevation: 1.4 } }) }, title: { fontSize: FONT_SIZE.NR, paddingLeft: SPACING, textAlign: "left", flex: 1 }, TopWrap: { width: WIDTH, backgroundColor: "transparent", flexDirection: "row", justifyContent: "space-between", alignItems: "center", borderWidth: 0, borderTopLeftRadius: BORDER_RADIUS, borderTopRightRadius: BORDER_RADIUS, paddingTop: SPACING / 2, paddingBottom: SPACING / 2, paddingLeft: SPACING / 1.5, paddingRight: SPACING / 1.5 }, bottomWrap: { height: adaptUnits(45, "H"), width: WIDTH, backgroundColor: "transparent", flexDirection: "row", justifyContent: "space-between", alignItems: "center", borderBottomLeftRadius: BORDER_RADIUS, borderBottomRightRadius: BORDER_RADIUS, paddingLeft: SPACING / 1.5, paddingRight: SPACING / 1.5 }, bottomRightWrap: { flexDirection: "row", alignItems: "center" }, bottomRightBadge: { backgroundColor: "#000", paddingLeft: SPACING / 2.5, paddingRight: SPACING / 2.5, marginRight: SPACING / 3 }, bottomRightBadgeText: { fontSize: FONT_SIZE.XXXXS }, bottomRightTime: { marginLeft: SPACING / 2.5, fontSize: FONT_SIZE.XS } }); <file_sep>/src/logics/reducers.js import { combineReducers } from 'redux'; import random from './random/reducer'; import appointType from './appointType/reducer'; import userSetting from './userSetting/reducer'; var Reducers = combineReducers({ random, appointType, userSetting, }) export default Reducers<file_sep>/src/components/navigateHeader.js import React, { PureComponent } from "react"; import { StyleSheet, View, Text, Platform } from "react-native"; import { Button, Icon } from "react-native-elements"; import { FONT_SIZE, HEADER_HEIGHT, MAIN_COLOR, adaptUnits } from "~/common/constants"; import MyButton from "./button"; import HeaderButton from "./navigateHeaderButton"; class NavigateHeader extends PureComponent { backBtn = ({ navigation, btnColor }) => ( <MyButton onPress={() => navigation.goBack()} style={styles.backBtn} ripple={true} ripplecolor="white" > <Icon large name="md-arrow-back" type="ionicon" color={btnColor} iconStyle={styles.backBtnIcon} /> </MyButton> ); render() { const { navigation = { goBack: () => {} }, title = "", //str titleAlign = "left", backBtn = true, leftComponent = false, // 左侧组件 rightComponent = false, // 左侧组件 btnColor = "#fff", style = {} } = this.props; return ( <View style={[styles.container, style]}> <View style={styles.leftWrap}> {backBtn && this.backBtn({ navigation, btnColor })} {leftComponent && leftComponent} {titleAlign === "left" && <Text style={styles.title}>{title}</Text>} </View> {titleAlign === "center" && <Text style={styles.title}>{title}</Text>} <View style={styles.rightWrap}> {titleAlign === "right" && <Text style={styles.title}>{title}</Text>} {rightComponent && rightComponent} </View> </View> ); } } // 阴影 let platformContainerShadowStyles = {}; if (Platform.OS === "ios") { platformContainerShadowStyles = { borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: "#A7A7AA" }; } else { platformContainerShadowStyles = { shadowColor: "black", shadowOpacity: 0.1, shadowRadius: StyleSheet.hairlineWidth, shadowOffset: { height: StyleSheet.hairlineWidth }, elevation: 4 }; } const styles = StyleSheet.create({ container: { width: "100%", height: HEADER_HEIGHT, flexDirection: "row", justifyContent: "center", alignItems: "center", zIndex: 9, backgroundColor: MAIN_COLOR, ...platformContainerShadowStyles }, leftWrap: { position: "absolute", left: 0, height: HEADER_HEIGHT, paddingLeft: adaptUnits(10, "W"), flexDirection: "row", alignItems: "center" }, rightWrap: { position: "absolute", right: 0, height: HEADER_HEIGHT, paddingRight: adaptUnits(10, "W"), flexDirection: "row", alignItems: "center" }, backBtn: { height: HEADER_HEIGHT / 1.2, width: HEADER_HEIGHT, marginLeft: adaptUnits(-12, "W"), flexDirection: "row", justifyContent: "center", alignItems: "center" }, title: { fontSize: FONT_SIZE.LG, color: "#fff" } }); export { HeaderButton }; export default NavigateHeader; <file_sep>/src/components/pullUploading.js import React, { PureComponent } from "react"; import { View, Text, StyleSheet } from "react-native"; // import Spinner from "react-native-spinkit"; import { FONT_SIZE, adaptUnits } from "~/common/constants"; import LoadingView from "./loadingView"; // 上拉加载状态 const PULLUPLOAD = { SUCCESS: "SUCCESS", FAILURE: "FAILURE", ING: "ING", NOMORE: "NOMORE" }; function WrapView(props) { return <View style={styles.wrapView}>{props.children}</View>; } /** * onScroll * @param {string} loadingKey props里上拉加载的键值 * @param {function} callback */ const onScroll = function(loadingKey, callback) { return function(event) { var loading = this.props[loadingKey]; // 已经在加载 if (loading === PULLUPLOAD.ING) return; const y = event.nativeEvent.contentOffset.y; const height = event.nativeEvent.layoutMeasurement.height; const contentHeight = event.nativeEvent.contentSize.height; // console.log('offsetY-->' + y); // console.log('height-->' + height); // console.log('contentHeight-->' + contentHeight); // 距离底部 if (y + height >= contentHeight - 300) { callback(); } }; }; /** * 上拉的底部组件 * @param {PULLUPLOAD.TYPE} state */ class ScrollViewFooter extends PureComponent { render() { const { state, mainColor, iconColor, textColor, retry = () => {} } = this.props; if (state === PULLUPLOAD.NOMORE) { return ( <LoadingView infoIconName="ios-information-circle" color={mainColor} text="没有更多了" textAlign="right" iconColor={iconColor} textColor={textColor} /> ); } else if (state === PULLUPLOAD.FAILURE) { return ( <LoadingView infoIconName="ios-alert" color={mainColor} text="加载失败" textAlign="right" btnText="重试" btnOnPress={retry} iconColor={iconColor} textColor={textColor} /> ); } else if (state === PULLUPLOAD.ING) { return ( <LoadingView size={adaptUnits(25, "F")} style={styles.loadingWrap} color={mainColor} loadingType="2" /> ); } return ( <LoadingView size={adaptUnits(25, "F")} style={styles.loadingWrap} color="rgba(255,255,255,0)" loadingType="2" /> ); } } const styles = StyleSheet.create({ loadingWrap: { paddingTop: adaptUnits(20, "H"), paddingBottom: adaptUnits(10, "H") }, normalView: { height: adaptUnits(100, "H") } }); export { ScrollViewFooter, PULLUPLOAD, onScroll }; <file_sep>/src/common/days.js // jp https://unpkg.com/dayjs@1.7.5/locale/ja export const jp = { name: "ja", weekdays: "日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"), months: "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), ordinal: function(e) { return e + "日" }, relativeTime: { future: "%s後", past: "%s前", s: "数秒", m: "1分", mm: "%d分", h: "1時間", hh: "%d時間", d: "1日", dd: "%d日", M: "1ヶ月", MM: "%dヶ月", y: "1年", yy: "%d年" } }; // jp https://unpkg.com/dayjs@1.7.5/locale/zh-cn export const zh = { name: "zh-cn", weekdays: "星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"), weekdaysShort: "周日_周一_周二_周三_周四_周五_周六".split("_"), weekdaysMin: "日_一_二_三_四_五_六".split("_"), months: "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"), monthsShort: "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), ordinal: function(_) { return _ + "日" }, relativeTime: { future: "%s内", past: "%s前", s: "几秒", m: "1 分钟", mm: "%d 分钟", h: "1 小时", hh: "%d 小时", d: "1 天", dd: "%d 天", M: "1 个月", MM: "%d 个月", y: "1 年", yy: "%d 年" } };<file_sep>/src/components/gankRenderItems/index.js import React, {PureComponent} from 'react'; import { View, Text } from 'react-native'; import Fili from './fuli'; import Android from './android'; const components = { FULI ({ data, mainColor, navigation }) { return <Fili {...data} mainColor={mainColor} navigation={navigation}/> }, ANDROID ({ data, mainColor, navigation }) { return <Android {...data} mainColor={mainColor} navigation={navigation}/> }, IOS ({ data, mainColor, navigation }) { return <Android {...data} mainColor={mainColor} navigation={navigation}/> }, LEISUREVIDEO ({ data, mainColor, navigation }) { return <Android {...data} mainColor={mainColor} navigation={navigation}/> }, EXPAND ({ data, mainColor, navigation }) { return <Android {...data} mainColor={mainColor} navigation={navigation}/> }, WEB ({ data, mainColor, navigation }) { return <Android {...data} mainColor={mainColor} navigation={navigation}/> }, BLINDRECOMMEND ({ data, mainColor, navigation }) { return <Android {...data} mainColor={mainColor} navigation={navigation}/> }, APP ({ data, mainColor, navigation }) { return <Android {...data} mainColor={mainColor} navigation={navigation}/> }, }; export default { bind: (that) => { return Object.keys(components) .map(v => [v, components[v].bind(that)]) .reduce((a, b) => { a[b[0]] = b[1]; return a; }, {}); } }<file_sep>/src/common/util.js import dayjs from "dayjs"; import { DEV } from "./constants"; export const Console = { log: (...args) => { if (DEV) console.log(...args); }, error: (...args) => { if (DEV) console.error(...args); } }; // 16进制颜色转rgba ` export const parseColorToRgba = ( color, opacity = 1, { R = 0, G = 0, B = 0 } ) => { try { color = color.split("#")[1]; color.length === 3 && (color = color + color); color = color .split("") .reduce((a, b, i) => { !(i % 2) ? a.push(b) : (a[a.length - 1] += b); return a; }, []) .map(v => parseInt("0x" + v)); (color[0] += R), (color[1] += G), (color[2] += B), (color = color.join(",")); return `rgba(${color},${opacity})`; } catch (err) { Console.log("func parseColorToRgba error: ", err); return "rgba(0,0,0, 1)"; } }; // 分配器 export const Distribution = (function() { const init = (data, defaultResult = "") => { let TYPES = []; let currentType = ""; let rootData = {}; let rootObj = {}; let tempObj = {}; try { paramValidate(data); rootData = Object.assign(data, rootData); TYPES = Object.keys(rootData); currentType = TYPES[0]; TYPES.forEach(v => { Object.keys(rootData[v]).forEach(_v => { if (!tempObj[_v]) tempObj[_v] = { // 若key不存在则返回defaultResult get: function() { return rootData[currentType][_v] || defaultResult; }, set: function(val) { throw new Error( "Distribution Obj set error: cannot set Distribution obj attr :)" ); } }; }); }); Object.defineProperties(rootObj, tempObj); return { data: rootObj, setType: type => { if (TYPES.indexOf(type) === -1) { throw new Error("Distribution Obj setType error: type no exist"); } else { currentType = type; } }, getType: () => currentType }; } catch (err) { throw err; } }; // 构造函数参数验证 const paramValidate = data => { const errorMsg = ["Distribution constructor param error:"]; if (!data) { throw new Error(`${errorMsg[0]} data is required`); } const keys = Object.keys(data); if (keys.length === 0) { throw new Error(`${errorMsg[0]} data is empty object`); } for (let i = 0, item; i < keys.length; i++) { if (Object.prototype.toString.call(data[keys[0]]) !== "[object Object]") { throw new Error(`${errorMsg[0]} data attribute Must be object`); break; } } }; return init; })(); export const isNumber = v => !Number.isNaN(parseInt(v)); export const delay = ms => { return new Promise((resolve, reject) => { if (!isNumber(ms)) { reject("ms is not a number"); } else { setTimeout(() => resolve(true), parseInt(ms)); } }); }; export const timeMsg = (time, { i18n, getLanguge }, defaultResult) => { try { let currDate = +new Date(); time = new Date(time); let interval = currDate - +time; const sixS = 60 * 1000; const sixM = 60 * sixS; const day = 24 * sixM; const swday = 15 * day; if (interval <= sixS) { return parseInt(interval / 1000) + i18n.secondsAgo; } else if (interval <= sixM) { return parseInt(interval / sixS) + i18n.minutesAgo; } else if (interval <= day) { return parseInt(interval / sixM) + i18n.hoursAgo; } else if (interval <= swday) { return parseInt(interval / day) + i18n.daysAgo; } else { if (getLanguge() === "en") { return dayjs(time).format("MMM DD YYYY"); } return `${time.getFullYear()}年${time.getMonth() + 1}月${time.getDate()}日`; } } catch (err) { Console.log(err); return defaultResult; } }; // 字符串截取 export function cutstr(str, len) { try { var str_length = 0; var str_len = 0; str_cut = new String(); str_len = str.length; for (var i = 0; i < str_len; i++) { a = str.charAt(i); str_length++; if (escape(a).length > 4) { //中文字符的长度经编码之后大于4 str_length++; } str_cut = str_cut.concat(a); if (str_length >= len) { str_cut = str_cut.concat("..."); return str_cut; } } //如果给定字符串小于指定长度,则返回源字符串; if (str_length < len) { return str; } } catch (err) { return str; } } export const randomColor = () => { let color = ""; while (color.length < 7) { color = "#" + Math.floor(Math.random() * 16777215).toString(16); } return color; }; // 数组去重 export const arrayUnique = (currArr, key = v => v) => { let arr = []; //创建一个临时数组 let obj = {}; //创建一个空对象 for (let i = 0, k; i < currArr.length; i++) { //遍历当前要去重的数组 k = key(currArr[i]); if (!obj[k]) { //判断obj对象中是否存有当前项,没有则执行 arr.push(currArr[i]); //将当前项push到临时数组中 obj[k] = 1; //将当前项存入obj对象 } else { // console.log(currArr) // console.log(currArr[i]) // debugger } } return arr; }; <file_sep>/src/logics/userSetting/action.js import { USER_SETTING } from "~/common/actionTypes"; export function setUserSetting(setting) { return { type: USER_SETTING.REQUEST, payload: { setting } }; } export function setUserSettingSuccess(setting) { return { type: USER_SETTING.SUCCESS, payload: { setting } }; } export function setUserSettingFailure(...err) { return { type: USER_SETTING.FAILURE, payload: { ...err } }; } export function userSettingLocalLoad() { return { type: USER_SETTING.LOCAL_LOAD }; } <file_sep>/src/screens/Apptest.js import React, { Component } from "react"; import { AppRegistry, StyleSheet, Text, View } from "react-native"; import { connect } from "react-redux"; import { Button, Icon, ButtonGroup } from "react-native-elements"; import * as randomAction from "../logics/random/action"; import * as appointTypeAction from "../logics/appointType/action"; import * as userSettingAction from "../logics/userSetting/action"; import { SCREENS } from "~/common/constants"; // import { RANDOM } from "~/common/actionTypes"; // import { gankio } from "~/common/Api"; import { FONT_SIZE } from "~/common/constants"; import i18n from "~/common/i18n"; import theme from "~/common/theme"; const styles = StyleSheet.create({ container: { flex: 1, // justifyContent: 'center', alignItems: "center", backgroundColor: "#fff" } }); class rnGank extends Component { constructor() { super(); this.state = { selectedLangugeIndex: 0, selectedThemeIndex: 0 }; this.selectedLanguge = ["zh", "en", "jp"]; this.selectedTheme = ["normal", "night"]; this.handleUpdateLangugeIndex = this.handleUpdateLangugeIndex.bind(this); this.handleUpdateThemeIndex = this.handleUpdateThemeIndex.bind(this); } componentDidMount() { const { fetchRandomData, fetchAppointTypeData } = this.props; // fetchRandomData(gankio.type.ANDROID); // fetchAppointTypeData(gankio.type.IOS); } // 修改语言 handleUpdateLangugeIndex(selectedLangugeIndex) { this.setState({ selectedLangugeIndex }); this.props.setUserSetting({ languge: this.selectedLanguge[selectedLangugeIndex] }); } // 修改主题 handleUpdateThemeIndex(selectedThemeIndex) { this.setState({ selectedThemeIndex }); this.props.setUserSetting({ themeName: this.selectedTheme[selectedThemeIndex] }); } render() { const { userSetting, navigation: { navigate } } = this.props; const { mainColor, languge, themeName } = userSetting; const { selectedLangugeIndex, selectedThemeIndex } = this.state; return ( <View style={styles.container}> <View style={{ width: "80%", height: 40, backgroundColor: mainColor, margin: 20 }} /> <Text style={{ fontSize: FONT_SIZE.HG, margin: 7 }}> huge size ABC abc {FONT_SIZE.HG} </Text> <Text style={{ fontSize: FONT_SIZE.LG, margin: 7 }}> large size ABC abc {FONT_SIZE.LG} </Text> <Text style={{ fontSize: FONT_SIZE.MD, margin: 7 }}> middle size ABC abc {FONT_SIZE.MD} </Text> <Text style={{ fontSize: FONT_SIZE.NM, margin: 7 }}> normal size ABC abc {FONT_SIZE.NM} </Text> <Text style={{ fontSize: FONT_SIZE.SM, margin: 7 }}> small size ABC abc {FONT_SIZE.SM} </Text> <Text style={{ fontSize: FONT_SIZE.XS, margin: 7 }}> xsmall size ABC abc {FONT_SIZE.XS} </Text> <Text style={[{ fontSize: FONT_SIZE.MD, margin: 7 }, theme.test]}> {i18n.randomRecommendation} </Text> <Text style={[{ fontSize: FONT_SIZE.MD, margin: 7 }, theme.test]}> languge: {languge} </Text> <Text style={[{ fontSize: FONT_SIZE.MD, margin: 7 }, theme.test]}> theme: {themeName} </Text> <ButtonGroup onPress={this.handleUpdateLangugeIndex} selectedIndex={selectedLangugeIndex} buttons={this.selectedLanguge} containerStyle={{ height: 30 }} /> <ButtonGroup onPress={this.handleUpdateThemeIndex} selectedIndex={selectedThemeIndex} buttons={this.selectedTheme} containerStyle={{ height: 30 }} /> <Button title={SCREENS.S.HOME} icon={{ name: "home", type: "entypo", color: "#fff" }} onPress={() => navigate(SCREENS.S.HOME)} buttonStyle={{ margin: 10 }} /> <Button title={SCREENS.S.WEBVIEW} icon={{ name: "blur-on", type: "mat​​erial-community" }} onPress={() => navigate(SCREENS.S.WEBVIEW)} buttonStyle={{ margin: 10 }} /> </View> ); } } export default connect( state => { return { ...state }; }, { ...randomAction, ...appointTypeAction, ...userSettingAction } )(rnGank); <file_sep>/src/components/button.js import React, { Component } from "react"; import { StyleSheet, Image, TouchableHighlight, View, TouchableNativeFeedback, Platform } from "react-native"; class Button extends Component { render() { const { style = {}, children = [<View />], noAction = false, // 是否无点击反应 不显示点击后透明, 点击后背景色 disabled = false, // 点击后不执行点击事件 ripple = false, // 涟漪是否渲染到视图的范围之外 ripplecolor = "black", // 涟漪状的背景色 black or white nativeUnderlayColor = ripplecolor === "black" ? "rgba(0,0,0,0.3)" : "rgba(255,255,255,255.3)" } = this.props; let { onPress = () => {}, underlayColor = "rgba(0,0,0,0.1)", // TouchableHighlight 点击后背景色 activeOpacity = 0.8 // TouchableHighlight 点击后透明程度 } = this.props; let component; onPress = disabled ? () => {} : onPress; underlayColor = noAction ? false : underlayColor; activeOpacity = noAction ? 1 : activeOpacity; if (Platform.OS === "android" && Platform.Version > 21 && !noAction) { component = ( <TouchableNativeFeedback background={TouchableNativeFeedback.Ripple( nativeUnderlayColor, ripple )} onPress={onPress} > <View style={style}>{children}</View> </TouchableNativeFeedback> ); } else { component = ( <TouchableHighlight underlayColor={!noAction ? underlayColor : null} activeOpacity={activeOpacity} onPress={onPress} > <View style={style}>{children}</View> </TouchableHighlight> ); } return component; } } export default Button; <file_sep>/src/App.js import React, { Component } from "react"; import { AppRegistry, StyleSheet, Text, View } from "react-native"; import { connect } from "react-redux"; import SplashScreen from "react-native-splash-screen"; import { Console } from "~/common/util"; import i18n from "~/common/i18n"; import theme from "~/common/theme"; import StackNavigator from "./navigations/stackNavigator"; import * as userSettingAction from "./logics/userSetting/action"; const styles = StyleSheet.create({ container: { flex: 1 // justifyContent: 'center', // alignItems: 'center', // backgroundColor: '#F5FCFF', } }); class rnGank extends Component { constructor(props) { super(props); const { userSettingLocalLoad } = this.props; // 加载本地设置 userSettingLocalLoad(); } componentDidUpdate(nextProps) { if (nextProps.userSettingLocalLoad) { SplashScreen.hide(); } } render() { const { mainColor, languge } = this.props; return ( <View style={styles.container}> <StackNavigator onNavigationStateChange={(p, c) => { const prevRouteName = p.routes[p.index].routeName; const currRouteName = c.routes[c.index].routeName; if (prevRouteName !== currRouteName) { Console.log(prevRouteName, " --> ", currRouteName); } }} screenProps={{ mainColor, i18n, theme }} /> </View> ); } } export default connect( ({ userSetting }) => { return { mainColor: userSetting.mainColor, languge: userSetting.languge, userSettingLocalLoad: userSetting.localLoad }; }, { ...userSettingAction } )(rnGank); <file_sep>/src/navigations/drawerNavigator/index.js import { createDrawerNavigator, DrawerItems } from "react-navigation"; import { DRAWER_WIDTH, SCREENS } from "~/common/constants"; import ContentComponent from "./contentComponent"; import random from "~/logics/random/views/drawerScreen"; import skill from "~/logics/appointType/views/skillDrawerScreen"; import leisure from "~/logics/appointType/views/leisureDrawerScreen"; import dayNew from "~/logics/appointType/views/dayNewDrawerScreen"; import setting from "~/logics/userSetting/views/drawerScreen"; const drawerNavigator = createDrawerNavigator( { [SCREENS.D.DAYNEW]: { screen: dayNew }, [SCREENS.D.RANDOM]: { screen: random }, [SCREENS.D.SKILL]: { screen: skill }, [SCREENS.D.LEISURE]: { screen: leisure }, [SCREENS.D.SETTING]: { screen: setting } }, { initialRouteName: SCREENS.D.DAYNEW, // initialRouteName: SCREENS.D.RANDOM, // order: [ ], contentComponent: ContentComponent, drawerWidth: DRAWER_WIDTH // 侧拉导航的宽度 } ); export default drawerNavigator; <file_sep>/src/logics/random/views/randomFlatList.js import React, { Component } from "react"; import { StyleSheet, Text } from "react-native"; import { connect } from "react-redux"; import Immutable from "immutable"; import FlatList from "~/components/FlatList"; import gankRenderItems from "~/components/gankRenderItems"; import LoadingView from "~/components/loadingView"; import { gankio } from "~/common/Api"; import { RANDOM } from "~/common/actionTypes"; import theme from "~/common/theme"; import * as randomAction from "../action"; // import { propsDiff } from '../../selector'; class RandomFlatList extends Component { constructor(props) { super(props); this.gankRenderItems = gankRenderItems.bind(this); this._renderItem = this._renderItem.bind(this); this._onRefresh = this._onRefresh.bind(this); this._onEndReached = this._onEndReached.bind(this); } // shouldComponentUpdate(nextProps) { // return propsDiff(this.props, nextProps) // } _keyExtractor = data => data._id; _renderItem({ item, i }) { const { dataType, mainColor, navigation } = this.props; const type = Object.keys(gankio.type).filter( v => gankio.type[v] === item.type )[0]; if (type) { const Item = this.gankRenderItems[type]; return <Item data={item} mainColor={mainColor} navigation={navigation} />; } else { return false; } // console.log('Item:', Item) // console.log('dataType:', dataType) } componentDidMount() { const { refreshRandomData, dataGankType, data } = this.props; if (data[dataGankType].data.length === 0) { refreshRandomData(dataGankType, RANDOM.REFRESH); } } _onRefresh() { const { refreshRandomData, dataGankType } = this.props; refreshRandomData(dataGankType, RANDOM.REFRESH); } _onEndReached() { const { fetchRandomData, dataGankType } = this.props; fetchRandomData(dataGankType); } render() { const { mainColor, dataGankType, data } = this.props; const currentData = data[dataGankType]; const extraData = { data: [...currentData.data], pullUpLoading: currentData.loading, mainColor }; return !currentData.loaded ? ( currentData.error ? ( <LoadingView fullScreen infoIconName="ios-alert" color={theme.blackText.color || mainColor} iconColor={theme.lightText.color || mainColor} color={theme.mainColor || mainColor} text="加载失败了" textAlign="left" btnText="重试" textColor={theme.lightText.color || "#444"} btnOnPress={this._onEndReached} /> ) : ( <LoadingView fullScreen color={theme.lightText.color || mainColor} /> ) ) : ( <FlatList style={styles.container} mainColor={mainColor} data={extraData.data} extraData={extraData} renderItem={this._renderItem} keyExtractor={this._keyExtractor} onEndReached={this._onEndReached} onRefresh={this._onRefresh} refreshing={currentData.refreshLoading} pullUpLoading={currentData.loading} /> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "transparent" } }); export default connect( ({ userSetting, random }) => { return { mainColor: userSetting.mainColor, data: random }; }, { ...randomAction } )(RandomFlatList); <file_sep>/src/components/ScrollableTabView.js import React, { PureComponent } from "react"; import { StyleSheet } from "react-native"; import ScrollableTabView, { ScrollableTabBar } from "react-native-scrollable-tab-view"; // import ScrollableTabBar from './ScrollableTabBar'; import { FONT_SIZE, adaptUnits, TAB_HEIGHT } from "~/common/constants"; import theme from "~/common/theme"; class MyScrollableTabBar extends PureComponent { render() { const { mainColor, children, tabHeight = TAB_HEIGHT // tabStyle, } = this.props; let addStyle = []; if (theme.tabContainerStyle.backgroundColor) { addStyle = [{ borderColor: theme.tabContainerStyle.backgroundColor }]; } return ( <ScrollableTabView tabBarBackgroundColor={ theme.tabContainerStyle.backgroundColor || "#fff" } tabBarInactiveTextColor={theme.text.color || "#999"} tabBarActiveTextColor={theme.lightText.color || mainColor} tabBarTextStyle={{ fontSize: FONT_SIZE.NM }} initialPage={0} tabBarUnderlineStyle={[ styles.underline, { backgroundColor: theme.lightText.color || mainColor } ]} prerenderingSiblingsNumber={0} renderTabBar={_props => ( <ScrollableTabBar style={[{ height: tabHeight }, ...addStyle]} tabStyle={[ styles.tab, { height: tabHeight }, theme.tabContainerStyle ]} {..._props} /> )} {...this.props} > {children} </ScrollableTabView> ); } } const styles = StyleSheet.create({ TabViewContainer: { height: adaptUnits(20, "H"), padding: 0 }, underline: { height: adaptUnits(3, "H") }, tab: { backgroundColor: "#fff", paddingLeft: adaptUnits(35, "W"), paddingRight: adaptUnits(35, "W") } }); export default MyScrollableTabBar;
3148dcb69f502e107c05445b87d861127e53d206
[ "JavaScript", "Markdown" ]
33
JavaScript
qw110946/rnGank
5f3ba48a1deedfa92dda15efdc64758c9e9ef8d6
ebae22f23d6b491a69cb12875bd459ddac6a7ecc
refs/heads/master
<repo_name>l1261351532/004-Investment_Guide<file_sep>/ChooseStock.py #coding=utf-8 """ 本函数实现了股票筛选功能。 使用get_today_all得到当日实时股票数据,运行成本高 过滤出市盈率在0-30倍之间,且今日换手率>1%,涨幅超2%的股票。 之后统计今日涨停和接近涨停的股票。 """ import pandas as pd import tushare as ts import numpy as np e=ts.get_today_all() code=e[u'code'] name = e[u'name'] per = e[u'per'] # 市盈率 tt = e[u'turnoverratio'] # 换手率 cc = e[u'changepercent'] # 涨跌幅 mm = e[u'mktcap'] # 总市值 idx = len(name) total = 0 while idx > 0: idx -= 1 #选择市盈率在0-30倍之间,且今日换手率>1%,涨幅超2%的 if per[idx] < 30 and per[idx] > 0 and tt[idx] > 1 and cc[idx] > 2: print (code[idx],' ',name[idx],":",per[idx],":",tt[idx],":",cc[idx],":",mm[idx]/10000) total += 1 print("total:",total,"/",len(name)) idx = len(name) total = 0 print("涨停股票:") while idx > 0: idx -= 1 # 涨停股票 if cc[idx] > 9.5: total += 1 print (code[idx],":",name[idx],":",cc[idx])
ccbe3d3238a1cfa25a13d4e0509252b1b0866283
[ "Python" ]
1
Python
l1261351532/004-Investment_Guide
086ce8c160f8e82ae62afcbb0bbd08e4461758f1
72898d179bfc05c963a1a2a3d5298f9f0c313faa
refs/heads/master
<file_sep># Awl Quiz The point is to help students work on academic words, and this app uses the Academic Word List (Coxhead, 2000) to do this. Pick a base word and fill in the missing words in the academic sentences. Currently the sentences are hardcoded and come from abstracts of computer science papers on arxiv.org. Eventually, this will use an API to serve sentences in a much more flexible manner. This is very MVP. <file_sep>import axios from 'axios'; import React, { Component } from 'react'; import data from './data/sentences'; import Loading from './Loading'; class Main extends Component { constructor(){ super(); this.state = { sentences: data, } } render() { const { sentences } = this.state; console.log({ sentences} ); return ( <div className="container"> <div>Pick a word to take a quiz</div> <ul> {sentences && sentences.map((item, index) => { <li key={index}>item</li> }) } </ul> </div> ) } } export default Main;
339017970e6703056936d2dd36d4a792307b2c54
[ "Markdown", "JavaScript" ]
2
Markdown
lpmi-13/awl-quiz
556e89fc816aba037e66158d3f55d3f08994b38c
34d2f0368004a69587b0b23dc6030e7b0c5fd911
refs/heads/master
<repo_name>AndriiDev96/toDoApp<file_sep>/src/components/shellApp/ShellApp.js import React, { Component } from 'react'; import './style.css'; import RenderTaks from '../renderTasks/RenderTasks'; class ShellApp extends Component { render() { const nameLocalSt = localStorage.getItem('name'); const nameUser = nameLocalSt === ' ' || nameLocalSt === null ? "User" : nameLocalSt; return ( <div> <section className="block-header mb-4"> <div className="container"> <h2>Hello {nameUser}!</h2> <p>Be successful! To arrange your tasks.</p> </div> </section> <section className="block-content mb-5"> <div className="container"> <RenderTaks /> </div> </section> </div> ); } } export default ShellApp;
c884915ea2d2fd8960571c5da4a2103fadd8a031
[ "JavaScript" ]
1
JavaScript
AndriiDev96/toDoApp
04d670f9384ba9ccfcbcbcc65ea7cf7b9322bcea
e1b7e46e8ca95d0c8b7d05c7f1c1378dd75f3a5b
refs/heads/master
<repo_name>mssiedler/saads<file_sep>/Assets/Scripts/Bola.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bola : MonoBehaviour { // Use this for initialization Vector3 velocidade; void Start () { velocidade = new Vector3(0.1f, 0.1f); } // Update is called once per frame void Update () { this.transform.position += velocidade; } private void OnCollisionEnter2D(Collision2D c) { if(c.gameObject.tag == "lateral") { velocidade.y = velocidade.y * -1; } else if (c.gameObject.tag == "jogador") { velocidade.x = velocidade.x * -1; } } } <file_sep>/README.md # Ping Pong Usando Unity Projeto desenvolvido na semana acadêmica do curso superior em bla bla bla. Abordando Tecnologias: C#, Unity Documentação: não tem Protótipo: www.meuprototipo.com Estágio Atual: Front End pronto .. classes de modelo criadas
811cbd515450f185fa4bed13f29174cddc69c388
[ "Markdown", "C#" ]
2
C#
mssiedler/saads
f8d63e03ac055f95dc12aa675e1ff5fe9ec6411b
52a01df6780dc4b4e582bfeab7ad06ccb0064789
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> typedef int bool; #define true 1 #define false 0 #define MAX(a,b) ((a) > (b) ? a : b) struct Node { int data; struct Node* left; struct Node* right; }; struct Node* root; struct Node* getnode(int x){ struct Node* newnode = (struct Node*)malloc(sizeof(struct Node)); newnode->data = x; newnode->right = NULL; newnode->left = NULL; return newnode; } struct Node* insert(struct Node *root, int x){ if(root == NULL){ root = getnode(x); } else if(x <= root->data){ root->left = insert(root->left,x); } else{ root->right = insert(root->right,x); } return root; } bool search(struct Node* root,int n){ if(root == NULL){ return false; } else if(root->data == n) { return true; } else if(n <= root->data) { return search(root->left, n); } else { return search(root->right, n); } } int findheight(struct Node* root){ if(root == NULL){ return 1; } else{ } } int main(){ root = NULL; int n, height; root = insert(root,15); root = insert(root,20); root = insert(root,10); root = insert(root,2); root = insert(root,12); root = insert(root,27); root = insert(root,23); root = insert(root,18); search(root, n); height = findheight(root); printf("The height is %d", height); printf("enter the number you wish to search\n"); scanf(" %d", &n); if(search(root,n)==1) printf("the number exits in the tree\n"); else if (search(root,n)==0) printf("the number does not exist in the tree\n"); }<file_sep>#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; struct Node* head; void insert(int data){ struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = data; temp->next = head; head = temp; } int print(){ struct Node* temp = head; int count = 0; while(temp != NULL){ printf("%d", temp->data); count++; temp = temp->next; } return count; } void findkth(int count, int k){ struct Node* temp1 = head; int i; for(i=0;i<count - k; i++){ temp1 = temp1->next; } printf("%d", temp1->data); } int main(){ head = NULL; int data, n, i,count, k; printf("enter the number of elements"); scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d", &data); insert(data); } count = print(); printf("\nCount : %d\n", count); print(); printf("enter the k value"); scanf("%d", &k); findkth(count, k); }<file_sep>#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* left; struct Node* right; }; struct Node* getnode(char data){ struct Node* newnode = (struct Node*)malloc(sizeof(struct Node)); newnode->data = data; newnode->left = NULL; newnode->right = NULL; return newnode; } struct Node* root; struct Node* insert(struct Node* root, int data){ if(root == NULL){ root = getnode(data); } else if(data <= root->data){ root->left = insert(root->left, data); } else{ root->right = insert(root->right, data); } return root; } struct Node* inorder(struct Node* root){ if(root == NULL){ return; } inorder(root->left); printf(" %i", root->data); inorder(root->right); } struct Node* preorder(struct Node* root){ if(root ==NULL) { return; } printf(" %i", root->data); preorder(root->left); preorder(root->right); } struct Node* postorder(struct Node* root){ if(root == NULL){ return; } postorder(root->left); postorder(root->right); printf(" %i", root->data); } int main(){ root = NULL; int i, n; int data; printf("enter the number of elements"); scanf("%d", &n); for(i=0;i<n;i++){ scanf("%i", &data); root = insert(root, data); } preorder(root); /*you need to pass root becuase a local root variable is taken in and that pointer is used to traverse in the tree as a recursive variable */ inorder(root); postorder(root); }<file_sep>#include <stdio.h> #include <stdlib.h> struct Node{ int data; struct Node* next; }; struct Node* head; void print(){ struct Node* temp = head; while(temp != NULL){ printf("%d",temp->data); temp = temp->next; } printf("\n)"); } void insert(int data){ head = NULL; struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = data; temp->next = head; head = temp; } int main(){ insert(2); insert(3); print(); }<file_sep>#include <stdio.h> #include <stdlib.h> void print(); void insert(int x, int n); struct Node { int data; struct Node* next; }; struct Node* Head; int main(){ Head = NULL; insert(5,1); insert(3,2);//to insert the elements insert(2,3); insert(8,4); insert(9,5); insert(1,6); insert(7,4); print(); //to print value of elements in the node } void insert(int x, int n){ struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node)); temp1->data = x; temp1->next = NULL; if(n == 1){ temp1->next = Head; Head = temp1; return; } struct Node* temp2 = Head; int i; for(i=0;i<n-2;i++){ /*so n-2 because if want to insert element at nth position the temp2 data should be pointed by nth-1 next address that is temp2(nth) = temp2.next(n-1)th also as as array starts from 0th position it is n-2*/ temp2 = temp2->next; } temp1->next = temp2->next; /*remember temp1 will be pointing to the new node not temp2, temp2 wil be poiting to either head or temp2.next of previous node where it should attach*/ temp2->next = temp1; } void print(){ int array_size = 256; int *array = (int)malloc(sizeof(array_size)); int i=0; int j =0; struct Node* temp = Head; while (temp != NULL){ printf("the list now:%d\n", temp->data); array[i] = temp->data; temp = temp->next; i++; } i++; int t,k; for(k =0;k<i-1;k++){ for(j=0;j<i-k-1;j++){ if(array[j]>array[j+1]){ t = array[j]; array[j]=array[j+1]; array[j+1]= t; printf("%d", array[j]); j++; } } k++; } printf("\n"); }<file_sep>#include <stdio.h> #include <stdlib.h> struct Node{ int data; struct Node* next; }; struct Node* insert(int data, struct Node* head){ //head = NULL; if you add head is null in the insert statenment it will not execute because everytime it iscalled head is null so link will not be created struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = data; temp->next = head; head =temp; return head; } struct Node* reverse(struct Node* head){ struct Node *prev, *current, *next; current = head; prev = NULL; while(current != 0){ next = current->next; current->next = prev; prev = current; current = next; } head = prev; return head; } void print(struct Node* head){ struct Node* temp = head; while(temp != NULL){ printf("elements:%d\n",temp->data); temp = temp->next; } printf("\n"); } int main(){ struct Node* head; head = NULL; int n; head = insert(4, head); head = insert(3, head); head = insert(5, head); head = insert(6, head); print(head); head = reverse(head); print(head); }<file_sep>/*always make sure you ve added typdef bool to add bool,as you are using recursive functio you need to send root as a inpt because when you are sending back right or left node you need to have it specified in the call function even if you have declared root globally*/ #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* left; struct Node* right; }; struct Node* root; struct Node* getnode(data){ struct Node* newnode = (struct Node*)malloc(sizeof(struct Node)); newnode->data = data; newnode->right = NULL; newnode->left = NULL; return newnode; } struct Node* insert(struct Node* root, int data){ if(root == NULL){ root = getnode(data); } else if (data <= root->data ){ root->left = insert(root->left,data); } else{ root->right = insert(root->right, data); } return root; } struct Node* findmin(struct Node* root){ if(root == NULL){ return 0; } else if(root->left == NULL){ /*check root->left not root->data with NULL because by the time root->data will be NULL root will be NULL so always if statement executes If you check root->left with NULL so the last leaf will show null, return type can be pointer or int because as you are returning root->data you can send both */ return root->data; } return findmin(root->left); } struct Node* findmax(struct Node* root){ if(root == NULL){ return 0; } else if(root->right == NULL){ return root->data; } return findmax(root->right); } int main(){ root = NULL; int n, i, data, min, max; int key = 0; printf("enter the elements you wish to add"); scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d", &data); root = insert(root,data); } min = findmin(root); printf("Minimum element: %d", min); max = findmax(root); printf("max element: %d", max); }<file_sep>#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; struct Node* head; void insert(int data){ struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = data; temp->next = head; head = temp; } void print(){ struct Node* temp = head; while(temp != NULL){ printf("%d\t", temp->data); temp = temp->next; } } void removedup(){ struct Node *p = head, *q = head; struct Node* prev; q = q->next; while(p != NULL){ while(q != NULL && p->data != q->data ){ prev = q; q = q->next; } if(q == NULL){ p = p->next; if(p != NULL){ //you need to mention if loop because the loop traverses completely even if it has removed dup q = p->next; } } else if(p->data == q->data){ struct Node* temp; prev->next = q->next; temp = q; q = q->next; free(temp); } } } int main(){ head = NULL; int middle; int data, n, i; printf("enter the nuber of elements"); scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d", &data); insert(data); } print(); removedup(); printf("\nNo Dup :"); print(); }<file_sep>#include <stdio.h> #include <stdlib.h> struct Node{ int data; struct Node* next; }; struct Node* head; void del(int n){ int i; struct Node* temp = head; if(n==1){ head = temp->next; free(temp); return; } struct Node* temp1 = head; for(i=0;i<n-2;i++){ temp1 = temp1->next; } struct Node* temp2 = temp1->next; temp1->next = temp2->next; free(temp2); } void insert(int data){ struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = data; temp->next = head; head = temp; } void print(){ struct Node* temp = head; while(temp != NULL){ printf("elements:%d\n",temp->data); temp = temp->next; } printf("\n"); } int main(){ head = NULL; int n; insert(4); insert(3); insert(5); insert(6); print(); printf("enter the node which you neeed to delete\n"); scanf("%d", &n); del(n); print(); }<file_sep>//logic int findheight(struct Node* root){ if(root == NULL) { return -1; } else{ return MAX(findheight(root->left),findheight(root->right)); } }<file_sep>/*always make sure you ve added typdef bool to add bool,as you are using recursive functio you need to send root as a inpt because when you are sending back right or left node * you need to have it specified in the call function even if you have declared root * globally*/ #include <stdio.h> #include <stdlib.h> typedef bool; #define true 1 #define false 0 struct Node { int data; struct Node* left; struct Node* right; }; struct Node* root; struct Node* getnode(data){ struct Node* newnode = (struct Node*)malloc(sizeof(struct Node)); newnode->data = data; newnode->right = NULL; newnode->left = NULL; return newnode; } struct Node* insert(struct Node* root, int data){ if(root == NULL){ root = getnode(data); } else if (data <= root->data ){ root->left = insert(root->left,data); } else{ root->right = insert(root->right, data); } return root; } bool search(struct Node* root, int key){ if(root == NULL){ return false; } else if(root->data == key){ return true; } else if (key <= root->data){ return search(root->left, key); } else { return search(root->right, key); } } int main(){ root = NULL; int n, i, data; int key = 0; printf("enter the elements you wish to add"); scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d", &data); root = insert(root,data); } printf("enter the number you wish to search"); scanf("%d", &key); if(search(root,key)== true){ printf("element exist"); } else{ printf("does not exist"); } }<file_sep>#include <stdio.h> #include <stdlib.h> #define MAX_SIZE 101 int A[MAX_SIZE]; int top = -1; /*always top will be pointing to -1th location if there is no elements in the stack */ void push(int n){ top++; A[top] = n; } void pop(){ top--; } void print(){ int i; printf("stack: "); for(i=0;i<top;i++){ /*as we have declared top globally whatever modifiaction we do on it, it will be updated in all the functions, so top will take the value of its current position */ printf(" %d",A[i]); } printf("\n"); } int main(){ push(1);print(); push(2);print(); push(4);print(); push(6);print(); push(7);print(); pop();print(); pop();print(); }<file_sep># datastructures Linkedlist problems, Binary tree
f65b1e8fa7e6a7881b37d7f8bd58aadfadf10386
[ "Markdown", "C" ]
13
C
iamkushel/datastructures
0b4fa6b337005d196afebceda641ef4f28945118
a3244e2bfb8c198d6f881b848299860f51e5acc0
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class LockControl : MonoBehaviour { private int[] result, correctCombination; public static bool guessPass; private void Start() { guessPass = false; // correct combination isn't guessed result = new int[] { 5, 5, 5 }; // what the wheels are currently set at correctCombination = new int[] {4,2,0}; rotate.Rotated += CheckResults; } private void Update() { correctCombination = GenerateCode.passWord; } private void CheckResults(string wheelName, int number) // this checks if the wheels are at the correct position / if the combination is correct { switch (wheelName) { case "wheel1": result[2] = number; break; case "wheel2": result[1] = number; break; case "wheel3": result[0] = number; break; } if (result[0] == correctCombination[0] && result[1] == correctCombination[1] && result[2] == correctCombination[2]) { // if everything is correct, set guessPass to true and print "Opened!" Debug.Log("Opened!"); guessPass = true; // this is passed on to OpenLock } } private void OnDestroy() { rotate.Rotated -= CheckResults; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class rotate : MonoBehaviour { public static event Action<string, int> Rotated = delegate { }; private bool coroutineAllowed; private int numberShown; void Start() { coroutineAllowed = true; // tells the program that we can click the wheels numberShown = 5; // this is the number the wheels are starting on in the game } private void OnMouseOver() // right click { if (Distance.distance < 3) { if (Input.GetMouseButtonDown(1)) { if (coroutineAllowed) StartCoroutine("RotateWheelUp"); } } } private void OnMouseDown() // left click { if (Distance.distance < 3) { if (coroutineAllowed) { StartCoroutine("RotateWheelDown"); } } } private IEnumerator RotateWheelDown() { coroutineAllowed = false; // makes the wheel unclickable while the rotation is happening for (int i = 0; i <= 11; i++) // this for loop makes the wheels rotation look realistic { transform.Rotate(0f, 0f, -3f); yield return new WaitForSeconds(0.01f); } coroutineAllowed = true; // makes the wheel clickable again numberShown += 1; // tells the program that the number we're seeing is the number that exists if (numberShown>9) // wraps around so the numbers can't exceed 9 { numberShown = 0; } Rotated(name, numberShown); } private IEnumerator RotateWheelUp() // exactly the opposite of RotateWheelUp { coroutineAllowed = false; for (int i = 0; i <= 11; i++) { transform.Rotate(0f, 0f, 3f); yield return new WaitForSeconds(0.01f); } coroutineAllowed = true; numberShown -= 1; if (numberShown < 0) { numberShown = 9; } Rotated(name, numberShown); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class GenerateCode : MonoBehaviour { private double yPosition = 4.135; public static int[] passWord = new int[3]; public static float distance; public GameObject Player, Object; void Update() { distance = Vector3.Distance(Player.transform.position, Object.transform.position); } private void OnMouseDown() { if (distance < 3) { StartCoroutine("ButtonPushed"); } } private IEnumerator ButtonPushed() { for (int i = 0; i <= 11; i++) // this for loop makes the button push look realistic { yPosition = yPosition - 0.005; transform.position = new Vector3(-48.89f, (float)yPosition, 53.607f); yield return new WaitForSeconds(0.01f); } for (int i = 0; i <= 11; i++) // this for loop makes the button push look realistic { yPosition = yPosition + 0.005; transform.position = new Vector3(-48.89f, (float)yPosition, 53.607f); yield return new WaitForSeconds(0.01f); } for (int i = 0; i < passWord.Length; i++) { passWord[i] = UnityEngine.Random.Range(0, 9); } Debug.Log(String.Join("", passWord)); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class OpenDoor : MonoBehaviour { public GameObject door; private bool coroutineAllowed; public static float distance; public GameObject Player, Object; // Start is called before the first frame update void Start() { coroutineAllowed = true; } // Update is called once per frame void Update() { distance = Vector3.Distance(Player.transform.position, Object.transform.position); } private void OnMouseDown() // left click { if (distance < 5) { if (coroutineAllowed) { coroutineAllowed = false; StartCoroutine("OpeningDoor"); } } } private IEnumerator OpeningDoor() { for (int i = 0; i <= 91; i++) { door.transform.Rotate(0f, -1f, 0f); yield return new WaitForSeconds(0.01f); } yield return new WaitForSeconds(5f); for (int i = 0; i <= 91; i++) { door.transform.Rotate(0f, 1f, 0f); yield return new WaitForSeconds(0.01f); } yield return new WaitForSeconds(0.5f); coroutineAllowed = true; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class OpenLock : MonoBehaviour { public static event Action<string, int> Rotated = delegate { }; private bool open; // Start is called before the first frame update void Start() { open = false; // tells the program that the lock is closed } void Update() { if (LockControl.guessPass) // if the correct combination is entered, open the lock and set the correct password back to false { LockControl.guessPass = false; StartCoroutine("Open"); } if (open) // if the lock is open, call this function described further below { StartCoroutine("Close"); } } private IEnumerator Open() // this will open the lock in a realistic manner { for (int i = 0; i <= 45; i++) { transform.Rotate(0f, 0f, 2f); yield return new WaitForSeconds(0.01f); } open = true; } private IEnumerator Close() // this will wait 5 seconds before closing the lock again { open = false; yield return new WaitForSeconds(5f); Debug.Log("The lock will now close again"); for (int i = 0; i <= 45; i++) { transform.Rotate(0f, 0f, -2f); yield return new WaitForSeconds(0.01f); } } }
b27a804112332c503ff931b9695e8ae9f05ad7ca
[ "C#" ]
5
C#
antonklinker/escape-room
536bae42481194c940576fe35b469a28cf49111d
3cb2dc0ffc1a9e4d8df40f6562e7931fb9ed72fa
refs/heads/master
<file_sep>package com.ghhitech.smisseal.base; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import java.util.List; public abstract class CommomAdapter<Data> extends BaseAdapter { private List<Data> mDatas; private AbsListView mListView; public CommomAdapter(AbsListView listView, List<Data> mDatas) { this.mDatas = mDatas; mListView = listView; } @Override public int getCount() { if (mDatas != null) { return mDatas.size(); } return 0; } @Override public Data getItem(int position) { if (mDatas != null && position < mDatas.size()) { return mDatas.get(position); } return null; } @Override public long getItemId(int position) { return position; } protected abstract BaseHolder getHolder(); @Override public View getView(int position, View convertView, ViewGroup viewGroup) { BaseHolder<Data> holder; if (convertView != null && convertView.getTag() instanceof BaseHolder) { holder = (BaseHolder<Data>) convertView.getTag(); } else { holder = getHolder(); } holder.setPosition(position); holder.setData(mDatas.get(position)); return holder.getRootView(); } } <file_sep># RxRetrofitMvp Retrofit+Rxjava2.0+MVP 网络请求框架 <file_sep>package com.ghhitech.smisseal.picture.datemanager; public class PictureViewHolder { } <file_sep>package com.ghhitech.smisseal.situation.model; public interface ISituation { } <file_sep>package com.ghhitech.smisseal.picture.view; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.model.GlideUrl; import com.bumptech.glide.load.model.LazyHeaders; import com.fasterxml.jackson.core.type.TypeReference; import com.ghhitech.smisseal.R; import com.ghhitech.smisseal.base.BaseHolder; import com.ghhitech.smisseal.base.CommomAdapter; import com.ghhitech.smisseal.base.Items; import com.ghhitech.smisseal.constants.SealConstants; import com.ghhitech.smisseal.datamanager.DataManager; import com.ghhitech.smisseal.picture.model.PictureModel; import com.ghhitech.smisseal.picture.presenter.IPicturePresenter; import com.ghhitech.smisseal.picture.presenter.PicturePresenterCompl; import com.ghhitech.smisseal.situation.model.SituationModel; import com.ghhitech.smisseal.situation.presenter.ISituationPresenter; import com.ghhitech.smisseal.situation.presenter.SituationPresenterCompl; import com.ghhitech.smisseal.situation.view.ISituationView; import com.ghhitech.smisseal.utils.DialogFactoryUtils; import com.ghhitech.smisseal.utils.JSONTOBean; import java.util.Date; import java.util.List; import io.reactivex.Observer; import io.reactivex.Scheduler; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import okhttp3.ResponseBody; public class PictureActivity extends FragmentActivity implements IPictrueView, ISituationView, View.OnClickListener { private DialogFactoryUtils dialogFactoryUtils; private IPicturePresenter picturePresenter; private ISituationPresenter situationPresenter; private PictureModel pictureModelList; // private ListView listView; private ImageView imageView; private Button loadPicture; private Button prePicture; private Button nextPicture; private CommomAdapter<PictureModel> adapter; private int size = 0; private int position = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_picture); // listView = this.findViewById(R.id.listView); imageView = this.findViewById(R.id.image); loadPicture = this.findViewById(R.id.btn_load); prePicture = this.findViewById(R.id.pre_pic); nextPicture = this.findViewById(R.id.next_pic); dialogFactoryUtils = DialogFactoryUtils.builder(this); picturePresenter = new PicturePresenterCompl(this); situationPresenter = new SituationPresenterCompl(this); loadPicture.setOnClickListener(this); prePicture.setOnClickListener(this); nextPicture.setOnClickListener(this); initData(); } private void initData() { // adapter = new CommomAdapter<PictureModel>(listView,pictureModelList) { // @Override // protected BaseHolder getHolder() { // return null; // } // }; } @Override public void showMessage(String title, int msgType) { dialogFactoryUtils.close(); switch (msgType) { case SealConstants.MESSAGE_TYPE_SUCCESS: dialogFactoryUtils.success(title).show(); break; case SealConstants.MESSAGE_TYPE_ERROR: dialogFactoryUtils.error(title).show(); break; case SealConstants.MESSAGE_TYPE_WORNING: dialogFactoryUtils.waring(title, false).show(); break; } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_load: dialogFactoryUtils.progress("正在加载中...").show(); picturePresenter.getPicture("636076636", "2018-02-05 17:37:24", "2018-02-05 17:48:38", 1, 4) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<PictureModel>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(PictureModel pictureModel) { dialogFactoryUtils.close(); if (pictureModel.getList().size() > 0) { loadPicture(pictureModel, 0); size = pictureModel.getList().size(); pictureModelList = pictureModel; position = 0; } } @Override public void onError(Throwable e) { } @Override public void onComplete() { System.out.println("On Complete!"); } }); // situationPresenter.getSituationInfo() // .subscribeOn(Schedulers.io()) // .unsubscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Observer<SituationModel>() { // @Override // public void onSubscribe(Disposable d) { // // } // // @Override // public void onNext(SituationModel situationModel) { // situationModel.isSuccess(); // System.out.println("BreakOffTaskNum:"+situationModel.getList().get(0).getBreakOffTaskNum()); // } // // @Override // public void onError(Throwable e) { // // } // // @Override // public void onComplete() { // System.out.println("On Complete!"); // } // }); break; case R.id.pre_pic: if(position == 0){ dialogFactoryUtils.waring("已经是第一张。",true).show(); }else{ position--; loadPicture(pictureModelList,position); } break; case R.id.next_pic: if((position+1) >= size){ dialogFactoryUtils.waring("已经是最后一张。",true).show(); }else{ position++; loadPicture(pictureModelList,position); } break; } } public void loadPicture(PictureModel pictureModel, int position) { GlideUrl glideUrl = new GlideUrl(pictureModel.getList().get(position).getPhotourl(), new LazyHeaders.Builder().addHeader("Cookie", DataManager.getCookie()).build()); Glide.with(PictureActivity.this) .load(glideUrl) .placeholder(R.drawable.empty) .error(R.drawable.pictures_no) .into(imageView); } } <file_sep>package com.ghhitech.smisseal.login.datamanager; import com.ghhitech.smisseal.login.model.UserModel; import io.reactivex.Observable; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; public interface LoginService { @POST("user/login") Observable<UserModel> getUserLogin(@Query("phone") String userName,@Query("password") String password); @POST("user/login") Call<UserModel> login(@Query("phone") String userName, @Query("password") String password); } <file_sep>package com.ghhitech.smisseal.situation.view; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.FragmentActivity; import com.ghhitech.smisseal.situation.presenter.ISituationPresenter; public class SituationActivity extends FragmentActivity implements ISituationView { private ISituationPresenter situationPresenter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(0); } } <file_sep>package com.ghhitech.smisseal.picture.presenter; import android.content.Context; import android.widget.ImageView; import com.ghhitech.smisseal.constants.SealConstants; import com.ghhitech.smisseal.login.datamanager.LoginService; import com.ghhitech.smisseal.login.model.UserModel; import com.ghhitech.smisseal.network.HttpProvider; import com.ghhitech.smisseal.picture.datemanager.PictureService; import com.ghhitech.smisseal.picture.model.PictureModel; import com.ghhitech.smisseal.picture.view.IPictrueView; import com.ghhitech.smisseal.utils.StringUtils; import io.reactivex.Observable; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class PicturePresenterCompl implements IPicturePresenter{ private IPictrueView iPictrueView; public PicturePresenterCompl(IPictrueView iPictrueView){ this.iPictrueView = iPictrueView; } @Override public Observable getPicture(String deviceId, String startTime, String endTime, int line,int deviceType) { if(StringUtils.isEmpty(deviceId)){ iPictrueView.showMessage("请选择设备!",SealConstants.MESSAGE_TYPE_ERROR); return Observable.error(NullPointerException::new); } if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)){ iPictrueView.showMessage("请选择开始时间与结束时间!",SealConstants.MESSAGE_TYPE_ERROR); return Observable.error(NullPointerException::new); } Retrofit retrofit = new Retrofit.Builder() .client(HttpProvider.Builder((Context) iPictrueView)) .baseUrl(SealConstants.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); PictureService pictureService = retrofit.create(PictureService.class); Observable<PictureModel> observable = pictureService.getTaskPicture(deviceId, startTime, endTime, line,deviceType); LoginService loginService = retrofit.create(LoginService.class); Observable<UserModel> observable2 = loginService.getUserLogin("18100000001","1"); return observable; } } <file_sep>package com.ghhitech.smisseal.network; import org.json.JSONException; import org.json.JSONObject; public class HandleResponseState { /** * 判断请求回来的json ,是否是请求成功的,请求成功返回true ,请求失败返回false * @param json * @return * @throws JSONException */ public static boolean doHandle(String json) { JSONObject jsonO= null; try { jsonO = new JSONObject(json); } catch (JSONException e) { e.printStackTrace(); } String rsp= jsonO.optString("rsp"); if ("succ".equals(rsp)) { return true; } return false; } } <file_sep>package com.ghhitech.smisseal.picture.model; public interface IPicture { } <file_sep>package com.ghhitech.smisseal.network; import android.content.Context; import com.ghhitech.smisseal.constants.SealConstants; import com.ghhitech.smisseal.interceptor.CookieInterceptor; import com.ghhitech.smisseal.interceptor.HeadersInterceptor; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.internal.cache.CacheInterceptor; public class HttpProvider { static OkHttpClient okHttpClient; public static OkHttpClient Builder(Context context){ if (okHttpClient==null) { synchronized (HttpProvider.class) { if (okHttpClient==null) { OkHttpClient client = new OkHttpClient.Builder() .retryOnConnectionFailure(true) .addNetworkInterceptor(new com.ghhitech.smisseal.interceptor.CacheInterceptor()) .cache(new CacheProvider(context).provideCache()) .connectTimeout(SealConstants.DEFAULT_TIMEOUT, TimeUnit.SECONDS) .addInterceptor(new CookieInterceptor()) .addInterceptor(new HeadersInterceptor(context)) .build(); okHttpClient = client; } } } return okHttpClient; } public static boolean checkNULL(String str) { return ((str == null) || ("null".equals(str)) || ("".equals(str))); } }
b97184c65f9d5b28b8369ddfde33ee6f21a17f5e
[ "Markdown", "Java" ]
11
Java
yijigu7745/RxRetrofitMvp
7c7ea5c092d2c69b7cb8861804b6f0d2915aa832
a1f1c6ee345cb4fba3ff6823b346f93d79fc43c2
refs/heads/master
<file_sep>//wishList const wishList = ['idd68', 'idd69', 'idd70', 'idd71',]; //cart const cartList = [ { id: 'idd023', count: 1 }, { id: 'idd024', count: 2 }, { id: 'idd025', count: 4 }, ]; export const loadData = () => { //First step of search if (location.search){ //Decode link name into readable format const search = decodeURI(location.search); console.log(search); //Divide search on before equal sign and after const prop = search.split('=')[0]; const value = search.split('=')[1]; } //Second step of search if (location.hash){ console.log('hash'); } //Third day of search if (location.pathname.includes('cart')){ console.log('cart'); } }; <file_sep>export const catalog = () => { // Day1 const btnBurger = document.querySelector('.btn-burger'); const catalog = document.querySelector('.catalog'); const btnClose = document.querySelector('.btn-close'); const catalogList = document.querySelector('.catalog-list'); const subCatalog = document.querySelector('.subcatalog'); const body = document.querySelector('body'); const subcatalogHeader = document.querySelector('.subcatalog-header'); const btnReturn = document.querySelector('.btn-return'); // const catalogListItem = document.querySelector('.catalog-list__item'); //Generate overlay div to avoid access issue on generated pages. const overlay = document.createElement('div'); overlay.classList.add('overlay'); document.body.insertAdjacentElement('beforeend', overlay); const openMenu = () => { catalog.classList.add('open'); overlay.classList.add('active'); body.classList.add('lock'); }; const closeMenu = () => { closeSubMenu(); catalog.classList.remove('open'); overlay.classList.remove('active'); body.classList.remove('lock'); }; // Открытие под меню const openSubMenu = (event) => { event.preventDefault(); const itemList = event.target.closest('.catalog-list__item'); if (itemList) { itemList.classList.toggle('active'); subcatalogHeader.innerHTML = itemList.innerHTML; subCatalog.classList.add('subopen'); //how to toggle active class for "this" instead of "itemList" variable ? Pls help,I am a new to JS world :) }; }; //Закрытие подменю const closeSubMenu = () => { subCatalog.classList.remove('subopen'); }; //навесить событие на константу btnBurger.addEventListener('click', openMenu); btnClose.addEventListener('click', closeMenu); catalogList.addEventListener('click', openSubMenu); btnReturn.addEventListener('click', closeSubMenu); // Закрытие по полю overlay.addEventListener('click', closeMenu); //Закрытие на клавишу ESC document.addEventListener('keydown', (event) => { if (event.code === 'Escape'){ closeMenu(); }; }); }<file_sep># Ikea-store-fake Учёбный проект интернет-магазина IKEA. https://webdevmaksim.github.io/Ikea-store-fake
0e365e6dc8ba12c2df3299096cf1a0f8af086460
[ "JavaScript", "Markdown" ]
3
JavaScript
Webdevmaksim/Ikea-store-fake
0f123ed4cb62af8f81ffec0bf2bae570303406fb
1ef714400add3e410cf69eb7389f626f80bfb291
refs/heads/master
<file_sep>const express = require('express'); const pool = require('../modules/pool.js'); const router = express.Router(); // get all the images router.get('/', (req, res) => { let query = `SELECT "images".id, "images".title, "images".path, array_agg("images_tag".tag_id) as tags FROM "images" FULL JOIN "images_tag" ON "images_tag".image_id = "images".id GROUP BY "images".id ORDER BY "images".id;` pool.query(query) .then( (results) => { console.log('GET from images router with results: ', results); res.send(results.rows); }).catch( (error) => { console.log('error in GET in images router: ', error); res.sendStatus(500); }) }) //post category tags to router router.post('/', (req, res) => { const queryText = ` INSERT INTO "images_tag"( "tag_id", "image_id") VALUES($1, $2); ` console.log('HERE BE THE BODY', req.body.tagId); pool.query(queryText, [req.body.tagId, req.body.imageId]) .then((result) => { console.log('Response from POST tag route:', result); res.sendStatus(201); }).catch((error) => { console.log('Error in POST tag route:', error); res.sendStatus(500); }) }); module.exports = router;<file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './components/App/App.js'; import registerServiceWorker from './registerServiceWorker'; import { createStore, combineReducers, applyMiddleware } from 'redux'; // Provider allows us to use redux within our react app import { Provider } from 'react-redux'; import logger from 'redux-logger'; // Import saga middleware import createSagaMiddleware from 'redux-saga'; import axios from 'axios'; import { takeEvery, put } from 'redux-saga/effects'; // Create sagaMiddleware const sagaMiddleware = createSagaMiddleware(); //SAGAS function* fetchImages(action) { //triggers our GET and then sending to image reducer and redux console.log('in fetchImages'); try{ let imageResponse = yield axios.get('/api/images'); yield put ({type: 'SET_IMAGES', payload: imageResponse.data}) } catch(error) { console.log('error in get images: ', error) } } function* fetchTagSaga() { const allTheTags = yield axios.get('/api/tags') yield put({ type: 'SET_TAGS', payload: allTheTags.data }) }; //end fetchTags // addTagSaga - add tagId and imageId to the junction table DB function* addTagSaga(action) { //triggers our POST to DB console.log('in addTagSaga with data LOOK HERE YO:', action.payload); try{ yield axios.post('/api/images/addtag', action.payload) yield put({ type: 'FETCH_IMAGES'}) }catch(error){ console.log('error in post: ', error) } } function* displayTagSaga(action) { console.log('YO YO YO', action.payload); try { const displaysToRender = yield axios.get(`/api/imagetag`) console.log('DISPLAYS TO RENDER BE HERE ', displaysToRender.data) yield put({ type: 'NEW_TAG_TO_SHOW', payload: displaysToRender.data }) console.log('in displayTagSaga with tag and imageid: ', displaysToRender.data); }catch(error){ console.log('STUPID EFFING ERROR HERE GUYS: ', error) } // const displaysToRender = axios.get(`/api/imagetag?imageId=${action.payload.imageId}`) // console.log('DISPLAYS TO RENDER BE HERE ', displaysToRender.data) // yield put({type: 'NEW_TAG_TO_SHOW', payload: displaysToRender.data}) // console.log('in displayTagSaga with tag and imageid: ', displaysToRender.data); } //REDUCERS const displayTagReducer = (state=[], action) => { console.log('BOOKS BOOKS BOOKS ',action.payload); switch (action.type) { case 'DISPLAY_TAG': return action.payload; default: return state; } } const newTagToShow = (state = [], action) => { //console.log('in NewTagToShow', action.payload) switch(action.type) { case 'NEW_TAG_TO_SHOW': console.log('in New_tag_to_show: ',action.payload) return action.payload; default: return state } } // GET IMAGES REDUCER // Used to store images returned from the server const images = (state = [], action) => { switch (action.type) { case 'SET_IMAGES': return action.payload; default: return state; } } //TAGS REDUCER // Used to store the images tags (e.g. 'Inspirational', 'Calming', 'Energy', etc.) const tags = (state = [], action) => { switch (action.type) { case 'SET_TAGS': return action.payload; default: return state; } } // Create one store that all components can use const storeInstance = createStore( combineReducers({ images, tags, displayTagReducer, newTagToShow }), // Add sagaMiddleware to our store applyMiddleware(sagaMiddleware, logger), ); // Create the rootSaga generator function function* rootSaga() { yield takeEvery('FETCH_IMAGES', fetchImages); yield takeEvery('ADD_TAG', addTagSaga); yield takeEvery('FETCH_TAGS', fetchTagSaga); yield takeEvery('SET_TAG_FOR_DISPLAY', displayTagSaga) } // Pass rootSaga into our sagaMiddleware sagaMiddleware.run(rootSaga); ReactDOM.render(<Provider store={storeInstance}><App /></Provider>, document.getElementById('root')); registerServiceWorker(); <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import './feeling.css'; import { Button } from '@material-ui/core'; import SingleImage from '../SingleImage/singleImage.jsx'; //import Tags from '../Tags/Tags.jsx'; class Feeling extends Component { state = { index: 0 } componentDidMount() { this.props.dispatch({ type: 'FETCH_IMAGES' }) this.props.dispatch({ type: 'FETCH_TAGS' }) } //if the original index state is 0 and the original index in the images array -1 is 0, show the first image // if the the state's index is not 0, increase the index value by 1 for each click handleIncrease = (event) => { console.log('in handleIncrease'); if(this.state.index === this.props.reduxState.images.length-1){ this.setState({ index: 0 }) } else{ this.setState({ index: this.state.index+1 }) } } //if the original index is set to 0, decrement through the images array backwards from the 'top' of the array ([5] I think) //if the image index is not set to zero, move through the array backwards. handleDecrease = (event) => { console.log('in handleDecrease') if(this.state.index === 0){ this.setState({ index: this.props.reduxState.images.length -1 }) } else{ this.setState({ index: this.state.index -1 }) } } render(){ // console.log('Here is the image array you asked for: ', this.props.reduxState.images); // console.log('LOOK HERE FOR TAGS STUFF: ', this.props.reduxState.tags); let index= this.state.index return( <div className="imageDiv"> <h2>How Does This Image Make You Feel?</h2> <Button onClick={this.handleDecrease} variant="contained" color="primary">Previous Image</Button> {this.props.reduxState.images.map((image, i) => { if(image.id-1 === index){ return ( <SingleImage key={i} image={image}/> )}} )} {/* <Tags/> */} <> <Button onClick={this.handleIncrease} variant="contained" color="primary">Forward</Button> </> </div> )} } // {/* <img key={image.id} src={image.path} alt={image.title} className="feelingImg" /> */ } // {/* // {this.props.reduxState.images.map(image => { */} // {/* // return ( // // <div> // // <Card className="image"> */} // {/* <CardMedia */} // {/* // image="Image path" // // title="IMAGE PATH" // // /> // // <Input placeholder="Test"></Input> // // <CardActions disableActionSpacing> // // <IconButton aria-label="Arrow Back"> // // <ArrowBackIcon /> // // </IconButton> // // <IconButton aria-label="Arrow Forward"> // // <ArrowForwardIcon /> // // </IconButton> // // </CardActions> // // </Card> // // </div> // // )); // // }) // // }} */} const mapStateToProps = (reduxState) => { return { reduxState } } export default connect(mapStateToProps)(Feeling);<file_sep>const express = require('express'); const pool = require('../modules/pool.js'); const router = express.Router(); // add a new tag to image router.get('/', (req, res) => { let query = `SELECT "tags".name, "images_tag".image_id FROM "tags" JOIN "images_tag" ON "tags".id = "images_tag".tag_id JOIN "images" ON "images".id = "images_tag".image_id;`; console.log('req.params is: ', req.params); console.log('req.body is: ', req.body); console.log('req.query is: ', req.query); console.log('the query is here:', query) //let imageId = req.query.imageId; pool.query(query) .then((results) => { console.log('GET from DISPLAY Tags with results: ', results.rows); res.send(results.rows); }).catch((error) => { console.log('error in GET Display in tags router: ', error); res.sendStatus(500); }) }) module.exports = router;<file_sep>## Image Mood Ring Mood Ring is a React-based image carousel, using Redux for client-side data storage and Redux Sagas for making requests to the server. The application allows the user to scroll backward and forward through a continuous loop of photos, see associated tags for each one, and add tags for each one. The application does not rely on any pre-built carousel functionality. ## Built With React Redux Node.js Express.js PostgreSQL, MaterialUI ## Prerequistes - [Node.js](https://nodejs.org/en/) - [PostgresQL](https://www.postgresql.org/) - [Postico](https://eggerapps.at/postico/) ## Installing Steps to get the development environment running. 1. Download this project. 2. Set up a local PostgreSQL database called `saga_weekend` 3. Use the data.sql instructions to create a table in your database 4. In the terminal, `npm install` in the project folder 5. In the terminal, `npm run server` and `npm run client` ## Screen Shot Coming soon ## Completed Features App allows users to - [x] Scroll backward and forward through all images - [x] View all associated tags for each image - [x] Add additional tags for each image ## Authors <NAME> # Acknowledgments Prime Digital Academy and the ENTIRETY of the awesome Baconian Cohort! <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import {Button} from '@material-ui/core'; import './singleImage.css'; class SingleImage extends Component { state = { tagId: '', imageId: this.props.image.id } componentDidMount() { // this.setState({ // imageId: this.props.image.id // }) this.props.dispatch({ type: 'SET_TAG_FOR_DISPLAY', payload: this.state }); //this.getTheThing(); } // getTheThing = (event) => { // this.props.dispatch({ type: 'SET_TAG_FOR_DISPLAY', payload: this.state.imageId }); // } handleTagChange = (event) => { this.setState({ // ...this.state, tagId: event.target.value, imageId: this.props.image.id }) // console.log('in handleTagChange with ID:', event.target.value); } handleSubmit = (event) => { console.log('in handleSubmit with tagID: ', this.state.tagId, this.props.image.id); this.setState({ ...this.state, tagId: event.target.value, imageId: this.props.image.id }) this.props.dispatch({ type: 'ADD_TAG', payload: this.state }) //let url = `/api/imagetag/${this.state.imageId}` this.props.dispatch({ type: 'SET_TAG_FOR_DISPLAY', payload: this.state }); } render(){ console.log('CHASE PROPS: ', this.props) console.log('LOOK HERE FOR RENDERING BUSINESS: ', this.state.imageId) console.log('IMAGE ID', this.state.imageId) return ( <> <img src={this.props.image.path} className="singleImage" alt={this.props.image.title}/> <select value={this.state.tagId} onChange={this.handleTagChange}> <option disabled value="0">This Image Makes Me Feel: </option> {/* <option>Select</option> */} {this.props.reduxState.tags.map(tag => { return ( <option key={tag.id} value={tag.id}>{tag.name}</option> ) })} </select> <Button onClick={this.handleSubmit} variant="contained" color="secondary"> Add My Feeling </Button> {this.props.tagsForImage.map((tagImageItem, i) => { if (tagImageItem.image_id === this.state.imageId){ return( <li key={i}>{tagImageItem.name}</li> ) } })} {/* <li>{this.props.image.tags}</li> */} </> ) } } const mapStateToProps = (reduxState) => { return { reduxState, tagsForImage: reduxState.newTagToShow } } export default connect(mapStateToProps)(SingleImage);<file_sep>// import React, { Component } from 'react'; // import { connect } from 'react-redux'; // import {Button} from '@material-ui/core'; // class Tags extends Component { // state = { // tagId: 0 // } // handleTagChange = (event) => { // this.setState({ // tagId: event.target.value // }) // console.log('in handleTagChange with ID:', event.target.value); // } // handleSubmit = (event) => { // console.log('in handleSubmit with tagID: ', this.state.tagId); // this.setState({ // tagId: event.target.value // }) // this.props.dispatch({type: 'ADD_TAG', payload: this.state}) // this.props.dispatch({type: 'SET_TAG_FOR_DISPLAY', payload:this.state.tagId}) // } // render() { // return ( // <> // <select value={this.state.tagId} onChange={this.handleTagChange}> // <option disabled value="0">This Image Makes Me Feel: </option> // {/* <option>Select</option> */} // {this.props.reduxState.tags.map(tag => { // return ( // <option key={tag.id} value={tag.id}>{tag.name}</option> // ) // })} // </select> // <Button onClick={this.handleSubmit} variant="contained" color="secondary"> Add My Feeling </Button> // </> // ) // } // } // const mapStateToProps = (reduxState) => { // return { // reduxState // } // } // export default connect(mapStateToProps)(Tags);
d12948d2dfb46ad5ad0d393ee84e5721178f84aa
[ "JavaScript", "Markdown" ]
7
JavaScript
mbts8984/saga-mood-ring
6c27dae5c06db5f827087f88e6a95135568954d6
4f383e84f68f1ca6107aacab4192c56218e73c78
refs/heads/master
<repo_name>kartiktanksali/ToDo-List-using-react.js<file_sep>/app.py from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from datetime import datetime from sqlalchemy import DateTime, func from flask_cors import CORS import os #init app app = Flask(__name__) CORS(app) basedir = os.path.abspath(os.path.dirname(__file__)) app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///" + os.path.join(basedir, "db.sqlite") app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False #Initialize DB db = SQLAlchemy(app) #Initialize Marshmallow ma = Marshmallow(app) #Product Class class ToDo(db.Model): id = db.Column(db.Integer, primary_key=True) task = db.Column(db.String(100), unique=True) description = db.Column(db.String(200)) completed = db.Column(db.Boolean) created = db.Column(db.DateTime, default=func.now()) tcomplete = db.Column(db.DateTime) def __init__(self,task,description="deafult"): self.task = task self.description = description self.completed = False #Product Schema class TaskSchema(ma.Schema): class Meta: fields = ("id","task","description","completed","created","tcomplete") #Initialize Schema task_schema = TaskSchema(strict=True) tasks_schema = TaskSchema(many=True, strict=True) #Create a Task @app.route('/todo', methods=["POST"]) def add_task(): task = request.json["task"] description = "default" new_task = ToDo(task,description) db.session.add(new_task) db.session.commit() return task_schema.jsonify(new_task) #Get all Tasks @app.route('/todo', methods=["GET"]) def get_all_tasks(): all_tasks = ToDo.query.all() results = tasks_schema.dump(all_tasks) return jsonify(results.data) #Get single product ''' @app.route('/product/<id>', methods=["GET"]) def get_product(id): product = Product.query.get(id) return product_schema.jsonify(product) ''' #Update a task @app.route('/todo/<id>', methods=["PUT"]) def update_task(id): task = ToDo.query.get(id) if task.completed == True: task.completed = False task.tcomplete = None else: task.completed = True task.tcomplete = func.now() db.session.commit() return task_schema.jsonify(task) #Delete a product @app.route('/todo/<id>', methods=["DELETE"]) def delete_task(id): task = ToDo.query.get(id) db.session.delete(task) db.session.commit() return task_schema.jsonify(task) #run server if __name__ == '__main__': app.run(debug=True)
7629b6b34740ec045663567ed5b899f78686f609
[ "Python" ]
1
Python
kartiktanksali/ToDo-List-using-react.js
7d7ecdbe512d786b37bc51d94920e2217879b601
9dea5597bcd46b4dc29ce2cdfecb13542d79d0b9
refs/heads/master
<repo_name>JackWangCS/StormDataProcessing<file_sep>/src/main/java/com/msopentech/bolt/RunoffControlRateBolt.java package com.msopentech.bolt; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; import com.msopentech.FieldTag; import com.msopentech.Tag; import org.apache.storm.shade.org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; /** * Created by v-wajie on 2015/11/18. */ public class RunoffControlRateBolt extends BaseTimedRichBolt { private final Double INVALID_DATA = -1.0; private final Logger logger = LoggerFactory.getLogger(RunoffControlRateBolt.class); private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private OutputCollector collector; private double rainfall = INVALID_DATA; private double flow = INVALID_DATA; private Jedis jedis; public RunoffControlRateBolt() {} public RunoffControlRateBolt(long interval) { super(interval); } public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) { this.collector = outputCollector; //jedis = new Jedis("172.16.58.3"); } public void execute(Tuple tuple) { if (isTickTuple(tuple)) { //当下雨量和径流量都没有收到时,或者都为0,不发送tuple. if (rainfall < 0.001 && flow < 0.001) return; if (rainfall < 0) { rainfall = 0; logger.info("Time: " + dateFormat.format(new Date()) + " did not receive rainfall tuple"); } if (flow < 0) { flow = 0; logger.info("Time: " + dateFormat.format(new Date()) + " did not receive totalFlow tuple"); } collector.emit(new Values(Tag.RunoffControl, new DateTime().getMillis(), rainfall, flow)); logger.warn("Emit: [{}, {}, {}, {}]", Tag.RunoffControl, new DateTime().toLocalDateTime().toString(), rainfall, flow); rainfall = INVALID_DATA; flow = INVALID_DATA; } else { if (tuple.contains("rainfall")) { rainfall = tuple.getDoubleByField("rainfall"); } else if (tuple.contains("totalFlow")) { flow = tuple.getDoubleByField("totalFlow"); } } collector.ack(tuple); } public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) { outputFieldsDeclarer.declare(new Fields("tag", FieldTag.Datetime.getTag(), "rainVol", "runoffVol")); } } <file_sep>/src/main/java/com/msopentech/Tag.java package com.msopentech; /** * Created by v-wajie on 2015/12/1. */ public enum Tag { RunoffControl, GroundWater, WaterPollution, WaterPonding, AirTemperature, DeviceState } <file_sep>/src/main/java/com/msopentech/bolt/DispatchBolt.java package com.msopentech.bolt; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichBolt; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; import org.json.JSONObject; import java.util.Map; /** * Created by v-wajie on 2015/11/18. * Dispatch the msg to different streams for further processing. */ public class DispatchBolt extends BaseRichBolt { private OutputCollector collector; public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) { collector = outputCollector; } //tuple from EventHubSpout has only one field: message. public void execute(Tuple tuple) { String msg = tuple.getStringByField("message"); JSONObject jsonMsg; try { jsonMsg = new JSONObject(msg); } catch (Exception e) { collector.ack(tuple); return; } String id = jsonMsg.getString("id"); collector.emit("deviceIdStream", new Values(id)); //get the measurements if (jsonMsg.has("eventType") && jsonMsg.get("eventType").equals("Measurements")) { JSONObject measurements = (JSONObject) jsonMsg.get("measurements"); if (measurements.has("rain")) { collector.emit("rainfallStream", new Values(id, measurements.getDouble("rain"))); if (measurements.has("airtemp")) { collector.emit("airTemperatureStream", new Values(id, measurements.getDouble("airtemp"))); } } else if (measurements.has("flowVelocity")) { collector.emit("flowVelocityStream", new Values(id, measurements.getDouble("flowVelocity"))); } else if (measurements.has("watergroundLevel")) { collector.emit("groundwaterStream", new Values(id, measurements.getDouble("watergroundLevel"))); } else if (measurements.has("COD")) { //TODO 完成其他的污染测量值的判断 collector.emit("waterPollutionStream", new Values(id, measurements.getDouble("COD"), measurements.getDouble("TSS"), measurements.getDouble("TN"), measurements.getDouble("TP"), measurements.getDouble("BOD"))); } else if (measurements.has("pondingwaterLevel")) { collector.emit("waterPondingStream", new Values(id, measurements.getDouble("pondingwaterLevel"))); } } collector.ack(tuple); } public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) { outputFieldsDeclarer.declareStream("flowVelocityStream", new Fields("id", "velocity")); outputFieldsDeclarer.declareStream("rainfallStream", new Fields("id", "rainfall")); outputFieldsDeclarer.declareStream("groundwaterStream", new Fields("id", "groundWaterLevel")); outputFieldsDeclarer.declareStream("waterPollutionStream", new Fields("id", "COD", "TSS", "TN", "TP", "BOD")); outputFieldsDeclarer.declareStream("waterPondingStream", new Fields("id", "waterLevel")); outputFieldsDeclarer.declareStream("airTemperatureStream", new Fields("id", "airTemperature")); outputFieldsDeclarer.declareStream("deviceIdStream", new Fields("id")); } } <file_sep>/src/main/java/com/msopentech/bolt/AvgGroundWaterBolt.java package com.msopentech.bolt; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; import com.msopentech.FieldTag; import com.msopentech.Tag; import org.apache.storm.shade.org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; /** * Created by v-wajie on 2015/12/1. * 计算整个地区的平均地下水潜水高度,只是对每个测量点数据进行简单平均 */ public class AvgGroundWaterBolt extends BaseTimedRichBolt { private static final Logger logger = LoggerFactory.getLogger(AvgGroundWaterBolt.class); private OutputCollector collector; private double groundHeightSum; private double groundwaterLevelSum; private int count; public AvgGroundWaterBolt() {} public AvgGroundWaterBolt(long interval) { super(interval); } public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) { this.collector = outputCollector; groundHeightSum = 0; groundwaterLevelSum = 0; count = 0; } //TODO 年平均地下水潜水水位的计算过程需要再讨论, 目前只是将各个测量点平均。 public void execute(Tuple tuple) { if (isTickTuple(tuple)) { if (count != 0) { collector.emit(new Values(Tag.GroundWater, new DateTime().getMillis(), groundHeightSum / count, groundwaterLevelSum / count)); logger.warn("Emit: [{}, {}, {}, {}]", Tag.GroundWater,new DateTime().toLocalDateTime().toString(), groundHeightSum / count, groundwaterLevelSum / count); } groundHeightSum = 0.0; groundwaterLevelSum = 0.0; count = 0; } else { groundHeightSum += tuple.getDoubleByField("groundHeight"); groundwaterLevelSum += tuple.getDoubleByField("groundWaterLevel"); ++count; } collector.ack(tuple); } public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) { outputFieldsDeclarer.declare(new Fields("tag", FieldTag.Datetime.getTag(), "groundHeight", "groundWaterLevel")); } } <file_sep>/src/main/resources/log4j.properties log4j.rootLogger=debug,consoleAppender log4j.appender.consoleAppender=org.apache.log4j.ConsoleAppender log4j.appender.consoleAppender.layout=org.apache.log4j.TTCCLayout log4j.logger.org.apache.storm=ERROR log4j.logger.org.apache.zookeeper=ERROR log4j.logger.backtype.storm=ERROR log4j.logger.org.apache.storm.jdbc=DEBUG log4j.logger.com.microsoft=ERROR <file_sep>/src/main/java/com/msopentech/bolt/FlowBolt.java package com.msopentech.bolt; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; import java.util.Map; /** * Created by v-wajie on 2015/11/20. */ public class FlowBolt extends BaseTimedRichBolt { private OutputCollector collector; private double totalFlow; public FlowBolt() { } public FlowBolt(long interval) { super(interval); } public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) { collector = outputCollector; totalFlow = 0; } public void execute(Tuple tuple) { if (isTickTuple(tuple)) { if (totalFlow > 0.001) { collector.emit(new Values(totalFlow)); totalFlow = 0; } } else { double flow = tuple.getDoubleByField("flow"); totalFlow += flow; } collector.ack(tuple); } public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) { outputFieldsDeclarer.declare(new Fields("totalFlow")); } } <file_sep>/src/main/java/com/msopentech/bolt/WaterPondingDepthBolt.java package com.msopentech.bolt; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; import com.msopentech.FieldTag; import com.msopentech.Tag; import org.apache.storm.shade.org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * Created by v-wajie on 2015/12/1. */ public class WaterPondingDepthBolt extends BaseTimedRichBolt { private static final Logger logger = LoggerFactory.getLogger(WaterPondingDepthBolt.class); private OutputCollector collector; private Map<String, Double> receivedSum; private Map<String, Integer> receivedCount; public WaterPondingDepthBolt() {} public WaterPondingDepthBolt(long interval) { super(interval); receivedCount = new HashMap<String, Integer>(); receivedSum = new HashMap<String, Double>(); } public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) { this.collector = outputCollector; } public void execute(Tuple tuple) { if (isTickTuple(tuple)) { for (String id : receivedCount.keySet()) { if (receivedCount.get(id) != 0) { double pondingDepth = getPondingDepth(id); double avgMeasuredValue= receivedSum.get(id) / receivedCount.get(id); double measurement = Math.abs(avgMeasuredValue - pondingDepth); collector.emit(new Values(Tag.WaterPonding, new DateTime().getMillis(), id, measurement)); logger.warn("Emit: [{}, {}, {}]", Tag.WaterPonding, new DateTime().toLocalDateTime().toString(), measurement); } } for (String id : receivedCount.keySet()) { receivedCount.put(id, 0); receivedSum.put(id, 0.0); } } else { String id = tuple.getStringByField("id"); Double measuredValue = tuple.getDoubleByField("waterLevel"); if (receivedCount.containsKey(id)) { receivedSum.put(id, receivedSum.get(id) + measuredValue); receivedCount.put(id, receivedCount.get(id) + 1); } else { receivedCount.put(id, 1); receivedSum.put(id, measuredValue); } } collector.ack(tuple); } public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) { outputFieldsDeclarer.declare(new Fields("tag", FieldTag.Datetime.getTag(), "id", "pondingLevel")); } private double getPondingDepth(String id) { return 20; } private String getPondingLocation(String id) { return "Location"; } } <file_sep>/src/main/java/com/msopentech/bolt/WaterPollutionControlBolt.java package com.msopentech.bolt; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; import com.msopentech.FieldTag; import com.msopentech.Tag; import org.apache.storm.shade.org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * Created by v-wajie on 2015/12/1. */ public class WaterPollutionControlBolt extends BaseTimedRichBolt { private static final Logger logger = LoggerFactory.getLogger(WaterPollutionControlBolt.class); private OutputCollector collector; private Map<String, PollutionValues> measurements; public WaterPollutionControlBolt() {} public WaterPollutionControlBolt(long interval) { super(interval); } public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) { this.collector = outputCollector; measurements = new HashMap<String, PollutionValues>(); } public void execute(Tuple tuple) { if (isTickTuple(tuple)) { for (String id : measurements.keySet()) { PollutionValues values = measurements.get(id); if (values.getCount() != 0) { collector.emit(new Values(Tag.WaterPollution, id, new DateTime().getMillis(), values.getCOD(), values.getTSS(), values.getTN(), values.getTP(), values.getBOD())); logger.warn("Emit [{}, {}, {}]", Tag.WaterPollution, new DateTime().toLocalDateTime().toString(), values); } values.reset(); measurements.put(id, values); } } else { String id = tuple.getStringByField("id"); double cod = tuple.getDoubleByField("COD"); double tss = tuple.getDoubleByField("TSS"); double tn = tuple.getDoubleByField("TN"); double tp = tuple.getDoubleByField("TP"); double bod = tuple.getDoubleByField("BOD"); if (!measurements.containsKey(id)) { measurements.put(id, new PollutionValues(id)); } PollutionValues values = measurements.get(id); values.addValue(cod, tss, tn, tp, bod); measurements.put(id, values); } collector.ack(tuple); } public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) { outputFieldsDeclarer.declare(new Fields("tag", "id", FieldTag.Datetime.getTag(), FieldTag.COD.getTag(), FieldTag.TSS.getTag(), FieldTag.TN.getTag(), FieldTag.TP.getTag(), FieldTag.BOD.getTag())); } static class PollutionValues { private String id; private double codSum; private double tssSum; private double tnSum; private double tpSum; private double bodSum; private int count; public void reset() { count = 0; codSum = 0.0; tssSum = 0.0; tnSum = 0.0; tpSum = 0.0; bodSum = 0.0; } public PollutionValues(String id) { this.id = id; reset(); } public void addValue(double cod, double tss, double tn, double tp, double bod) { this.codSum += cod; this.tssSum += tss; this.tnSum += tn; this.tpSum += tp; this.bodSum += bod; this.count++; } public String getId() { return id; } public int getCount() { return count; } public double getCOD() { if (count != 0) return codSum / count; return 0; } public double getTSS() { if (count != 0) return tssSum / count; return 0; } public double getTN() { if (count != 0) return tnSum / count; return 0; } public double getTP() { if (count != 0) return tpSum / count; return 0; } public double getBOD() { if (count != 0) return bodSum / count; return 0; } @Override public String toString() { return "COD: " + getCOD() + " TSS: " + getBOD() + " TN: " + getTN() + " TP: " + getTP() + " BOD: " + getBOD(); } } }<file_sep>/src/main/java/com/msopentech/bolt/AirTemperatureBolt.java package com.msopentech.bolt; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; import com.msopentech.FieldTag; import com.msopentech.Tag; import org.apache.storm.shade.org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; /** * Created by v-wajie on 2015/12/1. */ public class AirTemperatureBolt extends BaseTimedRichBolt { private static final Logger logger = LoggerFactory.getLogger(AirTemperatureBolt.class); private OutputCollector collector; private double sum; private int count; public AirTemperatureBolt() {} public AirTemperatureBolt(long interval) { super(interval); } public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) { this.collector = outputCollector; sum = 0.0; count = 0; } public void execute(Tuple tuple) { if (isTickTuple(tuple)) { if (count != 0) { collector.emit(new Values(Tag.AirTemperature, new DateTime().getMillis(), sum / count)); logger.warn("Emit: [{}, {}, {}]", Tag.AirTemperature, new DateTime().toLocalDateTime().toString(), sum / count); } sum = 0.0; count = 0; } else { sum += tuple.getDoubleByField("airTemperature"); ++count; } collector.ack(tuple); } public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) { outputFieldsDeclarer.declare(new Fields("tag", FieldTag.Datetime.getTag(), "airTemperature")); } } <file_sep>/src/main/java/com/msopentech/bolt/JdbcStoreBolt.java package com.msopentech.bolt; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.tuple.Tuple; import com.msopentech.Tag; import org.apache.storm.jdbc.bolt.AbstractJdbcBolt; import org.apache.storm.jdbc.common.Column; import org.apache.storm.jdbc.common.ConnectionProvider; import org.apache.storm.jdbc.mapper.JdbcMapper; import org.apache.storm.shade.org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.util.*; /** * Created by v-wajie on 2015/12/1. */ public class JdbcStoreBolt extends AbstractJdbcBolt{ private Map<Tag, JdbcMapper> mappers; private Map<Tag, String> sqlStatements; private Set<Tag> registeredTags; private final static int DEFAULT_QUERY_TIMEOUT_SECS = 10; private Jedis jedis = null; private final Logger logger = LoggerFactory.getLogger(JdbcStoreBolt.class); private static JedisPool jedisPool; public JdbcStoreBolt(ConnectionProvider connectionProvider, int timeoutSecs) { super(connectionProvider); this.queryTimeoutSecs = timeoutSecs; mappers = new HashMap<Tag, JdbcMapper>(); sqlStatements = new HashMap<Tag, String>(); registeredTags = new TreeSet<Tag>(); } public JdbcStoreBolt(ConnectionProvider connectionProvider) { this(connectionProvider, DEFAULT_QUERY_TIMEOUT_SECS); } public void register(Tag tag, JdbcMapper mapper, String insertSql) { registeredTags.add(tag); mappers.put(tag, mapper); sqlStatements.put(tag, insertSql); } public void remove(Tag tag) { if (isRegistered(tag)) { registeredTags.remove(tag); mappers.remove(tag); sqlStatements.remove(tag); } } private JedisPool getJedisPool() { if (jedisPool == null) { jedisPool = new JedisPool(new JedisPoolConfig(), "172.16.58.3", 6379); } return jedisPool; } private Jedis getJedis() { if (jedis == null) { //Redis客户端, 100000毫秒超时 try { jedis = new Jedis("172.16.58.3", 6379, 100000); } catch (Exception e) { jedis = null; logger.info("Jedis Connect to Server failed, Exception: {}", e.toString()); } } return jedis; } public boolean isRegistered(Tag tag) { return registeredTags.contains(tag); } @Override public void cleanup() { super.cleanup(); if (jedisPool != null) { jedisPool.destroy(); } } @Override public void prepare(Map map, TopologyContext topologyContext, OutputCollector collector) { super.prepare(map, topologyContext, collector); if (registeredTags.isEmpty()) { throw new IllegalArgumentException("You must supply at least one stream"); } } public void execute(Tuple tuple) { logger.warn("Time: {}. Received Tuple: {} and processed time is {}.", new DateTime().toLocalDateTime().toString(), tuple.getValues().toString(), new DateTime(tuple.getLongByField("datetime")).toLocalDateTime().toString()); collector.ack(tuple); final Tuple myTuple = tuple; final Tag tag = (Tag) tuple.getValueByField("tag"); if (tag != null && isRegistered(tag)) { List<Column> columns = mappers.get(tag).getColumns(tuple); final List<List<Column>> columnLists = new ArrayList<List<Column>>(); columnLists.add(columns); new Thread(new Runnable() { public void run() { //发送到Redis sendToRedis(myTuple); jdbcClient.executeInsertQuery(sqlStatements.get(tag), columnLists); } }).start(); } } private void sendToRedis(Tuple tuple) { StringBuilder builder = new StringBuilder(); Tag tag = (Tag) tuple.getValueByField("tag"); builder.append("type:").append(tag.toString()); if (Tag.RunoffControl == tag) { builder.append(" rain:").append(tuple.getDoubleByField("rainVol")) .append(" runoff:").append(tuple.getDoubleByField("runoffVol")) .append(" raincontrol:").append(0.0); } else if (Tag.GroundWater == tag) { builder.append(" groundwaterLevel:").append(tuple.getDoubleByField("groundWaterLevel")); } else if (Tag.AirTemperature == tag) { builder.append(" temperature:").append(tuple.getDoubleByField("airTemperature")); } else if (Tag.WaterPollution == tag) { String[] indexStrs = {"COD", "TSS", "TN", "TP"}; for (String index : indexStrs) { builder.append(" ").append(index).append(":").append(tuple.getDoubleByField(index)); } } else if (Tag.WaterPonding == tag) { builder.append(" waterLevel:").append(0.0) .append(" liquidLevel:").append(0.0) .append(" waterDepth:").append(tuple.getDoubleByField("pondingLevel")); } /*try { if (getJedis() != null && getJedis().) getJedis().publish("logstash-demo", builder.toString()); } catch (Exception e) { getJedis().connect(); logger.info("Redis publish Exception: {}", e.toString()); }*/ Jedis jedis = null; try { jedis = getJedisPool().getResource(); jedis.publish("logstash-demo", builder.toString()); } finally { if (jedis != null) { jedis.close(); } } } public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) { } } <file_sep>/src/main/java/com/msopentech/MainTopology.java package com.msopentech; import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.StormSubmitter; import backtype.storm.generated.AlreadyAliveException; import backtype.storm.generated.AuthorizationException; import backtype.storm.generated.InvalidTopologyException; import backtype.storm.generated.StormTopology; import backtype.storm.topology.TopologyBuilder; import backtype.storm.tuple.Fields; import com.microsoft.eventhubs.spout.EventHubSpout; import com.microsoft.eventhubs.spout.EventHubSpoutConfig; import com.msopentech.bolt.*; import org.apache.storm.jdbc.common.Column; import org.apache.storm.jdbc.common.ConnectionProvider; import org.apache.storm.jdbc.common.HikariCPConnectionProvider; import org.apache.storm.jdbc.mapper.SimpleJdbcMapper; import org.apache.storm.shade.org.joda.time.DateTime; import java.io.IOException; import java.sql.Types; import java.util.*; /** * Created by v-wajie on 2015/11/18. */ public class MainTopology { private EventHubSpoutConfig spoutConfig; private ConnectionProvider connectionProvider; private int numWorkers; private long interval = 60; private long deviceHeartBeatInterval = 90; private final boolean runLocal = true; private void initEventHubConfig() { Properties eventHubProps = PropertyUtil.loadProperties("eventhub"); String username = eventHubProps.getProperty("username"); String password = eventHubProps.getProperty("password"); String namespaceName = eventHubProps.getProperty("namespaceName"); String entityPath = eventHubProps.getProperty("entityPath"); String targetAddress = eventHubProps.getProperty("targetAddress"); int partitionCount = Integer.parseInt(eventHubProps.getProperty("partitionCount")); spoutConfig = new EventHubSpoutConfig(username, password, namespaceName, entityPath, partitionCount); spoutConfig.setTargetAddress(targetAddress); //Only Receive latest msgs in the Eventhub. spoutConfig.setEnqueueTimeFilter(new DateTime().getMillis()); numWorkers = spoutConfig.getPartitionCount(); } private Map<String, Object> initAzureSQLConfig() { Properties sqlServerProps = PropertyUtil.loadProperties("sqlserver"); Map<String, Object> map = new HashMap<String, Object>(); for (Object key : sqlServerProps.keySet()) { map.put(key.toString(), sqlServerProps.get(key)); } return map; } private JdbcStoreBolt buildJdbcStoreBolt() { connectionProvider = new HikariCPConnectionProvider(initAzureSQLConfig()); JdbcStoreBolt jdbcStoreBolt = new JdbcStoreBolt(connectionProvider); List<Column> schemaColumns = new ArrayList<Column>(); schemaColumns.add(new Column("datetime", Types.TIMESTAMP)); schemaColumns.add(new Column("rainVol", Types.FLOAT)); schemaColumns.add(new Column("runoffVol", Types.FLOAT)); SimpleJdbcMapper runoffControlRateMapper = new SimpleJdbcMapper(schemaColumns); jdbcStoreBolt.register(Tag.RunoffControl, runoffControlRateMapper, "insert into rainControlRate(datetime, rainVol, runoffVol) values (?, ?, ?)"); schemaColumns = new ArrayList<Column>(); schemaColumns.add(new Column("datetime", Types.TIMESTAMP)); schemaColumns.add(new Column("groundHeight", Types.FLOAT)); schemaColumns.add(new Column("groundWaterLevel", Types.FLOAT)); SimpleJdbcMapper groundwaterMapper = new SimpleJdbcMapper(schemaColumns); jdbcStoreBolt.register(Tag.GroundWater, groundwaterMapper, "insert into groundwaterMonitor(datetime, groundLevel, groundwaterLevel) values (?, ?, ?)"); schemaColumns = new ArrayList<Column>(); schemaColumns.add(new Column("datetime", Types.TIMESTAMP)); schemaColumns.add(new Column("COD", Types.FLOAT)); schemaColumns.add(new Column("TSS", Types.FLOAT)); schemaColumns.add(new Column("TN", Types.FLOAT)); schemaColumns.add(new Column("TP", Types.FLOAT)); schemaColumns.add(new Column("BOD", Types.FLOAT)); SimpleJdbcMapper waterPollutionMapper = new SimpleJdbcMapper(schemaColumns); jdbcStoreBolt.register(Tag.WaterPollution, waterPollutionMapper, "insert into pollutionMonitor(datetime, COD, TSS, TN, TP, BOD) values (?, ?, ?, ?, ?, ?)"); schemaColumns = new ArrayList<Column>(); schemaColumns.add(new Column("datetime", Types.TIMESTAMP)); //schemaColumns.add(new Column("location", Types.VARCHAR)); schemaColumns.add(new Column("pondingLevel", Types.FLOAT)); SimpleJdbcMapper waterPondingMapper = new SimpleJdbcMapper(schemaColumns); jdbcStoreBolt.register(Tag.WaterPonding, waterPondingMapper, "insert into waterloggingMonitor(datetime, waterLevel) values (?, ?)"); schemaColumns = new ArrayList<Column>(); schemaColumns.add(new Column("datetime", Types.TIMESTAMP)); schemaColumns.add(new Column("airTemperature", Types.FLOAT)); SimpleJdbcMapper airTemperatureMapper = new SimpleJdbcMapper(schemaColumns); jdbcStoreBolt.register(Tag.AirTemperature, airTemperatureMapper, "insert into heatislandMonitor(datetime, temperature) values (?, ?)"); schemaColumns = new ArrayList<Column>(); schemaColumns.add(new Column("datetime", Types.TIMESTAMP)); schemaColumns.add(new Column("id", Types.VARCHAR)); schemaColumns.add(new Column("state", Types.VARCHAR)); SimpleJdbcMapper deviceStateMapper = new SimpleJdbcMapper(schemaColumns); jdbcStoreBolt.register(Tag.DeviceState, deviceStateMapper, "insert into devicestateMonitor(datetime, id, state) values (?, ?, ?)"); return jdbcStoreBolt; } private StormTopology buildTopology() { int parallelismNum = spoutConfig.getPartitionCount(); TopologyBuilder builder = new TopologyBuilder(); EventHubSpout eventHubSpout = new EventHubSpout(spoutConfig); builder.setSpout("EventHubSpout", eventHubSpout, parallelismNum) .setNumTasks(parallelismNum); builder.setBolt("DispatchBolt", new DispatchBolt(), parallelismNum) .localOrShuffleGrouping("EventHubSpout") .setNumTasks(parallelismNum); //rainfall subTopology builder.setBolt("RainfallBolt", new RainfallBolt(interval), 2) .fieldsGrouping("DispatchBolt", "rainfallStream", new Fields("id")); builder.setBolt("PartialRainfallBolt", new PartialRainfallBolt(interval), 1) .localOrShuffleGrouping("RainfallBolt"); builder.setBolt("FinalRainfallBolt", new FinalRainfallBolt(interval), 1) .localOrShuffleGrouping("PartialRainfallBolt"); //runoff flow subTopology builder.setBolt("FlowVelocityBolt", new FlowVelocityBolt(interval), 2) .fieldsGrouping("DispatchBolt", "flowVelocityStream", new Fields("id")); builder.setBolt("FlowBolt", new FlowBolt(interval), 1) .localOrShuffleGrouping("FlowVelocityBolt"); //runoff Control Bolt builder.setBolt("RunoffControlBolt", new RunoffControlRateBolt(interval), 1) .localOrShuffleGrouping("FlowBolt") .localOrShuffleGrouping("FinalRainfallBolt"); //groundwater subTopology builder.setBolt("GroundWaterBolt", new GroundWaterBolt(interval), 4) .fieldsGrouping("DispatchBolt", "groundwaterStream", new Fields("id")); builder.setBolt("AvgGroundWaterBolt", new AvgGroundWaterBolt(interval), 1) .localOrShuffleGrouping("GroundWaterBolt"); //water pollution subTopology builder.setBolt("WaterPollutionControlBolt", new WaterPollutionControlBolt(interval), 1) .fieldsGrouping("DispatchBolt", "waterPollutionStream", new Fields("id")); //water ponding subTopology builder.setBolt("WaterPondingDepthBolt", new WaterPondingDepthBolt(interval), 1) .fieldsGrouping("DispatchBolt", "waterPondingStream", new Fields("id")); //air temperature subTopology builder.setBolt("AirTemperatureBolt", new AirTemperatureBolt(interval), 1) .fieldsGrouping("DispatchBolt", "airTemperatureStream", new Fields("id")); //device state subTopology builder.setBolt("DeviceStateBolt", new DeviceHeartBeatBolt(deviceHeartBeatInterval), 1) .fieldsGrouping("DispatchBolt", "deviceIdStream", new Fields("id")); JdbcStoreBolt jdbcStoreBolt = buildJdbcStoreBolt(); builder.setBolt("JdbcStoreBolt", jdbcStoreBolt, 1) .localOrShuffleGrouping("RunoffControlBolt") .localOrShuffleGrouping("AvgGroundWaterBolt") .localOrShuffleGrouping("WaterPollutionControlBolt") .localOrShuffleGrouping("WaterPondingDepthBolt") .localOrShuffleGrouping("AirTemperatureBolt") .localOrShuffleGrouping("DeviceStateBolt"); return builder.createTopology(); } private void runScenario(String[] args) throws IOException, InterruptedException, AlreadyAliveException, InvalidTopologyException, AuthorizationException { initEventHubConfig(); StormTopology topology = buildTopology(); Config config = new Config(); if (runLocal) { config.setMaxTaskParallelism(4); //config.setDebug(true); LocalCluster localCluster = new LocalCluster(); localCluster.submitTopology(args[0], config, topology); /*Thread.sleep(5000000); localCluster.shutdown();*/ } else { config.setNumWorkers(numWorkers); config.setDebug(true); StormSubmitter.submitTopology(args[0], config, topology); } } public long getInterval() { return interval; } public void setInterval(long interval) { this.interval = interval; } public static void main(String[] args) throws Exception { MainTopology mainTopology = new MainTopology(); mainTopology.runScenario(args); } }
11beb9ca5bbc952d6ff7fb6135260e4d5ce61daf
[ "Java", "INI" ]
11
Java
JackWangCS/StormDataProcessing
d42d05cbcd10c0c16d06a6e9e22c8f0fa16fa7b5
f08e6f47b6624d63430c3408f5eaa94a0de24f40
refs/heads/master
<repo_name>gotchacode/python-cookbook<file_sep>/data-structure-and-algo/eg1.py p = (4, 5) x, y = p data = ['ACME', 50, 20, 3, (34, 4, 5)] name, share, price, other = data s = 'Hello' a, b, c, d, e = s def drop_first_last(grades): first, *middle, last = grades return avg(middle) record = ('dave', '<EMAIL>', '86765444', '8765555') name, email, *phone_number = user_record *trailing, current = [9, 8, 8, 75, 6, 643, 3, 6] records = [ ('foo', 1, 2), ('bar', 'hello'), ('foo', 3, 4), ] def do_foo(x, y): print('foo', x, y) def do_bar(s): print('bar', s) for tag, *args in records: if tag == 'foo': do_foo(*args) elif tag == 'bar': do_bar(*args) <file_sep>/README.md python-cookbook =============== This repo contains the source code from the book Python cookbook.
e90d7eaf8d647d91597c8eca93afc5d0e785f23b
[ "Markdown", "Python" ]
2
Python
gotchacode/python-cookbook
103fbd6d7daa4ef208df189169d1fb6f32423674
58b1e0921d99a2f40ccd7ed313c305e4a66db62a
refs/heads/master
<repo_name>zygisn/game-development<file_sep>/Assets/scripts/player.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; //to catch empty Serialize fields public class player : MonoBehaviour { [SerializeField] private float jumpForce = 70f; [SerializeField] private AudioClip sfxJump; [SerializeField] private AudioClip sfxDeath; [SerializeField] private AudioClip sfxExplosion; private Animator anim; private Rigidbody rb; private AudioSource audioSource; void Awake() { Assert.IsNotNull (sfxJump); Assert.IsNotNull (sfxDeath); } // Use this for initialization void Start () { anim = GetComponent<Animator>(); rb = GetComponent<Rigidbody>(); audioSource = GetComponent<AudioSource>(); } // Update is called once per frame void Update () { } void FixedUpdate (){ jump(); } public void jump(){ if(!gameManager.instance.isGameOver() && gameManager.instance.isGameStarted()){ if(Input.GetKeyDown(KeyCode.Space) || (Input.touchCount > 0) && Input.GetTouch(0).phase == TouchPhase.Began){ gameManager.instance.playerBecomesActive(); rb.useGravity = true; rb.velocity = new Vector2(0f, 0f); // Disabling player falling velocity rb.freezeRotation = true; // Disabling player rotation on Y axis rb.AddForce(0f, jumpForce, 0f, ForceMode.Impulse); audioSource.PlayOneShot(sfxJump); anim.Play("jump"); } } } void OnCollisionEnter(Collision collision){ if(collision.gameObject.tag == "rock" || collision.gameObject.tag == "rocket" || collision.gameObject.tag == "ground"){ //gameObject.GetComponent<Collider>().isTrigger = true; rb.AddForce(-20f, -40f, 0f, ForceMode.Impulse); if(collision.gameObject.tag == "rock" || collision.gameObject.tag == "ground"){ audioSource.PlayOneShot(sfxDeath); }else{ audioSource.PlayOneShot(sfxExplosion); } gameManager.instance.gameIsOver(); StartCoroutine(gameManager.instance.gameOverTxt()); } } } <file_sep>/Assets/Scripts/gameManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.UI; // to catch empty Serialized fields using UnityEngine.SceneManagement; public class gameManager : MonoBehaviour { public static gameManager instance = null; private Vector3 fp; //First touch position private Vector3 lp; //Last touch position private float dragDistance; private int points = 0; [SerializeField] private List<GameObject> rocketList; [SerializeField] private GameObject mainMenu; [SerializeField] private GameObject gameOverTexture; [SerializeField] private GameObject zombie; [SerializeField] private GameObject zombieOnPlay; [SerializeField] private GameObject rockets; [SerializeField] private GameObject warning; [SerializeField] private GameObject scoreGO; [SerializeField] private Text score; private bool playerActive = false; private bool gameOver = false; private bool gameStarted = false; public Color originalPlayerMaterialColor; public Color currentPlayerMaterialColor; // pakeisti i private lauka void Awake () { Assert.IsNotNull (mainMenu); if (instance == null) { instance = this; } else if (instance != this) { Destroy (gameObject); } } // Use this for initialization void Start () { scoreGO.SetActive(false); score.text = "Score: 0"; dragDistance = Screen.height * 15 / 100; //dragDistance is 15% height of the screen originalPlayerMaterialColor = zombie.GetComponent<Renderer> ().material.color; currentPlayerMaterialColor = originalPlayerMaterialColor; InvokeRepeating("createRockets", 5f, 15f); InvokeRepeating("destroyRockets", 10f, 15f); InvokeRepeating("addPoints", 5f, 10f); } // Update is called once per frame void Update () { swipeControlls (); } public bool isPlayerActive () { return playerActive; } public void playerBecomesActive () { playerActive = true; } public bool isGameOver () { return gameOver; } public void gameIsOver () { gameOver = true; } public void startTheGame () { mainMenu.SetActive (false); gameStarted = true; scoreGO.SetActive(true); zombieOnPlay.GetComponent<Renderer>().material.color = currentPlayerMaterialColor; } public bool isGameStarted () { return gameStarted; } public IEnumerator gameOverTxt () { yield return new WaitForSeconds (3f); gameOverTexture.SetActive (true); } public void restartTheScene () { SceneManager.LoadScene ("game"); //mainMenu.SetActive(false); } public void createRockets(){ if(isPlayerActive()){ float y = Random.Range(-10f, 0f); //Instantiate(warning, new Vector3(13.07f, y-2, 1f), Quaternion.identity); rocketList.Add(Instantiate(rockets, new Vector3(transform.position.x,y,0), Quaternion.identity)); rocketList.Add(Instantiate(rockets, new Vector3(transform.position.x+9,y-2,0), Quaternion.identity)); rocketList.Add(Instantiate(rockets, new Vector3(transform.position.x+18,y-4,0), Quaternion.identity)); //StartCoroutine(blinkWarning()); } } public void addPoints(){ if(isPlayerActive() && !isGameOver()){ points += 20; score.text = "Score: " + points; } } public void destroyRockets(){ Destroy(rocketList[0]); Destroy(rocketList[1]); Destroy(rocketList[2]); rocketList.RemoveAt(2); rocketList.RemoveAt(1); rocketList.RemoveAt(0); } public void swipeControlls () { if (!gameStarted) { if (Input.touchCount == 1) { // user is touching the screen with a single touch Touch touch = Input.GetTouch (0); // get the touch if (touch.phase == TouchPhase.Began) { //check for the first touch fp = touch.position; lp = touch.position; } else if (touch.phase == TouchPhase.Moved) { // update the last position based on where they moved lp = touch.position; } else if (touch.phase == TouchPhase.Ended) { //check if the finger is removed from the screen lp = touch.position; //last touch position. Ommitted if you use list //Check if drag distance is greater than 20% of the screen height if (Mathf.Abs (lp.x - fp.x) > dragDistance || Mathf.Abs (lp.y - fp.y) > dragDistance) {//It's a drag //check if the drag is vertical or horizontal if (Mathf.Abs (lp.x - fp.x) > Mathf.Abs (lp.y - fp.y)) { //If the horizontal movement is greater than the vertical movement... if ((lp.x > fp.x)) { //If the movement was to the right) //Right swipe zombie.GetComponent<Renderer> ().material.color = Color.red; currentPlayerMaterialColor = zombie.GetComponent<Renderer> ().material.color; Debug.Log ("Right Swipe"); } else { //Left swipe zombie.GetComponent<Renderer> ().material.color = originalPlayerMaterialColor; currentPlayerMaterialColor = zombie.GetComponent<Renderer> ().material.color; Debug.Log ("Left Swipe"); } } else { //the vertical movement is greater than the horizontal movement if (lp.y > fp.y) { //If the movement was up//Up swipe Debug.Log ("Up Swipe"); } else { //Down swipe Debug.Log ("Down Swipe"); } } } else { //It's a tap as the drag distance is less than 20% of the screen height Debug.Log ("Tap"); } } } } } public IEnumerator blinkWarning(){ //warning.SetActive(false); for(int i=0; i < 5; i++) { warning.SetActive(true); yield return new WaitForSeconds(1); warning.SetActive(false); } } } <file_sep>/Assets/scripts/moveObject.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class moveObject : MonoBehaviour { public float objectSpeed = 4f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { moveObjectLeft(); } protected virtual void moveObjectLeft(){ if(!gameManager.instance.isGameOver()){ transform.Translate(Vector3.left * (objectSpeed * Time.deltaTime)); if(transform.localPosition.x <= -50){ Vector3 newPosition = new Vector3(32.9f, transform.position.y); transform.position = newPosition; } } } } <file_sep>/Assets/scripts/floatingRock.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class floatingRock : moveObject { [SerializeField] private Vector3 topPosition; [SerializeField] private Vector3 bottomPosition; [SerializeField] private int floatingSpeed = 3; // Use this for initialization void Start () { topPosition = new Vector3(transform.localPosition.x, 16.0f); bottomPosition = new Vector3(transform.localPosition.x, 9.0f); StartCoroutine (Move(bottomPosition)); } // Update is called once per frame void Update () { if(gameManager.instance.isPlayerActive()){ base.moveObjectLeft(); } } IEnumerator Move(Vector3 target){ while(Mathf.Abs((target - transform.localPosition).y) > 0.2f){ Vector3 direction = target.y == topPosition.y ? Vector3.up : Vector3.down; transform.localPosition += direction * (floatingSpeed * Time.deltaTime); yield return null; } yield return new WaitForSeconds(0.5f); Vector3 newTarget = target.y == topPosition.y ? bottomPosition : topPosition; StartCoroutine (Move(newTarget)); } }
3b7115fbf5ddcedd1bde9ba65fe54c198b78a799
[ "C#" ]
4
C#
zygisn/game-development
8c9528deb32ad45209e4c5887529427f2e17daca
2ce0d87ad55691119962cad1f7954b662ff331ab
refs/heads/master
<repo_name>brunoportes/rtage<file_sep>/web_crawler/document_formats_crawler.py import requests def crawler(homepage): dataset_list = requests.get(homepage+'api/action/package_list').json() datasetpage = homepage+'dataset/' format_dict = {} count = 1 #with open('format_dict.txt', 'a') as file: for dataset in dataset_list.get('result'): print(count, datasetpage+dataset) #if dataset != 'compras-publicas-do-governo-federal': sobre_dataset = requests.get(homepage+f'api/3/action/package_show?id={dataset}').json() for format in sobre_dataset.get('result')['resources']: if format.get('format') in format_dict: # append the new number to the existing array at this slot format_dict[format.get('format')] = format_dict[format.get('format')] + 1 else: format_dict[format.get('format')] = 1 count += 1 return(format_dict) def main(): homepage = input('Enter the Open Data Portal index page: Ex: https://www.datos.gov.py/') formats = crawler(homepage) print(formats) if __name__ == "__main__": main() <file_sep>/web_crawler/automatic_load.py import requests import ckanapi import os # Dataset origin from_ckan = input('Digite o nome/IP da máquina de origem (Ex: http://dados.contraosagrotoxicos.org/): ')#The homepage URL where data will #'http://dados.contraosagrotoxicos.org/' nome = input('Digite o nome/IP da máquina de destino: (Ex: http://dados.clone.org/)') # Dataset destination to_ckan = 'http://'+nome #The homepage URL where data will be load (Ex: http://meuportalckan.com.br/) apikey = input('Digite a chave da API: ') #'<KEY>' #The CKAN Portal API Key (Generated for CKAN Admin profile) ckan = ckanapi.RemoteCKAN(to_ckan, apikey=apikey) #from_ckan = 'http://dados.gov.br/' #The homepage URL where data will be crawled (Ex: http://meuportalckan.com.br/) #Retrieving dataset list pagina = requests.get(from_ckan+'api/action/package_list').json() base = from_ckan+'dataset/' #Creating first Organization try: ckan.action.organization_create(title='Laboratório GRECO', name='labgreco', id='labgreco') except Exception as orgError: print(orgError) pass for dataset in pagina.get('result'):#[:5]: sobre_dataset = requests.get(f'{from_ckan}api/3/action/package_show?id={dataset}').json() print(sobre_dataset) #Creating group for group in sobre_dataset.get('result')['groups']: print(group.get('display_name')) try: ckan.action.group_create(description=group.get('description'), display_name=group.get('display_name'), id=group.get('id'), image_display_url=group.get('image_display_url'), name=group.get('name'), title=group.get('title')) print(str(group.get('display_name'))+'. New group registered.') except Exception as cadastrado: print(str(group.get('display_name'))+'. This group was already registered.') pass #Creating organization try: ckan.action.organization_create( description=sobre_dataset.get('result')['organization'].get('description'), id=sobre_dataset.get('result')['organization'].get('id'), name=sobre_dataset.get('result')['organization'].get('name'), title=sobre_dataset.get('result')['organization'].get('title')) print(str(sobre_dataset.get('result')['organization'].get('title'))+'. Registered.') except Exception as cadastrado: try: print(str(sobre_dataset.get('result')['organization'].get('title'))+'. This organization was already registered.') except Exception as nulo: print('Organization is Null.') pass #Creating packages(datasets) print(base+dataset) try: ckan.action.package_create( author=sobre_dataset.get('result')['author'], groups=sobre_dataset.get('result')['groups'], id=sobre_dataset.get('result')['id'], isopen=True, license_id=sobre_dataset.get('result')['license_id'], license_title=sobre_dataset.get('result')['license_title'], name=sobre_dataset.get('result')['name'], notes=sobre_dataset.get('result')['notes'], num_tags=sobre_dataset.get('result')['num_tags'], tags=sobre_dataset.get('result')['tags'], organization=sobre_dataset.get('result')['organization'], #owner_org= sobre_dataset.get('result')['owner_org'] or "labgreco", owner_org= sobre_dataset.get('result')['owner_org'], title=sobre_dataset.get('result')['title'] ) except Exception as packageErro: print('Dataset already registered.') pass # Uploading resources (distributions / documents) for loop in range(len(sobre_dataset.get('result')['resources'])): url = sobre_dataset.get('result')['resources'][loop].get('url') extensao = os.path.splitext(url)[1][1:].lower() if extensao == '': extensao = 'html' package_id = sobre_dataset.get('result')['id'] resource_id = sobre_dataset.get('result')['resources'][loop].get('id') subpagina = f'{to_ckan}dataset/{package_id}/resource/{resource_id}.{extensao}' download = requests.get(url, allow_redirects=True) open(f'dataset/{resource_id}.{extensao}', 'wb').write(download.content) if extensao == 'html': try: ckan.action.resource_create( package_id = package_id, name = sobre_dataset.get('result')['resources'][loop].get('name'), format = sobre_dataset.get('result')['resources'][loop].get('format'), description = sobre_dataset.get('result')['resources'][loop].get('description'), url = url ) except Exception as packageErro: print('Resource already registered.') pass else: try: ckan.action.resource_create( package_id = package_id, name = sobre_dataset.get('result')['resources'][loop].get('name'), format = sobre_dataset.get('result')['resources'][loop].get('format'), description = sobre_dataset.get('result')['resources'][loop].get('description'), #url = to_ckan+'dataset/'+package_id+'/resource/'+resource_id+'.'+extensao, upload= open(f'dataset/{resource_id}.{extensao}','rb') ) except Exception as packageErro: print('Resource already registered.') pass #Deleting reource file file = resource_id+'.'+extensao try: os.remove(os.path.join('dataset/', file)) except: print('File can not be delete') <file_sep>/RTagE_v4.py import requests from winmagic import magic import PyPDF2 import re import textdistance import time import xlrd from nltk.corpus import stopwords from bs4 import BeautifulSoup from textblob import TextBlob from nltk.probability import FreqDist import unicodedata ################################################################ ###################### Uma funcao para cada formato ################################################################ def padrao_utf8(frase): texto_limpo = unicodedata.normalize('NFKD', frase) return str.lower(u"".join([c for c in texto_limpo if not unicodedata.combining(c)])) def get_pdf(): texto = [] try: leitor = PyPDF2.PdfFileReader(open('Dataset/dataset', 'rb')) try: for pagina in range(leitor.numPages): documento = leitor.getPage(pagina) documento = documento.extractText() texto.append(documento) except: print("PDF Codigficado") except: print("File type not PDF!") return(texto) #a def get_csv(): texto = [] try: #chardet.detect('dataset') encoding = (re.search(r'([^\s]+)',(magic.from_file("Dataset/dataset", mime=False))).group(0)).lower() if encoding == 'iso-8859': encoding = 'latin-1' for linha in open('Dataset/dataset', encoding=encoding).readlines(): leitor = (str(linha).strip().split(';')) for palavra in leitor: #texto.append(padrao_utf8(palavra)) texto.append(palavra) except: print("File type not CSV!") return(texto) def get_html(): texto=[] try: leitor = BeautifulSoup(open('Dataset/dataset', 'rb'),"html.parser") paragrafos = leitor.find_all('p') for frase in paragrafos: texto.append(str([re.sub(r'<.+?>',r'',str(a)) for a in frase])) except: print("File type not HTML!") return(texto) def get_xls(): texto=[] try: encoding = (re.search(r'([^\s]+)',(magic.from_file("Dataset/dataset", mime=False))).group(0)).lower() book = xlrd.open_workbook("Dataset/dataset",encoding_override=encoding) for sheet in range(book.nsheets): sh = book.sheet_by_index(sheet) for rx in range(sh.nrows): for cell in sh.row_values(rx): texto.append(str(cell)) except: print("File type not XLS or XLSX!") return(texto) # ============================================================================= # Stem # ============================================================================= #Funcao para extrair o radical das palavras def radical(lista): from nltk.stem.snowball import SnowballStemmer radical = [] stemmer = SnowballStemmer("portuguese") for palavra in lista: radical.append(stemmer.stem(palavra)) return(radical) ################################################################ ###################### API do Ckan ################################################################ pagina = requests.get('http://35.184.224.70/api/action/package_list').json() base = 'http://35.184.224.70/dataset/' acumulado = {} for dataset in pagina.get('result'): print(base+dataset) sobre_dataset = requests.get(f'http://35.184.224.70/api/3/action/package_show?id={dataset}').json() for loop in range(len(sobre_dataset.get('result')['resources'])): #print(sobre_dataset.get('result')['resources'][loop].get('url')) url = sobre_dataset.get('result')['resources'][loop].get('url') download = requests.get(url, allow_redirects=True) open('Dataset/dataset', 'wb').write(download.content) if sobre_dataset.get('result')['resources'][loop].get('url')[-4:] == '.pdf': coleta = get_pdf() elif sobre_dataset.get('result')['resources'][loop].get('url')[-4:] == '.csv': coleta = get_csv() elif sobre_dataset.get('result')['resources'][loop].get('url')[-4:] == '.xls' or sobre_dataset.get('result')['resources'][loop].get('url')[-4:] == 'xlsx': coleta = get_xls() else: coleta = get_html() if coleta != '': if base+dataset in acumulado: # append the new number to the existing array at this slot acumulado[base+dataset].append(coleta) else: acumulado[base+dataset] = coleta # ============================================================================= # Limpando o texto (matem acentuacao) # ============================================================================= #from translate import Translator # translator= Translator(from_lang="portuguese",to_lang="english") # translation = translator.translate("Insecto") # print translation #corpus_completo = [] corpus_stem = {} #translator = Translator() for key, value in acumulado.items(): token = (' '.join(re.findall(r'(\b[A-Za-zÀ-ÿ]{3,20}\b)', str(value).lower().replace("\\n",' ')))).split() if token != []: vinte = ' '.join(token[:20]) blob = TextBlob(vinte) if blob.detect_language() != 'pt': token = (str(blob.translate(to="pt"))).split() clean = [word for word in token if word not in stopwords.words('portuguese')] #corpus_completo.append(clean) if key in corpus_stem: # append the new number to the existing array at this slot corpus_stem[key].append(radical(clean)) else: corpus_stem[key] = radical(clean) #corpus_stem.append(radical(clean)) # ============================================================================= # TF-IDF # ============================================================================= corpus = corpus_stem.copy() soma = 0 ##### soma = 3.444.365 for i in corpus_stem.values(): #print(i) for x in i: soma += len(x) wordSet = set().union(*corpus.values()) #len(wordSet) # 22.340 wordSet = set().union(*corpus.values()) #len(wordSet) # 22.340 newDict = {} for key in corpus.keys(): newDict[key] = dict.fromkeys(wordSet, 0) #newDict[key]['minist'] for i in newDict.keys(): for word in corpus[i]: newDict[i][word]+=1 #len(newDict.get(i)) # TF def computeTF(wordDict, bow): try: tfDict = {} bowCount = len(bow) for word, count in wordDict.items(): tfDict[word] = count/float(bowCount) except: print('Error') return tfDict def computeIDF(docList): import math idfDict = {} N = len(docList) idfDict = dict.fromkeys(docList[0].keys(), 0) for doc in docList: for word, val in doc.items(): if val > 0: idfDict[word] += 1 for word, val in idfDict.items(): idfDict[word] = math.log10(N / float(val)) return idfDict tfidf = {} for i in newDict.keys(): tfidf[i] = computeTF(newDict.get(i), corpus.get(i)) count = 0 for key in tfidf.keys(): print(key) fdist = FreqDist(tfidf.get(key)) for word in fdist: if fdist[word] > 0.009: print(word, round(fdist[word],3)) count += 1 # ============================================================================= # Top keywords # ============================================================================= count = 1 with open('tags_versao_4.rdf','a') as rdf: rdf.write('''<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcat="http://www.w3.org/ns/dcat#" xmlns:dct="http://purl.org/dc/terms/" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#">''') pagina = requests.get('http://192.168.3.11/api/action/package_list').json() base = 'http://192.168.3.11/dataset/' for dataset, key in zip(pagina.get('result'), tfidf.keys()): sobre_dataset = requests.get(f'http://3172.16.58.3/api/3/action/package_show?id={dataset}').json() name_dataset = padrao_utf8(sobre_dataset.get('result')['title']) description = padrao_utf8(sobre_dataset.get('result')['notes'])[:600] print(base+dataset) dataset_url = base+dataset rdf.write(f''' <dcat:Dataset rdf:about="{dataset_url}"> <dct:title>{name_dataset}</dct:title> <dct:description>{description}</dct:description>''') fdist = FreqDist(tfidf.get(key)) for word in fdist: if fdist[word] > 0.009: #print(word, round(fdist[word],3)) coleta = requests.get(f'http://agrovoc.uniroma2.it/agrovoc/rest/v1/search/?query={word}*&lang=pt',timeout=10).json() #time.sleep(5) if coleta.get('results') != []: total = {} label = {} for linha in range(len(coleta.get('results'))): #print(linha) total[coleta.get('results')[linha].get('uri')] = textdistance.jaro_winkler(word,coleta.get('results')[linha].get('prefLabel')) label[coleta.get('results')[linha].get('uri')] = coleta.get('results')[linha].get('prefLabel') top = FreqDist(total) top1 = (top.most_common(1)[0][0]) print(word, label[top1], top.most_common(1)[0][0], top.most_common(1)[0][1]) rdf.write(f''' <dcat:keyword rdf:resource="{top1}"></dcat:keyword>''') for resource in sobre_dataset.get('result')['resources']: resource_url = padrao_utf8(resource.get('url')) resource_name = padrao_utf8(resource.get('name')) resource_desc = padrao_utf8(resource.get('description')) resource_format = padrao_utf8(resource.get('format')) rdf.write(f''' <dcat:distribution> <dcat:Distribution rdf:about="{resource_url}"> <dct:title>{resource_name}</dct:title> <dct:description>{resource_desc}</dct:description> <dct:format>{resource_format}</dct:format> </dcat:Distribution> </dcat:distribution>''') time.sleep(5) print(count) count += 1 rdf.write(f''' </dcat:Dataset>''') rdf.write(f''' </rdf:RDF> ''')
fe73aa1737d80615aa588548afbf7db3a9b8cf32
[ "Python" ]
3
Python
brunoportes/rtage
d0d6ea5d807fe5d2b162c0da4840894ff33bcad3
dd46a732f1ed81ce7f10cfb25533cb236aed07a4
refs/heads/main
<repo_name>DevNoobGames/zombiemanager<file_sep>/Assets/Scripts/Managers/GameManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class GameManager : MonoBehaviour { public int level = 1; public GameObject introText; public GameObject introBlackPanel; public List<GameObject> enemies = new List<GameObject>(); public List<GameObject> zombies = new List<GameObject>(); public GameObject[] UI; public List<GameObject> PlacementAreas = new List<GameObject>(); public List<levels> levelList = new List<levels>(); public GameObject EndGamePanel; public TextMeshProUGUI EndGameText; public PlayerManager playman; public GameObject introFolder; [System.Serializable] public class levels { public int level; public int amountOfZombies; public GameObject[] TypeOfZombies; } public void Start() { StartCoroutine("nextLevel", 1); //Clear out the areas foreach (GameObject placementArea in GameObject.FindGameObjectsWithTag("placementArea")) { PlacementAreas.Add(placementArea); } foreach (GameObject pa in PlacementAreas) { pa.GetComponent<MeshRenderer>().enabled = false; } } IEnumerator nextLevel(int level) { if (level == 21) { EndGamePanel.SetActive(true); EndGameText.text = "Congrats! Game finished with" + "\n" + "$" + playman.money; } else { introText.SetActive(true); introBlackPanel.SetActive(true); foreach (GameObject ui in UI) { ui.SetActive(false); } introText.GetComponent<TextMeshProUGUI>().text = "Level" + "\n" + "-" + level + "-"; introText.GetComponent<Animation>().Play(); introBlackPanel.GetComponent<Animation>().Play(); yield return new WaitForSeconds(3); foreach (GameObject zom in zombies) { Destroy(zom); } foreach (GameObject ui in UI) { ui.SetActive(true); } introText.SetActive(false); //After the intro is finished, place the enemies EnemyPlacement(level); if (level == 1) { introFolder.SetActive(true); } //also close blackpanel yield return new WaitForSeconds(0.5f); introBlackPanel.SetActive(false); } } public void EnemyPlacement(int level) { //Clean up the list PlacementAreas.Clear(); //Add all the areas again foreach (GameObject placementArea in GameObject.FindGameObjectsWithTag("placementArea")) { PlacementAreas.Add(placementArea); } foreach (levels lvl in levelList) { if (lvl.level == level) { for (int i = 0; i < lvl.amountOfZombies; i++) { int randInt = Random.Range(0, PlacementAreas.Count); //Find placement area - last one is Exclusive so will never b called int randZom = Random.Range(0, lvl.TypeOfZombies.Length); //Find which zombie to place GameObject enemyy = Instantiate(lvl.TypeOfZombies[randZom], PlacementAreas[randInt].transform.position, Quaternion.identity) as GameObject; enemies.Add(enemyy); enemyy.GetComponent<EnemyAI>().gameMan = this.GetComponent<GameManager>(); PlacementAreas.RemoveAt(randInt); if (PlacementAreas.Count == 0) //if we run out of placement areas { return; } } return; //return so it doesn't go through all the other levels } } } public void checkEnemiesLeft() { if (enemies.Count <= 0) { //start next level level += 1; StartCoroutine("nextLevel", level); } } } <file_sep>/Assets/Scripts/Testing/FleeUnit.cs using System.Collections; using System.Collections.Generic; using UnityEngine; namespace UnityMovementAI { public class FleeUnit : MonoBehaviour { public Transform target; SteeringBasics steeringBasics; Flee flee; private void Start() { steeringBasics = GetComponent<SteeringBasics>(); flee = GetComponent<Flee>(); } public void stop() { steeringBasics.maxVelocity = 0; Vector3 accel = flee.GetSteering(transform.position); steeringBasics.Steer(accel); } private void FixedUpdate() { if (target) { steeringBasics.maxVelocity = 3.5f; Vector3 accel = flee.GetSteering(target.position); steeringBasics.Steer(accel); steeringBasics.LookWhereYoureGoing(); } } } }<file_sep>/Assets/Scripts/Enemy/RunningDistance.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class RunningDistance : MonoBehaviour { public EnemyAI parentAI; public List<GameObject> inCircle = new List<GameObject>(); /*private void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Zombie")) { inCircle.Add(other.gameObject); parentAI.fleeunit.target = other.gameObject.transform; parentAI.fleeunit.enabled = true; parentAI.isFleeing = true; parentAI.agent.enabled = false; } } private void OnTriggerExit(Collider other) { if (other.gameObject.CompareTag("Zombie")) { inCircle.Remove(other.gameObject); } }*/ } <file_sep>/Assets/Scripts/Zombies/ZombieDragger.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ZombieDragger : MonoBehaviour { public bool inPlacementArea = false; public float cost; public Material green; public Material red; public PlayerManager playerManager; public float AmountOfZombies; public GameObject zombieToDrop; public AudioSource releaseSound; public GameManager gameMan; private void Start() { playerManager = GameObject.FindGameObjectWithTag("PlayerManager").GetComponent<PlayerManager>(); gameMan = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>(); releaseSound = GameObject.FindGameObjectWithTag("soundClick").GetComponent<AudioSource>(); } void Update() { followMouse(); if (Input.GetMouseButtonUp(0)) { if (inPlacementArea && playerManager.money >= cost) { for (int i = 0; i < AmountOfZombies; i++) { Instantiate(zombieToDrop, transform.position, Quaternion.identity); } releaseSound.Play(); playerManager.ChangeMoney(-cost); gameMan.introFolder.SetActive(false); Destroy(gameObject); } else { Destroy(gameObject); } } } void followMouse() { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit)) { float Y = (Mathf.RoundToInt(hit.point.y) + 1f); transform.position = new Vector3(hit.point.x, Y, hit.point.z); transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal); } } private void OnTriggerStay(Collider other) { if (other.CompareTag("GroundPlacement")) { if (playerManager.money >= cost) { inPlacementArea = true; GetComponent<Renderer>().material = green; } else { inPlacementArea = false; GetComponent<Renderer>().material = red; } } } private void OnTriggerExit(Collider other) { if (other.CompareTag("GroundPlacement")) { inPlacementArea = false; GetComponent<Renderer>().material = red; } } } <file_sep>/Assets/Scripts/Random/TreePositioning.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class TreePositioning : MonoBehaviour { private void Start() { transform.rotation = Quaternion.Euler(new Vector3(00, Random.Range(0, 360), 0)); transform.position = new Vector3(transform.position.x, Random.Range(-3f, 0.36f), transform.position.z); } } <file_sep>/Assets/Scripts/Enemy/EnemyAI.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class EnemyAI : MonoBehaviour { [Header("Settings")] public float MoneyReward = 100; PlayerManager playerMan; public GameManager gameMan; //is refered to when instantiaing in the gamemanager script public float Yfix = 0; public GameObject cam; [Header("Shooting")] public float reloadTime = 1; public float damage = 10; bool isReloaded = true; public Transform lineOrigin; [Header("Random")] public LineRenderer lineRender; public GameObject zombieTarget; public float health = 100; public ParticleSystem gunEffect; public AudioSource shotSound; public GameObject rewardText; void Start() { playerMan = GameObject.Find("PlayerManager").GetComponent<PlayerManager>(); float randVal = Random.Range(1.5f, 2.1f); InvokeRepeating("targetFinder", randVal, randVal); lineRender.SetPosition(0, lineOrigin.position); transform.position = new Vector3(transform.position.x, transform.position.y + Yfix, transform.position.z); } private void Update() { if (zombieTarget) { cam.transform.LookAt(zombieTarget.transform); /*Quaternion OriginalRot = transform.rotation; transform.LookAt(zombieTarget.transform); Quaternion NewRot = transform.rotation; transform.rotation = OriginalRot; transform.rotation = Quaternion.Lerp(transform.rotation, NewRot, 1 * Time.deltaTime);*/ lineRender.SetPosition(0, lineOrigin.position); lineRender.SetPosition(1, zombieTarget.transform.position); Vector3 targetPostition = new Vector3(zombieTarget.transform.position.x, this.transform.position.y, zombieTarget.transform.position.z); this.transform.LookAt(targetPostition); if (isReloaded) { isReloaded = false; gunEffect.Play(); shotSound.Play(); StartCoroutine(reloadCour()); zombieTarget.GetComponent<ZombieAI>().gotHit(damage); } } else { lineRender.SetPosition(1, transform.position); } } public void gotHit(float damage) { health -= damage; if (health <= 0) { GameObject reward = Instantiate(rewardText, transform.position, Quaternion.identity); reward.transform.rotation = Camera.main.transform.rotation; reward.GetComponent<TextMeshPro>().text = "$" + MoneyReward; playerMan.ChangeMoney(MoneyReward); foreach (GameObject thisobj in gameMan.enemies) { if (thisobj == gameObject) { gameMan.enemies.Remove(thisobj); gameMan.checkEnemiesLeft(); if (cam.activeInHierarchy) { GameObject.FindGameObjectWithTag("CameraManager").GetComponent<CameraManager>().mainCamSel(); } Destroy(gameObject); return; } } //if can't be found for some weird reason gameMan.checkEnemiesLeft(); Destroy(gameObject); } } public void targetFinder() { zombieTarget = nearestZombie(); } IEnumerator reloadCour() { yield return new WaitForSeconds(reloadTime); isReloaded = true; } public GameObject nearestZombie() { GameObject[] gos; gos = GameObject.FindGameObjectsWithTag("Zombie"); GameObject closest = null; float distance = Mathf.Infinity; Vector3 position = transform.position; foreach (GameObject go in gos) { RaycastHit hit; if (Physics.Raycast(transform.position, (go.transform.position - transform.position), out hit)) { if (hit.transform == go.transform) { Vector3 diff = go.transform.position - position; float curDistance = diff.sqrMagnitude; if (curDistance < distance) { closest = go; distance = curDistance; } } } } return closest; } } //Deleted the fleeing. Too much hassle /*public NavMeshAgent agent; public Vector3 startPos; public bool isFleeing; public UnityMovementAI.FleeUnit fleeunit; public UnityMovementAI.SteeringBasics steeringbasics; public RunningDistance runningdistanceRef; */ //START FUNCTION //startPos = transform.position; //fleeunit = GetComponent<UnityMovementAI.FleeUnit>(); //agent = GetComponent<NavMeshAgent>(); //UPDATE FUNCTION /*if (isFleeing && runningdistanceRef.inCircle.Count == 0) { fleeunit.stop(); fleeunit.enabled = false; isFleeing = false; agent.enabled = true; agent.SetDestination(startPos); }*/<file_sep>/Assets/Scripts/Menu/ZombieCreator.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using TMPro; public class ZombieCreator : MonoBehaviour, IPointerDownHandler { public GameObject zombieDragger; public GameObject zombieToDrop; public float Basecost; public float Cost; public string Name; public TextMeshProUGUI infoText; public PlayerManager playerManager; private void Start() { playerManager = GameObject.FindGameObjectWithTag("PlayerManager").GetComponent<PlayerManager>(); infoText.text = "$" + Cost; } public void OnPointerDown(PointerEventData eventData) { if (playerManager.money >= Cost) { GameObject zombieDrag = Instantiate(zombieDragger, new Vector3(0, 0, 0), Quaternion.identity); zombieDrag.GetComponent<ZombieDragger>().cost = Cost; zombieDrag.GetComponent<ZombieDragger>().AmountOfZombies = (Cost / Basecost); //a simple way to decide how many zombies to place zombieDrag.GetComponent<ZombieDragger>().zombieToDrop = zombieToDrop; } } } <file_sep>/Assets/Scripts/Zombies/ZombieAI.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class ZombieAI : MonoBehaviour { public NavMeshAgent agent; public GameObject target; float lowestDistance; public float health = 100; public List<Targets> targetlist = new List<Targets>(); float startSpeed; [Header("Attack")] public float range; bool isReloaded = true; public float reloadTime = 1; public float damage = 10; [System.Serializable] public class Targets { public GameObject target; public float length; } void Start() { agent = GetComponent<NavMeshAgent>(); startSpeed = agent.speed; //targetchecker(); InvokeRepeating("targetcheckersimple", 0, 2); //check closest target every 2 sec if (GameObject.FindGameObjectWithTag("GameManager")) { GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>().zombies.Add(gameObject); } } void Update() { if (target) { Vector3 targetPostition = new Vector3(target.transform.position.x, this.transform.position.y, target.transform.position.z); this.transform.LookAt(targetPostition); if (Vector3.Distance(target.transform.position, transform.position) < range) //if within range { agent.speed = 0; if (isReloaded) { isReloaded = false; StartCoroutine(reloadCour()); target.transform.SendMessage("gotHit", damage, SendMessageOptions.DontRequireReceiver); //inflict damage } } else { agent.speed = startSpeed; } } } IEnumerator reloadCour() { yield return new WaitForSeconds(reloadTime); isReloaded = true; } void targetcheckersimple() { lowestDistance = 99999999; foreach (GameObject trg in GameObject.FindGameObjectsWithTag("Enemy")) { float dist = Vector3.Distance(transform.position, trg.transform.position); if (dist <= lowestDistance) { lowestDistance = dist; target = trg; //so it looks at its target agent.SetDestination(trg.transform.position); } } } public void gotHit(float damage) { health -= damage; if (health <= 0) { Destroy(gameObject); } } } /* void targetchecker() { foreach (GameObject trg in GameObject.FindGameObjectsWithTag("Enemy")) { Targets t = new Targets(); t.target = trg; t.length = checkDist(trg); targetlist.Add(t); } } //Function not working? public float checkDist(GameObject trg) { agent.SetDestination(trg.transform.position); if (agent.CalculatePath(trg.transform.position, new NavMeshPath())) //check path { if (agent.pathStatus == NavMeshPathStatus.PathComplete) //can reach path? { return agent.remainingDistance; } } return 0; } */<file_sep>/Assets/Scripts/Random/CameraScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraScript : MonoBehaviour { public float speed; public int activePos; public Vector3[] position; private Vector3 currentAngle; public Vector3[] targetAngle; private void Update() { transform.position = Vector3.Lerp(transform.position, position[activePos], Time.deltaTime * speed); transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(targetAngle[activePos].x, targetAngle[activePos].y, transform.rotation.z), Time.deltaTime * speed); if (Input.GetKeyDown(KeyCode.E)) { if (activePos == 0) { activePos = (position.Length - 1); } else { activePos--; } } if (Input.GetKeyDown(KeyCode.Q)) { if (activePos == (position.Length - 1)) { activePos = 0; } else { activePos++; } } } } <file_sep>/Assets/Scripts/Random/CameraMover.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraMover : MonoBehaviour { public float moveSpeed; public float scrollSpeed; public float MaxUp; public float MaxDown; public float minDistance; public float maxDistance; public Camera cam; // Update is called once per frame void Update() { if (Input.GetKey(KeyCode.A)) { transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y + moveSpeed, transform.eulerAngles.z); } if (Input.GetKey(KeyCode.D)) { transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y - moveSpeed, transform.eulerAngles.z); } if (Input.GetKey(KeyCode.W)) { if (transform.eulerAngles.x <= MaxUp) { transform.eulerAngles = new Vector3(transform.eulerAngles.x + moveSpeed, transform.eulerAngles.y, transform.eulerAngles.z ); } } if (Input.GetKey(KeyCode.S)) { if (transform.eulerAngles.x >= MaxDown) { transform.eulerAngles = new Vector3(transform.eulerAngles.x - moveSpeed, transform.eulerAngles.y, transform.eulerAngles.z); } } if (Input.GetAxis("Mouse ScrollWheel") > 0f) //zoom in { if (Vector3.Distance(Camera.main.transform.position, this.transform.position) > minDistance) { Camera.main.transform.position = Vector3.MoveTowards(Camera.main.transform.position, this.transform.position, (scrollSpeed)); } } if (Input.GetAxis("Mouse ScrollWheel") < 0f) //zoom out { if (Vector3.Distance(Camera.main.transform.position, this.transform.position) < maxDistance) { Camera.main.transform.position = Vector3.MoveTowards(Camera.main.transform.position, this.transform.position, (-scrollSpeed)); } } } } <file_sep>/Assets/Scripts/Managers/CanvasManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class CanvasManager : MonoBehaviour { public List<int> amount = new List<int>(); public ZombieCreator[] ZombieCreators; public int activeAmount; public TextMeshProUGUI AmountText; public AudioSource clickSound; public GameObject pauseMenu; private void Start() { AmountText.text = amount[activeAmount].ToString(); } private void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { if (!pauseMenu.activeInHierarchy) { pauseMenu.SetActive(true); } else { pauseMenu.SetActive(false); } } } public void quitTheGame() { Application.Quit(); } public void continuetheGame() { pauseMenu.SetActive(false); } public void nextAmount() { if (activeAmount < (amount.Count- 1)) { activeAmount += 1; } else { activeAmount = 0; } AmountText.text = amount[activeAmount].ToString(); foreach (ZombieCreator zom in ZombieCreators) { zom.Cost = zom.Basecost * amount[activeAmount]; zom.infoText.text = "$" + zom.Cost; //Before it was zom.Name + "\n" + "$" + zom.Cost; } clickSound.Play(); } } <file_sep>/Assets/Scripts/Testing/OutlineColor.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class OutlineColor : MonoBehaviour { public Renderer rendCol; private void Start() { StartCoroutine(changeColor()); //rendCol.material.SetColor("_OutlineColor", new Color32(244,3,12,255)); } IEnumerator changeColor() { rendCol.material.SetColor("_OutlineColor", new Color32(0, 128, 0, 255)); //Green yield return new WaitForSeconds(0.2f); rendCol.material.SetColor("_OutlineColor", new Color32(191, 64, 191, 255)); //purple yield return new WaitForSeconds(0.2f); StartCoroutine(changeColor()); } } <file_sep>/Assets/Scripts/Managers/CameraManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraManager : MonoBehaviour { public GameObject mainCam; public GameObject[] nextCam; public GameManager gameMan; public int active = 0; public void DisableAllCams() { mainCam.SetActive(false); foreach (GameObject cam in nextCam) { cam.SetActive(false); } foreach (GameObject enCam in gameMan.enemies) { enCam.GetComponent<EnemyAI>().cam.SetActive(false); } } public void mainCamSel() { DisableAllCams(); mainCam.SetActive(true); } public void nextCamSel() { DisableAllCams(); if (nextCam.Length == (active + 1)) { active = 0; } else { active += 1; } nextCam[active].SetActive(true); } public void enemyCam() { if (gameMan.enemies.Count > 0) { DisableAllCams(); int randEne = Random.Range(0, gameMan.enemies.Count); gameMan.enemies[randEne].GetComponent<EnemyAI>().cam.SetActive(true); } } } <file_sep>/Assets/Scripts/Managers/PlayerManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class PlayerManager : MonoBehaviour { public float money = 1000; public TextMeshProUGUI moneyText; private void Start() { moneyText.text = "$" + money.ToString(); } public void ChangeMoney(float change) { money += change; moneyText.text = "$" + money.ToString(); } }
3ab098207225a275b2158e8b7d64c0ef610d1de8
[ "C#" ]
14
C#
DevNoobGames/zombiemanager
7362eff1fbd78d36d9ac8716b2d601a1c0e529fd
7e2c00b961bd94ac08e904c969f6d1dbec3d0725
refs/heads/master
<file_sep> var express = require('express'); var fs = require('fs'); var Usuario = require('../models/usuario'); var Medico = require('../models/medico'); var Hospital = require('../models/hospital'); var app = express(); var fileUpload = require('express-fileupload'); // default options app.use(fileUpload()); app.put('/:tipo/:id', ( req, resp, next ) => { var tipo = req.params.tipo; var id = req.params.id; var coleccionesValidas = ['usuarios', 'hospitales', 'medicos']; if( coleccionesValidas.indexOf( tipo ) < 0 ) { return resp.status(400).json({ ok: false, message: 'Debe indicar una colección válida', errors: {message: 'Colecciones permitidas: ' + coleccionesValidas.join(', ')} }); } if( !req.files ) { return resp.status(400).json({ ok: false, message: 'No hay archicos seleccionados', errors: {message: 'Debe seleccionar una imagen'} }); } // obtener nombre del archivo var archivo = req.files.imagen; var nombrePartido = archivo.name.split('.'); var extension = nombrePartido[nombrePartido.length - 1]; // extensiones permitidas var extensionesPermitidas = ['png', 'gif', 'jpeg', 'jpg']; if (extensionesPermitidas.indexOf(extension) < 0) { return resp.status(400).json({ ok: false, message: 'Extensión no válida', errors: {message: 'Las extensiones permitidas son: ' + extensionesPermitidas.join(', ')} }); } // definir nombre de archivo var nombreArchivo = `${ id }-${ new Date().getMilliseconds() }.${ extension }`; // definir path var path = `./uploads/${ tipo }/${ nombreArchivo }`; archivo.mv(path, error => { if (error) { return resp.status(500).json({ ok: false, message: 'Error al mover el archivo', errors: error }); } subirPorTipo(tipo, id, nombreArchivo, resp); }); }); function subirPorTipo( tipo, id, nombreArchivo, resp ) { switch( tipo ) { case 'usuarios': Usuario.findById(id, (error, usuario) => { if(!usuario) { return resp.status(400).json({ ok: false, message: 'Usuario no existe', errors: {message: 'Usuario no encontrado'} }); } var oldPath = `./uploads/usuarios/${ usuario.img }`; // si existe imagen se elimina if( fs.existsSync(oldPath) ) { fs.unlinkSync(oldPath); } usuario.img = nombreArchivo; usuario.save((err, usuarioUpd) => { if( err ) { return resp.status(500).json({ ok: false, message: 'Error al actualizar el archivo en usuarios', errors: error }); } usuarioUpd.password = ':)'; return resp.status(200).json({ ok: true, message: 'Imagen de usuario actualizada', usuario: usuarioUpd }); }); }); break; case 'hospitales': Hospital.findById(id, (error, hospital) => { if(!hospital) { return resp.status(400).json({ ok: false, message: 'Hospital no existe', errors: {message: 'Hospital no encontrado'} }); } var oldPath = `./uploads/hospitales/${ hospital.img }`; // si existe imagen se elimina if( fs.existsSync(oldPath) ) { fs.unlinkSync(oldPath); } hospital.img = nombreArchivo; hospital.save((err, hospitalUpd) => { if( err ) { return resp.status(500).json({ ok: false, message: 'Error al actualizar el archivo en hospitales', errors: error }); } return resp.status(200).json({ ok: true, message: 'Imagen de hospital actualizada', hospital: hospitalUpd }); }); }); break; case 'medicos': Medico.findById(id, (error, medico) => { if(!medico) { return resp.status(400).json({ ok: false, message: 'Médico no existe', errors: {message: 'Médico no encontrado'} }); } var oldPath = `./uploads/medicos/${ medico.img }`; // si existe imagen se elimina if( fs.existsSync(oldPath) ) { fs.unlinkSync(oldPath); } medico.img = nombreArchivo; medico.save((err, medicoUpd) => { if( err ) { return resp.status(500).json({ ok: false, message: 'Error al actualizar el archivo en médicos', errors: error }); } return resp.status(200).json({ ok: true, message: 'Imagen de médico actualizada', medico: medicoUpd }); }); }); break; } } module.exports = app;<file_sep>var jwt = require('jsonwebtoken'); var SEED = require('../config/config').SEED; // ===================================================== // Revisar token // ===================================================== exports.verifyToken = function(req, resp, next) { var token = req.query.token; jwt.verify(token, SEED, (error, decoded) => { if (error) { return resp.status(401).json({ ok: false, message: 'Token incorrecto!', errors: error }); } req.usuario = decoded.usuario; next(); }); }; // ===================================================== // Revisar ADMIN // ===================================================== exports.verifyADMIN = function(req, resp, next) { var usuario = req.usuario; if (usuario.role === 'ADMIN_ROLE') { next(); return; } else { return resp.status(401).json({ ok: false, message: 'Token incorrecto - No es ADMINISTRADOR', errors: { message: 'No es Administrador, no puede hacer eso' } }); } }; // ===================================================== // Revisar ADMIN o mismo usuario // ===================================================== exports.verifyAdminOMismoUsuario = function(req, resp, next) { var usuario = req.usuario; var id = req.params.id; if (usuario.role === 'ADMIN_ROLE' || usuario._id === id) { next(); return; } else { return resp.status(401).json({ ok: false, message: 'Token incorrecto - No es ADMINISTRADOR', errors: { message: 'No es Administrador, no puede hacer eso' } }); } }; <file_sep> var express = require('express'); var Hospital = require('../models/hospital'); var Medico = require('../models/medico'); var Usuario = require('../models/usuario'); var app = express(); // ============================================== // Búsqueda Específica // ============================================== app.get('/coleccion/:tabla/:busqueda', ( req, resp, next ) => { var tabla = req.params.tabla; var busqueda = req.params.busqueda; var regex = new RegExp(busqueda, 'i'); var promise; switch(tabla) { case 'usuarios': promise = buscarUsuarios(regex); break; case 'hospitales': promise = buscarHospitales(regex); break; case 'medicos': promise = buscarMedicos(regex); break; default: return resp.status(400).json({ ok: false, message: 'Los tipos de búsqueda son usuarios, hospitales y médicos', error: {message: 'Tipo de tabla/coleccion no válido'} }); } promise.then( result => { resp.status(200).json({ ok: true, message: 'Petición realizada correctamente', [tabla]: result }); } ); }); // ============================================== // Búsqueda Completa // ============================================== app.get('/todo/:busqueda', ( req, resp, next ) => { var busqueda = req.params.busqueda; var regex = new RegExp(busqueda, 'i'); Promise.all([ buscarHospitales(regex), buscarMedicos(regex), buscarUsuarios(regex) ]) .then(respuestas => { resp.status(200).json({ ok: true, message: 'Petición realizada correctamente', hospitales: respuestas[0], medicos: respuestas[1], usuarios: respuestas[2] }); }); }); function buscarHospitales( regex ) { return new Promise((resolve, reject) => { Hospital.find({nombre: regex}) .populate('usuario', 'nombre email img') .exec((error, hospitales) => { if(error) { reject('Error al obtener los hospitales', error); } else { resolve(hospitales); } }); }); } function buscarMedicos( regex ) { return new Promise((resolve, reject) => { Medico.find({nombre: regex}) .populate('usuario', 'nombre email img') .populate('hospital') .exec((error, medicos) => { if(error) { reject('Error al obtener los médicos', error); } else { resolve(medicos); } }); }); } function buscarUsuarios( regex ) { return new Promise((resolve, reject) => { Usuario.find({}, 'nombre email role img') .or([{ nombre: regex }, { email: regex }]) .exec((error, usuarios) => { if(error) { reject('Error al obtener usuarios', error); } else { resolve(usuarios); } }); }); } module.exports = app;<file_sep>module.exports.SEED = '@feanor_@Y_@finwe'; // Google module.exports.CLIENT_ID = '938363439474-u6r6r7e05ef984cv120pk4b433cop8rv.apps.googleusercontent.com';
887c14e44a6726bf801642cf162ccfdf68c6fafc
[ "JavaScript" ]
4
JavaScript
sugarnet/backend_server
c8525cb5e6ef71bca47409fe9abfab04e36397b0
ef02ee6dd12e59666df7d704ec672ba807b432f2
refs/heads/master
<file_sep># Birthday Helper # This read in names and birth dates from a text file. It will ask for a name # and the program will display the corresponding birthdate. # Chapter 12.6 Learn to Program by <NAME> # 20131118 Dir.chdir '/Users/jobdelcastillo/Tealeaf_Week1' # The file with the birthdates filename = 'birthday.rtf' # Info store in hashes for simple retrieval birth_dates = {} File.read(filename).each_line do |line| # reads each line of the file line = line.chomp # chomp the end of line # Need to account for comma as the end of the name counter = 0 while line[counter] != ',' && counter < line.length name = line[0..counter] # this gets up to comma as while will end when it encounters comma date = line[-12..-1] # this gets the date (counting from the right) # put this in hash birth_dates[name] = date counter = counter + 1 end end puts 'Whose birthday would you like to know?' name = gets.chomp date = birth_dates[name] if date == nil puts 'Oooh, I don\'t know that one...' else puts date[0..5] # telling the day and month only end <file_sep>#Blackjack using method from lessons # 20131108 def calculate_total(cards) # [['Diamond', '3'], ['Heart', 'Jack'], ...] total = 0 cards.each { |x| case x[1] when 'Jack' total += 10 when 'Queen' total += 10 when 'King' total += 10 when 'Ace' if total < 11 total += 11 else total += 1 end else total += x[1].to_i end } total end suits = %w(Diamond Heart Club Spade) cards = %w(2 3 4 5 6 7 8 9 10 Jack Queen King Ace) deck = suits.product(cards) puts 'Welcome to Blackjack!' # Dealing the cards deck.shuffle! playercards = [] dealercards = [] playercards << deck.pop dealercards << deck.pop playercards << deck.pop #Calculate total player_total = 0 dealer_total = 0 player_total = calculate_total(playercards) puts "Dealer has #{dealercards[0]}" puts "You have #{playercards[0]} and #{playercards[1]} for a total of #{player_total}." #Case for blackjack if player_total == 21 puts 'You hit blackjack!' # Check if dealer also has blackjack dealercards << deck.pop dealer_total = calculate_total(dealercards) puts "Dealer has #{dealercards[0]} and #{dealercards[1]} for a total #{dealer_total}." if dealer_total == 21 puts 'Dealer has blackjack! It\'s a draw!' else puts 'Congratulations! You win!' end exit end #All other cases while player_total < 21 puts 'Do you want to 1 Hit or 2 Stay?' hit_or_stay = gets.chomp if hit_or_stay == '1' newcard = deck.pop puts "Dealing new card for player: #{newcard}" playercards << newcard puts "You have #{playercards}" player_total = calculate_total(playercards) puts "Total #{player_total}" if player_total > 21 puts 'Sorry, you busted! You lost.' exit end elsif hit_or_stay == '2' puts 'You chose to stay.' break else puts 'Invalid choice. Please press 1 for Hit or 2 for Stay.' end end # Dealer's turn dealercards << deck.pop puts "Dealer has #{dealercards[0]} and #{dealercards[1]}" dealer_total = calculate_total(dealercards) puts "Total #{dealer_total}" # Case for dealer's blackjack if dealer_total == 21 && player_total != 21 puts 'Dealer has blackjack! Sorry, you lost.' exit end # All other cases while dealer_total < 17 newcard = deck.pop puts "Dealing new card for dealer: #{newcard}" dealercards << newcard puts "Dealer has #{dealercards}" dealer_total = calculate_total(dealercards) puts "Total #{dealer_total}" end # Comparing total to determine winner if dealer_total > 21 puts 'Dealer busted. Congratulations! You win!' elsif dealer_total == player_total puts 'It\'s a draw!' elsif dealer_total < player_total puts 'Congratulations! You win!' else puts 'Sorry, dealer wins!' end <file_sep># Shuffle extended to Array Class # from Learn to Program by <NAME> Chapter 13.1 # 20131119 words = %w(apple zoology berserk catnip daschund elephant aardvark major nuclear island major) class Array def shuffling arr = self shuffled_array = [] # Generate a random number up to the length of the array, then use that as the index # to move that particular obj in the array to the new array transfer_word = '' while arr.length != 0 # Set index in array to transfer to new array by random number random_number = Random.new random_number = random_number.rand(arr.length) transfer_word = arr[random_number] shuffled_array << transfer_word arr.slice!(arr.index(transfer_word)) # This gets the index of the # transfer_word then the slice! deletes that object at that index - brilliant! end shuffled_array end end puts 'Using the in-built array method "shuffle": ' puts words.shuffle new_words = [] new_words = words.shuffling puts 'Using my own shuffling method: ' puts new_words <file_sep># Playlist - search computer for music files and randomly creates playlist # Chapter 11 Learn to Program by <NAME> # 20131116 # Setting directory where the music files are stored Dir.chdir '/Users/jobdelcastillo/Music/ICE/Classical' # First we find the music for the playlist music_names = Dir['/Users/jobdelcastillo/Music/ICE/Classical/**.mp3'] # Creating the m3u playlist filename = 'music_playlist.m3u' # Array for playlist playlist = [] print "Searching music... found #{music_names.length} music files." # counter = 0 # This gets the music files and append to array playlist music_names.each do |name| # puts name # This is our "progress bar". playlist << File.basename(name) # puts playlist[counter] # counter = counter + 1 end # Saving the contents of array to the actual m3u file File.open(filename, 'a') { |f| playlist.each { |x| f.write x + "\n"} } <file_sep># Class Orange Tree # Chapter 13.6 from Learn to Program by <NAME> # 20131119 class OrangeTree def initialize @tree_height = 0 @tree_age = 0 @orange_count = 0 @picked = false end def height puts "The tree is currently #{@tree_height} metres tall." if @tree_height == 10 puts 'The orange tree has grown to its maximum height.' end end def count_the_oranges puts "The tree has #{@orange_count} oranges." end def pick_an_orange @picked = true if @orange_count == 0 puts 'There is currently no orange fruit in the tree.' else puts 'You have picked an orange. It was delicious!' @orange_count = @orange_count - 1 puts "There are #{@orange_count} left." end end def one_year_passes @tree_age = @tree_age + 1 puts 'One year has passed.' # The tree growing tall: if @tree_height <= 10 @tree_height = @tree_height + 2 end # The tree bearing fruit, the older, the more it bears fruits if @tree_age > 2 @orange_count = @orange_count + 2 end if @tree_age > 3 @orange_count = @orange_count + 2 end if @tree_age > 4 @orange_count = @orange_count + 2 end # if oranges were not picked if !@picked && @orange_count > 0 @orange_count = @orange_count - 1 end # Death of the tree if @tree_age == 7 puts 'The tree has grown too old. It died happy knowing it bore many oranges.' exit end end end orangesaft = OrangeTree.new orangesaft.height orangesaft.count_the_oranges orangesaft.one_year_passes orangesaft.height orangesaft.pick_an_orange orangesaft.count_the_oranges orangesaft.one_year_passes orangesaft.height orangesaft.count_the_oranges orangesaft.one_year_passes orangesaft.one_year_passes orangesaft.pick_an_orange orangesaft.one_year_passes orangesaft.one_year_passes orangesaft.height orangesaft.count_the_oranges orangesaft.one_year_passes orangesaft.one_year_passes orangesaft.one_year_passes orangesaft.one_year_passes<file_sep># Classes - creating classes with its own method and instance variables # from Learn to Program by <NAME> Chapter 13.3 # 20131119 class Die def initialize roll end def roll @number_showing = 1 + rand(6) end def showing @number_showing end def cheat puts 'What number would you like the die to roll?' @number_showing = gets.chomp.to_i if @number_showing > 6 puts 'Error: a die can only roll up to 6' end end end puts Die.new.showing die1 = Die.new puts die1.showing puts die1.roll puts die1.cheat<file_sep>#Variable Scope # 20131107 num1 = gets.chomp num2 = gets.chomp arr = [1,2,3] arr.each do |x| invar = 3+6 puts num1 # ok to access local variable in an inner scope end # puts invar # Cannot use variable from an inner scope in do end<file_sep># One billion seconds - Find out the exact second I was born # Chapter 12.2 of Learn to Program by <NAME> # 201311116 puts 'This program calculates the date when you will turn 1 billion seconds old.' puts "What day (dd) were you born?" day = gets.chomp.to_i puts 'What month (mm) were you born?' month = gets.chomp.to_i puts 'What year (yyyy) were you born?' year = gets.chomp.to_i birthdate = Time.local(year, month, day) puts "You were born on #{birthdate}." puts "One billion seconds after this date is on #{birthdate + 1000000000}" # Calculate how old year_now = Time.now.year month_now = Time.now.month day_now = Time.now.day puts "You are #{year_now - year} years, #{month_now - month} months and #{day_now - day} days old."<file_sep># Class Dragon # Ch13.5 of Learn to Program by <NAME> # 20131119 class Dragon def initialize @asleep = false @stuff_in_belly = 10 # ie he's full @stuff_in_intestine = 0 # ie he doesn't need to go yet. puts 'Welcome to Dragon World. So you decided to have a dragon as a pet?' puts 'What would you like to name your dragon?' @name = gets.chomp puts "#{@name} is born." command end def command choice = '' while choice != 'exit' puts 'What do you want to do with George?' puts 'Please choose: 1) feed, 2) walk, 3) toss, 4) put to bed, 5) rock' choice = gets.chomp.to_i case choice when 1 feed when 2 walk when 3 toss when 4 put_to_bed when 5 rock else puts 'Error: that choice is invalid. Please enter 1, 2, 3, 4 or 5.' end end end def feed puts "You feed #{@name}." @stuff_in_belly = 10 passage_of_time end def walk puts "You walk #{@name}." @stuff_in_intestine = 0 passage_of_time end def put_to_bed puts "You put #{@name} to bed." @asleep = true 3.times do if @asleep passage_of_time end if @asleep puts "#{@name} snores, filling the room with smoke." end if @asleep @asleep = false puts "#{@name} wakes up slowly." end end end def toss puts "You toss #{@name} up into the air." puts 'He giggles, which singes your eyebrows.' passage_of_time end def rock puts "You rock #{@name} gently." @asleep = true puts 'He briefly dozes off...' passage_of_time if @asleep @asleep = false puts '...but wakes when you stop.' end end private # 'private' means that the methods defined here are methods internal to the object. # (You can feed your dragon, but you cannot control when he's hungry.) def hungry? @stuff_in_belly <=2 end def poopy? @stuff_in_intestine >= 8 end def passage_of_time if @stuff_in_belly > 0 # Move from belly to intestine @stuff_in_belly = @stuff_in_belly - 1 @stuff_in_intestine = @stuff_in_intestine + 1 else # Dragon is starving! if @asleep @asleep = false puts 'He wakes up suddenly!' end puts "#{@name} is starving! In desperation, he ate YOU!" exit end if @stuff_in_intestine >= 10 @stuff_in_intestine = 0 puts "Whoops! #{@name} had an accident..." end if hungry? if @asleep @asleep = false puts 'He wakes up suddenly!' end puts "#{@name}'s stomach grumbles..." end if poopy? if @asleep @asleep = false puts 'He wakes up suddenly!' end puts "#{@name} does the potty dance..." end end end pet = Dragon.new <file_sep># Sorting from Learn to Program by <NAME> Chapter 10 # 20131110 words = %w(apple zoology berserk catnip daschund elephant aardvark major nuclear island major) def sorting some_array # This "wraps" recursive_sort. recursive_sort some_array, [] end def recursive_sort unsorted_array, sorted_array # Go through each element of the array, compare and find which word should go first # according to the dictionary # Then move that word into sorted_array while unsorted_array.length != 0 smallest_word = unsorted_array[0] unsorted_array.each { |x| if x < smallest_word smallest_word = x end } sorted_array << smallest_word unsorted_array.slice!(unsorted_array.index(smallest_word)) # This gets the index of the # smallest_word then the slice! deletes that object at that index - brilliant! end sorted_array end puts 'Using the in-built array method "sort": ' puts words.sort new_words = [] new_words = sorting(words) puts 'Using my own sorting method: ' puts new_words <file_sep># Shuffle from Learn to Program by <NAME> Chapter 10 # 20131112 words = %w(apple zoology berserk catnip daschund elephant aardvark major nuclear island major) def shuffling some_array # This "wraps" recursive_sort. recursive_shuffle some_array, [] end def recursive_shuffle unshuffled_array, shuffled_array # Generate a random number up to the length of the array, then use that as the index # to move that particular obj in the array to the new array transfer_word = '' while unshuffled_array.length != 0 # Set index in array to transfer to new array by random number random_number = Random.new random_number = random_number.rand(unshuffled_array.length) transfer_word = unshuffled_array[random_number] shuffled_array << transfer_word unshuffled_array.slice!(unshuffled_array.index(transfer_word)) # This gets the index of the # transfer_word then the slice! deletes that object at that index - brilliant! end shuffled_array end puts 'Using the in-built array method "shuffle": ' puts words.shuffle new_words = [] new_words = shuffling(words) puts 'Using my own shuffling method: ' puts new_words <file_sep>#HW9 Pass by Reference vs value # 20131107 def some_method(obj) #obj.uniq # uniq method does not change the arr reference - pass by value obj.uniq! #uniq! method changes the arr reference - pass by reference # Therefore Ruby is both, can be either pass by reference or value depending on the method called end arr = [1, 0, 2, 2,3,4,4] some_method(arr) puts arr <file_sep># Blackjack Game # 20131107 # Storage of cards card_deck = [ 'Ace Spade', '2 Spade', '3 Spade', '4 Spade', '5 Spade', '6 Spade', '7 Spade', '8 Spade','9 Spade', '10 Spade', 'Jack Spade', 'Queen Spade', 'King Spade', 'Ace Club', '2 Club', '3 Club', '4 Club', '5 Club', '6 Club', '7 Club', '8 Club', '9 Club', '10 Club', 'Jack Club', 'Queen Club', 'King Club', 'Ace Heart', '2 Heart', '3 Heart', '4 Heart', '5 Heart', '6 Heart', '7 Heart', '8 Heart', '9 Heart', '10 Heart', 'Jack Heart', 'Queen Heart', 'King Heart', 'Ace Diamond', '2 Diamond', '3 Diamond', '4 Diamond', '5 Diamond', '6 Diamond', '7 Diamond', '8 Diamond', '9 Diamond', '10 Diamond', 'Jack Diamond', 'Queen Diamond', 'King Diamond' ] def deal_cards(deck) deck.shuffle! card = deck.pop end def card_value(card) face = card[0,1].downcase #gets the first character of a string case face when 'j' card = 10 when 'q' card = 10 when 'k' card = 10 when 'a' card = 11 else card = card.to_i end end #Ask name puts 'Welcome to Blackjack! What is your name?' name = gets.chomp puts name + ', good luck!' #Deal cards for the player and dealer p_card = [] #array for player's cards d_card = [] # dealer's cards i = 0 #counter for player j = 0 #counter for dealer p_card[i] = deal_cards(card_deck) d_card[j] = deal_cards(card_deck) i += 1 j += 1 #2nd card: p_card[i] = deal_cards(card_deck) d_card[j] = deal_cards(card_deck) i += 1 j += 1 puts name + ', your cards are: ' + p_card[0] + ' and ' + p_card[1] puts 'The dealer\'s open card is: ' + d_card[0] #Evaluate initial deal p_hand = card_value(p_card[0]) + card_value(p_card[1]) d_hand = card_value(d_card[0]) + card_value(d_card[1]) if p_hand == 21 puts 'Blackjack!' puts 'Now checking to see dealer\'s other card...' puts d_card[1] if d_hand == 21 puts 'Dealer also has blackjack. It\'s a draw!' else puts 'Congratulations! You win!' end else puts 'You got: ' + p_hand.to_s while p_hand <= 21 puts 'Do you want to 1 Hit or 2 Stay?' p_choice = gets.chomp.to_i if p_choice == 1 p_card[i] = deal_cards(card_deck) puts 'Your next card is: ' + p_card[i] # Check for value of Ace if p_card[i][0,1] == 'A' && p_hand >= 11 p_hand = p_hand - 10 end p_hand = p_hand + card_value(p_card[i]) i += 1 puts 'You got: ' + p_hand.to_s if p_hand > 21 puts name + ', you busted! Sorry you lost!' end elsif p_choice == 2 #Dealer's turn puts 'Now checking to see dealer\'s other card...' puts d_card[1] while d_hand < 17 d_card[j] = deal_cards(card_deck) # Check for value of Ace if d_card[j][0,1] == 'A' && d_hand >= 11 d_hand = d_hand - 10 end d_hand = d_hand + card_value(d_card[j]) puts 'Dealer\'s next card is ' + d_card[j] + '. Total: ' + d_hand.to_s j += 1 end puts 'Dealer\'s total is: ' + d_hand.to_s if p_hand > d_hand puts 'Congratulations ' + name +'! You win!' elsif d_hand > 21 puts 'Dealer busted. Congratulations ' + name + '! You win!' elsif p_hand == d_hand puts 'It\'s a draw!' else puts 'Sorry ' + name + '. Dealer wins!' end break else puts 'Your choice is invalid. Please press 1 to Hit or 2 to Stay.' end end end <file_sep># Roman to Integer # Chapter 12.6 Learn to Program by <NAME> # This converts roman numerals to its decimal equivalent # 20131117 puts 'Please input a Roman numeral and it will be converted to its decimal form: ' input = gets.chomp.upcase def roman_to_integer roman # Gets the string eg MCMXCIX -- need to get 1999 # Go through each digit, convert as normal but if the digit after is bigger # than the current digit - it means it's a subtraction counter = 0 number = 0 while counter < roman.length case roman[counter] when 'M' number = number + 1000 when 'D' number = number + 500 when 'C' number = number + 100 when 'X' number = number + 10 when 'V' number = number + 5 when 'I' number = number + 1 else puts "Error. That is not a valid roman number." exit end # Test for precedence ie XC or CM or IV if roman[counter] == 'C' && roman[counter + 1] == 'M' number = number - 200 # double the deduction as it was added previously elsif roman[counter] == 'X' && roman[counter + 1] == 'C' number = number - 20 elsif roman[counter] == 'I' && roman[counter + 1] == 'V' number = number - 2 elsif roman[counter] == 'I' && roman[counter + 1] == 'X' number = number - 2 end counter = counter + 1 end number end puts roman_to_integer(input)
0d9e14e84c78712e8c0e26da40058aee71c3dcf3
[ "Ruby" ]
14
Ruby
eduardodelcastillo/Tealeaf_Week1
ad0451cf03e9400207e49051e8af244e02411a02
3412d648c04dad8c1a9edf8b6c28c56ac5df4949
refs/heads/master
<file_sep>require "open-uri" require "json" class GamesController < ApplicationController def new @letters = Array.new(10) { ('A'..'Z').to_a.sample } # The new action will be used to display a new random grid and a form. #The form will be submitted (with POST) to the score action. end def score @word = params[:word].upcase word_splited = @word.split('') @letters = params[:letters].split('') url = "https://wagon-dictionary.herokuapp.com/#{@word}" user_serialized = open(url).read user = JSON.parse(user_serialized) if user['found'] == false return @score = "Sorry but #{@word} does not seem to be a valid English word..." elsif (user['found'] == true) && ((word_splited.all? { |k| @letters.include? k }) == true) return @score = "Congratulations! #{@word} is a valid English word!" elsif ((word_splited.all? { |k| @letters.include? k }) == false) return @score = "Sorry but #{@word} can't be built out of #{@letters}" end end end
57782418460872c571cf92aae14e8b02362a9e2a
[ "Ruby" ]
1
Ruby
adri0713/rails-longest-word-game
ddd3618dc55d2a4d3a2c2d4e151cbbffdf46a091
4df34425f981dd1c3b521e06df6123cec1229873
refs/heads/master
<repo_name>JWRickyWan/CS61A<file_sep>/Lab/lab01/lab01_extra.py """Optional questions for Lab 1""" # While Loops def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 >>> falling(4, 0) 1 """ NFact = 1 while k > 0: NFact = NFact * n n -= 1 k -= 1 return NFact def double_eights(n): """Return true if n has two eights in a row. >>> double_eights(8) False >>> double_eights(88) True >>> double_eights(2882) True >>> double_eights(880088) True >>> double_eights(12345) False >>> double_eights(80808080) False """ nStr = str(n) nList = list(nStr) if len(nList) <2: return False for i in range (0,len(nList)-1): if int(nList[i])==8 and int(nList[i+1])==8: return True return False <file_sep>/Lab/lab01/lab01.py """Lab 1: Expressions and Control Structures""" def both_positive(a, b): """Returns True if both a and b are positive. >>> both_positive(-1, 1) False >>> both_positive(1, 1) True """ return a > 0 and b > 0 # You can replace this line! def sum_digits(x): """Sum all the digits of x. >>> sum_digits(10) # 1 + 0 = 1 1 >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12 >>> sum_digits(1234567890) 45 >>> a = sum_digits(123) # make sure that you are using return rather than print >>> a 6 """ digitStr = str(x) strlist = list(digitStr) digitSum = 0 for num in strlist: digitSum += int(num) return digitSum <file_sep>/Projects/Disc03.py """Discussion 3: Feb 12, 2020 -----------------Recursion--------------- """ def product_nums(m,n): if m ==0 or n==0: return 0 else: return m + product_nums(m,n-1) def hailstone(n): """Print out the hailstone sequence starting at n, and return thenumber of elements in the sequence. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 """ print(n) if n ==1: return 1 elif n%2 ==0: return 1+hailstone(n//2) else: return 1+hailstone(3*n+1) <file_sep>/Projects/Disc03/Disc03.py """Discussion 3: Feb 12, 2020 -----------------Recursion--------------- """ def product_nums(m,n): if m ==0 or n==0: return 0 else: return m + product_nums(m,n-1) <file_sep>/Homework/hw01/test1.py import hw01 a_plus_abs_b(1,3)
d659f9a8e5eae230273c6d6d8dc7730a4a902616
[ "Python" ]
5
Python
JWRickyWan/CS61A
cbc63e953f3479431bee0dfcf89fe229b3a5dba2
ae7b29ac6abda13509af2d37e0d9768366368497
refs/heads/main
<repo_name>codingwithlis/React-JSX-Practice<file_sep>/index.js // React App Multiple Components class App extends React.Component { render() { return ( <div> <Hello/> <NumPicker/> </div> ) } } ReactDOM.render(<App/>, document.getElementById("root")) /////////////////////////////////////////////////////////////// //JSX Demo // class JSXDemo extends React.Component { // render() { // return ( // <div> // <p>My current mood is {getMood()}</p> // </div> // ); // } // } // function getMood(){ // const moods = ["happy", "angry", "mad"]; // return moods[Math.floor(Math.random() * moods.length)] // } // ReactDOM.render(<JSXDemo/>, document.getElementById("root")) /////////////////////////////////////////////////////////////// // First Component // class Hello extends React.Component { // render(){ // return ( // <div> // <h1> Hello There! </h1> // <p>Welcome</p> // </div> // ); // } // }
9956d8dfbdc64794f5861b819ddceb7c0770d1eb
[ "JavaScript" ]
1
JavaScript
codingwithlis/React-JSX-Practice
748607ead6a9914356abf4af9879778c91172e3a
1551eebd7a1a8ea9a8b5c66ddaf241ef3823a4b7
refs/heads/master
<file_sep>--- title: "Project4_TextMining" author: "rbg" date: "May 9, 2016" output: html_document --- ```{r, echo=FALSE, warning=FALSE, message=FALSE} require('wordcloud') require('biclust') require('cluster') require('igraph') require('dplyr') require('scales') require('SnowballC') require('RColorBrewer') require('ggplot2') require('tm') # source("https://bioconductor.org/biocLite.R") # biocLite("Rgraphviz") require('Rgraphviz') require('fpc') ``` Loading the union address file into the database and then converting it into text mining corpus. ```{r, echo=FALSE} setwd("/home/rohitb/Dropbox/Spring16/ExploratoryDataAnalysis/Assignments/Project4") text <- readLines("State of the Union Addresses 1970-2016.txt") docs <- Corpus(VectorSource(paste(text,collapse="\n"))) #inspect(docs) ``` ```{r, echo=FALSE} docs <- Corpus(VectorSource( strsplit(as.character(docs[[1]]), ## coerce to character "***", fixed=TRUE)[[1]])) docs_backs <- docs #inspect(split.docs) #docs[[2]]$content ``` Adding author and data to meta-data of each document. ```{r echo=FALSE} docs <- docs_backs meta_data <- strsplit(docs[[1]]$content,"\n ",fixed = TRUE)[[1]] meta_data <- meta_data[grepl("[Union].*",meta_data,perl=TRUE)] meta_data <- sub("\n","",meta_data,perl = TRUE) meta_data <- trimws(meta_data) meta_data <- sub(", State of the Union Address, ","--",meta_data,perl=TRUE) meta_data <- strsplit(meta_data,"--",fixed=TRUE) docs[[1]] <- NULL for(j in seq(docs)) { docs[[j]]$content <- gsub("\n\n", "\n", docs[[j]]$content) docs[[j]]$content <- gsub("\\([^\\)]*\\)", "", docs[[j]]$content, perl=TRUE) meta(docs[[j]],"author") <- meta_data[[j]][1] meta(docs[[j]],"Date") <- meta_data[[j]][2] meta(docs[[j]],"description") <- "State of the Union Address" } #inspect(split.docs) docs[[2]]$meta ``` Cleaning ```{r echo=FALSE, warning=FALSE} docs = tm_map(docs, function(x){ x$content <- trimws(x$content) x }) docs = tm_map(docs, content_transformer(tolower)) docs = tm_map(docs, removeNumbers) docs = tm_map(docs, removePunctuation) docs = tm_map(docs, removeWords, stopwords("english")) docs = tm_map(docs, stemDocument) docs = tm_map(docs, stripWhitespace) ``` Analysis (term matrix): ```{r echo=FALSE, eval=FALSE} # Building term matrix doc_target = docs[180:224] doc_target[[1]]$content #names(doc_target) = paste("year", 1970:2016, sep = " ") dtm = DocumentTermMatrix(doc_target) dtm inspect(dtm[1:5,1:20]) write.csv(as.matrix(dtm),file='dtm.csv') mfreq = colSums(as.matrix(dtm)) p1 = ggplot(data.frame(word=names(mfreq),freq=mfreq),aes(word,freq))+ geom_bar(stat='identity') + theme(axis.text.x=element_text(angle=45,hjust=0.5)) p1 p1 = ggplot(subset(data.frame(word=names(mfreq),freq=mfreq),freq>800),aes(word,freq))+ geom_bar(stat='identity') + theme(axis.text.x=element_text(size=12,color='red',fac='bold.italic',angle=45,hjust=0.5)) p1 mord = order(mfreq, decreasing=TRUE) #increasing order as default mfreq[head(mord,20)] ``` Analysis (Word Cloud): ```{r echo=FALSE, warning=FALSE} wordCloud <- function (doc_target, president_name){ print(president_name) dtm = DocumentTermMatrix(doc_target) mfreq = colSums(as.matrix(dtm)) wordcloud(names(mfreq),mfreq, max.words = 100) return(mfreq) } i=1 presidents <- c() matrices <- list() while(i < length(docs)) { #print(c(i,"--",docs[[i]]$meta$author)) auth = docs[[i]]$meta$author i = i+1 j = i while (docs[[j]]$meta$author == auth){ #print(c(j,"--",docs[[j]]$meta$author)) j = j+1 if (j > length(docs)){ break } } docs_target <- docs[i:j-1] presidents <- c(presidents,auth) matrices <- unlist(list(matrices,list(wordCloud(docs_target,auth))), recursive = FALSE) i = j } length(presidents) length(matrices) matrices matrices[5] ``` <file_sep># TextViz Here is the repository of the text vvisualization, let's do it! <file_sep>f = open('full_contents.txt') data = f.read() f.close() doc = data.split('***') f = open('table_of_contents.txt') table = f.read() f.close() table_lines = table.split('\n') years = [] prez = [] for i in range(len(table_lines)) : line = table_lines[i].split(',') if line[0] != "" : prez.append(line[0]) years.append(line[-1].strip() + '_' + line[-2].strip().split(' ')[0] + '_' + line[-2].strip().split(' ')[1]) ## outputing text files for i in range(len(doc)) : file = open(prez[i] + "-" + years[i] + ".txt", "w") file.write(doc[i]) file.close() years_csv = [] months_csv = [] names_csv = [] for i in range(len(table_lines)) : line = table_lines[i].split(',') if line[-1] != "" : years_csv.append( line[-1].strip() ) months_csv.append( line[-2].strip().split(' ')[0] ) names_csv.append( line[0] ) ## outputing name - year correspondence import csv as csv output_file = open("name_year_month.csv", "wb") output_file_object = csv.writer(output_file) output_file_object.writerow(["Name","Year", "Month"]) output_file_object.writerows(zip(names_csv, years_csv, months_csv)) output_file.close() <file_sep>--- title: "vishal_writeup" author: "<NAME>" date: "May 13, 2016" output: html_document --- ### Hierarchichal clustering of President's speeches We obtained term-document matrices, representing each president as a vector (a dimension representing frequency of a single word). Pre-processing steps involved removing numbers, punctuation, stop-words and stemming. We removed sparse terms to keep dimensions/words which have atleast 10% non-zero values. ```{r, echo=FALSE, warning=FALSE, message=FALSE} require('wordcloud') require('biclust') require('cluster') require('igraph') require('dplyr') require('scales') require('SnowballC') require('RColorBrewer') require('ggplot2') require('tm') require('fpc') library("ggplot2") clean_docs=function(docs) { docs = tm_map(docs, content_transformer(tolower)) docs = tm_map(docs, removeNumbers) docs = tm_map(docs, removePunctuation) docs = tm_map(docs, removeWords, stopwords("english")) docs = tm_map(docs, stemDocument) docs = tm_map(docs, stripWhitespace) docs = tm_map(docs, PlainTextDocument) docs } cos.sim=function(ma, mb){ mat=tcrossprod(ma, mb) t1=sqrt(apply(ma, 1, crossprod)) t2=sqrt(apply(mb, 1, crossprod)) mat / outer(t1,t2) } setwd("/Users/vishaljuneja/Desktop/EDAV/Project5/textViz/") mypwd = "/Users/vishaljuneja/Desktop/EDAV/Project5/textViz/data" docs = Corpus(DirSource(mypwd)) docs = Corpus(VectorSource(strsplit(paste(docs[[1]]$content,collapse='\n'),"***",fixed=TRUE)[[1]])) speeches = docs[[1]]$content speeches = strsplit(speeches, "\n") speeches = speeches[[1]] speeches = speeches[speeches!=""] df = data.frame(speeches) df = data.frame(do.call('rbind', strsplit(as.character(df$speeches), "," ,fixed=TRUE))) colnames(df) = c("president","speech","month","year") # returns string w/o leading or trailing whitespace trim <- function (x) gsub("^\\s+|\\s+$", "", x) df = apply(df, 2, trim) df = df[-1,] ident = paste(df[,1], df[,4], sep="_") df = cbind(df, ident) docs = docs[-1] docs = tm_map(docs, content_transformer(tolower)) docs = tm_map(docs, removeNumbers) docs = tm_map(docs, removePunctuation) docs = tm_map(docs, removeWords, stopwords("english")) docs = tm_map(docs, stemDocument) docs = tm_map(docs, stripWhitespace) docs = tm_map(docs, PlainTextDocument) names(docs) = df[,5] dtm <- DocumentTermMatrix(docs) dtm tdm <- TermDocumentMatrix(docs) tdm tdmss = removeSparseTerms(tdm, 0.90) ``` Below is a hierarchical clustering of speeches of presidents from 1970 onwards. We deduce from the plot that speech style of each president is personal and very unqiue as most individual address fall into their own clusters (see <NAME>, <NAME> and <NAME>'s speeches which are all under one node). A few interesting exceptions to the above observation are <NAME>'s address of 1992 and George Bush's address of 2001 which appear together. Another exception is <NAME>'s address in 1981 which seems to be most far apart from all other clusters. ```{r, echo=FALSE, warning=FALSE, message=FALSE, fig.width = 10, fig.height = 7} tdmss_small = tdmss[,180:224] d <- dist(t(tdmss_small), method="euclidian") fit <- hclust(d=d, method="ward") plot.new() plot(fit, hang=-1) groups <- cutree(fit, k=5) # "k=" defines the number of clusters you are using rect.hclust(fit, k=5, border="red") # draw dendogram with red borders around the 5 clusters ``` When we observe clusters from a higher level. <NAME> and Clinton's speeches are tagged into the same cluster. Some of Nixon, <NAME>, Bush and Reagan's speeches fall into a single cluster as well. Lastly <NAME> and <NAME>'s addresses also seem to be similar in word frequency composition. The clustering results show that presidents focus on and care about different policy issues and topics in general. ### Comparison of addresses with those of more famous/in-famous personalities Seeing that our approach can largely distinguish between speech styles and major topics addressed; we thought about comparing the speeches with that of other famous personalities. #### Hitler Our aim was to discover which president's speech style closely resembles that of <NAME>. We took the translated version of Hitler's speeches over the years: starting from his ascendency to the highest office to his speeches during the world war. We express closeness or similarity in terms of cosine distances. ```{r, echo=FALSE, warning=FALSE, message=FALSE} hitd = "/Users/vishaljuneja/Desktop/EDAV/Project5/textViz/hitler" hdocs = Corpus(DirSource(hitd)) hdocs = Corpus(VectorSource(strsplit(paste(hdocs[[1]]$content,collapse='\n'),"***",fixed=TRUE)[[1]])) hdocs = clean_docs(hdocs) combined = c(docs, hdocs) sp = c(df[,5], "<NAME>") names(combined) = sp htdm = TermDocumentMatrix(combined) htdmss = removeSparseTerms(htdm, 0.90) #htdmss$dimnames m = as.matrix(htdmss) m = m[,180:225] c = cos.sim(t(m), t(m)) scores = c[46,] scores = scores[order(scores)] out = data.frame(cbind(names(scores), scores)) out$scores = as.numeric(as.character(out$scores)) o = out[36:46,] g1 = ggplot(o) g1 = g1 + geom_bar(aes(x=reorder(V1, -scores), y=scores, fill="blue", alpha=0.5), stat="identity") g1 = g1 + theme(axis.text.x = element_text(angle = 90, hjust = 1)) g1 = g1 + labs(title="Similarity with Hitler's Speeches", x="", y="Cosine similarity measures") g1 = g1 + theme(legend.position="none") g1 ``` In the above graph we show the top 10 most similar speeches (and speech givers) with those of Hitler's. As a sanity check Hitler's speech has a cosine similarity measure of 1 (completely identical) with his own speeches. We find that most matching speeches were made during war periods e.g. Nixon's address in 1972 during the Vietnam war, George W. Bush's speeches in 2003 and 2005 during Afghanistan invasion, George H.W. Bush's speech in 1991 was again made during the turmoil period in Afghanistan. #### Gandhi Mahatma Gandhi as we all know has been a preacher of non-violence and protagonist of peaceful ways for fighting in a just cause. We took Gandhi's speeches during freedom struggle and after independence and compared them with other presidents. ```{r, echo=FALSE, warning=FALSE, message=FALSE} hitd = "/Users/vishaljuneja/Desktop/EDAV/Project5/textViz/gandhi" hdocs = Corpus(DirSource(hitd)) hdocs = Corpus(VectorSource(strsplit(paste(hdocs[[1]]$content,collapse='\n'),"***",fixed=TRUE)[[1]])) hdocs = clean_docs(hdocs) combined = c(docs, hdocs) sp = c(df[,5], "<NAME>") names(combined) = sp htdm = TermDocumentMatrix(combined) htdmss = removeSparseTerms(htdm, 0.90) #htdmss$dimnames m = as.matrix(htdmss) m = m[,180:225] c = cos.sim(t(m), t(m)) scores = c[46,] scores = scores[order(scores)] out = data.frame(cbind(names(scores), scores)) out$scores = as.numeric(as.character(out$scores)) o = out[36:46,] g2 = ggplot(o) g2 = g2 + geom_bar(aes(x=reorder(V1, -scores), y=scores, fill="blue", alpha=0.5), stat="identity") g2 = g2 + theme(axis.text.x = element_text(angle = 90, hjust = 1)) g2 = g2 + labs(title="Similarity with Gandhi's Speeches", x="", y="Cosine similarity measures") g2 = g2 + theme(legend.position="none") g2 ``` First thing we note is that general similarity measure is very small compared to similarity with Hitler's speeches (~ 0.30). From the above plot we find that as in Hitler's case Gandhi's speeches are similar to George <NAME>, George <NAME>ush's speeches as well (although Barrack Obama does figures in the top 5). We conjecture that although Bush and Gandhi might both be talking about war, post-war situations and effects of war; their sentiment towards the topics might be different. Note that our similarity measure takes into account only frequency of occurance of words. This means that even though Gandhi and Bush might be talking about the same topics we would not know if there sentiment and opinions about the topics differ. #### <NAME> We further took recently elected Canadian president's address to the nation. <NAME> has been applauded for choosing a very diverse, secular and representative cabinet. His address was seen as being progressive and discussed roadmap for advancing Canada on frontiers of technology and innovation. ```{r, echo=FALSE, warning=FALSE, message=FALSE} ## read JT's speeches hitd = "/Users/vishaljuneja/Desktop/EDAV/Project5/textViz/jt" hdocs = Corpus(DirSource(hitd)) hdocs = Corpus(VectorSource(strsplit(paste(hdocs[[1]]$content,collapse='\n'),"***",fixed=TRUE)[[1]])) hdocs = clean_docs(hdocs) combined = c(docs, hdocs) sp = c(df[,5], "<NAME>") names(combined) = sp htdm = TermDocumentMatrix(combined) htdmss = removeSparseTerms(htdm, 0.75) m = as.matrix(htdmss) m = m[,180:225] c = cos.sim(t(m), t(m)) scores = c[46,] scores = scores[order(scores)] out = data.frame(cbind(names(scores), scores)) out$scores = as.numeric(as.character(out$scores)) o = out[36:46,] g2 = ggplot(o) g2 = g2 + geom_bar(aes(x=reorder(V1, -scores), y=scores, fill="blue", alpha=0.5), stat="identity") g2 = g2 + theme(axis.text.x = element_text(angle = 90, hjust = 1)) g2 = g2 + labs(title="Similarity with Gandhi's Speeches", x="", y="Cosine similarity measures") g2 = g2 + theme(legend.position="none") g2 ``` Other than a few exceptions we note that <NAME>'s speech seem to be similar in spirit with Barrack Obama's addresses to the nation. <file_sep>require('wordcloud') require('biclust') require('cluster') require('igraph') require('dplyr') require('scales') require('SnowballC') require('RColorBrewer') require('ggplot2') require('tm') require('Rgraphviz') require('fpc') setwd("/Users/vishaljuneja/Desktop/EDAV/Project5/textViz/") mypwd = "/Users/vishaljuneja/Desktop/EDAV/Project5/textViz/data" docs = Corpus(DirSource(mypwd)) #reading the file and creating a temporary corpus text <- readLines("State of the Union Addresses 1970-2016.txt") docs <- Corpus(VectorSource(paste(text,collapse="\n"))) # Creating the corpus of the documents docs <- Corpus(VectorSource( strsplit(as.character(docs[[1]]), ## coerce to character "***", fixed=TRUE)[[1]])) #Adding author and date as meta information for each document docs_backs <- docs meta_data <- strsplit(docs[[1]]$content,"\n ",fixed = TRUE)[[1]] meta_data <- list[grepl("[Union].*",meta_data,perl=TRUE)] meta_data <- sub("\n","",meta_data,perl = TRUE) meta_data <- trimws(meta_data) meta_data <- sub(", State of the Union Address, ","--",meta_data,perl=TRUE) meta_data <- strsplit(meta_data,"--",fixed=TRUE) docs[[1]] <- NULL meta_data[[1]] <- NULL for(j in seq(docs)) { meta(docs[[j]],"author") <- meta_data[[j]][1] meta(docs[[j]],"Date") <- meta_data[[j]][2] meta(docs[[j]],"description") <- "State of the Union Address" } docs[[1]]$meta # Processing documents - Cleaning docs = tm_map(docs, function(x){ x$content <- trimws(x$content) x }) docs = tm_map(docs, content_transformer(tolower)) docs = tm_map(docs, removeNumbers) docs = tm_map(docs, removePunctuation) docs = tm_map(docs, removeWords, stopwords("english")) docs = tm_map(docs, stemDocument) docs = tm_map(docs, stripWhitespace) #docs = tm_map(docs, PlainTextDocument) docs[[1]]$meta # Building term matrix doc_target = docs[180:224] doc_target[[1]]$content #names(doc_target) = paste("year", 1970:2016, sep = " ") dtm = DocumentTermMatrix(doc_target) dtm inspect(dtm[1:5,1:20]) write.csv(as.matrix(dtm),file='dtm.csv') mfreq = colSums(as.matrix(dtm)) p1 = ggplot(data.frame(word=names(mfreq),freq=mfreq),aes(word,freq))+ geom_bar(stat='identity') + theme(axis.text.x=element_text(angle=45,hjust=0.5)) p1 p1 = ggplot(subset(data.frame(word=names(mfreq),freq=mfreq),freq>800),aes(word,freq))+ geom_bar(stat='identity') + theme(axis.text.x=element_text(size=12,color='red',fac='bold.italic',angle=45,hjust=0.5)) p1 mord = order(mfreq, decreasing=TRUE) #increasing order as default mfreq[head(mord,20)] #wordcloud wordcloud(names(mfreq),mfreq, min.freq=70) <file_sep>library(stringr) library(plyr) library(dplyr) library(magrittr) library(mgcv) library(tm) #library(proxy) library(ggdendro) library(ggplot2) sous <- readLines(file("State of the Union Addresses 1970-2016.txt")) pres = sous[grep("^[//*]{3}$",sous)+3] pres = pres[grep("[[:alpha:]]$",pres)] strt1 = grep("^[//*]{3}$",sous)+5 strt = strt1[1:214] end1 = grep("^[//*]{3}$",sous)-2 end = end1[-c(1,216)] startend = data.frame ("start"=strt1, "end" =end1) comb=list() for (i in 1:length(startend[,1])){ comb[i] <- paste(sous[startend$start[i]:startend$end[i]], sep=" ", collapse=" " ) } s=list() for (i in 1:length(comb)){ test = sapply(comb[[i]], strsplit , split = "\\. |\\? ") s[i]= test } replace=list() for (g in 1:length(s)){ replace[[g]]=unlist(lapply(s[[g]],gsub, pattern = "[[:digit:]]|[\\']|\\([Aa]pplause\\.*\\)", replace = "")) } regexpr("\\([Aa]pplause\\.*\\)",s) regexpr("\\([Aa]pplause\\.*\\)",replace) #Test Case punct=list() for (i in 1:length(lower)){ punct[[i]] = unlist(lapply(lower[[i]], strsplit , "[[:punct:]]|[[:blank:]]")) } full=list() for (i in 1:length(punct)){ full[[i]] = punct[[i]][nchar(punct[[i]])>0] } library(SnowballC) steml = list() for (i in 1:length(full)){ steml[[i]] = unlist(lapply(full[[i]], wordStem)) } bagwords = sort(unique(unlist(steml))) bagwords = bagwords[nchar(bagwords)!=0] wordv = matrix(seq(1,(length(bagwords)*length(steml)),by=1), nrow=length(bagwords), ncol=length(steml), dimnames = list(bagwords,1:length(steml))) for(j in 1:length(steml)){ for (i in 1:length(bagwords)){ wordv[i,j] = length(steml[[j]][steml[[j]]==bagwords[i]]) } } computeSJDistance = function(tf, df, terms, logdf = TRUE, verbose = TRUE) { numTerms = nrow(tf) numDocs = ncol(tf) tfn = t(tf)/colSums(tf) if (logdf) tfidfs = t(tfn) * (log(numDocs) - log(df)) else tfidfs = numDocs * ( t(tfn) / df) D.SJ = matrix(0, numDocs, numDocs) for(i in 1:(numDocs -1)) { for(j in (i+1):numDocs) { D.SJ[i,j] = D.SJ[j,i] = DJ(tfidfs[, i], tfidfs[, j]) } if(verbose) print(i) } return(D.SJ) } DB = function(p, q) { tmp = !(p == 0 | q == 0) p = p[tmp] q = q[tmp] sum(- p*log(q) + p*log(p) ) } DJ = function(p, q) { T = 0.5 * (p + q) 0.5 * DB(p, T) + 0.5 * DB(q, T) } simMatrix = computeSJDistance(tf = wordv, df = dfq, terms = bagOfWords, logdf = FALSE) rownames(simMatrix) = paste(pres,year, sep = "-") colnames(simMatrix) = paste(pres,year, sep = "-") #Multidimensional Scaling mds =cmdscale(simMatrix) plot(mds, type = "n", xlab = "", ylab = "", main="MDS on Documents") par(cex=0.5) text(mds, rownames(simMatrix)) # write-up ''' From the plot of the MDS, we can see that most speeches from presidents are similar. It makes sense since they use many common words and topics. Notice that <NAME> and <NAME>'s speeches are most dissimliar than others' speeches (they are far from the dense cluster on the graph). Although the graph is dense on that cluster and hard to tell who are in that cluster, we can infer the names of presidents in that cluster by excluding the presidents outside the cluster. For example, Bush and Obama should be in that cluster and Bush's speech is more similar with Obama than presidents such as <NAME> or <NAME>. ''' <file_sep>require('wordcloud') require('biclust') require('cluster') require('igraph') require('dplyr') require('scales') require('SnowballC') require('RColorBrewer') require('ggplot2') require('tm') #require('Rgraphviz') require('fpc') setwd("D:/Google Drive/Courses_G/1B_Exploratory Data Analysis and Visualization/project4") mypwd = "D:/Google Drive/Courses_G/1B_Exploratory Data Analysis and Visualization/project4/data" docs = Corpus(DirSource(mypwd)) # split the documents into individual lists docs = Corpus(VectorSource(strsplit(paste(docs[[1]]$content,collapse='\n'),"***",fixed=TRUE)[[1]])) docs = tm_map(docs, content_transformer(tolower)) docs = tm_map(docs, removeNumbers) docs = tm_map(docs, removePunctuation) docs = tm_map(docs, removeWords, stopwords("english")) docs = tm_map(docs, stemDocument) docs = tm_map(docs, stripWhitespace) docs = tm_map(docs, PlainTextDocument) subset_docs = docs[180:224] dtm = DocumentTermMatrix(subset_docs) subset_docs[[1]]$content df_dtm <-data.frame(as.matrix(dtm)) df_party <- read.csv("party.csv") party <- df_party[,2] row.names(df_dtm) <- df_party[,4] df_dtm_label <- data.frame(cbind(df_dtm,party)) df_dtm_label$party library(randomForest) fit.rf = randomForest(party~., data=df_dtm_label, ntree = 10) #plot 1 plot(importance(fit.rf)) ################################################################# #library(devtools) #install_github("ggbiplot", "vqv") #library(ggbiplot) df_tdm <- t(df_dtm) pca_df <- prcomp(t(df_dtm),center = TRUE, scale = TRUE) plot(pca_df) require(ggplot2) ###PLOT 2 biplot(pca_df) theta <- seq(0,2*pi,length.out = 100) circle <- data.frame(x = 0.3*cos(theta), y = 0.3*sin(theta)) loadings <- data.frame(pca_df$rotation,.names = df_party[,4]) p <- ggplot(circle,aes(x,y)) + geom_path() + geom_text(data=loadings, mapping=aes(x = PC1-0.1, y = PC2, label = .names, colour = .names)) + coord_fixed(ratio=1) + labs(x = "PC2", y = "PC1") p <file_sep>require('wordcloud') require('biclust') require('cluster') require('igraph') require('dplyr') require('scales') require('SnowballC') require('RColorBrewer') require('ggplot2') require('tm') require('fpc') library("ggplot2") clean_docs=function(docs) { docs = tm_map(docs, content_transformer(tolower)) docs = tm_map(docs, removeNumbers) docs = tm_map(docs, removePunctuation) docs = tm_map(docs, removeWords, stopwords("english")) docs = tm_map(docs, stemDocument) docs = tm_map(docs, stripWhitespace) docs = tm_map(docs, PlainTextDocument) docs } cos.sim=function(ma, mb){ mat=tcrossprod(ma, mb) t1=sqrt(apply(ma, 1, crossprod)) t2=sqrt(apply(mb, 1, crossprod)) mat / outer(t1,t2) } setwd("/Users/vishaljuneja/Desktop/EDAV/Project5/textViz/") mypwd = "/Users/vishaljuneja/Desktop/EDAV/Project5/textViz/data" docs = Corpus(DirSource(mypwd)) docs = Corpus(VectorSource(strsplit(paste(docs[[1]]$content,collapse='\n'),"***",fixed=TRUE)[[1]])) speeches = docs[[1]]$content speeches = strsplit(speeches, "\n") speeches = speeches[[1]] speeches = speeches[speeches!=""] df = data.frame(speeches) df = data.frame(do.call('rbind', strsplit(as.character(df$speeches), "," ,fixed=TRUE))) colnames(df) = c("president","speech","month","year") # returns string w/o leading or trailing whitespace trim <- function (x) gsub("^\\s+|\\s+$", "", x) df = apply(df, 2, trim) df = df[-1,] ident = paste(df[,1], df[,4], sep="_") df = cbind(df, ident) docs = docs[-1] docs = tm_map(docs, content_transformer(tolower)) docs = tm_map(docs, removeNumbers) docs = tm_map(docs, removePunctuation) docs = tm_map(docs, removeWords, stopwords("english")) docs = tm_map(docs, stemDocument) docs = tm_map(docs, stripWhitespace) docs = tm_map(docs, PlainTextDocument) dtm <- DocumentTermMatrix(docs) dtm tdm <- TermDocumentMatrix(docs) tdm names(docs) = df[,5] tdmss = removeSparseTerms(tdm, 0.75) ## read hitler's speeches hitd = "/Users/vishaljuneja/Desktop/EDAV/Project5/textViz/hitler" hdocs = Corpus(DirSource(hitd)) hdocs = Corpus(VectorSource(strsplit(paste(hdocs[[1]]$content,collapse='\n'),"***",fixed=TRUE)[[1]])) hdocs = clean_docs(hdocs) combined = c(docs, hdocs) sp = c(df[,5], "Hitler") names(combined) = sp htdm = TermDocumentMatrix(combined) htdmss = removeSparseTerms(htdm, 0.75) htdmss$dimnames m = as.matrix(htdmss) m = m[,180:225] c = cos.sim(t(m), t(m)) scores = c[46,] scores = scores[order(scores)] plot(scores) out = data.frame(cbind(names(scores), scores)) out$scores = as.numeric(as.character(out$scores)) o = out[36:46,] ggplot(o) + geom_bar(aes(x=reorder(V1, -scores), y=scores, fill="blue", alpha=0.5), stat="identity") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) ## read JT's speeches hitd = "/Users/vishaljuneja/Desktop/EDAV/Project5/textViz/trump" hdocs = Corpus(DirSource(hitd)) hdocs = Corpus(VectorSource(strsplit(paste(hdocs[[1]]$content,collapse='\n'),"***",fixed=TRUE)[[1]])) hdocs = clean_docs(hdocs) combined = c(docs, hdocs) sp = c(df[,5], "TRUMP") names(combined) = sp htdm = TermDocumentMatrix(combined) htdmss = removeSparseTerms(htdm, 0.75) htdmss$dimnames m = as.matrix(htdmss) m = m[,180:225] c = cos.sim(t(m), t(m)) scores = c[46,] scores = scores[order(scores)] scores plot(scores) out = data.frame(cbind(names(scores), scores)) out$scores = as.numeric(as.character(out$scores)) o = out[36:46,] ggplot(o) + geom_bar(aes(x=reorder(V1, -scores), y=scores, alpha=0.5), stat="identity") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) <file_sep>import os import glob import ast import json import urllib import csv positive = {} cwd = os.getcwd() print cwd path = '/speech/*.txt' loc = cwd + path files = glob.glob(loc) with open('sentiment.csv', 'w') as csvfile: fieldnames = ['Prez', 'Date', 'Positive', 'Neutral', 'Negative'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for name in files: with open(name) as f: key = name.split("/")[9] key = key.strip() key = key.split(".txt")[0] prez = key.split("-")[0] date = key.split("-")[1] print key text = f.read() if len(text)<50000: data = urllib.urlencode({"text": text.encode('utf-8')}) u = urllib.urlopen("http://text-processing.com/api/sentiment/", data) the_page = u.read() prob = ast.literal_eval(the_page)['probability'] pos = prob['pos'] if prob['pos'] else 0 positive[key] = pos neutral = prob['neutral'] neg = prob['neg'] if prob['neg'] else 0 print pos, neutral, neg writer.writerow({'Prez': prez, 'Date':date, 'Positive' : pos, 'Neutral' : neutral, 'Negative' : neg })
181d21f8643cf153f4e517cb47b4911254efbf49
[ "Markdown", "Python", "R", "RMarkdown" ]
9
RMarkdown
xxiao1992/textViz
54ab6e17d580729579b7626b841f349f86db5712
fcdcf6469412e1be565e05e590bd6f5b51819744
refs/heads/master
<file_sep>#ifdef HAVE_CONFIG_H # include "config.h" #endif #include <gmodule.h> #include <epan/prefs.h> #include <epan/packet.h> #include <epan/dissectors/packet-tcp.h> /* forward reference */ void proto_register_minecraft(); void proto_reg_handoff_minecraft(); void dissect_minecraft(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree); /* Define version if we are not building Wireshark statically */ #ifndef ENABLE_STATIC G_MODULE_EXPORT const gchar version[] = "0.0"; #endif #define PROTO_TAG_MC "MC" static int proto_minecraft = -1; static dissector_handle_t minecraft_handle; proto_item *mc_item = NULL; proto_item *mc_sub_item = NULL; proto_tree *mc_tree = NULL; proto_tree *mc_header_tree = NULL; static const value_string packettypenames[] = { { 0x00, "Keep Alive" }, { 0x01, "Login" }, { 0x02, "Handshake" }, { 0x03, "Chat" }, { 0x04, "Update Time" }, { 0x05, "Inventory" }, { 0x06, "Unknown(1.1.0)"}, { 0x0A, "Unknown(0x0A)" }, { 0x0B, "Player Position" }, { 0x0C, "Player Look" }, { 0x0D, "Player Move + Look" }, { 0x0E, "Block Dig" }, { 0x0F, "Place" }, { 0x10, "Block/Item Switch" }, { 0x11, "Add to Inventory" }, { 0x12, "Arm Animation" }, { 0x14, "Named Entity Spawn" }, { 0x15, "Entity Spawn" }, { 0x16, "Collect Item" }, { 0x17, "Unknown(0x17)" }, { 0x18, "Mob Spawn" }, { 0x1D, "Destroy Entity" }, { 0x1E, "Entity" }, { 0x1F, "Relative Entity Move" }, { 0x20, "Entity Look" }, { 0x21, "Relative Entity Move + Look" }, { 0x22, "Entity Teleport" }, { 0x32, "Pre-Chunk" }, { 0x33, "Map Chunk" }, { 0x34, "Multi Block Change" }, { 0x35, "Block Change" }, { 0x3b, "Complex Entity"}, { 0xFF, "Kick" }, { 0, NULL } }; static const value_string directionnames[] = { {0, "-Y"}, {1, "+Y"}, {2, "-Z"}, {3, "+Z"}, {4, "-X"}, {5, "+X"}, {0, NULL} }; #ifndef ENABLE_STATIC G_MODULE_EXPORT void plugin_register(void) { /* register the new protocol, protocol fields, and subtrees */ if (proto_minecraft == -1) { /* execute protocol initialization only once */ proto_register_minecraft(); } } G_MODULE_EXPORT void plugin_reg_handoff(void) { proto_reg_handoff_minecraft(); } #endif static int ett_mc = -1; /* Setup protocol subtree array */ static int *ett[] = { &ett_mc }; static gint hf_mc_data = -1; static gint hf_mc_type = -1; static gint hf_mc_server_name = -1; static gint hf_mc_motd = -1; static gint hf_mc_username = -1; static gint hf_mc_password = -1; static gint hf_mc_serverid = -1; static gint hf_mc_handshake_username = -1; static gint hf_mc_chat = -1; static gint hf_mc_time = -1; static gint hf_mc_loaded = -1; static gint hf_mc_x = -1; static gint hf_mc_y = -1; static gint hf_mc_z = -1; static gint hf_mc_stance = -1; static gint hf_mc_rotation = -1; static gint hf_mc_pitch = -1; static gint hf_mc_status = -1; static gint hf_mc_ybyte = -1; static gint hf_mc_yshort = -1; static gint hf_mc_dig = -1; static gint hf_mc_block_type = -1; static gint hf_mc_direction = -1; static gint hf_mc_xint = -1; static gint hf_mc_yint = -1; static gint hf_mc_zint = -1; static gint hf_mc_unique_id = -1; static gint hf_mc_unknown_byte = -1; static gint hf_mc_rotation_byte = -1; static gint hf_mc_pitch_byte = -1; static gint hf_mc_size_x = -1; static gint hf_mc_size_y = -1; static gint hf_mc_size_z = -1; static gint hf_mc_block_type_byte = -1; static gint hf_mc_block_meta_byte = -1; void proto_register_minecraft(void) { module_t *module; if (proto_minecraft == -1) { static hf_register_info hf[] = { { &hf_mc_data, {"Data", "mc.data", FT_NONE, BASE_NONE, NULL, 0x0, "Packet Data", HFILL} }, { &hf_mc_type, { "Type", "mc.type", FT_UINT8, BASE_DEC, VALS(packettypenames), 0x0, "Packet Type", HFILL } }, { &hf_mc_server_name, {"Server Name", "mc.server_name", FT_STRING, BASE_NONE, NULL, 0x0, "Text", HFILL} }, { &hf_mc_motd, {"MOTD", "mc.motd", FT_STRING, BASE_NONE, NULL, 0x0, "Text", HFILL} }, { &hf_mc_username, {"Username", "mc.username", FT_STRING, BASE_NONE, NULL, 0x0, "Text", HFILL} }, { &hf_mc_password, {"Password", "<PASSWORD>", FT_STRING, BASE_NONE, NULL, 0x0, "Text", HFILL} }, { &hf_mc_serverid, {"Server ID", "mc.server_id", FT_STRING, BASE_NONE, NULL, 0x0, "Text", HFILL} }, { &hf_mc_handshake_username, {"Handshake Username", "mc.handshake_username", FT_STRING, BASE_NONE, NULL, 0x0, "Text", HFILL} }, { &hf_mc_chat, {"Chat", "mc.chat", FT_STRING, BASE_NONE, NULL, 0x0, "Text", HFILL} }, { &hf_mc_time, {"Time", "mc.time", FT_INT64, BASE_DEC, NULL, 0x0, "Update Time", HFILL } }, { &hf_mc_loaded, {"Loaded", "mc.loaded", FT_BOOLEAN, BASE_DEC, NULL, 0x0, "Loaded", HFILL } }, { &hf_mc_x, {"X", "mc.x", FT_DOUBLE, BASE_DEC, NULL, 0x0, "X Coord", HFILL } }, { &hf_mc_y, {"Y", "mc.y", FT_DOUBLE, BASE_DEC, NULL, 0x0, "Y Coord", HFILL } }, { &hf_mc_z, {"Z", "mc.z", FT_DOUBLE, BASE_DEC, NULL, 0x0, "Z Coord", HFILL } }, { &hf_mc_stance, {"Stance", "mc.stance", FT_DOUBLE, BASE_DEC, NULL, 0x0, "Stance", HFILL } }, { &hf_mc_rotation, {"Rotation", "mc.rotation", FT_FLOAT, BASE_DEC, NULL, 0x0, "Rotation", HFILL } }, { &hf_mc_pitch, {"Pitch", "mc.pitch", FT_FLOAT, BASE_DEC, NULL, 0x0, "Pitch", HFILL } }, { &hf_mc_status, {"Status", "mc.status", FT_INT8, BASE_DEC, NULL, 0x0, "Status", HFILL } }, { &hf_mc_ybyte, {"Y", "mc.ybyte", FT_INT8, BASE_DEC, NULL, 0x0, "Y Coord", HFILL } }, { &hf_mc_yshort, {"Y", "mc.yshort", FT_INT16, BASE_DEC, NULL, 0x0, "Y Coord", HFILL } }, { &hf_mc_dig, {"Dig", "mc.dig", FT_INT8, BASE_DEC, NULL, 0x0, "Digging/Stopped/Broken", HFILL } }, { &hf_mc_block_type, {"Block/Item Type", "mc.block_type", FT_INT16, BASE_DEC, NULL, 0x0, "Block/Item Type", HFILL } }, { &hf_mc_direction, {"Direction", "mc.direction", FT_INT8, BASE_DEC, VALS(directionnames), 0x0, "Direction", HFILL } }, { &hf_mc_xint, {"X", "mc.xint", FT_INT32, BASE_DEC, NULL, 0x0, "X Coord", HFILL } }, { &hf_mc_yint, {"Y", "mc.yint", FT_INT32, BASE_DEC, NULL, 0x0, "Y Coord", HFILL } }, { &hf_mc_zint, {"Z", "mc.zint", FT_INT32, BASE_DEC, NULL, 0x0, "Z Coord", HFILL } }, { &hf_mc_unique_id, {"Unique ID", "mc.unique_id", FT_INT32, BASE_DEC, NULL, 0x0, "Unique ID", HFILL } }, { &hf_mc_unknown_byte, {"Unknown Byte", "mc.unknown_byte", FT_INT8, BASE_DEC, NULL, 0x0, "Unknown Byte", HFILL } }, { &hf_mc_rotation_byte, {"Rotation Byte", "mc.rotation_byte", FT_INT8, BASE_DEC, NULL, 0x0, "Rotation Byte", HFILL } }, { &hf_mc_pitch_byte, {"Pitch", "mc.pitch_byte", FT_INT8, BASE_DEC, NULL, 0x0, "Pitch Byte", HFILL } }, { &hf_mc_size_x, {"Size X", "mc.size_x", FT_INT8, BASE_DEC, NULL, 0x0, "X Size", HFILL } }, { &hf_mc_size_y, {"Size Y", "mc.size_y", FT_INT8, BASE_DEC, NULL, 0x0, "Y Size", HFILL } }, { &hf_mc_size_z, {"Size Z", "mc.size_z", FT_INT8, BASE_DEC, NULL, 0x0, "Z Size", HFILL } }, { &hf_mc_block_type_byte, {"Block/Item Type", "mc.block_type_byte", FT_INT8, BASE_DEC, NULL, 0x0, "Block/Item Type", HFILL } }, { &hf_mc_block_meta_byte, {"Block Metadata", "mc.block_meta_byte", FT_INT8, BASE_DEC, NULL, 0x0, "Block Metadata", HFILL } }, }; proto_minecraft = proto_register_protocol ( "Minecraft Alpha SMP Protocol", /* name */ "Minecraft", /* short name */ "mc" /* abbrev */ ); module = prefs_register_protocol(proto_minecraft, proto_reg_handoff_minecraft); proto_register_field_array(proto_minecraft, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); } } void proto_reg_handoff_minecraft(void) { static int Initialized=FALSE; /* register with wireshark to dissect udp packets on port 3001 */ if (!Initialized) { minecraft_handle = create_dissector_handle(dissect_minecraft, proto_minecraft); dissector_add("tcp.port", 25565, minecraft_handle); } } static void add_login_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { guint16 strlen1, strlen2; strlen1 = tvb_get_ntohs( tvb, offset + 5 ); proto_tree_add_item(tree, hf_mc_server_name, tvb, offset + 5, strlen1, FALSE); strlen2 = tvb_get_ntohs( tvb, offset + 5 + strlen1 + 2 ); proto_tree_add_item(tree, hf_mc_motd, tvb, offset + 5 + strlen1 + 2, strlen2, FALSE); } static void add_handshake_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { guint16 strlen1; strlen1 = tvb_get_ntohs( tvb, offset + 1 ); proto_tree_add_item(tree, hf_mc_serverid, tvb, offset + 3, strlen1, FALSE); } static void add_chat_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { guint16 strlen1; strlen1 = tvb_get_ntohs( tvb, offset + 1 ); proto_tree_add_item(tree, hf_mc_chat, tvb, offset + 3, strlen1, FALSE); } static void add_time_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { guint64 time; time = tvb_get_ntoh64(tvb, offset + 1 ); proto_tree_add_item(tree, hf_mc_time, tvb, offset + 1, 8, FALSE); } static void add_loaded_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { proto_tree_add_item(tree, hf_mc_loaded, tvb, offset + 1, 1, FALSE); } static void add_player_position_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { /* gdouble x,y,z,s; x = tvb_get_gdouble(tvb, offset + 1); y = tvb_get_gdouble(tvb, offset + 9); s = tvb_get_gdouble(tvb, offset + 17); z = tvb_get_gdouble(tvb, offset + 25); */ proto_tree_add_item(tree, hf_mc_x, tvb, offset + 1, 8, FALSE); proto_tree_add_item(tree, hf_mc_y, tvb, offset + 9, 8, FALSE); proto_tree_add_item(tree, hf_mc_stance, tvb, offset + 17, 8, FALSE); proto_tree_add_item(tree, hf_mc_z, tvb, offset + 25, 8, FALSE); } static void add_player_look_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { proto_tree_add_item(tree, hf_mc_rotation, tvb, offset + 1, 4, FALSE); proto_tree_add_item(tree, hf_mc_pitch, tvb, offset + 5, 4, FALSE); } static void add_player_move_look_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { proto_tree_add_item(tree, hf_mc_x, tvb, offset + 1, 8, FALSE); proto_tree_add_item(tree, hf_mc_y, tvb, offset + 9, 8, FALSE); proto_tree_add_item(tree, hf_mc_stance, tvb, offset + 17, 8, FALSE); proto_tree_add_item(tree, hf_mc_z, tvb, offset + 25, 8, FALSE); proto_tree_add_item(tree, hf_mc_rotation, tvb, offset + 33, 4, FALSE); proto_tree_add_item(tree, hf_mc_pitch, tvb, offset + 37, 4, FALSE); } static void add_block_dig_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { proto_tree_add_item(tree, hf_mc_status, tvb, offset + 1, 1, FALSE); proto_tree_add_item(tree, hf_mc_xint, tvb, offset + 2, 4, FALSE); proto_tree_add_item(tree, hf_mc_ybyte, tvb, offset + 6, 1, FALSE); proto_tree_add_item(tree, hf_mc_zint, tvb, offset + 7, 4, FALSE); } static void add_place_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { proto_tree_add_item(tree, hf_mc_block_type, tvb, offset + 1, 2, FALSE); proto_tree_add_item(tree, hf_mc_xint, tvb, offset + 3, 4, FALSE); proto_tree_add_item(tree, hf_mc_ybyte, tvb, offset + 7, 1, FALSE); proto_tree_add_item(tree, hf_mc_zint, tvb, offset + 8, 4, FALSE); proto_tree_add_item(tree, hf_mc_direction, tvb, offset + 12, 1, FALSE); } static void add_block_item_switch_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { } static void add_add_to_inventory_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { } static void add_arm_animation_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { } static void add_named_entity_spawn_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { } static void add_pickup_spawn_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { proto_tree_add_item(tree, hf_mc_unique_id, tvb, offset + 1, 4, FALSE); proto_tree_add_item(tree, hf_mc_block_type, tvb, offset + 5, 2, FALSE); proto_tree_add_item(tree, hf_mc_unknown_byte, tvb, offset + 7, 1, FALSE); proto_tree_add_item(tree, hf_mc_xint, tvb, offset + 8, 4, FALSE); proto_tree_add_item(tree, hf_mc_yint, tvb, offset + 12, 4, FALSE); proto_tree_add_item(tree, hf_mc_zint, tvb, offset + 16, 4, FALSE); proto_tree_add_item(tree, hf_mc_rotation_byte, tvb, offset + 20, 1, FALSE); proto_tree_add_item(tree, hf_mc_pitch_byte, tvb, offset + 21, 1, FALSE); proto_tree_add_item(tree, hf_mc_unknown_byte, tvb, offset + 22, 1, FALSE); } static void add_pre_chunk_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { proto_tree_add_item(tree, hf_mc_xint, tvb, offset + 1, 4, FALSE); proto_tree_add_item(tree, hf_mc_zint, tvb, offset + 5, 4, FALSE); proto_tree_add_item(tree, hf_mc_ybyte, tvb, offset + 9, 1, FALSE); } static void add_map_chunk_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { proto_tree_add_item(tree, hf_mc_xint, tvb, offset + 1, 4, FALSE); proto_tree_add_item(tree, hf_mc_yshort, tvb, offset + 5, 2, FALSE); proto_tree_add_item(tree, hf_mc_zint, tvb, offset + 7, 4, FALSE); proto_tree_add_item(tree, hf_mc_size_x, tvb, offset + 11, 1, FALSE); proto_tree_add_item(tree, hf_mc_size_y, tvb, offset + 12, 1, FALSE); proto_tree_add_item(tree, hf_mc_size_z, tvb, offset + 13, 1, FALSE); } static void add_block_change_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { proto_tree_add_item(tree, hf_mc_xint, tvb, offset + 1, 4, FALSE); proto_tree_add_item(tree, hf_mc_ybyte, tvb, offset + 5, 1, FALSE); proto_tree_add_item(tree, hf_mc_zint, tvb, offset + 6, 4, FALSE); proto_tree_add_item(tree, hf_mc_block_type_byte, tvb, offset + 10, 1, FALSE); proto_tree_add_item(tree, hf_mc_block_meta_byte, tvb, offset + 11, 1, FALSE); } static void add_spawn_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { proto_tree_add_item(tree, hf_mc_xint, tvb, offset + 1, 4, FALSE); proto_tree_add_item(tree, hf_mc_yint, tvb, offset + 5, 4, FALSE); proto_tree_add_item(tree, hf_mc_zint, tvb, offset + 9, 4, FALSE); } static void add_complex_entity_details( proto_tree *tree, tvbuff_t *tvb, packet_info *pinfo, guint32 offset) { proto_tree_add_item(tree, hf_mc_xint, tvb, offset + 1, 4, FALSE); proto_tree_add_item(tree, hf_mc_yshort, tvb, offset + 5, 2, FALSE); proto_tree_add_item(tree, hf_mc_zint, tvb, offset + 7, 4, FALSE); } static void dissect_minecraft_message(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint8 type, guint32 offset, guint32 length) { if (check_col(pinfo->cinfo, COL_PROTOCOL)) col_set_str(pinfo->cinfo, COL_PROTOCOL, PROTO_TAG_MC); /* Clear out stuff in the info column */ // if(check_col(pinfo->cinfo,COL_INFO)){ // col_clear(pinfo->cinfo,COL_INFO); // } if (check_col(pinfo->cinfo, COL_INFO)) { col_add_fstr(pinfo->cinfo, COL_INFO, pinfo->match_port == pinfo->destport ? "C->S" : "S->C" ": %d > %d Info Type:[%s]", pinfo->srcport, pinfo->destport, val_to_str(type, packettypenames, "Unknown Type:0x%02x")); } if ( tree ) { mc_item = proto_tree_add_item(tree, proto_minecraft, tvb, offset, length, FALSE); mc_tree = proto_item_add_subtree(mc_item, ett_mc); proto_tree_add_item(mc_tree, hf_mc_type, tvb, offset, 1, FALSE); proto_tree_add_item(mc_tree, hf_mc_data, tvb, offset, length, FALSE); switch (type) { case 0x01: add_login_details(mc_tree, tvb, pinfo, offset); break; case 0x02: add_handshake_details(mc_tree, tvb, pinfo, offset); break; case 0x03: add_chat_details(mc_tree, tvb, pinfo, offset); break; case 0x04: add_time_details(mc_tree, tvb, pinfo, offset); break; case 0x06: add_spawn_details(mc_tree, tvb, pinfo, offset); break; case 0x0A: add_loaded_details(mc_tree, tvb, pinfo, offset); break; case 0x0B: add_player_position_details(mc_tree, tvb, pinfo, offset); break; case 0x0C: add_player_look_details(mc_tree, tvb, pinfo, offset); break; case 0x0D: add_player_move_look_details(mc_tree, tvb, pinfo, offset); break; case 0x0E: add_block_dig_details(mc_tree, tvb, pinfo, offset); break; case 0x0F: add_place_details(mc_tree, tvb, pinfo, offset); break; case 0x10: add_block_item_switch_details(mc_tree, tvb, pinfo, offset); break; case 0x11: add_add_to_inventory_details(mc_tree, tvb, pinfo, offset); break; case 0x12: add_arm_animation_details(mc_tree, tvb, pinfo, offset); break; case 0x14: add_named_entity_spawn_details(mc_tree, tvb, pinfo, offset); break; case 0x15: add_pickup_spawn_details(mc_tree, tvb, pinfo, offset); break; /* ... */ case 0x32: add_pre_chunk_details(mc_tree, tvb, pinfo, offset); break; case 0x33: add_map_chunk_details(mc_tree, tvb, pinfo, offset); break; case 0x35: add_block_change_details(mc_tree, tvb, pinfo, offset); break; case 0x3b: add_complex_entity_details(mc_tree, tvb, pinfo, offset); break; } } } guint get_minecraft_packet_len(guint8 type,guint offset, guint available, tvbuff_t *tvb) { guint len=-1; switch (type) { case 0x00: len = 1; break; case 0x01: { int len_strA, len_strB; if ( available >= 7 ) { len_strA = tvb_get_ntohs(tvb, offset + 5); if ( available >= 9 + len_strA ) { len_strB = tvb_get_ntohs(tvb, offset + 7 + len_strA); len = 5 + (2 + len_strA) + (2 + len_strB); } } } break; case 0x02: if ( available >= 3 ) { len = 3 + tvb_get_ntohs(tvb, offset + 1); } break; case 0x03: if ( available >= 3 ) { len = 3 + tvb_get_ntohs(tvb, offset + 1); } break; case 0x04: len = 9; break; case 0x05: { if ( available >= 7 ) { int num_inv, o, size, count; gint16 val; num_inv = tvb_get_ntohs(tvb, offset + 5); o = offset + 7; size = 0; count = 0; while ( o-offset < available && available -(o-offset) >= 2 && count != num_inv ) { count++; val = tvb_get_ntohs(tvb, o); if ( val == -1 ) { size += 2; o += 2; } else { size += 5; o += 5; } } if ( count == num_inv ) { len = 7 + size; } } } break; case 0x06: len = 13; break; case 0x0A: len = 2; break; case 0x0B: len = 34; break; case 0x0C: len = 10; break; case 0x0D: len = 42; break; case 0x0E: len = 12; break; case 0x0F: len = 13; break; case 0x10: len = 7; break; case 0x11: len = 6; break; case 0x12: len = 6; break; case 0x15: len = 23; break; case 0x16: len = 9; break; case 0x17: len = 18; break; case 0x18: len = 20; break; case 0x1D: len = 5; break; case 0x1E: len = 5; break; case 0x1F: len = 8; break; case 0x20: len = 7; break; case 0x21: len = 10; break; case 0x22: len = 19; break; case 0x32: len = 10; break; case 0x33: if ( available >= 18 ) { len = 18 + tvb_get_ntohl(tvb, offset + 14); } break; case 0x34: if ( available >= 11 ) { // the size we get here is number of elements in the arrays // and there are 3 arrays, a short, and two bytes, so multiply by 4 len = 11 + (4 * tvb_get_ntohs(tvb, offset + 9)); } break; case 0x35: len = 12; break; case 0x3b: if ( available >= 13 ) { len = 13 + tvb_get_ntohs(tvb, offset + 11); } break; case 0xff: if ( available >= 3 ) { len = 3 + tvb_get_ntohs(tvb, offset + 1); } break; default: printf("Unknown packet: 0x%x\n", type); len = -1; } return len; } #define FRAME_HEADER_LEN 17 void dissect_minecraft(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { guint8 packet; guint offset=0; while (offset < tvb_reported_length(tvb)) { packet = tvb_get_guint8(tvb, offset); gint available = tvb_reported_length_remaining(tvb, offset); gint len = get_minecraft_packet_len(packet, offset, available, tvb); if (len == -1 || len > available) { pinfo->desegment_offset = offset; if ( len == -1 ) { pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT; } else { pinfo->desegment_len = len - available; } return; } dissect_minecraft_message(tvb, pinfo, tree, packet, offset, len); offset += len; } } <file_sep># Modify to point to your Wireshark and glib include directories INCS = -I/usr/include/wireshark -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include SRCS = packet-minecraft.c CC = gcc OBJS = $(foreach src, $(SRCS), $(src:.c=.o)) PLUGIN_NAME = packet-minecraft PLUGIN_DIR = $(HOME)/.wireshark/plugins PLUGIN = $(PLUGIN_DIR)/$(PLUGIN_NAME).so CFLAGS = -DHAVE_CONFIG_H $(INCS) -DINET6 -D_U_=__attribute__\(\(unused\)\) -Wall -Wpointer-arith -g -DXTHREADS -D_REENTRANT -DXUSE_MTSAFE_API -fPIC -DPIC $(PLUGIN) : $(OBJS) mkdir -p $(PLUGIN_DIR) $(CC) -shared $(OBJS) -o $@ %.o : %.c $(CC) -c $(CFLAGS) $< -o $@ clean: rm -f $(PLUGIN) $(OBJS)
62a5d01247a5537566ed028a9d7ee0bf0733ac62
[ "C", "Makefile" ]
2
C
Jc2k/minecraft-dissector
5a59426f6a36527b6d103829f76aa0b510156372
72caadd221dd61d1903157f08f6f71d1b7414d80
refs/heads/master
<repo_name>personalj/scriptum<file_sep>/js/main.js $( document ).ready(function() { $('[data-opener]').click(function() { $this = $(this); if($this.is('.active')) { $this.removeClass('active'); $('[data-target="'+$this.data('opener')+'"]').removeClass('active'); }else{ $this.addClass('active'); $('[data-target="'+$this.data('opener')+'"]').addClass('active'); } }); $('.works__grid').isotope({ itemSelector: '.works__grid-item', masonry: { gutter: 25 } }); var $grid = $('.works__grid').imagesLoaded( function() { $grid.isotope({ itemSelector: '.works__grid-item img', percentPosition: true, }); }); $('.works__item').click(function(){ $('.works__item').removeClass('active'); $(this).addClass('active'); var selector = $(this).attr('data-filter'); $('.works__grid').isotope({ filter: selector }); return false; }); $(".testimonials__list").lightSlider({ item: 1 }); $('.scroll-top').click(function(){ window.scrollTo(0, 0); }); }); $(document).ready(function(){ var show = true; var countbox = ".skills"; $(window).on("scroll load resize", function(){ if(!show) return false; var w_top = $(window).scrollTop(); var e_top = $(countbox).offset().top; var w_height = $(window).height(); var d_height = $(document).height(); var e_height = $(countbox).outerHeight(); if(w_top + 10 >= e_top || w_height + w_top == d_height || e_height + e_top < w_height){ $(".progress-bar__inner_design").addClass('active'); $(".progress-bar__inner_css").addClass('active'); $(".progress-bar__inner_javascript").addClass('active'); } }); $(window).scroll(function(){ var wScroll = $(this).scrollTop(); var e_height = $('.header').outerHeight(); if (wScroll >= e_height) { $(".nav__icon-wrap").addClass("is_active"); } else { $(".nav__icon-wrap").removeClass("is_active"); } }); // $('.fadeIn').addClass("hide").viewportChecker({ // classToAdd: 'visible animated fadeInUp', // offset: 100 // }); AOS.init({ easing: 'ease-in-out-sine' }); $('.nav__list a[href^="#"]').click( function(){ var scroll_el = $(this).attr('href'); if ($(scroll_el).length != 0) { $('html, body').animate({ scrollTop: $(scroll_el).offset().top }, 500); } return false; }); }); $(document).ready(function(){ $("#form").submit(function(e) { e.preventDefault(); var form_data = $(this).serialize(); $.ajax({ url: "send.php", type: "POST", data: form_data, success: function() { $('.contact__pop-up-wrap').addClass('active'); $('.contact__form-input').val(''); $('.contact__form-textarea').val(''); } }); }); $('.contact__pop-up-btn').click(function(){ $('.contact__pop-up-wrap').removeClass('active'); }); $(document).click( function(event){ if( $(event.target).closest('.contact__pop-up-wrap').length ) return; $('.contact__pop-up-wrap').removeClass('active'); event.stopPropagation(); }); });
0c78ccac94d20e201df7605d688a546471e232e3
[ "JavaScript" ]
1
JavaScript
personalj/scriptum
ecd473421b4a3f1c40f0abf211da79e13f265a78
1f86824bb37151d944231b1439260d0109603033
refs/heads/master
<file_sep>package com.blackbrackets.tvarkarastis; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v4.app.FragmentActivity; import android.util.Log; import com.google.android.gms.ads.AdView; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Calendar; /** * Created by Simonas on 2014.07.06. */ public class Utils { AdView adView; boolean running = true; Calendar c = Calendar.getInstance(); // Current Time int h = c.get(Calendar.HOUR_OF_DAY); int m = c.get(Calendar.MINUTE); int s = c.get(Calendar.SECOND); Context context; boolean notificationAlive; DatabaseHandler db; public Utils(Context context, DatabaseHandler db) { this.context = context; this.db = db; } public Utils(Context context) { this.context = context; } public boolean isNetworkAvailable(Activity _activity) { ConnectivityManager connectivityManager = (ConnectivityManager) _activity.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } public static void sendTracker(Context instance, String activity) { GoogleAnalytics analytics = GoogleAnalytics.getInstance(instance); Tracker t = analytics.newTracker(R.xml.global_tracker); t.setScreenName(activity); t.send(new HitBuilders.AppViewBuilder().build()); } public Pos findPosition(int hoursNow, int minutesNow) { if (hoursNow * 60 + minutesNow < db.getTimeTable(0).getIntStartH() * 60 + db.getTimeTable(0).getIntStartM()) { return new Pos(false, -1); } if (isTimeRight(true, 0, hoursNow, minutesNow)) { return new Pos(true, 0); } if (isTimeRight(false, 0, hoursNow, minutesNow)) { return new Pos(false, 0); } if (isTimeRight(true, 1, hoursNow, minutesNow)) { return new Pos(true, 1); } if (isTimeRight(false, 1, hoursNow, minutesNow)) { return new Pos(false, 1); } if (isTimeRight(true, 2, hoursNow, minutesNow)) { return new Pos(true, 2); } if (isTimeRight(false, 2, hoursNow, minutesNow)) { return new Pos(false, 2); } if (isTimeRight(true, 3, hoursNow, minutesNow)) { return new Pos(true, 3); } if (isTimeRight(false, 3, hoursNow, minutesNow)) { return new Pos(false, 3); } if (isTimeRight(true, 4, hoursNow, minutesNow)) { return new Pos(true, 4); } if (isTimeRight(false, 4, hoursNow, minutesNow)) { return new Pos(false, 4); } if (isTimeRight(true, 5, hoursNow, minutesNow)) { return new Pos(true, 5); } if (isTimeRight(false, 5, hoursNow, minutesNow)) { return new Pos(false, 5); } if (isTimeRight(true, 6, hoursNow, minutesNow)) { return new Pos(true, 6); } if (isTimeRight(false, 6, hoursNow, minutesNow)) { return new Pos(false, 6); } if (isTimeRight(true, 7, hoursNow, minutesNow)) { return new Pos(true, 7); } if (isTimeRight(false, 7, hoursNow, minutesNow)) { return new Pos(false, 7); } if (isTimeRight(true, 8, hoursNow, minutesNow)) { return new Pos(true, 8); } // Out return new Pos(false, 0); } public int getFirstLecturePos(int day) { if (db.getLecture(day, 0).getName().length() != 0) return 0; else if (db.getLecture(day, 1).getName().length() != 0) return 1; else if (db.getLecture(day, 2).getName().length() != 0) return 2; else if (db.getLecture(day, 3).getName().length() != 0) return 3; else if (db.getLecture(day, 4).getName().length() != 0) return 4; else if (db.getLecture(day, 5).getName().length() != 0) return 5; else if (db.getLecture(day, 6).getName().length() != 0) return 6; else if (db.getLecture(day, 7).getName().length() != 0) return 7; else if (db.getLecture(day, 8).getName().length() != 0) return 8; // Error else return 0; } public void restartServices() { SharedPreferences.Editor editor = sharedPrefs().edit(); // Clear Notification and Restart it. restartNotificationReceiver(sharedPrefs()); // Restart Sound. restartSoundReceiver(sharedPrefs()); // Find longest day and get last lecture's pos editor.putInt("maxLecturePos", returnMaxPos()); editor.commit(); } // Returns Longest Day Size private int returnMaxPos() { int maxPos = -1; for (int day = 0; day < 5; day++) { if (maxPos < getLastLecturePos(day)) maxPos = getLastLecturePos(day); } return maxPos; } public int getLastLecturePos(int day) { if (db.getLecture(day, 8).getName().length() != 0) return 8; else if (db.getLecture(day, 7).getName().length() != 0) return 7; else if (db.getLecture(day, 6).getName().length() != 0) return 6; else if (db.getLecture(day, 5).getName().length() != 0) return 5; else if (db.getLecture(day, 4).getName().length() != 0) return 4; else if (db.getLecture(day, 3).getName().length() != 0) return 3; else if (db.getLecture(day, 2).getName().length() != 0) return 2; else if (db.getLecture(day, 1).getName().length() != 0) return 1; else if (db.getLecture(day, 0).getName().length() != 0) return 0; // Error else return -1; } public void restartSoundReceiver(SharedPreferences sp) { if (sp.getString("sound", "0") != "0") setAlarmTimer(true, 0, SoundReceiver.class); } public void restartNotificationReceiver(SharedPreferences sp) { if (sp.getBoolean("notifications", false)) setAlarmTimer(true, 0, NotificationReceiver.class); else new NotificationReceiver().cancelNotification(context); } public int timeLeftInMin(boolean isLecture, int pos) { int maxPos = getLastLecturePos(getCurrentDay()); if (isLecture) { // Pamoka END if (db.getLecture(getCurrentDay(), pos).getName().length() != 0) { return (db.getTimeTable(pos).getIntEndH() * 60 + db.getTimeTable(pos).getIntEndM()) - (h * 60 + m); } if (db.getLecture(getCurrentDay(), pos).getName().length() == 0) { int _pos = pos; if (pos == maxPos) { return (db.getTimeTable(_pos).getIntEndH() * 60 + db.getTimeTable(_pos).getIntEndM()) - (h * 60 + m); } else { while (db.getLecture(getCurrentDay(), _pos).getName().length() == 0 && _pos <= maxPos) _pos++; return (db.getTimeTable(_pos).getIntStartH() * 60 + db.getTimeTable(_pos).getIntStartM()) - (h * 60 + m); } } } if (!isLecture) { int _pos = pos + 1; while (db.getLecture(getCurrentDay(), _pos).getName().length() == 0 && _pos <= maxPos) _pos++; return (db.getTimeTable(_pos).getIntStartH() * 60 + db.getTimeTable(_pos).getIntStartM()) - (h * 60 + m); } // Error return 0; } public int nextLecturesPos(int pos) { int maxPos = getLastLecturePos(getCurrentDay()); pos++; // Pamoka END if (db.getLecture(getCurrentDay(), pos).getName().length() != 0) { return pos; } else { int _pos = pos; while (db.getLecture(getCurrentDay(), _pos).getName().length() == 0 && _pos <= maxPos) _pos++; return _pos; } } private boolean isTimeRight(boolean isLecture, int pos, int h, int m) { // Check if Lecture if (isLecture) { if ((h * 60 + m >= db.getTimeTable(pos).getIntStartH() * 60 + db.getTimeTable(pos).getIntStartM()) && (h * 60 + m < db.getTimeTable(pos).getIntEndH() * 60 + db.getTimeTable(pos).getIntEndM())) return true; else return false; } // Check if Recess else { if ((h * 60 + m >= db.getTimeTable(pos).getIntEndH() * 60 + db.getTimeTable(pos).getIntEndM()) && (h * 60 + m < db.getTimeTable(pos + 1).getIntStartH() * 60 + db.getTimeTable(pos + 1).getIntStartM())) return true; else return false; } } public int getRealCurrentDay() { Calendar calendar = Calendar.getInstance(); int current_day = calendar.get(Calendar.DAY_OF_WEEK); switch (current_day) { // Sek case 1: return 6; // Pir case 2: return 0; // Ant case 3: return 1; // Tre case 4: return 2; // Ket case 5: return 3; // Penk case 6: return 4; // Sest case 7: return 5; } return -1; } public int getCurrentDay() { Calendar calendar = Calendar.getInstance(); int hr = calendar.get(Calendar.HOUR_OF_DAY); int min = calendar.get(Calendar.MINUTE); int currentTimeInMins = hr * 60 + min; int current_day = calendar.get(Calendar.DAY_OF_WEEK); switch (current_day) { case 1: return 0; case 2: if (currentTimeInMins < db.getTimeTable(getLastLecturePos(0)).getIntEndH() * 60 + db.getTimeTable(getLastLecturePos(0)).getIntEndM()) { return 0; } else { return 1; } case 3: if (currentTimeInMins < db.getTimeTable(getLastLecturePos(1)).getIntEndH() * 60 + db.getTimeTable(getLastLecturePos(1)).getIntEndM()) { return 1; } else { return 2; } case 4: if (currentTimeInMins < db.getTimeTable(getLastLecturePos(2)).getIntEndH() * 60 + db.getTimeTable(getLastLecturePos(2)).getIntEndM()) { return 2; } else { return 3; } case 5: if (currentTimeInMins < db.getTimeTable(getLastLecturePos(3)).getIntEndH() * 60 + db.getTimeTable(getLastLecturePos(3)).getIntEndM()) { return 3; } else { return 4; } case 6: if (currentTimeInMins < db.getTimeTable(getLastLecturePos(4)).getIntEndH() * 60 + db.getTimeTable(getLastLecturePos(4)).getIntEndM()) { return 4; } else { return 5; } case 7: return 0; default: return 0; } } public void setAlarmTimer(final boolean startup, final int length_in_mills, final Class targetClass) { notificationAlive = true; new Thread(new Runnable() { @Override public void run() { Intent intent = new Intent(context, targetClass); PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager notificationAlarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); int offset; if (startup) { offset = 0; } // Corrects time offsets that happen over time else { offset = (Calendar.getInstance().get(Calendar.SECOND) * 1000); } // For >= KitKat if (android.os.Build.VERSION.SDK_INT >= 19) notificationAlarm.setExact(AlarmManager.RTC, length_in_mills + System.currentTimeMillis() - offset, alarmIntent); // For < KitKat else notificationAlarm.set(AlarmManager.RTC, length_in_mills + System.currentTimeMillis() - offset, alarmIntent); Log.d("Notification", "Refresh"); } }).start(); } public void cancelAlarmTimer(final Class targetClass) { Intent intent = new Intent(context, targetClass); PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager notificationAlarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); notificationAlarm.cancel(alarmIntent); } public SharedPreferences sharedPrefs() { return context.getSharedPreferences("com.blackbrackets.tvarkarastis_preferences", context.MODE_PRIVATE); } public DatabaseHandler db() { return db; } public void setTimeTable(final FragmentActivity activity, final String startTime, final int lectureDur, final int recessDur, final int longRecessDur, final boolean longRecessPos[]) { new Thread(new Runnable() { @Override public void run() { String[] startHM = startTime.split(":"); int startH = Integer.valueOf(startHM[0]); int startM = Integer.valueOf(startHM[1]); int endH; int endM; Log.d("Time", "Set time"); // Nope? K for (int pos = 0; pos < 9; pos++) { endH = startH; endM = startM + lectureDur; while (endM >= 60) { endM -= 60; endH++; } NumberFormat formatter = new DecimalFormat("00"); db.updateTimeTable(new TimeRow(pos, String.valueOf(startH), formatter.format(startM), String.valueOf(endH), formatter.format(endM))); // Add Recess time startH = endH; if (pos < 8) { if (longRecessPos[pos]) { Log.d("TimeTable", "Add Long Recess"); startM = endM + longRecessDur; } else { startM = endM + recessDur; } } while (endM >= 60) { endM -= 60; endH++; } while (startM >= 60) { startM -= 60; startH++; } } } }).start(); } public boolean isAlarmAlive(final Class targetClass) { Intent intent = new Intent(context, targetClass); return (PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_NO_CREATE) != null); } public boolean tableEndOutBounds(final String startTime, final int lectureDur, final int recessDur, final int longRecessDur, final boolean longRecessPos[]) { String[] startHM = startTime.split(":"); int startH = Integer.valueOf(startHM[0]); int startM = Integer.valueOf(startHM[1]); int endH; int endM; for (int pos = 0; pos < 9; pos++) { endH = startH; endM = startM + lectureDur; while (endM >= 60) { endM -= 60; endH++; } if (endH >= 24) { return false; } startH = endH; if (pos < 8) { if (longRecessPos[pos]) { startM = endM + longRecessDur; } else { startM = endM + recessDur; } } while (endM >= 60) { endM -= 60; endH++; } while (startM >= 60) { startM -= 60; startH++; } } return true; } }<file_sep>package com.blackbrackets.tvarkarastis; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.doomonafireball.betterpickers.timepicker.TimePickerBuilder; import com.doomonafireball.betterpickers.timepicker.TimePickerDialogFragment; import java.text.DecimalFormat; import java.text.NumberFormat; public class TimeManual extends Fragment { FragmentManager fManager; TextView start1, end1, start2, end2, start3, end3, start4, end4, start5, end5, start6, end6, start7, end7, start8, end8, start9, end9; DatabaseHandler db; Utils utils; @Override public void onDestroy() { Log.d("Destroy", "Destroy"); super.onDestroy(); db.close(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View main = inflater.inflate(R.layout.time_manual, container, false); db = new DatabaseHandler(getActivity()); utils = new Utils(getActivity(), db); fManager = getFragmentManager(); start1 = (TextView) main.findViewById(R.id.s1); end1 = (TextView) main.findViewById(R.id.e1); start2 = (TextView) main.findViewById(R.id.s2); end2 = (TextView) main.findViewById(R.id.e2); start3 = (TextView) main.findViewById(R.id.s3); end3 = (TextView) main.findViewById(R.id.e3); start4 = (TextView) main.findViewById(R.id.s4); end4 = (TextView) main.findViewById(R.id.e4); start5 = (TextView) main.findViewById(R.id.s5); end5 = (TextView) main.findViewById(R.id.e5); start6 = (TextView) main.findViewById(R.id.s6); end6 = (TextView) main.findViewById(R.id.e6); start7 = (TextView) main.findViewById(R.id.s7); end7 = (TextView) main.findViewById(R.id.e7); start8 = (TextView) main.findViewById(R.id.s8); end8 = (TextView) main.findViewById(R.id.e8); start9 = (TextView) main.findViewById(R.id.s9); end9 = (TextView) main.findViewById(R.id.e9); setContentText(); editDialog(start1, 0, true); editDialog(start2, 1, true); editDialog(start3, 2, true); editDialog(start4, 3, true); editDialog(start5, 4, true); editDialog(start6, 5, true); editDialog(start7, 6, true); editDialog(start8, 7, true); editDialog(start9, 8, true); editDialog(end1, 0, false); editDialog(end2, 1, false); editDialog(end3, 2, false); editDialog(end4, 3, false); editDialog(end5, 4, false); editDialog(end6, 5, false); editDialog(end7, 6, false); editDialog(end8, 7, false); editDialog(end9, 8, false); return main; } private void editDialog(TextView button, final int pos, final boolean isStart) { button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TimePickerBuilder dpb = new TimePickerBuilder() .setFragmentManager(fManager) .setStyleResId(R.style.BetterPickersDialogFragment); dpb.show(); dpb.addTimePickerDialogHandler(new TimePickerDialogFragment.TimePickerDialogHandler() { @Override public void onDialogTimeSet(int i, final int i2, final int i3) { Thread update = new Thread(new Runnable() { @Override public void run() { SharedPreferences sp = utils.sharedPrefs(); NumberFormat formatter = new DecimalFormat("00"); String h = String.valueOf(i2); String m = formatter.format(i3); // Lecture Beginning Time if (isStart) db.updateTimeTable(new TimeRow(pos, h, m, db.getTimeTable(pos).getStringEndH(), db.getTimeTable(pos).getStringEndM())); // Lecture Ending Time if (!isStart) db.updateTimeTable(new TimeRow(pos, db.getTimeTable(pos).getStringStartH(), db.getTimeTable(pos).getStringStartM(), h, m)); setContentText(); } }); update.start(); } }); } }); } public void setContentText() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { start1.setText(db.getTimeTable(0).getStringStartH() + ":" + db.getTimeTable(0).getStringStartM()); end1.setText(db.getTimeTable(0).getStringEndH() + ":" + db.getTimeTable(0).getStringEndM()); start2.setText(db.getTimeTable(1).getStringStartH() + ":" + db.getTimeTable(1).getStringStartM()); end2.setText(db.getTimeTable(1).getStringEndH() + ":" + db.getTimeTable(1).getStringEndM()); start3.setText(db.getTimeTable(2).getStringStartH() + ":" + db.getTimeTable(2).getStringStartM()); end3.setText(db.getTimeTable(2).getStringEndH() + ":" + db.getTimeTable(2).getStringEndM()); start4.setText(db.getTimeTable(3).getStringStartH() + ":" + db.getTimeTable(3).getStringStartM()); end4.setText(db.getTimeTable(3).getStringEndH() + ":" + db.getTimeTable(3).getStringEndM()); start5.setText(db.getTimeTable(4).getStringStartH() + ":" + db.getTimeTable(4).getStringStartM()); end5.setText(db.getTimeTable(4).getStringEndH() + ":" + db.getTimeTable(4).getStringEndM()); start6.setText(db.getTimeTable(5).getStringStartH() + ":" + db.getTimeTable(5).getStringStartM()); end6.setText(db.getTimeTable(5).getStringEndH() + ":" + db.getTimeTable(5).getStringEndM()); start7.setText(db.getTimeTable(6).getStringStartH() + ":" + db.getTimeTable(6).getStringStartM()); end7.setText(db.getTimeTable(6).getStringEndH() + ":" + db.getTimeTable(6).getStringEndM()); start8.setText(db.getTimeTable(7).getStringStartH() + ":" + db.getTimeTable(7).getStringStartM()); end8.setText(db.getTimeTable(7).getStringEndH() + ":" + db.getTimeTable(7).getStringEndM()); start9.setText(db.getTimeTable(8).getStringStartH() + ":" + db.getTimeTable(8).getStringStartM()); end9.setText(db.getTimeTable(8).getStringEndH() + ":" + db.getTimeTable(8).getStringEndM()); } }); } }<file_sep>package com.blackbrackets.tvarkarastis; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.AudioManager; import android.support.v4.app.NotificationCompat; import android.util.Log; import java.util.Calendar; import java.util.GregorianCalendar; public class NotificationReceiver extends BroadcastReceiver { public NotificationReceiver() { } @Override public void onReceive(Context context, Intent intent) { // an Intent broadcast. DatabaseHandler db = new DatabaseHandler(context); Utils utils = new Utils(context, db); SharedPreferences spPreferences = utils.sharedPrefs(); AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); Calendar c = Calendar.getInstance(); int h = c.get(Calendar.HOUR_OF_DAY); int m = c.get(Calendar.MINUTE); int currentDay = utils.getCurrentDay(); int realCurrentDay = utils.getRealCurrentDay(); int startPos = utils.getFirstLecturePos(realCurrentDay); int endPos = utils.getLastLecturePos(realCurrentDay); // School Starts int startH = db.getTimeTable(startPos).getIntStartH(); int startM = db.getTimeTable(startPos).getIntStartM(); // School Ends int endH = db.getTimeTable(endPos).getIntEndH(); int endM = db.getTimeTable(endPos).getIntEndM(); Pos pos = utils.findPosition(h, m); int timeLeft = utils.timeLeftInMin(pos.isLecture, pos.getPosition()); String currentLecture = ""; // If != *Langas* if (pos.isLecture && db.getLecture(currentDay, pos.getPosition()).getName().length() != 0) { currentLecture = "Dabar " + db.getLecture(realCurrentDay, pos.getPosition()).getName(); } else { currentLecture = "Sekanti " + db.getLecture(realCurrentDay, utils.nextLecturesPos(pos.getPosition())).getName(); } // During School if ((h * 60 + m >= startH * 60 + startM) && (h * 60 + m < endH * 60 + endM) && realCurrentDay != 5 && realCurrentDay != 6 && realCurrentDay != -1) { // Show Notification if(spPreferences.getBoolean("notifications", false)) { new MainActivity().finish(); Intent noteIntent = new Intent (context, MainActivity.class); intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pend = PendingIntent.getActivity(context, 0, noteIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.ic_launcher_bw) .setContentTitle(currentLecture) .setContentText("Liko " + timeLeft + " min.") .setContentIntent(pend); // TODO MORE ICONS THIS if(true) { if(android.os.Build.VERSION.SDK_INT >= 16) mBuilder.setPriority(Notification.PRIORITY_MIN); } // if(timeLeft == 5) mBuilder.setSmallIcon(R.drawable.five); // else if(timeLeft == 4) mBuilder.setSmallIcon(R.drawable.four); // else if(timeLeft == 3) mBuilder.setSmallIcon(R.drawable.three); // else if(timeLeft == 2) mBuilder.setSmallIcon(R.drawable.two); // else if(timeLeft == 1) mBuilder.setSmallIcon(R.drawable.one); if(android.os.Build.VERSION.SDK_INT >= 11) mBuilder.setOngoing(true); NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); mNotificationManager.notify(69, mBuilder.build()); utils.setAlarmTimer(false, 60000, NotificationReceiver.class); } } // Not During School else { NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); mNotificationManager.cancel(69); Calendar cal = new GregorianCalendar(); if(realCurrentDay == 5 || realCurrentDay == 4 || realCurrentDay == 6) { switch (realCurrentDay) { case 4: cal.add(Calendar.DATE, 3); cal.set(Calendar.HOUR_OF_DAY, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartH()); cal.set(Calendar.MINUTE, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartM()); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Log.d("Sound", "Wait for (Fri)" + (double) (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000 / 60 + " mins."); utils.setAlarmTimer(true, (int) (cal.getTimeInMillis() - System.currentTimeMillis()), NotificationReceiver.class); break; case 5: cal.add(Calendar.DATE, 2); cal.set(Calendar.HOUR_OF_DAY, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartH()); cal.set(Calendar.MINUTE, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartM()); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Log.d("Sound", "Wait for (Sat)" + (double) (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000 / 60 + " mins."); utils.setAlarmTimer(true, (int) (cal.getTimeInMillis() - System.currentTimeMillis()), NotificationReceiver.class); break; case 6: cal.add(Calendar.DATE, 1); cal.set(Calendar.HOUR_OF_DAY, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartH()); cal.set(Calendar.MINUTE, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartM()); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Log.d("Sound", "Wait for (Sun)" + (double) (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000 / 60 + " mins."); utils.setAlarmTimer(true, (int) (cal.getTimeInMillis() - System.currentTimeMillis()), NotificationReceiver.class); break; } } else { // Day++ if((h * 60 + m) >= endH * 60 + endM) { cal.add(Calendar.DATE, 1); cal.set(Calendar.HOUR_OF_DAY, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartH()); cal.set(Calendar.MINUTE, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartM()); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Log.d("Sound", "Wait for (Other++) " + (double)(cal.getTimeInMillis() - System.currentTimeMillis())/1000/60 +" mins."); utils.setAlarmTimer(true, (int) (cal.getTimeInMillis() - System.currentTimeMillis()), NotificationReceiver.class); } // Current Day if((h * 60 + m) <= startH * 60 + startM) { cal.set(Calendar.HOUR_OF_DAY, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartH()); cal.set(Calendar.MINUTE, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartM()); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Log.d("Sound", "Wait for (Other)" + (double)(cal.getTimeInMillis() - System.currentTimeMillis())/1000/60 +" mins."); utils.setAlarmTimer(true, (int) (cal.getTimeInMillis() - System.currentTimeMillis()), NotificationReceiver.class); } } } } public void cancelNotification(Context context) { NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); mNotificationManager.cancel(69); } } <file_sep>package com.blackbrackets.tvarkarastis; import android.content.SharedPreferences; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Toast; public class TimeLongRecess extends Fragment { Utils utils; DatabaseHandler db; Toast toast = null; @Override public void onDestroy() { super.onDestroy(); db.close(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { db = new DatabaseHandler(getActivity()); utils = new Utils(getActivity(), db); toast = Toast.makeText(getActivity(), "Klaida pamokų laikas tęsiasi į kitą dieną.", Toast.LENGTH_SHORT); // Inflate the layout for this fragment View main = inflater.inflate(R.layout.time_long_recess, container, false); CheckBox chBx1, chBx2, chBx3, chBx4, chBx5, chBx6, chBx7, chBx8; chBx1 = (CheckBox) main.findViewById(R.id.checkBox1); chBx2 = (CheckBox) main.findViewById(R.id.checkBox2); chBx3 = (CheckBox) main.findViewById(R.id.checkBox3); chBx4 = (CheckBox) main.findViewById(R.id.checkBox4); chBx5 = (CheckBox) main.findViewById(R.id.checkBox5); chBx6 = (CheckBox) main.findViewById(R.id.checkBox6); chBx7 = (CheckBox) main.findViewById(R.id.checkBox7); chBx8 = (CheckBox) main.findViewById(R.id.checkBox8); SharedPreferences sp = utils.sharedPrefs(); chBx1.setChecked(sp.getBoolean("longRecess1", false)); chBx2.setChecked(sp.getBoolean("longRecess2", false)); chBx3.setChecked(sp.getBoolean("longRecess3", false)); chBx4.setChecked(sp.getBoolean("longRecess4", false)); chBx5.setChecked(sp.getBoolean("longRecess5", false)); chBx6.setChecked(sp.getBoolean("longRecess6", false)); chBx7.setChecked(sp.getBoolean("longRecess7", false)); chBx8.setChecked(sp.getBoolean("longRecess8", false)); onCheckBoxChangeListener(chBx1, "longRecess1"); onCheckBoxChangeListener(chBx2, "longRecess2"); onCheckBoxChangeListener(chBx3, "longRecess3"); onCheckBoxChangeListener(chBx4, "longRecess4"); onCheckBoxChangeListener(chBx5, "longRecess5"); onCheckBoxChangeListener(chBx6, "longRecess6"); onCheckBoxChangeListener(chBx7, "longRecess7"); onCheckBoxChangeListener(chBx8, "longRecess8"); return main; } private void onCheckBoxChangeListener(final CheckBox checkBox, final String spName) { final SharedPreferences sp = utils.sharedPrefs(); final SharedPreferences.Editor editor = utils.sharedPrefs().edit(); checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, final boolean b) { Thread update = new Thread(new Runnable() { @Override public void run() { final boolean oldData = sp.getBoolean(spName, false); editor.putBoolean(spName, b); editor.commit(); if(utils.tableEndOutBounds(sp.getString("startTime","8:00"), sp.getInt("lectureDur", 45), sp.getInt("recessDur", 10), sp.getInt("longRecessDur", 20), new boolean[] { sp.getBoolean("longRecess1", false), sp.getBoolean("longRecess2", false), sp.getBoolean("longRecess3", false), sp.getBoolean("longRecess4", false), sp.getBoolean("longRecess5", false), sp.getBoolean("longRecess6", false), sp.getBoolean("longRecess7", false), sp.getBoolean("longRecess8", false) } )) { utils.setTimeTable(getActivity(), sp.getString("startTime", "8:00"), sp.getInt("lectureDur", 45), sp.getInt("recessDur", 10), sp.getInt("longRecessDur", 20), new boolean[]{ sp.getBoolean("longRecess1", false), sp.getBoolean("longRecess2", false), sp.getBoolean("longRecess3", false), sp.getBoolean("longRecess4", false), sp.getBoolean("longRecess5", false), sp.getBoolean("longRecess6", false), sp.getBoolean("longRecess7", false), sp.getBoolean("longRecess8", false)}); } else { getActivity().runOnUiThread(new Runnable() { @Override public void run() { editor.putBoolean(spName, oldData); editor.commit(); if(toast != null) toast.cancel(); toast = Toast.makeText(getActivity().getBaseContext(), "Klaida pamokų laikas tęsiasi į kitą dieną.", Toast.LENGTH_SHORT); toast.show(); checkBox.setChecked(false); } }); } } }); update.start(); } }); } } <file_sep>package com.blackbrackets.tvarkarastis; import android.content.SharedPreferences; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.doomonafireball.betterpickers.numberpicker.NumberPickerBuilder; import com.doomonafireball.betterpickers.numberpicker.NumberPickerDialogFragment; import com.doomonafireball.betterpickers.timepicker.TimePickerBuilder; import com.doomonafireball.betterpickers.timepicker.TimePickerDialogFragment; import java.text.DecimalFormat; import java.text.NumberFormat; public class TimeDurations extends Fragment { TextView startTime, lectureDur, recessDur, longRecessDur; SharedPreferences sp; FragmentManager fManager; Utils utils; DatabaseHandler db; Toast toast = null; @Override public void onDestroy() { super.onDestroy(); db.close(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment RelativeLayout startTimeEdit, lectureDurEdit, recessDurEdit, longRecessDurEdit; final View main = inflater.inflate(R.layout.time_durations, container, false); db = new DatabaseHandler(getActivity()); utils = new Utils(getActivity(), db); fManager = getFragmentManager(); sp = utils.sharedPrefs(); startTime = (TextView) main.findViewById(R.id.startTime); lectureDur = (TextView) main.findViewById(R.id.lectureDur); recessDur = (TextView) main.findViewById(R.id.recessDur); longRecessDur = (TextView) main.findViewById(R.id.longRecessDur); startTimeEdit = (RelativeLayout) main.findViewById(R.id.startTimeLayout); lectureDurEdit = (RelativeLayout) main.findViewById(R.id.lecureDurLayout); recessDurEdit = (RelativeLayout) main.findViewById(R.id.recessDurLayout); longRecessDurEdit = (RelativeLayout) main.findViewById(R.id.longRecessDurLayout); setContentText(); editTimeDialog(startTimeEdit, "startTime"); editNumberDialog(lectureDurEdit, "lectureDur"); editNumberDialog(recessDurEdit, "recessDur"); editNumberDialog(longRecessDurEdit, "longRecessDur"); return main; } private void setContentText() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { startTime.setText(sp.getString("startTime","8:00")); lectureDur.setText(String.valueOf(sp.getInt("lectureDur", 45))+" min."); recessDur.setText(String.valueOf(sp.getInt("recessDur", 10))+" min."); longRecessDur.setText(String.valueOf(sp.getInt("longRecessDur", 20))+" min."); } }); } private void editTimeDialog(RelativeLayout button, final String spName){ final SharedPreferences.Editor editor = utils.sharedPrefs().edit(); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TimePickerBuilder dpb = new TimePickerBuilder() .setFragmentManager(fManager) .setStyleResId(R.style.BetterPickersDialogFragment); dpb.show(); dpb.addTimePickerDialogHandler(new TimePickerDialogFragment.TimePickerDialogHandler() { @Override public void onDialogTimeSet(int i, final int i2, final int i3) { Thread update = new Thread(new Runnable() { @Override public void run() { String oldData = sp.getString(spName, "8:00"); NumberFormat formatter = new DecimalFormat("00"); String h = String.valueOf(i2); String m = formatter.format(i3); editor.putString(spName, h+":"+m); editor.commit(); if(utils.tableEndOutBounds(h+":"+m, sp.getInt("lectureDur", 45), sp.getInt("recessDur", 10), sp.getInt("longRecessDur", 20), new boolean[] { sp.getBoolean("longRecess1", false), sp.getBoolean("longRecess2", false), sp.getBoolean("longRecess3", false), sp.getBoolean("longRecess4", false), sp.getBoolean("longRecess5", false), sp.getBoolean("longRecess6", false), sp.getBoolean("longRecess7", false), sp.getBoolean("longRecess8", false) } )) { setContentText(); utils.setTimeTable(getActivity(), sp.getString("startTime","8:00"), sp.getInt("lectureDur", 45), sp.getInt("recessDur", 10), sp.getInt("longRecessDur", 20), new boolean[] { sp.getBoolean("longRecess1", false), sp.getBoolean("longRecess2", false), sp.getBoolean("longRecess3", false), sp.getBoolean("longRecess4", false), sp.getBoolean("longRecess5", false), sp.getBoolean("longRecess6", false), sp.getBoolean("longRecess7", false), sp.getBoolean("longRecess8", false) } ); } else { editor.putString(spName, oldData); editor.commit(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { if(toast != null) toast.cancel(); toast = Toast.makeText(getActivity().getBaseContext(), "Klaida pamokų laikas tęsiasi į kitą dieną.", Toast.LENGTH_SHORT); toast.show(); } }); } } }); update.start(); } }); } }); } private void editNumberDialog(RelativeLayout button, final String spName){ final SharedPreferences.Editor editor = utils.sharedPrefs().edit(); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { NumberPickerBuilder dpb = new NumberPickerBuilder() .setFragmentManager(fManager) .setStyleResId(R.style.BetterPickersDialogFragment) .setPlusMinusVisibility(View.INVISIBLE) .setDecimalVisibility(View.INVISIBLE) .setLabelText("min."); dpb.show(); dpb.addNumberPickerDialogHandler(new NumberPickerDialogFragment.NumberPickerDialogHandler() { @Override public void onDialogNumberSet(int i, final int i2, double v, boolean b, double v2) { Thread update = new Thread(new Runnable() { @Override public void run() { int oldData = 45; if(spName == "lectureDur") oldData = sp.getInt(spName, 45); if(spName == "recessDur") oldData = sp.getInt(spName, 10); if(spName == "longRecessDur") oldData = sp.getInt(spName, 20); editor.putInt(spName, i2); editor.commit(); if(utils.tableEndOutBounds(sp.getString("startTime","8:00"), sp.getInt("lectureDur", 45), sp.getInt("recessDur", 10), sp.getInt("longRecessDur", 20), new boolean[] { sp.getBoolean("longRecess1", false), sp.getBoolean("longRecess2", false), sp.getBoolean("longRecess3", false), sp.getBoolean("longRecess4", false), sp.getBoolean("longRecess5", false), sp.getBoolean("longRecess6", false), sp.getBoolean("longRecess7", false), sp.getBoolean("longRecess8", false) } )) { editor.putInt(spName, i2); editor.commit(); setContentText(); utils.setTimeTable(getActivity(), sp.getString("startTime", "8:00"), sp.getInt("lectureDur", 45), sp.getInt("recessDur", 10), sp.getInt("longRecessDur", 20), new boolean[]{ sp.getBoolean("longRecess1", false), sp.getBoolean("longRecess2", false), sp.getBoolean("longRecess3", false), sp.getBoolean("longRecess4", false), sp.getBoolean("longRecess5", false), sp.getBoolean("longRecess6", false), sp.getBoolean("longRecess7", false), sp.getBoolean("longRecess8", false)}); utils.restartServices(); } else { editor.putInt(spName, oldData); editor.commit(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { if(toast != null) toast.cancel(); toast = Toast.makeText(getActivity().getBaseContext(), "Klaida pamokų laikas tęsiasi į kitą dieną.", Toast.LENGTH_SHORT); toast.show(); } }); } } }); update.start(); } }); } }); } }<file_sep>package com.blackbrackets.tvarkarastis; /** * Created by Simonas on 2014.07.16. */ public class Pos { boolean isLecture; int position; public Pos(boolean isLecture, int position) { this.isLecture = isLecture; this.position = position; } public boolean isLecture() { return isLecture; } public int getPosition() { return position; } } <file_sep>package com.blackbrackets.tvarkarastis; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.AudioManager; import android.util.Log; import java.util.Calendar; import java.util.GregorianCalendar; public class SoundReceiver extends BroadcastReceiver { Utils utils; public SoundReceiver() { } @Override public void onReceive(Context context, Intent intent) { DatabaseHandler db = new DatabaseHandler(context); utils = new Utils(context, db); Calendar c = Calendar.getInstance(); int currentDay = utils.getCurrentDay(); int realCurrentDay = utils.getRealCurrentDay(); int h = c.get(Calendar.HOUR_OF_DAY); int m = c.get(Calendar.MINUTE); Pos pos = utils.findPosition(h, m); int startPos = utils.getFirstLecturePos(currentDay); int endPos = utils.getLastLecturePos(currentDay); // School Starts int startH = db.getTimeTable(startPos).getIntStartH(); int startM = db.getTimeTable(startPos).getIntStartM(); // School Ends int endH = db.getTimeTable(endPos).getIntEndH(); int endM = db.getTimeTable(endPos).getIntEndM(); Calendar cal = new GregorianCalendar(); Log.d("Sound", "onReceive"); if ((h * 60 + m >= startH * 60 + startM) && (h * 60 + m < endH * 60 + endM) && realCurrentDay != 5 && realCurrentDay != 6 && realCurrentDay != -1) { Log.d("Sound", "During School"); Calendar cur_cal = new GregorianCalendar(); cur_cal.setTimeInMillis(System.currentTimeMillis()); //set the current time and date for this calendar int maxPos = utils.getLastLecturePos(utils.getCurrentDay()); if (pos.isLecture) { Log.d("Sound", "Set"); if(db.getLecture(utils.getCurrentDay(), pos.getPosition()).getName().length() == 0) setSoundMode(context, true); else setSoundMode(context, false); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.HOUR_OF_DAY, db.getTimeTable(pos.getPosition()).getIntEndH()); cal.set(Calendar.MINUTE, db.getTimeTable(pos.getPosition()).getIntEndM()); Log.d("Sound", "Wait for " + (cal.getTimeInMillis() - System.currentTimeMillis())/1000 +" s."); utils.setAlarmTimer(true, (int) (cal.getTimeInMillis() - System.currentTimeMillis()), SoundReceiver.class); } if (!pos.isLecture) { Log.d("Sound", "Reset"); setSoundMode(context, true); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); int _pos = pos.getPosition() + 1; while (db.getLecture(utils.getCurrentDay(), _pos).getName().length() == 0 && _pos <= maxPos) _pos++; cal.set(Calendar.HOUR_OF_DAY, db.getTimeTable(_pos).getIntStartH()); cal.set(Calendar.MINUTE, db.getTimeTable(_pos).getIntStartM()); Log.d("Sound", "Wait for " + (cal.getTimeInMillis() - System.currentTimeMillis())/1000 +" s."); utils.setAlarmTimer(true, (int) (cal.getTimeInMillis() - System.currentTimeMillis()), SoundReceiver.class); } } else { Log.d("Sound", "Stop Managing"); setSoundMode(context, true); switch (realCurrentDay) { case 4: cal.add(Calendar.DATE, 3); cal.set(Calendar.HOUR_OF_DAY, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartH()); cal.set(Calendar.MINUTE, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartM()); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Log.d("Sound", "Wait for (Fri)" + (double)(cal.getTimeInMillis() - System.currentTimeMillis())/1000/60 +" mins."); utils.setAlarmTimer(true, (int) (cal.getTimeInMillis() - System.currentTimeMillis()), SoundReceiver.class); break; case 5: cal.add(Calendar.DATE, 2); cal.set(Calendar.HOUR_OF_DAY, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartH()); cal.set(Calendar.MINUTE, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartM()); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Log.d("Sound", "Wait for (Sat)" + (double)(cal.getTimeInMillis() - System.currentTimeMillis())/1000/60 +" mins."); utils.setAlarmTimer(true, (int) (cal.getTimeInMillis() - System.currentTimeMillis()), SoundReceiver.class); break; case 6: cal.add(Calendar.DATE, 1); cal.set(Calendar.HOUR_OF_DAY, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartH()); cal.set(Calendar.MINUTE, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartM()); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Log.d("Sound", "Wait for (Sun)" + (double)(cal.getTimeInMillis() - System.currentTimeMillis())/1000/60 +" mins."); utils.setAlarmTimer(true, (int) (cal.getTimeInMillis() - System.currentTimeMillis()), SoundReceiver.class); break; default: // Day++ if((h * 60 + m) >= endH * 60 + endM) { cal.add(Calendar.DATE, 1); cal.set(Calendar.HOUR_OF_DAY, db.getTimeTable(utils.getFirstLecturePos(currentDay+1)).getIntStartH()); cal.set(Calendar.MINUTE, db.getTimeTable(utils.getFirstLecturePos(currentDay+1)).getIntStartM()); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Log.d("Sound", "Wait for (Other++) " + (cal.getTimeInMillis() - System.currentTimeMillis())/1000/60 +" mins."); utils.setAlarmTimer(true, (int) (cal.getTimeInMillis() - System.currentTimeMillis()), SoundReceiver.class); } // Current Day if((h * 60 + m) < startH * 60 + startM) { cal.set(Calendar.HOUR_OF_DAY, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartH()); cal.set(Calendar.MINUTE, db.getTimeTable(utils.getFirstLecturePos(currentDay)).getIntStartM()); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Log.d("Sound", "Wait for (Other)" + (double)(cal.getTimeInMillis() - System.currentTimeMillis())/1000/60 +" mins."); utils.setAlarmTimer(true, (int) (cal.getTimeInMillis() - System.currentTimeMillis()), SoundReceiver.class); } break; } } } private void setSoundMode(Context context, boolean reset) { SharedPreferences spPreferences = utils.sharedPrefs(); AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); if(reset) { audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); } else if(spPreferences.getString("sound", "0") != "0") { switch (Integer.valueOf(spPreferences.getString("sound", "0"))) { case 1: audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); break; case 2: audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); break; } } } } <file_sep>package com.blackbrackets.tvarkarastis; import android.content.Context; /** * Created by Simonas on 2014.06.28. */ public class DatabaseLoader { public void fillDB(Context context){ DatabaseHandler databaseHandler = new DatabaseHandler(context); // Create Table for (int day = 0; day < 5; day++) { for (int pos = 0; pos < 9; pos++){ databaseHandler.addLecture(new Lecture(day, pos, "", "", "")); } } // Create Table for (int pos = 0; pos < 9; pos++) { databaseHandler.addTimeTable(new TimeRow(pos, "0", "0", "0", "0")); } // Update Table new Utils(context, new DatabaseHandler(context)).setTimeTable(null, "8:00", 45, 10, 20, new boolean[] { false, false, false, false, false, false, false, false } ); databaseHandler.close(); } } <file_sep>package com.blackbrackets.tvarkarastis; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * Created by Simonas on 2014.08.24. */ public class RebootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Utils utils = new Utils(context, new DatabaseHandler(context)); utils.restartServices(); } } <file_sep># Tvarkarasis 2014 Mokyklos pamokų tvarkaraštis https://play.google.com/store/apps/details?id=com.blackbrackets.tvarkarastis<file_sep>package com.blackbrackets.tvarkarastis; /** * Created by Simonas on 2014.06.27. */ public class Lecture { int id; // SQL id int day; // Weekday int pos; // Position in the table String name; // Name of a lecture String number; // Room number String time; // Time of a lecture public Lecture() { } public Lecture(int id, int day, int pos, String name, String number, String time) { this.id = id; this.day = day; this.pos = pos; this.name = name; this.number = number; this.time = time; } public void setId(int id) { this.id = id; } public void setDay(int day) { this.day = day; } public void setPos(int pos) { this.pos = pos; } public void setName(String name) { this.name = name; } public void setNumber(String number) { this.number = number; } public void setTime(String time) { this.time = time; } public Lecture(int day, int pos, String name, String number, String time) { this.day = day; this.pos = pos; this.name = name; this.number = number; this.time = time; } public int getDay() { return day; } public int getPos() { return pos; } public String getName() { return name; } public String getNumber() { return number; } public String getTime() { return time; } public int getId() { return id; } } <file_sep>package com.blackbrackets.tvarkarastis; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TabHost; public class SetupTimeFragment extends Fragment { TabHost tabHost; ViewPager viewPager; Utils utils = new Utils(getActivity()); public SetupTimeFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View main = inflater.inflate(R.layout.fragment_setup_time, container, false); // Google Analytics utils.sendTracker(getActivity(), "Time Fragment"); // Inflate the layout for this fragment tabHost = (TabHost) main.findViewById(R.id.tabHost); tabHostSetup(tabHost); viewPager = (ViewPager) main.findViewById(R.id.pager); TimeFragmentAdapter mAdapter = new TimeFragmentAdapter(getActivity().getSupportFragmentManager()); viewPager.setAdapter(mAdapter); viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { tabHost.setCurrentTab(position); } @Override public void onPageScrollStateChanged(int state) { } }); tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() { @Override public void onTabChanged(String s) { viewPager.setCurrentItem(Integer.valueOf(s), true); } }); return main; } private void tabHostSetup(TabHost tabHost) { tabHost.setup(); TabHost.TabSpec dur = tabHost.newTabSpec("0"); TabHost.TabSpec l_recess = tabHost.newTabSpec("1"); TabHost.TabSpec manual = tabHost.newTabSpec("2"); dur.setIndicator(getResources().getString(R.string.time_tab1)); l_recess.setIndicator(getResources().getString(R.string.time_tab2)); manual.setIndicator(getResources().getString(R.string.time_tab3)); dur.setContent(R.id.tab1); l_recess.setContent(R.id.tab1); manual.setContent(R.id.tab1); tabHost.addTab(dur); tabHost.addTab(l_recess); tabHost.addTab(manual); } }
7fb354523c647d9fa204a34a88e6b36eac564d80
[ "Markdown", "Java" ]
12
Java
simonassank/Tvarkarasis
f25d17c958252ea82fc64c67778666be0cc2c33b
3015e05cbcbe70b57f792dbd8f4fb205e6111183
refs/heads/master
<file_sep>#!/usr/bin/env ruby # encoding: UTF-8 require File.expand_path('../test_helper', __FILE__) class GcTest < TestCase def some_method Array.new(3 * 4) end def run_profile RubyProf.profile do self.some_method end end def test_hold_onto_thread threads = 1000.times.reduce(Array.new) do |array, i| array.concat(run_profile.threads) GC.start array end threads.each do |thread| error = assert_raises(RuntimeError) do thread.id end assert_match(/has already been freed/, error.message) end assert(true) end def test_hold_onto_method methods = 1000.times.reduce(Array.new) do |array, i| array.concat(run_profile.threads.map(&:methods).flatten) GC.start array end methods.each do |method| error = assert_raises(RuntimeError) do method.method_name end assert_match(/has already been freed/, error.message) end assert(true) end def test_hold_onto_parent_callers call_infos = 1000.times.reduce(Array.new) do |array, i| array.concat(run_profile.threads.map(&:methods).flatten.map(&:callers).flatten) GC.start array end call_infos.each do |call_info| error = assert_raises(RuntimeError) do call_info.source_file end assert_match(/has already been freed/, error.message) end assert(true) end def test_hold_onto_parent_callees call_infos = 1000.times.reduce(Array.new) do |array, i| array.concat(run_profile.threads.map(&:methods).flatten.map(&:callees).flatten) GC.start array end call_infos.each do |call_info| error = assert_raises(RuntimeError) do call_info.source_file end assert_match(/has already been freed/, error.message) end assert(true) end def test_hold_onto_measurements measurements = 1000.times.reduce(Array.new) do |array, i| array.concat(run_profile.threads.map(&:methods).flatten.map(&:callers).flatten.map(&:measurement)) GC.start array end measurements.each do |measurement| error = assert_raises(RuntimeError) do measurement.total_time end assert_match(/has already been freed/, error.message) end assert(true) end end <file_sep>#!/usr/bin/env ruby # encoding: UTF-8 require File.expand_path('../test_helper', __FILE__) require 'fiber' require 'timeout' require 'set' # -- Tests ---- class FiberTest < TestCase def fiber_test @fiber_ids << Fiber.current.object_id enum = Enumerator.new do |yielder| [1,2].each do |x| @fiber_ids << Fiber.current.object_id sleep 0.1 yielder.yield x end end while true begin enum.next rescue StopIteration break end end sleep 0.1 end def setup # Need to use wall time for this test due to the sleep calls RubyProf::measure_mode = RubyProf::WALL_TIME @fiber_ids = Set.new @root_fiber = Fiber.current.object_id @thread_id = Thread.current.object_id end def test_fibers result = RubyProf.profile { fiber_test } profiled_fiber_ids = result.threads.map(&:fiber_id) assert_equal(2, result.threads.length) assert_equal([@thread_id], result.threads.map(&:id).uniq) assert_equal(@fiber_ids, Set.new(profiled_fiber_ids)) assert profiled_fiber_ids.include?(@root_fiber) assert(root_fiber_profile = result.threads.detect{|t| t.fiber_id == @root_fiber}) assert(enum_fiber_profile = result.threads.detect{|t| t.fiber_id != @root_fiber}) assert_in_delta(0.3, root_fiber_profile.total_time, 0.05) assert_in_delta(0.2, enum_fiber_profile.total_time, 0.05) assert(method_next = root_fiber_profile.methods.detect{|m| m.full_name == "Enumerator#next"}) assert(method_each = enum_fiber_profile.methods.detect{|m| m.full_name == "Enumerator#each"}) assert_in_delta(0.2, method_next.total_time, 0.05) assert_in_delta(0.2, method_each.total_time, 0.05) end def test_merged_fibers result = RubyProf.profile(merge_fibers: true) { fiber_test } assert_equal(1, result.threads.length) thread = result.threads.first assert_equal(thread.id, thread.fiber_id) assert_in_delta(0.3, thread.total_time, 0.05) assert(method_next = thread.methods.detect{|m| m.full_name == "Enumerator#next"}) assert(method_each = thread.methods.detect{|m| m.full_name == "Enumerator#each"}) assert_in_delta(0.2, method_next.total_time, 0.05) assert_in_delta(0.2, method_each.total_time, 0.05) end end
f0b9428d00e356c106c4af4b019d6ab8f748cbca
[ "Ruby" ]
2
Ruby
baelter/ruby-prof
9e0ab4c01874bd9bf52752a6410cf8d342f5f31d
f6383dca8d0d3057761ea322149d53192302119b
refs/heads/main
<repo_name>ashi-mark/16-2-21<file_sep>/ESS_DAL/Repository/IGenericRepository.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text.RegularExpressions; namespace ESS_BLG { public interface IGenericRepository<T> where T : class { IQueryable<T> GetAll(); // IEnumerable<T> GetAll1(); IQueryable<T> FindBy(Expression<Func<T, bool>> predicate); void Add(T entity); void Delete(T entity); void Edit(T entity); void Save(); } } <file_sep>/ESS_DAL/PartialsEntities/customer.cs using ESS_Objects; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ESS_DAL { public partial class customer { public OM_Customer GetOMCustomer() { return new OM_Customer { customerNumber = this.customerNumber, CustomerName = this.customerName, Phone = this.phone, ContactLastName = this.contactLastName, ContactFirstName = this.contactFirstName, City = this.city, Country = this.country, AddressLine1 = this.addressLine1 }; } public customer(OM_Customer m_Customer) { SetData(m_Customer); } public void SetData(OM_Customer m_Customer) { this.customerName = m_Customer.CustomerName; this.phone = m_Customer.Phone; this.contactFirstName = m_Customer.ContactFirstName; this.contactLastName = m_Customer.ContactLastName; this.city = m_Customer.City; this.country = m_Customer.Country; this.addressLine1 = m_Customer.AddressLine1; } } } <file_sep>/ESS_BLG/BLayer.cs  using ESS_DAL; using ESS_Objects; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ESS_BLG { public class BLayer { public List<OM_Customer> GetCustomers() { using (var ctx = new ESS_DBEntities()) { CustomerLogic clog = new CustomerLogic(); var qlog = from item in clog.GetAll() select item; var list = qlog.ToList().Select(x => x.GetOMCustomer()).ToList(); return list; } } public void AddNewCustomer(OM_Customer oM_Customer) { CustomerLogic clog = new CustomerLogic(); var newCustomer = new customer(oM_Customer); clog.Add(newCustomer); clog.Save(); } public void EditCustomer(OM_Customer oM_Customer) { CustomerLogic clog = new CustomerLogic(); var existingCustomer = clog.FindBy(x => x.customerNumber == oM_Customer.customerNumber).SingleOrDefault(); existingCustomer.SetData(oM_Customer); clog.Edit(existingCustomer); clog.Save(); } public List<OM_Customer> GetRiskyCustomers(decimal riskValue) { CustomerLogic clog = new CustomerLogic(); var rCstmr = clog.GetRiskyCustomers(riskValue); return rCstmr.Select(x => x.GetOMCustomer()).ToList(); } } }<file_sep>/ESS_Objects/OM_Customer.cs  using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ESS_Objects { public class OM_Customer { public int customerNumber { set; get; } [DisplayName("Customer Name")] public string CustomerName { set; get; } public string Phone { set; get; } [DisplayName("Contact First Name")] public string ContactFirstName { get; set; } public string ContactLastName { get; set; } public string City { get; set; } public string Country { get; set; } public string AddressLine1 { get; set; } } } <file_sep>/ESS_Client/Form1.cs using ESS_BLG; using ESS_Objects; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ESS_Client { public partial class Form1 : Form { public Form1() { InitializeComponent(); LoadCustomers(bl.GetCustomers()); } BLayer bl = new BLayer(); OM_Customer currentCustomer; private void LoadCustomers(List<OM_Customer> list) { // var list = d.GetCustomers(); dataGridView1.DataSource = null; dataGridView1.Rows.Clear(); dataGridView1.DataSource = list; label1.Text = list.Count.ToString(); } private void dataGridView1_SelectionChanged(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count > 0) { currentCustomer = dataGridView1.SelectedRows[0].DataBoundItem as OM_Customer; textBoxAddressLine1.Text = currentCustomer.AddressLine1; textBoxCity.Text = currentCustomer.City; textBoxContactFirstName.Text = currentCustomer.ContactFirstName; textBoxContactLastName.Text = currentCustomer.ContactLastName; textBoxCountry.Text = currentCustomer.Country; textBoxCustomerName.Text = currentCustomer.CustomerName; textBoxPhone.Text = currentCustomer.Phone; } } private void BtnAdd_click(object sender, EventArgs e) { var om = new OM_Customer { AddressLine1 = textBoxAddressLine1.Text, City = textBoxCity.Text, ContactFirstName = textBoxContactFirstName.Text, ContactLastName = textBoxContactLastName.Text, Country = textBoxCountry.Text, CustomerName = textBoxCustomerName.Text, Phone = textBoxPhone.Text }; bl.AddNewCustomer(om); LoadCustomers(bl.GetCustomers()); } private void btnEdit_Click(object sender, EventArgs e) { var om = new OM_Customer { AddressLine1 = textBoxAddressLine1.Text, City = textBoxCity.Text, ContactFirstName = textBoxContactFirstName.Text, ContactLastName = textBoxContactLastName.Text, Country = textBoxCountry.Text, CustomerName = textBoxCustomerName.Text, Phone = textBoxPhone.Text, customerNumber = currentCustomer.customerNumber//TODO }; bl.EditCustomer(om); LoadCustomers(bl.GetCustomers()); } private void button3_Click(object sender, EventArgs e) { LoadCustomers(bl.GetCustomers()); } private void buttonriskyclient_Click(object sender, EventArgs e) { LoadCustomers(bl.GetRiskyCustomers(nudRiskyVal.Value)); } private void btnClear_Click(object sender, EventArgs e) { var txbxes = panel1.Controls.OfType<TextBox>(); foreach (var item in txbxes) { item.Text = ""; } } } } <file_sep>/ESS_BLG/CustomerLogic.cs using ESS_DAL; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace ESS_BLG { internal class CustomerLogic : GenericRepository<ESS_DBEntities, customer> { public override void Add(customer entity) { var newid = base.Entities.customers.Max(x => x.customerNumber) + 1; entity.customerNumber = newid; base.Add(entity); } internal List<customer> GetRiskyCustomers(decimal value) { if (value < 1 || value > 100) { throw new Exception("The value must be between 1 and 100"); } List<customer> riskCustomers = new List<customer>(); var riskyClients = from item in Entities.customers where item.orders.Count > item.payments.Count select item; foreach (var item in riskyClients) { var ordersCnt = item.orders.Count; var pmntCnt = item.payments.Count; if (IsRisky(value, ordersCnt, pmntCnt)) { riskCustomers.Add(item); } } return riskCustomers; } private bool IsRisky(decimal value, int ordersCnt, int pmntCnt) { var percent = 100 - (pmntCnt * 100 / ordersCnt); return percent > value; } } }
80cce13fb2b37e22353a572820c7343a64df3db0
[ "C#" ]
6
C#
ashi-mark/16-2-21
2f0c9b6bd17b83badea8a6e5f0b82d0d3f83d098
61a00c8875d76fd100763df62b7fb5fd0f2f7a4e
refs/heads/master
<repo_name>Chekote/docker-node<file_sep>/bin/yarn #!/bin/bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" . "${DIR}"/lib/tty.sh docker run -i $TTY -v "$(pwd):/workdir" --rm chekote/node yarn "$@" <file_sep>/entrypoint.sh #!/usr/bin/env sh # Based on: <NAME> https://denibertovic.com/posts/handling-permissions-with-docker-volumes/ # Use the LOCAL_USER_ID that was passed in, or fallback to 9001 USER_ID="${LOCAL_USER_ID:-9001}" # Get the username that is associated with the user id (if any) USER_NAME=$(getent passwd | awk -F: '$3 == '$USER_ID' { print $1 }') # Does the user already exist? if [ "$USER_NAME" = "" ]; then # No, Set the id of node USER_NAME=node usermod -u "$USER_ID" "$USER_NAME" fi # Make sure node modules is part of the path. export PATH="$PATH:./node_modules/.bin" # Execute the command su-exec "$USER_NAME" "$@"
fe1d6c60a7773c8201f4e66d3e326a6c41a392b3
[ "Shell" ]
2
Shell
Chekote/docker-node
981dc7670a0aad5de58a80aebd5a40c24cfa2b09
7fa0c572acff165695f7182b904a32d1136120cc
refs/heads/master
<repo_name>crewsycrews/cli-php-ssh-client<file_sep>/README.md # SSH CLI PHP client Small client for regular tasks. Requires PHP 7.4 Usage: ```bash $ php crews-cli-ssh-php-client Usage: crews-cli-ssh-php-client [--help] [-h host, --host host] [-p password, --password <PASSWORD>] [--port port] [-u user, --user user] Required Arguments: -h host, --host host Host machine -u user, --user user Username -p password, --password <PASSWORD> <PASSWORD> Optional Arguments: --help Prints this message --port port Port for the connection ``` Actual command is placed under `app/Commands/SSHConnectCommand.php`. We make it be passed as argument to our tool later. <file_sep>/crews-cli-ssh-php-client #!/usr/bin/php <?php use App\Commands\SSHConnectCommand; use DivineOmega\SSHConnection\SSHConnection; require_once('vendor/autoload.php'); $climate = new League\CLImate\CLImate; $connection = new SSHConnection(); $command = new SSHConnectCommand($climate, $connection); $command->handle();<file_sep>/app/Commands/SSHConnectCommand.php <?php namespace App\Commands; use DivineOmega\SSHConnection\SSHConnection; use League\CLImate\CLImate; /** * Default command execution class. */ class SSHConnectCommand { protected $cliMate; protected $connection; protected string $host; protected int $port; protected string $username; protected string $password; /** * Pass the cliMate to use inside commands. */ public function __construct(CLImate $cliMate, SSHConnection $connection) { $this->cliMate = $cliMate; $this->connection = $connection; $this->configureArguments(); } /** * Actual handling functionality. * * @return void */ public function handle() { if ($this->cliMate->arguments->defined('help')) { $this->cliMate->usage(); return; } try { $this->cliMate->arguments->parse(); } catch (\Throwable $th) { $this->cliMate->usage(); $this->cliMate->error($th->getMessage()); // exit; } $this->setCredentials( $this->cliMate->arguments->get('user'), $this->cliMate->arguments->get('password'), $this->cliMate->arguments->get('host'), $this->cliMate->arguments->defined('port') ? $this->cliMate->arguments->get('port') : 22 ); try { $this->connection ->to($this->host) ->onPort($this->port) ->as($this->username) ->withPassword($this->password) ->connect(); } catch (\Throwable $th) { $this->cliMate->error($th->getMessage()); exit; } // $command = $this->connection->run('zsh'); $command = $this->connection->run('service sockd restart'); $this->cliMate->backgroundGreen($command->getOutput()); } /** * Sets all needed information for SSH connection. * * @return void */ protected function setCredentials(string $username, string $password, string $host, int $port) { $this->host = $host; $this->port = $port; $this->username = $username; $this->password = <PASSWORD>; } /** * Add descriptions for arguments for our tool. * * @return void */ protected function configureArguments() { $this->cliMate->arguments->add([ 'help' => [ 'longPrefix' => 'help', 'description' => 'Prints this message', 'noValue' => true, ], 'port' => [ 'longPrefix' => 'port', 'description' => 'Port for the connection', 'castTo' => 'int', ], 'host' => [ 'prefix' => 'h', 'longPrefix' => 'host', 'description' => 'Host machine', 'required' => true, ], 'user' => [ 'prefix' => 'u', 'longPrefix' => 'user', 'description' => 'Username', 'required' => true, ], 'password' => [ 'prefix' => 'p', 'longPrefix' => 'password', 'description' => 'Password', 'required' => true, ], ]); } }
0845395383efa8472f858c8dfc848982cf779d67
[ "Markdown", "PHP" ]
3
Markdown
crewsycrews/cli-php-ssh-client
7071f264576271f21445500f4ab3f0812e0593b6
38eae5c87e52239be9a887338f7699c7adc010d3
refs/heads/main
<repo_name>DevOps-Spring2021/uber<file_sep>/src/components/Toast/Toast.js import React from "react"; import { Alert } from "react-bootstrap"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faTimes } from '@fortawesome/fontawesome-free-solid' const Toast = (props) => { return ( props.message && ( <div className=""> <Alert variant={props.mode} className="text-center"> <div className="mr-auto"> {props.message} </div> <div className="pointer" onClick={() => { props.updateShow(false) }}> <FontAwesomeIcon icon={faTimes}></FontAwesomeIcon> </div> </Alert> </div> ) ) } export default Toast;<file_sep>/src/components/AutoComplete/AutoComplete.js import React, { useState } from "react"; import { Form, ListGroup } from "react-bootstrap"; import axios from 'axios'; import Cookies from "js-cookie"; const AutoComplete = ({ label, onSelect }) => { const [searchTerm, setSearchTerm] = useState(''); const [searchList, setSearchList] = useState([]); const [timeoutId, setTimeoutId] = useState(); const getLstLocation = async (e) => { setSearchTerm(e.target.value); if (timeoutId) { clearTimeout(timeoutId); setTimeoutId(null); } const timer = setTimeout(async () => { if (e.target.value) { let url = `${process.env.REACT_APP_BACKEND_HOST}/maps/${e.target.value}`; let resp = await axios.get(url, { headers: { Authorization: `Bearer ${Cookies.get("jwt")}` } }); setSearchList(resp?.data?.predictions?.map(pred => ({ name: pred.description, place_id: pred.place_id })).slice(0, 5) || []) } }, 500) setTimeoutId(timer); } return ( <Form.Group controlId="formSource" className="position-relative"> <Form.Control type="text" value={searchTerm} onInput={getLstLocation} placeholder={label} required /> {searchList && (<ListGroup className="dropdown-location"> { searchList.map(({ name, place_id }) => { return ( <ListGroup.Item key={place_id} onClick={(e) => { setSearchTerm(name); onSelect({ name, place_id }); setSearchList([]) }}>{name}</ListGroup.Item> ) }) } </ListGroup>)} </Form.Group> ) } export default AutoComplete;<file_sep>/src/components/App/App.js import 'bootstrap/dist/css/bootstrap.min.css'; import './App.css'; import BookRide from '../BookRide/BookRide'; import Nav from '../UberNavbar/UberNavbar'; import Rides from '../Rides/Rides'; import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom'; import { Container } from "react-bootstrap"; import RideDetails from '../RideDetails/RideDetails'; import TestHealth from "../Test/TestHealth"; import TestComms from "../Test/TestComms"; import Login from '../Login/Login'; import Buses from '../Buses/Buses'; import React, { useState } from "react"; import UserContext from "../../context/UserContext"; import Cookie from "js-cookie"; function App() { const token = Cookie.get("jwt"); const [isAuthenticated, setIsAuthenticated] = useState(!!token); return ( <UserContext.Provider value={{ isAuthenticated, setIsAuthenticated }}> <BrowserRouter> {isAuthenticated ? <> <div className="bg-dark"> <Container> <Nav></Nav> </Container> </div> <Container> <Switch> <Route path="/" exact component={BookRide}></Route> <Route path="/login" component={Login}></Route> <Route path="/rides/:id" component={RideDetails}></Route> <Route path="/rides" component={Rides}></Route> <Route path="/buses" component={Buses}></Route> <Route path="/testHealth" component={TestHealth}></Route> <Route path="/testComms" component={TestComms}></Route> </Switch> </Container> </> : <div> <Route path="/login" component={Login}></Route> <Redirect to="/login" /> </div> } </BrowserRouter> </UserContext.Provider> ) } export default App; <file_sep>/src/components/Buses/Buses.js import React, { useState, useEffect } from "react"; import { Button, ListGroup, Form, Table } from "react-bootstrap"; import AutoComplete from "../AutoComplete/AutoComplete"; import axios from "axios"; import Cookies from "js-cookie"; import Toast from "../Toast/Toast"; const Buses = () => { const [selected, setSelected] = useState("all"); const [source, setSource] = useState(''); const [destination, setDestination] = useState(''); const [seats, setSeats] = useState(''); const [busId, setBusId] = useState(''); const [busName, setBusName] = useState(''); const [showInfo, setShowInfo] = useState(false); const [showError, setShowError] = useState(false); const [lstBus, setLstBus] = useState([]); useEffect(() => { axios.get(`${process.env.REACT_APP_BACKEND_HOST}/bus/`, { headers: { Authorization: `Bearer ${Cookies.get("jwt")}` } }) .then(res => { setLstBus(res.data) }) .catch(err => console.log(err)); }, []) const sourceChange = (data) => { setSource(data); } const destinationChange = (data) => { setDestination(data); } const addBus = (e) => { e.preventDefault(); if (source !== '' && destination !== '' && seats !== '') { axios.post(`${process.env.REACT_APP_BACKEND_HOST}/bus/`, { source: source.name, destination: destination.name, sourceId: source.place_id, destinationId: destination.place_id, busName: busName, totalSeats: parseInt(seats) }, { headers: { Authorization: `Bearer ${Cookies.get("jwt")}` }, }) .then(res => { console.log("Bus added successfully"); setShowInfo(true); setSeats("") }) .catch(err => setShowError(true)); } } const getBusList = () => { return ( [...lstBus].map((bus) => { return ( <tr key={bus.busID}> <td>{bus.busID}</td> <td>{bus.busName}</td> <td>{bus.source}</td> <td>{bus.destination}</td> <td>{bus.totalSeats}</td> </tr> ) }) ) } const removeBus = (e) => { e.preventDefault(); if (busId !== '') { axios.delete(`${process.env.REACT_APP_BACKEND_HOST}/bus/${busId}`, { headers: { Authorization: `Bearer ${Cookies.get("jwt")}` }, }) .then(res => { console.log("Bus removed successfully"); setShowInfo(true); setBusId("") }) .catch(err => setShowError(true)); } } // const updateBus = (e) => { // e.preventDefault(); // if (seats !== '') { // axios.put(`${process.env.REACT_APP_BACKEND_HOST}/bus/${busId}?seats=${seats}`, { // headers: { // Authorization: `Bearer ${Cookies.get("jwt")}` // }, // }) // .then(res => { setShowInfo(true); setBusId(""); setSeats("") }) // .catch(err => setShowError(true)); // } // } return ( <> { showInfo && (<Toast updateShow={setShowInfo} message="Successfully!!!" mode="success"></Toast>)} { showError && (<Toast updateShow={setShowError} message="Error while performing operation, please try again later" mode="danger"></Toast>)} <div className="row mt-3"> <div className="col-12 col-sm-4"> <ListGroup> <ListGroup.Item onClick={() => { setSelected("all") }} className={selected === "all" ? "bg-dark text-white" : ""}>All Buses</ListGroup.Item> <ListGroup.Item onClick={() => { setSelected("add") }} className={selected === "add" ? "bg-dark text-white" : ""}>Add Bus</ListGroup.Item> <ListGroup.Item onClick={() => { setSelected("remove") }} className={selected === "remove" ? "bg-dark text-white" : ""}>Remove Bus</ListGroup.Item> {/* <ListGroup.Item onClick={() => { setSelected("update") }} className={selected === "update" ? "bg-dark text-white" : ""}>Update Bus</ListGroup.Item> */} </ListGroup> </div> <div className="col-12 col-sm-8"> {selected === "all" && ( <Table striped bordered hover> <thead> <tr> <th>Bus ID</th> <th>Bus Name</th> <th>Pick up</th> <th>Destination</th> <th>Seats</th> </tr> </thead> <tbody> {getBusList()} </tbody> </Table> )} {selected === "add" && ( <div> <Form onSubmit={addBus}> <div> <Form.Group controlId="source"> <label>Source</label> <AutoComplete label="Enter pickup location" onSelect={sourceChange}></AutoComplete> </Form.Group> <Form.Group controlId="destination"> <label>Destination</label> <AutoComplete label="Enter destination" onSelect={destinationChange}></AutoComplete> </Form.Group> <Form.Group controlId="busName"> <label>Bus Name</label> <Form.Control type="text" value={busName} onChange={(e) => { setBusName(e.target.value) }} required /> </Form.Group> <Form.Group controlId="seats"> <label>Seats</label> <Form.Control type="number" value={seats} onChange={(e) => { setSeats(e.target.value) }} required /> </Form.Group> <Button type="submit" className="btn btn-dark">Submit</Button> </div> </Form> </div> )} {selected === "remove" && ( <div> <Form onSubmit={removeBus}> <div> <Form.Group controlId="source"> <label>Enter Bus Id to be removed</label> <Form.Control type="number" value={busId} onChange={(e) => { setBusId(e.target.value) }} required /> </Form.Group> <Button type="submit" className="btn btn-dark">Submit</Button> </div> </Form> </div> )} {/* {selected === "update" && ( <Form onSubmit={updateBus}> <div> <Form.Group controlId="source"> <label>Enter Bs Id to be removed</label> <Form.Control type="number" value={busId} onChange={(e) => { setBusId(e.target.value) }} required /> </Form.Group> <Form.Group controlId="source"> <label>Enter Bus Id to be updated</label> <Form.Control type="number" value={seats} onChange={(e) => { setSeats(e.target.value) }} required /> </Form.Group> <Button type="submit" className="btn btn-dark">Submit</Button> </div> </Form> )} */} </div> </div> </> ) } export default Buses;<file_sep>/src/components/Test/TestHealth.js import React from "react"; const TestHealth = ()=>{ return ( <div> Hello from frontend!!! </div> ) } export default TestHealth;<file_sep>/src/components/Login/Login.js import React, { useContext, useState } from "react"; import { Form, Button } from "react-bootstrap"; import axios from "axios"; import { useHistory } from 'react-router-dom'; import Cookies from "js-cookie"; import UserContext from "../../context/UserContext"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faBus } from '@fortawesome/fontawesome-free-solid' import Toast from "../Toast/Toast"; const Login = () => { const { setIsAuthenticated } = useContext(UserContext); const history = useHistory(); const [isSignUp, setIsSignUp] = useState(false); const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [firstName, setfirstName] = useState(''); const [lastName, setlastName] = useState(''); const [validated, setValidated] = useState(false); const [showInfo, setShowInfo] = useState(false); const [showError, setShowError] = useState(false); const [errorMessage, setErrorMessage] = useState(""); const reset = () => { setfirstName(''); setlastName(''); setUsername(''); setPassword(''); setIsSignUp(false); setValidated(false); } const handleSubmit = (event) => { console.log(process.env.REACT_APP_BACKEND_HOST); const form = event.currentTarget; if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } else { event.preventDefault(); event.stopPropagation(); if (isSignUp) { axios.post(`${process.env.REACT_APP_BACKEND_HOST}/register`, { firstName: firstName, lastName: lastName, password: <PASSWORD>, username: username }) .then(resp => { setShowInfo(true); reset(); history.push("/login"); console.log("User created.") }) .catch((err) => { setValidated(false); console.log("Error while creating user") console.log(err); // err.response.data ? setErrorMessage(err.response.data) : setErrorMessage("error while creating user"); setShowError(true); }); } else { axios.post(`${process.env.REACT_APP_BACKEND_HOST}/login`, { password: <PASSWORD>, username: username }) .then(res => { Cookies.set('jwt', res.data.token); console.log("Login Successful!!!") setIsAuthenticated(true); if(username ==="<EMAIL>"){ history.push("/buses") } else { history.push("/"); } }) .catch(err => { setErrorMessage("Please enter valid credentials"); setShowError(true) }); } } setValidated(true); }; return ( <div className="bg-dark vh-100"> {showInfo && (<Toast updateShow={setShowInfo} message="Successful!!! Please login using new credentials" mode="info"></Toast>)} {showError && (<Toast updateShow={setShowError} message={errorMessage} mode="danger"></Toast>)} <div className="login-div p-3 bg-white rounded"> <div className="text-center p-1 mb-2"> <FontAwesomeIcon className="fa-lg" icon={faBus}></FontAwesomeIcon> <h3>UberBus</h3> </div> <Form noValidate validated={validated} onSubmit={handleSubmit}> <div className="mb-2"> <Button onClick={() => { setIsSignUp(false) }} className={`${isSignUp ? 'btn-light' : 'btn-dark'} w-50 `}>Login</Button> <Button onClick={() => { setIsSignUp(true) }} className={`${isSignUp ? 'btn-dark' : 'btn-light'} w-50 `}>SignUp</Button> </div> <div> <Form.Group> <Form.Group controlId="email"> <Form.Control type="email" value={username} onChange={(e) => { setUsername(e.target.value) }} placeholder="Enter Email" required /> <Form.Text className="text-muted"> We'll never share your email with anyone else. </Form.Text> <Form.Control.Feedback>Looks good!</Form.Control.Feedback> <Form.Control.Feedback type="invalid"> Please enter valid email address. </Form.Control.Feedback> </Form.Group> <Form.Group controlId="password"> <Form.Control type="password" value={password} onChange={(e) => { setPassword(e.target.value) }} placeholder="Enter Password" required /> <Form.Text className="text-muted"> Password is protected with end to end encryption </Form.Text> <Form.Control.Feedback>Looks good!</Form.Control.Feedback> <Form.Control.Feedback type="invalid"> Please enter valid password. </Form.Control.Feedback> </Form.Group> {isSignUp && (<div><Form.Group controlId="firstName"> <Form.Control type="text" value={firstName} onChange={(e) => { setfirstName(e.target.value) }} placeholder="<NAME>" required /> <Form.Control.Feedback>Looks good!</Form.Control.Feedback> <Form.Control.Feedback type="invalid"> Please enter first name. </Form.Control.Feedback> </Form.Group> <Form.Group controlId="lastName"> <Form.Control type="text" value={lastName} onChange={(e) => { setlastName(e.target.value) }} placeholder="<NAME>" required /> <Form.Control.Feedback>Looks good!</Form.Control.Feedback> <Form.Control.Feedback type="invalid"> Please enter valid last name. </Form.Control.Feedback> </Form.Group> </div>)} </Form.Group> </div> <div> <Button type="submit" className="bg-dark w-100">{isSignUp ? 'Signup' : 'Login'}</Button> </div> </Form> </div> </div> ) } export default Login;<file_sep>/Dockerfile FROM node as build WORKDIR /app COPY package*.json /app/ RUN npm install COPY ./ /app/ EXPOSE 3000 CMD npm start<file_sep>/src/components/Test/TestComms.js import React, { useState, useEffect } from "react"; import axios from 'axios'; const TestComms = () => { const [message, setMessage] = useState('Making Backend API Call'); useEffect( () => { axios.get(`${process.env.REACT_APP_BACKEND_HOST}/testHealth`) .then(resp => setMessage(resp.data)) .catch(err => setMessage("Error connecting backend")); } ,[]); return ( <div> {message} </div> ) } export default TestComms;
4db028f9196d77742dfe4446f115df60c810a851
[ "JavaScript", "Dockerfile" ]
8
JavaScript
DevOps-Spring2021/uber
618c6a3ff06e4f8b20c3d14eb760036943b59389
58872b344925fc1dba251376e79c7579b702b9e8
refs/heads/master
<file_sep>using Foundation; using System; using System.CodeDom.Compiler; using UIKit; using System.Diagnostics; namespace WeatherSettings { partial class SettingsViewController : UITableViewController { public SettingsViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); SwitchAlerts.ValueChanged += (sender, e) => Debug.WriteLine ("Alerts " + (SwitchAlerts.On ? "On" : "Off")); SwitchUnits.ValueChanged += (sender, e) => Debug.WriteLine ("Use " + (SwitchUnits.On ? "Celsius" : "Fahrenheit")); CellDefaultCity.DetailTextLabel.Text = "Virginia Beach"; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { Debug.WriteLine (String.Format ("Row {0} tapped", indexPath.Row)); } public override void AccessoryButtonTapped (UITableView tableView, NSIndexPath indexPath) { Debug.WriteLine (String.Format ("Accessory {0} tapped", indexPath.Row)); } } } <file_sep>using System; using System.Collections.Generic; namespace WeatherApp { public enum Conditions { Sunny, Cloudy, Windy, Rain, Snow, Rainbow, count } public class Weather { public string City { get; set; } public float Temperature { get; set; } public float High {get; set; } public float Low { get; set; } public Conditions CurrentConditions { get; set; } public override string ToString () { return string.Format ("[Weather: City={0}, Temperature={1}, High={2}, Low={3}, CurrentConditions={4}]", City, Temperature, High, Low, CurrentConditions); } } public static class WeatherFactory { public static List<Weather> GetWeatherData () { return new List<Weather> { new Weather () { City = "San Fransisco", Temperature = 50, High = 55, Low = 45, CurrentConditions = Conditions.Windy}, new Weather () { City = "Seattle", Temperature = 40, High = 46, Low = 33, CurrentConditions = Conditions.Rain }, new Weather () { City = "Vancouver", Temperature = 52, High = 53, Low = 46, CurrentConditions = Conditions.Cloudy }, new Weather () { City = "Washington DC", Temperature = 70, High = 75, Low = 55, CurrentConditions = Conditions.Sunny }, new Weather () { City = "Boston", Temperature = 40, High = 41, Low = 33, CurrentConditions = Conditions.Snow }, new Weather () { City = "Virginia Beach", Temperature = 75, High = 79, Low = 70, CurrentConditions = Conditions.Rainbow }, new Weather () { City = "Farmington", Temperature = 75, High = 79, Low = 70, CurrentConditions = Conditions.Sunny }, new Weather () { City = "Richardson", Temperature = 75, High = 79, Low = 70, CurrentConditions = Conditions.Cloudy }, new Weather () { City = "Buddina", Temperature = 75, High = 79, Low = 70, CurrentConditions = Conditions.Windy }, new Weather () { City = "Phoenix", Temperature = 75, High = 79, Low = 70, CurrentConditions = Conditions.Rain }, new Weather () { City = "Brunswick", Temperature = 75, High = 79, Low = 70, CurrentConditions = Conditions.Sunny }, new Weather () { City = "Cape Town", Temperature = 75, High = 79, Low = 70, CurrentConditions = Conditions.Cloudy }, new Weather () { City = "Haidholzen", Temperature = 75, High = 79, Low = 70, CurrentConditions = Conditions.Windy }, }; } } }
b09cb85e8434f5757fe82da039989c4701db01b1
[ "C#" ]
2
C#
XamarinUniversity/IOS115
aedd7cb9471f055acb560cfefe3b4b5fc8373c70
8b182973d556c22a3d9deb50672984cd7290822c
refs/heads/master
<repo_name>koerstz/QMConfTool<file_sep>/modules/createConformers.py from rdkit import Chem from rdkit.Chem import AllChem, rdmolops from rdkit.Chem import rdMolTransforms import itertools from multiprocessing import Pool import time import copy def systematic(m, theta=120.): """ Systematic rotation of dihedral angles theta degrees""" # Find indexes of atoms in dihedral angles. # Remember alcohols, thiols, and primery amines. rot_bonds_smarts = [ "[!#1]~[!$(*#*)&!D1]-!@[!$(*#*)&!D1]~[!#1]", # general rot bonds "[*]~[*]-[O,S]-[#1]", # alchol, and thiols "[*]~[*]-[NX3;H2]-[#1]", # primery amines ] raw_dihedral_idx = list() for bond_smart in rot_bonds_smarts: raw_dihedral_idx += m.GetSubstructMatches(Chem.MolFromSmarts(bond_smart)) rot_bonds_idx = list() # indexes of bonds to rotate around dihedral_idx = list() # indexes of dihedral for k, i, j, l in raw_dihedral_idx: if (i,j) not in rot_bonds_idx: rot_bonds_idx.append((i,j)) dihedral_idx.append((k,i,j,l)) ## find dihedrals of parent molecule and create all combinations ## where the angles are rotated theta degrees. parent_conf = m.GetConformer() dihedrals = list() for k, i, j, l in dihedral_idx: parent_dihedral = rdMolTransforms.GetDihedralDeg(parent_conf, k,i,j,l) new_dihedrals = [parent_dihedral + x*theta for x in range(int(360./theta))] dihedrals.append(new_dihedrals) dihedralCombs = list(itertools.product(*dihedrals)) print("number of initial conformers: {}".format(len(dihedralCombs))) # Create the conformations according to angle combinations # in dihedralCombs. mol_list = [] root_name = m.GetProp("_Name") for idx, dihedrals in enumerate(dihedralCombs): parent_mol = copy.deepcopy(m) parent_conf = m.GetConformer() for (k,i,j,l), angle in zip(dihedral_idx, dihedrals): rdMolTransforms.SetDihedralDeg(parent_conf, k,i,j,l, angle ) #rdMolTransforms.CanonicalizeConformer(parent_conf, ignoreHs=False) # translate mol to centroid parent_mol.SetProp("_Name", root_name + "-" + str(idx)) mol_list.append(parent_mol) return mol_list def random(m, numConfs): """ Create numConfs new random conformers from m """ AllChem.EmbedMultipleConfs(m, numConfs, AllChem.ETKDG()) mol_list = list() for idx, conf in enumerate(m.GetConformers()): conf_sdf_txt = Chem.SDWriter.GetText(m, conf.GetId()) rdkit_mol = Chem.MolFromMolBlock(conf_sdf_txt, removeHs=False) conf_name = m.GetProp("_Name") + "-" + str(idx) rdkit_mol.SetProp("_Name", conf_name) mol_list.append(rdkit_mol) return mol_list if __name__ == "__main__": smi = "C[C](O)CC[C@@H](C)OO" m = Chem.MolFromSmiles(smi) m = Chem.AddHs(m) AllChem.EmbedMolecule(m) m.SetProp("_Name", "test") w = Chem.SDWriter("test.sdf") for x in systematic(m, theta=180.): w.write(x) #print(Chem.MolToSmiles(x, isomericSmiles=True)) #Chem.DetectBondStereochemistry(m) #Chem.AssignStereochemistry(m, flagPossibleStereoCenters=True, force=True) #Chem.AssignAtomChiralTagsFromStructure(m) #print(Chem.MolToSmiles(m, isomericSmiles=True)) <file_sep>/modules/qmorca.py import re import os from subprocess import Popen, PIPE from multiprocessing import Pool import pandas as pd # local modules from modules.xyz2mol.xyz2mol import get_atomicNumList __ORCA_PATH__ = "/opt/orca/4.0.0/orca" def writeInput(rdkit, name, method, charge, mult, cpus, ts): """ Prepare ORCA input files """ # TODO: set procs and mem atomicSymbols = list() for atom in rdkit.GetAtoms(): atomicSymbols.append(atom.GetSymbol()) atomicPositions = rdkit.GetConformer().GetPositions() # write input file with open(name + "_orca.inp", 'w') as inp: # header inp.write("# " + name + "\n") inp.write("! " + method + "\n" ) # Mol block inp.write("* xyz " + str(charge) + " " + str(mult) + "\n") for i, symbol in enumerate(atomicSymbols): line = symbol + " " + " ".join(map(str, atomicPositions[i,:])) + "\n" inp.write(line) inp.write("*") def runORCA(name, method, keepFiles, ts): """ Run Calculation """ orca_cmd = __ORCA_PATH__ + " {}_orca.inp".format(name) with Popen( orca_cmd, shell=True, stdout=PIPE, stderr=PIPE) as p: output = p.stdout.read().decode('utf-8') # Write output files if keepFiles is True. if keepFiles: with open(name + "_orca.out", 'w') as out: out.write(output) # remove input files if keepFiles is False: if not keepFiles: os.remove(name + "_orca.inp") # Check if calculation converged. orca_converged = re.findall(".*ORCA TERMINATED NORMALLY.*",output,re.M) if not orca_converged: output = "not-converged" # clean dir for redundant files. if ts: redFiles = [".gbw", ".prop", ".txt", ".allxyz", ".trj", ".opt" ] else: if "opt" in method: redFiles = [ ".trj", ".gbw", ".engrad", ".xyz", "_property.txt", ".prop" ] else: redFiles = [".gbw", "_property.txt", ".prop"] for f in os.listdir('.'): if name in f and f.endswith(tuple(redFiles)): os.remove(f) return output def extractProps(content, confName, method, ts): """ """ if ts: # find idx of ts guess: scan_data = pd.read_csv(confName + "_orca.relaxscanscf.dat", sep="\s+", names=["dist", "energy"]) max_idx = scan_data["energy"].idxmax() atomicSymbolList = list() atomicPos = list() # extract TS guess structure with open(confName + "_orca.{:03}.xyz".format(max_idx+1), 'r') as f: num_atoms = f.readline() f.readline() for lines_read, line in enumerate(f): if lines_read == num_atoms: break atom = re.findall(r'[a-zA-Z]+', line)[0] numbers = re.findall(r'[-]?\d+\.\d*(?:[Ee][-\+]\d+)?', line) numbers = [float(number) for number in numbers] atomicPos.append(numbers) atomicSymbolList.append(atom) atomicNumList = get_atomicNumList(atomicSymbolList) new_props = {"confName": confName, "atomicNumList": atomicNumList, "atomicPos": atomicPos, "structure_method": "ts guess"} # clean dir os.system("rm {0}*_orca*xyz {0}*dat".format(confName)) else: energy = re.findall("FINAL SINGLE POINT ENERGY.*", content,re.MULTILINE) energy = energy[-1].split()[4] # find structure atomicSymbolList = list() atomicPos = list() p = "CARTESIAN COORDINATES \(ANGSTROEM\)(.*?)CARTESIAN COORDINATES \(A.U.\)" mol_block = re.findall(p, content, re.S)[-1] mol_block = mol_block.split('\n')[2:-3] for line in mol_block: line = line.split() atomicSymbolList.append(str(line[0])) coords = list(map(float, line[1:])) atomicPos.append(coords) atomicNumList = get_atomicNumList(atomicSymbolList) # use xyz2mol module # set properties theory = method.replace("opt", "").strip() new_props = {"confName": confName, "atomicNumList": atomicNumList, "atomicPos": atomicPos, "orca:(" + theory + ")": energy} if "opt" in method: new_props["structure_method"] = "orca:(" + theory + ")" return new_props def helpORCA(var): """ """ oldConf, oldProps, vardict = var writeInput(oldConf, oldProps["confName"], vardict["method"], vardict["charge"], vardict["mult"], vardict["cpus"], vardict["ts"]) output = runORCA(oldProps["confName"], vardict["method"], vardict["keepFiles"], vardict["ts"]) if output != "not-converged": newProps = extractProps(output, oldProps["confName"], vardict["method"], vardict["ts"]) updatedProps = {**oldProps, **newProps} else: print("did not converge: " + oldProps["confName"]) updatedProps = None return updatedProps def orca(confs, method="pm3", charge=0, mult=1, charged_fragments=True, cpus=8, keepFiles=False, ts=False): # Prepare dict with values needed for calculations vardict = {"method": method, "ts": ts, "charge": charge, "mult": mult, "cpus": cpus, "keepFiles": keepFiles, "charged_fragments": charged_fragments} varlist = list() for oldConf in confs: #confName = oldConf.GetProp("_Name") oldProps = oldConf.GetPropsAsDict() oldProps["confName"] = oldConf.GetProp("_Name") varlist.append((oldConf, oldProps, vardict)) # Run calculations in parallel. confsProps = list() if ts: # daemonic processes are not allowed to have children confsProps = [helpORCA(varlist[0])] else: with Pool(processes=cpus) as pool: confsProps = pool.map(helpORCA, varlist) return confsProps <file_sep>/modules/qmxtb.py import re import os from subprocess import Popen, PIPE from multiprocessing import Pool # local modules from modules.xyz2mol.xyz2mol import xyz2mol, get_atomicNumList __XTB_PATH__ = "/opt/xtb/5.8/xtb" def writeInput(rdkit, name, charge): """ Prepare xTB input (.xyz file) """ atomicSymbols = list() for atom in rdkit.GetAtoms(): atomicSymbols.append(atom.GetSymbol()) atomicPositions = rdkit.GetConformer().GetPositions() # write input file with open(name + ".xyz", 'w') as inp: # header inp.write(str(rdkit.GetNumAtoms()) + "\n") inp.write(name + "\n") # Mol block for i, symbol in enumerate(atomicSymbols): line = symbol + " " + " ".join(map(str, atomicPositions[i,:])) + "\n" inp.write(line) inp.write("$set \n") inp.write("chrg " + str(charge) + "\n") inp.write("$end") def runXTB(name, method, mult, keepFiles): """ Run Calculation """ if mult == 1: method = " -{}".format(method) else: method = " -{} -uhf {}".format(method, int(mult) -1) # Set env os.environ['XTBHOME'] = "/opt/xtb/5.8" os.environ['OMP_NUM_THREADS'] = str(1) os.environ['MKL_NUM_THREADS'] = str(1) # run XTB os.mkdir(name) os.rename(name + ".xyz", "./{0}/{0}.xyz".format(name)) xtb_cmd = __XTB_PATH__ + " {}.xyz".format(name) + method with Popen(xtb_cmd, shell=True, stdout=PIPE, stderr=PIPE, cwd=name) as p: output = p.stdout.read().decode('utf-8') # Write output files if keepFiles is True. if keepFiles: os.rename("./{0}/{0}.xyz".format(name), name + ".xyz") with open(name + ".out", 'w') as out: out.write(output) # Check if calculation converged. xtb_converged = re.findall(".*ancopt converged in .* cycles",output,re.M) if not xtb_converged: output = "not-converged" # clean dir for redundant directories. os.system("rm -rf " + name) return output def extractProps(content, confName, method): """ Extract properties from output file """ # Find mol block. It contains energy. atomicSymbolList = list() atomicPositions = list() mol_block = re.findall("final structure(.*?)Bond Distances", content, re.S) mol_block = mol_block[-1].split("\n") num_atoms = int(mol_block[2]) # Extract number of atoms energy = mol_block[3].strip() # Extract energy for line in mol_block[4:4+num_atoms]: line = line.split() atomicSymbolList.append(str(line[0])) coords = list(map(float, line[1:])) atomicPositions.append(coords) atomicNumList = get_atomicNumList(atomicSymbolList) # use xyz2mol module # collect new props new_props = {"confName": confName, "atomicNumList": atomicNumList, "atomicPos": atomicPositions, "xTB_energy": energy } if "opt" in method: new_props["structure_method"] = "xTB" return new_props def helpXTB(var): """ XTB helper funciton """ oldConf, oldProps, vardict = var writeInput(oldConf, oldProps["confName"], vardict["charge"]) output = runXTB(oldProps["confName"], vardict["method"], vardict["mult"], vardict["keepFiles"]) if output != "not-converged": newProps = extractProps(output, oldProps["confName"], vardict["method"]) updatedProps = {**oldProps, **newProps} else: print("did not converge: " + oldProps["confName"]) updatedProps = None return updatedProps def xtb(confs, method="opt", charge=0, mult=1, charged_fragments=True, cpus=8, keepFiles=False): """ """ # Prepare dict with values needed for calculations vardict = {"method": method, "charge": charge, "mult": mult, "cpus": cpus, "keepFiles": keepFiles, "charged_fragments": charged_fragments} varlist = list() for oldConf in confs: oldProps = oldConf.GetPropsAsDict() oldProps["confName"] = oldConf.GetProp("_Name") varlist.append((oldConf, oldProps, vardict)) # Run xTB calculation confsProps = [] with Pool(processes=cpus) as pool: confsProps = pool.map(helpXTB, varlist) return confsProps <file_sep>/modules/out2mol.py from rdkit import Chem import openbabel # Local Modules import modules.xyz2mol.xyz2mol as xyz2mol from modules import qmxtb, qmorca, qmdftbopt, qmgaussian, qmrdkit def writeXYZstring(name, atomicNumList, charge, xyz_coordinates): pt = Chem.GetPeriodicTable() xyzString = str(len(atomicNumList)) + "\n" xyzString += name + "\n" for i, pos in enumerate(xyz_coordinates): symbol = pt.GetElementSymbol(atomicNumList[i]) xyzString += "{} {} {} {} \n".format(symbol, pos[0],pos[1],pos[2]) xyzString += "$set" xyzString += str(charge) + "\n" xyzString += "$end" return xyzString def babelAC2mol(name, atomicNumList, charge, xyz_coordinates, charged_fragments): """ Get new RDKit mol using babels adjecency matrix (AC) """ xyzString = writeXYZstring(name, atomicNumList, charge, xyz_coordinates) # Use obabel to convert xyz string to sdf string obConversion = openbabel.OBConversion() obConversion.SetInAndOutFormats("xyz", "sdf") m = openbabel.OBMol() obConversion.ReadString(m, xyzString) sdfString = obConversion.WriteString(m) # Create RDKit mol from sdf string rdkit = Chem.MolFromMolBlock(sdfString, removeHs=False) ACmat = Chem.GetAdjacencyMatrix(rdkit) atomicNumList = list() # atomic numbers for atom in rdkit.GetAtoms(): atomicNumList.append(int(atom.GetAtomicNum())) xyz = [] # atomic posistions for atomPos in rdkit.GetConformer().GetPositions(): xyz.append(atomPos) # Create proto_mol and set coords and bond order. proto_mol = xyz2mol.get_proto_mol(atomicNumList) conf = Chem.Conformer(proto_mol.GetNumAtoms()) for i in range(proto_mol.GetNumAtoms()): conf.SetAtomPosition(i,(xyz[i][0],xyz[i][1],xyz[i][2])) proto_mol.AddConformer(conf) new_mol = xyz2mol.AC2mol(proto_mol, ACmat, atomicNumList, charge, charged_fragments, quick=False) return new_mol def normalAC2mol(atomicNumList, charge, xyz_coordinates, charged_fragments): """ Get new RDKit mol using xyz2mols adjacency matrix (AC) """ new_mol = xyz2mol.xyz2mol(atomicNumList, charge, xyz_coordinates, charged_fragments, quick=True) return new_mol def updateProps(newConfsProps, charge, method, charged_fragments, babelAC): """ Update the properties of the new RDKit mol(confName, energy, structure_method, etc.) """ updatedConfs = list() for confProps in newConfsProps: # if calculation didn't converge don't # create new mol. if confProps == None: continue confName = confProps.pop("confName") atomicNumList = confProps.pop("atomicNumList") atomicPos = confProps.pop("atomicPos") if babelAC: newConf = babelAC2mol(confName, atomicNumList, charge, atomicPos, charged_fragments) if not babelAC: newConf = normalAC2mol(atomicNumList, charge, atomicPos, charged_fragments) # set conf properties newConf.SetProp("_Name", confName) for prop in confProps.items(): propName, val = prop newConf.SetProp(str(propName), str(val)) updatedConfs.append(newConf) return updatedConfs def runCalculation(confs, program, method="opt", charge=0, mult=1, cpus=8, charged_fragments=True, keepFiles=False, babelAC=False, ts=False): """ Run QM calculation. And return updated RDKit mols """ if program == "rdkit": newConfsProps = qmrdkit.rdkit(confs, method, cpus) # update properties for rdkit confs. newConfs = list() for confProps in newConfsProps: newConf = confProps.pop("newConf") newConf.SetProp("_Name", confProps.pop("confName")) for propName, val in confProps.items(): newConf.SetProp(str(propName), str(val)) newConfs.append(newConf) else: if program == "xtb": newConfsProps = qmxtb.xtb(confs, method, charge, mult, charged_fragments, cpus, keepFiles) if program == "orca": newConfsProps = qmorca.orca(confs, method, charge, mult, charged_fragments, cpus, keepFiles, ts) if program == "dftb": newConfsProps = qmdftbopt.dftb(confs, method, charge, mult, charged_fragments, cpus, keepFiles) if program in ["gaussian", "g19"]: newConfsProps = qmgaussian.gaussian(confs, method, charge, mult, charged_fragments, cpus, keepFiles) newConfs = updateProps(newConfsProps, charge, method, charged_fragments, babelAC) for conf in newConfs: Chem.SanitizeMol(conf) # Clean confs after QM opt. return newConfs <file_sep>/modules/qmgaussian.py import re import os from subprocess import Popen, PIPE from multiprocessing import Pool # local modules from modules.xyz2mol import xyz2mol __GAUSSIAN_PATH__ = "/opt/gaussian/g16/g16" def writeInput(rdkit, name, method, charge, mult): """ Prepare gaussian input files """ atomicSymbols = list() for atom in rdkit.GetAtoms(): atomicSymbols.append(atom.GetSymbol()) atomicPositions = rdkit.GetConformer().GetPositions() # write input file with open(name + "_g16.com", 'w') as inp: # header inp.write("%nprocshared=1 \n") inp.write("%mem=4GB \n") # method block inp.write("# " + method + "\n") # title block inp.write("\n" + name + "\n" + "\n") # mol block inp.write(str(charge) + " " + str(mult) + "\n") for i, symbol in enumerate(atomicSymbols): line = symbol + " " + " ".join(map(str, atomicPositions[i,:])) + "\n" inp.write(line) inp.write("\n") # mysterious blank line def runGaussian(name, keepFiles): """ Run calculation """ g16_cmd = __GAUSSIAN_PATH__ + " {}_g16.com".format(name) with Popen( g16_cmd, shell=True, stdout=PIPE, stderr=PIPE) as p: output = p.stdout.read().decode('utf-8') # Write output files if keepFiles is True. if keepFiles: with open(name + "_g16.out", 'w') as out: out.write(output) # remove input files if keepFiles is False: if not keepFiles: os.remove(name + "_g16.com") # Check if calculation converged. g16_converged = re.findall("Normal termination of Gaussian.*",output,re.M) if not g16_converged: output = "not-converged" return output def extractProps(content, confName, method): """ extract properties from output """ energy = re.findall("SCF Done: .*", content,re.MULTILINE)[-1] energy = energy.split()[4] dipole = re.findall(".*Tot=.*", content,re.M)[-1] dipole = dipole.split()[-1] # find structure atomicNumList = list() atomicPositions = list() mol_block = re.findall("Standard orientation:(.*?)Rotational constants", content, re.S)[-1] mol_block = mol_block.split('\n')[5:-2] for line in mol_block: line = line.split() atomicNumList.append(int(line[1])) coords = list(map(float, line[3:])) atomicPositions.append(coords) # collect new updated props theory = method.replace("opt", "").strip() newProps = {"confName": confName, "atomicNumList": atomicNumList, "atomicPos": atomicPositions, "g16:(" + theory + ")": energy} if "opt" in method: newProps["g16(" + theory + ")_dipole"] = dipole newProps["structure_method"] = "g16:(" + theory + ")" return newProps def helpGaussian(var): """ Gaussian helper function """ oldConf, oldProps, vardict = var writeInput(oldConf, oldProps["confName"], vardict["method"], vardict["charge"], vardict["mult"]) output = runGaussian(oldProps["confName"], vardict["keepFiles"]) if output != "not-converged": newProps = extractProps(output, oldProps["confName"], vardict["method"]) updatedProps = {**oldProps, **newProps} else: print("did not converge: " + oldProps["confName"]) updatedProps = None return updatedProps def gaussian(confs, method="pm3", charge=0, mult=1, charged_fragments=True, cpus=8, keepFiles=False): # Prepare dict with values needed for calculations vardict = {"method": method, "charge": charge, "mult": mult, "cpus": cpus, "keepFiles": keepFiles, "charged_fragments": charged_fragments} varlist = list() for oldConf in confs: oldProps = oldConf.GetPropsAsDict() oldProps["confName"] = oldConf.GetProp("_Name") varlist.append((oldConf, oldProps, vardict)) # Run GAUSSIAN calculation confsProps = [] with Pool(processes=cpus) as pool: confsProps = pool.map(helpGaussian, varlist) return confsProps <file_sep>/qmconftool.py import sys from rdkit import Chem from rdkit.Chem import AllChem, TorsionFingerprints from rdkit.ML.Cluster import Butina # local modules from modules import createConformers from modules import out2mol class QMMol(): """ To get properties ie. rdkit_mol.GetPropsAsDict() """ def __init__(self, mol_info, fmt='smiles', name="useless_name", charge=0, multi=1, charged_fragments=True): self.name = str(name) self.conformers = list() # molecular attributes self.charge = int(charge) self.multi = int(multi) self.charged_fragments = charged_fragments if fmt not in ['smiles', 'smi', 'rdkit_mol', 'rdkit','mol_list']: sys.exit("format not suported") if fmt.lower() in ['smiles', 'smi']: self.init_mol = Chem.MolFromSmiles(mol_info) self.init_mol = Chem.AddHs(self.init_mol) self.init_mol.SetProp("_Name", self.name) # Initialize conf AllChem.EmbedMolecule(self.init_mol) AllChem.UFFOptimizeMolecule(self.init_mol) if fmt.lower() == 'rdkit_mol': self.init_mol = Chem.AddHs(mol_info) self.init_mol.SetProp("_Name", self.name) self.conformers = [self.init_mol] if fmt.lower() == 'mol_list': self.conformers = mol_info def InitiateConformers(self, method='systematic', theta=120, numConfs=100): """ Create conformers """ if method == "systematic": confs = createConformers.systematic(self.init_mol, theta=theta) if method == "random": confs = createConformers.random(self.init_mol, numConfs) self.conformers = confs def optimize(self, program="gaussian", method="pm3", cpus=8, keepFiles=False, babelAC=False, maxIters=200, ts=False): """ Use QM programs to optimize structures. Update old RDKit mol to the new optimized structure, and set molecular properties (energy, structure_method, etc.). """ # Check if program is implemented. if program.lower() not in ["gaussian", "dftb", "orca", "xtb", "rdkit"]: sys.exit(program + " is not implemeted yet") self.conformers = out2mol.runCalculation(self.conformers, program, method, self.charge, self.multi, cpus, self.charged_fragments, keepFiles, babelAC, ts) def GetUniqueConformers(self, method='TFD', distThresh=0.01): """ Perform Butina clustering on structures to remove identical conformers. """ if method.upper() not in ["RMS", "TFD"]: sys.exit("method not defined.") for i, conf in enumerate(self.conformers): if i == 0: mol = conf else: mol.AddConformer(conf.GetConformer(), assignId=i) AllChem.AlignMolConformers(mol) numConfs = mol.GetNumConformers() if method.upper() == 'TFD': diffmat = TorsionFingerprints.GetTFDMatrix(mol) if method.upper() == 'RMS': diffmat = AllChem.GetConformerRMSMatrix(mol, prealigned=True) clt = Butina.ClusterData(diffmat, numConfs, distThresh, isDistData=True, reordering=True) uniqeConfs = list() for idx, clust in enumerate(clt): centroid_idx = clust[0] # 0th element is cluster centroid. conf_sdf_txt = Chem.SDWriter.GetText(mol, centroid_idx) uniqueConf = Chem.MolFromMolBlock(conf_sdf_txt, removeHs=False) uniqueConf.SetProp("_Name", self.name + "-" + str(idx)) uniqeConfs.append(uniqueConf) self.conformers = uniqeConfs def GetConformers(self): """ Return conformers """ if not self.conformers: sys.exit("no conformers created") return self.conformers def GetConformer(self, ConfId): """ Return conformer with ConfId """ if not self.conformers: sys.exit("no conformers created") return self.conformers[ConfId] def GetNumConformers(self): """ Return the number of conformers """ return len(self.conformers) if __name__ == "__main__": #smi = "CC(=O)Nc1ccc(cc1)O" smi = "O=C(Oc1ccccc1C(=O)O)C" # acetylsalicylsyre #smi = "C[C](C[C@@H](CC)OO)O" # mult 2, charge=0 - ie radical. #smi = "CCO" # ethanol m = QMMol(smi, fmt="smiles", name="ethanol", charge=0, multi=1) m.InitiateConformers(method="systematic", theta=180.) #m.optimize(program="dftb", method="rhf", cpus=8, keepFiles=False, babelAC=False) m.optimize(program="xtb", method="opt", cpus=8, keepFiles=False, babelAC=False) #m.optimize(program="rdkit", method="opt MMFF94", cpus=8, maxIters=200) #m.optimize(program="orca", method="pm3", cpus=8, keepFiles=False, babelAC=False) #m.optimize(program="rdkit", method="MMFF94", cpus=8, maxIters=200) #m.optimize(program="gaussian", method="pm3", cpus=8, keepFiles=False, babelAC=False) for c in m.GetConformers(): print(c.GetPropsAsDict(), c.GetProp("_Name")) <file_sep>/modules/qmdftbopt.py import re import os from itertools import product, repeat from subprocess import Popen, PIPE from multiprocessing import Pool from modules.xyz2mol import xyz2mol __GAMESS_PATH__ = "/home/charnley/opt/gamess/github-2017-08-29/rungms" __SKF_PATH__ = "/home/andersx/dftb/3ob-3-1" __GAMESS_SCR_DIR__ = "/home/koerstz/scr" def writeInput(rdkit, name, method="RHF", charge=0, mult=1): """ Prepare DFTB input for GAMESS """ header = """ $system mwords=20 modio=32 $end $scf npunch=0 $end $contrl runtyp=optimize scftyp={} icharg={} mult={} nprint=-5 $end $statpt nstep=500 opttol=5.0e-4 $end $basis gbasis=dftb $end $dftb ndftb=3 dampxh=.t. dampex=4.0 $end $dftbsk \n""".format(method, charge, mult) atomicSymbol = list() atomicNumber = list() for atom in rdkit.GetAtoms(): atomicSymbol.append(atom.GetSymbol()) atomicNumber.append(atom.GetAtomicNum()) atomicPositions = rdkit.GetConformer().GetPositions() # Write SKF block for atomPair in product(set(atomicSymbol),repeat=2): skf = ' {0} {1} "/home/andersx/dftb/3ob-3-1/{0}-{1}.skf" \n'.format(*atomPair) header += skf header += " $end \n \n" # Write mol data block data_block =" $DATA \n \n C1 \n" for i in range(len(atomicSymbol)): atom_line = atomicSymbol[i] + "\t" + str(atomicNumber[i]) + "\t" atom_line += " ".join(map(str,atomicPositions[i,:])) + "\n" data_block += atom_line data_block += " $END" # Write DFTB input file with open(name + "_dftb.inp", 'w') as f: f.write(header + data_block) def runDFTB(name, keepFiles): """ Starts GAMESS DFTB calculation. Writes output files if keepFiles is True, and removes input if False. """ dftb_cmd = __GAMESS_PATH__ + " " + name + "_dftb.inp" with Popen(dftb_cmd, shell=True, stdout=PIPE, stderr=PIPE) as p: output = p.stdout.read().decode('utf-8') # Write output files if keepFiles is True. if keepFiles: with open(name + "_dftb.out", 'w') as out: out.write(output) # remove input files if keepFiles is False: if not keepFiles: os.remove(name + "_dftb.inp") # Check if DFTB converged gamess_converged = re.findall("EXECUTION OF GAMESS TERMINATED NORMALLY .*", output) if not gamess_converged: output = "not-converged" return output def extractProps(content, confName, numAtoms): """ Extracts properties from output content """ energy = re.findall(" NSERCH:.*", content)[-1] energy = energy.split()[3] # find structure structurePattern = re.compile("COORDINATES OF ALL ATOMS ARE") content_split = content.split('\n') for i, line in enumerate(content_split): if re.search(structurePattern, line) is not None: start_line = i atomicNumList = list() atomicPos = list() for atomInfo in content_split[start_line+3:start_line+numAtoms+3]: atomInfo = atomInfo.split() atomicNumList.append(int(float(atomInfo[1]))) atomicPos.append(list(map(float, atomInfo[2:]))) new_props = {"confName": confName, "atomicNumList": atomicNumList, "atomicPos": atomicPos, "dftb_energy": energy, "structure_method": "dftb"} return new_props def helpDFTB(var): """ MP helper function""" oldConf, oldProps, numAtoms, vardict = var writeInput(oldConf, oldProps["confName"], vardict["method"], vardict["charge"], vardict["mult"]) output = runDFTB(oldProps["confName"], vardict["keepFiles"]) if output != "not-converged": newProps = extractProps(output, oldProps["confName"], numAtoms) updatedProps = {**oldProps, **newProps} else: print("did not converge: " + oldProps["confName"]) updatedProps = None return updatedProps def dftb(confs, method="opt", charge=0, mult=1, charged_fragments=True, cpus=8, keepFiles=False): os.system("rm -f ~/scr/*") # remove files in scr dir # Prepare dict with values needed for calculations vardict = {"method": method, "charge": charge, "mult": mult, "cpus": cpus, "keepFiles": keepFiles, "charged_fragments": charged_fragments} varlist = list() for oldConf in confs: oldProps = oldConf.GetPropsAsDict() oldProps["confName"] = oldConf.GetProp("_Name") numAtoms = oldConf.GetNumAtoms() varlist.append((oldConf, oldProps, numAtoms, vardict)) # Run DFTB calculation confsProps = [] with Pool(processes=cpus) as pool: confsProps = pool.map(helpDFTB, varlist) return confsProps <file_sep>/modules/qmrdkit.py from rdkit import Chem from rdkit.Chem import AllChem from multiprocessing import Pool import copy def extractProps(conf, method, maxIters=200): """ """ forcefield = method.replace("opt", "").strip() # Choose forcefield if forcefield in ["MMFF", "MMFF94"]: pyMP = AllChem.MMFFGetMoleculeProperties(conf, mmffVariant=forcefield) ff = AllChem.MMFFGetMoleculeForceField(conf, pyMP) if forcefield in ["UFF"]: ff = AllChem.UFFGetMoleculeForceField(conf) # optimize conformer of get sp energy if "opt" in method: ff.Initialize() ff.Minimize(maxIts=maxIters) energy = ff.CalcEnergy() # set new props new_props = {"newConf": conf, "rdkit(" + forcefield +"):": energy} if "opt" in method: new_props["structure_method"] = "rdkit( " + forcefield +"):" return new_props def helpRDKit(var): oldConf, oldProps, vardict = var newProps = extractProps(oldConf, vardict["method"], vardict["maxIters"]) updatedProps = {**oldProps, **newProps} return updatedProps def rdkit(confs, method="MMFF94s", cpus=8, maxIters=200): """ """ vardict = {"method": method, "cpus": cpus, "maxIters": maxIters} varlist = list() for oldConf in confs: oldProps = oldConf.GetPropsAsDict() oldProps["confName"] = oldConf.GetProp("_Name") varlist.append((oldConf, oldProps, vardict)) confsProps = list() with Pool(processes=cpus) as pool: newConfs = pool.map(helpRDKit, varlist) return newConfs
b935a8e17e1097a00dbbe05fd7e3f75f9f0dd8c4
[ "Python" ]
8
Python
koerstz/QMConfTool
1391f3ff4ed6861839879744a852b86ef392c580
6f6056b0e59f8cc6e0d4fafca201c1f646ea5eef
refs/heads/master
<repo_name>xuyangit/SpatialExperiments<file_sep>/make-dis.sh~ #! /bin/bash rm -r /env/sparkspatial-bak mv /env/sparkspatial /env/sparkspatial-bak cp -r /home/xuyang/SparkSpatialKeyword/SparkSpatial/dist /env/sparkspatial rm -r /env/sparkspatial/conf cp -r /env/sparkspatial-bak/conf/ /env/sparkspatial/conf rm -r /env/sparkspatial/sbin/ cp -r /env/sparkspatial-bak/sbin/ /env/sparkspatial/sbin rm -r /env/sparkspatial/bin/ cp -r /env/sparkspatial-bak/bin/ /env/sparkspatial/bin cd /env ./dist-sparkspatial.sh /env/sparkspatial/sbin/stop-all.sh /env/sparkspatial/sbin/start-all.sh <file_sep>/run_knn #!/bin/bash echo "run knn" #input=(sample1_5k) #part=(10) #k=(1 3) #input=(sample1_10k sample1_50k sample1_100k sample1_200k sample1_300k ) #input=(sample1_5k sample1_10k sample1_50k sample1_100k sample1_200k sample1_300k ) #part=(10 54 108 216) k=(10) #input=(gaussian_30m gaussian_50m gaussian_70m gaussian_100m gaussian_300m gaussian_500m gaussian_700m) #query=(query_gaussian_30m_10k query_gaussian_50m_10k query_gaussian_70m_10k query_gaussian_100m_10k query_gaussian_300m_10k query_gaussian_500m_10k query_gaussian_700m_10k) #size=(30000000 50000000 70000000 100000000 300000000 500000000 700000000) input=(gdelt_75427954) query=(gdelt-query-point) size=(75427954) part=(500000) #part=(100000 300000 500000 700000) #input=(sample1_5k) #part=(10) #sample_rate=(0.0001) for ((n = 0; n < 1; ++n)) do #for i in ${input[@]}; do # for ds in ${size[@]}; do for p in ${part[@]}; do for s in ${k[@]}; do i=${input[$n]} ds=${size[$n]} q=${query[$n]} name="knn-"$i'_'$p'_'$s echo -e "knn-"$i"\t"$p"\t"$s"\t" /env/sparkspatial/bin/spark-submit \ --class org.apache.spark.examples.experiment.KNNQuery \ --master spark://head:7077 \ --driver-memory 10g \ --executor-memory 15g \ --total-executor-cores 54 \ ./target/scala-2.10/knn-join_2.10-1.0.jar \ 'hdfs://head:9000/user/gefei/gdelt/'$i \ 'hdfs://head:9000/user/gefei/gdelt/'$q \ 'hdfs://head:9000/user/zhouliang/output/'$name \ $ds \ $p \ $s \ 2> stderr/$name #1> ./throughput/$name 2> stderr/$name done done # done done <file_sep>/run_brq~ #!/bin/bash echo "run brq" input=("CA/CAN14m" "TA/TXN14M") query=("CA/BRQ/" "TA/BRQ") size=(13820481 14182368) part=(500000) isExact=("true" "false") usingNaive=("true" "false") theta=(0 1 2 3 4) sampleRate=1.0 for ((n = 0; n <= 1; ++n)) do for flagOfExact in ${isExact[@]}; do for flagOfNaive in ${usingNaive[@]}; do for p in ${part[@]}; do for s in ${theta[@]}; do i=${input[$n]} ds=${size[$n]} q=${query[$n]} name="brq-"$i'_'$p'_exactis'$flagOfExact'_usingNaiveis'$flagOfNative'_'$s'_percent' echo -e "brq-"$i"\t"$p"\t"$s"\t" /env/sparkspatial/bin/spark-submit \ --class org.apache.spark.examples.experiment.BooleanRangeQuery \ --master spark://head:7077 \ --driver-memory 10g \ --executor-memory 15g \ --total-executor-cores 54 \ ./target/scala-2.10/knn-join_2.10-1.0.jar \ 'hdfs://head:9000/user/xuyang/Dataset/'$i \ 'hdfs://head:9000/user/xuyang/Dataset/'$q'query'$s'.txt' \ 'hdfs://head:9000/user/xuyang/output/'$name \ $ds \ $p \ $sampleRate \ $flagOfExact \ $flagOfNaive \ 2> stderr/$name #1> ./throughput/$name 2> stderr/$name done done done done done
43d9c11df38ff9b94c205e7860fa7f77977e054c
[ "Shell" ]
3
Shell
xuyangit/SpatialExperiments
b03d0665a57a7d3f5cb0e40408e187b486075dc8
44054bf62fd6fa767ecce776dfb386d3b4342792
refs/heads/main
<file_sep>import tkinter as tk from PIL import Image, ImageTk from functools import partial from tkinter import messagebox import os #背包类 class PackageGUI(tk.Canvas): #初始化参数 def __init__(self, root, w=360, h=400): """ Initialize :return: """ super().__init__(root, width=w, height=h) #初始化对象,同时设置高宽 self.width = w self.height = h self.imglist = {} #保存图片对象 #弹窗显示描述 def display(self, description): """ The popover displays the description :return: """ messagebox.showinfo(title='Description', message=description) #更新背包内容 def udpate(self, package): """ Update backpack content :return: """ self.delete(tk.ALL) #先清空画布 #布置背景图 try: img = ImageTk.PhotoImage(Image.open('res/package.png').resize((360, 400), Image.ANTIALIAS)) #缩放图片 self.imglist['package'] = img #添加图片对象到列表 self.create_image(0, 0, image=img, anchor='nw') except Exception as e: print(str(e)) #布置背包内容 count = 0 #记录第几个物品 for i in package: #新建物品按钮 bt = tk.Button(self, bd=0, relief=tk.SOLID, command=partial(self.display, i.description)) #新建按钮组件 bt_win = self.create_window(15+90*(count%4), 20+90*(count//4), window=bt, anchor='nw', width=60, height=60) #绘制组件 #设置物品的图片 try: imgpath = 'res/thing'+str(i.type)+'.png' ## print(imgpath) if os.path.exists(imgpath): img = ImageTk.PhotoImage(Image.open(imgpath).resize((60, 60), Image.ANTIALIAS)) #缩放图片 else: img = ImageTk.PhotoImage(Image.open('res/thing.png').resize((60, 60), Image.ANTIALIAS)) #缩放图片 self.imglist['thing'+str(i.id)] = img #添加图片对象到列表,这里注意下,要用ID,不能把上一个按钮的图片对象给覆盖掉 bt.config(image=img) #给按钮加上图片 except Exception as e: print(str(e)) count += 1 #计数+1 <file_sep>import unittest from Room import Room from Thing import Thing from Game import Game from Package import PackageGUI class MyTestCase(unittest.TestCase): def setUp(self): self.game = Game() def test_updateRoom(self): try: self.game.updateRoom() assert(True) self.game.currentRoom = self.game.lobby self.game.updateRoom() assert(True) except Exception as e: print('error'+str(e)) assert(False) def test_addMsg(self): try: self.game.addMsg('sksksk') assert(True) except Exception as e: print('error:'+str(e)) assert(False) def test_start(self): try: self.game.start() assert(True) except Exception as e: print('error:'+str(e)) assert(False) def test_startPage(self): try: self.game.startPage() assert(True) except Exception as e: print('error:'+str(e)) assert(False) def test_move(self): try: self.game.move([11,233], ('aaa', None)) assert(True) except Exception as e: print('error:'+str(e)) assert(False) def test_moving(self): try: self.game.moving() assert(True) except Exception as e: print('error:'+str(e)) assert(False) def test_doAttackCommand(self): try: self.game.doAttackCommand([111,22]) assert(True) except Exception as e: print('error:'+str(e)) assert(False) def test_doPackageCommand(self): try: self.game.doPackageCommand() assert(True) except Exception as e: print('error:'+str(e)) assert(False) def test_saveGame(self): try: self.game.saveGame() assert(True) except Exception as e: print('error:'+str(e)) assert(False) if __name__ == '__main__': unittest.main() <file_sep>""" Create a room described "description". Initially, it has no exits. 'description' is something like 'kitchen' or 'an open court yard' """ from Thing import Thing class Room: #加一个房间名 def __init__(self, roomname, description): """ Constructor method :param description: text description for this room """ self.description = description self.exits = {} # Dictionary self.key = 0 # Key id[int] big then 0 self.things = [] #加一个房间名 self.roomname = roomname def setExit(self, direction, neighbour): """ Adds an exit for a room. The exit is stored as a dictionary entry of the (key, value) pair (direction, room) :param direction: The direction leading out of this room :param neighbour: The room that this direction takes you to :return: None """ self.exits[direction] = neighbour def getShortDescription(self): """ Fetch a short text description :return: text description """ return self.description def getLongDescription(self): """ Fetch a longer description including available exits :return: text description """ return f'Location: {self.description}, Exits: {self.getExits()} ' def getLongDescription2(self): """ Fetch a longer description for bedroom. :return: text description """ return f'Location: {self.description} ' def getLongDescription3(self): """ Fetch a longer description including available exits :return: text description """ return f'Location: {self.description}, Exits: {self.getExits()} ' def getExits(self): """ Fetch all available exits as a list :return: list of all available exits """ allExits = self.exits.keys() return list(allExits) def getExit(self, direction): """ Fetch an exit in a specified direction :param direction: The direction that the player wishes to travel :return: Room object that this direction leads to, None if one does not exist """ if direction in self.exits: return self.exits[direction] else: return None def createThing(self, _desc, _id, _type = 0): """ Create a item or key in your package. :param _desc, _id, _type: The attribute of these item. :return: None """ t = Thing(_desc) t.setType(_type) t.setId(_id) self.pushThing(t) def pushThing(self, _thing): """ add item/key :param _thing: The object item/key. :return: None """ self.things.append(_thing) def popThing(self): """ delete item/key from the list :return: delete the object from the list """ return self.things.pop() def isEmpty(self): """ Whether it is empty :return: return 0 if the it is empty """ return len(self.things) == 0 def listThing(self): """ list all the item/key in there. :return: return all the element in the list """ return ", ".join([t.description for t in self.things]) def checkThingType(self): """ check the item, and print the detail of it. :return: return details """ for t in self.things: if t.type == 1: return f'Detail: You are getting closer and closer to success.' elif t.type == 2: return f'Detail: This is a very important item.' elif t.type == 66: return f'Detail: These are the weapens which can be used to defeat Dr. Evil.' else: return f'Detail: This is just a normal item.' def pickupThing(self): """ After picking up the item/key, the place(room) where it was stored loses this item/key. :return: Remove the item in the place, None otherwise """ if len(self.things) > 0: return self.things.pop(0) else: return None def setLock(self, lockid): """ set the lock in the door of the room :param lockid: The id of the door. :return: None """ self.key = lockid def needKey(self): """ check whether it need a key or not. :return: key > 0 """ return self.key > 0 def getLockId(self): """ The lock. :return: key """ return self.key <file_sep>import random class Thing: def __init__(self, description): """ Constructor method :param description: text description for this room """ # Type [0: normal, 1: key, 2: final thing] self.description = description self.type = 0 self.id = 0 self.location = [random.randint(80, 750), random.randint(80, 420)] #随机生成地址 def setType(self, _type): self.type = _type def getType(self): return self.type def setId(self, _id): self.id = _id def getId(self): return self.id def getShortDescription(self): """ Fetch a short text description :return: text description """ return self.description def getLongDescription(self): """ Fetch a longer description including available exits :return: text description """ if (1 == self.type): return f'this is a key, can unlock room:{self.type}' elif (2 == self.type): return f'this is a final thing.' else: return f'this is a normal thing' <file_sep>from Thing import Thing from Room import Room from TextUI import TextUI #添加部分 import tkinter as tk from tkinter import messagebox from PIL import Image, ImageTk from functools import partial import time, os """ You are a person with the ability to travel through time and space, and you live in a peaceful and warm world. However, on an ordinary day, Dr. Evil broke this peace …… Dr. Evil, who lives in the future, is ready to come to the world you live in and planning to destroy your world. The only way to save your world is to bring back Dr. Evil's weapons, handbooks for invasion, or other important items from the future in Dr. Evil’s territory, and defeat Dr. Evil through the Homeland Defense Bureau's research. As the only time traveler in the current world, you have to take your time shuttle to the future Dr. Evil's home, find these useful items successfully and return to your world in the time shuttle timely. Of course, you can also destroy Dr. Evil by using laser weapons. But the risk is also great. Once you meet Dr. Evil and without laser weapon in your hand, you will be brutally killed by him. According to the manual, your initial point will be the location: <OUTSIDE> of Dr. Evil's house and you can find your time shuttle in the location: <GARAGE>. You need to collect no less than 6 items(don’t exceed the limit of the backpack capacity)! You need to go across many kinds of rooms to find these useful items, and even some of rooms are locked differently. So what you should do is to find the keys and follow the clues to unlock the corresponding doors Be careful not to be caught by Dr. Evil!Dr. Evil will catch and kill you if you go to his location: <BEDROOM>! The game will provide 5 different endings and evaluate the level you get –- from S to D! """ class Game: def __init__(self): """ Initialises the game """ self.createRooms() self.currentRoom = self.outside self.textUI = TextUI() self.package = [] #初始化界面 self.root = tk.Tk() #TK主程序 self.root.title("Game") #左上角标题 screen_width = self.root.winfo_screenwidth() #windows屏幕宽 screen_height = self.root.winfo_screenheight() #windows屏幕高 self.width = 960 #窗口宽 self.height = 720 #窗口高 x = (screen_width/2) - (self.width/2) #计算中心点位置 y = (screen_height/2) - (self.height/2) self.root.geometry('%dx%d+%d+%d' % (self.width, self.height, x, y)) #重置窗口大小和位置 self.root.resizable(0, 0) #设置窗口大小不可变化 self.root.config(bg='black') #背景色 #初始化游戏界面 self.createGUI() #初始化游戏界面 def createGUI(self): #初始化界面 self.imglist = {} #保存图片对象用的 self.player_location = [450, 210] #玩家位置 self.move_flag = False #设置开始动画的标识 #房间背景 self.roombg = tk.Label(self.root, bd=0, width=960, height=540) #房间背景的标签对象 self.roombg.place(x=0, y=0, width=960, height=540) #布置到界面上 try: img = ImageTk.PhotoImage(Image.open('res/bg.png').resize((960, 540), Image.ANTIALIAS)) #缩放图片 self.imglist['roombg'] = img #添加图片对象到列表 self.roombg.config(image=img) #给标签对象加上图片背景 except: pass #房间名,左下角的标签 self.roomname = tk.Label(self.root, bd=0, font=('Arial', 16), width=len('Hello')*15, bg='black', fg='white', height=20) #房间名的标签对象 self.roomname.place(x=0, y=520, width=len('Hello')*15, height=20) #布置到界面上 self.roomname.config(text='Hello') #文本内容框 text_frame = tk.Frame(self.root) #建一个容器来放 text_frame.place(x=0, y=540, width=700, height=180) #布置位置 sb = tk.Scrollbar(text_frame) #新建滚动条,这里注意下,滚动条用的是WINDOWS的风格,无法自定义 sb.pack(side=tk.RIGHT, fill=tk.Y) #布置位置 self.textbox = tk.Text(text_frame, width=700, font=('Arial', 12), bg='black', fg='white', yscrollcommand=sb.set, wrap='char', state=tk.DISABLED) #新建文本框 self.textbox.pack(expand=tk.YES, fill=tk.BOTH) #布置文本框 sb.config(command=self.textbox.yview) #关联滚动条功能 self.textbox.config(state=tk.DISABLED) #禁止文本框修改 #操作按钮 #help self.help_button = tk.Button(self.root, bd=0, bg='black', activebackground='black', width=40, height=40, relief=tk.SOLID, command=partial(self.processCommand, ("help", None))) #创建按钮对象 self.help_button.place(x=740, y=580, width=40, height=40) #布置按钮位置 try: img = ImageTk.PhotoImage(Image.open('res/help.png').resize((40, 40), Image.ANTIALIAS)) #缩放图片 self.imglist['help'] = img #添加图片对象到列表 self.help_button.config(image=img, state=tk.DISABLED) #关联按钮图案,先设置为不可用 except: pass #map self.map_button = tk.Button(self.root, bd=0, bg='black', activebackground='black', width=40, height=40, relief=tk.SOLID, command=partial(self.processCommand, ("map", None))) #创建按钮对象 self.map_button.place(x=820, y=580, width=40, height=40) #布置按钮位置 try: img = ImageTk.PhotoImage(Image.open('res/map.png').resize((40, 40), Image.ANTIALIAS)) #缩放图片 self.imglist['map'] = img #添加图片对象到列表 self.map_button.config(image=img, state=tk.DISABLED) #关联按钮图案,先设置为不可用 except: pass #check self.check_button = tk.Button(self.root, bd=0, bg='black', activebackground='black', width=40, height=40, relief=tk.SOLID, command=partial(self.processCommand, ("check", None))) #创建按钮对象 self.check_button.place(x=900, y=580, width=40, height=40) #布置按钮位置 try: img = ImageTk.PhotoImage(Image.open('res/check.png').resize((40, 40), Image.ANTIALIAS)) #缩放图片 self.imglist['check'] = img #添加图片对象到列表 self.check_button.config(image=img, state=tk.DISABLED) #关联按钮图案,先设置为不可用 except: pass #pickup self.pickup_button = tk.Button(self.root, bd=0, bg='black', activebackground='black', width=40, height=40, relief=tk.SOLID, command=partial(self.processCommand, ("pickup", None))) #创建按钮对象 self.pickup_button.place(x=740, y=640, width=40, height=40) #布置按钮位置 try: img = ImageTk.PhotoImage(Image.open('res/pickup.png').resize((40, 40), Image.ANTIALIAS)) #缩放图片 self.imglist['pickup'] = img #添加图片对象到列表 self.pickup_button.config(image=img, state=tk.DISABLED) #关联按钮图案,先设置为不可用 except: pass #inventory self.inventory_button = tk.Button(self.root, bd=0, bg='black', activebackground='black', width=40, height=40, relief=tk.SOLID, command=partial(self.processCommand, ("inventory", None))) #创建按钮对象 self.inventory_button.place(x=820, y=640, width=40, height=40) #布置按钮位置 try: img = ImageTk.PhotoImage(Image.open('res/inventory.png').resize((40, 40), Image.ANTIALIAS)) #缩放图片 self.imglist['inventory'] = img #添加图片对象到列表 self.inventory_button.config(image=img, state=tk.DISABLED) #关联按钮图案,先设置为不可用 except: pass #quit self.quit_button = tk.Button(self.root, bd=0, bg='black', activebackground='black', width=40, height=40, relief=tk.SOLID, command=partial(self.processCommand, ("quit", None))) #创建按钮对象 self.quit_button.place(x=900, y=640, width=40, height=40) #布置按钮位置 try: img = ImageTk.PhotoImage(Image.open('res/quit.png').resize((40, 40), Image.ANTIALIAS)) #缩放图片 self.imglist['quit'] = img #添加图片对象到列表 self.quit_button.config(image=img, state=tk.DISABLED) #关联按钮图案,先设置为不可用 except: pass #四个门 #south self.south_button = tk.Button(self.root, bd=0, bg='black', activebackground='black', width=140, height=74, relief=tk.SOLID) #创建按钮对象 self.south_button.place(x=410, y=456, width=140, height=74) #布置按钮位置 try: img = ImageTk.PhotoImage(Image.open('res/south.png').resize((140, 74), Image.ANTIALIAS)) #缩放图片 self.imglist['south'] = img #添加图片对象到列表 self.south_button.config(image=img) #关联按钮图案 except: pass self.south_button.place(x=410, y=456, width=0, height=0) #隐藏按钮位置 #north self.north_button = tk.Button(self.root, bd=0, bg='black', activebackground='black', width=140, height=74, relief=tk.SOLID) #创建按钮对象 self.north_button.place(x=410, y=10, width=140, height=74) #布置按钮位置 try: img = ImageTk.PhotoImage(Image.open('res/north.png').resize((140, 74), Image.ANTIALIAS)) #缩放图片 self.imglist['north'] = img #添加图片对象到列表 self.north_button.config(image=img) #关联按钮图案 except: pass self.north_button.place(x=410, y=10, width=0, height=0) #隐藏按钮位置 #east self.east_button = tk.Button(self.root, bd=0, bg='black', activebackground='black', width=72, height=140, relief=tk.SOLID) #创建按钮对象 self.east_button.place(x=876, y=210, width=72, height=140) #布置按钮位置 try: img = ImageTk.PhotoImage(Image.open('res/east.png').resize((72, 140), Image.ANTIALIAS)) #缩放图片 self.imglist['east'] = img #添加图片对象到列表 self.east_button.config(image=img) #关联按钮图案 except: pass self.east_button.place(x=876, y=210, width=0, height=0) #隐藏按钮位置 #west self.west_button = tk.Button(self.root, bd=0, bg='black', activebackground='black', width=72, height=140, relief=tk.SOLID) #创建按钮对象 self.west_button.place(x=10, y=210, width=72, height=140) #布置按钮位置 try: img = ImageTk.PhotoImage(Image.open('res/west.png').resize((72, 140), Image.ANTIALIAS)) #缩放图片 self.imglist['west'] = img #添加图片对象到列表 self.west_button.config(image=img) #关联按钮图案 except: pass self.west_button.place(x=10, y=210, width=0, height=0) #隐藏按钮位置 #物品对象 self.thing = tk.Button(self.root, bd=0, width=100, height=100, relief=tk.SOLID) #物品对象 self.thing.place(x=720, y=150, width=100, height=100) #布置到界面上(右上方) #怪物对象 self.monster_flag = True self.monster = tk.Button(self.root, bd=0, width=60, height=80, command=partial(self.move, [450, 210], ("attack", None))) #怪物对象 self.monster.place(x=450, y=210, width=100, height=100) #布置到界面上(右上方) try: img = ImageTk.PhotoImage(Image.open('res/monster.png').resize((100, 100), Image.ANTIALIAS)) #缩放图片 self.imglist['monster'] = img #添加图片对象到列表 self.monster.config(image=img) #给标签对象加上图片背景 except: pass #人物对象 self.player = tk.Label(self.root, bd=0, width=60, height=80) #人物对象 self.player.place(x=450, y=210, width=60, height=80) #布置到界面上(正中) try: img = ImageTk.PhotoImage(Image.open('res/player.png').resize((60, 80), Image.ANTIALIAS)) #缩放图片 self.imglist['player'] = img #添加图片对象到列表 self.player.config(image=img) #给标签对象加上图片背景 except: pass #小地图对象,放到最下面可以在最上层 self.minimap_flag = True self.minimap = tk.Label(self.root, bd=0, width=960, height=340) #小地图对象 self.minimap.place(x=0, y=100, width=960, height=340) #布置到界面上 try: img = ImageTk.PhotoImage(Image.open('res/minimap.png').resize((500, 350), Image.ANTIALIAS)) #缩放图片 self.imglist['minimap'] = img #添加图片对象到列表 self.minimap.config(image=img) #给标签对象加上图片背景 except: pass #背包对象 from Package import PackageGUI self.package_flag = True self.packagegui = PackageGUI(self.root) #背包对象 self.packagegui.place(x=300, y=60, width=360, height=400) #布置到界面上 #开始按钮 self.start_button = tk.Button(self.root, text='Start Game', font=('Arial', 16), bd=0, width=180, height=40, relief=tk.SOLID, command=self.start) #创建按钮对象 self.start_button.place(x=390, y=280, width=180, height=40) #布置按钮位置 #刷新当前房间 def updateRoom(self): #隐藏开始按钮 self.start_button.place(x=390, y=280, width=0, height=0) #隐藏按钮位置 #如果存在当前房间 if self.currentRoom: roomname = self.currentRoom.roomname #提取房间名 #缩小小地图 self.minimap_flag = False self.minimap.place(x=0, y=100, width=0, height=0) #隐藏小地图 #设置房间的背景(不同房间可以不同背景) try: imgpath = 'res/room_'+roomname+'.png' if os.path.exists(imgpath): img = ImageTk.PhotoImage(Image.open(imgpath).resize((960, 540), Image.ANTIALIAS)) #缩放图片 self.imglist['room_'+roomname] = img #添加图片对象到列表 self.roombg.config(image=img) #给标签对象加上图片背景 else: self.roombg.config(image=self.imglist['roombg']) #给标签对象加上图片背景 except Exception as e: ## print(str(e)) pass #设置门 exits = self.currentRoom.exits #提取可以走的方向 if "upstairs" in exits or "north" in exits: self.north_button.place(x=410, y=10, width=140, height=74) #布置按钮位置 #设置按钮功能 if "upstairs" in exits: command = ('go', 'upstairs') self.north_button.config(command=partial(self.move, [450, 50], command)) else: command = ('go', 'north') self.north_button.config(command=partial(self.move, [450, 50], command)) else: self.north_button.place(x=410, y=10, width=0, height=0) #隐藏按钮位置 if "downstairs" in exits or "south" in exits: self.south_button.place(x=410, y=456, width=140, height=74) #布置按钮位置 #设置按钮功能 if "downstairs" in exits: command = ('go', 'downstairs') self.south_button.config(command=partial(self.move, [450, 410], command)) else: command = ('go', 'south') self.south_button.config(command=partial(self.move, [450, 410], command)) else: self.south_button.place(x=410, y=456, width=0, height=0) #隐藏按钮位置 if "east" in exits: self.east_button.place(x=876, y=210, width=72, height=140) #布置按钮位置 command = ('go', 'east') self.east_button.config(command=partial(self.move, [830, 240], command)) else: self.east_button.place(x=876, y=210, width=0, height=0) #隐藏按钮位置 if "west" in exits: self.west_button.place(x=10, y=210, width=72, height=140) #布置按钮位置 command = ('go', 'west') self.west_button.config(command=partial(self.move, [60, 240], command)) else: self.west_button.place(x=10, y=210, width=0, height=0) #隐藏按钮位置 #修改房间标签 self.roomname.config(text=roomname, width=len(roomname)*15) self.roomname.place(x=0, y=520, width=len(roomname)*15, height=20) #布置到界面上 #确认物品 if self.currentRoom.things: temp = self.currentRoom.things[0] #设置物品的图片 try: imgpath = 'res/bthing'+str(temp.type)+'.png' if os.path.exists(imgpath): img = ImageTk.PhotoImage(Image.open(imgpath).resize((100, 100), Image.ANTIALIAS)) #缩放图片 else: img = ImageTk.PhotoImage(Image.open('res/bthing.png').resize((100, 100), Image.ANTIALIAS)) #缩放图片 self.imglist['bthing'+str(temp.type)] = img #添加图片对象到列表 self.thing.config(image=img) #给按钮加上图片 except Exception as e: ## print(str(e)) pass #设置物品位置,同时修改pickup功能 self.thing.config(command=partial(self.move, temp.location, ("pickup", temp.location))) self.pickup_button.config(command=partial(self.move, temp.location, ("pickup", temp.location))) self.thing.place(x=temp.location[0], y=temp.location[1], width=100, height=100) #布置到界面上 else: self.thing.place(x=720, y=150, width=0, height=0) #隐藏物品按钮 self.pickup_button.config(command=partial(self.processCommand, ("pickup", None))) #恢复pickup功能不用移动人物 #确认怪物 if self.currentRoom == self.bedroom and self.monster_flag: self.monster.place(x=450, y=210, width=100, height=100) #显示怪物 else: self.monster.place(x=450, y=210, width=0, height=0) #隐藏怪物 #添加内容到文本框 def addMsg(self, msg): self.textbox.config(state=tk.NORMAL) #开放文本框修改权限 self.textbox.insert('end', msg) #在文本框最底部加上内容 self.textbox.config(state=tk.DISABLED) #禁止文本框修改 self.textbox.see(tk.END) #自动滚动到最底部 #开始游戏 def start(self): """ Initialises the game """ self.createRooms() self.currentRoom = self.outside self.textUI = TextUI() self.package = [] #欢迎词 self.printWelcome() #缩小小地图 self.minimap_flag = False self.minimap.place(x=0, y=100, width=0, height=0) #隐藏小地图 #缩小背包 self.package_flag = False self.packagegui.place(x=300, y=60, width=0, height=0) #隐藏背包 #刷新房间 self.updateRoom() #设置按钮可用 self.help_button.config(state=tk.NORMAL) self.map_button.config(state=tk.NORMAL) self.check_button.config(state=tk.NORMAL) self.pickup_button.config(state=tk.NORMAL) self.inventory_button.config(state=tk.NORMAL) self.quit_button.config(state=tk.NORMAL) #显示人物在最中央 self.player.place(x=450, y=210, width=60, height=80) #布置到界面上(正中) #开始界面 def startPage(self): #缩小小地图 self.minimap_flag = False self.minimap.place(x=0, y=100, width=0, height=0) #隐藏小地图 #缩小背包 self.package_flag = False self.packagegui.place(x=300, y=60, width=0, height=0) #隐藏背包 #怪物存在 self.monster_flag = True self.monster.place(x=720, y=150, width=0, height=0) #隐藏怪物 #关闭门 self.north_button.place(x=410, y=10, width=0, height=0) #隐藏按钮位置 self.south_button.place(x=410, y=456, width=0, height=0) #隐藏按钮位置 self.east_button.place(x=876, y=210, width=0, height=0) #隐藏按钮位置 self.west_button.place(x=10, y=210, width=0, height=0) #隐藏按钮位置 #修改房间标签 roomname = 'Hello' self.roomname.config(text=roomname, width=len(roomname)*15) self.roomname.place(x=0, y=520, width=len(roomname)*15, height=20) #布置到界面上 #设置按钮不可用 self.help_button.config(state=tk.DISABLED) self.map_button.config(state=tk.DISABLED) self.check_button.config(state=tk.DISABLED) self.pickup_button.config(state=tk.DISABLED) self.inventory_button.config(state=tk.DISABLED) self.quit_button.config(state=tk.DISABLED) #隐藏人物 self.player.place(x=450, y=210, width=0, height=0) #隐藏人物 #隐藏物品按钮 self.thing.place(x=720, y=150, width=0, height=0) #隐藏物品按钮 #隐藏怪物 self.monster.place(x=450, y=210, width=0, height=0) #隐藏怪物 #玩家移动效果 def move(self, location, command): if not self.move_flag: ## print(self.player_location, location , command) ## print(self.package) self.move_flag = True #设置开始动画的标识 ox = self.player_location[0] oy = self.player_location[1] nx = location[0] ny = location[1] #更新动画用到的属性 self.location = location #动画的目标位置 self.command = command #动画完成后执行的动作 framenum = 45 #设置45帧完成动画效果 speed = (840-60)/framenum #行走速度 sframe = (abs(ox-nx)**2+abs(oy-ny)**2)**0.5 / speed if sframe: self.mx = (ox-nx)/sframe #X轴一帧走的偏移量 self.my = (oy-ny)/sframe #Y轴一帧走的偏移量 else: self.mx = 0 self.my = 0 ## print(sframe, speed, self.mx, self.my) self.moving() #移动动画实现 def moving(self): if self.move_flag: self.player_location[0] -= self.mx self.player_location[1] -= self.my if self.player_location[0]<=self.location[0]+abs(self.mx)+0.1 and self.player_location[1]<=self.location[1]+abs(self.my)+0.1 \ and self.player_location[0]>=self.location[0]-abs(self.mx)-0.1 and self.player_location[1]>=self.location[1]-abs(self.my)-0.1: #到达目标位置 self.move_flag = False self.processCommand(self.command) #操作 return #更新人物位置 self.player.place(x=self.player_location[0], y=self.player_location[1], width=60, height=80) #执行动画效果 self.root.after(33, self.moving) #33ms一帧,1s 30帧 def createRooms(self): """ Sets up all room assets :return: None """ #这里初始化要把房间名称也加上 self.outside = Room("Outside", "You are outside") self.lobby = Room("Lobby", "in the lobby") self.lobby.createThing("laser weapons", 0, 66) self.policeoffice = Room("Police Office", "You are in the police office") self.policeoffice.createThing("key 4 --- clue: can open a room near the police office",4,1) self.prison = Room("Prison", "You are in the prison") self.prison.setLock(4) self.prison.createThing("The hair of a mutant",14) self.plants = Room("Manufacturing Plants", "in a manufacturing plants") self.lab = Room("Future Factory Laboratory", "in the future factory Laboratory") self.lab.createThing("key 3 --- clue: can open a room near the Dr. Evil's office", 3, 1) self.office = Room("Dr. Evil's Office", "in the Dr. Evil's office") self.office.createThing("key 2 --- clue: can open a room near the future factory Laboratory", 2, 1) self.archive = Room("Scientific And Technical Archives Room", "in the scientific and technical archives room") #locked has thing self.archive.setLock(1) self.archive.createThing("confidential manufacturing files", 10, 2) self.storeroom = Room("Hi-tech Products Storeroom", "in the hi-tech products storeroom") # locked has thing self.storeroom.setLock(2) self.storeroom.createThing("time machine", 11, 2) self.conference = Room("Conference Room", "in the conference room") self.conference.createThing("Dr. Evil's notebook for invading", 15, 2) self.restaurant = Room("Restaurant", "in the restaurant") # has food self.restaurant.createThing("artificial meat burger", 13) self.finance = Room("Vault", "in the vault") # locked self.finance.setLock(3) self.finance.createThing("key 1 --- clue: can open a room near the manufacturing plants", 1, 1) self.garage = Room("Garage", "in the garage, your time shuttle is in there, you can back to your world ------ quit") self.garage.createThing("gravity apparatus", 14) self.bedroom = Room("Dr. Evil's Bedroom", "in the Dr. Evil's bedroom, you woke Dr. Evil up and he caught you! Mission failed! You can quit the game and start it again!") self.outside.setExit("east", self.lobby) self.outside.setExit("south", self.lab) self.outside.setExit("west", self.plants) self.outside.setExit("north",self.policeoffice) self.policeoffice.setExit("upstairs",self.prison) self.policeoffice.setExit("south",self.outside) self.prison.setExit("downstairs",self.policeoffice) self.lobby.setExit("west", self.outside) self.lobby.setExit("east", self.restaurant) self.restaurant.setExit("west", self.lobby) self.plants.setExit("east", self.outside) self.plants.setExit("west", self.archive) self.plants.setExit("south", self.garage) self.plants.setExit("north", self.conference) self.archive.setExit("east", self.plants) self.garage.setExit("north", self.plants) self.conference.setExit("south", self.plants) self.lab.setExit("north", self.outside) self.lab.setExit("east", self.office) self.lab.setExit("west", self.storeroom) self.storeroom.setExit("east", self.lab) self.office.setExit("west", self.lab) self.office.setExit("east", self.finance) self.office.setExit("south", self.bedroom) self.bedroom.setExit("north", self.office) self.finance.setExit("west", self.office) self.win = False def play(self): """ The main play loop :return: None """ self.printWelcome() finished = False while (finished == False): command = self.textUI.getCommand() # Returns a 2-tuple finished = self.processCommand(command) ## print('command:', command) print("Thank you for playing!") self.addMsg("Thank you for playing!\n") def printWelcome(self): """ Displays a welcome message :return: """ """ self.textUI.printtoTextUI("You are a person with the ability to travel through time and space, and you live in a peaceful and warm world. However, on an ordinary day, Dr. Evil broke this peace ……") self.textUI.printtoTextUI("Dr. Evil, who lives in the future, is ready to come to the world you live in and planning to destroy your world.") self.textUI.printtoTextUI("The only way to save your world is to bring back Dr. Evil's weapons, handbooks for invasion, or other important items from the future in Dr. Evil’s territory, and defeat Dr. Evil through the Homeland Defense Bureau's research.") self.textUI.printtoTextUI("As the only time traveler in the current world, you have to take your time shuttle to the future Dr. Evil's home, find these useful items successfully and return to your world in the time shuttle timely.") self.textUI.printtoTextUI("According to the manual, your initial point will be the location:<OUTSIDE> of Dr. Evil's house and you can find your time shuttle in the location:<GARAGE>.") self.textUI.printtoTextUI("You need to collect no less than 6 items! Be careful not to be caught by Dr. Evil unless you have the laser weapons! He may be waiting for you in one of these rooms! ") self.textUI.printtoTextUI("") self.textUI.printtoTextUI("") self.textUI.printtoTextUI(f'Your command words are: {self.showCommandWords()}') """ #添加文本 text = "You are a person with the ability to travel through time and space, and you live in a peaceful and warm world. However, on an ordinary day, Dr. Evil broke this peace ……\n" text = text + "Dr. Evil, who lives in the future, is ready to come to the world you live in and planning to destroy your world.\n" text = text + "The only way to save your world is to bring back Dr. Evil's weapons, handbooks for invasion, or other important items from the future in Dr. Evil’s territory, and defeat Dr. Evil through the Homeland Defense Bureau's research.\n" text = text + "As the only time traveler in the current world, you have to take your time shuttle to the future Dr. Evil's home, find these useful items successfully and return to your world in the time shuttle timely.\n" text = text + "According to the manual, your initial point will be the location:<OUTSIDE> of Dr. Evil's house and you can find your time shuttle in the location:<GARAGE>.\n" text = text + "You need to collect no less than 6 items! Be careful not to be caught by Dr. Evil unless you have the laser weapons! He may be waiting for you in one of these rooms! \n" text = text + "\n" text = text + "\n" text = text + f'Your command words are: {self.showCommandWords()}\n' self.addMsg(text) #弹窗提示 messagebox.showinfo(title='warn', message=text) def showCommandWords(self): """ Show a list of available commands :return: None """ return ['help', 'map', 'go', 'check', 'pickup', 'inventory', 'quit'] def processCommand(self, command): """ Process a command from the TextUI :param command: a 2-tuple of the form (commandWord, secondWord) :return: True if the game has been quit, False otherwise """ commandWord, secondWord = command if commandWord != None: commandWord = commandWord.upper() wantToQuit = False if commandWord == "HELP": self.doPrintHelp() elif commandWord == "MAP": self.doPrintMap() elif commandWord == "GO": self.doGoCommand(secondWord) elif commandWord == "CHECK": self.doCheckCommand() elif commandWord == "PICKUP": self.doPickUpCommand(secondWord) elif commandWord == "ATTACK": self.doAttackCommand(secondWord) elif commandWord == "INVENTORY": self.doPackageCommand() elif commandWord == "QUIT": # quit the game, you can quit the game anytime as you want but you may lose the game. while the game has 2 endings --- 1.come back but cannot save your world.(bad ending) 2.come back and save your world successfully.(happy ending) text = "" if self.currentRoom == self.bedroom: """ self.textUI.printtoTextUI("-------- You lose! Level: D --------\nSADLY: You were captured and brutally murdered by Dr. Evil!") """ text = text + "-------- You lose! Level: D --------\nSADLY: You were captured and brutally murdered by Dr. Evil!" else: if self.checkIsWin() == False and self.currentRoom != self.garage: """ self.textUI.printtoTextUI("-------- You lose! Level: C --------\nSORRY: You didn't find the garage to back to your world!") """ text = text + "-------- You lose! Level: C --------\nSORRY: You didn't find the garage to back to your world!" elif self.checkIsWin() == False and self.currentRoom == self.garage: """ self.textUI.printtoTextUI("-------- You win! Level: A --------\nWELL DONE: You took a time shuttle back to your world safely but you didn't bring back enough future supplies to make the research continue!!! You can not save your world!! What a pity!") """ text = text + "-------- You win! Level: A --------\nWELL DONE: You took a time shuttle back to your world safely but you didn't bring back enough future supplies to make the research continue!!! You can not save your world!! What a pity!" elif self.checkIsWin() == True and self.currentRoom == self.garage: """ self.textUI.printtoTextUI("-------- You win! Level: S --------\nPERFECT: You took a time shuttle back to your world safely and you've finally developed a weapon to save the world!") """ text = text + "-------- You win! Level: S --------\nPERFECT: You took a time shuttle back to your world safely and you've finally developed a weapon to save the world!" elif self.checkIsWin() == True and self.currentRoom != self.garage: """ self.textUI.printtoTextUI("-------- You lose! Level: B --------\nSORRY: Although you have found enough useful items, You didn't find the garage to back to your world!") """ text = text + "-------- You lose! Level: B --------\nSORRY: Although you have found enough useful items, You didn't find the garage to back to your world!" wantToQuit = True self.addMsg(text) #弹窗提示 messagebox.showinfo(title='warn', message=text) #保存日志 self.saveGame() self.root.quit() else: # Unknown command ... self.textUI.printtoTextUI("Don't know what you mean") return wantToQuit def doPrintHelp(self): # that is the --help information of this game. """ Display some useful help text :return: None """ """ self.textUI.printtoTextUI("You need to collect some useful items from Dr. Evil's rooms and find your time shuttle in the <GARAGE>.") self.textUI.printtoTextUI("Dr. Evil's rooms will have a lot of secret rooms which means you need to crack it successfully with your wisdom.") self.textUI.printtoTextUI("You need to collect no less than 6 items! Be careful not to be caught by Dr. Evil unless you have the laser weapons!") self.textUI.printtoTextUI("") self.textUI.printtoTextUI(f'Your command words are: {self.showCommandWords()}') """ #刷新房间 self.updateRoom() #信息 text = "You need to collect some useful items from Dr. Evil's rooms and find your time shuttle in the <GARAGE>.\n" text = text + "Dr. Evil's rooms will have a lot of secret rooms which means you need to crack it successfully with your wisdom.\n" text = text + "You need to collect no less than 6 items! Be careful not to be caught by Dr. Evil unless you have the laser weapons!\n" text = text + "You need to collect no less than 6 items! Be careful not to be caught by Dr. Evil unless you have the laser weapons!\n" text = text + "\n" text = text + f'Your command words are: {self.showCommandWords()}\n' self.addMsg(text) messagebox.showinfo(title='warn', message=text) def doPrintMap(self): # that is the -- print map of this game. """ Display map :return: None """ """ print(" |-------------------| ") print(" N | prison | ") print(" W E |-------------------| ") print(" S | | ") print(" | | ") print(" |-------------------| |-------------------| ") print(" | conference room | | police office | ") print(" |-------------------| |-------------------| ") print(" | | | | ") print(" | | | | ") print(" |-------------------| |-------------------| |-------------------| |-------------------| |-------------------| ") print(" | archives room | == | plants | == | outside | == | lobby | == | restaurant | ") print(" |-------------------| |-------------------| |-------------------| |-------------------| |-------------------| ") print(" | | | | ") print(" |-------------------| | | ") print(" | garage | | | ") print(" |-------------------| | | ") print(" | | ") print(" |-------------------| |-------------------| |-------------------| |-------------------| ") print(" | hi-tech storeroom | == | future lab | == | Dr.E's office | == | vault | ") print(" |-------------------| |-------------------| |-------------------| |-------------------| ") print(" | | ") print(" |-------------------| ") print(" | Dr.E's bedroom | ") print(" |-------------------| ") """ #显示/关闭小地图 if self.minimap_flag: self.minimap_flag = False self.minimap.place(x=0, y=100, width=0, height=0) #隐藏小地图 else: self.minimap_flag = True self.minimap.place(x=0, y=100, width=960, height=340) #打开小地图 def doGoCommand(self, secondWord): """ Performs the GO command :param secondWord: the direction the player wishes to travel in :return: None """ if secondWord == None: # Missing second word ... self.textUI.printtoTextUI("Go where? Such as you can enter <go north> to make the character walk to the north") return nextRoom = self.currentRoom.getExit(secondWord) if nextRoom == None: self.textUI.printtoTextUI(f"There has no door in the <{secondWord}> or you spelled words wrongly!") else: # Check if the room is locked here if nextRoom.needKey(): """ self.textUI.printtoTextUI(f"The room need key:{nextRoom.getLockId()}") """ self.addMsg(f"The room need key:{nextRoom.getLockId()}\n") if self.checkHasKey(nextRoom.getLockId()): """ self.textUI.printtoTextUI(f"I have the key:{nextRoom.getLockId()} in my package!! unlock the room.") """ self.addMsg(f"I have the key:{nextRoom.getLockId()} in my package!! unlock the room.\n") self.useKey(nextRoom.getLockId()) nextRoom.setLock(0) else: """ self.textUI.printtoTextUI(f"I need to find the key:{nextRoom.getLockId()} in other room.") """ self.addMsg(f"I need to find the key:{nextRoom.getLockId()} in other room.\n") messagebox.showinfo(title='warn', message=f"I need to find the key:{nextRoom.getLockId()} in other room.\n") return self.currentRoom = nextRoom self.addMsg(self.currentRoom.getLongDescription()+'\n') ## messagebox.showinfo(title='warn', message=self.currentRoom.getLongDescription()+'\n') #刷新显示房间 self.updateRoom() #刷新人物位置 if secondWord == 'upstairs' or secondWord == 'north': #从上方进门,出来在最下 self.player.place(x=450, y=410, width=60, height=80) #布置到界面上(最下) self.player_location = [450, 410] elif secondWord == 'downstairs' or secondWord == 'south': #从下方进门,出来在最上 self.player.place(x=450, y=50, width=60, height=80) #布置到界面上(最上) self.player_location = [450, 50] elif secondWord == 'west': #从左方进门,出来在最右 self.player.place(x=830, y=240, width=60, height=80) #布置到界面上(最右) self.player_location = [830, 240] elif secondWord == 'east': #从右方进门,出来在最左 self.player.place(x=60, y=240, width=60, height=80) #布置到界面上(最左) self.player_location = [60, 240] def doCheckCommand(self): # Check whether the place has supplies or not. """ Performs the CHECK command :return: None """ if self.currentRoom.isEmpty(): """ self.textUI.printtoTextUI("There's nothing here!") """ self.addMsg("There's nothing here!\n") messagebox.showinfo(title='warn', message="There's nothing here!\n") else: """ self.textUI.printtoTextUI(f"Find: {self.currentRoom.listThing()}!") self.textUI.printtoTextUI(self.currentRoom.checkThingType()) """ self.addMsg(f"Find: {self.currentRoom.listThing()}!\n") self.addMsg(self.currentRoom.checkThingType()+"\n") messagebox.showinfo(title='warn', message=f"Find: {self.currentRoom.listThing()}!\n"+self.currentRoom.checkThingType()+"\n") def doPickUpCommand(self, secondWord): # If the place has supplies then you can pick it up and store it in your package. """ Performs the PICKUP command :return: None """ if self.currentRoom.isEmpty(): """ self.textUI.printtoTextUI("There's nothing here!") """ self.addMsg("There's nothing here!\n") messagebox.showinfo(title='warn', message="There's nothing here!\n") else: while(True): t = self.currentRoom.pickupThing() if t == None: break; self.package.append(t) # self.textUI.printtoTextUI(f"Find: {self.currentRoom.listThing()}!") #刷新房间状态 self.updateRoom() #移动人物到宝箱位置 if secondWord: self.player.place(x=secondWord[0], y=secondWord[1], width=60, height=80) #布置到物品所在位置 #攻击怪物 def doAttackCommand(self, secondWord): if len(self.package) == 0: """ self.textUI.printtoTextUI(self.currentRoom.getLongDescription2()) """ self.addMsg(self.currentRoom.getLongDescription2()+'\n') messagebox.showinfo(title='warn', message=self.currentRoom.getLongDescription2()+'\n') self.processCommand(("quit", None)) else: condition1 = 0 for t in self.package: if t.type == 66: condition1 += 1 if condition1 >= 1: """ self.textUI.printtoTextUI(f"You have the laser weapons and you killed Dr. Evil without hesitation!So you can come to the <garage> back to your world, Exits: ['north'] ") """ self.addMsg(f"You have the laser weapons and you killed Dr. Evil without hesitation!So you can come to the <garage> back to your world, Exits: ['north'] \n") messagebox.showinfo(title='warn', message=f"You have the laser weapons and you killed Dr. Evil without hesitation!So you can come to the <garage> back to your world, Exits: ['north'] \n") #击杀成功,修改标识,刷新房间 self.monster_flag = False self.updateRoom() else: """ self.textUI.printtoTextUI(self.currentRoom.getLongDescription2()) """ self.addMsg(self.currentRoom.getLongDescription2()+'\n') messagebox.showinfo(title='warn', message=self.currentRoom.getLongDescription2()+'\n') self.processCommand(("quit", None)) def doPackageCommand(self): """ Performs the INVENTORY command :return: None """ countItem = 0 countKey = 0 for t in self.package: if t.type == 1: countKey += 1 elif t.type != 1: countItem += 1 """ self.textUI.printtoTextUI(f"My package has: {countItem} items and {countKey} keys, {8-countKey-countItem} left spaces") # show all items in the package self.textUI.printtoTextUI(f"These are:{', '.join([t.description for t in self.package])}") # show all items in the package """ text = f"My package has: {countItem} items and {countKey} keys, {8-countKey-countItem} left spaces\n" text = text + f"These are:{', '.join([t.description for t in self.package])}\n" if len(self.package) >=8: # give tips ---- Determine whether you have enough space in your backpack to store supplies. weight limits """ self.textUI.printtoTextUI("Warning: Backpack capacity is not enough. No more than 8 items in your package is better!") """ text = text + "Warning: Backpack capacity is not enough. No more than 8 items in your package is better!\n" else: """ self.textUI.printtoTextUI("Your packages still have enough space.No more than 8 items in your package is better!") """ text = text + "Your packages still have enough space.No more than 8 items in your package is better!\n" self.addMsg(text) ## messagebox.showinfo(title='warn', message=text) #打开/关闭背包 if self.package_flag: self.package_flag = False self.packagegui.place(x=0, y=100, width=0, height=0) #隐藏背包 else: self.package_flag = True self.packagegui.place(x=300, y=60, width=360, height=400) #打开背包 self.packagegui.udpate(self.package) #更新背包内容 def checkHasKey(self, _id): """ check whether you have the right key which can open the door correctly in your package. :param _id: the id of the key :return: True if the id of the key is correct -- has key to open the door, False otherwise """ for t in self.package: if t.type == 1 and t.id == _id: return True return False def useKey(self, _id): """ Use the key in your backpack to open the correct door and destroy it after you finish using it. :param _id: the id of the key :return: self.package.pop(i) ---> drop the key after using and package space +1, None """ for i in range(0, len(self.package)): t = self.package[i] if t.type == 1 and t.id == _id: return self.package.pop(i) return None def checkIsWin(self): """ Check if sufficient supplies have been collected. :return: True if you collected enough item, False otherwise """ count = 0 for t in self.package: if t.type != 1: count += 1 if count >= 6: # Determine if there are enough supplies in the package (keys are not counted as supplies). You can reset one of the conditions of win (collecting how many supplies) by changing the value of number. return True # if you collected more than 6 item, it will return true return False # if you collected less than 6 item, it will return false #保存LOG def saveGame(self): #日志 text = self.textbox.get('0.0','end') #读取时间戳做为文件名 filename = str(int(time.time())) with open("save/" + filename +'.txt', 'w') as f: f.write(text) def main(): game = Game() ## game.play() game.createGUI() game.startPage() game.root.mainloop() if __name__ == "__main__": main() <file_sep>""" A simple text based User Interface (UI) for the Adventure World game """ class TextUI: def __init__(self): # Nothing to do ... pass def getCommand(self): """ Fetches a command from the console :return: a 2-tuple of the form (commandWord, secondWord) """ word1 = None word2 = None print('> ', end='') inputLine = input() if inputLine != "": allWords = inputLine.split() word1 = allWords[0] if len(allWords) > 1: word2 = allWords[1] else: word2 = None # Just ignore any other words return (word1, word2) def printtoTextUI(self, text): """ Displays text to the console :param text: Text to be displayed :return: None """ print(text)
1788ec3b4c415fc9b2d23cd48798cb093c856fd1
[ "Python" ]
6
Python
Omoafolayan22/Python-AdventureGames
7b7bc3d79fc4eb9df06e2d30ec1c20ce09011b2e
04a3766805c54eeba581b42fe72aaef2036e63bd
refs/heads/master
<file_sep> const ALL_CARS =[] cars_sorted = { } function loadDoc() { var xhttp = new XMLHttpRequest(); // create and xhr object -- request object xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // everything this take place between this block let data = JSON.parse(this.responseTEXT) for (item in data) { let car = new Car(item) car.make = new Car(item, data[item].make, data[item].model, data[item].model_year, data[item].color) cars_sorted[data[item].make] = } } }; xhttp.open("GET", "https://raw.githubusercontent.com/mlaw-nycda/empireCommerce/master/cars.json", true); xhttp.send(); } Class car { constructor(vin, make, model, year, color) { this.vin = vin this.make = make this.model = model this.year = year this.color = color if (ALL_CARS.length < 15) { ALL_CARS.push(this) } } }
62d64e51f3ae8e1f539e7e8350aa038bc1580f92
[ "JavaScript" ]
1
JavaScript
ashleyalmonte/day20
123fbc67dd6d7102e4e89bbe09d97016765ae9cf
5d734e17cb8d0e8adb8550a820f51e4ee49912d1
refs/heads/master
<repo_name>jjinny0105/portfolio_jinny<file_sep>/js/menu.js $("#triger").click(function() { $("#desktopMenu").addClass("on"); $("#m_gnb_close").click(function() { $("#desktopMenu").removeClass("on"); }); }); <file_sep>/js/scrolltop.js $(function () { $("#top").css("cursor", "pointer"); $("#top").on("click", function () { $("html").animate({ scrollTop: 0 }, 500); }); // 처음 탑 초기화 var scrollNum = $(window).scrollTop(); if (scrollNum > 200) { $("#top").css("display", "block"); } else { $("#top").css("display", "none"); } $(window).on("scroll", function () { scrollNum = $(window).scrollTop(); console.log(scrollNum); if (scrollNum < 200) { $("#top").css("display", "none"); } else if (scrollNum >= 200 && scrollNum < 550) { $("#top").css("display", "block"); $("#top").css("color", "white"); } else { $("#top").css("color", "black"); } }); });
496d190c1112a56907de5d1ef812f31aef6b0562
[ "JavaScript" ]
2
JavaScript
jjinny0105/portfolio_jinny
dbc0e5f1c85df6d05606d143670f73df4a22af24
032a306234d60f79e6bc5a843c893774ccafb817
refs/heads/master
<repo_name>miahmia/MyLab1<file_sep>/Solution/HelloWinForms/Form1.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; namespace HelloWinForms { public partial class Form1 : Form { public Form1() { InitializeComponent(); //Button buttonToClick = new Button(); //buttonToClick.Text = "Click"; //Controls.Add(buttonToClick); } private void buttonToClick_Click(object sender, EventArgs e) { MessageBox.Show("It was clicked"); } } }
4c302612371d111cef27e575b7d5912283d907ad
[ "C#" ]
1
C#
miahmia/MyLab1
da547fa46f4a33f2150ac1f88313b05b109167c8
405a56201ee5f243743d20f9407c703861132a2e
refs/heads/master
<file_sep>import Ember from 'ember'; import {ENCRYPTION_METHODS} from "cryptography/constants/encryption-methods"; export default Ember.Controller.extend({ encryptionMethods: Object.keys(ENCRYPTION_METHODS).map(key => ENCRYPTION_METHODS[key]), encryption: Ember.inject.service(), input: "", output: "", selectedEncryptionMethod: null, specialMethodConfiguration: {}, selectedEncryptionMethodConfigComponentName: Ember.computed('selectedEncryptionMethod', function () { return this.get('selectedEncryptionMethod') + '-config' }), activeSpecialConfigurationObject: Ember.computed('selectedEncryptionMethod', function () { return this.get('specialMethodConfiguration')[this.get('selectedEncryptionMethod')]; }), canEncrypt: Ember.computed.notEmpty('selectedEncryptionMethod'), actions: { changeEncryptionMethod: function (method) { this.set('selectedEncryptionMethod', method); /** Reset method configurations. */ this.get("specialMethodConfiguration")[`${this.get('selectedEncryptionMethod')}`] = {}; }, encrypt: function () { if (!this.get('canEncrypt')) { return; } const method = this.get('selectedEncryptionMethod'); const encryptionResult = this.get('encryption').encrypt({ method: Ember.String.camelize.call(this, method), text: this.get('input'), specialOptions: this.get(`specialMethodConfiguration.${method}`) }); this.set('output', encryptionResult); }, decrypt: function () { if (!this.get('canEncrypt')) { return; } const method = this.get('selectedEncryptionMethod'); const encryptionResult = this.get('encryption').decrypt({ method: Ember.String.camelize.call(this, method), text: this.get('input'), specialOptions: this.get(`specialMethodConfiguration.${method}`) }); this.set('output', encryptionResult); } } }); <file_sep>import Ember from 'ember'; import CryptoJS from 'npm:crypto-js' export default Ember.Service.extend({ encrypt: function ({text, secret}) { const keyHex = CryptoJS.enc.Utf8.parse(secret); const encrypted = CryptoJS.DES.encrypt(text, keyHex, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }); return encrypted.toString(); }, decrypt: function ({text, secret}) { const keyHex = CryptoJS.enc.Utf8.parse(secret); const decrypted = CryptoJS.DES.decrypt({ ciphertext: CryptoJS.enc.Base64.parse(text) }, keyHex, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }); return decrypted.toString(CryptoJS.enc.Utf8); } }); <file_sep>import Ember from 'ember'; export default Ember.Component.extend({ tag: '', options: null, didReceiveAttrs: function () { this.get('options')['keyWord'] = null; } }); <file_sep>import Ember from 'ember'; let p_cache = 3557; let g_cache = 2579; let e = 3; let e_secret = 6111579; export default Ember.Service.extend({ encrypt: function ({text, p, g}) { p = parseInt(p, 10); g = parseInt(g, 10); text = parseInt(text, 10); p_cache = p; g_cache = g; const n = p_cache * g_cache; const euler_f = (p_cache - 1) * (g_cache - 1); const public_key = [e, euler_f]; const secret_key = [e_secret, euler_f]; const cipher_text = Math.pow(text, e) % n; return JSON.stringify({ public_key, secret_key, cipher_text }) }, decrypt: function ({text}) { text = parseInt(text); const n = p_cache * g_cache; return Math.pow(text, e_secret) % n; } }); <file_sep>export default function ({alphabet, position, offset}) { const length = alphabet.length; if(position + offset < 0) { return alphabet[length + (position+ offset)]; } const offsetOverlap = ( position + offset ) - length; if(offsetOverlap >= 0) { return alphabet[offsetOverlap]; } return alphabet[position + offset]; } <file_sep>export const ENCRYPTION_METHODS = { "caesar-cipher": "caesar-cipher", "vigenere-cipher": "vigenere-cipher", "swapping-cipher": "swapping-cipher", "des-cipher": "des-cipher", "aes-cipher": "aes-cipher", "el-gamal-cipher": "el-gamal-cipher", "rsa-cipher": "rsa-cipher" }; <file_sep>import Ember from 'ember'; let p_cache = 11; let g_cache = 2; let x_cache = 8; let k_cache = 9; let a; let b; export default Ember.Service.extend({ encrypt: function ({text, x = 8, p = 11, g = 2, k = 9}) { x = parseInt(x, 10); p = parseInt(p, 10); g = parseInt(g, 10); k = parseInt(k, 10); text = parseInt(text, 10); if (x > p || x < 1) { throw new Error(`expected x < p and x > 1`) } if (x > p) { throw new Error(`expected m < p`) } p_cache = p; g_cache = g; x_cache = x; k_cache = k; const y = Math.pow(g_cache, x_cache) % p_cache; const public_key = [p_cache, g_cache, y]; const private_key = x_cache; a = Math.pow(g_cache, k_cache) % p_cache; b = Math.pow(y, k_cache) * text % p_cache; const cipher_text = [a, b]; return JSON.stringify({ p: p_cache, g: g_cache, public_key, private_key, cipher_text }); }, decrypt: function ({text}) { const cipher_text = JSON.parse(text); const initial_text = b * Math.pow(a, p_cache - 1 -x_cache) % p_cache; return JSON.stringify({ initial_text }) } }); <file_sep>import Ember from 'ember'; function _preProcessText({text, keySequence}) { const lengthInconsistency = text.length % keySequence.length; return text + ' '.repeat(keySequence.length - lengthInconsistency); } function _toBlocks({array, blockLength}) { const blockArray = []; const blockAmount = array.length / blockLength; for (let i = 0; i < blockAmount; i++) { blockArray.push(array.slice(i * blockLength, (i + 1) * blockLength)) } return blockArray; } function _applySwappingMask({block, mask}) { const newBlock = []; block.forEach((item, index) => newBlock[mask[index]] = item); return newBlock; } function _applySwappingMaskInverted({block, mask}) { const newBlock = []; block.forEach((item, index) => newBlock[index] = block[mask[index]]); return newBlock; } export default Ember.Service.extend({ encrypt: function ({text, keySequence}) { text = _preProcessText({ text: text, keySequence: keySequence }); return _toBlocks({ array: text.split(''), blockLength: keySequence.length }).map(block => _applySwappingMask({ block: block, mask: keySequence.split('').map(numberAsString => parseInt(numberAsString)) })).map(processedBlock => processedBlock.join('')).join('').trim(); }, decrypt: function ({text, keySequence}) { text = _preProcessText({ text: text, keySequence: keySequence }); return _toBlocks({ array: text.split(''), blockLength: keySequence.length }).map(block => _applySwappingMaskInverted({ block: block, mask: keySequence.split('').map(numberAsString => parseInt(numberAsString)) })).map(processedBlock => processedBlock.join('')).join('').trim(); } }); <file_sep>import Ember from 'ember'; import CryptoJS from 'npm:crypto-js' export default Ember.Service.extend({ encrypt: function ({text, secret}) { return CryptoJS.AES.encrypt(text, secret).toString() }, decrypt: function ({text, secret}) { return CryptoJS.AES.decrypt(text, secret).toString(CryptoJS.enc.Utf8); } }); <file_sep>export function iterator(array) { let index = 0; const length = array.length; return { next: function () { if(index === length) { index = 0; } return array[index++]; } } }
7e9f4898d005bb8dbd4481a11dc712df6e86db4e
[ "JavaScript" ]
10
JavaScript
andrey-lavrov/crypto
e92c63dfb9685b121632f3b9e881ec9403bfd066
a15471aa3f460001195040b19ec5272f5b14b207
refs/heads/master
<file_sep>cp make_installer.py pyami cp make_installer.py pycdb cp make_installer.py pydaq <file_sep>#!/bin/bash $PREFIX/daq-links/install_pycdb.sh <file_sep>#!/bin/bash # Pull out links, then replace the ones that were still needed. LINKS=$PREFIX/daq-links $LINKS/uninstall_pycdb.sh for module in pydaq pyami; do SCRIPT=$LINKS/install_$module.sh if [ -f $SCRIPT ]; then $SCRIPT fi done <file_sep>#!/usr/bin/env python # Condensed version of nsls-ii's build scripts import argparse import shutil import subprocess import sys from multiprocessing import cpu_count from multiprocessing.pool import ThreadPool from pathlib import Path from socket import gethostname import binstar_client PACKAGES = ['epics-base', 'pcaspy', 'pyca', 'pydm', 'pyepics', 'pyqt', 'mysqlclient', 'qdarkstyle', 'caproto', 'timechart'] PYTHON = ['3.6', '3.5'] NUMPY = ['1.14', '1.13', '1.12', '1.11'] BUILD_DIR = str(Path(__file__).parent / 'conda-bld') def get_uploaded_files(client, channel): print('Checking uploaded files') files = set() for fl in client.show_channel('main', channel)['files']: files.add(fl['basename']) return files def build_args(package, channel, py=None, np=None, dev=False): args = ['conda', 'build', package, '-c', channel, '-c', 'defaults', '-c', 'conda-forge', '--override', '--output-folder', BUILD_DIR, '--old-build-string'] if py is not None: args.extend(['--python', py]) if np is not None: args.extend(['--numpy', np]) return args def check_filename(package, channel, py=None, np=None): args = build_args(package, channel, py=py, np=np) + ['--output'] print(' '.join(args)) output = subprocess.check_output(args, universal_newlines=True).strip('\n') return output def check_all(files, channel): to_build = {} index = 0 pool = ThreadPool(processes=cpu_count()-1) results = [] for package in PACKAGES: new_package = True for py in PYTHON: for np in NUMPY: args = (files, to_build, index, package, channel, py, np) if new_package: # Do the first by itself or conda build may throw errors pool.apply(func=_check_thread, args=args) new_package = False else: # Do the rest in parallel res = pool.apply_async(func=_check_thread, args=args) results.append(res) index += 1 for res in results: res.wait() return to_build def _check_thread(files, to_build, index, package, channel, py, np): full_path = check_filename(package, channel, py=py, np=np) short_path = '/'.join(full_path.split('/')[-2:]) if short_path not in files: files.add(short_path) to_build[index] = (package, channel, py, np, full_path) def build(package, channel, py=None, np=None): print('Building {}'.format(package)) args = build_args(package, channel, py=py, np=np) print(' '.join(args)) subprocess.run(args, stdout=sys.stdout, stderr=subprocess.STDOUT) def upload(client, channel, filename): print('Uploading {}'.format(filename)) args = ['anaconda', '-t', client.token, 'upload', '-u', channel, filename] print(' '.join(args)) subprocess.run(args, stdout=sys.stdout, stderr=subprocess.STDOUT) def build_all(): allowed_host = 'psbuild-rhel6' if gethostname() != allowed_host: print('You should be running this on {}!'.format(allowed_host)) return print('Running build script') parser = argparse.ArgumentParser() parser.add_argument('--channel', action='store', required=True) parser.add_argument('--token', action='store', required=True) parser.add_argument('--no-build', action='store_true', required=False) args = parser.parse_args() channel = args.channel token = args.token client = binstar_client.Binstar(token=token) files = get_uploaded_files(client, channel) try: shutil.rmtree(BUILD_DIR) except Exception: pass build_path = Path(BUILD_DIR) build_path.mkdir() to_build = check_all(files, channel) built = [] num = 0 for _, (package, channel, py, np, full_path) in sorted(to_build.items()): if full_path not in built: num += 1 built.append(full_path) if not args.no_build: build(package, channel, py=py, np=np) upload(client, channel, full_path) print('') if num == 0: print('Done. Built 0 packages.') else: print('Done. Built {} packages:'.format(num)) for pkg in built: print(pkg) if __name__ == '__main__': build_all() <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Build a package that is a symbolic link to the current correct daq python package. This ensures we are always sync'd as we change daq releases. Using a release for this package instead of using conda-develop lets us track module dependencies. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * # NOQA import sys import os import stat import subprocess import re def get_deps(shared_object): ldd_out = subprocess.check_output(["ldd", shared_object]) deps = {} regex = re.compile(r'\t(.*) => (.*) \(0x') for line in ldd_out.splitlines(): match = regex.match(line.decode('utf-8')) if match: deps[match.group(1)] = match.group(2) return deps if __name__ == "__main__": try: hutch = os.environ["HUTCH"] except KeyError: raise RuntimeError("Set HUTCH environment variable before linking.") try: module = sys.argv[1] except IndexError: raise RuntimeError("Provide name of daq python package to link") hutch = hutch.lower() version = sys.version_info[0] package_name = module + ".so" package_ver = package_name + "." + str(version) if hutch == "dev": # This is a dev build! Point DEV_DIR to the build directory daq_root = os.environ["DEV_DIR"] ami_root = daq_root common_root = daq_root else: common_root = "/reg/g/pcds/dist/pds" if hutch != "current": common_root = os.path.join(common_root, hutch) daq_root = os.path.join(common_root, "current/build") ami_root = os.path.join(common_root, "ami-current/build") arch_ext = "lib/x86_64-linux" daq_py_dir = os.path.join(daq_root, "pdsapp", arch_ext) ami_py_dir = os.path.join(ami_root, "ami", arch_ext) daq_so = os.path.join(daq_py_dir, package_ver) ami_so = os.path.join(ami_py_dir, package_ver) if os.path.exists(daq_so): target = daq_so elif os.path.exists(ami_so): target = ami_so else: raise RuntimeError(("Could not find package dir for" "HUTCH={}").format(hutch)) deps = get_deps(target) lib_dir = os.path.join(os.environ["PREFIX"], "lib") install = os.path.join(lib_dir, "python" + os.environ["PY_VER"], "site-packages", package_name) ln = "if [ ! -f {1} ]; then\n ln -s {0} {1}\nfi\n" rm = "if [ -L {0} ]; then\n rm {0}\nfi\n" links = ln.format(target, install) unlinks = rm.format(install) for libname, path in deps.items(): if common_root in path: links += ln.format(path, os.path.join(lib_dir, libname)) unlinks += rm.format(os.path.join(lib_dir, libname)) paths = [] for name in ("install", "uninstall"): paths.append(os.path.join(os.environ["PREFIX"], "daq-links/{0}_{1}.sh".format(name, module))) for filename in paths: dirname = os.path.dirname(filename) if not os.path.exists(dirname): os.makedirs(dirname) with open(filename, "w") as f: if "uninstall" in filename: f.write(unlinks) else: f.write(links) st = os.stat(filename) os.chmod(filename, st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) <file_sep>#!/bin/bash $PREFIX/daq-links/install_pyami.sh <file_sep>#!/bin/bash $PREFIX/daq-links/install_pydaq.sh
302c80cc536e602f2af11ee8147724272b836249
[ "Python", "Shell" ]
7
Shell
klauer/pcds-recipes
6602351f58851608224adaa193866823dda7c1cb
8d6442be904ba7e9e9e7c42e630d7142822fb625
refs/heads/master
<file_sep># Budget-App-JavaScript Application for planning home budget <file_sep>const {resolve} = require('path'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const AppManifestWebpackPlugin = require('app-manifest-webpack-plugin'); module.exports = { mode: 'none', entry:'./src/js/app.js', devServer: { contentBase: './dist', }, output: { path: resolve(__dirname, 'dist'), filename: 'bundle.js', }, module: { rules: [ { test: /\.css/, use: [MiniCssExtractPlugin.loader, 'css-loader'] }, { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] }, plugins: [ new MiniCssExtractPlugin(), new HtmlWebpackPlugin({ title: 'Budget App JavaScript', template: 'src/index-template.html', filename: 'index.html', meta: { 'viewport': 'width=device-width, initial-scale=1.0', 'author': '<NAME>, <EMAIL>', 'description': 'Aplikacja do przeliczania i planowania domowych wydatków', 'keywords': 'domowy budżet, domowe wydatki, kalkulator wydatków', 'geo.region': 'PL-PK', 'geo.placename': 'Rzeszów', 'geo.position': '50.0054089,21.9184154', 'ICBM': '50.0054089,21.9184154', 'theme-color': '#000' }}), new CleanWebpackPlugin(), new AppManifestWebpackPlugin({ logo: './src/image/logo.png', inject: true, prefix: '', output: '/icons/', config: { appName: 'Budget App JavaScript', appDescription: null, developerName: null, developerURL: null, background: null, theme_color: null, version: '1.0', logging: false, icons: { android: false, appleIcon: true, appleStartup: false, coast: false, favicons: true, firefox: false, windows: false, yandex: false, }, } }) ] }
106d0d216394045816062281c85358190b0dc8ca
[ "Markdown", "JavaScript" ]
2
Markdown
mklepacz/Budget-App-JavaScript
a0c3ae0cf5f45000c81b75d04d330cabb8301515
ada6c734b65093104a9044962c7c98120795e0dd
refs/heads/master
<file_sep>import pandas as pd import numpy as np import string yelpDataset = pd.read_csv('Yelp.txt', sep='\t', header=None, encoding='latin-1') yelpDataset.columns = ['review', 'sentiment'] def removePunct(text): noPunct = ''.join([char for char in text if char not in string.punctuation]) return noPunct yelpDataset['review_clean'] = yelpDataset['review'].apply(lambda x: removePunct(x.lower())) df1 = pd.DataFrame(data = yelpDataset['review_clean']) #numpy array for review df1 = df1.values df2 = pd.DataFrame(data = yelpDataset['sentiment']) #numpy array for sentiment df2 = df2.values <file_sep>''' You will start with: Tokenized, cleaned, phrases Here, as the `phrases` variable. Give it a look! You will want to end up with: Normallized vectors, ready to be passed into a neural net ''' import random from sklearn.feature_extraction.text import CountVectorizer with open("words.txt") as f: words = f.readlines() words = [x.strip() for x in words] phrases = [] for i in range (0,10): phraselength = random.randint(5,15) phrase = [] for j in range(0,phraselength): choice = random.randint(0,len(words)) phrase.append(words[choice]) sentence = ' '.join(phrase) phrases.append(sentence) print(phrases) ''' Some ideas: Let's use Bag of Words Are there any libraries that have this built in? (Almost certainly yes!) How do I give those functions my data (Probably a Pandas Dataframe!) ''' #wasn't working properly without lowercase set to false, I thint it has to do with apostrophes #binary set to false will give us a count of how many times that word was present in the sentence #ngram set to groupings of 2 words only, can implement a range if we want vectorizer = CountVectorizer(binary=True, lowercase=False, ngram_range=(2, 2)) vector = vectorizer.fit_transform(phrases) print( vector.todense() ) print( vectorizer.vocabulary_ ) print(len( vectorizer.vocabulary_ )) <file_sep>''' You will start with: Normallized vectors, sparse, representing phrases Here as the `features` variable. Give it a look! You will want to end up with: A trained model that predicts positive or negative sentiment! (Woot!) ''' import random NUM_UNIQUE = 50 features = [] for i in range(20): piece = [0] * NUM_UNIQUE normal = 1.0 while (normal > 0): place = random.randint(0, NUM_UNIQUE-1) amount = random.random()/4 if (amount > normal): amount = normal piece[place] = amount normal -= amount features.append(piece) print(features) ''' Ideas/Questions: Do any libaries have NaiveBayesClassifier built in? (This is a yes, so which one?) How do we arrange the data to be sent into the model? (Probably with a Pandas Dataframe!) '''<file_sep># Twitter Sentiment Analysis ## What The Project Was >The programmer worked on a sentiment analysis project, where they were interested in developing a sentiment analysis model to >analyze sentiment of tweets by people in different cities to see if there was a correlation between the number of positive tweets and city. In short, the programmer was interested in determining in which cities are the citizens happiest. ## Toolkits and Libraries Used for the Project >The programmer used **BeautifulSoup**, **Pandas**, **NLTK**, **pprint**, **numpy**, **csv**, and **matplotlib.pyplot** libraries and toolkits. ## Datasets and Features Used for the Project >The project made use of the _"Sentiment 140"_ data set that was created by _**Stanford University**_. A copy of the data set can be found [_here_](http://help.sentiment140.com/for-students/). >The data set was a ranked data set that used the following fields for consideration in the sentiment analysis: 0 - the polarity of the tweet (0 = negative, 2 = neutral, 4 = positive) 1 - the tweet id 2 - the data of the tweet 3 - the query 4 - the user the tweet belongs to 5 - the text of the tweet itself >For training the sentiment analysis model, 1.6 million distinct entries were used for training, where half of the tweets were labelled as positive, > and the other half of tweets were labelled negative. >Since the data set contained a few unrelated fields for the desired purpose of the project, the programmer decided to drop fields 1-4 as seen above. This >left tweet polarity, and the text of the tweet itself as the main focus of the data set and model training. ## Data Preparation >After determining which fields in the data set were relevant to the project, the programmer then proceeded to clean the data, since there were some >data entries that were obviously invalid (used a string length check to verify which data entries were within the 140 character limit typical of a tweet >where it was found some entries exceeded the 140 character limit). Once that was completed, the programmer then took the HTML encoded text and parsed >it using **BeautifulSoup**. >After parsing the text, the programmer then refined it to remove any twitter mentions, and links as they concluded that these would not add any value to the model. >The programmer then found UTF-8 encoded text which interfered with the text processing, so they used 'utf-8-sig' to decode the text and replace it with a'?'. >Lastly, the programmer decided to remove any special characters contained in the tweet to account for hashtags since the special characters may interfere with >the model processing. >With cleaned data, the programmer then used the cleaning function that accounted for the above cleaning necessities to clean the whole data set. Once this was >completed, the programmer then exported the data to a csv file to use for training, where the data set was divided into four distinct batches. <file_sep># LanguageWarmUp Warm up repo for the QMIND Language team. Let's do some NLP! This small project predicts the sentiment (positive or negative) of Yelp reviews. ## Team Members * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> With <NAME> as PM
8819439f79906448b421f884d526bf4fb929a947
[ "Markdown", "Python" ]
5
Python
QMIND-Team/LanguageWarmUp
f7f698d161c8b0f80a56fb24c9e2d8106b8e2aed
115069cf292e2b53aad530edbde2e8ecfb407a88
refs/heads/master
<repo_name>zilin9g/sit725-prac2<file_sep>/server.js var express = require('express'); var app = express(); app.use(express.static(__dirname + '/public')); app.set('views', __dirname + '/public/views'); // Mapping the EJS template engine to ".html" files app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); // use for store accounts let accounts = [ {id:1,name:'alex',deposit:5},{id:2,name:'sarah',deposit:5},{id:3,name:'jim',deposit:15}]; //linked list var list = require('./LList.class'); //the reason of use a linkedlist instead of an array is that Linked lists are easier to traverse and linked lists are not limited by length var account1={id:1,name:'alex',deposit:5}; var account2={id:2,name:'sarah',deposit:5}; var account3={id:3,name:'jim',deposit:15} list.insert(account1,'head'); list.insert(account2,account1); list.insert(account3,account2); app.get('/', function (req, res) { res.render("index.html"); }) //add numbers app.get('/addNumber', function (req, res) { res.writeHead(200, { 'Content-Type': 'application/json' }); var Number1=+req.query.Number1; var Number2=+req.query.Number2; // 输出 JSON 格式 response = { result:(Number1+Number2) }; res.end(JSON.stringify(response)); }) //get data from array app.get('/getArrayData', function (req, res) { res.writeHead(200, { 'Content-Type': 'application/json' }); // 输出 JSON 格式 response = { data:accounts }; res.end(JSON.stringify(response)); }) //get data from array by id app.get('/getArrayDataById', function (req, res) { res.writeHead(200, { 'Content-Type': 'application/json' }); var id = req.query.id; var account; for(var i=0;i<accounts.length;i++) { if(accounts[i].id==id) { account=accounts[i]; } } // 输出 JSON 格式 response = { data:account }; res.end(JSON.stringify(response)); }) //get data from linked list app.get('/getLinkedData', function (req, res) { res.writeHead(200, { 'Content-Type': 'application/json' }); var accounts = []; var node = list.findLast(); while(node.element!='head') { accounts.push(node.element); node = node.previous; } // 输出 JSON 格式 response = { data:accounts }; res.end(JSON.stringify(response)); }) //get data from linked list by id app.get('/getLinkedDataById', function (req, res) { res.writeHead(200, { 'Content-Type': 'application/json' }); var id = req.query.id; var account; var node = list.findLast(); while(true) { if(parseInt(node.element.id)==parseInt(id)) { account=node.element; break; } if(node.previous==null) { account=null; break; }else{ node = node.previous; } } // 输出 JSON 格式 response = { data:account }; res.end(JSON.stringify(response)); }) var server = app.listen(3000, function () { var host = server.address().address var port = server.address().port //print host console.log("App is listening on http://%s:%s", host, port) })
962036eb29459ed8d6670e6982b0b4edf11fe8e0
[ "JavaScript" ]
1
JavaScript
zilin9g/sit725-prac2
e151cf911180fbc09e6bc4b9e50a0b3256261ce4
7f1ae1414925a67a0f994147dfc92ef7e2fbae8c
refs/heads/master
<file_sep>from django import forms from pycosite.models import Page, PageUrl STATUS_CHOICES = (('offline', 'offline'), ('published', 'published')) class PageForm(forms.ModelForm): status = forms.ChoiceField(choices=STATUS_CHOICES) class Meta: model = Page class UrlForm(forms.ModelForm): class Meta: model = PageUrl <file_sep>from djazz.models import Post, PostManager, PostVar, PostVarManager from django.db import IntegrityError class PageManager(PostManager): POST_TYPE = 'pycopage' def get_from_url(self, url): p = Page.objects.get(postvar__key='url', postvar__value=url) return p class Page(Post): objects = PageManager() class Meta: proxy = True def get_url(self): return self.postvar.get(key='url').value def set_url(self, url): if PageUrl.objects.filter(value=url)\ .exclude(post=self)\ .count() > 0: raise IntegrityError("url %s already exists" % url) o, c = self.postvar.get_or_create(key='url') o.value = url o.save() def get_layout(self): try: return self.postvar.get(key='layout').value except PostVar.DoesNotExist: return 'default.html' def set_layout(self, layout): o, c = self.postvar.get_or_create(key='layout') o.value = layout o.save() def save(self, *args, **kwargs): from django.utils import timezone if not self.id: self.date = timezone.now() self.last_date = timezone.now() return super(Page, self).save(*args, **kwargs) class UrlManager(PostVarManager): VAR_TYPE = 'url' class PageUrl(PostVar): objects = UrlManager() class Meta: proxy = True <file_sep>from django.shortcuts import render from django.http import HttpResponseNotFound from django.template import loader, RequestContext from pycosite.models import Page def page_unavailable(request, url): tpl_name = 'pycosite/responses/HttpResponseNotFound.html' t = loader.get_template(tpl_name) c = RequestContext(request, {}) c['url'] = url return HttpResponseNotFound(t.render(c)) def view(request, url): try: p = Page.objects.get_from_url(url) if p.status == 'published': return render(request, 'pycosite/layouts/%s' % p.get_layout(), {'page': p}) else: return page_unavailable(request, url) except Page.DoesNotExist: return page_unavailable(request, url) <file_sep>from django.contrib import admin from pycosite.models import Page, PageUrl from pycosite.forms import PageForm, UrlForm class UrlInline(admin.TabularInline): model = PageUrl form = UrlForm extra = 1 max_num = 1 exclude = ['key'] class PageAdmin(admin.ModelAdmin): form = PageForm inlines = [UrlInline] readonly_fields = ['author', 'date', 'last_editor', 'last_date'] exclude = ['type', 'format'] def save_model(self, request, obj, form, change): if not obj.id: obj.author = request.user obj.last_editor = request.user super(PageAdmin, self).save_model(request, obj, form, change) admin.site.register(Page, PageAdmin)
e9e6ab396b5f33eff5f1b4b01196182364b2037d
[ "Python" ]
4
Python
djazzfm/pycosite
9bd5a005320cef1c2c7367096d187ee604d00af6
78e97ba07c41404638525685b9c7595d649421fe
refs/heads/master
<repo_name>Karthiattri/PageObjectModelEx<file_sep>/pageobjt/src/pageObjts/Loginpageobjts.java package pageObjts; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; //import org.openqa.selenium.By; //import org.openqa.selenium.WebDriver; //import org.openqa.selenium.WebElement; public class Loginpageobjts { @FindBy(how = How.NAME,using = "username") public static WebElement username; @FindBy(name = "password") public static WebElement password; @FindBy(xpath = "//*[@id=\"loginfrm\"]/button") public static WebElement sumit; // public static WebElement username(WebDriver driver) // { // return driver.findElement(By.name("username")); // // } // public static WebElement password(WebDriver driver) // { // return driver.findElement(By.name("password")); // } // public static WebElement login(WebDriver driver) // { // return driver.findElement(By.xpath("//*[@id=\"loginfrm\"]/button")); // } } <file_sep>/README.md # PageObjectModelEx This contain POM Example in eclipse
0dfafef7d3717dc29b84586cdeb56ea6b3d7eb95
[ "Markdown", "Java" ]
2
Java
Karthiattri/PageObjectModelEx
9a62750ca7a48978fd80b030da4b06a3502e0cf0
e5b834d2593784126f4e7eac6f60f4935ebea0a9
refs/heads/master
<repo_name>gedunlap/rockandrow-frontend<file_sep>/src/components/Header.js import React from 'react' import { Link } from 'react-router-dom' export default function Header() { return ( <nav className="nav"> <img src="https://i.imgur.com/hSdfdNu.png" alt="rock and row logo" className="navitem" /> <Link to='/' style={{textDecoration: "none"}} className="navitem"> <div>Home</div> </Link> <Link to='/list' style={{textDecoration: "none"}} className="navitem"> <div>Log</div> </Link> </nav> ) } <file_sep>/src/components/Main.js import React from 'react' import { useEffect, useState } from 'react' import { Route, Switch } from 'react-router-dom' import Index from '../pages/Index' import Show from '../pages/Show' import Home from '../pages/Home' export default function Main(props) { const [workouts, setWorkouts] = useState(null) const URL = "https://rockandrow-backend.herokuapp.com/workouts/" const getWorkouts = async () => { const response = await fetch(URL) const data = await response.json() setWorkouts(data) } const createWorkouts = async (workout) => { await fetch(URL, { method: "post", headers: { "Content-Type": "application/json" }, body: JSON.stringify(workout) }) getWorkouts() } const updateWorkouts = async (workout, id) => { await fetch(URL + id, { method: "put", headers: { "Content-Type": "application/json", }, body: JSON.stringify(workout) }) getWorkouts() } const deleteWorkouts = async id => { await fetch(URL + id, { method: "delete" }) getWorkouts() } useEffect(() => getWorkouts(), []) return ( <main> <Switch> <Route exact path='/'> <Home /> </Route> <Route path='/list'> <Index workouts={workouts} createWorkouts={createWorkouts} /> </Route> <Route path='/workouts/:id' render={(rp) => ( <Show workouts={workouts} updateWorkouts={updateWorkouts} deleteWorkouts={deleteWorkouts} {...rp} /> )} /> </Switch> </main> ) } <file_sep>/src/pages/Show.js import React from 'react' import { useState } from 'react' export default function Show(props) { const id = props.match.params.id const workouts = props.workouts const workout = workouts.find(w => w._id === id) const [editForm, setEditForm] = useState(workout) const handleChange = event => { setEditForm({ ...editForm, [event.target.name]: event.target.value }) } const handleSubmit = event => { event.preventDefault() props.updateWorkouts(editForm, workout._id) props.history.push('/list') } const removeWorkout = () => { props.deleteWorkouts(workout._id) props.history.push('/list') } return ( <div className="show"> <h1 className="workoutitem">Date: {workout.date}</h1> <h1 className="workoutitem">Time: {workout.time}</h1> <h1 className="workoutitem">Distance: {workout.distance}</h1> <h1 className="workoutitem">Drag: {workout.drag}</h1> <form onSubmit={handleSubmit} className="form"> <input type="date" value={editForm.date} name="date" onChange={handleChange} className="formitem" /> <input type="text" value={editForm.time} name="time" placeholder="00:00" onChange={handleChange} className="formitem" /> <input type="number" value={editForm.distance} name="distance" placeholder="Distance" onChange={handleChange} className="formitem" /> <input type="number" value={editForm.drag} name="drag" placeholder="Drag" onChange={handleChange} className="formitem" /> <input type="submit" value="UPDATE" className="formitem" id="submit" /> </form> <button id="delete" onClick={removeWorkout} style={{ backgroundColor:"red", borderRadius:"5px", border:"solid black 1px", color:"white", marginBottom:"30px"}}>DELETE WORKOUT</button> </div> ) } <file_sep>/src/pages/Home.js import React from 'react' import YoutubeEmbed from '../components/YoutubeEmbed' export default function Home() { return ( <div className="homepage"> <img src="https://i.imgur.com/PgK41G7.png" alt="rock and row logo" /> <p>Rock and Row is an app made simply to store your rowing workout stats.</p> <p>Check out this video for some form pointers.</p> <YoutubeEmbed className="youtube" /> </div> ) } <file_sep>/src/pages/Index.js import React from 'react' import { useState } from 'react' import { Link } from 'react-router-dom' export default function Index(props) { const [newForm, setNewForm] = useState({ date: "", time: "", distance: "", drag: "", }) const handleChange = (event) => { setNewForm({ ...newForm, [event.target.name]: event.target.value }) } const handleSubmit = (event) => { event.preventDefault() props.createWorkouts(newForm) setNewForm({ date: "", time: "", distance: "", drag: "", }) } const loaded = () => { return props.workouts.map((workout) => ( <div key={workout._id} className='workout'> <Link to={`/workouts/${workout._id}`} style={{ textDecoration: "none" }}><h1><button>{workout.date}</button></h1></Link> </div> )) } const loading = () => { return <h1>Loading...</h1> } return ( <section className="index"> <form onSubmit={handleSubmit} className="form"> <label htmlFor="date">Date</label> <input type="date" value={newForm.date} name="date" onChange={handleChange} className="formitem" /> <label htmlFor="time">Time</label> <input type="text" value={newForm.time} name="time" placeholder="00:00" onChange={handleChange} className="formitem" /> <label htmlFor="distance">Distance</label> <input type="number" value={newForm.distance} name="distance" placeholder="0" onChange={handleChange} className="formitem" /> <label htmlFor="drag">Drag</label> <input type="number" value={newForm.drag} name="drag" placeholder="0" onChange={handleChange} className="formitem" /> <input type="submit" value="SUBMIT" className="formitem" id="submit" /> </form> {props.workouts ? loaded() : loading()} </section> ) }
8c78c9aaec8f0e1430873e9a01e96c22f7832b99
[ "JavaScript" ]
5
JavaScript
gedunlap/rockandrow-frontend
a7592c482340dbcb7401b238baa4ab18d8a58590
66db72db626a82a237ed2a54c705ac81dbebf10e
refs/heads/master
<file_sep>import axios from 'axios' import { bindActionCreators } from 'redux' import {initialState} from '../readucer/reducer' export const FETCH_WEATHER_START = "FETCH_WEATHER_START" export const FETCH_WEATHER_SUCCESS = "FETCH_WEATHER_SUCCESS" export const FETCH_WEATHER_FAILURE = "FETCH_WEATHER_FAILURE" // export const FETCH_WEATHER_CITY = "FETCH_WEATHER_CITY" export const fetchReports = (newCity) => { return dispatch => { dispatch({type: FETCH_WEATHER_START}) axios .get(`https://api.openweathermap.org/data/2.5/weather?q=${newCity}&appid=a635da4f8eb097418cecae91074f75ae&units=imperial`) .then( res => { dispatch({type: FETCH_WEATHER_SUCCESS, payload: res.data.weather , payload2: res.data.main , payload3: res.data.name}) }) .catch(err => { dispatch({type: FETCH_WEATHER_FAILURE , payload: err.message}) }) } }<file_sep>import React , {useEffect ,useState} from 'react' import {connect} from 'react-redux' import {fetchReports} from '../actions/index' const Weather = props => { const [newCity , setNewCity] = useState(props.updateCity) const handleChanges = e => { setNewCity({ [e.target.name]: e.target.value }); }; useEffect(()=>{ props.fetchReports(newCity); }, []) return ( <div className='box'> <div className='container'> <div className='input'> <input type='text' name='newcity' onChange={handleChanges} /> <button className='input' >Find a new city</button> </div> {props.isLoading && <h4>Loading your weather report...</h4>} {props.error && (<p className="error"> Uh oh it's cloudy with a chance of no weather report...{props.error}</p>)} {props.weatherReport.length > 0 && ( <div> <p>City: {props.city}</p> {props.weatherReport.map(weather => ( <div key={weather.id}><p> Description: {weather.main}</p></div> ))} <p> Temperature: {props.weatherTemp.temp}F°</p> <p> Feels Like: {props.weatherTemp.feels_like} F°</p> <p> High: {props.weatherTemp.temp_max }F° </p> <p> Low: {props.weatherTemp.temp_min} F°</p> <p> humidity: {props.weatherTemp.humidity} %</p> </div> )} </div> </div> ) } const mapStateToProps = state => { return { isLoading: state.isLoading, weatherReport: state.weatherReport, error: state.error, weatherTemp: state.weatherTemp, city: state.city, updateCity: state.updateCity } } export default connect(mapStateToProps, {fetchReports})(Weather);<file_sep>import {FETCH_WEATHER_FAILURE, FETCH_WEATHER_SUCCESS, FETCH_WEATHER_START} from '../actions/index' export const initialState = { isLoading: false, weatherReport: [], weatherTemp: [], city: [], updateCity :'Houston.', error: "", } export const reducer = (state = initialState , action) => { switch(action.type){ case FETCH_WEATHER_START: return{ ...state, isLoading: true }; case FETCH_WEATHER_SUCCESS: return { ...state, isLoading: false, weatherReport: action.payload, weatherTemp: action.payload2, city: action.payload3, error: "" } case FETCH_WEATHER_FAILURE: return{ ...state, isLoading: false, error: action.payload } default: return state } };
6345f918acc003941dc0083f88b5b236380f3713
[ "JavaScript" ]
3
JavaScript
JazmineMT/React-Redux-App
5e7f6b8472e6363a9f9fdd7804117039d44932b6
5a7355983151a7ce272ec7fa8173ef72299937b9
refs/heads/master
<file_sep>package in.codeshuffle.scratchcardlayoutexample.ui.fragment.demoscreen; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SeekBar; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import in.codeshuffle.scratchcardlayout.listener.ScratchListener; import in.codeshuffle.scratchcardlayout.ui.ScratchCardLayout; import in.codeshuffle.scratchcardlayout.util.ScratchCardUtils; import in.codeshuffle.scratchcardlayoutexample.util.AppUtils; import in.codeshuffle.scratchcardviewexample.R; import in.codeshuffle.scratchcardviewexample.databinding.FragmentDemoBinding; public class DemoFragment extends DialogFragment implements ScratchListener { private static final String TAG = DemoFragment.class.getSimpleName(); private Context context; private FragmentDemoBinding binding; public static DemoFragment getInstance() { Bundle bundle = new Bundle(); DemoFragment demoFragment = new DemoFragment(); demoFragment.setArguments(bundle); return demoFragment; } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); this.context = context; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = FragmentDemoBinding.inflate(inflater); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); resetLibraryView(); setControlPanelListeners(); } private void resetLibraryView() { binding.reset.setOnClickListener(v -> { //Java reset binding.scratchCard.setScratchDrawable(getResources().getDrawable(R.drawable.scratch)); binding.scratchCard.setScratchListener(DemoFragment.this); binding.scratchCard.setScratchWidthDip(ScratchCardUtils.dipToPx(context, 40)); binding.scratchCard.setRevealFullAtPercent(40); binding.scratchCard.setScratchEnabled(true); binding.scratchCard.resetScratch(); //Xml Reset binding.brushSizeSeekBar.setProgress(40); binding.revealFullAtSeekBar.setProgress(40); binding.scratchEffectToggle.setChecked(true); binding.scratchEffectToggle.setText(getString(R.string.enabled)); }); binding.reset.performClick(); } private void setControlPanelListeners() { //Scratch Brush size config binding.brushSizeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { binding.scratchCard.setScratchWidthDip(ScratchCardUtils.dipToPx(context, seekBar.getProgress())); } }); //Scratch effect config binding.scratchEffectToggle.setOnCheckedChangeListener((buttonView, isChecked) -> { binding.scratchCard.setScratchEnabled(isChecked); binding.scratchEffectToggle.setText(getString(isChecked ? R.string.enabled : R.string.disabled)); }); //Scratch reveal at percent binding.revealFullAtSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { AppUtils.showShortToast(getActivity(), getString(R.string.resetting_view_since_reveal_percent_was_changed)); binding.scratchCard.setRevealFullAtPercent(seekBar.getProgress()); binding.scratchCard.resetScratch(); } }); } @Override public void onDetach() { super.onDetach(); } @Override public void onDestroy() { super.onDestroy(); } @Override public void onScratchStarted() { Log.d(TAG, "Scratch started"); } @Override public void onScratchProgress(ScratchCardLayout scratchCardLayout, int atLeastScratchedPercent) { Log.d(TAG, "Progress = " + atLeastScratchedPercent); } @Override public void onScratchComplete() { Log.d(TAG, "Scratch ended"); } } <file_sep>package in.codeshuffle.scratchcardlayout.ui; import android.content.Context; import android.graphics.drawable.Drawable; import androidx.cardview.widget.CardView; import android.util.AttributeSet; import android.view.ViewGroup; import in.codeshuffle.scratchcardlayout.listener.ScratchListener; public class ScratchCardLayout extends CardView implements ScratchCard.ScratchCardInterface { private ScratchCard scratchCard; private Context mContext; public ScratchCardLayout(Context context) { super(context); init(context, null, 0); } public ScratchCardLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0); } public ScratchCardLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr); } /** * Set the scratch brush width * * @param mScratchWidthDip width in dp (Use Utility method {@code ScratchCardUtils.dipToPx} for conversion) */ public void setScratchWidthDip(float mScratchWidthDip) { scratchCard.setScratchWidthDip(mScratchWidthDip); } /** * Set the layout resource id of image to show as overlay for scratching * ({@code Drawable} image or {@code ColorDrawable}) * * @param mScratchDrawable layout resource id */ public void setScratchDrawable(Drawable mScratchDrawable) { scratchCard.setScratchDrawable(mScratchDrawable); } /** * Scratch listener * * @param mListener listener object * (implement the interface in the type of the instance passed in which to listen to callbacks) */ public void setScratchListener(ScratchListener mListener) { scratchCard.setListener(mListener); } private void init(Context context, AttributeSet attrs, int defStyleAttr) { this.mContext = context; scratchCard = new ScratchCard(context, attrs, defStyleAttr); scratchCard.setRevealListener(this); setupScratchView(); } /** * Adding the scratch card to layout */ private void setupScratchView() { scratchCard.setLayoutParams(new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); post(new Runnable() { @Override public void run() { addView(scratchCard); } }); } /** * Stop or Interrupt scratch effect */ public void stopScratching() { scratchCard.setVisibility(GONE); } /** * Reveal full layout when some threshold percent is scratched * * @param revealFullAtPercent threshold percent */ public void setRevealFullAtPercent(int revealFullAtPercent) { scratchCard.setRevealFullAtPercent(revealFullAtPercent); } @Override public void onFullReveal() { stopScratching(); } /** * Enable/Disable scratch effect * @param enableScratching true/false based on your choice */ public void setScratchEnabled(boolean enableScratching) { scratchCard.setScratchEnabled(enableScratching); } /** * Reset scratch. (As if its a whole new scratch session */ public void resetScratch() { scratchCard.resetScratch(); } }
a795c17f8b31596fc074dd7c7397856b8289440a
[ "Java" ]
2
Java
rupamrd/scratchCardLayout
b3f0936a5935a6bd431df6bcefe772dcb70d6e6b
51e4570a53ffe0dcdd0222448a07c3edad1bf465
refs/heads/master
<repo_name>tonykobe8/typescript-kahhcg<file_sep>/README.md # typescript-kahhcg [Edit on StackBlitz ⚡️](https://stackblitz.com/edit/typescript-kahhcg)<file_sep>/index.ts // Import stylesheets import './style.css'; // Write TypeScript code! const appDiv: HTMLElement = document.getElementById('app'); appDiv.innerHTML = ''; var hours = seconds / 3600 ; var minutes =(seconds % 3600)/ 60; var seconds = 60 ; function convert(hours,minutes) { return seconds; } console.log(seconds)
b01703db34da7fe34af1244098f514b3edda611a
[ "Markdown", "TypeScript" ]
2
Markdown
tonykobe8/typescript-kahhcg
ee59c2fa266ff26422f2428b59e99ce6452351fb
a1e18d1e467c85a7306005062e0e4d89bbb09806
refs/heads/master
<file_sep>package com.inpainting; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; /** * Wrapper/Helper for Masked RGB Bitmap * * @author <NAME> */ public class MaskedImage { // image data private boolean[][] mask; private Bitmap image; public final int W, H; // the maximum value returned by MaskedImage.distance() public static final int DSCALE = 65535; // array for converting distance to similarity public static final double[] similarity; static { // build similarity curve such that similarity[0%]=0.999 and similarity[4%]=0.5 double s_zero = 0.999; double t_halfmax = 0.10; double x = (s_zero - 0.5) * 2; double invtanh = 0.5 * Math.log((1 + x) / (1 - x)); double coef = invtanh / t_halfmax; similarity = new double[DSCALE + 1]; for (int i = 0; i < similarity.length; i++) { double t = (double) i / similarity.length; similarity[i] = 0.5 - 0.5 * Math.tanh(coef * (t - t_halfmax)); } } // construct from existing Bitmap and mask public MaskedImage(Bitmap image, boolean[][] mask) { this.image = image; this.W = image.getWidth(); this.H = image.getHeight(); this.mask = mask; if (this.mask == null) this.mask = new boolean[W][H]; } // construct empty image public MaskedImage(int width, int height) { this.W = width; this.H = height; this.image = Bitmap.createBitmap(W, H, Bitmap.Config.ARGB_8888); this.mask = new boolean[W][H]; } public Bitmap getBitmap() { return image; } public int getSample(int x, int y, int band) { int val = 0; int pixel = image.getPixel(x, y); if (band == 0) val = Color.red(pixel); else if (band == 1) val = Color.green(pixel); else if (band == 2) val = Color.blue(pixel); return val; } public void setSample(int x, int y, int r, int g, int b) { int pixel = image.getPixel(x, y); image.setPixel(x, y, Color.rgb(r, g, b)); } public boolean isMasked(int x, int y) { return mask[x][y]; } public void setMask(int x, int y, boolean value) { mask[x][y] = value; } public int countMasked() { int count = 0; for (int y = 0; y < H; y++) for (int x = 0; x < W; x++) if (mask[x][y]) count++; return count; } // return true if the patch contains one (or more) masked pixel public boolean constainsMasked(int x, int y, int S) { for (int dy = -S; dy <= S; dy++) { for (int dx = -S; dx <= S; dx++) { int xs = x + dx, ys = y + dy; if (xs < 0 || xs >= W) continue; if (ys < 0 || ys >= H) continue; if (mask[xs][ys]) return true; } } return false; } // distance between two patches in two images public static int distance(MaskedImage source, int xs, int ys, MaskedImage target, int xt, int yt, int S) { long distance = 0, wsum = 0, ssdmax = 10 * 255 * 255; // for each pixel in the source patch for (int dy = -S; dy <= S; dy++) { for (int dx = -S; dx <= S; dx++) { wsum += ssdmax; int xks = xs + dx, yks = ys + dy; if (xks < 0 || xks >= source.W) { distance += ssdmax; continue; } if (yks < 0 || yks >= source.H) { distance += ssdmax; continue; } // cannot use masked pixels as a valid source of information if (source.isMasked(xks, yks)) { distance += ssdmax; continue; } // corresponding pixel in the target patch int xkt = xt + dx, ykt = yt + dy; if (xkt < 0 || xkt >= target.W) { distance += ssdmax; continue; } if (ykt < 0 || ykt >= target.H) { distance += ssdmax; continue; } // cannot use masked pixels as a valid source of information if (target.isMasked(xkt, ykt)) { distance += ssdmax; continue; } // SSD distance between pixels (each value is in [0,255^2]) long ssd = 0; // value distance (weight for R/G/B components = 3/6/1) for (int band = 0; band < 3; band++) { int weight = (band == 0) ? 3 : (band == 1) ? 6 : 1; double diff2 = Math.pow(source.getSample(xks, yks, band) - target.getSample(xkt, ykt, band), 2); // Value ssd += weight * diff2; } // add pixel distance to global patch distance distance += ssd; } } return (int) (DSCALE * distance / wsum); } // Helper for Bitmap resize public static Bitmap resize(Bitmap input, int newwidth, int newheight) { Bitmap out = Bitmap.createBitmap(newwidth, newheight, Bitmap.Config.ARGB_8888); Canvas g = new Canvas(out); Bitmap scaled = Bitmap.createScaledBitmap(input, newwidth, newheight, true); g.drawBitmap(scaled, 0f, 0f, new Paint()); return out; } // return a copy of the image public MaskedImage copy() { boolean[][] newmask = new boolean[W][H]; Bitmap newimage = Bitmap.createBitmap(image, 0, 0, W, H); //newimage.createGraphics().drawImage(image, 0, 0, null); for (int y = 0; y < H; y++) for (int x = 0; x < W; x++) newmask[x][y] = mask[x][y]; return new MaskedImage(newimage, newmask); } // return a downsampled image (factor 1/2) public MaskedImage downsample() { int newW = W / 2, newH = H / 2; // Binomial coefficient kernels int[] kernelEven = new int[]{1, 5, 10, 10, 5, 1}; int[] kernelOdd = new int[]{1, 4, 6, 4, 1}; int[] kernelx = (W % 2 == 0) ? kernelEven : kernelOdd; int[] kernely = (H % 2 == 0) ? kernelEven : kernelOdd; MaskedImage newimage = new MaskedImage(newW, newH); for (int y = 0, ny = 0; y < H - 1; y += 2, ny++) { for (int x = 0, nx = 0; x < W - 1; x += 2, nx++) { long r = 0, g = 0, b = 0, ksum = 0, masked = 0, total = 0; for (int dy = 0; dy < kernely.length; dy++) { int yk = y + dy - 2; if (yk < 0 || yk >= H) continue; for (int dx = 0; dx < kernelx.length; dx++) { int xk = x + dx - 2; if (xk < 0 || xk >= W) continue; total++; if (mask[xk][yk]) { masked++; continue; } int k = kernelx[dx] * kernely[dy]; r += k * this.getSample(xk, yk, 0); g += k * this.getSample(xk, yk, 1); b += k * this.getSample(xk, yk, 2); ksum += k; } } if (ksum > 0) { newimage.setSample(nx, ny, (int) ((double) r / ksum + 0.5), (int) ((double) g / ksum + 0.5), (int) ((double) b / ksum + 0.5)); newimage.setMask(nx, ny, false); } else { newimage.setMask(nx, ny, true); } if (masked > 0.75 * total) newimage.setMask(nx, ny, true); else newimage.setMask(nx, ny, false); } } return newimage; } // return an upscaled image public MaskedImage upscale(int newW, int newH) { MaskedImage newimage = new MaskedImage(newW, newH); newimage.image = resize(this.image, newW, newH); return newimage; } } <file_sep>include ':inpainting' include ':app' rootProject.name = "androidInpainting"<file_sep># androidInpainting -------------- [![](https://jitpack.io/v/jongwonleee/androidInpainting.svg)](https://jitpack.io/#jongwonleee/androidInpainting) [![API](https://img.shields.io/badge/API-21%2B-brightgreen.svg?style=flat)](https://android-arsenal.com/api?level=21) This will fill the empty space of mask when you excute the library. This object uses patch-match algorithm to inpaint the image, it takes 20 secs to 5 minutes depends on the size of the image. refer to [@davidchatting](https://github.com/davidchatting/PatchMatch) --- ### Example ##### Original Image ![original](/sample/original.jpg) ##### Mask Image ![mask](/sample/mask.jpg) ##### Result Image ![result](/sample/result.jpg) --- ### Gradle ##### Root build.gradle ```gradle allprojects { repositories { ... maven { url 'https://jitpack.io' } } } ``` ##### App build.gradle ```gradle implementation 'com.github.jongwonleee:androidInpainting:0.10.2 ``` --- ### How To USe ```java val bitmap = Inpaint().inpaint(@originalImage, @maskedImage , @calculateRadius) ``` - @original image: a bitmap image you want to get filled - @masked image: a bitmap image which contains hole where original image wants to get filled - @calculate radius: the smaller the radius, high quality you get, slower the algorithm - return: a bitmap image that has filled by inpainting --- ### License Copyright 2020 @jongwonleee Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
c1a5672ceefb349c5d1ee465bc0b932ee446c13d
[ "Markdown", "Java", "Gradle" ]
3
Java
zhangzhiao/androidInpainting
1aff367ec7ad30ddb6052401cdd39d85163be581
c386a2105bd5f61c9308b494e52707bb34681043
refs/heads/master
<repo_name>funnylau29/worksapplication2013recruite<file_sep>/Exam/src/jp/co/wap/exam/test/Problem1Test.java package jp.co.wap.exam.test; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import jp.co.wap.exam.Problem1; import jp.co.wap.exam.lib.Interval; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; public class Problem1Test { @Test public void testGetMaxIntervalOverlapCount() { Problem1 p = new Problem1(); // example Figure 1 Interval interval1 = new Interval("08:00", "12:00"); Interval interval2 = new Interval("06:00", "09:00"); Interval interval3 = new Interval("11:00", "13:00"); List<Interval> figure1 = Arrays.asList(interval1, interval2, interval3); assertThat(p.getMaxIntervalOverlapCount(figure1), is(2)); // example Figure 2 List<Interval> figure2 = Arrays.asList(new Interval("09:00", "12:30"), new Interval("06:00", "09:30"), new Interval("12:00", "14:30"), new Interval("10:00", "10:30"), new Interval("11:00", "13:30")); assertThat(p.getMaxIntervalOverlapCount(figure2), is(3)); // other examples assertThat(p.getMaxIntervalOverlapCount(new ArrayList<Interval>()), is(0)); assertThat(p.getMaxIntervalOverlapCount(null), is(0)); assertThat(p.getMaxIntervalOverlapCount(Arrays.asList(new Interval( "09:00", "09:30"), new Interval("06:00", "09:00"))), is(2)); assertThat(p.getMaxIntervalOverlapCount(Arrays.asList(new Interval( "09:00", "09:30"), new Interval("06:00", "09:30"))), is(2)); assertThat(p.getMaxIntervalOverlapCount(Arrays.asList(new Interval( "09:00", "09:00"), new Interval("06:00", "09:30"))), is(2)); assertThat(p.getMaxIntervalOverlapCount(Arrays.asList(new Interval( "09:00", "09:00"), new Interval("06:00", "09:30"))), is(2)); assertThat(p.getMaxIntervalOverlapCount(Arrays.asList(new Interval( "09:00", "09:00"), new Interval("09:00", "09:00"))), is(2)); assertThat(p.getMaxIntervalOverlapCount(Arrays.asList(new Interval( "08:00", "09:00"), new Interval("09:00", "09:00"), new Interval("09:00", "19:00"))), is(3)); } @Test public void testGetMaxIntervalOverlapCountPerformance() { Problem1 p = new Problem1(); int num = 0; while ((num += 500) <= 10000) { List<Interval> randomGenIntervals = Problem2Test .randomGenIntervals(num); long current = System.currentTimeMillis(); p.getMaxIntervalOverlapCount(randomGenIntervals); // System.out.println("benchmark:" + num + " time:" // + (System.currentTimeMillis() - current)); } } } <file_sep>/Exam/src/jp/co/wap/exam/Utils.java package jp.co.wap.exam; import java.util.Comparator; import java.util.List; import jp.co.wap.exam.lib.Interval; public class Utils { /** * Find the nearest mutually exclusive (non-overlapping) interval that * starts before a given BeginMinuteUnit. * * @param orderedIntervals * @param beginMinUnit * @return an integer represents the index (start from 1) of target interval */ public static int bisecRightID(List<Interval> orderedIntervals, int beginMinUnit) { int m; int l = 0, r = orderedIntervals.size() - 1; while (r >= l) { m = (l + r) / 2; if (orderedIntervals.get(m).getEndMinuteUnit() < beginMinUnit) l = m + 1; else r = m - 1; } return r + 1; } public static Comparator<Interval> endMinuteUnitComparator = new Comparator<Interval>() { @Override public int compare(Interval o1, Interval o2) { return o1.getEndMinuteUnit() - o2.getEndMinuteUnit(); } }; }
90a8a8a4efd1f3e4b73751161d7a318a9b437ca3
[ "Java" ]
2
Java
funnylau29/worksapplication2013recruite
f7ad07c61ab4cfa08be124d554629c671287ed4b
dcc968c3c417b54ea714eb09f6cc61dfa66e594f
refs/heads/master
<file_sep>class Bowling def hit(pins) end def score foo = 10 if true && self.hit foo 10 else 0 end end end
c2293caf33caf94dbd8927ead100654a76f67462
[ "Ruby" ]
1
Ruby
abrom/travis-rspec-test
359c731c2b0f97bc4d12d851e99ade028d26ba5e
7d2db93674e5418e931cbe38dc1263bda583530d
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpanEnemies : MonoBehaviour { private Vector3 positionV = new Vector3(9f, -4f, 0f); public GameObject enemies; private int enemiesAmount = 0; private GameObject []enemyArray = new GameObject[3]; private Vector3[] posArray = new Vector3[3]; public void Spawn() { int spawn_num = (int)Random.Range(1, 4); for (int i = 0; i < spawn_num; i++) { enemyArray[i]=Instantiate(enemies, positionV, Quaternion.identity); posArray[i] = positionV; positionV.y = positionV.y + 3; enemiesAmount++; } Debug.Log(this.getSize()); } public GameObject getEnemy(int index) { return enemyArray[index]; } public void removeEnemy(int at) { GameObject[] tempEnemyArray = new GameObject[enemiesAmount-1]; int index = 0; for (int i = 0; i < enemiesAmount; i++) { if (i != at) { tempEnemyArray[index] = enemyArray[i]; index++; } } enemyArray = tempEnemyArray; enemiesAmount--; } public int getSize() { return enemiesAmount; } public Vector3 getOgPos(int index) { return posArray[index]; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class InventoryController : MonoBehaviour { Manager game_manager_properties = new Manager(); ///////////////////////// // INVENTORY AND ITEMS // ///////////////////////// public static GameObject[] inventory = new GameObject[100]; public static int[] inventory_amt = new int [100]; public static int inventoryIndex = 0; public GameObject[] all_items; ///////////////////////// // INVENTORY FUNCTIONS // ///////////////////////// bool hasItem(string itemName) { for (int i = 0; i < inventoryIndex; i++) { if (itemName == inventory[i].name) { int amt = inventory_amt[i]++; amt++; inventory_amt[i] = amt; return true; } } return false; } public void add_to_inventory(string itemName) { if (!hasItem(itemName)) { inventory[inventoryIndex] = findItem(itemName); inventory_amt[inventoryIndex] = 1; inventoryIndex++; } } public GameObject findItem(string itemName) { for (int i = 0; i < all_items.Length; i++) if (itemName == all_items[i].name) return all_items[i]; return null; } public GameObject[] getInventory() { return inventory; } public int[] getInventoryAmount() { return inventory_amt; } public int getInventoryIndex() { return inventoryIndex; } public void printInventory() { for (int i = 0; i < inventoryIndex; i++) { Debug.Log(inventory[i].name); } } public void useItem(int index) { if (inventory_amt[index-1] == 1) { index--; inventory_amt[index] = 0; game_manager_properties.set_jerry_health(game_manager_properties.get_jerry_health() + inventory[index].GetComponent<ItemAttr>().HP_restore); game_manager_properties.set_jerry_ap(game_manager_properties.get_jerry_ap() + inventory[index].GetComponent<ItemAttr>().AP_restore); if (game_manager_properties.get_jerry_health() > game_manager_properties.get_jerry_max_health()) game_manager_properties.set_jerry_health(game_manager_properties.get_jerry_max_health()); if (game_manager_properties.get_jerry_ap() > game_manager_properties.get_jerry_max_ap()) game_manager_properties.set_jerry_ap(game_manager_properties.get_jerry_max_ap()); setInventory(index); } else { int tmp = inventory_amt[index-1]-1; inventory_amt[index-1] = tmp; } } public void setInventory(int removeAt) { //////////////////////////////////////// // THIS IS DONE FOR THE INVENTORY AND // // THE INVENTORY AMOUNT // //////////////////////////////////////// int oldLength = getInventoryIndex(); int newIndex = 0; GameObject[] tempInventory = new GameObject[100]; int[] tempItemAmt = new int[100]; for (int i = 0; i < oldLength; i++) { if (i != removeAt) { tempInventory[newIndex] = inventory[i]; tempItemAmt[newIndex] = inventory_amt[i]; newIndex++; } } inventory = tempInventory; inventory_amt = tempItemAmt; inventoryIndex--; Debug.Log("INVENTORY INDEX IS NOW: " + inventoryIndex); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class debugMenuBehavior : MonoBehaviour { public bool status = false; public GameObject healthInput; InputField healthInput_text; public GameObject levelInput; InputField levelInput_text; public Text BACK; public GameObject cursor; GameObject cursor_debug; Vector3 cursorSpawnPos; public GameObject overworldUIManager; OverworldUIManager overworldUIManager_properties; //////////////////////// // GAME MANAGER STUFF // //////////////////////// Manager gameManager_properties = new Manager(); ////////////////////////// // *** BUTTON GUIDE *** // // 0 = HEALTH // // 1 = LEVEL // // 2 = BACK // ////////////////////////// int choiceIndex = 0; void Start() { //////////////////// // STATUS OF MENU // //////////////////// status = true; overworldUIManager = GameObject.Find("Overworld_UI"); //////////// // CURSOR // //////////// cursorSpawnPos = new Vector3(BACK.transform.position.x + 2f, BACK.transform.position.y); cursor_debug = Instantiate(cursor, cursorSpawnPos, Quaternion.identity); ////////////////////// // TEXT FIELD STUFF // ////////////////////// healthInput_text = healthInput.GetComponent<InputField>(); levelInput_text = levelInput.GetComponent<InputField>(); ///////////////////////// // OVERWORLD MANAGER // // UPDATE OVERWORLD UI // ///////////////////////// overworldUIManager_properties = overworldUIManager.GetComponent<OverworldUIManager>(); } // Update is called once per frame void Update() { ////////////////////////// // *** BUTTON GUIDE *** // // 0 = HEALTH // // 1 = LEVEL // // 2 = BACK // ////////////////////////// /* if (Input.GetKeyDown(KeyCode.DownArrow)) choiceIndex++; if (Input.GetKeyDown(KeyCode.UpArrow)) choiceIndex--; if (choiceIndex > 2) choiceIndex = 0; if (choiceIndex < 0) choiceIndex = 2; */ if (Input.GetKeyDown(KeyCode.Return) && choiceIndex == 0) { //Debug.Log("HEALTH: " + healthInput_text.text+ "/t" + "LEVEL: " + levelInput_text.text); gameManager_properties.set_jerry_health(System.Convert.ToInt32(healthInput_text.text)); gameManager_properties.set_jerry_level(System.Convert.ToInt32(levelInput_text.text)); overworldUIManager_properties.updateUIValues(); Destroy(this.gameObject); Destroy(cursor_debug); status = false; } } public bool getStatus() { return status; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class ExpManager : MonoBehaviour { private int total_experience; public void gainExp(int expGained) { total_experience += expGained; } public int calculateLevel() { return (int)Math.Round( Math.Sqrt(total_experience) *0.01, 2); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { // Start is called before the first frame update private float distance; private bool canMove = false; private Vector3 originalPosition; private Vector3 toPosition; private float speed = 5f; private float startTime; private float dist; void Start() { originalPosition = transform.position; } void Update() { if (canMove) { transform.position = Vector3.MoveTowards(transform.position, toPosition, Time.deltaTime*speed); } } public void destroyEnemy() { Destroy(this); } public void setMove(bool value) { canMove = value; } public void setToPosition(Vector3 value) { toPosition = value; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class OverworldUIManager : MonoBehaviour { public Text CharacterName; public Text HPValue; public Text LevelValue; public Text enemiesKilledValue; public GameObject character; Manager gameManager_properties = new Manager(); public void setUIValues() { JerryInfo character_properties = character.GetComponent<JerryInfo>(); CharacterName.text = character_properties.getName(); HPValue.text = character_properties.getHealth(); LevelValue.text = character_properties.getLevel(); enemiesKilledValue.text = character_properties.getEnemiesKilled().ToString(); } public void updateUIValues() { HPValue.text = gameManager_properties.get_jerry_health().ToString(); LevelValue.text = gameManager_properties.get_jerry_level().ToString(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class damNum : MonoBehaviour { // Start is called before the first frame update public GameObject enemy; public GameObject player; public GameObject battleMan; private GameObject myGameObject; private GameObject myDamNums; BattleManagerS damNumbers; Text damageNum; void Start() { damageNum = GetComponent<Text>(); damNumbers = battleMan.GetComponent<BattleManagerS>(); } // Update is called once per frame void Update() { damageDisplay(); } public void damageDisplay() { } public Text getDamNumIns() { return damageNum; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ItemAttr : MonoBehaviour { // Manager game_manager_properties = new Manager(); InventoryController inv_controller_properties; public GameObject manager; public string Name = "<NAME>"; public string Description = "Gross over cooked burger... But your crack head ass doesn't really care..."; public int HP_restore = 20; public int AP_restore = 0; public void item_attr() { } void Start() { inv_controller_properties = GetComponentInParent<InventoryController>(); //game_manager_properties = GetComponentInParent<Manager>(); } private void OnTriggerEnter2D(Collider2D collision) { //game_manager_properties.add_to_inventory(this.gameObject.name); inv_controller_properties.add_to_inventory(this.gameObject.name); Destroy(this.gameObject); } void Update() { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System; public class BattleManagerS : MonoBehaviour { // *** GAME MANAGER *** //public GameObject gameManager; private Manager gameManager_properties = new Manager(); // *** BATTLE STATES *** public enum BattleState { DECIDETURN, PLAYERPARTYTURNSTART, PLAYERPARTYTURN,PARTYSELECTACTION, PARTYSELECTENEMY, PARTYATTACKSTART, PARTYATTACKING,PARTYATTACKEND, PARTYSELECTITEM,ENEMYPARTYTURN, ENEMYSELECTACTION, ENEMYATTACKSTART,ENEMYATTACKEND,WON, LOST} public BattleState state; private float moveSpeed = 30f; // **** PLAYER AND ENEMY GAME OBJECTS **** // *** PLAYER *** public GameObject player; private BattleChar player_properties; // *** ENEMY *** public GameObject enemy; private SpanEnemies enemy_properties; private GameObject enemyChosen; private BattleEnemy enemyChosen_properties; private int enemyChosenIndex = 0; // *** TURN QUEUE *** private GameObject[] turnQueue = new GameObject[6]; private int turnQueueLength = 0; private int turnIndex; // *** UI OBJECTS *** // public GameObject UIController; UIController UI_properties; public GameObject damageDisplayer; DamageSpawner floating_damage_number; public GameObject victoryScreen; VictoryScreen victoryScreen_properties; public Canvas itemMenu; Canvas tmpItemMenu; Vector3 itemMenu_spawnV = new Vector3(3,0); ItemsMenuBehavior menuBehav; private Vector3 end_text_location; GameObject cursor; GameObject abilityList; // UI OBJECTS, BUT USED FOR THE LOCATION OF CERTAIN BUTTONS private Text playerName; private Vector3 attackButton; private Vector3 abilitiesButton; private Vector3 itemsButton; private Vector3[] buttonArr; private int buttonSelectIndex; // **** MOVEMENT VARIABLES **** // *** PLAYER/PARTY *** private Vector3 player_original_position; private Vector3 travel_to; private float player_initial_start_time; private float player_travel_length; // *** ENEMY *** private Vector3 enemy_attack_pos; private GameObject currentEnemy; BattleEnemy currentEnemy_properties; private Vector3 enemy_original_position; private float enemy_initial_start_time; private float enemy_travel_length; ///////////////////////////// // HOPEFULLY A TEMP VAR... // ///////////////////////////// bool displayDamage = true; ////////////////////////////////// // EXP GAINED THROUGHOUT BATTLE // ////////////////////////////////// private int battle_exp = 0; void Start() { //gameManager_properties.printInventory(); // *** INITIALIZING PLAYER OBJECT *** player_properties = player.GetComponent<BattleChar>(); // *** INITIALIZING ENEMY OBJECT[S]*** enemy_properties = enemy.GetComponent<SpanEnemies>(); // *** INITIALIZING UI OBJECTS[S]*** UI_properties = UIController.GetComponent<UIController>(); // *** THIS IS THE LOCATION OF THE PLAYER'S NAME... *** // *** WILL NEED SOMETHING FOR OTHER PARTY MEMBERS... *** //playerName = UIController.GetComponent<UIController>().charName; playerName = UI_properties.charName; // *** THIS IS USED THE MOVE FUNCTION *** // *** WILL PROBABLY NEED ONE FOR EACH PARTY MEMEBER *** player_original_position = player.transform.position; // *** THIS INDEX IS USED FOR WHAT BUTTON THE CURSOR SHOULD MOVE TO *** buttonSelectIndex = 0; // *** THIS FUNCTION WILL SPAWN BETWEEN 1-3 ENEMIES FOR THE PLAYER TO FIGHT *** enemy_properties.Spawn(); /// **** THIS INITIALIZES THE 'TURN QUEUE' BASED ON THE SPEED OF THE GAME OBJECT **** /* ***HOW THIS FUNCTION WORKS*** * initTurnQueue creates an array of game objects... * It sorts each object by their speed stat. * Fastest first, slowest last. */ initTurnQueue(); // *** THIS GETS THE LENGTH OF THE 'TURN QUEUE'... IT SHOULD PROBABLY BE IT'S OWN FUNCTION... *** for (int i = 0; i < turnQueue.Length; i++) { if (turnQueue[i] != null) { turnQueueLength++; } } // ***THIS CODE BLOCK FIGURES OUT WHO GOES FIRST*** if (turnQueue[0].name == "Final_Jerry_Battle") { state = BattleState.PLAYERPARTYTURNSTART; } else { state = BattleState.ENEMYPARTYTURN; } // ***THIS IS FOR THE DAMAGE NUMBERS THAT POP-UP*** floating_damage_number = damageDisplayer.GetComponent<DamageSpawner>(); } // *** MAIN GAME LOOP *** void Update() { turnManager(); } // JERRY NEEDS TO GO UP // ENEMY GO DOWN public void initTurnQueue() { //Place holder for when other party memebers are added int queueIndex = 0; int [] speedArray = new int[turnQueue.Length]; for (int i = 0; i < enemy_properties.getSize(); i++) { turnQueue[i] = enemy_properties.getEnemy(i); speedArray[i] = (int)enemy_properties.getEnemy(i).GetComponent<BattleEnemy>().getEnemySpeed(); queueIndex++; } turnQueue[queueIndex] = player; speedArray[queueIndex] = (int)player_properties.getPlayerSpeed(); for (int i = 0; i < queueIndex+1; i++) { for (int j = i; j < queueIndex; j++) { if (speedArray[i] < speedArray[j+1]) { int temp = speedArray[j+1]; GameObject tempG = turnQueue[j+1]; speedArray[j + 1] = speedArray[i]; turnQueue[j + 1] = turnQueue[i]; speedArray[i] = temp; turnQueue[i] = tempG; } } } } public void turnManager() { if (turnIndex >= turnQueueLength) { turnIndex = 0; } ///////////////// // VICTORY !!! // ///////////////// if (state == BattleState.WON) { ////////////////////////////////////////// // Configure the victory screen here... // ////////////////////////////////////////// if (Input.GetKeyUp(KeyCode.Return)) { player_properties.updateStats(true); SceneManager.LoadScene("SampleScene"); } Debug.Log(victoryScreen.transform.position); } /// *** THIS BLOCK WILL DECIDE WHO WILL GO NEXT... *** /// *** THIS WILL CHANGE LATER ONCE OTHER PARTY MEMBERS ARE ADDED *** if (state == BattleState.DECIDETURN) { if (turnQueue[turnIndex].name == "Final_Jerry_Battle") state = BattleState.PLAYERPARTYTURNSTART; else state = BattleState.ENEMYPARTYTURN; if (enemy_properties.getSize() < 1) { state = BattleState.WON; Vector3 victoryScreenPos = new Vector3(player.transform.position.x + 13f, player.transform.position.y - 4f); victoryScreen = Instantiate(victoryScreen, victoryScreenPos, Quaternion.identity); victoryScreen_properties = victoryScreen.GetComponent<VictoryScreen>(); configureVictoryScreen(); } } /*************************************************** *******************#PLAYER TURN#******************** ****************************************************/ else if (state == BattleState.PLAYERPARTYTURNSTART) { Vector3 playerNamePos = new Vector3(playerName.transform.position.x + 3f, playerName.transform.position.y, 0f); cursor = UI_properties.insCursor(playerNamePos); state = BattleState.PLAYERPARTYTURN; } else if (state == BattleState.PLAYERPARTYTURN) { if (Input.GetKeyUp(KeyCode.Return)) { Vector3 abilityListPos = new Vector3(playerName.transform.position.x + 5.8f, playerName.transform.position.y - 1.38f, 0f); abilityList = UI_properties.insAbilityMenu(abilityListPos); cursor.transform.position = initButtons()[0]; state = BattleState.PARTYSELECTACTION; buttonArr = initButtons(); } } else if (state == BattleState.PARTYSELECTACTION) { changeActionSelection(cursor, buttonArr, initEnemyArray()[0]); } else if (state == BattleState.PARTYSELECTENEMY) { changeEnemySelection(cursor, initEnemyArray(), BattleState.PARTYATTACKSTART); player_initial_start_time = Time.time; player_travel_length = Vector3.Distance(player.transform.position, initEnemyArray()[buttonSelectIndex]); } else if (state == BattleState.PARTYATTACKSTART) { // ***PLAYER MOVES TOWARDS THE ENEMY*** move(player, player_original_position, travel_to, player_initial_start_time, player_travel_length); player_properties.setAllAnimFalseBut("walk_right"); if (player.transform.position == travel_to) { player_properties.setAllAnimFalseBut("attack"); state = BattleState.PARTYATTACKING; enemyChosen_properties.takeDamage(player_properties.getAttack()); } } else if (state == BattleState.PARTYATTACKING) { if (Math.Round(player_properties.getNormTime(), 2) > 0.55 && displayDamage) { floating_damage_number.insDam(enemyChosen, enemyChosen_properties.getDamageTaken()); displayDamage = false; if (enemyChosen_properties.getHealth() <= 0) { killEnemy(enemyChosen); } } if (!player_properties.getAnimState()) { state = BattleState.PARTYATTACKEND; player_initial_start_time = Time.time; player_properties.setAllAnimFalseBut("walk_left"); } } else if (state == BattleState.PARTYATTACKEND) { /////////////////////////////////////// // I HATE THAT I HAVE TO USE THIS... // /////////////////////////////////////// displayDamage = true; // ***PLAYER MOVES BACK TO ORIGINAL SPOT*** // move(player, travel_to, player_original_position, player_initial_start_time, player_travel_length); if (player.transform.position == player_original_position) { player_properties.setAllAnimFalseBut("idle"); state = BattleState.DECIDETURN; turnIndex++; } } else if (state == BattleState.PARTYSELECTITEM) { if (Input.GetKeyUp(KeyCode.Return)) { state = BattleState.DECIDETURN; Destroy(cursor); Destroy(abilityList); turnIndex++; } } /*************************************************** **************************************************** ****************************************************/ /*************************************************** *******************#ENEMY TURN#******************** ***************************************************/ else if (state == BattleState.ENEMYPARTYTURN) { currentEnemy = turnQueue[turnIndex]; currentEnemy_properties = currentEnemy.GetComponent<BattleEnemy>(); enemy_original_position = currentEnemy.transform.position; enemy_travel_length = Vector3.Distance(currentEnemy.transform.position, player.transform.position); state = BattleState.ENEMYSELECTACTION; } else if (state == BattleState.ENEMYSELECTACTION) { // **I'll put enemy abilites here later... but for now...** state = BattleState.ENEMYATTACKSTART; Vector3 modPlayerPos = player.transform.position; enemy_attack_pos = new Vector3(modPlayerPos.x + 0.2f, modPlayerPos.y - 2.8f); enemy_initial_start_time = Time.time; } else if (state == BattleState.ENEMYATTACKSTART) { move(currentEnemy, enemy_original_position, enemy_attack_pos, enemy_initial_start_time, enemy_travel_length); if (currentEnemy.transform.position == enemy_attack_pos) { player_properties.takeDamage(currentEnemy_properties.getAttack()); floating_damage_number.insDam(player, player_properties.getDamageTaken()); state = BattleState.ENEMYATTACKEND; enemy_initial_start_time = Time.time; } } else if (state == BattleState.ENEMYATTACKEND) { move(currentEnemy, enemy_attack_pos, enemy_original_position, enemy_initial_start_time, enemy_travel_length); if (currentEnemy.transform.position == enemy_original_position) { state = BattleState.DECIDETURN; turnIndex++; } } /*************************************************** **************************************************** ****************************************************/ } private void move(GameObject mover, Vector3 from, Vector3 to, float startTime, float distance) { /// THIS FUNCTION WILL MOVE ONE OBJECT TO ANOTHER... /// I USED THIS TO 'STREAMLINE' USING LERP float distanceTravled = (Time.time - startTime) * moveSpeed; mover.transform.position = Vector3.Lerp(from, to, distanceTravled / distance); } private void changeActionSelection(GameObject cursor, Vector3[] positionArr, Vector3 enemyLocation) { /// THIS FUNCTION IS FOR CHANGING THE POSITION OF THE CURSOR THAT SELECTS THE PLAYER'S ACTION... /// THE CURSOR IS JUST FOR SHOW, BUT THE UP AND DOWN ARROWS CHANGE THE ACTION THAT IS SELECTED. //// ** BUTTON SELECT INDEX GUIDE ** // ATTACK = 0 // ABILITY = 1 // ITEMS = 2 //// ******************************* /// MOVE CURSOR UP OR DOWN ////// if (Input.GetKeyUp(KeyCode.UpArrow)) { buttonSelectIndex--; if (buttonSelectIndex < 0) buttonSelectIndex = positionArr.Length - 1; cursor.transform.position = positionArr[buttonSelectIndex]; } else if (Input.GetKeyUp(KeyCode.DownArrow)) { buttonSelectIndex++; if (buttonSelectIndex == positionArr.Length) buttonSelectIndex = 0; cursor.transform.position = positionArr[buttonSelectIndex]; } //////////////////////////////// /// ONCE ENTER IS PRESSED THE CURSOR WILL CHANGE POSITION //////////// // ATTACK // //////////// else if (Input.GetKeyUp(KeyCode.Return) && buttonSelectIndex == 0) { state = BattleState.PARTYSELECTENEMY; cursor.transform.position = enemyLocation; buttonSelectIndex = 0; } ////////// // ITEM // ////////// else if (Input.GetKeyUp(KeyCode.Return) && buttonSelectIndex == 2) { state = BattleState.PARTYSELECTITEM; tmpItemMenu = Instantiate(itemMenu, itemMenu_spawnV, Quaternion.identity); tmpItemMenu.GetComponent<Canvas>().worldCamera = Camera.main; tmpItemMenu.GetComponent<Canvas>().sortingLayerName = "BattleItemMenuLayer"; tmpItemMenu.GetComponent<Canvas>().planeDistance = 10f; } ///////////////////////////////////////////////////////// } private void changeEnemySelection(GameObject cursor, Vector3[] positionArr, BattleState stateToChangeTo) { /// THIS FUNCTION IS FOR CHANGING THE POSITION OF THE CURSOR THAT SELECTS THE ENEMY TO ATTACK... /// THE CURSOR IS JUST FOR SHOW, BUT THE UP AND DOWN ARROWS CHANGE THE ACTION THAT IS SELECTED. /// MOVE CURSOR UP OR DOWN ////// if (Input.GetKeyUp(KeyCode.UpArrow)) { buttonSelectIndex--; if (buttonSelectIndex < 0) buttonSelectIndex = positionArr.Length - 1; cursor.transform.position = positionArr[buttonSelectIndex]; } else if (Input.GetKeyUp(KeyCode.DownArrow)) { buttonSelectIndex++; if (buttonSelectIndex == positionArr.Length) buttonSelectIndex = 0; cursor.transform.position = positionArr[buttonSelectIndex]; } //////////////////////////////////////////////////////// // ONCE ENTER IS PRESSED THE CURSOR WILL BE DESTROYED // // AND THE ENEMY WILL BE SELECTED // //////////////////////////////////////////////////////// else if (Input.GetKeyUp(KeyCode.Return)) { state = stateToChangeTo; enemyChosen = enemy.GetComponent<SpanEnemies>().getEnemy(buttonSelectIndex); enemyChosen_properties = enemyChosen.GetComponent<BattleEnemy>(); travel_to = enemyChosen.transform.position; travel_to = new Vector3(travel_to.x, travel_to.y+2.5f); enemyChosenIndex = buttonSelectIndex; buttonSelectIndex = 0; Destroy(cursor); Destroy(abilityList); } ///////////////////////////////////////////////////////// } private Vector3[] initButtons() { // *** POORLY NAMED FUNCTION... *** // *** THIS RETURNS AN ARRAY OF VECTOR3's FOR THE CURSOR TO POINT TO *** // ** THESE ARE THE ACTUAL BUTTONS AND THEIR 'UNMODIFIED' POSITIONS... ** attackButton = abilityList.transform.GetChild(0).GetChild(0).position; abilitiesButton = abilityList.transform.GetChild(0).GetChild(1).position; itemsButton = abilityList.transform.GetChild(0).GetChild(2).position; // ** THESE ARE 'MODIFIED' POSITIONS BECAUSE THE ORIGINAL POSITIONS ARE KINDA WONKY... ** Vector3 modAttackButton = new Vector3 (attackButton.x+2f, attackButton.y, attackButton.z); Vector3 modAbilitiesButton = new Vector3(abilitiesButton.x+2f, abilitiesButton.y, abilitiesButton.z); Vector3 modItemsButton = new Vector3(itemsButton.x+2f, itemsButton.y, itemsButton.z); Vector3 [] positionArr = new Vector3[] {modAttackButton, modAbilitiesButton, modItemsButton}; return positionArr; } private Vector3[] initEnemyArray () { // ***ESSENTIALLY DOES THE SAME THING AS ABOVE EXCEPT WITH ENEMIES*** int enemy_amount = enemy.GetComponent<SpanEnemies>().getSize(); SpanEnemies enemy_x = enemy.GetComponent<SpanEnemies>(); Vector3[] enemyPosArr = new Vector3[enemy_amount]; for (int i = 0; i < enemy_amount; i++) { enemyPosArr[i] = enemy_x.getEnemy(i).transform.position; } return enemyPosArr; } public void killEnemy(GameObject enemyToKill) { SpanEnemies enemyToKill_properties = enemyToKill.GetComponent<SpanEnemies>(); int enemyToKill_speed = (int)enemy_properties.getEnemy(enemyChosenIndex).GetComponent<BattleEnemy>().getEnemySpeed(); ///////////// // Get EXP // ///////////// int enemyToKill_exp = enemy_properties.getEnemy(enemyChosenIndex).GetComponent<BattleEnemy>().getExpDroped(); player_properties.gainExp(enemyToKill_exp); battle_exp += enemyToKill_exp; /////////////////////////////////////// // Remove enemy and reset turn queue // /////////////////////////////////////// enemy_properties.removeEnemy(enemyChosenIndex); turnQueue = new GameObject[enemy_properties.getSize()+1]; turnQueueLength--; ///////////////////////////////////////////////////////////////// // This is done if the enemy's speed is high than the player's // ///////////////////////////////////////////////////////////////// if (enemyToKill_speed > player_properties.getPlayerSpeed()) turnIndex--; initTurnQueue(); Destroy(enemyToKill); } private void configureVictoryScreen() { ///////////////////////////////////////// // Fill in text for who is leveling up // ///////////////////////////////////////// victoryScreen_properties.set_exp_text("Jerry: "); victoryScreen_properties.set_exp_text_int(battle_exp); //////////////////////////////// // If the player levels up... // //////////////////////////////// if (player_properties.level < player_properties.calculateLevel() && player_properties.level >= 0) { victoryScreen_properties.set_lvl_text(player_properties.level, player_properties.calculateLevel()); player_properties.level = player_properties.calculateLevel() + 1; gameManager_properties.jerry_level_up(); } /////////////////////////////////////////////////////////////////////////// // Spawn the cursor to the end button so player can go back to overworld // /////////////////////////////////////////////////////////////////////////// end_text_location = victoryScreen.transform.GetChild(0).transform.GetChild(4).transform.position; end_text_location = new Vector3(end_text_location.x + 1f, end_text_location.y); cursor = UI_properties.insCursor(end_text_location); } ///////////////////////////////////////////////////////////////// // THIS FUNCTION WILL SHIFT VECTORS (SINCE IT HAPPENS SO MUCH) // ///////////////////////////////////////////////////////////////// public Vector3 vectorShift(Vector3 v, float x, float y, float z = 0) { return new Vector3(v.x + x, v.y + y, v.z + z); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnEnemyOverworld : MonoBehaviour { public GameObject spawne; public Enemy[] enemies; public Vector2 levelBorderPos; public Vector2 levelBorderNeg; public int maxEnemyNum; public int enemiesToSpawn; public GameObject playerChar; private Vector3 playerPosition; void Start() { enemiesToSpawn = (int)Random.Range(1, maxEnemyNum); spawnOverworldEnemies(enemiesToSpawn); } // Update is called once per frame void Update() { playerPosition = playerChar.transform.position; for (int i = 0; i < enemies.Length; i ++) { if (Vector2.Distance(playerPosition, enemies[i].transform.position) < 15) { enemies[i].setMove(true); enemies[i].setToPosition(playerPosition); } else { enemies[i].setMove(false); } } } public void spawnOverworldEnemies (int enemySpawnLimit) { enemies = new Enemy[enemySpawnLimit]; for (int i = 0; i < enemySpawnLimit; i++) { ///////////////////////////////// // Generate random coordinates // ///////////////////////////////// float randomXCoord = Random.Range(levelBorderNeg.x, levelBorderPos.x); float randomYCoord = Random.Range(levelBorderNeg.y, levelBorderPos.y); Vector2 spawnLocation = new Vector2(randomXCoord, randomYCoord); /////////////////////////////////////////////////////// // Keep track of the newly spawned overworld enemies // /////////////////////////////////////////////////////// GameObject spawnedEnemy; spawnedEnemy = Instantiate(spawne, spawnLocation, Quaternion.identity); enemies[i] = spawnedEnemy.GetComponent<Enemy>(); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MenuController : MonoBehaviour { //////////////////// // MAIN MENU VARS // //////////////////// public GameObject menu; MenuBehaviour menu_properties; Canvas menuCanvas; bool isActive = false; ///////////////////// // STATS MENU VARS // ///////////////////// public GameObject stats_menu; GameObject stats_menu_tmp; statsMenuBehavior stats_menu_properties; statsMenuBehavior stats_menu_tmp_properties; Canvas stats_menuCanvas; ///////////////////// // ITEMS MENU VARS // ///////////////////// public GameObject items_menu; GameObject items_menu_tmp; ItemsMenuBehavior items_menu_properties; ItemsMenuBehavior items_menu_tmp_properties; Canvas items_menuCanvas; ///////////////////// // DEBUG MENU VARS // ///////////////////// public GameObject debug_menu; GameObject debug_menu_tmp; debugMenuBehavior debug_menu_properties; debugMenuBehavior debug_menu_tmp_properties; Canvas debug_menuCanvas; public enum MenuControl_States { MAIN, STAT, DEBUG, ITEMS} public MenuControl_States mainState; public GameObject player; void Start() { menu_properties = menu.GetComponent<MenuBehaviour>(); menu.SetActive(false); } // Update is called once per frame void Update() { if ( (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))) { if (Input.GetKeyDown(KeyCode.M) && isActive == false) { mainState = MenuControl_States.MAIN; player.SetActive(false); isActive = true; setUpMenu(); menu_properties.getChoicePos(); menu_properties.setUpCursor(); } } if (Input.GetKeyDown(KeyCode.Escape) && isActive == true) { menu.SetActive(false); player.SetActive(true); isActive = false; menu_properties.destroyCursor(); } } ///////////////////////////////////////////////////////////// // SET UP MENU SO IT ATTACHES ITSELF TO THE MAIN CAMERA... // // AND SOME OTHER CAMERA STUFF // ///////////////////////////////////////////////////////////// public void setUpMenu() { menuCanvas = menu.GetComponent<Canvas>(); menuCanvas.renderMode = RenderMode.ScreenSpaceCamera; menuCanvas.worldCamera = Camera.main; menuCanvas.planeDistance = 10f; menuCanvas.sortingLayerName = "Tilestuff"; menuCanvas.sortingOrder = 9; menu.SetActive(true); } /////////////////////////// // SETTING UP STATS MENU // /////////////////////////// public void setUpMenu_stats() { mainState = MenuControl_States.STAT; stats_menu_tmp = Instantiate(stats_menu); stats_menu_tmp_properties = stats_menu_tmp.GetComponent<statsMenuBehavior>(); setStatus_stats(); stats_menuCanvas = stats_menu_tmp.GetComponent<Canvas>(); stats_menuCanvas.renderMode = RenderMode.ScreenSpaceCamera; stats_menuCanvas.worldCamera = Camera.main; stats_menuCanvas.planeDistance = 10f; stats_menuCanvas.sortingLayerName = "statMenuLayer"; stats_menuCanvas.sortingOrder = 1; } public bool getStatus_stats() { return stats_menu_tmp_properties.getStatus(); } public void setStatus_stats() { stats_menu_tmp_properties.status = true; } /////////////////////////// // SETTING UP DEBUG MENU // /////////////////////////// public void setUpMenu_debug() { mainState = MenuControl_States.DEBUG; debug_menu_tmp = Instantiate(debug_menu); debug_menu_tmp_properties = debug_menu_tmp.GetComponent<debugMenuBehavior>(); setStatus_debug(); debug_menuCanvas = debug_menu_tmp.GetComponent<Canvas>(); debug_menuCanvas.renderMode = RenderMode.ScreenSpaceCamera; debug_menuCanvas.worldCamera = Camera.main; debug_menuCanvas.planeDistance = 10f; debug_menuCanvas.sortingLayerName = "statMenuLayer"; debug_menuCanvas.sortingOrder = 1; } public void setStatus_debug() { debug_menu_tmp_properties.status = true; } public bool getStatus_debug() { return debug_menu_tmp_properties.getStatus(); } /////////////////////////// // SETTING UP ITEMS MENU // /////////////////////////// public void setUpMenu_items() { mainState = MenuControl_States.ITEMS; items_menu_tmp = Instantiate(items_menu); items_menu_tmp_properties = items_menu_tmp.GetComponent<ItemsMenuBehavior>(); setStatus_items(); items_menuCanvas = items_menu_tmp.GetComponent<Canvas>(); items_menuCanvas.renderMode = RenderMode.ScreenSpaceCamera; items_menuCanvas.worldCamera = Camera.main; items_menuCanvas.planeDistance = 10f; items_menuCanvas.sortingLayerName = "statMenuLayer"; items_menuCanvas.sortingOrder = 1; } public void setStatus_items() { items_menu_tmp_properties.status = true; } public bool getStatus_items() { return items_menu_tmp_properties.getStatus(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ITEM : MonoBehaviour { ////////////////////////////// // ATTRIBUTES OF EVERY ITEM // ////////////////////////////// public string Name; public string Description; public int HP_restore; public int AP_restore; } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Manager { //////////////////////////// // STATIC STATS FOR JERRY // //////////////////////////// /********************************** * THESE VALUES ARE JUST DEFAULTS * **********************************/ public static int jerry_health = 100; private static int jerry_max_health = 100; public static int jerry_attack = 25; public static int jerry_ap = 50; public static int jerry_max_ap = 50; public static int jerry_defense = 10; public static int jerry_speed = 50; public static int jerry_level = 1; public static int jerry_exp = 0; public static int enemies_killed = 0; public static Vector3 last_pos = new Vector3(-13.35f, -1.34f); ///////////////////////// // INVENTORY AND ITEMS // ///////////////////////// //public static GameObject[] inventory = new GameObject[100]; //public static int inventoryIndex = 0; //public GameObject[] all_items; ///////////////////////////////// // SET/GET THESE STATS (JERRY) // ///////////////////////////////// public void set_jerry_health(int value) { jerry_health = value; } public int get_jerry_health() { return jerry_health; } public void set_jerry_max_health(int value) { jerry_max_health = value; } public int get_jerry_max_health() { return jerry_max_health; } public void set_jerry_attack(int value) { jerry_attack = value; } public int get_jerry_attack() { return jerry_attack; } public void set_jerry_ap(int value) { jerry_ap = value; } public int get_jerry_ap() { return jerry_ap; } public int get_jerry_max_ap() { return jerry_max_ap; } public void set_jerry_defense(int value) { jerry_defense = value; } public int get_jerry_defense() { return jerry_defense; } public void set_jerry_speed(int value) { jerry_speed = value; } public int get_jerry_speed() { return jerry_speed; } public void set_jerry_level(int value) { jerry_level = value; } public int get_jerry_level() { return jerry_level; } public void set_jerry_exp(int value) { jerry_exp = value; } public int get_jerry_exp() { return jerry_exp; } public void set_jerry_last_pos(Vector3 value) { last_pos = value; } public Vector3 get_jerry_last_pos() { return last_pos; } public void jerry_level_up() { jerry_max_health += 20; jerry_attack += 3; jerry_max_ap += 5; jerry_ap += 5; jerry_defense += 2; jerry_speed += 4; } public void set_enemies_killed() { enemies_killed++; } public int get_enemies_killed() { return enemies_killed; } ///////////////////////// // INVENTORY FUNCTIONS // ///////////////////////// ///////////////////////////////////////////////// // *** THESE FUNCTIONS NEED TO BE MOVED... *** // // *** UNITY KEEPS BITCHING AT ME... *** // ///////////////////////////////////////////////// /* public void add_to_inventory(string itemName) { inventory[inventoryIndex] = findItem(itemName); inventoryIndex++; } public GameObject findItem(string itemName) { for (int i = 0; i < all_items.Length; i++) { if (itemName == all_items[i].name) { return all_items[i]; } } return null; } public GameObject[] getInventory() { return inventory; } public int getInventoryIndex() { return inventoryIndex; } public void printInventory() { for (int i = 0; i < inventoryIndex; i++) { Debug.Log(inventory[i].name); } } public void useItem(int index) { index--; set_jerry_health(get_jerry_health()+inventory[index].GetComponent<ItemAttr>().HP_restore); set_jerry_ap(get_jerry_ap() + inventory[index].GetComponent<ItemAttr>().AP_restore); if (get_jerry_health() > get_jerry_max_health()) set_jerry_health(get_jerry_max_health()); if (get_jerry_ap() > get_jerry_max_ap()) set_jerry_ap(get_jerry_max_ap()); setInventory(index); } public void setInventory(int removeAt) { int oldLength = getInventoryIndex(); int newIndex = 0; GameObject [] tempInventory = new GameObject [100]; for (int i = 0; i < oldLength; i++) { if (i != removeAt) { tempInventory[newIndex] = inventory[i]; newIndex++; } } inventory = tempInventory; inventoryIndex--; } */ } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class LoadNewArea : MonoBehaviour { private GameObject Enemy; // Start is called before the first frame update private Manager gameManager_properties = new Manager(); void Start() { } // Update is called once per frame void Update() { } void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.name == "Final_Jerry_Overworld") { //Debug.Log(other.transform.position); gameManager_properties.set_jerry_last_pos(other.transform.position); SceneManager.LoadScene("BattleScene"); Destroy(FindObjectOfType<GameObject>(), 0.1f); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DamageBehavior : MonoBehaviour { // Start is called before the first frame update public float timeToAppear; public float floatSpeed; private float timer; void Start() { timer = 0f; } // Update is called once per frame void Update() { if (timer >= timeToAppear) { Destroy(gameObject); } timer += Time.deltaTime; floatUp(); } public void floatUp() { transform.Translate(new Vector2(0f,floatSpeed *Time.deltaTime)); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class BattleEnemy : MonoBehaviour { // ***ENEMY STATS*** // ****Base**** public int attack = 15; public int health = 75; public int defense = 10; public float speed = 35; private int damageTaken; // ***************** ///////////////////// // EXP DROP AMOUNT // ///////////////////// private int exp_drop = 5; void Start() { health = 25; } public void setHealth(int damage) { health -= damage; } public void takeDamage(int damage) { damageTaken = damage - defense; if (damageTaken < 0) { damageTaken = 0; } health -= damageTaken; } public int getHealth() { return health; } public int getDamageTaken() { return damageTaken; } public int getAttack() { return attack; } public float getEnemySpeed() { return speed; } public int getExpDroped() { return exp_drop; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class VictoryScreen : MonoBehaviour { public Text exp_text; public Text exp_text_int; public Text lvl_text; public GameObject end_text; public void set_exp_text(string exp) { exp_text.text = exp; } public void set_exp_text_int(int exp) { exp_text_int.text = exp.ToString() + " EXP"; } public void set_lvl_text(int lvl_old, int lvl_new) { lvl_text.text = "LVL UP!!! "+ lvl_old.ToString() + " -> " + lvl_new.ToString(); } public Vector3 get_end_text_location() { return new Vector3(end_text.transform.position.x, end_text.transform.position.y); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraMovement : MonoBehaviour { public GameObject follow; private float xFollow; private float yFollow; float height; float width; void Start() { //////////////////////////////////////////// // GET THE HEIGHT AND WIDTH OF THE CAMERA // //////////////////////////////////////////// Camera cam = Camera.main; height =2f* cam.orthographicSize; width = cam.aspect * height; } void Update() { ///////////////////////////////////////////////////////////////////////// // FOLLOW THE PLAYER AND MAKE SURE THE CAMERA DOESN'T GO OUT OF BOUNDS // ///////////////////////////////////////////////////////////////////////// if ( (follow.transform.position.x + width/2) < 54f && (follow.transform.position.x - width/2) > -40f) { xFollow = follow.transform.position.x; } if ( (follow.transform.position.y + height / 2) < 31f && (follow.transform.position.y - height / 2) > -53f) { yFollow = follow.transform.position.y; } transform.position = new Vector3(xFollow, yFollow, -10); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class statsMenuBehavior : MonoBehaviour { public Text HP_VALUE; public Text MAX_HP_VALUE; public Text AP_VALUE; public Text ATK_VALUE; public Text DEF_VALUE; public Text SPD_VALUE; public Text EXP_VALUE; public Text LEVEL_VALUE; public Text BACK; public GameObject cursor; GameObject cursor_stat; Vector3 cursorSpawnPos; public bool status = false; //////////////////////// // GAME MANAGER STUFF // //////////////////////// Manager gameManager_properties = new Manager(); ////////////////////////// // *** BUTTON GUIDE *** // // 0 = BACK // ////////////////////////// public int choice_index = 0; void Start() { status = true; cursorSpawnPos = new Vector3(BACK.transform.position.x + 2f, BACK.transform.position.y); cursor_stat = Instantiate(cursor, cursorSpawnPos, Quaternion.identity); getValues(); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Return)) { Destroy(this.gameObject); Destroy(cursor_stat); status = false; } } public void getValues() { HP_VALUE.text = gameManager_properties.get_jerry_health().ToString(); MAX_HP_VALUE.text = gameManager_properties.get_jerry_max_health().ToString(); AP_VALUE.text = gameManager_properties.get_jerry_ap().ToString(); ATK_VALUE.text = gameManager_properties.get_jerry_attack().ToString(); DEF_VALUE.text = gameManager_properties.get_jerry_defense().ToString(); SPD_VALUE.text = gameManager_properties.get_jerry_speed().ToString(); EXP_VALUE.text = gameManager_properties.get_jerry_exp().ToString(); LEVEL_VALUE.text = gameManager_properties.get_jerry_level().ToString(); } public bool getStatus() { return status; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Character : MonoBehaviour { public int health; public int attack; public int defense; public int level; public int total_exp; public float speed; public string characterName; } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIController : MonoBehaviour { // *** THIS IS FOR THE CHARACTER'S NAME ON THE BATTLE SCREEN *** public Text charName; // *** THIS THE POINTER/CURSOR/GLOVE THING YOU SEE ON THE SCREEN *** public GameObject cursor; // *** THIS IS THE ABILITY MENU THAT POPS UP AFTER YOU PRESS ENTER WHEN IT IS THE PLAYER'S TURN *** public GameObject abilityMenuJerry; /*EVERY FUNCTION... **All of these functions are to initialize and destroy the cursor and ability menu objects. **I would have put this in 'BattleManagerS' but UNITY is weird about destroying stuff. */ public GameObject insCursor(Vector3 position) { GameObject newCursor = Instantiate(cursor, position, Quaternion.identity); return newCursor; } public GameObject insAbilityMenu(Vector3 position) { GameObject abilityMenu = Instantiate(abilityMenuJerry, position, Quaternion.identity); return abilityMenu; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class OverworldManager : MonoBehaviour { // Start is called before the first frame update\ public GameObject playerChar; public GameObject enemies; SpawnEnemyOverworld enemies_properties; float startTime; void Start() { enemies_properties = enemies.GetComponent<SpawnEnemyOverworld>(); } // Update is called once per frame void Update() { //////////////////////////////////////////////////////////////////// // Check to see if the distance from any enemy to the player < 15 // //////////////////////////////////////////////////////////////////// } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MenuBehaviour : MonoBehaviour { public GameObject menuController; MenuController menuController_properties; public enum Menu_States {CHOOSE, STATS, ITEMS, SAVE, DEBUG} public Menu_States state; public GameObject cursor; GameObject myCursor; public Text stats; public Text items; public Text save; public Text debug; Vector3[] choicePos; int choiceIndex = 0; void Start() { menuController_properties = menuController.GetComponent<MenuController>(); state = Menu_States.CHOOSE; } void Update() { //////////////////////// // ***CHOICE GUIDE*** // // 0 = stats // // 1 = items // // 2 = save // // 3 = debug // //////////////////////// if (state == Menu_States.CHOOSE) { if (Input.GetKeyDown(KeyCode.UpArrow)) { choiceIndex--; //////////////////////////// // OBLIGATORY INDEX CHECK // //////////////////////////// if (choiceIndex < 0) choiceIndex = 3; myCursor.transform.position = choicePos[choiceIndex]; } if (Input.GetKeyUp(KeyCode.DownArrow)) { choiceIndex++; //////////////////////////// // OBLIGATORY INDEX CHECK // //////////////////////////// if (choiceIndex > 3) choiceIndex = 0; myCursor.transform.position = choicePos[choiceIndex]; } if (Input.GetKeyDown(KeyCode.Return) && state == Menu_States.CHOOSE) { if (choiceIndex == 0) { menuController_properties.setUpMenu_stats(); state = Menu_States.STATS; } if (choiceIndex == 1) { menuController_properties.setUpMenu_items(); state = Menu_States.ITEMS; } if (choiceIndex == 2) state = Menu_States.SAVE; if (choiceIndex == 3) { menuController_properties.setUpMenu_debug(); state = Menu_States.DEBUG; } //choiceIndex = 0; } } if (state == Menu_States.STATS) { myCursor.SetActive(false); if (menuController_properties.getStatus_stats() == false) { myCursor.SetActive(true); state = Menu_States.CHOOSE; } } else if (state == Menu_States.DEBUG) { myCursor.SetActive(false); if (menuController_properties.getStatus_debug() == false) { myCursor.SetActive(true); state = Menu_States.CHOOSE; } } else if (state == Menu_States.ITEMS) { myCursor.SetActive(false); if (menuController_properties.getStatus_items() == false) { myCursor.SetActive(true); state = Menu_States.CHOOSE; } } } public void setUpCursor() { Vector3 cursorSpawnPos = new Vector3(stats.transform.position.x+2f, stats.transform.position.y); myCursor = Instantiate(cursor); myCursor.transform.SetParent(this.transform); myCursor.transform.position = cursorSpawnPos; } public void destroyCursor() { Destroy(myCursor); } public void getChoicePos() { Vector3 statsPos = new Vector3(stats.transform.position.x + 2f, stats.transform.position.y); Vector3 itemsPos = new Vector3(items.transform.position.x + 2f, items.transform.position.y); Vector3 savePos = new Vector3(save.transform.position.x + 2f, save.transform.position.y); Vector3 debugPos = new Vector3(debug.transform.position.x + 2f, debug.transform.position.y); Vector3 [] posArr = { statsPos, itemsPos, savePos, debugPos }; choicePos = posArr; } void statsMenu() { } void itemsMenu() { } void debugMenu() { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MountainView_item : ITEM { public void item_attr() { Name = "Mountain View"; Description = "Knock off mountain dew... You can't even get Mello Yellow"; HP_restore = 0; AP_restore = 10; } void Start() { item_attr(); } void Update() { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ItemsMenuBehavior : MonoBehaviour { public bool status = false; int childNum; //////////// // CURSOR // //////////// public GameObject cursor; GameObject cursor_items; Vector3 cursorSpawnPos; //////////////// // ITEM ATTRS // //////////////// //Manager game_manager_properties = new Manager(); InventoryController inv_controller_properties; int[] inv_amt; ///////////////// // TEXT FIELDS // ///////////////// public Text itemName; public Text itemDescriptions; public Text itemAttrs_hp; public Text itemAttrs_ap; public Text itemAmt_x; public Text itemAmt; public GameObject itemsGrid; Vector3[] fourCorners = new Vector3[4]; public GameObject BACK; //////////////////////// // OVERWORLD UI STUFF // //////////////////////// public GameObject overworldUI; private OverworldUIManager overworldUI_properties; ////////////////// // CHOICE INDEX // ////////////////// int choiceIndex = 0; int gridLength = 12; int rows = 3; int column = 4; //////////////////////// // ***CHOICE GUIDE*** // // 0 = back // // 1-12 = items // //////////////////////// Transform itemGrid; void Start() { /////////////////////////////////////// // GET THE INVENTORY DATA STRUCTURES // /////////////////////////////////////// inv_controller_properties = GameObject.Find("ITEM_MANAGER").GetComponent<InventoryController>(); inv_amt = inv_controller_properties.getInventoryAmount(); try { overworldUI_properties = GameObject.Find("Overworld_UI").GetComponent<OverworldUIManager>(); } catch { } status = true; ///////////////// // CURSOR VARS // ///////////////// cursorSpawnPos = new Vector3(BACK.transform.position.x + 2f, BACK.transform.position.y); cursor_items = Instantiate(cursor, cursorSpawnPos, Quaternion.identity); //////////////////////////////////////////////////// // 'ITEM_GRID' SHOULD ALWAYS BE THE LAST CHILD... // //////////////////////////////////////////////////// childNum = this.gameObject.transform.childCount; itemGrid = this.gameObject.transform.GetChild(childNum-1); displayInventory(); } void Update() { ///////////////////// // SELECTING ITEMS // ///////////////////// if (choiceIndex > 0 && choiceIndex <= inv_controller_properties.getInventoryIndex() && inv_controller_properties.getInventoryIndex() > 0) { if (Input.GetKeyUp(KeyCode.LeftArrow)) { choiceIndex--; if (choiceIndex == (1 - 1) || choiceIndex == (5 - 1) || choiceIndex == (9 - 1)) { if (getRow(choiceIndex + 1) == 0) { if (inv_controller_properties.getInventoryIndex() < 4) { choiceIndex = inv_controller_properties.getInventoryIndex(); } else { choiceIndex = 4; } } else if (getRow(choiceIndex + 1) == 1) { if (inv_controller_properties.getInventoryIndex() < 8) { choiceIndex = inv_controller_properties.getInventoryIndex(); } else { choiceIndex = 8; } } else if (getRow(choiceIndex + 1) == 2) { if (inv_controller_properties.getInventoryIndex() < 12) { choiceIndex = inv_controller_properties.getInventoryIndex(); } else { choiceIndex = 12; } } } } else if (Input.GetKeyUp(KeyCode.RightArrow)) { choiceIndex++; if (choiceIndex == 5 || choiceIndex == 9 || choiceIndex == 13 || choiceIndex == inv_controller_properties.getInventoryIndex() + 1) { if (getRow(choiceIndex - 1) == 0) { choiceIndex = 1; } else if (getRow(choiceIndex - 1) == 1) { choiceIndex = 5; } else { choiceIndex = 4; } } } else if (Input.GetKeyUp(KeyCode.UpArrow)) { choiceIndex -= 4; if (choiceIndex == (1 - 4)) { choiceIndex = 0; } else if (choiceIndex == (2 - 4) || choiceIndex == (3 - 4) || choiceIndex == (4 - 4)) { int currentLength = inv_controller_properties.getInventoryIndex(); int scaler = (getRow(currentLength) + 1) * 4; int sLength = scaler + choiceIndex; if (getRow(currentLength) == 0) { choiceIndex = 0; } else if (getRow(currentLength) > 1) { if (sLength > currentLength) { choiceIndex = sLength - 4; } else if (sLength <= currentLength) { choiceIndex = sLength; } } else { if (sLength > currentLength) { choiceIndex = 0; } else if (sLength <= currentLength) { choiceIndex = sLength; } } } } else if (Input.GetKeyUp(KeyCode.DownArrow)) { int currentLength = inv_controller_properties.getInventoryIndex(); choiceIndex += 4; int rows = getRow(currentLength); if ((choiceIndex != (1 + 4) && choiceIndex != (5 + 4) && choiceIndex != (9 + 4)) && choiceIndex > inv_controller_properties.getInventoryIndex()) { switch (rows) { case 0: choiceIndex = 0; break; case 1: if (currentLength < 8) choiceIndex = 0; else choiceIndex -= 8; break; case 2: choiceIndex -= 12; break; } } else if ((choiceIndex == (1 + 4) || choiceIndex == (5 + 4) || choiceIndex == (9 + 4)) && choiceIndex > inv_controller_properties.getInventoryIndex()) { choiceIndex = 0; } } if (choiceIndex != 0) { cursor_items.transform.position = itemGrid.GetChild(choiceIndex - 1).transform.position; displayDescription(choiceIndex); } } else if (inv_controller_properties.getInventoryIndex() > 0) { if (Input.GetKeyUp(KeyCode.UpArrow)) { if (inv_controller_properties.getInventoryIndex() >= 5 && inv_controller_properties.getInventoryIndex() <= 8) { choiceIndex = 5; } else if (inv_controller_properties.getInventoryIndex() >= 9) { choiceIndex = 9; } else { choiceIndex = 1; } } if (Input.GetKeyUp(KeyCode.DownArrow)) { choiceIndex = 1; } if (choiceIndex > 0) { cursor_items.transform.position = itemGrid.GetChild(choiceIndex - 1).transform.position; displayDescription(choiceIndex); } } if (choiceIndex == 0) { cursor_items.transform.position = BACK.transform.position; clearDescription(); } //////////////////// // PRESSING ENTER // //////////////////// if (Input.GetKeyDown(KeyCode.Return)) { if (choiceIndex == 0) { Destroy(cursor_items); Destroy(this.gameObject); status = false; } else { inv_controller_properties.useItem(choiceIndex); overworldUI_properties.updateUIValues(); if (inv_amt[choiceIndex - 1] < 1) { redoInventory(choiceIndex); } else displayDescription(choiceIndex); if (inv_controller_properties.getInventoryIndex() == 0) choiceIndex = 0; else if (inv_controller_properties.getInventoryIndex() == choiceIndex - 1) choiceIndex--; } } } public void displayInventory() { GameObject[] inventory = inv_controller_properties.getInventory(); GameObject temp; Vector3 scaleVector = new Vector3(0.25f, 0.25f, 0); for (int i = 0; i < inv_controller_properties.getInventoryIndex(); i++) { temp = Instantiate(inventory[i]); temp.transform.localScale = scaleVector; temp.transform.SetParent(itemGrid); temp.transform.position = itemGrid.GetChild(i).transform.position; temp.GetComponent<SpriteRenderer>().sortingLayerName = "BattleCursorLayer"; } } public void redoInventory(int index) { int inventoryLength = inv_controller_properties.getInventoryIndex(); for (int i = 12; i < inventoryLength + 13; i++) { Destroy(itemGrid.GetChild(i).gameObject); } displayInventory(); } public void displayDescription(int index) { ItemAttr item_properties = itemGrid.GetChild(index + 11).GetComponent<ItemAttr>(); itemName.text = item_properties.Name; itemDescriptions.text = item_properties.Description; itemAttrs_hp.text = "+" + item_properties.HP_restore.ToString() + " HP"; itemAttrs_ap.text = "+" + item_properties.AP_restore.ToString() + " AP"; itemAmt_x.text = "x"; itemAmt.text = inv_controller_properties.getInventoryAmount()[index-1].ToString(); for (int i = 0; i < inv_controller_properties.getInventoryIndex(); i++) { Debug.Log(i+ ": " + inv_controller_properties.getInventoryAmount()[i]); } } public void clearDescription() { itemName.text = ""; itemDescriptions.text = ""; itemAttrs_hp.text = ""; itemAttrs_ap.text = ""; itemAmt_x.text = ""; itemAmt.text = ""; } private int getRow(int length) { return (length - 1) / column; } public bool getStatus() { return status; } public void battleStart() { /////////////////////////////////////// // GET THE INVENTORY DATA STRUCTURES // /////////////////////////////////////// inv_controller_properties = GameObject.Find("ITEM_MANAGER").GetComponent<InventoryController>(); inv_amt = inv_controller_properties.getInventoryAmount(); //overworldUI_properties = GameObject.Find("Overworld_UI").GetComponent<OverworldUIManager>(); status = true; ///////////////// // CURSOR VARS // ///////////////// cursorSpawnPos = new Vector3(BACK.transform.position.x + 2f, BACK.transform.position.y); cursor_items = Instantiate(cursor, cursorSpawnPos, Quaternion.identity); //////////////////////////////////////////////////// // 'ITEM_GRID' SHOULD ALWAYS BE THE LAST CHILD... // //////////////////////////////////////////////////// childNum = this.gameObject.transform.childCount; itemGrid = this.gameObject.transform.GetChild(childNum - 1); displayInventory(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class JerryInfo_Battle : Character { private OverworldUIManager UIManager_properties; private Manager GameManager_properties = new Manager(); void Start() { getStats(); transform.position = GameManager_properties.get_jerry_last_pos(); UIManager_properties.setUIValues(); } public string getLevel() { return level.ToString(); } public string getHealth() { return health.ToString(); } public string getName() { return characterName; } public int getEnemiesKilled() { return GameManager_properties.get_enemies_killed(); } public void getStats() { level = GameManager_properties.get_jerry_level(); speed = GameManager_properties.get_jerry_speed(); health = GameManager_properties.get_jerry_health(); attack = GameManager_properties.get_jerry_attack(); total_exp = GameManager_properties.get_jerry_exp(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterController2D : MonoBehaviour { //////////////////////////////////////////////////////////////// // States for showing which direction the character is moving // //////////////////////////////////////////////////////////////// public enum MovementState { UP, DOWN, LEFT, RIGHT, STILL } public MovementState state; ////////////////////////////////////////////////////// // Speed variable... Kinda buggy for some reason... // ////////////////////////////////////////////////////// public float speed; ////////////////////////////////// // Variables used for animation // ////////////////////////////////// Animator animator; private string[] anim_bools = { "key_up", "key_down", "key_left", "key_right" }; ////////////////////////////////////////////// // Rigid body stuff... will need this later // ////////////////////////////////////////////// Rigidbody2D rb; void Start() { animator = GetComponent<Animator>(); rb = GetComponent<Rigidbody2D>(); state = MovementState.STILL; } void Update() { setState(); if (state == MovementState.DOWN) { transform.Translate(new Vector2(0f, -0.01f*speed)); setAllAnimFalseBut("key_down"); } else if (state == MovementState.UP) { transform.Translate(new Vector2(0f, 0.01f * speed)); setAllAnimFalseBut("key_up"); } else if (state == MovementState.LEFT) { transform.Translate(new Vector2(-0.01f * speed, 0f)); setAllAnimFalseBut("key_left"); } else if (state == MovementState.RIGHT) { transform.Translate(new Vector2(0.01f * speed, 0f)); setAllAnimFalseBut("key_right"); } else { setAllAnimFalse(); } } private void setState() { if (Input.GetKey(KeyCode.RightArrow)) { state = MovementState.RIGHT; } else if (Input.GetKey(KeyCode.LeftArrow)) { state = MovementState.LEFT; } else if (Input.GetKey(KeyCode.UpArrow)) { state = MovementState.UP; } else if (Input.GetKey(KeyCode.DownArrow)) { state = MovementState.DOWN; } else { state = MovementState.STILL; } } /////////////////////////////////////////////////////////////// // These functions are here for managing animation variables // /////////////////////////////////////////////////////////////// private void setAllAnimFalse() { for (int i = 0; i < anim_bools.Length; i++) { animator.SetBool(anim_bools[i], false); } } private void setAllAnimFalseBut(string exception) { for (int i = 0; i < anim_bools.Length; i++) { if (anim_bools[i] != exception) animator.SetBool(anim_bools[i], false); else animator.SetBool(exception, true); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class BattleChar : MonoBehaviour { // ***PLAYER STATS*** // ***Base*** private Manager gameManager_properties = new Manager(); public int health; public int attack; public int defense; public int level; public float speed; // ****************** /////////////// // EXP STUFF // /////////////// public int total_exp; private int damageTaken; public GameObject enemyB; public GameObject selector; public Canvas bUI; ///////////////////// // ANIMATION STUFF // ///////////////////// Animator animator; private string [] anim_bools = { "idle", "walk_right", "walk_left", "attack" }; private string[] anim_states = { "Final_Jerry_Idle_Right", "Final_Jerry_Walk_Right", "Final_Jerry_Walk_Left", "Final_Jerry_Attack" }; ///////////////////////// // UPDATE STATIC STATS // ///////////////////////// //private Manager gameManager_properties = new Manager(); void Start() { animator = GetComponent<Animator>(); enemyB.GetComponent<SpanEnemies>(); getStats(); } private void Update() { } public float getPlayerSpeed() { return speed; } public int getDefense() { return gameManager_properties.get_jerry_defense(); } public void takeDamage(int damage) { damageTaken = damage - defense; if (damageTaken < 0) { damageTaken = 0; } health = gameManager_properties.get_jerry_health(); health -= damageTaken; gameManager_properties.set_jerry_health(health); } public int getDamageTaken() { return damageTaken; } public int getPlayerHealth() { return health; } public int getAttack() { return gameManager_properties.get_jerry_attack(); } public int getExp() { return total_exp; } public void gainExp(int expGained) { total_exp += expGained; } public int calculateLevel() { return (int)(0.3 * Math.Round(Math.Sqrt(total_exp))) + 1; } /////////////////////////////////////////////////////////////// // These functions are here for managing animation variables // /////////////////////////////////////////////////////////////// private void setAllAnimFalse() { for (int i = 0; i < anim_bools.Length; i++) { animator.SetBool(anim_bools[i], false); } } public void setAllAnimFalseBut(string exception) { for (int i = 0; i < anim_bools.Length; i++) { if (anim_bools[i] != exception) animator.SetBool(anim_bools[i], false); else animator.SetBool(exception, true); } } public void playAttack() { animator.Play(anim_states[3]); } public bool getAnimState() { return animator.GetCurrentAnimatorStateInfo(0).IsName("Final_Jerry_Attack"); } public float getNormTime() { return animator.GetCurrentAnimatorStateInfo(0).normalizedTime; } //////////////////////////////// // SET ALL OF THE STATIC VARS // //////////////////////////////// public void updateStats(bool killed=false) { //getStats(); gameManager_properties.set_jerry_level(calculateLevel()); gameManager_properties.set_jerry_health(getPlayerHealth()); gameManager_properties.set_jerry_attack(getAttack()); gameManager_properties.set_jerry_defense(getDefense()); gameManager_properties.set_jerry_exp(getExp()); if (killed) { gameManager_properties.set_enemies_killed(); } } public void getStats() { level = gameManager_properties.get_jerry_level(); speed = gameManager_properties.get_jerry_speed(); health = gameManager_properties.get_jerry_health(); attack = gameManager_properties.get_jerry_attack(); defense = gameManager_properties.get_jerry_defense(); total_exp = gameManager_properties.get_jerry_exp(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DamageSpawner : MonoBehaviour { public Text damageText; public void insDam(GameObject damageTaker, int damageDone) { damageText.text = damageDone.ToString(); Instantiate(damageText, new Vector3 (damageTaker.transform.position.x, damageTaker.transform.position.y, 0f), Quaternion.identity).transform.SetParent(transform); } }
dbb4b6f70c5e06c41c09547a5578a2a4ffdbc239
[ "C#" ]
29
C#
EveyJSwag/CHRPG
ce68e410c6e8fdce1d99c4c43a16ae81fabd2162
1c93999a62fee20940b3476f6df08d950d537e25
refs/heads/master
<repo_name>neige28/auto-clicker<file_sep>/README.md # auto-clicker pick color, auto click <file_sep>/src/auto-clicker/auto-clicker/MainForm.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.Runtime.InteropServices; using System.Drawing; using System.Drawing.Imaging; namespace auto_clicker { public partial class MainForm : Form { [DllImport("user32.dll")] static extern bool GetCursorPos(ref Point lpPoint); [DllImport("gdi32.dll")] public static extern int BitBlt(IntPtr hDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop); [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)] static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); /// <summary> /// プログラム有効 /// </summary> private bool isEnabled; /// <summary> /// 色検知待機中 /// </summary> private bool isActive; /// <summary> /// カーソル座標 /// </summary> private Point cursorPoint; private Bitmap screenPixel; private Color beforeColor; private int wheelDelta_p; private int wheelDelta_m; List<InputSimulator.Input> inputs; List<InputSimulator.MouseStroke> flags; private static readonly int ActiveTime = 5000; public MainForm() { InitializeComponent(); this.screenPixel = new Bitmap(1, 1, PixelFormat.Format32bppArgb); this.isEnabled = true; this.debugTable1.SetValue("isEnable", this.isEnabled); this.debugTable1.SetValue("DateTime", this.isEnabled); this.debugTable1.SetValue("isActive", this.isEnabled); this.debugTable1.SetValue("StartColor", "null"); this.debugTable1.SetValue("CurrentColor", "null"); this.debugTable1.SetValue("Cursor", "null"); this.debugTable1.SetValue("Wheel+", "null"); this.debugTable1.SetValue("Wheel-", "null"); MouseHook.AddEvent(this.HookMouse); MouseHook.Start(); inputs = new List<InputSimulator.Input>(); flags = new List<InputSimulator.MouseStroke>(); flags.Add(InputSimulator.MouseStroke.LEFT_DOWN); flags.Add(InputSimulator.MouseStroke.LEFT_UP); InputSimulator.AddMouseInput(ref inputs, flags, 0, false, 0, 0); } #region トリガー /// <summary> /// /// </summary> /// <param name="s"></param> private void HookMouse(ref MouseHook.StateMouse s) { if (s.Stroke == MouseHook.Stroke.WHEEL_DOWN) { this.wheelDelta_m++; } if (s.Stroke == MouseHook.Stroke.WHEEL_UP) { this.wheelDelta_p++; } } private void wheelTimer_Tick(object sender, EventArgs e) { if (this.wheelDelta_m > 0) { this.wheelDelta_m--; } if (this.wheelDelta_p > 0) { this.wheelDelta_p--; } this.debugTable1.SetValue("Wheel+", this.wheelDelta_p); this.debugTable1.SetValue("Wheel-", this.wheelDelta_m); if (this.wheelDelta_m > 3 || this.wheelDelta_p > 3) { this.SetIsActive(true); } } DateTime startDt; private void activeTimer_Tick(object sender, EventArgs e) { this.SetIsActive(false); } private void SetIsActive(bool isActive) { this.isActive = isActive; this.debugTable1.SetValue("IsActive", isActive); if (isActive) { this.startDt = DateTime.Now; this.cursorPoint = Cursor.Position; this.beforeColor = this.GetColorAt(this.cursorPoint); this.activeTimer.Interval = ActiveTime; this.activeTimer.Start(); this.checkTimer.Start(); this.wheelDelta_m = 0; this.wheelDelta_p = 0; } else { this.activeTimer.Stop(); this.checkTimer.Stop(); } } #endregion private void checkTimer_Tick(object sender, EventArgs e) { this.debugTable1.SetValue("ActiveTime", (ActiveTime - (DateTime.Now - startDt).TotalMilliseconds) / 1000); // 判定 var color = this.GetColorAt(this.cursorPoint); this.debugTable1.SetValue("Color", color); var isChangedColor = color != this.beforeColor; var click = isActive && isChangedColor; this.debugTable1.SetValue("Click", click); // クリックする if (this.isEnabled && click) { this.debugTable1.SetValue("Click", true); var sDt = DateTime.Now; InputSimulator.SendInput(inputs); var eDt = DateTime.Now; this.debugTable1.SetValue("wait",( eDt - sDt).TotalMilliseconds); this.SetIsActive(false); } else { this.debugTable1.SetValue("Click", false); } this.beforeColor = color; } private bool IsChangedColor() { // 色取得 var color = GetColorAt(this.cursorPoint); this.debugTable1.SetValue("CurrentColor", color); return color != this.beforeColor; } public Color GetColorAt(Point location) { using (Graphics gdest = Graphics.FromImage(screenPixel)) { using (Graphics gsrc = Graphics.FromHwnd(IntPtr.Zero)) { IntPtr hSrcDC = gsrc.GetHdc(); IntPtr hDC = gdest.GetHdc(); int retval = BitBlt(hDC, 0, 0, 1, 1, hSrcDC, location.X, location.Y, (int)CopyPixelOperation.SourceCopy); gdest.ReleaseHdc(); gsrc.ReleaseHdc(); } } return screenPixel.GetPixel(0, 0); } private void debugTable1_Load(object sender, EventArgs e) { } } } <file_sep>/src/py/auto-clicker.py import pyautogui import time from datetime import datetime, timedelta class Main(object): def __init__(self): self.debug = False def run(self): p = (0,0) befCol = None activeDt = datetime.now() while True: self.debug_print('roop') nowDt = datetime.now() if self.check_trigger(): self.debug_print('active') activeDt = nowDt + timedelta(minutes=5) if nowDt < activeDt: self.debug_print('run auto click') pos = pyautogui.position() img = pyautogui.screenshot(region=(pos[0] -13, pos[1], 1, 1)) col = img.getpixel(p) if befCol != None and col != befCol: pyautogui.click(pos) activeDt = nowDt befCol = col # time.sleep(0.001) def check_trigger(self): self.debug_print('check event') return True def debug_print(self, args): if self.debug: print(args) if __name__ == '__main__': main = Main() main.run() <file_sep>/src/auto-clicker/auto-clicker/DebugTable.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace auto_clicker { public partial class DebugTable : UserControl { public Dictionary<string, object> dict; public Dictionary<string, Label> labels; public Dictionary<string, Label> values; public DebugTable() { InitializeComponent(); this.dict = new Dictionary<string, object>(); this.labels = new Dictionary<string, Label>(); this.values = new Dictionary<string, Label>(); this.SetValue("key", "value"); } public void SetValue(string key, object value) { if (!this.dict.ContainsKey(key)) { var l = new Label() { Text = key, AutoSize = true, }; var v = new Label() { Text = value.ToString(), AutoSize = true, }; var r = this.tableLayoutPanel1.Controls.Count / 2; this.tableLayoutPanel1.Controls.Add(l, 0, r); this.tableLayoutPanel1.Controls.Add(v, 1, r); this.labels.Add(key, l); this.values.Add(key, v); } this.dict[key] = value; this.values[key].Text = value.ToString(); } } }
427b3befb8d471782fb988ff63563372a7ffe232
[ "Markdown", "C#", "Python" ]
4
Markdown
neige28/auto-clicker
857089cf3f3615bbee123098ad098ac98320b884
1ce8c98f849cdea9dbd4764413ce95129a9b054b
refs/heads/master
<file_sep>package VideoAI import ( video "cloud.google.com/go/videointelligence/apiv1" "context" "fmt" videopb "google.golang.org/genproto/googleapis/cloud/videointelligence/v1" "io/ioutil" ) type VideoAI struct { } func (videoAI *VideoAI) Label(file string) ([]string, error) { fmt.Println("LABELS: ") labelsStringArray := []string{} ctx := context.Background() client, err := video.NewClient(ctx) if err != nil { return nil, fmt.Errorf("video.NewClient: %v", err) } fileBytes, err := ioutil.ReadFile(file) if err != nil { return nil, err } op, err := client.AnnotateVideo(ctx, &videopb.AnnotateVideoRequest{ Features: []videopb.Feature{ videopb.Feature_LABEL_DETECTION, }, InputContent: fileBytes, }) if err != nil { return nil, fmt.Errorf("AnnotateVideo: %v", err) } resp, err := op.Wait(ctx) if err != nil { return nil, fmt.Errorf("Wait: %v", err) } printLabels := func(labels []*videopb.LabelAnnotation) { for _, label := range labels { fmt.Printf( "\tDescription: %s\n", label.Entity.Description) labelsStringArray = append(labelsStringArray, label.Entity.Description) for _, category := range label.CategoryEntities { fmt.Printf("\t\tCategory: %s\n", category.Description) labelsStringArray = append(labelsStringArray, category.Description) } /*for _, segment := range label.Segments { start, _ := ptypes.Duration(segment.Segment.StartTimeOffset) end, _ := ptypes.Duration(segment.Segment.EndTimeOffset) fmt.Printf("\t\tSegment: %s to %s\n", start, end) fmt.Printf("\tConfidence: %v\n", segment.Confidence) }*/ } } // A single video was processed. Get the first result. result := resp.AnnotationResults[0] fmt.Printf("SegmentLabelAnnotations:") printLabels(result.SegmentLabelAnnotations) fmt.Printf( "ShotLabelAnnotations:") printLabels(result.ShotLabelAnnotations) fmt.Printf( "FrameLabelAnnotations:") printLabels(result.FrameLabelAnnotations) return labelsStringArray, nil }<file_sep>package Worker import ( "fmt" "github.com/streadway/amqp" "log" "video-analysis-worker/Models" ) type RabbitMqConnection struct { Conn *amqp.Connection Ch *amqp.Channel q amqp.Queue msgs <-chan amqp.Delivery } func initRabbitMqConnection(env *Models.Env) *RabbitMqConnection { fmt.Println("Rabbit port connection: ", env.RabbitPort) conn, err := amqp.Dial("amqp://" + env.RabbitUser + ":" + env.RabbitPassword + "@" + env.RabbitHost + ":"+env.RabbitPort) // amqp://uros:uros123@localhost:5672/ failOnError(err, "Failed to connect to RabbitMQ") ch, err := conn.Channel() failOnError(err, "Failed to open a channel") q, err := ch.QueueDeclare( env.RabbitQueue, true, false, false, false, nil, ) failOnError(err, "Failed to declare a queue") err = ch.Qos( 1, 0, false, ) failOnError(err, "Failed to set QoS") msgs, err := ch.Consume( q.Name, "", false, false, false, false, nil, ) failOnError(err, "Failed to register a consumer") return &RabbitMqConnection{ Conn: conn, Ch: ch, q: q, msgs: msgs, } } func failOnError(err error, msg string) { if err != nil { log.Fatalf("%s: %s", msg, err) } }<file_sep>package grpc_client import ( "context" "fmt" "google.golang.org/grpc" "log" "video-analysis-worker/Models" pbMediaMetadata "video-analysis-worker/proto/media_metadata" ) type MediaMetadataClient struct { Conn *grpc.ClientConn client pbMediaMetadata.MediaMetadataClient } func (mediaMetadataClient *MediaMetadataClient) GetMediaMetadata(mediaId int) (*pbMediaMetadata.MediaMetadataResponse, error) { response, err := mediaMetadataClient.client.GetMediaMetadata(context.Background(), &pbMediaMetadata.GetMediaMetadataRequest{ MediaId: int32(mediaId), }) if err != nil { return nil, err } return response, nil } func (mediaMetadataClient *MediaMetadataClient) UpdateMediaKeywords(mediaId int32, keywords []string) (*pbMediaMetadata.MediaMetadataResponse, error) { response, err := mediaMetadataClient.client.UpdateMediaKeywords(context.Background(), &pbMediaMetadata.UpdateMediaKeywords{ MediaId: mediaId, Keywords: keywords, }) if err != nil { return nil, err } return response, nil } func InitMediaMetadataGrpcClient() *MediaMetadataClient { env := Models.GetEnvStruct() fmt.Println("CONNECTING") conn, err := grpc.Dial(env.MediaMetadataGrpcServer + ":" + env.MediaMetadataGrpcPort, grpc.WithInsecure(), grpc.WithBlock()) if err != nil { log.Fatalf("did not connect: %v", err) } fmt.Println("END CONNECTION") client := pbMediaMetadata.NewMediaMetadataClient(conn) return &MediaMetadataClient{ Conn: conn, client: client, } } <file_sep>package Worker import ( "encoding/json" "fmt" "log" "os" "video-analysis-worker/Http" "video-analysis-worker/Models" "video-analysis-worker/VideoAI" "video-analysis-worker/grpc_client" ) type Worker struct { RabbitMQ *RabbitMqConnection env *Models.Env mediaMetadataGrpcClient *grpc_client.MediaMetadataClient mediaDowLoader *Http.MediaDownloader videoAI *VideoAI.VideoAI } func (worker *Worker) Work() { forever := make(chan bool) go func() { for d := range worker.RabbitMQ.msgs { log.Printf("Received a message: %s", d.Body) rabbiMQMessageAnalysis := &Models.RabbitMQMessageAnalysis{} err := json.Unmarshal(d.Body, rabbiMQMessageAnalysis) if err != nil{ log.Println(err) } // fmt.Println(rabbiMQMessageAnalysis) mediaMetadata, err := worker.mediaMetadataGrpcClient.GetMediaMetadata(rabbiMQMessageAnalysis.MediaId) if err != nil{ log.Println(err) } // fmt.Println(mediaMetadata) fileUrl := worker.env.AwsStorageUrl + "v1/awsStorage/media/" + mediaMetadata.AwsBucketWholeMedia + "/" + mediaMetadata.AwsStorageNameWholeMedia err = worker.mediaDowLoader.DownloadFile("./assets/" + mediaMetadata.AwsStorageNameWholeMedia, fileUrl) if err != nil { log.Println(err) } labelsStringArray, err := worker.videoAI.Label("./assets/" + mediaMetadata.AwsStorageNameWholeMedia) if err != nil { log.Println(err) } // fmt.Println() // fmt.Println(labelsStringArray) _, err = worker.mediaMetadataGrpcClient.UpdateMediaKeywords(mediaMetadata.MediaId, labelsStringArray) if err != nil{ log.Println(err) } // fmt.Println(updatedMetadata) worker.removeFile("./assets/" + mediaMetadata.AwsStorageNameWholeMedia) log.Printf("Done") _ = d.Ack(false) } }() log.Printf(" [*] Waiting for messages. To exit press CTRL+C") <-forever } func (worker *Worker) removeFile(path string) { err := os.Remove(path) if err != nil { fmt.Println(err) } } func InitWorker() *Worker { return &Worker{ RabbitMQ: initRabbitMqConnection(Models.GetEnvStruct()), env: Models.GetEnvStruct(), mediaMetadataGrpcClient: grpc_client.InitMediaMetadataGrpcClient(), mediaDowLoader: &Http.MediaDownloader{}, videoAI: &VideoAI.VideoAI{}, } } <file_sep>FROM golang:alpine RUN apk upgrade -U \ && apk add ca-certificates ffmpeg libva-intel-driver \ && rm -rf /var/cache/* ENV GO111MODULE=on \ CGO_ENABLED=0 \ GOOS=linux \ GOARCH=amd64 VOLUME $GOOGLE_APPLICATION_CREDENTIALS:magisterij-6d3594ec69ea.json:ro ENV GOOGLE_APPLICATION_CREDENTIALS=magisterij-6d3594ec69ea.json WORKDIR /build COPY go.mod . COPY go.sum . RUN go mod download COPY . . RUN go build -o main . WORKDIR /dist RUN cp /build/main . COPY .live.env . RUN cp .live.env .env && mkdir assets && mkdir assets/chunks COPY magisterij-6d3594ec69ea.json . CMD ["/dist/main"]<file_sep># video-analysis-worker ## * set GOOGLE_APPLICATION_CREDENTIALS=magisterij-6d3594ec69ea.json * export GOOGLE_APPLICATION_CREDENTIALS="magisterij-6d3594ec69ea.json" ## Worker example message ``` {"mediaId":7} {"mediaId":10} {"mediaId":12} ``` ##PROTOCOL BUFFER ```.env protoc proto\helloworld.proto --go_out=plugins=grpc:. ```<file_sep>module video-analysis-worker go 1.13 require ( cloud.google.com/go v0.57.0 github.com/dustin/go-humanize v1.0.0 github.com/golang/protobuf v1.4.2 github.com/google/go-cmp v0.4.1 // indirect github.com/heptiolabs/healthcheck v0.0.0-20180807145615-6ff867650f40 // indirect github.com/joho/godotenv v1.3.0 // indirect github.com/prometheus/client_golang v1.6.0 // indirect github.com/streadway/amqp v0.0.0-20200108173154-1c71cc93ed71 golang.org/x/net v0.0.0-20200528225125-3c3fba18258b // indirect golang.org/x/sys v0.0.0-20200523222454-059865788121 // indirect google.golang.org/api v0.25.0 // indirect google.golang.org/genproto v0.0.0-20200528191852-705c0b31589b google.golang.org/grpc v1.29.1 ) <file_sep>package Models type RabbitMQMessageAnalysis struct { MediaId int `json:"mediaId"` } <file_sep>package main import ( "crypto/tls" "github.com/heptiolabs/healthcheck" "github.com/joho/godotenv" "log" "net/http" "time" "video-analysis-worker/Models" Worker "video-analysis-worker/worker" ) func init() { if err := godotenv.Load(); err != nil { log.Print("No .env file found") } Models.InitEnv() } func main() { http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} env := Models.GetEnvStruct() health := healthcheck.NewHandler() health.AddLivenessCheck("aws-service-check-url: " + Models.GetEnvStruct().AwsStorageUrl + "health", healthcheck.HTTPGetCheck(Models.GetEnvStruct().AwsStorageUrl + "health", 5*time.Second)) health.AddLivenessCheck("media-metadata: " + env.MediaMetadataGrpcServer + ":" + env.MediaMetadataGrpcPort, healthcheck.TCPDialCheck(env.MediaMetadataGrpcServer + ":" + env.MediaMetadataGrpcPort, 5*time.Second)) health.AddLivenessCheck("rabbit-mq: " + env.RabbitHost + ":" + env.RabbitPort, healthcheck.TCPDialCheck(env.RabbitHost + ":" + env.RabbitPort, 5*time.Second)) go http.ListenAndServe("0.0.0.0:8888", health) worker := Worker.InitWorker() defer worker.RabbitMQ.Conn.Close() defer worker.RabbitMQ.Ch.Close() worker.Work() }<file_sep>package Http import ( "fmt" "github.com/dustin/go-humanize" "io" "net/http" "os" "strings" ) type writeCounter struct { Total uint64 } func (wc *writeCounter) Write(p []byte) (int, error) { n := len(p) wc.Total += uint64(n) wc.PrintProgress() return n, nil } func (wc writeCounter) PrintProgress() { fmt.Printf("\r%s", strings.Repeat(" ", 35)) fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.Total)) } type MediaDownloader struct { } func (mediaDownloader *MediaDownloader) DownloadFile(filepath string, url string) error { out, err := os.Create( filepath + ".tmp") if err != nil { return err } resp, err := http.Get(url) if err != nil { out.Close() return err } defer resp.Body.Close() counter := &writeCounter{} if _, err = io.Copy(out, io.TeeReader(resp.Body, counter)); err != nil { out.Close() return err } fmt.Print("\n") out.Close() if err = os.Rename(filepath+".tmp", filepath); err != nil { return err } return nil } <file_sep>package Models import ( "fmt" "os" ) var envStruct *Env type Env struct { RabbitUser string RabbitPassword string RabbitQueue string RabbitHost string RabbitPort string AwsStorageUrl string Env string MediaMetadataGrpcServer string MediaMetadataGrpcPort string } func InitEnv() { envStruct = &Env{ RabbitUser: os.Getenv("RABBIT_USER"), RabbitPassword: os.Getenv("RABBIT_PASSWORD"), RabbitQueue: os.Getenv("RABBIT_QUEUE"), RabbitHost: os.Getenv("RABBIT_HOST"), AwsStorageUrl: os.Getenv("AWS_STORAGE_URL"), RabbitPort: os.Getenv("RABBIT_PORT"), Env: os.Getenv("ENV"), MediaMetadataGrpcServer: os.Getenv("MEDIA_METADATA_GRPC_SERVER"), MediaMetadataGrpcPort: os.Getenv("MEDIA_METADATA_GRPC_PORT"), } fmt.Println(envStruct) } func GetEnvStruct() *Env { return envStruct }
19fc28490a83480ecf71c9489b928808c1970a07
[ "Markdown", "Go Module", "Go", "Dockerfile" ]
11
Go
magistrsko-delo/video-analysis-worker
678716fbefaceb6e9d6337221dc62cbdc96a01a2
c5a68254d6dc8fc47ed2448c6901f1cc507c5ad6
refs/heads/master
<repo_name>vncaMichaelD/periodical<file_sep>/backend/model/inventory.rb class Inventory < Sequel::Model(:inventory) include ASModel corresponds_to JSONModel(:inventory) include InventoryFldrs set_model_scope :global end <file_sep>/frontend/routes.rb ArchivesSpace::Application.routes.draw do match 'prdcl_titles/defaults' => 'prdcl_titles#defaults', :via => [:get] match 'prdcl_titles/defaults' => 'prdcl_titles#update_defaults', :via => [:post] resources :prdcl_titles match 'prdcl_titles/:id' => 'prdcl_titles#update', :via => [:post] match 'prdcl_titles/:id/delete' => 'prdcl_titles#delete', :via => [:post] end <file_sep>/backend/model/agent_family_ext.rb AgentFamily.include(MailingLists) AgentFamily.include(Militarys) AgentFamily.include(Civilians) AgentFamily.include(FriendsMemberships) AgentFamily.include(Staffs)<file_sep>/backend/model/mixins/notaccepteds.rb module Notaccepteds def self.included(base) base.one_to_many :notaccepted base.def_nested_record(:the_property => :notaccepteds, :contains_records_of_type => :notaccepted, :corresponding_to_association => :notaccepted) end end <file_sep>/backend/model/notaccepted.rb class Notaccepted < Sequel::Model(:notaccepted) include ASModel corresponds_to JSONModel(:notaccepted) include Extents set_model_scope :repository end <file_sep>/backend/model/digital_object_ext.rb DigitalObject.include(Audiovisuals) DigitalObject.include(Oralhistorys) DigitalObject.include(Prdcls) DigitalObject.include(Maps) DigitalObject.include(SeeAlsos) <file_sep>/frontend/assets/javascripts/prdcl_titles.crud.js //= require form $(function() { var init_prdcl_title_form = function(form) { var $form = $(form); var newSelector = "#prdcl_title"; if ( $form.selector === '#new_prdcl_title_batch' ) { newSelector = "#prdcl_title_batch"; } }; // This is for binding event to prdcl_links, which link prdcl_titles to // resources // this is also for init the form in modals $(document).ready(function() { // this inits the form in the new prdcl_title page if ( $('#new_prdcl_title').length > 0 ) { init_prdcl_title_form($("#new_prdcl_title")); } // this inits the form in the new prdcl_title batch page if ( $('#new_prdcl_title_batch').length > 0 ) { init_prdcl_title_form($("#new_prdcl_title_batch")); } // this init the form in the modal $(document).bind("loadedrecordform.aspace", function(event, $container) { init_prdcl_title_form(("#new_prdcl_title", $container) ); }) // this is for prdcl_link, which link resources to prdcl_titles $(document).bind("subrecordcreated.aspace", function(event, object_name, subform) { if ( object_name === 'prdcl_link' ){ // just in case..lets init the form init_prdcl_title_form($(subform)); } }); }); }); <file_sep>/schemas/prdcl_title.rb { :schema => { "$schema" => "http://www.archivesspace.org/archivesspace.json", "version" => 1, "type" => "object", "uri" => "/prdcl_titles", "properties" => { "uri" => {"type" => "string", "required" => false}, "title" => {"type" => "string", "readonly" => true}, "publication" => {"type" => "string", "maxLength" => 255, "minLength" => 1, "ifmissing" => "error"}, "publisher" => {"type" => "string", "maxLength" => 255}, }, }, } <file_sep>/backend/model/mixins/map_subs.rb module MapSubs def self.included(base) base.one_to_many :map_sub base.def_nested_record(:the_property => :map_subs, :contains_records_of_type => :map_sub, :corresponding_to_association => :map_sub) end end <file_sep>/backend/model/mixins/ohsessions.rb module Ohsessions def self.included(base) base.one_to_many :ohsession base.def_nested_record(:the_property => :ohsessions, :contains_records_of_type => :ohsession, :corresponding_to_association => :ohsession) end end <file_sep>/schemas/prdcl.rb { :schema => { "$schema" => "http://www.archivesspace.org/archivesspace.json", "version" => 1, "type" => "object", "properties" => { "publication" => {"type" => "string", "maxLength" => 255}, "volume_num" => {"type" => "string", "maxLength" => 255}, "issue_num" => {"type" => "string", "maxLength" => 255}, "num_of_articles" => {"type" => "string", "maxLength" => 255}, "num_of_issues" => {"type" => "string", "maxLength" => 255}, "donor" => {"type" => "string", "maxLength" => 255}, "publisher" => {"type" => "string", "maxLength" => 255}, "pub_city" => {"type" => "string", "maxLength" => 255}, "pub_country" => {"type" => "string", "maxLength" => 255}, "pub_frequency" => {"type" => "string", "dynamic_enum" => "prdcl_pub_frequency"}, "pub_format" => {"type" => "string", "dynamic_enum" => "prdcl_pub_format"}, "potential" => {"type" => "boolean"}, "association" => {"type" => "string", "maxLength" => 255}, "contact_name" => {"type" => "string", "maxLength" => 255}, "address" => {"type" => "string", "maxLength" => 255}, "phone" => {"type" => "string", "maxLength" => 255}, "email" => {"type" => "string", "maxLength" => 255}, "place" => {"type" => "string", "maxLength" => 255}, "city" => {"type" => "string", "maxLength" => 255}, "state" => {"type" => "string", "maxLength" => 255}, "country" => {"type" => "string", "maxLength" => 255}, "zip" => {"type" => "string", "maxLength" => 20}, "general_note" => {"type" => "string", "maxLength" => 65000}, "start" => {"type" => "string", "maxLength" => 255}, "end" => {"type" => "string", "maxLength" => 255}, "prdcl_links" => { "type" => "array", "minItems" => 1, "items" => { "type" => "JSONModel(:prdcl_link) object", } } }, }, } <file_sep>/backend/model/staff.rb class Staff < Sequel::Model(:staff) include ASModel corresponds_to JSONModel(:staff) include Telephones set_model_scope :global end <file_sep>/backend/model/civilian.rb class Civilian < Sequel::Model(:civilian) include ASModel corresponds_to JSONModel(:civilian) set_model_scope :global end <file_sep>/backend/model/agent_corporate_entity_ext.rb AgentCorporateEntity.include(MailingLists) AgentCorporateEntity.include(Militarys) AgentCorporateEntity.include(Civilians) AgentCorporateEntity.include(FriendsMemberships) AgentCorporateEntity.include(Staffs)<file_sep>/backend/model/prdcl_title.rb class PrdclTitle < Sequel::Model(:prdcl_title) include ASModel corresponds_to JSONModel(:prdcl_title) include AutoGenerator set_model_scope :global def self.generate_title(json) title = "" title << json['publication'] title << " (#{json['publisher']})" if json['publisher'] title end auto_generate :property => :title, :generator => proc {|json| PrdclTitle.generate_title(json) } def delete # only allow delete if the prdcl_title doesn't have any relationships object_graph = self.object_graph if object_graph.models.any? {|model| model.is_relationship?} raise ConflictException.new("Periodical title cannot be deleted if linked") end super end end <file_sep>/backend/model/ohsession.rb class Ohsession < Sequel::Model(:ohsession) include ASModel corresponds_to JSONModel(:ohsession) set_model_scope :repository end <file_sep>/backend/model/map.rb class Map < Sequel::Model(:map) include ASModel corresponds_to JSONModel(:map) include MapGrids include MapSubs set_model_scope :global def self.sequel_to_jsonmodel(objs, opts = {}) jsons = super jsons.zip(objs).each do |json, obj| p json country = json['country'] ? json['country'] : "" country_alt = json['country_alt'] ? json['country_alt'] : "" json['both_country'] = "" if !country.empty? json['both_country'] += "#{country} " end if !country_alt.empty? json['both_country'] += "#{country_alt} " end nlat_degrees = json['nlat_degrees'] ? json['nlat_degrees'] : "" slat_degrees = json['slat_degrees'] ? json['slat_degrees'] : "" json['northsouth_d'] = "" if !nlat_degrees.empty? json['northsouth_d'] += "#{nlat_degrees} " end if !slat_degrees.empty? json['northsouth_d'] += "#{slat_degrees} " end nlat_mins = json['nlat_mins'] ? json['nlat_mins'] : "" slat_mins = json['slat_mins'] ? json['slat_mins'] : "" json['northsouth_m'] = "" if !nlat_mins.empty? json['northsouth_m'] += "#{nlat_mins} " end if !slat_mins.empty? json['northsouth_m'] += "#{slat_mins} " end wlon_degrees = json['wlon_degrees'] ? json['wlon_degrees'] : "" elon_degrees = json['elon_degrees'] ? json['elon_degrees'] : "" json['eastwest_d'] = "" if !wlon_degrees.empty? json['eastwest_d'] += "#{wlon_degrees} " end if !elon_degrees.empty? json['eastwest_d'] += "#{elon_degrees} " end wlon_mins = json['wlon_mins'] ? json['wlon_mins'] : "" elon_mins = json['elon_mins'] ? json['elon_mins'] : "" json['eastwest_m'] = "" if !wlon_mins.empty? json['eastwest_m'] += "#{wlon_mins} " end if !elon_mins.empty? json['eastwest_m'] += "#{elon_mins} " end end jsons end end <file_sep>/backend/model/mailing_list.rb class MailingList < Sequel::Model(:mailing_list) include ASModel corresponds_to JSONModel(:mailing_list) set_model_scope :global end <file_sep>/backend/model/friends_membership.rb class FriendsMembership < Sequel::Model(:friends_membership) include ASModel corresponds_to JSONModel(:friends_membership) set_model_scope :global end <file_sep>/frontend/plugin_init.rb my_routes = [File.join(File.dirname(__FILE__), "routes.rb")] ArchivesSpace::Application.config.paths['config/routes'].concat(my_routes) ArchivesSpace::Application.config.after_initialize do # Force the module to load ApplicationController class ApplicationController < ActionController::Base def find_opts { "resolve[]" => ["subjects", "related_resources", "linked_agents", "revision_statements", "prdcl_links", "container_locations", "digital_object", "classifications", "related_agents", "resource", "parent", "creator", "linked_instances", "linked_records", "related_accessions", "linked_events", "linked_events::linked_records", "linked_events::linked_agents"] } end end end<file_sep>/schemas/digital_object_ext.rb { "prdcls" => {"type" => "array", "items" => {"type" => "JSONModel(:prdcl) object"}}, } <file_sep>/backend/model/mixins/civilians.rb module Civilians def self.included(base) base.one_to_many :civilian base.def_nested_record(:the_property => :civilians, :contains_records_of_type => :civilian, :corresponding_to_association => :civilian) end end <file_sep>/backend/model/mixins/militarys.rb module Militarys def self.included(base) base.one_to_many :military base.def_nested_record(:the_property => :militarys, :contains_records_of_type => :military, :corresponding_to_association => :military) end end <file_sep>/backend/model/mixins/mailing_lists.rb module MailingLists def self.included(base) base.one_to_many :mailing_list base.def_nested_record(:the_property => :mailing_lists, :contains_records_of_type => :mailing_list, :corresponding_to_association => :mailing_list) end end <file_sep>/migrations/002_prdcl_titles.rb Sequel.migration do up do $stderr.puts("VVA adding Periodical Titles tables.") create_table(:prdcl_title) do primary_key :id Integer :lock_version, :default => 0, :null => false Integer :json_schema_version, :null => false HalfLongString :title String :publication String :publisher apply_mtime_columns end create_table(:prdcl_ti_rlshp) do primary_key :id Integer :prdcl_id Integer :prdcl_title_id Integer :aspace_relationship_position apply_mtime_columns(false) end alter_table(:prdcl_ti_rlshp) do add_foreign_key([:prdcl_id], :prdcl, :key => :id) add_foreign_key([:prdcl_title_id], :prdcl_title, :key => :id) add_column(:suppressed, :integer, :null => false, :default => 0) end end end <file_sep>/backend/model/oralhistory.rb class Oralhistory < Sequel::Model(:oralhistory) include ASModel corresponds_to JSONModel(:oralhistory) include Ohstats include Ohsessions include Ohforms set_model_scope :repository end <file_sep>/migrations/001_periodicals.rb Sequel.migration do up do $stderr.puts("Adding VVA Periodical tables, fields, and constraints.") create_table(:prdcl) do primary_key :id Integer :lock_version, :default => 0, :null => false Integer :json_schema_version, :null => false Integer :digital_object_id String :publication String :volume_num String :issue_num String :num_of_articles String :num_of_issues String :donor String :publisher String :pub_city String :pub_country Integer :pub_frequency_id Integer :pub_format_id Integer :potential String :association String :contact_name String :address String :phone String :email String :place String :city String :state String :country String :zip TextField :general_note String :start String :end apply_mtime_columns Integer :star_record end alter_table(:prdcl) do add_foreign_key([:digital_object_id], :digital_object, :key => :id) end create_editable_enum('prdcl_pub_frequency', ["daily", "weekly", "biweekly", "monthly", "bimonthly", "varied"]) create_editable_enum('prdcl_pub_format', ["hardcopy", "microfilm", "microfiche"]) end end <file_sep>/backend/model/prdcl_link.rb class PrdclLink < Sequel::Model(:prdcl_link) include ASModel corresponds_to JSONModel(:prdcl_link) end <file_sep>/backend/model/inventory_fldr.rb class InventoryFldr < Sequel::Model(:inventory_fldr) include ASModel corresponds_to JSONModel(:inventory_fldr) include InventoryDocs set_model_scope :global end <file_sep>/schemas/prdcl_link.rb { :schema => { "$schema" => "http://www.archivesspace.org/archivesspace.json", "version" => 1, "type" => "object", "subtype" => "ref", "properties" => { "ref" => {"type" => "JSONModel(:prdcl_title) uri", "ifmissing" => "error"}, "_resolved" => { "type" => "object", "readonly" => "true" } }, }, } <file_sep>/backend/plugin_init.rb Permission.define("update_prdcl_title_record", "The ability to create/update/delete publication records", :level => "global") <file_sep>/backend/model/military.rb class Military < Sequel::Model(:military) include ASModel corresponds_to JSONModel(:military) set_model_scope :global end <file_sep>/backend/model/mixins/friends_memberships.rb module FriendsMemberships def self.included(base) base.one_to_many :friends_membership base.def_nested_record(:the_property => :friends_memberships, :contains_records_of_type => :friends_membership, :corresponding_to_association => :friends_membership) end end <file_sep>/backend/model/prdcl.rb class Prdcl < Sequel::Model(:prdcl) include ASModel corresponds_to JSONModel(:prdcl) include Relationships set_model_scope :global def self.handle_delete(ids) relationship_defn = find_relationship(:prdcl_ti) relationships = relationship_defn.find_by_participant_ids(self, ids) relationship_defn.handle_delete(relationships.map(&:id)) super end define_relationship(:name => :prdcl_ti, :json_property => 'prdcl_links', :contains_references_to_types => proc {[PrdclTitle]}, ) end <file_sep>/backend/model/ohform.rb class Ohform < Sequel::Model(:ohform) include ASModel corresponds_to JSONModel(:ohform) set_model_scope :repository end <file_sep>/backend/model/mixins/staffs.rb module Staffs def self.included(base) base.one_to_many :staff base.def_nested_record(:the_property => :staffs, :contains_records_of_type => :staff, :corresponding_to_association => :staff) end end <file_sep>/backend/model/map_grid.rb class MapGrid < Sequel::Model(:map_grid) include ASModel corresponds_to JSONModel(:map_grid) set_model_scope :global def self.sequel_to_jsonmodel(objs, opts = {}) jsons = super jsons.zip(objs).each do |json, obj| p json west = json['west'] ? json['west'] : "" east = json['east'] ? json['east'] : "" json['eastwest'] = "" if !east.empty? json['eastwest'] += "#{east} " end if !west.empty? json['eastwest'] += "#{west} " end north = json['north'] ? json['north'] : "" south = json['south'] ? json['south'] : "" json['northsouth'] = "" if !south.empty? json['northsouth'] += "#{south} " end if !north.empty? json['northsouth'] += "#{north} " end end jsons end end <file_sep>/backend/model/mixins/maps.rb module Maps def self.included(base) base.one_to_many :map base.def_nested_record(:the_property => :maps, :contains_records_of_type => :map, :corresponding_to_association => :map) end end <file_sep>/backend/model/resource_ext.rb Resource.include(Inventorys) Resource.include(SeeAlsos) <file_sep>/backend/model/accession_ext.rb Accession.include(Notaccepteds) <file_sep>/backend/model/agent_software_ext.rb AgentSoftware.include(MailingLists) AgentSoftware.include(Militarys) AgentSoftware.include(Civilians) AgentSoftware.include(FriendsMemberships) AgentSoftware.include(Staffs)<file_sep>/backend/model/see_also.rb class SeeAlso < Sequel::Model(:see_also) include ASModel corresponds_to JSONModel(:see_also) set_model_scope :global end <file_sep>/frontend/controllers/prdcl_titles_controller.rb class PrdclTitlesController < ApplicationController set_access_control "view_repository" => [:index, :show], "update_prdcl_title_record" => [:new, :edit, :create, :update, :delete], "manage_repository" => [:defaults, :update_defaults] FACETS = [] def self.FACETS FACETS end def index @search_data = Search.for_type(session[:repo_id], "prdcl_title", params_for_backend_search.merge({"facet[]" => FACETS})) end def get_prdcl_title @prdcl_title = JSONModel(:prdcl_title).find(params[:id]) end def show get_prdcl_title end def new prdcl_title_params = params.inject({}) { |c, (k,v)| c[k] = v ; c } @prdcl_title = JSONModel(:prdcl_title).new(prdcl_title_params)._always_valid! if user_prefs['default_values'] defaults = DefaultValues.get 'prdcl_title' @prdcl_title.update(defaults.values) if defaults end render_aspace_partial :partial => "prdcl_titles/new" if inline? end def edit get_prdcl_title end def create handle_crud(:instance => :prdcl_title, :model => JSONModel(:prdcl_title), :on_invalid => ->(){ return render_aspace_partial :partial => "prdcl_titles/new" if inline? return render :action => :new }, :on_valid => ->(id){ return render :json => @prdcl_title.to_hash if inline? flash[:success] = I18n.t("prdcl_title._frontend.messages.created") if params.has_key?(:plus_one) sticky_params = { :controller => :prdcl_titles, :action => :new} @prdcl_title.to_hash.each_pair do |k,v| sticky_params[k] = v if LOCATION_STICKY_PARAMS.include?(k) end return redirect_to sticky_params end redirect_to :controller => :prdcl_titles, :action => :edit, :id => id }) end def update handle_crud(:instance => :prdcl_title, :model => JSONModel(:prdcl_title), :obj => JSONModel(:prdcl_title).find(params[:id]), :on_invalid => ->(){ return render :action => :edit }, :on_valid => ->(id){ flash[:success] = I18n.t("prdcl_title._frontend.messages.updated") redirect_to :controller => :prdcl_titles, :action => :edit, :id => id }) end def defaults defaults = DefaultValues.get 'prdcl_title' values = defaults ? defaults.form_values : {} @prdcl_title = JSONModel(:prdcl_title).new(values)._always_valid! render "defaults" end def update_defaults begin DefaultValues.from_hash({ "record_type" => "prdcl_title", "lock_version" => params[:prdcl_title].delete('lock_version'), "defaults" => cleanup_params_for_schema( params[:prdcl_title], JSONModel(:prdcl_title).schema) }).save flash[:success] = I18n.t("default_values.messages.defaults_updated") redirect_to :controller => :prdcl_titles, :action => :defaults rescue Exception => e flash[:error] = e.message redirect_to :controller => :prdcl_titles, :action => :defaults end end def batch @is_batch_update = false @action = "create" # we use this for some label in the view.. if request.post? # if it's a post, we're starting an update @is_batch_update = true @action = "update" # we use this for some label in the view.. @prdcl_title_batch = JSONModel(:prdcl_title_batch_update).new(params)._always_valid! else # we're just creatinga new batch from scratch prdcl_title_params = params.inject({}) { |c, (k,v)| c[k] = v if LOCATION_STICKY_PARAMS.include?(k); c } @prdcl_title_batch = JSONModel(:prdcl_title_batch).new(prdcl_title_params) end end def batch_create begin if params[:prdcl_title_batch][:record_uris] && params[:prdcl_title_batch][:record_uris].length > 0 batch = cleanup_params_for_schema(params[:prdcl_title_batch], JSONModel(:prdcl_title_batch_update).schema) @prdcl_title_batch = JSONModel(:prdcl_title_batch_update).from_hash(batch, false)._always_valid! uri = "#{JSONModel::HTTP.backend_url}/prdcl_titles/batch_update" response = JSONModel::HTTP.post_json(URI(uri), batch.to_json) batch_response = ASUtils.json_parse(response.body) else batch = cleanup_params_for_schema(params[:prdcl_title_batch], JSONModel(:prdcl_title_batch).schema) @prdcl_title_batch = JSONModel(:prdcl_title_batch).from_hash(batch, false) uri = "#{JSONModel::HTTP.backend_url}/prdcl_titles/batch" if params["dry_run"] uri += "?dry_run=true" end response = JSONModel::HTTP.post_json(URI(uri), batch.to_json) batch_response = ASUtils.json_parse(response.body) end if batch_response.kind_of?(Hash) and batch_response.has_key?("error") if params["dry_run"] return render_aspace_partial :partial => "shared/quick_messages", :locals => {:exceptions => batch_response, :jsonmodel => "prdcl_title_batch"} else @exceptions = {:errors => batch_response["error"]} return render :action => :batch end end if params["dry_run"] render_aspace_partial :partial => "prdcl_titles/batch_preview", :locals => {:prdcl_titles => batch_response} else # we want 'created' or 'updated' messages displayed if @prdcl_title_batch.jsonmodel_type == "prdcl_title_batch_update" flash[:success] = I18n.t("prdcl_title_batch._frontend.messages.updated", :number_created => batch_response.length) else flash[:success] = I18n.t("prdcl_title_batch._frontend.messages.created", :number_created => batch_response.length) end if params.has_key?(:plus_one) sticky_params = { :controller => :prdcl_titles, :action => :batch} @prdcl_title_batch.to_hash.each_pair do |k,v| sticky_params[k] = v if LOCATION_STICKY_PARAMS.include?(k) end return redirect_to sticky_params end redirect_to :action => :index end rescue JSONModel::ValidationException => e @exceptions = @prdcl_title_batch._exceptions return render :action => :batch end end def delete prdcl_title = JSONModel(:prdcl_title).find(params[:id]) begin prdcl_title.delete rescue ConflictException => e flash[:error] = prdcl_title.translate_exception_message(e.conflicts) return redirect_to(:controller => :prdcl_titles, :action => :show, :id => prdcl_title.id) end flash[:success] = I18n.t("prdcl_title._frontend.messages.deleted", JSONModelI18nWrapper.new(:prdcl_title => prdcl_title)) redirect_to(:controller => :prdcl_titles, :action => :index, :deleted_uri => prdcl_title.uri) end end <file_sep>/backend/model/agent_person_ext.rb AgentPerson.include(MailingLists) AgentPerson.include(Militarys) AgentPerson.include(Civilians) AgentPerson.include(FriendsMemberships) AgentPerson.include(Staffs)<file_sep>/backend/controllers/prdcl_title.rb class ArchivesSpaceService < Sinatra::Base Endpoint.post('/prdcl_titles/:id') .description("Update a Periodical Title") .params(["id", :id], ["prdcl_title", JSONModel(:prdcl_title), "The updated record", :body => true]) .permissions([:update_prdcl_title_record]) .returns([200, :updated]) \ do handle_update(PrdclTitle, params[:id], params[:prdcl_title]) end Endpoint.post('/prdcl_titles') .description("Create a Periodical Title") .params(["prdcl_title", JSONModel(:prdcl_title), "The record to create", :body => true]) .permissions([:update_prdcl_title_record]) .returns([200, :created]) \ do handle_create(PrdclTitle, params[:prdcl_title]) end Endpoint.get('/prdcl_titles') .description("Get a list of Periodical Titles") .params() .paginated(true) .permissions([]) .returns([200, "[(:prdcl_title)]"]) \ do handle_listing(PrdclTitle, params) end Endpoint.get('/prdcl_titles/:id') .description("Get a Periodical Title by ID") .params(["id", :id]) .permissions([]) .returns([200, "(:prdcl_title)"]) \ do json_response(PrdclTitle.to_jsonmodel(params[:id])) end Endpoint.delete('/prdcl_titles/:id') .description("Delete a Periodical Title") .params(["id", :id]) .permissions([:update_prdcl_title_record]) .returns([200, :deleted]) \ do handle_delete(PrdclTitle, params[:id]) end end <file_sep>/backend/model/audiovisual.rb class Audiovisual < Sequel::Model(:audiovisual) include ASModel corresponds_to JSONModel(:audiovisual) set_model_scope :global end <file_sep>/backend/model/map_sub.rb class MapSub < Sequel::Model(:map_sub) include ASModel corresponds_to JSONModel(:map_sub) set_model_scope :global end <file_sep>/backend/model/inventory_doc.rb class InventoryDoc < Sequel::Model(:inventory_doc) include ASModel corresponds_to JSONModel(:inventory_doc) set_model_scope :global end <file_sep>/backend/model/ohstat.rb class Ohstat < Sequel::Model(:ohstat) include ASModel corresponds_to JSONModel(:ohstat) set_model_scope :repository end <file_sep>/backend/model/mixins/inventorys.rb module Inventorys def self.included(base) base.one_to_many :inventory base.def_nested_record(:the_property => :inventorys, :contains_records_of_type => :inventory, :corresponding_to_association => :inventory) end end <file_sep>/backend/model/mixins/prdcls.rb module Prdcls def self.included(base) base.one_to_many :prdcl base.def_nested_record(:the_property => :prdcls, :contains_records_of_type => :prdcl, :corresponding_to_association => :prdcl) end end <file_sep>/indexer/periodical_indexer.rb class CommonIndexer @@record_types << :prdcl_title @@global_types << :prdcl_title self.add_indexer_initialize_hook do |indexer| indexer.add_document_prepare_hook {|doc, record| if doc['primary_type'] == 'digital_object' if record['record']['prdcls'] && record['record']['prdcls'].length > 0 doc['prdcl_title_uris'] = record['record']['prdcls']. collect{|prdcl| prdcl["ref"]}.uniq end end if doc['primary_type'] == 'prdcl_title' doc['title'] = record['record']['title'] end } end end
2abb7b62a3490c6f6ef9eb55f327feffe4bfc708
[ "JavaScript", "Ruby" ]
52
Ruby
vncaMichaelD/periodical
bcfe6b6445f52d32688067dd84d4fc16b327b34d
99ccab51ee39dc27b63099d25563abc46bb76e80
refs/heads/master
<repo_name>thekiear/RPS-BOT<file_sep>/Sample/rock.py # rock bot output = "R"<file_sep>/referee/match/api.py # myapp/api.py from tastypie.resources import ModelResource from match.models import Match, UserProfile, User, MatchRequest class MatchRequestResource(ModelResource): class Meta: queryset = MatchRequest.objects.all() resource_name = 'matchRequest' class MatchResource(ModelResource): class Meta: queryset = Match.objects.all() resource_name = 'match' class UserProfileResource(ModelResource): class Meta: queryset = UserProfile.objects.all() resource_name = 'userProfile' class UserResource(ModelResource): class Meta: queryset = User.objects.all() resource_name = 'user'<file_sep>/Sample/Goats/superlists/lists/models.py from django.db import models class Item(models.Model): text = models.TestField() # Create your models here. <file_sep>/referee/referee/urls.py from django.conf.urls import patterns, include, url from django.contrib import admin from match.api import MatchResource, UserProfileResource, UserResource, MatchRequestResource from tastypie.api import Api admin.autodiscover() v1_api = Api(api_name='v1') v1_api.register(UserProfileResource()) v1_api.register(MatchResource()) v1_api.register(UserResource()) v1_api.register(MatchRequestResource()) urlpatterns = patterns('', # Examples: # url(r'^$', 'referee.views.home', name='home'), # url(r'^blog/', include('blog.urls')), #url(r'^player/', 'player.views.home', name='player_app_home'), url(r'^match/', 'match.views.home_page', name="match_home"), url(r'^matchRequest/', 'match.views.join_match', name="join_match"), url(r'^register/$','match.views.register', name='register'), url(r'^$', 'match.views.register', name="root_page"), url(r'^api/', include(v1_api.urls)), ) <file_sep>/docs/index.rst --README.rst This program is going to consist of 2 parts: brain A python program that plays rock paper scissors bot An arduino based robot hand that will be controlled by the brain.<file_sep>/referee/match/tests.py from django.core.urlresolvers import resolve from django.http import HttpRequest from django.template.loader import render_to_string from django.test import TestCase from match.views import home_page class HomePageTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve('/match/') self.assertEqual(found.func, home_page) def test_home_page_returns_correct_html(self): request = HttpRequest() response = home_page(request) expected_html = render_to_string('home.html') self.assertEqual(response.content.decode(), expected_html) def test_home_page_can_save_a_POST_request(self): request = HttpRequest() request.method = 'POST' player_name = 'justin' request.POST['username'] = player_name request.POST['role'] = 'player' request.POST['callback'] = 'http://localhost/player1/' response = home_page(request) self.assertIn(player_name, response.content.decode())<file_sep>/referee/match/models.py from django.contrib.auth.models import User from django.db import models from django.utils.text import slugify from tastypie.utils.timezone import now class UserProfile(models.Model): # This line is required. Links UserProfile to a User model instance. user = models.OneToOneField(User) # The additional attributes we wish to include. callback_url = models.URLField(blank=True) # Override the __unicode__() method to return out something meaningful! def __unicode__(self): return self.user.username class Match(models.Model): players = models.ManyToManyField(User) # player2 = models.ForeignKey(User) pub_date = models.DateTimeField(default=now) slug = models.SlugField() body = models.TextField() def __unicode__(self): return self.body def save(self, *args, **kwargs): # For automatic slug generation. if not self.slug: self.slug = slugify(self.body)[:50] return super(Entry, self).save(*args, **kwargs) class MatchRequest(models.Model): player = models.OneToOneField(UserProfile) pub_date = models.DateTimeField(default=now) def __unicode__(self): return "this is a matcherequest"<file_sep>/Sample/bots/random.py # random bot import random output = random.choice(["R","P","S"])<file_sep>/referee/referee/test.py #this test should confirm that players can register <file_sep>/bot/demo.py #!/usr/bin/python print "Hello Would you like to play Rock Paper Scissors?" <file_sep>/notes/modular_approach.rst a modular approach to rock paper scissors write 2 python programs, a ref and a player REF rps-ref is a web app that exposes a REST api It allows people (or bots) to register as players or fans BOT rps-bot is a separate web-app that wraps an rpscontest bot it has its own rest api for ref to post to it posts to ref api REF endpoints: referee/register POST to this with: your status (player/fan) your name callback url returns: url to match (referee/match/<uuid>/) referee/match/<uuid>/ready POST to this with: player name returns: accepted 201 when both players have sent ready, ref will post to each bot with match uuid and a throw uuid (unique to each bot) ref will also post to fans a match uuid to say match is beginning match/<uuid>/throw/<uuid> POST to this with: throw (rock, paper, scissors, forfeit) returns: accepted once both bots have sent throws, ref will post to each bots callback url: matchresult (opponent throw, your throw, winner, opponent wins, ties, your wins) ref will post matchresult to fans callback urls as well This allows both bots and fans to control hardware with matchresults as they see fit. some links: http://www.bbc.com/news/technology-24803751 http://www.nytimes.com/interactive/science/rock-paper-scissors.html?_r=0 http://www.rpscontest.com/
ed9c7bf2f31c5c3ea3436ddbc1dc943fa694e1bb
[ "Python", "reStructuredText" ]
11
Python
thekiear/RPS-BOT
832919cf105e9d4e8922e2c73bda6cfabaea044a
ce3d040f9a8f8f9446679aa4460840b50c7d9d53