language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Python
UTF-8
7,214
2.890625
3
[]
permissive
""" Components/Chip =============== .. seealso:: `Material Design spec, Chips <https://material.io/components/chips>`_ .. rubric:: Chips are compact elements that represent an input, attribute, or action. .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/chips.png :align: center Usage ----- .. code-block:: kv MDChip: label: 'Coffee' color: .4470588235118, .1960787254902, 0, 1 icon: 'coffee' callback: app.callback_for_menu_items The user function takes two arguments - the object and the text of the chip: .. code-block:: python def callback_for_menu_items(self, instance, value): print(instance, value) .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/ordinary-chip.png :align: center Use custom icon --------------- .. code-block:: kv MDChip: label: 'Kivy' icon: 'data/logo/kivy-icon-256.png' .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/chip-custom-icon.png :align: center Use without icon ---------------- .. code-block:: kv MDChip: label: 'Without icon' icon: '' .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/chip-without-icon.png :align: center Chips with check ---------------- .. code-block:: kv MDChip: label: 'Check with icon' icon: 'city' check: True .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/chip-check-icon.gif :align: center Choose chip ----------- .. code-block:: kv MDChooseChip: MDChip: label: 'Earth' icon: 'earth' selected_chip_color: .21176470535294, .098039627451, 1, 1 MDChip: label: 'Face' icon: 'face' selected_chip_color: .21176470535294, .098039627451, 1, 1 MDChip: label: 'Facebook' icon: 'facebook' selected_chip_color: .21176470535294, .098039627451, 1, 1 .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/chip-shoose-icon.gif :align: center .. Note:: `See full example <https://github.com/HeaTTheatR/KivyMD/wiki/Components-Chip>`_ """ from kivy.animation import Animation from kivy.lang import Builder from kivy.metrics import dp from kivy.properties import ( BooleanProperty, ListProperty, NumericProperty, ObjectProperty, StringProperty, ) from kivy.uix.boxlayout import BoxLayout from kivymd.theming import ThemableBehavior from kivymd.uix.button import MDIconButton from kivymd.uix.stacklayout import MDStackLayout Builder.load_string( """ #:import DEVICE_TYPE kivymd.material_resources.DEVICE_TYPE <MDChooseChip> adaptive_height: True spacing: "5dp" <MDChip> size_hint: None, None height: "26dp" padding: 0, 0, "5dp", 0 width: self.minimum_width - (dp(10) if DEVICE_TYPE == "desktop" else dp(20)) \ if root.icon != 'checkbox-blank-circle' else self.minimum_width canvas: Color: rgba: root.color RoundedRectangle: pos: self.pos size: self.size radius: [root.radius] MDBoxLayout: id: box_check adaptive_size: True pos_hint: {'center_y': .5} MDBoxLayout: adaptive_width: True padding: dp(10) Label: id: label text: root.label size_hint_x: None width: self.texture_size[0] color: root.text_color if root.text_color else (root.theme_cls.text_color) MDIconButton: id: icon icon: root.icon size_hint_y: None height: "20dp" pos_hint: {"center_y": .5} user_font_size: "20dp" disabled: True """ ) class MDChip(BoxLayout, ThemableBehavior): label = StringProperty() """Chip text. :attr:`label` is an :class:`~kivy.properties.StringProperty` and defaults to `''`. """ icon = StringProperty("checkbox-blank-circle") """Chip icon. :attr:`icon` is an :class:`~kivy.properties.StringProperty` and defaults to `'checkbox-blank-circle'`. """ color = ListProperty() """Chip color in ``rgba`` format. :attr:`color` is an :class:`~kivy.properties.ListProperty` and defaults to `[]`. """ text_color = ListProperty() """Chip's text color in ``rgba`` format. :attr:`text_color` is an :class:`~kivy.properties.ListProperty` and defaults to `[]`. """ check = BooleanProperty(False) """ If True, a checkmark is added to the left when touch to the chip. :attr:`check` is an :class:`~kivy.properties.BooleanProperty` and defaults to `False`. """ callback = ObjectProperty() """Custom method. :attr:`callback` is an :class:`~kivy.properties.ObjectProperty` and defaults to `None`. """ radius = NumericProperty("12dp") """Corner radius values. :attr:`radius` is an :class:`~kivy.properties.NumericProperty` and defaults to `'12dp'`. """ selected_chip_color = ListProperty() """The color of the chip that is currently selected in ``rgba`` format. :attr:`selected_chip_color` is an :class:`~kivy.properties.ListProperty` and defaults to `[]`. """ def __init__(self, **kwargs): super().__init__(**kwargs) if not self.color: self.color = self.theme_cls.primary_color def on_icon(self, instance, value): if value == "": self.icon = "checkbox-blank-circle" self.remove_widget(self.ids.icon) def on_touch_down(self, touch): if self.collide_point(*touch.pos): md_choose_chip = self.parent if self.selected_chip_color: Animation( color=self.theme_cls.primary_dark if not self.selected_chip_color else self.selected_chip_color, d=0.3, ).start(self) if issubclass(md_choose_chip.__class__, MDChooseChip): for chip in md_choose_chip.children: if chip is not self: chip.color = self.theme_cls.primary_color if self.check: if not len(self.ids.box_check.children): self.ids.box_check.add_widget( MDIconButton( icon="check", size_hint_y=None, height=dp(20), disabled=True, user_font_size=dp(20), pos_hint={"center_y": 0.5}, ) ) else: check = self.ids.box_check.children[0] self.ids.box_check.remove_widget(check) if self.callback: self.callback(self, self.label) class MDChooseChip(MDStackLayout): def add_widget(self, widget, index=0, canvas=None): if isinstance(widget, MDChip): return super().add_widget(widget)
SQL
UTF-8
2,211
3.09375
3
[]
no_license
-- MySQL dump 10.13 Distrib 8.0.16, for Win64 (x86_64) -- -- Host: localhost Database: dbescola -- ------------------------------------------------------ -- Server version 8.0.16 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; SET NAMES utf8 ; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `tblturma` -- DROP TABLE IF EXISTS `tblturma`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `tblturma` ( `upkChave` binary(16) NOT NULL, `strSigla` varchar(7) NOT NULL, `enumDia` enum('Segunda','Terça','Quarta','Quinta','Sexta','Sábado','Domingo') DEFAULT NULL, `enumPeriodo` enum('Matutino','Vespertino','Noturno') DEFAULT NULL, `dcCriado` datetime DEFAULT CURRENT_TIMESTAMP, `dcAtualizado` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`upkChave`), KEY `fkChave` (`fkChave`), KEY `idx_tblturma_upkChave` (`upkChave`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `tblturma` -- LOCK TABLES `tblturma` WRITE; /*!40000 ALTER TABLE `tblturma` DISABLE KEYS */; /*!40000 ALTER TABLE `tblturma` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2019-06-16 20:38:55
Shell
UTF-8
249
2.8125
3
[]
no_license
#!/bin/bash echo "Enter the title:" read title sed -i -e "s/^\# Papar Template/# ${title}/" ./README.md NOW_DATE=`date "+%F"` sed -i -e "s/YYYY-MM-DD/${NOW_DATE}/" ./README.md git init mkdir figs mkdir out mkdir release rm README.md-e rm init.sh
PHP
UTF-8
3,092
2.65625
3
[ "MIT" ]
permissive
<?php namespace CaptJM\Bundle\StorytellerBundle\Entity; use CaptJM\Bundle\StorytellerBundle\Repository\FontRepository; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(repositoryClass: FontRepository::class)] class Font { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; #[ORM\Column(length: 255)] private ?string $slug = null; #[ORM\Column(length: 255)] private ?string $name = null; #[ORM\Column(length: 255, nullable: true)] private ?string $ttf = null; #[ORM\Column(length: 255, nullable: true)] private ?string $woff = null; #[ORM\Column(length: 255, nullable: true)] private ?string $woff2 = null; #[ORM\Column(length: 255, nullable: true)] private ?string $eot = null; #[ORM\Column(length: 255, nullable: true)] private ?string $otf = null; #[ORM\Column(length: 255, nullable: true)] private ?string $svg = null; private const FORMATS = [ 'eot' => 'embedded-opentype', 'ttf' => 'truetype', 'woff' => 'woff', 'woff2' => 'woff2', 'otf' => 'opentype', 'svg' => 'svg', ]; public function getId(): ?int { return $this->id; } public function getSlug(): ?string { return $this->slug; } public function setSlug(string $slug): self { $this->slug = $slug; return $this; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getTtf(): ?string { return $this->ttf; } public function setTtf(?string $ttf): self { $this->ttf = $ttf; return $this; } public function getWoff(): ?string { return $this->woff; } public function setWoff(?string $woff): self { $this->woff = $woff; return $this; } public function getWoff2(): ?string { return $this->woff2; } public function setWoff2(?string $woff2): self { $this->woff2 = $woff2; return $this; } public function getEot(): ?string { return $this->eot; } public function setEot(?string $eot): self { $this->eot = $eot; return $this; } public function getOtf(): ?string { return $this->otf; } public function setOtf(?string $otf): self { $this->otf = $otf; return $this; } public function getSvg(): ?string { return $this->svg; } public function setSvg(?string $svg): self { $this->svg = $svg; return $this; } public function getCSS(): string { $css = sprintf("@font-face {\n font-family:'%s';\n src:", $this->name); foreach (self::FORMATS as $key => $format) { if ($this->$key) $css .= sprintf("\n url(\"%s\") format(\"%s\"),", $this->$key, $format); } return rtrim($css, ',') . ";\n}"; } }
C
UTF-8
3,646
3.046875
3
[]
no_license
// Klaudia Nowak // 297936 #include "sliding_window.h" FILE *fp; int WINDOW_SIZE = 1500; int all_packets; int not_all_received(window_object_t *window) { for (int i = 0; i < WINDOW_SIZE; i++) { if (window[i].status != SAVED) { return 1; } } return 0; } int print_to_file(window_object_t *window, char filename[], int saved_packets) { int status0 = window[0].status; if (status0 != RECEIVED && status0 != SAVED) { return saved_packets; } int index = 0; fp = fopen(filename, "ab"); while (index < WINDOW_SIZE) { window_object_t el_to_write = window[index]; if (el_to_write.status == SAVED) { index++; continue; } if (el_to_write.status != RECEIVED) { break; } else { char *saveme; size_t elements_written = fwrite(el_to_write.data, sizeof *el_to_write.data, el_to_write.length, fp); if (elements_written != el_to_write.length){ ERROR("Writing to file error: %s\n"); } window[index].status = SAVED; saved_packets++; double percent = (saved_packets / (double)all_packets) * 100; printf("%0.3f%% done\n", percent); } index++; } fclose(fp); return saved_packets; } int main(int argc, char *argv[]) { char ip_address[20]; int port; char file_name[100]; int bytes; int saved_packets = 0; // Check input data if (argc != 5) { ERROR("Usage: ./transport ip port output_file bytes\n"); } // Assign input data strcpy(ip_address, argv[1]); port = atoi(argv[2]); strcpy(file_name, argv[3]); bytes = atoi(argv[4]); int packets_left = bytes % DEFAULT_LENGTH == 0 ? (int)(bytes / DEFAULT_LENGTH) : (int)(bytes / DEFAULT_LENGTH) + 1; all_packets = packets_left; if (packets_left < WINDOW_SIZE) { WINDOW_SIZE = packets_left; } // Remove file if exists - appending data on the end of file could be incorrect if file exists before and contains same data remove(file_name); // Create socket int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { ERROR("socket error: %s\n"); } // Set server address struct sockaddr_in server_address; bzero(&server_address, sizeof(server_address)); server_address.sin_family = AF_INET; server_address.sin_port = htons(port); int server_len = sizeof(server_address); if (inet_pton(AF_INET, ip_address, &server_address.sin_addr) != 1) { ERROR("Incorrect IP address\n"); } window_object_t current_window[WINDOW_SIZE]; // initialize window initialize_window(current_window, bytes, WINDOW_SIZE); packets_left -= WINDOW_SIZE; // Send requests, receive packages and save to file untill all packages are not received while (packets_left > 0 || not_all_received(current_window)) { // Send packets from current window send_packets(current_window, 0, sockfd, &server_address, server_len, WINDOW_SIZE); // Proceed received packets proceed_packets(sockfd, &server_address, current_window, WINDOW_SIZE,all_packets-saved_packets); // Print to file first packages from current window saved_packets = print_to_file(current_window, file_name, saved_packets); // Slide window packets_left = slide_window(current_window, packets_left, bytes, WINDOW_SIZE); } // Close socket if (close(sockfd) < 0) ERROR("close error"); }
SQL
UTF-8
660
2.890625
3
[ "MIT" ]
permissive
CREATE TABLE `user_site_image_library_version_meta` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `site_id` int(11) unsigned NOT NULL, `library_id` int(11) unsigned NOT NULL, `version_id` int(11) unsigned NOT NULL, `extension` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '.jpg', `type` varchar(15) COLLATE utf8_unicode_ci NOT NULL, `width` smallint(5) NOT NULL DEFAULT '1', `height` smallint(5) NOT NULL DEFAULT '1', `size` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `site_id` (`site_id`), KEY `library_id` (`library_id`), KEY `version_id` (`version_id`) ) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
PHP
UTF-8
1,233
2.609375
3
[]
no_license
<?php namespace App; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\SoftDeletes; class User extends Authenticatable { use Notifiable; use SoftDeletes; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'company_name', 'email', 'password', 'company_code', 'address', 'user_profile_image', 'login_status', 'status', 'last_login', 'role' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public static function LogInStatusUpdate($status) { if(\Auth::check()){ if($status=='login') { $change_status=1; } else { $change_status=0; } $loginstatuschange = \App\User::where('email',\Auth::user()->email)->update(array('login_status'=>$change_status)); return $loginstatuschange; } } }
Python
UTF-8
397
4.09375
4
[]
no_license
# N킬로그램 배달. 최대한 적은 봉지. 봉지는 3킬로그램, 5킬로그램 있음. sugar = int(input()) bag = 0 while sugar >= 0: if sugar % 5 == 0: # 입력받은 수가 5의 배수이면 bag += (sugar // 5) print(bag) break sugar -= 3 # 입력받은 수가 5의 배수가 아니면 3킬로그램을 빼주고 봉지+1 bag += 1 else: print(-1)
C#
UTF-8
15,707
2.578125
3
[]
no_license
namespace nManager.Helpful.Forms.UserControls { using System; using System.Collections.Generic; using System.Drawing; using System.Runtime.InteropServices; using System.Text; public class XmlStateMachine { private string _cujahegijaXawaebi = string.Empty; private string _qiujaejuto = ""; private Stack<XmlTokenType> _unudurokexo = new Stack<XmlTokenType>(); public XmlTokenType CurrentState = XmlTokenType.Unknown; private string AleukiIgeusef(string uleavacaom, int qaikiepiceutOjepoku) { string str = ""; int index = uleavacaom.IndexOf('='); if (index != -1) { str = uleavacaom.Substring(0, index); } return str; } private string EcausuodekuitNoatoi(string uleavacaom, int qaikiepiceutOjepoku) { string str = ""; int index = uleavacaom.IndexOf('<'); if (index != -1) { str = uleavacaom.Substring(0, index); } return str; } public string GetNextToken(string s, int location, out XmlTokenType ttype) { ttype = XmlTokenType.Unknown; string str = this.IgitauciOmoduici(s, location); if (!string.IsNullOrEmpty(str)) { location += str.Length; } this._qiujaejuto = s.Substring(location, s.Length - location); this._cujahegijaXawaebi = string.Empty; if (this.CurrentState == XmlTokenType.CDataStart) { if (this._qiujaejuto.StartsWith("]]>")) { this.CurrentState = XmlTokenType.CDataEnd; this._cujahegijaXawaebi = "]]>"; } else { this.CurrentState = XmlTokenType.CDataValue; int index = this._qiujaejuto.IndexOf("]]>"); this._cujahegijaXawaebi = this._qiujaejuto.Substring(0, index); } } else if (this.CurrentState == XmlTokenType.DocTypeStart) { this.CurrentState = XmlTokenType.DocTypeName; this._cujahegijaXawaebi = "DOCTYPE"; } else if (this.CurrentState == XmlTokenType.DocTypeName) { this.CurrentState = XmlTokenType.DocTypeDeclaration; int length = this._qiujaejuto.IndexOf("["); this._cujahegijaXawaebi = this._qiujaejuto.Substring(0, length); } else if (this.CurrentState == XmlTokenType.DocTypeDeclaration) { this.CurrentState = XmlTokenType.DocTypeDefStart; this._cujahegijaXawaebi = "["; } else if (this.CurrentState == XmlTokenType.DocTypeDefStart) { if (this._qiujaejuto.StartsWith("]>")) { this.CurrentState = XmlTokenType.DocTypeDefEnd; this._cujahegijaXawaebi = "]>"; } else { this.CurrentState = XmlTokenType.DocTypeDefValue; int num3 = this._qiujaejuto.IndexOf("]>"); this._cujahegijaXawaebi = this._qiujaejuto.Substring(0, num3); } } else if (this.CurrentState == XmlTokenType.DocTypeDefValue) { this.CurrentState = XmlTokenType.DocTypeDefEnd; this._cujahegijaXawaebi = "]>"; } else if (this.CurrentState == XmlTokenType.DoubleQuotationMarkStart) { if (this._qiujaejuto[0] == '"') { this.CurrentState = XmlTokenType.DoubleQuotationMarkEnd; this._cujahegijaXawaebi = "\""; } else { this.CurrentState = XmlTokenType.AttributeValue; int num4 = this._qiujaejuto.IndexOf("\""); this._cujahegijaXawaebi = this._qiujaejuto.Substring(0, num4); } } else if (this.CurrentState == XmlTokenType.SingleQuotationMarkStart) { if (this._qiujaejuto[0] == '\'') { this.CurrentState = XmlTokenType.SingleQuotationMarkEnd; this._cujahegijaXawaebi = "'"; } else { this.CurrentState = XmlTokenType.AttributeValue; int num5 = this._qiujaejuto.IndexOf("'"); this._cujahegijaXawaebi = this._qiujaejuto.Substring(0, num5); } } else if (this.CurrentState == XmlTokenType.CommentStart) { if (this._qiujaejuto.StartsWith("-->")) { this.CurrentState = XmlTokenType.CommentEnd; this._cujahegijaXawaebi = "-->"; } else { this.CurrentState = XmlTokenType.CommentValue; this._cujahegijaXawaebi = this.Pomuav(this._qiujaejuto, location); } } else if (this.CurrentState == XmlTokenType.NodeStart) { this.CurrentState = XmlTokenType.NodeName; this._cujahegijaXawaebi = this.Ucouta(this._qiujaejuto, location); } else if (this.CurrentState == XmlTokenType.XmlDeclarationStart) { this.CurrentState = XmlTokenType.NodeName; this._cujahegijaXawaebi = this.Ucouta(this._qiujaejuto, location); } else if (this.CurrentState == XmlTokenType.NodeName) { if ((this._qiujaejuto[0] != '/') && (this._qiujaejuto[0] != '>')) { this.CurrentState = XmlTokenType.AttributeName; this._cujahegijaXawaebi = this.AleukiIgeusef(this._qiujaejuto, location); } else { this.Keoceuhiag(); } } else if (this.CurrentState == XmlTokenType.NodeEndValueStart) { if (this._qiujaejuto[0] == '<') { this.Keoceuhiag(); } else { this.CurrentState = XmlTokenType.NodeValue; this._cujahegijaXawaebi = this.EcausuodekuitNoatoi(this._qiujaejuto, location); } } else if (this.CurrentState == XmlTokenType.DoubleQuotationMarkEnd) { this.Uwairitubaijoe(location); } else if (this.CurrentState == XmlTokenType.SingleQuotationMarkEnd) { this.Uwairitubaijoe(location); } else { this.Keoceuhiag(); } if (this._cujahegijaXawaebi != string.Empty) { ttype = this.CurrentState; return (str + this._cujahegijaXawaebi); } return string.Empty; } public Color GetTokenColor(XmlTokenType ttype) { Color.FromArgb(0xee, 0x95, 0x44); switch (ttype) { case XmlTokenType.XmlDeclarationStart: case XmlTokenType.XmlDeclarationEnd: case XmlTokenType.NodeStart: case XmlTokenType.NodeEnd: case XmlTokenType.NodeEndValueStart: case XmlTokenType.AttributeValue: case XmlTokenType.CommentStart: case XmlTokenType.CommentEnd: case XmlTokenType.CDataStart: case XmlTokenType.CDataEnd: case XmlTokenType.DocTypeStart: case XmlTokenType.DocTypeDefStart: case XmlTokenType.DocTypeDefEnd: case XmlTokenType.DocTypeEnd: return Color.Blue; case XmlTokenType.NodeName: case XmlTokenType.DocTypeName: return Color.Blue; case XmlTokenType.NodeValue: case XmlTokenType.EqualSignStart: case XmlTokenType.EqualSignEnd: case XmlTokenType.DoubleQuotationMarkStart: case XmlTokenType.DoubleQuotationMarkEnd: case XmlTokenType.SingleQuotationMarkStart: case XmlTokenType.SingleQuotationMarkEnd: return Color.Black; case XmlTokenType.AttributeName: case XmlTokenType.DocTypeDeclaration: return Color.Red; case XmlTokenType.CommentValue: return Color.Green; case XmlTokenType.CDataValue: case XmlTokenType.DocTypeDefValue: return Color.Gray; } return Color.Orange; } public string GetXmlDeclaration(string s) { int index = s.IndexOf("<?"); int num2 = s.IndexOf("?>"); if ((index > -1) && (num2 > index)) { return s.Substring(index, (num2 - index) + 2); } return string.Empty; } private string IgitauciOmoduici(string uleavacaom, int qaikiepiceutOjepoku) { bool flag = false; StringBuilder builder = new StringBuilder(); for (int i = 0; (qaikiepiceutOjepoku + i) < uleavacaom.Length; i++) { char c = uleavacaom[qaikiepiceutOjepoku + i]; if (!char.IsWhiteSpace(c)) { break; } flag = true; builder.Append(c); } if (flag) { return builder.ToString(); } return string.Empty; } private void Keoceuhiag() { if (this._qiujaejuto.StartsWith("<![CDATA[")) { this.CurrentState = XmlTokenType.CDataStart; this._cujahegijaXawaebi = "<![CDATA["; } else if (this._qiujaejuto.StartsWith("<!DOCTYPE")) { this.CurrentState = XmlTokenType.DocTypeStart; this._cujahegijaXawaebi = "<!"; } else if (this._qiujaejuto.StartsWith("</")) { this.CurrentState = XmlTokenType.NodeStart; this._cujahegijaXawaebi = "</"; } else if (this._qiujaejuto.StartsWith("<!--")) { this.CurrentState = XmlTokenType.CommentStart; this._cujahegijaXawaebi = "<!--"; } else if (this._qiujaejuto.StartsWith("<?")) { this.CurrentState = XmlTokenType.XmlDeclarationStart; this._cujahegijaXawaebi = "<?"; } else if (this._qiujaejuto.StartsWith("<")) { this.CurrentState = XmlTokenType.NodeStart; this._cujahegijaXawaebi = "<"; } else if (this._qiujaejuto.StartsWith("=")) { this.CurrentState = XmlTokenType.EqualSignStart; if (this.CurrentState == XmlTokenType.AttributeValue) { this.CurrentState = XmlTokenType.EqualSignEnd; } this._cujahegijaXawaebi = "="; } else if (this._qiujaejuto.StartsWith("?>")) { this.CurrentState = XmlTokenType.XmlDeclarationEnd; this._cujahegijaXawaebi = "?>"; } else if (this._qiujaejuto.StartsWith(">")) { this.CurrentState = XmlTokenType.NodeEndValueStart; this._cujahegijaXawaebi = ">"; } else if (this._qiujaejuto.StartsWith("-->")) { this.CurrentState = XmlTokenType.CommentEnd; this._cujahegijaXawaebi = "-->"; } else if (this._qiujaejuto.StartsWith("]>")) { this.CurrentState = XmlTokenType.DocTypeEnd; this._cujahegijaXawaebi = "]>"; } else if (this._qiujaejuto.StartsWith("]]>")) { this.CurrentState = XmlTokenType.CDataEnd; this._cujahegijaXawaebi = "]]>"; } else if (this._qiujaejuto.StartsWith("/>")) { this.CurrentState = XmlTokenType.NodeEnd; this._cujahegijaXawaebi = "/>"; } else if (this._qiujaejuto.StartsWith("\"")) { if (this.CurrentState == XmlTokenType.AttributeValue) { this.CurrentState = XmlTokenType.DoubleQuotationMarkEnd; } else { this.CurrentState = XmlTokenType.DoubleQuotationMarkStart; } this._cujahegijaXawaebi = "\""; } else if (this._qiujaejuto.StartsWith("'")) { this.CurrentState = XmlTokenType.SingleQuotationMarkStart; if (this.CurrentState == XmlTokenType.AttributeValue) { this.CurrentState = XmlTokenType.SingleQuotationMarkEnd; } this._cujahegijaXawaebi = "'"; } } private string Pomuav(string uleavacaom, int qaikiepiceutOjepoku) { string str = ""; int index = uleavacaom.IndexOf("-->"); if (index != -1) { str = uleavacaom.Substring(0, index); } return str; } private List<string> Seateqa(string uleavacaom) { List<string> list = new List<string>(); string[] strArray = uleavacaom.Split(new char[] { ' ' }); for (int i = 0; i < strArray.Length; i++) { strArray[i] = strArray[i].Trim(); if (strArray[i].Length > 0) { list.Add(strArray[i]); } } return list; } private string Ucouta(string uleavacaom, int qaikiepiceutOjepoku) { string str = ""; for (int i = 0; i < uleavacaom.Length; i++) { if (((uleavacaom[i] == '/') || (uleavacaom[i] == ' ')) || (uleavacaom[i] == '>')) { return str; } str = str + uleavacaom[i].ToString(); } return str; } private void Uwairitubaijoe(int qaikiepiceutOjepoku) { if (this._qiujaejuto.StartsWith(">")) { this.Keoceuhiag(); } else if (this._qiujaejuto.StartsWith("/>")) { this.Keoceuhiag(); } else if (this._qiujaejuto.StartsWith("?>")) { this.Keoceuhiag(); } else { this.CurrentState = XmlTokenType.AttributeName; this._cujahegijaXawaebi = this.AleukiIgeusef(this._qiujaejuto, qaikiepiceutOjepoku); } } } }
Java
UTF-8
4,694
2.859375
3
[]
no_license
package com.ntu.api.controller.additional; import javafx.fxml.FXML; import javafx.scene.control.TextArea; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; public class AboutController { @FXML AnchorPane aboutDlg; @FXML private TextArea aboutTextArea; private static boolean bool; public static void setBool(boolean bool) { AboutController.bool = bool; } @FXML public void initialize() { if (bool) { aboutTextArea.setText(" Програма для розрахунку конструкції дорожнього одягу «ConstRoad» призначена для розрахунку її надійності та конструкції дорожнього одягу за наступними параметрами: \n" + "- за допустимим пружнім прогином, \n" + "- за умовою стійкості проти зсуву у ґрунті земляного полотна,\n" + "- за умовою стійкості проти зсуву у невязких шарах земляного покриття,\n" + "- за критерієм пружного прогину. \n" + " Конструктивно програма складається з п'яти основних блоків: блоку введення даних; блоку представлення результатів розрахунків; блоку розрахункових даних, блоку оптимізації та блоку довідкових даних. \n" + " Блок введення даних призначений для вибору користувачем параметрів та умов експлуатації дорожнього покриття. \n" + " Блок довідкових даних включає в себе сукупність довідкових таблиць з нормативних документів та довідників по розрахунку конструкції дорожнього одягу. \n" + " Блок розрахункових даних включає в себе розрахунки за критерієм пружного прогину, за критерієм зсуву у ґрунті земляного полотна, за критерієм зсуву у невязких шарах земляного покриття, за критерієм опору шарів з монолітних матеріалів розтягу при згині. \n" + " Блок оптимізації призначений для оптимізації товщин шарів дорожнього покриття за одним із критеріїв.\n" + " Блоку представлення результатів розрахунків призначений для формування звіту по конструкції дорожнього покриття та його збереження в зручному для перегляду форматі."); } else { aboutTextArea.setText("Алгоритм роботи з програмою:\n" + "- відкрити збережену або вести нову конструкцію дорожнього покриття;\n" + "- вибрати режим роботи програми: \n" + " - \"Розрахунок експлуатаційних параметрів конструкції дорожнього покриття\",\n" + " - \"Перебір можливих варіантів конструкції дорожнього одягу, які задовольняють умови надійності та експлуатаційним критеріям\";\n" + "- переглянути результати розрахунку;\n" + "- провести оптимізацію конструкції дорожнього одягу, за необхідності;\n" + "- зберегти результати розрахунку, сформувавши звіт по конструкції дорожнього одягу."); } } @FXML public void okOnClick(){ Stage dlg = (Stage)(aboutDlg.getScene().getWindow()); dlg.close(); } }
Markdown
UTF-8
5,315
2.578125
3
[]
no_license
# Determining Available Restriction Enzyme Recognition Sites for Molecular Cloning: ## Introduction This pipeline is written Python3. When two DNA sequences are input as fasta files (or optionally as sequence strings) the output is a print of three lists: one list is the restriction enzymes which do not cut in either sequences. The other two lists are restriction enzymes which are unique cutters to only one of the two sequences. ## Getting Started Download all Python scripts in this repository along with the example fasta files. ### Prerequisites 1. Requires Python3 and JupyterNotebook both available via the Anaconda Navigator package (https://www.anaconda.com/products/individual) or available separately 2. Requires Biopython to be installed (code to do this available in annotation of 'Unique and non-cutting restriction site analysis.ipynb' file). ## How To Run Sample Data 1. Ensure DNA files 'addgene_pUC19.fasta' and 'dCas9.fasta' are available in the same directory as the coding files. 2. Open 'Unique and non-cutting restriction site analysis.ipynb' Jupyter notebook file. 3. Run the first cell which: imports the required packages, reads in the DNA files, and analyses the restriction enzyme recognition sites. (This example is currently set to search with the New England Biolabs restriction enzymes list as default.) 4. The purpose of this first cell is to assign a Bio.Restriction.Restriction.Analysis object for each DNA sequence which contains, amongst other things, the positions of (or lack thereof) all restriction enzymes recognition sites searched in the DNA sequence. 5. Run the second cell. This imports the Restriction_analysis_module1.txt module and uses the function within this module that counts the the number of recognition sites for each restriction enzyme. Restriction enzymes that are not in either sequence or cut only once in one sequence and not the other are filtered to respective RestrictionBatches. 6. Run the third cell. This prints the RestrictionBatches created by the previous cell as alphabetised lists of all the restriction enzyme names contained therein. *Example output:* Non_cutting_enzymes: AfeI, AflII, AgeI, ApaI, AscI, AsiSI, AvrII, BaeI, BbvCI, BglII, BseRI, BsiWI, BspDI, BspEI, BsrGI, BssHII, BstEII, BstXI, Bsu36I, BtgZI, ClaI, CspCI, DraIII, EagI, EcoNI, FseI, HpaI, MscI, NaeI, NgoMIV, NotI, NsiI, PacI, PaeR7I, PflFI, PflMI, PmeI, PpuMI, PspOMI, PspXI, RsrII, SacII, SexAI, SfiI, SgrAI, SnaBI, SpeI, SrfI, StuI, Tth111I, XcmI, XhoI Sequence1_unique_enzymes: AatII, AhdI, AlwNI, AvaI, BsaI, BseYI, BsoBI, BspQI, BsrFI, EcoO109I, KasI, NarI, NmeAIII, PluTI, PstI, SalI, SapI, SbfI, SfoI, SmaI, TspMI, XbaI, XmaI, ZraI Sequence2_unique_enzymes: AleI, BmgBI, BmtI, BsgI, BsmFI, BsmI, BstBI, BstZ17I, BtgI, MluI, NcoI, NheI, NruI, PmlI, SwaI ## Custom usage: To run on your own DNA sequences edit the filepaths from the sample data filepath to desired input DNA sequence fasta file filepath. ## Optional customisation in 'Unique and non-cutting restriction site analysis.ipynb': 1. DNA sequences, in the form of a string of 'A', 'G', 'C', 'T' characters, can be manually entered by replacing "sequence1 = SeqIO.read("filepath", "fasta")" with "seqeunce1 = Seq("{Paste sequence here}")". This also required the .seq to be removed from the sequence1.seq and sequence2.seq Analysis arguments at the end of the first cell. 2. The list of restriction enzyme recognition sites (the restriction batch) used when analysing the DNA sequence can be altered via two means: - Other supplier lists can be changed/added to the 'restriction_search_database' by using other supplier codes in the 'suppliers' argument of the 'RestrictionBatch' function. - E.g.: C = Minotech Biotechnology; B = Life Technologies; E = Agilent Technologies; I = SibEnzyme Ltd.; K = Takara Bio Inc.; J = Nippon Gene Co., Ltd.; M = Roche Applied Science; O = Toyobo Biochemicals; N = New England Biolabs; Q = Molecular Biology Resources - CHIMERx; S = Sigma Chemical Corporation; R = Promega Corporation; V = Vivantis Technologies; Y = SinaClon BioScience Co.; X = EURx Ltd. - Within the 'Analysis' function the restriction batch argument can be changed from the custom 'restriction_search_database' to either 'AllEnzymes' or 'CommOnly' to search for either all available restriction enzyme recognition sites or all commercially avialable restriction enzymes respectively. 3. DNA sequences can either be set at linear (linear = True) or circular (linear = False) in the Analysis function at the end of the first cell. ## Summary of the 'restriction_sites_analysis' Function: - Input: two Bio.Restriction.Restriction.Analysis objects, one for each DNA sequence. - Output: a dictionary containing 3 RestrictionBatch objects: - "Non_cutting_enzymes": containing the restriction enzymes that cut neither sequence, - "Sequence1_unique_enzymes": containing the restriction enzymes that only cut uniquely in sequence 1, - "Sequence2_unique_enzymes": containing restriction enzymes that only cut uniquely in sequence 2. Author: Josie Elliott Acknowledgments BioPython Tutorial and Cookbook: http://biopython.org/DIST/docs/tutorial/Tutorial.html#sec11 and specifically the restriction enzymes section: http://biopython.org/DIST/docs/cookbook/Restriction.html
Markdown
UTF-8
2,071
2.875
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Business and Technical Decision Makers learning catalog description: Find all the training options for Power Automation author: loreleishannonmsft ms.topic: article ms.date: 03/21/2020 ms.author: v-lshann --- # Business and Technical Decision Makers Learning Catalog Do you decide whether to invest in new technologies? The following catalog is organized from core knowledge to specific domains, and from most basic to most advanced. If content exists in multiple formats, we'll let you know, so that you can choose the training format that best meets your needs. ## Get started<a name="get-started"></a> |Content |Description | Format | Length | |-----------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------|--------------------| | [Microsoft Power Platform Fundamentals](https://docs.microsoft.com/learn/certifications/courses/pl-900t00) | Learn about the components of Power Platform, ways to connect data, and how organizations can leverage this technology | Instructor-led in person or online training, cost varies by region and partner | 2 days | | [Automate a business process using Power Automate](https://docs.microsoft.com/learn/paths/automate-process-power-automate/) | This learning path introduces you to Power Automate, teaches you how to build workflows, and how to administer flows. | Free, self-paced online learning path | 3 hours 11 minutes | | [Get started with Power Automate](https://docs.microsoft.com/learn/modules/get-started-flows/) | Power Automate is an online workflow service that automates actions across the most common apps and services. | Free, self-paced online learning path | 58 minutes |
Python
UTF-8
4,889
2.875
3
[]
no_license
import copy import numpy as np import matplotlib.pyplot as plt import time class Environment: cliff = -3; road = -1; sink = -2; goal = 2 goal_position = [2, 3] reward_list = [[road, road, road, road], [road, road, sink, road], [road, road, road, goal]] reward_list1 = [['road', 'road', 'road', 'road'], ['road', 'road', 'sink', 'road'], ['road', 'road', 'road', 'goal']] def __init__(self): self.reward = np.asarray(self.reward_list) def move(self, agent, action): done = False new_pos = agent.pos + agent.action[action] if self.reward_list1[agent.pos[0]][agent.pos[1]] == 'goal': reward = self.goal observation = agent.set_pos(agent.pos) done = True elif new_pos[0] < 0 or new_pos[0] >= self.reward.shape[0] or new_pos[1] < 0 or new_pos[1] >= self.reward.shape[ 1]: reward = self.cliff observation = agent.set_pos(agent.pos) done = True else: observation = agent.set_pos(new_pos) reward = self.reward[observation[0], observation[1]] return observation, reward, done class Agent: action = np.array([[-1, 0], [0, 1], [1, 0], [0, -1]]) select_action_pr = np.array([0.25, 0.25, 0.25, 0.25]) def __init__(self, initial_position): self.pos = initial_position def set_pos(self, position): self.pos = position return self.pos def get_pos(self): return self.pos def policy_evaluation(env, agent, v_table, policy): while True: delta = 0 temp_v = copy.deepcopy(v_table) for i in range(env.reward.shape[0]): for j in range(env.reward.shape[1]): agent.set_pos([i,j]) action = policy[i,j] observation, reward, done = env.move(agent, action) v_table[i,j] = reward + gamma*v_table[observation[0], observation[1]] delta = np.max([delta, np.max(np.abs(temp_v - v_table))]) if delta < 0.000001: break return v_table, delta def policy_improvement(env, agent, v_table, policy): policyStable = True # 기존엔 pilicy for i in range(env.reward.shape[0]): for j in range(env.reward.shape[1]): old_action = policy[i,j] temp_action = 0 temp_value = -1e+10 for action in range(len(agent.action)): agent.set_pos([i,j]) observation, reward, done = env.move(agent, action) if temp_value < reward + gamma*v_table[observation[0], observation[1]]: temp_action = action temp_value = reward + gamma*v_table[observation[0], observation[1]] if old_action != temp_action: policyStable = False # 위에어 오류랑 킹리적 갓심 policy[i,j] = temp_action return policy, policyStable def show_policy(policy, env): for i in range(env.reward.shape[0]): print('+----------' * env.reward.shape[1], end=''); print('+'); print('|', end='') for j in range(env.reward.shape[1]): if env.reward_list1[i][j] != 'goal': if policy[i, j] == 0: print(' ↑ |', end='') elif policy[i, j] == 1: print(' → |', end='') elif policy[i, j] == 2: print(' ↓ |', end='') elif policy[i, j] == 3: print(' ← |', end='') else: print(' * |', end='') print() def show_v_table(v_table, env): for i in range(env.reward.shape[0]): print('+-----------------' * env.reward.shape[1], end='') print('+') for k in range(3): print('|', end='') for j in range(env.reward.shape[1]): if k == 0: print(' |', end='') if k == 1: print(' {0:8.2f} |'.format(v_table[i, j]), end='') if k == 2: print(' |', end='') print() print('+-----------------' * env.reward.shape[1], end='') print('+') np.random.seed(0) env = Environment() initial_position = np.array([0,0]) agent = Agent(initial_position) gamma = 0.0 v_table = np.random.rand(env.reward.shape[0], env.reward.shape[1]) policy = np.random.randint(0, 4, (env.reward.shape[0], env.reward.shape[1])) max_iter_number = 20000 for iter_number in range(max_iter_number): v_table, delta = policy_evaluation(env, agent, v_table, policy) policy, policyStable = policy_improvement(env, agent, v_table, policy) show_v_table(v_table, env) show_policy(policy, env) if policyStable == True: break
JavaScript
UTF-8
2,504
2.5625
3
[]
no_license
const browser = require('webextension-polyfill') import { OneTimeSecretApi } from 'onetimesecret-api' import { Storage } from '../modules/storage' function processSecret(secret) { var myStorage = Storage() myStorage.init().then(function() { if (!secret.length) { browser.tabs.create({ url: myStorage.getHost() }); } else { const ots = new OneTimeSecretApi( myStorage.getUsername(), myStorage.getApiKey(), { url: myStorage.getHost(), apiVersion: 'v1' } ) var options = { ttl: parseInt(myStorage.getLifetime()) } if (myStorage.getAskForPassphrase()) { var passphrase = prompt('Please enter an optional passphrase: ', '') if (passphrase.length) { options.passphrase = passphrase } } ots .share(secret, options) .then(function(response) { browser.tabs.create({ url: myStorage.getHost() + '/private/' + response.metadata_key }) }) .catch(function(error) { alert('Unable to create secret link: ' + error.message) }) } }) } // Create OTS page context menu options function createContextItem() { const contexts = ['page', 'link', 'selection'] browser.contextMenus.create({ id: '1', title: 'Create secret link', contexts: contexts }) browser.contextMenus.onClicked.addListener(function(info, tab) { var secret if (info.selectionText) { secret = info.selectionText } else if (info.linkUrl) { secret = info.linkUrl } else { secret = info.pageUrl } processSecret(secret); }); } // add the context buttons createContextItem() // register a handler for the icon click browser.browserAction.onClicked.addListener(function(tab) { var myStorage = Storage() myStorage.init().then(function() { browser.tabs.create({ url: myStorage.getOpenSettingsOnIconClick() ? "options.html" : myStorage.getHost() }); }); }); // register a handler for our commands browser.commands.onCommand.addListener(function(command) { switch (command) { case 'create-secret-from-selection': browser.tabs.executeScript({ code: "window.getSelection().toString();" }) .then(function(selection) { var secret = selection[0]; processSecret(secret); }) .catch(function(err) { console.log(err); }); break; } });
JavaScript
UTF-8
1,320
3.453125
3
[ "BSD-3-Clause", "MIT" ]
permissive
/** * @fileOverview Contains collection of primitive operations under graph. * * @author Andrei Kashcha (aka anvaka) / https://github.com/anvaka */ module.exports = operations; function operations() { return { /** * Gets graph density, which is a ratio of actual number of edges to maximum * number of edges. I.e. graph density 1 means all nodes are connected with each other with an edge. * Density 0 - graph has no edges. Runtime: O(1) * * @param graph represents oriented graph structure. * @param directed (optional boolean) represents if the graph should be treated as a directed graph. * * @returns density of the graph if graph has nodes. NaN otherwise. Returns density for undirected graph by default but returns density for directed graph if a boolean 'true' is passed along with the graph. */ density : function (graph,directed) { var nodes = graph.getNodesCount(); if (nodes === 0) { return NaN; } if(directed){ return graph.getLinksCount() / (nodes * (nodes - 1)); } else { return 2 * graph.getLinksCount() / (nodes * (nodes - 1)); } } }; };
C#
UTF-8
1,266
2.578125
3
[]
no_license
try { int packetsize, requestid, serverdata; string string1, string2; List&lt;byte&gt; str = new List&lt;byte&gt;(); using (BinaryReader reader = new BinaryReader(clientStream)) { packetsize = reader.ReadInt32(); requestid = reader.ReadInt32(); serverdata = reader.ReadInt32(); Console.WriteLine("Packet Size: {0} RequestID: {1} ServerData: {2}", packetsize, requestid, serverdata); byte nextByte = reader.ReadByte(); while (nextByte != 0) { str.Add(nextByte); nextByte = reader.ReadByte(); } // Password Sent to be Authenticated string1 = Encoding.UTF8.GetString(str.ToArray()); str.Clear(); nextByte = reader.ReadByte(); while (nextByte != 0) { str.Add(nextByte); nextByte = reader.ReadByte(); } } // NULL string string2 = Encoding.UTF8.GetString(str.ToArray()); Console.WriteLine("String1: {0} String2: {1}", string1, string2); // Reply to Authentication Request using (MemoryStream stream = new MemoryStream()) using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Write((int)(1)); // Packet Size writer.Write((int)(requestid)); // Mirror RequestID if Authenticated, -1 if Failed byte[] buffer = stream.ToArray(); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); } }
C
IBM852
532
2.921875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include "macros.h" #include "syst_jeu.h" /* test exist() teste si un lement existe dans un tableau ou pas */ int testexist(int nb, int *tab, int cmp){ //printf("nb dans texExist= %d \n", nb); int trouve =FALSE; int *p1; p1=tab; int i=0; // printf("taille %d \n", cmp); while(i<cmp && trouve==FALSE){ //printf("element i : %d \n", *p1); if(*p1==nb){ trouve=TRUE; } p1++; i++; } return trouve; }
Java
UTF-8
2,531
1.921875
2
[ "Apache-2.0" ]
permissive
package ru.tcsbank.mb.ui.activities.cashback; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Context; import android.support.v7.widget.RecyclerView.v; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import java.util.Iterator; import java.util.List; import ru.tcsbank.mb.utils.g.d; import ru.tinkoff.mb.api.entities.loyalty.b; public final class e extends d<c> { List<b> a; boolean[] b; a c; int d; private final LayoutInflater e; public e(Context paramContext) { this.e = LayoutInflater.from(paramContext); } public final int a() { if (this.a == null) { return 0; } return this.a.size(); } public final int a(int paramInt) { return 0; } public final void a(List<b> paramList) { this.a = paramList; this.b = new boolean[paramList.size()]; paramList = paramList.iterator(); int i = 0; while (paramList.hasNext()) { b localB = (b)paramList.next(); this.b[i] = localB.c; i += 1; } notifyDataSetChanged(); } public final int b() { int j = 0; boolean[] arrayOfBoolean = this.b; int m = arrayOfBoolean.length; int i = 0; while (i < m) { int k = j; if (arrayOfBoolean[i] != 0) { k = j + 1; } i += 1; j = k; } return j; } public final void b(int paramInt) { if (paramInt == this.d) { return; } this.d = paramInt; notifyItemRangeChanged(0, a(), new Object()); } public static abstract interface a { public abstract int a(int paramInt); public abstract void a(b paramB); } public static enum b { public static final int a = 1; public static final int b = 2; public static final int c = 3; } static final class c extends RecyclerView.v { final ImageView a; final TextView b; final ImageButton c; final CheckBox d; c(View paramView) { super(); this.a = ((ImageView)paramView.findViewById(2131296812)); this.b = ((TextView)paramView.findViewById(2131296813)); this.c = ((ImageButton)paramView.findViewById(2131296811)); this.d = ((CheckBox)paramView.findViewById(2131296810)); } } }
Java
UTF-8
1,457
3.234375
3
[]
no_license
package com.company; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Main { public static void main(String[] args) { JFrame window = new JFrame("Zamiana temperatury"); window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); window.setSize(400, 200); window.setLocationRelativeTo(null); window.setLayout(null); JLabel cel = new JLabel("Celcjusze"); cel.setBounds(240, 20, 100, 30); window.add(cel); JLabel wyn = new JLabel("Tutaj pojawi się wynik po przeliczeniu C na F"); wyn.setBounds(50, 110, 400, 30); window.add(wyn); JTextField stopnie = new JTextField(); stopnie.setBounds(135, 20, 100, 25); window.add(stopnie); JButton button = new JButton("Przelicz na F"); button.setBounds(120, 75, 125, 30); window.add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { String liczba = stopnie.getText(); Integer.parseInt(liczba); double wynik = (Integer.parseInt(liczba) * 1.8 + 32); wyn.setText(liczba + " stopni w Cejcjuszach to " + wynik + " stopni w Fahrenheita"); } } ); window.setVisible(true); } }
Python
UTF-8
573
4.78125
5
[]
no_license
# Exercise 055: Highest and Lowest of the sequence # Make a program that reads the weight of five people. # At the end, show which was the highest and the lowest weight inputted. highest = 0 lowest = 0 for person in range(1, 6): weight = float(input(f'{person}º person\'s weight: ')) if person == 1: highest = weight lowest = weight else: if weight > highest: highest = weight elif weight < lowest: lowest = weight print(f'The highest weight was: {highest}\n' f'The lowest weight was: {lowest}')
Java
UTF-8
1,368
2.46875
2
[]
no_license
package edu.stevens.cs.cs548.clinic.rest.server; import java.io.IOException; import java.net.URI; import java.util.HashMap; import java.util.Map; import javax.ws.rs.core.UriBuilder; import org.glassfish.grizzly.http.server.HttpServer; import com.sun.jersey.api.container.grizzly2.GrizzlyWebContainerFactory; public class Main { private Main() { BASE_URI = getBaseURI(); } private URI getBaseURI() { return UriBuilder.fromUri("http://localhost/").port(9090).build(); } public URI BASE_URI; protected HttpServer startServer() throws IOException { final Map<String, String> initParams = new HashMap<String, String>(); initParams.put("com.sun.jersey.config.property.packages", "edu.stevens.cs.cs548.clinic.rest.resource"); System.out.println("Starting grizzly..."); return GrizzlyWebContainerFactory.create(BASE_URI, initParams); } public static void main(String[] args) throws IOException { Main main = new Main(); HttpServer httpServer = main.startServer(); System.out.println(String.format("Jersey app started with WADL available at " + "%sapplication.wadl\nTry out %shello\nHit enter to stop it...", main.BASE_URI, main.BASE_URI)); System.in.read(); httpServer.stop(); } }
C++
UTF-8
2,585
2.640625
3
[ "WTFPL" ]
permissive
#include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include "SDL.h" #include "Syndicate/Data/Palette.h" #include "Animation.h" SDL_Surface *screen = 0; Syndicate::Data::Palette *palette = 0; Animation *anim = 0; unsigned anim_index = 69; Uint32 anim_callback(Uint32 interval, void *param) { static unsigned frame_num = 0; static const unsigned x_offset = 128; static const unsigned y_offset = 128; SDL_FillRect(screen, 0, 255); uint8_t *pixels = reinterpret_cast<uint8_t *>(screen->pixels) + y_offset * screen->pitch + x_offset; anim->get(pixels, screen->pitch, frame_num); frame_num++; SDL_UpdateRect(screen, 0, 0, 0, 0); return interval; } int main(int argc, char *argv[]) { while(--argc) { anim_index = strtol(argv[argc], 0, 0); } printf("Initializing SDL.\n"); /* Initialize defaults, Video */ if((SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER)==-1)) { printf("Could not initialize SDL: %s.\n", SDL_GetError()); exit(-1); } printf("SDL initialized.\n"); screen = SDL_SetVideoMode(640, 480, 8, SDL_HWSURFACE | SDL_DOUBLEBUF| SDL_RESIZABLE); if ( screen == NULL ) { fprintf(stderr, "Couldn't set 640x480x8 video mode: %s\n", SDL_GetError()); exit(1); } /* Clean up on exit, exit on window close and interrupt */ atexit(SDL_Quit); /* Init palette */ palette = new Syndicate::Data::Palette(); palette->load("HPAL02.DAT"); static SDL_Color colors[256]; for(unsigned index = 0; index < 256; index++) { palette->get(index, colors[index].r, colors[index].g, colors[index].b); } SDL_SetColors(screen, colors, 0, 256); /* Init anim */ anim = new Animation("HSTA-0.ANI", "HFRA-0.ANI", "HELE-0.ANI", "HSPR-0.TAB", "HSPR-0.DAT"); anim->set(anim_index); /* clear screen */ SDL_FillRect(screen, 0, 255); SDL_UpdateRect(screen, 0, 0, 0, 0); /* add timer for frame updates */ SDL_TimerID timer_id = SDL_AddTimer(1000, anim_callback, 0); /* Loop waiting for ESC+Mouse_Button */ SDL_Event event; bool stop = false; while (!stop) { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: { printf("Quit requested, quitting.\n"); stop = true; } break; case SDL_VIDEORESIZE: { if(!stop) { screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 8, SDL_HWSURFACE | SDL_DOUBLEBUF| SDL_RESIZABLE); SDL_SetColors(screen, colors, 0, 256); } } break; } } } delete palette; delete anim; exit(0); }
Python
UTF-8
160
3.28125
3
[]
no_license
age=int(input()) balance=9000 if 7<=age<=12: balance-=650 elif 13<=age<=18: balance-=1050 elif 19<=age: balance-=1250 else: pass print(balance)
Python
UTF-8
5,154
3.796875
4
[]
no_license
#Player Name player=input("Enter your name:") print("Hello",player,"\nWelcome to Tometri's 'Meme War'!") #Start Menu while True: start=input("Type 'Start' to begin your adventure\nFor any Yes/No questions please type 'Yes' or 'No'\nFor any numerical questions please input the number e.g. choice one=1") if start =='Start': break else: print("Please press start") #Fight Start print("You wake up to see CNN President, ZuckerDude standing above you\nHe is wearing a chestplate with the CNN logo engraved into it and he brandishes a sword made of gold and blackmail\nYou don't know where you are and you're very confused\nYou look over to see the meme you posted to Reddit displayed on a screen with the words 'We know it was you.' pasted over") #Answering ZuckerDude answerZD=input("ZuckerDude: Are you ready to die for the creation of your meme"+" "+player+"?") if answerZD=='Yes': print("ZuckerDude: You coward\n*ZuckerDude hits you with the back of his fist and disembers each part of your body with ease\nYour pain is over when he kicks you in the face knocking you out") #No branches:Answering ZuckerDude elif answerZD=='No': defy=int(input("ZuckerDude: If you seek a fight you won't find it here, I put a swift end to the last MemeDaddy; you will be no different!\n1.Pull out the 'Dagger of Bork' and take a defensive stance\n2.Call him a Weeb\n3.Call upon the MemeLord Pepe")) #Defy Choice One: Dagger of Doggo if defy==1: dagger=input("You pull out the dagger and stand defensively as ZuckerDude lunges towards you\nYou evade his attack and counter him by switly stabbing him in the leg\nZuckerDude:THIS IS UNNACCEPTABLE, DO YOU TRULY WISH TO BATTLE ME!?") #Dagger Branch if dagger=='No': print("*ZuckerDude posts your nudes to all of social media and pressures into suicide*\n*you die*") elif dagger=='Yes': print("ZuckerDude: You must wish for a horrible death"+" "+player) dagger2=int(input("ZuckerDude transforms into a beast of ultimate blackmailing capibilities and an assortment of threats\nZuckerDude is no more; there is only ZuckerBeast\nZuckerBeast leaps towards you and you have little time to think\nWhat do you do?\n1.Hold your dagger upwards for him to land on\n2.Jolt backwards")) #Dagger2 Branch if dagger2==1: print("ZuckerBeast lands upon you, flattening and killing you\nYour dagger went into his hip and caused him to have immediate hip surgery if that's anything") elif dagger2==2: print("You quickly jolt backwards resulting in ZuckerBeast landing upon, and breaking, his knee\nZuckerBeast: Dude what the hell!? I can't walk now, Fuck!") #Dagger2 End #Fallen1 branch fallen1=input("ZuckerBeast is down and in shock\nNow is the time to end this if you desire\nDo you wish to kill him?") if fallen1=='Yes': print("You approach him fom behind and slice his throat open\nYou can finally return home\nYou can finally retire\nLife is normal\nMemes will be plentiful\nYou are happy\nThak you for playing 'Meme War'") elif fallen1=='No': print("You hold the dagger firmly as your adreneline fades and so does your will to kill\nYou choose to end this all, peacefully\nYou walk away\nZuckerBeast grabs you from behind and begins to choke the life out of you\nThe dagger has fallen and your strength is wavering\nYou feel the life rushing out of you\nYou realize mercy was a mistake\nYou have been killed\nYou have failed the MemeLord\nYou have failed the world") #Fallen1 End #Defy Choice Two: Call him a weeb if defy==2: print("ZuckerDude: WhO dO yOu ThInK yOu ArE? I wIlL eNd YoU!\nZuckerDude begins yelling in Japanese before teleporting behind you and piercing your heart with his sword") #Defy Choice Three if defy==3: print("You pray upon the MemeLord Pepe and everything begins to glow with a golden aura\nTime stands still as you see Pepe The Boneless descend from the land of rare pepes\nPepeTheBoneless: I have heard your calls MemeDaddy"+" "+player) #Prayer Branch prayer=int(input("PepeTheBoneless: I can bestow upon you two things to help you\n1.I can give you the power of Boneless Pizza, a power to turn anything boneless; but you must be a Pepe Jim delivery boi\nOr\n2.I can give you the power of Memohkiin, but you will have to look at memes every thirty minutes to live")) if prayer==1: #Power Of Boneless Pizza print("PepeTheBoneless:You now have the ability to turn your enemies to figures without bone structure, have a nice day"+" "+player) print("You think to yourself\nYou're curious as to how powerful you truly are") #pobp pobp=input("You decide that there are only two way you can use your power\nYou can use it to the maximum amount, completely melting ZuckerDude\nOr\nYou can use the power in a limited manner\n")
PHP
UTF-8
2,404
3.140625
3
[]
no_license
<?php namespace Assign3; /** * MySQL implementation of WorkflowDB methods. */ class SQLWorkflow implements WorkflowDB { /** * Get an array of all workflows. */ public function getWorkflows() { $conn = Conn::getDbConnection(); $sql = "SELECT w.id, w.name, w.description "; $sql .= "FROM workflow w "; $sql .= "ORDER BY w.name;"; $result = mysqli_query($conn, $sql); $workflows = array(); while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { $workflow = new Workflow($row['id'], $row['name'], $row['description']); array_push($workflows, $workflow); } return $workflows; } /** * Get an individual workflow */ public function getWorkflow($workflow_id) { if (!isset($workflow_id)) { return null; } $conn = Conn::getDbConnection(); $sql = "SELECT w.id, w.name, w.description "; $sql .= "FROM workflow w "; $sql .= "WHERE w.id = ".$workflow_id." "; $sql .= "ORDER BY w.name;"; $result = mysqli_query($conn, $sql); $row = mysqli_fetch_array($result, MYSQLI_ASSOC); $count = mysqli_num_rows($result); $workflow = null; if ($count == 1) { $workflow = new Workflow($row['id'], $row['name'], $row['description']); } $this->getProcesses($workflow); return $workflow; } /** * Set all processes for a given workflow. */ public function getProcesses($workflow) { if (!isset($workflow)) { return false; } $conn = Conn::getDbConnection(); $sql = "SELECT p.id, p.name, p.active, wp.sequence, wp.estimated_time "; $sql .= "FROM process p INNER JOIN workflow_process wp ON p.id = wp.process_id "; $sql .= "WHERE wp.workflow_id = ".$workflow->id." "; $sql .= "ORDER BY wp.sequence;"; $result = mysqli_query($conn, $sql); $workflow->processes = array(); while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { $process = new Process($row['id'], $row['name'], $row['active']); $process->workflowSequence = $row['sequence']; $process->workflowEstimateTime = $row['estimated_time']; array_push($workflow->processes, $process); } return true; } }
JavaScript
UTF-8
1,327
2.78125
3
[]
no_license
import * as PIXI from 'pixi.js'; export default class Button { constructor(onStartGame, position) { this.container = new PIXI.Container(); this.position = position; this.isActive = true; this.onStartGame = onStartGame; this.initialize(); } initialize() { const resources = PIXI.Loader.shared.resources.assets.data; this.activeBtn = resources.other['activeBtn']; this.inactiveBtn = resources.other['inactiveBtn']; this.container.position.x = this.position.x; this.container.position.y = this.position.y; const btnTexture = PIXI.Texture.from(this.activeBtn); this.button = new PIXI.Sprite(btnTexture); this.button.anchor.set(0.5); this.container.buttonMode = this.isActive; this.container.interactive = this.isActive; this.container.addChild(this.button); this.container.addListener('pointerdown', this.handleOnClick.bind(this)); } handleOnClick() { if (!this.isActive) return; this.changeBtnState(false); this.onStartGame(this.changeBtnState.bind(this)) } changeBtnState(state) { this.isActive = state; this.button.texture = PIXI.Texture.from(this.isActive ? this.activeBtn : this.inactiveBtn); } }
C++
UTF-8
3,071
3.265625
3
[]
no_license
#pragma once #include <functional> #include <vector> #include "BangCore/Containers.h" namespace Bang { template <class T> class Array { public: using Ref = typename std::vector<T>::reference; using ConstRef = typename std::vector<T>::const_reference; using Iterator = typename std::vector<T>::iterator; using RIterator = typename std::vector<T>::reverse_iterator; using Const_Iterator = typename std::vector<T>::const_iterator; using Const_RIterator = typename std::vector<T>::const_reverse_iterator; static const Array<T> &Empty(); Array(); Array(const std::vector<T> &v); explicit Array(std::size_t size); explicit Array(std::size_t size, const T &initValue); Array(std::initializer_list<T> l); template <class OtherIterator> explicit Array(OtherIterator begin, OtherIterator end); template <template <class> class Container> explicit Array(const Container<T> &container); void Insert(const T &x, int index); void PushBack(const T &x); void PushBack(T &&x); void PushFront(const T &x); template <class IteratorClass> void PushBack(IteratorClass itBegin, IteratorClass itEnd); template <template <class OtherT> class Container, class OtherT> void PushBack(const Container<OtherT> &container); T *Data(); const T *Data() const; Const_Iterator Find(const T &x) const; Iterator Find(const T &x); Iterator FindLast(const T &x); bool Contains(const T &x) const; const T &Front() const; const T &Back() const; T &Front(); T &Back(); Iterator Remove(const Iterator &first, const Iterator &last); Iterator Remove(Iterator it); Iterator Remove(const T &x); Iterator RemoveByIndex(std::size_t i); void RemoveAll(const T &x); void PopBack(); void PopFront(); int IndexOf(const T &x) const; void Reserve(std::size_t n); void Resize(std::size_t n, const T &value = T()); uint Size() const; void Clear(); bool IsEmpty() const; void Reverse(); void Sort(); template <class StrictWeakOrdering> void Sort(const StrictWeakOrdering &sortClass); typename Array<T>::Ref At(std::size_t i); typename Array<T>::ConstRef At(std::size_t i) const; typename Array<T>::Ref operator[](std::size_t i); typename Array<T>::ConstRef operator[](std::size_t i) const; bool operator==(const Array<T> &rhs) const; bool operator!=(const Array<T> &rhs) const; template <template <class> class Container, class OtherT = T> Container<OtherT> To() const; Iterator Begin(); Iterator End(); Const_Iterator Begin() const; Const_Iterator End() const; RIterator RBegin(); RIterator REnd(); Const_RIterator RBegin() const; Const_RIterator REnd() const; // To allow range-based for loops Iterator begin(); Iterator end(); Const_Iterator begin() const; Const_Iterator end() const; const std::vector<T>& GetVector() const; private: std::vector<T> m_vector; }; } // namespace Bang #include "Array.tcc"
Java
UTF-8
4,384
2.546875
3
[]
no_license
package de.tud.jenkins; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; /** * Singleton class reading and providing the properties * defined in resources/jenkinsJobConfig/jobConfig.properties. * * @author svenseemann */ public class JobPropertiesManager { /** * Location of Properties file. */ private static final String JOB_PROPERTIES = "/jenkinsJobConfig/jobConfig.properties"; /** * Properties object holding the read properties * from file. */ private final Properties properties; /** * Static Singleton instance. */ private static JobPropertiesManager instance; /** * Call this to get the only instance of JobPropertiesManager. * * @return JobPropertiesManager object. */ public static JobPropertiesManager instanceOf() { if (instance == null) { instance = new JobPropertiesManager(); } return instance; } /** * Private Constructor. (Singleton-Pattern) */ private JobPropertiesManager() { this.properties = this.readProperties(); } /** * Read Properties from defined .properties file. * * @return Properties object containing all defined properties. */ private Properties readProperties() { Properties prop = new Properties(); InputStream input; try { input = getClass().getResourceAsStream(JobPropertiesManager.JOB_PROPERTIES); prop.load(input); input.close(); } catch (IOException ex) { Logger.getLogger(JobPropertiesManager.class.getName()) .log(Level.SEVERE, null, ex); } return prop; } /** * Returns the value of the scm.class.* property, * which can be used in config files for jenkins jobs. * Depending on usingGit it uses property scm.class.git or scm.class.none. * Other scm classes are not supported. * * @param usingGit - set true when using git as scm * @return value of the scm.class.* property */ public String getScmClass(Boolean usingGit) { if (usingGit) { return this.properties.getProperty("scm.class.git"); } else { return this.properties.getProperty("scm.class.none"); } } /** * Returns the plugin value, which can be used to configure scm * usage in jenkins jobs. * Currently only git is supported as plugin. * * @return git plugin string value */ public String getScmPlugin() { return this.properties.getProperty("scm.plugin.git"); } /** * Returns the plugin value, which can be used to * configure GitHub in jenkins jobs. * * @return GitHub plugin string value */ public String getPluginGitHub() { return this.properties.getProperty("github.plugin"); } public String getJdkName() { return this.properties.getProperty("builders.jdk.name"); } /** * Returns the name of the maven installation, which is (ddefault) configured * in jenkins. * * @return */ public String getMavenName() { return this.properties.getProperty("builders.mvn.name"); } /** * Currently only 'install' is supported. * * @return */ public String getMavenTarget() { return this.properties.getProperty("builders.mvn.target"); } public String getCredentialsId() { return this.properties.getProperty("scm.credentials"); } public String getCanRoam() { return this.properties.getProperty("canRoam"); } public String getConcurrentBuilds() { return this.properties.getProperty("concurrentBuild"); } public String getDisabled() { return this.properties.getProperty("disabled"); } public String getBlockBuildWhenDownstreamBuilding() { return this.properties.getProperty("blockBuildWhenDownstreamBuilding"); } public String getBlockBuildWhenUpstreamBuilding() { return this.properties.getProperty("blockBuildWhenUpstreamBuilding"); } public String getKeppDependencies() { return this.properties.getProperty("keepDependencies"); } }
Python
UTF-8
287
3.359375
3
[]
no_license
''' for item in 'Python': print (item) for item in ['vishal','Tushar','Subhash']: print (item) for item1 in [1,2,3,4,5]: print(item1) for item2 in range(10): print (item2) for item3 in range(5,10): print (item3) ''' for item4 in range(5,10,2): print (item4)
Java
UTF-8
1,249
2.78125
3
[]
no_license
package com.example.demo.entity; import javax.persistence.Entity; /** * @Author: 余锡鸿 * @Description: * @Date: Create in 8:17 PM 7/27/2018 * @Modified By: */ public class Company { public Long id; public String name; public int employeeNumber; public Company(){} public Company(Long id, String name, int employeeNumber) { this.id = id; this.name = name; this.employeeNumber = employeeNumber; } public Company(String name, int employeeNumber) { this.name = name; this.employeeNumber = employeeNumber; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getEmployeeNumber() { return employeeNumber; } public void setEmployeeNumber(int EmployeeNumber) { this.employeeNumber = EmployeeNumber; } @Override public String toString() { return "Company{" + "id=" + id + ", name='" + name + '\'' + ", EmployeeNumber=" + employeeNumber + '}'; } }
C
UTF-8
6,166
3.5625
4
[]
no_license
/** * @author Roy Ackerman */ #include <stdbool.h> #include <stdio.h> #include <math.h> #include "calculator.h" typedef enum Neighbours { RIGHT, LEFT, UP, BOTTOM } Neighbour; int gIs_cyclic; size_t gRows; size_t gColumns; source_point *gSources; size_t gNumOfSources; double **gGrid; /** * calculates the sum of the matrix grid. * @param grid - the matrix * @param y - num of rows * @param x - num of columns * @param sum output parameter contains the sum. */ void heatSum(double *sum) { *sum = 0; for (size_t row = 0; row < gRows; ++row) ////int instead of size_t { for (size_t col = 0; col < gColumns; ++col) ////////int instead of size_t { (*sum) += gGrid[row][col]; } } } /** * Checls weather the coordinate (x,y) is one of the sources. * @param row * @param col * @return true if is, false otherwise. */ bool isSource(const size_t row, const size_t col) { for (size_t i = 0; i < gNumOfSources; ++i) ////////int instead of size_t { if (gSources[i].x == (int)row && gSources[i].y == (int)col) ////////casting to int has been added { return true; } } return false; } /** * A custom mod operation uses the floor value instead of rounding to zero. * @param numerator is what we has to calculate * @param n a filed of the mod we has to calculate as a non-negative number * @return MOD(x,N) - the reminder of the division of x / N. */ size_t mod(const int denominator, const int numerator) { return (size_t) (((numerator % denominator) + denominator) % denominator); } /** * checks weather the coordinate (col, row) is out of the grid's matrix. * @param row * @param col * @return true if is, false otherwise. */ bool indexOutOfMatrix(const size_t row, const size_t col) { const size_t START_MATRIX_INDEX = 0; return (col < START_MATRIX_INDEX) || (row < START_MATRIX_INDEX) || (col >= gColumns) || (row >= gRows); } /** * Returns the value of the required member. */ double getNeighbourValue(size_t row, size_t col, const enum Neighbours neighbour) { const int VALUE_FOR_OUT_OF_MATRIX = 0; if (neighbour == RIGHT) { col++; } if (neighbour == LEFT) { col--; } if (neighbour == UP) { row++; } if (neighbour == BOTTOM) { row--; } if (gIs_cyclic) { row = mod((int) gRows, (int) row); col = mod((int) gColumns, (int) col); } if (indexOutOfMatrix(row, col)) { return VALUE_FOR_OUT_OF_MATRIX; } else { return gGrid[row][col]; } } /** * activates the function 'function' on the coordinate (r,c) * and calculates the RIGHT, LEFT, TOP, and BOTTOM as well. * @param function * @param r the row * @param c the column */ void activateFunction(const diff_func function, const size_t r, const size_t c) { double cell, onRight, onLeft, onTop, onDown; onRight = getNeighbourValue(r, c, RIGHT); onLeft = getNeighbourValue(r, c, LEFT); onTop = getNeighbourValue(r, c, UP); onDown = getNeighbourValue(r, c, BOTTOM); cell = gGrid[r][c]; gGrid[r][c] = function(cell, onRight, onTop, onLeft, onDown); } /** * performing the heat activity by activates the function * 'function' on each one of the matrix. * grid-array's cells. * @param function. */ void heat(const diff_func function) { for (size_t r = 0; r < gRows; r++) { for (size_t c = 0; c < gColumns; c++) { if (!isSource(r, c)) { // activate function on the coordinate (r,c) activateFunction(function, r, c); } } } } /** * checks weather we should terminate the * loop by iterations or not. * @param n_iter * @return true if should, otherwise false. */ bool isTerminatedByIterations(const int n_iter) { const int NO_ITERATIONS = 0; return (n_iter > NO_ITERATIONS); } /** * Checks weather the precision is good enough * by validates the remainder of currSum - prevSum. * @param prevSum - the sum of the previous iteration. * @param currSum - the sum of the current iteration. * @param terminate - the required precision. * @return */ bool isPrecise(const double prevSum, const double currSum, const double terminate) { return fabs(currSum - prevSum) < terminate; } /** * Calculates the heat and its dissipation according to the source points 'sources', *by activating the function 'function' on the matrix grid. * @param function the function to activate * @param grid the matrix * @param n the rows * @param m the columns * @param sources array of the heat sources points * @param num_sources the number of sources * @param terminate the 'epsilon' for detecting the required precision * @param n_iter num of iterations * @param is_cyclic is it should be cyclic * @return the heat reminder of the last iteration */ double calculate(diff_func function, double **grid, size_t n, size_t m, source_point *sources, size_t num_sources, double terminate, unsigned int n_iter, int is_cyclic) { //............ global variables initialization .......// gIs_cyclic = is_cyclic; gRows = n; gColumns = m; gSources = sources; gNumOfSources = num_sources; gGrid = grid; double prevSum; heatSum(&prevSum); // get the heat sum into sum double currSum = prevSum; if (isTerminatedByIterations(n_iter)) { for (unsigned int i = 0; i < n_iter; ++i) { prevSum = currSum; heat(function); // activate the heat function heatSum(&currSum); // get the current heat sum into currentSum } } else { do { prevSum = currSum; heat(function); // activate the heat function heatSum(&currSum); // get the current heat sum into currentSum } while (!isPrecise(prevSum, currSum, terminate)); } return fabs(currSum - prevSum); }
Java
UTF-8
568
3.640625
4
[]
no_license
// check number is prime or not import java.util.Scanner; public class Test8 { public static void main(String[] args) { // TODO Auto-generated method stub int num; System.out.println("Enter the number:"); Scanner sc=new Scanner(System.in); num=sc.nextInt(); boolean check=true; for(int i=2;i<=num/2;i++) { if(num%i == 0) { check = false; break; } } if(check) System.out.println(num+" is a prime number"); else System.out.println(num+" is not a prime number"); sc.close(); } }
Java
UTF-8
3,773
3.234375
3
[]
no_license
package CreatingObservable; import rx.Observable; import rx.Scheduler; import rx.Subscriber; import rx.Subscription; import rx.observers.Subscribers; import rx.schedulers.Schedulers; import java.awt.*; /* RxJava is a library that allows us to represent any operation as an asynchronous data stream that can be created on any thread, declaratively composed, and consumed by multiple objects on any thread.*/ public class ObservableCreate2 { public static void main(String[] args) { Observable observable = Observable.defer(() -> Observable.create((Observable.OnSubscribe<String>) subscriber -> { if (!subscriber.isUnsubscribed()) { try { subscriber.onNext("lovely"); subscriber.onNext("nice"); subscriber.onNext("Thread executed on: " + Thread.currentThread().getName()); subscriber.onCompleted(); } catch (Exception e) { subscriber.onError(e); } } }).subscribeOn(Schedulers.io()) ); /*Schedulers determine the thread on which Observables emit their asynchronous data streams and the thread on which Observers consume those data streams*/ /*There is another method on Observable that takes a Scheduler: observeOn(). The Scheduler passed into this method will determine the thread on which the Observer consumes the data emitted by the Observable subscribeOn() actually returns an Observable, so you can chain observeOn() onto the Observable that is returned by the call to subscribeOn():*/ Subscription subscription = observable.subscribe( o -> System.out.println(o), throwable -> System.out.println("Error"), () -> System.out.println("Completed") ); /*In cases where an Observable may live longer than its Observer because it is emitting items on a separate thread calling Subscription.unsubscribe() clears the Observable’s reference to the Observer whose connection is represented by the Subscription object.*/ /* * * Any call to Observable.subscribe() returns a Subscription. Subscriptions represent * a connection between an Observable that’s * emitting data and an Observer that’s consuming that data. More * specifically, the Subscription returned by Observable.subscribe() * represents the connection between the Observable receiving * the subscribe() message and the Observer that is passed in as a * parameter to the subscribe() method. Subscriptions give us the * ability to sever that connection by calling Subscription.unsubscribe(). * */ subscription.unsubscribe(); /*If an Activity utilizes multiple Observables, then the Subscriptions returned from each call to Observable.subscribe() can all be added to a CompositeSubscription, a Subscription whose unsubscribe() method will unsubscribe all Subscriptions that were previously added to it and that may be added to it in the future.*/ /*Android: As long as an Observable survives an Activity’s configuration change, RxJava provides several operators that save us from having to re-query a data source after a configuration change: the cache and replay operators. These operators both ensure that Observers who subscribe to an Observable after that Observable has emitted its items will still see that same sequence of items.*/ } }
C++
UTF-8
2,047
3
3
[]
no_license
#include <cstdio> #include <cstring> #define Parent(i) ((i - 1) >> 1) #define LChild(i) ((i << 1) + 1) #define RChild(i) ((i + 1) << 1) struct Task { long long priority; char name[9]; }; long long LIMIT = 0x100000000LL; int n, m; Task *tasks; class ComplHeap { public: ComplHeap(Task *tasks, int size) { _size = size; _heap = tasks; heapify(); } void heapify() { for (int i = Parent(_size - 1); -1 < i; i--) { percolateDown(_size, i); } } Task fetchMin() { Task min = _heap[0]; _heap[0].priority = _heap[0].priority << 1; percolateDown(_size, 0); return min; } private: int minIn(int a, int b) { if (b < 0 || _size <= b) { return a; } else if (a < 0 || _size <= a) { return b; } else { if (_heap[a].priority < _heap[b].priority) { return a; } else if (_heap[b].priority < _heap[a].priority){ return b; } else { if (strcmp(_heap[a].name, _heap[b].name) < 0) { return a; } else { return b; } } } } void percolateUp(int i) { int p; while (-1 < Parent(i)) { p = Parent(i); if (i != minIn(i, p)) break; Task t = _heap[i]; _heap[i] = _heap[p]; _heap[p] = t; i = p; } } void percolateDown(int hi, int i) { int j; while (i != (j = minIn(i, minIn(LChild(i), RChild(i))))) { Task t = _heap[i]; _heap[i] = _heap[j]; _heap[j] = t; i = j; } } Task *_heap; int _size; }; int main(void) { setvbuf(stdin, new char[1 << 20], _IOFBF, 1 << 20); setvbuf(stdout, new char[1 << 20], _IOFBF, 1 << 20); scanf("%d %d\n", &n, &m); tasks = new Task[n]; for (int i = 0; i < n; i++) { scanf("%lld %s\n", &tasks[i].priority, tasks[i].name); } ComplHeap *heap = new ComplHeap(tasks, n); for (int i = 0; i < m; i++) { Task task = heap->fetchMin(); if (LIMIT <= task.priority) break; printf("%s\n", task.name); } return 0; }
JavaScript
UTF-8
1,838
2.609375
3
[]
no_license
'use strict'; const request = require('request'); /** * Use this command to launch the handler from console: * * node_modules/.bin/serverless invoke local -f lambda -d '{"httpMethod":"GET","queryStringParameters":{"url":"http://github.com"}}' * * or from browser * * http://localhost:3000/?url=https://github.com */ module.exports.corsProxy = async (event, context) => { let params = event.queryStringParameters; console.log(event); console.log(`Got request with params:`, params); if (!params.url) { const errorResponse = { statusCode: 400, body: 'Unable get url from \'url\' query parameter' }; callback(null, errorResponse); return; } let originalRequestBody = event.body let options = { url: params.url, method: event.httpMethod, json: event.httpMethod === 'POST' ? JSON.parse(originalRequestBody) : null }; const { response, body } = await requestHandler(options); console.log(`Got response from ${params.url} ---> {statusCode: ${response.statusCode}}`); return { statusCode: 200, body: originalRequestBody ? JSON.stringify(body) : response.body, headers: { "Access-Control-Allow-Origin" : "*", // Required for CORS support to work "Access-Control-Allow-Credentials" : true, // Required for cookies, authorization headers with HTTPS "content-type": response.headers['content-type'] }, } }; const requestHandler = (options) => new Promise((resolve, reject) => { request(options, (error, response, body) => { if (error) { console.error(error); reject(error); } else { console.log(response, body); resolve({ response, body }); } }); });
JavaScript
UTF-8
362
2.71875
3
[ "MIT" ]
permissive
var Emoji = /** @class */ (function () { function Emoji(icon) { this.icon = icon; } return Emoji; }()); var unicorn = new Emoji("🦄"); unicorn.icon = "💩"; console.log(unicorn); // check the precomiple version on class.js // if you want to use typescript via cli do following // npm install typescript -g // tsc class.ts // node class.js
JavaScript
UTF-8
519
3.078125
3
[]
no_license
let screen = document.querySelector(".screen"); let equal = document.querySelector(".btn-equal"); let clear = document.querySelector(".btn-clear"); let buttons = document.querySelectorAll(".btn"); buttons.forEach((button) => { button.addEventListener("click", (e) => { let value = e.target.dataset.num; screen.value += value; console.log(value); }); }); equal.addEventListener("click", () => { screen.value = eval(screen.value); }); clear.addEventListener("click", () => { screen.value = ""; });
Java
UTF-8
3,906
3.109375
3
[]
no_license
package de.fh.aachen.dental.imagej.processor; import ij.ImagePlus; import ij.process.ImageProcessor; /** * * @author Daniel Wirtz * */ public class ReflectionFilter implements Preprocessor { private static final int STEPWIDTH = 10; private static final int STEPHEIGHT = 10; private static final int UPPERBOUND_OF_REFLECTION = 225; ImagePlus originalImage; int pixelWithReflectionCount = 0; public ReflectionFilter() { } /** * Duplicates the original image and removes all reflections. * * @return new image without reflections. */ public ImagePlus removeReflections() { ImagePlus clonedImage = this.originalImage.duplicate(); ImageProcessor originalProcessor = this.originalImage.getProcessor(); ImageProcessor clonedProcessor = clonedImage.getProcessor(); int[] rgb = new int[3]; // dummy to enter while-loop pixelWithReflectionCount = 1; // stop when there are no reflections anymore while (pixelWithReflectionCount != 0) { pixelWithReflectionCount = 0; for (int y = 0; y < originalProcessor.getHeight(); y++) { for (int x = 0; x < originalProcessor.getWidth(); x++) { originalProcessor.getPixel(x, y, rgb); int[] rgbAdapted = adaptivLocalRgbValues(x, y, rgb, originalProcessor); if (rgbAdapted != null) { clonedProcessor.putPixel(x, y, rgbAdapted); } } } this.originalImage = clonedImage; originalProcessor = this.originalImage.getProcessor(); clonedProcessor = clonedImage.getProcessor(); } clonedImage.setTitle(originalImage.getTitle() + " without reflections"); return clonedImage; } /** * * @param x * - x-coordinate of image * @param y * - y-coordinate of image * @param rgb * - rgb-values at coordinate (x,y) * @param ip * - imageprocessor of current image * @return averaged rgb-values at coordinate (x,y) */ private int[] adaptivLocalRgbValues(int x, int y, int[] rgb, ImageProcessor ip) { int rgbAdapted[] = new int[3]; int meanValue = 0; int rgbSum[] = new int[3]; // when current pixel is a reflection if (ReflectionFilter.isReflection(rgb)) { // local adaption for (int y_local = y - 5; y_local < (y - 5) + STEPHEIGHT; y_local++) { for (int x_local = x - 5; x_local < (x - 5) + STEPWIDTH; x_local++) { int[] tmpArray = ip.getPixel(x_local, y_local, rgbAdapted); // ignore pixel which are out of bounds if (!pixelIsOutOfBounds(tmpArray)) { if (!ReflectionFilter.isReflection(rgbAdapted)) { // summarize rgb values for (int i = 0; i < 3; i++) { rgbSum[i] += rgbAdapted[i]; } meanValue++; } } } } if (meanValue == 0) return null; for (int i = 0; i < 3; i++) { rgbAdapted[i] = rgbSum[i] / meanValue; } pixelWithReflectionCount++; return rgbAdapted; } return null; } /** * Checks whether the given rgb-values have coordinates (x,y) that are out * of the image. In this case the rgb-values are zero. * * @param rgb * - rgb-values * @return true, if rgb-values are zero, otherwise false */ boolean pixelIsOutOfBounds(int[] rgb) { return rgb[0] == 0 && rgb[1] == 0 && rgb[2] == 0; } /** * Checks whether the given rgb-values at coordinates (x,y) is a reflection. * A pixel is a reflection when there is at least one value (r,g,b) greater * equals than {@link ReflectionFilter#UPPERBOUND_OF_REFLECTION}. * * @param rgb * - rgb-values * @return true, if this rgb-values represents a reflection, otherwise false */ protected static boolean isReflection(int[] rgb) { return (rgb[0] >= UPPERBOUND_OF_REFLECTION || rgb[1] >= UPPERBOUND_OF_REFLECTION || rgb[2] >= UPPERBOUND_OF_REFLECTION); } @Override public ImagePlus process(ImagePlus image) { this.originalImage = image; return removeReflections(); } }
C#
UTF-8
2,118
2.984375
3
[ "MIT" ]
permissive
using Jotunn.Managers; namespace Jotunn.Entities { /// <summary> /// Main interface for adding custom status effects to the game.<br /> /// All custom status effects have to be wrapped inside this class to add it to Jötunns <see cref="ItemManager"/>. /// </summary> public class CustomStatusEffect : CustomEntity { /// <summary> /// The <see cref="global::StatusEffect"/> for this custom status effect. /// </summary> public StatusEffect StatusEffect { get; } /// <summary> /// Indicator if references from <see cref="Entities.Mock{T}"/>s will be replaced at runtime. /// </summary> public bool FixReference { get; set; } /// <summary> /// Custom status effect from a <see cref="global::StatusEffect"/>.<br /> /// Can fix references for <see cref="Entities.Mock{T}"/>s. /// </summary> /// <param name="statusEffect">A preloaded <see cref="global::StatusEffect"/></param> /// <param name="fixReference">If true references for <see cref="Entities.Mock{T}"/> objects get resolved at runtime by Jötunn.</param> public CustomStatusEffect(StatusEffect statusEffect, bool fixReference) { StatusEffect = statusEffect; FixReference = fixReference; } /// <summary> /// Checks if a custom status effect is valid (i.e. has a <see cref="global::StatusEffect"/>). /// </summary> /// <returns>true if all criteria is met</returns> public bool IsValid() { return StatusEffect != null && StatusEffect.IsValid(); } /// <inheritdoc/> public override bool Equals(object obj) { return obj.GetHashCode() == GetHashCode(); } /// <inheritdoc/> public override int GetHashCode() { return StatusEffect.name.GetStableHashCode(); } /// <inheritdoc/> public override string ToString() { return StatusEffect.name; } } }
Markdown
UTF-8
10,748
2.59375
3
[ "MIT" ]
permissive
serverless-dynamodb-local ================================= [![Join the chat at https://gitter.im/99xt/serverless-dynamodb-local](https://badges.gitter.im/99xt/serverless-dynamodb-local.svg)](https://gitter.im/99xt/serverless-dynamodb-local?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![npm version](https://badge.fury.io/js/serverless-dynamodb-local.svg)](https://badge.fury.io/js/serverless-dynamodb-local) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) ## This Plugin Requires * serverless@^1 * Java Runtime Engine (JRE) version 6.x or newer _OR_ docker CLI client ## Features * Install DynamoDB Local Java program * Run DynamoDB Local as Java program on the local host or in docker container * Start DynamoDB Local with all the parameters supported (e.g port, inMemory, sharedDb) * Table Creation for DynamoDB Local ## Install Plugin `npm install --save serverless-dynamodb-local` Then in `serverless.yml` add following entry to the plugins array: `serverless-dynamodb-local` ```yml plugins: - serverless-dynamodb-local ``` ## Using the Plugin 1) Install DynamoDB Local (unless using docker setup, see below) `sls dynamodb install` 2) Add DynamoDB Resource definitions to your Serverless configuration, as defined here: https://serverless.com/framework/docs/providers/aws/guide/resources/#configuration 3) Start DynamoDB Local and migrate (DynamoDB will process incoming requests until you stop it. To stop DynamoDB, type Ctrl+C in the command prompt window). Make sure above command is executed before this. `sls dynamodb start --migrate` Note: Read the detailed section for more information on advanced options and configurations. Open a browser and go to the url http://localhost:8000/shell to access the web shell for dynamodb local. ## Install: sls dynamodb install This installs the Java program locally. If using docker, this step is not required. To remove the installed dynamodb local, run: `sls dynamodb remove` Note: This is useful if the sls dynamodb install failed in between to completely remove and install a new copy of DynamoDB local. ## Start: sls dynamodb start This starts the DynamoDB Local instance, either as a local Java program or, if the `--docker` flag is set, by running it within a docker container. The default is to run it as a local Java program. All CLI options are optional: ``` --port -p Port to listen on. Default: 8000 --cors -c Enable CORS support (cross-origin resource sharing) for JavaScript. You must provide a comma-separated "allow" list of specific domains. The default setting for -cors is an asterisk (*), which allows public access. --inMemory -i DynamoDB; will run in memory, instead of using a database file. When you stop DynamoDB;, none of the data will be saved. Note that you cannot specify both -dbPath and -inMemory at once. --dbPath -d The directory where DynamoDB will write its database file. If you do not specify this option, the file will be written to the current directory. Note that you cannot specify both -dbPath and -inMemory at once. For the path, current working directory is <projectroot>/node_modules/serverless-dynamodb-local/dynamob. For example to create <projectroot>/node_modules/serverless-dynamodb-local/dynamob/<mypath> you should specify -d <mypath>/ or --dbPath <mypath>/ with a forwardslash at the end. --sharedDb -h DynamoDB will use a single database file, instead of using separate files for each credential and region. If you specify -sharedDb, all DynamoDB clients will interact with the same set of tables regardless of their region and credential configuration. --delayTransientStatuses -t Causes DynamoDB to introduce delays for certain operations. DynamoDB can perform some tasks almost instantaneously, such as create/update/delete operations on tables and indexes; however, the actual DynamoDB service requires more time for these tasks. Setting this parameter helps DynamoDB simulate the behavior of the Amazon DynamoDB web service more closely. (Currently, this parameter introduces delays only for global secondary indexes that are in either CREATING or DELETING status.) --optimizeDbBeforeStartup -o Optimizes the underlying database tables before starting up DynamoDB on your computer. You must also specify -dbPath when you use this parameter. --migration -m After starting dynamodb local, run dynamodb migrations. --heapInitial The initial heap size --heapMax The maximum heap size --migrate -m After starting DynamoDB local, create DynamoDB tables from the Serverless configuration. --seed -s After starting and migrating dynamodb local, injects seed data into your tables. The --seed option determines which data categories to onload. --convertEmptyValues -e Set to true if you would like the document client to convert empty values (0-length strings, binary buffers, and sets) to be converted to NULL types when persisting to DynamoDB. --docker Run DynamoDB inside docker container instead of as a local Java program --dockerImage Specify custom docker image. Default: amazon/dynamodb-local ``` All the above options can be added to serverless.yml to set default configuration: e.g. ```yml custom: dynamodb: # If you only want to use DynamoDB Local in some stages, declare them here stages: - dev start: port: 8000 inMemory: true heapInitial: 200m heapMax: 1g migrate: true seed: true convertEmptyValues: true # Uncomment only if you already have a DynamoDB running locally # noStart: true ``` Docker setup: ```yml custom: dynamodb: # If you only want to use DynamoDB Local in some stages, declare them here stages: - dev start: docker: true port: 8000 inMemory: true migrate: true seed: true convertEmptyValues: true # Uncomment only if you already have a DynamoDB running locally # noStart: true ``` ## Migrations: sls dynamodb migrate ### Configuration In `serverless.yml` add following to execute all the migration upon DynamoDB Local Start ```yml custom: dynamodb: start: migrate: true ``` ### AWS::DynamoDB::Table Resource Template for serverless.yml ```yml resources: Resources: usersTable: Type: AWS::DynamoDB::Table Properties: TableName: usersTable AttributeDefinitions: - AttributeName: email AttributeType: S KeySchema: - AttributeName: email KeyType: HASH ProvisionedThroughput: ReadCapacityUnits: 1 WriteCapacityUnits: 1 ``` **Note:** DynamoDB local doesn't support TTL specification, therefore plugin will simply ignore ttl configuration from Cloudformation template. ## Seeding: sls dynamodb seed ### Configuration In `serverless.yml` seeding categories are defined under `dynamodb.seed`. If `dynamodb.start.seed` is true, then seeding is performed after table migrations. If you wish to use raw AWS AttributeValues to specify your seed data instead of Javascript types then simply change the variable of any such json files from `sources:` to `rawsources:`. ```yml custom: dynamodb: start: seed: true seed: domain: sources: - table: domain-widgets sources: [./domainWidgets.json] - table: domain-fidgets sources: [./domainFidgets.json] test: sources: - table: users rawsources: [./fake-test-users.json] - table: subscriptions sources: [./fake-test-subscriptions.json] ``` ```bash > sls dynamodb seed --seed=domain,test > sls dynamodb start --seed=domain,test ``` If seed config is set to true, your configuration will be seeded automatically on startup. You can also put the seed to false to prevent initial seeding to use manual seeding via cli. ```fake-test-users.json example [ { "id": "John", "name": "Doe", }, ] ``` ## Using DynamoDB Local in your code You need to add the following parameters to the AWS NODE SDK dynamodb constructor e.g. for dynamodb document client sdk ``` var AWS = require('aws-sdk'); ``` ``` new AWS.DynamoDB.DocumentClient({ region: 'localhost', endpoint: 'http://localhost:8000', accessKeyId: 'DEFAULT_ACCESS_KEY', // needed if you don't have aws credentials at all in env secretAccessKey: 'DEFAULT_SECRET' // needed if you don't have aws credentials at all in env }) ``` e.g. for dynamodb document client sdk ``` new AWS.DynamoDB({ region: 'localhost', endpoint: 'http://localhost:8000', accessKeyId: 'DEFAULT_ACCESS_KEY', // needed if you don't have aws credentials at all in env secretAccessKey: 'DEFAULT_SECRET' // needed if you don't have aws credentials at all in env }) ``` ### Using with serverless-offline plugin When using this plugin with serverless-offline, it is difficult to use above syntax since the code should use DynamoDB Local for development, and use DynamoDB Online after provisioning in AWS. Therefore we suggest you to use [serverless-dynamodb-client](https://github.com/99xt/serverless-dynamodb-client) plugin in your code. The `serverless dynamodb start` command can be triggered automatically when using `serverless-offline` plugin. Please note that you still need to install DynamoDB Local first. Add both plugins to your `serverless.yml` file: ```yaml plugins: - serverless-dynamodb-local - serverless-offline ``` Make sure that `serverless-dynamodb-local` is above `serverless-offline` so it will be loaded earlier. Now your local DynamoDB database will be automatically started before running `serverless offline`. ### Using with serverless-offline and serverless-webpack plugin Run `serverless offline start`. In comparison with `serverless offline`, the `start` command will fire an `init` and a `end` lifecycle hook which is needed for serverless-offline and serverless-dynamodb-local to switch off both ressources. Add plugins to your `serverless.yml` file: ```yaml plugins: - serverless-webpack - serverless-dynamodb-local - serverless-offline #serverless-offline needs to be last in the list ``` ## Reference Project * [serverless-react-boilerplate](https://github.com/99xt/serverless-react-boilerplate) ## Links * [Dynamodb local documentation](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html) * [Contact Us](mailto:ashanf@99x.lk) * [NPM Registry](https://www.npmjs.com/package/serverless-dynamodb-local) ## License [MIT](LICENSE)
Markdown
UTF-8
3,043
2.828125
3
[]
no_license
# Characters.CharProps Property (Visio) Sets a character property of a **Characters** object to a new value. Write-only. ## Syntax _expression_ . **CharProps**( **_CellIndex_** ) _expression_ An expression that returns a **Characters** object. ### Parameters |**Name**|**Required/Optional**|**Data Type**|**Description**| |:-----|:-----|:-----|:-----| | _CellIndex_|Required| **Integer**|The index of the cell in the Character section to set. See Remarks for possible values.| ### Return Value Integer ## Remarks Depending on the extent of the text range and the format, setting the **CharProps** property may cause rows to be added or removed from a shape's Character ShapeSheet section. The **CharProps** property is a write-only property. To retrieve formatting properties of a **Characters** object, use the **CharPropsRow** property. The values of the CellIndex argument correspond to cells in the Character section of the ShapeSheet window, and the values of the **CharProps** property correspond to the values that can be entered in those cells. Constants for CellIndex and for the **CharProps** property value are declared in the Visio type library in **VisCellIndices** . |** CellIndex**|** Value**|** intExpression**|** Value**| |:-----|:-----|:-----|:-----| | **visCharacterFont**| 0| An integer that represents an index into the **Fonts** collection installed on a system. Zero (0) represents the default font.| N/A| | **visCharacterColor**| 1| An integer from 0 to 23 that corresponds to a color in the current color palette.| N/A| | **visCharacterStyle**| 2| **visBold** **visItalic** **visUnderLine** **visSmallCaps**| &amp;H1 &amp;H2 &amp;H4 &amp;H8| | **visCharacterCase**| 3| **visCaseNormal** **visCaseAllCaps** **visCaseInitialCaps**| 0 1 2| | **visCharacterPos**| 4| **visPosNormal** **visPosSuper** **visPosSub**| 0 1 2| | **visCharacterSize**| 7| An integer that represents point size.| N/A| | **visCharacterColorTrans**|17|An integer from 0 to 100 that corresponds to the degree of transparency of the text color, as a percentage.|N/A| | **visCharacterDblUnderline**|8| **Boolean**|N/A| | **visCharacterFontScale**|5|An integer from 0 to 655 that represents the width of the text font, as a percentage, relative to the default (100%). |N/A| | **visCharacterLangID**|57|A **Long** that represents the language the text is in. The language ID (LANGID) for a character is a 16-bit value defined by Windows, consisting of a primary language ID and a secondary language ID. To determine the value for particular languages, see the Platform SDK documentation on MSDN.|N/A| | **visCharacterLetterspace**|16|An integer that represents additional space between adjacent letters, in points.|N/A| | **visCharacterOverline**|9| **Boolean**|N/A| | **visCharacterStrikethru**|10| **Boolean**|N/A| If your Visual Studio solution includes the **Microsoft.Office.Interop.Visio** reference, this property maps to the following types: - **Microsoft.Office.Interop.Visio.IVCharacters.set_CharProps**
Markdown
UTF-8
794
2.890625
3
[]
no_license
# send_email_or_text Send an e-mail or text message from Python Use this function to send an e-mail or text from Python. You must fill in: EMAIL_LIST - a list of recipients EMAIL_SENDER - address of email sending message from EMAIL_PASSWORD - the password for the sender address SMTP_SERVER - currently configured for gmail, check your email address provider To send a text message simply enter a string as a recipient with the phone number followed by @provider.com where provider.com is from the list below based on the cell service provider of the recipient. AT&T: number@txt.att.net T-Mobile: number@tmomail.net Verizon: number@vtext.com Sprint: number@messaging.sprintpcs.com or number@pm.sprint.com Virgin Mobile: number@vmobl.com For example to send a text to someone with the number 123-456-7890 who uses Verizon, enter the address as "1234567890@vtext.com".
JavaScript
UTF-8
858
2.875
3
[]
no_license
const express = require('express') const app = express() const port = process.env.PORT || 3000 const articals = [{title: 'artical1'}, {title: 'artical2'}, {title: 'artical3'}] // 响应静态文件请求,通过express.static将文件注册到适当地位置。 app.use( '/css/bootstrap.css', express.static('node_modules/bootstrap/dist/css/bootstrap.css') ) // 可以用res.format 通过 请求头的Accept来判断用哪种返回模式。 // res.render 指定渲染模板 和传入数据来指定ejs模板 app.get('/articals', (req, res) => { res.format({ 'text/html': () => { res.render('articals.ejs', {articals: articals}) }, 'application/json': () => { res.send(articals) } }) }) app.listen(port, () => { console.log(`Express web app available at localhost: ${port}`) })
C#
UTF-8
5,075
2.75
3
[ "MIT" ]
permissive
/* Name: Tabs.cs Purpose: Contains the Page Object Model for the tabs page on www.demoqa.com. Author: Matthew Comeaux. Github: https://www.github.com/matt-comeaux Linkedin: https://www.linkedin.com/in/matthew-comeaux Created On: 5/3/2021 First Uploaded To Github On: 5/4/2021 MIT License Copyright (c) [2021] [Matthew H. Comeaux] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; using Xunit; namespace AutomatedUITest_DemoQA.Page_Object_Models.Widgets { class TabsPage { private readonly IWebDriver Driver; private readonly string url = "https://demoqa.com/tabs"; private readonly string mainHeader = "Tabs"; //Use whenever WebDriverWait is needed. private WebDriverWait Wait() { return new WebDriverWait(Driver, TimeSpan.FromSeconds(5)); } //Create instance of POM. public TabsPage(IWebDriver driver) { this.Driver = driver; } //Load page. public void LoadPage() { Driver.Navigate().GoToUrl(url); EnsurePageLoaded(); } //Validate that the correct page loaded. public void EnsurePageLoaded() { bool isLoaded = (Driver.Url == url) && (Driver.FindElement(By.ClassName("main-header")).Text == mainHeader); if (!isLoaded) { throw new Exception($"The requested page did not load correctly. The page url is: '{url}' The page source is: \r\n '{Driver.PageSource}'"); } } public void Display_WhatTab() { //Click different tab as the 'what' tab is open on load. Driver.FindElement(By.Id("demo-tab-origin")).Click(); //Click 'what' tab and wait for text to appear. Driver.FindElement(By.Id("demo-tab-what")).Click(); Wait().Until((d) => Driver.FindElement(By.XPath("//*[@id='demo-tabpane-what']/p")).Text); //Validate text to determine if correct tab opened. Only testing first sentence due to text length. var firstSentence = Driver.FindElement(By.XPath("//*[@id='demo-tabpane-what']/p")).Text.Remove(74); var expectedText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."; Assert.True(firstSentence == expectedText, "The 'What' tab did not display its text properly"); } public void Display_OriginTab() { //Click tab and wait for text to appear. Driver.FindElement(By.Id("demo-tab-origin")).Click(); Wait().Until((d) => Driver.FindElement(By.XPath("//*[@Class='tab-content']/div[2]/p[1]")).Text); //Validate text to determine if correct tab opened. Only testing first sentence due to text length. var firstSentence = Driver.FindElement(By.XPath("//*[@Class='tab-content']/div[2]/p[1]")).Text.Remove(66); var expectedText = "Contrary to popular belief, Lorem Ipsum is not simply random text."; Assert.True(firstSentence == expectedText, "The 'Origin' tab did not display its text properly"); } public void Display_UseTab() { //Click tab and wait for text to appear. Driver.FindElement(By.Id("demo-tab-use")).Click(); Wait().Until((d) => Driver.FindElement(By.XPath("//*[@Class='tab-content']/div[3]/p")).Text); //Validate text to determine if correct tab opened. Only testing first sentence due to text length. var firstSentence = Driver.FindElement(By.XPath("//*[@Class='tab-content']/div[3]/p")).Text.Remove(124); var expectedText = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout."; Assert.True(firstSentence == expectedText, "The 'Use' tab did not display its text properly"); } } }
Java
UTF-8
11,263
1.984375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package propertyViewer; import Database.areaManager; import Database.connectionDB; import Database.landlord; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import com.jfoenix.controls.JFXDatePicker; import com.jfoenix.controls.JFXTextField; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import javafx.util.StringConverter; /** * FXML Controller class * * @author muzab */ public class addingPropertyController implements Initializable { public connectionDB connectSQL; private Connection connected; public ObservableList<landlord> landlordList = FXCollections.<landlord>observableArrayList(); @FXML private JFXDatePicker ContractEndPicker; @FXML private JFXTextField FlatNoTxt; @FXML private JFXTextField DoorNoTxt; @FXML private JFXTextField FirstLineTxt; @FXML private JFXTextField TownTxt; @FXML private JFXTextField BoroughTxt; @FXML private JFXTextField RateTxt; @FXML private JFXDatePicker ContractPicker; @FXML private JFXComboBox<landlord> landlordPicker; @FXML private AnchorPane propertyList; @FXML private JFXTextField rentTxt; @FXML private JFXButton addpropBtn; @FXML private JFXTextField postCodeTxt; @FXML private JFXComboBox<areaManager> areaManagerPicker; public ObservableList<areaManager> areaManagerList = FXCollections.<areaManager>observableArrayList(); @Override public void initialize(URL url, ResourceBundle rb) { // TODO connectSQL = new Database.connectionDB(); RateTxt.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { //when focus lost if (RateTxt.getText().matches("[a-z]")) { //when it not matches the pattern (1.0 - 6.0) //set the textField empty RateTxt.setText(""); } } }); RateTxt.focusedProperty().addListener((arg0, oldValue, newValue) -> { if (!newValue) { // when focus lost if (!RateTxt.getText().matches("[0-9]+(?:\\.[0-9]{0,2})?")) { // when it not matches the pattern (1.0 - 6.0) // set the textField empty RateTxt.setText(""); } } }); RateTxt.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { //when focus lost if (RateTxt.getText().matches("[a-z]")) { //when it not matches the pattern (1.0 - 6.0) //set the textField empty RateTxt.setText(""); } } }); rentTxt.focusedProperty().addListener((arg0, oldValue, newValue) -> { if (!newValue) { // when focus lost if (!rentTxt.getText().matches("[0-9]+(?:\\.[0-9]{0,2})?")) { // when it not matches the pattern (1.0 - 6.0) // set the textField empty rentTxt.setText(""); } } }); rentTxt.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { //when focus lost if (rentTxt.getText().matches("[a-z]")) { //when it not matches the pattern (1.0 - 6.0) //set the textField empty rentTxt.setText(""); } } }); landlord l = new landlord("1", "2", "3", "4"); try { populateLandlords(); populateAreaManager(); } catch (SQLException ex) { Logger.getLogger(addingPropertyController.class.getName()).log(Level.SEVERE, null, ex); } ContractPicker.setConverter(new StringConverter<LocalDate>() { private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); @Override public String toString(LocalDate localDate) { if (localDate == null) { return ""; } return dateTimeFormatter.format(localDate); } @Override public LocalDate fromString(String dateString) { if (dateString == null || dateString.trim().isEmpty()) { return null; } return LocalDate.parse(dateString, dateTimeFormatter); } }); ContractEndPicker.setConverter(new StringConverter<LocalDate>() { private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); @Override public String toString(LocalDate localDate) { if (localDate == null) { return ""; } return dateTimeFormatter.format(localDate); } @Override public LocalDate fromString(String dateString) { if (dateString == null || dateString.trim().isEmpty()) { return null; } return LocalDate.parse(dateString, dateTimeFormatter); } }); } @FXML public void addNewProperty() { Stage stage = (Stage) addpropBtn.getScene().getWindow(); connected = connectSQL.returnConnection(); try { String FlatNo = FlatNoTxt.getText(); String DoorNo = DoorNoTxt.getText(); String FirstLine = FirstLineTxt.getText(); String Town = TownTxt.getText(); String Borough = BoroughTxt.getText(); String ContractStarted = ContractPicker.getValue().toString(); String RentDate=String.valueOf(ContractPicker.getValue().getDayOfMonth()); String ContractEnded = ContractEndPicker.getValue().toString(); String rate = RateTxt.getText(); String rentCost = rentTxt.getText(); String PostCode = postCodeTxt.getText(); String areaManagerID=areaManagerPicker.getValue().getAreaManagerID(); landlord nu = landlordPicker.getValue(); java.sql.Statement stmt = connected.createStatement(); String Sqlite = "INSERT INTO property (FlatNo,DoorNo,FirstLine,Town,Borough,ContractStarted,ContractEnded,Rate,Landlord,Cost,PostCode,AreaManager,DayOfMonth) Values ('" + FlatNo + "','" + DoorNo + "','" + FirstLine + "','" + Town + "','" + Borough + "','" + ContractStarted + "','" + ContractEnded + "','" + rate + "','" + nu.getLandlordID() + "','" + rentCost + "','" + PostCode + "','"+areaManagerID+"','"+RentDate+"')"; stmt.executeUpdate(Sqlite); Sqlite = "SELECT PropertyID FROM property WHERE FlatNo='" + FlatNo + "' AND FirstLine='" + FirstLine + "' OR DoorNo='" + DoorNo + "' AND FirstLine='" + FirstLine + "'"; stmt = connected.createStatement(); ResultSet rs = stmt.executeQuery(Sqlite); rs.next(); Sqlite = "INSERT INTO utilities \n" + "(`PropertyID`,`CTaxBorough`,`CTaxAccntNo`,`CTaxCost`,`EnegComp`,`EnegAcntNo`,`EnegCost`,`GasComp`,`GasAcntNo`,`GasCost`,`WaterComp`,`WaterAcntNo`,`WaterCost`)\n" + "VALUES('" + rs.getString("PropertyID") + "','awaiting','awaiting',0.0,'awaiting','awaiting',0.0,'awaiting','awaiting',0.0,'awaiting','awaiting',0.0);"; stmt.executeUpdate(Sqlite); stage.close(); } catch (SQLException ex) { Logger.getLogger(addingPropertyController.class.getName()).log(Level.SEVERE, null, ex); } stage.close(); } @FXML public void addNewLandlord() throws IOException { addingLandlord addingLandlord = new addingLandlord(); Stage primaryStage = new Stage(); addingLandlord.start(primaryStage); primaryStage.setOnHidden(e -> { try { populateLandlords(); } catch (SQLException ex) { Logger.getLogger(addingPropertyController.class.getName()).log(Level.SEVERE, null, ex); } }); } public void populateLandlords() throws SQLException { landlordList.clear(); connected = connectSQL.returnConnection(); String Sqlite = "SELECT * FROM landlord"; ResultSet rs; java.sql.Statement st = connected.createStatement(); rs = st.executeQuery(Sqlite); while (rs.next()) { landlord l = new landlord(rs.getString("LandlordID"), rs.getString("landlordName"), rs.getString("bankAccountNo"), rs.getString("sortCode")); landlordList.add(l); } landlordPicker.setItems(landlordList); landlordPicker.setConverter(new StringConverter<landlord>() { @Override public String toString(landlord object) { return object.getLandlordName(); } @Override public landlord fromString(String string) { return null; } }); } public void populateAreaManager() throws SQLException { areaManagerList.clear(); connected = connectSQL.returnConnection(); String Sqlite = "SELECT * FROM areamanager"; ResultSet rs; java.sql.Statement st = connected.createStatement(); rs = st.executeQuery(Sqlite); while (rs.next()) { areaManager l = new areaManager(rs.getString("idAreaManager"), rs.getString("FirstName"), rs.getString("FirstName")); areaManagerList.add(l); } areaManagerPicker.setItems(areaManagerList); areaManagerPicker.setConverter(new StringConverter<areaManager>() { @Override public String toString(areaManager object) { return object.getFirstName() + " " + object.getLastName(); } @Override public areaManager fromString(String string) { return null; } }); } }
C#
UTF-8
13,687
2.71875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Text.Json; using System.Text.Json.Serialization; using System.IO; using PopulateDatabaseFromRescueGroupAPI.Services.Interfaces; using PopulateDatabaseFromRescueGroupAPI.Models; namespace PopulateDatabaseFromRescueGroupAPI.Services { public class RescueGroupJsonFileDAO { private string jsonFilePath = @"C:\Users\Student\final-capstone-net-14-orange-november\dotnet\PopulateDatabaseFromRescueGroupAPI\Services\Data\"; public Dictionary<int, Pet> Pets { get; set; } public Dictionary<int, Picture> Pictures { get; set; } public Dictionary<int, Breed> Breeds { get; set; } public Dictionary<int, Species> Species { get; set; } public Dictionary<int, Agency> Agencies { get; set; } public RescueGroupJsonFileDAO() { Pets = new Dictionary<int, Pet>(); Pictures = new Dictionary<int, Picture>(); Breeds = new Dictionary<int, Breed>(); Species = new Dictionary<int, Species>(); Agencies = new Dictionary<int, Agency>(); for (int i = 0; i <= 2 ; i++) { string jsonString = ""; try { jsonString = File.ReadAllText(jsonFilePath + $"page{i}.json"); } catch (IOException e) { Console.WriteLine("Error reading the file"); Console.WriteLine(e.Message); } ParseJson(jsonString); } } private void ParseJson(string jsonString) { using (JsonDocument document = JsonDocument.Parse(jsonString)) { JsonElement root = document.RootElement; JsonElement dataElement = root.GetProperty("data"); foreach (JsonElement animalElement in dataElement.EnumerateArray()) { ParseAnimal(animalElement); } JsonElement includedArrayElement = root.GetProperty("included"); foreach (JsonElement includedObject in includedArrayElement.EnumerateArray()) { string type = includedObject.GetProperty("type").GetString(); switch (type) { case "pictures": ParsePictures(includedObject); break; case "orgs": ParseOrgs(includedObject); break; case "breeds": ParseBreeds(includedObject); break; case "species": ParseSpecies(includedObject); break; } } } } private void ParseAnimal(JsonElement animalElement) { JsonElement idElement = animalElement.GetProperty("id"); int id = Int32.Parse(idElement.GetString()); if (!Pets.ContainsKey(id)) { JsonElement attributesElement = animalElement.GetProperty("attributes"); Pet pet = ParseAnimalAttributes(attributesElement); pet.PetId = id; Pets.Add(pet.PetId, pet); if (animalElement.TryGetProperty("relationships", out JsonElement relationshipsElement)) { ParseRelationships(relationshipsElement, pet); } } } private Pet ParseAnimalAttributes(JsonElement attributesElement) { Pet pet = new Pet(); if (attributesElement.TryGetProperty("breedPrimaryId", out JsonElement breedPrimaryIdElement)) { pet.BreedId = breedPrimaryIdElement.GetInt32(); } if (attributesElement.TryGetProperty("pictureThumbnailUrl", out JsonElement pictureThumbnailUrlElement)) { pet.ThumbnailUrl = pictureThumbnailUrlElement.GetString(); } if (attributesElement.TryGetProperty("name", out JsonElement nameElement)) { pet.Name = nameElement.GetString(); } if (attributesElement.TryGetProperty("descriptionText", out JsonElement descriptionTextElement)) { pet.DescriptionText = descriptionTextElement.GetString(); } if (attributesElement.TryGetProperty("sex", out JsonElement sexElement)) { pet.Sex = sexElement.GetString(); } if (attributesElement.TryGetProperty("ageGroup", out JsonElement ageGroupElement)) { pet.AgeGroup = ageGroupElement.GetString(); } if (attributesElement.TryGetProperty("ageString", out JsonElement ageStringElement)) { pet.AgeString = ageStringElement.GetString(); } if (attributesElement.TryGetProperty("activityLevel", out JsonElement activityLevelElement)) { pet.ActivityLevel = activityLevelElement.GetString(); } if (attributesElement.TryGetProperty("exerciseNeeds", out JsonElement exerciseNeedsElement)) { pet.ExerciseNeeds = exerciseNeedsElement.GetString(); } if (attributesElement.TryGetProperty("ownerExperience", out JsonElement ownerExperienceElement)) { pet.OwnerExperience = ownerExperienceElement.GetString(); } if (attributesElement.TryGetProperty("sizeGroup", out JsonElement sizeGroupElement)) { pet.SizeGroup = sizeGroupElement.GetString(); } if (attributesElement.TryGetProperty("vocalLevel", out JsonElement vocalLevelElement)) { pet.VocalLevel = vocalLevelElement.GetString(); } return pet; } private void ParseRelationships(JsonElement relationshipsElement, Pet pet) { if (relationshipsElement.TryGetProperty("pictures", out JsonElement picturesElement)) { picturesElement = picturesElement.GetProperty("data"); bool firstPicture = true; foreach (JsonElement pictureElement in picturesElement.EnumerateArray()) { Picture picture = new Picture(); picture.PictureId = Int32.Parse(pictureElement.GetProperty("id").GetString()); picture.PetId = pet.PetId; if (firstPicture) { Pets[pet.PetId].PrimaryImageId = picture.PictureId; } firstPicture = false; if (!Pictures.ContainsKey(picture.PictureId)) { Pictures.Add(picture.PictureId, picture); } } } if (relationshipsElement.TryGetProperty("orgs", out JsonElement orgsElement)) { orgsElement = orgsElement.GetProperty("data"); bool firstOrg = true; foreach (JsonElement orgElement in orgsElement.EnumerateArray()) { Agency agency = new Agency(); agency.AgencyId = Int32.Parse(orgElement.GetProperty("id").GetString()); if (firstOrg) { Pets[pet.PetId].AgencyId = agency.AgencyId; } firstOrg = false; if (!Agencies.ContainsKey(agency.AgencyId)) { Agencies.Add(agency.AgencyId, agency); } } } if (relationshipsElement.TryGetProperty("species", out JsonElement allSpeciesElement)) { allSpeciesElement = allSpeciesElement.GetProperty("data"); foreach (JsonElement speciesElement in allSpeciesElement.EnumerateArray()) { Species species = new Species(); species.SpeciesId = Int32.Parse(speciesElement.GetProperty("id").GetString()); Pets[pet.PetId].SpeciesId = species.SpeciesId; if (!Species.ContainsKey(species.SpeciesId)) { Species.Add(species.SpeciesId, species); } } } if (relationshipsElement.TryGetProperty("breeds", out JsonElement breedsElement)) { breedsElement = breedsElement.GetProperty("data"); foreach (JsonElement breedElement in breedsElement.EnumerateArray()) { Breed breed = new Breed(); breed.BreedId = Int32.Parse(breedElement.GetProperty("id").GetString()); if (!Breeds.ContainsKey(breed.BreedId)) { Breeds.Add(breed.BreedId, breed); } Breeds[breed.BreedId].SpeciesId = pet.SpeciesId; } } } private void ParsePictures(JsonElement pictureElement) { int id = Int32.Parse(pictureElement.GetProperty("id").GetString()); JsonElement attributesElement = pictureElement.GetProperty("attributes"); if (Pictures.ContainsKey(id)) { Pictures[id].Url = attributesElement.GetProperty("original").GetProperty("url").GetString(); } foreach (Pet pet in Pets.Values) { if (pet.PrimaryImageId == id) { pet.PrimaryImageUrl = Pictures[id].Url; } } } private void ParseOrgs(JsonElement orgElement) { int id = Int32.Parse(orgElement.GetProperty("id").GetString()); JsonElement attributesElement = orgElement.GetProperty("attributes"); if (Agencies.ContainsKey(id)) { if (attributesElement.TryGetProperty("name", out JsonElement nameElement)) { Agencies[id].Name = nameElement.GetString(); } if (attributesElement.TryGetProperty("street", out JsonElement streetElement)) { Agencies[id].Street = streetElement.GetString(); } if (attributesElement.TryGetProperty("city", out JsonElement cityElement)) { Agencies[id].City = cityElement.GetString(); } if (attributesElement.TryGetProperty("state", out JsonElement stateElement)) { Agencies[id].State = stateElement.GetString(); } if (attributesElement.TryGetProperty("postalcode", out JsonElement postalcodeElement)) { Agencies[id].PostalCode = postalcodeElement.GetString(); } if (attributesElement.TryGetProperty("email", out JsonElement emailElement)) { Agencies[id].Email = emailElement.GetString(); } if (attributesElement.TryGetProperty("phone", out JsonElement phoneElement)) { Agencies[id].Phone = phoneElement.GetString(); } if (attributesElement.TryGetProperty("lat", out JsonElement latElement)) { Agencies[id].Lat = latElement.GetDouble(); } if (attributesElement.TryGetProperty("lon", out JsonElement lonElement)) { Agencies[id].Lon = lonElement.GetDouble(); } if (attributesElement.TryGetProperty("about", out JsonElement aboutElement)) { Agencies[id].About = aboutElement.GetString(); } if (attributesElement.TryGetProperty("url", out JsonElement urlElement)) { Agencies[id].Url = urlElement.GetString(); } } } private void ParseBreeds(JsonElement breedElement) { int id = Int32.Parse(breedElement.GetProperty("id").GetString()); JsonElement attributesElement = breedElement.GetProperty("attributes"); if (Breeds.ContainsKey(id)) { Breeds[id].Name = attributesElement.GetProperty("name").GetString(); } } private void ParseSpecies(JsonElement speciesElement) { int id = Int32.Parse(speciesElement.GetProperty("id").GetString()); JsonElement attributesElement = speciesElement.GetProperty("attributes"); if (Species.ContainsKey(id)) { Species[id].Name = attributesElement.GetProperty("singular").GetString(); Species[id].Plural = attributesElement.GetProperty("plural").GetString(); Species[id].YoungSingular = attributesElement.GetProperty("youngSingular").GetString(); Species[id].YoungPlural = attributesElement.GetProperty("youngPlural").GetString(); } } } }
Java
UTF-8
4,617
2.625
3
[ "MIT" ]
permissive
package org.habv.automation.commons; import org.habv.automation.pageobjects.AddUserPage; import org.habv.automation.pageobjects.AuthUserPage; import org.habv.automation.pageobjects.ChangePasswordPage; import org.habv.automation.pageobjects.ChangeUserPage; import org.habv.automation.pageobjects.DashBoardPage; import org.habv.automation.pageobjects.DeleteUserPage; import org.habv.automation.pageobjects.LoginPage; import org.testng.Assert; public class UserCommons { public static void createUser(LoginPage loginPage, String userName, String password, String newUser, String newPassword) { // llenar el formulario de login DashBoardPage dashBoardPage = LoginCommons.login(loginPage, userName, password); Assert.assertTrue(dashBoardPage.isUsersLinkDisplayed(), "NO se mostro el link de Users"); AuthUserPage authUserPage = dashBoardPage.usersLinkClick(); Assert.assertTrue(authUserPage.isTitleDisplayed(), "NO se mostro el titulo"); Assert.assertTrue(authUserPage.isAddUserLinkDisplayed(), "NO se mostro el boton de Add Users"); AddUserPage addUserPage = authUserPage.addUserClick(); Assert.assertTrue(addUserPage.isTitleDisplayed(), "No se mostro el titulo"); addUserPage.fillUserName(newUser); addUserPage.fillPasswod1(newPassword); addUserPage.fillPasswod2(newPassword); ChangeUserPage changeUserPage = addUserPage.submit(); Assert.assertTrue(changeUserPage.isTitleDisplayed(), "No se mostro el titulo"); changeUserPage.checkStaff(); changeUserPage.checkSuperuser(); authUserPage = changeUserPage.submit(); Assert.assertTrue(authUserPage.isUserLinkDisplayed(newUser), "No se mostro el nuevo usuario"); LoginCommons.logout(authUserPage); } public static void changePassword(LoginPage loginPage, String userName, String password, String newUser, String changePassword) { DashBoardPage dashBoardPage = LoginCommons.login(loginPage, userName, password); Assert.assertTrue(dashBoardPage.isUsersLinkDisplayed(), "NO se mostro el link de Users"); AuthUserPage authUserPage = dashBoardPage.usersLinkClick(); Assert.assertTrue(authUserPage.isTitleDisplayed(), "NO se mostro el titulo"); Assert.assertTrue(authUserPage.isUserLinkDisplayed(newUser), "NO se mostro el link del usuario"); ChangeUserPage changeUserPage = authUserPage.userLinkClick(newUser); Assert.assertTrue(changeUserPage.isChangePasswordLinkDisplayed(), "No se mostro el link para cambiar la clave"); ChangePasswordPage changePasswordPage = changeUserPage.changePasswordClick(); Assert.assertTrue(changePasswordPage.isPassword1Displayed(), "No se mostro el campo Password1"); Assert.assertTrue(changePasswordPage.isPassword2Displayed(), "No se mostro el campo Password2"); changePasswordPage.fillPassword1(changePassword); changePasswordPage.fillPassword2(changePassword); changeUserPage = changePasswordPage.submit(); Assert.assertTrue(changeUserPage.isTitleDisplayed(), "No se mostro el titulo"); LoginCommons.logout(changeUserPage); } public static void checkUser(LoginPage loginPage, String newUser, String changePassword) { DashBoardPage dashBoardPage = LoginCommons.login(loginPage, newUser, changePassword); Assert.assertTrue(dashBoardPage.isUserNameDisplayed(newUser), "NO se mostro el nombre de usuario"); LoginCommons.logout(dashBoardPage); } public static void deleteUser(LoginPage loginPage, String userName, String password, String newUser) { // llenar el formulario de login DashBoardPage dashBoardPage = LoginCommons.login(loginPage, userName, password); Assert.assertTrue(dashBoardPage.isUsersLinkDisplayed(), "NO se mostro el link de Users"); AuthUserPage authUserPage = dashBoardPage.usersLinkClick(); Assert.assertTrue(authUserPage.isTitleDisplayed(), "NO se mostro el titulo"); Assert.assertTrue(authUserPage.isUserLinkDisplayed(newUser), "NO se mostro el link del usuario"); ChangeUserPage changeUserPage = authUserPage.userLinkClick(newUser); Assert.assertTrue(changeUserPage.isDeleteLinkDisplayed(), "No se mostro el link para cambiar la clave"); DeleteUserPage deleteUserPage = changeUserPage.deleteLinkClick(); authUserPage = deleteUserPage.submit(); Assert.assertFalse(authUserPage.isUserLinkDisplayed(newUser), "SI se mostro el link del usuario"); LoginCommons.logout(authUserPage); } }
C++
UTF-8
5,620
3.4375
3
[]
no_license
// -------------------------------- Customer.cpp --------------------------------- // // Author Name: Tim Lawton // // Creation Date: 07/16/2019 // // Date of Last Modification: 8/19/2019 // // Description: a Customer Class implementation file. // This file is the interface for the Customer class. Each object of this class // represents a current customer of the business. The objects are hashed into the // hash table. Each object stores it's own transaction history in a vector, which // is updated as transactions are processed. // // Customers are indexed in a hash table in the class CustomerHash // ----------------------------------------------------------------------------- #include "Customer.h" #include "Transaction.h"//check #include <vector> using namespace std; // ------------------------------Customer------------------------------- // Description: this a default constructor for a Customer // preconditions: *this is a totally un-initialized Customer // postconditions: The fields of *this will be initialized, and the // Customer will contain default values for its data // --------------------------------------------------------------------- Customer::Customer() { customerID = 0; firstName = ""; lastName = ""; } // -----------------~Customer()------------------ // Description: this is the deconstructor. // preconditions: None. // postconditions: a Customer deconstructed. // -------------------------------------------------- Customer::~Customer() {} // ------------------------------setCustomerInfo------------------------------- // Description: this a setter for a Customer //preconditions: a string with valid data format is passed in. //postconditions: a new instance of customer is created and returned. // --------------------------------------------------------------------- void Customer::setCustomerInfo(istream &inFile) { inFile >> customerID; //sets customer ID if(inFile.eof()) { return; //end of file } inFile.get(); inFile >> lastName; //sets last name inFile.get(); inFile >> firstName; //sets first name } // ------------------------------getID------------------------------- // Description: returns calling object's customerID. //preconditions: must be called on a valid instance of customer. //postconditions: instance values remain unchanged. // --------------------------------------------------------------------- int Customer::getID() const { return customerID; } // ------------------------------getFirstName------------------------------- // Description: returns calling objects firstName. //preconditions: must be called on a valid instance of customer. //postconditions: instance values remain unchanged. // --------------------------------------------------------------------- string Customer::getFirstName() const { return firstName; } // ------------------------------getLastName------------------------------- // Description: returns calling objects lastName. //preconditions: must be called on a valid instance of customer. //postconditions: instance values remain unchanged. // --------------------------------------------------------------------- string Customer::getLastName() const { return lastName; } // ------------------------------printHistory------------------------------- // Description: prints the customers transaction history. //preconditions: None //postconditions: prints history vector // --------------------------------------------------------------------- void Customer::printHistory() const { cout << "Customer ID: " << customerID << " Last Name: " << lastName << " First Name: " << firstName << endl; if(transHistory.size() > 0) { for (unsigned int i = 0; i < transHistory.size(); i++) { transHistory[i].display(); } cout << "End of History" << endl; } else { cout << "No Customer History" << endl; } } // ------------------------------StoreTransaction------------------------------- // Description: stores the passed Transaction param in this objects history //by inserting it into the vector //preconditions: proper param passed //postconditions: the objects tranHistory contains the param Transaction // --------------------------------------------------------------------- void Customer::storeTransaction(Transaction &trans) { transHistory.push_back(trans); } // ------------------------------addToCustomerInventory------------------------------- // Description: Adds movie to customer's current inventory. //preconditions: the movie being added //postconditions: customer inventory vector updated // --------------------------------------------------------------------- void Customer::addToCustomerInventory(Movie *theMovie) { currentCheckOut.push_back(*theMovie); } // ------------------------------removeFromCustomerInventory------------------------------- // Description: removes movie from customer's current inventory. //preconditions: the movie being removed //postconditions: customer inventory vector updated // --------------------------------------------------------------------- bool Customer::removeFromCustomerInventory(Movie *theMovie) { if(currentCheckOut.size() > 0) { for (unsigned int i = 0; i < currentCheckOut.size(); i++) { if(currentCheckOut[i] == *theMovie) { currentCheckOut.erase(currentCheckOut.begin() + i); return true; } } } cout << "Customer Does not have the Item" << endl; return false; }
Shell
UTF-8
632
3.734375
4
[ "MIT" ]
permissive
if [ -z "$1" ]; then echo "Usage:" echo " npm run link -- <relative_path_to_project>" fi PROJECT_PATH="$1" PACKAGE_PATH="$PWD" BUILT_PACKAGE_PATH="$PACKAGE_PATH/pkg" PROJECT_REACT_PATH="../$PROJECT_PATH/node_modules/react" if [ ! -d $PROJECT_PATH ]; then echo "Looks like no project exists under `$PROJECT_PATH`. Aborting..." fi echo "Linking package ${PACKAGE_PATH} to project ${PROJECT_PATH}" echo "> Building package" npm run build echo "> Linking package in the project" cd $PROJECT_PATH npm link $BUILT_PACKAGE_PATH echo "> Linking package react back to project" cd $BUILT_PACKAGE_PATH npm link $PROJECT_REACT_PATH
Python
UTF-8
1,750
3.1875
3
[]
no_license
''' ID: cruzan1 LANG: PYTHON3 TASK: marathon ''' def inPut(): f = open('marathon.in', 'r') numCheckpoints = int(f.readline().strip()) overalLst = [] for i in range(numCheckpoints): coordinateLst = [] coordinatePair = f.readline().strip().split() coordinateLst.append(int(coordinatePair[0])) coordinateLst.append(int(coordinatePair[1])) overalLst.append(coordinateLst) return numCheckpoints, overalLst def calculate(numCheckpoints, overalLst): if numCheckpoints == 3: return abs(overalLst[0][0] - overalLst[2][0]) + abs(overalLst[0][1] - overalLst[2][1]) overallMax = 0 currentMax = 0 currentMaxMinusStarting = 0 currentIndex = 0 for i in range(1, numCheckpoints - 1): currentMax = abs(overalLst[i + 1][0] - overalLst[i - 1][0]) + abs(overalLst[i + 1][1] - overalLst[i - 1][1]) currentMaxMinusStarting = abs(overalLst[i][0] - overalLst[i + 1][0]) + abs(overalLst[i][1] - overalLst[i + 1][1]) + abs(overalLst[i][0] - overalLst[i - 1][0]) + abs(overalLst[i][1] - overalLst[i - 1][1]) currentMax = currentMaxMinusStarting - currentMax print("i: " + str(i)) print("currentMax: " + str(currentMax)) if currentMax > overallMax: overallMax = currentMax currentIndex = i print(currentIndex) tempLst = overalLst currentRemove = overalLst[currentIndex] tempLst.pop(currentIndex) counter = checkNewLst(tempLst) overalLst.insert(currentIndex, currentRemove) return counter def checkNewLst(tempLst): counter = 0 for j in range(len(tempLst) - 1): counter += abs(tempLst[j][0] - tempLst[j + 1][0]) + abs(tempLst[j][1] - tempLst[j + 1][1]) return counter out = open('marathon.out', 'w') out.write(str(calculate(inPut()[0], inPut()[1])) + '\n') out.close()
Markdown
UTF-8
2,580
3.28125
3
[]
no_license
# ORF-Finder This is a Python programming project completed as part of my Bioinformatics MSc at the University of Manchester. The command line tool searches an input genetic sequence for Open Reading Frames (potential protein-coding sequences). ## Motivation DNA sequencing outputs a list of As, Ts, Cs and Gs that make up the genetic code. To predict what proteins are encoded by a given sequence we need to find the Open Reading Frames. In eukaryotic organisms (i.e. not bacteria) these match the pattern: ATG([ATGC]{3})+(TAA|TGA|TAG) A universal start sequence ATG, then one or more codons (triplets of bases), followed by a termination signal. Each codon is matched to a specific amino acid, the subunits that make up proteins - by mapping the codons in the located ORF to their corresponding amino acids we can calculate the encoded protein sequence. ## Assignment A single Python script to detect ORFs and predict protein sequences as the first part of a pipeline of scripts to predict proteins for virtual mass spectrometry. ## Input: - DNA sequence(s) in .fasta format. Tested with C. elegans genome. ## Output: - All protein sequences potentially encoded by the input DNA, written to standard output or .fasta file. ## Documentation: orf_finder.py reads in sequence files in standard .fasta format, splits files into individual sequences and locates all open reading frames (ORFs) in each sequence. Multiple .fasta files can be specified, and each file can contain multiple sequences. Each sequence is scanned for ORFs matching the pattern (start codon, x codons, stop codon). Default behaviour is to only return ORFs between 150 and 2500nt in length, from all reading frames, containing no nonstandard bases and with no overlapping ORFs. This behaviour can be overridden using the appropriate optional flags, e.g. -f 123 if only ORFs on the forward strand are of interest. Valid ORFs are assigned a unique identifier and converted to a peptide sequence using the standard genetic code; if nonstandard bases are permitted the resulting unknown codons will be marked 'X'. All output in fasta format is returned to standard output by default; if a filename is specified the output will instead be written to file (e.g. -o output.fasta). Summary information of number of sequences, total number of ORFs, ORFs per reading frame etc. can be written to StdOut by using the -s flag. ## Learning outcomes: - Command line Python using argparse - Practice with regular expressions - Object orientation - practical use of classes
Java
UTF-8
636
3.125
3
[ "MIT" ]
permissive
package bg.uni.sofia.fmi.mjt.dungeon.treasure; import bg.uni.sofia.fmi.mjt.dungeon.actor.Hero; public class HealthPotion implements Treasure { private int healingPoints; public HealthPotion(int healingPoints) { this.healingPoints = healingPoints; } public HealthPotion(HealthPotion other) { this.healingPoints = other.healingPoints; } public int heal() { return this.healingPoints; } @Override public String collect(Hero hero) { hero.takeHealing(healingPoints); return "Health potion found! "+ healingPoints +" health points added to your hero!"; } }
C#
UTF-8
5,194
2.671875
3
[]
no_license
using System; using System.Runtime.InteropServices; namespace JuggleServerCore { /// <summary> /// Rock Crypto Class /// </summary> class RockCrypto { private byte[] _Data = new byte[120]; [DllImport("RockBaseML.dll", EntryPoint = "??0CRockCrypto@RockBase@@QAE@XZ", CallingConvention = CallingConvention.ThisCall)] static extern int RockCrypto_Init(byte[] RVFClass); [DllImport("RockBaseML.dll", EntryPoint = "?SetKey@CRockCrypto@RockBase@@QAEXPBD000@Z", CallingConvention = CallingConvention.ThisCall)] static extern int RockCrypto_SetKey(byte[] RVFClass, byte[] StrmKey, byte[] RcKey, byte[] DesKey, byte[] AesKey); [DllImport("RockBaseML.dll", EntryPoint = "?Decrypt@CRockCrypto@RockBase@@QAEXPAXH@Z", CallingConvention = CallingConvention.ThisCall)] static extern int RockCrypto_Decrypt(byte[] RVFClass, byte[] Data, int Len); [DllImport("RockBaseML.dll", EntryPoint = "?Encrypt@CRockCrypto@RockBase@@QAEXPAXH@Z", CallingConvention = CallingConvention.ThisCall)] static extern int RockCrypto_Encrypt(byte[] RVFClass, byte[] Data, int Len); public RockCrypto( ) { RockCrypto_Init(_Data); } /// <summary> /// Init Class with a Key /// </summary> /// <param name="StrmKey">The Key of 1st Step (Strm Crypto)</param> /// <param name="RcKey">The Key of 2nd Step (Rc Crypto)</param> /// <param name="DesKey">The Key of 3rd Step (Des Crypto)</param> /// <param name="AesKey">The Key of 4th Step (Aes Crypto)</param> public RockCrypto(byte[] StrmKey, byte[] RcKey, byte[] DesKey, byte[] AesKey) { RockCrypto_Init(_Data); SetKey(StrmKey, RcKey, DesKey, AesKey); } public RockCrypto(RockCrypto Cls) { _Data = Cls._Data; } /// <summary> /// Sets The Default Key of Deco Data /// </summary> public void SetRVFKey() { byte[] MainKey = new byte[] { 0x6A, 0x2C, 0x67, 0xE1, 0x42, 0x34, 0x93, 0xBC, 0x0A, 0x76, 0xC1, 0x0B }; RockCrypto_SetKey(_Data, MainKey, null, null, null); } /// <summary> /// Sets A Custom Key /// </summary> /// <param name="StrmKey">The Key of 1st Step (Strm Crypto)</param> /// <param name="RcKey">The Key of 2nd Step (Rc Crypto)</param> /// <param name="DesKey">The Key of 3rd Step (Des Crypto)</param> /// <param name="AesKey">The Key of 4th Step (Aes Crypto)</param> public void SetKey(byte[] StrmKey, byte[] RcKey, byte[] DesKey, byte[] AesKey) { if (StrmKey == null && RcKey == null && DesKey == null && AesKey == null) throw new Exception("You must set one key at least"); RockCrypto_SetKey(_Data, StrmKey, RcKey, DesKey, AesKey); } /// <summary> /// Decrypts Block of bytes /// </summary> /// <param name="Data">The buffer of Cipher Bytes</param> /// <returns>The buffer of Decrypted Bytes</returns> public byte[] DecryptBlock(byte[] Data) { byte[] Result = new byte[Data.Length]; Buffer.BlockCopy(Data, 0, Result, 0, Result.Length); RockCrypto_Decrypt(_Data, Result, Result.Length); return Result; } /// <summary> /// Decrypts Block of bytes /// </summary> /// <param name="Data">The buffer of Cipher Bytes</param> /// <returns>The buffer of Decrypted Bytes</returns> public byte[] DecryptBlock(byte[] Data, int Offset, int Len) { byte[] Result = new byte[Len]; Buffer.BlockCopy(Data, Offset, Result, 0, Len); RockCrypto_Decrypt(_Data, Result, Result.Length); return Result; } /// <summary> /// Decrypts Block of bytes /// </summary> /// <param name="Data">The buffer of Cipher Bytes</param> /// <returns>The buffer of Decrypted Bytes</returns> public byte[] DecryptBlock(byte[] Data, int Offset, int Len, int CryptLen) { byte[] Result = new byte[Len]; Buffer.BlockCopy(Data, Offset, Result, 0, Len); RockCrypto_Decrypt(_Data, Result, CryptLen); return Result; } /// <summary> /// Encrypts Block of bytes /// </summary> /// <param name="Data">The buffer of Cipher Bytes</param> /// <returns>The buffer of Encrypted Bytes</returns> public byte[] EncryptBlock(byte[] Data) { byte[] Result = new byte[Data.Length]; Buffer.BlockCopy(Data, 0, Result, 0, Result.Length); RockCrypto_Encrypt(_Data, Result, Result.Length); return Result; } public void EncryptBlockInPlace(byte[] Data) { RockCrypto_Encrypt(_Data, Data, Data.Length); } } }
Markdown
UTF-8
789
3.1875
3
[ "MIT" ]
permissive
## MOTIVATION When I develop for the mobile or web frontend, I usually get some RGB values on zepline from our designers, which I need to transform them into the hex code. Sounds like just trivial, right? But it does become painful when you need to do a lot of them. And I feel that the worst part is that I have to copy three times to put in the red, green, and blue values to get a result (https://www.rgbtohex.net/), which does not look right to me! So I decided to build a small tool for myself to make life easier. The nice part about the tool is that it uses regex to try to extract the rgb values from your input. Whether you put 0, 0, 0, or 0 0 0 or rgb(0, 0, 0) or (0, 0, 0), it will always give you the correct hex string. ## USAGE I am hosting this at https://4rgbtohex.com/
C++
UTF-8
714
2.78125
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #include <stack> #include <vector> #include <string> using namespace std; #define print(x) cout << x << endl #define input(x) cin >> x int main() { string s; input(s); stack<int> q; const int n = s.size(); vector<pair<int, int> > ps; for (int i = 0; i < n; i++) { if (s[i] == '(') { q.push(i + 1); } else { int pre = q.top(); q.pop(); ps.push_back({ pre, i + 1 }); } } sort(ps.begin(), ps.end()); for (auto p: ps) { print(p.first << ' ' << p.second); } return 0; }
Ruby
UTF-8
1,357
2.640625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby unless system('git --version > /dev/null') STDERR.puts 'Git does not appear to be installed.' exit 2 end unless system('git rev-parse --is-inside-work-tree > /dev/null') STDERR.puts 'The current working directory must be a Git repo.' exit 3 end $LOAD_PATH << File.join(File.dirname(__FILE__), '..', 'lib') require 'code_owners' require 'code_owners/version' require 'optparse' options = {} OptionParser.new do |opts| opts.banner = "usage: code_owners [options]" opts.on('-u', '--unowned', TrueClass, 'Display unowned files only') do |u| options[:unowned] = u end opts.on('-e', '--error-unowned', TrueClass, 'Exit with error status if any files are unowned') do |e| options[:error_unowned] = e end opts.on('-v', '--version', TrueClass, 'Display the version of the gem') do |_| puts "Version: #{CodeOwners::VERSION}" exit 0 end end.parse! unowned_error = false CodeOwners.ownerships.each do |ownership_status| owner_info = ownership_status[:owner].dup if owner_info != CodeOwners::NO_OWNER next if options[:unowned] else unowned_error ||= options[:error_unowned] end owner_info += " per line #{ownership_status[:line]}, #{ownership_status[:pattern]}" if owner_info != "UNOWNED" puts "#{ownership_status[:file].ljust(100,' ')} #{owner_info}" end exit(unowned_error && 1 || 0)
Java
UTF-8
6,418
1.867188
2
[]
no_license
package com.imall.iportal.core.weshop.service.impl; import com.imall.commons.base.interceptor.BusinessException; import com.imall.commons.base.service.impl.AbstractBaseService; import com.imall.commons.dicts.BoolCodeEnum; import com.imall.commons.dicts.FansSourceCodeEnum; import com.imall.iportal.core.main.commons.ServiceManager; import com.imall.iportal.core.shop.commons.ResGlobalExt; import com.imall.iportal.core.shop.entity.Member; import com.imall.iportal.core.shop.entity.WeShop; import com.imall.iportal.core.weshop.entity.Fans; import com.imall.iportal.core.weshop.repository.FansRepository; import com.imall.iportal.core.weshop.service.FansService; import com.imall.iportal.core.weshop.vo.FansPageVo; import com.imall.iportal.core.weshop.vo.FansRemarkUpdateVo; import com.imall.iportal.core.weshop.vo.FansSearchParam; import com.imall.iportal.core.weshop.vo.FansTotalVo; import com.imall.iportal.dicts.UserSexCodeEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; /** * (服务层实现) * * @author by imall core generator * @version 1.0.0 */ @Service @Transactional(readOnly = true) public class FansServiceImpl extends AbstractBaseService<Fans, Long> implements FansService { private Logger logger = LoggerFactory.getLogger(this.getClass()); @SuppressWarnings("unused") private FansRepository getFansRepository() { return (FansRepository) baseRepository; } @Override public List<Fans> findByOpenId(String openId) { return getFansRepository().findByOpenIdOrderByCreateDateAsc(openId); } @Override public Fans findByOpenIdAndShopId(String openId, Long shopId) { return getFansRepository().findByOpenIdAndShopId(openId, shopId); } @Override public Page<FansPageVo> query(Pageable pageable, FansSearchParam fansSearchParam) { Page<Fans> fansPage = getFansRepository().query(pageable, fansSearchParam); List<FansPageVo> fansPageVoList = new ArrayList<>(); for (Fans fans : fansPage.getContent()) { fansPageVoList.add(buildFansPageVo(fans)); } return new PageImpl<>(fansPageVoList, pageable, fansPage.getTotalElements()); } @Override @Transactional public Long updateRemark(FansRemarkUpdateVo fansRemarkUpdateVo) { Fans fans = this.findOne(fansRemarkUpdateVo.getId()); if (fans == null || !fans.getShopId().equals(fansRemarkUpdateVo.getShopId())) { String message = ServiceManager.sysExceptionCodeService.getMessageByCode(ResGlobalExt.COMMON_OBJECT_NO_FOUND); throw new BusinessException(ResGlobalExt.COMMON_OBJECT_NO_FOUND, String.format(message, new Object[]{"粉丝"})); } fans.setRemark(fansRemarkUpdateVo.getRemark()); return this.update(fans).getId(); } @Override public FansTotalVo countFansTotal(Long shopId) { Long isMemberFansTotal = 0L; Long isNotMemberFansTotal = 0L; WeShop weShop = ServiceManager.weShopService.findByShopId(shopId); if (weShop == null) { FansTotalVo fansTotalVo = new FansTotalVo(); //粉丝总数 fansTotalVo.setFansTotalCount(0L); //会员粉丝数 fansTotalVo.setFansIsMemberTotalCount(isMemberFansTotal); //非会员粉丝数 fansTotalVo.setFansIsNotMemberTotalCount(isNotMemberFansTotal); return fansTotalVo; } List<Fans> fansList = getFansRepository().listFansByShopId(shopId); for (Fans fans : fansList) { if (BoolCodeEnum.YES == BoolCodeEnum.fromCode(fans.getIsMember())) { isMemberFansTotal += 1; } else { isNotMemberFansTotal += 1; } } FansTotalVo fansTotalVo = new FansTotalVo(); //粉丝总数 fansTotalVo.setFansTotalCount((long) fansList.size()); //会员粉丝数 fansTotalVo.setFansIsMemberTotalCount(isMemberFansTotal); //非会员粉丝数 fansTotalVo.setFansIsNotMemberTotalCount(isNotMemberFansTotal); return fansTotalVo; } @Override public List<Fans> findByMobileAndIsMember(String mobile,String isMember) { return getFansRepository().findByMobileAndIsMember(mobile,isMember); } @Override public List<Fans> findByWeChatUserId(Long weChatUserId) { return getFansRepository().findByWeChatUserId(weChatUserId); } @Override public Fans findByWeChatUserIdAndShopId(Long weChatUserId, Long shopId) { return getFansRepository().findByWeChatUserIdAndShopId(weChatUserId, shopId); } private FansPageVo buildFansPageVo(Fans fans) { FansPageVo fansPageVo = new FansPageVo(); fansPageVo.setId(fans.getId()); fansPageVo.setShopId(fans.getShopId()); fansPageVo.setOpenId(fans.getOpenId()); fansPageVo.setFansName(fans.getFansName()); fansPageVo.setMobile(fans.getMobile()); fansPageVo.setNickName(fans.getNickName()); fansPageVo.setFansSourceCode(FansSourceCodeEnum.fromCode(fans.getFansSourceCode()).toCode()); fansPageVo.setIsMember(BoolCodeEnum.fromCode(fans.getIsMember()).toCode()); fansPageVo.setMemberId(fans.getMemberId()); fansPageVo.setBuyTimes(fans.getBuyTimes()); fansPageVo.setRemark(fans.getRemark()); fansPageVo.setWeChatUserId(fans.getWeChatUserId()); if (fans.getMemberId() != null) { Member member = ServiceManager.memberService.findOne(fans.getMemberId()); if (member == null) { String message = ServiceManager.sysExceptionCodeService.getMessageByCode(ResGlobalExt.COMMON_OBJECT_NO_FOUND); throw new BusinessException(ResGlobalExt.COMMON_OBJECT_NO_FOUND, String.format(message, new Object[]{"会员"})); } fansPageVo.setSexCode(UserSexCodeEnum.fromCode(member.getSexCode()).toCode()); fansPageVo.setMemberCardNum(member.getMemberCardNum()); fansPageVo.setHomeAddr(member.getHomeAddr()); } return fansPageVo; } }
Shell
UTF-8
5,975
4.03125
4
[]
no_license
#!/bin/sh # Flags: # -r = Resolution. Options: hd, fhd, sd (default hq) # -p = Preview. # VIDEO DEVICE VIDEO_DEVICE=/dev/video0 if [ ! -e /dev/video0 ]; then zenity --error \ --title="Video capture device not found" \ --text="No video capture device could be found.\nPlease connect a webcam and try again." exit fi #Resolution settings FHD=width=1920:height=1080 # Full HD (1080p) HD=width=1280:height=720 # HD ready (720p) HQ=width=800:height=600 # High Quality SD=width=640:height=480 # Standard Definition # Flag variables widescreen=$SD # Used for preview res=$HQ # Resolution (default HQ) preview=false # Show preview during recording? # Check for flags while getopts rp option do case "${option}" in # Check for custom resolution r) ARG1=$(zenity --list \ --title="Video Recorder: Choose resolution" \ --text="The option ${OPTARG} is not available.\nPlease choose from the available modes:" \ --width=500 \ --height=240 \ --radiolist \ --column="" --column="flag" --column="Image quality" --column="Resolution" \ FALSE sd "Standard Definition" "640 * 480 px (4:3)" \ TRUE hq "High Quality" "800 * 600 px (4:3)" \ FALSE hd "HD-ready" "1280 * 720 px (16:9 / widescreen)" \ FALSE fhd "Full-HD" "1920 * 1080 px 16:9 / widescreen)"); ;; # Check for preview during recording p) zenity --question \ --title="Video Recorder" \ --text="Do you want a live preview during recording?\nThis might make your computer slower.\n\nYou will still see a live preview before recording starts if you click 'no'. However, this window will disappear once you start recording." \ --height=50 \ --width=500 ARG2=$? esac done # If flag for resolution i set, check the case $ARG1 in hd) res=$HD widescreen=width=852:height=480 ;; fhd) res=$FHD widescreen=width=852:height=480 ;; hq) res=$HQ ;; sd) res=$SD ;; "") ;; *) zenity --error \ --title="Video Recorder" \ --text="Resolution could not be set.\nDefault resolution will be used" esac # Calculate the scale factor for the transcoding of the preview # CURRENTLY NOT WORKING! screenHeight=$(xrandr --current | grep '*' | uniq | awk '{print $1}' | cut -d 'x' -f2) displayHeight=$(echo "$res" | cut -d '=' -f3) wantedHeight=$((screenHeight / 2)) cropFactor=$(echo "$wantedHeight $displayHeight" | awk '{printf "%.1f", $1/$2}' ) # Set the preview variable case $ARG2 in 0) preview=true ;; 1) ;; "") ;; *) zenity --error \ --title="Video recorder" \ --text="Something went wrong. Live preview could not be enabled." ;; esac # The current date will make the default file name DATE=`date +%Y%m%d-%H%M%S` # If the video device is not found, an error is thrown and # the program exits case $? in 0) ;; *) zenity --error \ --title="Video Recorder" \ --text="Unable to select video device inputs." exit;; esac # I really don't know the point of this if [ -d videos ]; then cd videos > /dev/null fi # Allow user to select a filename and a folder where # the file should be saved. # All files will be saved as .mp4, as that supports H.264 # codec FILE=`zenity --file-selection \ --title="Video Recorder" \ --save \ --confirm-overwrite \ --file-filter=*.mp4 \ --filename="$DATE.mp4"` case $? in 0) ;; *) exit;; esac # Open a new preview window cvlc v4l2://$VIDEO_DEVICE:$widescreen --sout '#transcode{codec=mp4v,vb=200,fps=20}:display' > /dev/null & PROCESSID=$! # Set the recording prompt text recordingPrompt="Live preview is now playing.\n\nTHE SYSTEM IS NOT YET RECORDING\n\nPress 'start' to start recording." if ! $preview ; then # If live preview is disabled recordingPrompt="$recordingPrompt\nOnce you press start, the live preview window will disappear." fi # Prompt for the user to start the recording zenity --question \ --title="Video Recorder" \ --text="$recordingPrompt" \ --ok-label=Start \ --width=500 \ --height=100 \ --no-wrap \ --cancel-label=Cancel case $? in 0) ;; *) kill $PROCESSID exit;; esac # Creates a folder in the temp folder where the temp video # file is then saved mkdir -p /tmp/videos TEMPFILE=/tmp/videos/$DATE.mp4 # Terminate current live stream kill $PROCESSID sleep 1 if ! $preview; then # Start VLC with the right settings and begin recording cvlc v4l2://$VIDEO_DEVICE:$res --sout '#standard{access=file,mux=ts,dst='$TEMPFILE'}' > /dev/null & else # Or start a duplicated stream # Transcode doesn work with duplicating a stream cvlc v4l2://$VIDEO_DEVICE:$res --sout '#duplicate{dst=standard{access=file,mux=ts,dst='$TEMPFILE'},dst="transcode{vcodec=mp4v,vb=10,fps=20,scale='$cropFactor'}:display"}' & fi PROCESSID=$! while true; do zenity --question \ --title="Video Recorder" \ --text="Video recording running." \ --ok-label=Finish \ --cancel-label=Abort case $? in 0) kill $PROCESSID sleep 1 if [ -e $TEMPFILE ]; then ( echo 1 cp -r $TEMPFILE $FILE & sourceSize=$(stat --format=%s $TEMPFILE) while true ; do while ! [ -e $FILE ]; do sleep 0.2 done progress=$(( $(stat --format="%s" $FILE)* 100 / $sourceSize )) if [ $progress = "100" ]; then break else echo $progress fi done ) | zenity --progress \ --title="Saving file..." \ --text="Saving file to $FILE" \ --percentage=0 rm $TEMPFILE else zenity --error \ --title="Video Recorder" \ --text="Temp file could not be recovered. Recording failed.\n Please check $TEMPFILE to see if you can recover it, or ask lab support to help you\n(do not shut down your computer while you haven't recovered the recording!)" fi exit ;; esac zenity --question \ --title="Video Recorder" \ --text="Are you sure to abort the recording?" case $? in 0) kill $PROCESSID if [ -e $TMPVIDEO ]; then mv $TMPVIDEO "$FILE".aborted fi zenity --info \ --title="Video Recorder: Aborted" \ --text="Video recording aborted." exit;; esac done
PHP
UTF-8
228
2.65625
3
[]
no_license
<?php include('db-conn.php'); $q = "SELECT * FROM tblUsers"; $result = mysqli_query($conn, $q); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo $row['username'] . "<br>"; } } ?>
Java
UTF-8
807
3.25
3
[]
no_license
package com.asiainfo.chapter15; /** * 通用的Generator * * @author zhiwangzhang * @date 2016年7月3日 下午4:02:26 */ public class Test33 { public void m1() { System.out.println("m1"); } public static void main(String[] args) { Test33 t = BasicGenerator.create(Test33.class).next(); t.m1(); } } class BasicGenerator<T> implements Generator<T> { private Class<T> cla; private BasicGenerator() { } public BasicGenerator(Class<T> cla) { this.cla = cla; } @Override public T next() { try { return (T) cla.newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public static <T> Generator<T> create(Class<T> cla) { return new BasicGenerator<T>(cla); } }
Java
UTF-8
1,073
2.203125
2
[ "Apache-2.0" ]
permissive
package com.jota.udacity.project2.app; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.jota.udacity.project2.ui.features.BasePresenter; import com.jota.udacity.project2.ui.features.View; public abstract class BaseActivity extends AppCompatActivity implements View { private BasePresenter mPresenter; protected abstract BasePresenter bindPresenter(); protected abstract int bindLayout(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initializeActivity(); } @Override protected void onResume() { super.onResume(); mPresenter.resume(); } @Override protected void onPause() { super.onPause(); mPresenter.pause(); } @Override protected void onDestroy() { super.onDestroy(); mPresenter.destroy(); } private void initializeActivity() { mPresenter = bindPresenter(); mPresenter.attachView(this); mPresenter.create(); setContentView(bindLayout()); } }
Java
UTF-8
489
3.015625
3
[]
no_license
class Solution { public int[] sortArrayByParityII(int[] A) { int i = 0, j = 1; while (i<A.length && j<A.length){ while (i<A.length && A[i]%2 == 0) i += 2; while (j<A.length && A[j]%2 == 1) j += 2; if (i<A.length && j<A.length){ int temp = A[i]; A[i] = A[j]; A[j] = temp; i += 2; j += 2; } } return A; } }
C
UTF-8
4,624
2.59375
3
[]
no_license
#include "common.h" sNodeTree* gNodes; int gSizeNodes = 0; int gUsedNodes = 0; void init_nodes() { const int node_size = 32; if(gUsedNodes == 0) { gNodes = (sNodeTree*)xcalloc(1, sizeof(sNodeTree)*node_size); gSizeNodes = node_size; gUsedNodes = 1; // 0 of index means null } } void free_nodes() { if(gUsedNodes > 0) { int i; for(i=1; i<gUsedNodes; i++) { switch(gNodes[i].mNodeType) { case kNodeTypeCString: free(gNodes[i].uValue.sString.mString); break; case kNodeTypeFunction: sNodeBlock_free(gNodes[i].uValue.sFunction.mNodeBlock); break; case kNodeTypeIf: { if(gNodes[i].uValue.sIf.mIfNodeBlock) { sNodeBlock_free(gNodes[i].uValue.sIf.mIfNodeBlock); } int j; for(j=0; j<gNodes[i].uValue.sIf.mElifNum; j++) { sNodeBlock* node_block = gNodes[i].uValue.sIf.mElifNodeBlocks[j]; if(node_block) { sNodeBlock_free(node_block); } } if(gNodes[i].uValue.sIf.mElseNodeBlock) { sNodeBlock_free(gNodes[i].uValue.sIf.mElseNodeBlock); } } break; case kNodeTypeWhile: { if(gNodes[i].uValue.sWhile.mWhileNodeBlock) { sNodeBlock_free(gNodes[i].uValue.sWhile.mWhileNodeBlock); } } break; case kNodeTypeFor: if(gNodes[i].uValue.sFor.mForNodeBlock) { sNodeBlock_free(gNodes[i].uValue.sFor.mForNodeBlock); } break; case kNodeTypeSimpleLambdaParam: if(gNodes[i].uValue.sSimpleLambdaParam.mBuf) { free(gNodes[i].uValue.sSimpleLambdaParam.mBuf); } break; case kNodeTypeGenericsFunction: free(gNodes[i].uValue.sFunction.mBlockText); break; case kNodeTypeInlineFunction: free(gNodes[i].uValue.sFunction.mBlockText); break; case kNodeTypeNormalBlock: if(gNodes[i].uValue.sNormalBlock.mNodeBlock) { sNodeBlock_free(gNodes[i].uValue.sNormalBlock.mNodeBlock); } break; case kNodeTypeSwitch: if(gNodes[i].uValue.sSwitch.mSwitchExpression) { free(gNodes[i].uValue.sSwitch.mSwitchExpression); } break; default: break; } } free(gNodes); gSizeNodes = 0; gUsedNodes = 0; } } // return node index unsigned int alloc_node() { if(gSizeNodes == gUsedNodes) { int new_size = (gSizeNodes+1) * 2; gNodes = (sNodeTree*)xrealloc(gNodes, sizeof(sNodeTree)*new_size); // memset(gNodes + gSizeNodes, 0, sizeof(sNodeTree)*(new_size - gSizeNodes)); gSizeNodes = new_size; } return gUsedNodes++; } sNodeBlock* sNodeBlock_alloc() { sNodeBlock* block = (sNodeBlock*)xcalloc(1, sizeof(sNodeBlock)); block->mSizeNodes = 32; block->mNumNodes = 0; block->mNodes = (unsigned int*)xcalloc(1, sizeof(unsigned int)*block->mSizeNodes); block->mLVTable = NULL; return block; } void sNodeBlock_free(sNodeBlock* block) { /// this is compiler, so allow me to make memory leak /* if(block->mNodes) free(block->mNodes); free(block->mSource.mBuf); free(block); */ } void append_node_to_node_block(sNodeBlock* node_block, unsigned int node) { if(node_block->mSizeNodes <= node_block->mNumNodes) { unsigned int new_size = node_block->mSizeNodes * 2; node_block->mNodes = (unsigned int*)xrealloc(node_block->mNodes, sizeof(unsigned int)*new_size); memset(node_block->mNodes + node_block->mSizeNodes, 0, sizeof(unsigned int)*(new_size-node_block->mSizeNodes)); node_block->mSizeNodes = new_size; } node_block->mNodes[node_block->mNumNodes] = node; node_block->mNumNodes++; }
Java
UTF-8
190
1.625
2
[]
no_license
/** * Package containing an implementation of a simple swing application for displaying two equal lists of dynamically generated primes. * * @since 7.0 */ package hr.fer.oprpp1.gui.prim;
Swift
UTF-8
1,370
2.828125
3
[]
no_license
// // PhotoCoreDataManager.swift // MobileUpTest // // Created by Macbook Pro on 23.07.2021. // import UIKit import CoreData //MARK: - Photos Core Data Manager final class PhotosCoreDataManager { static var shared = PhotosCoreDataManager() var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "Photos") container.loadPersistentStores { (_, error) in guard let error = error else { return } print(error.localizedDescription) } return container }() var moc: NSManagedObjectContext { persistentContainer.viewContext } //MARK: - Save Photo func savePhoto(photoItem: PhotoItem) -> Photo? { let newPhoto = Photo(context: moc) newPhoto.setValue(photoItem.url, forKey: "url") newPhoto.setValue(photoItem.date, forKey: "date") do { try self.moc.save() return newPhoto } catch { return nil } } //MARK: - Get All Photos func fetchPhotos() -> [Photo] { do { let fetchRequest = NSFetchRequest<Photo>(entityName: "Photo") let photos = try moc.fetch(fetchRequest) return photos } catch { return [] } } }
Python
UTF-8
1,069
2.921875
3
[]
no_license
n = int(input()) number = list(map(int, input().split())) oper = list(map(int, input().split())) max_answer = -10000000000 min_answer = 10000000000 def getSol(cur_value, idx, plus, minus, mul, div): global n, max_answer, min_answer if idx == n: max_answer = max(max_answer, cur_value) min_answer = min(min_answer, cur_value) return if plus>0: getSol(cur_value + number[idx], idx+1, plus-1, minus, mul, div) if minus>0: getSol(cur_value - number[idx], idx+1, plus, minus-1, mul, div) if mul>0: getSol(cur_value * number[idx], idx+1, plus, minus, mul-1, div) if div>0: next_val = 0 if cur_value<0: cur_value *= (-1) next_val = cur_value // number[idx] next_val *= (-1) else: next_val = cur_value // number[idx] getSol(next_val, idx+1, plus, minus, mul, div-1) if __name__ == '__main__': getSol(number[0], 1, oper[0], oper[1], oper[2], oper[3]) print(max_answer) print(min_answer)
JavaScript
UTF-8
2,632
2.71875
3
[]
no_license
import React, { Component } from "react"; import { StyleSheet, View, TextInput, Button, } from "react-native"; export default class NewMessageForn extends Component { constructor(props) { super(props); this.state = { user_name: "", time_stamp: "2020-03-06 18:35:14", message_text: "" }; } async onPostNewMessage() { var data = { user_name: this.state.user_name, time_stamp: this.state.time_stamp, message_text: this.state.message_text }; try { console.log(data); let response = await fetch( "http://192.168.1.125:3000/messages", { method: "POST", headers: { "Accept": "application/json", "Content-Type": "application/json" }, body: JSON.stringify(data) } ); if (response.status >= 200 && response.status < 300) { alert("Message Sent Successfully"); } } catch (errors) { alert(errors); } } onPressSubmitButton() { this.onPostNewMessage(); } render() { return ( <View style={loginStyles.container}> <TextInput ref="txtUserName" style={loginStyles.textInput} placeholder="User Name" keyboardType="default" returnKeyType="next" onSubmitEditing={event => { this.refs.txtTimeStamp.focus(); }} onChangeText={text => this.setState({ user_name: text })} /> <TextInput ref="txtTimeStamp" style={loginStyles.textInput} placeholder="2020-03-06 18:35:14" keyboardType="default" returnKeyType="next" onSubmitEditing={event => { this.refs.txtMessageText.focus(); }} onChangeText={text => this.setState({ time_stamp: text })} /> <TextInput ref="txtMessageText" style={loginStyles.textInput} placeholder="Message Text" returnKeyType="done" onChangeText={text => this.setState({ message_text: text })} /> <Button title="Submit" style={loginStyles.buttonSubmit} onPress={this.onPressSubmitButton.bind(this)} /> </View> ); } } const loginStyles = StyleSheet.create({ container: { alignItems: "center", justifyContent: "center", flex: 1, flexDirection: "column", backgroundColor: "#F5FCFF", width: 250, }, textInput: { height: 40, textAlign: "center", borderWidth: 0, width: 250, }, buttonSubmit: { width: 200, color: "#9AE446", } });
C
UTF-8
5,529
2.796875
3
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2020 Tobias Svehagen * * SPDX-License-Identifier: Apache-2.0 */ #include <zephyr/ztest.h> #include <stdio.h> #include <unistd.h> #include <errno.h> #include <zephyr/net/socket.h> #include <poll.h> #include <sys/eventfd.h> #define TESTVAL 10 ZTEST_SUITE(test_eventfd, NULL, NULL, NULL, NULL, NULL); static int is_blocked(int fd, short *event) { struct pollfd pfd; int ret; pfd.fd = fd; pfd.events = *event; ret = poll(&pfd, 1, 0); zassert_true(ret >= 0, "poll failed %d", ret); *event = pfd.revents; return ret == 0; } ZTEST(test_eventfd, test_eventfd) { int fd = eventfd(0, 0); zassert_true(fd >= 0, "fd == %d", fd); close(fd); } ZTEST(test_eventfd, test_eventfd_read_nonblock) { eventfd_t val = 0; int fd, ret; fd = eventfd(0, EFD_NONBLOCK); zassert_true(fd >= 0, "fd == %d", fd); ret = eventfd_read(fd, &val); zassert_true(ret == -1, "read unset ret %d", ret); zassert_true(errno == EAGAIN, "errno %d", errno); ret = eventfd_write(fd, TESTVAL); zassert_true(ret == 0, "write ret %d", ret); ret = eventfd_read(fd, &val); zassert_true(ret == 0, "read set ret %d", ret); zassert_true(val == TESTVAL, "red set val %d", val); ret = eventfd_read(fd, &val); zassert_true(ret == -1, "read subsequent ret %d val %d", ret, val); zassert_true(errno == EAGAIN, "errno %d", errno); close(fd); } ZTEST(test_eventfd, test_eventfd_write_then_read) { eventfd_t val; int fd, ret; fd = eventfd(0, 0); zassert_true(fd >= 0, "fd == %d", fd); ret = eventfd_write(fd, 3); zassert_true(ret == 0, "write ret %d", ret); ret = eventfd_write(fd, 2); zassert_true(ret == 0, "write ret %d", ret); ret = eventfd_read(fd, &val); zassert_true(ret == 0, "read ret %d", ret); zassert_true(val == 5, "val == %d", val); close(fd); /* Test EFD_SEMAPHORE */ fd = eventfd(0, EFD_SEMAPHORE); zassert_true(fd >= 0, "fd == %d", fd); ret = eventfd_write(fd, 3); zassert_true(ret == 0, "write ret %d", ret); ret = eventfd_write(fd, 2); zassert_true(ret == 0, "write ret %d", ret); ret = eventfd_read(fd, &val); zassert_true(ret == 0, "read ret %d", ret); zassert_true(val == 1, "val == %d", val); close(fd); } ZTEST(test_eventfd, test_eventfd_poll_timeout) { struct pollfd pfd; int fd, ret; fd = eventfd(0, 0); zassert_true(fd >= 0, "fd == %d", fd); pfd.fd = fd; pfd.events = POLLIN; ret = poll(&pfd, 1, 500); zassert_true(ret == 0, "poll ret %d", ret); close(fd); } static void eventfd_poll_unset_common(int fd) { eventfd_t val = 0; short event; int ret; event = POLLIN; ret = is_blocked(fd, &event); zassert_equal(ret, 1, "eventfd not blocked with initval == 0"); ret = eventfd_write(fd, TESTVAL); zassert_equal(ret, 0, "write ret %d", ret); event = POLLIN; ret = is_blocked(fd, &event); zassert_equal(ret, 0, "eventfd blocked after write"); zassert_equal(event, POLLIN, "POLLIN not set"); ret = eventfd_write(fd, TESTVAL); zassert_equal(ret, 0, "write ret %d", ret); ret = eventfd_read(fd, &val); zassert_equal(ret, 0, "read ret %d", ret); zassert_equal(val, 2*TESTVAL, "val == %d, expected %d", val, TESTVAL); /* eventfd shall block on subsequent reads */ event = POLLIN; ret = is_blocked(fd, &event); zassert_equal(ret, 1, "eventfd not blocked after read"); } ZTEST(test_eventfd, test_eventfd_unset_poll_event_block) { int fd; fd = eventfd(0, 0); zassert_true(fd >= 0, "fd == %d", fd); eventfd_poll_unset_common(fd); close(fd); } ZTEST(test_eventfd, test_eventfd_unset_poll_event_nonblock) { int fd; fd = eventfd(0, EFD_NONBLOCK); zassert_true(fd >= 0, "fd == %d", fd); eventfd_poll_unset_common(fd); close(fd); } static void eventfd_poll_set_common(int fd) { eventfd_t val = 0; short event; int ret; event = POLLIN; ret = is_blocked(fd, &event); zassert_equal(ret, 0, "eventfd is blocked with initval != 0"); ret = eventfd_read(fd, &val); zassert_equal(ret, 0, "read ret %d", ret); zassert_equal(val, TESTVAL, "val == %d", val); event = POLLIN; ret = is_blocked(fd, &event); zassert_equal(ret, 1, "eventfd is not blocked after read"); } ZTEST(test_eventfd, test_eventfd_set_poll_event_block) { int fd; fd = eventfd(TESTVAL, 0); zassert_true(fd >= 0, "fd == %d", fd); eventfd_poll_set_common(fd); close(fd); } ZTEST(test_eventfd, test_eventfd_set_poll_event_nonblock) { int fd; fd = eventfd(TESTVAL, EFD_NONBLOCK); zassert_true(fd >= 0, "fd == %d", fd); eventfd_poll_set_common(fd); close(fd); } ZTEST(test_eventfd, test_eventfd_overflow) { short event; int fd, ret; fd = eventfd(0, EFD_NONBLOCK); zassert_true(fd >= 0, "fd == %d", fd); event = POLLOUT; ret = is_blocked(fd, &event); zassert_equal(ret, 0, "eventfd write blocked with initval == 0"); ret = eventfd_write(fd, UINT64_MAX); zassert_equal(ret, -1, "fd == %d", fd); zassert_equal(errno, EINVAL, "did not get EINVAL"); ret = eventfd_write(fd, UINT64_MAX-1); zassert_equal(ret, 0, "fd == %d", fd); event = POLLOUT; ret = is_blocked(fd, &event); zassert_equal(ret, 1, "eventfd write not blocked with cnt == UINT64_MAX-1"); ret = eventfd_write(fd, 1); zassert_equal(ret, -1, "fd == %d", fd); zassert_equal(errno, EAGAIN, "did not get EINVAL"); close(fd); } ZTEST(test_eventfd, test_eventfd_zero_shall_not_unblock) { short event; int fd, ret; fd = eventfd(0, 0); zassert_true(fd >= 0, "fd == %d", fd); ret = eventfd_write(fd, 0); zassert_equal(ret, 0, "fd == %d", fd); event = POLLIN; ret = is_blocked(fd, &event); zassert_equal(ret, 1, "eventfd unblocked by zero"); close(fd); }
C#
UTF-8
2,000
3.765625
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ComputerScience { public class InsertionSort { private int[] data; private static Random generator = new Random(); public InsertionSort(int size) { data = new int[size]; for(int i = 0; i < size; i++) { data[i] = generator.Next(100, 200); } } public void Sort() { Console.Write("\n(Insertion method) Sorted Array Elements: (Step by step)\n\n"); displayArrayElements(); for(int i = 0; i < data.Length - 1; i++) { //бере кожне число по черзі і відразу ставить її в потрібне місце у відсортовану частину масиву //порівнюючи з елементами відсортованої частини //таким чином невідсортований масив зменш на 1 при кожному проході for(int j = i + 1; 0 < j; j--) { if(data[j-1] > data[j]) { Swap(j - 1, j); displayArrayElements(); } //щоб побачити повний алгоритм //displayArrayElements(); } //Console.Write("\n\n"); } } public void Swap(int first, int second) { int temp = data[first]; data[first] = data[second]; data[second] = temp; } public void displayArrayElements() { foreach(var element in data) { Console.Write(element + " "); } Console.Write("\n\n"); } } }
Java
UTF-8
1,116
2.21875
2
[]
no_license
package POM; import Commons.Driver; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class FooterTextValidation { @FindBy(xpath = "//h4[contains (text(), 'BOOKMYSHOW APP ')]") private WebElement BookmyshowApp; @FindBy(xpath = "//h4[contains (text(), 'BOOKMYSHOW NEWS')]") private WebElement BookmyshowNews; @FindBy(xpath = "//h4[contains (text(), 'EXCLUSIVES')]") private WebElement Exclusive; @FindBy(xpath = "//h4[contains (text(), 'HELP')]") private WebElement Help; public FooterTextValidation(WebDriver driver) { PageFactory.initElements(driver,this);} public boolean verifyFooter(){ if(BookmyshowApp.isDisplayed()&&BookmyshowNews.isDisplayed()&&Exclusive.isDisplayed()&&Help.isDisplayed()){ return true; } else{ return false; } } }
Python
UTF-8
871
4.15625
4
[]
no_license
"""PROBLEM: Given an array of integers nums, write a method that returns the "pivot" index of this array. We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index. If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index. """ """SOLUTION: Set right_sum = sum(nums) and left_sum = 0. Then iterate through nums and decrement right_sum. If left_sum = right_sum then that is the pivot index or else increment left_sum. """ class Solution: def pivotIndex(self, nums: List[int]) -> int: l_sum = 0 r_sum = sum(nums) for i in range(len(nums)): r_sum -= nums[i] if l_sum == r_sum: return i l_sum += nums[i] return -1
Java
UTF-8
722
1.648438
2
[ "Apache-2.0" ]
permissive
/* * @(#)RoleGroupSearchConditions.java 1.0 Aug 28, 2015 * Copyright 2015 by GNU Lesser General Public License (LGPL). All rights reserved. */ package org.nlh4j.web.system.role.dto; import lombok.Data; import lombok.EqualsAndHashCode; import org.nlh4j.web.base.common.controller.AbstractSearchConditionsDto; import org.nlh4j.web.core.domain.entity.RoleGroup; /** * {@link RoleGroup} search conditions * * @author Hai Nguyen (hainguyenjc@gmail.com) * */ @Data @EqualsAndHashCode(callSuper = false) public class RoleGroupSearchConditions extends AbstractSearchConditionsDto { /** */ private static final long serialVersionUID = 1L; /** group code/name keyword */ private String keyword; }
Java
UTF-8
1,028
2.328125
2
[ "Apache-2.0" ]
permissive
package cn.gao.studs.login; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import cn.gao.studs.domain.User; public class LoginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); // User user = new User(); try { BeanUtils.populate(user, req.getParameterMap()); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } user = new LoginService().login(user); if(user==null) {//登录没有成功 //重定向到index.html resp.sendRedirect(req.getContextPath()+"/index.html?error"); }else { //去显示所有学生 resp.sendRedirect(req.getContextPath()+"/stud"); } } }
Java
UTF-8
2,138
3.4375
3
[]
no_license
package Utils; /** * * <h2>青阳龙野中文姓名随机生成工具-姓氏字典</h2> * <p>该接口定义了获取随机中文名生成工具(RandomChineseNameUtile)需要使用的姓氏字典的格式, * 随机中文名工具将通过这个字典获取能够使用的姓氏集合。如果您需要自定义姓氏生成范围, * 请创建自定义姓氏字典类并按照功能说明实现这个接口。 * </p> * @author 青阳龙野(kohgylw) * @version 1.0 */ public interface SurnameDictionaries { /** * * <h2>检查当前姓氏字典中是否有某一姓氏</h2> * <p> * 实现:该方法检查传入的字符串是否存在于姓氏字典中。 * </p> * * @author 青阳龙野(kohgylw) * @param testsurname * String 需要检查的姓氏字符串 * @return boolean 表示是否存在 */ boolean haveSurnameOf(String testsurname); /** * * <h2>获取当前姓氏集合规模</h2> * <p> * 实现:以int形式返回当前数据集合的规模 * </p> * * @author 青阳龙野(kohgylw) * @param 无 * @return int 集合规模 */ int getSurnameSetSize(); /** * * <h2>从姓氏字典中随机获取一个单姓</h2> * <p> * 实现:该方法每次调用均重新随机。如果姓氏集合为空,则返回一个空字符串。 * </p> * * @author 青阳龙野(kohgylw) * @param 无 * @return String 随机的单字姓氏 */ String getRandomSingleSurname(); /** * * <h2>从姓氏字典中随机获取一个复姓</h2> * <p> * 实现:该方法每次调用均重新随机。如果双字姓氏字典为空,则返回一个空字符串。 * </p> * * @author 青阳龙野(kohgylw) * @param 无 * @return String 随机的双字姓氏 */ String getRandomDoubleSurname(); /** * * <h2>得到单姓与复姓的比率</h2> * <p>实现:该方法返回复姓集合规模占姓氏总规模的比值,该值会决定姓名随机生成时使用单复姓的占比。其值应小于1。</p> * @author 青阳龙野(kohgylw) * @param 无 * @return double 比值 */ double getSingleDoubleRate(); }
Markdown
UTF-8
1,539
3.15625
3
[]
no_license
### NIO &ensp;&ensp;同步非阻塞IO。它利用了自 NIO 子系统被引入 JDK 1.4 时便可用的基于选择器的 API。 #### Java NIO: Channels and Buffers(通道和缓冲区) &ensp;&ensp;标准的IO基于字节流和字符流进行操作的,而NIO是基于通道(Channel)和缓冲区(Buffer)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。 #### Java NIO: Non-blocking IO(非阻塞IO) &ensp;&ensp;Java NIO可以让你非阻塞的使用IO,例如:当线程从通道读取数据到缓冲区时,线程还是可以进行其他事情。当数据被写入到缓冲区时,线程可以继续处理它。从缓冲区写入通道也类似。 #### Java NIO: Selectors(选择器) &ensp;&ensp;Java NIO引入了选择器的概念,选择器用于监听多个通道的事件(比如:连接打开,数据到达)。因此,单个的线程可以监听多个数据通道。 &ensp;&ensp;选择器背后的基本概念是充当一个注册表,在哪里你将可以请求在 Channel 的状态发生变化时 得到通知。可能的状态变化有: * 新的 Channel 已被接受并且就绪; * Channel 的连接已经完成; * Channel 有已经就绪的可供读取的数据; * Channel 可用于写数据 &ensp;&ensp;选择器运行在一个检查状态变化并对其做出相应响应的线程上,在应用程序状态改变的改变做出响应之后,选择器将会被重置,并将重复这个过程。 ### NIO问题 * 资源浪费
Java
UTF-8
2,707
2.578125
3
[]
no_license
package kr.ac.kaist.se.model.abst.cap; import kr.ac.kaist.se.data.SimLogEvent; import kr.ac.kaist.se.model.abst.obj._SimObject_; import kr.ac.kaist.se.model.sos.SoS; import java.util.ArrayList; /** * Abstract class to represent an action object * * In SIMVA-SoS Lite, _SimAction_ can be specialized into FuncAction, MoveAction, CommAction, * but this project only implements MoveAction class to update ObjectLocation of a _SimObject_. * Note that this implementation is independent from the implementation of SIMVA-SoS Lite * * @author ymbaek */ public abstract class _SimAction_ { protected SoS accessibleSoS; //Accessible SimModel (SoS) protected _SimObject_ actionSubject; //Subject who performs this action protected String actionId; //id of action protected String actionName; //name of action // ArrayList to store SimLogEvents of executed actions for return protected ArrayList<SimLogEvent> actionLogEvents = new ArrayList<>(); public _SimAction_(SoS accessibleSoS, _SimObject_ actionSubject, String actionId, String actionName) { this.accessibleSoS = accessibleSoS; this.actionSubject = actionSubject; this.actionId = actionId; this.actionName = actionName; } /** * A method to check precondition of this action * * @return true if this action is executable */ public abstract boolean checkPrecondition(); /** * A method to actually execute this action * The original version of this method returns ArrayList of SimLogEvent to generate logs * * @param tick current tick of simulation */ public abstract ArrayList<SimLogEvent> executeAction(int tick); /** * A method to generate event specification for SimEventLog * * @return Generated String-type log event specification */ public abstract String generateLogEventSpec(); /* Getters & Setters */ public SoS getAccessibleSoS() { return accessibleSoS; } public void setAccessibleSoS(SoS accessibleSoS) { this.accessibleSoS = accessibleSoS; } public _SimObject_ getActionSubject() { return actionSubject; } public void setActionSubject(_SimObject_ actionSubject) { this.actionSubject = actionSubject; } public String getActionId() { return actionId; } public void setActionId(String actionId) { this.actionId = actionId; } public String getActionName() { return actionName; } public void setActionName(String actionName) { this.actionName = actionName; } }
Java
UTF-8
3,879
1.898438
2
[]
no_license
package com.hms.pojo; import com.baomidou.mybatisplus.annotation.IdType; import java.util.Date; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableField; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * <p> * * </p> * * @author szy * @since 2020-10-25 */ @ApiModel(value="Pharmacy对象", description="") public class Pharmacy implements Serializable { private static final long serialVersionUID=1L; @TableId(value = "pharmacyId", type = IdType.AUTO) private Integer pharmacyId; @TableField("pharmacyName") private String pharmacyName; @TableField("drugstoreId") private Integer drugstoreId; @TableField("skullId") private Integer skullId; @TableField("warehouseId") private Integer warehouseId; private Integer unit; @TableField("sellingPrice") private Double sellingPrice; private Integer area; private Integer type; @TableField("produceDate") private Date produceDate; @TableField("validDate") private Date validDate; private Integer drugstorenum; private String skullbatch; public Integer getPharmacyId() { return pharmacyId; } public void setPharmacyId(Integer pharmacyId) { this.pharmacyId = pharmacyId; } public String getPharmacyName() { return pharmacyName; } public void setPharmacyName(String pharmacyName) { this.pharmacyName = pharmacyName; } public Integer getDrugstoreId() { return drugstoreId; } public void setDrugstoreId(Integer drugstoreId) { this.drugstoreId = drugstoreId; } public Integer getSkullId() { return skullId; } public void setSkullId(Integer skullId) { this.skullId = skullId; } public Integer getWarehouseId() { return warehouseId; } public void setWarehouseId(Integer warehouseId) { this.warehouseId = warehouseId; } public Integer getUnit() { return unit; } public void setUnit(Integer unit) { this.unit = unit; } public Double getSellingPrice() { return sellingPrice; } public void setSellingPrice(Double sellingPrice) { this.sellingPrice = sellingPrice; } public Integer getArea() { return area; } public void setArea(Integer area) { this.area = area; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Date getProduceDate() { return produceDate; } public void setProduceDate(Date produceDate) { this.produceDate = produceDate; } public Date getValidDate() { return validDate; } public void setValidDate(Date validDate) { this.validDate = validDate; } public Integer getDrugstorenum() { return drugstorenum; } public void setDrugstorenum(Integer drugstorenum) { this.drugstorenum = drugstorenum; } public String getSkullbatch() { return skullbatch; } public void setSkullbatch(String skullbatch) { this.skullbatch = skullbatch; } @Override public String toString() { return "Pharmacy{" + "pharmacyId=" + pharmacyId + ", pharmacyName=" + pharmacyName + ", drugstoreId=" + drugstoreId + ", skullId=" + skullId + ", warehouseId=" + warehouseId + ", unit=" + unit + ", sellingPrice=" + sellingPrice + ", area=" + area + ", type=" + type + ", produceDate=" + produceDate + ", validDate=" + validDate + ", drugstorenum=" + drugstorenum + ", skullbatch=" + skullbatch + "}"; } }
JavaScript
UTF-8
1,219
2.53125
3
[]
no_license
'use strict'; import TodoService from '../service/todo-service'; const todoService = new TodoService(); ///////////////// // Fetch todos // ///////////////// export const FETCH_TODOS_REQUEST = 'FETCH_TODOS_REQUEST'; function fetchTodosRequest() { return { type: FETCH_TODOS_REQUEST }; } export const FETCH_TODOS_RESPONSE = 'FETCH_TODOS_RESPONSE'; function fetchTodosResponse(todos) { return { type: FETCH_TODOS_RESPONSE, todos }; } export function fetchTodos() { return dispatch => { dispatch(fetchTodosRequest()); return todoService.all().then(todos => { dispatch(fetchTodosResponse(todos)); return todos; }); } } ////////////// // Add todo // ////////////// export const ADD_TODO_REQUEST = 'ADD_TODO_REQUEST'; function addTodoRequest(todo) { return { type: ADD_TODO_REQUEST, todo } } export const ADD_TODO_RESPONSE = 'ADD_TODO_RESPONSE'; function addTodoResponse(todo) { return { type: ADD_TODO_RESPONSE, todo } } export function addTodo(todo) { return dispatch => { dispatch(addTodoRequest(todo)); return todoService.add(todo).then(newTodo => { dispatch(addTodoResponse(newTodo)); return newTodo; }); } }
Swift
UTF-8
1,101
3.03125
3
[]
no_license
// // RowView.swift // ControlADOX // // Created by Teo Toledo on 07/06/2021. // import SwiftUI struct RowView: View { var dispositive: Dispositive var body: some View { HStack{ dispositive.avatar .resizable() .frame(width: 40, height: 40).padding() VStack(alignment: .leading){ Text(dispositive.name) .font(.title) Text(dispositive.description) .font(.subheadline) } Spacer() if(dispositive.favorite) {Image(systemName: "star.fill").foregroundColor(.yellow)} } } } struct RowView_Previews: PreviewProvider { static var previews: some View { RowView(dispositive: Dispositive(id: 0, name: "Fenotipado", description: "Consola de comandos", color: .blue, banner: Image("fenotipadoBanner"), ip: "192.168.0.205", port: 3489, control: 1, avatar: Image(systemName: "terminal.fill"), favorite: true)).previewLayout(.fixed(width: 400, height: 60)) } }
JavaScript
UTF-8
1,209
3.546875
4
[]
no_license
// Below are two imports at once: React and Component from 'react; // Import BookList and add it to the render function below, to render it inside the app. // Then make sure BookList has a link to Redux because we want our app to showcase a list of books. // So, go to book-list.js and import 'react-redux' library // Also, import individual containers, to make sure they get rendered , // + add the components to the render() method below. import React, { Component } from "react"; import BookList from "../containers/book-list"; import BookDetail from "../containers/book-detail"; // We render BookList which is a container/smart component (React side), bonded to the application state (help by Redux) // When we saw the list in the browser, behind the scenes: // Redux generated a state object that contained our books and mapped that state // as props to our component. // Because the state was updated through our reducer, our component rerendered that list of books. // Whenever the application state changes, the application will rerender as well. export default class App extends Component { render() { return ( <div> <BookList /> <BookDetail /> </div> ); } }
Ruby
UTF-8
1,765
2.828125
3
[ "MIT" ]
permissive
module Airbrake # A class that is capable of unwinding nested exceptions and representing them # as JSON-like hash. # # @api private # @since v1.0.4 class NestedException # @return [Integer] the maximum number of nested exceptions that a notice # can unwrap. Exceptions that have a longer cause chain will be ignored MAX_NESTED_EXCEPTIONS = 3 # On Ruby 3.1+, the error highlighting gem can produce messages that can # span multiple lines. We don't display multiline error messages in the # title of the notice in the Airbrake dashboard. Therefore, we want to strip # out the higlighting part so that the errors look consistent. The full # message with the exception will be attached to the notice body. # # @return [String] RUBY_31_ERROR_HIGHLIGHTING_DIVIDER = "\n\n".freeze # @return [Hash] the options for +String#encode+ ENCODING_OPTIONS = { invalid: :replace, undef: :replace }.freeze def initialize(exception) @exception = exception end def as_json unwind_exceptions.map do |exception| { type: exception.class.name, message: message(exception), backtrace: Backtrace.parse(exception) } end end private def unwind_exceptions exception_list = [] exception = @exception while exception && exception_list.size < MAX_NESTED_EXCEPTIONS exception_list << exception exception = (exception.cause if exception.respond_to?(:cause)) end exception_list end def message(exception) return unless (msg = exception.message) msg .encode(Encoding::UTF_8, **ENCODING_OPTIONS) .split(RUBY_31_ERROR_HIGHLIGHTING_DIVIDER) .first end end end
Markdown
UTF-8
10,078
3.03125
3
[]
no_license
# 0801. 特别放送 | 深度关系与精神资源 > 梁宁·产品思维30讲 2018-01-14 在《02用户体验与结婚教练》中,我提到会有两篇关于深度关系的文章作为彩蛋。 我选取了这两篇文章的精彩片段作为赏读,让你从不同侧面对一个人的精神资源,以及对人与人之间的精神关系,希望你能有更深刻的理解。 ## 01. 深度关系 原标题为《关系的深度——「纸牌屋」安德伍德与克莱尔夫妇的深刻关系》,感兴趣的话可以到公众号「梁宁-闲花照水录」(ID:cafeday)查看原文,以下为精彩节选。 春风沉醉,柳絮纷纷。走在草坪的小径里,想起《纸牌屋》第二季开篇的第一幕,安德伍德与克莱尔一起跑步登场。 《纸牌屋》的镜头里,这对夫妻独处的时候,总是在窗前一起吸烟,或者一起跑步。从来没有一个镜头,是安德伍德与克莱尔一起躺在床上,松弛随意地聊天。 克莱尔的情人亚当,是位敏感的摄影师。克莱尔拜会丈夫的出轨对象后,离家出走,到了亚当身边。两个人拥抱着入睡,醒来并不马上起身,而是依偎在床上继续聊天——这是在安德伍德身边从未见过的轻松惬意。 一般的女人,这样也就算是找到所谓的爱情了,该留在这里。 但是,克莱尔告诉亚当:我爱你只能偶尔一周。然后,继续回到安德伍德身边。 为什么?因为克莱尔与安德伍德,拥有比和亚当更为深刻的关系。 我曾在一篇文章中说过,人生重要的天分是持续快乐的地方。每个人都没办法拒绝自己真实的快乐,会情不自禁地在自己喜欢的事情上花时间,不知不觉地放一万个小时在那里。 然而,成就最高的那批人,他们还有一个比快乐更重要的天分——痛苦。 有人受不了自己不被人围绕着需要的痛苦; 有人受不了自己不是注意力焦点的痛苦; 有人受不了其他人在他前面、在他上面的痛苦; 有人受不了「我想要的那张椅子上坐的不是我」的痛苦…… 向上爬、严格自律、昼度夜思、殚精竭虑……这样日复一日的日子,委实不快乐,但是驱动他们的是痛苦。巨大的痛苦,让他们无法停下来。 什么叫普通人? 就是快乐没有那么强烈,痛苦也没有那么巨大。所以,他们的人生会在既定的轨道上相对平稳地运行,而不会被快乐和痛苦牵引撕扯,没完没了地折腾。 什么叫有一技之长的人? 就是当他在沉下来做某件事的时候,他不厌其烦,乐在其中,完全不理会别人的诧异或者不理解。 什么是杰出的人? 就是如果他想要的那个,他得不到,他就像万蚁噬心那样痛苦。牺牲什么都可以,他必须得到他要的那个东西。 当他不再痛苦的时候,也许他超越了,也许他就此平庸了。 所以,要想和一个优秀的人在一起,就要懂他真实的快乐,懂他真实的痛苦,并且给予他能量。 《纸牌屋》里,很多男人喜欢克莱尔,喜欢她的优雅、聪慧、得体。 在克莱尔的内核,一直点燃她,推动她,折磨她的,是她自己勃勃的野心。 亚当对克莱尔说:你一直想要万众瞩目。克莱尔摇摇头说:不止,我要举足轻重。  一个女人,拥有这样野心的内核,99.9% 的男人都不会喜欢,他们只想要这个女人令人愉悦的那一面。   只有安德伍德,那个穷小子,看懂了这个被野心折磨的富家女。因为他有一样的痛。对于拥有这样巨大痛苦的人,欢愉是多么的短暂与廉价。 才华与美好的肉体,确实令人怦然心动。在美好的清晨有放松的心情,一起早餐,一起散步,一起创作,确实是好生活。 可是,对于安德伍德和克莱尔这样的人,「我想要的那张椅子上,坐的不是我」的那种痛苦,令他们寤寐思服、辗转反侧、销魂蚀骨。轻松惬意的好生活,并无法安抚她如影随行的真痛苦。 唯有回到战场,回到伙伴身边,拿起武器,继续准备作战,才能让她缓解焦虑。能赢与否,天知道。但是,他们在做准备,他们在做事情,他们在一寸一寸前进,他和她在一起,这一切的动作里,她的痛苦才能得到慰藉。 这就是人与人关系的深浅远近。 安德伍德一次一次去找年轻的佐伊,毫无疑问佐伊给了他欢愉,但是佐伊不能懂他的痛苦。 亚当一个电话、一个吻都可以令克莱尔微笑,但是亚当不能懂克莱尔的痛苦。 安德伍德和克莱尔,可以与无数人共享欢愉。但是只有他们二人,才能真实地分享痛苦。他们彼此交换了太多的能量,交换了太多的灵魂。 两个人都很难把另外一个人从自己的生命中剥离出去——这就是深刻的关系。 所以,傻白甜是不可能真正搞定霸道总裁的。因为,她可能真实地给了霸道总裁欢愉,可是欢愉如此脆弱。 两个人能否建立深刻的关系还是取决于,她是否能懂他的痛苦,两个人交换了多少能量,交换了多少灵魂。 所以,很多人一生关系里,最大的痛是与父母的关系。 论获得能量,我们的生命都是父母给的,父母的爱是一生最大的能量。 可是,当父母不能理解子女的快乐,不能理解子女的痛苦,只会向子女提出一些角色化的要求,那种生生疏离的痛苦,其实并不是一起吃一顿年夜饭可以慰藉的。 ## 02. 精神资源 原标题为《一个人的精神结构和他的精神资源》,感兴趣的话可以搜索公众号「梁宁-闲花照水录」(ID:cafeday)查看原文。原文末尾有书目推荐,以下为精彩节选。 上个月,陪父母在欧洲旅游了一个月。其间,读了一篇文章,分析伊丽莎白一世与慈禧太后这两个女强人的差别。两位都是执政能力超强的女子,单身主政国家 40 余年。 伊丽莎白一世统治近半世纪,英国成为欧洲最强大的国家之一。英格兰文化也在此期间达到了一个顶峰,涌现出了诸如莎士比亚、弗朗西斯·培根这样的大师。同时英国建设了航海能力,并开始确立了在北美的殖民地。 伊丽莎白一世统治时期,在英国历史上被称为「黄金时代」。 而比伊丽莎白一世晚生 300 年,咱们中国的慈禧,用了一生的手腕与智慧,维持国家的封闭与思想的禁锢。 那篇文章说,两个人的第一个不同,是「精神资源」。 伊丽莎白童年的教师,是英国文艺复兴时期著名人文主义者罗杰·阿斯卡姆,伊丽莎白懂六国语言,她的精神资源中有亚里士多德、凯撒、哥伦布...... 而慈禧的精神资源,是《资治通鉴》,以及戏文比如《挑滑车》、《四郎探母》……这些内容形成了咱们当时最高统治者的世界观与精神结构。 为什么家庭环境对人一生的影响,远大于他在学校里收到的教育?因为,家庭与家教,给了一个孩子影响他一生的做事习惯与精神资源。 有些家长怕影响孩子学习成绩,不许孩子看课外书。但孩子成人之后,一生的所有重要决策,不是基于数学考 90 分还是 60 分,而是从幼年开始,你有意无意提供给他的精神资源。 精神资源将形成他的精神结构。精神结构会主导他一生的好恶感与羞耻心,他的愿望、梦想与恐惧,从而影响他后来所有的决定。 在塞尔维亚到里斯本的路上,博客中国的甜夏让我推荐 5 本书,我微信回了《三体》、《新宋》、《光荣与梦想》、《失恋排行榜》、《对冲基金风云录》。 《三体》的故事,很多朋友几乎都非常熟悉了。 《三体》给了个黑暗的结局,作者大刘的那段描写看得我思绪澎湃。地球上的人类目睹太阳在眼前熄灭。然后站在木星上的地球人,眼睁睁再看着地球被碾轧成一幅画上的一点点蓝色,最后整个太阳系毁灭了。 太阳系毁灭以及地球人基本灭绝的直接原因,是一个叫程心的美女。当时,她拥有人类世界的最高权柄,但她连续两次做出了错误的决策。最后,覆水难收。 女主角「程心」,我觉得像慈禧。 以一个成熟的人揣摩慈禧,她不会是那些传奇故事里被妖魔化的样子。她手下的大臣,有曾国藩、左宗棠、李鸿章、张之洞、袁世凯……这些人每一个如果出现在汉末、唐末、宋末、明末,都可以只手遮天、主导废立,但在慈禧手下数十年,无人起不臣之心。 慈禧的权术与个人魅力可见一般。 程心也拥有倾倒「云天明」与天下选民的魅力。 可是,程心与慈禧,拥有可以左右人心的魅力。但她们并不具备在宇宙生存竞争中,带领一个知识与技术不占优势的种族,劈开红海断腕而出,开辟自己的生存空间的精神结构。 无论程心还是慈禧,共同的精神特点是——「苟安」。 曾和一个 NASA 的职员聊《三体》,他说: 《三体》里程心做出了两个重大且错误的决策:放弃对三体人的威慑,放弃曲率飞船研发。这是因为她的精神世界,只有她当下眼睛可以看到的那么一点点。她只会基于避免让自己小小的精神结构感到痛苦,而做出决策。 而书中地球人,温顺地、麻木地接受了这个必然导致种族灭亡的决策。大家选择了当下的苟安和谐,不去想子孙将被毁灭。 大刘写得出质子七维空间的展开,写得出太阳系毁灭的凄丽。但他写不出,百年后在更高的地球文明里,重大公众事件的决策如何组织和执行。 也许,这也是我们的精神资源,导致了精神结构的整体缺失。
Ruby
UTF-8
2,516
4.0625
4
[]
no_license
class Game @@WORDS = ["hat", "cat", "ate", "run", "eye", "soup", "date", "bake", "wake", "grape", "apple", "pride", "drive", "tacos", "linux", "orange", "purple", "volume", "liquid", "palace", "molasses", "diamond", "sausage", "america", "england", "titties"] @@ALPH = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] @@NUM_OF_LIMBS = 6 @@STATES = { "Guess" => "Guess", "Win" => "Win", "Die" => "Die" } def initialize() @secretWord = @@WORDS[rand(@@WORDS.length())] @secretWordLength = @secretWord.length() @lettersGuessed = { } for i in 0..@secretWordLength - 1 @lettersGuessed[@secretWord[i]] = false end @countOfUnguessedLetters = @lettersGuessed.length(); @numOfGuessesLeft = @@NUM_OF_LIMBS @currentState = @@STATES["Guess"] end def get_game_state return @currentState end def get_letter_guessed puts(@lettersGuessed) end def get_count_of_unguessed_letters return @countOfUnguessedLetters end #guess function def make_guess(letter) if @lettersGuessed[letter] == true puts("You have already guessed this letter") @numOfGuessesLeft -= 1 elsif @lettersGuessed[letter] == false @lettersGuessed[letter] = true puts("You have guessed a letter correct! Congrats!") @countOfUnguessedLetters -= 1 else puts("You guessed the letter incorrectly, try again") @numOfGuessesLeft -= 1 end if @numOfGuessesLeft == 0 @currentState = @@STATES["Die"] elsif @countOfUnguessedLetters == 0 @currentState = @@STATES["Win"] end end #get's current number of guesses def get_num_of_guesses return @numOfGuessesLeft end #gets current state of word def get_current_state_of_word() wordString = "" for i in 0..@secretWordLength-1 do key = @secretWord[i] if @lettersGuessed[key] == true wordString += key elsif @lettersGuessed[key] == false wordString += "_ " end end return wordString end end
Java
UTF-8
5,400
2.03125
2
[]
no_license
package com.barang; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.core.models.barang_model; import com.google.android.material.appbar.AppBarLayout; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.todkars.shimmer.ShimmerRecyclerView; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class AllBarang extends AppCompatActivity { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.appbar) AppBarLayout appbar; @BindView(R.id.tv_deskripsi) TextView tvDeskripsi; @BindView(R.id.shimmer_recycler_semuabarang) ShimmerRecyclerView shimmerRecyclerSemuabarang; private List<barang_model> modelList = new ArrayList<>(); private AdapterBarang adapter; private FirebaseAuth firebaseAuth = FirebaseAuth.getInstance(); private FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); private DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference(); private Context context = AllBarang.this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_all_barang); ButterKnife.bind(this); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Semua Sayuran"); shimmerRecyclerSemuabarang.showShimmer(); Intent intent = getIntent(); if (intent.getExtras() != null) { if (intent.getStringExtra(getResources().getString(R.string.INTENT_PUT_IDKATEGORI)) == null) { getAllBarang(); } else { String idkategori = intent.getStringExtra(getResources().getString(R.string.INTENT_PUT_IDKATEGORI)); getBarangByKategori(idkategori); } } else { getAllBarang(); } } private void getBarangByKategori(String idkategori) { databaseReference .child(getString(R.string.CHILD_BARANG)) .child(getString(R.string.CHILD_BARANG_ALL)) .orderByChild("idkategori") .equalTo(idkategori) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { barang_model model = new barang_model(); modelList.clear(); for (DataSnapshot data : dataSnapshot.getChildren()) { model = data.getValue(barang_model.class); assert model != null; modelList.add(model); } adapter = new AdapterBarang(context, modelList); RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context, 2); shimmerRecyclerSemuabarang.setLayoutManager(layoutManager); shimmerRecyclerSemuabarang.setAdapter(adapter); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void getAllBarang() { databaseReference .child(getString(R.string.CHILD_BARANG)) .child(getString(R.string.CHILD_BARANG_ALL)) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { barang_model model = new barang_model(); modelList.clear(); for (DataSnapshot data : dataSnapshot.getChildren()) { model = data.getValue(barang_model.class); assert model != null; modelList.add(model); } adapter = new AdapterBarang(context, modelList); RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context, 2); shimmerRecyclerSemuabarang.setLayoutManager(layoutManager); shimmerRecyclerSemuabarang.setAdapter(adapter); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }
C#
UTF-8
1,556
2.609375
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Timer : MonoBehaviour { public bool allowUnscaledDeltaTime = false; private float duration; private Status status; private float countingTime; private bool counting; public void SetTimer(float duration) { SetTimer(duration, Timer.Status.IDLE); } public void SetTimer(float duration, Timer.Status startingStatus) { this.duration = duration; this.status = startingStatus; } public Status GetStatus() { return this.status; } public void StartTimer() { status = Status.RUNNING; counting = true; //StartCoroutine(Count()); } public void ResetTimer() { //StopCoroutine(Count()); counting = false; countingTime = 0; status = Status.IDLE; } private IEnumerator Count() { if (allowUnscaledDeltaTime) yield return new WaitForSecondsRealtime(duration); else yield return new WaitForSeconds(duration); status = Status.FINISHED; yield return 0; } private void Update() { if (!counting) return; if (allowUnscaledDeltaTime) countingTime += Time.unscaledDeltaTime; else countingTime += Time.deltaTime; if (countingTime >= duration) { ResetTimer(); status = Status.FINISHED; } } public enum Status { IDLE, RUNNING, FINISHED } }
C++
UTF-8
1,177
3.359375
3
[ "MIT" ]
permissive
#include <iostream> #define MAX_SIZE 101 void merge(int list[], int p, int q, int r) { int i = 0; int j = 0; int n1 = q - p + 1; int n2 = r - q - 1; int L[MAX_SIZE]; int R[MAX_SIZE]; for (i = 0; i < n1; i++) { L[i] = list[p+i]; } for (j = 0; j < n2; j++) { R[j] = list[q+j]; } i = 0; j = 0; for (int k = p; k < r; k++) { if (L[i] <= R[j]) { list[k] = L[i]; i++; } else { list[k] = R[j]; j++; } } } void merge_sort(int list[], int p, int r) { if (p < r) { int q = (p + r) / 2; merge_sort(list, p, q); merge_sort(list, q + 1, r); printf("%d %d %d\n", p, q, r); merge(list, p, q, r); } } int main(void) { int i, n; int list[MAX_SIZE]; printf("Enter the number of numbers to generate: "); scanf("%d", &n); if ( n < 1 || n > MAX_SIZE) { fprintf(stderr, "Improper value of n\n"); exit(-1); } for (i = 0; i < n; i++) { list[i] = rand() % 1000; printf("%d ", list[i]); } printf("\n"); merge_sort(list, 0, n); printf("\nSorted array:\n"); for (i = 0; i < n; i++) printf("%d ", list[i]); printf("\n"); return 0; return 0; }
Java
UTF-8
1,723
3.15625
3
[]
no_license
package leetcode; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class no301 { HashSet<String> set=new HashSet<>(); int len; public List<String> removeInvalidParentheses(String s) { List<String> res=new ArrayList<>(); len=s.length(); int left=0; int right=0; int count=0; while(count<len) { if(s.charAt(count)=='(') left++; else if(s.charAt(count)==')') { if(left==0) right++; else left--; } count++; } dfs(left,right,0,0,0,s,new StringBuilder()); System.out.println(set); return new ArrayList<>(set); } public void dfs(int left,int right,int countl,int countr,int index,String s,StringBuilder path) { if(index==len) { if(left==0&&right==0) set.add(path.toString()); return; } char cur=s.charAt(index); if(cur=='('&&left>0) dfs(left-1,right,countl,countr,index+1,s,path); else if(cur==')'&&right>0) dfs(left,right-1,countl,countr,index+1,s,path); path.append(cur); if(cur=='(') dfs(left,right,countl+1,countr,index+1,s,path); else if(cur!=')') dfs(left,right,countl,countr,index+1,s,path); else if(countl>countr) dfs(left,right,countl,countr+1,index+1,s,path); path.deleteCharAt(path.length()-1); } public static void main(String[] args) { no301 t=new no301(); t.removeInvalidParentheses("()())()"); } }
Java
UTF-8
639
2.953125
3
[]
no_license
package com.leetcode.offer.No61; import java.util.HashSet; /** * @author jtchen * @version 1.0 * @date 2021/2/15 23:47 */ public class Solution3 { public boolean isStraight(int[] nums) { int[] map = new int[13]; int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE; for (int i = 0; i < 5; i++) { if (nums[i] != 0) { if (map[nums[i] - 1] != 0) return false; map[nums[i] - 1]++; min = Math.min(nums[i], min); max = Math.max(nums[i], max); } } return max - min < 5; } }
JavaScript
UTF-8
1,235
2.890625
3
[ "MIT" ]
permissive
/** * Created by Catter on 2016/3/9. */ //(function(){ //js实现hasClass,addClass,removeClass,ToggleClass function hasClass(obj, cName){ return obj.className.match(new RegExp('(\\s|^)' + cName + '(\\s|$)')); } function addClass(obj, cName){ if(!hasClass(obj, cName)){ obj.className = obj.className+" "+cName; } } function removeClass(obj, cName){ if(hasClass(obj, cName)){ var reg = new RegExp('(\\s|^)' + cName + '(\\s|$)'); obj.className = obj.className.replace(reg, ""); } } function ToggleClass(obj, cName){ if(!hasClass(obj, cName)){ addClass(obj, cName); }else{ removeClass(obj, cName); } } (function($){ //字符替换 $(document).ready(function(){ if (!String.prototype.format) { String.prototype.format = function() { var hash = arguments; //console.log(arguments.length); return this.replace(/{(\w+)}/g, function(match, item) { return typeof hash[item] != 'undefined' ? hash[item] : match; }); }; } }); })(jQuery); //})();
Python
UTF-8
949
3.640625
4
[]
no_license
#MENU DE UN RECIEN NACIDO import libreria opc=0 #ocpiones max=3 #maximo de opciones def opcionA(): nom2=libreria.validar_nombre(input("OPCION 1: INGRESE SU NOMBRE PARA QUE PUEDA SUFRAGAR:")) #validad si es un nombre True y sino es False print("el nombre del cliente es:",nom2) print("") def opcionB(): a=libreria.pedir_sexo(input("OPCION 2: INGRESE EL SEXO DEL NIÑO:")) #validad si el sexo del niño es HOMBRE o MUJER print("el sexo del niño es:",a) while (opc !=max): #IMPRECION DE MENU print("######## MENU #########") print("1.NOMBRE: ") print("2.SEXO: ") print("3.SALIR: ") print("#########################") #ELECCION DE LAS OPCIONES opc=libreria.pedir_entero("INGRESE LA OPCION:",1,3) #MAPEO DE OPCIONES if (opc==1): opcionA() if (opc==2): opcionB() #fin_mapeo #fin_menu print("fin del programa")
Markdown
UTF-8
24,893
2.515625
3
[ "BSD-2-Clause" ]
permissive
# 修改、改进 RxGo 包 ## 题目要求 - 阅读 ReactiveX 文档。请在 pmlpml/RxGo 基础上, 1. 修改、改进它的实现 2. 或添加一组新的操作,如 filtering - 该库的基本组成: * rxgo.go 给出了基础类型、抽象定义、框架实现、Debug工具等 * generators.go 给出了 sourceOperater 的通用实现和具体函数实现 * transforms.go 给出了 transOperater 的通用实现和具体函数实现 ## 注意事项 - 本次开发使用环境为linux - api文档使用godoc生成 - 说明文档编辑采用csdn编辑,故图片可能会有水印 - 本次项目参考了老师已给函数的实现形式 - 本次项目参考了原有RxGo和RxJava等包的实现以及部分GitHub和Gitee中的自建包 - 由于老师给的文档里已经有filter函数,故在本项目中不再实现 - 本项目实现如下的八个函数 * Debounce — only emit an item from an Observable if a particular timespan has passed without it emitting another item * Distinct — suppress duplicate items emitted by an Observable * ElementAt — emit only item n emitted by an Observable * First — emit only the first item, or the first item that meets a condition, from an Observable * IgnoreElements — do not emit any items from an Observable but mirror its termination notification * Last — emit only the last item emitted by an Observable * Sample — emit the most recent item emitted by an Observable within periodic time intervals * Skip — suppress the first n items emitted by an Observable * SkipLast — suppress the last n items emitted by an Observable * Take — emit only the first n items emitted by an Observable * TakeLast — emit only the last n items emitted by an Observable ## api文档 api文档见同目录下:api文档.pdf ## 代码分析 ### 变量定义 定义10个变量用来表示将要实现的功能。 - debounce用于记录延迟接受的时间 - distinct用于是否跳过重复 - elementAt用于指定输出特定的位置 - ignoreElement用于是否跳过全部 - first用于是否输出第一个 - last用于是否输出最后一个 - sample用于记录定时接受最近发出的时间 - skip用于记录跳过的个数 - take用于记录获得的个数 - takeOrSkip用于记录是take还是skip ```go debounce time.Duration distinct bool elementAt int ignoreElement bool first bool last bool sample time.Duration skip int take int takeOrSkip bool ``` ### 转换节点实现 模仿老师已给的`transform.go`中的`transOperater`结构体,直接写出我们需要的`filteringOperator`结构体 ```go type filteringOperator struct { opFunc func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) } ``` ### 初始化 初始化函数完全参考老师已给的`transform.go`中的`newTransformObservable`函数,就是一个简单的初始化过程 ```go func (parent *Observable) newFilteringObservable(name string) (o *Observable) { //new Observable o = newObservable() o.Name = name //chain Observables parent.next = o o.pred = parent o.root = parent.root //set options o.buf_len = BufferLen return o } ``` ### filteringTotalOperator 由于将要实现的函数中都是类似的filter操作,故我们定义一个统一的operator进行操作,然后把不同实现在op函数中。 ```go var filteringTotalOperator = filteringOperator{opFunc: func(ctx context.Context, o *Observable, x reflect.Value, out chan interface{}) (end bool) { var params = []reflect.Value{x} x = params[0] if !end { end = o.sendToFlow(ctx, x.Interface(), out) } return }, } ``` ### Debounce ![debounce](https://img-blog.csdnimg.cn/20201108013521325.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjgzMjY1,size_16,color_FFFFFF,t_70) Debounce用于在一个数据发出后的指定延迟后获取它,如果在该延迟时间内有新的数据,则重新计时。我们对`Observable`中的`debounce`变量传入需要延迟的时间,然后将其它我们定义的变量都复位即可。`operator `需要赋值`filteringTotalOperator`也就是刚才定义的变量 ```go func (parent *Observable) Debounce(_debounce time.Duration) (o *Observable) { o = parent.newFilteringObservable("debounce") o.first, o.last, o.ignoreElement, o.distinct = false, false, false, false o.debounce, o.take, o.skip = _debounce, 0, 0 o.operator = filteringTotalOperator return o } ``` ### Distinct ![distinct](https://img-blog.csdnimg.cn/2020110823282113.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjgzMjY1,size_16,color_FFFFFF,t_70) Distinct用于去重,即如果有重复的数据我们就不再对它输出。我们对`Observable`中的`distinct `变量置位,然后将其它我们定义的变量都复位即可。`operator `需要赋值`filteringTotalOperator`也就是刚才定义的变量 ```go func (parent *Observable) Distinct() (o *Observable) { o = parent.newFilteringObservable("distinct") o.ignoreElement, o.first, o.last, o.distinct = false, false, false, true o.debounce, o.take, o.skip = 0, 0, 0 o.operator = filteringTotalOperator return o } ``` ### ElementAt ![elementAt](https://img-blog.csdnimg.cn/20201108232922781.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjgzMjY1,size_16,color_FFFFFF,t_70) ElementAt用于输出第x个数据,x从0计数。我们对`Observable`中的`elementAt`变量赋值指定的数据位置,然后将其它我们定义的变量都复位即可。`operator `需要赋值`filteringTotalOperator`也就是刚才定义的变量 ```go func (parent *Observable) ElementAt(index int) (o *Observable) { o = parent.newFilteringObservable("elementAt") o.first, o.last, o.distinct, o.ignoreElement, o.takeOrSkip = false, false, false, false, false o.debounce, o.skip, o.take, o.elementAt = 0, 0, 0, index o.operator = filteringTotalOperator return } ``` ### First ![first](https://img-blog.csdnimg.cn/20201108233203631.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjgzMjY1,size_16,color_FFFFFF,t_70) First用于输出第1个数据。我们对`Observable`中的`first`变量置位,然后将其它我们定义的变量都复位即可。`operator `需要赋值`filteringTotalOperator`也就是刚才定义的变量 ```go func (parent *Observable) First() (o *Observable) { o = parent.newFilteringObservable("first") o.first, o.last, o.ignoreElement, o.distinct = true, false, false, false o.debounce, o.take, o.skip = 0, 0, 0 o.operator = filteringTotalOperator return o } ``` ### IgnoreElement ![ignoreElement](https://img-blog.csdnimg.cn/20201108234325746.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjgzMjY1,size_16,color_FFFFFF,t_70) IgnoreElement用于忽略全部数据。我们对`Observable`中的`ignoreElement `变量置位,然后将其它我们定义的变量都复位即可。`operator `需要赋值`filteringTotalOperator`也就是刚才定义的变量 ```go func (parent *Observable) IgnoreElement() (o *Observable) { o = parent.newFilteringObservable("ignoreElement") o.first, o.last, o.distinct, o.ignoreElement = false, false, false, true o.debounce, o.take, o.skip = 0, 0, 0 o.operator = filteringTotalOperator return o } ``` ### Last ![Last](https://img-blog.csdnimg.cn/20201109001953356.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjgzMjY1,size_16,color_FFFFFF,t_70) Last用于获取最后一个数据。我们对`Observable`中的`last`变量置位,然后将其它我们定义的变量都复位即可。`operator `需要赋值`filteringTotalOperator`也就是刚才定义的变量 ```go func (parent *Observable) Last() (o *Observable) { o = parent.newFilteringObservable("last") o.first, o.last, o.distinct, o.ignoreElement = false, true, false, false o.debounce, o.take, o.skip = 0, 0, 0 o.operator = filteringTotalOperator return o } ``` ### Sample ![Sample](https://img-blog.csdnimg.cn/20201109002128886.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjgzMjY1,size_16,color_FFFFFF,t_70) Sample在指定时间段内获取最新数据。我们对`Observable`中的`sample `变量赋值指定的时间,然后将其它我们定义的变量都复位即可。`operator `需要赋值`filteringTotalOperator`也就是刚才定义的变量 ```go func (parent *Observable) Sample(_sample time.Duration) (o *Observable) { o = parent.newFilteringObservable("sample") o.first, o.last, o.distinct, o.ignoreElement, o.takeOrSkip = false, false, false, false, false o.debounce, o.skip, o.take, o.elementAt, o.sample = 0, 0, 0, 0, _sample o.operator = filteringTotalOperator return o } ``` ### Skip And SkipLast ![skip](https://img-blog.csdnimg.cn/20201109002631933.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjgzMjY1,size_16,color_FFFFFF,t_70) ![skipLast](https://img-blog.csdnimg.cn/20201109002649281.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjgzMjY1,size_16,color_FFFFFF,t_70) Skip在前面跳过指定的个数的数据。我们对`Observable`中的`skip `变量赋值要跳过的个数,然后将其它我们定义的变量都复位即可。`operator `需要赋值`filteringTotalOperator`也就是刚才定义的变量。 SkipLast同理是指定从最后开始往前跳过的个数。 ```go func (parent *Observable) Skip(num int) (o *Observable) { o = parent.newFilteringObservable("skip") o.first, o.last, o.distinct, o.ignoreElement, o.takeOrSkip = false, false, false, false, false o.debounce, o.take, o.skip = 0, 0, num o.operator = filteringTotalOperator return o } func (parent *Observable) SkipLast(num int) (o *Observable) { o = parent.newFilteringObservable("skipLast") o.first, o.last, o.distinct, o.ignoreElement, o.takeOrSkip = false, false, false, false, false o.debounce, o.take, o.skip = 0, 0, -num o.operator = filteringTotalOperator return o } ``` ### Take And TakeLast ![take](https://img-blog.csdnimg.cn/20201109003100389.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjgzMjY1,size_16,color_FFFFFF,t_70) ![takeLast](https://img-blog.csdnimg.cn/20201109003132675.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjgzMjY1,size_16,color_FFFFFF,t_70) Take在前面取指定的个数的数据。我们对`Observable`中的`take`变量赋值要取的个数,然后将其它我们定义的变量都复位即可。`operator `需要赋值`filteringTotalOperator`也就是刚才定义的变量。 TakeLast同理是指定从最后开始往前要取的个数。 ```go func (parent *Observable) Take(num int) (o *Observable) { o = parent.newFilteringObservable("Take") o.first, o.last, o.distinct, o.ignoreElement, o.takeOrSkip = false, false, false, false, true o.debounce, o.skip, o.take = 0, 0, num o.operator = filteringTotalOperator return o } func (parent *Observable) TakeLast(num int) (o *Observable) { o = parent.newFilteringObservable("takeLast") o.first, o.last, o.distinct, o.ignoreElement, o.takeOrSkip = false, false, false, false, true o.debounce, o.skip, o.take = 0, 0, -num o.operator = filteringTotalOperator return o } ``` ### 操作接口op 首先模仿老师已给的文件进行变量定义,这些变量都是用于输入输出 ```go in := o.pred.outflow out := o.outflow var _out []interface{} var wg sync.WaitGroup ``` 然后我们需要调用一个函数,首先定义临时变量,变量用于计时和记录结束,flag用于记录是否存在(实现distinct) ```go end := false flag := make(map[interface{}]bool) timeStart := time.Now() timeSample := time.Now() ``` 对于输入,我们进行一次遍历,在遍历中首先确定如果结束或跳过全部或时间不符(sample和debounce操作) ```go if end { continue } if o.ignoreElement { continue } if o.sample > 0 && timeSampleFromStart < o.sample { continue } if o.debounce > time.Duration(0) && timeFromStart < o.debounce { continue } ``` 与其它op类似,我们在这也要进行错误匹配,并将其输出到字节流 ```go xv := reflect.ValueOf(x) // send an error to stream if the flip not accept error if e, ok := x.(error); ok && !o.flip_accept_error { o.sendToFlow(ctx, e, out) continue } ``` 下面对剩下的操作进行判断 ```go if o.elementAt > 0 || o.take != 0 || o.skip != 0 || o.last || (o.distinct && flag[xv.Interface()]) { continue } ``` 为了实现`distinct`,需要将当前的元素的`flag`标记为`true` ```go flag[xv.Interface()] = true ``` 下面是一个线程管理,除了需要在`ThreadingDefault`中处理一下`sample`的时间计数之外,其余可以完全参考老师`transform`功能包中的`op`函数的处理 ```go switch threading := o.threading; threading { case ThreadingDefault: if o.sample > 0 { timeSample = timeSample.Add(o.sample) } if fop.opFunc(ctx, o, xv, out) { end = true } case ThreadingIO: fallthrough case ThreadingComputing: wg.Add(1) go func() { defer wg.Done() if fop.opFunc(ctx, o, xv, out) { end = true } }() ``` 下面进行`first`和`last`的处理。`first`处理直接`break`即可,因为第一次运行到这里的就是第一个数据,我们需要的数据已经拿到,就不再需要往下进行遍历了。last则是处理当不是第一个的时候直接用`fop.opFunc(ctx, o, xv, out)`处理 ```go if o.first { break } } if o.last && len(_out) > 0 { wg.Add(1) go func() { defer wg.Done() xv := reflect.ValueOf(_out[len(_out)-1]) fop.opFunc(ctx, o, xv, out) }() } ``` 下面处理take和skip,首先利用`take`和`skip`不为0和`takeOrSkip`的值共同确定是什么操作。首先获得要处理的步长step ```go var step int if o.takeOrSkip { step = o.take } else { step = o.skip } ``` 如果是take或skiplast操作,本质是一样的,都是忽略了后面的几个,故在一起处理 ```go if (o.takeOrSkip && step > 0) || (!o.takeOrSkip && step < 0) { if !o.takeOrSkip { step = len(_out) + step } if step >= len(_out) || step <= 0 { newIn, err = nil, errors.New("OutOfBound") } else { newIn, err = _out[:step], nil } ``` 如果是takelast或skip操作,本质是一样的,都是忽略了前面的几个,故在一起处理 ```go if (o.takeOrSkip && step < 0) || (!o.takeOrSkip && step > 0) { if o.takeOrSkip { step = len(_out) + step } if step >= len(_out) || step <= 0 { newIn, err = nil, errors.New("OutOfBound") } ``` 最后写入即可 ```go if err != nil { o.sendToFlow(ctx, err, out) } else { xv := newIn for _, val := range xv { fop.opFunc(ctx, o, reflect.ValueOf(val), out) } } ``` 最后处理取特定位置的`elementAt`,这里只需要取`_out[o.elementAt-1])`位即可 ```go if o.elementAt != 0 { if o.elementAt < 0 || o.elementAt > len(_out) { o.sendToFlow(ctx, errors.New("OutOfBound"), out) } else { xv := reflect.ValueOf(_out[o.elementAt-1]) fop.opFunc(ctx, o, xv, out) } } ``` 以上就是op的大概过程(部分不太重要的细节因篇幅问题没有展示) ## 测试部分 ### 单元测试 单元测试部分针对每个函数进行了测试,我们仿照老师给出的测试格式,来编写自己的测试文件。 #### TestDebounce 使用100s进行测试,由于时间很长,所以返回的应该是空。 ```go func TestDebounce(t *testing.T) { res := []int{} ob := rxgo.Just(0, 1, 2, 3, 4, 5).Map(func(x int) int { return x }).Debounce(100 * time.Millisecond) ob.Subscribe(func(x int) { res = append(res, x) }) assert.Equal(t, []int{}, res, "Debounce Test Error!") } ``` 测试结果: ![TestDebounce](https://img-blog.csdnimg.cn/20201109195248225.png) #### TestDistinct 用一串有重复的数字对其进行测试,看其是否能达到去重的效果 ```go func TestDistinct(t *testing.T) { res := []int{} ob := rxgo.Just(0, 1, 2, 3, 4, 5, 3, 4, 5, 6).Map(func(x int) int { return x }).Distinct() ob.Subscribe(func(x int) { res = append(res, x) }) assert.Equal(t, []int{0, 1, 2, 3, 4, 5, 6}, res, "Distinct Test Error!") } ``` 测试结果: ![TestDistinct](https://img-blog.csdnimg.cn/20201109195532651.png) #### TestElementAt 用返回第五个数即4进行测试`ElementAt`是否能争取取值 ```go func TestElementAt(t *testing.T) { res := []int{} ob := rxgo.Just(0, 1, 2, 3, 4, 5).Map(func(x int) int { return x }).ElementAt(5) ob.Subscribe(func(x int) { res = append(res, x) }) assert.Equal(t, []int{4}, res, "ElementAt Test Error!") } ``` 测试结果: ![TestElementAt](https://img-blog.csdnimg.cn/20201109195733919.png) #### TestIgnoreElement 看是否返回空来测试该函数的正确性 ```go func TestIgnoreElement(t *testing.T) { res := []int{} ob := rxgo.Just(0, 1, 2, 3, 4, 5).Map(func(x int) int { return x }).IgnoreElement() ob.Subscribe(func(x int) { res = append(res, x) }) assert.Equal(t, []int{}, res, "IgnoreElement Test Error!") } ``` 测试结果: ![TestIgnoreElement](https://img-blog.csdnimg.cn/20201109195847482.png) #### TestFirst 输入一组数据看返回的是不是第一个数据 ```go func TestFirst(t *testing.T) { res := []int{} ob := rxgo.Just(0, 1, 2, 3, 4, 5).Map(func(x int) int { return x }).First() ob.Subscribe(func(x int) { res = append(res, x) }) assert.Equal(t, []int{0}, res, "First Test Error!") } ``` 测试结果: ![TestFirst](https://img-blog.csdnimg.cn/20201109201629872.png) #### TestLast 与First同理,输入一组数据看返回的是不是最后一个数据 ```go func TestLast(t *testing.T) { res := []int{} ob := rxgo.Just(0, 1, 2, 3, 4, 5).Map(func(x int) int { return x }).Last() ob.Subscribe(func(x int) { res = append(res, x) }) assert.Equal(t, []int{5}, res, "Last Test Error!") } ``` 测试结果: ![TestLast](https://img-blog.csdnimg.cn/20201109201758189.png) #### TestSample 用很大的时间段来对Sample测试,看其是否返回空 ```go func TestSample(t *testing.T) { res := []int{} rxgo.Just(0, 1, 2, 3, 4, 5).Map(func(x int) int { time.Sleep(2 * time.Millisecond) return x }).Sample(20* time.Millisecond).Subscribe(func(x int) { res = append(res, x) }) assert.Equal(t, []int{}, res, "SkipLast Test Error!") } ``` 测试结果: ![TestSample](https://img-blog.csdnimg.cn/20201109202152119.png) #### TestSkip 用一组数据跳过前两个来测试结果是否正确 ```go func TestSkip(t *testing.T) { res := []int{} ob := rxgo.Just(0, 1, 2, 3, 4, 5).Map(func(x int) int { return x }).Skip(2) ob.Subscribe(func(x int) { res = append(res, x) }) assert.Equal(t, []int{2, 3, 4, 5}, res, "Skip Test Error!") } ``` 测试结果: ![TestSkip](https://img-blog.csdnimg.cn/20201109202341298.png) #### TestSkipLast 用一组数据跳过最后三个来测试结果是否正确 ```go func TestSkipLast(t *testing.T) { res := []int{} ob := rxgo.Just(0, 1, 2, 3, 4, 5).Map(func(x int) int { return x }).SkipLast(3) ob.Subscribe(func(x int) { res = append(res, x) }) assert.Equal(t, []int{0, 1, 2}, res, "SkipLast Test Error!") } ``` 测试结果: ![TestSkipLast](https://img-blog.csdnimg.cn/20201109202435399.png) #### TestTake 用一组数据取出前两个来测试结果是否正确 ```go func TestTake(t *testing.T) { res := []int{} ob := rxgo.Just(0, 1, 2, 3, 4, 5).Map(func(x int) int { return x }).Take(2) ob.Subscribe(func(x int) { res = append(res, x) }) assert.Equal(t, []int{0, 1}, res, "Take Test Error!") } ``` 测试结果: ![TestTake](https://img-blog.csdnimg.cn/20201109202601286.png) #### TestTakeLast 用一组数据取出最后三个来测试结果是否正确 ```go func TestTakeLast(t *testing.T) { res := []int{} ob := rxgo.Just(0, 1, 2, 3, 4, 5).Map(func(x int) int { return x }).TakeLast(3) ob.Subscribe(func(x int) { res = append(res, x) }) assert.Equal(t, []int{3, 4, 5}, res, "TakeLast Test Error!") } ``` 测试结果: ![TestTakeLast](https://img-blog.csdnimg.cn/20201109202700170.png#pic_center) #### 文件测试结果 执行整个测试文件,结果如下: ![filetest](https://img-blog.csdnimg.cn/2020110920281173.png#pic_center) #### 包测试结果 执行整个测试文件包,结果如下: ![packagetest](https://img-blog.csdnimg.cn/2020110920291132.png#pic_center) 可以看出达到了85%的代码覆盖率,这是因为老师已给文件中一些异常处理以及自己编写的代码中的异常处理部分无法完全覆盖,其余部分都已经覆盖测试。 ### 功能测试(使用案例) 使用一个简单的main函数对所有的功能进行测试,代码如下: ```go package main import ( "fmt" "time" rxgo "github.com/yilin0041/service-computing/rxgo" ) func main() { fmt.Println("测试数据:0,1,2,3,4,5,3,4,5") res := []int{} ob := rxgo.Just(0, 1, 2, 3, 4, 5, 3, 4, 5).Map(func(x int) int { return x }).Debounce(999999) ob.Subscribe(func(x int) { res = append(res, x) }) fmt.Print("Debounce(999999): ") for _, val := range res { fmt.Print(val, " ") } fmt.Print("\n") res = []int{} ob = rxgo.Just(0, 1, 2, 3, 4, 5, 3, 4, 5).Map(func(x int) int { return x }).Distinct() ob.Subscribe(func(x int) { res = append(res, x) }) fmt.Print("Distinct(): ") for _, val := range res { fmt.Print(val, " ") } fmt.Print("\n") res = []int{} ob = rxgo.Just(0, 1, 2, 3, 4, 5, 3, 4, 5).Map(func(x int) int { return x }).ElementAt(5) ob.Subscribe(func(x int) { res = append(res, x) }) fmt.Print("ElementAt(5): ") for _, val := range res { fmt.Print(val, " ") } fmt.Print("\n") res = []int{} ob = rxgo.Just(0, 1, 2, 3, 4, 5, 3, 4, 5).Map(func(x int) int { return x }).First() ob.Subscribe(func(x int) { res = append(res, x) }) fmt.Print("First(): ") for _, val := range res { fmt.Print(val, " ") } fmt.Print("\n") res = []int{} ob = rxgo.Just(0, 1, 2, 3, 4, 5, 3, 4, 5).Map(func(x int) int { return x }).Last() ob.Subscribe(func(x int) { res = append(res, x) }) fmt.Print("Last(): ") for _, val := range res { fmt.Print(val, " ") } fmt.Print("\n") res = []int{} rxgo.Just(0, 1, 2, 3, 4, 5, 3, 4, 5).Map(func(x int) int { time.Sleep(4 * time.Millisecond) return x }).Sample(40 * time.Millisecond).Subscribe(func(x int) { res = append(res, x) }) fmt.Print("Sample(40): (sleep (4))") for _, val := range res { fmt.Print(val, " ") } fmt.Print("\n") res = []int{} ob = rxgo.Just(0, 1, 2, 3, 4, 5, 3, 4, 5).Map(func(x int) int { return x }).Skip(4) ob.Subscribe(func(x int) { res = append(res, x) }) fmt.Print("Skip(4): ") for _, val := range res { fmt.Print(val, " ") } fmt.Print("\n") res = []int{} ob = rxgo.Just(0, 1, 2, 3, 4, 5, 3, 4, 5).Map(func(x int) int { return x }).SkipLast(2) ob.Subscribe(func(x int) { res = append(res, x) }) fmt.Print("SkipLast(2): ") for _, val := range res { fmt.Print(val, " ") } fmt.Print("\n") res = []int{} ob = rxgo.Just(0, 1, 2, 3, 4, 5, 3, 4, 5).Map(func(x int) int { return x }).Take(4) ob.Subscribe(func(x int) { res = append(res, x) }) fmt.Print("Take(4) :") for _, val := range res { fmt.Print(val, " ") } fmt.Print("\n") res = []int{} ob = rxgo.Just(0, 1, 2, 3, 4, 5, 3, 4, 5).Map(func(x int) int { return x }).TakeLast(2) ob.Subscribe(func(x int) { res = append(res, x) }) fmt.Print("TakeLast(2): ") for _, val := range res { fmt.Print(val, " ") } fmt.Print("\n") } ``` 测试结果如下: ![maintest](https://img-blog.csdnimg.cn/20201109214046998.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjgzMjY1,size_16,color_FFFFFF,t_70) 经验证,符合要求,测试成功。 ## 总结 本次实验是一个包完善的实验,通过老师已经写好的包,来写一个新的功能文件。其实参考老师已经给出的文件,我们就可以知道写函数的大体格式,然后参考网上已有的代码和要实现函数的逻辑就可以具体进行实现了。 通过本次实验,让我更好的理解了线程的使用以及并发的设计思维与模式,会让以后的编程工作有更多的选择
Java
UTF-8
1,702
2.375
2
[ "MIT" ]
permissive
package com.dim.cls.model; import com.dim.cls.util.BilCycleTypes; public class Subject { private String name; private int grade; private int charge; private int discount; private int discountPercentage; private BilCycleTypes bilCycleType; private int admissionFee; private int admissionDiscount; private int admissionDiscountPercentage; public int getDiscountPercentage() { return discountPercentage; } public void setDiscountPercentage(int discountPercentage) { this.discountPercentage = discountPercentage; } public int getAdmissionFee() { return admissionFee; } public void setAdmissionFee(int admissionFee) { this.admissionFee = admissionFee; } public int getAdmissionDiscount() { return admissionDiscount; } public void setAdmissionDiscount(int admissionDiscount) { this.admissionDiscount = admissionDiscount; } public int getAdmissionDiscountPercentage() { return admissionDiscountPercentage; } public void setAdmissionDiscountPercentage(int admissionDiscountPercentage) { this.admissionDiscountPercentage = admissionDiscountPercentage; } public int getCharge() { return charge; } public void setCharge(int charge) { this.charge = charge; } public int getDiscount() { return discount; } public void setDiscount(int discount) { this.discount = discount; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } public BilCycleTypes getBilCycleType() { return bilCycleType; } public void setBilCycleType(BilCycleTypes bilCycleType) { this.bilCycleType = bilCycleType; } }
Java
UTF-8
9,774
1.953125
2
[]
no_license
package com.woniu.car.message.web.service.impl; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.woniu.car.commons.web.util.BeanCopyUtil; import com.woniu.car.message.model.dto.StationCommentDto; import com.woniu.car.message.model.feign.CommentPageParam; import com.woniu.car.message.model.param.StationCommentParam; import com.woniu.car.message.model.param.StationTagNameLookCommentParam; import com.woniu.car.message.web.domain.CommentTagConnection; import com.woniu.car.message.web.domain.StationComment; import com.woniu.car.message.web.domain.Tag; import com.woniu.car.message.web.mapper.CommentTagConnectionMapper; import com.woniu.car.message.web.mapper.StationCommentMapper; import com.woniu.car.message.web.mapper.TagMapper; import com.woniu.car.message.web.service.StationCommentService; import com.woniu.car.message.web.util.MessageFileUpload; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.ObjectUtils; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; /** * <p> * 电站评论 服务实现类 * </p> * * @author zyy * @since 2021-04-05 */ @Service @Transactional @Slf4j public class StationCommentServiceImpl extends ServiceImpl<StationCommentMapper, StationComment> implements StationCommentService { @Resource private MessageFileUpload messageFileUpload; @Resource private CommentTagConnectionMapper commentTagConnectionMapper; @Resource private StationCommentMapper stationCommentMapper; @Resource private TagMapper tagMapper; @Override public Boolean addStationComment(StationCommentParam param) { if (!ObjectUtils.isEmpty(param)){ param.setCommentTime(new Date().getTime()); MultipartFile[] file = param.getFile(); ArrayList<String> uploads = messageFileUpload.upload(file); JSONObject jsonObject = new JSONObject(); if (uploads.size()==0) { System.out.println("没有上传车站评价图片!!!"); }else{ uploads.forEach(upload->{ jsonObject.put("ST"+ UUID.randomUUID().toString(),upload); }); } String commentImages = JSONObject.toJSONString(jsonObject); StationComment stationComment = BeanCopyUtil.copyOne(param, StationComment::new); stationComment.setCommentImage(commentImages); String comment="ST"+UUID.randomUUID().toString(); stationComment.setCommentStcode(comment); int insert = stationCommentMapper.insert(stationComment); if (insert>0){ //修改Tag表的全部评论的数量 Tag tag = tagMapper.selectById(1); tag.setTagNum(tag.getTagNum()+1); tagMapper.updateById(tag); //自动增加在标签联系表内容 CommentTagConnection tagConnection = new CommentTagConnection(); tagConnection.setTagId(1); tagConnection.setCommentCode(comment); commentTagConnectionMapper.insert(tagConnection); return true; } } return false; } @Override public Boolean deleteStationComment(String commentStCode) { QueryWrapper<CommentTagConnection> wrapper = new QueryWrapper<>(); wrapper.eq("comment_code",commentStCode); List<CommentTagConnection> commentTagConnections = commentTagConnectionMapper.selectList(wrapper); if(!ObjectUtils.isEmpty(commentTagConnections)){ commentTagConnections.forEach(commentTagConnection -> { QueryWrapper<Tag> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("tag_id",commentTagConnection.getTagId()); Tag tag = tagMapper.selectOne(queryWrapper); if(!ObjectUtils.isEmpty(tag)){ tag.setTagNum(tag.getTagNum()-1); tagMapper.updateById(tag); } }); } commentTagConnectionMapper.delete(wrapper); QueryWrapper<StationComment> wrapper1 = new QueryWrapper<>(); wrapper1.eq("comment_stcode",commentStCode); int i = stationCommentMapper.delete(wrapper1); if (i>0){ return true; } return false; } /** * @Author Lints * @Date 2021/4/7/007 13:26 * @Description 此方法是为了返回相同的商品评论相关分页信息 * @Param [pageParam, page, wrapper] * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.woniu.car.message.model.dto.ProductCommentDto> * @Since version-1.0 */ private List<StationCommentDto> getSameResult(List<StationComment> productComments){ List<StationCommentDto> stationCommentDtos = BeanCopyUtil.copyList(productComments, StationCommentDto::new); for (int i=0;i<productComments.size();i++){ JSONObject jsonObject = JSONObject.parseObject(productComments.get(i).getCommentImage()); stationCommentDtos.get(i).setCommentImages(jsonObject); stationCommentDtos.get(i).setCommentTimes(new Date(stationCommentDtos.get(i).getCommentTime())); } return stationCommentDtos; } @Override public List<StationCommentDto> lookUserStationComments(Integer userId) { QueryWrapper<StationComment> queryWrapper = new QueryWrapper<>(); if(!ObjectUtils.isEmpty(userId)){ queryWrapper.eq("comment_user_id",userId); } List<StationComment> stationComments = stationCommentMapper.selectList(queryWrapper); return getSameResult(stationComments); } @Override public List<StationCommentDto> lookSomeStationCommentssByPowerCode(Integer powerId) { QueryWrapper<StationComment> wrapper = new QueryWrapper<>(); if(!ObjectUtils.isEmpty(powerId)){ wrapper.eq("comment_power_code",powerId); } List<StationComment> serviceComments = stationCommentMapper.selectList(wrapper); return getSameResult(serviceComments); } /** * list查询根据标签查询该电站的所有评论 * @param tagName * @return */ @Override public List<StationCommentDto> lookAllStationCommentsByTagName(StationTagNameLookCommentParam tagName) { log.info("根据参数{}查询整个标签内容",tagName); QueryWrapper<Tag> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("tag_name",tagName.getTagName()); Tag tag = tagMapper.selectOne(queryWrapper); if(ObjectUtils.isEmpty(tag)){ return null; } log.info("根据标签内容的id:{}去查询评论编码",tag.getTagId()); QueryWrapper<CommentTagConnection> queryWrapper1 = new QueryWrapper<>(); queryWrapper1.eq("tag_id",tag.getTagId()); List<CommentTagConnection> commentTagConnections = commentTagConnectionMapper.selectList(queryWrapper1); if(!ObjectUtils.isEmpty(commentTagConnections)){ QueryWrapper<StationComment> queryWrapper2 = new QueryWrapper<>(); //删选出只有商品的评论编号 List<String> productCodes=new ArrayList<>(); commentTagConnections.forEach(commentTagConnection -> { if("ST".equals(commentTagConnection.getCommentCode().substring(0,2))){ productCodes.add(commentTagConnection.getCommentCode()); } }); for(int i=0;i<productCodes.size();i++){ queryWrapper2.or().eq("comment_stcode",productCodes.get(i)); } queryWrapper2.eq("comment_power_code",tagName.getCommentPowerCode()); List<StationComment> productComments = stationCommentMapper.selectList(queryWrapper2); return getSameResult(productComments); } return null; } @Override public IPage<StationCommentDto> lookSomeStationCommentsByPowerCode(CommentPageParam pageParam) { Page<StationComment> page = new Page<>(pageParam.getCurrent(), pageParam.getSize()); QueryWrapper<StationComment> wrapper = new QueryWrapper<>(); if(!ObjectUtils.isEmpty(pageParam.getId())){ wrapper.eq("comment_power_code",pageParam.getId()); } Page<StationComment> serviceCommentPage = stationCommentMapper.selectPage(page, wrapper); IPage<StationCommentDto> serviceCommentDtos=new Page<>(pageParam.getCurrent(), pageParam.getSize()); serviceCommentDtos.setTotal(serviceCommentPage.getTotal()); serviceCommentDtos.setPages(serviceCommentPage.getPages()); List<StationCommentDto> serviceCommentDtosList = BeanCopyUtil.copyList(serviceCommentPage.getRecords(), StationCommentDto::new); for (int i=0;i<serviceCommentPage.getRecords().size();i++){ JSONObject jsonObject = JSONObject.parseObject(serviceCommentPage.getRecords().get(i).getCommentImage()); serviceCommentDtosList.get(i).setCommentImages(jsonObject); serviceCommentDtosList.get(i).setCommentTimes(new Date(serviceCommentDtosList.get(i).getCommentTime())); } serviceCommentDtos.setRecords(serviceCommentDtosList); return serviceCommentDtos; } }
Java
UTF-8
452
1.703125
2
[]
no_license
package com.awscourse.filesmanagementsystem.api.file; import com.awscourse.filesmanagementsystem.api.label.LabelSuggestionDTO; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.net.URI; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor public class FileUploadResponseDTO { private String filename; private URI url; private List<LabelSuggestionDTO> calculatedLabels; }
Java
UTF-8
169
2.75
3
[]
no_license
public abstract class Car { private double price; private String model; private String year; public abstract void goUphill(); public abstract void goFast(); }
JavaScript
ISO-8859-1
11,347
2.671875
3
[ "MIT" ]
permissive
/** * Funciones de busqueda javascript * */ function searchArtist( artista ){ //alert("Buscando artista "+artista); artista=replaceAll(artista,' ','+'); $('#searchGif').show(); $('#searchresults').html(''); $('#searchresults').load('searchArtist.do?artist='+artista, function() { $('#searchGif').hide(); // alert('Load was performed.'); //$('#tabs').tabs('select', 0); }); //busqueda en los videos de youtube youtubeSearch(artista); } //variable para contar los albumes del artista y saber cuando se han recogido todos var gets=0; var numalbumes=0; var imgArtist=""; var artist=""; function searchArtist2( artista ){ closeSuggestions(); //alert("Buscando artista "+artista); artista=replaceAll(artista,' ','+'); $('#searchGif').show(); $.getJSON("searchArtistHeader.do?artist="+artista, function(data) { var test=data; //actualiza la informacin del artista en la pagina $('#searchresults').load('music/searchArtist2.jsp', function() { $('#imgArtist').attr("src",test.imageURL); var elname=replaceAll(unescape(test.name),'+',' '); $('#nameArtist').text(elname); var summary=decodeURIComponent(test.summary); summary=replaceAll(summary,'+',' '); $('#descArtist').html((summary)); imgArtist=test.imageURL; artist=test.name; //artistas similares var similares=test.similares; var htmlSimilares="<h3>Artistas Similares</h3>"; for(var i=0;i<similares.length-1;i++){ //alert(similares[i].name); var artistaSimilar=replaceAll(similares[i].name,'+',' '); htmlSimilares+=" <a href='#' style='color:black' onclick='searchArtist2(\""+escape(decodeURIComponent(similares[i].name))+"\")'>"+decodeURIComponent(artistaSimilar)+"</a> "; } $('#similaresArts').html((htmlSimilares)); $('#searchGif').hide(); }); var album=test.albums; var albumes=new Array(); //console.debug("gets inicial: "+gets); //ponemos el numero de albumes del artista a 0 gets=0; //obtiene las canciones de los albumes numalbumes=album.length; $('#searchGif').show(); for (var x = 0 ; x < album.length ; x++) { //console.debug("album: "+album[x].name); $.getJSON("getAlbumArtista.do?artist="+artista+"&album="+album[x].name, function(data) { //actualiza los albumes en la pagina del artista albumes.push(data); //console.debug(albumes); actualizarAlbumesArtista(data); }) .error(function() {actualizarAlbumesArtistaError(); }); } $('#searchGif').hide(); showMusica(); }); //busqueda en los videos de youtube youtubeSearch(artista); } //saca los albumes del artista por pantalla function actualizarAlbumesArtista(album){ //alert("eeee --> "+album.artista); var tracks=album.tracks; gets++; //console.debug("gets1 x: "+gets); //ponemos para que pare la barra de progreso faltando 5 albumes //por si acaso fallan algunos... if(gets>=numalbumes-5){ //console.debug("gets total x: "+gets); $('#searchGif').hide(); } //solo mostramos el disco si lleva alguna cancion if(tracks.length>=0) { //codigo html del album var html=""+album.name+"<br />"; //----------------------------------- //sacamos el ao de releaseDate: //formato: Jun 5, 2007 12:00:00 AM var releaseDate=""; if (typeof album.releaseDate == "undefined"){ //console.debug(album.name+ "NO Existe fecha"); }else{ //console.debug(album.name +"Existe fecha"); var fragmentos = album.releaseDate.split(','); var fragmentos2=fragmentos[1].split(' '); //console.debug('fecha: '+fragmentos2[1]); releaseDate="("+fragmentos2[1]+")"; } //si el album viene sin imagen ponemos la del artista! var img=album.urlImage; //console.debug("imagen: "+img); if (typeof album.urlImage == "undefined" || album.urlImage=="" ){ img=imgArtist; } //ponemos el nombre del album para que se muestre correctamente var albunname=album.name; albunname=unescape(albunname); albunname=replaceAll(albunname,'+',' '); var html2_1=""; //aqu tomamos las canciones del album //------------------------------------- if(tracks.length>0){ html2_1="<table cellspacing='10px' class='testTable' width='100%' border='0' bordercolor='green'>" + "<tr>" + " <td align='left' valign='top' width='10%'>" + " <a href='#' class='linkNoDecore' style='cursor: default' class='menuAlbums' id='"+album.name+"_"+artist+"' ondblclick='searchAlbum(\""+unescape(artist)+"\",\""+album.name+"\")'><img src='"+img+"' /></a>" +"</td>" +"<td align='left' valign='top'>" +"<strong><a href='#' class='linkNoDecore' onclick='searchAlbum(\""+artist+"\",\""+album.name+"\")'>"+albunname+"</a></strong> "+releaseDate +"<br/><div></div><br/><br/>" +"<table class='album_artista' cellspacing='0' width='100%' border='0' bordercolor='red'>" +"<tbody>"; for (var x = 0 ; x < tracks.length ; x++) { var style=''; if ( x % 2 == 0 ) { /* even row: add class="even" */ style='odd'; } var nombre=unescape(tracks[x].name); var elartista=unescape(album.artist); elartista=replaceAll(elartista,'+',' '); nombre=replaceAll(nombre,'+',' '); //alert("elartista: "+tracks[x].artist); var artista=unescape(tracks[x].artist); artista=replaceAll(artista,'+',' '); var albumnombre=unescape(tracks[x].album); albumnombre=replaceAll(albumnombre,'+',' '); html2_1 = html2_1+" <tr class='menuc' id='"+tracks[x].name+"_"+tracks[x].name+"_"+tracks[x].artist+"_"+tracks[x].album+"_"+tracks[x].duration+"' ondblclick='reproducirAlbumEnCola(\""+tracks[x].id+"\",\""+tracks[x].id+"\",\""+escape(tracks[x].name)+"\",\""+album.artist+"\",\""+escape(albumnombre)+"\",\""+tracks[x].duration+"\");'>" +"<td class='"+style+"' align='left'><a href='#' class='linkNoDecore' style='text-decoration: none;cursor: default;font-weight:normal' >"+nombre+"</a></td>" +"<td class='"+style+"'>&nbsp;</td>" +"<td class='"+style+"' align='left'><a href='#' class='linkNoDecore' style='text-decoration: none;cursor: default;font-weight:normal' onclick='searchArtist();'>"+elartista+"</a></td>" +"<td class='"+style+"'>&nbsp;</td>" +"<td class='"+style+"' align='left'><a href='#' class='linkNoDecore' style='text-decoration: none;cursor: default;font-weight:normal' onclick='searchAlbum();'>"+albumnombre+"</a></td>" +"<td class='"+style+"'>&nbsp;</td>" +"<td class='"+style+"' align='left'><a href='#' class='linkNoDecore' style='text-decoration: none;cursor: default;font-weight:normal'>"+segundos_a_minutos(tracks[x].duration)+"</a></td>" +"</tr>"; } } else{ //html2_1 = html2_1+"<tr><td colspan='4'>No se encontraron canciones</td></tr>"; } //-------------------------------------- var html2_2="</tbody>" +"</td>" +"</tr>" +"</table><br/><br/>"; //----------------------------------- $('.menuc').draggable({ revert: true , cursor: "move", opacity: 0.99, zIndex: 9999999999999, helper: function(event, ui) { var id=$(this).attr('id'); var params=id.split("_"); var cancion=params[1]; var artista=params[2]; cancion=replaceAll(cancion,"+"," "); artista=replaceAll(artista,"+"," "); var foo = $('<span style="white-space:nowrap;border:1px solid #000;background-color: #FFFAF0; color:black; padding-left:5px;padding-right:5px;font-size: 10pt "></span>').text(" "+cancion + " de " + artista+ " "); return foo; } }); $('#ArtistAlbums').append(html2_1); $('#ArtistAlbums').append(html2_2); } } //se produce un error al buscar el album del artista function actualizarAlbumesArtistaError(){ gets++; // console.debug("gets2 x: "+gets); if(gets>=numalbumes-5){ //console.debug("gets total x: "+gets); $('#searchGif').hide(); } } function searchAlbum( artista, album ){ closeSuggestions(); //alert('searchAlbum.do?artist='+artista+'&album='+album); artista=replaceAll(artista,' ','+'); album=replaceAll(album,' ','+'); $('#searchGif').show(); $('#searchresults').load('searchAlbum.do?artist='+artista+'&album='+album, function() { //alert('Load was performed.'); $('#searchGif').hide(); //muestra la pestaa //showAlbums(); showMusica(); }); //busqueda en los videos de youtube youtubeSearch(artista+"+"+album); } //FIXME Esta funcin no hace nada ahora mismo, solo es una copia de la de arriba para //hacer el menu secundario en la pagina de albums function searchAlbum2( artista, album ){ closeSuggestions(); //alert('searchAlbum.do?artist='+artista+'&album='+album); artista=replaceAll(artista,' ','+'); album=replaceAll(album,' ','+'); $('#searchGif').show(); $('#div_tab_albums').load('searchAlbum.do?artist='+artista+'&album='+album, function() { // alert('Load was performed.'); $('#searchGif').hide(); //muestra la pestaa showAlbums(); }); //busqueda en los videos de youtube youtubeSearch(artista+"+"+album); } function getTrackInfo(cancion, artista){ //alert('1'); var trackInfo={"id":"182354617","nombre":"A+Milli","album":"A+Milli","artista":"Lil%27+Wayne","duracion":"223"}; //alert("id: "+trackInfo.artista); $.getJSON('getTrackInfo.do?cancion='+cancion+"&artista="+artista, function(data) { var test=data; //alert("artista: "+test.artista); reproducirCancionEnCola(test.id,test.nombre,test.artista,test.album,test.duracion); }); } function getTrackInfo2(cancion, artista){ //alert('2'); var trackInfo={"id":"182354617","nombre":"A+Milli","album":"A+Milli","artista":"Lil%27+Wayne","duracion":"223"}; //alert("id: "+trackInfo.artista); $.getJSON('getTrackInfo.do?cancion='+cancion+"&artista="+artista, function(data) { var test=data; //alert("artista: "+test.artista); // reproducirCancionEnCola(test.id,test.nombre,test.artista,test.album,test.duracion); anadirCancionEnCola(test.id,test.nombre,test.artista,test.album,test.duracion); }); } function youtubeSearch(query){ var tamanyoPantalla=TamVentana(); // alert('buscando en youtube... '+query); $('#youtubeResults').load('youtubeSearch.do?q='+query+'&tamPantalla='+tamanyoPantalla[0], function() { $("#searchVideos").hide(); }); }
Markdown
UTF-8
4,035
2.8125
3
[]
no_license
## 文档 #### Base64 - [v2.0.0] 字符串base64编码 `yutil.Base64.Encode(data string) string` - [v2.0.0] 对象进行base64编码 `yutil.Base64.Encode4Obj(data interface{}) string` - [v2.0.0] base64字符串解码 `yutil.Base64.Decode(data string) string` - [v2.0.0] base64字符串反序列化对象 `yutil.Base64.Decode2Obj(data string,v interface{})` #### Md5 - [v2.0.0] md5加密 `yutil.Md5.Encode(data string) string` - [v2.0.0] md5 加密附带盐值 `yutil.Md5.EncodeWithSalt(data, salt string) string` #### Sha1 - [v2.0.0] sha1加密 `yutil.Sha1.Encode(data string) string` - [v2.0.0] sha1 加密附带盐值 `yutil.Sha1.EncodeWithSalt(data, salt string) string` #### Json - [v2.0.0] 将对象转成json字符串 `yutil.Json.Marshal(v interface{}) string` - [v2.0.0] 将字符串反序列化为对象 `yutil.Json.Unmarshal(s string,v interface{})` #### Regexp - [v2.0.0] 正则切割字符串 `yutil.Regexp.SplitAll(s, pattern string) []string` - [v2.0.0] 正则替换字符串 `yutil.Regexp.ReplaceAll(s, pattern string, repl string) string` - [v2.0.0] 正则获取符合的所有字符串 `yutil.Regexp.FindAll(s, pattern string) []string` #### File - [v2.0.0] 判断文件是否存在 `yutil.File.IsExists(filePath string) bool` - [v2.0.0] 一次性读取文件所有内容 `yutil.File.ReadAll(filePath string) string` - [v2.0.0] 按行读取 `yutil.File.ReadLines(filePath string) []string` - [v2.0.0] 逐行读取文件内容,去除空行和首尾空格 `yutil.File.ReadLinesTrim(filePath string) []string` - [v2.0.0] 自定义处理每一行 `yutil.File.ReadLine(filePath string, f func(line string))` #### Time - [v2.0.0] 获取当前时间并格式化成 2006-01-02 15:04:05 `yutil.Time.Now() string` - [v2.0.0] 获取当前时间并格式化成 2006-01-02 `yutil.Time.NowDate() string` - [v2.0.0] 将2006-01-02 15:04:05字符串转换成时间 `yutil.Time.Parse(s string) time.Time` - [v2.0.0] 将2006-01-02字符串转换成时间 `yutil.Time.DateParse(s string) time.Time` - [v2.0.0] 打印时间间隔 ,params任意参数都会导致函数重置 `yutil.Time.Interval(params ...interface{})` #### String - [v2.0.0] 模板渲染 `yutil.String.TemplateParse(tmpl string, v interface{}) string` - [v2.0.2] 字符串大驼峰 `yutil.String.BigCamelCase(s string) string` - [v2.0.2] 字符串小驼峰 `yutil.String.LittleCamelCase(s string) string` #### Random - [v2.0.0] 随机指定长度的字符串,(范围包含: 大小写数字下划线) `yutil.Random.String(length int) string` #### Ip - [v2.0.0] 获取客户端Ip `yutil.Ip.ClientIp(req *http.Request) string` - [v2.0.0] 将Ip转成uint32 `yutil.Ip.Tolong(ipstr string) uint32` #### Runtime - [v2.0.0] 获取系统类型 `yutil.Runtime.GetOSName() string` - [v2.0.0] 获取调用栈上的函数信息(函数名、文件名、调用行数) `yutil.Runtime.CurrentFuncInfo(skip int) (funcName string, fileName string, line int)` #### Convert - [v2.0.0] 将任意切片转成[]interface{} `yutil.Convert.ToSlinceInterface(slice interface{}) []interface{}` - [v2.0.0] 将任意类型转string `yutil.Convert.ToString(v interface{}) string` - [v2.0.0] 将任意类型转int `yutil.Convert.ToInt(v interface{}) int` - [v2.0.0] 将任意类型转interface `yutil.Convert.ToInterface(v interface{}) interface{}` - [v2.0.3] 将Int切片转成字符串切片 `yutil.Convert.IntSliceToStrSlice(v []int) []string` - [v2.0.3] 将字符串切片转成int切片 `yutil.Convert.StrSliceToIntSlice(v []string) []int` #### Slice - [v2.0.0] 切片洗牌 `yutil.Slice.Shuffle(v interface{})` - [v2.0.3] 切片去重,如果传入指针则直接操作指针,如果传入非指针则返回一个interface,可自行断言 `yutil.Slice.Distinct(v interface{}) interface{}` #### Other - [v2.0.0] 比较两个版本号: v1 > v2 => 1; v1 == v2 => 0; v1 < v2 => -1 > 版本号示例: v1.0 v0.01 v1.0.0.0.1 v0.0.1 ... `yutil.Other.CompareVersion(v1, v2 string) (int, error)`
C++
UTF-8
2,028
2.625
3
[]
no_license
/// TestEntry: utils_fs_module /// With: ../src/utils/fs.cc /// With: ../src/log/methods.cc /// ---------------------- #include <stdio.h> #include <string.h> #include <unistd.h> #include<sys/stat.h> #include "../utilities/index.hpp" #include "../../src/utils/utils.hpp" char buf[128]; int main() { char result[128]; joinPath("./", "abc", result); if(testCompareStrings(result, "./abc") != 0) return 1; testPassed("compare 0"); joinPath(".", "abc", result); if(testCompareStrings(result, "./abc") != 0) return 1; testPassed("compare 1"); joinPath(".", "/abc", result); if(testCompareStrings(result, "./abc") != 0) return 1; testPassed("compare 2"); joinPath("./", "/abc", result); if(testCompareStrings(result, "./abc") != 0) return 1; testPassed("compare 3"); joinPath(nullptr, "/abc", result); if(testCompareStrings(result, "/abc") != 0) return 1; testPassed("compare 4"); struct stat st; const char* createDir = "./test-env/a/b/cccddd"; if(stat(createDir, &st) == 0) { if(rmdir(createDir) != 0) { sprintf(buf, "remove test folder failed: %s", createDir); return testFailed(buf); } } if(!mkdirRecursively(createDir)){ sprintf(buf, "create test folder failed: %s", createDir); return testFailed(buf); } testPassed("create test folder recursively!"); const char* testFile = "./test-env/reg.file"; sprintf(buf, "touch %s", testFile); if(system(buf) != 0){ sprintf(buf, "create test file failed: %s", testFile); return testFailed(buf); } if(!isPathAFile(testFile)) { sprintf(buf, "isPathAFile return false with a existed file: %s", testFile); return testFailed(buf); } testPassed("isPathAFile(file) => true"); if(isPathAFile("./test-env/i-dont-existed")) return testFailed("isPathAFile return true with a non-existed path!"); testPassed("isPathAFile(non-existed) => false"); if(isPathAFile(createDir)) return testFailed("isPathAFile return true with a directory path!"); testPassed("isPathAFile(directory) => false"); return testDone("Fs utils test"); }
C#
UTF-8
817
2.5625
3
[]
no_license
using System; using CodeNameTwang.ViewModels.DataStructures; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestProject1 { [TestClass] public class TestRoom { [TestMethod] public void testID() { Room usr = new Room(); usr.id = 1; Assert.AreEqual(usr.GetProperty<int>("id"), 1); } [TestMethod] public void testname() { Room usr = new Room(); usr.rname = "hello"; Assert.AreEqual(usr.GetProperty<string>("rname"), "hello"); } [TestMethod] public void testpkey() { Room usr = new Room(); usr.capcaity = 123456; Assert.AreEqual(usr.GetProperty<int>("capacity"), 123456); } } }
PHP
UTF-8
1,952
2.796875
3
[]
no_license
<?php // use filter_input to sanitize video search $search = (filter_input(INPUT_GET, "search", FILTER_SANITIZE_STRING)); if(empty($search) === true) { echo "<span class=\"alert alert-danger\">Invalid search parameters. Please re-enter the search query and try again.</span>"; exit; } // load the API key and encode the search require_once("../lib/encrypted-config.php"); $config = readConfig("/etc/apache2/arlo.ini"); $apiKey = $config["rottenTomatoesApiKey"]; $q = urlencode($search); // build query with apikey and video search query $endpoint = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=$apiKey&q=$q"; if (($jsonData = file_get_contents($endpoint)) === false) { echo "<span class=\"alert alert-danger\">Unable to download Rotten Tomatoes search results.</span>"; exit; } // decode the json data to make it easier to parse the php $searchResults = json_decode($jsonData); if ($searchResults === null){ echo "<span class=\"alert alert-danger\">Unable to read Rotten Tomatoes search results.</span>"; exit; } $results = array(); foreach($searchResults->movies as $movie) { // get the core data about the movie $result["id"] = $movie->id; $result["name"] = $movie->title; $result["plot"] = $movie->synopsis; $result["imdbId"] = $movie->alternate_ids->imdb; // get the actors for the movie $actors = array(); foreach($movie->abridged_cast as $actor) { $actors[] = $actor->name; } $result["actors"] = $actors; // get the movie banners $banners = array(); foreach($movie->posters as $banner) { $banners[] = $banner; } $result["banners"] = $banners; // get the available stream and digital purchase options $imdbid = $movie->alternate_ids->imdb; $canIStreamItURL = "http://www.canistream.it/external/imdb/$imdbid?l=default"; $result["stream"] = $canIStreamItURL; // save this result $results[] = $result; } // send the result header("Content-type: text/json"); echo json_encode($results); ?>