content
stringlengths
10
4.9M
// resourceCalicoIpPoolUpdate update an ippool in Calico func resourceCalicoIpPoolUpdate(d *schema.ResourceData, m interface{}) error { d.Partial(false) calicoClient := m.(config).Client ipPoolInterface := calicoClient.IPPools() ipPool, err := createIpPoolApiRequest(d) if err != nil { return err } _, err = ipPoolInterface.Update(ctx, ipPool, opts) if err != nil { return err } return nil }
<gh_stars>0 /****************************************************************** * muensterTPCsim * * Simulations of the Muenster TPC * * @author <NAME>, based on muensterTPC (Levy) and Xenon100 * @date 2015-04-14 * * @comment ******************************************************************/ #include <G4UnitsTable.hh> #include <G4VVisManager.hh> #include <G4Circle.hh> #include <G4Colour.hh> #include <G4VisAttributes.hh> #include "G4SystemOfUnits.hh" #include "muensterTPCPmtHit.hh" G4Allocator<muensterTPCPmtHit> muensterTPCPmtHitAllocator; muensterTPCPmtHit::muensterTPCPmtHit() {} muensterTPCPmtHit::~muensterTPCPmtHit() {} muensterTPCPmtHit::muensterTPCPmtHit(const muensterTPCPmtHit &hmuensterTPCPmtHit):G4VHit() { m_hPosition = hmuensterTPCPmtHit.m_hPosition; m_dTime = hmuensterTPCPmtHit.m_dTime; m_iPmtNb = hmuensterTPCPmtHit.m_iPmtNb; } const muensterTPCPmtHit & muensterTPCPmtHit::operator=(const muensterTPCPmtHit &hmuensterTPCPmtHit) { m_hPosition = hmuensterTPCPmtHit.m_hPosition; m_dTime = hmuensterTPCPmtHit.m_dTime; m_iPmtNb = hmuensterTPCPmtHit.m_iPmtNb; return *this; } G4int muensterTPCPmtHit::operator==(const muensterTPCPmtHit &hmuensterTPCPmtHit) const { return ((this == &hmuensterTPCPmtHit) ? (1) : (0)); } void muensterTPCPmtHit::Draw() { //G4VVisManager* pVVisManager = G4VVisManager::GetConcreteInstance(); //if(pVVisManager) //{ // G4Circle hCircle(m_hPosition); // G4Colour hColour(1.000, 0.973, 0.184); // G4VisAttributes hVisAttributes(hColour); // // hCircle.SetScreenSize(0.1); // hCircle.SetFillStyle(G4Circle::filled); // hCircle.SetVisAttributes(hVisAttributes); // pVVisManager->Draw(hCircle); //} } void muensterTPCPmtHit::Print() { G4cout << "Pmt hit ---> " << "Pmt#" << m_iPmtNb << " Position: " << m_hPosition.x()/mm << " " << m_hPosition.y()/mm << " " << m_hPosition.z()/mm << " mm" << " Time: " << m_dTime/s << " s" << G4endl; }
// Fake wrapper to force AMD loading interface Hammer { } export = Hammer;
// Tests mapping of an action profile with group type. TEST_F(P4TableMapperTest, TestActionProfileGroup) { ASSERT_OK(p4_table_mapper_->PushForwardingPipelineConfig( forwarding_pipeline_config_)); SetUpActionProfileTest(); action_profile_group_.set_group_id(1); action_profile_group_.add_members()->set_member_id(1); action_profile_group_.add_members()->set_member_id(2); MappedAction mapped_action; auto map_status = p4_table_mapper_->MapActionProfileGroup( action_profile_group_, &mapped_action); EXPECT_OK(map_status); EXPECT_EQ(P4_ACTION_TYPE_PROFILE_GROUP_ID, mapped_action.type()); EXPECT_EQ(MappedAction::ACTION_VALUE_NOT_SET, mapped_action.action_value_case()); }
Estimating LAI and mapping canopy storage capacity for hydrological applications in wattle infested ecosystems using Sentinel-2 MSI derived red edge bands This study assessed the strength of Sentinel-2 multispectral instrument (MSI) derived Red Edge (RE) bands in estimating Leaf Area Index (LAI) and mapping canopy storage capacity (CSC) for hydrological applications in wattle infested ecosystems. To accomplish this objective, this study compared the estimation strength of models derived, using standard bands (all bands excluding the RE band) with those including RE bands, as well as different vegetation indices. Sparse Partial Least Squares (SPLSR) and Partial Least Squares Regression (PLSR) ensembles were used in this study. Results showed that the RE spectrum covered by the Sentinel-2 MSI satellite reduced the estimation error by a magnitude of 0.125 based on simple ratio (RE SR) vegetation indices from 0.157 m2· m−2 based on standard bands, and by 0.078 m2· m−2 based on red edge normalised difference vegetation (NDVI-RE). The optimal models for estimating LAI to map CSC were obtained based on the RE bands centered at 705 nm (Band 5), 740 nm (Band 6), 783 nm (Band 7) as well as 865 nm (Band 8a). A root mean square error of prediction (RMSEP) of 0.507 m2· m−2 a relative root mean square error of prediction (RRMSEP) of 11.3% and R2 of 0.91 for LAI and a RMSEP of 0.246 m2/m2 (RRMSEP = 7.9%) and R2 of 0.91 for CSC were obtained. Overall, the findings of this study underscore the relevance of the new copernicus satellite product in rapid monitoring of ecosystems that are invaded by alien invasive species.
// NewProposalIDReimbursementPair returns a new ProposalIDReimbursementPair instance. func NewProposalIDReimbursementPair(proposalID uint64, reimbursement Reimbursement) ProposalIDReimbursementPair { return ProposalIDReimbursementPair{ ProposalID: proposalID, Reimbursement: reimbursement, } }
Don't mess with this monkey. Footage from a security camera is said to show a young man in Shimla, India, giving the finger to one of the area's famously belligerent monkeys. And as you might expect, the monkey is having none of it. It drop kicks the man right in the head, knocking him to the ground. The man, however, appears to be OK after the attack as he gets up and walks off. Shimla's monkeys are known to cause problems for both tourists and locals visiting the Jakhoo temple, which is dedicated to the monkey god Hanuman. "The monkeys of Shimla are not pleasant animals, they roam around in gangs looking for the opportunity to rob tourists of their food or any other item which catches their eyes," the Shimla India Guide website says. The website advises tourists to rent a stick to use to threaten the monkeys. "Without the deterrent of the stick expect to have pockets and bags rummaged through no less intensely than by a human criminal," the website says. The monkeys are mostly after food, but the website says they are also known to take cameras and wallets. In this case, however, the monkey was apparently provoked. "As you can see, the boy looks straight into the eyes of this monkey who is sitting near a bench, where other people are also seated and provokes the animal by showing middle finger," the YouTube description reads. "This is seen as an open challenge by the monkey, who knocks the boy down with a wrestling like move."
<reponame>mlandefeld/daffodil import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { DaffLinkSetHeadingDirective } from './link-set-heading/link-set-heading.directive'; import { DaffLinkSetItemComponent } from './link-set-item/link-set-item.component'; import { DaffLinkSetSubheadingDirective } from './link-set-subheading/link-set-subheading.directive'; import { DaffLinkSetComponent } from './link-set/link-set.component'; @NgModule({ imports: [ CommonModule, ], exports: [ DaffLinkSetComponent, DaffLinkSetHeadingDirective, DaffLinkSetSubheadingDirective, DaffLinkSetItemComponent, ], declarations: [ DaffLinkSetComponent, DaffLinkSetHeadingDirective, DaffLinkSetSubheadingDirective, DaffLinkSetItemComponent, ], }) export class DaffLinkSetModule {}
Matt woke up Thursday morning to a nagging migraine. While he had experienced headaches before, this one seemed different. It lasted all day, and by evening he grew nauseous. I left to go to a meeting, and by the time I returned Matt was very sick. He had vomited several times while I was gone, and felt terrible. As the night went on, his condition grew worse. And Charlie worried. I could hear Matt heaving in the bathroom, and went to check on him. I stood at the door, peeking in, and Charlie nosed the door open, softly walking toward Matt. “Charlie NO!” I said, but it was too late. He walked to where Matt lay curled around the toilet, gently rubbed his nose on his hand, then sat down. He wasn’t leaving. While Matt grew sicker, he refused to go to the doctor. So I went to bed and hoped for the best. As I slept, Matt grew seriously ill, back spasms gripping his body, followed by violent retching sessions. Matt later told me he never got a wink of sleep, and that Charlie never left his side. By morning, I found Matt laying face down on the bathroom floor. Charlie sat nearby, his brown ears pulled back, his puppy lips pursed. Matt finally agreed to get medical care. I called in sick, filled Charlie’s purple KONG with liver treats, then rushed Matt to the hospital. Matt quickly was diagnosed with kidney stones, and eventually was kept for overnight observation. After about six hours, I took a break to run home to grab some toiletries, and to check on the dogs. Charlie greeted me tentatively, and looked out the front window looking for Matt. I quickly grabbed what I needed, fed the dogs and drove back to the hospital. About 12 hours later (around 4 a.m.) I decided to run home to grab a bit of sleep. Both dogs were staring out the front window when I pulled up. Charlie hugged my legs with his paws, and softly cried. I had never heard him do that before, and my heart melted. I pulled Charlie into my arms and held him as he continued to whimper. I whispered in his ear. “Daddy’s gonna be all right. Daddy loves you.” He anxiously licked my nose. Amazingly, after leaving the dogs alone for 12 hours the house was in perfect condition. I was grateful for that gift, and promptly slept for about three hours. At 8 a.m. I woke up, and spoke with Matt. The doctors were filling out his discharge paperwork, so I could come get him. I was gone just a few hours, and Lex and Charlie were dutifully watching out the window when we returned. The first thing we noticed was the fluff. Everywhere. It took me a moment to realize what happened, then Matt screamed out confirmation. “You ate the bleepin’ comforter!!!” he screamed at Charlie. Charlie dropped to his stomach, and wiggled his way out of the room. After everything we had just been through, I was pretty sure a tore up comforter was the least of our worries. Matt grabbed the blanket, and threw it down into the basement. Charlie trotted after Matt, following him to the couch. “C’mon,” Matt said, patting the cushion next to him. Without hesitation, Charlie in one motion hopped up and snuggled into Matt’s side. Charlie was glad to have his daddy home. If you would like to receive email notifications when Our Furever Family publishes a new blog entry, please go to the home page and click on “Email subscriptions” in the right nav. Thanks for joining our journey! Advertisements
import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np from subprocess import call from pf.pfasst import PFASST, Experiment, Params def init(): lines[0].set_data([], []) lines[1].set_data([], []) lines[2].set_data([], []) return lines def animate(i): # for j, line in enumerate(lines): # line.set_data(np.sin(q[i:i+10, j]), np.cos(q[i:i+10, j])) thisx = [0.75*np.sin(q[i, j])-0.02 for j in range(nparticles)] thisy = [0.75*np.cos(q[i, j]) for j in range(nparticles)] lines[0].set_data(thisx, thisy) histx.append([0.75*np.sin(q[i, j])-0.02 for j in [0]])#, nparticles-1]]) histy.append([0.75*np.cos(q[i, j]) for j in [0]])#, nparticles-1]]) lines[1].set_data(histx, histy) # histx.append([0.5*np.sin(q[i, j])-0.05 for j in [0]])#, nparticles-1]]) # histy.append([0.5*np.cos(q[i, j])-0.05 for j in [0]])#, nparticles-1]]) lines[2].set_data(histx, histy) return lines # return lines[0], lines[1], lines[2], lines[3], \ # lines[4], lines[5], lines[6], lines[7], \ # lines[8], lines[9], lines[10], time_text if __name__ == '__main__': exe = '/home/bkrull/devel/pfasst-nwchem/libpfasst/tests/toda/main.exe' exp = Experiment() cmap = plt.cm.Dark2.colors*2 nsteps = 4096 nparticles = 11 periodic = True tfinal = 25.0 dt = tfinal/nsteps params = Params(tfinal=tfinal, nodes=[3], magnus=[2], tasks=8, sweeps_pred=[2], particles=nparticles, periodic=periodic, tolerance=1e-10, iterations=20, nsteps=nsteps, solutions=True) toda = PFASST(exe, params) results = toda.run()[0] q, p = toda.get_toda_solutions(results) fig, ax = plt.subplots(figsize=(3,3), dpi=300) lines = [ax.plot([],[], marker='o', color=cmap[0])[0], ax.plot([],[], lw=1, color='red')[0], ax.plot([],[], lw=1, color='black')[0]] histx = [] histy = [] ax.set_xlim(-1, 1) ax.set_ylim(-1, 1) ax.axis('off') ax.grid(); ani = animation.FuncAnimation(fig, animate, np.arange(0, nsteps), \ interval=5, blit=True, init_func=init) ani.save('input.mp4', fps=60) #plt.show() #convert_to_gif = 'ffmpeg -i input.mp4 -r 10 -f image2pipe -vcodec ppm - | ' + 'convert -delay 5 -loop 0 - output.gif' #convert_to_gif = convert_to_gif.split() #shrink_gif = 'gifsicle output.gif --resize 300x300 > output300.gif'.split() #call(convert_to_gif) #call(shrink_gif, shell=True)
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} module Telegram.API.Updates ( TelegramUpdatesAPI, getUpdates ) where import Data.Proxy import Network.HTTP.Client (newManager) import Network.HTTP.Client.TLS (tlsManagerSettings) import Servant.API import Servant.Client import Telegram.API.Core import Telegram.Requests import Telegram.Responses import Telegram.Types type TelegramUpdatesAPI = TelegramToken :> "getUpdates" :> ReqBody '[JSON] GetUpdatesRequest :> Get '[JSON] GetUpdatesResponse updatesApi :: Proxy TelegramUpdatesAPI updatesApi = Proxy search = client updatesApi query :: Token -> GetUpdatesRequest -> ClientM GetUpdatesResponse query token request = do t <- search token request return t getUpdates token manager offset = runClientM (query token (getUpdatesRequest offset)) (mkClientEnv manager telegramUrl)
// EnsureDefaults will ensure that if a user omits and fields in the // spec that are required, we set some sensible defaults. // For example a user can choose to omit the version // and number of members. func (t *Tenant) EnsureDefaults() *Tenant { if t.Spec.PodManagementPolicy == "" || (t.Spec.PodManagementPolicy != appsv1.OrderedReadyPodManagement && t.Spec.PodManagementPolicy != appsv1.ParallelPodManagement) { t.Spec.PodManagementPolicy = DefaultPodManagementPolicy } if t.Spec.Image == "" { t.Spec.Image = GetTenantMinIOImage() } if t.Spec.ImagePullPolicy == "" { t.Spec.ImagePullPolicy = DefaultImagePullPolicy } for pi, pool := range t.Spec.Pools { if pool.Name == "" { pool.Name = fmt.Sprintf("%s-%d", StatefulSetPrefix, pi) } t.Spec.Pools[pi] = pool } if t.Spec.Mountpath == "" { t.Spec.Mountpath = MinIOVolumeMountPath } if t.Spec.Subpath == "" { t.Spec.Subpath = MinIOVolumeSubPath } if t.Spec.CertConfig != nil { if t.Spec.CertConfig.CommonName == "" { t.Spec.CertConfig.CommonName = t.MinIOWildCardName() } if t.Spec.CertConfig.DNSNames == nil || len(t.Spec.CertConfig.DNSNames) == 0 { t.Spec.CertConfig.DNSNames = t.MinIOHosts() } if t.Spec.CertConfig.OrganizationName == nil || len(t.Spec.CertConfig.OrganizationName) == 0 { t.Spec.CertConfig.OrganizationName = DefaultOrgName } } else { t.Spec.CertConfig = &CertificateConfig{ CommonName: t.MinIOWildCardName(), DNSNames: t.MinIOHosts(), OrganizationName: DefaultOrgName, } } if t.HasConsoleEnabled() { if t.Spec.Console.Image == "" { t.Spec.Console.Image = GetTenantConsoleImage() } if t.Spec.Console.Replicas == 0 { t.Spec.Console.Replicas = DefaultConsoleReplicas } if t.Spec.Console.ImagePullPolicy == "" { t.Spec.Console.ImagePullPolicy = DefaultImagePullPolicy } } if t.HasKESEnabled() { if t.Spec.KES.Image == "" { t.Spec.KES.Image = GetTenantKesImage() } if t.Spec.KES.Replicas == 0 { t.Spec.KES.Replicas = DefaultKESReplicas } if t.Spec.KES.ImagePullPolicy == "" { t.Spec.KES.ImagePullPolicy = DefaultImagePullPolicy } if t.Spec.KES.KeyName == "" { t.Spec.KES.KeyName = KESMinIOKey } } if t.HasPrometheusEnabled() { if t.Spec.Prometheus.Image == "" { t.Spec.Prometheus.Image = PrometheusImage } if t.Spec.Prometheus.SideCarImage == "" { t.Spec.Prometheus.SideCarImage = PrometheusSideCarImage } if t.Spec.Prometheus.InitImage == "" { t.Spec.Prometheus.InitImage = PrometheusInitImage } } if t.HasLogEnabled() { if t.Spec.Log.Image == "" { t.Spec.Log.Image = DefaultLogSearchAPIImage } } return t }
<filename>app/core/tools/utils.ts export const asType = <T>(value: T): T => value /** * 格式化日期 * @param d * @param format 'YYYY-MM-DD H:I:S.MS' */ export function formatDate(date: Date = new Date(), format = 'YYYY-MM-DD H:I:S.MS') { const obj = { YYYY: date.getFullYear().toString().padStart(4, '0'), MM: (date.getMonth() + 1).toString().padStart(2, '0'), DD: date.getDate().toString().padStart(2, '0'), H: date.getHours().toString().padStart(2, '0'), I: date.getMinutes().toString().padStart(2, '0'), S: date.getSeconds().toString().padStart(2, '0'), MS: date.getMilliseconds().toString().padStart(3, '0'), } return format.replace(/(YYYY|MM|DD|H|I|S|MS)/g, (_, $1) => { return obj[$1] }) } /** 获取 url 参数 */ export function getQuery(search: string): AnyObj { const query: AnyObj = {} search .substr(1) .split('&') .forEach((str) => { const strArr = str.split('=') const key = strArr[0] if (!key) return query let val = decodeURIComponent(strArr[1]) try { val = JSON.parse(val) } catch (err) {} query[key] = val }) return query } /** 转换成 url search */ export function toSearch(obj: AnyObj): string { const arr = Object.keys(obj).map((key) => { let val = obj[key] if (typeof val !== 'string') { try { val = JSON.stringify(val) } catch (err) { console.error(err) } } return `${key}=${encodeURIComponent(val)}` }) return '?' + arr.join('&') }
Arkham Asylum is a home for the 'criminally insane'. The prisoners there are the most dangerous people in the Batman universe. It makes Gotham's plan to let them loose in their own neighbourhood beyond dumb. But dumb ideas make for interesting games. Arkham City expands everything that made 2009's third-person action game Arkham Asylum so much fun: five times more space for the criminals to settle into and for Batman to roam, more Batpunches in his repertoire, and a better class of criminal with Two-Face, Catwoman, the Riddler and Professor Hugo Strange joining the Joker and his team of jesters. And an expanded arsenal of gadgets and weapons expands the previous game's tally. Arkham Asylum was hardly cramped, but now there's more vertical space to take advantage of. Taking cues from both the Assassin's Creed and Just Cause series, Bats will be able to climb on almost anything, using telephone wires to silently get around, topping buildings to get a view on the criminal scum below before leaping off like a leathery missile. He can even use his grappling hook to boost into the air and insta-glide. The slick combo fighting system, which gave Batman the edge over multiple foes in the asylum, has been tweaked. Bats is now able to counter multiple attacks from all angles, and a perfectly timed attack has a chance to instantly take down a thug. More excitingly, there's a new beatdown mechanic, where you simply unload a flurry of blows into a single enemy, letting loose all that inner violence that the Caped Crusader keeps suppressed. There's a greater focus on environmental violence: you can counter any tossed projectile, or turn Bruce into one, launching from walls to fly into enemies like a gimp rocket. He also has access to his gadgets in fights. Where previously he could only use his grapple and Batarang, the expanded use of his gadgets means he'll be able to spray his enemies with his wall-wrecking explosive gel. I predict that becoming my main tactic. And then there's detective mode, little more than an interactive map in Arkham Asylum that gave you trails to follow. This time around, the forensic portions of the game will require proper sleuthing, more like the puzzles the Riddler left for Batman to solve in the mental hospital. In one instance, Batman has to work out where a sniper is hidden, back-tracing the bullet's trajectory. Your investigations will lead you to the side-missions that litter Gotham's streets. With so much space to fill, Arkham City will be jammed things to do and riddles to puzzle over, and there's not a lot of competition for it on the horizon. It'll be 2011's premium prisoner puncher.
GIRK Channel Activation Contributes to the Muscarinic Modulation of XII Motoneuron Excitability in Neonatal Mice in Vitro Sleep specific decreases in airway muscle tone, and particularly the genioglossus muscle of the tongue (primary tongue protruder), have been causally implicated in obstructive sleep apnea. During REM (rapid eye movement) sleep, decreased excitability of the XII motoneurons that innervate the genioglossus muscle may be due to a loss of excitatory noradrenergic modulation, or due to activation of muscarinic acetylcholine receptors that may act via G‐protein coupled inward rectifying potassium (GIRK) channels. GIRK channel activation results in membrane hyperpolarization and thus could mediate a decrease in excitability of XII motoneurons during REM sleep. Here we test the hypothesis that muscarine acts via GIRK channels to inhibit inspiratory burst amplitude of XII motoneurons in vitro. Using immunohistochemical techniques, our preliminary data indicate that XII motoneurons express GIRK1, GIRK2, and GIRK3 isoforms. Next, using rhythmically medullary slice preparations from neonatal CD1 mice (postnatal day, P0–5), we investigated the effects of GIRK channel and muscarinic acetycholine receptor activation on XII inspiratory burst characteristics including burst amplitude and burst period. Local application of muscarine (30 s, 100 mM) to the XII motor nucleus had the net effect of increasing XII inspiratory burst amplitude, although local pre‐application of the GIRK channel antagonist Tertiapin Q (TQ, 60 s, 100 nM) led to two different responses. In P0–2 mice (n = 4), muscarine increased burst amplitude to 120% of control (range 105–133%) while pre‐application of TQ followed by local application of muscarine led to a similar 115% (range 104–123%) increase in amplitude, suggesting that muscarine does not activate GIRK channels in P0–2 mice. In P3–5 mice (n = 4), however, local application of muscarine increased burst amplitude to 135% (range 122–156%) of baseline, and pre‐application of TQ to block GIRK channel activation further increased the response to muscarine to 160% (range 130–170%) of baseline amplitude. These results indicate that muscarine acts at GIRK channels to inhibit XII motoneuron excitability in P3–5 mice, but also acts at other channels to enhance XII motoneuron excitability. Preliminary data suggests this effect is specific to muscarinic activation of GIRK channels because bath application of TQ (10 nM) in P3–5 mice resulted in no change in inspiratory burst amplitude (mean: 102% of baseline, range 90–109%, after 30 min in TQ, n = 3). In contrast, bath application of the GIRK channel agonist ML297 (10 mM) resulted burst amplitude decrease to 80–88% of baseline in 2 out of 3 P3–5 neonatal mice and an increase in burst amplitude to 120% of baseline in a third prep. Burst period increased to 179% of baseline (range: 128–263%) indicating that GIRK channels are likely also present in preBötzinger Complex where inspiratory rhythm is generated. These data support the hypothesis that activation of muscarinic receptors in XII motoneurons leads to GIRK channel activation in P3–5 neonatal mice, which may be one mechanism through which muscarine mediates a decrease in XII motoneuron excitability in vivo.
<gh_stars>0 import { useState } from "react"; import { CameraIcon } from "@heroicons/react/solid"; import getBearerToken from "../util/getBearerToken"; const InputBox: React.FC = () => { const [postContent, setPostContent] = useState(""); const submitPost = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); const data = { content: postContent }; const formData = JSON.stringify(data); try { const userObject = await localStorage.getItem("user") || ''; const bearerToken = await getBearerToken(userObject); const req = await fetch( "http://localhost:5000/api/posts", { method: "POST", body: formData, headers: { Accept: "application/json", "Content-Type": "application/json", "Authorization": bearerToken } } ); const jsonPostData = await req.json(); // Use post data to update current post state // Error handling if (req.status !== 200) { // setPostErr(true); return; } } catch (err) { console.log(err) // setPostErr(true); } } return ( <div className="bg-white mt-6 p-2 rounded-2xl shadow-sm text-gray-500 font-medium"> <div className="flex space-x-4 p-2 items-center"> <img className="rounded-full" src="https://i.ibb.co/42drhRP/mcerleantom-79390488-2535626826491703-1307724872187531610-n-1.jpg" alt="" width="40" height="40" /> <form className="flex flex-1" onSubmit={submitPost}> <input type="text" placeholder="What's your story?" className="rounded-full h-12 bg-gray-100 flex-grow px-5 border-none focus:outline-none" value={postContent} onChange={(e) => setPostContent(e.target.value)} /> </form> </div> <div className="flex justify-center pt-2 border-t"> <div className="flex items-center space-x-1 p-2 hover:bg-gray-100 justify-center rounded-lg cursor-pointer"> <CameraIcon className="h-7 text-green-400" /> <p className="text-xs sm:text-sm xl:text-base">Add Photo</p> </div> </div> </div> ) } export default InputBox;
import { browser } from 'webextension-polyfill-ts' import { IGNORE_CLICK_OUTSIDE_CLASS } from '../constants' import { ContentScriptRegistry, SidebarScriptMain } from './types' import { createInPageUI, destroyInPageUI } from 'src/in-page-ui/utils' import { setupInPageSidebarUI, destroyInPageSidebarUI, } from 'src/sidebar/annotations-sidebar/index' import { InPageUIRootMount } from 'src/in-page-ui/types' export const main: SidebarScriptMain = async (dependencies) => { const cssFile = browser.extension.getURL(`/content_script_sidebar.css`) let mount: InPageUIRootMount | null = null const createMount = () => { if (!mount) { mount = createInPageUI('sidebar', cssFile, [ IGNORE_CLICK_OUTSIDE_CLASS, ]) } } createMount() dependencies.inPageUI.events.on( 'componentShouldSetUp', ({ component, options }) => { if (component === 'sidebar') { setUp({ showOnLoad: options.showSidebarOnLoad }) } }, ) dependencies.inPageUI.events.on( 'componentShouldDestroy', ({ component }) => { if (component === 'sidebar') { destroy() } }, ) const setUp = async (options: { showOnLoad?: boolean } = {}) => { createMount() setupInPageSidebarUI(mount, { ...dependencies, pageUrl: dependencies.getPageUrl(), initialState: options.showOnLoad ? 'visible' : 'hidden', }) } const destroy = () => { if (!mount) { return } destroyInPageUI('sidebar') destroyInPageSidebarUI(mount.rootElement, mount.shadowRoot) } } const registry = window['contentScriptRegistry'] as ContentScriptRegistry registry.registerSidebarScript(main)
/* G N O K I I A Linux/Unix toolset and driver for the mobile phones. This file is part of gnokii. Copyright (C) 2000 <NAME> & <NAME>. Copyright (C) 2001-2003 <NAME>, <NAME> This file provides functions specific to the Nokia 6100/5100 series. See README for more details on supported mobile phones. */ #ifndef _gnokii_phones_nk6100_h #define _gnokii_phones_nk6100_h #include "gnokii.h" /* Phone Memory types */ #define NK6100_MEMORY_MT 0x01 /* ?? combined ME and SIM phonebook */ #define NK6100_MEMORY_ME 0x02 /* ME (Mobile Equipment) phonebook */ #define NK6100_MEMORY_SM 0x03 /* SIM phonebook */ #define NK6100_MEMORY_FD 0x04 /* ?? SIM fixdialling-phonebook */ #define NK6100_MEMORY_ON 0x05 /* ?? SIM (or ME) own numbers list */ #define NK6100_MEMORY_EN 0x06 /* ?? SIM (or ME) emergency number */ #define NK6100_MEMORY_DC 0x07 /* ME dialled calls list */ #define NK6100_MEMORY_RC 0x08 /* ME received calls list */ #define NK6100_MEMORY_MC 0x09 /* ME missed (unanswered received) calls list */ #define NK6100_MEMORY_VOICE 0x0b /* Voice Mailbox */ /* This is used when the memory type is unknown. */ #define NK6100_MEMORY_XX 0xff #define NK6100_MAX_SMS_MESSAGES 12 /* maximum number of sms messages */ #define NK6100_CAP_OLD_CALL_API 1 #define NK6100_CAP_NBS_UPLOAD 2 #define NK6100_CAP_PB_UNICODE 4 #define NK6100_CAP_OLD_KEY_API 8 #define NK6100_CAP_NO_PSTATUS 16 #define NK6100_CAP_NO_CB 32 #define NK6100_CAP_CAL_UNICODE 64 #define NK6100_CAP_NO_PB_GROUP 128 /* phone doesn't support categories in phonebook entries (caller groups) */ typedef struct { gn_key_code key; int repeat; } nk6100_keytable; typedef struct { /* callbacks */ void (*on_cell_broadcast)(gn_cb_message *msg, struct gn_statemachine *state, void *callback_data); void (*call_notification)(gn_call_status call_status, gn_call_info *call_info, struct gn_statemachine *state, void *callback_data); void (*rlp_rx_callback)(gn_rlp_f96_frame *frame); gn_error (*on_sms)(gn_sms *message, struct gn_statemachine *state, void *callback_data); unsigned char magic_bytes[4]; bool sms_notification_in_progress; bool sms_notification_lost; gn_display_output *display_output; nk6100_keytable keytable[256]; int capabilities; int max_sms; char model[GN_MODEL_MAX_LENGTH]; char imei[GN_IMEI_MAX_LENGTH]; char sw_version[10]; char hw_version[10]; gn_phone_model *pm; /* callback local data */ void *cb_callback_data; /* to be passed as callback_data to on_cell_broadcast */ void *call_callback_data; /* to be passed as callback_data to call_notification */ void *sms_callback_data; /* to be passed as callback_data to on_sms */ } nk6100_driver_instance; void pnok_get_nokia_auth(unsigned char *imei, unsigned char *magic_bytes, unsigned char *magic_response); #endif /* #ifndef _gnokii_phones_nk6100_h */
/** * Clicks at the coordinates of the given {@link IDomNode}. * <p> * Does <b>not</b> click the associated {@link WebElement} directly, in * order to support click-intercepting overlay elements. * <p> * If there is a click-intercepting overlay above the {@link WebElement} to * click, an attempt to click the the associated {@link WebElement} directly * (via {@link WebElement#click()}) would cause Selenium to throw a * {@link WebDriverException}. Clicking at the coordinates of the * {@link WebElement} circumvents that {@link WebDriverException}. * * @param node * the {@link IDomNode} to click (never <i>null</i>) * @param clickType * the {@link ClickType} (never <i>null</i>) */ private void clickAtNodeCoordinates(IDomNode node, ClickType clickType) { WebElement webElement = getWebElement(node); AjaxSeleniumTestPoint clickPoint = createPoint(webElement); screenshotQueue .addNewScreenshot("sendEvent-%s-x%s-y%s".formatted(clickType.getName(), clickPoint.getX(), clickPoint.getY())) .drawPointMarker(clickPoint); var actions = new Actions(getWebDriver()).moveToElement(webElement); var clickFunction = clickType.getClickFunction(); clickFunction.apply(actions).perform(); }
def search(self, task, entry, config=None): self.rss_key = config['rss_key'] username = config['username'] password = hashlib.md5(config['password'].encode('utf-8')).hexdigest() data = {'cookieuser': '1', 'do': 'login', 's': '', 'securitytoken': 'guest', 'vb_login_username': username, 'vb_login_password': '', 'vb_login_md5password': password, 'vb_login_md5password_utf': password } try: login = requests.post('https://www.fuzer.me/login.php?do=login', data=data) except RequestException as e: raise PluginError('Could not connect to fuzer: %s' % str(e)) login_check_phrases = ['ההתחברות נכשלה', 'banned'] if any(phrase in login.text for phrase in login_check_phrases): raise PluginError('Login to Fuzer failed, check credentials') self.user_id = requests.cookies.get('fzr2userid') category = config.get('category', [0]) if not isinstance(category, list): category = [category] categories = [c if isinstance(c, int) else CATEGORIES[c] for c in category] c_list = [] for c in categories: c_list.append('c{}={}'.format(quote_plus('[]'), c)) entries = [] if entry.get('imdb_id'): log.debug('imdb_id {} detected, using in search.'.format(entry['imdb_id'])) soup = self.get_fuzer_soup(entry['imdb_id'], c_list) entries = self.extract_entry_from_soup(soup) if entries: for e in list(entries): e['imdb_id'] = entry.get('imdb_id') else: for search_string in entry.get('search_strings', [entry['title']]): query = normalize_unicode(search_string).replace(":", "") text = quote_plus(query.encode('windows-1255')) soup = self.get_fuzer_soup(text, c_list) entries += self.extract_entry_from_soup(soup) return sorted(entries, reverse=True, key=lambda x: x.get('search_sort')) if entries else []
<filename>channels/core/clientHelper.go package core import ( "fmt" "os" ) // GetClient - Get client from cache first, then try database and update cache if found func GetClient(appID string, clientID string) (*Client, error) { client := GetEngine().GetCacheStorage().GetClient(appID, clientID) if client != nil { return client, nil } client, err := GetEngine().GetClientRepository().GetAppClient(appID, clientID) if err != nil { _, _ = fmt.Fprintf(os.Stderr, "Get client failed %v\n", err) return nil, err } if client == nil { return nil, nil } GetEngine().GetCacheStorage().StoreClient(appID, clientID, client) return client, nil } // CreateClient - Create client and also cache it func CreateClient(appID string, clientID string, username string, extra string) (bool, error) { err := GetEngine().GetClientRepository().CreateClient(clientID, username, appID, extra) if err != nil { fmt.Fprintf(os.Stderr, "Create Client failed %v\n", err) return false, err } GetEngine().GetCacheStorage().StoreClient(appID, clientID, &Client{ ID: clientID, Username: username, Extra: extra, AppID: appID, }) return true, nil } // DeleteClient - Remove client from database and cache func DeleteClient(appID string, clientID string) (bool, error) { exists, err := GetEngine().GetClientRepository().ExistsAppClient(appID, clientID) if err != nil { fmt.Fprintf(os.Stderr, "Delete Client: failed to check client existence %v\n", err) return false, err } if exists { return false, nil } err = GetEngine().GetClientRepository().DeleteClient(clientID) if err != nil { fmt.Fprintf(os.Stderr, "Delete Client failed %v\n", err) return false, err } // Remove client cache GetEngine().GetCacheStorage().RemoveClient(appID, clientID) GetEngine().GetCacheStorage().RemoveClientChannels(clientID) return true, nil } // UpdateClient - Update client on the database and cache func UpdateClient(appID string, clientID string, username string, extra string) (bool, error) { exists, err := GetEngine().GetClientRepository().ExistsAppClient(appID, clientID) if err != nil { fmt.Fprintf(os.Stderr, "Update Client: failed to check client existence %v\n", err) return false, err } if !exists { return false, nil } err = GetEngine().GetClientRepository().UpdateClient(clientID, username, extra) if err != nil { fmt.Fprintf(os.Stderr, "Update Client failed %v\n", err) return false, err } GetEngine().GetCacheStorage().StoreClient(appID, clientID, &Client{ ID: clientID, AppID: appID, Username: username, Extra: extra, }) return true, nil }
<filename>data/db/src/main/java/leap/db/model/DbTable.java<gh_stars>10-100 /* * Copyright 2013 the original author or authors. * * 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 leap.db.model; import java.sql.DatabaseMetaData; import leap.lang.Args; import leap.lang.Arrays2; import leap.lang.Assert; import leap.lang.Strings; import leap.lang.json.JsonStringable; import leap.lang.json.JsonWriter; public class DbTable extends DbSchemaObjectName implements JsonStringable { public static DbTable fromJson(String json) { DbTableBuilder b = new DbTableBuilder(); b.parseJson(json); return b.build(); } protected final String type; protected final String comment; protected final DbPrimaryKey primaryKey; protected final DbColumn[] primaryKeyColumns; protected final DbColumn[] columns; protected final DbForeignKey[] foreignKeys; protected final DbIndex[] indexes; public DbTable(String catalog, String schema, String name, String type, boolean quoted, String comment, String primaryKeyName, String[] primaryKeyColumnNames, DbColumn[] columns, DbForeignKey[] foreignKeys, DbIndex[] indexes) { super(catalog, schema, name, quoted); Args.notEmpty(type,"table type"); Args.notEmpty(columns,"columns' of table '" + name + ""); Args.assertFalse(!Arrays2.isEmpty(primaryKeyColumnNames) && Strings.isEmpty(primaryKeyName), "primaryKeyName must not be empty if primary key exists"); this.type = type; this.comment = comment; this.columns = columns; this.foreignKeys = null == foreignKeys ? new DbForeignKey[]{} : foreignKeys; this.indexes = null == indexes ? new DbIndex[]{} : indexes; this.primaryKey = Arrays2.isEmpty(primaryKeyColumnNames) ? null : new DbPrimaryKey(primaryKeyName, primaryKeyColumnNames); this.primaryKeyColumns = fromNames(primaryKeyColumnNames); } /** * @see DatabaseMetaData#getTableTypes() */ public String getType() { return type; } /** * returns the comment of this table. */ public String getComment() { return comment; } /** * returns truth if this table's type is view. * * @see DbTableTypes#VIEW * @see DatabaseMetaData#getTableTypes() */ public boolean isView(){ return DbTableTypes.VIEW.equals(this.type); } /** * returns true if this table has primary key(s). */ public boolean hasPrimaryKey(){ return primaryKeyColumns.length > 0; } public DbPrimaryKey getPrimaryKey() { return primaryKey; } /** * Returns the constraint name of the primary key if exists. * * <p> * Returns <code>null</code> if no primary key in this table. */ public String getPrimaryKeyName() { return primaryKey == null ? null : primaryKey.getName(); } /** * returns the primary key {@link DbColumn} objects (order by physical position) of this table. * * <p> * * the array returned must not be null but may be empty. */ public DbColumn[] getPrimaryKeyColumns() { return primaryKeyColumns; } /** * returns the primary key column names (order by physical position) of this table. * * <p> * * the array returned must not be null but may be empty. */ public String[] getPrimaryKeyColumnNames() { return null == primaryKey ? Arrays2.EMPTY_STRING_ARRAY : primaryKey.getColumnNames(); } /** * returns the {@link DbColumn} objects of this table. * * <p> * the array returned must not be null or empty. */ public DbColumn[] getColumns() { return columns; } /** * returns the {@link DbColumn} stored in the given position. * * <p> * index starts from 0. * * @throws IndexOutOfBoundsException if index out of bounds. */ public DbColumn getColumn(int index) throws IndexOutOfBoundsException{ return columns[index]; } /** * returns the {@link DbForeignKey} objects of this table. * * <p> * the array returned must be not null but may be empty. */ public DbForeignKey[] getForeignKeys() { return foreignKeys; } public boolean hasForeignKeys(){ return foreignKeys.length > 0; } /** * returns the {@link DbIndex} objects of this table. * * <p> * * the array returned must be not null but may be empty. */ public DbIndex[] getIndexes() { return indexes; } public boolean hasIndexes(){ return indexes.length > 0; } /** * returns the {@link DbColumn} object matched the given name (ignore case) in this table. * * <p> * returns <code>null</code> if no column match the given name. */ public DbColumn findColumn(String name){ for(int i=0;i<columns.length;i++){ DbColumn column = columns[i]; if(Strings.equalsIgnoreCase(column.getName(), name)){ return column; } } return null; } /** * returns the {@link DbForeignKey} object matched the given name (ignore case) in this table. * * <p> * returns <code>null</code> if no foreign key match the given name. */ public DbForeignKey findForeignKey(String name){ for(int i=0;i<foreignKeys.length;i++){ DbForeignKey fk = foreignKeys[i]; if(Strings.equalsIgnoreCase(fk.getName(), name)){ return fk; } } return null; } /** * returns the {@link DbIndex} object matched the given name (ignore case) in this table. * * <p> * returns <code>null</code> if no index match the given name. */ public DbIndex findIndex(String name){ for(int i=0;i<indexes.length;i++){ DbIndex ix = indexes[i]; if(Strings.equalsIgnoreCase(ix.getName(), name)){ return ix; } } return null; } public boolean isSameColumnNamesWith(DbTable t2) { if(getColumns().length != t2.getColumns().length) { return false; } for(DbColumn c1 : getColumns()) { if(null == t2.findColumn(c1.getName())) { return false; } } return true; } public boolean isSubColumnsNamesOf(DbTable t2) { if(getColumns().length >= t2.getColumns().length) { return false; } for(DbColumn c1 : getColumns()) { if(null == t2.findColumn(c1.getName())) { return false; } } return true; } private DbColumn[] fromNames(String[] columnNames){ DbColumn[] columns = new DbColumn[columnNames.length]; for(int i=0;i<columns.length;i++){ columns[i] = findColumn(columnNames[i]); Assert.isTrue(columns[i] != null); } return columns; } public String toString() { StringBuffer result = new StringBuffer(); result.append("Table {name="); result.append(getName()); result.append("; "); result.append(columns.length); result.append(" columns}"); return result.toString(); } @Override public void toJson(JsonWriter writer) { writer.startObject(); writeName(writer); writer.property("type", type); writer.propertyOptional("comment", comment) .propertyOptional("primaryKeyName", primaryKey == null ? null : primaryKey.getName()); writer.propertyJsonable("columns",columns); if(foreignKeys.length > 0){ writer.propertyJsonable("foreignKeys",foreignKeys); } if(indexes.length > 0){ writer.propertyJsonable("indexes",indexes); } writer.endObject(); } }
import typing # import urllib # expected_value = urllib.parse.unquote(expected_value) # mypy: error: Module has no attribute "parse" from urllib.parse import unquote as urllib__parse__unquote # ****************************************************************************** # ****************************************************************************** def split_name_index(node_name: str) -> typing.Tuple[ # typing.Any, str, typing.Union[ str, typing.Tuple[str, str, typing.Union[str, bool]] ] ]: if not isinstance(node_name, str): raise Exception("node_name (%s)%s must be string" % (type(node_name), node_name)) node_index_tuple = None if '[' in node_name and node_name.endswith(']'): node_name, node_index_str = node_name[:-1].split('[', 1) node_name = node_name.strip() node_index_str = node_index_str.strip() if isinstance(node_index_str, str): if node_index_str != "": if node_index_str.lower().startswith('contains') and node_index_str.endswith(')'): node_index_part1, node_index_part2 = node_index_str[8:-1].strip().split('(',1)[1].split(',',1) if node_index_part1.lower().startswith('text'): node_index_str = "text()~~" + node_index_part2 if '=' in node_index_str or '~' in node_index_str: separators = ("==","!=","~~","!~","~","=") for separator in separators: if separator in node_index_str: expected_node_name, expected_value = node_index_str.split(separator,1) expected_node_name = expected_node_name.strip() expected_value = expected_value.strip() if separator == '=': separator = '==' if separator == '~': separator = '~~' break else: raise Exception("Never must be happend!") expected_value_bool = False # Default value, in real None was used, but mypy raised error if expected_value.lower() == "true()": expected_value = "" expected_value_bool = True elif expected_value.lower() == "false()": expected_value = "" expected_value_bool = False elif (expected_value.startswith('"') and expected_value.endswith('"')) or \ (expected_value.startswith("'") and expected_value.endswith("'")): expected_value = expected_value[1:-1] # expected_value = urllib.parse.unquote(expected_value) # mypy: error: Module has no attribute "parse" expected_value = urllib__parse__unquote(expected_value) node_index_tuple = (expected_node_name, separator, expected_value or expected_value_bool) else: node_index_str = None return node_name, (node_index_tuple if not node_index_tuple is None else node_index_str) # ****************************************************************************** # notemptyitems(item): # Check item or recursively subitems of item. # Return count of notempty item/subitems. # ****************************************************************************** def notemptyitems(item): not_empty_items_count = 0 # if isinstance(item, (dict, OrderedDict, n0dict)): if isinstance(item, dict): for key in item: not_empty_items_count += notemptyitems(item[key]) elif isinstance(item, (list, tuple)): for itm in item: not_empty_items_count += notemptyitems(itm) else: if item: not_empty_items_count += 1 return not_empty_items_count # ****************************************************************************** # ******************************************************************************
// NOTE tests for individual tag values exist in JpegReaderTest.java @Test public void testGetImageWidth() throws Exception { _directory.setInt(JpegDirectory.TAG_IMAGE_WIDTH, 123); assertEquals(123, _directory.getImageWidth()); }
Adidas-owned GPS fitness app Runtastic is introducing a new integration with Google Play Music today, one that promises “free” access to an array of music playlists directly within the Runtastic app. Available only on Android from today, Runtastic’s millions of users will be able to access a selection of playlists, according to a blog post, geared towards those who pound the pavements and parks. It’s worth noting here that Runtastic already links in with other music apps installed on your phone, including Google Play Music, Spotify, and media players that play your locally stored tunes. But that is more about creating shortcuts to your own music collection, so you can control songs without having to switch between apps. What Google and Runtastic are promising now is twofold. Users can “access a wide array of free workout playlists to suit any mood or activity curated by Google Play Music,” according to Brandon Bilinski, product manager at Google Play Music, in his blog post. Later he adds: “Additionally, Google Play Music is offering all Runtastic users — both Android and iOS — a two-month free trial so that can you can create your own playlists and access Google Play’s library of more than 40 million tracks from your favorite artists to stream and enjoy ad-free.” On the surface, the announcement sounds like all Android users will be able to access free workout playlists indefinitely, with the added bonus of being able to sign up for a free two-month promo to access the full Google Play Music feature set. According to the blog post: “After opening the Runtastic app’s music section, users will be presented with relevant workout playlists that they can play, pause and skip directly within the Runtastic app.” But upon further inspection, there is no such free playlist option without signing up for the promo. When I hit “No Thanks” on the offer for the free 2 months, there were none of the promised playlists, just a handful of playlists relating to some of my own existing music. Founded out of Austria in 2009, Runtastic has built a big user base in the digital fitness realm, primarily for its flagship GPS fitness tracking app, which has racked up more than 140 million downloads globally. The startup has launched a ton of hardware, too, including GPS watches and smartphone mounts for bikes, in addition to niche apps for building six-packs and improving your sleep. This is why Adidas ended up shelling out $239 million for the company last year. Runtastic isn’t the first fitness app to enter partnerships with music-streaming apps. Last year, Runkeeper teamed up with Spotify, which delivered some fitness-focused playlists as part of the deal — and yes, a premium Spotify account was required. But the difference in that case was, it was made clear that a Premium account was required. I can’t help but feel that some users will be confused about the messaging around this latest tie-up, including some of the subsequent media reporting on the news. The partnership is just a promotion, really, one that gives you two free months of Google Play Music as opposed to the usual 30 days. So it’s still worth it if you’re on the market for a new music-streaming service, but just don’t expect anything “free” that doesn’t involve signing up for a two-month promotion. Last year, Google announced it was powering locally themed music stations within TripAdvisor’s Android app. So this latest move is a continuation of that, as the internet giant seeks new ways to gain mindshare in the ongoing battle against Spotify and Apple Music.
<gh_stars>0 /// <reference path="../../typings/tsd.d.ts" /> import ChatMessageUtil from "../utils/ChatMessageUtil"; import {ChatAction} from "../actions/ChatAction"; import {MessageData, RawMessage} from "./MessageStore"; import {ChatActionID} from "../actions/ChatActionID"; import {ChatAppDispatcher} from "../dispatcher/ChatDispatcher"; import EventEmitter = require('eventemitter3'); const CHANGE_EVENT = 'change'; interface MapStringTo<T> { [key:string] : T; } export interface ThreadData { id : string, lastMessage : MessageData, name : string, } type ThreadMap = MapStringTo<ThreadData> let _threads: ThreadMap = {}; let _currentID : string; class ThreadStoreStatic extends EventEmitter { private dispatchToken : string; constructor() { super(); } public setDispatchToken(dispatchToken : string) : void { this.dispatchToken = dispatchToken; } public getDispatchToken() : string { return this.dispatchToken; } public emitChange() : void { this.emit(CHANGE_EVENT); } public addChangeListener(callback: () => void): void { this.on(CHANGE_EVENT, callback); } public removeChangeListener(callback: () => void): void { this.removeListener(CHANGE_EVENT, callback); } public init(rawMessages : RawMessage[]) { rawMessages.forEach((message : RawMessage) => { const threadID = message.threadID; const thread = _threads[threadID]; if (thread && thread.lastMessage.timestamp > message.timestamp) { return; } _threads[threadID] = { id : threadID, name : message.threadName, lastMessage : ChatMessageUtil.convertRawMessage(message, _currentID) } }); if (!_currentID) { let allChrono = this.getAllChrono(); _currentID = allChrono[allChrono.length - 1].id; } _threads[_currentID].lastMessage.isRead = true; } public get(id : string): ThreadData { return _threads[id]; } public getAll(): ThreadMap { return _threads; } public getAllChrono(): ThreadData[] { let orderedThreads : ThreadData[] = []; for (let id in _threads) { let thread = _threads[id]; orderedThreads.push(thread); } orderedThreads.sort((a : ThreadData,b : ThreadData) => { if (a.lastMessage.date < b.lastMessage.date) { return -1; } else if (a.lastMessage.date > b.lastMessage.date) { return 1; } return 0; }); return orderedThreads; } public getCurrentID() : string { return _currentID; } public getCurrent() : ThreadData { return this.get(this.getCurrentID()); } } export var ThreadStore: ThreadStoreStatic = new ThreadStoreStatic(); ThreadStore.setDispatchToken(ChatAppDispatcher.register((action: ChatAction) => { switch (action.type) { case ChatActionID.CLICK_THREAD: _currentID = action.threadID; _threads[_currentID].lastMessage.isRead = true; ThreadStore.emitChange(); break; case ChatActionID.RECEIVE_RAW_MESSAGES: ThreadStore.init(action.rawMessages); ThreadStore.emitChange(); break; default: // do nothing } }));
# Nessa aula, vamos continuar nossos estudos de funções em Python, aprendendo mais sobre Interactive Help em Python, # o uso de docstrings para documentar nossas funções, argumentos opcionais para dar mais dinamismo em funções Python, # escopo de variáveis e retorno de resultados. print(f'{"Parâmetros Opcionais":=^40}') # Parâmetros Opcionais # para que não tenha erros na quantidade de parametros recebidos, voce pode inicializar eles na passagem da chamada da função. # Exemplo com a função somar() def somar(a=0,b=0,c=0): s = a + b + c print(f'A Soma vale {s}.') #chamad da função somar(2,3,4) somar(2,8) somar(b=3,a=5) print(f'{"Utilizando o RETURN":=^40}') # utilizando o retorno de resultado. # Exemplo com a função somar() def somar(a=0,b=0,c=0): s = a + b + c return s #chamad da função r1 = somar(3,5,7) r2 = somar(9,2) r3 = somar(b=4,a=7) print(f'A Soma dos valores são {r1}, {r2} e {r3}.')
/** * Recursive function to read objects from a specific level in the xml. * * Nowadays there are quite a few of them : * - Layers : a diagram may have different layers, but this function does *not* * add the created objects to them as it does not know on which nesting level it * is called. So the topmost caller must add the returned objects to the layer. * - Groups : groups in itself can have an arbitrary nesting level including other * groups or objects or both of them. A group not containing any objects is by * definition useless. So it is not created. This is to avoid trouble with some older * diagrams which happen to be saved with empty groups. * - Parents : if the parent relations would have been there from the beginning of * Dias file format they probably would have been added as nesting level * themselves. But to maintain forward compatibility (allow to let older versions * of Dia to see as much as possible) they were added all on the same level and * the parent child relation is reconstructed from additional attributes. */ static GList * read_objects(xmlNodePtr objects, GHashTable *objects_hash,const char *filename, DiaObject *parent, GHashTable *unknown_objects_hash) { GList *list; DiaObjectType *type; DiaObject *obj; ObjectNode obj_node; char *typestr; char *versionstr; char *id; int version; xmlNodePtr child_node; list = NULL; obj_node = objects->xmlChildrenNode; while ( obj_node != NULL) { if (xmlIsBlankNode(obj_node)) { obj_node = obj_node->next; continue; } if (!obj_node) break; if (xmlStrcmp(obj_node->name, (const xmlChar *)"object")==0) { typestr = (char *) xmlGetProp(obj_node, (const xmlChar *)"type"); versionstr = (char *) xmlGetProp(obj_node, (const xmlChar *)"version"); id = (char *) xmlGetProp(obj_node, (const xmlChar *)"id"); version = 0; if (versionstr != NULL) { version = atoi(versionstr); xmlFree(versionstr); } type = object_get_type((char *)typestr); if (!type) { if (g_utf8_validate (typestr, -1, NULL) && NULL == g_hash_table_lookup(unknown_objects_hash, typestr)) g_hash_table_insert(unknown_objects_hash, g_strdup(typestr), 0); } else { obj = type->ops->load(obj_node, version, filename); list = g_list_append(list, obj); if (parent) { obj->parent = parent; parent->children = g_list_append(parent->children, obj); } g_hash_table_insert(objects_hash, g_strdup((char *)id), obj); child_node = obj_node->children; while(child_node) { if (xmlStrcmp(child_node->name, (const xmlChar *)"children") == 0) { GList *children_read = read_objects(child_node, objects_hash, filename, obj, unknown_objects_hash); list = g_list_concat(list, children_read); break; } child_node = child_node->next; } } if (typestr) xmlFree(typestr); if (id) xmlFree (id); } else if (xmlStrcmp(obj_node->name, (const xmlChar *)"group")==0 && obj_node->children) { GList *inner_objects = read_objects(obj_node, objects_hash, filename, NULL, unknown_objects_hash); if (inner_objects) { obj = group_create(inner_objects); #ifdef USE_NEWGROUP { DiaObject *newgroup; GList *objects; Point lower_right; type = object_get_type("Misc - NewGroup"); lower_right = obj->position; newgroup = type->ops->create(&lower_right, NULL, NULL, NULL); list = g_list_append(list, newgroup); for (objects = group_objects(obj); objects != NULL; objects = g_list_next(objects)) { DiaObject *subobj = (DiaObject *) objects->data; list = g_list_append(list, subobj); subobj->parent = newgroup; newgroup->children = g_list_append(newgroup->children, subobj); if (subobj->bounding_box.right > lower_right.x) { lower_right.x = subobj->bounding_box.right; } if (subobj->bounding_box.bottom > lower_right.y) { lower_right.y = subobj->bounding_box.bottom; } } newgroup->ops->move_handle(newgroup, newgroup->handles[7], &lower_right, NULL, HANDLE_MOVE_CREATE_FINAL, 0); group_destroy_shallow(obj); } #else list = g_list_append(list, obj); #endif } } else { } obj_node = obj_node->next; } return list; }
/** * Data Transfer object (DTO) for Protocol. A project may represent a Protcol for scheduling * questionnaires. * * @see <a href="https://github.com/RADAR-base/RADAR-aRMT-protocols">aRMT Protocols</a> * @author yatharthranjan */ @Data public class Protocol { private String version; private String schemaVersion; private String name; private List<String> healthIssues; private List<Assessment> protocols; }
This article is over 1 year old Defectors now being offered $860,000 cash reward for sensitive information about Kim Jong-un regime South Korea will quadruple the cash reward it offers to defectors from North Korea who pass over classified information about the reclusive state, reports said on Sunday. The government currently offers up to $217,000 to defectors from the north with sensitive information about the state and its regime. It is now offering $860,000 (£700,000), the first increase in reward money in two decades. The rewards would go to “people who provide intelligence and knowledge that can enhance South Korea’s security”, the Yonhap news agency reported. The sums paid would be determined on the basis of the importance of the intelligence, Yonhap said. Other amounts would be given to soldiers who defected with weapons. The cash incentive is aimed at encouraging more members of the north’s elite to flee to the south, it added. “One of the biggest reasons why North Koreans are hesitant about defecting is because they are fearful of [how they would make a living] after they come to South Korea,” Yonhap cited a ministry official as saying. Facebook Twitter Pinterest Thae Yong-ho, the former North Korean deputy ambassador to the UK who defected last August. Photograph: Ed Jones/AP High-profile defectors have served as a vital source of intelligence about the Pyongyang government over the years. Last August, North Korea’s former deputy ambassador to Britain Thae Yong-ho became one of the highest-ranking defectors. He has vowed to raise awareness about the “gruesome realities” of his country. Analysts say Thae may have invaluable information about the secretive regime of Kim Jong-un, who has been in power since 2011. Since defecting, he is likely to have been grilled by foreign intelligence agencies over Kim’s leadership, the mood among North Korea’s ruling elite and the fate of senior members of the last government, some of whom have been purged and executed. The move follows the killing of the North Korean leader’s estranged half-brother at Kuala Lumpur airport in Malaysia in February. Kim Jong-nam, 48, was exposed to the super-toxic VX nerve agent that killed him within minutes. Malaysian police have issued an arrest warrant for an employee at North Korea’s state airline over the fatal poisoning.
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.06.12 at 09:16:35 AM EDT // package com.vmware.vim25; /** * */ @SuppressWarnings("all") public class ProfileParameterMetadataParameterRelationMetadata extends DynamicData { private final static String[] NULL_RELATION_TYPES_ARRAY = new String[ 0 ] ; public String[] relationTypes; private final static Object[] NULL_VALUES_ARRAY = new Object[ 0 ] ; public Object[] values; public ProfilePropertyPath path; public int minCount; public int maxCount; public String[] getRelationTypes() { if ((relationTypes) == null) { return (NULL_RELATION_TYPES_ARRAY); } return relationTypes; } public void setRelationTypes(String[] relationTypes) { this.relationTypes = relationTypes; } public Object[] getValues() { if ((values) == null) { return (NULL_VALUES_ARRAY); } return values; } public void setValues(Object[] values) { this.values = values; } public ProfilePropertyPath getPath() { return path; } public void setPath(ProfilePropertyPath path) { this.path = path; } public int getMinCount() { return minCount; } public void setMinCount(int minCount) { this.minCount = minCount; } public int getMaxCount() { return maxCount; } public void setMaxCount(int maxCount) { this.maxCount = maxCount; } }
Okay so that may seem an obvious statement to make, but it was only when I went behind the camera and made my first short film did I truly understand how different it is. As a theatre director I am used to allowing plenty of rehearsal time to allow an actor to build his part, improvise, connect to her partner, find the moment etc but on a film set when time is ticking away and your First AD keeps reminding you of schedules and set-ups and you often shoot out of sequence, how can you keep that organic creativity flowing? Also in theatre my indication of my best work is when the actors make the play their own once it’s up in front of an audience and work off of that new energy, a factor entirely devoid in film. I have attended brilliant courses on working with actors for film such as Tools for Directing Actors with Simon Phillips at The Directors Guild for Great Britain and completely understand the theory of it but I am still working on the practicalities. When I shot my first short film in 2011 I was overwhelmed by the technical aspects and I admit, I occasionally forgot the story or character or felt pressured by time… Luckily I had two very experienced actors and a wonderfully talented crew for support so whilst my first short is flawed in a way most first time attempts are; it was a very enjoyable learning curve. I am very much a film directing novice, since Brainstorm, I have mainly worked on trailer shorts for my theatre projects, however here are a couple of tips I have learnt and discovered about directing actors for camera… Think about what you want your audience to see specifically in that character’s journey, you will discuss it with your DOP for camera angles, lighting effects etc. Talk to your actor too so they understand what you are going for. Get them out of their head and into their gut. Give them permission to feel it instead of think about it. Ask your actor what they can see, hear, feel and even smell in that moment. Keep them focused on visceral and sensory sources; this will register on camera beautifully. If you can, give them play time. Allow them to be at ease and to play around within the structure of the frame and the moment. A good actor’s instincts are invaluable. Give them permission to listen to them and make sure you do too. The very controlled environment of film can make time feel like a pressure, don’t let it. And so with that…here’s the link to my first short. I had wanted to do a film course and couldn’t afford to, so instead I bribed some talented friends with food, booze and some expenses to give up a weekend and to help me learn about film-making. I learnt loads and have some more planned this year now I have an idea of what it’s all about, but I’m proud of my first go. Enjoy.Brainstorm by Richard Smith Directed by moi Advertisements
/** * A class to manage the location of horses in a barn. */ public class HorseBarn { // The stalls or spaces in the barn. Each array element holds a reference to the horse // that is currently occupying the space. A null value indicates an empty space. private ArrayList<Horse> spaces = new ArrayList<Horse>(); private ArrayList<Horse> originalOrder = new ArrayList<Horse>(); /** * Constructor for the HorseBarn class. Loads data from the horsedata.txt file * and populates the ArrayList spaces. If a blank line occurs in the data file, * the array element is assigned a value of null to indicate the absense of a horse. */ public HorseBarn() { // a try is like an if statement, "throwing" an error if the body of the try fails try { Scanner sc = new Scanner(new File("horsedata.txt")); // The Scanner method hasNextLine returns true if there is // another line of input while (sc.hasNextLine()) { // String method trim removes whitepsace from the beginning // and end of strings String temp = sc.nextLine().trim(); if (temp.equals("")) { // no horse in this stall, add a null entry spaces.add(null); } else { // String method split splits this string based on the // specified token and returns an array of individual substrings String[] tokens = temp.split(","); String name = tokens[0]; int weight = Integer.parseInt(tokens[1]); // add the horse to the array list spaces.add(new Horse(name, weight)); } } } catch (Exception e) { System.out.println("Error reading or parsing horsedata.txt" + e); } originalOrder = spaces; } /** * Displays pairs of horses * */ public void pairUp(){ System.out.println(spaces.size()); for(int i = 0; i < spaces.size(); i+=2){ Horse horse = spaces.get(i); Horse pair = null; if(spaces.size()-1 >= i+1){ pair = spaces.get(i+1); }else{ pair = new Horse("Partnerless", 1); } System.out.println(horse.getName() + " " + pair.getName()); } } /** * Randomize List */ public void randomizeList(){ Collections.shuffle(spaces); } /** * Restore spaces original */ public void restoreSpaces(){ spaces = originalOrder; } /* * Returns the average weight of all the horses in the barn. * * @return the average weight */ public int getAverageWeight(){ int averageWeight = 0; for(Horse horse: spaces){ if(horse != null){ averageWeight += horse.getWeight(); } } return averageWeight/spaces.size(); } /** * Displays the horses that weigh more than the average weight * */ public void aboveAverageWeight(){ for(Horse horse: spaces){ if(horse != null){ // this is nested because of null check // otherwise could throw null point exception if(horse.getWeight() > getAverageWeight()){ System.out.println(horse.getName() + ": "+horse.getWeight()); } } } } /** * Displays the heaviest and lightest horse */ public void heaviestAndLightest(){ Horse heaviest = null; int heaviestWeight = 0; Horse lightest = null; int lightestWeight = Integer.MAX_VALUE; for(Horse horse: spaces){ if(horse != null){ // this is nested because of null check // otherwise could throw null point exception if(heaviestWeight < horse.getWeight()){ heaviest = horse; heaviestWeight = horse.getWeight(); } if(lightestWeight > horse.getWeight()){ lightest = horse; lightestWeight = horse.getWeight(); } } } System.out.println(lightest + ": " + lightestWeight); System.out.println(heaviest + ": " + heaviestWeight); } /** * Returns the current list of spaces in the barn. If a space does not * have a horse in it, the element will be null. * * @return the ArrayList of spaces */ public ArrayList<Horse> getSpaces() { return spaces; } }
// argument. Delete all edges to all other towns before deleting this town public void deleteTown(String town){ Node townNd = null; for (Node nd : graph) { if(nd.label.equals(town)) townNd = nd; } if(townNd == null){ System.out.print("Town not found"); }else{ for (Node nd : graph) { deleteEdge(townNd, nd); } } }
President Ram Nath Kovind meeting ministers and other leaders after the oath taking ceremony. (Photo: Doordarshan) A section of BJP MPs shouted Jai Shri Ram after Ram Nath Kovind was sworn in as India's 14th President in a ceremony in Parliament's Central Hall today. Full text: President Ram Nath Kovind's speech in Parliament The slogan Jai Shri Ram originated during the Ram Janmabhoomi-Babari Masjid movement in the 80s that catapulted the BJP from a marginal player to India's political mainstream. Kovind, former Bihar Governor, is a long-time member of the Rashtriya Swayamsevak Sangh (RSS), the ideological fountainhead of the BJP. President inspecting Guard of Honour. pic.twitter.com/8LbBvDveSx - All India Radio News (@airnewsalerts) July 25, 2017 This is not the first time Jai Shri Ram slogans were raised inside Parliament. In March this year, Prime Minister Narendra Modi was greeted with the same slogan by the BJP MPs when he walked into the House following the party's stunning victory in Uttar Pradesh and Uttarakhand Assembly elections. Opposition leaders have often accused Modi of using the presidential race, which Kovind won easily in an electoral college last week, to further a divisive Hindutva agenda. Kovind's rise also caps a series of top appointments backed by Modi - including naming hardline Yogi Adityanath as Chief Minister of Uttar Pradesh - that tighten the grip of the Hindu right on key public offices. ALSO READ: What President Ram Nath Kovind said in his first address after taking oath Ram Nath Kovind set to enter Rashtrapati Bhavan: All about 340-room Raisina Hill palace BJP's presidential candidate Ram Nath Kovind: An ardent dog lover Watch the video here: Jai Shri Ram: How some BJP MPs greeted Ram Nath Kovind after his swearing-in
// deleteNode deletes node from sc.Nodes. func (sc *SchedulerCache) deleteNode(node *corev1.Node) error { if _, ok := sc.Nodes[node.Name]; !ok { return fmt.Errorf("node <%s> does not exist", node.Name) } numaInfo := sc.Nodes[node.Name].NumaInfo if numaInfo != nil { klog.V(3).Infof("delete numatopo <%s/%s>", numaInfo.Namespace, numaInfo.Name) err := sc.vcClient.NodeinfoV1alpha1().Numatopologies().Delete(context.TODO(), numaInfo.Name, metav1.DeleteOptions{}) if err != nil { klog.Errorf("delete numatopo <%s/%s> failed.", numaInfo.Namespace, numaInfo.Name) } } delete(sc.Nodes, node.Name) return nil }
<reponame>iamdual/whois-parser package com.github.iamdual.whoisparser.templates.tld; import com.github.iamdual.whoisparser.templates.DefaultTemplate; /** * A WHOIS pattern of .br TLD. * * @author: <NAME> <<EMAIL>> * @license: Apache-2.0 License */ public class DotBr extends DefaultTemplate { @Override public String getWhoisAddress() { return "whois.registro.br"; } @Override public String getRegexAvailable() { return "% No match for .+"; } @Override public String getRegexExpiryDate() { // expires: 20210518 return "expires:[\\s]+([0-9]+)"; } @Override public String getFormatExpiryDate() { return "yyyyMMdd"; } @Override public String getRegexUpdatedDate() { // changed: 20191105 return "changed:[\\s]+([0-9]+)"; } @Override public String getFormatUpdatedDate() { return "yyyyMMdd"; } }
<gh_stars>0 import * as dotenv from 'dotenv' dotenv.config() import { HardhatUserConfig } from 'hardhat/types' import { task } from 'hardhat/config' // Plugins import '@nomiclabs/hardhat-ethers' import '@nomiclabs/hardhat-etherscan' import '@nomiclabs/hardhat-waffle' import 'hardhat-abi-exporter' import 'hardhat-gas-reporter' import 'hardhat-contract-sizer' import '@tenderly/hardhat-tenderly' import '@openzeppelin/hardhat-upgrades' import '@typechain/hardhat' import '@nomiclabs/hardhat-web3' import web3 from 'web3' // Networks type Accounts = string[] | { mnemonic: string } interface NetworkConfig { network: string chainId: number gas?: number | 'auto' gasPrice?: number | 'auto' accounts?: Accounts } const networkConfigs: NetworkConfig[] = [ { network: 'mainnet', chainId: 1 }, { network: 'ropsten', chainId: 3 }, { network: 'rinkeby', chainId: 4, accounts: [process.env.PRIVATE_KEY] }, { network: 'kovan', chainId: 42 }, ] function getAccountMnemonic() { return process.env.MNEMONIC || '' } function getDefaultProviderURL(network: string) { return `https://${network}.infura.io/v3/${process.env.INFURA_KEY}` } function setupDefaultNetworkProviders(buidlerConfig) { for (const netConfig of networkConfigs) { let accounts: Accounts = [] if (netConfig.accounts) { accounts = netConfig.accounts } else { accounts = { mnemonic: getAccountMnemonic() } } buidlerConfig.networks[netConfig.network] = { chainId: netConfig.chainId, url: getDefaultProviderURL(netConfig.network), gas: netConfig.gasPrice || 'auto', gasPrice: netConfig.gasPrice || 'auto', accounts: accounts, } } } // Tasks task('accounts', 'Prints the list of accounts', async (taskArgs, bre) => { const accounts = await bre.ethers.getSigners() for (const account of accounts) { console.log(await account.getAddress()) } }) task('balance', "Prints an account's balance") .addParam('account', "The account's address") .setAction(async (taskArgs) => { const web3Instance = new web3(getDefaultProviderURL('rinkeby')) const account = web3Instance.utils.toChecksumAddress(taskArgs.account) const balance = await web3Instance.eth.getBalance(account) console.log(web3Instance.utils.fromWei(balance, 'ether'), 'ETH') }) // Config const config: HardhatUserConfig = { paths: { sources: './contracts', tests: './test', artifacts: './build/contracts', }, solidity: { compilers: [ { version: '0.8.4', settings: { optimizer: { enabled: true, runs: 200, }, }, }, ], }, defaultNetwork: 'hardhat', networks: { hardhat: { chainId: 1337, loggingEnabled: false, gas: 12000000, gasPrice: 'auto', blockGasLimit: 12000000, accounts: { mnemonic: 'myth like bonus scare over problem client lizard pioneer submit female collect', }, }, ganache: { chainId: 1337, url: 'http://localhost:8545', }, }, etherscan: { apiKey: process.env.ETHERSCAN_API_KEY, }, gasReporter: { enabled: process.env.REPORT_GAS ? true : false, showTimeSpent: true, currency: 'USD', outputFile: 'reports/gas-report.log', }, typechain: { outDir: 'build/types', target: 'ethers-v5', }, abiExporter: { path: './build/abis', clear: false, flat: true, }, tenderly: { project: process.env.TENDERLY_PROJECT, username: process.env.TENDERLY_USERNAME, }, contractSizer: { alphaSort: true, runOnCompile: false, disambiguatePaths: true, }, } setupDefaultNetworkProviders(config) export default config
/** * Created by Yuriy Chernyshov * At Android Studio * On 12/14/14 * E-Mail: [email protected] * * Utility class to help on queue related tasks. * Media IDs used on browseable items of {@link android.media.browse.MediaBrowser}. */ public final class MediaIDHelper { public static final String MEDIA_ID_ROOT = "__ROOT__"; public static final String MEDIA_ID_ALL_CATEGORIES = "__ALL_CATEGORIES__"; public static final String MEDIA_ID_COUNTRY_STATIONS = "__COUNTRY_STATIONS__"; public static final String MEDIA_ID_COUNTRIES_LIST = "__COUNTRIES_LIST__"; public static final String MEDIA_ID_FAVORITES_LIST = "__FAVORITES_LIST__"; public static final String MEDIA_ID_LOCAL_RADIO_STATIONS_LIST = "__MEDIA_ID_LOCAL_RADIO_STATIONS_LIST__"; public static final String MEDIA_ID_PARENT_CATEGORIES = "__PARENT_CATEGORIES__"; public static final String MEDIA_ID_CHILD_CATEGORIES = "__CHILD_CATEGORIES__"; public static final String MEDIA_ID_RADIO_STATIONS_IN_CATEGORY = "__RADIO_STATIONS_IN_CATEGORY__"; public static final String MEDIA_ID_SEARCH_FROM_APP = "__SEARCH_FROM_APP__"; public static final String MEDIA_ID_POPULAR_STATIONS = "__POPULAR_STATIONS__"; public static final String MEDIA_ID_ALL_STATIONS = "__ALL_STATIONS__"; public static final String MEDIA_ID_RECENT_PLAYED_SONGS = "__RECENT_PLAYED_SONGS__"; public static final String MEDIA_ID_RECENT_ADDED_STATIONS = "__RECENT_ADDED_STATIONS__"; public static final String MEDIA_ID_LIST_ENDED = "MEDIA_ID_LIST_ENDED"; /** * */ private static final String[] IDS = { MEDIA_ID_ALL_CATEGORIES, MEDIA_ID_CHILD_CATEGORIES, MEDIA_ID_COUNTRIES_LIST, MEDIA_ID_COUNTRY_STATIONS, MEDIA_ID_FAVORITES_LIST, MEDIA_ID_LOCAL_RADIO_STATIONS_LIST, MEDIA_ID_PARENT_CATEGORIES, MEDIA_ID_RADIO_STATIONS_IN_CATEGORY, MEDIA_ID_ROOT, MEDIA_ID_SEARCH_FROM_APP, MEDIA_ID_ALL_STATIONS, MEDIA_ID_POPULAR_STATIONS, MEDIA_ID_RECENT_PLAYED_SONGS, MEDIA_ID_RECENT_ADDED_STATIONS }; /** * Default constructor. */ private MediaIDHelper() { super(); } /** * Gets Id that is use to extract correct command implementation of the * {@link com.yuriy.openradio.business.mediaitem.MediaItemCommand}. * * @param value String pattern that represents loaded menu item. * * @return Extracted Id. */ public static String getId(final String value) { if (value == null) { return null; } for (final String id : IDS) { if (value.startsWith(id) || value.equals(id)) { if (!TextUtils.isEmpty(getCountryCode(value))) { return MEDIA_ID_COUNTRY_STATIONS; } return id; } } return null; } /** * Checks whether provided category Id is belongs to the "Stations in the Country" Id. * If {@code true} - extract Country Code and return it, in case of {@code false} - return null. * * @param value Category Id. * * @return The value of the Country Code, {@code null} - otherwise. */ public static String getCountryCode(final String value) { if (TextUtils.isEmpty(value)) { return null; } if (!value.startsWith(MEDIA_ID_COUNTRIES_LIST) || value.equals(MEDIA_ID_COUNTRIES_LIST)) { return null; } final String result = value.substring(value.length() - 2, value.length()); if (!TextUtils.isEmpty(value) && result.length() == 2) { return result.toUpperCase(); } return null; } /** * Returns whether or not current Catalog is sortable, for instance Favorites or * Local Radio Stations. * * @param categoryMediaId Category Media Id. * @return {@code true} in case of Catalog is sortable, {@code false} otherwise. */ public static boolean isMediaIdSortable(final String categoryMediaId) { return MEDIA_ID_FAVORITES_LIST.equals(categoryMediaId) || MEDIA_ID_LOCAL_RADIO_STATIONS_LIST.equals(categoryMediaId); } /** * Returns whether or not current Catalog is refreshable once end of list reached, for instance * Local Radio Stations. * * @param categoryMediaId Category Media Id. * @return {@code true} in case of Catalog is refreshable, {@code false} otherwise. */ public static boolean isMediaIdRefreshable(final String categoryMediaId) { return !TextUtils.isEmpty(categoryMediaId) && (MEDIA_ID_ALL_STATIONS.equals(categoryMediaId) || MEDIA_ID_COUNTRY_STATIONS.equals(categoryMediaId) || MEDIA_ID_POPULAR_STATIONS.equals(categoryMediaId) || MEDIA_ID_RADIO_STATIONS_IN_CATEGORY.equals(categoryMediaId) || MEDIA_ID_RECENT_ADDED_STATIONS.equals(categoryMediaId) || MEDIA_ID_RECENT_PLAYED_SONGS.equals(categoryMediaId) || categoryMediaId.contains(MEDIA_ID_CHILD_CATEGORIES)); } }
""" Draw samples and apply KDSD and MMD tests to the Bernoulli RBM. """ from __future__ import division from util import * from kernels import * from ksd import * from ksd_utils import * from mmd import * from rbm import * if __name__ == "__main__": n, sigma, seed, res_dir = sys.argv[1:] n = int(n) # Sample size sigma = float(sigma) # Linear-spacing # sigma = 10.**float(sigma) # Log-spacing seed = int(seed) # Random seed print "n = %d\nsigma=%.1f\nseed=%s\nres_dir=%s\n" % \ (n, sigma, seed, res_dir) rand.seed(seed) m = 50 # Number of visible units k = 25 # Number of hidden units W = rand.normal(size=(m, k)) / m bvec = rand.normal(size=(m,)) cvec = rand.normal(size=(k,)) # ------------------------- Draw MCMC samples ------------------------- # print "Drawing MCMC samples ..." model_p = RBM(m, k, W, bvec, cvec) # Null model samples_p, _ = model_p.sample(num_iters=1e5, num_samples=n) # Set q to perturbed dist or true p true_dist = rand.binomial(n=1, p=.5) # 0 for p, 1 for q # Add Gaussian noise W_q = W + rand.normal(loc=0, scale=sigma) if true_dist else W model_q = RBM(m, k, W_q, bvec, cvec) samples_q, _ = model_q.sample(num_iters=1e5, num_samples=n) # ------------------------- Perform KDSD test ------------------------- # print "Performing KDSD test ..." model = RBM(m, k, W, bvec, cvec) # Null model ksd = KSD(neg_fun=model.neg, score_fun=model.score, kernel_fun=exp_hamming_kernel) # Use null model kappa_vals = ksd.compute_kappa(samples=samples_q) # Compute U-statistics and bootstrap intervals ksd_stats, _ = ksd_est([kappa_vals]) ksd_boot_list, ksd_thres_list = ksd_boot([kappa_vals]) ksd_pvals = ksd_pvalue(ksd_boot_list, ksd_stats) ksd_stat = ksd_stats[0] ksd_thres = ksd_thres_list[0] ksd_pval = ksd_pvals[0] ksd_pred = 1 * (ksd_stat > ksd_thres) # 0 for p, 1 for q # ------------------------- Perform MMD test ------------------------- # print "Performing MMD test ..." mmd = MMD(kernel_fun=exp_hamming_kernel) mmd_stat, mmd_thres, mmd_pval, _ = mmd.perform_test(samples_p, samples_q) mmd_pred = 1 * (mmd_stat > mmd_thres) # 0 for p, 1 for q res = {'n': n, 'sigma': sigma, 'true_dist': true_dist, 'ksd_stat': ksd_stat, 'ksd_thres': ksd_thres, 'ksd_pval': ksd_pval, 'ksd_pred': ksd_pred, 'mmd_stat': mmd_stat, 'mmd_thres': mmd_thres, 'mmd_pval': mmd_pval, 'mmd_pred': mmd_pred} pckl_write(res, res_dir + "pow-rbm%.3f-n%d-m%d-k%d-seed%d.res" % (sigma, n, m, k, seed)) print 'Finished!'
def _init_config_parser(common, subparsers): config_parser = subparsers.add_parser( ACTION_CONFIG, parents=[common], description='Config related actions', add_help=False) config_subparsers = config_parser.add_subparsers(dest='config_action') show_config_parser = config_subparsers.add_parser( ACTION_CONFIG_SHOW, parents=[common], description='Print config used by exec command or config specified by an option', add_help=False) show_config_parser.add_argument('-dc', '--def-config', action='store_true', help='show default config') create__config_parser = config_subparsers.add_parser(ACTION_CONFIG_CREATE, parents=[common], description='create config file', add_help=False) create__config_parser.add_argument("--overwrite", action="store_true", help="overwrite config file to default")
package cn.edu.seu.alumni_server.dao.mapper; import cn.edu.seu.alumni_server.controller.dto.MessageDTO; import cn.edu.seu.alumni_server.dao.entity.Message; import org.springframework.stereotype.Repository; import tk.mybatis.mapper.common.Mapper; import java.util.List; @Repository public interface MessageMapper extends Mapper<Message> { List<MessageDTO> getMessagesByAccountId(Long accountId,Integer status); }
#!/usr/bin/env python # pylint: disable=W0212 def having(self, aggregations, test): """ Create a new :class:`.TableSet` with only those tables that pass a test. This works by applying a sequence of :class:`Aggregation` instances to each table. The resulting dictionary of properties is then passed to the :code:`test` function. This method does not modify the underlying tables in any way. :param aggregations: A list of tuples in the format :code:`(name, aggregation)`, where each :code:`aggregation` is an instance of :class:`.Aggregation`. :param test: A function that takes a dictionary of aggregated properties and returns :code:`True` if it should be included in the new :class:`.TableSet`. :type test: :class:`function` :returns: A new :class:`.TableSet`. """ new_tables = [] new_keys = [] for key, table in self.items(): props = table.aggregate(aggregations) if test(props): new_tables.append(table) new_keys.append(key) return self._fork(new_tables, new_keys)
package com.yarolegovich.materialprefsample; import android.os.Bundle; import com.yarolegovich.mp.MaterialChoicePreference; import com.yarolegovich.mp.MaterialPreferenceScreen; import com.yarolegovich.mp.view.ListEntry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by yarolegovich on 15.05.2016. * edit by loongg-max on 19.08.12 */ public class AppConfigsActivity extends ToolbarActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_config); setupToolbar(); MaterialPreferenceScreen screen = findViewById(R.id.preference_screen); screen.setVisibilityController(R.id.pref_auto_loc, Arrays.asList(R.id.pref_location), false); //add by loongg-max //用代码设置参数 MaterialChoicePreference materialChoicePreference = findViewById(R.id.choice); //------------------方式一,直接在xml中设置(必须设置)-------------------------- //------------- 方式二 (设置方式二后,一失效)------------------------ CharSequence[] entryName = {"第一个", "第二个", "第三个"}; CharSequence[] entryValue = {"1", "2", "3"}; boolean[] isNeedVip = {false, true, true}; materialChoicePreference.setEntryNames(entryName); materialChoicePreference.setEntryValues(entryValue); materialChoicePreference.setIsNeedVip(isNeedVip); //--------------方式三 (设置方式三后,一二失效)----------------------------------- List<ListEntry> entries = new ArrayList<>(); entries.add(new ListEntry("xxxxx", "xxx", 0, false, false)); entries.add(new ListEntry("sssssss", "sss", 0, false, true)); entries.add(new ListEntry("yyyyy", "yyy", 0, true, true)); materialChoicePreference.setEntries(entries); } }
/** * A simple implementation of {@link StephenerializationService}. * @author Stephen Hopper * */ public class SimpleStephenerializationService implements StephenerializationService { private Stephenerializer stephenerializer; private Destephenerializer destephenerializer; /** * {@inheritDoc} */ public void stephenerialize(Object object, ObjectOutputStream streamer, Class<?> clazz) { getStephenerializer().stephenerialize(object, createStephenerializationStream(streamer), clazz); } /** * {@inheritDoc} */ public void destephenerialize(Object object, ObjectInputStream streamer, Class<?> clazz) { getDestephenerializer().destephenerialize(object, createDestephenerializationStream(streamer), clazz); } /** * @param stephenerializer The stephenerializer to use. */ public void setStephenerializer(Stephenerializer stephenerializer) { this.stephenerializer = stephenerializer; } /** * Returns the current {@link Stephenerializer} or creates a new one * if one does not already exists. * @return A stephenerializer instance. */ public Stephenerializer getStephenerializer() { if (stephenerializer == null) { stephenerializer = new SimpleStephenerializer(); } return stephenerializer; } /** * @param destephenerializer The destephenerializer to use. */ public void setDestephenerializer(Destephenerializer destephenerializer) { this.destephenerializer = destephenerializer; } /** * Returns the current {@link Destephenerializer} or creates a new one * if one does not already exist. * @return A destephenerializer instance. */ public Destephenerializer getDestephenerializer() { if (destephenerializer == null) { destephenerializer = new SimpleDestephenerializer(); } return destephenerializer; } /** * Creates a new {@link StephenerializationStream}. * @param streamer The stream to wrap. * @return A new {@link StephenerializationStream}. */ private StephenerializationStream createStephenerializationStream(ObjectOutputStream streamer) { return new SimpleStephenerializationStream(streamer); } /** * Creates a new {@link DestephenerializationStream}. * @param streamer The stream to wrap. * @return A new {@link DestephenerializationStream}. */ private DestephenerializationStream createDestephenerializationStream(ObjectInputStream streamer) { return new SimpleDestephenerializationStream(streamer); } }
<gh_stars>1-10 // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.1 // protoc v3.17.3 // source: ras/messages/v1/working_servers_messages.proto package messagesv1 import ( _ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2/options" _ "github.com/v8platform/protoc-gen-go-ras/plugin/ras/encoding" v1 "github.com/v8platform/protos/gen/v8platform/serialize/v1" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type GetWorkingServersRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ClusterId string `protobuf:"bytes,1,opt,name=cluster_id,json=clusterId,proto3" json:"cluster_id,omitempty"` } func (x *GetWorkingServersRequest) Reset() { *x = GetWorkingServersRequest{} if protoimpl.UnsafeEnabled { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GetWorkingServersRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetWorkingServersRequest) ProtoMessage() {} func (x *GetWorkingServersRequest) ProtoReflect() protoreflect.Message { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetWorkingServersRequest.ProtoReflect.Descriptor instead. func (*GetWorkingServersRequest) Descriptor() ([]byte, []int) { return file_ras_messages_v1_working_servers_messages_proto_rawDescGZIP(), []int{0} } func (x *GetWorkingServersRequest) GetClusterId() string { if x != nil { return x.ClusterId } return "" } type GetWorkingServersResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Servers []*v1.ServerInfo `protobuf:"bytes,1,rep,name=servers,proto3" json:"servers,omitempty"` } func (x *GetWorkingServersResponse) Reset() { *x = GetWorkingServersResponse{} if protoimpl.UnsafeEnabled { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GetWorkingServersResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetWorkingServersResponse) ProtoMessage() {} func (x *GetWorkingServersResponse) ProtoReflect() protoreflect.Message { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetWorkingServersResponse.ProtoReflect.Descriptor instead. func (*GetWorkingServersResponse) Descriptor() ([]byte, []int) { return file_ras_messages_v1_working_servers_messages_proto_rawDescGZIP(), []int{1} } func (x *GetWorkingServersResponse) GetServers() []*v1.ServerInfo { if x != nil { return x.Servers } return nil } type GetWorkingServerInfoRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ClusterId string `protobuf:"bytes,1,opt,name=cluster_id,json=clusterId,proto3" json:"cluster_id,omitempty"` ServerId string `protobuf:"bytes,2,opt,name=server_id,json=serverId,proto3" json:"server_id,omitempty"` } func (x *GetWorkingServerInfoRequest) Reset() { *x = GetWorkingServerInfoRequest{} if protoimpl.UnsafeEnabled { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GetWorkingServerInfoRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetWorkingServerInfoRequest) ProtoMessage() {} func (x *GetWorkingServerInfoRequest) ProtoReflect() protoreflect.Message { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetWorkingServerInfoRequest.ProtoReflect.Descriptor instead. func (*GetWorkingServerInfoRequest) Descriptor() ([]byte, []int) { return file_ras_messages_v1_working_servers_messages_proto_rawDescGZIP(), []int{2} } func (x *GetWorkingServerInfoRequest) GetClusterId() string { if x != nil { return x.ClusterId } return "" } func (x *GetWorkingServerInfoRequest) GetServerId() string { if x != nil { return x.ServerId } return "" } type GetWorkingServerInfoResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Info *v1.ServerInfo `protobuf:"bytes,1,opt,name=info,proto3" json:"info,omitempty"` } func (x *GetWorkingServerInfoResponse) Reset() { *x = GetWorkingServerInfoResponse{} if protoimpl.UnsafeEnabled { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *GetWorkingServerInfoResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*GetWorkingServerInfoResponse) ProtoMessage() {} func (x *GetWorkingServerInfoResponse) ProtoReflect() protoreflect.Message { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GetWorkingServerInfoResponse.ProtoReflect.Descriptor instead. func (*GetWorkingServerInfoResponse) Descriptor() ([]byte, []int) { return file_ras_messages_v1_working_servers_messages_proto_rawDescGZIP(), []int{3} } func (x *GetWorkingServerInfoResponse) GetInfo() *v1.ServerInfo { if x != nil { return x.Info } return nil } type AddWorkingServerRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ClusterId string `protobuf:"bytes,1,opt,name=cluster_id,json=clusterId,proto3" json:"cluster_id,omitempty"` Info *v1.ServerInfo `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` } func (x *AddWorkingServerRequest) Reset() { *x = AddWorkingServerRequest{} if protoimpl.UnsafeEnabled { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AddWorkingServerRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*AddWorkingServerRequest) ProtoMessage() {} func (x *AddWorkingServerRequest) ProtoReflect() protoreflect.Message { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AddWorkingServerRequest.ProtoReflect.Descriptor instead. func (*AddWorkingServerRequest) Descriptor() ([]byte, []int) { return file_ras_messages_v1_working_servers_messages_proto_rawDescGZIP(), []int{4} } func (x *AddWorkingServerRequest) GetClusterId() string { if x != nil { return x.ClusterId } return "" } func (x *AddWorkingServerRequest) GetInfo() *v1.ServerInfo { if x != nil { return x.Info } return nil } type AddWorkingServerResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ServerId string `protobuf:"bytes,1,opt,name=server_id,json=serverId,proto3" json:"server_id,omitempty"` } func (x *AddWorkingServerResponse) Reset() { *x = AddWorkingServerResponse{} if protoimpl.UnsafeEnabled { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AddWorkingServerResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*AddWorkingServerResponse) ProtoMessage() {} func (x *AddWorkingServerResponse) ProtoReflect() protoreflect.Message { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AddWorkingServerResponse.ProtoReflect.Descriptor instead. func (*AddWorkingServerResponse) Descriptor() ([]byte, []int) { return file_ras_messages_v1_working_servers_messages_proto_rawDescGZIP(), []int{5} } func (x *AddWorkingServerResponse) GetServerId() string { if x != nil { return x.ServerId } return "" } // renamed UnregWorkingServerRequest type DeleteWorkingServerRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ClusterId string `protobuf:"bytes,1,opt,name=cluster_id,json=clusterId,proto3" json:"cluster_id,omitempty"` ServerId string `protobuf:"bytes,2,opt,name=server_id,json=serverId,proto3" json:"server_id,omitempty"` } func (x *DeleteWorkingServerRequest) Reset() { *x = DeleteWorkingServerRequest{} if protoimpl.UnsafeEnabled { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DeleteWorkingServerRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*DeleteWorkingServerRequest) ProtoMessage() {} func (x *DeleteWorkingServerRequest) ProtoReflect() protoreflect.Message { mi := &file_ras_messages_v1_working_servers_messages_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use DeleteWorkingServerRequest.ProtoReflect.Descriptor instead. func (*DeleteWorkingServerRequest) Descriptor() ([]byte, []int) { return file_ras_messages_v1_working_servers_messages_proto_rawDescGZIP(), []int{6} } func (x *DeleteWorkingServerRequest) GetClusterId() string { if x != nil { return x.ClusterId } return "" } func (x *DeleteWorkingServerRequest) GetServerId() string { if x != nil { return x.ServerId } return "" } var File_ras_messages_v1_working_servers_messages_proto protoreflect.FileDescriptor var file_ras_messages_v1_working_servers_messages_proto_rawDesc = []byte{ 0x0a, 0x2e, 0x72, 0x61, 0x73, 0x2f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x2f, 0x76, 0x31, 0x2f, 0x77, 0x6f, 0x72, 0x6b, 0x69, 0x6e, 0x67, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0f, 0x72, 0x61, 0x73, 0x2e, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x2e, 0x76, 0x31, 0x1a, 0x16, 0x72, 0x61, 0x73, 0x2f, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x2f, 0x72, 0x61, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x25, 0x76, 0x38, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2f, 0x73, 0x65, 0x72, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65, 0x6e, 0x2d, 0x6f, 0x70, 0x65, 0x6e, 0x61, 0x70, 0x69, 0x76, 0x32, 0x2f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xb3, 0x03, 0x0a, 0x18, 0x47, 0x65, 0x74, 0x57, 0x6f, 0x72, 0x6b, 0x69, 0x6e, 0x67, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x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75, 0x73, 0x74, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x8a, 0xf5, 0xea, 0x94, 0x0e, 0x1d, 0x3a, 0x1b, 0x47, 0x45, 0x54, 0x5f, 0x57, 0x4f, 0x52, 0x4b, 0x49, 0x4e, 0x47, 0x5f, 0x53, 0x45, 0x52, 0x56, 0x45, 0x52, 0x53, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53, 0x54, 0x22, 0x8a, 0x01, 0x0a, 0x19, 0x47, 0x65, 0x74, 0x57, 0x6f, 0x72, 0x6b, 0x69, 0x6e, 0x67, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x47, 0x0a, 0x07, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x23, 0x2e, 0x76, 0x38, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x73, 0x65, 0x72, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x42, 0x08, 0x82, 0xf5, 0xea, 0x94, 0x0e, 0x02, 0x10, 0x01, 0x52, 0x07, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x3a, 0x24, 0x8a, 0xf5, 0xea, 0x94, 0x0e, 0x1e, 0x3a, 0x1c, 0x47, 0x45, 0x54, 0x5f, 0x57, 0x4f, 0x52, 0x4b, 0x49, 0x4e, 0x47, 0x5f, 0x53, 0x45, 0x52, 0x56, 0x45, 0x52, 0x53, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x22, 0xc8, 0x05, 0x0a, 0x1b, 0x47, 0x65, 0x74, 0x57, 0x6f, 0x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, 0x0a, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x23, 0x2e, 0x76, 0x38, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x73, 0x65, 0x72, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x42, 0x08, 0x82, 0xf5, 0xea, 0x94, 0x0e, 0x02, 0x10, 0x01, 0x52, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x3a, 0x28, 0x8a, 0xf5, 0xea, 0x94, 0x0e, 0x22, 0x3a, 0x20, 0x47, 0x45, 0x54, 0x5f, 0x57, 0x4f, 0x52, 0x4b, 0x49, 0x4e, 0x47, 0x5f, 0x53, 0x45, 0x52, 0x56, 0x45, 0x52, 0x5f, 0x49, 0x4e, 0x46, 0x4f, 0x5f, 0x52, 0x45, 0x53, 0x50, 0x4f, 0x4e, 0x53, 0x45, 0x22, 0xee, 0x03, 0x0a, 0x17, 0x41, 0x64, 0x64, 0x57, 0x6f, 0x72, 0x6b, 0x69, 0x6e, 0x67, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0xd8, 0x01, 0x0a, 0x0a, 0x63, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0xb8, 0x01, 0x92, 0x41, 0xa6, 0x01, 0x32, 0x55, 0xd0, 0xa3, 0xd0, 0xbd, 0xd0, 0xb8, 0xd0, 0xba, 0xd0, 0xb0, 0xd0, 0xbb, 0xd1, 0x8c, 0xd0, 0xbd, 0xd1, 0x8b, 0xd0, 0xb9, 0x20, 0xd0, 0xb8, 0xd0, 0xb4, 0xd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, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x76, 0x38, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2f, 0x67, 0x65, 0x6e, 0x2f, 0x72, 0x61, 0x73, 0x2f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x2f, 0x76, 0x31, 0x3b, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x76, 0x31, 0xa2, 0x02, 0x03, 0x52, 0x4d, 0x58, 0xaa, 0x02, 0x0f, 0x52, 0x61, 0x73, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x2e, 0x56, 0x31, 0xca, 0x02, 0x0f, 0x52, 0x61, 0x73, 0x5c, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x5c, 0x56, 0x31, 0xe2, 0x02, 0x1b, 0x52, 0x61, 0x73, 0x5c, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x5c, 0x56, 0x31, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x11, 0x52, 0x61, 0x73, 0x3a, 0x3a, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_ras_messages_v1_working_servers_messages_proto_rawDescOnce sync.Once file_ras_messages_v1_working_servers_messages_proto_rawDescData = file_ras_messages_v1_working_servers_messages_proto_rawDesc ) func file_ras_messages_v1_working_servers_messages_proto_rawDescGZIP() []byte { file_ras_messages_v1_working_servers_messages_proto_rawDescOnce.Do(func() { file_ras_messages_v1_working_servers_messages_proto_rawDescData = protoimpl.X.CompressGZIP(file_ras_messages_v1_working_servers_messages_proto_rawDescData) }) return file_ras_messages_v1_working_servers_messages_proto_rawDescData } var file_ras_messages_v1_working_servers_messages_proto_msgTypes = make([]protoimpl.MessageInfo, 7) var file_ras_messages_v1_working_servers_messages_proto_goTypes = []interface{}{ (*GetWorkingServersRequest)(nil), // 0: ras.messages.v1.GetWorkingServersRequest (*GetWorkingServersResponse)(nil), // 1: ras.messages.v1.GetWorkingServersResponse (*GetWorkingServerInfoRequest)(nil), // 2: ras.messages.v1.GetWorkingServerInfoRequest (*GetWorkingServerInfoResponse)(nil), // 3: ras.messages.v1.GetWorkingServerInfoResponse (*AddWorkingServerRequest)(nil), // 4: ras.messages.v1.AddWorkingServerRequest (*AddWorkingServerResponse)(nil), // 5: ras.messages.v1.AddWorkingServerResponse (*DeleteWorkingServerRequest)(nil), // 6: ras.messages.v1.DeleteWorkingServerRequest (*v1.ServerInfo)(nil), // 7: v8platform.serialize.v1.ServerInfo } var file_ras_messages_v1_working_servers_messages_proto_depIdxs = []int32{ 7, // 0: ras.messages.v1.GetWorkingServersResponse.servers:type_name -> v8platform.serialize.v1.ServerInfo 7, // 1: ras.messages.v1.GetWorkingServerInfoResponse.info:type_name -> v8platform.serialize.v1.ServerInfo 7, // 2: ras.messages.v1.AddWorkingServerRequest.info:type_name -> v8platform.serialize.v1.ServerInfo 3, // [3:3] is the sub-list for method output_type 3, // [3:3] is the sub-list for method input_type 3, // [3:3] is the sub-list for extension type_name 3, // [3:3] is the sub-list for extension extendee 0, // [0:3] is the sub-list for field type_name } func init() { file_ras_messages_v1_working_servers_messages_proto_init() } func file_ras_messages_v1_working_servers_messages_proto_init() { if File_ras_messages_v1_working_servers_messages_proto != nil { return } if !protoimpl.UnsafeEnabled { file_ras_messages_v1_working_servers_messages_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetWorkingServersRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_ras_messages_v1_working_servers_messages_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetWorkingServersResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_ras_messages_v1_working_servers_messages_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetWorkingServerInfoRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_ras_messages_v1_working_servers_messages_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetWorkingServerInfoResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_ras_messages_v1_working_servers_messages_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AddWorkingServerRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_ras_messages_v1_working_servers_messages_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AddWorkingServerResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_ras_messages_v1_working_servers_messages_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DeleteWorkingServerRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_ras_messages_v1_working_servers_messages_proto_rawDesc, NumEnums: 0, NumMessages: 7, NumExtensions: 0, NumServices: 0, }, GoTypes: file_ras_messages_v1_working_servers_messages_proto_goTypes, DependencyIndexes: file_ras_messages_v1_working_servers_messages_proto_depIdxs, MessageInfos: file_ras_messages_v1_working_servers_messages_proto_msgTypes, }.Build() File_ras_messages_v1_working_servers_messages_proto = out.File file_ras_messages_v1_working_servers_messages_proto_rawDesc = nil file_ras_messages_v1_working_servers_messages_proto_goTypes = nil file_ras_messages_v1_working_servers_messages_proto_depIdxs = nil }
On a fall day in 2010, half a dozen wealthy investors and portfolio managers converged on an office in midtown Manhattan. These were serious Wall Street moneymen; in aggregate, they handled more than a billion dollars. They had access to the most exclusive hedge funds and investment partnerships and often rubbed shoulders with the elite of New York, Greenwich and Palm Beach. But on this day, they had turned out to meet an unknown college dropout from Utah -- and to find out how he was knocking them all into a cocked hat. The unknown, Allan Mecham, had been posting mind-bogglingly high returns for a decade at a tiny private-investment fund called Arlington Value Management, and the Wall Streeters were considering jumping on board. For nearly two hours, they peppered him with questions. Where did he get his business background? I read a lot, he replied. Did he have an MBA? No. I dropped out of college. Did he have a clever computer model or algorithm? No, he replied. I don't use spreadsheets much. Could the group look at some of his investment analyses? I don't have any of those either, he said. It's all in my head. The investors were baffled. Well, could he at least tell them where he thought the stock market was headed? "I don't know," Mecham replied. When the meeting broke up, "most people left the room mystified," says Brendan O'Brien, a New York City money manager who was there. "They were expecting to see this very sharp-dressed, fast-talking guy. They were saying, I don't get it, I don't understand why he wouldn't have a view on the market, because money managers get paid to have a view on the market." Mecham has faced this kind of befuddlement before -- which is one reason he meets only rarely with potential investors. It's tough to sell his product to an industry that's used to something very different. After all, according to their rules, he shouldn't even be in the business to begin with. Over a 12-year stretch, through the end of 2011, Mecham, now a mere 34 years old, has earned an astounding cumulative return of more than 400 percent by investing in the stock of U.S. companies -- many of them larger ones like Philip Morris, AutoZone and PepsiCo. That investment performance leaves the stock market indexes and most mutual funds trailing far in the dust. Of the thousands of mutual funds in America, only a smattering of stock-oriented funds have done better, according to Lipper. Arlington, which is structured like a hedge fund, has put most firms in that category deep in the shade as well. It even managed to turn a profit during the crash of 2008, when Standard & Poor's 500-stock index fell nearly 40 percent. And Mecham has done this mostly while sitting in an armchair, in an office above a taco shop, in downtown Salt Lake City. Mecham doesn't look, talk or act like a typical Wall Street manager. He's soft-spoken. He doesn't use jargon. He dresses like he works in a bookshop, with a patterned shirt and a plain tie. And the story of his success, arguably, says a lot about the flaws of the fund-management industry. By his own account, and those of other investors who have vetted his fund, Mecham has no secret sauce or amazing algorithm; what's extraordinary about this young man is how ordinary he is. But his investment approach relies on a handful of common-sense tactics -- focusing on just a few stocks, for example, and avoiding or ignoring short-term statistical analysis -- that big money-management firms either can't use or are reluctant to try. Skeptics and admirers alike agree that Mecham's approach involves a higher-than-usual potential for hefty losses. Russ Kinnel, director of fund research at Morningstar, says most fund customers would be unlikely to take that chance. "Pension funds, consultants, investors in general are quite benchmark-centric," Kinnel notes; they get uncomfortable when their money managers deviate. But that notwithstanding, it would be a bit of a stretch to characterize Mecham as a rebel -- this is a man, after all, for whom one of the highlights of the past year was a trip to Omaha. (He took his girlfriend to Warren Buffett's annual investment conference.) As does virtually every other manager in the business, Mecham says he would like to raise more capital to invest -- his firm is small, with $80 million under management. But for now, the handful of pros who have jumped on his bandwagon are happy to have the fund remain undiscovered. It's clear that several think they're onto something special. After the awkward New York meeting, O'Brien, who runs Gold Coast Wealth Management, was sufficiently intrigued to do more digging -- and after spending months talking with Mecham and checking his results, he got on board, investing more than $1 million with the Utah unknown. "To use a sports analogy," O'Brien says, finding Mecham was like "one of the rare few times when a star free agent becomes available in the beginning of his prime." It's sensible these days for investors to approach the story of any stock market wunderkind with caution -- all the more so in the private-investment world, where money managers operate without the checks, balances and scrutiny that large mutual funds endure. Many such funds don't have to register with the Securities and Exchange Commission, especially if they're small and if big research companies like Morningstar don't track their performance. With the minimum stakes in such funds often very high -- at Arlington Value, the ante is typically at least $1 million -- investors have an even bigger incentive to do their own due diligence. (O'Brien, for instance, says he spoke to Arlington's auditors to confirm the investment figures, then did a background check on the auditors.) Factor in that the history of Wall Street is littered with the careers of investment hotshots who flamed out, and betting on a manager ultimately becomes a leap of faith. Rule-Breaker's Rules Money pros who know him say none of Allan Mecham's investing tactics are astonishingly difficult -- but for various reasons, most investors don't use them. Ignore the economy. Where is the economy going next quarter? Where is the S&P headed? Mecham says he ignores those issues; instead, he looks for stable, defensive businesses that can thrive whenever bad times come. Don't diversify. Most mutual funds own dozens or even hundreds of stocks (regulations usually require them to own at least 15). But to outperform with a big portfolio, a manager has to outsmart the market simultaneously on a raft of securities. Smaller funds and private-investment funds, which are not under the same requirements, can rely on just six or eight stocks. Don't sweat the spreadsheets. Many Wall Street analysts build elaborate financial analyses to calculate a company's earnings growth and other patterns. But some say it's more productive to use that time trying to understand a company and its industry -- the management, the competition, the customers and so on. Think decades, not quarters. Shareholders and managers tend to focus on companies' announcements of quarterly or annual earnings, and whether they beat or miss analysts' estimates. But some managers -- including one Warren Buffett -- say it's more useful to try to figure out where a company will be in a decade or more. Don't just do something. Stand there! One of the toughest things for investors to do is to sit still and do nothing -- especially when nervous clients demand that they respond to short-term fluctuations in the market. But most of the time, say a few contrarians, inactivity is the right longer-term move. It's about "keeping emotions from corroding the decision process," says Mecham. In Mecham's case, that faith resides in someone whose background is highly unusual for this industry. Mecham attended a community college and the University of Utah for two years -- but soon after starting an investment club, he says, he found his schoolwork boring by comparison. He would read books about investing and business. "I was 19," he recalls. "I was staying up till 3:30 a.m. devouring this stuff." Salt Lake City is a cohesive town where people know each other, and a classmate knew people at Wasatch Advisors, a local mutual fund company. Mecham landed a job there and eventually decided not to go back to school, choosing to stay on with the firm instead. Mecham's Wasatch bosses say they remember him as a good, but not unusually good, employee who made one memorably successful stock pick, recommending that the firm buy a health-services company that did quite well. Still, it was only about a year before Mecham decided he could run money himself. He raised seed capital -- less than $200,000, he says -- from a handful of local investors led by Robert Raybould, a former real estate developer who is the father of Mecham's childhood friend Ben Raybould. And in 1999, Mecham launched his fund -- at the well-seasoned age of 22. Since then, word of mouth has drawn more assets to Arlington, with Ben Raybould acting as Mecham's partner and the fund's main salesperson; regulatory filings show that the firm has about 120 investors, with more than 75 percent of them identified as "high-net-worth individuals." According to Raybould, of the $80 million in the fund, about half is investors' principal, and the rest, profit. But Mecham says his habits today are roughly the same as they were back when he had $200,000 to invest. He sits in that armchair by the window, carefully reading company filings and other records from atop a giant pile of material that he prints out each day. (Mecham prefers to read only on paper, not online -- old school.) His investment approach will be familiar to anyone who has been even a casual follower of Buffett. Mecham looks for businesses with great long-term prospects, great management, strong cash flow and big defensive "moats," or barriers to entry for potential competitors. And he stresses the importance of sitting still and doing nothing. "Activity is the enemy of returns," says Mecham. "If I find two new ideas a year, that's phenomenal." Two ideas a year adds up to a pretty small portfolio -- Mecham typically owns between six and 12 stocks. (That's one thing that sets him apart from mutual fund managers; because of industry regulations on diversification, traditional funds typically have to have at least 15 holdings.) The names of the stocks from which he has made his money over the years tell a lot of the story. They're not exactly glamorous or sexy businesses. (Mecham has never owned Apple. "Our portfolio is not one to get you excited," he jokes.) Some are well known, such as PepsiCo, fast-food giant Wendy's, health care firm Wyeth, consumer-products company 3M and Buffett's Berkshire Hathaway. Others are less so, like Watsco, a $2 billion company that's the U.S.'s largest distributor of air-conditioning equipment and supplies. Mecham says he loves the company's management and business model, but the choice was an industry pick as well -- in much of the country, he notes, when your air-conditioning system breaks down, getting it fixed "isn't a want, it's a need." Another little-known favorite, Heico, makes components for jet engines. Mecham's argument for the stock is brief, straightforward and Buffett-like: There are huge barriers to entry, he says, the replacement cycle is driven by regulation, and customers are not aggressive about demanding lower prices. Indeed, Mecham can tell a good story like this about any stock he owns. But he writes these stories by himself, based on his own research -- unlike most fund managers, he generally doesn't meet company management. That's partly a function of his fund being small; he's not in a position to buy huge stakes that can make or break a company. But Mecham doesn't like meeting management even where it's possible. "Management is usually likable," he says. "They'll never tell you things are going to hell in a basket." Indeed, Arlington's worst patch came from getting too close to a company: local Internet retailer Overstock.com. Ben and Robert Raybould take the blame for persuading Mecham to invest in it and then persuading him to hang on when the stock cratered in 2005. Mecham called the decision "management by committee." The fund dropped by a third that year, while the market rose. Mecham argued with his backer, and in the aftermath, Raybould agreed to leave Mecham alone. (Overstock.com President Jonathan Johnson declined to comment about the stock price, but says he knows and likes Mecham.) It was a very different story in 2008, Wall Street's annus horribilis, the year of Bear Stearns and Lehman Brothers. The financial meltdown was an event that blew up almost every smart money manager from Boston to Beijing. The S&P crashed 37 percent. Most actively managed stock funds did worse, and those that cut their losses often did so by fleeing stocks for cash. Arlington? It doubled down, loading up on stocks that would do well in a downturn. An Elite Club A 400% gain, which turns a $100,000 stake into a $500,000 jackpot, is a hall-of-fame feat for money managers. Below, some of the few who have pulled it off. Warren Buffett Holding company: Berkshire Hathaway Market cap: $191 billion $191 billion The 400% run: 80 Months. july 1989-February 1996 80 Months. july 1989-February 1996 The Oracle of Omaha has punched his 400 percent membership card more than once. This run, capped with a 57 percent gain in 1995 alone, got a boost from Buffett's famous investment in Coca-Cola, which he bought in 1988. Berkshire's recent returns haven't been as dramatic, but the company largely managed to avoid stumbles that have tripped up other well-known managers over the past decade. Kenneth Smith (with others) Fund: Munder Growth Opportunities (MNNAX) Munder Growth Opportunities (MNNAX) Assets: $460 million $460 million The 400% run: 17 Months. october 1998-February 2000 17 Months. october 1998-February 2000 This fund, formerly known as Munder NetNet, epitomized the industry's embrace of the dot-com era. After it nearly tripled investors' money in 1999, its assets ballooned to more than $11 billion…and then the bubble burst. In the three years that followed, the fund lost 85 percent of its value. Over the past decade, though, Growth Opportunities, which has shuffled its management team, has beaten the market handily. Bill Miller Fund: Legg Mason Capital Management Value Trust (LMVTX) Legg Mason Capital Management Value Trust (LMVTX) Assets: $2.6 billion $2.6 billion The 400% run: 85 months. April 1994-April 2001 85 months. April 1994-April 2001 Miller, who quintupled investors' money in just seven years, attributes gains during this period to savvy tech calls: buying names like AOL and Dell early, then selling ahead of the tech crash. But he will be stepping down from the fund in April on a less triumphant note. After a series of big bets on banks went sour during the financial crisis, he has trailed the S&P 500 in five of the past six years. Sam Stewart, Robert Gardiner, Daniel Chace Fund: Wasatch Micro Cap (WMICX) Wasatch Micro Cap (WMICX) Assets: $275 million $275 million The 400% run: 90 months. november 1999-April 2007 90 months. november 1999-April 2007 This fund managed a four-bagger in less than eight years by finding bargains among companies valued below $1 billion. The bad news: Small firms "struggled mightily" when financing dried up during the recession, according to Wasatch founder Sam Stewart. Micro Cap lost roughly half its value in 2008, but investors who stuck with it have beaten the S&P 500 by three percentage points a year, on average, over the past decade. -- By Ian Salisbury One was AutoZone, the chain that made more than $8 billion in revenue in 2011 selling car parts directly to consumers. Mecham had been building a stake since 2005, and he was convinced it was a "countercyclical stock" that would thrive even in a poor economy -- when consumers are hurting, he explains, they keep their old cars longer and fix them themselves. AutoZone stock gained more than 16 percent in 2008; since then, it has more than doubled. Mecham also zeroed in on Canadian insurance company Fairfax Financial Holdings. Wall Street had dumped the stock overboard in the panic, but Mecham had actually read the company's filings -- and he knew most of its assets were in Treasury bills and other ultrasafe positions. Arlington added to its already large position, and Fairfax rose 12 percent in the last two months of the year. The result: Arlington as a whole was up a remarkable 11 percent in 2008 and another 59 percent in 2009. No public equity mutual fund in America came close. So why don't other mutual fund managers think and act like this? Bonnie Sewell, a wealth manager at American Capital Planning who oversees money for high-net-worth clients across the country, says concentrated portfolios can prove incredibly volatile. She says she wouldn't bet more than about 10 percent of a portfolio on an individual manager like Mecham, no matter how good, because of the inevitable risk -- or even likelihood -- that what goes up will come down. Regardless of their strategy, even managers with terrific track records can get cocky or complacent, or they can just make mistakes. As investing sages like Buffett often point out, people on Wall Street are also subject to enormous career pressure to conform. If they took a big bet, like Mecham's on Fairfax, and it didn't work out, clients would bolt, and they typically would be fired or pushed out. But no one would get fired for missing an opportunity like that. The same goes for how managers react to short-term news in the market. Mecham says one of his big advantages over Wall Street managers is that he is free to ignore "noise" -- like the quarterly obsession over short-term earnings, which often drive stock prices sharply up and down as investors stampede in herd behavior. The first question he asks of any investment, he says, is where it will be in 10 years or more: "You have to have a high degree of confidence in the cash flows over the next decade." Mecham says that in contrast, the typical mutual fund manager is like someone who's hired to run a marathon -- only to have his clients announce that they're going to compare his time every 100 meters with that of an Olympic sprinter running a dash. "It's a myopic process," he says, with resignation. Where does Arlington head next? Mecham says he won't compromise his strategy to play the Wall Street game. That leaves Ben Raybould battling to market a fund, and a manager, that many other money managers can't even understand. Mecham is bemused that so many people expect him to hold a broad basket of stocks and follow a benchmark, such as the S&P 500. "It's laughable to think that in this competitive world, you're going to find brilliant ideas every day," he says. "The world's just not set up that way."
import AMQPMessageBroker from "./MessageBrokers/AMQP"; import EnvironmentVariableConfigurationSource from "./ConfigurationSources/EnvironmentVariables"; const mb : AMQPMessageBroker = new AMQPMessageBroker( new EnvironmentVariableConfigurationSource() );
def testListReference(self): r = S3Represent(lookup="org_organisation", multiple=True, show_link=True) a = current.request.application result = r(self.id1) self.assertTrue(isinstance(result, DIV)) self.assertEqual(len(result), 1) self.assertTrue(isinstance(result[0], A)) self.assertEqual(result[0].attributes["_href"], "/%s/org/organisation/%s" % (a, self.id1)) self.assertEqual(result[0].components[0], "Represent Test Organisation1") result = r(self.id1, show_link=False) self.assertEqual(result, self.name1) result = r([self.id1, self.id2], show_link=False).split(", ") self.assertEqual(len(result), 2) self.assertTrue(self.name1 in result) self.assertTrue(self.name2 in result) values = [[self.id1, self.id2], [self.id2], [None, self.id1]] result = r.multiple(values, show_link=False).split(", ") self.assertEqual(len(result), 3) self.assertTrue(self.name1 in result) self.assertTrue(self.name2 in result) self.assertTrue(current.messages.NONE in result) result = r.bulk(values, show_link=False) self.assertTrue(isinstance(result, dict)) self.assertEqual(len(result), 3) self.assertEqual(result[self.id1], self.name1) self.assertEqual(result[self.id2], self.name2) self.assertTrue(None in result) repr1 = r.render_list(values[0], result, show_link=False) self.assertEqual(repr1, ", ".join([self.name1, self.name2])) repr2 = r.render_list(values[1], result, show_link=False) self.assertEqual(repr2, self.name2) result = r.bulk(values) repr1 = r.render_list(values[0], result) self.assertTrue(isinstance(repr1, DIV)) self.assertEqual(len(repr1), 3) self.assertTrue(isinstance(repr1[0], A)) self.assertEqual(repr1[0].attributes["_href"], "/%s/org/organisation/%s" % (a, self.id1)) self.assertEqual(repr1[0].components[0], "Represent Test Organisation1") self.assertEqual(repr1[1], ", ") self.assertTrue(isinstance(repr1[2], A)) self.assertEqual(repr1[2].attributes["_href"], "/%s/org/organisation/%s" % (a, self.id2)) self.assertEqual(repr1[2].components[0], "Represent Test Organisation2") repr2 = r.render_list(values[2], result) self.assertTrue(isinstance(repr2, DIV)) self.assertEqual(len(repr2), 3) self.assertEqual(str(repr2[0]), str(current.messages.NONE)) self.assertEqual(r(None, show_link=False), str(current.messages.NONE)) self.assertEqual(r([]), str(current.messages.NONE)) self.assertEqual(r.multiple([None], show_link=False), str(current.messages.NONE)) self.assertEqual(r.multiple([[]], show_link=False), str(current.messages.NONE)) self.assertEqual(r.queries, 2)
def testRegistryAPI(self): url = ADMIN_CLIENT["endpoint"] user_common_password = "Aa123456" TestProjects.user_Alice_id, user_Alice_name = self.user.create_user(user_password = user_common_password, **ADMIN_CLIENT) USER_ALICE_CLIENT=dict(endpoint = url, username = user_Alice_name, password = user_common_password) TestProjects.project_Alice_id, TestProjects.project_Alice_name = self.project.create_project(metadata = {"public": "false"}, **USER_ALICE_CLIENT) src_tag = "latest" image_a = "image_a" TestProjects.repo_a, tag_a = push_self_build_image_to_project(TestProjects.project_Alice_name, harbor_server, user_Alice_name, user_common_password, image_a, src_tag) image_b = "image_b" TestProjects.repo_b, tag_b = push_self_build_image_to_project(TestProjects.project_Alice_name, harbor_server, user_Alice_name, user_common_password, image_b, src_tag) image_c = "image_c" TestProjects.repo_c, tag_c = push_self_build_image_to_project(TestProjects.project_Alice_name, harbor_server, user_Alice_name, user_common_password, image_c, src_tag) create_tags = ["1.0","2.0","3.0"] for tag in create_tags: self.artifact.create_tag(TestProjects.project_Alice_name, image_c, tag_c, tag, **USER_ALICE_CLIENT) tags = list_image_tags(harbor_server,TestProjects.repo_c,user_Alice_name,user_common_password) for tag in create_tags: self.assertTrue(tags.count(tag)>0, "Expect tag: %s is not listed"%tag) page_tags = list_image_tags(harbor_server,TestProjects.repo_c,user_Alice_name,user_common_password,len(tags)/2+1) page_tags += list_image_tags(harbor_server,TestProjects.repo_c,user_Alice_name,user_common_password,len(tags)/2+1,tags[int(len(tags)/2)]) for tag in create_tags: self.assertTrue(page_tags.count(tag)>0, "Expect tag: %s is not listed by the pagination query"%tag) repos = list_repositories(harbor_server,admin_user,admin_pwd) self.assertTrue(repos.count(TestProjects.repo_a)>0 and repos.count(TestProjects.repo_b)>0 and repos.count(TestProjects.repo_c)>0, "Expected repo not found") for repo in [TestProjects.repo_a,TestProjects.repo_b,TestProjects.repo_c]: self.assertTrue(repos.count(repo)>0,"Expected repo: %s is not listed"%repo) page_repos = list_repositories(harbor_server,admin_user,admin_pwd,len(repos)/2+1) page_repos += list_repositories(harbor_server,admin_user,admin_pwd,len(repos)/2+1,repos[int(len(repos)/2)]) for repo in [TestProjects.repo_a,TestProjects.repo_b,TestProjects.repo_c]: self.assertTrue(page_repos.count(repo)>0,"Expected repo: %s is not listed by the pagination query"%repo) null_repos = list_repositories(harbor_server,user_Alice_name,user_common_password) self.assertEqual(null_repos, "")
<gh_stars>10-100 //! @file //! //! Copyright (c) Memfault, Inc. //! See License.txt for details //! @brief //! Example MBed specific routines for populating version data. #include "memfault/core/platform/device_info.h" #include <stdio.h> #include <string.h> #include "memfault/core/math.h" #ifndef MEMFAULT_MBED_MAIN_SOFTWARE_VERSION # define MEMFAULT_MBED_MAIN_SOFTWARE_VERSION "1.0.0" #endif #ifndef MEMFAULT_MBED_SOFTWARE_TYPE # define MEMFAULT_MBED_SOFTWARE_TYPE "mbed-main" #endif #ifndef MEMFAULT_MBED_HW_REVISION # define MEMFAULT_MBED_HW_REVISION "mbed-proto" #endif #ifdef TARGET_STM32F4 #include "stm32f4xx_hal.h" static char prv_nib_to_hex_ascii(uint8_t val) { return val < 10 ? (char)val + '0' : (char)(val - 10) + 'A'; } #define MEMFAULT_MBED_UID_SIZE_IN_WORDS (3) #define MEMFAULT_MBED_UID_SIZE_IN_BYTES (MEMFAULT_MBED_UID_SIZE_IN_WORDS * 4) #define MEMFAULT_MBED_UID_SIZE_IN_ASCII (MEMFAULT_MBED_UID_SIZE_IN_BYTES * 2) static char *prv_get_device_serial(void) { uint32_t uid[MEMFAULT_MBED_UID_SIZE_IN_WORDS]; HAL_GetUID(uid); uint8_t *byte_reader = (uint8_t *)uid; static char s_device_serial[MEMFAULT_MBED_UID_SIZE_IN_ASCII + 1]; // +1 for null char *serial_write_ptr = &s_device_serial[0]; for (size_t i=0; i<MEMFAULT_MBED_UID_SIZE_IN_BYTES; i++) { uint8_t c = byte_reader[i]; *serial_write_ptr++ = prv_nib_to_hex_ascii(c >> 4); *serial_write_ptr++ = prv_nib_to_hex_ascii(c & 0xf); } *serial_write_ptr = 0; // null terminate the ascii string return s_device_serial; } #else /* * TODO: At the time this example was created (MBed OS 5.14), no release version * had support for reading a target's unique id in a platform independent way * but they were working on it. This example should use it when it is released. * See: https://github.com/ARMmbed/mbed-os/pull/5557 * * This example supports reading the unique ID from the STM32F4xx only. We only * use the unique ID as a fake device serial number for demo purposes. You'll * need to implement prv_get_device_serial() here for your target. To just see * the demo run, you could even use a dummy string. */ #error Querying unique ID is only supported for STM32F4; you need to implement prv_get_device_serial() #endif void memfault_platform_get_device_info(struct MemfaultDeviceInfo *info) { *info = (struct MemfaultDeviceInfo) { .device_serial = prv_get_device_serial(), .hardware_version = MEMFAULT_MBED_HW_REVISION, .software_version = MEMFAULT_MBED_MAIN_SOFTWARE_VERSION, .software_type = MEMFAULT_MBED_SOFTWARE_TYPE, }; }
// Create a new node which has the specified `key' and `userdata' // Return NULL if failed static avlbst_p avlbst_new_node(const size_t key, void *userdata) { avlbst_p n = calloc(1, sizeof *n); if(!n) return n; n->key = key; n->userdata = userdata; return n; }
A recent road trip took me through five Canadian provinces — Ontario, Quebec, New Brunswick, Nova Scotia and P.E.I. It turned out to be an eye-opening education in how Canada’s political culture changes completely the moment you step away from Parliament Hill. While official Ottawa is consumed with all things Duffy, Harper, Mulcair, Trudeau and … er, Duffy, a much different reality is at play across Canada, where people are far more consumed with squeezing a little more fun out of the waning summer than with tracking the leaders and their daily policy pitches. So here’s a broad summary of what I was hearing from friends, relatives and complete strangers. (Names withheld to protect the disgruntled.) Wait … there’s an election? Setting aside the hardcore political junkies and those who watch the evening news every night, many of the people I talked to didn’t even know we’re in an election campaign. One 20-something put it succinctly: “Now all the ads on TV make sense.” Just as the last five minutes of a close game is far more interesting than the first inning, Election 42 is still background noise for most Canadians. Winds of change are blowing … but in which direction? Many of the people I spoke to said they believe we need a new government in Ottawa. “People around here say it’s time for a change,” said a woman who runs a bed-and-breakfast in New Brunswick. She also said that the people she talks to are having a hard time putting their trust in the other options. So far, ‘none of the above’ seems to be the preferred option for many Canadians. We’ve reached the point where voters actually expect politicians to break their promises — which makes it hard to engage them on policy. So far, ‘none of the above’ seems to be the preferred option for many Canadians. We’ve reached the point where voters actually expect politicians to break their promises — which makes it hard to engage them on policy. We’ve seen this force at work before. In several recent provincial elections the polling indicated an appetite for change — but when the vote got close that ‘time for a change’ factor became less of a driver once people took the time to review the alternatives in detail. Whether the same phenomenon repeats itself at the federal level this fall is anyone’s guess — but it’s clear that a lot of Canadians who want a change in government still haven’t picked a horse in this race. Mike Duffy is no OJ They called the OJ Simpson trial the “Trial of the Century” for a while. Those journalists and observers who would love to attach the same label to the Duffy trial obviously forgot to tell anyone outside the Ottawa bubble. Just as a lot of people only woke up to the election because of the political ads on TV, people are only vaguely aware of the Mike Duffy trial because it’s being heavily covered by the parliamentary press gallery. And it’s only the talk of the town in Ottawa (and perhaps in P.E.I.). What have you done for me lately? When my political chats advanced to a point where actual policy and issues came up, people started owning up to the fact that they’re approaching this election with an eye on the bottom line. “Without income splitting, my family will send more of our hard-earned money to Ottawa,” said one man heavily in favour of the Harper government’s tax policy. “The government wants to punish those who collect EI and that’s just mean,” a seasonal worker told me. I’m not suggesting that we are completely uncaring and self-interested. But in the absence of big national issues driving the overall debate, we’re seeing people making their choices on the basis of what the parties are offering them personally — things like tax cuts or free daycare. It’s like how, when there’s an in-flight emergency on a commercial aircraft, the flight crew always tells you to secure your own oxygen mask before helping anyone else. Canadians are most likely to react or respond to developments in this campaign when they feel their personal interests are at stake. A pox on all their houses And here’s what should worry all the parties and their candidates: so far, “none of the above” seems to be the preferred option for many Canadians. We’ve reached the point where voters actually expect politicians to break their promises — which makes it hard to engage them on policy. “Politicians are all the same,” one lady told me. She also said she probably won’t vote. “What’s the point?” With interest low and cynicism high, it’s hardly surprising that Canadians haven’t tuned in yet. But when they do, it will be interesting to see how this unprecedented mix of self-interested voting groups, apathy, an appetite for change and election fatigue drives the results. So far, it’s anyone’s guess. Adam Taylor is a director at ENsight Canada and a former director of communications in the Harper government. The views, opinions and positions expressed by all iPolitics columnists and contributors are the author’s alone. They do not inherently or expressly reflect the views, opinions and/or positions of iPolitics.
package wcs.java.model.editors; /** * Created by jelerak on 3/11/2015. */ public class RichTextEditor extends AbstractAttributeEditor { //Default Values private String widthValue = "400"; private String heightValue = "600"; private String allowedAssetTypesValue; private String toolbarValue; private String configValue; private String configObjValue; private RichTextEditor(String name) { super(name); } public String toXml() { return "<CKEDITOR"+ getConfigElements()+ "/>"; } public String getConfigElements() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(" WIDTH=\"").append(widthValue).append("\"") .append(" HEIGHT=\"").append(heightValue).append("\""); if (allowedAssetTypesValue != null) { stringBuilder.append(" ALLOWEDASSETTYPES=\"").append(allowedAssetTypesValue).append("\""); } if (toolbarValue != null) { stringBuilder.append(" TOOLBAR=\"").append(toolbarValue).append("\""); } if (configValue != null) { stringBuilder.append(" CONFIG=\"").append(configValue).append("\""); } if (configObjValue != null) { stringBuilder.append(" CONFIGOBJ=\"").append(configObjValue).append("\""); } return stringBuilder.toString(); } public static RichTextEditorBuilder getBuilder(String name) { return new RichTextEditorBuilder(name); } public static class RichTextEditorBuilder { private RichTextEditor richTextEditor; private RichTextEditorBuilder(String name) { richTextEditor = new RichTextEditor(name); } public RichTextEditorBuilder widthValue(String widthValue) { richTextEditor.widthValue = widthValue; return this; } public RichTextEditorBuilder heightValue(String heightValue) { richTextEditor.heightValue = heightValue; return this; } public RichTextEditorBuilder allowedAssetTypesValue(String allowedAssetTypesValue) { richTextEditor.allowedAssetTypesValue= allowedAssetTypesValue; return this; } public RichTextEditorBuilder toolbarValue(String toolbarValue) { richTextEditor.toolbarValue = toolbarValue; return this; } public RichTextEditorBuilder configValue(String configValue) { richTextEditor.configValue = configValue; return this; } public RichTextEditorBuilder configObjValue(String configObjValue) { richTextEditor.configObjValue = configObjValue; return this; } public RichTextEditor build() { return richTextEditor; } } public enum YesNoEnum { YES("YES"), NO("NO"); private String value; private YesNoEnum(String value) { this.value = value; } public String toString() { return value; } } }
//! Box id type use std::convert::TryFrom; use crate::serialization::SigmaSerializeResult; use sigma_ser::ScorexSerializable; use crate::serialization::{ sigma_byte_reader::SigmaByteRead, sigma_byte_writer::SigmaByteWrite, SigmaParsingError, SigmaSerializable, }; use derive_more::From; use derive_more::Into; use ergo_chain_types::{Digest32, Digest32Error}; use sigma_util::AsVecI8; /// newtype for box ids #[derive(PartialEq, Eq, Hash, Debug, Clone, From, Into)] #[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "arbitrary", derive(proptest_derive::Arbitrary))] pub struct BoxId(Digest32); impl BoxId { /// Size in bytes pub const SIZE: usize = Digest32::SIZE; /// All zeros pub fn zero() -> BoxId { BoxId(Digest32::zero()) } } impl AsRef<[u8]> for BoxId { fn as_ref(&self) -> &[u8] { self.0.as_ref() } } impl From<BoxId> for String { fn from(v: BoxId) -> Self { v.0.into() } } impl TryFrom<String> for BoxId { type Error = Digest32Error; fn try_from(value: String) -> Result<Self, Self::Error> { Ok(Digest32::try_from(value)?.into()) } } impl From<BoxId> for Vec<i8> { fn from(b: BoxId) -> Self { let bytes: Vec<u8> = b.0.into(); bytes.as_vec_i8() } } impl SigmaSerializable for BoxId { fn sigma_serialize<W: SigmaByteWrite>(&self, w: &mut W) -> SigmaSerializeResult { self.0.scorex_serialize(w)?; Ok(()) } fn sigma_parse<R: SigmaByteRead>(r: &mut R) -> Result<Self, SigmaParsingError> { Ok(Self(Digest32::scorex_parse(r)?)) } } #[allow(clippy::unwrap_used)] #[allow(clippy::panic)] #[cfg(test)] mod tests { use super::*; use crate::serialization::sigma_serialize_roundtrip; use proptest::prelude::*; proptest! { #[test] fn ser_roundtrip(v in any::<BoxId>()) { prop_assert_eq![sigma_serialize_roundtrip(&v), v]; } } }
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <jni.h> #include <pthread.h> #include <string.h> #include <android/log.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> #define TAG "Noizer" #define SIZE_BUFFER 1024 * 1024 // 1 MB // engine interfaces static SLObjectItf engineObject = NULL; static SLEngineItf engineEngine; // output mix interfaces static SLObjectItf outputMixObject = NULL; // buffer queue player interfaces static SLObjectItf bqPlayerObject = NULL; static SLPlayItf bqPlayerPlay; static SLAndroidSimpleBufferQueueItf bqPlayerBufferQueue; static SLEffectSendItf bqPlayerEffectSend; static SLVolumeItf bqPlayerVolume; enum stateMachine { UNINITIALIZED, IS_STOPPED, IS_PLAYING }; static stateMachine mState = UNINITIALIZED; static pthread_mutex_t mStateLock = PTHREAD_MUTEX_INITIALIZER; static uint8_t noiseBuffer[SIZE_BUFFER]; static bool bqGenerateNoise(uint8_t *buf, uint32_t size) { __android_log_print(ANDROID_LOG_DEBUG, TAG, "Updating noise buffer"); int rng = open("/dev/urandom", O_RDONLY); if (rng < 0) { __android_log_print(ANDROID_LOG_ERROR, TAG, "Could not open /dev/urandom"); return false; } ssize_t result = read(rng, buf, size); if (result != SIZE_BUFFER) { __android_log_print(ANDROID_LOG_ERROR, TAG, "Unsatisfied generation of pseudo-random values! Read %zu to buffer, size %d", result, size); return false; } return true; } // Fill buffer with noise from /dev/urandom on load __attribute__((constructor)) static void onLoad(void) { bqGenerateNoise(noiseBuffer, SIZE_BUFFER); } // this callback handler is called every time a buffer finishes playing void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context) { assert(bq == bqPlayerBufferQueue); assert(NULL == context); bqGenerateNoise(noiseBuffer, SIZE_BUFFER); // for streaming playback, replace this test by logic to find and fill the next buffer SLresult result; result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, noiseBuffer, SIZE_BUFFER); assert(SL_RESULT_SUCCESS == result); } void bqCreateBufferQueueAudioPlayer() { SLresult result; // configure audio source SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2}; SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, 1, SL_SAMPLINGRATE_16, SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, SL_SPEAKER_FRONT_CENTER, SL_BYTEORDER_LITTLEENDIAN}; SLDataSource audioSrc = {&loc_bufq, &format_pcm}; // configure audio sink SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObject}; SLDataSink audioSnk = {&loc_outmix, NULL}; /* * create audio player: * fast audio does not support when SL_IID_EFFECTSEND is required, skip it * for fast audio case */ const SLInterfaceID ids[3] = {SL_IID_BUFFERQUEUE, SL_IID_VOLUME, SL_IID_EFFECTSEND, /*SL_IID_MUTESOLO,*/}; const SLboolean req[3] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, /*SL_BOOLEAN_TRUE,*/ }; result = (*engineEngine)->CreateAudioPlayer(engineEngine, &bqPlayerObject, &audioSrc, &audioSnk, 3, ids, req); assert(SL_RESULT_SUCCESS == result); (void) result; // realize the player result = (*bqPlayerObject)->Realize(bqPlayerObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); (void) result; // get the play interface result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_PLAY, &bqPlayerPlay); assert(SL_RESULT_SUCCESS == result); (void) result; // get the buffer queue interface result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_BUFFERQUEUE, &bqPlayerBufferQueue); assert(SL_RESULT_SUCCESS == result); (void) result; result = (*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQueue, bqPlayerCallback, NULL); assert(SL_RESULT_SUCCESS == result); (void) result; // get the effect send interface bqPlayerEffectSend = NULL; result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_EFFECTSEND, &bqPlayerEffectSend); assert(SL_RESULT_SUCCESS == result); (void) result; // get the volume interface result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_VOLUME, &bqPlayerVolume); assert(SL_RESULT_SUCCESS == result); (void) result; // set the player's state to playing result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING); assert(SL_RESULT_SUCCESS == result); (void) result; } static jboolean stop() { assert(mState == IS_PLAYING); if (!pthread_mutex_lock(&mStateLock)) { (*bqPlayerObject)->Destroy(bqPlayerObject); mState = IS_STOPPED; pthread_mutex_unlock(&mStateLock); return JNI_TRUE; } else { __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to lock"); return JNI_FALSE; } } static jboolean play() { assert(mState == IS_STOPPED); if (!pthread_mutex_lock(&mStateLock)) { bqCreateBufferQueueAudioPlayer(); bqGenerateNoise(noiseBuffer, SIZE_BUFFER); SLresult result; result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, noiseBuffer, SIZE_BUFFER); assert(result == SL_RESULT_SUCCESS); mState = IS_PLAYING; pthread_mutex_unlock(&mStateLock); return JNI_TRUE; } else { __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to lock"); return JNI_FALSE; } } extern "C" JNICALL void Java_com_application_noizer_NoizerService_initialize(JNIEnv *env, jclass clazz) { if (mState != UNINITIALIZED) return; SLresult result; // create the engine result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); (void) result; // realize the engine result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); (void) result; // get the engine interface, which is needed in order to create other objects result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); assert(SL_RESULT_SUCCESS == result); (void) result; // create output mix const SLInterfaceID ids[1] = {SL_IID_NULL}; const SLboolean req[1] = {SL_BOOLEAN_FALSE}; result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 1, ids, req); assert(SL_RESULT_SUCCESS == result); (void) result; // realize the output mix result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); (void) result; mState = IS_STOPPED; } extern "C" JNICALL jboolean Java_com_application_noizer_NoizerService_play(JNIEnv *env, jclass clazz) { assert(mState == IS_STOPPED); return play(); } extern "C" JNICALL jboolean Java_com_application_noizer_NoizerService_stop(JNIEnv *env, jclass clazz) { assert(mState == IS_PLAYING); return stop(); }
from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, QObject, QVariant from py.common.FramListModel import FramListModel import logging import unittest import arrow import os import glob import ntpath from pathlib import Path class Notes(QObject): notesPathChanged = pyqtSignal() noteSaved = pyqtSignal(str, arguments=['imageNameStr']) def __init__(self, app=None, db=None): super().__init__() self._app = app self._db = db self._notes_path = "notes" if not os.path.exists(path=self._notes_path): os.makedirs(self._notes_path, 777) @pyqtProperty(str, notify=notesPathChanged) def notesPath(self): """ Method to return the self._notes_path :return: """ return self._notes_path @pyqtSlot(name="getNextNoteName", result=str) def get_next_note_name(self): """ Method to return the name of the next note in the self._notes_path folder :return: """ next_file = "note_1.png" try: note_files = [int(x.split("note_")[1].strip(".png")) for x in glob.glob(self._notes_path + "/note_*.png")] note_files = sorted(note_files, reverse=True) if len(note_files) > 0: last_file_number = note_files[0] next_file = f"note_{last_file_number+1}.png" except Exception as ex: logging.error(f"Error getting the name note image filename: {ex}") next_path = os.path.join(self._notes_path, next_file) return next_path @pyqtSlot(str, str, str, QVariant, QVariant, QVariant, QVariant, QVariant, QVariant, name="insertNote") def insert_note(self, app_name, screen, value, site_op_id=None, drop=None, angler=None, hook=None, observation=None, imageNameStr=None): """ Method to insert a note into the NOTES table :param value: :return: """ try: if value == "" or value is None: return sql = """ INSERT INTO NOTES(APP_NAME, SCREEN_NAME, NOTE, OPERATION_ID, HL_DROP, HL_ANGLER, HL_HOOK, CUTTER_OBSERVATION_NAME, DATE_TIME, IMAGE_NAME_STR, IMAGE_NAME_BLOB) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); """ date_time = arrow.now().to("US/Pacific").isoformat() # Read in the image into memory for insertion into the blob if os.path.exists(imageNameStr): # with open(imageNameStr, mode='rb') as file: # image = file.read() image = Path(imageNameStr).read_bytes() params = [app_name, screen, value, site_op_id, drop, angler, hook, observation, date_time, imageNameStr, image] logging.info(f"Saving note: app_name={app_name}, screen={screen}, value={value}, " f"site_op_id={site_op_id}, drop={drop}, angler={angler}, hook={hook}, " f"observation={observation}, date_time={date_time}, imageNameStr={imageNameStr}") results = self._app.rpc.execute_query(sql=sql, params=params) # image.close() logging.info(f"emitting noteSaved") self.noteSaved.emit(imageNameStr) except Exception as ex: logging.info(f"Error inserting a new note: {ex}")
In August, 1966, the Beatles played their final concert at Candlestick Park near San Francisco. They had decided to stop touring — and no one knew how to be a band without playing gigs. After that last show, George Harrison said, “Well, I guess I’m not a Beatle anymore.” When they gathered at EMI Studios in November 1966, their prospects seemed uncertain. Of course, we now know they more than met the challenge, producing one of rock’s greatest albums, Sgt. Pepper’s Lonely Hearts Club Band, and the remarkable Double A-Side single, “Penny Lane“/“Strawberry Fields Forever.” In this particular installment of his popular film series Deconstructing the Beatles, Beatleologist Scott Freiman delves deeply into the creative process that produced this masterpiece. Deconstructing Sgt. Pepper brings you into EMI Studios to see how this landmark album evolved. There’s a lot to digest, too, as The Beatles and George Martin really “played” the studio for Sgt. Pepper. Unencumbered by the pressures of touring, they took time to experiment, explore and invent – both creatively and technologically. Exceptional songwriting is the heart of any Beatles’ record. The film traces the evolution of these now-familiar tracks, often starting with rough demos and developing through successive takes. Scott also sprinkles odd factoids throughout, answering questions you didn’t know you had, like: • Which track features background vocals in German? • Why is one song in different keys for the British and American versions? • Why didn’t George Martin write the string arrangement for “She’s Leaving Home”? • Which tracks featured toilet paper, bass harmonica, ocarina and calliope? Deconstructing Sgt. Peppers opened on Feb. 6, 2017, in most cases playing for only one night. But now you can watch this fascinating multimedia lecture in the comfort of your own home. Get a sneak peek of the series with the short video below then head on over to the CultureSonar online shop to order the DVD. – The CS Team Other Posts You Might Like
package controllers import ( "github.com/gin-gonic/gin" "gnt-cc/config" "gnt-cc/model" ) type ClusterController struct{} // GetAll godoc // @Summary Get all clusters // @Description Get all clusters configured in the config file. Sensitive values will be omitted // @Produce json // @Success 200 {object} model.AllClustersResponse // @Router /clusters [get] func (controller *ClusterController) GetAll(c *gin.Context) { configClusters := config.Get().Clusters clusters := make([]model.GntCluster, len(configClusters)) for i, cluster := range configClusters { clusters[i] = model.GntCluster{ Name: cluster.Name, Hostname: cluster.Hostname, Description: cluster.Description, Port: cluster.Port, } } c.JSON(200, model.AllClustersResponse{ Clusters: clusters, }) }
. According to the author there are five possible kinds of relationship between visceral neoplasmas and diseases of the skin. 1. Instances in which neoplasma induces dermatosis (the so-called paraneoplastic diseases). 2. Instances in which defective immune mechanism or long-lasting immune suppression promote the development of neoplasma as well as of skin diseases due to microorganism and viruses. 3. Instances in which the tumor and dermatosis are associated without causal relationship. 4. Cases of malignant lymphoma arising from neoplastic proliferation of the cells of the reticulohistiocytic system involving visceral organs and the skin. 5. Skin metastases of internal neoplastic processes.
<filename>src/test/java/com/swime/mapper/StudySurveyMapperTests.java package com.swime.mapper; import com.swime.domain.StudyListVO; import com.swime.domain.StudySurveyVO; import lombok.Setter; import lombok.extern.log4j.Log4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {com.swime.config.RootConfig.class}) @Log4j public class StudySurveyMapperTests { @Setter(onMethod_ = @Autowired) private StudySurveyMapper mapper; @Test public void testGetList() { List<StudySurveyVO> list = mapper.getList(82L); for(StudySurveyVO li : list) { assert (li.getStdSn() == 82L); } } @Test public void testInsert() { List<StudySurveyVO> list = mapper.getList(84L); for(StudySurveyVO li : list) { if(li.getQuestionSn() == 1L) return; // 이미 있으면 return } StudySurveyVO survey = new StudySurveyVO(); survey.setStdSn(84L); survey.setQuestionSn(1); survey.setQuestion("매주 나오셔야하는데 각오한마디 부탁드립니다."); assert(mapper.insert(survey) == 1); } @Test public void testDelete() { if(mapper.getList(84L).size() == 0) return; assert(mapper.delete(84L) == 1); assert (mapper.getList(84L).size() == 0); } }
<filename>LStgEngine/gameobj/shooter/LShooters.cpp<gh_stars>1-10 #include "stdafx.h" #include "LShooters.h" #include "LSegShooter.h" #include "LRayShooter.h" LShooters::LShooters() { } LShooters::~LShooters() { } LShooter* LShooters::Add(ShooterType type, IGameObject* pParent) { LShooter* pShooter = nullptr; switch (type) { case ShooterType::Normal: pShooter = new LShooter(pParent); break; case ShooterType::Segment: pShooter = new LSegShooter(pParent); break; case ShooterType::Ray: pShooter = new LRayShooter(pParent); break; case ShooterType::Curve: break; default: break; } m_thisList.push_back(pShooter); return pShooter; } LShooter* LShooters::AddNormalShooter(IGameObject* pParent) { QuickImplGameObjAdd(LShooter); } LSegShooter* LShooters::AddSegShooter(IGameObject* pParent) { QuickImplGameObjAdd(LSegShooter); } LRayShooter* LShooters::AddRayShooter(IGameObject* pParent) { QuickImplGameObjAdd(LRayShooter); }
/** * \file Stack.h * * \brief content: class declaration of the stack class, providing stack-functionality */ #ifndef STACK_H_ #define STACK_H_ #include <iostream> #include "ListElem.h" /** * \brief This class provides a stack-like data-structure */ class Stack { private: // member /** * \brief pointer to the top element on the stack as ListElem */ ListElem *head; /** * \brief pointer to the bottom element of the stack as ListElem */ ListElem *tail; public: /** * \brief Standardkonstruktor * the default constructor for stack class */ Stack(); /** * \brief Pushes one element on the stack * This function takes a student object and pushes it onto the stack * \param student the student object to push on the stack */ void push(Student &student); /** * \brief Pops one element off the stack * This function pops off one element of the stack and passes the content to referenced student * \param student the student to write the read data in */ bool pop(Student &student); /** * \brief Ausgabefunktion * This function prints out the whole content of the stack to the console */ void ausgabe() const; }; #endif
/* an edit menu handler for TextEdit */ short NATEmenup(na_win *winp, WORD menuid, WORD itemno) { MenuHandle mh = NAmenuh(mEdit); TEHandle hTE = teinfo->hTE; TEPtr pte; short status = NA_NOTPROCESSED; switch (menuid) { case 0: pte = *hTE; if (pte->selStart != pte->selEnd) { EnableItem(mh, iCopy); if (!(winp->flags & NATE_READONLY)) { EnableItem(mh, iCut); EnableItem(mh, iClear); } } else { DisableItem(mh, iCopy); if (!(winp->flags & NATE_READONLY)) { DisableItem(mh, iCut); DisableItem(mh, iClear); } } EnableItem(mh, iSelAll); if (!(winp->flags & NATE_READONLY)) { EnableItem(mh, iPaste); } break; case mEdit: switch (itemno) { case iCut: TECut(hTE); goto DOSCRAP; case iCopy: TECopy(hTE); DOSCRAP: ZeroScrap(); TEToScrap(); goto EDITDONE; case iPaste: TEFromScrap(); TEPaste(hTE); goto EDITDONE; case iClear: TEDelete(hTE); goto EDITDONE; case iSelAll: TESetSelect(0, 32767, hTE); TESelView(hTE); EDITDONE: status = NA_PROCESSED; NATEsetscroll(winp, false, (Rect*) NULL, (Rect*) NULL); break; } default: DisableItem(mh, iSelAll); break; } return (status); }
/** * Creates a new instance of a given class, without invoking any constructor. * If the given class is <tt>abstract</tt> or an <tt>interface</tt>, then a concrete class is created, with empty * implementations for the <tt>abstract</tt>/<tt>interface</tt> methods. * * @param classToInstantiate the class to be instantiated * @param <T> type to which the returned instance should be assignable * * @return a newly created instance of the specified class, with any instance fields left uninitialized */ public static <T> T newUninitializedInstance(Class<? extends T> classToInstantiate) { if (classToInstantiate.isInterface()) { T instance = Impl.newEmptyProxy(classToInstantiate.getClassLoader(), classToInstantiate); return instance; } if (isAbstract(classToInstantiate.getModifiers())) { classToInstantiate = new ConcreteSubclass<T>(classToInstantiate).generateClass(); } return ConstructorReflection.newUninitializedInstance(classToInstantiate); }
import { program } from 'commander' import { execSync } from 'child_process' program .option('-p, --project <name>', 'specified project name') .option('--list', 'print affected projects', false) .option('--base <commit>', 'base commit to compare', 'HEAD~1') .option('--head <commit>', 'head commit to compare', `HEAD`) program.parse(process.argv) const { list, project, base, head } = program.opts() const printAffected = JSON.parse(execSync(`yarn --silent nx print-affected --base=${base} --head=${head}`).toString()) if (list) { printAffected.projects.map(o => console.log(o)) } else { console.log(printAffected.projects.includes(project)) }
package icu.d4peng.cloud.common.log.web; import com.dtflys.forest.http.ForestRequest; import com.dtflys.forest.interceptor.Interceptor; import icu.d4peng.cloud.common.core.util.NetUtils; import icu.d4peng.cloud.common.core.util.SpringAware; import icu.d4peng.cloud.common.log.constant.LogConstant; import icu.d4peng.cloud.common.log.context.LogContext; import icu.d4peng.cloud.common.log.generator.LogGenerator; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> LogHttpInterceptor:Http时引用 * * @author <a href="mailto:<EMAIL>">d4peng</a> * @version 1.0.0 * @since 2022-03-27 */ public class LogHttpInterceptor implements Interceptor<Object> { private final Logger log = LoggerFactory.getLogger(this.getClass()); @Override public boolean beforeExecute(ForestRequest request) { String traceId = LogContext.getTraceId(); if (StringUtils.isNotBlank(traceId)) { String appName = SpringAware.getEnvironmentProperty("spring.application.name"); request.addHeader(LogConstant.TRACE_ID, traceId); request.addHeader(LogConstant.SPAN_ID, LogGenerator.generatorSpanId(LogContext.getSpanId())); request.addHeader(LogConstant.PRE_APP_NAME, appName); request.addHeader(LogConstant.PRE_HOST, NetUtils.getLocalHostName()); request.addHeader(LogConstant.PRE_IP, NetUtils.getLocalIp()); } else { log.debug("[TLOG]本地threadLocal变量没有正确传递traceId,本次调用不传递traceId"); } return true; } }
/** * A JLabel with a built-in SimpleObjectFormat. The component has the concept of an active object which is passed * through the ObjectFormat to create the JLabel text. * * @author * @version $Revision: 1.3 $ */ public class ObjectRenderLabel extends JLabel { private static final String DEFAULT_NULL_STRING = "[none]"; private SimpleObjectFormat messageString; private boolean antiAliased = false; public ObjectRenderLabel(String renderPattern) { this(renderPattern, DEFAULT_NULL_STRING); } public ObjectRenderLabel(String renderPattern, String nullString) { this.messageString = new SimpleObjectFormat(renderPattern, nullString, true); setRenderObject(null); } public void setRenderObject(Object dataBean) { setText(messageString.formatObject(dataBean)); } public boolean isAntiAliased() { return antiAliased; } public void setAntiAliased(boolean antiAliased) { this.antiAliased = antiAliased; repaint(); } protected void paintComponent(Graphics g) { if (antiAliased) { Graphics2D graphics2D = (Graphics2D) g; Object oldHint = graphics2D.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); super.paintComponent(g); graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldHint); } else { super.paintComponent(g); } } }
def func_wrap(self, *args): if self.db_mutex: self.db_mutex.acquire() result = func(self, *args) self.db_conn.commit() if self.db_mutex: self.db_mutex.release() return result
// NewMockVirtualRouterStatusWriter creates a new mock instance. func NewMockVirtualRouterStatusWriter(ctrl *gomock.Controller) *MockVirtualRouterStatusWriter { mock := &MockVirtualRouterStatusWriter{ctrl: ctrl} mock.recorder = &MockVirtualRouterStatusWriterMockRecorder{mock} return mock }
<filename>src/music/BasicGUIManager.java /* * Music Visualizations: http:/github.com/michaelbrooks/music-visualization * Copyright 2012, <NAME>. BSD License. */ package music; import graphics.AnimatedNGraph; import graphics.AnimatedNGraphPanel; import graphics.ArrayLineGraphPanel; import graphics.GraphPanel; import graphics.ParticleCloud; import graphics.ParticleLine; import graphics.ScanningLineGraphPanel; import graphics.VerticalPitchGraphPanel; import graphics.VerticalQualityGraphPanel; import java.awt.Color; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import music.data.DataFrame; import music.data.calc.DPoint; import music.data.calc.NoteConverter; import music.data.calc.PeakPicker; import music.data.calc.Smoother; import music.data.calc.SmootherTwo; import music.data.impl.DirectDataFrame; /** * * @author michael */ public class BasicGUIManager extends AbstractGUIManager { public BasicGUIManager() { } VerticalQualityGraphPanel qualityGraphPanel; VerticalPitchGraphPanel pitchGraphPanel; AnimatedNGraphPanel particleCloudGraphPanel; AnimatedNGraphPanel particleLineGraphPanel; ScanningLineGraphPanel scanningLineGraphPanel; ArrayLineGraphPanel arrayLineGraphPanel; @Override public void initialize() { super.initialize(); qualityGraphPanel = new VerticalQualityGraphPanel("Quality", 120, 300); positionGraphPanel(qualityGraphPanel); qualityGraphPanel.getGraph().setHighLowValues(1, 0); qualityGraphPanel.getGraph().setHighLowColors(Color.green, Color.red); addGraphPanel(qualityGraphPanel); pitchGraphPanel = new VerticalPitchGraphPanel("Pitch", 120, 500); pitchGraphPanel.getGraph().setHighLowNote(120, 40); //pitchGraphPanel.getFrame().setLocation(0, 350); positionGraphPanel(pitchGraphPanel); pitchGraphPanel.getGraph().setDisplayGridLines(true); pitchGraphPanel.getGraph().setNoteLineWidth(2); addGraphPanel(pitchGraphPanel); AnimatedNGraph animatedGraph = new ParticleCloud(300); particleCloudGraphPanel = new AnimatedNGraphPanel(animatedGraph, 50, "Particles", 500, 500); //particleCloudGraphPanel.getFrame().setLocation(150, 0); positionGraphPanel(particleCloudGraphPanel); particleCloudGraphPanel.getGraph().setLowerLimit(0, 0); particleCloudGraphPanel.getGraph().setUpperLimit(0, 1); particleCloudGraphPanel.getGraph().setLowerLimit(1, 0); particleCloudGraphPanel.getGraph().setUpperLimit(1, Math.PI * 2); particleCloudGraphPanel.getGraph().setLowerLimit(2, 0); particleCloudGraphPanel.getGraph().setUpperLimit(2, 1); addGraphPanel(particleCloudGraphPanel); animatedGraph = new ParticleLine(300); particleLineGraphPanel = new AnimatedNGraphPanel(animatedGraph, 50, "Particle Line", 500, 200); //particleLineGraphPanel.getFrame().setLocation(680, 0); positionGraphPanel(particleLineGraphPanel); particleLineGraphPanel.getGraph().setLowerLimit(0, 0); particleLineGraphPanel.getGraph().setLowerLimit(0, 1); addGraphPanel(particleLineGraphPanel); arrayLineGraphPanel = new ArrayLineGraphPanel("WAV", 500, 300); //arrayLineGraphPanel.getFrame().setLocation(150, 550); positionGraphPanel(arrayLineGraphPanel); arrayLineGraphPanel.getGraph().setVerticalRangeAuto(true); arrayLineGraphPanel.getGraph().setConnectPoints(true); addGraphPanel(arrayLineGraphPanel); scanningLineGraphPanel = new ScanningLineGraphPanel(400, "Line", 500, 300); //scanningLineGraphPanel.getFrame().setLocation(680, 550); positionGraphPanel(scanningLineGraphPanel); scanningLineGraphPanel.getGraph().setVerticalRange(0,1); scanningLineGraphPanel.getGraph().setVerticalRangeAuto(true); addGraphPanel(scanningLineGraphPanel); setupThread(new Runnable() { Recorder rec; long lastGraphedTime = 0; Smoother qualitySmoother = new SmootherTwo(0.333, 0.333); Smoother pitchSmoother = new SmootherTwo(0.333, 0.333); Smoother spectralFluxSmoother = new SmootherTwo(0.333, 0.333); Smoother spectralCentroidSmoother = new SmootherTwo(0.333, 0.333); public void run() { rec = getAudioComponents().getRecorder(); while (polling()) { List<DataFrame> latestFrames = rec.popFrames(); if (latestFrames.size() > 0) { DataFrame frame = latestFrames.get(latestFrames.size() - 1); if (frame.getTime() != lastGraphedTime) { double pitch = 0; double quality = 0; double spectralFlux = 0; double spectralCentroid = 0; for (int i = 0; i < latestFrames.size(); i++) { DataFrame subFrame = latestFrames.get(i); pitch = subFrame.getPitchInfo().getPrimaryPitch(); quality = subFrame.getQualityInfo().getPrimaryCorrelation(); spectralFlux = subFrame.getQualityInfo().getSpectralFlux(); spectralCentroid = subFrame.getQualityInfo().getSpectralCentroidFrequency(); if (subFrame.getSM().isSilence()) { pitch = 0; quality = 0; spectralFlux = 0; //spectralCentroid = 0; } pitch = pitchSmoother.newValue(pitch); quality = qualitySmoother.newValue(quality); spectralFlux = spectralFluxSmoother.newValue(spectralFlux); spectralCentroid = spectralCentroidSmoother.newValue(spectralCentroid); if (scanningLineGraphPanel.isVisible() && quality > 0.8) { scanningLineGraphPanel.graph(spectralCentroid / NoteConverter.pitchToFrequency(pitch)); } } if (scanningLineGraphPanel.isVisible()) { scanningLineGraphPanel.repaint(); } if (arrayLineGraphPanel.isVisible()) { arrayLineGraphPanel.graph(frame.getPS().getRawData()); } if (qualityGraphPanel.isVisible()) qualityGraphPanel.graph(quality); if (pitchGraphPanel.isVisible()) { pitchGraphPanel.setConfidence(quality); pitchGraphPanel.graph(pitch); } if (particleLineGraphPanel.isVisible()) { particleLineGraphPanel.getGraph().setData(0, 1-quality); } if (particleCloudGraphPanel.isVisible()) { AnimatedNGraph particleCloudGraph = particleCloudGraphPanel.getGraph(); particleCloudGraph.setData(2, quality); } } lastGraphedTime = frame.getTime(); } try { Thread.sleep(50); } catch (InterruptedException ex) { ex.printStackTrace(); } } } }); } }
/// Removes the provided token/path pair from the watch list. /// Does not stop watching this path, if it is associated with /// other tokens. pub fn unwatch(&mut self, path: &Path, token: WatchToken) { let mut state = self.state.lock().unwrap(); let idx = state.watchees.iter().position(|w| w.token == token && w.path == path); if let Some(idx) = idx { let removed = state.watchees.remove(idx); if !state.watchees.iter().any(|w| w.path == removed.path) { if let Err(e) = self.inner.unwatch(&removed.path) { warn!("unwatching error {:?}", e); } } //TODO: Ideally we would be tracking what paths we're watching with // some prefix-tree-like structure, which would let us keep track // of when some child path might need to be reregistered. How this // works and when registration would be required is dependent on // the underlying notification mechanism, however. There's an // in-progress rewrite of the Notify crate which use under the // hood, and a component of that rewrite is adding this // functionality; so until that lands we're using a fairly coarse // heuristic to determine if we need to re-watch subpaths. // if this was recursive, check if any child paths need to be // manually re-added if removed.recursive { // do this in two steps because we've borrowed mutably up top let to_add = state .watchees .iter() .filter(|w| w.path.starts_with(&removed.path)) .map(|w| (w.path.to_owned(), mode_from_bool(w.recursive))) .collect::<Vec<_>>(); for (path, mode) in to_add { if let Err(e) = self.inner.watch(&path, mode) { warn!("watching error {:?}", e); } } } } }
// IsPartitionAvailable checks whether the partition table replica was available. func (tr *TiFlashReplicaInfo) IsPartitionAvailable(pid int64) bool { for _, id := range tr.AvailablePartitionIDs { if id == pid { return true } } return false }
<reponame>worldiety/gapt /* * MinIO Cloud Storage, (C) 2015, 2016 MinIO, 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 gapt // MatchSimple - finds whether the text matches/satisfies the pattern string. // supports only '*' wildcard in the pattern. // considers a file system path as a flat name space. func MatchSimple(pattern, name string) bool { if pattern == "" { return name == pattern } if pattern == "*" { return true } rname := make([]rune, 0, len(name)) rpattern := make([]rune, 0, len(pattern)) for _, r := range name { rname = append(rname, r) } for _, r := range pattern { rpattern = append(rpattern, r) } simple := true // Does only wildcard '*' match. return deepMatchRune(rname, rpattern, simple) } // Match - finds whether the text matches/satisfies the pattern string. // supports '*' and '?' wildcards in the pattern string. // unlike path.Match(), considers a path as a flat name space while matching the pattern. // The difference is illustrated in the example here https://play.golang.org/p/Ega9qgD4Qz . func Match(pattern, name string) (matched bool) { if pattern == "" { return name == pattern } if pattern == "*" { return true } rname := make([]rune, 0, len(name)) rpattern := make([]rune, 0, len(pattern)) for _, r := range name { rname = append(rname, r) } for _, r := range pattern { rpattern = append(rpattern, r) } simple := false // Does extended wildcard '*' and '?' match. return deepMatchRune(rname, rpattern, simple) } func deepMatchRune(str, pattern []rune, simple bool) bool { for len(pattern) > 0 { switch pattern[0] { default: if len(str) == 0 || str[0] != pattern[0] { return false } case '?': if len(str) == 0 && !simple { return false } case '*': return deepMatchRune(str, pattern[1:], simple) || (len(str) > 0 && deepMatchRune(str[1:], pattern, simple)) } str = str[1:] pattern = pattern[1:] } return len(str) == 0 && len(pattern) == 0 }
Species Mention Entity Recognition, Linking and Classification Using RoBERTa in Combination with Spanish Medical Embeddings This paper introduces the solution submitted by puma’s team to the LivingNER 2022 shared task. The proposed system finds species mentions inside clinical case reports, links the mentions to the NCBI taxonomy database, and classifies the identified species according to clinically relevant categories. Our architecture combines a Spanish biomedical RoBERTa model with a neural network layer for sequence classification. We used the NCBI taxonomy entries for the entity linking problem and calculated the Levenshtein distance to each identified species. We used the medical Spanish word embeddings to train a logistic regression classifier to identify clinically relevant categories of the species. The obtained results ranked above the mean for all tasks, confirming that a RoBERTa-based system, pre-trained with texts related to the biomedical field, performs well in the named entity recognition task. Using a dictionary of terms in the entity linking task proved to improve the performance.
pub mod definitions; pub mod mesh; pub mod pipeline; pub mod prelude; pub mod system; pub mod utils; pub use system::System; use crate::utils::Event; use winit::{ event::{self, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; /////////////////////////////////////////////////////////////////////////// // Base trait for application /////////////////////////////////////////////////////////////////////////// pub trait Base: 'static + Sized { fn init(system: &mut System) -> Self; fn update(&mut self, system: &mut System, events: &Event); fn render(&mut self, swap_chain: &mut wgpu::SwapChain, system: &mut System); } /////////////////////////////////////////////////////////////////////////// // Main Application logic /////////////////////////////////////////////////////////////////////////// pub fn app<E: Base>() { let window_event_loop = EventLoop::new(); let adapter = wgpu::Adapter::request(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, backends: wgpu::BackendBit::PRIMARY, }) .unwrap(); let (device, queue) = adapter.request_device(&wgpu::DeviceDescriptor { extensions: wgpu::Extensions { anisotropic_filtering: false, }, limits: wgpu::Limits::default(), }); let sc_desc = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, format: wgpu::TextureFormat::Bgra8Unorm, width: 0, height: 0, present_mode: wgpu::PresentMode::Vsync, }; let mut system = System { device, screen_descriptor: sc_desc, queue, window: WindowBuilder::new() .with_title("title") .with_resizable(true), }; let mut example = E::init(&mut system); let window = system.window.clone().build(&window_event_loop).unwrap(); let hidpi_factor = window.hidpi_factor(); let size = window.inner_size().to_physical(hidpi_factor); let surface = wgpu::Surface::create(&window); system.screen_descriptor.width = size.width.round() as u32; system.screen_descriptor.height = size.height.round() as u32; let mut swap_chain = system .device .create_swap_chain(&surface, &system.screen_descriptor); let mut input_events = Event::new(); /////////////////////////////////////////////////////////////////////////// // Render loop /////////////////////////////////////////////////////////////////////////// window_event_loop.run(move |event, _, control_flow| { *control_flow = if cfg!(feature = "metal-auto-capture") { ControlFlow::Exit } else { ControlFlow::Poll }; match event { event::Event::WindowEvent { event: WindowEvent::Resized(size), .. } => { let physical = size.to_physical(hidpi_factor); input_events.dpi_factor = hidpi_factor; input_events.resized = true; system.screen_descriptor.width = physical.width.round() as u32; system.screen_descriptor.height = physical.height.round() as u32; swap_chain = system .device .create_swap_chain(&surface, &system.screen_descriptor); } event::Event::WindowEvent { event, .. } => match event { WindowEvent::CloseRequested => { *control_flow = ControlFlow::Exit; } _ => { input_events.handle_event(event); example.update(&mut system, &input_events); input_events.clear(); } }, event::Event::EventsCleared => { example.render(&mut swap_chain, &mut system); } _ => (), } }); }
/* Routine to determine the base address of the BroadSync Register cache on KT2 */ uint32 soc_cmic_bs_reg_cache(int unit, int bs_num) { uint32 msg_end = MSG_AREA_END(_soc_cmic_uc_msg_base(unit)); return msg_end + bs_num * sizeof(mos_msg_bs_reg_cache_t); }
<reponame>jfass/scythe #ifndef SCYTHE_H #define SCYTHE_H #include <zlib.h> #include "kseq.h" /* KSEQ_INIT() cannot be called here, because we only need the types defined. Calling KSEQ_INIT() would also define functions, leading to an unused function warning with GCC. So, the basic typedefs kseq.h has are included here, and each file that reads needs: This was a fix also used in <NAME> Sickle (which I also helped with) and is the only way I know of dealing with this. __KS_GETC(gzread, BUFFER_SIZE) __KS_GETUNTIL(gzread, BUFFER_SIZE) __KSEQ_READ */ #define BUFFER_SIZE 4096 __KS_TYPE(gzFile) __KS_BASIC(gzFile, BUFFER_SIZE) __KSEQ_TYPE(gzFile) __KSEQ_BASIC(gzFile) #define MAX_ADAPTERS 1000 #define MATCH_SCORE 1 #define MISMATCH_SCORE -1 #define IS_FASTQ(quality_type) INTEGER(quality_type)[0] >= 0 typedef enum { PHRED, SANGER, SOLEXA, ILLUMINA } quality_type; #define Q_OFFSET 0 #define Q_MIN 1 #define Q_MAX 2 /* The quality constants come from: http://www.biopython.org/DIST/docs/api/Bio.SeqIO.QualityIO-module.html*/ static const int quality_contants[4][3] = { /* offset, min, max */ {0, 4, 60}, /* PHRED */ {33, 0, 93}, /* SANGER */ {64, -5, 62}, /* SOLEXA, early Illumina (pre-pipeline 1.3) */ {64, 0, 62} /* ILLUMINA (post-pipeline 1.3) */ }; typedef struct adapter { char *name; char *seq; int length; unsigned int *occurrences; } adapter; typedef struct adapter_array { adapter *adapters; int n; } adapter_array; enum contam { NOT_CONTAM, CONTAM }; typedef struct likelihood_set { double random; double contam; } likelihood_set; typedef struct posterior_set { enum contam is_contam; double random; double contam; } posterior_set; typedef struct match { int *match; int n; int score; int *match_pos; float *p_quals; posterior_set *ps; int adapter_index; } match; /* prob.c prototypes */ float *qual_to_probs(const char *qual, quality_type q_type); double p_data(const int *matches, float *p_quals, float p_prior_contam, float p_match, int n); posterior_set *posterior(const int *matches, float *p_quals, float p_prior, float p_match, int n); likelihood_set *likelihood(const int *matches, float *p_quals, float p_match, int n); /* util.c prototypes */ void *xmalloc(size_t size); adapter_array *load_adapters(gzFile fp); void destroy_adapters(adapter_array *aa, int n); char *fmt_matches(const char *seqa, const char *seqb, const int *matches, const int n); void print_float_array(const float *array, int n); void fprint_float_array(FILE *fp, const float *array, int n); void print_int_array(const int *array, int n); void print_uint_array(const unsigned int *array, int n); void fprint_uint_array(FILE *fp, const unsigned int *array, int n); int sum(const int *x, int n); void write_fastq(gzFile output_fp, kseq_t *seq, int add_tag, char *tag, int match_n); /* match.c prototypes */ int *score_sequence(const char *seqa, const char *seqb, int n); match *find_best_match(const adapter_array *aa, const char *read, float *p_quals, float prior, float p_match, int min); void destroy_match(match *m); #endif /* SCYTHE_H */
<reponame>guochunhe/Vitis-AI # Copyright 2019 Xilinx 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. import os import random import torch import numpy as np import torchvision.transforms as standard_transforms import torchvision.utils as vutils from torch import optim from torch.autograd import Variable from torch.backends import cudnn from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.data import DataLoader import torch.nn.functional as F from code.data_loader import cityscapes from code.models.enet_xilinx import ENet from code.utils import evaluate, AverageMeter, CrossEntropyLoss2d, save_checkpoint, compute_flops cudnn.benchmark = True import torch.nn as nn from collections import OrderedDict import tqdm from code.configs.model_config import Configs def main(args): if not os.path.exists(args.checkpoint_dir): os.makedirs(args.checkpoint_dir) open(os.path.join(args.checkpoint_dir, 'arguments.txt'), 'w').write(str(args) + '\n\n') # network net = ENet(num_classes=args.num_classes) # flops current_epoch =0 if args.resume: checkpoint = torch.load(args.weight, map_location='cuda:0') # strict=False, so that it is compatible with old pytorch saved models checkpoint['state_dict'] = OrderedDict([(k[5:], v) if 'base' in k else (k, v) for k, v in checkpoint['state_dict'].items()]) net.load_state_dict(checkpoint['state_dict']) print("=> loaded checkpoint '{}' (epoch {})".format(args.weight, checkpoint['epoch'])) current_epoch = checkpoint['epoch'] else: print("=> training from scratch!") net = torch.nn.DataParallel(net) net = net.cuda() train_set = cityscapes.CityScapes(root=args.data_root, quality='fine', mode='train', size=(1024, 512)) train_loader = DataLoader(train_set, batch_size=args.train_batch_size, num_workers=16, shuffle=True) val_set = cityscapes.CityScapes(root=args.data_root, quality='fine', mode='val', size=(1024, 512)) val_loader = DataLoader(val_set, batch_size=args.val_batch_size, num_workers=16, shuffle=False) criterion = torch.nn.CrossEntropyLoss(ignore_index=args.ignore_label).cuda() optimizer = optim.SGD([ {'params': [param for name, param in net.named_parameters() if name[-4:] == 'bias'],'lr': 2 * args.lr}, {'params': [param for name, param in net.named_parameters() if name[-4:] != 'bias'], 'lr': args.lr, 'weight_decay': args.weight_decay}], momentum=args.momentum) scheduler = ReduceLROnPlateau(optimizer, 'min', patience=args.lr_patience, min_lr=1e-10) best_miou = 0.0 if args.test_only: _ = validate(val_loader, net, criterion, optimizer, current_epoch, args, best_miou) exit() else: for epoch in range(current_epoch, args.total_epoch): train(train_loader, net, criterion, optimizer, epoch, args) val_loss, best_miou = validate(val_loader, net, criterion, optimizer, epoch, args, best_miou) scheduler.step(val_loss) def train(train_loader, net, criterion, optimizer, epoch, args): net.train() train_loss = AverageMeter() curr_iter = epoch* len(train_loader) max_iters = args.total_epoch * len(train_loader) for i, data in enumerate(train_loader): optimizer.param_groups[0]['lr'] = 2 * args.lr *(1 - float(curr_iter) / max_iters) ** args.lr_decay optimizer.param_groups[1]['lr'] = args.lr *(1 - float(curr_iter) / max_iters) ** args.lr_decay inputs, labels = data N = inputs.size(0) inputs = inputs.cuda() labels = labels.cuda() optimizer.zero_grad() outputs = net(inputs) if outputs.size()[2:] != labels.size()[1:]: outputs = F.upsample(outputs, size=gts.size()[1:], mode='bilinear') loss = criterion(outputs, labels) loss.backward() optimizer.step() train_loss.update(loss.data) curr_iter += 1 if (i + 1) % args.print_freq == 0: print('[epoch %d], [iter %d / %d], [train loss %.5f], [lr %.10f]' % ( epoch, i + 1, len(train_loader), train_loss.avg, optimizer.param_groups[1]['lr'])) def validate(val_loader, net, criterion, optimizer, epoch, args, best_miou): net.eval() val_loss = AverageMeter() inputs_all, gts_all, predictions_all = [], [], [] for vi, data in enumerate(val_loader): inputs, gts = data with torch.no_grad(): inputs = inputs.cuda() gts = gts.cuda() outputs = net(inputs) if outputs.size()[2:] != gts.size()[1:]: outputs = nn.functional.interpolate(outputs, size=gts.size()[1:], mode='bilinear', align_corners=True) predictions = outputs.data.max(1)[1].squeeze_(1).cpu().numpy() val_loss.update(criterion(outputs, gts).data) inputs_all.append(inputs.data.cpu()) gts_all.append(gts.data.cpu().numpy()) predictions_all.append(predictions) gts_all = np.concatenate(gts_all) predictions_all = np.concatenate(predictions_all) acc, acc_cls, ious, mean_iu, fwavacc = evaluate(predictions_all, gts_all, args.num_classes, args.ignore_label) print('[epoch %d], [val loss %.5f], [mean_iu %.5f]' % ( epoch, val_loss.avg, mean_iu)) if mean_iu > best_miou: best_miou = mean_iu save_checkpoint({ 'epoch': epoch + 1, 'state_dict': net.module.state_dict(), 'optimizer': optimizer.state_dict(), 'best_pred': best_miou, }, args.checkpoint_dir, True) print('-------------------------------------------------------------') print('best record: [val loss %.5f], [mean_iu %.5f], [epoch %d]' % ( val_loss.avg, mean_iu, epoch)) print('-------------------------------------------------------------') return val_loss.avg, best_miou if __name__ == '__main__': args = Configs().parse() torch.manual_seed(args.seed) main(args)
//============================================================================== /// Representation of a player in the game. This player could be local or /// remote. //============================================================================== class PlayerController: public ObjectBase { public: DEFINE_TYPE(PlayerController,ObjectBase) DEFINE_CREATE_AND_CLONE PlayerController (void); PlayerController (const PlayerController &rhs); PlayerController & operator = (const PlayerController &rhs); virtual ~PlayerController (void); virtual void archive (const std::shared_ptr<Archive> &archive); public: }
THE BARYONIC ACOUSTIC FEATURE AND LARGE-SCALE CLUSTERING IN THE SLOAN DIGITAL SKY SURVEY LUMINOUS RED GALAXY SAMPLE We examine the correlation function ξ of the Sloan Digital Sky Survey Luminous Red Galaxy sample at large scales (60 h−1 Mpc < s < 400 h−1 Mpc) using the final data release (DR7). Focusing on a quasi-volume-limited (0.16 < z < 0.36) subsample and utilizing mock galaxy catalogs, we demonstrate that the observed baryonic acoustic peak and larger scale signal are consistent with ΛCDM at 70%–95% confidence. Fitting data to a non-linear, redshift-space, template-based model, we constrain the peak position at sp = 101.7± 3.0 h−1 Mpc when fitting the range 60 h−1 Mpc < s < 150 h−1 Mpc (1σ uncertainties). This redshift-space distance sp is related to the comoving sound horizon scale rs after taking into account matter-clustering non-linearities, redshift distortions, and galaxy-clustering bias. Mock catalogs show that the probability that a DR7-sized sample would not have an identifiable peak is at least ∼10%. As a consistency check of a fiducial cosmology, we use the observed sp to obtain the distance relative to the acoustic scale. We find rs/DV(z = 0.278) = 0.1389 ± 0.0043. This result is in excellent agreement with Percival et al., who examine roughly the same data set, but use the power spectrum. Comparison with other determinations in the literature are also in very good agreement. The signal of the full sample at 125 h−1 Mpc < s < 200 h−1 Mpc tends to be high relative to theoretical expectations; this slight deviation can probably be attributed to sample variance. We have tested our results against a battery of possible systematic effects, finding all effects are smaller than our estimated sample variance.
<filename>lib/src/layers/LayerVideo.ts import Layer from './Layer'; import { fileName } from '../utils'; /** * A video element. */ export default class LayerVideo extends Layer { constructor(json: any, assets: any) { super(json, assets); this.fileID = fileName(json.content.source); this.file = assets.videos[this.fileID] as HTMLVideoElement; if (!json.content.audioEnabled) { this.file.setAttribute('muted', 'true'); this.file.muted = false; this.file.volume = 0; } } dispose() { this.file.pause(); } }
/** * Absolute bounds always same to relative bounds, because diagrams can't have a parent! */ @Override public void testGetAbsoluteBounds() { BasicDiagram d = new BasicDiagram("diagram"); BasicShape grandfather = getBasicShapeToTest("Grandfather"); BasicShape father = getBasicShapeToTest("Father"); BasicShape son = getBasicShapeToTest("Son"); d.addChildShape(grandfather); grandfather.addChildShape(father); father.addChildShape(son); Point p1 = new Point(rand.nextDouble(), rand.nextDouble()); Point p2 = new Point(rand.nextDouble(), rand.nextDouble()); Point p3 = new Point(rand.nextDouble(), rand.nextDouble()); Point p4 = new Point(rand.nextDouble(), rand.nextDouble()); Point p5 = new Point(rand.nextDouble(), rand.nextDouble()); Point p6 = new Point(rand.nextDouble(), rand.nextDouble()); Bounds b1 = new Bounds(p1, p2); Bounds b2 = new Bounds(p3, p4); Bounds b3 = new Bounds(p5, p6); grandfather.setBounds(b1); father.setBounds(b2); son.setBounds(b3); assertEquals(grandfather.getBounds().getUpperLeft().getX(), grandfather.getAbsoluteBounds().getUpperLeft().getX(), delta); assertEquals(grandfather.getBounds().getUpperLeft().getY(), grandfather.getAbsoluteBounds().getUpperLeft().getY(), delta); assertEquals(grandfather.getBounds().getLowerRight().getX(), grandfather.getAbsoluteBounds().getLowerRight().getX(), delta); assertEquals(grandfather.getBounds().getLowerRight().getY(), grandfather.getAbsoluteBounds().getLowerRight().getY(), delta); assertEquals(father.getBounds().getUpperLeft().getX(), father.getAbsoluteBounds().getUpperLeft().getX(), delta); assertEquals(father.getBounds().getUpperLeft().getY(), father.getAbsoluteBounds().getUpperLeft().getY(), delta); assertEquals(father.getBounds().getLowerRight().getX(), father.getAbsoluteBounds().getLowerRight().getX(), delta); assertEquals(father.getBounds().getLowerRight().getY(), father.getAbsoluteBounds().getLowerRight().getY(), delta); assertEquals(son.getBounds().getUpperLeft().getX(), son.getAbsoluteBounds().getUpperLeft().getX(), delta); assertEquals(son.getBounds().getUpperLeft().getY(), son.getAbsoluteBounds().getUpperLeft().getY(), delta); assertEquals(son.getBounds().getLowerRight().getX(), son.getAbsoluteBounds().getLowerRight().getX(), delta); assertEquals(son.getBounds().getLowerRight().getY(), son.getAbsoluteBounds().getLowerRight().getY(), delta); }
// appendFilterForTask will create a new filter for a task and append // that filter at the end of the pipeline. If processing has not // been started yet, it will be started. func (w *Walker) appendFilterForTask(task workerTask, udata interface{}, buflen int) error { if w.promising { return ErrNoMoreFiltersAccepted } newFilter := newFilter(task, udata, buflen) if w.pipe.empty() { w.startProcessing() } w.pipe.appendFilter(newFilter) return nil }
#include <stdio.h> #include <stdlib.h> #include <string.h> void send_data(unsigned char *data, int len) { printf("[Sent data]\n"); for (int i=0; i < len; i++) { printf("%2x ", data[i]); } printf("\n"); } unsigned char* bar() { // Array data[8] is deallocated immediately on function return as it falls // out of scope. It is deallocated with the bar()'s stack frame. unsigned char data[8] = {1, 2, 3, 4, 5, 6, 7, 8}; return data; } int main() { unsigned char *data = bar(); // At this point, data becomes a dangling pointer! send_data(data, 8); return 0; }
/* * Check whether request parameters has specified parameter fields * @param form is a url.Values point which will be checked * @param args are checking field names * @return nil if check successfully, otherwise a ChatError indicates first unfound parameter */ func CheckChatParameter(form *url.Values, args ...string) error { for _, arg := range args { if _, ok := (*form)[arg]; !ok { return ChatError(fmt.Sprintf("client not send %s parameter", arg)) } } return nil }
from torch_scope import basic_wrapper as bw import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import os import argparse import logging import functools import codecs import json from abnlp.model import seqLabel, ensembledSeqLabel from abnlp.encoder import strFromFileEncoderWrapper from abnlp.common.utils import adjust_learning_rate, rank_by_number, conlidate_code_switch logger = logging.getLogger(__name__) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--gpu', default='auto') parser.add_argument('--cp_root', default="./checkpoint") parser.add_argument('--config_list', nargs='+', default=["./config/sner0.json", "./config/sner1.json", "./config/sner2.json", "./config/sner3.json", "./config/sner4.json", "./config/sner5.json", "./config/sner6.json", "./config/sner7.json", "./config/sner8.json"]) parser.add_argument('-i', '--input', nargs='+', default = ["../processed_data/dev.json", "../processed_data/test.json"]) parser.add_argument('-n', '--name', nargs='+', default = ["dev.txt", "test.txt"]) parser.add_argument('-o', '--output', default = "../processed_data/dev_output_0.csv") conf = parser.parse_args() gpu_index = bw.auto_device() if 'auto' == conf.gpu else int(conf.gpu) device = torch.device("cuda:" + str(gpu_index) if gpu_index >= 0 else "cpu") if gpu_index >= 0: torch.cuda.set_device(gpu_index) dev_data, test_data = None, None with torch.no_grad(): for config_file in conf.config_list: with open(config_file, 'r') as fin: args = json.load(fin) if dev_data is None: logger.info('Loading the data...') args['strEncoder'] = {k: v for k, v in args['strEncoder'].items() if k != 'label'} if len(conf.input) > 0: dev_data = strFromFileEncoderWrapper(args, processed_file = conf.input[0]) dev_data = [tup for tup in dev_data.get_tqdm(device, args['batch_size'], shuffle = False)] if len(conf.input) > 1: test_data = strFromFileEncoderWrapper(args, processed_file = conf.input[1]) test_data = [tup for tup in test_data.get_tqdm(device, args['batch_size'], shuffle = False)] logger.info("Model: {}".format(args['checkpoint_name'])) logger.info("Config: {}".format(args)) model_path = os.path.join(conf.cp_root, args['checkpoint_name'], 'best.th') logger.info('Building the model from:{}...'.format(model_path)) model = torch.load(model_path, map_location=lambda storage, loc: storage) logger.info('Loading to GPU: {}'.format(gpu_index)) model.to(device) model.spEncoder.pipeline_dict['lm'].f_lm.move_hidden(device) model.spEncoder.pipeline_dict['lm'].b_lm.move_hidden(device) model.eval() ensembledModel = ensembledSeqLabel(model) if dev_data is not None: for x, _ in dev_data: ensembledModel.ensemble(x) if test_data is not None: for x, _ in test_data: ensembledModel.ensemble(x) model.cpu() logger.info('Ensemble completed') if dev_data is not None: dev_output = ensembledModel.decode(dev_data, conf.name[0]) dev_output = rank_by_number(dev_output) if test_data is not None: test_output = ensembledModel.decode(test_data, conf.name[1]) test_output = rank_by_number(test_output) with codecs.open(conf.output, 'w', 'utf-8') as fout: fout.write('Filename,Start,End,Type,Score,Surface\n') if dev_data is not None: fout.write(dev_output+'\n') if test_data is not None: fout.write(test_output)
// #include<bits/stdc++.h> using namespace std; #define ll long long #define itn int #define endl "\n" #define h printf("\n") #define MAXN 111111 inline int read(){ int x=0,y=1;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') y=-1;c=getchar();} while (c>='0'&&c<='9') x=(x<<3)+(x<<1)+c-'0',c=getchar(); return x*y; } map<string,int>S; string ans,a; int main(){ int n=read(); int maxx=0; while(n--){ cin>>a; S[a]++; if(S[a]>maxx)maxx=S[a],ans=a; } cout<<ans; return 0; }
1 of 1 2 of 1 John Kerry has been U.S. Secretary of State for precisely one year, and he has already 1) rescued President Obama from his ill-considered promise to bomb Syria if it crossed the “red line” and used poison gas; 2) opened serious negotiations with Iran on its alleged attempt to build nuclear weapons; and 3) taken on the job of brokering an Israeli-Palestinian peace accord. Getting Obama off the hook was useful, and may yet lead to the U.S. ending its support for the insurgency in Syria, which at this point would probably be the least bad outcome. Opening negotiations with Iran was long overdue, and makes the nightmare prospect of an American or a joint U.S.-Israeli air attack on Iran less likely. But even King Solomon and Avicenna (Ibn Sina), sitting jointly in judgement on the Israeli-Palestinian dispute, could not broker a peace accord there. Kerry is indefatigable. He has been to Israel/Palestine eleven times in the past year, and spent as much as a hundred hours face to face with Israeli Prime Minister Binyamin Netanyahu, Palestinian leader Mahmoud Abbas, or their close advisers. Unlike all the previous “brokers”, he has been astoundingly discreet: not a hint of what has been said in private has leaked into the public domain. And yet there is almost no hope of a real peace deal. If persistence in the face of all the odds were enough, Kerry would be the man who finally made it happen. (Israeli Defence Minister Moshe Yaalon recently complained that his approach is “obsessive and messianic.”) But Kerry has no leverage: he has to rely on the desire of the two leaders to make the “peace process” work, and it just isn’t there; not, at least, on any terms that both would find acceptable. The list of deal-breakers includes almost every topic under discussion: the borders of a Palestinian state, the future of the Jewish settlements in the occupied territories, whether Jerusalem can be the joint capital of Israel and Palestine, whether Israel can maintain a military presence in the Jordan Valley, the right of Palestinian refugees to return to their ancestral homes, and Israel’s demand that the Palestinians recognise it as an explicitly Jewish state. This last demand, which was only raised in the past couple of years, seems deliberately designed to be unacceptable to the Palestinians. Not only are they required to acknowledge the legitimacy of the Israeli state (which they have already done), but also to give their blessing to the ethnic and religious character of that state. It is not normal in diplomacy for one state to comment upon the internal arrangements of another, let alone to give them its public support. Even the United States, Israel’s closest ally and supporter, does not officially recognise it as a “Jewish state.” The Israeli demand is an attempt to rub the Palestinians’ noses in their defeat, and why would you set out to do that if you really wanted a deal? The Palestinian insistence on a “right of return,” however rooted in natural justice, is equally self-defeating in practice. Everybody knows that a peace deal must mean compensation for the refugees of 1948 and their descendants, not a general right of return to what is now Israel, for that really would mean the end of the “Jewish state.” But no Palestinian leader has ever dared to say so out loud. So why, then, has John Kerry embarked on his quixotic mission to make the “peace process” work? It has been effectively dead for at least a dozen years, although it remains unburied because the pretense that it is still alive allows everybody to avoid hard decisions. But Kerry, with his nine-month deadline to achieve a comprehensive “final-status agreement” (which expires in April), is taking it seriously. His own explanation is lyrical but opaque: “I believe that history is not made by cynics. It is made by realists who are not afraid to dream.” But the business about “making history” – that, perhaps, is sincere. Kerry has had a long and interesting career as a senator, and even took a shot at the presidency, but this is probably his last big job, and he wants to make his mark. As the reality of what he is up against strikes home, he has scaled back his ambitions a good deal. For some months now he has been talking about a more modest “framework” deal by April that would establish a set of basic principles for further talks. Such deals commit nobody to anything, and are therefore a popular way of pretending to make progress, but he’ll be lucky to get even that. The French general Pierre Bosquet, watching the suicidal charge of the British Light Brigade in the Crimean War in 1854, said: “It is magnificent, but it is not war. It’s madness.” Kerry’s foredoomed quest for a final peace settlement between Israel and the Palestinians is magnificent too, in its own peculiar way, but it’s not diplomacy. It’s hubris.
def search_services(query, services, quiet): cards = set() for svc in services: if (svc.uses_feature(query) or svc.uses_database(query) or query.upper() in svc.mxd.upper() or query.upper() in svc.name.upper()): if quiet >= 2: cards.add(svc.veryquiet_repr()) elif quiet == 1: cards.add(svc.quiet_repr()) else: cards.add(repr(svc)) return list(cards)
By Richard Black Environment correspondent, BBC News website Lake sediments contain a record of Arctic temperatures Arctic temperatures are now higher than at any time in the last 2,000 years, research reveals. Changes to the Earth's orbit drove centuries of cooling, but temperatures rose fast in the last 100 years as human greenhouse gas emissions rose. Scientists took evidence from ice cores, tree rings and lake sediments. Writing in the journal Science, they say this confirms that the Arctic is very sensitive both to changes in solar heating and to greenhouse warming. The 23 sites sampled were good enough to provide a decade-by-decade picture of temperatures across the region. How much energy we're getting from the Sun is no longer the most important thing governing the temperature of the Arctic Nicholas McKay, University of Arizona, Tucson The result is a "hockey stick"-like curve in which the last decade - 1998-2008 - stands out as the warmest in the entire series. "The most pervasive signal in the reconstruction, the most prominent trend, is the overall cooling that took place for the first 1,900 years [of the record]," said study leader Darrell Kaufman from Northern Arizona University in Flagstaff, US. "The 20th Century stands out in strong contrast to the cooling that should have continued. The last half-century was the warmest of the 2,000-year temperature record, and the last 10 years have been especially dramatic," he told BBC News. On average, the region cooled at a rate of 0.2C per millennium until about 1900. Since then, it has warmed by about 1.2C. The research shows a long, slow cooling followed by an abrupt warming Much debate on climate change has centred on the Mediaeval Warm Period, or Mediaeval Climate Anomaly - a period about 1,000 years ago when, historical records suggest, Vikings colonised Greenland and may have grown grapes in Newfoundland. The new analysis shows that temperatures were indeed warmer in this region 1,000 years ago than they were 100 years ago - but not as warm as they are now, or 1,000 years previously. "It shows that the Mediaeval Warm Period is real, and is... an exception from the general trend of cooling," commented Eystein Jansen from Bergen University in Norway, who was not involved in the research. "It also shows there's lots of variability on the 100-year timescale, and that's probably more so in the Arctic than elsewhere." Professor Jansen was a co-ordinating lead author on the palaeoclimate (ancient climate) chapter of the last Intergovernmental Panel on Climate Change (IPCC) assessment. Arctic wobbles The root cause of the slow cooling was the orbital "wobble" that slowly varies, over thousands of years, the month in which the Earth approaches closest to the Sun. Arctic ice shows winter thinning This wobble slowly decreased the total amount of solar energy arriving in the Arctic region in summertime, and the temperature responded - until greenhouse warming took over. "The 20th Century is the first century for which how much energy we're getting from the Sun is no longer the most important thing governing the temperature of the Arctic," said another of the study team, Nicholas McKay from the University of Arizona. The recent warming of the Arctic has manifested itself most clearly in the drastic shrinkage in summer sea-ice extent, with the smallest area in the satellite era documented in 2007. As the Science study emerged, UN Secretary-General Ban Ki-moon was telling the World Climate Conference in Geneva that many of the "more distant scenarios" forecast by climate scientists were "happening now". Earlier this week, Mr Ban visited the Arctic in an attempt to gain first-hand experience of how the region is changing. "Scientists have been accused for years of scaremongering. But the real scaremongers are those who say we cannot afford climate action," he said in his Geneva speech, calling for world leaders to make bigger pledges of action in the run-up to December's UN climate summit in Copenhagen. [email protected] Bookmark with: Delicious Digg reddit Facebook StumbleUpon What are these? E-mail this to a friend Printable version
package rpc import ( "context" ) // GetFeeRateGovernor returns the fee rate governor information from the root bank. func (cl *Client) GetFeeRateGovernor(ctx context.Context) (out *GetFeeRateGovernorResult, err error) { err = cl.rpcClient.CallForInto(ctx, &out, "getFeeRateGovernor", nil) return } type GetFeeRateGovernorResult struct { RPCContext Value FeeRateGovernorResult `json:"value"` } type FeeRateGovernorResult struct { FeeRateGovernor FeeRateGovernor `json:"feeRateGovernor"` } type FeeRateGovernor struct { // Percentage of fees collected to be destroyed. BurnPercent uint8 `json:"burnPercent"` // Largest value lamportsPerSignature can attain for the next slot. MaxLamportsPerSignature uint64 `json:"maxLamportsPerSignature"` // Smallest value lamportsPerSignature can attain for the next slot. MinLamportsPerSignature uint64 `json:"minLamportsPerSignature"` // Desired fee rate for the cluster. TargetLamportsPerSignature uint64 `json:"targetLamportsPerSignature"` // Desired signature rate for the cluster. TargetSignaturesPerSlot uint64 `json:"targetSignaturesPerSlot"` }
A new report commissioned by the Swiss Jewish Community Federation (SIG) and the Foundation against Racism and Anti-Semitism (GRA) found that anti-Semitic attitudes persist in Switzerland.According to the study, anti-Semitic attitudes are encountered in 10 to 25 percent of the country's German-speaking population. In 2016, several serious anti-Semitic incidents were recorded from the spectrum of the extreme-right: In October 2016, in Toggenburg, a concert was held featuring some notorious neo-Nazi bands. According to media reports, around 5,000 people attended the event. A number of the bands appearing there included songs with anti-Semitic content in their repertoire, and photos of the event show concertgoers giving the Hitler salute. In October 2016, members of a neo-Nazi band made death threats against SIG President Herbert Winter and members of the SIG management team. They also warned of bomb attacks at Jewish institutions in Zurich. In July the SIG received an e-mail containing threats which held Jews as responsible for all the world’s misfortunes. The unknown sender demanded a large amount of money from the SIG, and failing that threatened that “Jewish people in Switzerland will bear the consequences”. Two incidents of physical violence occurred in Zurich: At a soccer ground, two Jewish youngsters asked other footballers if they could join in. The answer was: “You’re Jews. There’s nothing here for Jews." The two Jewish youngsters were then spat at. As they left, they were followed by jeers of “Heil Hitler”. Again in Zurich, in April 2016, a Jewish boy became the victim of anti-Semitic diatribes in the street and was spat at as he was riding on his bicycle past three young people. In the report, its author - the historian Daniel Rickenbacher - looks at the 'cross-front' phenomenon in Switzerland. Cross-front is the term coined to describe associations which are formed between groups who are at opposite ends of the political spectrum. Rickenbacher shows that in Switzerland informal interaction exists between groups on the far-left, the extreme-right, and radical Islamists. According to Rickenbacher, the embedding of anti-Semitism in a range of different political spectra provides the basis for groups who would otherwise be deemed to be incompatible with each other to find a common enemy: the Jews. The report can be accessed at www.antisemitismus.ch.
// detect user can update the mirror func detectCanUpdateMirror(ctx context.Context, m *repo_model.Mirror, gitArgs []string) (bool, error) { repoPath := m.Repo.RepoPath() newRepoPath := fmt.Sprintf("%s_update", repoPath) err := util.CopyDir(repoPath, newRepoPath) defer func() { errDelete := util.RemoveAll(newRepoPath) if errDelete != nil { log.Error("DeleteRepositoryTempDirectoryError: %v", errDelete) } }() if err != nil { log.Error("GetMirrorCanUpdate [repo: %-v]: CopyDirectory Error %v", m.Repo, err) return false, err } syncStatus, err := syncRepoMirror(ctx, m, gitArgs, newRepoPath) if err != nil { return false, err } if !syncStatus { return false, nil } gitCommitCountArgs := []string{"rev-list", "HEAD", "--count"} stdoutNewRepoCommitCount, _, err := getGitCommandStdoutStderr(ctx, m, gitCommitCountArgs, newRepoPath) if err != nil { return false, err } stdoutNewRepoCommitCount = strings.TrimSpace(stdoutNewRepoCommitCount) stdoutRepoCommitCount, _, err := getGitCommandStdoutStderr(ctx, m, gitCommitCountArgs, repoPath) if err != nil { return false, err } stdoutRepoCommitCount = strings.TrimSpace(stdoutRepoCommitCount) var repoCommitCount, newRepoCommitCount int64 if i, err := strconv.ParseInt(stdoutRepoCommitCount, 10, 64); err == nil { repoCommitCount = i } else { return false, err } if i, err := strconv.ParseInt(stdoutNewRepoCommitCount, 10, 64); err == nil { newRepoCommitCount = i } else { return false, err } if repoCommitCount > newRepoCommitCount { return false, nil } else if repoCommitCount == newRepoCommitCount { return true, nil } else { skipcout := newRepoCommitCount - repoCommitCount gitNewRepoLastCommitIDArgs := []string{"log", "-1", fmt.Sprintf("--skip=%d", skipcout), "--format='%H'"} stdoutNewRepoCommitID, _, err := getGitCommandStdoutStderr(ctx, m, gitNewRepoLastCommitIDArgs, newRepoPath) if err != nil { return false, err } gitRepoLastCommitIDArgs := []string{"log", "--format='%H'", "-n", "1"} stdoutRepoCommitID, _, err := getGitCommandStdoutStderr(ctx, m, gitRepoLastCommitIDArgs, repoPath) if err != nil { return false, err } if stdoutNewRepoCommitID != stdoutRepoCommitID { return false, fmt.Errorf("Old repo commit id: %s not match new repo id: %s", stdoutRepoCommitID, stdoutNewRepoCommitID) } } return true, nil }
<gh_stars>1-10 package dynamic import ( "github.com/pkg/errors" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/discovery" "k8s.io/client-go/dynamic" "k8s.io/client-go/rest" "k8s.io/client-go/restmapper" ) // A scoped down meta.MetadataAccessor type MetadataAccessor interface { Namespace(runtime.Object) (string, error) Name(runtime.Object) (string, error) ResourceVersion(runtime.Object) (string, error) } // A scoped down meta.RESTMapper type mapper interface { RESTMapping(gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error) } // APIHelper wraps the client-go dynamic client and exposes a simple interface. type APIHelper struct { Client dynamic.Interface Mapper mapper Accessor MetadataAccessor } // NewAPIHelperFromRESTConfig creates a new APIHelper with default objects // from client-go. func NewAPIHelperFromRESTConfig(cfg *rest.Config) (*APIHelper, error) { dynClient, err := dynamic.NewForConfig(cfg) if err != nil { return nil, errors.Wrap(err, "could not create dynamic client") } discover, err := discovery.NewDiscoveryClientForConfig(cfg) if err != nil { return nil, errors.Wrap(err, "could not create discovery client") } groupResources, err := restmapper.GetAPIGroupResources(discover) if err != nil { return nil, errors.Wrap(err, "could not get api group resources") } mapper := restmapper.NewDiscoveryRESTMapper(groupResources) return NewAPIHelper(dynClient, mapper, meta.NewAccessor()) } // NewAPIHelper returns an APIHelper with the internals instantiated. func NewAPIHelper(dyn dynamic.Interface, mapper mapper, accessor MetadataAccessor) (*APIHelper, error) { return &APIHelper{ Client: dyn, Mapper: mapper, Accessor: accessor, }, nil } // CreateObject attempts to create any kubernetes object. func (a *APIHelper) CreateObject(obj *unstructured.Unstructured) (*unstructured.Unstructured, error) { restMapping, err := a.Mapper.RESTMapping(obj.GroupVersionKind().GroupKind(), obj.GroupVersionKind().Version) if err != nil { return nil, errors.Wrap(err, "could not get restMapping") } name, err := a.Accessor.Name(obj) if err != nil { return nil, errors.Wrap(err, "could not get name for object") } namespace, err := a.Accessor.Namespace(obj) if err != nil { return nil, errors.Wrapf(err, "couldn't get namespace for object %s", name) } rsc := a.Client.Resource(restMapping.Resource) if rsc == nil { return nil, errors.New("failed to get a resource interface") } ri := rsc.Namespace(namespace) return ri.Create(obj) } // Name returns the name of the kubernetes object. func (a *APIHelper) Name(obj *unstructured.Unstructured) (string, error) { return a.Accessor.Name(obj) } // Namespace returns the namespace of the kubernetes object. func (a *APIHelper) Namespace(obj *unstructured.Unstructured) (string, error) { return a.Accessor.Namespace(obj) } // ResourceVersion returns the resource version of a kubernetes object. func (a *APIHelper) ResourceVersion(obj *unstructured.Unstructured) (string, error) { restMapping, err := a.Mapper.RESTMapping(obj.GroupVersionKind().GroupKind(), obj.GroupVersionKind().Version) if err != nil { return "", errors.Wrap(err, "could not get restMapping") } return restMapping.Resource.GroupResource().Resource, nil }
/* Routine to initialize the style cache */ Boolean StyleInit(void) { ushort *pistd; int i; hStyles = MemAllocLMem(LMEM_TYPE_GENERAL, sizeof(StyleHeader)); if (hStyles == NullHandle) { SetError(TE_OUT_OF_MEMORY); return FALSE; } MemLock(hStyles); cStyleIndexArray = LMemAlloc(hStyles, sizeof(ushort) * STYLE_CACHE_EXPANDED_MAX); pistd = LMemDerefHandles(hStyles, cStyleIndexArray); for (i = 0; i < STYLE_CACHE_EXPANDED_MAX; i++, pistd++) *pistd = CA_NULL_ELEMENT; cStyleArray = ChunkArrayCreate(hStyles, 0, 0, 0); MemUnlock(hStyles); return TRUE; }
/* overwrites an existing value . Adds a new entry if not. * returns * 1 OK * 0 Memory problems */ int pair_set(pair p, const char* name, const char* value) { size_t i, cbAvailable, cbRequired; if(!pair_find(p, name, &i)) return pair_add(p, name, value); cbAvailable = strlen(p->element[i].value) + 1; cbRequired = strlen(value) + 1; if(cbAvailable < cbRequired) { char* s = realloc(p->element[i].value, cbRequired); if(NULL == s) return 0; p->element[i].value = s; } strcpy(p->element[i].value, value); return 1; }
<reponame>JeffyLu/gormqy package gormqy import ( "strings" ) type Query struct { exprs []string vals []interface{} orders []string limit uint64 } func New() *Query { return &Query{} } func (q *Query) Condition() *Condition { return NewCondition(q) } func (q *Query) AndCondition() *Condition { return q.conditionAfter(LogicAnd) } func (q *Query) OrCondition() *Condition { return q.conditionAfter(LogicOr) } func (q *Query) conditionAfter(logic string) *Condition { if len(q.exprs) != 0 { q.exprs = append(q.exprs, logic) } return q.Condition() } func (q *Query) Where() (expr string, vals []interface{}) { if len(q.exprs) == 0 { return "", nil } return strings.Join(q.exprs, " "), q.vals } func (q *Query) ToPageQuery(page uint64, size uint64) *PageQuery { if page == 0 { page = 1 } if size == 0 { size = 10 } return &PageQuery{ Query: q, page: page, size: size, offset: (page - 1) * size, } } type PageQuery struct { *Query page uint64 size uint64 offset uint64 } func (pq *PageQuery) Page() uint64 { return pq.page } func (pq *PageQuery) Size() uint64 { return pq.size } func (pq *PageQuery) Offset() uint64 { return pq.offset }
// A has enough buffer for B void merge(int A[], int n, int B[], int m) { int x = n - 1; int y = m - 1; for (int i = m + n - 1; i >= 0 && y >= 0; --i) { if (A[x] > B[y]) A[i] = A[x--]; else A[i] = B[y--]; } }
package rule import ( "strings" ) // variable encodes a variable for interpolation, eg. ${foo.bar.baz}, or a // segment of one, e.g. ${foo.bar} of ${foo.bar.baz} type variable struct { segment string // e.g. "bar" from ${foo.bar.baz} segmentName string // e.g. "foo.bar" from ${foo.bar.baz} fullName string // e.g. "foo.bar.baz" from ${foo.bar.baz} } // VariableResolver resolves a variable (a string of form "${foo.bar.baz}"), and returns // a list of values type VariableResolver interface { Resolve(varString string) ([]string, error) } // VariablePinner is a variable resolver that can pin variables to specific values type VariablePinner interface { VariableResolver Pin(variable, value string) VariablePinner // return a VariablePinner that pins a variable to the given value } type passThroughResolver struct{} func (passThroughResolver) Resolve(varString string) ([]string, error) { return []string{varString}, nil } // IsVariable determines if a string is a variable (e.g. of the form '${foo.bar.baz}') func IsVariable(text string) bool { return strings.HasPrefix(text, "${") && strings.HasSuffix(text, "}") } // toVariable creates a Variable from a string like '${foo.bar.baz}' (dollar sign and braces required) func toVariable(text string) (variable, bool) { if !IsVariable(text) { return variable{}, false } return variable{ fullName: strings.TrimRight(strings.TrimLeft(text, "${"), "}"), }, true } // shift is used for producing a segment of a variable, e.g. Shift() of ${foo.bar.baz}, // is ${foo}. Shift() of that ${foo} is ${foo.bar}, and Shift() of ${foo.bar} is ${foo.bar.baz} func (v variable) shift() (variable, bool) { remaining := strings.TrimLeft(strings.TrimPrefix(v.fullName, v.segmentName), ".") // no more variable segments if remaining == "" { return v, false } shifted := variable{ fullName: v.fullName, } if v.segment == "" { shifted.segment = strings.Split(v.fullName, ".")[0] shifted.segmentName = shifted.segment } else { parts := strings.Split(remaining, ".") shifted.segment = parts[0] shifted.segmentName = strings.Join([]string{v.segmentName, parts[0]}, ".") } return shifted, true } func (v variable) prev() variable { prev := variable{ fullName: v.fullName, } if v.segment == "" { return prev } prev.segmentName = strings.Trim(strings.TrimSuffix(v.segmentName, v.segment), ".") segments := strings.Split(prev.segmentName, ".") prev.segment = segments[len(segments)-1] return prev }