images
images listlengths
1
1
texts
listlengths
1
1
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_C_>/*\n * Copyright 2016-2017 The OpenSSL Project Authors. All Rights Reserved.\n *\n * Licensed under the OpenSSL license (the \"License\"). You may not use\n * this file except in compliance with the License. You can obtain a copy\n * in the file LICENSE in the source distribution or at\n * https://www.openssl.org/source/license.html\n */\n\n#include <string.h>\n#include \"../ssl_locl.h\"\n#include \"statem_locl.h\"\n\nstatic int final_renegotiate(SSL *s, unsigned int context, int sent,\n int *al);</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_SQL_>SELECT b.lower_username username, a.SUCCESSDATE lastlogin \r\nFROM dbo.logininfo a, dbo.user_mapping b \r\nwhere b.user_key = a.USERNAME and a.SUCCESSDATE < '2015-01-01' \r\norder by a.SUCCESSDATE desc; \r\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_TypeScript_>import { Inject } from '@nestjs/common';\nimport { BOOT } from '@nestcloud/common';\n\nexport const InjectBoot = () => Inject(BOOT);\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_JavaScript_>import {Divide} from 'yo-design-vue';\nVue.use(Divide);</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Python_>import numpy as np\nimport sys\nread = sys.stdin.buffer.read\nreadline = sys.stdin.buffer.readline\nreadlines = sys.stdin.buffer.readlines\n\nn = int(readline())\na = np.array(readline().split(), dtype=np.int32)\nb = np.array(readline().split(), dtype=np.int32)\nc = np.array(readline().split(), dtype=np.int32)\n\na.sort()\nb.sort()\nc.sort()\n\ncnt_a = np.searchsorted(a, b, side='left')\ncnt_c = np.searchsorted(c, -b, side='left')\n \nanswer = (cnt_a * cnt_c).sum()\nprint(answer)\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Python_>a,b,c,d = map(int,input().split())\nif abs(a-b) <= d and abs(b-c) <= d:\n print(\"Yes\")\nelse:\n print(\"No\")\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Go_>// Copyright 2009 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Package printer implements printing of AST nodes.\npackage printer\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/tabwriter\"\n\t\"unicode\"\n\n\t\"github.com/gowasm/gox/ast\"\n\t\"github.com/gowasm/gox/token\"\n)\n\nconst (\n\tmaxNewlines = 2 // max. number of newlines between source text\n\tdebug = false // enable for debugging\n\tinfinity = 1 << 30\n)\n\ntype whiteSpace byte\n\nconst (\n\tignore = whiteSpace(0)\n\tblank = whiteSpace(' ')</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Java_>package io.quarkus.vertx.http.runtime;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InterruptedIOException;\nimport java.nio.channels.ClosedChannelException;\nimport java.util.ArrayDeque;\nimport java.util.Deque;\n\nimport io.netty.buffer.ByteBuf;\nimport io.netty.handler.codec.http.HttpHeaderNames;\nimport io.netty.handler.codec.http.HttpResponseStatus;\nimport io.vertx.core.Context;\nimport io.vertx.core.Handler;\nimport io.vertx.core.buffer.Buffer;\nimport io.vertx.core.http.HttpHeaders;\nimport io.vertx.core.http.HttpServerRequest;\nimport io.vertx.core.http.HttpServerResponse;\nimport io.vertx.core.net.impl.ConnectionBase;\nimport io.vertx.ext.web.RoutingContext;\n\npublic class VertxInputStream extends InputStream {\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_C++_> showRestartWarning(true);\n\n QString strLabel = model->getOverriddenByCommandLine();\n if (strLabel.isEmpty())\n strLabel = tr(\"none\");\n ui->overriddenByCommandLineLabel->setText(strLabel);\n\n mapper->setModel(model);\n setMapper();\n mapper->toFirst();\n\n updateDefaultProxyNets();\n }\n\n /* warn when one of the following settings changes by user action (placed here so init via mapper doesn't trigger them) */\n\n /* Main */\n connect(ui->databaseCache, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));\n connect(ui->threadsScriptVerif, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));\n /* Wallet */\n connect(ui->showMasternodesTab, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));\n connect(ui->spendZeroConfChange, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));\n /* Network */\n connect(ui->allowIncoming, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));\n connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));\n connect(ui->connectSocksTor, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));\n /* Display */\n connect(ui->digits, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));\n connect(ui->theme, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));\n connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));\n connect(ui->thirdPartyTxUrls, SIGNAL(textChanged(const QString &)), this, SLOT(showRestartWarning()));\n}\n\nvoid OptionsDialog::setMapper()\n{\n /* Main */\n mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);\n mapper->addMapping(ui->threadsScriptVerif, OptionsModel::ThreadsScriptVerif);\n mapper->addMapping(ui->databaseCache, OptionsModel::DatabaseCache);\n\n /* Wallet */\n mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);\n mapper->addMapping(ui->showMasternodesTab, OptionsModel::ShowMasternodesTab);</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_C#_>/*\r\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r\n * \r\n * Licensed under the Apache License, Version 2.0 (the \"License\").\r</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Scala_>package com.htmlism\npackage http\n\nimport io.netty.channel.{ ChannelHandlerContext, SimpleChannelInboundHandler }\nimport io.netty.handler.codec.http._\n\nclass HttpHandler extends SimpleChannelInboundHandler[HttpRequest] {\n def channelRead0(ctx: ChannelHandlerContext, msg: HttpRequest): Unit =\n forEffect {\n val response =\n new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK)\n\n response\n .headers()\n// .add(HttpHeaderNames.DATE, \"asdf \\\", , , ,, \")\n\n ctx\n .writeAndFlush(response)\n\n ctx\n .close()\n }\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_SQL_>create index \"DELETED_ROUTES_DELETED_AT_IDX\" on \"DELETED_ROUTES\" (\"DELETED_AT\");\n\ncreate index \"PATHS_UPDATED_AT_IDX\" on \"PATHS\" (\"UPDATED_AT\");\n\ncreate index \"ROUTES_UPDATED_AT_IDX\" on \"ROUTES\" (\"UPDATED_AT\");\ncreate index \"ROUTES_ACTIVATE_AT_IDX\" on \"ROUTES\" (\"ACTIVATE_AT\");\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_JavaScript_>//Opgave I\r\nfunction OBJpersoon (achternaam,tussenvoegsel,voornaam){\r\n let newForm = this;\r\n newForm.Achternaam = achternaam;\r\n newForm.Tussenvoegsel = tussenvoegsel;\r\n newForm.Voornaam = voornaam;\r\n}\r\n\r\nlet student = new OBJpersoon (\"Andrade \",\"\",\" Leroy\");\r\n//typeof(student.Studentnummer);\r\n\r\n\r\nlet forIn=\"\";\r\nfor (const property in student) {\r\nforIn+=(`${property}: ${student[property]}`+'<br/>');\r\n}document.write(\"Opgave 1\" +'<br/>'+ forIn);\r\n\r\n\r\n//Opgave II\r\nfunction OBJboek (titel,isbn,druk,jaar,auteur,type,korting){\r\n let OBJBoek = this;\r\n OBJBoek.Titel = titel.toUpperCase();\r\n OBJBoek.Isbn = isbn;\r\n OBJBoek.Druk = druk;\r\n OBJBoek.Jaar = jaar;\r\n OBJBoek.Auteur = auteur;\r\n OBJBoek.Type = type;\r\n OBJBoek.Korting = korting;\r\n}\r\nlet forIn2=\"\";\r\nlet boek = new OBJboek (\"The Adventures of Tom Sawyer\",\"ISBN-13: 978-0553211283\",\"1\", 1876, \"Mark Twain\", \"Fictie\", \"10%\");\r\nfor (const property in boek) {\r\nforIn2+=(`${property}: ${boek[property]}`+'<br/>');\r\n}document.write('<br/>'+\"Opgave 2\" +'<br/>'+ '<form>'+'<td>'+forIn2+'</td>'+ '</form>');\r\n\r\n\r\n//Opgave III\r\nfunction bluePrintVoertuig (merknaam,model,gewicht,motorinhoud,kleur){\r\n let bluePrintVoertuig = this;\r\n bluePrintVoertuig.Merknaam = merknaam;\r\n bluePrintVoertuig.Model = model;\r\n bluePrintVoertuig.Gewicht = gewicht;\r\n bluePrintVoertuig.MotorInhoud = motorinhoud;\r\n bluePrintVoertuig.Kleur = kleur;\r\n}\r\n\r\nlet forIn3=\"\";\r\nlet voertuig1 = new bluePrintVoertuig(\"Ferrari\", 'ENZO', '1,480 kg', '6L V12', 'Rood');\r\nfor (const property in voertuig1) {\r\nforIn3+=(`${property}: ${voertuig1[property]}`+'<br/>');\r\n}document.write('<br/>'+\"Opgave 3\" +'<br>'+forIn3);\r\n\r\n//Opgave III.I\r\nlet forIn31=\"\";\r\nlet voertuig2 = new bluePrintVoertuig(\"theFuture\", 'Grande', '1,481 kg', '33L V12 + Efficiënt appart Hybrid en Energy Recovery System tijdens remmen', 'Groen');\r\nfor (const property in voertuig2) {\r\nforIn31+=(`${property}: ${voertuig1[property]}`+'<br/>');\r\n}document.write('<br/>'+\"Opgave 3.1\" +'<br>'+forIn31);\r\n\r\n\r\n//Opgave IV\r\nfunction OBJStudent (studentnummer,naam,klasnaam,opleiding){\r\n let newStudent = this;\r\n newStudent.Studentnummer = studentnummer;\r\n newStudent.Naam = naam;\r\n newStudent.Klasnaam = klasnaam;\r\n newStudent.Opleiding = opleiding;\r\n}\r\n\r\nlet student2 = new OBJStudent (123,\"Pietje Puk\",\"MD1A\", \"Mediadevelopment\");\r\nlet student3 = new OBJStudent (1234,\"Pietje Puki\",\"MD1B\", \"Mediadevelopment\");\r\n/*foreach item, lukt mij niet op het moment*/\r\nlet student2Arr = [student2.Studentnummer,student2.Naam,student2.Klasnaam,student2.Opleiding +'<br>'];\r\nlet student3Arr = [student3.Studentnummer+student3.Naam,student3.Klasnaam,student3.Opleiding];\r\n\r\nlet storeArr = student2Arr.concat(student3Arr);\r\n//document.write('<br/>'+\"Opgave 4\"+'<br/>');\r\ndocument.write('<br/>'+\"Opgave 4\"+'<br/>'+storeArr);\r\n\r\n\r\n\r\n//let boek = new OBJBoek (\"\");\r\n//Opgave V\r\nfunction OBJLessen (studentnummer,klasnaam,opleiding,lessen){\r\n let OBJLessen = this;\r\n OBJLessen.Studentnummer = studentnummer;\r</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Ruby_>Airbrake.configure do |config|\n config.host = ENV['airbrake_host']\n config.project_id = ENV['airbrake_project_id']\n config.project_key = ENV['airbrake_project_key']\n config.root_directory = Rails.root\n config.logger =\n if ENV['RAILS_LOG_TO_STDOUT'].present?\n Logger.new(STDOUT, level: Rails.logger.level)\n else\n Logger.new(\n Rails.root.join('log', 'airbrake.log'),\n level: Rails.logger.level\n )\n end\n config.environment = ENV['airbrake_env'] || Rails.env\n config.ignore_environments = %w[test]\n config.blacklist_keys = Rails.application.config.filter_parameters\nend\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_C++_>/*\n * Copyright (C) 2021 Huawei Device Co., Ltd.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include <gtest/gtest.h>\n#include \"libmmi_util.h\"\n#include \"knuckle_func_proc.h\"\n#include \"proto.h\"\n\nnamespace {\nusing namespace testing::ext;\nusing namespace OHOS::MMI;\n\n class KnuckleFuncProcTest : public testing::Test {\n public:\n static void SetUpTestCase(void) {}\n static void TearDownTestCase(void) {}\n };\n\n HWTEST_F(KnuckleFuncProcTest, Test_DeviceEventDispatchProcess_001, TestSize.Level1)\n {\n KnuckleFuncProc knuckleServer;\n const RawInputEvent event = { 0, 0, 0, 0 };\n int32_t retResult = knuckleServer.DeviceEventDispatchProcess(event);\n EXPECT_TRUE(retResult == RET_ERR);\n }\n\n HWTEST_F(KnuckleFuncProcTest, Test_GetDevType_001, TestSize.Level1)\n {\n KnuckleFuncProc knuckleServer;\n int32_t retResult = knuckleServer.GetDevType();\n EXPECT_EQ(retResult, static_cast<int32_t>(INPUT_DEVICE_CAP_KNUCKLE));\n }\n\n HWTEST_F(KnuckleFuncProcTest, Test_CheckEventCode_001, TestSize.Level1)\n {\n KnuckleFuncProc knuckleServer;\n RawInputEvent event = { };\n event.ev_code = static_cast<uint32_t>(MmiMessageId::ON_SCREEN_SHOT);\n int32_t retResult = knuckleServer.CheckEventCode(event);\n EXPECT_TRUE(retResult == RET_OK);\n }\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_SQL_>-- file:collate.sql ln:94 expect:true\nCREATE VIEW collview1 AS SELECT * FROM collate_test1 WHERE b COLLATE \"C\" >= 'bbc'\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Haskell_>import Data.List (subsequences)\n\nmain:: IO ()\nmain = do\n [n,p] <- (map read . words) <$> getLine\n as <- (map read . words) <$> getLine\n print $ solve p as\n\n-- |\n--\n-- >>> solve 0 [1,3]\n-- 2\n--\nsolve :: Int -> [Int] -> Int\nsolve p = length . filter f . subsequences\n where f xs = sum xs `mod` 2 == p\n\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_C_>#include <stdio.h>\n#include <math.h>\n\nint main(){\n\tint n,i,pt=0,ph=0;\n\tchar ct[101],ch[101];\n\tscanf(\"%d\",&n);\n\tfor (i=0;i<n;i++){\n\t\tscanf(\"%s %s\",&ct,&ch);\n\t\tif (strcmp(ct,ch)>0){\n\t\t\tpt+=3;\n\t\t}else if (strcmp(ct,ch)<0){\n\t\t\tph+=3;\n\t\t}else{\n\t\t\tpt++;ph++;\n\t\t}\n\t}\n\tprintf(\"%d %d\\n\",pt,ph);\n\treturn 0;\n}\t</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_JavaScript_>import React, {useState} from 'react';\nimport CategoryItem from './CategoryItem';\nimport CategoryModal from './CategoryModal';\nimport DatePicker from 'react-native-date-picker';\nimport {Link} from 'react-router-native';\nimport {readTime, readDate} from '../utils/auth';\nimport Icon from 'react-native-vector-icons/dist/FontAwesome';\nIcon.loadFont();\nimport {\n View,\n SafeAreaView,\n TouchableOpacity,\n Text,\n TextInput,\n StyleSheet,\n FlatList,\n} from 'react-native';\n\nconst CreateForm = ({setProj, selectedProject, editProject}) => {\n const [open, setOpen] = useState(false);\n const [openModal, setOpenModal] = useState(false);\n const [time, setTime] = useState(\n selectedProject ? selectedProject.time : new Date(),\n );\n const [date, setDate] = useState(\n selectedProject ? selectedProject.date : new Date(),\n );\n const [selectedCategory, setSelectedCategory] = useState(\n selectedProject\n ? selectedProject.category\n : {\n id: 0,\n name: 'Work',\n categoryColor: '#2EA7BD',\n },\n );\n const [title, setTitle] = useState(\n selectedProject ? selectedProject.title : '',\n );\n const [desc, setDesc] = useState(selectedProject ? selectedProject.desc : '');\n const [categoryName, setCategoryName] = useState('');\n const [categories, setCategories] = useState(\n selectedProject\n ? [selectedProject.category]\n : [\n {\n id: 0,\n name: 'Work',\n categoryColor: '#2EA7BD',\n },\n {\n id: 1,\n name: 'Home',\n categoryColor: '#F58B00',\n },\n {\n id: 2,\n name: 'Health',\n categoryColor: '#1ec337',\n },\n ],\n );\n\n const onCreateProjPress = () => {\n let obj = {\n id: Math.random(),\n title: title,\n date: date,\n time: time,\n desc: desc,\n category: selectedCategory,\n tasks: [],\n complete: false,\n timestamp: new Date(),\n };\n setProj(obj);\n };\n\n const onEditProjPress = () => {\n let obj = {\n id: selectedProject.id,\n title: title,\n date: date,\n time: time,\n desc: desc,\n category: selectedCategory,\n tasks: selectedProject.tasks,\n complete: false,\n timestamp: selectedProject.timestamp,\n };\n editProject(obj);\n };\n\n const renderCategories = ({item}) => (\n <CategoryItem\n setSelectedCategory={setSelectedCategory}\n category={item}\n selectedCategory={selectedCategory}\n />\n );\n\n const onPlusPress = () => {\n setOpenModal(true);\n setCategoryName('');\n };\n return (\n <SafeAreaView style={styles.container}>\n <View style={styles.titleContainer}>\n <Text style={styles.header}>Title</Text>\n <View style={styles.inputContainer}>\n <TextInput\n style={styles.titleInput}\n placeholder=\"Your Project's Title\"\n placeholderTextColor=\"grey\"\n onChangeText={setTitle}\n value={title}\n maxLength={28}\n />\n <Icon\n name=\"times\"\n size={24}\n color=\"#d3d3d3\"\n onPress={() => setTitle('')}\n />\n </View>\n </View>\n\n <View>\n <Text style={styles.header}>Deadline</Text>\n <View style={styles.whenContainer}>\n <TouchableOpacity\n onPress={() => setOpen(true)}\n style={styles.dateContainer}>\n <View style={styles.inputContainer}>\n <Text style={styles.whenText}>{readDate(date)}</Text>\n <DatePicker\n timeZoneOffsetInMinutes={-420}\n minimumDate={new Date()}\n modal\n mode=\"datetime\"\n open={open}\n date={date}\n onConfirm={date => {\n setOpen(false);\n setDate(date);\n }}\n onCancel={() => {\n setOpen(false);\n }}\n />\n <Icon\n name=\"calendar\"\n size={20}\n color=\"#00c7be\"\n style={{marginBottom: 6}}\n />\n </View></code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_C#_>using System;\nusing System.Collections.Generic;\n\nnamespace Altinn.Platform.Storage.Configuration\n{\n /// <summary>\n /// Configuration object used to hold general settings for the storage application.\n /// </summary>\n public class GeneralSettings\n {\n /// <summary>\n /// Open Id Connect Well known endpoint. Related to JSON WEB token validation.\n /// </summary>\n public string OpenIdWellKnownEndpoint { get; set; }\n\n /// <summary>\n /// Hostname\n /// </summary>\n public string Hostname { get; set; }\n\n /// <summary>\n /// Name of the cookie for runtime\n /// </summary>\n public string RuntimeCookieName { get; set; }\n\n /// <summary>\n /// Gets or sets the URI for the SBL Bridge Authorization API.\n /// </summary>\n public Uri BridgeApiAuthorizationEndpoint { get; set; }\n\n /// <summary>\n /// Gets or sets the scopes for Instance Read.\n /// </summary>\n public List<string> InstanceReadScope { get; set; }\n\n /// <summary>\n /// Gets or sets the cache lifetime for text resources.\n /// </summary>\n public int TextResourceCacheLifeTimeInSeconds { get; set; }\n\n /// <summary>\n /// Gets or sets the cache lifetime for application title dictionary.\n /// </summary>\n public int AppTitleCacheLifeTimeInSeconds { get; set; }\n\n /// <summary>\n /// Gets or sets the cache lifetime for application metadata document.\n /// </summary>\n public int AppMetadataCacheLifeTimeInSeconds { get; set; }\n }\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Rust_>use std::fs::OpenOptions;\nuse std::io::{prelude::*, stdout};\nuse std::path::Path;\nuse std::process::{self, Command};\n\nuse docopt::Docopt;\nuse rsgen_avro::{Generator, Source};\nuse serde::Deserialize;\n\nconst VERSION: &'static str = env!(\"CARGO_PKG_VERSION\");\n\nconst USAGE: &'static str = \"\nUsage:\n rsgen-avro [options] <schema-file-or-dir> <output-file>\n rsgen-avro (-h | --help)\n rsgen-avro (-V | --version)\n\nOptions:\n --fmt Run rustfmt on the resulting <output-file>\n --nullable Replace null fields with their default value\n when deserializing.\n --precision=P Precision for f32/f64 default values\n that aren't round numbers [default: 3].\n -V, --version Show version.\n -h, --help Show this screen.\n\";\n\n#[derive(Debug, Deserialize)]\nstruct CmdArgs {\n arg_schema_file_or_dir: String,\n arg_output_file: String,\n flag_fmt: bool,\n flag_nullable: bool,\n flag_precision: Option<usize>,\n flag_version: bool,\n}\n\nfn main() {\n let args: CmdArgs = Docopt::new(USAGE)\n .and_then(|d| d.deserialize())\n .unwrap_or_else(|e| e.exit());\n\n if args.flag_version {\n println!(\"{}\", VERSION);\n process::exit(0);\n }\n\n let p = Path::new(&args.arg_schema_file_or_dir);\n if !p.exists() {\n eprintln!(\"Doesn't exist: {:?}\", p);\n process::exit(1);\n }\n\n let source = if p.is_dir() {\n Source::DirPath(p)\n } else {\n Source::FilePath(p)\n };\n\n let mut out: Box<dyn Write> = if &args.arg_output_file == \"-\" {\n Box::new(stdout())\n } else {\n Box::new(\n OpenOptions::new()\n .write(true)\n .create(true)\n .truncate(true)\n .open(&args.arg_output_file)\n .unwrap_or_else(|e| {\n eprintln!(\"Output file error: {}\", e);\n process::exit(1);\n }),\n )\n };\n\n let g = Generator::builder()\n .precision(args.flag_precision.unwrap())\n .nullable(args.flag_nullable)\n .build()\n .unwrap_or_else(|e| {\n eprintln!(\"Problem during prepartion: {}\", e);\n process::exit(1);\n });\n\n g.gen(&source, &mut out).unwrap_or_else(|e| {\n eprintln!(\"Problem during code generation: {}\", e);\n process::exit(1);\n });\n\n if args.flag_fmt && &args.arg_output_file != \"-\" {\n Command::new(\"rustfmt\")\n .arg(&args.arg_output_file)\n .status()\n .unwrap_or_else(|e| {\n eprintln!(\"Problem with rustfmt: {}\", e);\n process::exit(1);\n });\n }\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Kotlin_>package uz.boywonder.simplemvvmnewsapp.features.bookmarks\n\nimport androidx.lifecycle.ViewModel\nimport androidx.lifecycle.viewModelScope\nimport dagger.hilt.android.lifecycle.HiltViewModel\nimport kotlinx.coroutines.flow.SharingStarted\nimport kotlinx.coroutines.flow.stateIn\nimport kotlinx.coroutines.launch</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Python_>s = input()\nt = input()\n\nsDash = sorted(s)\ntDash = sorted(t, reverse=True)\n\n\ndef checkAlphabetOrder(a, b):\n temp = [a, b]\n compare = sorted(temp)\n return temp[0] == compare[0]\n\n\n# main\nfor i in range(min(len(s), len(t))):\n if sDash[i] == tDash[i]: continue\n elif checkAlphabetOrder(sDash[i], tDash[i]):\n print('Yes')\n break\n else:\n print('No')\n break\nelse:\n if len(s) < len(t):\n print('Yes')\n else:\n print('No')</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_ObjectiveC_>/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#import \"ABI40_0_0RCTActivityIndicatorViewComponentView.h\"\n\n#import <ABI40_0_0React/components/rncore/ComponentDescriptors.h>\n#import <ABI40_0_0React/components/rncore/EventEmitters.h>\n#import <ABI40_0_0React/components/rncore/Props.h>\n\n#import \"ABI40_0_0FBABI40_0_0RCTFabricComponentsPlugins.h\"\n\nusing namespace ABI40_0_0facebook::ABI40_0_0React;\n\nstatic UIActivityIndicatorViewStyle convertActivityIndicatorViewStyle(const ActivityIndicatorViewSize &size)\n{\n switch (size) {\n case ActivityIndicatorViewSize::Small:\n return UIActivityIndicatorViewStyleWhite;\n case ActivityIndicatorViewSize::Large:\n return UIActivityIndicatorViewStyleWhiteLarge;\n }\n}\n\n@implementation ABI40_0_0RCTActivityIndicatorViewComponentView {\n UIActivityIndicatorView *_activityIndicatorView;\n}\n\n#pragma mark - ABI40_0_0RCTComponentViewProtocol\n\n+ (ComponentDescriptorProvider)componentDescriptorProvider\n{\n return concreteComponentDescriptorProvider<ActivityIndicatorViewComponentDescriptor>();\n}\n\n- (instancetype)initWithFrame:(CGRect)frame\n{\n if (self = [super initWithFrame:frame]) {\n static const auto defaultProps = std::make_shared<const ActivityIndicatorViewProps>();\n _props = defaultProps;\n\n _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithFrame:self.bounds];\n _activityIndicatorView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;\n\n if (defaultProps->animating) {\n [_activityIndicatorView startAnimating];\n } else {\n [_activityIndicatorView stopAnimating];\n }\n _activityIndicatorView.color = [UIColor colorWithCGColor:defaultProps->color.get()];\n _activityIndicatorView.hidesWhenStopped = defaultProps->hidesWhenStopped;\n _activityIndicatorView.activityIndicatorViewStyle = convertActivityIndicatorViewStyle(defaultProps->size);\n\n [self addSubview:_activityIndicatorView];\n }\n\n return self;\n}\n\n- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps\n{\n const auto &oldViewProps = *std::static_pointer_cast<const ActivityIndicatorViewProps>(_props);\n const auto &newViewProps = *std::static_pointer_cast<const ActivityIndicatorViewProps>(props);\n\n if (oldViewProps.animating != newViewProps.animating) {\n if (newViewProps.animating) {\n [_activityIndicatorView startAnimating];\n } else {\n [_activityIndicatorView stopAnimating];\n }\n }\n\n if (oldViewProps.color.get() != newViewProps.color.get()) {\n _activityIndicatorView.color = [UIColor colorWithCGColor:newViewProps.color.get()];\n }\n\n // TODO: This prop should be deprecated.\n if (oldViewProps.hidesWhenStopped != newViewProps.hidesWhenStopped) {\n _activityIndicatorView.hidesWhenStopped = newViewProps.hidesWhenStopped;\n }\n\n if (oldViewProps.size != newViewProps.size) {\n _activityIndicatorView.activityIndicatorViewStyle = convertActivityIndicatorViewStyle(newViewProps.size);\n }\n\n [super updateProps:props oldProps:oldProps];\n}\n\n@end\n\nClass<ABI40_0_0RCTComponentViewProtocol> ABI40_0_0RCTActivityIndicatorViewCls(void)\n{\n return ABI40_0_0RCTActivityIndicatorViewComponentView.class;\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_C++_>/**\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with this\n * work for additional information regarding copyright ownership. The ASF\n * licenses this file to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance with the\n * License. You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n#include \"ppl/cv/cuda/split.h\"\n\n#include <tuple>\n#include <sstream>\n\n#include \"opencv2/core.hpp\"\n#include \"gtest/gtest.h\"\n\n#include \"utility/infrastructure.hpp\"\n\nusing Parameters = std::tuple<cv::Size>;\ninline std::string convertToString(const Parameters& parameters) {\n std::ostringstream formatted;\n\n cv::Size size = std::get<0>(parameters);\n formatted << size.width << \"x\";\n formatted << size.height;\n\n return formatted.str();\n}\n\ntemplate <typename T, int channels>\nclass PplCvCudaSplitTest : public ::testing::TestWithParam<Parameters> {\n public:\n PplCvCudaSplitTest() {\n const Parameters& parameters = GetParam();\n size = std::get<0>(parameters);\n }\n\n ~PplCvCudaSplitTest() {\n }\n\n bool apply();\n\n private:\n cv::Size size;\n};\n\ntemplate <typename T, int channels>\nbool PplCvCudaSplitTest<T, channels>::apply() {\n cv::Mat src;\n src = createSourceImage(size.height, size.width,\n CV_MAKETYPE(cv::DataType<T>::depth, channels));\n cv::Mat dst0(size.height, size.width, CV_MAKETYPE(cv::DataType<T>::depth, 1));\n cv::Mat dst1(size.height, size.width, CV_MAKETYPE(cv::DataType<T>::depth, 1));\n cv::Mat dst2(size.height, size.width, CV_MAKETYPE(cv::DataType<T>::depth, 1));\n cv::Mat dst3(size.height, size.width, CV_MAKETYPE(cv::DataType<T>::depth, 1));\n cv::Mat cv_dst0(size.height, size.width,\n CV_MAKETYPE(cv::DataType<T>::depth, 1));\n cv::Mat cv_dst1(size.height, size.width,\n CV_MAKETYPE(cv::DataType<T>::depth, 1));\n cv::Mat cv_dst2(size.height, size.width,\n CV_MAKETYPE(cv::DataType<T>::depth, 1));\n cv::Mat cv_dst3(size.height, size.width,\n CV_MAKETYPE(cv::DataType<T>::depth, 1));\n cv::cuda::GpuMat gpu_src(src);\n cv::cuda::GpuMat gpu_dst0(dst0);\n cv::cuda::GpuMat gpu_dst1(dst1);\n cv::cuda::GpuMat gpu_dst2(dst2);\n cv::cuda::GpuMat gpu_dst3(dst3);\n\n int src_size = size.height * size.width * channels * sizeof(T);\n int dst_size = size.height * size.width * sizeof(T);\n T* input = (T*)malloc(src_size);\n T* output0 = (T*)malloc(dst_size);\n T* output1 = (T*)malloc(dst_size);\n T* output2 = (T*)malloc(dst_size);\n T* output3 = (T*)malloc(dst_size);\n T* gpu_input;\n T* gpu_output0;\n T* gpu_output1;\n T* gpu_output2;\n T* gpu_output3;\n cudaMalloc((void**)&gpu_input, src_size);\n cudaMalloc((void**)&gpu_output0, dst_size);\n cudaMalloc((void**)&gpu_output1, dst_size);\n cudaMalloc((void**)&gpu_output2, dst_size);\n cudaMalloc((void**)&gpu_output3, dst_size);\n copyMatToArray(src, input);\n cudaMemcpy(gpu_input, input, src_size, cudaMemcpyHostToDevice);\n\n if (channels == 3) {\n cv::Mat dsts[3] = {cv_dst0, cv_dst1, cv_dst2};\n cv::split(src, dsts);</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_CSS_>\n\n .card {\n left:160px;\n top:80px;\n box-shadow: 0 0 30px rgba(0, 0, 0, .1)\n \n}\n\n:host {\n background-color: #232527;\n}</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Java_>\timport java.util.*;\n\timport java.util.Map.Entry;\n\t \n\t \n\t class Main {\n\t\t static int mod = (int) (Math.pow(10,9)+7);\n\t\t static List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();\n\t public static void main(String[] args) {\n\t \t\n\t Scanner sc = new Scanner(System.in);\n\t int N = sc.nextInt();\t\n\t long[] a = new long[N];\n\t long ave =0;\n\t for (int i=0 ; i<N; i++) {\n\t a[i] = Long.parseLong(sc.next())-(i+1);\n\t }\n\t Arrays.sort(a);\n\t \n\t long ans=Long.MAX_VALUE;\n\t for(int i=Math.max(N/2-1, 0);i<Math.min(N/2+2, N);i++) {\n\t \tlong t = a[i];\n\t \tlong tmp=0;\n\t \tfor(int j=0;j<N;j++) {\n\t\t \ttmp=tmp+Math.abs(a[j]-t);\t \t\t\n\t \t}\n\t \tans=Math.min(ans,tmp);\n\t }\n\t System.out.println(ans);\n\t \n\t }\n\t}</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Dart_>import 'dart:async';\n\nimport 'package:flutter/material.dart';\n\nimport 'package:bloc/bloc.dart';\nimport 'package:flutter_bloc/flutter_bloc.dart';\n\nclass SimpleBlocDelegate extends BlocDelegate {\n @override\n void onTransition(Transition transition) {\n print(transition);\n }\n\n @override\n void onError(Object error, StackTrace stacktrace) {\n print(error);\n }\n}\n\nvoid main() {\n BlocSupervisor().delegate = SimpleBlocDelegate();\n runApp(App());\n}\n\nclass App extends StatefulWidget {\n @override\n State<StatefulWidget> createState() => _AppState();\n}\n\nclass _AppState extends State<App> {\n final CounterBloc _counterBloc = CounterBloc();\n final ThemeBloc _themeBloc = ThemeBloc();\n\n @override\n Widget build(BuildContext context) {\n return BlocProviderTree(\n blocProviders: [\n BlocProvider<CounterBloc>(bloc: _counterBloc),\n BlocProvider<ThemeBloc>(bloc: _themeBloc)\n ],\n child: BlocBuilder(\n bloc: _themeBloc,\n builder: (_, ThemeData theme) {\n return MaterialApp(\n title: 'Flutter Demo',\n home: CounterPage(),\n theme: theme,\n );\n },\n ),\n );\n }\n\n @override\n void dispose() {\n _counterBloc.dispose();\n _themeBloc.dispose();\n super.dispose();\n }\n}\n\nclass CounterPage extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n final CounterBloc _counterBloc = BlocProvider.of<CounterBloc>(context);\n final ThemeBloc _themeBloc = BlocProvider.of<ThemeBloc>(context);\n\n return Scaffold(\n appBar: AppBar(title: Text('Counter')),\n body: BlocBuilder<CounterEvent, int>(\n bloc: _counterBloc,\n builder: (BuildContext context, int count) {\n return Center(\n child: Text(\n '$count',\n style: TextStyle(fontSize: 24.0),\n ),\n );\n },\n ),\n floatingActionButton: Column(\n crossAxisAlignment: CrossAxisAlignment.end,\n mainAxisAlignment: MainAxisAlignment.end,\n children: <Widget>[\n Padding(\n padding: EdgeInsets.symmetric(vertical: 5.0),\n child: FloatingActionButton(\n child: Icon(Icons.add),\n onPressed: () {\n _counterBloc.dispatch(CounterEvent.increment);\n },\n ),\n ),\n Padding(\n padding: EdgeInsets.symmetric(vertical: 5.0),\n child: FloatingActionButton(\n child: Icon(Icons.remove),\n onPressed: () {\n _counterBloc.dispatch(CounterEvent.decrement);\n },\n ),\n ),\n Padding(\n padding: EdgeInsets.symmetric(vertical: 5.0),\n child: FloatingActionButton(\n child: Icon(Icons.update),\n onPressed: () {\n _themeBloc.dispatch(ThemeEvent.toggle);\n },\n ),\n ),\n ],\n ),\n );\n }\n}\n\nenum CounterEvent { increment, decrement }\n\nclass CounterBloc extends Bloc<CounterEvent, int> {\n @override\n int get initialState => 0;\n\n @override\n Stream<int> mapEventToState(int currentState, CounterEvent event) async* {\n switch (event) {\n case CounterEvent.decrement:\n yield currentState - 1;\n break;\n case CounterEvent.increment:\n yield currentState + 1;\n break;\n }\n }\n}\n\nenum ThemeEvent { toggle }\n\nclass ThemeBloc extends Bloc<ThemeEvent, ThemeData> {\n @override\n ThemeData get initialState => ThemeData.light();\n\n @override\n Stream<ThemeData> mapEventToState(\n ThemeData currentState,\n ThemeEvent event,\n ) async* {\n switch (event) {\n case ThemeEvent.toggle:\n yield currentState == ThemeData.dark()\n ? ThemeData.light()\n : ThemeData.dark();\n break;\n }\n }\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Java_>// Code automatically generated by \"Generate_Cone_Mapping_Model\" script by Jolyon Troscianko\n\n//Model fits:\n//swR2 0.99966383995596\n//lwR2 0.999866093413636\n//rodR2 0.999489296934988\n\n// Modelled based on Natural Spectra 400-700 database, containing 3139 spectra.\n\n// Generated: 2015/5/17 9:15:44\n\n\nimport ij.*;\nimport ij.plugin.filter.PlugInFilter;\nimport ij.process.*;\n\npublic class D7000_Nikkor_105mm_Pollack_D65 implements PlugInFilter {\n\nImageStack stack;\n\tpublic int setup(String arg, ImagePlus imp) { \n\tstack = imp.getStack(); \n\treturn DOES_32 + STACK_REQUIRED; \n\t}\npublic void run(ImageProcessor ip) {\n\nfloat[] vR;\nfloat[] vG;\nfloat[] vB;\nint w = stack.getWidth();\nint h = stack.getHeight();\nint dimension = w*h;\n\nfloat[] sw = new float[dimension];\nfloat[] lw = new float[dimension];\nfloat[] rod = new float[dimension];\n\nvR = (float[]) stack.getPixels(1);\nvG = (float[]) stack.getPixels(2);\nvB = (float[]) stack.getPixels(3);\n\nfor (int i=0;i<dimension;i++) {\nsw[i] = (float) ( 11.2837867411232 + vR[i] * -0.00612639302180127 + vG[i] * -0.0921988508679037 + vB[i] * 1.08868694206719 + vR[i]*vG[i] * -2.81981672920286e-07 + vR[i]*vB[i] * 1.27055332344145e-08 + vG[i]*vB[i] * -4.29512556569778e-07 + vR[i]*vG[i]*vB[i] * 1.3129858573511e-11);\nlw[i] = (float) ( -17.3220991266698 + vR[i] * -0.1687363880117 + vG[i] * 0.909710916470307 + vB[i] * 0.24786301049987 + vR[i]*vG[i] * -2.02861660911468e-07 + vR[i]*vB[i] * 8.25232052076577e-07 + vG[i]*vB[i] * 8.51047509620092e-08 + vR[i]*vG[i]*vB[i] * -8.38114966440038e-12);\nrod[i] = (float) ( -25.2024609585824 + vR[i] * -0.163005985207044 + vG[i] * 0.582765669018155 + vB[i] * 0.565204833597946 + vR[i]*vG[i] * -1.47363270175611e-07 + vR[i]*vB[i] * 1.23510286752307e-06 + vG[i]*vB[i] * 1.25869349396112e-07 + vR[i]*vG[i]*vB[i] * -1.53871080301447e-11);\n}\n\nImageStack outStack = new ImageStack(w, h);\noutStack.addSlice(\"sw\", sw);\noutStack.addSlice(\"lw\", lw);\noutStack.addSlice(\"rod\", rod);\nnew ImagePlus(\"Output\", outStack).show();\n\n}\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_XML_><interface name=\"ImageMarker\" namespace=\"ROS::visualization_msgs\">\n <args>\n <arg name=\"ImageMarker\" pass_by=\"reference\" type=\"ROS::visualization_msgs::ImageMarker\"/>\n </args>\n <import_serializable_type>ROS/Gen/visualization_msgs/Types/ImageMarkerSerializableAi.xml</import_serializable_type>\n</interface>\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_C_>#include<stdio.h>\nint main(void){\n long int n,i;\n long int min;\n long int max;\n long int sum=0;\n scanf(\"%ld\",&n);\n long int a[n+1];\n for(i=0;i<n;i++){\n \n scanf(\"%ld\",&a[i]);\n }\n max=a[0];\n min=a[0];\n for(i=0;i<n;i++){\n if(a[i]<min)min=a[i];\n if(a[i]>max)max=a[i];\n sum=a[i]+sum;\n }\n printf(\"%ld %ld %ld\\n\",min,max,sum);\n return 0;\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Clojure_>(defn product [a b]\n (if (zero? (rem (* a b) 2))\n \"Even\"\n \"Odd\"))\n\n(println (product (read) (read)))</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Java_>package org.sunbird.graph.model.relation;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.commons.lang3.StringUtils;\nimport org.sunbird.common.dto.Request;\nimport org.sunbird.common.exception.ServerException;\nimport org.sunbird.graph.common.mgr.BaseGraphManager;\nimport org.sunbird.graph.dac.enums.SystemNodeTypes;\nimport org.sunbird.graph.dac.model.Node;\nimport org.sunbird.graph.exception.GraphRelationErrorCodes;\n\npublic class HasValueRelation extends AbstractRelation {\n \n public static final String RELATION_NAME = \"hasValue\"; \n\n public HasValueRelation(BaseGraphManager manager, String graphId, String startNodeId, String endNodeId) {\n super(manager, graphId, startNodeId, endNodeId);\n }\n\n @Override\n public String getRelationType() {\n return RELATION_NAME;\n }\n\n @Override\n public Map<String, List<String>> validateRelation(Request request) {\n try {\n List<String> futures = new ArrayList<String>();\n Node startNode = getNode(request, this.startNodeId);\n Node endNode = getNode(request, this.endNodeId);\n String startNodeMsg = null;\n\t\t\tif (null == startNode) {\n\t\t\t\tstartNodeMsg = \"Start Node Id is invalid\";\n\t\t\t} else {\n\t\t\t\tString nodeType = startNode.getNodeType();\n\t\t\t\tif (StringUtils.equals(SystemNodeTypes.METADATA_NODE.name(), nodeType)\n\t\t\t\t\t\t|| StringUtils.equals(SystemNodeTypes.RELATION_NODE.name(), nodeType)) {\n\t\t\t\t\tstartNodeMsg = null;\n\t\t\t\t} else {\n\t\t\t\t\tstartNodeMsg = \"Start Node \" + startNodeId + \" should be a Metadata Node or Relation Node\";\n }\n\t\t\t}\n futures.add(startNodeMsg);\n\t\t\tString endNodeMsg = getNodeTypeFuture(this.endNodeId, endNode,\n\t\t\t\t\tnew String[] { SystemNodeTypes.VALUE_NODE.name() });\n futures.add(endNodeMsg);\n\t\t\treturn getMessageMap(futures);\n } catch (Exception e) {\n throw new ServerException(GraphRelationErrorCodes.ERR_RELATION_VALIDATE.name(), e.getMessage(), e);\n }\n }\n\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_C++_> * @version 0.1\r\n *\r\n * @history\r\n * <author> <date> <version> <description>\r\n * sheng 2015-02-15 0.1 build thee function\r\n *\r\n */\r\nNumberLineEdit::~NumberLineEdit()\r\n{\r\n\r\n}\r\n\r\n\r\n\r\n\r\n/**\r\n * @brief NumberLineEdit::FinishingEdit The slot to emit the FinishingLineedit\r\n * signal.\r\n *\r\n * @author sheng\r\n * @date 2015-02-15\r\n * @version 0.1\r\n *\r\n * @history\r\n * <author> <date> <version> <description>\r\n * sheng 2015-02-15 0.1 build thee function\r\n *\r\n */\r\nvoid NumberLineEdit::FinishingEdit()\r\n{\r\n emit FinishingLineedit(Row);\r\n}\r\n\r\n\r\n\r\n\r</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_PHP_> <a class=\"test\" href=\"#\">Signages <span class=\"caret\"></span></a>\n <ul class=\"dropdown-menu\">\n <li><a href=\"products.php#ACPsignages\">ACP acrylic signage</a></li>\n <li><a href=\"products.php#ACPsignages\">ACP signage</a></li>\n <li><a href=\"products.php#ACPsignages\">Glow sign board</a></li>\n <li><a href=\"products.php#ACPsignages\">Front-lit flex board</a></li>\n <li><a href=\"products.php#signages\">Box-type flex board</a></li>\n <li><a href=\"products.php#signages\">Neon signage</a></li>\n </ul>\n </li>\n <li class=\"dropdown-submenu\">\n <a class=\"test\" href=\"#\">In-shops <span class=\"caret\"></span></a>\n <ul class=\"dropdown-menu\">\n <li><a href=\"products.php#InshopBranding\">Vinyl on sunboard</a></li>\n <li><a href=\"products.php#InshopBranding\">Frosted vinyl</a></li>\n <li><a href=\"products.php#InshopBranding\">Vinyl sticker</a></li>\n <li><a href=\"products.php#InshopBranding\">Translite print</a></li>\n <li><a href=\"products.php#InshopBranding\">One-way vision</a></li>\n <li><a href=\"products.php#InshopBranding\">Acrylic sandwich</a></li>\n <li><a href=\"products.php#CliponFrame\">Clip-on frame</a></li>\n <li><a href=\"products.php#PhotoFrame\">Photo frame</a></li>\n <li><a href=\"products.php#InshopBranding\">Vinyl on plywood</a></li>\n\n </ul>\n </li>\n </ul>\n\n </li>\n <li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"about.php\">About</a></li>\n <li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"infrastructure.php\">Infrastructure</a></li>\n <li class=\"nav-item\"><a class=\"nav-item-child nav-item-hover\" href=\"contact.php\">Contact</a></li>\n </ul>\n </div>\n </div>\n <!-- End Navbar Collapse -->\n </div>\n </nav>\n <!-- Navbar -->\n</header>\n<script>\n $(document).ready(function(){\n $('.dropdown-submenu a.test').on(\"click\", function(e){\n $(this).next('ul').toggle();\n e.stopPropagation();\n e.preventDefault();\n });\n });\n</script>\n\n<!--========== END HEADER ==========--></code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Rust_>use crate::core::Ray;\nuse crate::sampler::Sampler;\nuse crate::types::Real;\nuse crate::vec2::*;\nuse crate::vec3::*;\n\npub trait Camera {\n fn sample_ray(&self, uv: Vec2, sampler: &mut Sampler) -> Ray;\n}\n\npub struct PinholeCamera {\n position: Vec3, // camera position\n forward: Vec3, // camera forward direction\n right: Vec3, // camera right direction\n up: Vec3, // camera up direction\n f: Real, // focal length\n}\n\nimpl PinholeCamera {\n pub fn new(position: Vec3, forward: Vec3, fov: Real) -> Self {\n let right = forward.cross(Vec3::new(0.0, 1.0, 0.0)).normalize();\n let up = right.cross(forward).normalize();\n let f = 1.0 / (0.5 * fov).tan();\n PinholeCamera {\n position,\n forward,\n right,\n up,\n f,\n }\n }\n}\n\nimpl Camera for PinholeCamera {\n fn sample_ray(&self, uv: Vec2, _sampler: &mut Sampler) -> Ray {\n let sensor_pos = self.position + uv.x() * self.right + uv.y() * self.up;\n let pinhole_pos = self.position + self.f * self.forward;\n Ray::new(sensor_pos, (pinhole_pos - sensor_pos).normalize())\n }\n}\n\n#[cfg(test)]\nmod tests {\n use std::f32::consts::FRAC_PI_2;\n\n use crate::camera::*;\n\n #[test]\n fn init_camera() {\n let camera = PinholeCamera::new(\n Vec3::new(0.0, 0.0, 0.0),\n Vec3::new(0.0, 0.0, -1.0),\n FRAC_PI_2,\n );</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_C_>/*\r\n * Copyright (c) 2000-2006, Sci. All rights reserved.\r\n *\r\n * THIS CODE AND INFORMATION IS PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY\r\n * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR\r\n * PURPOSE.\r\n *\r\n * This module contains routines for creating and managing a io channel server (socket/pip\")\r\n *\r\n * Name: bofioserver.h\r\n * Author: Bernard HARMEL: [email protected]\r\n * Revision: 1.0\r\n *\r\n * Rem: Nothing\r\n *\r\n * History:\r\n *\r\n * V 1.00 Oct 13 2017 BHA : Initial release\r\n */\r\n#pragma once\r\n\r\n\r\n/*** Include ****************************************************************/\r\n#include <map>\r\n//#include <bofstd/ibofiosessionfactory.h>\r\n//#include <bofstd/bofiosession.h>\r\n#include <bofstd/bofio.h>\r\n#include <bofstd/bofthread.h>\r\n#include <bofstd/bofsocketos.h>\r\n\r\nBEGIN_BOF_NAMESPACE()\r\nclass BofIoSession;\r\n\r\nclass IBofIoSessionFactory;\r\n/*** Defines ****************************************************************/\r\n\r\n/*** Macro ****************************************************************/\r\n\r\n/*** Structures *************************************************************/\r\n\r\nstruct BOF_IO_SERVER_PARAM\r\n{\r\n\t\tBOF_IO_PARAM BofIoParam_X;\r\n\r\n\t\tint32_t ThreadPolicy_i;\r\n\t\tint32_t ThreadPriority_i;\r\n\t\tuint32_t ThreadStartStopTimeoutInMs_U32;\r\n\r\n\t\tbool ReUseAddress_B;\r\n\t\tstd::string Address_S;\r\n\t\tuint32_t NbMaxSession_U32;\r\n\t\tuint32_t SessionRcvBufferSize_U32;\r\n\t\tuint32_t SessionSndBufferSize_U32;\r\n\r\n\t\tBOF_IO_SERVER_PARAM()\r\n\t\t{\r\n\t\t\tReset();\r\n\t\t}\r\n\r\n\t\tvoid Reset()\r\n\t\t{\r\n\t\t\tBofIoParam_X.Reset();\r\n\r\n\t\t\tThreadPolicy_i = BOF_THREAD_POLICY_OTHER;\r\n\t\t\tThreadPriority_i = BOF_THREAD_DEFAULT_PRIORITY;\r\n\t\t\tThreadStartStopTimeoutInMs_U32 = 5000;\r\n\r\n\t\t\tReUseAddress_B = true;\r\n\t\t\tAddress_S = \"\";\r\n\t\t\tNbMaxSession_U32 = 1;\r\n\t\t\tSessionRcvBufferSize_U32 = 0x10000;\r\n\t\t\tSessionSndBufferSize_U32 = 0x10000;\r\n\t\t}\r\n};\r\n\r\n\r\nstruct BOF_UV_SESSION\r\n{\r\n\t\tBofIoSession *pBofIoSession;\r\n\t\tuv_tcp_t *pUvTcp_X;\r\n\r\n\t\tBOF_UV_SESSION()\r\n\t\t{\r\n\t\t\tReset();\r\n\t\t}\r\n\r\n\t\tvoid Reset()\r\n\t\t{\r\n\t\t\tpBofIoSession = nullptr;\r\n\t\t\tpUvTcp_X = nullptr;\r\n\t\t}\r\n};\r\n\r\n\r\nclass BofIoServer : public BofThread, public BofIo\r\n{\r\nprivate:\r\n\t\tBOF_SOCK_TYPE mIoSocketType_E;\r\n\t\tBOF_MUTEX mMtx;\r\n\t\tBOF_IO_SERVER_PARAM mBofIoServerParam_X;\r\n\t\tstd::map<BofIoSession *, BOF_UV_SESSION> mSessionCollection;\r\n\t\tIBofIoSessionFactory *mpIBofIoSessionFactory;\r\n\t\tstd::unique_ptr<uv_tcp_t> mpuTcpServer_X;\r\n\r\npublic:\r\n\t\tBofIoServer(const BOF_IO_SERVER_PARAM &_rBofSocketServerParam_X, IBofIoSessionFactory *_pIBofIoSessionFactory);\r\n\r\n\t\tvirtual ~BofIoServer();\r\n\r\n\t\tBofIoServer &operator=(const BofIoServer &) = delete; // Disallow copying\r\n\t\tBofIoServer(const BofIoServer &) = delete;\r\n\r\n\t\tuint32_t GetNbConnectedSession() const;\r\n\r\n\t\tBOFERR CloseSession(BofIoSession *pBofIoSession);\r\n\r\n\t\tBOFERR SimulateConnectionRequest(BofIoSession **_ppBofIoSession);\r\n\r\n\t\tBOFERR SimulateDisconnectionRequest(BofIoSession *_pBofIoSession);\r\n\r\n\t\tBOFERR SessionDisconnected(BofIoSession *_pBofIoSession);\r\n\r\n\t\tBOFERR WriteData(uint32_t _TimeoutInMs_U32, const std::string &_rBuffer_S);\r\n\r\n\t\tBOFERR WriteData(uint32_t _TimeoutInMs_U32, uint32_t _Nb_U32, const uint8_t *_pBuffer_U8);\r\n\r\nprivate:\r\n\t\tBOFERR V_OnProcessing() override;\r\n\r\n\t\tBOFERR V_OnUvAsync(BOF_UV_CALLBACK *_pBofUvCallback, uv_async_t *_pHandle) override;\r\n\r\n\t\tBOFERR V_OnUvTimer(BOF_UV_CALLBACK *_pBofUvCallback, uv_timer_t *_pHandle) override;\r\n\r\n\t\tBOFERR V_OnUvAlloc(BOF_UV_CALLBACK *_pBofUvCallback, uv_handle_t *_pHandle, size_t _SuggestedSize, uv_buf_t *_pBuffer_X) override;\r\n\r\n//\tBOFERR\t\t\t\tV_OnUvClose(BOF_UV_CALLBACK *_pBofUvCallback, uv_handle_t *_pHandle) override;\r</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Java_>import java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\n@Service\npublic class JCOIngresoDescManualImpl implements JCOIngresoDescManualService {\n\n public IngresoDesManualExports Guardar(IngresoDescManualImports imports)throws Exception{\n\n IngresoDesManualExports idm= new IngresoDesManualExports();\n\n try {\n\n JCoDestination destination = JCoDestinationManager.getDestination(Constantes.DESTINATION_NAME);\n JCoRepository repo = destination.getRepository();\n\n JCoFunction stfcConnection = repo.getFunction(Constantes.ZFL_RFC_SAVE_DESC_MANUAL);\n\n JCoParameterList importx = stfcConnection.getImportParameterList();\n importx.setValue(\"P_USER\", imports.getP_user());\n\n\n JCoParameterList tables = stfcConnection.getTableParameterList();\n EjecutarRFC exec=new EjecutarRFC();\n\n List<HashMap<String, Object>> data = imports.getStr_des();\n for (int i = 0; i < data.size(); i++){\n HashMap<String, Object> record = data.get(i);\n Iterator iterator = record.entrySet().iterator();\n while (iterator.hasNext()) {\n Map.Entry tmpImport = (Map.Entry) iterator.next();\n String key = tmpImport.getKey().toString();\n Object value = tmpImport.getValue();\n if (key.equalsIgnoreCase(\"HIDES\") || key.equalsIgnoreCase(\"HFDES\")) {\n DateFormat formatter = new SimpleDateFormat(\"HH:mm\");\n Time timeValue = new Time(formatter.parse(String.valueOf(value)).getTime());\n record.put(key, timeValue);\n }\n }\n }\n\n exec.setTable(tables, Tablas.STR_DES, imports.getStr_des());\n stfcConnection.execute(destination);\n JCoTable T_MENSAJE = tables.getTable(Tablas.T_MENSAJE);\n\n Metodos metodo = new Metodos();\n List<HashMap<String, Object>> t_mensaje = metodo.ObtenerListObjetos(T_MENSAJE, imports.getFieldst_mensaje());\n\n idm.setT_mensaje(t_mensaje);\n idm.setMensaje(\"Ok\");\n\n }catch (Exception e){\n idm .setMensaje(e.getMessage());\n }\n return idm;\n }\n\n}</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_JavaScript_> if (typeof val === 'object') {\n el.cnode(build(val, xml`<${key}/>`))\n } else if (val) {\n el.cnode(xml`<${key}>${val}</${key}>`)\n } else {\n el.cnode(xml`<${key}/>`)\n }\n }\n return el\n}\n\nmodule.exports = plugin('vcard', {\n NS,\n get(...args) {\n return this.plugins['iq-caller'].get(xml`<vCard xmlns='${NS}'/>`, ...args).then(parse)\n },\n set(vcard) {\n return this.plugins['iq-caller'].set(build(vcard))\n },\n build,\n parse,\n}, [iqCaller])\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Python_>#----------------------------------------------------------------------\n# Purpose: This test compares k-means centers between H2O and MLlib.\n#----------------------------------------------------------------------\n\nimport sys\nsys.path.insert(1, \"../../\")\nimport h2o, tests\nimport numpy as np\n\ndef kmeans_mllib():\n \n\n # Check if we are running inside the H2O network by seeing if we can touch\n # the namenode.\n running_inside_h2o = tests.is_running_internal_to_h2o()\n\n if running_inside_h2o:\n hdfs_name_node = tests.get_h2o_internal_hdfs_name_node()\n hdfs_cross_file = \"/datasets/runit/BigCross.data\"\n\n print \"Import BigCross.data from HDFS\"\n url = \"hdfs://{0}{1}\".format(hdfs_name_node, hdfs_cross_file)\n cross_h2o = h2o.import_file(url)\n n = cross_h2o.nrow\n\n err_mllib = np.genfromtxt(tests.locate(\"smalldata/mllib_bench/bigcross_wcsse.csv\"), delimiter=\",\", skip_header=1)\n ncent = [int(err_mllib[r][0]) for r in range(len(err_mllib))]\n\n for k in ncent:\n print \"Run k-means++ with k = {0} and max_iterations = 10\".format(k)\n cross_km = h2o.kmeans(training_frame = cross_h2o, x = cross_h2o, k = k, init = \"PlusPlus\",\n max_iterations = 10, standardize = False)\n\n clust_mllib = np.genfromtxt(tests.locate(\"smalldata/mllib_bench/bigcross_centers_\" + str(k) + \".csv\"),\n delimiter=\",\").tolist()\n clust_h2o = cross_km.centers()\n\n # Sort in ascending order by first dimension for comparison purposes\n clust_mllib.sort(key=lambda x: x[0])\n clust_h2o.sort(key=lambda x: x[0])\n\n print \"\\nMLlib Cluster Centers:\\n\"\n print clust_mllib\n print \"\\nH2O Cluster Centers:\\n\"\n print clust_h2o\n\n wcsse_mllib = err_mllib[err_mllib[0:4,0].tolist().index(k)][1]\n wcsse_h2o = cross_km.tot_withinss() / n\n print \"\\nMLlib Average Within-Cluster SSE: \\n\".format(wcsse_mllib)\n print \"H2O Average Within-Cluster SSE: \\n\".format(wcsse_h2o)\n assert wcsse_h2o == wcsse_mllib, \"Expected mllib and h2o to get the same wcsse. Mllib got {0}, and H2O \" \\\n \"got {1}\".format(wcsse_mllib, wcsse_h2o)\n\nif __name__ == \"__main__\":\n tests.run_test(sys.argv, kmeans_mllib)\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_TypeScript_>/**\n * Server-side routes. Only the listed routes support html5pushstate.\n * Has to match client side routes.\n *\n * Index (/) route does not have to be listed here.\n *\n * @example\n * export const routes: string[] = [\n * 'home', 'about'\n * ];\n **/\nexport const routes: string[] = [\n // 'demo1',\n // 'demo2',\n // 'demo3'\n];\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_PHP_><html>\n \n <head>\n <title>Blog</title>\n <link rel=\"stylesheet\" href=\"{{ URL::asset('css/style.css') }}\" />\n </head>\n <body>\n \n <div class='container'>\n @yield('content')\n </div> \n \n </body>\n</html>\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Python_>\"\"\"\nRecurring Event Module.\n\nContains the Recurring event tracking class as well as relevant\nconstants for time conversion.\n\"\"\"\nimport json\nfrom datetime import datetime\nfrom io import BytesIO\nfrom typing import List, Optional\n\nfrom discord import (\n Attachment, Colour, Embed, File, Guild, Message, NoMoreItems, TextChannel\n)\nfrom loguru import logger\n\nfrom ophelia import settings\nfrom ophelia.events.calendar.base_event import BaseEvent, EventLoadError\nfrom ophelia.output.output import disp_str\nfrom ophelia.utils.discord_utils import FETCH_FAIL_EXCEPTIONS\nfrom ophelia.utils.text_utils import escape_json_formatting\nfrom ophelia.utils.time_utils import to_utc_datetime, utc_time_now\n\nDAY_SECONDS = 60 * 60 * 24\nMINUTE_SECONDS = 60\n\n\nclass RecurringEvent(BaseEvent):\n \"\"\"Recurring events that post messages from a queue channel\"\"\"\n\n __slots__ = [\n \"queue_channel\",\n \"target_channel\",\n \"post_template\",\n \"post_embed\",\n \"repeat_interval\",\n \"next_content\",\n \"event_cancelled\",\n \"notified\"\n ]\n\n @staticmethod\n def config_name() -> str:\n \"\"\"Type Name used in configuration.\"\"\"\n return \"recurring_event\"\n\n def __init__(\n self,\n queue_channel: TextChannel,\n target_channel: TextChannel,\n post_template: str,\n post_embed: str,\n repeat_interval: int,\n **kwargs\n ) -> None:\n \"\"\"\n Initializer for the RecurringEvent class.\n\n :param init_bundle: Base class init argument bundle\n :param queue_channel: Recurring message queue channel\n :param target_channel: Recurring message target channel\n :param post_template: Event post template\n :param post_embed: Event post embed in dictionary format as a\n string; empty string if no embed configured.\n :param repeat_interval: Event interval (in days)\n \"\"\"\n super().__init__(**kwargs)\n self.queue_channel = queue_channel\n self.target_channel = target_channel\n self.post_template = post_template\n self.post_embed = post_embed\n self.repeat_interval = repeat_interval\n self.next_content: Optional[Message] = None\n self.event_cancelled = False\n self.notified = False\n\n def time_to_notify(self, time: Optional[datetime] = None) -> bool:\n \"\"\"\n Check if it's time to send out event notifications.\n\n :param time: Time to check against\n :return: Boolean representing if the notification time has\n passed or if the event has already been notified\n \"\"\"\n if self.notified:\n return False\n\n return super().time_to_notify()\n\n async def distribute_dm(self, notif_msg: str, organizer_msg: str) -> None:\n \"\"\"\n Send notification DMs to all members subscribed and mark the\n event as notified.\n\n :param notif_msg: Notification message format\n :param organizer_msg: Organizer notification message format\n \"\"\"\n self.notified = True\n await super().distribute_dm(notif_msg, organizer_msg)\n\n def time_to_update(self, time: Optional[datetime] = None) -> bool:\n \"\"\"\n Check if it's time to update the event time to the next event.\n\n :param time: Time to check against\n :return: Boolean representing if the update time has\n passed\n \"\"\"\n if time is None:\n time = utc_time_now()\n\n return time >= to_utc_datetime(self.start_time)\n\n def update_time(self) -> None:\n \"\"\"\n Update event with next event time and make the appropriate\n message edits.\n\n Note that this DOES NOT account for any discrepencies in time-\n keeping, including timezone changes or Daylight Savings Time.\n All this does is add the interval time to the UTC timestamp.\n Users will have to reschedule themselves if they'd like to keep\n the time consistent with DST.\n \"\"\"\n while self.time_to_start():\n self.start_time = (\n self.start_time + self.repeat_interval * DAY_SECONDS\n )\n\n self.notif_time = self.start_time - self.notif_min_before * 60\n self.event_cancelled = False\n self.notified = False\n\n async def get_calendar_embed(\n self,\n colour: Colour = Colour(settings.embed_color_important)\n ) -> Embed:\n \"\"\"\n Get the recurrent event embed to be posted to the calendar\n channel.\n\n :param colour: Embed colour\n :return: Calendar event embed\n \"\"\"\n return await self.get_event_embed(\n disp_str(\"events_recurring_embed_text\").format(\n self.desc,\n self.repeat_interval\n ),\n colour\n )\n\n async def get_approval_embed(\n self,\n colour: Colour = Colour(settings.embed_color_important)\n ) -> Embed:\n \"\"\"\n Get the recurrent event embed to be posted to the approval\n channel.\n\n :param colour: Embed colour\n :return: Approval embed\n \"\"\"\n return await self.get_event_embed(\n disp_str(\"events_recurring_approval\").format(\n self.organizer.mention,\n self.desc,\n self.queue_channel.mention,\n self.target_channel.mention,\n self.dm_msg,\n self.notif_min_before,\n self.repeat_interval\n ),\n colour\n )\n\n @staticmethod\n async def load_from_dict(\n config_dict: dict,\n guild: Guild\n ) -> \"RecurringEvent\":\n \"\"\"\n Loads recurring event object from configuration parameters.\n\n :param config_dict: Dictionary containing configuration\n parameters\n :param guild: Event guild\n :return: Recurring event object\n :raises EventLoadError: Invalid arguments passed\n \"\"\"\n try:\n base_dict = await BaseEvent.base_event_params(config_dict, guild)\n\n queue_channel = guild.get_channel(int(config_dict[\"queue_channel\"]))\n if queue_channel is None:\n raise EventLoadError\n\n target_channel = guild.get_channel(\n int(config_dict[\"target_channel\"])\n )\n if queue_channel is None:\n raise EventLoadError\n\n post_template = str(config_dict[\"post_template\"])\n post_embed = str(config_dict[\"post_embed\"])\n repeat_interval = int(config_dict[\"repeat_interval\"])\n\n base_dict.update({\n \"queue_channel\": queue_channel,\n \"target_channel\": target_channel,\n \"post_template\": post_template,\n \"post_embed\": post_embed,\n \"repeat_interval\": repeat_interval\n })\n\n return RecurringEvent(**base_dict)\n except KeyError as e:\n raise EventLoadError from e\n\n async def save_to_dict(self) -> dict:\n \"\"\"\n Saves recurrent event object into dictionary containing\n configuration parameters so that it may be loaded again.\n\n :return: Dictionary of configuration parameters\n \"\"\"\n save_dict = await super().save_to_dict()\n save_dict.update({\n \"type\": \"recurring_event\",\n \"queue_channel\": self.queue_channel.id,\n \"target_channel\": self.target_channel.id,\n \"post_template\": self.post_template,\n \"post_embed\": self.post_embed,\n \"repeat_interval\": self.repeat_interval\n })\n\n return save_dict\n\n async def retrieve_content(self) -> None:\n \"\"\"\n Retrieve an event post or inform the scheduler if there is\n nothing to retrieve.\n\n :raises NoMoreItems: When there are no messages to retrieve from\n the queue\n \"\"\"\n if self.next_content is not None or self.event_cancelled:\n return\n\n try:\n self.next_content = await self.queue_channel.history(\n limit=1,\n oldest_first=True\n ).next()</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Go_>\tgcompute \"google.golang.org/api/compute/v1\"\n\n\tv1 \"k8s.io/api/core/v1\"\n\tapierrors \"k8s.io/apimachinery/pkg/api/errors\"\n\tclusterv1 \"sigs.k8s.io/cluster-api/api/v1alpha4\"\n\tcapierrors \"sigs.k8s.io/cluster-api/errors\"\n\t\"sigs.k8s.io/cluster-api/util\"\n\t\"sigs.k8s.io/cluster-api/util/annotations\"\n\t\"sigs.k8s.io/cluster-api/util/predicates\"\n\t\"sigs.k8s.io/cluster-api/util/record\"\n\tctrl \"sigs.k8s.io/controller-runtime\"\n\t\"sigs.k8s.io/controller-runtime/pkg/client\"\n\t\"sigs.k8s.io/controller-runtime/pkg/controller\"\n\t\"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil\"\n\t\"sigs.k8s.io/controller-runtime/pkg/handler\"\n\t\"sigs.k8s.io/controller-runtime/pkg/source\"\n\n\tinfrav1 \"sigs.k8s.io/cluster-api-provider-gcp/api/v1alpha4\"\n\t\"sigs.k8s.io/cluster-api-provider-gcp/cloud/scope\"\n\t\"sigs.k8s.io/cluster-api-provider-gcp/cloud/services/compute\"\n\t\"sigs.k8s.io/cluster-api-provider-gcp/util/reconciler\"\n)\n\n// GCPMachineReconciler reconciles a GCPMachine object.\ntype GCPMachineReconciler struct {\n\tclient.Client\n\tLog logr.Logger\n\tReconcileTimeout time.Duration\n\tWatchFilterValue string\n}\n\nfunc (r *GCPMachineReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager, options controller.Options) error {\n\tlog := r.Log.WithValues(\"controller\", \"GCPMachine\")\n\n\tc, err := ctrl.NewControllerManagedBy(mgr).\n\t\tWithOptions(options).\n\t\tFor(&infrav1.GCPMachine{}).\n\t\tWithEventFilter(predicates.ResourceNotPausedAndHasFilterLabel(ctrl.LoggerFrom(ctx), r.WatchFilterValue)).\n\t\tWatches(\n\t\t\t&source.Kind{Type: &clusterv1.Machine{}},\n\t\t\thandler.EnqueueRequestsFromMapFunc(util.MachineToInfrastructureMapFunc(infrav1.GroupVersion.WithKind(\"GCPMachine\"))),\n\t\t).\n\t\tWatches(\n\t\t\t&source.Kind{Type: &infrav1.GCPCluster{}},\n\t\t\thandler.EnqueueRequestsFromMapFunc(r.GCPClusterToGCPMachines),\n\t\t).\n\t\tBuild(r)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error creating controller\")\n\t}\n\n\tgcpMachineMapper, err := util.ClusterToObjectsMapper(r.Client, &infrav1.GCPMachineList{}, mgr.GetScheme())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create mapper for Cluster to GCPMachines\")\n\t}\n\n\t// Add a watch on clusterv1.Cluster object for unpause & ready notifications.\n\tif err := c.Watch(\n\t\t&source.Kind{Type: &clusterv1.Cluster{}},\n\t\thandler.EnqueueRequestsFromMapFunc(gcpMachineMapper),\n\t\tpredicates.ClusterUnpausedAndInfrastructureReady(log),\n\t); err != nil {\n\t\treturn errors.Wrap(err, \"failed adding a watch for ready clusters\")\n\t}\n\n\treturn nil\n}\n\n// +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=gcpmachines,verbs=get;list;watch;create;update;patch;delete\n// +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=gcpmachines/status,verbs=get;update;patch\n// +kubebuilder:rbac:groups=cluster.x-k8s.io,resources=machines;machines/status,verbs=get;list;watch\n// +kubebuilder:rbac:groups=\"\",resources=events,verbs=get;list;watch;create;update;patch\n// +kubebuilder:rbac:groups=\"\",resources=secrets;,verbs=get;list;watch\n\nfunc (r *GCPMachineReconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Result, reterr error) {\n\tctx, cancel := context.WithTimeout(ctx, reconciler.DefaultedLoopTimeout(r.ReconcileTimeout))\n\tdefer cancel()\n\tlogger := r.Log.WithValues(\"namespace\", req.Namespace, \"gcpMachine\", req.Name)\n\n\t// Fetch the GCPMachine instance.\n\tgcpMachine := &infrav1.GCPMachine{}\n\terr := r.Get(ctx, req.NamespacedName, gcpMachine)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Fetch the Machine.\n\tmachine, err := util.GetOwnerMachine(ctx, r.Client, gcpMachine.ObjectMeta)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\tif machine == nil {\n\t\tlogger.Info(\"Machine Controller has not yet set OwnerRef\")\n\n\t\treturn ctrl.Result{}, nil\n\t}\n\n\tlogger = logger.WithValues(\"machine\", machine.Name)\n\n\t// Fetch the Cluster.\n\tcluster, err := util.GetClusterFromMetadata(ctx, r.Client, machine.ObjectMeta)\n\tif err != nil {\n\t\tlogger.Info(\"Machine is missing cluster label or cluster does not exist\")\n\n\t\treturn ctrl.Result{}, nil\n\t}\n\n\tif annotations.IsPaused(cluster, gcpMachine) {\n\t\tlogger.Info(\"GCPMachine or linked Cluster is marked as paused. Won't reconcile\")\n\t\treturn ctrl.Result{}, nil\n\t}\n\n\tlogger = logger.WithValues(\"cluster\", cluster.Name)\n\n\tgcpCluster := &infrav1.GCPCluster{}\n\n\tgcpClusterName := client.ObjectKey{\n\t\tNamespace: gcpMachine.Namespace,\n\t\tName: cluster.Spec.InfrastructureRef.Name,\n\t}\n\tif err := r.Client.Get(ctx, gcpClusterName, gcpCluster); err != nil {\n\t\tlogger.Info(\"GCPCluster is not available yet\")\n\n\t\treturn ctrl.Result{}, nil\n\t}\n\n\tlogger = logger.WithValues(\"gcpCluster\", gcpCluster.Name)\n\n\t// Create the cluster scope</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Python_># Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for tensorflow.ops.math_ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nimport numpy as np\n\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import constant_op\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.platform import googletest\n\nexp = math.exp\nlog = math.log\n\nclass ReduceTest(test_util.TensorFlowTestCase):\n\n def testReduceAllDims(self):\n x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)\n with self.test_session():\n y_tf = math_ops.reduce_sum(x).eval()\n self.assertEqual(y_tf, 21)\n\nclass RoundTest(test_util.TensorFlowTestCase):\n\n def testRounding(self):\n x = [0.49, 0.7, -0.3, -0.8]\n for dtype in [np.float32, np.double]:\n x_np = np.array(x, dtype=dtype)\n for use_gpu in [True, False]:\n with self.test_session(use_gpu=use_gpu):\n x_tf = constant_op.constant(x_np, shape=x_np.shape)\n y_tf = math_ops.round(x_tf)\n y_tf_np = y_tf.eval()\n y_np = np.round(x_np)\n self.assertAllClose(y_tf_np, y_np, atol=1e-2)\n\n\nclass ModTest(test_util.TensorFlowTestCase):\n\n def testFloat(self):\n x = [0.5, 0.7, 0.3]\n for dtype in [np.float32, np.double]:\n # Test scalar and vector versions.\n for denom in [x[0], [x[0]] * 3]:\n x_np = np.array(x, dtype=dtype)\n with self.test_session():\n x_tf = constant_op.constant(x_np, shape=x_np.shape)\n y_tf = math_ops.mod(x_tf, denom)\n y_tf_np = y_tf.eval()\n y_np = np.fmod(x_np, denom)\n self.assertAllClose(y_tf_np, y_np, atol=1e-2)\n\n def testFixed(self):\n x = [5, 10, 23]\n for dtype in [np.int32, np.int64]:\n # Test scalar and vector versions.\n for denom in [x[0], x]:\n x_np = np.array(x, dtype=dtype)\n with self.test_session():\n x_tf = constant_op.constant(x_np, shape=x_np.shape)\n y_tf = math_ops.mod(x_tf, denom)\n y_tf_np = y_tf.eval()</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Python_>\"\"\"\n* Copyright 2019 EPAM Systems\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n\"\"\"\n\nimport logging\nimport json\nimport pika\nimport commons.launch_objects as launch_objects\n\nlogger = logging.getLogger(\"analyzerApp.amqpHandler\")\n\n\ndef prepare_launches(launches):\n \"\"\"Function for deserializing array of launches\"\"\"\n return [launch_objects.Launch(**launch) for launch in launches]\n\n\ndef prepare_search_logs(search_data):\n \"\"\"Function for deserializing search logs object\"\"\"\n return launch_objects.SearchLogs(**search_data)\n\n\ndef prepare_launch_info(launch_info):\n \"\"\"Function for deserializing search logs object\"\"\"\n return launch_objects.LaunchInfoForClustering(**launch_info)\n\n\ndef prepare_clean_index(clean_index):\n \"\"\"Function for deserializing clean index object\"\"\"\n return launch_objects.CleanIndex(**clean_index)\n\n\ndef prepare_delete_index(body):\n \"\"\"Function for deserializing index id object\"\"\"\n return int(body)\n\n\ndef prepare_test_item_info(test_item_info):\n \"\"\"Function for deserializing test item info for suggestions\"\"\"\n return launch_objects.TestItemInfo(**test_item_info)\n\n\ndef prepare_search_response_data(response):\n \"\"\"Function for serializing response from search request\"\"\"\n return json.dumps(response)\n\n\ndef prepare_analyze_response_data(response):\n \"\"\"Function for serializing response from analyze request\"\"\"\n return json.dumps([resp.dict() for resp in response])\n\n\ndef prepare_index_response_data(response):\n \"\"\"Function for serializing response from index request\n and other objects, which are pydantic objects\"\"\"\n return response.json()\n\n\ndef output_result(response):\n \"\"\"Function for serializing int object\"\"\"\n return str(response)\n\n\ndef handle_amqp_request(channel, method, props, body,\n request_handler, prepare_data_func=prepare_launches,\n prepare_response_data=prepare_search_response_data):\n \"\"\"Function for handling amqp reuqest: index, search and analyze\"\"\"\n logger.debug(\"Started processing %s method %s props\", method, props)\n logger.debug(\"Started processing data %s\", body)\n try:\n launches = json.loads(body, strict=False)\n except Exception as err:\n logger.error(\"Failed to load json from body\")\n logger.error(err)\n return False\n try:\n launches = prepare_data_func(launches)\n except Exception as err:\n logger.error(\"Failed to transform body into objects\")\n logger.error(err)\n return False\n try:\n response = request_handler(launches)\n except Exception as err:\n logger.error(\"Failed to process launches\")\n logger.error(err)\n return False\n\n try:\n response_body = prepare_response_data(response)\n except Exception as err:\n logger.error(\"Failed to dump launches result\")\n logger.error(err)\n return False\n try:\n channel.basic_publish(exchange='',\n routing_key=props.reply_to,\n properties=pika.BasicProperties(\n correlation_id=props.correlation_id,\n content_type=\"application/json\"),\n mandatory=False,\n body=response_body)\n except Exception as err:\n logger.error(\"Failed to publish result\")\n logger.error(err)\n logger.debug(\"Finished processing %s method\", method)\n return True\n\n\ndef handle_inner_amqp_request(channel, method, props, body, request_handler):\n \"\"\"Function for handling inner amqp reuqests\"\"\"\n logger.debug(\"Started processing %s method %s props\", method, props)\n logger.debug(\"Started processing data %s\", body)\n try:\n stats_info = json.loads(body, strict=False)\n except Exception as err:\n logger.error(\"Failed to load json from body\")\n logger.error(err)\n return False\n try:\n request_handler(stats_info)\n except Exception as err:\n logger.error(\"Failed to process stats info\")\n logger.error(err)\n return False\n logger.debug(\"Finished processing %s method\", method)\n return True\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Python_># Copyright 2016 Canonical Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Note that the unit_tests/__init__.py has the following lines to stop\n# side effects from the imorts from charm helpers.\n\n# sys.path.append('./lib')\n# mock out some charmhelpers libraries as they have apt install side effects\n# sys.modules['charmhelpers.contrib.openstack.utils'] = mock.MagicMock()\n# sys.modules['charmhelpers.contrib.network.ip'] = mock.MagicMock()\n\nimport unittest\nimport mock\n\nimport charms_openstack.adapters as c_adapters\nimport charms_openstack.plugins.adapters as pl_adapters\n\n\nclass FakeCephClientRelation():\n\n relation_name = 'storage-ceph'\n\n def mon_hosts(self):\n return ['c', 'b', 'a']\n\n\nclass TestCephRelationAdapter(unittest.TestCase):\n\n def test_class(self):\n test_config = {}\n with mock.patch.object(c_adapters.hookenv, 'related_units',\n return_value=[]), \\\n mock.patch.object(c_adapters.hookenv,\n 'config',\n new=lambda: test_config):\n interface_ceph = FakeCephClientRelation()\n adapter_ceph = pl_adapters.CephRelationAdapter(\n relation=interface_ceph)\n self.assertEqual(adapter_ceph.monitors, 'a,b,c')\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_C++_> // inherit tensor dimension from sourceData, minus the last (column or time) dimension. TODO this needs to become simpler...\n if (sourceHasDynamicAxis)\n outputShape = m_inputs[0].Shape();\n else\n {\n if (m_inputs[0].Shape().Rank() > 1)\n outputShape = outputShape.SubShape(0, outputShape.Rank() - 1);\n else\n outputShape = {};\n }\n\n break;\n }\n case PrimitiveOpType::Splice:\n {\n assert(m_inputs.size() >= 2);\n auto maxInputRank = MaxInputRank(m_inputs);\n auto spliceAxis = NormalizeStaticAxis(m_attributes[PrimitiveFunction::AttributeNameAxis].Value<Axis>(), NDShape(maxInputRank));\n\n if (!spliceAxis.IsStaticAxis())\n LogicError(\"Function '%S': Splice operation currently does not support splicing along dynamic axis\", AsString().c_str());\n\n if (spliceAxis.StaticAxisIndex() < 0)\n InvalidArgument(\"Function '%S': Splice operation's axis index (%d) must be >= 0.\", AsString().c_str(), spliceAxis.StaticAxisIndex());\n\n outputShape = SpliceOutputShape(m_inputs, spliceAxis.StaticAxisIndex());\n break;\n }\n case PrimitiveOpType::RandomSample:\n case PrimitiveOpType::RandomSampleInclusionFrequency:\n {\n auto numSamples = m_attributes[PrimitiveFunction::AttributeNameNumSamples].Value<size_t>();\n auto allowDuplicates = m_attributes[PrimitiveFunction::AttributeNameAllowDuplicates].Value<bool>();\n\n if (numSamples == 0)\n InvalidArgument(\"RandomSample/RandomSampleInclusionFrequency: Number of requested samples must be > 0.\");\n\n let& shape = m_inputs[0].Shape();\n size_t numClasses = shape.Dimensions()[0];\n\n if (numClasses != NDShape::InferredDimension && !allowDuplicates && numClasses <= numSamples)\n InvalidArgument(\"RandomSample/RandomSampleInclusionFrequency: For sampling without duplicates the number of requested samples \"\n \"(%lu) must be less than the number of classes (%lu).\", numSamples, numClasses);\n\n // within this block we handle RandomSample and RandomSampleInclusionFrequency\n if (m_op == PrimitiveOpType::RandomSampleInclusionFrequency)\n outputShape = shape;\n else\n {\n vector<size_t> dimensions{ numClasses, numSamples };\n outputShape = NDShape(dimensions);\n }\n\n break;\n }\n case PrimitiveOpType::OptimizedRNNStack:\n {\n assert(m_inputs.size() == 2);\n auto operand = m_inputs[0];\n auto parameter = m_inputs[1];\n if (operand.Shape().Rank() != 1)\n InvalidArgument(\"OptimizedRNNStack: input '%S' must have rank 1; actual input rank is %lu.\", operand.AsString().c_str(), operand.Shape().Rank());\n if (operand.DynamicAxes().empty())\n InvalidArgument(\"OptimizedRNNStack: input '%S' must have at least one dynamic axis.\", operand.AsString().c_str());\n auto numLayers = m_attributes[PrimitiveFunction::AttributeNameNumLayers].Value<size_t>();\n if (numLayers == 0)\n InvalidArgument(\"Number of layers (%d) in OptimizedRNNStack operation must be > 0.\", (int)numLayers);\n auto bidirectional = m_attributes[PrimitiveFunction::AttributeNameBidirectional].Value<bool>();\n auto hiddenSize = m_attributes[PrimitiveFunction::AttributeNameHiddenSize].Value<size_t>();\n\n // output dims\n outputShape = operand.Shape();\n outputShape[0] = (bidirectional ? 2 : 1) * hiddenSize;\n // infer input size\n // Note: Output dim is second axis, so say initOutputRank=-1.\n if (parameter.Shape().Rank() == 2)\n {\n const auto recurrentOp = m_attributes[PrimitiveFunction::AttributeNameRecurrentOp].Value<std::wstring>();\n const auto attributes = RnnAttributes(bidirectional, numLayers, hiddenSize, recurrentOp, -1);\n const auto numParameters = attributes.GetNumParameters(operand.Shape().TotalSize());\n std::vector<std::pair<Variable, NDShape>> newOperandShapes = { { parameter, std::move(NDShape({ numParameters.first, numParameters.second })) } };\n UpdateOperandShapes(newOperandShapes);\n }\n break;\n }\n case PrimitiveOpType::ReconcileDynamicAxis:\n {\n assert(m_inputs.size() == 2);\n auto operand = m_inputs[0];\n auto layout = m_inputs[1];\n // data operand can be a constant or a param matrix\n if (layout.DynamicAxes().empty())\n InvalidArgument(\"ReconcileDynamicAxis: layout operand '%S' must have at least one dynamic axis.\", layout.AsString().c_str());\n outputShape = operand.Shape();\n break;\n }\n case PrimitiveOpType::CosDistanceWithNegativeSamples:\n {\n assert(m_inputs.size() == 4);\n\n auto shiftInput = m_inputs[2];\n auto numNegativeSamplesInput = m_inputs[3];\n if (!IsConstantScalar(shiftInput) || !IsConstantScalar(numNegativeSamplesInput))\n InvalidArgument(\"CosDistanceWithNegativeSamples: Input(2) '%S' and Input(3) '%S' correpond to shift and numNegativeSamples inputs and must be scalar constants.\",\n shiftInput.AsString().c_str(), numNegativeSamplesInput.AsString().c_str());\n\n auto numNegativeSamples = (size_t)Constant(numNegativeSamplesInput).Value()->AsScalar<float>();\n outputShape = NDShape({ numNegativeSamples + 1 });\n break;\n }\n default:\n LogicError(\"Specified Primitive Function op %S is not supported\", PrimitiveOpTypeName(m_op).c_str());\n break;\n }\n }\n }\n }\n\n outputs.push_back({ OutputVariable(outputShape, outputDataType, outputDynamicAxes, Name().empty() ? L\"\" : Name()) });\n }\n }\n\n static const std::wstring s_primitiveFunctionTypeValue = L\"PrimitiveFunction\";\n\n /*virtual*/ Dictionary PrimitiveFunction::Serialize() const \n {\n Dictionary dict;\n\n dict[versionKey] = CurrentVersion();\n dict[typeKey] = s_primitiveFunctionTypeValue;\n dict[opKey] = static_cast<size_t>(m_op);\n dict[attributesKey] = Attributes();\n dict[uidKey] = Uid();\n if (!Name().empty())\n dict[nameKey] = Name();\n \n auto inputs = Inputs();\n vector<DictionaryValue> inputUids;\n inputUids.reserve(inputs.size());\n for (auto& input : inputs)\n {\n inputUids.push_back(input.Uid());\n }\n\n dict[inputsKey] = std::move(inputUids);\n\n if (m_op == PrimitiveOpType::Block)\n {\n auto blockFunction = dynamic_cast<const BlockFunction*>(this);\n auto blockCompositeFunc = dynamic_cast<const CompositeFunction*>(blockFunction->Composite().get());\n dict[blockFunctionCompositeKey] = blockCompositeFunc->SerializeBlockComposite();\n dict[blockFunctionOpNameKey] = OpName();\n\n const auto& blockArgumentsMap = BlockArgumentsMapping();\n std::vector<std::wstring> serializedArgumentsMapKeys;\n std::vector<std::wstring> serializedArgumentsMapValues;\n for (auto argumentMapping : blockArgumentsMap)\n {\n serializedArgumentsMapKeys.push_back(argumentMapping.first.Uid());\n serializedArgumentsMapValues.push_back(argumentMapping.second.Uid());\n }\n\n dict[blockFunctionCompositeArgumentsMapKeysKey] = AsDictionaryValueVector(serializedArgumentsMapKeys);\n dict[blockFunctionCompositeArgumentsMapValuesKey] = AsDictionaryValueVector(serializedArgumentsMapValues);\n }\n\n return dict;\n }\n\n /*static*/ FunctionPtr PrimitiveFunction::Deserialize(const Dictionary& dict, \n const std::unordered_map<std::wstring, Variable>& uidToVariableMap,</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Rust_>use habitat_core::{self as hab_core,\n util,</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_C++_> EXPECT_EQ(developer::HOST_ACCESS_ON_CLICK,\n info->permissions.runtime_host_permissions->host_access);\n }\n\n // Grant http://example.com, which is a subset of the requested host pattern\n // (*://example.com).\n modifier.GrantHostPermission(GURL(\"http://example.com/\"));\n {\n std::unique_ptr<developer::ExtensionInfo> info =\n GenerateExtensionInfo(extension->id());\n ASSERT_TRUE(info->permissions.runtime_host_permissions);\n // We should display that http://example.com is granted, but *://example.com\n // is still requested. This is technically correct.\n // TODO(devlin): This is an edge case, so it's okay for it to be a little\n // rough (as long as it's not incorrect), but it would be nice to polish it\n // out. Ideally, for extensions requesting specific hosts, we'd only allow\n // granting/revoking specific patterns (e.g., all example.com sites).\n EXPECT_EQ(\n R\"([{\"granted\":true,\"host\":\"http://example.com/*\"},)\"\n R\"({\"granted\":false,\"host\":\"*://example.com/*\"},)\"\n R\"({\"granted\":false,\"host\":\"https://chromium.org/*\"}])\",\n SiteControlsToString(\n info->permissions.runtime_host_permissions->hosts));\n EXPECT_FALSE(info->permissions.runtime_host_permissions->has_all_hosts);\n EXPECT_EQ(developer::HOST_ACCESS_ON_SPECIFIC_SITES,\n info->permissions.runtime_host_permissions->host_access);\n }\n\n // Grant the requested pattern (\"*://example.com/*\").\n {\n URLPattern example_com(Extension::kValidHostPermissionSchemes,\n \"*://example.com/*\");\n PermissionSet example_com_set(APIPermissionSet(), ManifestPermissionSet(),\n URLPatternSet({example_com}),\n URLPatternSet({example_com}));\n PermissionsUpdater(profile()).GrantRuntimePermissions(\n *extension, example_com_set, base::DoNothing::Once());\n }\n\n {\n std::unique_ptr<developer::ExtensionInfo> info =\n GenerateExtensionInfo(extension->id());\n ASSERT_TRUE(info->permissions.runtime_host_permissions);\n // The http://example.com/* pattern should be omitted, since it's consumed\n // by the *://example.com/* pattern.\n EXPECT_EQ(\n R\"([{\"granted\":true,\"host\":\"*://example.com/*\"},)\"\n R\"({\"granted\":false,\"host\":\"https://chromium.org/*\"}])\",\n SiteControlsToString(\n info->permissions.runtime_host_permissions->hosts));\n EXPECT_FALSE(info->permissions.runtime_host_permissions->has_all_hosts);\n EXPECT_EQ(developer::HOST_ACCESS_ON_SPECIFIC_SITES,\n info->permissions.runtime_host_permissions->host_access);\n }\n\n // Grant permission beyond what was requested (*://*.example.com, when\n // subdomains weren't in the extension manifest).\n {\n URLPattern example_com(Extension::kValidHostPermissionSchemes,\n \"*://*.example.com/*\");\n PermissionSet example_com_set(APIPermissionSet(), ManifestPermissionSet(),\n URLPatternSet({example_com}),\n URLPatternSet({example_com}));\n PermissionsUpdater(profile()).GrantRuntimePermissions(\n *extension, example_com_set, base::DoNothing::Once());\n }\n\n {\n std::unique_ptr<developer::ExtensionInfo> info =\n GenerateExtensionInfo(extension->id());\n ASSERT_TRUE(info->permissions.runtime_host_permissions);\n // The full granted pattern should be visible.\n EXPECT_EQ(\n R\"([{\"granted\":true,\"host\":\"*://*.example.com/*\"},)\"\n R\"({\"granted\":false,\"host\":\"https://chromium.org/*\"}])\",\n SiteControlsToString(\n info->permissions.runtime_host_permissions->hosts));\n EXPECT_FALSE(info->permissions.runtime_host_permissions->has_all_hosts);\n EXPECT_EQ(developer::HOST_ACCESS_ON_SPECIFIC_SITES,\n info->permissions.runtime_host_permissions->host_access);\n }\n}\n\n// Tests the population of withheld runtime hosts when they overlap with granted\n// patterns.\nTEST_F(ExtensionInfoGeneratorUnitTest,\n WithheldUrlsOverlappingWithContentScript) {\n scoped_refptr<const Extension> extension =\n ExtensionBuilder(\"extension\")\n .AddPermissions({\"*://example.com/*\", \"*://chromium.org/*\"})\n .AddContentScript(\"script.js\", {\"*://example.com/foo\"})\n .Build();\n {\n ExtensionRegistry::Get(profile())->AddEnabled(extension);\n PermissionsUpdater updater(profile());\n updater.InitializePermissions(extension.get());\n updater.GrantActivePermissions(extension.get());\n }\n\n ScriptingPermissionsModifier modifier(profile(), extension);\n modifier.SetWithholdHostPermissions(true);\n\n {\n std::unique_ptr<developer::ExtensionInfo> info =\n GenerateExtensionInfo(extension->id());\n ASSERT_TRUE(info->permissions.runtime_host_permissions);\n // Initially, no hosts are granted.\n EXPECT_EQ(\n R\"([{\"granted\":false,\"host\":\"*://chromium.org/*\"},)\"\n R\"({\"granted\":false,\"host\":\"*://example.com/*\"}])\",\n SiteControlsToString(\n info->permissions.runtime_host_permissions->hosts));\n EXPECT_FALSE(info->permissions.runtime_host_permissions->has_all_hosts);\n EXPECT_EQ(developer::HOST_ACCESS_ON_CLICK,\n info->permissions.runtime_host_permissions->host_access);\n }\n}\n\n// Tests that file:// access checkbox shows up for extensions with activeTab\n// permission. See crbug.com/850643.\nTEST_F(ExtensionInfoGeneratorUnitTest, ActiveTabFileUrls) {\n scoped_refptr<const Extension> extension =\n CreateExtension(\"activeTab\", ListBuilder().Append(\"activeTab\").Build(),\n ManifestLocation::kInternal);\n std::unique_ptr<developer::ExtensionInfo> info =\n GenerateExtensionInfo(extension->id());\n\n EXPECT_TRUE(extension->wants_file_access());\n EXPECT_TRUE(info->file_access.is_enabled);\n EXPECT_FALSE(info->file_access.is_active);\n}\n\n// Tests that blocklisted extensions are returned by the ExtensionInfoGenerator.\nTEST_F(ExtensionInfoGeneratorUnitTest, Blocklisted) {\n const scoped_refptr<const Extension> extension1 =\n CreateExtension(\"test1\", std::make_unique<base::ListValue>(),\n ManifestLocation::kInternal);\n const scoped_refptr<const Extension> extension2 =\n CreateExtension(\"test2\", std::make_unique<base::ListValue>(),\n ManifestLocation::kInternal);\n\n std::string id1 = extension1->id();\n std::string id2 = extension2->id();\n ASSERT_NE(id1, id2);\n\n ExtensionInfoGenerator::ExtensionInfoList info_list =</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Java_>/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.hadoop.hdfs.server.namenode;\n\nimport static org.apache.hadoop.util.ExitUtil.terminate;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.URI;\nimport java.net.URL;\nimport java.security.PrivilegedAction;\nimport java.security.PrivilegedExceptionAction;\nimport java.util.*;\n\nimport com.google.common.collect.Lists;\nimport org.apache.commons.cli.CommandLine;\nimport org.apache.commons.cli.CommandLineParser;\nimport org.apache.commons.cli.HelpFormatter;\nimport org.apache.commons.cli.Option;\nimport org.apache.commons.cli.OptionBuilder;\nimport org.apache.commons.cli.Options;\nimport org.apache.commons.cli.ParseException;\nimport org.apache.commons.cli.PosixParser;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.apache.hadoop.HadoopIllegalArgumentException;\nimport org.apache.hadoop.classification.InterfaceAudience;\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.fs.FileSystem;\nimport org.apache.hadoop.hdfs.DFSConfigKeys;\nimport org.apache.hadoop.hdfs.DFSUtil;\nimport org.apache.hadoop.hdfs.HAUtil;\nimport org.apache.hadoop.hdfs.HdfsConfiguration;\nimport org.apache.hadoop.hdfs.NameNodeProxies;\nimport org.apache.hadoop.hdfs.protocol.HdfsConstants;\nimport org.apache.hadoop.hdfs.server.common.HdfsServerConstants;\nimport org.apache.hadoop.hdfs.server.common.InconsistentFSStateException;\nimport org.apache.hadoop.hdfs.server.common.JspHelper;\nimport org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory;\nimport org.apache.hadoop.hdfs.server.common.Storage.StorageState;</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Haskell_>module Seal.Util.Json.Parse\n ( tryParseString\n , wrapConstructor\n ) where\n\nimport Universum\n\nimport Data.Typeable (typeRep)\nimport Text.JSON.Canonical (JSValue (..),\n ReportSchemaErrors (expected), expectedButGotValue)\n\ntryParseString ::\n forall a m e. (Typeable a, ReportSchemaErrors m, ToString e)\n => (Text -> Either e a)\n -> JSValue\n -> m a\ntryParseString parser =\n \\case\n JSString str ->\n case parser (toText str) of\n Right res -> pure res\n Left (toString -> err) ->\n expected typeName (Just $ str <> \", err was: \" <> err)\n val -> expectedButGotValue typeName val\n where\n typeName = show $ typeRep (Proxy @a)\n\nwrapConstructor ::\n forall e a m. (Typeable a, ReportSchemaErrors m, ToString e)\n => Either e a\n -> m a\nwrapConstructor =\n \\case\n Left err ->\n expected typeName (Just $ \"error occurred: \" <> toString err)\n Right x -> pure x\n where\n typeName = show $ typeRep (Proxy @a)\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_ObjectiveC_> fclose(fp);\n remove(writer_cstr);\n }\n \n BOOL autoLvlOK = &AVVideoProfileLevelH264MainAutoLevel != NULL;\n \n \n NSDictionary* settings = @{AVVideoCodecKey: AVVideoCodecH264,\n AVVideoCompressionPropertiesKey: @{AVVideoAverageBitRateKey: @(m_bitrate),\n AVVideoMaxKeyFrameIntervalKey: @(m_fps*2),\n AVVideoProfileLevelKey: (autoLvlOK ? AVVideoProfileLevelH264BaselineAutoLevel : AVVideoProfileLevelH264Main32),\n },\n AVVideoWidthKey: @(m_frameW),\n AVVideoHeightKey: @(m_frameH)\n };\n AVAssetWriterInput* input = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:settings];\n input.expectsMediaDataInRealTime = YES;\n \n NSURL* target = [NSURL fileURLWithPath:writer];\n m_assetWriters[wid] = [[AVAssetWriter alloc] initWithURL:target fileType:AVFileTypeQuickTimeMovie error:nil];\n m_pixelBuffers[wid] = [[AVAssetWriterInputPixelBufferAdaptor alloc] initWithAssetWriterInput:input sourcePixelBufferAttributes:nil];\n \n if([(id)m_assetWriters[wid] canAddInput:input]) {\n [(id)m_assetWriters[wid] addInput:input];\n } else {\n teardownWriter(wid);\n return false;\n }\n \n CMTime time = {0};\n time.timescale = m_fps;\n time.flags = kCMTimeFlags_Valid;\n \n [(id)m_assetWriters[wid] startWriting];\n [(id)m_assetWriters[wid] startSessionAtSourceTime:time];\n \n }\n return true;\n }\n void\n H264Encode::teardownWriter(int wid)\n {\n if(m_assetWriters[wid] != nullptr)\n {\n [(id)m_assetWriters[wid] release], m_assetWriters[wid] = nullptr;\n }\n if(m_pixelBuffers[wid] != nullptr)\n {\n [(id)m_pixelBuffers[wid] release], m_pixelBuffers[wid] = nullptr;\n }\n }\n void\n H264Encode::swapWriters( bool force )\n {\n if(force || ((m_frameCount++ > ((m_fps * 2) * 5)) && m_sps.size() && m_pps.size())) {\n // swap.\n int old = m_currentWriter;\n m_currentWriter = !m_currentWriter;\n m_frameCount = 0;\n m_lastFilePos = 36;\n m_queue.enqueue([this,old]() {\n#if 0\n [(id)this->m_assetWriters[old] finishWritingWithCompletionHandler:^{\n#endif\n this->teardownWriter(old);\n this->setupWriter(old);\n#if 0\n }];\n#endif\n });\n } else if(m_sps.size() == 0 || m_pps.size() == 0) {\n if(m_frameCount > 3) {\n // after one GOP stop movie and get the sps and pps.\n \n int old = m_currentWriter;\n m_currentWriter = !m_currentWriter;\n int lastFrame = m_frameCount;\n m_frameCount = 0;\n m_lastFilePos = 36;\n </code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_C++_>\t\tm_LayerInsertIndex++;\n\t}\n\n\tvoid LayerStack::PushOverlay(Layer* overlay)\n\t{\n\t\tm_Layers.emplace_back(overlay);\n\t}\n\n\tvoid LayerStack::PopLayer(Layer* layer)\n\t{\n\t\tauto it = std::find(m_Layers.begin(), m_Layers.end(), layer);\n\t\tif (it != m_Layers.end())\n\t\t{\n\t\t\tlayer->OnDetach();\n\t\t\tm_Layers.erase(it);\n\t\t\tm_LayerInsertIndex--;\n\t\t}\n\t}\n\n\tvoid LayerStack::PopOverlay(Layer* overlay)\n\t{\n\t\tauto it = std::find(m_Layers.begin(), m_Layers.end(), overlay);\n\t\tif (it != m_Layers.end()) \n\t\t{\n\t\t\toverlay->OnDetach();\n\t\t\tm_Layers.erase(it);\n\t\t}\n\t}\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Python_>\ndef search_rolling_hash(S, T):\n base = 1234\n mod = 10**9+7\n n, m = len(S), len(T)\n rolling_hash = [0]*(n-m+1) \n rolling_hash[0] = ord(S[0])\n b_m = pow(base, m, mod)\n T_hash = ord(T[0])\n start_index = []\n for i in range(1, m):\n rolling_hash[0]*=base\n rolling_hash[0]+=ord(S[i])\n rolling_hash[0]%=mod\n T_hash = (T_hash*base+ord(T[i]))%mod\n if rolling_hash[0] == T_hash: start_index.append(0)\n for i in range(1, ls):\n rolling_hash[i] = (rolling_hash[i-1]*base-ord(S[i-1])*b_m+ord(S[i+m-1]))%mod\n if rolling_hash[i] == T_hash: start_index.append(i)\n return start_index\nimport sys\ns = input()\nt = input()\nls, lt = len(s), len(t)\nS = s*(lt//ls+2)\nindex = search_rolling_hash(S, t)\nflag = [False]*ls\nfor i in index:\n flag[i] = True\nstack = []\ninf = float('inf')\ncnt = [inf]*ls\nfor i in range(ls):\n if flag[i] == False:\n stack.append(i)\n cnt[i] = 0\nwhile stack:\n x = stack.pop()\n y = (x-lt)%ls\n if cnt[y] == inf:\n cnt[y] = cnt[x]+1\n stack.append(y)\nans = max(cnt)\nif ans == inf:\n print(-1)\nelse:\n print(ans)</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Python_>import sys\ninput = sys.stdin.buffer.readline\nfrom collections import Counter\n\ndef main():\n N,M = map(int,input().split())\n x = list(map(int,input().split()))\n \n ml = [[] for _ in range(M)]\n for num in x:\n ml[num%M].append(num)\n\n cl = [[0,0] for _ in range(M)]\n for i in range(M):\n y = ml[i]\n c = tuple(Counter(y).values())\n for num in c:\n cl[i][0] += num//2*2\n cl[i][1] += num%2\n\n ans = (cl[0][0]+cl[0][1])//2\n for i in range(1,-(-M//2)):\n da,oa = cl[i]\n db,ob = cl[M-i]\n num = 0\n if oa >= ob:\n num += (ob+min(oa-ob,db)+da//2)\n else:\n num += (oa+min(ob-oa,da)+db//2)\n ans += num\n \n if M%2 == 0:\n m = M//2\n ans += (cl[m][0]+cl[m][1])//2\n \n print(ans)\n\nif __name__ == \"__main__\":\n main()</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Python_>print(round(int(input())/2))</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Python_># pylint: disable=E1101,E1103\n# pylint: disable=W0703,W0622,W0613,W0201\nfrom functools import partial\nimport itertools\n\nimport numpy as np\n\nfrom pandas._libs import algos as _algos, reshape as _reshape\nfrom pandas._libs.sparse import IntIndex\nfrom pandas.compat import PY2, range, text_type, u, zip\n\nfrom pandas.core.dtypes.cast import maybe_promote\nfrom pandas.core.dtypes.common import (\n ensure_platform_int, is_bool_dtype, is_extension_array_dtype, is_list_like,\n is_object_dtype, needs_i8_conversion)\nfrom pandas.core.dtypes.missing import notna\n\nfrom pandas import compat\nimport pandas.core.algorithms as algos\nfrom pandas.core.arrays import SparseArray\nfrom pandas.core.arrays.categorical import _factorize_from_iterable\nfrom pandas.core.frame import DataFrame\nfrom pandas.core.index import Index, MultiIndex\nfrom pandas.core.series import Series\nfrom pandas.core.sorting import (\n compress_group_index, decons_obs_group_ids, get_compressed_ids,\n get_group_index)\nfrom pandas.core.sparse.api import SparseDataFrame, SparseSeries\n\n\nclass _Unstacker(object):\n \"\"\"\n Helper class to unstack data / pivot with multi-level index\n\n Parameters\n ----------\n values : ndarray\n Values of DataFrame to \"Unstack\"\n index : object\n Pandas ``Index``\n level : int or str, default last level\n Level to \"unstack\". Accepts a name for the level.\n value_columns : Index, optional\n Pandas ``Index`` or ``MultiIndex`` object if unstacking a DataFrame\n fill_value : scalar, optional\n Default value to fill in missing values if subgroups do not have the\n same set of labels. By default, missing values will be replaced with\n the default fill value for that data type, NaN for float, NaT for\n datetimelike, etc. For integer types, by default data will converted to\n float and missing values will be set to NaN.\n constructor : object\n Pandas ``DataFrame`` or subclass used to create unstacked\n response. If None, DataFrame or SparseDataFrame will be used.\n\n Examples\n --------\n >>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),\n ... ('two', 'a'), ('two', 'b')])\n >>> s = pd.Series(np.arange(1, 5, dtype=np.int64), index=index)\n >>> s\n one a 1\n b 2\n two a 3\n b 4\n dtype: int64\n\n >>> s.unstack(level=-1)\n a b\n one 1 2\n two 3 4\n\n >>> s.unstack(level=0)\n one two\n a 1 3\n b 2 4\n\n Returns\n -------\n unstacked : DataFrame\n \"\"\"\n\n def __init__(self, values, index, level=-1, value_columns=None,\n fill_value=None, constructor=None):\n\n if values.ndim == 1:\n values = values[:, np.newaxis]\n self.values = values\n self.value_columns = value_columns\n self.fill_value = fill_value\n\n if constructor is None:\n constructor = DataFrame\n self.constructor = constructor\n\n if value_columns is None and values.shape[1] != 1: # pragma: no cover\n raise ValueError('must pass column labels for multi-column data')\n\n self.index = index.remove_unused_levels()\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Scala_>package codes.quine.labo.box2d\n\nimport minitest.SimpleTestSuite\n\nobject Mat22Suite extends SimpleTestSuite {\n test(\"Mat22.apply\") {\n val m1 = Mat22(Vec2(1, 2), Vec2(3, 4))\n val m2 = Mat22(1, 3, 2, 4)\n assert(m1 == m2)\n }\n\n test(\"Mat22.rotation\") {\n val m = Mat22.rotation(0)\n assertEquals(m, Mat22(1, 0, 0, 1))\n }\n\n test(\"Mat22#transpose\") {\n val m = Mat22(1, 2, 3, 4)\n assertEquals(m.transpose, Mat22(1, 3, 2, 4))\n }\n\n test(\"Mat22#invert\") {\n val m = Mat22(1, 2, 3, 4)\n assertEquals(m.invert * m, Mat22(1, 0, 0, 1))\n assertEquals(m * m.invert, Mat22(1, 0, 0, 1))\n }\n\n test(\"Mat22#*\") {\n val m1 = Mat22(2, 0, 0, 3)\n val m2 = Mat22(1, 4, 2, 3)\n val v = Vec2(1, 2)\n assertEquals(m1 * v, Vec2(2, 6))\n assertEquals(m1 * m2, Mat22(2, 8, 6, 9))\n }\n\n test(\"Mat22#+\") {\n val m1 = Mat22(1, 2, 3, 4)\n val m2 = Mat22(4, 3, 2, 1)\n assertEquals(m1 + m2, Mat22(5, 5, 5, 5))\n }\n\n test(\"Mat22#equals\") {\n val m1 = Mat22(1, 2, 3, 4)\n val m2 = Mat22(1, 2, 3, 4)\n val m3 = Mat22(3, 4, 5, 6)\n assert(m1 == m2)\n assert(m1 != m3)\n }\n\n test(\"Mat22#toString\") {\n val m = Mat22(0.5f, 1.5f, 2.5f, 3.5f)\n assertEquals(m.toString, \"Mat22(0.5, 1.5, 2.5, 3.5)\")\n }\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Python_>\"\"\".format(filename)\n super(MyIOError, self).__init__(message)\n\nclass word2vec(object):\n def __init__(self,model_path,binary=True):\n model = gensim.models.KeyedVectors.load_word2vec_format(model_path, binary=binary)\n print(\"Successfully loaded word2vec file!\")\n self.word_vectors = model.wv\n self.vocab= list((dict(self.word_vectors.vocab).keys()))\n\nclass CoNLLDataset(object):\n \"\"\"Class that iterates over CoNLL Dataset\n\n __iter__ method yields a tuple (words, tags)\n words: list of raw words\n tags: list of raw tags\n\n If processing_word and processing_tag are not None,\n optional preprocessing is appplied\n\n Example:\n ```python\n data = CoNLLDataset(filename)\n for sentence, tags in data:\n pass\n ```\n\n \"\"\"\n def __init__(self, filename, processing_word=None, processing_tag=None,\n max_iter=None):\n \"\"\"\n Args:\n filename: path to the file\n processing_words: (optional) function that takes a word as input\n processing_tags: (optional) function that takes a tag as input\n max_iter: (optional) max number of sentences to yield\n\n \"\"\"\n self.filename = filename\n self.processing_word = processing_word\n self.processing_tag = processing_tag\n self.max_iter = max_iter\n self.length = None\n\n\n def __iter__(self):\n niter = 0\n with open(self.filename) as f:\n words, tags = [], []\n for line in f:\n line = line.strip()\n if (len(line) == 0 or line.startswith(\"-DOCSTART-\")):\n if len(words) != 0:\n niter += 1\n if self.max_iter is not None and niter > self.max_iter:\n break\n yield words, tags\n words, tags = [], []\n else:\n ls = line.split(' ')\n word, tag = ls[0],ls[-1]\n if self.processing_word is not None:\n word = self.processing_word(word)\n if self.processing_tag is not None:\n tag = self.processing_tag(tag)\n words += [word]\n tags += [tag]\n\n\n def __len__(self):\n \"\"\"Iterates once over the corpus to set and store length\"\"\"\n if self.length is None:\n self.length = 0\n for _ in self:\n self.length += 1\n\n return self.length\n\n\ndef get_vocabs(datasets):\n \"\"\"Build vocabulary from an iterable of datasets objects\n\n Args:\n datasets: a list of dataset objects\n\n Returns:\n a set of all the words in the dataset\n\n \"\"\"\n print(\"Building vocab...\")\n vocab_words = set()\n vocab_tags = set()\n for dataset in datasets:\n for words, tags in dataset:\n vocab_words.update(words)\n vocab_tags.update(tags)\n print(\"- done. {} tokens\".format(len(vocab_words)))\n return vocab_words, vocab_tags\n\n\ndef get_char_vocab(dataset):\n \"\"\"Build char vocabulary from an iterable of datasets objects\n\n Args:\n dataset: a iterator yielding tuples (sentence, tags)\n\n Returns:\n a set of all the characters in the dataset\n\n \"\"\"\n vocab_char = set()\n for words, _ in dataset:\n for word in words:\n vocab_char.update(word)\n\n return vocab_char\n\n\ndef get_glove_vocab(filename):\n \"\"\"Load vocab from file\n\n Args:\n filename: path to the glove vectors\n\n Returns:\n vocab: set() of strings\n \"\"\"\n print(\"Building vocab...\")\n vocab = set()\n with open(filename) as f:\n for line in f:\n word = line.strip().split(' ')[0]\n vocab.add(word)\n print(\"- done. {} tokens\".format(len(vocab)))\n return vocab\n\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Python_>\nh, w = map(int, input().split())\nprint(-(-h * w // 2))</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_TypeScript_>/*\n * Copyright 2019 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {MithrilViewComponent} from \"jsx/mithril-component\";\nimport m from \"mithril\";\nimport Stream from \"mithril/stream\";\nimport {GoCDAttributes} from \"models/roles/roles\";\nimport styles from \"./index.scss\";\n\ninterface UsersWidgetAttrs {\n roleAttributes: Stream<GoCDAttributes>;\n selectedUser?: string;\n readOnly?: boolean;\n}\n\nexport class UsersWidget extends MithrilViewComponent<UsersWidgetAttrs> {\n view(vnode: m.Vnode<UsersWidgetAttrs>): m.Children | void | null {\n return vnode.attrs.roleAttributes().users.map((user) => {\n const isSelectedUser = user === vnode.attrs.selectedUser;</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Clojure_>(ns satellite-clj.ephemeris\n \"Functions for satellite ephemeris propagation.\"\n (:require [satellite-clj.math :as m]\n [satellite-clj.orbit :as orbit]\n [satellite-clj.time :as time])\n (:import [uk.me.g4dpz.satellite SatelliteFactory TLE]))\n\n;;;; NORAD TLE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n(defn str->tle\n \"Convert a Two Line Element (TLE) set, into a usable predict4java TLE\n object. Takes a single vector containing text strings of the form\n [name first-line second-line] where:\n\n name - The name of the spacecraft \n first-line - Line 1 of the orbital elements \n second-line - Line 2 of the orbital elements\n\n Returns a predict4java TLE object for use with the SGP4 propagator.\"\n [tle]\n (TLE. ^\"[Ljava.lang.String;\" (into-array String tle)))\n\n(defn valid-tle?\n \"Determine if a Two Line Element Set (TLE) is valid based on the checksum\n value for each line. Takes a single vector containing text strings of the\n form [name first-line second-line] where:\n\n name - The name of the spacecraft \n first-line - Line 1 of the orbital elements \n second-line - Line 2 of the orbital elements\n\n Returns true if the TLE vector appears properly formatted and passes a\n checksum.\"\n [[name first-line second-line :as tle]]\n (let [char->int #(Character/getNumericValue ^char %)\n digits (set (map char (range 48 58)))\n replace-dash #(clojure.string/replace % \"-\" \"1\")\n valid? #(= (mod (reduce + (butlast %)) 10) (last %))\n tle-clean (->> (map replace-dash (rest tle))\n (map #(filter digits (apply vector %)))\n (map #(map char->int (apply vector %))))]\n (and (not (clojure.string/blank? (.trim (str name))))\n (not (clojure.string/blank? (.trim (str first-line))))\n (not (clojure.string/blank? (.trim (str second-line))))\n (every? true? (map valid? tle-clean)))))\n\n;;;; SGP4 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n(defn sgp4\n \"Propagate satellite ephemeris using a Two Line Element (TLE) set. Takes two\n arguments:\n\n tle - Vector containing tle data (see valid-tle?) \n date - A java.util.Date object used as the propagation time\n\n Returns the satellite's location as a vector containing the [lat lon alt]\n in degrees and meters.\"\n [tle date]\n (let [tle (str->tle tle)\n factory (doto (SatelliteFactory/createSatellite tle)\n (.calculateSatelliteVectors date))\n position (.calculateSatelliteGroundTrack factory)\n lat (Math/toDegrees (.getLatitude position))\n temp-lon (Math/toDegrees (.getLongitude position))\n lon (cond\n (> temp-lon 180) (- temp-lon 360)\n (neg? temp-lon) (+ temp-lon 360)\n :else temp-lon)\n alt (.getAltitude position)]\n [lat lon alt]))\n\n;; Perturbations ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n(defn sma-rate\n [semi-major-axis time-derivative]\n (let [a semi-major-axis\n nd (* 2 time-derivative)</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Python_>from django.db import models\n\nfrom django.contrib.auth import get_user_model\n\n\nclass Fund(models.Model):\n '''Model represents and stores funds.'''\n\n user = models.ForeignKey(\n get_user_model(),\n on_delete=models.CASCADE,\n null=False,\n blank=False,\n )\n\n code = models.CharField(\n max_length=8,\n null=False,\n blank=False,\n )\n\n name = models.CharField(\n max_length=128,\n null=False,\n blank=False,\n )\n\n class Meta:\n unique_together = (\n ('user', 'code'),\n ('user', 'name'),\n )\n\n index_together = (\n ('user', 'code'),\n ('user', 'name'),\n )\n\n def save(self, *args, **kwargs):\n\n # Remove leading or trailing spaces from strings\n for field in self._meta.fields:\n if isinstance(field, (models.CharField, models.TextField)):\n value = getattr(self, field.name)\n if value:\n setattr(self, field.name, value.strip())\n\n # Field validations run here\n self.full_clean()\n\n super().save(*args, **kwargs)\n\n def update(self, **fields):\n '''Updates and returns a fund.'''\n\n for key, value in fields.items():\n setattr(self, key, value)\n\n self.save()\n\n return self\n\n def __str__(self):\n return f'{self.name}'\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Python_>N = int(input())\ns = input()\n\ne = [0]\nw = [0]\n\nte, tw = 0, 0\nfor i in range(N):\n if s[i] == 'E':\n te += 1\n else:\n tw += 1\n e.append(te)\n w.append(tw)\n\nans = N\nfor leader_idx in range(N):\n t = 0\n t += (e[N] - e[leader_idx + 1])\n t += (w[leader_idx] - w[0])\n ans = min(ans, t)\nprint(ans)\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_C++_>\n// (C) Copyright John Maddock 2017. \n// Use, modification and distribution are subject to the \n// Boost Software License, Version 1.0. (See accompanying file \n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n# include <boost/type_traits/is_convertible.hpp>\n#include \"../test.hpp\"\n\nint main()\n{\n return boost::is_convertible<UDT, incomplete_type>::value;\n}\n\n\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_C++_> }\n\n int padding_planes = dims.SpatialPadding(padding_, 0);\n int padding_rows = dims.SpatialPadding(padding_, 1);\n int padding_cols = dims.SpatialPadding(padding_, 2);\n const bool planes_odd = (padding_planes % 2 != 0);\n const bool rows_odd = (padding_rows % 2 != 0);\n const bool cols_odd = (padding_cols % 2 != 0);\n\n TensorShape compatible_input_shape;\n if (rows_odd || cols_odd || planes_odd) {\n // cuDNN only supports the same amount of padding on both sides.\n compatible_input_shape = {\n dims.batch_size,\n dims.in_depth,\n dims.input_size(0) + planes_odd,\n dims.input_size(1) + rows_odd,\n dims.input_size(2) + cols_odd,\n };\n } else {\n compatible_input_shape = {dims.batch_size, dims.in_depth,\n dims.input_size(0), dims.input_size(1),\n dims.input_size(2)};\n }\n\n CHECK(padding_rows >= 0 && padding_cols >= 0 && padding_planes >= 0)\n << \"Negative paddings: (\" << padding_rows << \", \" << padding_cols\n << \", \" << padding_planes << \")\";\n se::dnn::BatchDescriptor input_desc(3);\n input_desc.set_count(dims.batch_size)\n .set_spatial_dim(DimIndex::X, compatible_input_shape.dim_size(4))\n .set_spatial_dim(DimIndex::Y, compatible_input_shape.dim_size(3))\n .set_spatial_dim(DimIndex::Z, compatible_input_shape.dim_size(2))\n .set_feature_map_count(dims.in_depth)\n .set_layout(se::dnn::DataLayout::kBatchDepthYX);\n se::dnn::BatchDescriptor output_desc(3);\n output_desc.set_count(dims.batch_size)\n .set_spatial_dim(DimIndex::X, dims.output_size(2))\n .set_spatial_dim(DimIndex::Y, dims.output_size(1))\n .set_spatial_dim(DimIndex::Z, dims.output_size(0))\n .set_feature_map_count(dims.out_depth)\n .set_layout(se::dnn::DataLayout::kBatchDepthYX);\n se::dnn::FilterDescriptor filter_desc(3);\n filter_desc.set_spatial_dim(DimIndex::X, dims.filter_size(2))\n .set_spatial_dim(DimIndex::Y, dims.filter_size(1))\n .set_spatial_dim(DimIndex::Z, dims.filter_size(0))\n .set_input_feature_map_count(filter_shape.dim_size(3))\n .set_output_feature_map_count(filter_shape.dim_size(4));\n se::dnn::ConvolutionDescriptor conv_desc(3);\n conv_desc.set_dilation_rate(DimIndex::X, dims.dilation(2))\n .set_dilation_rate(DimIndex::Y, dims.dilation(1))\n .set_dilation_rate(DimIndex::Z, dims.dilation(0))\n .set_filter_stride(DimIndex::X, dims.stride(2))\n .set_filter_stride(DimIndex::Y, dims.stride(1))\n .set_filter_stride(DimIndex::Z, dims.stride(0))\n .set_zero_padding(DimIndex::X, padding_cols / 2)\n .set_zero_padding(DimIndex::Y, padding_rows / 2)\n .set_zero_padding(DimIndex::Z, padding_planes / 2)\n .set_group_count(dims.in_depth / filter_shape.dim_size(3));\n\n // Shape: out, in, z, y, x.\n Tensor transformed_filter;\n OP_REQUIRES_OK(\n context, context->allocate_temp(\n DataTypeToEnum<T>::value,\n TensorShape({filter_shape.dim_size(4),\n filter_shape.dim_size(3), dims.filter_size(0),\n dims.filter_size(1), dims.filter_size(2)}),\n &transformed_filter));\n functor::TransformFilter<GPUDevice, T, int, 5>()(\n context->eigen_device<GPUDevice>(), FORMAT_OIHW,\n To32Bit(filter.tensor<T, 5>()),\n To32Bit(transformed_filter.tensor<T, 5>()));\n\n // Shape: batch, filters, z, y, x.\n Tensor transformed_out_backprop;\n if (data_format_ == FORMAT_NHWC) {\n TensorShape nchw_shape = {dims.batch_size, dims.out_depth,\n dims.output_size(0), dims.output_size(1),\n dims.output_size(2)};\n if (dims.out_depth > 1) {\n OP_REQUIRES_OK(context, context->allocate_temp(\n DataTypeToEnum<T>::value, nchw_shape,\n &transformed_out_backprop));\n functor::NHWCToNCHW<GPUDevice, T, 5>()(\n context->eigen_device<GPUDevice>(), out_backprop.tensor<T, 5>(),\n transformed_out_backprop.tensor<T, 5>());\n } else {\n CHECK(transformed_out_backprop.CopyFrom(out_backprop, nchw_shape));\n }\n } else {\n transformed_out_backprop = out_backprop;\n }\n // Shape: batch, filters, z, y, x.\n Tensor pre_transformed_in_backprop;\n OP_REQUIRES_OK(\n context,\n context->allocate_temp(DataTypeToEnum<T>::value, compatible_input_shape,\n &pre_transformed_in_backprop));\n\n auto out_backprop_ptr =\n AsDeviceMemory(transformed_out_backprop.template flat<T>().data(),\n transformed_out_backprop.template flat<T>().size());\n auto filter_ptr =\n AsDeviceMemory(transformed_filter.template flat<T>().data(),\n transformed_filter.template flat<T>().size());\n auto in_backprop_ptr =\n AsDeviceMemory(pre_transformed_in_backprop.template flat<T>().data(),\n pre_transformed_in_backprop.template flat<T>().size());\n\n static int64 ConvolveBackwardDataScratchSize = GetDnnWorkspaceLimit(\n \"TF_CUDNN_WORKSPACE_LIMIT_IN_MB\", 1LL << 32); // 4GB by default\n\n const int device_id = stream->parent()->device_ordinal();\n DataType dtype = context->input(0).dtype();\n const ConvParameters conv_parameters = {\n dims.batch_size,\n dims.in_depth,\n {{dims.input_size(0), dims.input_size(1), dims.input_size(2)}},\n FORMAT_NCHW,\n dims.out_depth,\n {{dims.filter_size(0), dims.filter_size(1), dims.filter_size(2)}},\n {{dims.dilation(0), dims.dilation(1), dims.dilation(2)}},\n {{dims.stride(0), dims.stride(1), dims.stride(2)}},\n {{padding_planes, padding_rows, padding_cols}},\n dtype,\n device_id,\n conv_desc.group_count()};\n\n using se::dnn::AlgorithmConfig;\n using se::dnn::AlgorithmDesc;\n using se::dnn::ProfileResult;\n AlgorithmConfig algorithm_config;\n if (cudnn_use_autotune_ && !AutoTuneConv3dBwdData::GetInstance()->Find(\n conv_parameters, &algorithm_config)) {\n#if GOOGLE_CUDA\n se::TfAllocatorAdapter tf_allocator_adapter(\n context->device()->GetAllocator({}), stream);\n se::RedzoneAllocator rz_allocator(stream, &tf_allocator_adapter,\n se::GpuAsmOpts());\n se::DeviceMemory<T> in_backprop_ptr_rz(\n WrapRedzoneBestEffort(&rz_allocator, in_backprop_ptr));\n std::vector<AlgorithmDesc> algorithms;\n CHECK(stream->parent()->GetConvolveBackwardDataAlgorithms(</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Scala_>object Main {\n def main(args: Array[String]): Unit = {\n import scala.io.StdIn.readLine\n val datS = readLine\n val datT = readLine\n\n var ans = 0;\n (0 until datS.length) foreach { i =>\n if (datS(i) != datT(i)) ans += 1\n }\n\n println(ans)\n }\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_D_>import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;\n\nenum R = [\n \"SUN\": 7,\n \"MON\": 6,\n \"TUE\": 5,\n \"WED\": 4,\n \"THU\": 3,\n \"FRI\": 2,\n \"SAT\": 1\n];\n\nvoid main()\n{\n writeln(R[readln.chomp]);\n}</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Java_>import java.util.Scanner;\nimport java.util.Arrays;\n\npublic class Main {\n\n public static void main(String[] args) {\n new Main().solve();\n }\n\n void solve() {\n Scanner sc = new Scanner(System.in);\n int n = sc.nextInt();\n long[] a = new long[n];\n long A = 0;\n long ANS = 0;\n long ans = 0;\n long q = 1;\n a[0] = sc.nextLong();\n A = a[0];\n for (int i = 1; i < n; i++) {\n a[i] = sc.nextLong();\n A += a[i];\n q = q * -1;\n if (A <= 0 && q == 1) {\n ans += Math.abs(A - 1);\n A += Math.abs(A - 1);\n } else if (A >= 0 && q == -1) {\n ans += Math.abs(A + 1);\n A -= Math.abs(A + 1);\n }\n }\n ANS = ans;\n A = a[0];\n ans = 0;\n q = -1;\n for (int i = 0; i < n; i++) {\n A += a[i];\n q = q * -1;\n if (A <= 0 && q == 1) {\n ans += Math.abs(A - 1);\n A += Math.abs(A - 1);\n } else if (A >= 0 && q == -1) {\n ans += Math.abs(A + 1);\n A -= Math.abs(A + 1);\n }\n }\n ANS = Math.min(ANS, ans);\n System.out.println(ANS);\n }\n}</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_C++_> Task::Task()\n : BackgroundJob( true /* deleteSelf */ ) {\n n = 0;\n repeat = 0;\n }\n\n void Task::halt() { repeat = 0; }\n\n void Task::setUp() {}\n\n void Task::run() {\n verify( n == 0 );\n\n setUp();\n\n while( 1 ) {\n n++;\n try {\n doWork();\n }\n catch(...) { }\n sleepmillis(repeat);\n if( inShutdown() )\n break;\n if( repeat == 0 )\n break;\n }\n }\n\n void Task::begin() {\n go();\n }\n\n void fork(Task *t) {\n t->begin();\n }\n\n void repeat(Task *t, unsigned millis) {\n t->repeat = millis;\n t->begin();\n }\n\n }\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_SML_>(*\n * How to represent a predicate so that various logical operations can\n * be performed.\n *\n * -- Allen ([email protected])\n *)\nfunctor SSAPredicate(T : MLTREE) : SSA_PREDICATE =\nstruct\n structure T = T\n\n datatype expr = FALSE | TRUE | IF of T.ty * T.Basis.cond * expr * expr\n\n fun toString : expr -> string\n\n fun And : expr * expr -> expr\n fun Or : expr * expr -> expr\n fun Not : expr -> expr\n\n fun isDisjoint : expr * expr -> bool\n fun implies : expr * expr -> bool\n\nend\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_CSS_>body {\n font-family: \"Comic Sans\", sans-serif; /* try roboto, otherwise try this generic family */\n font-weight: 400;\n color: #b9b9b9;\n background-color: black;\n}\n\np {\n text-align: center;\n}\n\na:link {\n color: #03dac5; /* Colors from https://material.io/design/color/dark-theme.html#ui-application */\n}\n\na:visited {\n color: #bb86fc;\n}\n\n/* Header styles */\nheader nav {\n padding: 16px 0;\n\n font-weight: 400;\n}\n\nheader nav a {\n margin-right: 16px;\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Python_>import dataclasses\n\nfrom covid.types.blockchain_format.sized_bytes import bytes32\nfrom covid.util.byte_types import hexstr_to_bytes\nfrom covid.util.ints import uint8, uint32, uint64, uint128\n\n\[email protected](frozen=True)\nclass ConsensusConstants:\n SLOT_BLOCKS_TARGET: uint32 # How many blocks to target per sub-slot\n MIN_BLOCKS_PER_CHALLENGE_BLOCK: uint8 # How many blocks must be created per slot (to make challenge sb)\n # Max number of blocks that can be infused into a sub-slot.\n # Note: this must be less than SUB_EPOCH_BLOCKS/2, and > SLOT_BLOCKS_TARGET\n MAX_SUB_SLOT_BLOCKS: uint32\n NUM_SPS_SUB_SLOT: uint32 # The number of signage points per sub-slot (including the 0th sp at the sub-slot start)\n\n SUB_SLOT_ITERS_STARTING: uint64 # The sub_slot_iters for the first epoch\n DIFFICULTY_CONSTANT_FACTOR: uint128 # Multiplied by the difficulty to get iterations\n DIFFICULTY_STARTING: uint64 # The difficulty for the first epoch\n # The maximum factor by which difficulty and sub_slot_iters can change per epoch\n DIFFICULTY_CHANGE_MAX_FACTOR: uint32\n SUB_EPOCH_BLOCKS: uint32 # The number of blocks per sub-epoch\n EPOCH_BLOCKS: uint32 # The number of blocks per sub-epoch, must be a multiple of SUB_EPOCH_BLOCKS\n\n SIGNIFICANT_BITS: int # The number of bits to look at in difficulty and min iters. The rest are zeroed\n DISCRIMINANT_SIZE_BITS: int # Max is 1024 (based on ClassGroupElement int size)\n NUMBER_ZERO_BITS_PLOT_FILTER: int # H(plot id + challenge hash + signage point) must start with these many zeroes\n MIN_PLOT_SIZE: int\n MAX_PLOT_SIZE: int\n SUB_SLOT_TIME_TARGET: int # The target number of seconds per sub-slot\n NUM_SP_INTERVALS_EXTRA: int # The difference between signage point and infusion point (plus required_iters)\n MAX_FUTURE_TIME: int # The next block can have a timestamp of at most these many seconds more\n NUMBER_OF_TIMESTAMPS: int # Than the average of the last NUMBER_OF_TIMESTAMPS blocks\n # Used as the initial cc rc challenges, as well as first block back pointers, and first SES back pointer\n # We override this value based on the chain being run (testnet0, testnet1, mainnet, etc)\n GENESIS_CHALLENGE: bytes32\n # Forks of covid should change this value to provide replay attack protection\n AGG_SIG_ME_ADDITIONAL_DATA: bytes\n GENESIS_PRE_FARM_POOL_PUZZLE_HASH: bytes32 # The block at height must pay out to this pool puzzle hash\n GENESIS_PRE_FARM_FARMER_PUZZLE_HASH: bytes32 # The block at height must pay out to this farmer puzzle hash\n MAX_VDF_WITNESS_SIZE: int # The maximum number of classgroup elements within an n-wesolowski proof\n # Size of mempool = 10x the size of block\n MEMPOOL_BLOCK_BUFFER: int\n # Max coin amount uint(1 << 64). This allows coin amounts to fit in 64 bits. This is around 18M covid.\n MAX_COIN_AMOUNT: int\n # Max block cost in clvm cost units\n MAX_BLOCK_COST_CLVM: int\n # Cost per byte of generator program\n COST_PER_BYTE: int\n\n WEIGHT_PROOF_THRESHOLD: uint8\n WEIGHT_PROOF_RECENT_BLOCKS: uint32\n MAX_BLOCK_COUNT_PER_REQUESTS: uint32\n BLOCKS_CACHE_SIZE: uint32\n NETWORK_TYPE: int\n MAX_GENERATOR_SIZE: uint32\n MAX_GENERATOR_REF_LIST_SIZE: uint32\n POOL_SUB_SLOT_ITERS: uint64\n\n def replace(self, **changes) -> \"ConsensusConstants\":</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Go_>package main\n\nimport \"fmt\"\n\nfunc main() {\n\n\tvar a, b int\n\n\tfmt.Scanln(&a, &b)\n\n\tfmt.Printf(\"%v %v %f\\n\", a/b, a%2, float64(a)/float64(b))\n\n}\n\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_JavaScript_>import React, { Component} from 'react'\nimport {elements} from '../base'\nimport Recipe from './Recipe'\n\n\n\n\nexport default class Top extends Component{\n constructor (props) {\n super(props)\n this.handleSubmit = this.handleSubmit.bind(this)\n this.savedRecipes = this.savedRecipes.bind(this)</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_HTML_><h1>TODO: Add Transactions list here</h1>\n<ol>\n <li>\n NB: Create a reusable search component and use it here to serach a\n transaction by transaction ID)\n </li>\n <li></li>\n <li>Display the search results in the table below</li>\n</ol>\n\n<app-search\n (messageEvent)=\"receiveTransList($event)\"\n [transType]=\"transType\"\n></app-search>\n\n<table class=\"table\">\n <thead>\n <tr>\n <th>Transaction Id</th>\n <th>Customer Id</th>\n <th>Account No</th>\n <th>Amount</th>\n <th>Balance</th>\n <th>Trn Type</th>\n <th>Debit/Credit</th>\n </tr>\n </thead>\n <tbody>\n <tr *ngFor=\"let tran of transList\">\n <td>{{ tran.transactionId }}</td>\n <td>{{ tran.customerId }}</td>\n <td>{{ tran.accountNo }}</td>\n <td>{{ tran.amount }}</td>\n <td>{{ tran.balance }}</td>\n <td>{{ tran.transactionType }}</td>\n <td>{{ tran.debitOrCredit }}</td>\n </tr>\n </tbody>\n</table>\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Python_>import fractions\n\nA,B,C,D = map(int,input().split())\nA -= 1\ng = fractions.gcd(C, D)\nl = C * D / g\n\nsA = A // C\neA = A // D\nlA = A - (eA + sA) + A // l\n\nsB = B // C\neB = B // D\nlB = B - (eB + sB) + B // l\nprint(int(lB - lA))\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Java_>/*\n * Copyright © 2019 Cask Data, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n\npackage co.cask.cdap.security.store.client;\n\nimport co.cask.cdap.api.security.store.SecureStore;\nimport co.cask.cdap.api.security.store.SecureStoreData;\nimport co.cask.cdap.api.security.store.SecureStoreManager;\nimport co.cask.cdap.api.security.store.SecureStoreMetadata;\nimport co.cask.cdap.common.SecureKeyAlreadyExistsException;\nimport co.cask.cdap.common.SecureKeyNotFoundException;\nimport co.cask.cdap.common.conf.Constants;\nimport co.cask.cdap.common.http.DefaultHttpRequestConfig;\nimport co.cask.cdap.common.internal.remote.RemoteClient;\nimport co.cask.cdap.proto.id.SecureKeyId;\nimport co.cask.cdap.proto.security.SecureKeyCreateRequest;\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.gson.Gson;\nimport com.google.gson.reflect.TypeToken;\nimport com.google.inject.Inject;\nimport io.cdap.common.http.HttpMethod;\nimport io.cdap.common.http.HttpRequest;\nimport io.cdap.common.http.HttpResponse;\nimport org.apache.twill.discovery.DiscoveryServiceClient;\n\nimport java.io.IOException;\nimport java.lang.reflect.Type;\nimport java.net.HttpURLConnection;\nimport java.util.List;\nimport java.util.Map;\nimport javax.annotation.Nullable;\n\n/**\n * The client side implementation of {@link SecureStore} and {@link SecureStoreManager} which uses rest apis to get\n * sensitive data. This class is meant to be used internally and should not be exposed to end user.\n */\npublic class RemoteSecureStore implements SecureStoreManager, SecureStore {\n private static final Type LIST_TYPE = new TypeToken<List<SecureStoreMetadata>>() { }.getType();\n private static final Gson GSON = new Gson();\n private final RemoteClient remoteClient;\n\n @VisibleForTesting\n @Inject\n RemoteSecureStore(DiscoveryServiceClient discoveryServiceClient) {\n this.remoteClient = new RemoteClient(discoveryServiceClient, Constants.Service.SECURE_STORE_SERVICE,\n new DefaultHttpRequestConfig(), \"/v3/namespaces/\");\n }\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Java_>import java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.*;\n\npublic class Main {\n private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n private static final int MAX = 1000000;\n private static boolean isPrime[];\n\n public static void main(String[] args) throws Exception{\n int[] temp = readIntArray();\n int n = temp[0];\n int m = temp[1];\n int k = temp[2];\n long[] a = readLongArray();\n long[] b = readLongArray();\n TreeMap<Long,Integer> bMap = new TreeMap<>();\n for(int i=1;i<a.length;i++){\n a[i] += a[i-1];\n }\n bMap.put(b[0],0);\n for(int i=1;i<b.length;i++){\n b[i] += b[i-1];\n bMap.put(b[i],i);\n }\n int ans = 0;\n for(int i=0;i<a.length;i++){\n if(k==a[i])\n ans = Math.max(i+1,ans);\n if(bMap.floorEntry(k-a[i])!=null){\n ans = Math.max(ans,\n i+bMap.floorEntry(k-a[i]).getValue()+2\n );\n }\n }\n System.out.println(ans);\n }\n\n private static List<Integer> preprocessPrimes(int limit){\n isPrime = new boolean[limit+1];\n List<Integer> primes = new ArrayList<>();\n Arrays.fill(isPrime,true);\n isPrime[0] = isPrime[1] = false;\n int sqrt = (int)Math.sqrt(limit);\n for(int i=2;i<=sqrt;){\n for(int j=i*i;j<=limit;j+=i){\n isPrime[j] = false;\n }\n i++;\n while(i<=sqrt && !isPrime[i])\n i++;\n }\n for(int i=2;i<=limit;i++){\n if(isPrime[i])\n primes.add(i);\n }\n return primes;\n }\n\n private static int pow(int base,int exp,int MOD){\n if(exp==0)\n return 1;\n if(base==1 || exp==1)\n return base%MOD;\n int part = pow(base,exp/2,MOD);\n part*=part;\n part%=MOD;\n if(exp%2==1){\n part*=base;\n part%=MOD;\n }\n return part;\n }\n\n private static long pow(long base,long exp,long MOD){\n if(exp==0)\n return 1;\n if(base==1 || exp==1)\n return base%MOD;\n long part = pow(base,exp/2,MOD);\n part*=part;\n part%=MOD;\n if(exp%2==1){\n part*=base;\n part%=MOD;\n }\n return part;\n }\n\n private static int gcd(int max,int min){\n if(min==0){\n return max;\n }\n return gcd(min,max%min);\n }\n\n private static long gcd(long max,long min){\n if(min==0){\n return max;\n }\n return gcd(min,max%min);\n }\n\n private static int lcm(int max,int min){\n int gcd = gcd(max,min);\n return (max/gcd)*min;\n }\n\n private static long lcm(long max,long min){\n long gcd = gcd(max,min);\n return (max/gcd)*min;\n }\n\n private static int gcd(int[] nums){\n int gcd = nums[0];\n for(int i=1;i<nums.length;i++){\n gcd = gcd(Math.max(gcd,nums[i]),Math.min(gcd,nums[i]));\n }\n return gcd;\n }\n\n private static long gcd(long[] nums){\n long gcd = nums[0];\n for(int i=1;i<nums.length;i++){\n gcd = gcd(Math.max(gcd,nums[i]),Math.min(gcd,nums[i]));\n }\n return gcd;\n }\n\n private static int lcm(int[] nums){\n if(nums.length<2)\n return nums[0];\n int lcm = lcm(Math.max(nums[0],nums[1]),Math.min(nums[0],nums[1]));\n for(int i=2;i<nums.length;i++){\n lcm = lcm(lcm,nums[i]);\n }\n return lcm;\n }\n\n private static long lcm(long[] nums){\n if(nums.length<2)\n return nums[0];\n long lcm = lcm(Math.max(nums[0],nums[1]),Math.min(nums[0],nums[1]));\n for(int i=2;i<nums.length;i++){\n lcm = lcm(lcm,nums[i]);\n }\n return lcm;\n }\n\n public static int readInt() throws Exception{\n return Integer.parseInt(br.readLine());\n }\n public static long readLong() throws Exception {\n return Long.parseLong(br.readLine());\n }\n public static double readDouble() throws Exception {\n return Double.parseDouble(br.readLine());\n }\n public static String readLine() throws Exception{\n return br.readLine();\n }\n public static int[] readIntArray() throws Exception{\n String[] tokens = br.readLine().split(\" \");\n int[] nums = new int[tokens.length];\n for(int i=0;i<tokens.length;i++){\n nums[i] = Integer.parseInt(tokens[i]);\n }\n return nums;\n }\n public static long[] readLongArray() throws Exception{\n String[] tokens = br.readLine().split(\" \");\n long[] nums = new long[tokens.length];\n for(int i=0;i<tokens.length;i++){\n nums[i] = Long.parseLong(tokens[i]);\n }\n return nums;\n }\n public static double[] readDoubleArray() throws Exception {\n String[] tokens = br.readLine().split(\" \");\n double[] nums = new double[tokens.length];\n for(int i=0;i<tokens.length;i++){\n nums[i] = Double.parseDouble(tokens[i]);\n }\n return nums;\n }\n public static String[] readWords() throws Exception {\n return br.readLine().split(\" \");\n }\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Python_># coding=utf-8\n#! ./kt/bin/python\n\nfrom flask_script import Manager, Shell\nfrom flask_migrate import Migrate, MigrateCommand\nfrom app import create_app, db\n\napp = create_app(config_name='default')\nmigrate = Migrate(app, db)\n\ndef _make_context():\n return dict(app=app, db=db)\n\nmanager = Manager(app)\nmanager.add_command('db', MigrateCommand)\nmanager.add_command('shell', Shell(make_context=_make_context))\n\nif __name__ == '__main__':\n manager.run()\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Ruby_>r='#'\nloop do\nh,w=gets.split.map &:to_i\nbreak if h==0 && w==0\nputs r*w\nv=(w-2) * '.'\n(h-2).times do \n puts \"r + v + r\"\nend\nputs r*w\nputs \"\"\nend\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_ObjectiveC_>// Copyright 2017 The Lynx Authors. All rights reserved.\n\n#include \"base/render_tree_host_impl_bridge.h\"\n\n#include \"render/ios/render_tree_host_impl_ios.h\"\n#include \"render/ios/render_object_impl_ios.h\"\n\n@implementation RenderTreeHostImplBridge\n\n- (id) initWithRenderTreeHost:(lynx::RenderTreeHostImplIOS *) renderTreeHostImpl\n andRenderObjectImpl:(lynx::RenderObjectImplIOS *) renderObjectImpl {\n self = [super init];\n if (self) {\n render_tree_host_impl_ = renderTreeHostImpl;\n _rootRenderObjectImpl = renderObjectImpl->renderer_bridge();\n _collector = [[LynxUIActionCollector alloc] init];\n }\n return self;\n}\n\n- (void) onVSync {\n render_tree_host_impl_->OnVSync();\n}\n\n- (void) beginFrame {\n _lastCollector = _collector;\n _collector = [[LynxUIActionCollector alloc] init];\n}\n\n- (void) prepareCommit {\n if (_lastCollector && [_lastCollector needDoAction]) {\n [_lastCollector doActions];\n }\n}\n\n- (void) updateViewport:(CGRect) frame {\n int left = frame.origin.x;\n int top = frame.origin.y;\n int right = left + frame.size.width;\n int bottom = top + frame.size.height;\n render_tree_host_impl_->UpdateViewport(left, top, right, bottom);\n}\n\n- (void) collectAction:(LynxUIAction *)action {\n [_collector collectAction:action];\n}\n\n@end\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Kotlin_>/*\n * Copyright 2021 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.netflix.graphql.dgs.mvc\n\nimport com.fasterxml.jackson.core.JsonParseException\nimport com.fasterxml.jackson.databind.exc.InvalidDefinitionException\nimport com.fasterxml.jackson.module.kotlin.jacksonObjectMapper\nimport com.fasterxml.jackson.module.kotlin.readValue\nimport com.netflix.graphql.dgs.DgsQueryExecutor\nimport com.netflix.graphql.dgs.internal.utils.MultipartVariableMapper\nimport com.netflix.graphql.dgs.internal.utils.TimeTracer\nimport graphql.ExecutionResultImpl\nimport graphql.GraphqlErrorBuilder\nimport graphql.execution.reactive.CompletionStageMappingPublisher\nimport org.slf4j.Logger\nimport org.slf4j.LoggerFactory\nimport org.springframework.http.HttpHeaders\nimport org.springframework.http.ResponseEntity\nimport org.springframework.web.bind.annotation.*\nimport org.springframework.web.context.request.WebRequest\nimport org.springframework.web.multipart.MultipartFile\n\n/**\n * HTTP entrypoint for the framework. Functionality in this class should be limited, so that as much code as possible\n * is reused between different transport protocols and the testing framework.\n *\n * In addition to regular graphql queries, this method also handles multipart POST requests containing files for upload.\n * This is usually a POST request that has Content type set to multipart/form-data. Here is an example command.\n *\n * Each part in a multipart request is identified by the -F and is identified by the part name - \"operations, map etc.\"\n * The \"operations\" part is the graphql query containing the mutation for the file upload, with variables for files set to null.\n * The \"map\" part and the subsequent parts specify the path of the file in the variables of the query, and will get mapped to\n * construct the graphql query that looks like this:\n *\n * {\"query\": \"mutation ($input: FileUploadInput!) { uploadFile(input: $input) }\",\n * \"variables\": { \"input\": { \"description\": \"test\", \"files\": [file1.txt, file2.txt] } }\n *\n * where files map to one or more MultipartFile(s)\n *\n * The remaining parts in the request contain the mapping of file name to file path, i.e. a map of MultipartFile(s)\n * The format of a multipart request is also described here:\n * https://github.com/jaydenseric/graphql-multipart-request-spec</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_C_>#ifndef\t_CA_ParametersNR_v1560_H_\n#define\t_CA_ParametersNR_v1560_H_\n\n\n#include \"asn_application.h\"\n\n/* Including external dependencies */\n#include \"NativeEnumerated.h\"\n#include \"constr_SEQUENCE.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* Dependencies */\ntypedef enum CA_ParametersNR_v1560__diffNumerologyWithinPUCCH_GroupLargerSCS {\n\tCA_ParametersNR_v1560__diffNumerologyWithinPUCCH_GroupLargerSCS_supported\t= 0\n} e_CA_ParametersNR_v1560__diffNumerologyWithinPUCCH_GroupLargerSCS;\n\n/* CA-ParametersNR-v1560 */\ntypedef struct CA_ParametersNR_v1560 {\n\tlong\t*diffNumerologyWithinPUCCH_GroupLargerSCS\t/* OPTIONAL */;\n\t\n\t/* Context for parsing across buffer boundaries */\n\tasn_struct_ctx_t _asn_ctx;\n} CA_ParametersNR_v1560_t;\n\n/* Implementation */\n/* extern asn_TYPE_descriptor_t asn_DEF_diffNumerologyWithinPUCCH_GroupLargerSCS_2;\t// (Use -fall-defs-global to expose) */\nextern asn_TYPE_descriptor_t asn_DEF_CA_ParametersNR_v1560;\nextern asn_SEQUENCE_specifics_t asn_SPC_CA_ParametersNR_v1560_specs_1;\nextern asn_TYPE_member_t asn_MBR_CA_ParametersNR_v1560_1[1];\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\t/* _CA_ParametersNR_v1560_H_ */\n#include \"asn_internal.h\"\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Python_>c = 0\nnums = [int(e) for e in input().split()]\nfor i in range(nums[0],nums[1]+1):\n if(nums[2] % i) == 0:\n c+=1\nprint(c)\n\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Go_>package napodate\n\nimport (\n\t\"context\"\n\t//\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestStatus(t *testing.T) {\n\tsrv, ctx := setup()\n\ts, err := srv.Status(ctx)\n\tif err != nil {</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_PHP_><?php\n\ndeclare(strict_types=1);\n/**\n * This file is part of Hyperf.\n *\n * @link https://www.hyperf.io\n * @document https://hyperf.wiki\n * @contact [email protected]\n * @license https://github.com/hyperf/hyperf/blob/master/LICENSE\n */\nnamespace Hyperf\\HttpMessage\\Exception;\n\nclass MethodNotAllowedHttpException extends HttpException\n{\n public function __construct($message = null, $code = 0, \\Throwable $previous = null)\n {\n parent::__construct(405, $message, $code, $previous);\n }\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_C++_>#include \"VoreealPrivatePCH.h\"\n#include \"VoreealPagedVolumeComponent.h\"\n#include \"VoreealBlueprintLibrary.h\"\n#include <PolyVox/Impl/Morton.h>\n\n#include \"MessageLog.h\"\n\nFPagedVolumeChunk::FPagedVolumeChunk(TSharedPtr<FSparseOctree> Octree, uint32 LocationHash, FVoreealRegion Bounds)\n\t: m_octree(Octree)\n\t, m_locationHash(LocationHash)\n\t, m_bounds(Bounds)\n{\n\n}\n\nUPagedVolumeComponent::UPagedVolumeComponent(const class FObjectInitializer& ObjectInitializer)\n\t: Super(ObjectInitializer)\n{\n\tPrimaryComponentTick.bTickEvenWhenPaused = true;\n\tPrimaryComponentTick.bCanEverTick = true;\n\tPrimaryComponentTick.bStartWithTickEnabled = true;\n\n\tVolume = ObjectInitializer.CreateDefaultSubobject<UVoreealPagedVolume>(this, TEXT(\"NewPagedVolume\"));\n\tPager = ObjectInitializer.CreateDefaultSubobject<UPagedVolumePager>(this, TEXT(\"NewPagerVolume\"));\n}\n\nvoid UPagedVolumeComponent::PostLoad()\n{\n\tSuper::PostLoad();\n\n\tif (Volume)\n\t{\n\t\tVolume->ConditionalPostLoad();\n\t}\n}\n\nFString UPagedVolumeComponent::GetDetailedInfoInternal() const\n{\n\treturn (Volume != NULL) ? Volume->GetPathName(NULL) : TEXT(\"No_Volume\");\n}\n\nvoid UPagedVolumeComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)\n{\n\tSuper::TickComponent(DeltaTime, TickType, ThisTickFunction);\n\n\t// Check what chunks should be loaded.\n\n\t// TODO: \n\n\n\t// Loop and create new tasks if required.\n\tfor (TSharedPtr<FPagedVolumeChunk> Chunk : ArrayChunks)\n\t{\n\t\tif (Chunk->m_octree.IsValid())\n\t\t{\n\t\t\t// Traverse all the nodes and see if they need to be updated,\n\t\t\t// if so we queue a task.\n\t\t\tChunk->m_octree->Traverse([=](FSparseOctreeNode* Node) -> ETraverseOptions\n\t\t\t{\n\t\t\t\tif (Node->m_hasChildren)\n\t\t\t\t{\n\t\t\t\t\treturn ETraverseOptions::Continue;\n\t\t\t\t}\n\n\t\t\t\tif (!Node->IsUpToDate() && !Node->IsSceduled() && !Node->IsTaskRunning())\n\t\t\t\t{\n\t\t\t\t\tNode->m_lastSceduledForUpdate = FTimespan(0, 0, FPlatformTime::Seconds());\n\t\t\t\t\tNode->m_bTaskRunning = true;\n\n\t\t\t\t\tFVoreealExtractorOptions Options(Chunk->m_octree, Node->m_selfId, Node->m_bounds, 0);\n\n\t\t\t\t\tSCOPE_CYCLE_COUNTER(STAT_RequestMesh);\n\n\t\t\t\t\tAddTask(Volume, Options);\n\t\t\t\t}\n\n\t\t\t\treturn ETraverseOptions::Continue;\n\t\t\t});\n\t\t}\n\t}\n\n\t// Get Finished Tasks\n\tTSharedPtr<FVoreealMesh> Task;\n\twhile (FindFinishedTask(Task))\n\t{\n\t\tif (Task.IsValid())\n\t\t{\n\t\t\t// Get the task result\n\t\t\tFVoreealMesh* Mesh = Task.Get();\n\t\t\tFVoreealExtractorOptions Options = Mesh->GetOptions();\n\n\t\t\tconst uint32 LocationHash = MortonHash(Options.PagedIdentifier.X, Options.PagedIdentifier.Y, Options.PagedIdentifier.Z);\n\n\t\t\t// Get the procedural mesh component \n\t\t\tUProceduralMeshComponent* MComponent = nullptr;\n\t\t\tif (ProceduralMeshComponents.Contains(LocationHash))\n\t\t\t\tMComponent = ProceduralMeshComponents[LocationHash];\n\n\t\t\tif (MComponent == nullptr)\n\t\t\t{\n\t\t\t\tMComponent = NewObject<UProceduralMeshComponent>();\n\t\t\t\tMComponent->AttachToComponent(this, FAttachmentTransformRules::KeepWorldTransform);\n\t\t\t\tProceduralMeshComponents.Add(LocationHash, MComponent);\n\t\t\t}\n\n\t\t\t// Update the mesh node\n\t\t\tMesh->CreateSection(MComponent, true);\n\n\t\t\t// this shouldn't be needed, but lets have it here in case.\n\t\t\tif (Options.Octree.IsValid())\n\t\t\t{\n\t\t\t\tTSharedPtr<FSparseOctree> Octree = Options.Octree.Pin();\n\t\t\t\t\n\t\t\t\tFSparseOctreeNode* Node = Octree->GetNodeAt(Options.Identifier);\n\t\t\t\tNode->m_meshLastChanged = FTimespan(0, 0, FPlatformTime::Seconds());\n\t\t\t\tNode->m_bTaskRunning = false;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid UPagedVolumeComponent::BeginPlay()\n{\n\tSuper::BeginPlay();\n\tVolume->OnChanged.AddDynamic(this, &UPagedVolumeComponent::OnVolumeChanged);\n}\n\nbool UPagedVolumeComponent::SetPagedVolume(UVoreealPagedVolume* NewVolume)\n{\n\tif (NewVolume == Volume && NewVolume == nullptr)\n\t\treturn false;\n\n\tAActor* Owner = GetOwner();\n\tif (!AreDynamicDataChangesAllowed() && Owner != NULL)\n\t{\n\t\tFMessageLog(\"PIE\").Warning(FText::Format(\n\t\t\tFText::FromString(TEXT(\"Calling SetPagedVolume on '{0}' but Mobility is Static.\")),\n\t\t\tFText::FromString(GetPathName())));\n\t\treturn false;\n\t}\n\n\tVolume = NewVolume;\n\n\t// If there were a volume before we call then we force gc\n\tUWorld* World = GetWorld();\n\tif (World)\n\t{\n\t\tWorld->ForceGarbageCollection(true);\n\t}\n\n\treturn true;\n}\n\nFPagedVolumeChunk* UPagedVolumeComponent::GetChunk(int32 X, int32 Y, int32 Z) const\n{\n\tconst uint32 LocationHash = MortonHash(X, Y, Z);\n\n\t// check if it's the last one we accessed. \n\tif (getChunkCache) //< TODO: Validate?\n\t{\n\t\tif (getChunkCache->m_locationHash == LocationHash)\n\t\t{\n\t\t\treturn getChunkCache;\n\t\t}\n\t}\n\n\t// loop all chunks\n\tfor (TSharedPtr<FPagedVolumeChunk> Chunk : ArrayChunks)\n\t{\n\t\tif (Chunk->m_octree.IsValid())\n\t\t{</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Ruby_>require 'test_helper'\n\nclass ComfortableMexicanLoveseatTest < ActiveSupport::TestCase\n test \"truth\" do\n assert_kind_of Module, ComfortableMexicanLoveseat\n end\nend\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_C++_> aom_smooth_v_predictor_16x4_ssse3,\n aom_smooth_h_predictor_16x4_ssse3)\n#endif\n#endif // HAVE_SSSE3\n\n#if HAVE_AVX2\nINTRA_PRED_TEST(AVX2_1, TX_16X16, NULL, NULL, NULL, NULL, NULL, NULL,\n aom_paeth_predictor_16x16_avx2, NULL, NULL, NULL)\nINTRA_PRED_TEST(AVX2_2, TX_16X8, NULL, NULL, NULL, NULL, NULL, NULL,\n aom_paeth_predictor_16x8_avx2, NULL, NULL, NULL)\nINTRA_PRED_TEST(AVX2_3, TX_16X32, NULL, NULL, NULL, NULL, NULL, NULL,\n aom_paeth_predictor_16x32_avx2, NULL, NULL, NULL)\n#if !CONFIG_REALTIME_ONLY\nINTRA_PRED_TEST(AVX2_4, TX_16X64, NULL, NULL, NULL, NULL, NULL, NULL,\n aom_paeth_predictor_16x64_avx2, NULL, NULL, NULL)\n#endif\n#endif // HAVE_AVX2\n\n#if HAVE_DSPR2\nINTRA_PRED_TEST(DSPR2, TX_16X16, aom_dc_predictor_16x16_dspr2, NULL, NULL, NULL,\n NULL, aom_h_predictor_16x16_dspr2, NULL, NULL, NULL, NULL)\n#endif // HAVE_DSPR2\n\n#if HAVE_NEON\nINTRA_PRED_TEST(NEON, TX_16X16, aom_dc_predictor_16x16_neon,\n aom_dc_left_predictor_16x16_neon,\n aom_dc_top_predictor_16x16_neon,\n aom_dc_128_predictor_16x16_neon, aom_v_predictor_16x16_neon,\n aom_h_predictor_16x16_neon, NULL, NULL, NULL, NULL)\n#endif // HAVE_NEON\n\n#if HAVE_MSA\nINTRA_PRED_TEST(MSA, TX_16X16, aom_dc_predictor_16x16_msa,\n aom_dc_left_predictor_16x16_msa, aom_dc_top_predictor_16x16_msa,\n aom_dc_128_predictor_16x16_msa, aom_v_predictor_16x16_msa,</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_C++_> case Thunk::kCudnnBatchNormBackward:\n return \"kCudnnBatchNormBackward\";\n case Thunk::kCudnnBatchNormForwardInference:\n return \"kCudnnBatchNormForwardInference\";\n case Thunk::kCudnnBatchNormForwardTraining:\n return \"kCudnnBatchNormForwardTraining\";\n case Thunk::kCustomCall:\n return \"kCustomCall\";\n case Thunk::kNcclAllGather:\n return \"kNcclAllGather\";\n case Thunk::kNcclAllReduce:\n return \"kNcclAllReduce\";\n case Thunk::kNcclAllReduceStart:\n return \"kNcclAllReduceStart\";\n case Thunk::kNcclAllReduceDone:\n return \"kNcclAllReduceDone\";\n case Thunk::kNcclReduceScatter:\n return \"kNcclReduceScatter\";\n case Thunk::kNcclAllToAll:\n return \"kNcclAllToAll\";\n case Thunk::kFft:\n return \"kFft\";\n case Thunk::kGemm:\n return \"kGemm\";\n case Thunk::kInfeed:\n return \"kInfeed\";\n case Thunk::kKernel:\n return \"kKernel\";\n case Thunk::kMemset32BitValue:\n return \"kMemset32BitValue\";\n case Thunk::kMemzero:\n return \"kMemzero\";\n case Thunk::kOutfeed:\n return \"kOutfeed\";\n case Thunk::kReplicaId:\n return \"kReplicaId\";\n case Thunk::kPartitionId:\n return \"kPartitionId\";\n case Thunk::kSequential:\n return \"kSequential\";\n case Thunk::kTriangularSolve:\n return \"kTriangularSolve\";\n case Thunk::kWhile:\n return \"kWhile\";\n }\n}\n\nstd::ostream& operator<<(std::ostream& os, Thunk::Kind kind) {\n return os << Thunk::KindToString(kind);\n}\n\nstd::string ThunkSequence::ToString(\n int indent,\n std::function<std::string(const Thunk*)> get_thunk_annotation) const {\n const std::string indent_str(\" \", indent * 2);\n if (empty()) return indent_str + \"No thunks.\";\n\n auto thunk_with_longest_kind = absl::c_max_element(\n *this,\n [](const std::unique_ptr<Thunk>& a, const std::unique_ptr<Thunk>& b) {\n return Thunk::KindToString(a->kind()).length() <\n Thunk::KindToString(b->kind()).length();\n });\n int64_t max_thunk_kind_len =\n Thunk::KindToString(thunk_with_longest_kind->get()->kind()).length();\n std::string result;\n for (const std::unique_ptr<Thunk>& thunk : *this) {\n // Write out the thunk kind, padded out to max_thunk_kind_len.\n absl::string_view kind_str = Thunk::KindToString(thunk->kind());\n absl::StrAppend(&result, indent_str, kind_str,\n string(max_thunk_kind_len - kind_str.length(), ' '), \"\\t\");\n if (get_thunk_annotation) {\n absl::StrAppend(&result, get_thunk_annotation(thunk.get()));\n }\n absl::StrAppend(&result, thunk->ToStringExtra(indent));\n absl::StrAppend(&result, \"\\n\");\n }\n return result;\n}\n\n} // namespace gpu\n} // namespace xla\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_HTML_><!-- HTML header for doxygen 1.8.16-->\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/xhtml;charset=UTF-8\"/>\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=9\"/>\n<meta name=\"generator\" content=\"Doxygen 1.8.18\"/>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>\n<title>BL3 SDK: Member List</title>\n<link href=\"tabs.css\" rel=\"stylesheet\" type=\"text/css\"/>\n<script type=\"text/javascript\" src=\"jquery.js\"></script>\n<script type=\"text/javascript\" src=\"dynsections.js\"></script>\n<link href=\"search/search.css\" rel=\"stylesheet\" type=\"text/css\"/>\n<script type=\"text/javascript\" src=\"search/searchdata.js\"></script>\n<script type=\"text/javascript\" src=\"search/search.js\"></script>\n<link href=\"stylesheet.css\" rel=\"stylesheet\" type=\"text/css\" />\n</head>\n<body>\n<div id=\"top\"><!-- do not remove this div, it is closed by doxygen! -->\n<div id=\"titlearea\">\n<table cellspacing=\"0\" cellpadding=\"0\">\n <tbody>\n <tr style=\"height: 56px;\">\n <td id=\"projectalign\" style=\"padding-left: 0.5em;\">\n <div id=\"projectname\">BL3 SDK\n &#160;<span id=\"projectnumber\">0.0.1</span>\n </div>\n <div id=\"projectbrief\">Borderlands 3 Class Documentation</div>\n </td>\n </tr>\n </tbody>\n</table>\n</div>\n<!-- end header part -->\n<!-- Generated by Doxygen 1.8.18 -->\n<script type=\"text/javascript\">\n/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */\nvar searchBox = new SearchBox(\"searchBox\", \"search\",false,'Search');\n/* @license-end */\n</script>\n<script type=\"text/javascript\" src=\"menudata.js\"></script>\n<script type=\"text/javascript\" src=\"menu.js\"></script>\n<script type=\"text/javascript\">\n/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */\n$(function() {\n initMenu('',true,false,'search.php','Search');\n $(document).ready(function() { init_search(); });\n});\n/* @license-end */</script>\n<div id=\"main-nav\"></div>\n<!-- window showing the filter options -->\n<div id=\"MSearchSelectWindow\"\n onmouseover=\"return searchBox.OnSearchSelectShow()\"\n onmouseout=\"return searchBox.OnSearchSelectHide()\"\n onkeydown=\"return searchBox.OnSearchSelectKey(event)\">\n</div>\n\n<!-- iframe showing the search results (closed by default) -->\n<div id=\"MSearchResultsWindow\">\n<iframe src=\"javascript:void(0)\" frameborder=\"0\" \n name=\"MSearchResults\" id=\"MSearchResults\">\n</iframe>\n</div>\n\n<div id=\"nav-path\" class=\"navpath\">\n <ul>\n<li class=\"navelem\"><a class=\"el\" href=\"a23606.html\">BL3SDK</a></li><li class=\"navelem\"><a class=\"el\" href=\"a43575.html\">UHealthTypeData</a></li> </ul>\n</div>\n</div><!-- top -->\n<div class=\"header\">\n <div class=\"headertitle\">\n<div class=\"title\">UHealthTypeData Member List</div> </div>\n</div><!--header-->\n<div class=\"contents\">\n\n<p>This is the complete list of members for <a class=\"el\" href=\"a43575.html\">UHealthTypeData</a>, including all inherited members.</p>\n<table class=\"directory\">\n <tr class=\"even\"><td class=\"entry\"><a class=\"el\" href=\"a43575.html#a311234f6d69890e7dd67452e6a0b72c2\">BalanceData</a></td><td class=\"entry\"><a class=\"el\" href=\"a43575.html\">UHealthTypeData</a></td><td class=\"entry\"></td></tr></code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_JavaScript_>(function() {\n $('.grid').height( $(window).height() );\n });\n var myTextarea = document.getElementById('html');\n var editor = CodeMirror.fromTextArea(myTextarea, {\n mode: \"javascript\",\n lineNumbers: true,\n theme: \"monokai\"\n });\n\n $('#run').click(function()) {\n // create an instance\n var editor = CodeMirror.fromTextArea('code');\n // store it\n $('#code').data('CodeMirrorInstance', editor);\n // get it\n var myInstance = $('code').data('CodeMirrorInstance');\n // from here on the API functions are available to 'myInstance' again.\n\n }\n})();\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_Python_>n = int(input())\ninfo =[]\n\nfor i in range(n):\n info.append([int(input()),i])\ninfo = sorted(info)\n \nans = 0\nfor i in range(n):\n if i%2 != info[i][1]%2:\n ans = ans+1\nprint(ans//2)</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<loc_0><loc_0><loc_500><loc_500><_TypeScript_>import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.scss']\n})\nexport class AppComponent {\n title = 'cc-menu';\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "<code>" } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Rust_> let data = sectors_manager.read_data(0).await;\n\n // then\n assert_eq!(sectors_manager.read_metadata(0).await, (1, 1));\n assert_eq!(data.0.len(), 4096);\n assert_eq!(data.0, vec![2; 4096])\n}\n\n#[tokio::test]\n#[timeout(200)]\nasync fn data_survives_crash() {\n // given\n let root_drive_dir = tempdir().unwrap();\n {\n let sectors_manager = build_sectors_manager(root_drive_dir.path().to_path_buf());\n sectors_manager\n .write(1, &(SectorVec(vec![7; 4096]), 1, 2))\n .await;\n }\n\n let sectors_manager = build_sectors_manager(root_drive_dir.path().to_path_buf());\n\n // when\n let (timestamp, write_rank) = sectors_manager.read_metadata(1).await;\n let data = sectors_manager.read_data(1).await;\n\n // then\n assert_eq!(timestamp, 1);\n assert_eq!(write_rank, 2);\n assert_eq!(data.0, vec![7; 4096]);\n}\n\n#[tokio::test]\n#[timeout(5000)]\nasync fn concurrent_operation_on_different_sectors() {\n // given\n let root_drive_dir = tempdir().unwrap();\n let sectors_manager = Arc::new(build_sectors_manager(root_drive_dir.path().to_path_buf()));\n let tasks: usize = 10;\n let sectors_batch = 16;\n let mut task_handles = vec![];\n\n // when\n for i in 0..tasks {\n let sectors_manager = sectors_manager.clone();\n task_handles.push(tokio::spawn(async move {\n let sectors_start = sectors_batch * i;\n let sectors_end = sectors_start + sectors_batch;\n\n for sector_idx in sectors_start..sectors_end {\n let sector_idx = sector_idx as u64;\n let data = SectorVec(\n (0..4096)\n .map(|_| rand::thread_rng().gen_range(0..255))\n .collect(),\n );\n\n sectors_manager\n .write(sector_idx, &(data.clone(), 1, 1))\n .await;\n assert_eq!(sectors_manager.read_metadata(sector_idx).await, (1, 1));\n assert_eq!(sectors_manager.read_data(sector_idx).await, data);\n }\n }));\n }\n\n // then\n for handle in task_handles {\n assert!(handle.await.is_ok())\n }\n}\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_HTML_><!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<!-- NewPage -->\n<html lang=\"en\">\n<head>\n<!-- Generated by javadoc -->\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<title>BloomType (Apache HBase 2.3.0 API)</title>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"../../../../../stylesheet.css\" title=\"Style\">\n<script type=\"text/javascript\" src=\"../../../../../script.js\"></script>\n</head>\n<body>\n<script type=\"text/javascript\"><!--\n try {\n if (location.href.indexOf('is-external=true') == -1) {</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Python_>a, b, c, d = map(int,input().split())\nif (a - b) <= d or (b - c) <= d:\n print(\"Yes\")\n\nelif (a - b) == 0 or (b - c) == 0:\n print(\"Yes\")\n \nelse:\n print(\"No\")\n</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]
[ { "assistant": "<code><loc_0><loc_0><loc_500><loc_500><_Rust_>use crate::cx::*;\nuse std::f64::consts::PI;\n\n#[derive(Clone)]\npub struct AnimArea {\n pub area: Area,\n pub start_time: f64,\n pub total_time: f64\n}\n\n#[derive(Clone)]\npub struct Anim {\n pub mode: Play,\n pub tracks: Vec<Track>\n}\n\n#[derive(Clone)]\npub enum AnimLastValue {\n Float(f32),\n Vec2(Vec2),\n Vec3(Vec3),\n Vec4(Vec4),\n Color(Color),\n}\n\n#[derive(Default, Clone)]\npub struct Animator {\n current: Option<Anim>,\n next: Option<Anim>,\n pub area: Area,\n pub theme_update_id: usize,\n pub last_values: Vec<(InstanceType, AnimLastValue)>,\n}\n\nimpl Animator {\n\n pub fn init<F>(&mut self, cx: &mut Cx, cb: F)\n where F: Fn(&Cx) -> Anim {\n if self.theme_update_id != cx.theme_update_id {\n self.theme_update_id = cx.theme_update_id;\n let anim = cb(cx);\n // lets stop all animations if we had any\n if let Some(anim_area) = cx.playing_anim_areas.iter_mut().find( | v | v.area == self.area) {\n anim_area.total_time = 0.;\n }\n self.set_anim_as_last_values(&anim);\n }\n }\n \n pub fn set_anim_as_last_values(&mut self, anim: &Anim) {\n for track in &anim.tracks {\n // we dont have a last float, find it in the tracks\n let ident = track.ident();\n match track {\n Track::Color(ft) => {\n let val = if ft.track.len()>0 {ft.track.last().unwrap().1}else {Color::default()};\n if let Some((_name, value)) = self.last_values.iter_mut().find( | (name, _) | *name == ident) {\n *value = AnimLastValue::Color(val);\n }\n else {\n self.last_values.push((ident.clone(), AnimLastValue::Color(val)));\n }\n },\n Track::Vec4(ft) => {\n let val = if ft.track.len()>0 {ft.track.last().unwrap().1}else {Vec4::default()};\n if let Some((_name, value)) = self.last_values.iter_mut().find( | (name, _) | *name == ident) {\n *value = AnimLastValue::Vec4(val);\n }\n else {\n self.last_values.push((ident.clone(), AnimLastValue::Vec4(val)));\n }\n },\n Track::Vec3(ft) => {\n let val = if ft.track.len()>0 {ft.track.last().unwrap().1}else {Vec3::default()};\n if let Some((_name, value)) = self.last_values.iter_mut().find( | (name, _) | *name == ident) {\n *value = AnimLastValue::Vec3(val);\n }\n else {\n self.last_values.push((ident.clone(), AnimLastValue::Vec3(val)));\n }\n },\n Track::Vec2(ft) => {\n let val = if ft.track.len()>0 {ft.track.last().unwrap().1}else {Vec2::default()};\n if let Some((_name, value)) = self.last_values.iter_mut().find( | (name, _) | *name == ident) {\n *value = AnimLastValue::Vec2(val);\n }\n else {\n self.last_values.push((ident.clone(), AnimLastValue::Vec2(val)));\n }\n },\n Track::Float(ft) => {\n let val = if ft.track.len()>0 {ft.track.last().unwrap().1}else {0.};\n if let Some((_name, value)) = self.last_values.iter_mut().find( | (name, _) | *name == ident) {\n *value = AnimLastValue::Float(val);\n }\n else {\n self.last_values.push((ident.clone(), AnimLastValue::Float(val)));\n }\n },\n }\n }\n }\n \n pub fn end(&mut self) {\n if let Some(current) = self.current.take() {\n self.set_anim_as_last_values(&current);\n }\n }\n \n pub fn end_and_set(&mut self, anim: Anim) {\n self.current = None;\n self.set_anim_as_last_values(&anim);\n }\n \n pub fn term_anim_playing(&mut self) -> bool {\n if let Some(current) = &self.current {\n return current.mode.term();\n }\n return false\n }\n \n pub fn play_anim(&mut self, cx: &mut Cx, anim: Anim) {\n // if our area is invalid, we should just set our default value\n if let Some(current) = &self.current {\n if current.mode.term() { // can't override a term anim\n return\n }\n }\n \n if !self.area.is_valid(cx) {\n self.set_anim_as_last_values(&anim);\n self.current = Some(anim);\n return\n }\n // alright first we find area, it already exists\n if let Some(anim_area) = cx.playing_anim_areas.iter_mut().find( | v | v.area == self.area) {\n //do we cut the animation in right now?\n if anim.mode.cut() || self.current.is_none() {\n self.current = Some(anim);\n anim_area.start_time = std::f64::NAN;\n self.next = None;\n anim_area.total_time = self.current.as_ref().unwrap().mode.total_time();\n }\n else { // queue it\n self.next = Some(anim);\n // lets ask an animation anim how long it is\n anim_area.total_time = self.current.as_ref().unwrap().mode.total_time() + self.next.as_ref().unwrap().mode.total_time()\n }\n }\n else if self.area != Area::Empty { // its new\n self.current = Some(anim);\n self.next = None;\n cx.playing_anim_areas.push(AnimArea {\n area: self.area.clone(),\n start_time: std::f64::NAN,\n total_time: self.current.as_ref().unwrap().mode.total_time()\n })\n }\n }\n \n pub fn set_area(&mut self, cx: &mut Cx, area: Area) {\n if self.area != Area::Empty {\n cx.update_area_refs(self.area, area.clone());\n }\n self.area = area.clone();\n }\n \n \n pub fn update_anim_track(&mut self, cx: &mut Cx, time: f64) -> Option<f64> {\n // alright first we find area in running animations\n let anim_index_opt = cx.playing_anim_areas.iter().position( | v | v.area == self.area);\n if anim_index_opt.is_none() {\n return None\n }\n let anim_index = anim_index_opt.unwrap();\n \n // initialize start time\n if cx.playing_anim_areas[anim_index].start_time.is_nan() {\n cx.playing_anim_areas[anim_index].start_time = time;\n }\n let mut start_time = cx.playing_anim_areas[anim_index].start_time;\n \n // fetch current anim\n if self.current.is_none() { // remove anim\n cx.playing_anim_areas.remove(anim_index);\n return None\n }\n \n let current_total_time = self.current.as_ref().unwrap().mode.total_time();\n \n // process queueing\n if time - start_time >= current_total_time && !self.next.is_none() {\n self.current = self.next.clone();\n self.next = None;\n // update animation slot\n start_time += current_total_time;\n if let Some(anim) = cx.playing_anim_areas.iter_mut().find( | v | v.area == self.area) {</code>", "source": "SynthCodeNetNoImageTag", "user": "Convert code to text." } ]