content
stringlengths
10
4.9M
#include "util.h" int main() { int shmid = shmget(SHM_KEY, SHM_SIZE, SHM_R | SHM_W | IPC_CREAT); if (shmid == -1) { error("shmid"); return 1; } int semid = semget(SEM_KEY, 0, IPC_CREAT | 0600); if (semid == -1) { error("semget"); return 1; } auto shmp = shmat(shmid, nullptr, 0); if (shmp == reinterpret_cast<void*>(-1)) { error("shmat"); return 1; } struct Msg *msg = static_cast<struct Msg*>(shmp); while (msg->num < 10) { if (sem_p2(semid) == -1) { error("sem_p1"); return 1; } std::printf("[recvmsg] %s\n", msg->buf); if (sem_v1(semid) == -1) { error("sem_v2"); return 1; } sleep(1); } if (shmdt(shmp) == -1) { error("shmdt"); return 1; } if (shmctl(shmid, IPC_RMID, nullptr) == -1) { error("shmctl"); return 1; } if (semctl(semid, SEM_XYZ, IPC_RMID, nullptr) == -1) { error("semctl"); return 1; } return 0; }
/** * Implementation of diagnostic mbean. */ public class DiagnosticDumpMBeanImpl extends StandardMBean implements DiagnosticDumpMBean { /** * Dump providers. */ private BundleContext bundleContext; private SimpleDateFormat dumpFormat = new SimpleDateFormat("yyyy-MM-dd_HHmmss"); private final static Logger LOGGER = LoggerFactory.getLogger(DiagnosticDumpMBeanImpl.class); /** * Creates new diagnostic mbean. * * @throws NotCompliantMBeanException */ public DiagnosticDumpMBeanImpl() throws NotCompliantMBeanException { super(DiagnosticDumpMBean.class); } /** * Creates dump witch given name * * @param name Name of the dump. */ public void createDump(String name) { createDump(false, name); } /** * {@inheritDoc} */ public void createDump(boolean directory, String name) { if (name == null || name.trim().length() == 0) { name = dumpFormat.format(new Date()); if (!directory) { name += ".zip"; } } File target = new File(name); DumpDestination destination; if (directory) { destination = Dump.directory(target); } else { destination = Dump.zip(target); } Dump.dump(bundleContext, destination); LOGGER.info("Created dump " + destination.toString()); } /** * Sets the bundle context */ public void setBundleContext(BundleContext bundleContext) { this.bundleContext = bundleContext; } }
Weeks before the release of a scathing report into military sexual misconduct, Canada's top general issued orders for the military to plan to ignore key recommendations, including the creation of an independent centre to take complaints and provide support and expertise. CBC News has obtained orders written by Chief of the Defence Staff Gen. Tom Lawson and circulated for "Action" to 21 top generals and military managers on Feb. 25. The orders lay out the first steps of the military's response to the report, declaring, "Sexual misconduct and harassment constitute abhorrent behaviours that have no place in the CAF." The orders, called an initiating directive, show that in the case of at least three recommendations, military brass were told to plan to effectively ignore the advice of the external reviewer, former Supreme Court justice Marie Deschamps. Her report found the Canadian Forces possessed a misogynistic and sexualized culture in which harassment and abuse are overlooked, under-reported and poorly understood. Deschamps made 10 recommendations for improvement. Among those was a plan to create an agency independent of the military chain of command to act as a centre of accountability for advice and questions about sexual misconduct, including complaints and reports. Deschamps warned that independence was essential. But Lawson's orders, which were written two months before Deschamps's report was made public but after a draft copy had been delivered to the chief of the defence staff, suggest the idea of independence had already been scrubbed. "The current sexual misconduct investigation and justice system authorities will remain unchanged," Lawson's orders say under the heading of "Assumptions." That assumption would also rule out other changes, apparently rejecting out of hand Deschamps's recommendation to allow victims to report to that independent centre or have civilian police handle an entire investigation, if the victim chooses. It would force victims to rely on the military chain of command, and the military police and justice system, all of which, Deschamps suggested, had failed and lost the trust of women. Centre's independence The general appointed by Lawson to lead the military's response team, Maj.-Gen. Christine Whitecross, said her new unit would be the "genesis" of the centre Deschamps recommended and would also go abroad to study international best practices to determine how best to arrange itself. Both Whitecross and Lawson told reporters on April 30 an independent centre would be one of the permanent options studied. Maj.-Gen. Chris Whitecross, commander of the strategic response team on sexual misconduct, says the military accepted the recommendation of an independent organization for victims in principle because the military needs to learn more about its options. (Canadian Press) But the directive suggests Whitecross's team should prepare itself to, "on order, transition to a permanent establishment in [National Defence headquarters...] reporting to the CDS." Finally, the chief of defence staff's orders say the definition of sexual harassment will not change, despite Deschamps's recommendation the Canadian Forces should "develop a simple, broad definition of sexual harassment that effectively captures all dimensions of the member's relationship with the CAF." In that case — in fact, in all three cases — the military said it agreed in principle with Deschamps's recommendation and would "review many of its definitions that relate to inappropriate sexual behaviour." But the orders suggest, whether any review is undertaken, the definition will remain the same: "The definition of harassment as developed by Treasury Board ... will remain in effect." Orders limit response: Liberal MP Liberal defence critic Joyce Murray said the orders amount to restrictions on Whitecross's ability to effectively respond to the challenge of military sexual misconduct. "Yes, they are clearly limitations. And they're limitations on a framework that is proposed by Madame Deschamps to actually address this culture, this hostile culture in the Canadian Armed Forces." Murray said the existence of the orders help explain why Lawson and Whitecross appeared to disagree with Deschamps at that April 30 news conference. Deschamps told reporters she felt whatever a Canadian military centre on sexual misconduct ended up looking like, "I thought it had to be independent and it was an essential element." Lawson said that recommendation was "unique" and was one that "anyone in the chain of command would at first be concerned with." Murray said it's up to the Conservative government to settle that dispute and clarify the chief of defence staff's orders. "Let's hear from the minister what their plan is. Are they accepting the recommendation?" Murray asked. "The minister was nowhere to be seen when this report came out. And has never ... made a statement about his intention to fix this problem, to accept this recommendation." The office of Defence Minister Jason Kenney has refused to comment Tuesday on the orders. In Winnipeg last week, where she was travelling to meet with soldiers, Whitecross said she was not familiar with the restrictions the orders appear to impose on her. "I have no idea where they would have got that," she said. "My marching orders are very clear. My mandate is to get a team together, to get an action plan to address all 10 recommendations." The military refused a formal request for an interview on the orders, but it did provide a written statement. "Maj.-Gen. Chris Whitecross has not received any formal or informal direction from the chief of defence staff that in any way constrains [her] capacity to develop implementation approaches to the 10 recommendations presented in Mme Deschamps' report," it said. "Maj.-Gen. Whitecross feels fully empowered to develop optimal approaches." Those same February orders issued by Lawson also established Whitecross as commander of a Strategic Review Team on Sexual Misconduct and in charge of the military's response to Deschamps's report. CBC News showed the orders to three different retired high-ranking generals, who each confirmed the assumptions set out in the directive could be seen as limitations or constraints on Whitecross's ability to act. The office of the chief of the defence staff refused an interview request on the topic, but Lawson's press officer, Lt.-Cmdr. Jordan Holder, said the general had not ordered any assumptions that could not be changed. Any changes would require a supplementary initiating directive. Staff for Whitecross's team concede no such supplementary order has been issued. "There has been no change. [Whitecross's] mission, mandate and approach are directed and informed by the CDS's initiating directive," Capt. Jean-François Lambert said in an email.
<filename>run.py #!/usr/bin/env python3.6 import random from user import User def create_user(fName, lName, password) : """ to create a new user """ new_user = User(fName, lName, password) return new_user def save_users(user) : """function to save users """ user.save_user() def del_user(user) : """ function to delete user """ contact.delete_user() def find_contact(lName) : """ function that finds user by lastname and returns the contact """ return User.find_by_lastName(lName) def check_existing_user(lName) : """ function to check if user exist with that lastname and return a boolean """ return User.user_exist(lName) def display_users(): """ function that returns all saved users """ return User.display_user() def main() : print("Hello welcome to your users list. What is your first name?") first_Name = input() print("Enter second name") last_Name = input() print(f"Hello {first_Name} {last_Name}. what would you like to do?") print('\n') while True : print("please use this short codes : s - signUp, gg - generate password, l - login, p - save password, fu - find user") short_code = input().lower() if short_code == "s": print("First Name ....") fName = input() print("Second Name ....") lName = input() print("Password ....") password = input() save_users(create_user(fName,lName,password)) # create and save new account print('\n') print(f"New account {fName} {lName} is created") print('\n') elif short_code == "gg" : print("Enter First Name....") fName = input() print("Enter Last name......") lName = input() print("password ....") username = random.randint(000000,999999) # generated a random password using the randint method password = input(username) save_users(create_user(fName,lName,password)) # create and save generated new password print('\n') print(f" New generated account and password {fName} {lName} {password}") elif short_code == "l" : print("First Name ....") fName = input() print("Second Name ....") lName = input() print("Password ....") password = input() if password == '<PASSWORD>' : print(f"{fName} {lName} has login") print('\n') else : print("you entered the wrong passward") save_users(create_user(fName,lName,password)) # create and save login print('\n') elif short_code == "p" : print("First Name ....") fName = input() print("Second Name ....") lName = input() print("Password ....") password = input() save_users(create_user(fName,lName,password))# save password print('\n') print(f"{fName} {lName} has been saved") print('\n') elif short_code == "fu": print("Enter the user you want to search ") search_user = input() if check_existing_user(search_user): search_user = find_contact(search_user) print(f"{search_user.firstName} {search_user.lastName}") print('-' * 20) print(f"First Name.......{search_user.lastName}") print(f"password.......{search_user.user_password}") else: print("That user does not exist") else : print("i do not understand what you are saying") if __name__ == '__main__' : main()
def main(): N = int(input()) health = set(map(int, input().split())) min_num = min(health) for i in health: while i % min_num != 0: temporary_min_num = min_num min_num = i % min_num i = temporary_min_num print(min_num) main()
// Prepend adds an item to the beginning of the collection. func (c NumberArrayCollection) Prepend(values ...interface{}) Collection { var d NumberArrayCollection var n = make([]decimal.Decimal, len(c.value)) copy(n, c.value) d.value = append([]decimal.Decimal{newDecimalFromInterface(values[0])}, n...) d.length = len(d.value) return d }
import torch import os import argparse import json import pytorch_lightning as pl from fengshen.models.model_utils import add_module_args from fengshen.data.task_dataloader.task_datasets import AbstractCollator from fengshen.data.universal_datamodule import UniversalDataModule from fengshen.utils.universal_checkpoint import UniversalCheckpoint from fengshen.utils.utils import chinese_char_tokenize from torchmetrics.text.rouge import ROUGEScore from pytorch_lightning import Trainer, loggers from pytorch_lightning.callbacks import LearningRateMonitor from transformers import AutoTokenizer, AutoModelForSeq2SeqLM import sys sys.path.append('../../../') # os.environ["CUDA_VISIBLE_DEVICES"] = '3,4' class FinetuneSummary(pl.LightningModule): @staticmethod def add_model_specific_args(parent_args): parser = parent_args.add_argument_group('BaseModel') parser.add_argument('--rouge_keys', default='rougeL,rouge1,rouge2', type=str) return parent_args def __init__(self, args, tokenizer=None): super().__init__() self.save_hyperparameters(args) self.model = AutoModelForSeq2SeqLM.from_pretrained( args.pretrained_model_path) self.tokenizer = tokenizer assert self.tokenizer, "tokenizer is None!" self.rouge_keys = tuple(args.rouge_keys.split(',')) self.rouge_metric = ROUGEScore(rouge_keys=self.rouge_keys, normalizer=lambda x: x) def setup(self, stage) -> None: if stage == 'fit': train_loader = self.trainer._data_connector._train_dataloader_source.dataloader() # Calculate total steps tb_size = self.hparams.train_batchsize * max(1, self.trainer.gpus) ab_size = self.trainer.accumulate_grad_batches * \ float(self.trainer.max_epochs) self.total_steps = ( len(train_loader.dataset) // tb_size) // ab_size print('total_steps is :', self.total_steps) def training_step(self, batch, batch_idx): output = self.model(input_ids=batch['input_ids'], attention_mask=batch['attention_mask'], labels=batch['labels']) self.log('train_loss', output.loss, sync_dist=True) return output.loss def on_validation_start(self) -> None: # rm file at validation start prefix, ext = os.path.splitext(self.hparams.output_save_path) file_path_rank = '{}_{}{}'.format( prefix, self.trainer._accelerator_connector.cluster_environment.global_rank(), ext) if os.path.exists(file_path_rank): print('rm {}'.format(file_path_rank)) os.remove(file_path_rank) def validation_step(self, batch, batch_idx): output = self.model(input_ids=batch['input_ids'], attention_mask=batch['attention_mask'], labels=batch['labels']) generated_ids = self.model.generate( input_ids=batch['input_ids'], attention_mask=batch['attention_mask'], max_length=self.hparams.max_dec_length ) preds = self.tokenizer.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True) labels = torch.where(batch['labels'] != -100, batch['labels'], self.tokenizer.pad_token_id) labels = self.tokenizer.batch_decode( labels, skip_special_tokens=True, clean_up_tokenization_spaces=True) # save preds for every rank prefix, ext = os.path.splitext(self.hparams.output_save_path) file_path_rank = '{}_{}{}'.format( prefix, self.trainer._accelerator_connector.cluster_environment.global_rank(), ext) self.save_prediction_to_file(preds=preds, texts=batch['text'], summarys=batch['summary'], file_path=file_path_rank) # you need to split chinese char with space for rouge metric new_preds = [chinese_char_tokenize(p) for p in preds] new_labels = [chinese_char_tokenize(label) for label in labels] # update metric self.rouge_metric.update(preds=new_preds, target=new_labels) self.log('val_loss', output.loss, sync_dist=True) def validation_epoch_end(self, outputs): # compute metric for all process rouge_dict = self.rouge_metric.compute() # reset the metric after once validation self.rouge_metric.reset() for k, v in rouge_dict.items(): self.log('val_{}'.format(k), v, sync_dist=True) if self.trainer._accelerator_connector.cluster_environment.global_rank() == 0: print('rouge:\n', rouge_dict) def on_save_checkpoint(self, checkpoint) -> None: if self.trainer._accelerator_connector.cluster_environment.global_rank() == 0: self.model.save_pretrained(os.path.join( self.trainer.checkpoint_callback.dirpath, 'hf_pretrained_epoch{}_step{}'.format(checkpoint['epoch'], checkpoint['global_step']))) def save_prediction_to_file(self, preds, texts, summarys, file_path): with open(file_path, 'a', encoding='utf-8') as f: for idx, pred in enumerate(preds): text = texts[idx] summary = summarys[idx] tmp_result = dict() tmp_result['pred'] = pred tmp_result['label'] = summary tmp_result['text'] = text json_data = json.dumps(tmp_result, ensure_ascii=False) f.write(json_data + '\n') def predict_step(self, batch, batch_idx): # print(batch) texts = batch['text'] # output summary and metrics generated_ids = self.model.generate( input_ids=batch['input_ids'], attention_mask=batch['attention_mask'], max_length=self.hparams.max_dec_length ) preds = self.tokenizer.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True) labels = self.tokenizer.batch_decode( batch['labels'], skip_special_tokens=True, clean_up_tokenization_spaces=True) print(batch_idx, len(preds), len(labels)) self.save_prediction_to_file(preds, texts, labels) def configure_optimizers(self): from fengshen.models.model_utils import configure_optimizers return configure_optimizers(self) def main(): total_parser = argparse.ArgumentParser("Summary Task") total_parser.add_argument('--do_eval_only', action='store_true', default=False) total_parser.add_argument('--pretrained_model_path', default='google/mt5-small', type=str) total_parser.add_argument('--output_save_path', default='./predict.json', type=str) total_parser.add_argument('--self_tokenizer', action='store_true', default=False) total_parser.add_argument('--max_enc_length', default=1024, type=int) total_parser.add_argument('--max_dec_length', default=256, type=int) total_parser.add_argument('--prompt', default='summarize:', type=str) # * Args for data preprocessing # from fengshen.data.task_dataloader.task_datasets import LCSTSDataModel total_parser = UniversalDataModule.add_data_specific_args(total_parser) # * Args for training total_parser = add_module_args(total_parser) total_parser = Trainer.add_argparse_args(total_parser) total_parser = UniversalCheckpoint.add_argparse_args(total_parser) total_parser = FinetuneSummary.add_model_specific_args(total_parser) # * Args for base model args = total_parser.parse_args() if args.self_tokenizer: from fengshen.examples.pegasus.tokenizers_pegasus import PegasusTokenizer tokenizer = PegasusTokenizer.from_pretrained(args.pretrained_model_path) else: tokenizer = AutoTokenizer.from_pretrained(args.pretrained_model_path, use_fast=False) collator = AbstractCollator(tokenizer, args.max_enc_length, args.max_dec_length, args.prompt) data_model = UniversalDataModule(tokenizer=tokenizer, args=args, collate_fn=collator) model = FinetuneSummary(args, tokenizer) if not args.do_eval_only: lr_monitor = LearningRateMonitor(logging_interval='step') logger = loggers.TensorBoardLogger(save_dir=os.path.join( args.default_root_dir, 'log/')) checkpoint_callback = UniversalCheckpoint(args) trainer = Trainer.from_argparse_args(args, logger=logger, callbacks=[lr_monitor, checkpoint_callback] ) trainer.fit(model, data_model) else: trainer = Trainer.from_argparse_args(args) # trainer.predict(model, data_model) trainer.validate(model, data_model) if __name__ == '__main__': main()
Efficient logic architectures for CMOL nanoelectronic circuits CMOS molecular (CMOL) circuits promise great opportunities for future hybrid nanoscale IC implementation. Two new CMOL building blocks using transmission gates have been introduced to obtain efficient combinational and sequential logic for CMOL designs. Compared with the existing CMOL circuits, the proposed CMOL designs based on these blocks can achieve more than 30% improvement in speed and up to 80% improvement in density and power consumption while providing similar fault tolerance capabilities. This work significantly advances the applications of CMOL to actual electronic circuits and systems
Chinese President Xi Jinping during a call with President Trump reportedly urged restraint in dealing with North Korea. Chinese state media reported that Xi said China "strongly opposes" anything that would go against United Nations Security Council resolutions, according to USA Today. Xi also told Trump that China wishes "the parties concerned will exercise restraint and avoid actions that aggravate tensions on the Peninsula," the state-run Xinhua news agency reported. ADVERTISEMENT “Xi noted that if the parties shoulder their due responsibilities and meet each other halfway, they can solve the nuclear issue of the Democratic People's Republic of Korea and denuclearize the Korean Peninsula,” Xinhua added. Last week, Trump put new pressure on China to rein in North Korea. "China is very much the economic lifeline to North Korea so, while nothing is easy, if they want to solve the North Korean problem, they will," the president tweeted last week. Vice President Pence last week said the U.S. would have an "overwhelming and effective" response should North Korea test its resolve. He warned North Korea not to test Trump or the U.S. military and said the "era of strategic patience is over." The call between Trump and the Chinese president comes amid heightened tensions between the U.S. and North Korea, with both sides floating the possibility of military action against one another.
<gh_stars>10-100 // Libs import React from 'react'; // App import {bemBlock} from 'common/utils/bem'; // Module import './NotificationLink.less'; type LinkProps = React.AnchorHTMLAttributes<HTMLAnchorElement> const block = bemBlock('neptune-link'); export const NotificationLink:React.FC<LinkProps> = (props) => { return ( <a className={block()} {...props} /> ); };
def _bitflips_designated(self, value, fi_indices): for item in fi_indices: val = value[item] bits = str(value.dtype)[-2:] if str(value.dtype)[-2].isdigit() else str(value.dtype)[-1] if 'uint' in str(val.dtype): pos = int(bits) - 1 else: pos = int(bits) - 2 val_new = self._bitflip(val, [pos]) value[item] = val_new return value
Effects of the Fuel Injection Parameters on the Performance and Emissions Formation in a Large-Bore Marine Diesel Engine Reductions in the emissions of nitrogen oxides (NO x ) and soot from marine diesel engines can be supported by employing multiple-injection strategies, similar to those used in automotive engines. In the present computational study, the possibility of improving the operation of a large two-stroke marine diesel engine at full load by implementing an appropriate pilot injection is explored. A KIVA-3-based computational fluid dynamics code is used, coupled with an evolutionary algorithm. Multi-objective engine optimization is performed by parameterizing the fuel injection profiles in terms of four design variables, which fully define the pilot and main injections. Two objective functions are defined: the final NO x concentration and the specific fuel oil consumption (SFOC), both normalized by the corresponding values of a reference case of continuous injection. Three problem set-ups have been considered: first, an unconstrained problem; second, a problem constrained by the maximum cylinder pressure; third, a problem constrained by both the maximum pressure and the minimum work output per engine cycle. It is found that, in both the unconstrained and the one-constraint problems, the optimum solutions are characterized by substantial improvements in the NO x emissions (of the order of 15—20 per cent) and the SFOC (of the order of 2 per cent). The improvements are less pronounced when both constraints are imposed. A detailed sensitivity analysis of the effects of each of the design variables is presented.
<gh_stars>1-10 package parameter type RelationshipTypeKind string const ( RelationshipTypeKindParent RelationshipTypeKind = "PARENT" RelationshipTypeKindChild RelationshipTypeKind = "CHILD" RelationshipTypeKindSibling RelationshipTypeKind = "SIBLING" RelationshipTypeKindXName RelationshipTypeKind = "X-NAME" )
// check condition and set state func (f *FSM) doTransit(ctx context.Context, transition *Transition) error { log.Printf("\t[fsm] start condition check for transit(%s)\n", transition.Key) if transition.Condition != nil { if flag, err := transition.Condition(ctx, transition.From.Name); err != nil { log.Printf("\t[fsm] transit(%s) condition check err %s\n", transition.Key, err) return err } else if flag == false { err = errors.New(fmt.Sprintf("[fsm] transit(%s) condition not met", transition.Key)) log.Printf("\t[fsm] transit(%s) condition check err %s\n", transition.Key, err) return err } } else { log.Printf("\t[fsm] skipped condition check for transit(%s) due to condition is nil\n", transition.Key) } f.setState(ctx, transition.To) return nil }
import React, { useState } from 'react'; import { storiesOf } from '@storybook/react'; import { CardOpenClose } from './CardOpenClose'; storiesOf('core/CardOpenClose', module) .addParameters({ component: CardOpenClose }) .add('basic', () => { const [isOpen, setIsOpen] = useState(false); return ( <CardOpenClose header="You should see this!" isOpen={isOpen} toggle={() => setIsOpen(!isOpen)} > {() => ( <iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ?controls=0&autoplay=1" title="YouTube video player" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen ></iframe> )} </CardOpenClose> ); });
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * This is the type of the Future instance users get in an async call: * 1. unwrap AppResponse in appResponseFuture and convert to plain biz result represented by FutureAdapter. * 2. customized behaviors meaningful for RPC, for example, {@link #cancel(boolean)} */ public class FutureAdapter<V> extends CompletableFuture<V> { private CompletableFuture<AppResponse> appResponseFuture; public FutureAdapter(CompletableFuture<AppResponse> future) { this.appResponseFuture = future; future.whenComplete((appResponse, t) -> { if (t != null) { if (t instanceof CompletionException) { t = t.getCause(); } this.completeExceptionally(t); } else { if (appResponse.hasException()) { this.completeExceptionally(appResponse.getException()); } else { this.complete((V) appResponse.getValue()); } } }); } // TODO figure out the meaning of cancel in DefaultFuture. @Override public boolean cancel(boolean mayInterruptIfRunning) { // Invocation invocation = invocationSoftReference.get(); // if (invocation != null) { // invocation.getInvoker().invoke(cancel); // } return appResponseFuture.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return appResponseFuture.isCancelled(); } @Override public boolean isDone() { return super.isDone(); } @Override @SuppressWarnings("unchecked") public V get() throws InterruptedException, ExecutionException { try { return super.get(); } catch (ExecutionException | InterruptedException e) { throw e; } catch (Throwable e) { throw new RpcException(e); } } @Override @SuppressWarnings("unchecked") public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { try { return super.get(timeout, unit); } catch (TimeoutException | ExecutionException | InterruptedException e) { throw e; } catch (Throwable e) { throw new RpcException(e); } } }
Tomorrow, Mozilla will release Firefox 3 Beta 3, the eleventh milestone in the longest development time for a Firefox revision since the initial Firefox 1.0 on 2004. The eight alphas and trio of betas (so far), if anything, are a reflection of the long list of enhancements it (Firefox) and the underlying Gecko rendering engine, are bringing along. Visual Refresh Without a doubt the most visible change introduced in this beta are the theme updates in all platforms. On Windows XP and Vista, a large part of the planned new XP icons has been added to the main toolbar, the Options window, the Download Manager, here and there. Reception hasn’t been warm precisely as was to be expected: just the same happened when Firefox dropped the Qute theme for Winstripe around version 0.9, again with the updates just before 1.0 and yet again when Radiant Core updated Firefox 2.0 icons to its current washed out aspect. I haven’t been a big fan of any Firefox default theme so far and it doesn’t seem Firefox 3’s will be an exception. But we’ll see. There are still theme updates pending, as well as small icons, and Vista icons. The Options window on Windows XP with the new icons. Firefox 3 Beta 3 options On the other hand, Mac OS X users seem to be more satisfied with the landing of Proto, a Safari-like theme introduced along with Beta 2. Linux users also get a very well integrated theme that uses native icons. The back and forward buttons have been combined in a single keyhole-shaped widget featuring a single history menu. So far just Windows XP and Vista feature it but Mac OS X versions are ready and waiting to get in. An option to split the combined icons in the customize toolbar dialog is being considered. We can also expect a revised throbber (the connection activity indicator) coming soon. The Home button has been moved to the Bookmarks toolbar by default (but can be easily moved back) and the splitter that allows to resize the search and location bars when placed next to each other has become invisible. Developers are aiming to deliver better operating system integration in Firefox 3. This will be most notorious for Mac OS X and Linux users who will now get native widgets like text boxes, menus, check boxes, icons, button order and orientation following each OS guidelines. On Linux, Beta 3 adds native file open and print dialogs that provide image thumbnails and more printing options. Mac OS X users get integration with Growl, a popular centralized notification system, while Windows Vista gets native looking menus and new icons that should be added for the next beta. Firefox 3 with native menus The Page Information dialog has been reviewed to become more organized and informative and allows to set all site specific preference from a single location. Places A much announced and expected feature is Places, the integrated history and bookmarks manager interface powered by SQLite, a small open source database engine that provides much more robust querying capabilities. With Places you are able to search your history, tags and bookmarks with a fully fledged search interface. You can select where to search (History, Bookmarks Menu, Bookmarks Toolbar, All Bookmarks or the selected folder), what to search (visited date, web address or title), combine criteria and then save the search as a Smart Bookmark that updates as your personal web grows and changes. Places Library The Library, Places manager, also adds backup and restore UI so it is easier to recover a damaged file or incorrectly deleted bookmark. Tagging is a new Firefox feature tightly related with Places and some of the changes to the location bar: click on an empty star icon in the location bar to save the current page as a bookmark. Click it again and you can specify a certain folder to save the bookmark to and you can add tags which you can later use to perform searches. Tagging You may also notice that the Go button is gone. It only appears when you are entering some text in the location bar and you may actually need to press it. The Location Bar The autocomplete list that appears when you start entering letters in the location bar is no longer restricted to web addresses but also looks into bookmark and history page titles and tags which make it more comprehensive. Suggestions are are shown in two different lines and colors for page titles and addresses, which according to studies on human cognition, makes it easier for us to focus on what we are looking for. So, if the user knows she is entering part of a web address or a page title it will be easier for her to find what she’s looking for. Highlighting the match result also helps to direct the user’s attention. Firefox 3 location bar I believe this feature alone is the best Firefox 3 has to offer, justifies Places large resources investment and will become a landmark in Firefox and web browsers in general development. Once you get used to it, there is no turning back. Tabbed Browsing On tabbed browsing, Firefox will not only warn you when closing several tabs and windows at once but will prompt if you want to save the currently open tab set: a good catch and a good way to introduce this helpful feature to new users. Tabs now scroll smoothly, and, new in Beta 3, you can sort of duplicate tabs when you press Ctrl while dragging a tab. A similar feature allows to drag a tab to another window. It’s not actual duplication or moving though, since in both cases a new navigation occurs and the original tab history is not preserved, but still a helpful addition I hope to see perfected in the next version. Web experience Firefox can save site specific preferences. For example you could allow just some pages to use AJAX, set a specific spell checker language, images, etc. Firefox 3 will remember the zoom level you have applied for a certain site and will zoom automatically the next time you visit it. Net protocols (like irc, news, webcal and mailto) and certain documents handling can be passed to web services. For example, Yahoo Mail or Gmail may become your default application for mailto: links. For this, the previous web feeds page has been extended to the Options window for all content and protocols. Beta 3 distinguishes podcasts and video podcast feeds from regular ones so you can specify a different application for each. Options Application Window Media feeds are displayed with a link to the media file in feed preview mode. Media feed preview By default, web sites can’t move or resize Firefox via JavaScript. A list of authorized web sites can be maintained through Advanced JavaScript Settings in the Content page in Options. JavaScript move, resize exceptions Search engines The search engine manager lets you set and change keywords for search engines. With keywords, if you associate the w keyword with Wikipedia (now a default search engine), you could enter w hawaii in the locationbar and search Wikipedia for Hawaii. Downloads One of the most requested features: downloads can be paused and resumed across sessions, limited only by the server capabilities. Also, on Windows, downloaded files are automatically passed to the installed anti-virus if present and honor Windows Vista parental controls. As seen in previous betas, the Download Manager has received a serious face lift as an easier to track download list. Download manager Beta 3 adds a cool new status bar notification that provides summarized status of current downloads. You can click it to open the Download Manager. Download status Add-ons The Add-ons Manager has been integrated with Mozilla Add-ons, Mozilla’s official extensions and themes repository, providing recommendations, search, rating and add-ons install without leaving Firefox. Together with previously added Plugins page, which allows easy plugin enabling and disabling, it makes it a powerful control panel for Firefox enhancements. Add-ons manager integrated with Mozilla Add-on When installing, updating, disabling or enabling back an add-on, an information bar is displayed to remind a restart is needed for changes to apply, and a restart button. Plus, just installed themes are automatically selected so Firefox uses it after the next restart. Restart Add-ons Among other minor tweaks: FTP and gopher listings get a better styled and functional page where the list can be sorted by name, size and date by clicking the appropriate header, and a warning is displayed when accessing advanced preferences (about:config). about:config warning Security In the security front, Firefox will check visited sites with a list of known malware sites provided by stopbadware.org and served by Google for sites as a way to prevent spyware, rootkits, viruses, dialers and other kinds of malware from even being offered to you. A rewritten password manager now unobtrusively prompts to store an entered password in the information bar and after trying a logon so you know if it is the correct one or not and avoid cluttering autocomplete lists. Remember password infobar Identifying authentic sites and avoiding fake ones is now easier with the addition of the site button which provides details about the identity of the current web site. While the largest part of the web has no verified identity, financial institutions and similar usually do and it makes the site button in the location bar to change color and size so you can know with a glimpse. site button As great as add-ons are they are also a liability and have proved they can become a security vector. Firefox 3 requires add-ons updates to happen over an encrypted connection (to block malicious sites purporting the update site) or the add-on developer to sign it with a digital signature so updates can be verified to be from the same source. This will prevent middle-man attacks where bad guys could fake an update site address to serve malicious software. Under the hood The list of changes for Gecko is not short either and benefit not only Firefox Powered by Mozilla loga but all “powered by Mozilla” products including Thunderbird, Flock, SeaMonkey, Joost, Miro, Songbird and more. Since Alpha 1, Firefox 3 passes the Acid2 test, a popular test of a browser styling standard compatibility. Firefox can use color profiles embedded on pictures and images to better replicate the original environment conditions as light and focus, thanks to new color management. Discontinuous selections of text and images are now possible for better control on what you copy or print from a web page. A biggie: page zoom magnifies the complete page and not only text. This is a much requested feature and a must for Mozilla plans for a Mobile Firefox. Web developers can mark certain web page components such as images and scripts to be available while offline. In practice you could be able to compose emails or write documents though a web service while disconnected from the Internet. Some interesting tricks that will please JavaScript developers: the ability to load local files for local use, cross site AJAX (XMLHttpRequest), native JSON support and most notably, FUEL, a library of Firefox programming interfaces that will ease the development of new extensions and ensure better practices (such as memory management) for common Firefox tasks. A much needed memory cycle collector is now in place and it should take care of freeing memory no longer used by modules that requested it but failed to release it properly. This will improve to optimize Firefox’s memory footprint. Support for editable content, so a user can change portions of a web page marked by the author. The MySpell spell-checking engine has been replaced with Hunspell which does a better job handling complex languages including Asians, Hungarian, Basque, etc. For Gecko 1.9, Mozilla switched to open source Cairo rendering engine for better rendering performance. The change also enables easy PDF printing capabilities but it is only possible through an extension right now though. More beautiful animated images are possible with animated PNGs (APNG): a full 16 million color palette and partial transparency will hopefully sweep GIF images in the future. While APNG was rejected as a standard PNG extension last year, Opera has announced it will support the format in future versions. Proprietary TalkBack, the tool for reporting crashes to Mozilla included with Firefox and Thunderbird, has been replaced with open source Breakpad (formerly Airbag). Socorro, is a server crash reporting tool that will help developers track the most recurring crashes and identify stability and performance bugs. Users can see their submitted crashes entering about:crashes in the location bar. Beta 4 There will be a fourth beta and it is expected quite soon. Probably by Febrary’s end. Release candidates could start by mid-March and hopefully on schedule for a first quarter final release. Not much is left for the next beta: more theme retouches in all platforms, Vista icons, plus more retouches to Places and several other areas, some of them already available in the latest nightlies that followed Beta 3 freeze. According to the latest meeting minutes, the revamped location bar’s autocomplete font size and colors could be reviewed to address some common complaints about it being too obtrusive. Support for multi-word searches is also planned, so for example entering star and then wii, will filter out starbucks while keeping that cool Super Mario Galaxy guide in the results. Add-ons-wise, Firefox 3 support is moving fast and as much as 40% of the top extensions are keeping up with the betas and most likely to be ready by final release. This is at least in part thanks to a very early documentation process and a continuous call for developers. We could see an easy transition for the large number of users that rely on extensions and themes for their best web experience.
#include "pch.h" #include <iostream> #include <map> #include <string> using namespace std; int main() { /* pair<int, string> myPair_1(1, "Test_1"); pair<int, string> myPair_2(2, "Test_2"); pair<int, string> myPair_3(3, "Test_3"); cout << endl << " | " << myPair_1.first << " | " << myPair_1.second << endl; cout << endl << " | " << myPair_2.first << " | " << myPair_2.second << endl; cout << endl << " | " << myPair_3.first << " | " << myPair_3.second << endl; */ map<int, string> myMap; //----------------------------------------------- myMap.insert(make_pair(1, "Test_1")); //or myMap.insert(pair<int, string>(2, "Test_2")); //or myMap.emplace(4, "Test_4"); //----------------------------------------------- myMap.emplace(3, "Test_3"); // auto it = myMap.find(756890); // return end(); cout << endl << " | ---------------------------------------- | " << endl; for (auto it = myMap.begin(); it != myMap.end(); it++) { cout << endl << " | " << it->first << " | " << it->second << endl; } cout << endl << " | ---------------------------------------- | " << endl; auto it = myMap.find(3); if (it != myMap.end()) { cout << endl << " | " << it->first << " | " << it->second << endl; } map<string, int> myMap_2; myMap_2.emplace("Test_1", 1); myMap_2.emplace("Test_2", 2); cout << endl << " | " << myMap_2["Test_2"] << " | " << endl; myMap_2["Test_2"] = 4; cout << endl << " | " << myMap_2["Test_2"] << " | " << endl; myMap_2.erase("Test_2"); // at(); multimap<string, int> myMultiMap; myMultiMap.emplace("Test_1", 1); myMultiMap.emplace("Test_1", 2); myMultiMap.emplace("Test_1", 3); myMultiMap.emplace("Test_1", 4); return 0; }
def OnEpisodeFinishedCallback( self, env: Environment, qfunc: QFunction, episode_idx: int, num_of_episodes: int, episode_reward: float, steps: int, ): pass
#include<bits/stdc++.h> #define inf 0x3f3f3f3f using namespace std; typedef long long LL; const int maxn=2e5+100; LL pos[maxn]; int main() { string ss; LL n,q; cin>>n>>q; cin>>ss; pos[0]=0; for(int i=1;i<=n;i++){ pos[i]=pos[i-1]+ss[i-1]-'a'+1; //cout<<pos[i]<<" "; } for(int i=0;i<q;i++){ LL l,r; cin>>l>>r; LL ans=pos[r]-pos[l-1]; cout<<ans<<endl; } }
At the end of the French presidential debate between frontrunners Emmanuel Macron and Marine Le Pen, the National Front candidate (Le Pen) attacked her rival by saying that she hoped that his offshore Bahamian account would not be revealed. On the next day, she repeated this during a morning political talk show but protected herself by adding that there was no evidence. Macron immediately filed a complaint with the prosecution for the dissemination of fake news to influence the outcome of the presidential election, and the Paris Prosecutor’s Office launched proceedings. The French media quickly tracked the fake news trail, published at 7 p.m. in the American 4chan right-wing forum, and immediately propagated by dozens of pro-Kremlin twitter accounts with the #MacronCacheCash and #MacronGate tags. The rumor spread and was used only two hours later by Le Pen at the end of the debate. Two documents were published in the forum, which, according to the anonymous user, expose Emmanuel Macron of having an offshore account. The first is an Operating Agreement for a company registered in the jurisdiction of Nevis Island, with Macron’s signature as the beneficiary and the second is a bank letter from a bank in the Cayman Islands, issued to a company with a similar name. Both documents were refuted by Macron’s campaign headquarters, which published his signatures and a graphology expert report backing the forgery claim. Dear Friends, thank you for reading Bivol. Please, support our investigations and our authors Pay a Bivol Tax! Become our supporter with or a regular supporter with Send SMS: Bivol studied the metadata of the two documents, which show some interesting details, undetected by the French media so far as they have focused on spreading fake news. Both PDFs appear to have been created with professional high-end equipment manufactured by Canon. Here is what the metadata of the company La Providence LLC’s 14-page Operating Agreement contains: PDF Version : 1.4 Linearized : No Create Date : 2017:05:03 04:22:12-04:00 Creator : Canon iR-ADV 6255 PDF Modify Date : 2017:05:03 04:27:37-04:00 XMP Toolkit : Adobe XMP Core 5.2-c001 63.139439, 2010/09/27-13:37:26 Creator Tool : Canon iR-ADV 6255 PDF Metadata Date : 2017:05:03 04:27:37-04:00 Producer : Adobe PSL 1.2e for Canon Format : application/pdf Document ID : uuid:44930959-0000-2c9e-fc1c-efd800000000 Instance ID : uuid:b78218a3-b5dd-48d8-8911-47a87bf3850d Page Count : 14 The specified time of the file’s creation 4:22 a.m. Eastern Standard Time; the file was last modified five minutes later at 4:27 a.m. on May 3, the day of the debate. The scanning machine is a Canon iR-ADV 6255, professional-grade black and white printer. The price of this gadget (new) is USD 29,999 and it looks like this: The second file is in color and contains a single page. In its metadata we read the following: PDF Version : 1.4 Linearized : No Create Date : 2017:05:03 04:23:15-04:00 Creator : Canon iPR C700 PDF Modify Date : 2017:05:03 04:27:26-04:00 XMP Toolkit : Adobe XMP Core 5.2-c001 63.139439, 2010/09/27-13:37:26 Creator Tool : Canon iPR C700 PDF Metadata Date : 2017:05:03 04:27:26-04:00 Producer : Adobe PSL 1.2e for Canon Format : application/pdf Document ID : uuid:7a930959-0000-2c9e-fcff-0d6e00000000 Instance ID : uuid:510044f5-8850-4054-a6c4-3fb911957f0d Page Count : 1 This file was created just a minute after the previous one, at 4:23 a.m., and was last changed four minutes later. The Canon iPR C700 color printing machine that has scanned the document costs over USD 100,000 and looks like this: What conclusions can be drawn from these scarce data? If the metadata in these two documents are original and not manipulated, it is obvious that the masterminds of the discrediting claim have access to high-end equipment that is used by large companies or institutions. The time of creation of the two documents, which is only a minute apart, indicates that the two machines were in the same room and they were, most likely, operated by two people. Moreover, the date of the files’ creation that coincides with the day of the debate, contradicts the anonymous source’s assertion that the documents had been sent to many French journalists, but no one paid attention to them. However, it is important to note that time parameters are not a reliable indicator since such devices are difficult to set up and/or may not be set correctly for local time and the factory default data might have been kept. More interesting is the unique identifier UUID. In Document ID, it is in version 2 and contains information on the time and the MAC address of the device that is unique to its network card. The UUID of both devices contains the 2c-9e-fc characters. These are Canon’s MAC addresses, which confirm the printers’ descriptive data. Moreover, it is not a problem to get to the printers themselves, as their addresses are globally unique. The black-and-white printer has a MAC address 2C-9E-FC-1C-EF-D8 and the color one – 2C-9E-FC-ff-0D-6E. In addition, metadata may be manipulated, which is impossible to prove, but such manipulation would also be a sign of high professionalism, not an amateur forgery concocted by Macron’s opponents and Le Pen’s fans. It is ironic that Canon in French means cannon – a killing machine. Canon pour Macron La fausse nouvelle d’un compte d’Emmanuel Macron dans un paradis fiscal paraît bien trop professionnelle Vers la fin du débat de l’entre-deux-tours entre Emmanuel Macron et Marine Le Pen, la candidate du Front National a attaqué son adversaire en disant qu’elle espérait qu’on ne lui découvre pas un compte bancaire quelque part aux Bahamas. Le lendemain, elle a répété ceci dans une matinale, mais en indiquant bien, avec prudence, qu’elle n’avait pas de preuves. Macron a immédiatement déposé plainte pour diffusion de fausse nouvelle en vue de détourner les suffrages et le parquet de Paris a ouvert une enquête. Les médias français ont rapidement remonté le fil de la fausse nouvelle publiée à 19 h. dans le forum américain 4chan, terrain de prédilection pour l’expression des idées l’extrême droite ainsi que pour la diffusion anonyme de toute sorte de théories complotistes. La « nouvelle » a été reprise immédiatement par des dizaines de comptes twitter pro Kremlin avec les tags #MacronCacheCash et #MacronGate. La rumeur se répand pour être utilisée à peine deux heures plus tard par Le Pen en fin de débat. Le post sur le forum publie deux documents qui, selon le profil anonyme, démontrent qu’Emmanuel Macron possède un compte offshore : le premier représente les statuts d’une société, immatriculée par la juridiction de l’île de Niévès, portant la signature de Macron dans la qualité de bénéficiaire, et le deuxième est une lettre d’une banque des îles Caïmans, délivrée à une société portant un nom similaire. Les documents ont été réfutés par le QG de Macron, publiant ses signatures et une expertise de graphologie prouvant la contrefaçon. Bivol a examiné les métadonnées des deux documents qui montrent des détails intéressants, pour le moment restés en dehors des regards des médias français qui se concentrent sur la diffusion de la fausse nouvelle. Les deux fichiers PDF semblent être créés au moyen d’un équipement professionnel très haut de gamme, produit par Canon. Voici le contenu des métadonnées du fichier de 14 pages des statuts de la société La Providence LLC : PDF Version : 1.4 Linearized : No Create Date : 2017:05:03 04:22:12-04:00 Creator : Canon iR-ADV 6255 PDF Modify Date : 2017:05:03 04:27:37-04:00 XMP Toolkit : Adobe XMP Core 5.2-c001 63.139439, 2010/09/27-13:37:26 Creator Tool : Canon iR-ADV 6255 PDF Metadata Date : 2017:05:03 04:27:37-04:00 Producer : Adobe PSL 1.2e for Canon Format : application/pdf Document ID : uuid:44930959-0000-2c9e-fc1c-efd800000000 Instance ID : uuid:b78218a3-b5dd-48d8-8911-47a87bf3850d Page Count : 14 L’heure indiquée de création du fichier est 04 :22 temps est américain et le fichier a été modifié une dernière fois cinq minutes plus tard à 04 :27 le 3 mai, jour du débat. Le matériel utilisé pour le scan est une imprimante noir et blanc de type professionnel Canon iR-ADV 6255. Le prix de ce jouet neuf est de 29 999 USD et il ressemble à ceci : Le deuxième fichier est en couleurs et comporte une page. Ses métadonnées nous indiquent ce qui suit : PDF Version : 1.4 Linearized : No Create Date : 2017:05:03 04:23:15-04:00 Creator : Canon iPR C700 PDF Modify Date : 2017:05:03 04:27:26-04:00 XMP Toolkit : Adobe XMP Core 5.2-c001 63.139439, 2010/09/27-13:37:26 Creator Tool : Canon iPR C700 PDF Metadata Date : 2017:05:03 04:27:26-04:00 Producer : Adobe PSL 1.2e for Canon Format : application/pdf Document ID : uuid:7a930959-0000-2c9e-fcff-0d6e00000000 Instance ID : uuid:510044f5-8850-4054-a6c4-3fb911957f0d Page Count : 1 Ce fichier est créé une minute seulement après le précédent, à 04 :23 et a été modifié en dernier 4 minutes plus tard. L’imprimante couleurs Canon iPR C700 sur laquelle le scan a été fait coûte plus de 100 000 USD et ressemble à ça : Quelles sont les conclusions à tirer de ces données parcimonieuses ? Si les métadonnées de ces deux documents sont originales et non manipulées, il est évident que les créateurs de l’attaque disposent d’un accès à un matériel haut de gamme, présent dans de grandes sociétés ou institutions. L’heure de création des deux documents, d’un décalage d’une minute seulement, montre que probablement les deux machines se trouvaient dans la même pièce et que les opérations ont été effectuées très probablement par deux personnes. D’autre part la date du jour du débat contredit l’affirmation de la source anonyme que les documents avaient été envoyés à de nombreux journaliste français dont personne n’y a prêté attention. Ceci dit, il est important de noter que les paramètres temporels ne sont pas un indicateur fiable car la configuration de ce type de machines est difficile et il est tout à fait possible qu’elle ne le soient pas correctement par rapport au temps et à l’heure locale, gardant par défaut les données de leur fabrication. Ce qui est plus intéressant, c’est l’identifiant unique UUID. Dans Document ID, il s’agit d’une version 2 et il comporte une information sur le temps et l’adresse MAC de l’appareil, qui est unique pour sa carte réseau. Les UUID des deux appareils comportent les symboles 2c-9e-fc . Ce sont des adresses MAC du fabricant Canon, ce qui confirme en soi les données identifiant les imprimantes. De plus, il n’y aurait pas de difficulté d’arriver aux imprimantes elles-mêmes, étant donné que leurs adresses sont uniques au plan mondial. L’imprimante noir et blanc a l’adresse MAC 2C-9E-FC-1C-EF-D8, quant à l’imprimante couleur, c’est : 2C-9E-FC-ff-0D-6E Bien entendu, il est possible que les métadonnées soient manipulées et c’est impossible de le prouver, mais une telle manipulation ne ferait que confirmer le haut degré de professionnalisme, pour arriver au point de créer un UUID conforme, y glissant les adresses MAC d’appareils réellement existants pour tromper l’adversaire. De plus, la source des fichiers PDF comporte beaucoup de références renvoyant à des Canon du type % CANON_PFINF_TYPE2_TEXTOFF Finalement, la version d’une manipulation est moins probable et il serait plus vraisemblable que les fichiers proviennent effectivement de ces deux appareils. Et dans les deux cas, à savoir des métadonnées authentiques pointant sur des scanners Canon ou bien des métadonnées manipulées, le mode opératoire est professionnel et pas du tout celui d’une affaire montée de façon amateur par des adversaires de Macron et supporters de Le Pen. Ce qui est amusant, c’est que Canon en français est bien une arme qui tue. ***
def convert_K(cube_name, output_folder, is_huge=True, verbose=False): hdr = fits.getheader(cube_name) new_hdr = hdr.copy() new_hdr['BUNIT'] = 'K' spec_shape = hdr['NAXIS3'] cube_K_name = os.path.join(output_folder, f"{cube_name.rstrip('.fits')}_K.fits") if is_huge: create_huge_fits(cube_K_name, new_hdr, verbose=verbose) if verbose: pbar = ProgressBar(spec_shape) for chan in range(spec_shape): cube = SpectralCube.read(cube_name, mode='denywrite') cube_K_hdu = fits.open(cube_K_name, mode='update') cube_K_hdu[0].data[chan] = cube[chan:chan + 1].to(u.K).unitless_filled_data[:] cube_K_hdu.flush() cube_K_hdu.close() del cube if verbose: pbar.update(chan + 1) orig_cube = fits.open(cube_name, mode='denywrite') if len(orig_cube) == 2: cube_K_hdu = fits.open(cube_K_name, mode='update') cube_K_hdu.append(orig_cube[1]) cube_K_hdu.flush() cube_K_hdu.close() orig_cube.close() else: cube = SpectralCube.read(cube_name) cube_K = cube.to(u.K) cube_K.write(cube_K_name)
// NewMember creates a new member. // It panics if value type is not one of the return value type // of Member As* methods. func NewMember(val interface{}) Member { m := &member{val: val} m.Type() return m }
package ivy import ( "net" "net/http" ) // Dial dial a single connection to an IvyHub func Dial(network, address, registration string) (c net.Conn, err error) { // create REGISTER request var req *http.Request if req, err = NewRegisterRequest(registration); err != nil { return } // dial if c, err = net.Dial(network, address); err != nil { return } // send REGISTER request if err = req.Write(c); err != nil { c.Close() c = nil return } return }
/** * @module botbuilder-testing */ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /* eslint-disable @typescript-eslint/ban-types */ import { Activity, TestAdapter, Middleware, ConversationState, MemoryStorage, AutoSaveStateMiddleware, TurnContext, StatePropertyAccessor, } from 'botbuilder-core'; import { Dialog, DialogContext, DialogSet, DialogTurnStatus, DialogTurnResult, DialogState } from 'botbuilder-dialogs'; /** * A client for testing dialogs in isolation. */ export class DialogTestClient { private readonly _callback: (turnContext: TurnContext) => Promise<void>; private _dialogContext: DialogContext = null; private readonly _testAdapter: TestAdapter; /** * A DialogTurnResult instance with the result of the last turn. */ dialogTurnResult: DialogTurnResult; /** * A ConversationState instance for the current test client. */ conversationState: ConversationState; /** * Creates a [DialogTestClient](xref:botbuilder-testing.DialogTestClient) to test a [Dialog](xref:botbuilder-dialogs.Dialog) without having to create a full-fledged adapter. * ```javascript * let client = new DialogTestClient('test', MY_DIALOG, MY_OPTIONS); * let reply = await client.sendActivity('first message'); * assert.strictEqual(reply.text, 'first reply', 'reply failed'); * ``` * * @param channelId The `channelId` to be used for the test. * Use 'emulator' or 'test' if you are uncertain of the channel you are targeting. * Otherwise, it is recommended that you use the id for the channel(s) your bot will be using and write a test case for each channel. * @param targetDialog The [Dialog](xref:botbuilder-dialogs.Dialog) to be tested. This will be the root dialog for the test client. * @param initialDialogOptions Optional. Additional argument(s) to pass to the [Dialog](xref:botbuilder-dialogs.Dialog) being started. * @param middlewares Optional. A [Middleware](xref:botbuilder-core.Middleware) list to be added to the test adapter. * @param conversationState Optional. A [ConversationState](xref:botbuilder-core.ConversationState) instance to use in the test client. */ constructor( channelId: string, targetDialog: Dialog, initialDialogOptions?: unknown, middlewares?: Middleware[], conversationState?: ConversationState ); /** * Creates a [DialogTestClient](xref:botbuilder-testing.DialogTestClient) to test a [Dialog](xref:botbuilder-dialogs.Dialog) without having to create a full-fledged adapter. * ```javascript * let client = new DialogTestClient(MY_DIALOG, MY_OPTIONS); * let reply = await client.sendActivity('first message'); * assert.strictEqual(reply.text, 'first reply', 'reply failed'); * ``` * * @param testAdapter The [TestAdapter](xref:botbuilder-core.TestAdapter) to use. * @param targetDialog The [Dialog](xref:botbuilder-dialogs.Dialog) to be tested. This will be the root dialog for the test client. * @param initialDialogOptions Optional. Additional argument(s) to pass to the [Dialog](xref:botbuilder-dialogs.Dialog) being started. * @param middlewares Optional. A [Middleware](xref:botbuilder-core.Middleware) list to be added to the test adapter. * @param conversationState Optional. A [ConversationState](xref:botbuilder-core.ConversationState) instance to use in the test client. */ constructor( testAdapter: TestAdapter, targetDialog: Dialog, initialDialogOptions?: unknown, middlewares?: Middleware[], conversationState?: ConversationState ); /** * Creates a [DialogTestClient](xref:botbuilder-testing.DialogTestClient) to test a [Dialog](xref:botbuilder-dialogs.Dialog) without having to create a full-fledged adapter. * * @param channelOrAdapter The `channelId` or the [TestAdapter](xref:botbuilder-core.TestAdapter) to be used for the test. * @param targetDialog The [Dialog](xref:botbuilder-dialogs.Dialog) to be tested. This will be the root dialog for the test client. * @param initialDialogOptions Optional. Additional argument(s) to pass to the [Dialog](xref:botbuilder-dialogs.Dialog) being started. * @param middlewares Optional. A [Middleware](xref:botbuilder-core.Middleware) list to be added to the test adapter. * @param conversationState Optional. A [ConversationState](xref:botbuilder-core.ConversationState) instance to use in the test client. */ constructor( channelOrAdapter: string | TestAdapter, targetDialog: Dialog, initialDialogOptions?: object, middlewares?: Middleware[], conversationState?: ConversationState ) { this.conversationState = conversationState || new ConversationState(new MemoryStorage()); const dialogState = this.conversationState.createProperty('DialogState'); this._callback = this.getDefaultCallback(targetDialog, initialDialogOptions || null, dialogState); if (typeof channelOrAdapter == 'string') { const channelIdToUse: string = channelOrAdapter; this._testAdapter = new TestAdapter(this._callback, { channelId: channelIdToUse }).use( new AutoSaveStateMiddleware(this.conversationState) ); } else { const testAdapterToUse: TestAdapter = channelOrAdapter; this._testAdapter = testAdapterToUse; } this.addUserMiddlewares(middlewares); } /** * Gets a reference for the DialogContext. * * @remarks * This property will be null until at least one activity is sent to DialogTestClient. * * @returns the dialog context */ get dialogContext(): DialogContext { return this._dialogContext; } /** * Send an activity into the dialog. * * ```javascript * await DialogTest.send('hello').assertReply('hello yourself').startTest(); * ``` * * @param activity an activity potentially with text * @returns a TestFlow that can be used to assert replies etc */ // eslint-disable-next-line @typescript-eslint/no-explicit-any async sendActivity(activity: Partial<Activity> | string): Promise<any> { await this._testAdapter.receiveActivity(activity); return this._testAdapter.activityBuffer.shift(); } /** * Get the next reply waiting to be delivered (if one exists) * * @returns the next reply */ getNextReply(): Partial<Activity> { return this._testAdapter.activityBuffer.shift(); } private getDefaultCallback( targetDialog: Dialog, initialDialogOptions: object, dialogState: StatePropertyAccessor<DialogState> ): (turnContext: TurnContext) => Promise<void> { return async (turnContext: TurnContext): Promise<void> => { const dialogSet = new DialogSet(dialogState); dialogSet.add(targetDialog); this._dialogContext = await dialogSet.createContext(turnContext); this.dialogTurnResult = await this._dialogContext.continueDialog(); if (this.dialogTurnResult.status === DialogTurnStatus.empty) { this.dialogTurnResult = await this._dialogContext.beginDialog(targetDialog.id, initialDialogOptions); } }; } /** * @private */ private addUserMiddlewares(middlewares: Middleware[]): void { if (middlewares != null) { middlewares.forEach((middleware): void => { this._testAdapter.use(middleware); }); } } }
<filename>src/base/model.ts import { Field, ObjectType } from "@nestjs/graphql"; @ObjectType() export class BaseModel{ @Field(()=> String, {nullable : true, name:"id"}) id : String @Field(()=> Date, {defaultValue : Date.now(), name:"createdAt"}) createdAt : Date }
12 students who were injured in the clashes were rushed to hospital 12 students at a private engineering college in Punjab were injured after clashes erupted over Kashmiri students cheering for Pakistan in a cricket match against Sri Lanka.The college has been closed till September 8.The fight took place yesterday at the hostel of a college 35 kilometres from Chandigarh.Students in the common room at the hostel were watching the match when Kashmiri students allegedly cheered Pakistan and others asked them to stop.The argument turned into a brawl and 12 students were rushed to local hospitals.200 students from Kashmir are enrolled at the college and most of them stay in the hostel on campus.In March, 60 Kashmiri students at a college in Uttar Pradesh were charged with sedition after they supported Pakistan in a match against India. 60 Kashmiri students had been suspended in Meerut and removed from campus. ( Sedition charges against Kashmiri students, who cheered for Pak in cricket match, dropped) The charges against them were dropped after Kashmir Chief Minister Omar Abdullah spoke to his counterpart in Uttar Pradesh, Akhilesh Yadav.
Rodgers, the Liverpool manager, has targeted the midfielder for a potential £30 million move and has made an enquiry to the Russian club ahead of a possible bid before the transfer window closes. Willian only moved to Anzhi in January from Shakhtar Donetsk but he has been put up for sale, together with all of his team-mates, due to a major financial restructuring that has been introduced to drastically cut costs. Tottenham Hotspur manager Andre Villas-Boas has been a long-term admirer of the playmaker and will also consider making an offer, while Rodgers has turned his attentions to Willian as he attempts to make one significant signing this summer. Liverpool have experienced frustration in their bids to sign Armenia international Henrikh Mkhitaryan, who joined Borussia Dortmund, and Atletico Madrid forward Diego Costa over the last two months but Willian has emerged as a genuine target for the Merseyside club. Rodgers has spent around £24 million this summer but has been assured of further funds to make one marquee signing, regardless of whether Luis Suarez does depart Anfield, with the £5 million sale of Stewart Downing to West Ham United only serving to enhance his spending power. Downing completed his move to London on Tuesday and has agreed a four-year contract, linking up with former Liverpool team-mates Andy Carroll and Joe Cole. He said: "It's a great opportunity for me being here, it's a great club and I'm really excited to get going. "I'm ready and I'm fit for the first game against Cardiff City (on Saturday). I've played a decent few games for Liverpool in pre-season, so there will be no problems on that front."
/** * Use this class to execute requests <b>synchronously</b> against the Box REST API(V2). Full details about the Box API can be found at {@see <a * href="http://developers.box.com/docs">http://developers.box.com/docs</a>} . You must have an OpenBox application with a valid API key to use the Box API. All * methods in this class are executed in the invoking thread, and therefore are NOT safe to execute in the UI thread of your application. You should only use * this class if you already have worker threads or AsyncTasks that you want to incorporate the Box API into. */ public class BoxItemsManager extends BoxResourceManager { /** * Constructor. * * @param config * BoxConfig * @param resourceHub * IResourceHub * @param parser * json parser * @param auth * auth for api calls * @param restClient * REST client to make api calls. */ public BoxItemsManager(IBoxConfig config, IBoxResourceHub resourceHub, final IBoxJSONParser parser, final IBoxRequestAuth auth, final IBoxRESTClient restClient) { super(config, resourceHub, parser, auth, restClient); } /** * Get item given an item id. * * @param id * id of the item * @param BoxBasicRequestObject * requestObject * @param type * resource type * @return requested box file/folder * @throws BoxRestException * exception * @throws BoxServerException * exception * @throws AuthFatalFailureException * exception indicating authentication totally failed */ public BoxItem getItem(final String id, BoxDefaultRequestObject requestObject, final BoxResourceType type) throws BoxRestException, BoxServerException, AuthFatalFailureException { GetItemRequest request = new GetItemRequest(getConfig(), getJSONParser(), id, type, requestObject); Object result = getResponseAndParse(request, type, getJSONParser()); return (BoxItem) tryCastBoxItem(type, result); } /** * Get a trashed item. * * @param itemId * item id * @param type * type * @param requestObject * request object * @return the item * @throws BoxRestException * exception * @throws AuthFatalFailureException * exception * @throws BoxServerException * exception */ public BoxItem getTrashItem(final String itemId, final BoxResourceType type, final BoxDefaultRequestObject requestObject) throws BoxRestException, AuthFatalFailureException, BoxServerException { GetTrashItemRequest request = new GetTrashItemRequest(getConfig(), getJSONParser(), itemId, type, requestObject); Object result = getResponseAndParse(request, type, getJSONParser()); return (BoxItem) tryCastBoxItem(type, result); } /** * Copy an item. * * @param id * id of the item * @param requestObject * request object * @param type * resource type of the item * @return copied file/folder * @throws BoxRestException * exception * @throws BoxServerException * exception * @throws AuthFatalFailureException * exception */ public BoxItem copyItem(final String id, BoxItemRequestObject requestObject, final BoxResourceType type) throws BoxRestException, BoxServerException, AuthFatalFailureException { CopyItemRequest request = new CopyItemRequest(getConfig(), getJSONParser(), id, requestObject, type); return (BoxItem) getResponseAndParseAndTryCast(request, type, getJSONParser()); } /** * Update info for an item * * @param id * id of the item * @param requestObject * request object * @param type * resource type of the item * @return updated file/folder * @throws UnsupportedEncodingException * exception * @throws BoxRestException * exception * @throws BoxServerException * exception * @throws AuthFatalFailureException * exception indicating authentication totally failed */ public BoxItem updateItemInfo(final String id, BoxItemRequestObject requestObject, final BoxResourceType type) throws UnsupportedEncodingException, BoxRestException, BoxServerException, AuthFatalFailureException { UpdateItemInfoRequest request = new UpdateItemInfoRequest(getConfig(), getJSONParser(), id, requestObject, type); return (BoxItem) getResponseAndParseAndTryCast(request, type, getJSONParser()); } /** * Create a shared link for an item, given the id . * * @param auth * authorization * @param id * id of the item * @param requestObject * request object * @param type * resource type of this item * @return the file/folder, with shared link related fields filled in. * @throws BoxRestException * exception * @throws BoxServerException * exception * @throws AuthFatalFailureException * exception indicating authentication totally failed */ public BoxItem createSharedLink(final String id, BoxItemRequestObject requestObject, final BoxResourceType type) throws BoxRestException, BoxServerException, AuthFatalFailureException { CreateSharedLinkRequest request = new CreateSharedLinkRequest(getConfig(), getJSONParser(), id, requestObject, type); return (BoxItem) getResponseAndParseAndTryCast(request, type, getJSONParser()); } /** * Permanently delete a trashed item. * * @param id * id of the item * @param type * resource type of the item. * @param requestObject * request object * @throws BoxRestException * @throws AuthFatalFailureException * @throws BoxServerException */ public void deleteTrashItem(final String id, final BoxResourceType type, final BoxFileRequestObject requestObject) throws BoxRestException, BoxServerException, AuthFatalFailureException { DeleteTrashItemRequest request = new DeleteTrashItemRequest(getConfig(), getJSONParser(), id, type, requestObject); executeRequestWithNoResponseBody(request); } /** * Restore a trashed item. * * @param id * id of the trashed item. * @param type * type of the item * @param requestObject * @return the item. * @throws BoxRestException * @throws AuthFatalFailureException * @throws BoxServerException */ public BoxItem restoreTrashItem(final String id, final BoxResourceType type, final BoxItemRestoreRequestObject requestObject) throws BoxRestException, AuthFatalFailureException, BoxServerException { RestoreTrashItemRequest request = new RestoreTrashItemRequest(getConfig(), getJSONParser(), id, type, requestObject); return (BoxItem) getResponseAndParseAndTryCast(request, type, getJSONParser()); } }
package projects import "time" const ( // GetSbomEndpoint is the current endpoint for retrieving an organization's SBOMs GetSbomEndpoint = "v1/project/getSBOM" // GetSbomsEndpoint is the current endpoint for retrieving an organization's SBOMs GetSbomsEndpoint = "v1/project/getSBOMs" ) // SourceDetails contains the original package information retrieved directly from an uploaded SBOM. type SourceDetails struct { Name string `json:"sbom_name"` Org string `json:"sbom_org"` Version string `json:"sbom_version"` } // SBOMEntry represents a single entry within an SBOM. type SBOMEntry struct { ID string `json:"id"` SBOMID string `json:"sbom_id"` Confidence float32 `json:"confidence"` Name string `json:"name"` Org string `json:"org"` Version string `json:"version"` IonID string `json:"ion_id"` Selected bool `json:"selected"` LocationInSBOM int `json:"location_in_sbom"` Source SourceDetails `json:"source"` ErrMsg string `json:"error_message"` } // SBOM represents a software list containing zero or more SBOMEntry objects. type SBOM struct { ID string `json:"id"` Name string `json:"sbom_name"` Version string `json:"sbom_version"` Supplier string `json:"supplier_name"` SbomType string `json:"sbom_type"` SbomStatus string `json:"sbom_status"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` EntryCount int `json:"entry_count"` Entries []SBOMEntry `json:"entries"` TeamID string `json:"team_id"` OrgID string `json:"org_id"` RulesetID string `json:"ruleset_id"` }
<reponame>Fintan-contents/example-chat import React from 'react'; import './Label.css'; export const Label: React.FC<React.LabelHTMLAttributes<HTMLLabelElement>> = (props) => { return ( <label className="Label" {...props}>{props.children}</label> ); };
package source import ( "context" "sync" "github.com/pkg/errors" "k8s.io/client-go/util/workqueue" "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/predicate" "sigs.k8s.io/controller-runtime/pkg/runtime/inject" "sigs.k8s.io/controller-runtime/pkg/source" ) // Stoppable is a stoppable source type Stoppable interface { source.Source inject.Stoppable } // DynamicSource is a funnel for sources that can be // dynamically (de)registered before & after the controller has started type Dynamic interface { source.Source // sources must be registered with a unique id Add(id string, src source.Source) error // remove a source. errors if not found Remove(id string) error } // cache of sources type cachedSource struct { // the original source source source.Source // cancel function to stop it cancel context.CancelFunc } // the args with which the dynamic source was started type startArgs struct { h handler.EventHandler i workqueue.RateLimitingInterface ps []predicate.Predicate } // DynamicSource implements Dynamic type DynamicSource struct { // cancel this context to stop all registered sources ctx context.Context // the cached sources that can be dynamically added/removed cache map[string]cachedSource // cache access lock sync.RWMutex // has source started? started *startArgs // the channel to which to push events output source.Channel } func NewDynamicSource(ctx context.Context) *DynamicSource { return &DynamicSource{ ctx: ctx, cache: make(map[string]cachedSource), } } // start all the sources func (s *DynamicSource) Start(ctx context.Context, h handler.EventHandler, i workqueue.RateLimitingInterface, ps ...predicate.Predicate) error { s.lock.Lock() defer s.lock.Unlock() if s.started != nil { return errors.Errorf("source was already started") } for _, src := range s.cache { if err := src.source.Start(ctx, h, i, ps...); err != nil { return err } } s.started = &startArgs{ h: h, i: i, ps: ps, } return nil } // only Stoppable sources are currently supported func (s *DynamicSource) Add(id string, src Stoppable) error { s.lock.Lock() defer s.lock.Unlock() if _, exists := s.cache[id]; exists { return errors.Errorf("source %v already exists", id) } ctx, cancel := context.WithCancel(s.ctx) if err := src.InjectStopChannel(ctx.Done()); err != nil { return err } if s.started != nil { if err := src.Start(ctx, s.started.h, s.started.i, s.started.ps...); err != nil { return errors.Wrapf(err, "failed to start source %v", id) } } s.cache[id] = cachedSource{ source: src, cancel: cancel, } return nil } // remove (and stop) a source func (s *DynamicSource) Remove(id string) error { s.lock.Lock() defer s.lock.Unlock() src, ok := s.cache[id] if !ok { return errors.Errorf("no source in cache with id %v", id) } src.cancel() delete(s.cache, id) return nil }
<reponame>FabianoVeglianti/syncope<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.syncope.core.persistence.jpa.dao; import java.util.stream.Collectors; import org.apache.syncope.core.persistence.api.dao.PlainAttrValueDAO; import org.apache.syncope.core.persistence.api.entity.AnyUtils; import org.apache.syncope.core.persistence.api.entity.Entity; import org.apache.syncope.core.persistence.api.entity.PlainAttr; import org.apache.syncope.core.persistence.api.entity.PlainAttrValue; import org.apache.syncope.core.persistence.api.entity.anyobject.APlainAttrUniqueValue; import org.apache.syncope.core.persistence.api.entity.anyobject.APlainAttrValue; import org.apache.syncope.core.persistence.api.entity.group.GPlainAttrUniqueValue; import org.apache.syncope.core.persistence.api.entity.group.GPlainAttrValue; import org.apache.syncope.core.persistence.api.entity.user.UPlainAttrUniqueValue; import org.apache.syncope.core.persistence.api.entity.user.UPlainAttrValue; import org.apache.syncope.core.persistence.jpa.entity.AbstractPlainAttrValue; import org.apache.syncope.core.persistence.jpa.entity.anyobject.JPAAPlainAttrUniqueValue; import org.apache.syncope.core.persistence.jpa.entity.anyobject.JPAAPlainAttrValue; import org.apache.syncope.core.persistence.jpa.entity.group.JPAGPlainAttrUniqueValue; import org.apache.syncope.core.persistence.jpa.entity.group.JPAGPlainAttrValue; import org.apache.syncope.core.persistence.jpa.entity.user.JPAUPlainAttrUniqueValue; import org.apache.syncope.core.persistence.jpa.entity.user.JPAUPlainAttrValue; public class JPAPlainAttrValueDAO extends AbstractDAO<PlainAttrValue> implements PlainAttrValueDAO { @SuppressWarnings("unchecked") public static <T extends PlainAttrValue> Class<? extends AbstractPlainAttrValue> getEntityReference( final Class<T> reference) { return AbstractPlainAttrValue.class.isAssignableFrom(reference) ? (Class<? extends AbstractPlainAttrValue>) reference : reference.equals(GPlainAttrValue.class) ? JPAGPlainAttrValue.class : reference.equals(GPlainAttrUniqueValue.class) ? JPAGPlainAttrUniqueValue.class : reference.equals(APlainAttrValue.class) ? JPAAPlainAttrValue.class : reference.equals(APlainAttrUniqueValue.class) ? JPAAPlainAttrUniqueValue.class : reference.equals(UPlainAttrValue.class) ? JPAUPlainAttrValue.class : reference.equals(UPlainAttrUniqueValue.class) ? JPAUPlainAttrUniqueValue.class : null; } @Override public void deleteAll(final PlainAttr<?> attr, final AnyUtils anyUtils) { if (attr.getUniqueValue() == null) { attr.getValues().stream().map(Entity::getKey).collect(Collectors.toSet()).forEach(attrValueKey -> { PlainAttrValue attrValue = anyUtils.plainAttrValueClass().cast( entityManager().find(getEntityReference(anyUtils.plainAttrValueClass()), attrValueKey)); if (attrValue != null) { entityManager().remove(attrValue); attr.getValues().remove(attrValue); } }); } else { entityManager().remove(attr.getUniqueValue()); attr.setUniqueValue(null); } } }
/* Fetch IRQ information of specific IR index */ static int vtd_remap_irq_get(IntelIOMMUState *iommu, uint16_t index, X86IOMMUIrq *irq, uint16_t sid) { VTD_IR_TableEntry irte = {}; int ret = 0; ret = vtd_irte_get(iommu, index, &irte, sid); if (ret) { return ret; } irq->trigger_mode = irte.irte.trigger_mode; irq->vector = irte.irte.vector; irq->delivery_mode = irte.irte.delivery_mode; irq->dest = le32_to_cpu(irte.irte.dest_id); if (!iommu->intr_eime) { #define VTD_IR_APIC_DEST_MASK (0xff00ULL) #define VTD_IR_APIC_DEST_SHIFT (8) irq->dest = (irq->dest & VTD_IR_APIC_DEST_MASK) >> VTD_IR_APIC_DEST_SHIFT; } irq->dest_mode = irte.irte.dest_mode; irq->redir_hint = irte.irte.redir_hint; trace_vtd_ir_remap(index, irq->trigger_mode, irq->vector, irq->delivery_mode, irq->dest, irq->dest_mode); return 0; }
// GetNoticesOk returns a tuple with the Notices field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTFeatureScriptEvalResponse1859) GetNoticesOk() (*[]BTNotice227, bool) { if o == nil || o.Notices == nil { return nil, false } return o.Notices, true }
import copy from pprint import pprint with open("input.txt") as f: arr = [line.strip().split("-") for line in f.readlines()] #print(arr) connections = {} for line in arr: if line[0] in connections.keys(): connections[line[0]].append(line[1]) else: connections[line[0]] = [line[1]] if line[1] in connections.keys(): connections[line[1]].append(line[0]) else: connections[line[1]] = [line[0]] #print(connections) def find_paths(location, path, visited, dup): #print("Location: " + str(location) + " Paths: " + str(path) + " Visited: " + str(visited)) new_path = copy.deepcopy(path) new_visited = copy.deepcopy(visited) if location == 'end': new_path.append('end') return [new_path] final_paths = [] new_path.append(location) if location.islower(): new_visited.append(location) for new_location in connections[location]: if new_location not in visited: final_paths += find_paths(new_location, new_path, new_visited, dup) elif new_location != 'start' and dup: final_paths += find_paths(new_location, new_path, new_visited, False) return final_paths print(len(find_paths('start', [], [], False))) print(len(find_paths('start', [], [], True))) #pprint(find_paths_2('start', [], [], True))
/** * * @author Sandeep Reddy,Murthy * */ public class SplunkAuthTokenProviderTest extends PowerMockTestCase{ @Mock HttpClientProvider httpClientProvider; // @Autowired SplunkAuthTokenProvider splunkAuthTokenProvider; // @Autowired AlertBuilder alertBuilder; private static final Logger logger = LoggerFactory .getLogger(SplunkAuthTokenProviderTest.class); @BeforeTest public void setup() { logger.info(SOURCE_TYPE,"Test Phase","Setting the environment"); System.setProperty(ENVIORNMENT, ENVIRONMENT_VALUE); splunkAuthTokenProvider=new SplunkAuthTokenProvider(); alertBuilder=new AlertBuilder(); } @Test public void getAuthTokenTest() throws ClientProtocolException, IOException, AuthorizationException, URISyntaxException { SplunkAuthTokenProvider splunkAuthTokenProvider = new SplunkAuthTokenProvider(); HttpClientProvider httpClientProvider = Mockito .mock(HttpClientProvider.class); String authToken = null; CloseableHttpClient closeableHttpClient = Mockito .mock(CloseableHttpClient.class); Mockito.when(httpClientProvider.getHttpClient()).thenReturn( closeableHttpClient); CloseableHttpResponse closeableHttpResponse = Mockito .mock(CloseableHttpResponse.class); Mockito.when(closeableHttpClient.execute(Mockito.any(HttpPost.class))) .thenReturn(closeableHttpResponse); StatusLine statusLine = Mockito.mock(StatusLine.class); Mockito.when(closeableHttpResponse.getStatusLine()).thenReturn( statusLine); Mockito.when(statusLine.getStatusCode()).thenReturn(200); JsonNode jsonNode2 = Mockito.mock(JsonNode.class); ObjectMapper objectMapper = Mockito.mock(ObjectMapper.class); HttpEntity httpEntity = Mockito.mock(HttpEntity.class); Mockito.when(closeableHttpResponse.getEntity()).thenReturn(httpEntity); String json = "{\"sessionKey\":\"value\"}"; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( json.getBytes(Charset.defaultCharset())); Mockito.when(httpEntity.getContent()).thenReturn(byteArrayInputStream); Mockito.when(objectMapper.readTree(byteArrayInputStream)).thenReturn( jsonNode2); JsonNode jsonNode3 = Mockito.mock(JsonNode.class); Mockito.when(jsonNode2.get(Mockito.any(String.class))).thenReturn( jsonNode3); Mockito.when(jsonNode3.asText()).thenReturn("testString"); ReflectionTestUtils.setField(splunkAuthTokenProvider, "httpClientProvider", httpClientProvider); ReflectionTestUtils.setField(splunkAuthTokenProvider, "authToken", authToken); Assert.assertNotNull(splunkAuthTokenProvider.getNewAuthToken()); } @Test(expectedExceptions = { AuthorizationException.class }) public void getAuthTokenNot200Test() throws ClientProtocolException, IOException, AuthorizationException, URISyntaxException { SplunkAuthTokenProvider splunkAuthTokenProvider = new SplunkAuthTokenProvider(); HttpClientProvider httpClientProvider = Mockito .mock(HttpClientProvider.class); String authToken = null; CloseableHttpClient closeableHttpClient = Mockito .mock(CloseableHttpClient.class); Mockito.when(httpClientProvider.getHttpClient()).thenReturn( closeableHttpClient); CloseableHttpResponse closeableHttpResponse = Mockito .mock(CloseableHttpResponse.class); Mockito.when(closeableHttpClient.execute(Mockito.any(HttpPost.class))) .thenReturn(closeableHttpResponse); StatusLine statusLine = Mockito.mock(StatusLine.class); Mockito.when(closeableHttpResponse.getStatusLine()).thenReturn( statusLine); Mockito.when(statusLine.getStatusCode()).thenReturn(201); ReflectionTestUtils.setField(splunkAuthTokenProvider, "httpClientProvider", httpClientProvider); ReflectionTestUtils.setField(splunkAuthTokenProvider, "authToken", authToken); splunkAuthTokenProvider.getAuthToken(); } @Test(expectedExceptions = { AuthorizationException.class }) public void getNewAuthTokenAuthorizationExceptionforServiceUnavailabilityTest() throws AuthorizationException, IOException, URISyntaxException{ SplunkAuthTokenProvider splunkAuthTokenProvider = new SplunkAuthTokenProvider(); HttpClientProvider httpClientProvider = Mockito .mock(HttpClientProvider.class); ReflectionTestUtils.setField(splunkAuthTokenProvider, "httpClientProvider", httpClientProvider); ReflectionTestUtils.setField(splunkAuthTokenProvider, "SPLUNK_HOST", "test"); ReflectionTestUtils.setField(splunkAuthTokenProvider, "SPLUNK_PORT", 8080); ReflectionTestUtils.setField(splunkAuthTokenProvider, "USERNAME_VALUE", "test"); ReflectionTestUtils.setField(splunkAuthTokenProvider, "PASSWORD_VALUE", "test"); ReflectionTestUtils.setField(splunkAuthTokenProvider, "authToken", "test"); CloseableHttpClient closeableHttpClient=Mockito.mock(CloseableHttpClient.class); CloseableHttpResponse closeableHttpResponse=Mockito.mock(CloseableHttpResponse.class); Mockito.when(httpClientProvider.getHttpClient()).thenReturn(closeableHttpClient); Mockito.when(closeableHttpClient.execute((HttpUriRequest) Mockito.any())).thenReturn(closeableHttpResponse); StatusLine statusLine=Mockito.mock(StatusLine.class); Mockito.when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine); Mockito.when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_SERVICE_UNAVAILABLE); splunkAuthTokenProvider.getNewAuthToken(); } @Test(expectedExceptions = { AuthorizationException.class }) public void getNewAuthTokenAuthorizationExceptionforUnauthorizedTest() throws AuthorizationException, IOException, URISyntaxException{ SplunkAuthTokenProvider splunkAuthTokenProvider = new SplunkAuthTokenProvider(); HttpClientProvider httpClientProvider = Mockito .mock(HttpClientProvider.class); ReflectionTestUtils.setField(splunkAuthTokenProvider, "httpClientProvider", httpClientProvider); ReflectionTestUtils.setField(splunkAuthTokenProvider, "SPLUNK_HOST", "test"); ReflectionTestUtils.setField(splunkAuthTokenProvider, "SPLUNK_PORT", 8080); ReflectionTestUtils.setField(splunkAuthTokenProvider, "USERNAME_VALUE", "test"); ReflectionTestUtils.setField(splunkAuthTokenProvider, "PASSWORD_VALUE", "test"); ReflectionTestUtils.setField(splunkAuthTokenProvider, "authToken", "test"); CloseableHttpClient closeableHttpClient=Mockito.mock(CloseableHttpClient.class); CloseableHttpResponse closeableHttpResponse=Mockito.mock(CloseableHttpResponse.class); Mockito.when(httpClientProvider.getHttpClient()).thenReturn(closeableHttpClient); Mockito.when(closeableHttpClient.execute((HttpUriRequest) Mockito.any())).thenReturn(closeableHttpResponse); StatusLine statusLine=Mockito.mock(StatusLine.class); Mockito.when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine); Mockito.when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED); splunkAuthTokenProvider.getNewAuthToken(); } }
Preparation and thermal characteristics of caprylic acid based composite as phase change material for thermal energy storage The present work is focused on the phase change behavior of the lately prepared caprylic acid based composite as phase change materials (PCMs) for thermal energy storage. The composite PCMs were prepared with caprylic acid as base material whereas, CuO, ZnO, Ag and graphene oxide (GO) are used as supporting materials. The 0.5 weight fraction (wt%) of CuO, ZnO, Ag and GO nanoparticles (NPs) were dispersed in caprylic acid, separately aiming to assess the maximum enhancement of thermal conductivity. The morphological structure was found by using field emission scanning electron microscopy (FESEM) and crystalloid phase was studied by x-ray diffraction. The phase change properties of base PCM and composite PCMs were determined by using differential scanning calorimetry (DSC) analyses. Enhancement of thermal conductivity of caprylic acid with 0.5 wt% of CuO, ZnO, Ag and GO NPs separately, was estimated as 36%, 43%, 52%, and 87%, respectively when compared to caprylic acid alone. The results obtained from the experiment proved that freezing and melting times of the composite PCMs using GO were less while comparing to the rest. Thus, GO based composite PCM can be considered as one of the suitable candidates for low temperature thermal energy storage application.
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * <pre> * You've got a way to keep me on your side. You give me cause for love that I can't hide. * For you I know I'd even try to turn the tide. Because you're mine, I walk the line. * </pre> * @author bodmas */ public class ProblemB2 { private static class Block { int smallest, biggest; } private boolean solve(int[] a, int[] p) { int biggest, smallest; Arrays.sort(p); List<Block> blocks = new ArrayList<>(); if (p[0] != 0) { biggest = smallest = a[0]; for (int j = 1; j < p[0]; j++) { if (a[j - 1] > a[j]) return false; if (a[j] > biggest) biggest = a[j]; if (a[j] < smallest) smallest = a[j]; } addBlock(blocks, biggest, smallest); } int i = 0; while (i != p.length) { biggest = smallest = a[p[i]]; while (++i != p.length && p[i] == p[i - 1] + 1) { if (a[p[i]] > biggest) biggest = a[p[i]]; if (a[p[i]] < smallest) smallest = a[p[i]]; } if (a[p[i - 1] + 1] > biggest) biggest = a[p[i - 1] + 1]; if (a[p[i - 1] + 1] < smallest) smallest = a[p[i - 1] + 1]; addBlock(blocks, biggest, smallest); int x = i == p.length ? a.length : p[i]; if (p[i - 1] + 2 != x) { int j = p[i - 1] + 2; smallest = biggest = a[j]; while (++j != x) { if (a[j - 1] > a[j]) return false; if (a[j] > biggest) biggest = a[j]; if (a[j] < smallest) smallest = a[j]; } addBlock(blocks, biggest, smallest); } } int[] ss = new int[blocks.size()]; ss[ss.length - 1] = blocks.get(ss.length - 1).smallest; for (i = ss.length - 2; i >= 0; i--) { if (blocks.get(i).biggest > ss[i + 1]) return false; ss[i] = Math.min(blocks.get(i).smallest, ss[i + 1]); } return true; } private void addBlock(List<Block> blocks, int biggest, int smallest) { Block block = new Block(); block.biggest = biggest; block.smallest = smallest; blocks.add(block); } public static void main(String[] args) throws IOException { try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out))) { int n = Integer.parseInt(readLine(in)); while (n-- != 0) { int[] x = Stream.of(readLine(in).split(" ")).mapToInt(Integer::parseInt).toArray(); int[] a = Stream.of(readLine(in).split(" ")).mapToInt(Integer::parseInt).toArray(); int[] p = Stream.of(readLine(in).split(" ")).mapToInt(Integer::parseInt).toArray(); for (int i = 0; i < p.length; i++) { p[i]--; } out.println(new ProblemB2().solve(a, p) ? "YES" : "NO"); } } } private static String readLine(BufferedReader in) { try { return in.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } }
<gh_stars>10-100 import { emptyProjects } from "cypress/fixtures/db/emptyProjects"; import { realWorldState } from "cypress/fixtures/db/realworld-state"; import { generatedEditorTestId, schemaEditorTestId } from "cypress/support/selectors"; import { treeTestId } from "cypress/support/tree"; import { DB_NAME } from "src/database/constants"; describe.skip("Demo", () => { it("Should run demo", () => { indexedDB.deleteDatabase(DB_NAME); cy.createProjects(emptyProjects); cy.setProjectState(1, realWorldState); cy.viewport(1280, 720); cy.visit("#/1/Realworld"); cy.findByTestId(treeTestId).within(() => { cy.contains("li", "Schemas").toggleTreeNode(); cy.contains("li", "Profile").clickTreeNode(); }); cy.findByTestId(schemaEditorTestId) .getMonacoEditor() .within(() => { cy.get("textarea") .focus() .type( "{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{leftarrow}", { force: true } ) .type(",{enter}x-fa", { force: true }) .type("{ctrl} ", { force: true }) .type("{enter}", { force: true }) .type(": usern", { force: true }) .type("{ctrl} ", { force: true }) .type("{enter}", { force: true }); cy.get("textarea") .type("{downarrow}{downarrow}{downarrow}", { force: true }) .type(",{enter}x-fa", { force: true }) .type("{ctrl} ", { force: true }) .type("{enter}", { force: true }) .type(": jobti", { force: true }) .type("{ctrl} ", { force: true }) .type("{enter}", { force: true }); cy.get("textarea") .type("{downarrow}{downarrow}{downarrow}", { force: true }) .type(",{enter}x-fa", { force: true }) .type("{ctrl} ", { force: true }) .type("{enter}", { force: true }) .type(": avatar", { force: true }) .type("{ctrl} ", { force: true }) .type("{enter}", { force: true }); }); cy.findByTestId(generatedEditorTestId) .getMonacoEditor() .within(() => { cy.get( "textarea" ).type( "{shift}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}", { force: true } ); }); cy.wait(5000); cy.findByTestId(treeTestId) .scrollTo("top") .within(() => { cy.contains("li", "Article").clickTreeNode(); }); cy.findByTestId(generatedEditorTestId) .getMonacoEditor() .within(() => { cy.get("textarea") .click({ force: true }) .type("{esc}", { force: true }); }); cy.findByTestId(schemaEditorTestId) .getMonacoEditor() .within(() => { cy.get("textarea") .type("{pagedown}{pagedown}{leftarrow}", { force: true }) .type("{shift}{uparrow}{uparrow}{uparrow}{uparrow}", { force: true }); }); cy.findByTestId(generatedEditorTestId) .getMonacoEditor() .within(() => { cy.get("textarea") .type("{pageup}", { force: true }) .type( "{shift}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}", { force: true } ); }); cy.wait(5000); cy.findByTestId(schemaEditorTestId) .getMonacoEditor() .within(() => { cy.get("textarea") .type("{uparrow}{uparrow}{end},{enter}minim", { force: true }) .type("{ctrl} ", { force: true }) .type("{enter}", { force: true }) .type("{ctrl} ", { force: true }) .type("{enter}", { force: true }) .type("{rightarrow},{enter}maxim", { force: true }) .type("{ctrl} ", { force: true }) .type("{enter}", { force: true }) .type("100", { force: true }); }); cy.findByTestId(generatedEditorTestId) .getMonacoEditor() .within(() => { cy.get("textarea") .type("{pageup}{home}", { force: true }) .type( "{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}{downarrow}", { force: true } ) .type("{shift}{end}", { force: true }); }); cy.wait(5000); cy.findByTestId(treeTestId).within(() => { cy.contains("li", "Paths").toggleTreeNode(); cy.contains("li", /\/articles$/).toggleTreeNode(); cy.contains("li", "get").toggleTreeNode(); cy.contains("li", "200").clickTreeNode(); cy.contains("li", "Paths").scrollIntoView(); }); cy.findByTestId(schemaEditorTestId) .getMonacoEditor() .within(() => { cy.get("textarea").type("{pageup}", { force: true }); }); cy.findByTestId(generatedEditorTestId) .getMonacoEditor() .within(() => { cy.get("textarea").type("{pageup}", { force: true }); }); }); });
def compute_normalized_histograms(channels, nbins=8, bins_range=(0,256)): histograms = [ np.histogram(x, bins=nbins, range=bins_range)[0] for x in channels ] hist_features = np.concatenate(histograms).astype(np.float64) normed_features = hist_features / np.sum(hist_features) return normed_features
<reponame>majacQ/objective-c #import <Foundation/Foundation.h> #pragma mark Class forward @class PNUUIDMetadata; NS_ASSUME_NONNULL_BEGIN #pragma mark Interface declaration /** * @brief Object which is used to represent \c chanel \c member. * * @author <NAME> * @version 4.14.1 * @since 4.14.1 * @copyright © 2010-2020 PubNub, Inc. */ @interface PNChannelMember : NSObject #pragma mark - Information /** * @brief \c Metadata associated with \c UUID which is listed in \c channel's members list. * * @note This property will be set only if \b PNChannelMemberUUIDField has been added to * \c includeFields list during request. */ @property (nonatomic, nullable, readonly, strong) PNUUIDMetadata *metadata; /** * @brief Additional information from \c metadata which has been associated with \c UUID during * \c channel \c member \c add requests. */ @property (nonatomic, nullable, readonly, strong) NSDictionary *custom; /** * @brief \c Member data modification date. */ @property (nonatomic, readonly, strong) NSDate *updated; /** * @brief Identifier which is listed in \c channel's members list. */ @property (nonatomic, readonly, copy) NSString *uuid; /** * @brief \c Member object version identifier. */ @property (nonatomic, readonly, copy) NSString *eTag; #pragma mark - @end NS_ASSUME_NONNULL_END
#!/usr/bin/env python import os import yaml def actions_awstest(self): """Checks the GitHub Actions awstest is valid. In addition to small test datasets run on GitHub Actions, we provide the possibility of testing the pipeline on AWS. This should ensure that the pipeline runs as expected on AWS (which often has its own unique edge cases). .. warning:: Running tests on AWS incurs costs, so these tests are not triggered automatically. Instead, they use the ``workflow_dispatch`` trigger, which allows for manual triggering of the workflow when testing on AWS is desired. .. note:: You can trigger the tests by going to the `Actions` tab on the pipeline GitHub repository and selecting the `nf-core AWS test` workflow on the left. The ``.github/workflows/awstest.yml`` file is tested for the following: * Must *not* be turned on for ``push`` or ``pull_request``. * Must be turned on for ``workflow_dispatch``. """ fn = os.path.join(self.wf_path, ".github", "workflows", "awstest.yml") if not os.path.isfile(fn): return {"ignored": ["'awstest.yml' workflow not found: `{}`".format(fn)]} try: with open(fn, "r") as fh: wf = yaml.safe_load(fh) except Exception as e: return {"failed": ["Could not parse yaml file: {}, {}".format(fn, e)]} # Check that the action is only turned on for workflow_dispatch try: assert "workflow_dispatch" in wf[True] assert "push" not in wf[True] assert "pull_request" not in wf[True] except (AssertionError, KeyError, TypeError): return {"failed": ["'.github/workflows/awstest.yml' is not triggered correctly"]} else: return {"passed": ["'.github/workflows/awstest.yml' is triggered correctly"]}
n = int(input()) a = [int(i) for i in input()] u = [[] for i in range(10)] u[2] = [2] u[3] = [3] u[4] = [2, 2, 3] u[5] = [5] u[6] = [3, 5] u[7] = [7] u[8] = [2, 2, 2, 7] u[9] = [2, 3, 3, 7] c = [] for i in a: if i > 1: c += u[i] c.sort() c = list(map(str,reversed(c))) print(''.join(c))
def check_ssl(self, ssl, sslmode, monitor=False, primary=False): key = self.sslServerKey crt = self.sslServerCert crl = None rootCert = self.sslCAFile if self.sslSelfSigned: key = os.path.join(self.datadir, "server.key") crt = os.path.join(self.datadir, "server.crt") eq_(self.pg_config_get('ssl'), ssl) eq_(self.config_get("ssl.sslmode"), sslmode) expected_ciphers = ( "ECDHE-ECDSA-AES128-GCM-SHA256:" "ECDHE-ECDSA-AES256-GCM-SHA384:" "ECDHE-RSA-AES128-GCM-SHA256:" "ECDHE-RSA-AES256-GCM-SHA384:" "ECDHE-ECDSA-AES128-SHA256:" "ECDHE-ECDSA-AES256-SHA384:" "ECDHE-RSA-AES128-SHA256:" "ECDHE-RSA-AES256-SHA384" ) if not monitor: eq_(self.pg_config_get("ssl_ciphers"), expected_ciphers) def check_conn_string(conn_string): print("checking connstring =", conn_string) assert f"sslmode={sslmode}" in conn_string if rootCert: assert f"sslrootcert={rootCert}" in conn_string if crl: assert f"sslcrl={crl}" in conn_string monitor_uri = self.get_monitor_uri() self.check_conn_string_ssl(monitor_uri, sslmode) if not monitor: monitor_uri = self.config_get("pg_autoctl.monitor") self.check_conn_string_ssl(monitor_uri, sslmode) formation_uri = self.get_formation_uri() self.check_conn_string_ssl(formation_uri, sslmode) for pg_setting, autoctl_setting, file_path in [ ("ssl_key_file", "ssl.key_file", key), ("ssl_cert_file", "ssl.cert_file", crt), ("ssl_crl_file", "ssl.crl_file", crl), ("ssl_ca_file", "ssl.ca_file", rootCert)]: if file_path is None: continue assert os.path.isfile(file_path) print("checking", pg_setting) eq_(self.pg_config_get(pg_setting), file_path) eq_(self.config_get(autoctl_setting), file_path) if monitor or primary: return if self.pgmajor() >= 12: check_conn_string(self.pg_config_get('primary_conninfo'))
/// Create a new Metadata with the given brokers pub fn with_brokers(brokers: Vec<Broker>) -> Self { Metadata { brokers, topic_partitions: HashMap::new(), group_coordinators: HashMap::new(), } }
/** * The processor that takes care of user activation mapping to an account (outbound direction). * * @author Radovan Semancik */ @Component public class ActivationProcessor { private static final Trace LOGGER = TraceManager.getTrace(ActivationProcessor.class); private static final QName SHADOW_EXISTS_PROPERTY_NAME = new QName(SchemaConstants.NS_C, "shadowExists"); private static final QName LEGAL_PROPERTY_NAME = new QName(SchemaConstants.NS_C, "legal"); private static final QName ASSIGNED_PROPERTY_NAME = new QName(SchemaConstants.NS_C, "assigned"); private static final QName FOCUS_EXISTS_PROPERTY_NAME = new QName(SchemaConstants.NS_C, "focusExists"); @Autowired private ContextLoader contextLoader; @Autowired private PrismContext prismContext; @Autowired private MappingEvaluator mappingEvaluator; @Autowired private MidpointFunctions midpointFunctions; private PrismObjectDefinition<UserType> userDefinition; private PrismContainerDefinition<ActivationType> activationDefinition; public <O extends ObjectType, F extends FocusType> void processActivation(LensContext<O> context, LensProjectionContext projectionContext, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { LensFocusContext<O> focusContext = context.getFocusContext(); if (focusContext != null && !FocusType.class.isAssignableFrom(focusContext.getObjectTypeClass())) { // We can do this only for focal object. return; } processActivationFocal((LensContext<F>)context, projectionContext, now, task, result); } private <F extends FocusType> void processActivationFocal(LensContext<F> context, LensProjectionContext projectionContext, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { LensFocusContext<F> focusContext = context.getFocusContext(); if (focusContext == null) { processActivationMetadata(context, projectionContext, now, result); return; } try { processActivationUserCurrent(context, projectionContext, now, task, result); processActivationMetadata(context, projectionContext, now, result); processActivationUserFuture(context, projectionContext, now, task, result); } catch (ObjectNotFoundException e) { if (projectionContext.isThombstone()) { // This is not critical. The projection is marked as thombstone and we can go on with processing // No extra action is needed. } else { throw e; } } } public <F extends FocusType> void processActivationUserCurrent(LensContext<F> context, LensProjectionContext projCtx, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { String projCtxDesc = projCtx.toHumanReadableString(); SynchronizationPolicyDecision decision = projCtx.getSynchronizationPolicyDecision(); SynchronizationIntent synchronizationIntent = projCtx.getSynchronizationIntent(); if (decision == SynchronizationPolicyDecision.BROKEN) { LOGGER.trace("Broken projection {}, skipping further activation processing", projCtxDesc); return; } if (decision != null) { throw new IllegalStateException("Decision "+decision+" already present for projection "+projCtxDesc); } if (synchronizationIntent == SynchronizationIntent.UNLINK) { projCtx.setSynchronizationPolicyDecision(SynchronizationPolicyDecision.UNLINK); LOGGER.trace("Evaluated decision for {} to {} because of unlink synchronization intent, skipping further activation processing", projCtxDesc, SynchronizationPolicyDecision.UNLINK); return; } if (projCtx.isThombstone()) { if (shouldKeepThombstone(projCtx)) { // Let's keep thombstones linked until they expire. So we do not have shadows without owners. // This is also needed for async delete operations. projCtx.setSynchronizationPolicyDecision(SynchronizationPolicyDecision.KEEP); LOGGER.trace("Evaluated decision for {} to {} because it is thombstone, skipping further activation processing", projCtxDesc, SynchronizationPolicyDecision.KEEP); } else { projCtx.setSynchronizationPolicyDecision(SynchronizationPolicyDecision.UNLINK); LOGGER.trace("Evaluated decision for {} to {} because it is thombstone, skipping further activation processing", projCtxDesc, SynchronizationPolicyDecision.UNLINK); } return; } if (synchronizationIntent == SynchronizationIntent.DELETE || projCtx.isDelete()) { // TODO: is this OK? projCtx.setSynchronizationPolicyDecision(SynchronizationPolicyDecision.DELETE); LOGGER.trace("Evaluated decision for {} to {}, skipping further activation processing", projCtxDesc, SynchronizationPolicyDecision.DELETE); return; } boolean shadowShouldExist = evaluateExistenceMapping(context, projCtx, now, true, task, result); LOGGER.trace("Evaluated intended existence of projection {} to {}", projCtxDesc, shadowShouldExist); // Let's reconcile the existence intent (shadowShouldExist) and the synchronization intent in the context LensProjectionContext lowerOrderContext = LensUtil.findLowerOrderContext(context, projCtx); if (synchronizationIntent == null || synchronizationIntent == SynchronizationIntent.SYNCHRONIZE) { if (shadowShouldExist) { projCtx.setActive(true); if (projCtx.isExists()) { if (lowerOrderContext != null && lowerOrderContext.isDelete()) { // HACK HACK HACK decision = SynchronizationPolicyDecision.DELETE; } else { decision = SynchronizationPolicyDecision.KEEP; } } else { if (lowerOrderContext != null) { if (lowerOrderContext.isDelete()) { // HACK HACK HACK decision = SynchronizationPolicyDecision.DELETE; } else { // If there is a lower-order context then that one will be ADD // and this one is KEEP. When the execution comes to this context // then the projection already exists decision = SynchronizationPolicyDecision.KEEP; } } else { decision = SynchronizationPolicyDecision.ADD; } } } else { // Delete if (projCtx.isExists()) { decision = SynchronizationPolicyDecision.DELETE; } else { // we should delete the entire context, but then we will lost track of what // happened. So just ignore it. decision = SynchronizationPolicyDecision.IGNORE; // if there are any triggers then move them to focus. We may still need them. LensUtil.moveTriggers(projCtx, context.getFocusContext()); } } } else if (synchronizationIntent == SynchronizationIntent.ADD) { if (shadowShouldExist) { projCtx.setActive(true); if (projCtx.isExists()) { // Attempt to add something that is already there, but should be OK decision = SynchronizationPolicyDecision.KEEP; } else { decision = SynchronizationPolicyDecision.ADD; } } else { throw new PolicyViolationException("Request to add projection "+projCtxDesc+" but the activation policy decided that it should not exist"); } } else if (synchronizationIntent == SynchronizationIntent.KEEP) { if (shadowShouldExist) { projCtx.setActive(true); if (projCtx.isExists()) { decision = SynchronizationPolicyDecision.KEEP; } else { decision = SynchronizationPolicyDecision.ADD; } } else { throw new PolicyViolationException("Request to keep projection "+projCtxDesc+" but the activation policy decided that it should not exist"); } } else { throw new IllegalStateException("Unknown sync intent "+synchronizationIntent); } LOGGER.trace("Evaluated decision for projection {} to {}", projCtxDesc, decision); projCtx.setSynchronizationPolicyDecision(decision); PrismObject<F> focusNew = context.getFocusContext().getObjectNew(); if (focusNew == null) { // This must be a user delete or something similar. No point in proceeding LOGGER.trace("focusNew is null, skipping activation processing of {}", projCtxDesc); return; } if (decision == SynchronizationPolicyDecision.UNLINK || decision == SynchronizationPolicyDecision.DELETE) { LOGGER.trace("Decision is {}, skipping activation properties processing for {}", decision, projCtxDesc); return; } ResourceObjectTypeDefinitionType resourceAccountDefType = projCtx.getResourceObjectTypeDefinitionType(); if (resourceAccountDefType == null) { LOGGER.trace("No refined object definition, therefore also no activation outbound definition, skipping activation processing for account " + projCtxDesc); return; } ResourceActivationDefinitionType activationType = resourceAccountDefType.getActivation(); if (activationType == null) { LOGGER.trace("No activation definition in projection {}, skipping activation properties processing", projCtxDesc); return; } ActivationCapabilityType capActivation = ResourceTypeUtil.getEffectiveCapability(projCtx.getResource(), ActivationCapabilityType.class); if (capActivation == null) { LOGGER.trace("Skipping activation status and validity processing because {} has no activation capability", projCtx.getResource()); return; } ActivationStatusCapabilityType capStatus = CapabilityUtil.getEffectiveActivationStatus(capActivation); ActivationValidityCapabilityType capValidFrom = CapabilityUtil.getEffectiveActivationValidFrom(capActivation); ActivationValidityCapabilityType capValidTo = CapabilityUtil.getEffectiveActivationValidTo(capActivation); ActivationLockoutStatusCapabilityType capLockoutStatus = CapabilityUtil.getEffectiveActivationLockoutStatus(capActivation); if (capStatus != null) { evaluateActivationMapping(context, projCtx, activationType.getAdministrativeStatus(), SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, capActivation, now, true, ActivationType.F_ADMINISTRATIVE_STATUS.getLocalPart(), task, result); } else { LOGGER.trace("Skipping activation administrative status processing because {} does not have activation administrative status capability", projCtx.getResource()); } ResourceBidirectionalMappingType validFromMappingType = activationType.getValidFrom(); if (validFromMappingType == null || validFromMappingType.getOutbound() == null) { LOGGER.trace("Skipping activation validFrom processing because {} does not have appropriate outbound mapping", projCtx.getResource()); } else if (capValidFrom == null && !ExpressionUtil.hasExplicitTarget(validFromMappingType.getOutbound())) { LOGGER.trace("Skipping activation validFrom processing because {} does not have activation validFrom capability nor outbound mapping with explicit target", projCtx.getResource()); } else { evaluateActivationMapping(context, projCtx, activationType.getValidFrom(), SchemaConstants.PATH_ACTIVATION_VALID_FROM, SchemaConstants.PATH_ACTIVATION_VALID_FROM, null, now, true, ActivationType.F_VALID_FROM.getLocalPart(), task, result); } ResourceBidirectionalMappingType validToMappingType = activationType.getValidTo(); if (validToMappingType == null || validToMappingType.getOutbound() == null) { LOGGER.trace("Skipping activation validTo processing because {} does not have appropriate outbound mapping", projCtx.getResource()); } else if (capValidTo == null && !ExpressionUtil.hasExplicitTarget(validToMappingType.getOutbound())) { LOGGER.trace("Skipping activation validTo processing because {} does not have activation validTo capability nor outbound mapping with explicit target", projCtx.getResource()); } else { evaluateActivationMapping(context, projCtx, activationType.getValidTo(), SchemaConstants.PATH_ACTIVATION_VALID_TO, SchemaConstants.PATH_ACTIVATION_VALID_TO, null, now, true, ActivationType.F_VALID_TO.getLocalPart(), task, result); } if (capLockoutStatus != null) { evaluateActivationMapping(context, projCtx, activationType.getLockoutStatus(), SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, capActivation, now, true, ActivationType.F_LOCKOUT_STATUS.getLocalPart(), task, result); } else { LOGGER.trace("Skipping activation lockout status processing because {} does not have activation lockout status capability", projCtx.getResource()); } } private boolean shouldKeepThombstone(LensProjectionContext projCtx) { PrismObject<ShadowType> objectCurrent = projCtx.getObjectCurrent(); if (objectCurrent != null) { ShadowType objectCurrentType = objectCurrent.asObjectable(); if (!objectCurrentType.getPendingOperation().isEmpty()) { return true; } } // TODO: thombstone expiration return false; } public <F extends FocusType> void processActivationMetadata(LensContext<F> context, LensProjectionContext accCtx, XMLGregorianCalendar now, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { ObjectDelta<ShadowType> projDelta = accCtx.getDelta(); if (projDelta == null) { return; } PropertyDelta<ActivationStatusType> statusDelta = projDelta.findPropertyDelta(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); if (statusDelta != null && !statusDelta.isDelete()) { // we have to determine if the status really changed PrismObject<ShadowType> oldShadow = accCtx.getObjectOld(); ActivationStatusType statusOld = null; if (oldShadow != null && oldShadow.asObjectable().getActivation() != null) { statusOld = oldShadow.asObjectable().getActivation().getAdministrativeStatus(); } PrismProperty<ActivationStatusType> statusPropNew = (PrismProperty<ActivationStatusType>) statusDelta.getItemNewMatchingPath(null); ActivationStatusType statusNew = statusPropNew.getRealValue(); if (statusNew == statusOld) { LOGGER.trace("Administrative status not changed ({}), timestamp and/or reason will not be recorded", statusNew); } else { // timestamps PropertyDelta<XMLGregorianCalendar> timestampDelta = LensUtil.createActivationTimestampDelta(statusNew, now, getActivationDefinition(), OriginType.OUTBOUND); accCtx.swallowToSecondaryDelta(timestampDelta); // disableReason if (statusNew == ActivationStatusType.DISABLED) { PropertyDelta<String> disableReasonDelta = projDelta.findPropertyDelta(SchemaConstants.PATH_ACTIVATION_DISABLE_REASON); if (disableReasonDelta == null) { String disableReason = null; ObjectDelta<ShadowType> projPrimaryDelta = accCtx.getPrimaryDelta(); ObjectDelta<ShadowType> projSecondaryDelta = accCtx.getSecondaryDelta(); if (projPrimaryDelta != null && projPrimaryDelta.findPropertyDelta(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS) != null && (projSecondaryDelta == null || projSecondaryDelta.findPropertyDelta(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS) == null)) { disableReason = SchemaConstants.MODEL_DISABLE_REASON_EXPLICIT; } else if (accCtx.isLegal()) { disableReason = SchemaConstants.MODEL_DISABLE_REASON_MAPPED; } else { disableReason = SchemaConstants.MODEL_DISABLE_REASON_DEPROVISION; } PrismPropertyDefinition<String> disableReasonDef = activationDefinition.findPropertyDefinition(ActivationType.F_DISABLE_REASON); disableReasonDelta = disableReasonDef.createEmptyDelta(new ItemPath(FocusType.F_ACTIVATION, ActivationType.F_DISABLE_REASON)); disableReasonDelta.setValueToReplace(new PrismPropertyValue<>(disableReason, OriginType.OUTBOUND, null)); accCtx.swallowToSecondaryDelta(disableReasonDelta); } } } } } public <F extends FocusType> void processActivationUserFuture(LensContext<F> context, LensProjectionContext accCtx, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { String accCtxDesc = accCtx.toHumanReadableString(); SynchronizationPolicyDecision decision = accCtx.getSynchronizationPolicyDecision(); SynchronizationIntent synchronizationIntent = accCtx.getSynchronizationIntent(); if (accCtx.isThombstone() || decision == SynchronizationPolicyDecision.BROKEN || decision == SynchronizationPolicyDecision.IGNORE || decision == SynchronizationPolicyDecision.UNLINK || decision == SynchronizationPolicyDecision.DELETE) { return; } accCtx.recompute(); evaluateExistenceMapping(context, accCtx, now, false, task, result); PrismObject<F> focusNew = context.getFocusContext().getObjectNew(); if (focusNew == null) { // This must be a user delete or something similar. No point in proceeding LOGGER.trace("focusNew is null, skipping activation processing of {}", accCtxDesc); return; } ResourceObjectTypeDefinitionType resourceAccountDefType = accCtx.getResourceObjectTypeDefinitionType(); if (resourceAccountDefType == null) { return; } ResourceActivationDefinitionType activationType = resourceAccountDefType.getActivation(); if (activationType == null) { return; } ActivationCapabilityType capActivation = ResourceTypeUtil.getEffectiveCapability(accCtx.getResource(), ActivationCapabilityType.class); if (capActivation == null) { return; } ActivationStatusCapabilityType capStatus = CapabilityUtil.getEffectiveActivationStatus(capActivation); ActivationValidityCapabilityType capValidFrom = CapabilityUtil.getEffectiveActivationValidFrom(capActivation); ActivationValidityCapabilityType capValidTo = CapabilityUtil.getEffectiveActivationValidTo(capActivation); if (capStatus != null) { evaluateActivationMapping(context, accCtx, activationType.getAdministrativeStatus(), SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, capActivation, now, false, ActivationType.F_ADMINISTRATIVE_STATUS.getLocalPart(), task, result); } if (capValidFrom != null) { evaluateActivationMapping(context, accCtx, activationType.getAdministrativeStatus(), SchemaConstants.PATH_ACTIVATION_VALID_FROM, SchemaConstants.PATH_ACTIVATION_VALID_FROM, null, now, false, ActivationType.F_VALID_FROM.getLocalPart(), task, result); } if (capValidTo != null) { evaluateActivationMapping(context, accCtx, activationType.getAdministrativeStatus(), SchemaConstants.PATH_ACTIVATION_VALID_TO, SchemaConstants.PATH_ACTIVATION_VALID_TO, null, now, false, ActivationType.F_VALID_FROM.getLocalPart(), task, result); } } private <F extends FocusType> boolean evaluateExistenceMapping(final LensContext<F> context, final LensProjectionContext projCtx, final XMLGregorianCalendar now, final boolean current, Task task, final OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { final String projCtxDesc = projCtx.toHumanReadableString(); final Boolean legal = projCtx.isLegal(); if (legal == null) { throw new IllegalStateException("Null 'legal' for "+projCtxDesc); } LOGGER.trace("Evaluating intended existence of projection {}; legal={}", projCtxDesc, legal); ResourceObjectTypeDefinitionType resourceAccountDefType = projCtx.getResourceObjectTypeDefinitionType(); if (resourceAccountDefType == null) { return legal; } ResourceActivationDefinitionType activationType = resourceAccountDefType.getActivation(); if (activationType == null) { return legal; } ResourceBidirectionalMappingType existenceType = activationType.getExistence(); if (existenceType == null) { return legal; } List<MappingType> outbound = existenceType.getOutbound(); if (outbound == null || outbound.isEmpty()) { // "default mapping" return legal; } MappingEvaluatorParams<PrismPropertyValue<Boolean>, PrismPropertyDefinition<Boolean>, ShadowType, F> params = new MappingEvaluatorParams<>(); params.setMappingTypes(outbound); params.setMappingDesc("outbound existence mapping in projection " + projCtxDesc); params.setNow(now); params.setAPrioriTargetObject(projCtx.getObjectOld()); params.setEvaluateCurrent(current); params.setTargetContext(projCtx); params.setFixTarget(true); params.setContext(context); params.setInitializer(builder -> { // Source: legal ItemDeltaItem<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> legalSourceIdi = getLegalIdi(projCtx); Source<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> legalSource = new Source<>(legalSourceIdi, ExpressionConstants.VAR_LEGAL); builder.defaultSource(legalSource); // Source: assigned ItemDeltaItem<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> assignedIdi = getAssignedIdi(projCtx); Source<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> assignedSource = new Source<>(assignedIdi, ExpressionConstants.VAR_ASSIGNED); builder.addSource(assignedSource); // Source: focusExists ItemDeltaItem<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> focusExistsSourceIdi = getFocusExistsIdi(context.getFocusContext()); Source<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> focusExistsSource = new Source<>(focusExistsSourceIdi, ExpressionConstants.VAR_FOCUS_EXISTS); builder.addSource(focusExistsSource); // Variable: focus builder.addVariableDefinition(ExpressionConstants.VAR_FOCUS, context.getFocusContext().getObjectDeltaObject()); // Variable: user (for convenience, same as "focus") builder.addVariableDefinition(ExpressionConstants.VAR_USER, context.getFocusContext().getObjectDeltaObject()); // Variable: shadow builder.addVariableDefinition(ExpressionConstants.VAR_SHADOW, projCtx.getObjectDeltaObject()); // Variable: resource builder.addVariableDefinition(ExpressionConstants.VAR_RESOURCE, projCtx.getResource()); builder.originType(OriginType.OUTBOUND); builder.originObject(projCtx.getResource()); return builder; }); final MutableBoolean output = new MutableBoolean(false); params.setProcessor((mappingOutputPath,outputStruct) -> { PrismValueDeltaSetTriple<PrismPropertyValue<Boolean>> outputTriple = outputStruct.getOutputTriple(); if (outputTriple == null) { // The "default existence mapping" output.setValue(legal); return false; } Collection<PrismPropertyValue<Boolean>> nonNegativeValues = outputTriple.getNonNegativeValues(); // MID-3507: this is probably the bug. The processor is executed after every mapping. // The processing will die on the error if one mapping returns a value and the other mapping returns null // (e.g. because the condition is false). This should be fixed. if (nonNegativeValues == null || nonNegativeValues.isEmpty()) { throw new ExpressionEvaluationException("Activation existence expression resulted in null or empty value for projection " + projCtxDesc); } if (nonNegativeValues.size() > 1) { throw new ExpressionEvaluationException("Activation existence expression resulted in too many values ("+nonNegativeValues.size()+") for projection " + projCtxDesc); } output.setValue(nonNegativeValues.iterator().next().getValue()); return false; }); PrismPropertyDefinitionImpl<Boolean> shadowExistsDef = new PrismPropertyDefinitionImpl<>( SHADOW_EXISTS_PROPERTY_NAME, DOMUtil.XSD_BOOLEAN, prismContext); shadowExistsDef.setMinOccurs(1); shadowExistsDef.setMaxOccurs(1); params.setTargetItemDefinition(shadowExistsDef); mappingEvaluator.evaluateMappingSetProjection(params, task, result); return (boolean) output.getValue(); } private <T, F extends FocusType> void evaluateActivationMapping(final LensContext<F> context, final LensProjectionContext projCtx, ResourceBidirectionalMappingType bidirectionalMappingType, final ItemPath focusPropertyPath, final ItemPath projectionPropertyPath, final ActivationCapabilityType capActivation, XMLGregorianCalendar now, final boolean current, String desc, final Task task, final OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { MappingInitializer<PrismPropertyValue<T>,PrismPropertyDefinition<T>> initializer = builder -> { // Source: administrativeStatus, validFrom or validTo ItemDeltaItem<PrismPropertyValue<T>,PrismPropertyDefinition<T>> sourceIdi = context.getFocusContext().getObjectDeltaObject().findIdi(focusPropertyPath); if (capActivation != null && focusPropertyPath.equals(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS)) { ActivationValidityCapabilityType capValidFrom = CapabilityUtil.getEffectiveActivationValidFrom(capActivation); ActivationValidityCapabilityType capValidTo = CapabilityUtil.getEffectiveActivationValidTo(capActivation); // Source: computedShadowStatus ItemDeltaItem<PrismPropertyValue<ActivationStatusType>,PrismPropertyDefinition<ActivationStatusType>> computedIdi; if (capValidFrom != null && capValidTo != null) { // "Native" validFrom and validTo, directly use administrativeStatus computedIdi = context.getFocusContext().getObjectDeltaObject().findIdi(focusPropertyPath); } else { // Simulate validFrom and validTo using effectiveStatus computedIdi = context.getFocusContext().getObjectDeltaObject().findIdi(SchemaConstants.PATH_ACTIVATION_EFFECTIVE_STATUS); } Source<PrismPropertyValue<ActivationStatusType>,PrismPropertyDefinition<ActivationStatusType>> computedSource = new Source<>(computedIdi, ExpressionConstants.VAR_INPUT); builder.defaultSource(computedSource); Source<PrismPropertyValue<T>,PrismPropertyDefinition<T>> source = new Source<>(sourceIdi, ExpressionConstants.VAR_ADMINISTRATIVE_STATUS); builder.addSource(source); } else { Source<PrismPropertyValue<T>,PrismPropertyDefinition<T>> source = new Source<>(sourceIdi, ExpressionConstants.VAR_INPUT); builder.defaultSource(source); } // Source: legal ItemDeltaItem<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> legalIdi = getLegalIdi(projCtx); Source<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> legalSource = new Source<>(legalIdi, ExpressionConstants.VAR_LEGAL); builder.addSource(legalSource); // Source: assigned ItemDeltaItem<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> assignedIdi = getAssignedIdi(projCtx); Source<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> assignedSource = new Source<>(assignedIdi, ExpressionConstants.VAR_ASSIGNED); builder.addSource(assignedSource); // Source: focusExists ItemDeltaItem<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> focusExistsSourceIdi = getFocusExistsIdi(context.getFocusContext()); Source<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> focusExistsSource = new Source<>(focusExistsSourceIdi, ExpressionConstants.VAR_FOCUS_EXISTS); builder.addSource(focusExistsSource); return builder; }; evaluateOutboundMapping(context, projCtx, bidirectionalMappingType, focusPropertyPath, projectionPropertyPath, initializer, now, current, desc + " outbound activation mapping", task, result); } private <T, F extends FocusType> void evaluateOutboundMapping(final LensContext<F> context, final LensProjectionContext projCtx, ResourceBidirectionalMappingType bidirectionalMappingType, final ItemPath focusPropertyPath, final ItemPath projectionPropertyPath, final MappingInitializer<PrismPropertyValue<T>,PrismPropertyDefinition<T>> initializer, XMLGregorianCalendar now, final boolean evaluateCurrent, String desc, final Task task, final OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { if (bidirectionalMappingType == null) { LOGGER.trace("No '{}' definition in projection {}, skipping", desc, projCtx.toHumanReadableString()); return; } List<MappingType> outboundMappingTypes = bidirectionalMappingType.getOutbound(); if (outboundMappingTypes == null || outboundMappingTypes.isEmpty()) { LOGGER.trace("No outbound definition in '{}' definition in projection {}, skipping", desc, projCtx.toHumanReadableString()); return; } String projCtxDesc = projCtx.toHumanReadableString(); PrismObject<ShadowType> shadowNew = projCtx.getObjectNew(); MappingInitializer<PrismPropertyValue<T>,PrismPropertyDefinition<T>> internalInitializer = builder -> { builder.addVariableDefinitions(Utils.getDefaultExpressionVariables(context, projCtx).getMap()); builder.originType(OriginType.OUTBOUND); builder.originObject(projCtx.getResource()); initializer.initialize(builder); return builder; }; MappingEvaluatorParams<PrismPropertyValue<T>, PrismPropertyDefinition<T>, ShadowType, F> params = new MappingEvaluatorParams<>(); params.setMappingTypes(outboundMappingTypes); params.setMappingDesc(desc + " in projection " + projCtxDesc); params.setNow(now); params.setInitializer(internalInitializer); params.setTargetLoader(new ProjectionMappingLoader<>(context, projCtx, contextLoader)); params.setAPrioriTargetObject(shadowNew); params.setAPrioriTargetDelta(LensUtil.findAPrioriDelta(context, projCtx)); if (context.getFocusContext() != null) { params.setSourceContext(context.getFocusContext().getObjectDeltaObject()); } params.setTargetContext(projCtx); params.setDefaultTargetItemPath(projectionPropertyPath); params.setEvaluateCurrent(evaluateCurrent); params.setEvaluateWeak(true); params.setContext(context); params.setHasFullTargetObject(projCtx.hasFullShadow()); Map<ItemPath, MappingOutputStruct<PrismPropertyValue<T>>> outputTripleMap = mappingEvaluator.evaluateMappingSetProjection(params, task, result); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Mapping processing output after {}:\n{}", desc, DebugUtil.debugDump(outputTripleMap, 1)); } if (projCtx.isDoReconciliation()) { reconcileOutboundValue(context, projCtx, outputTripleMap, desc); } } /** * TODO: can we align this with ReconciliationProcessor? */ private <T, F extends FocusType> void reconcileOutboundValue(LensContext<F> context, LensProjectionContext projCtx, Map<ItemPath, MappingOutputStruct<PrismPropertyValue<T>>> outputTripleMap, String desc) throws SchemaException { // TODO: check for full shadow? for (Entry<ItemPath,MappingOutputStruct<PrismPropertyValue<T>>> entry: outputTripleMap.entrySet()) { ItemPath mappingOutputPath = entry.getKey(); MappingOutputStruct<PrismPropertyValue<T>> mappingOutputStruct = entry.getValue(); if (mappingOutputStruct.isWeakMappingWasUsed()) { // Thing to do. All deltas should already be in context LOGGER.trace("Skip reconciliation of {} in {} because of weak", mappingOutputPath, desc); continue; } if (!mappingOutputStruct.isStrongMappingWasUsed()) { // Normal mappings are not processed for reconciliation LOGGER.trace("Skip reconciliation of {} in {} because not strong", mappingOutputPath, desc); continue; } LOGGER.trace("reconciliation of {} for {}", mappingOutputPath, desc); PrismObjectDefinition<ShadowType> targetObjectDefinition = projCtx.getObjectDefinition(); PrismPropertyDefinition<T> targetItemDefinition = targetObjectDefinition.findPropertyDefinition(mappingOutputPath); if (targetItemDefinition == null) { throw new SchemaException("No definition for item "+mappingOutputPath+" in "+targetObjectDefinition); } PropertyDelta<T> targetItemDelta = targetItemDefinition.createEmptyDelta(mappingOutputPath); PrismValueDeltaSetTriple<PrismPropertyValue<T>> outputTriple = mappingOutputStruct.getOutputTriple(); PrismProperty<T> currentTargetItem = null; PrismObject<ShadowType> shadowCurrent = projCtx.getObjectCurrent(); if (shadowCurrent != null) { currentTargetItem = shadowCurrent.findProperty(mappingOutputPath); } Collection<PrismPropertyValue<T>> hasValues = new ArrayList<>(); if (currentTargetItem != null) { hasValues.addAll(currentTargetItem.getValues()); } Collection<PrismPropertyValue<T>> shouldHaveValues = outputTriple.getNonNegativeValues(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Reconciliation of {}:\n hasValues:\n{}\n shouldHaveValues\n{}", mappingOutputPath, DebugUtil.debugDump(hasValues, 2), DebugUtil.debugDump(shouldHaveValues, 2)); } for (PrismPropertyValue<T> shouldHaveValue: shouldHaveValues) { if (!PrismPropertyValue.containsRealValue(hasValues, shouldHaveValue)) { if (targetItemDefinition.isSingleValue()) { targetItemDelta.setValueToReplace(shouldHaveValue.clone()); } else { targetItemDelta.addValueToAdd(shouldHaveValue.clone()); } } } if (targetItemDefinition.isSingleValue()) { if (!targetItemDelta.isReplace() && shouldHaveValues.isEmpty()) { targetItemDelta.setValueToReplace(); } } else { for (PrismPropertyValue<T> hasValue: hasValues) { if (!PrismPropertyValue.containsRealValue(shouldHaveValues, hasValue)) { targetItemDelta.addValueToDelete(hasValue.clone()); } } } if (!targetItemDelta.isEmpty()) { LOGGER.trace("Reconciliation delta:\n{}", targetItemDelta.debugDumpLazily(1)); projCtx.swallowToSecondaryDelta(targetItemDelta); } } } private ItemDeltaItem<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> getLegalIdi(LensProjectionContext accCtx) throws SchemaException { Boolean legal = accCtx.isLegal(); Boolean legalOld = accCtx.isLegalOld(); return createBooleanIdi(LEGAL_PROPERTY_NAME, legalOld, legal); } @NotNull private ItemDeltaItem<PrismPropertyValue<Boolean>, PrismPropertyDefinition<Boolean>> createBooleanIdi( QName propertyName, Boolean old, Boolean current) throws SchemaException { PrismPropertyDefinitionImpl<Boolean> definition = new PrismPropertyDefinitionImpl<>(propertyName, DOMUtil.XSD_BOOLEAN, prismContext); definition.setMinOccurs(1); definition.setMaxOccurs(1); PrismProperty<Boolean> property = definition.instantiate(); property.add(new PrismPropertyValue<>(current)); if (current == old) { return new ItemDeltaItem<>(property); } else { PrismProperty<Boolean> propertyOld = property.clone(); propertyOld.setRealValue(old); PropertyDelta<Boolean> delta = propertyOld.createDelta(); delta.setValuesToReplace(new PrismPropertyValue<>(current)); return new ItemDeltaItem<>(propertyOld, delta, property); } } private ItemDeltaItem<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> getAssignedIdi(LensProjectionContext accCtx) throws SchemaException { Boolean assigned = accCtx.isAssigned(); Boolean assignedOld = accCtx.isAssignedOld(); return createBooleanIdi(ASSIGNED_PROPERTY_NAME, assignedOld, assigned); } private <F extends ObjectType> ItemDeltaItem<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> getFocusExistsIdi( LensFocusContext<F> lensFocusContext) throws SchemaException { Boolean existsOld = null; Boolean existsNew = null; if (lensFocusContext != null) { if (lensFocusContext.isDelete()) { existsOld = true; existsNew = false; } else if (lensFocusContext.isAdd()) { existsOld = false; existsNew = true; } else { existsOld = true; existsNew = true; } } PrismPropertyDefinitionImpl<Boolean> existsDef = new PrismPropertyDefinitionImpl<>(FOCUS_EXISTS_PROPERTY_NAME, DOMUtil.XSD_BOOLEAN, prismContext); existsDef.setMinOccurs(1); existsDef.setMaxOccurs(1); PrismProperty<Boolean> existsProp = existsDef.instantiate(); existsProp.add(new PrismPropertyValue<>(existsNew)); if (existsOld == existsNew) { return new ItemDeltaItem<>(existsProp); } else { PrismProperty<Boolean> existsPropOld = existsProp.clone(); existsPropOld.setRealValue(existsOld); PropertyDelta<Boolean> existsDelta = existsPropOld.createDelta(); existsDelta.setValuesToReplace(new PrismPropertyValue<>(existsNew)); return new ItemDeltaItem<>(existsPropOld, existsDelta, existsProp); } } @SuppressWarnings({ "unchecked", "rawtypes" }) public <O extends ObjectType> void processLifecycle(LensContext<O> context, LensProjectionContext projCtx, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { LensFocusContext<O> focusContext = context.getFocusContext(); if (focusContext != null && !FocusType.class.isAssignableFrom(focusContext.getObjectTypeClass())) { // We can do this only for focal object. LOGGER.trace("Skipping lifecycle evaluation because focus is not FocusType"); return; } processLifecycleFocus((LensContext)context, projCtx, now, task, result); } private <F extends FocusType> void processLifecycleFocus(LensContext<F> context, LensProjectionContext projCtx, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { LensFocusContext<F> focusContext = context.getFocusContext(); if (focusContext == null) { LOGGER.trace("Skipping lifecycle evaluation because there is no focus"); return; } ResourceObjectLifecycleDefinitionType lifecycleDef = null; ResourceObjectTypeDefinitionType resourceAccountDefType = projCtx.getResourceObjectTypeDefinitionType(); if (resourceAccountDefType != null) { lifecycleDef = resourceAccountDefType.getLifecycle(); } ResourceBidirectionalMappingType lifecycleStateMappingType = null; if (lifecycleDef != null) { lifecycleStateMappingType = lifecycleDef.getLifecycleState(); } if (lifecycleStateMappingType == null || lifecycleStateMappingType.getOutbound() == null) { if (!projCtx.isAdd()) { LOGGER.trace("Skipping lifecycle evaluation because this is not add operation (default expression)"); return; } PrismObject<F> focusNew = focusContext.getObjectNew(); if (focusNew == null) { LOGGER.trace("Skipping lifecycle evaluation because there is no new focus (default expression)"); return; } PrismObject<ShadowType> projectionNew = projCtx.getObjectNew(); if (projectionNew == null) { LOGGER.trace("Skipping lifecycle evaluation because there is no new projection (default expression)"); return; } String lifecycle = midpointFunctions.computeProjectionLifecycle( focusNew.asObjectable(), projectionNew.asObjectable(), projCtx.getResource()); LOGGER.trace("Computed projection lifecycle (default expression): {}", lifecycle); if (lifecycle != null) { PrismPropertyDefinition<String> propDef = projCtx.getObjectDefinition().findPropertyDefinition(SchemaConstants.PATH_LIFECYCLE_STATE); PropertyDelta<String> lifeCycleDelta = propDef.createEmptyDelta(SchemaConstants.PATH_LIFECYCLE_STATE); PrismPropertyValue<String> pval = new PrismPropertyValue<>(lifecycle); pval.setOriginType(OriginType.OUTBOUND); lifeCycleDelta.setValuesToReplace(pval); projCtx.swallowToSecondaryDelta(lifeCycleDelta); } } else { LOGGER.trace("Computing projection lifecycle (mapping): {}", lifecycleStateMappingType); evaluateActivationMapping(context, projCtx, lifecycleStateMappingType, SchemaConstants.PATH_LIFECYCLE_STATE, SchemaConstants.PATH_LIFECYCLE_STATE, null, now, true, ObjectType.F_LIFECYCLE_STATE.getLocalPart(), task, result); } } private PrismObjectDefinition<UserType> getUserDefinition() { if (userDefinition == null) { userDefinition = prismContext.getSchemaRegistry() .findObjectDefinitionByCompileTimeClass(UserType.class); } return userDefinition; } private PrismContainerDefinition<ActivationType> getActivationDefinition() { if (activationDefinition == null) { PrismObjectDefinition<UserType> userDefinition = getUserDefinition(); activationDefinition = userDefinition.findContainerDefinition(UserType.F_ACTIVATION); } return activationDefinition; } }
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String []args)throws IOException { PrintWriter pw=new PrintWriter(new BufferedOutputStream(System.out)); BufferedReader var=new BufferedReader(new InputStreamReader(System.in)); String line=var.readLine(); StringTokenizer token=new StringTokenizer(line); int n=Integer.parseInt(token.nextToken()); int m=Integer.parseInt(token.nextToken()); line=var.readLine(); StringTokenizer token2=new StringTokenizer(line); int arr[]=new int[n]; int p=0,neg=0; for(int c=0;c<n;c++) { arr[c]=Integer.parseInt(token2.nextToken()); if(arr[c]>0) p++; else neg++; } int r=0,l=0,aux=0,pos; for(int i=0;i<m;i++) { aux=0; line=var.readLine(); StringTokenizer token3=new StringTokenizer(line); r=Integer.parseInt(token3.nextToken()); l=Integer.parseInt(token3.nextToken()); if(r==l) pw.println("0"); else { pos=(Math.abs(r-l)+1); if(pos%2!=0) pw.println("0"); else { //for(int j=(r-1);j<l;j++) //aux+=arr[j]; // if(aux>0) //{ if((pos/2)<=neg && (pos/2)<=p) pw.println("1"); else pw.println("0"); //} /* else { if((pos/2)<=p) pw.println("1"); else pw.println("0"); } */ } } } pw.close(); } }
<filename>app/src/main/java/com/codepath/apps/dwitter/fragments/TweetsListFragment.java package com.codepath.apps.dwitter.fragments; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.codepath.apps.dwitter.R; import com.codepath.apps.dwitter.TweetsArrayAdapter; import com.codepath.apps.dwitter.models.EndlessScrollListener; import com.codepath.apps.dwitter.models.Tweet; import java.util.ArrayList; import java.util.List; /** * Created by lee on 8/10/16. */ public abstract class TweetsListFragment extends Fragment { private ArrayList<Tweet> tweets; private TweetsArrayAdapter aTweets; private SwipeRefreshLayout swipeContainer; private final int REQUEST_CODE = 20; // private RecyclerView rvTweets; ListView lvTweets; MenuItem miActionProgressItem; private OnItemSelectedListener listener; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //create arraylist (data source) tweets = new ArrayList<>(); //construct the adapter from data source aTweets = new TweetsArrayAdapter(getActivity(), tweets); } // @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup parent, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_tweets_list, parent, false); lvTweets = (ListView) v.findViewById(R.id.lvTweets); // //connect adapter to list view lvTweets.setAdapter(aTweets); // rvTweets = (RecyclerView) v.findViewById(R.id.rvTweets); // LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()); // rvTweets.setLayoutManager(linearLayoutManager); // // rvTweets.setAdapter(aTweets); // swipeContainer = (SwipeRefreshLayout) v.findViewById(R.id.swipeContainer); // setupEndlessScroll(linearLayoutManager); lvTweets.setOnScrollListener(new EndlessScrollListener() { @Override public boolean onLoadMore(int page, int totalItemsCount) { populateTimeline(page); return true; // ONLY if more data is actually being loaded; false otherwise. } }); // setupSwipeRefresh(); return v; } public void addAll(List<Tweet> tweets) { aTweets.addAll(tweets); } public void add(Tweet tweet) { aTweets.insert(tweet, 0); aTweets.notifyDataSetChanged(); } protected abstract void populateTimeline(int page); // public void setupSwipeRefresh() { // swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { // @Override // public void onRefresh() { // tweets.clear(); // aTweets.notifyDataSetChanged(); // Tweet.resetMaxId(); // populateTimeline(); // swipeContainer.setRefreshing(false); // } // }); // // swipeContainer.setColorSchemeResources(R.color.colorPrimary, // android.R.color.holo_green_light, // android.R.color.holo_orange_light, // android.R.color.holo_red_light); // } // // public void setupEndlessScroll(LinearLayoutManager linearLayoutManager) { // rvTweets.addOnScrollListener(new EndlessRecyclerViewScrollListener(linearLayoutManager) { // @Override // public void onLoadMore(int page, int totalItemsCount) { // populateTimeline(); // } // }); // } // public Boolean isNetworkAvailable() { // ConnectivityManager connectivityManager // = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); // return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting(); // } // // public boolean isOnline() { // Runtime runtime = Runtime.getRuntime(); // try { // Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); // int exitValue = ipProcess.waitFor(); // return (exitValue == 0); // } catch (IOException e) { // e.printStackTrace(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // return false; // } // public TweetsArrayAdapter getAdapter() { // return aTweets; // } // // Define the events that the fragment will use to communicate public interface OnItemSelectedListener { public void showProgressBar(); public void hideProgressBar(); } // Store the listener (activity) that will have events fired once the fragment is attached @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnItemSelectedListener) { listener = (OnItemSelectedListener) context; } else { throw new ClassCastException(context.toString() + " must implement MyListFragment.OnItemSelectedListener"); } } // Now we can fire the event when the user selects something in the fragment public void showProgressBar() { listener.showProgressBar(); } public void hideProgressBar() { listener.hideProgressBar(); } }
/// Receives the next incoming message and returns the message's content /// (i.e., without the message size and without the HMAC tag) if the /// message's HMAC tag is correct. Otherwise returns `SecureServerError`. pub fn recv_message(&mut self) -> Result<Vec<u8>, SecureServerError> { let mut sizebytes: [u8; 4] = [0; 4]; self.server.read_exact(sizebytes.as_mut()).unwrap(); let size: u32 = u32::from_be_bytes(sizebytes); let mut data: Vec<u8> = vec![0; size.try_into().unwrap()]; self.server.read_exact(data.as_mut()).unwrap(); let mut tag: [u8; 32] = [0; 32]; self.server.read_exact(tag.as_mut()).unwrap(); let mut mac = HmacSha256::new_from_slice(&self.hmac_key).unwrap(); mac.update(&data); if !mac.verify(&tag).is_ok() { return Err(SecureServerError::InvalidHmac); } return Ok(data); }
This has been the most difficult season of Baltimore Ravens quarterback Joe Flacco's six-year career. His 14 interceptions are a career high. His 78.5 passer rating is a career worst. And his dislike of the Wildcat offense caused a backlash from fans. But, as Flacco has so often repeated, it's all about wins with him and he's on the verge of distinguishing himself in that area. If Flacco beats the Minnesota Vikings on Sunday, he will have the most wins by a Super Bowl-era quarterback through his first six seasons. Flacco currently has 60 wins in the regular season, which is tied with the total produced by Pittsburgh Steelers quarterback Ben Roethlisberger from 2004 to 2009. Here are some other significant win totals for Flacco: His 60 regular season wins rank only behind Drew Brees (61) for the most by a starting quarterback since 2008. Flacco has 38 career regular season wins at home, the most among NFL starting quarterbacks since he entered the league in 2008. His nine playoff victories are tied with Tom Brady for the most among quarterbacks in the first five seasons of a career. “I think he’s just continued to grow over the course of his career," Vikings defensive end Jared Allen said in a conference call with Baltimore reporters. "He’s always been, in my opinion, a top-level quarterback, with his pocket presence, his timing to get the ball out, and the ability to throw the deep ball. He’s obviously continued to grow to put himself in that elite quarterback category.”
Natural cytotoxicity of human blood monocytes and natural killer cells and their cytotoxic factors: Discriminating effects of actinomycin D The effect of actinomycin D on target susceptibility to human blood natural killer (NK) cells and monocytes was analysed in direct cell‐mediated and their cytotoxic factor‐mediated cytotoxicity assays. Treatment of K562 cells with actinomycin D reduced their susceptibility to lysis by non‐adherent lymphocytes and Percoll‐purified large granular lymphocytes (LGL) in a 4‐hr 51Cr‐release assay, without affecting their sensitivity to monocytes purified by adherence to autologous serum‐coated plastic surfaces. The drug treatment caused no shift in the kinetics of cytotoxicity. In the target binding assay LGL formed fewer conjugates with actinomycin‐D‐treated K562 cells than with untreated ones, while the binding of monocytes to targets was not reduced by the drug treatment of K562 cells. The cold target competition assay revealed that actinomycin‐D‐treated cold K562 cells showed less successful inhibition than untreated cold K562 cells. Lymphocytes and monocytes could be induced to release soluble cytotoxic factors, termed natural killer cytotoxic factors (NKCF) and monocyte cytotoxic factors (MCF), respectively, when co‐cultured with K562 cells. Both cytotoxic factors lysed NK‐sensitive target cells in a 48‐hr assay. Actinomycin‐D‐treated K562 cells reduced or abolished the ability to stimulate the release of NKCF from lymphocytes, whereas they induced MCF secretion from monocytes as effectively as untreated ones. On the other hand, actinomycin D treatment of K562 cells enhanced their susceptibility to NKCF and MCF. This actinomycin‐D‐induced augmentation of target sensitivity to the cytotoxic factors was restricted to NK‐sensitive target cells (K562 and Molt‐4). NK‐resistant target cells (Raji, YAC‐I, EL4 and T blasts) were not lysed by NKCF and MCF even after they were treated with actinomycin D. The capacity of K562 cells to bind NKCF and MCF was not altered by actinomycin D. Treatment of the adherent cell population with OKMI or Leu‐MI plus complement abrogated both cell‐mediated cytotoxicity and MCF production, while Leu‐11b plus complement was ineffective. These results suggest that the effect of actinomycin‐D treatment can be used to distinguish the two distinct types of blood mononuclear cells with natural cytotoxicity, NK cells and monocytes, and that each effector type recognizes different plasma membrane moieties of NK target cells, although the cytotoxic factors released from each effector cell similarly bind to and lyse the target cells.
Occupational Noise Induced Hearing Loss in India: A Systematic Review and Meta-Analysis Background: India has over 50 million workers employed in industries with exposure to very high sound levels, predisposing them to noise-induced hearing loss (NIHL). Methods: We conducted a systematic review and meta-analysis by using the following criteria: (1) Observational or experimental studies conducted in India; (2) English language studies; (3) Published during January 2010–December 2019; (4) Primary outcome: proportion of participants detected with NIHL. We reviewed bibliographic databases (PubMed, Scopus, and DOAJ) and Google Scholar, and extracted the relevant data. Results: A total of 160 documents were identified after removing duplicates, and 33 full texts were screened, of which 22 studies were included. The mean (SD) effective sample size of the studies was 107.1 (78.9). The pooled proportion of participants with NIHL irrespective of the category was 0.49 (95%CI: 0.22–0.76) and that of hearing loss was 0.53 (95%CI: 0.28– 0.78). Most studies reported that none of the workers, especially in the informal sectors, used auditory protection. Conclusions: NIHL is a major neglected public health occupational health challenge in India linked with adverse social determinants of health. Sustained advocacy for implementation of legislative and behavior change communication for protecting the hearing of workers is warranted. although it recognizes NIHL as a notifiable disease. A maximum of 90 dB (A) for 8 h continuous noise exposure is the limit recommended by the Directorate General of Factories Advisory Services and Labor Institutes. However, several industries especially concentrated in the developing world, including India, providing employment to millions of workers routinely exceed this 90-dB (A) limit, such as the textile (woolen and jute mills), woodworker, marble, ceramic, and other industries. The objective of this study was to ascertain the burden and determinants of occupational NIHL in workers potentially exposed to hazardous noise levels at the workplace in Indian industries. Search strategy and selection criteria We conducted a systematic review and meta-analysis using the following criteria: (1) Observational or experimental studies conducted in India; (2) English language studies; (3) Published during January 2010-December 2019; (4) Primary outcome was the proportion of participants detected with NIHL. The protocol was prospectively registered with PROSPERO (CRD42020165221). Review approach We used the following search terms "Noise-induced hearing loss" (MeSH and entry terms), "Hearing loss" (MeSH and entry terms), "occupational health" ((MeSH and entry terms), "workers" (MeSH and entry terms), and "India" in specific combinations. A total of 57 PubMed/Medline records, 181 Scopus records, and 17 DOAJ records were identified, which were imported into Mendeley reference management software, following which the duplicate records were removed. All the titles were then subjected to abstract screening. Our inclusion criterion was original research with the objective of detecting occupational hearing loss in any workers. Studies were included if their abstracts reported methods or results relating to NIHL or hearing loss in people employed in any specific occupation . We included observational studies only with no restrictions by age, gender, and sexual identity of the participants. Using a predesigned data extraction form, two reviewers extracted data from the selected articles independently, and any disagreements were resolved by consensus. Data extraction Information on the sociodemographic population characteristics, namely age, gender, the name of the first author, year of publication, study design, study period, type of industry, sample size, application of audiometry and/or BERA, prevalence of NIHL, prevalence of hearing loss and its categorization (into mild, moderate, and severe categories), use of protective hearing equipment (PPE), and factors associated with hearing loss. The primary outcome measure was the proportion of participants detected with NIHL. The risk of bias (quality) assessment was assessed using a modified Joanna Briggs Institute (JBI) appraisal checklist for studies reporting prevalence data (https://joannabriggs.org/sites/default/ files/2019-05/JBI_Critical_Appraisal-Checklist_for_ Prevalence_Studies2017_0.pdf). Statistical analysis: The extracted data were entered and analyzed in IBM SPSS Version 25. Meta-analysis was conducted using the "Metaprop_one" function in STATA-14. As there was significant heterogeneity between the studies, the random-effects model was used to calculate the pooled estimates for measuring the prevalence of NIHL and HL. The pooled estimate was expressed as proportions with 95% confidence intervals. Identification of studies A total of 160 documents were identified after removing duplicates, and 33 full texts were screened, of which 21 studies were included in the meta-analysis . Characteristics of included studies The mean (SD) effective sample size of the studies was 106.1 (80.5). The mean (SD) age of the participants in the included studies was 36.1 (5.1). The studies were conducted among workers in the following industries: stone cutting, ginning, plywood, heavy metal, farming, mining, explosive, sugarcane, steel, handicraft, and plastic weaving. All the studies employed a cross-sectional design. A control group was recruited in eight (38.1%) studies. Prolonged duration of exposure was the most common risk factor for NIHL. Most studies reported none of the workers using any auditory protection. Interestingly, a study among steel industry workers, a formal industry, by Singh et al. (2013) reported the workers avoiding the use of ear protectors primarily due to lack of comfort from failure of ergonomic fit and the reduction of annoyance from the workplace noise due to its acceptance and shifting of the hearing threshold leading to adaption to the high noise levels in their workplace environment. The study by Biswas and Kumar found that nearly half the workers engaged in activities involving hammering metal, welding, wood joinery, sawmilling, and grain grinding had audiogram patterns typical of NIHL. The study by Lokhande in Goa observed notched hearing loss in 6% of the exposed workers in a ship-building industry but none in the age-and sex-matched office controls. The study among cotton ginning workers by Dube et al. observed exposure to continuous noise levels of 89-106 dBA, with binaural hearing impairment present in 86% of the workers. Bilateral and symmetrical hearing loss in traffic policemen with chronic noise exposure was reported in the study by Indora et al. The study by Tikriwal et al. among carpet workers observed a high prevalence of both tinnitus and hearing loss, with increasing prevalence associated with the greater severity of hearing loss. Several studies reported a positive correlation between duration of hazardous noise exposure in the workplace and the degree of hearing loss in the workers. Were study participants sampled in an appropriate way? Was the sample size adequate? Were the study subjects and the setting described in detail? Was the data analysis conducted with sufficient coverage of the identified sample? Were valid methods used for the identification of the condition? Was the condition measured in a standard, reliable way for all participants? Was there appropriate statistical analysis? Was the response rate adequate, and if not, was the low response rate managed appropriately? Yes No Unclear Not Applicable Limitations of existing studies Only a solitary study with a small sample size was conducted in construction and welding workers who are at high risk of occupational NIHL, and being mostly informal contractual workers may lack comprehensive health protection and largely being outside the purview of implementable protective regulatory legislation. Similarly, few studies have been conducted on workers in the mining and textile industries, which provide employment to millions of workers and expose their workers to a high risk of NIHL. Less than half of the studies used pure-tone audiometry for assessing hearing function in the workers, while only a single study with a small sample size used the brainstem evoked response audiometry (BERA) method to also evaluate the auditory pathway affection. The advantage of BERA is the ability to objective assess whether the central or peripheral component of the auditory pathway is involved in individuals with NIHL. Binoaural hearing impairment assessment was lacking in most studies. Similarly, future studies should also assess speech reception to assess those cases when pure-tone audiometry is normal but the individual cannot comprehend speech. Symptoms such as tinnitus and vertigo associated with hearing loss, which can affect quality of life of the affected workers, were not assessed in most studies. This systematic review has certain limitations. The risk of NIHL is linked to the intensity and duration of occupational sound exposure; thus, the aggregate pooled prevalence of occupational NIHL estimated from studies including divergent occupational profiles can be subject to selection bias. Searches were conducted only in standardized databases; thus, research published in gray literature may have been inadvertently omitted. Implications for future research India's National Program for Prevention and Control of Deafness (NPPCD) was initiated in 2007 with the long-term objective of preventing and controlling major causes of hearing impairment and deafness to reduce the total disease burden by 25% of the existing burden. However, within the program, there exists no specific initiatives and targets for addressing occupational NIHL. The occurrence of avoidable NIHL and extreme discomfort from exposure to hazardous noise also indicates undermining of human rights of the socioeconomically vulnerable workers. Consequently, regular audiometry for screening of NIHL, health promotion through the mandatory provision of protective auditory equipment to all workers, and advancing protection to the more vulnerable informal workers is urgently warranted. Modernization of industries with safer technology has the potential to eliminate harmful noise exposure to workers, but economic constraints need to be overcome to achieve hearing protection in workers. Future studies should design and assess the effectiveness of interventions to preserve and protect hearing loss resulting from hazardous noise exposure at the workplace. Financial support and sponsorship Nil. Conflicts of interest There are no conflicts of interest.
/** * Transaction of the portfolio. */ @ApiModel(description = "Transaction of the portfolio.") @JsonPropertyOrder({ PortfolioTransactionModifyDataTransaction.JSON_PROPERTY_ID, PortfolioTransactionModifyDataTransaction.JSON_PROPERTY_NOTATION, PortfolioTransactionModifyDataTransaction.JSON_PROPERTY_TIME, PortfolioTransactionModifyDataTransaction.JSON_PROPERTY_NUMBER_SHARES, PortfolioTransactionModifyDataTransaction.JSON_PROPERTY_PRICE, PortfolioTransactionModifyDataTransaction.JSON_PROPERTY_CHARGES, PortfolioTransactionModifyDataTransaction.JSON_PROPERTY_EXCHANGE_RATE }) @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class PortfolioTransactionModifyDataTransaction implements Serializable { private static final long serialVersionUID = 1L; public static final String JSON_PROPERTY_ID = "id"; private String id; public static final String JSON_PROPERTY_NOTATION = "notation"; private PortfolioTransactionDeleteDataNotation notation; public static final String JSON_PROPERTY_TIME = "time"; private String time; public static final String JSON_PROPERTY_NUMBER_SHARES = "numberShares"; private BigDecimal numberShares; public static final String JSON_PROPERTY_PRICE = "price"; private BigDecimal price; public static final String JSON_PROPERTY_CHARGES = "charges"; private BigDecimal charges; public static final String JSON_PROPERTY_EXCHANGE_RATE = "exchangeRate"; private BigDecimal exchangeRate; public PortfolioTransactionModifyDataTransaction() { } @JsonCreator public PortfolioTransactionModifyDataTransaction( @JsonProperty(value=JSON_PROPERTY_ID, required=true) String id ) { this(); this.id = id; } public PortfolioTransactionModifyDataTransaction id(String id) { this.id = id; return this; } /** * Identifier of the transaction. * @return id **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "Identifier of the transaction.") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.ALWAYS) public String getId() { return id; } @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.ALWAYS) public void setId(String id) { this.id = id; } public PortfolioTransactionModifyDataTransaction notation(PortfolioTransactionDeleteDataNotation notation) { this.notation = notation; return this; } /** * Get notation * @return notation **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_NOTATION) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public PortfolioTransactionDeleteDataNotation getNotation() { return notation; } @JsonProperty(JSON_PROPERTY_NOTATION) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setNotation(PortfolioTransactionDeleteDataNotation notation) { this.notation = notation; } public PortfolioTransactionModifyDataTransaction time(String time) { this.time = time; return this; } /** * Date and time of the trade. * @return time **/ @javax.annotation.Nullable @ApiModelProperty(value = "Date and time of the trade.") @JsonProperty(JSON_PROPERTY_TIME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public String getTime() { return time; } @JsonProperty(JSON_PROPERTY_TIME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setTime(String time) { this.time = time; } public PortfolioTransactionModifyDataTransaction numberShares(BigDecimal numberShares) { this.numberShares = numberShares; return this; } /** * Number of shares bought or sold. * @return numberShares **/ @javax.annotation.Nullable @ApiModelProperty(value = "Number of shares bought or sold.") @JsonProperty(JSON_PROPERTY_NUMBER_SHARES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public BigDecimal getNumberShares() { return numberShares; } @JsonProperty(JSON_PROPERTY_NUMBER_SHARES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setNumberShares(BigDecimal numberShares) { this.numberShares = numberShares; } public PortfolioTransactionModifyDataTransaction price(BigDecimal price) { this.price = price; return this; } /** * Purchase price. * @return price **/ @javax.annotation.Nullable @ApiModelProperty(value = "Purchase price.") @JsonProperty(JSON_PROPERTY_PRICE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public BigDecimal getPrice() { return price; } @JsonProperty(JSON_PROPERTY_PRICE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setPrice(BigDecimal price) { this.price = price; } public PortfolioTransactionModifyDataTransaction charges(BigDecimal charges) { this.charges = charges; return this; } /** * Charges accrued in portfolio&#39;s base currency. * @return charges **/ @javax.annotation.Nullable @ApiModelProperty(value = "Charges accrued in portfolio's base currency.") @JsonProperty(JSON_PROPERTY_CHARGES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public BigDecimal getCharges() { return charges; } @JsonProperty(JSON_PROPERTY_CHARGES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setCharges(BigDecimal charges) { this.charges = charges; } public PortfolioTransactionModifyDataTransaction exchangeRate(BigDecimal exchangeRate) { this.exchangeRate = exchangeRate; return this; } /** * The exchange rate between the notation&#39;s currency and the portfolio currency. * @return exchangeRate **/ @javax.annotation.Nullable @ApiModelProperty(value = "The exchange rate between the notation's currency and the portfolio currency.") @JsonProperty(JSON_PROPERTY_EXCHANGE_RATE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public BigDecimal getExchangeRate() { return exchangeRate; } @JsonProperty(JSON_PROPERTY_EXCHANGE_RATE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setExchangeRate(BigDecimal exchangeRate) { this.exchangeRate = exchangeRate; } /** * Return true if this _portfolio_transaction_modify_data_transaction object is equal to o. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PortfolioTransactionModifyDataTransaction portfolioTransactionModifyDataTransaction = (PortfolioTransactionModifyDataTransaction) o; return Objects.equals(this.id, portfolioTransactionModifyDataTransaction.id) && Objects.equals(this.notation, portfolioTransactionModifyDataTransaction.notation) && Objects.equals(this.time, portfolioTransactionModifyDataTransaction.time) && Objects.equals(this.numberShares, portfolioTransactionModifyDataTransaction.numberShares) && Objects.equals(this.price, portfolioTransactionModifyDataTransaction.price) && Objects.equals(this.charges, portfolioTransactionModifyDataTransaction.charges) && Objects.equals(this.exchangeRate, portfolioTransactionModifyDataTransaction.exchangeRate); } @Override public int hashCode() { return Objects.hash(id, notation, time, numberShares, price, charges, exchangeRate); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PortfolioTransactionModifyDataTransaction {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" notation: ").append(toIndentedString(notation)).append("\n"); sb.append(" time: ").append(toIndentedString(time)).append("\n"); sb.append(" numberShares: ").append(toIndentedString(numberShares)).append("\n"); sb.append(" price: ").append(toIndentedString(price)).append("\n"); sb.append(" charges: ").append(toIndentedString(charges)).append("\n"); sb.append(" exchangeRate: ").append(toIndentedString(exchangeRate)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
/* access modifiers changed from: package-private */ public final void a(h<Void> hVar, t0 t0Var) { Status m2; if (t0Var == null || t0Var.m() == null) { a(hVar, (Status) null); return; } int t = t0Var.m().t(); this.f7889g.writeLock().lock(); if (t != -6508) { if (t != 6507) { if (t != -6506) { if (t != -6505) { switch (t) { case 6500: case 6501: case 6503: case 6504: m2 = t0Var.m(); a(hVar, m2); break; case 6502: break; default: try { if (t0Var.m().w()) { StringBuilder sb = new StringBuilder(45); sb.append("Unknown (successful) status code: "); sb.append(t); Log.w("FirebaseRemoteConfig", sb.toString()); } m2 = t0Var.m(); a(hVar, m2); break; } catch (Throwable th) { this.f7889g.writeLock().unlock(); throw th; } } this.f7889g.writeLock().unlock(); } Map<String, Set<String>> l2 = t0Var.l(); HashMap hashMap = new HashMap(); for (String str : l2.keySet()) { HashMap hashMap2 = new HashMap(); for (String str2 : l2.get(str)) { hashMap2.put(str2, t0Var.a(str2, null, str)); } hashMap.put(str, hashMap2); } this.a = new p(hashMap, System.currentTimeMillis(), t0Var.o()); this.f7886d.a(-1); hVar.a((Void) null); c(); this.f7889g.writeLock().unlock(); } } this.f7886d.a(2); hVar.a(new d(t0Var.n())); c(); this.f7889g.writeLock().unlock(); } this.f7886d.a(-1); if (this.a != null && !this.a.d()) { Map<String, Set<String>> l3 = t0Var.l(); HashMap hashMap3 = new HashMap(); for (String str3 : l3.keySet()) { HashMap hashMap4 = new HashMap(); for (String str4 : l3.get(str3)) { hashMap4.put(str4, t0Var.a(str4, null, str3)); } hashMap3.put(str3, hashMap4); } this.a = new p(hashMap3, this.a.a(), t0Var.o()); } hVar.a((Void) null); c(); this.f7889g.writeLock().unlock(); }
def process_middleware(self, user_agent, cache_get_many_calls_for_request=1): fake_request = HttpRequest() fake_request.META['HTTP_USER_AGENT'] = user_agent with mock.patch.object(caches['default'], 'get_many', wraps=caches['default'].get_many) as mocked_code: request_response = self.middleware.process_request(fake_request) assert cache_get_many_calls_for_request == mocked_code.call_count with mock.patch.object(caches['default'], 'get_many', wraps=caches['default'].get_many) as mocked_code: processed_response = self.middleware.process_response(fake_request, request_response or HttpResponse()) assert 0 == mocked_code.call_count return request_response, processed_response
<reponame>VerdePeach/Speedik<filename>src/main/java/com/in726/app/model/Disk.java package com.in726.app.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import javax.persistence.*; /** * Model of Disk entity. */ @Data @NoArgsConstructor @Entity @JsonIgnoreProperties(ignoreUnknown = true) @ToString(exclude = "agentData") public class Disk { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String origin; private long free; private long total; @JsonIgnore @ManyToOne(fetch = FetchType.LAZY) private AgentData agentData; }
/** * Class implementation for the method-reference annotation. * * @author JUnit-Tools-Team * */ public class MethodRef { private String name; private String signature; private boolean signatureChanged = false; private String signatureNew; private boolean unresolvedConflict = false; public MethodRef(String name, String signature) { this.name = name; this.signature = signature; } public String getName() { return name; } public String getSignature() { return signature; } @Override public String toString() { return name + signature; } public boolean isSignatureChanged() { return signatureChanged; } public void setSignatureChanged(boolean signatureChanged) { this.signatureChanged = signatureChanged; } public void setSignatureNew(String signatureNew) { setSignatureChanged(true); this.signatureNew = signatureNew; } public String getSignatureNew() { return signatureNew; } public void setUnresolvedConflict(boolean unresolvedConflict) { this.unresolvedConflict = unresolvedConflict; } public boolean isUnresolvedConflict() { return unresolvedConflict; } public String getSignatureToCompare() { if (isSignatureChanged()) { return getSignatureNew(); } return getSignature(); } public boolean isEquals(MethodRef mrToCompare) { if (mrToCompare.getName().equals(getName()) && mrToCompare.getSignatureToCompare().equals( getSignatureToCompare())) { return true; } return false; } public boolean isEquals(IMethod methodToCompare) { try { return isEquals(new MethodRef(methodToCompare.getElementName(), methodToCompare.getSignature())); } catch (JavaModelException e) { return false; } } }
/// Gets a listof Meals from the API. /// This has been extracted since its used in multiple functions. /// Returns up to `limit` results (ordered by whatever the API returns) async fn _get_filtered_meals_response(&self, url: String) -> Result<Option<Vec<String>>> { let response = get(url).await?.text().await?; // println!("------------"); // println!("{}", response); // println!("------------"); let data: crate::api_datamodel::filtered_meal_response::_FilteredMealResponse = serde_json::from_str(&response)?; // Async closures arn't stable yet (https://github.com/rust-lang/rust/issues/62290) // therefore we have to do this the hard way. if let Some(filtered_meals) = data.meals { Ok(Some( filtered_meals .into_iter() .map(|response| response.idMeal) .collect::<Vec<String>>(), )) } else { Ok(None) } }
Unit customization is not a natural fit for a strategy game, particularly not a 4X game where research and economic infrastructure are the chief drivers of military progress. We don't even know where to start. Armor bone is connected to the hip bone, flak cannon is connected to the shoulder bone... Customize all you want, but your battleship should still be a heavily armored slugger, and your cruisers should unleash a torrent of gunfire. Fodder fodder everywhere. Whenever I see a strategy game touting the fact that I will be able to design and build my own custom units, I enjoy a flicker of hope that this time, maybe, unit customization will add something exciting. Then I remember Ascendancy, Alpha Centauri, Elemental: War of Magic, Sword of the Stars 2, Gratuitous Tank Battles, Endless Space, and a dozen other half-forgotten sci-fi strategy games that thought I cared how many Whocaresitron guns my space ships carried, and whether they could penetrate Adadurasteeltanium armor. I cannot think of another feature with such a mixed track record that enjoys such enduring popularity among gamers and developers. While customization might be fun for tinkerers, strategy games aren't Lego, and customization brings complications that may not translate to greater depth.The main problem is that unit customization is not a natural fit for a strategy game, particularly not a 4X game where research and economic infrastructure are the chief drivers of military progress. When you play a game like Alpha Centauri, for instance, there is a fairly narrow band of weapons and armors that you can employ in battle. If you are using weapons that are more than a step or two behind the current cutting edge, the exact unit specifications don't matter. Units simply will not have the firepower to make a successful attack. If their armor is a step or two behind the standard, it can't survive an attack. Unit customization ends up being this ritual where you confirm your technological progress by updating the specs on a few basic unit templates: garrison units, artillery, tanks, fighter-bombers, etc. It's kind of like an RPG: you level up and your stats improve and you get some new loot, but nothing really changes because all the enemies advance so that you have the same relative relationship.To a greater or lesser extent, this same dynamic is at work in most 4X games. It doesn't make customization meaningless, but it does marginalize customization's impact. Loading an extra pair of lasers at the expense of a bit of armor plating isn't going to make much difference compared to having a couple more research labs and factories. In fact, I even get a little annoyed when I have to spend an hour drawing up new unit specifications when all I really want are units that fulfill simple tactical roles. The question of how to make a unit fulfill that role is not a question I play strategy games in order to answer.Consider what happens when the focus changes, however. Any BattleTech game, like MechWarrior or Mech Commander, is also driven by customization. X-COM: UFO Defense and Jagged Alliance 2 are as much about what your soldiers are carrying as what you do with them once the shots start to fly. But these games are 90% about battles and tactics. Customization and loadouts are hugely important here because I want squads and lances that are appropriate for the battlefield and allow me to execute the tactics I prefer. Besides which, obsolescence doesn't make the majority of my options irrelevant at any given time. A shotgun in the hands of an assault trooper still has a role to play in some circumstances, and a BattleTech game still gives me reasons to employ lasers, despite the fact that Gauss rifles do more damage.The other problem with customization is it throws open a huge menu of options, but it's by no means certain that players will have the context to make smart decisions about the units they build. It creates an entirely avoidable learning-curve issue. If a game gives me units called "Siege Artillery" or "Interceptor," I have a pretty good idea of what those will do and how to use them. If it gives me a blank chassis and a bunch of cryptic-sounding pieces of equipment, each with its own stats, I'm at a loss.Endless Space is clever about how it solves these problems, but the solutions are also revealing about why customization tends to be unsatisfying. It gives you several different types of ships, and each has stat modifiers that allow it to carry particular types of equipment at a lower cost than normal. So battleships can add more armor without going over their weight limit, corvettes carry support equipment like repair modules and long-range sensors, and cruisers can carry extra weaponry. It's not a bad approach, but it also slaps the player upside the head and says, "This is what this ship is for, dummy!" Customize all you want, but your battleship should still be a heavily armored slugger, and your cruisers should unleash a torrent of gunfire. It is a tacit admission that there is a "right" way to build these units, and customization is really just a way to tinker at the margins. Furthermore, once you've designed a ship, it's very easy to click "auto-upgrade" to make sure the same basic design persists through several generations of technology. Because, again, tech is what matters, not loadouts. Endless Space just does us the courtesy of acknowledging this.But my real problem isn't with customization itself. It's the way it's so often treated like a condiment. It's not easy to make customization fun and exciting even when it's the overwhelming focus of the game, like in Gratuitous Tank Battles. It's even harder to offer a rewarding, challenging customization system on top of a fully featured 4X strategy game.So by all means, let's have games that let us custom-build units and set our mechanical creations against our enemies.' But let's make those games be about custom-built units and learning to use them in conjunction with each other, and leave all the Civilization trappings aside. I don't need every game to span the galaxy or the globe. I just need them to get their arms around their own big ideas.: Everything is better when it's customized! For example, you don't think this green fedora was bought off the shelf, do you? What's the best custom unit you've ever made in a game?
Ownership structure and oppurtunistic accounting: A Case of listed food and beverage firms in Nigeria Earnings management has been identified by regulators and practitioners as a tool used by managers to mislead investors about the underlying economic conditions of their firms. Although, the relationship between ownership structure and the discretionery behaviour of managers has been considerably discussed in developed countries, an examination into this relationship has only recently attracted the attention of researchers in the developing economies such as Nigeria. This paper examines the impact of ownership structure on earnings management in quoted food and beverage firms in Nigeria. Secondary data were extracted from the annual reports of our sample firms for the period between 2006 to 2010 and OLS multiple regression is used as a tool for data analysis. The result indicates that ownership structure affects earnings management in divergent ways. Specifically, the study documents an inverse relationship between institutional sherholding and discretionery accruals. While ownership concentration and family ownership positively impact on earnings manipulation.
import java.util.Scanner; /** * Created by leo on 16/12/15. * http://codeforces.com/problemset/problem/158/A * Next Round * "Contestant who earns a score equal to or greater than the * k-th place finisher's score will advance to the next round, * as long as the contestant earns a positive score..." [excerpt * from contest rules.] * * A total of n >= k participants took part in the contest, and * you know their scores. How many will advance to the next round? * * Input: * First line = 2 n and k: 1 <= k <= n <= 50 separated by a single space. * 2nd line = n space-separated integers 0 <= a_i <= 100, where * a_i is the score earned by the participant who got the i-th place. * The sequence is non-increasing, i.e. a_i >= a_i+1 for all i from * 1 to n-1. * * Output: * The number of participants who advance to the next round. */ public final class A158 { private A158() { } public static void main(final String[] notUsed) { Scanner sin = new Scanner(System.in); int n = sin.nextInt(); int k = sin.nextInt(); int as[] = new int[n + 1]; // 1-indexed is easier here /* * It is not actually necessary to read the scores * into an array first. It suffices to remember the * kth score. Reading is easier though. So we read. */ for (int i = 1; i <= n; i++) { as[i] = sin.nextInt(); } int count = 0; for (int i = 1; i <= n; i++) { if (as[i] == 0) { break; } if (i > k && as[i] < as[k]) { break; } ++count; } System.out.println(count); } }
///Bismillahir Rahmanir Rahim #include<bits/stdc++.h> #define ll long long #define pll pair<ll,ll> #define ff first #define ss second #define mp make_pair #define pb push_back #define cy cout<<"YES"<<endl #define cn cout<<"NO"<<endl using namespace std; const ll inf=1e18; const int mod=1e9+7; const int mod2=2147483647; ///2^31-1 const int M=500005; ll a[M]; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll t,i,j; cin>>t; while(t--) { ll n,k1,k2;cin>>n>>k1>>k2; ll w,b;cin>>w>>b; ll x=(k1+k2); //if(k1!=0 and k2!=0) x=(k1+k2); //else x=k1+k2; ll y=(n-k1)+(n-k2); //if(k1!=n and k2!=n) y=(n-k1)+(n-k2); // else y=(n-k1)+(n-k2); if(x>=2*w and y>=2*b) cy; else cn; } return 0; }
<filename>source/svgnumber.h<gh_stars>0 #ifndef SVGNUMBER_H #define SVGNUMBER_H #include "svgproperty.h" namespace lunasvg { class SVGNumber : public SVGPropertyBase { public: SVGNumber(); void setValue(double value) { m_value = value; } double value() const { return m_value; } std::string valueAsString() const; virtual void setValueAsString(const std::string& value); virtual SVGPropertyBase* clone() const; protected: double m_value; }; class SVGNumberPercentage : public SVGNumber { public: SVGNumberPercentage(); void setValueAsString(const std::string& value); SVGPropertyBase* clone() const; }; class SVGNumberList : public SVGListProperty<SVGNumber> { public: SVGNumberList(); std::vector<double> values() const; void setValueAsString(const std::string& value); SVGPropertyBase* clone() const; }; typedef DOMSVGProperty<SVGNumber> DOMSVGNumber; typedef DOMSVGProperty<SVGNumberPercentage> DOMSVGNumberPercentage; typedef DOMSVGProperty<SVGNumberList> DOMSVGNumberList; } // namespace lunasvg #endif // SVGNUMBER_H
Characterization of the High Temperature Form of Fe2(MoO4)3 Ferric molyhdate in its high temperature orthorhomhic phase has been characterized by conductometric and thermogravimetric measurements. In the temperature range 793-973 K the compound can exist with O2 and MoO3 deficiencies. Defect models are proposed which can explain the experimental results: while a majority defect pair constituted by (Vo2-,e') seems to be valid at T = 793 K, two majority defect pairs (Vo2-, e'; V6'Mo, VO2') are taken as possible at T = 873 K
import dedent from 'dedent'; export type WhoisTestResponse = { server: string; data: string; }; export type WhoisIANATestResponse = WhoisTestResponse & { refer: string; }; export const iana: WhoisIANATestResponse = { server: 'whois.iana.org', refer: 'whois.nic.io', data: dedent` % IANA WHOIS server % for more information on IANA, visit http://www.iana.org % This query returned 1 object refer: whois.nic.io domain: IO organisation: Internet Computer Bureau Limited address: c/o Sure (Diego Garcia) Limited address: Diego Garcia address: British Indian Ocean Territories, PSC 466 Box 59 address: FPO-AP 96595-0059 address: British Indian Ocean Territory contact: administrative name: Internet Administrator organisation: Internet Computer Bureau Limited address: c/o Sure (Diego Garcia) Limited address: Diego Garcia address: British Indian Ocean Territories, PSC 466 Box 59 address: FPO-AP 96595-0059 address: British Indian Ocean Territory phone: +246 9398 fax-no: +246 9398 e-mail: <EMAIL> contact: technical name: Administrator organisation: Internet Computer Bureau Ltd address: Greytown House, 221-227 High Street address: Orpington address: Kent address: BR6 0NZ address: United Kingdom phone: +44 (0)1689 827505 fax-no: +44 (0)1689 831478 e-mail: <EMAIL> nserver: A0.NIC.IO fc00:e968:6179::de52:7100 172.16.31.10 nserver: A2.NIC.IO fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b 192.168.127.12 nserver: B0.NIC.IO fdf8:f53e:61e4::18 192.168.127.12 nserver: C0.NIC.IO fc00:e968:6179::de52:7100 192.168.3.11 ds-rdata: 57355 8 2 95a57c3bab7849dbcddf7c72ada71a88146b141110318ca5be672057e865c3e2 ds-rdata: 57355 8 1 434e91e206134f5b3b0ac603b26f5e029346abc9 whois: whois.nic.io status: ACTIVE remarks: Registration information: http://www.nic.io/ created: 1997-09-16 changed: 2019-10-29 source: IANA `, }; export type WhoisDomainTestResponse = WhoisTestResponse & { updatedDate: string; createdDate: string; expiryDate: string; }; export const responses: WhoisDomainTestResponse[] = [ { server: 'whois.nic.io', updatedDate: '2019-03-05T14:41:54Z', createdDate: '2003-09-15T11:13:53Z', expiryDate: '2027-05-01T00:00:02Z', data: dedent` Domain Name: NIC.IO Registry Domain ID: D503300000040453277-LRMS Registrar WHOIS Server: Registrar URL: Updated Date: 2019-03-05T14:41:54Z Creation Date: 2003-09-15T11:13:53Z Registry Expiry Date: 2027-05-01T00:00:02Z Registrar Registration Expiration Date: Registrar: Afilias GRS Test Account Registrar IANA ID: 119 Registrar Abuse Contact Email: Registrar Abuse Contact Phone: Reseller: Domain Status: serverDeleteProhibited https://icann.org/epp#serverDeleteProhibited Domain Status: serverTransferProhibited https://icann.org/epp#serverTransferProhibited Domain Status: serverUpdateProhibited https://icann.org/epp#serverUpdateProhibited Registrant Organization: Internet Computer Bureau Ltd Registrant State/Province: Dorset Registrant Country: GB Name Server: B0.NIC.IO Name Server: A2.NIC.IO Name Server: A0.NIC.IO Name Server: C0.NIC.IO DNSSEC: unsigned URL of the ICANN Whois Inaccuracy Complaint Form is https://www.icann.org/wicf/ `, }, { server: 'whois.nic.google', updatedDate: '2020-02-19T17:44:36Z', createdDate: '2015-01-05T17:44:36Z', expiryDate: '2021-01-05T17:44:36Z', data: dedent` Domain Name: nic.dev Registry Domain ID: 4E9533-DEV Registrar WHOIS Server: whois.nic.google Registrar URL: Updated Date: 2020-02-19T17:44:36Z Creation Date: 2015-01-05T17:44:36Z Registry Expiry Date: 2021-01-05T17:44:36Z Registrar: Charleston Road Registry NonBillable Registrar IANA ID: 9999 Registrar Abuse Contact Email: <EMAIL> Registrar Abuse Contact Phone: +1.2125652633 Domain Status: serverDeleteProhibited https://icann.org/epp#serverDeleteProhibited Domain Status: serverTransferProhibited https://icann.org/epp#serverTransferProhibited Domain Status: serverUpdateProhibited https://icann.org/epp#serverUpdateProhibited Registry Registrant ID: REDACTED FOR PRIVACY Registrant Name: REDACTED FOR PRIVACY Registrant Organization: Charleston Road Registry, Inc. Registrant Street: REDACTED FOR PRIVACY Registrant Street: Registrant City: REDACTED FOR PRIVACY Registrant State/Province: CA Registrant Postal Code: REDACTED FOR PRIVACY Registrant Country: US Registrant Phone: REDACTED FOR PRIVACY Registrant Fax: REDACTED FOR PRIVACY Registrant Email: Please query the WHOIS server of the owning registrar identified in this output for information on how to contact the Registrant, Admin, or Tech contact of the queried domain name. Registry Admin ID: REDACTED FOR PRIVACY Admin Name: REDACTED FOR PRIVACY Admin Organization: REDACTED FOR PRIVACY Admin Street: REDACTED FOR PRIVACY Admin Street: Admin City: REDACTED FOR PRIVACY Admin State/Province: REDACTED FOR PRIVACY Admin Postal Code: REDACTED FOR PRIVACY Admin Country: REDACTED FOR PRIVACY Admin Phone: REDACTED FOR PRIVACY Admin Fax: REDACTED FOR PRIVACY Admin Email: Please query the WHOIS server of the owning registrar identified in this output for information on how to contact the Registrant, Admin, or Tech contact of the queried domain name. Registry Tech ID: REDACTED FOR PRIVACY Tech Name: REDACTED FOR PRIVACY Tech Organization: REDACTED FOR PRIVACY Tech Street: REDACTED FOR PRIVACY Tech Street: Tech City: REDACTED FOR PRIVACY Tech State/Province: REDACTED FOR PRIVACY Tech Postal Code: REDACTED FOR PRIVACY Tech Country: REDACTED FOR PRIVACY Tech Phone: REDACTED FOR PRIVACY Tech Fax: REDACTED FOR PRIVACY Tech Email: Please query the WHOIS server of the owning registrar identified in this output for information on how to contact the Registrant, Admin, or Tech contact of the queried domain name. Name Server: ns1.google.com Name Server: ns2.google.com Name Server: ns3.google.com Name Server: ns4.google.com DNSSEC: unsigned `, }, ];
def keyPressEvent(self, event): if event.key() in [ QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return, QtCore.Qt.Key_Tab, QtCore.Qt.Key_Comma, QtCore.Qt.Key_Space, ]: tag = self.get_typed_text() tag.strip() self.add_tag(tag) self.clear_typed_text() event.ignore() return super(TagsEditorWidget, self).keyPressEvent(event)
/*This file is part of the FEBio source code and is licensed under the MIT license listed below. See Copyright-FEBio.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #pragma once #include "FECoreFactory.h" #include "ClassDescriptor.h" #include <vector> #include <string.h> #include <stdio.h> #include "version.h" //----------------------------------------------------------------------------- // Forward declarations class FEModel; class LinearSolver; //----------------------------------------------------------------------------- //! This is the FECore kernel class that manages the interactions between the //! different modules. In particular, it manages the factory classes //! which are responsible for the creation of different classes that are registered //! with the kernel. class FECORE_API FECoreKernel { // forward declaration of Module class class Module; public: // Do not call this function from a plugin as it will not return the correct // instance. Instead, use the FECoreKernel object that is passed in the PluginInitialize method static FECoreKernel& GetInstance(); // set the instance of the kernel static void SetInstance(FECoreKernel* pkernel); public: //! Register a class with the framework void RegisterFactory(FECoreFactory* ptf); //! Create a specific using a superclass ID and an alias void* Create(int superClassID, const char* szalias, FEModel* pfem); //! Create a specific class void* CreateClass(const char* szclassName, FEModel* fem); //! Create a class from a class descriptor void* Create(int superClassID, FEModel* pfem, const ClassDescriptor& cd); //! count the number of registered classes with a given super-class id int Count(SUPER_CLASS_ID sid); //! List the registered classes with a given super-class id void List(SUPER_CLASS_ID sid); //! Get the number of registered factory classes int FactoryClasses(); //! return a factory class const FECoreFactory* GetFactoryClass(int i); //! return a factory class const FECoreFactory* GetFactoryClass(int classID, int i); //! find a factory class FECoreFactory* FindFactoryClass(int classID, const char* sztype); //! remove a factory class bool UnregisterFactory(FECoreFactory* ptf); //! unregister factories from allocator void UnregisterFactories(int alloc_id); //! set the current allocator ID void SetAllocatorID(int alloc_id); //! generate a allocator ID int GenerateAllocatorID(); public: // Modules //! count modules int Modules() const; //! Create a module (also makes it the active module) bool CreateModule(const char* szmodule); //! set the active module bool SetActiveModule(const char* szmodule); //! set a dependency on a module bool SetModuleDependency(const char* szmodule); //! Get a module's name const char* GetModuleName(int i) const; const char* GetModuleNameFromId(int id) const; //! Get a module's dependencies vector<int> GetModuleDependencies(int i) const; //! set the spec ID. Features with a matching spec ID will be preferred //! set spec ID to -1 to stop caring void SetSpecID(int nspec); public: //! Register a new domain class void RegisterDomain(FEDomainFactory* pf); //! Create a domain of a certain type FEDomain* CreateDomain(const FE_Element_Spec& spec, FEMesh* pm, FEMaterial* pmat); public: //! set the default linear solver FECoreFactory* SetDefaultSolverType(const char* sztype); void SetDefaultSolver(ClassDescriptor* linsolve); //! get the linear solver type const char* GetLinearSolverType() const; //! Get a linear solver LinearSolver* CreateDefaultLinearSolver(FEModel* fem); private: std::vector<FECoreFactory*> m_Fac; // list of registered factory classes std::vector<FEDomainFactory*> m_Dom; // list of domain factory classes std::string m_default_solver_type; // default linear solver ClassDescriptor* m_default_solver; // module list vector<Module*> m_modules; int m_activeModule; int m_nspec; int m_alloc_id; //!< current allocator ID int m_next_alloc_id; //!< next allocator ID private: // make singleton FECoreKernel(); FECoreKernel(const FECoreKernel&){} void operator = (const FECoreKernel&){} private: static FECoreKernel* m_pKernel; // the one-and-only kernel object }; //----------------------------------------------------------------------------- //! This class helps with the registration of a class with the framework template <typename T> class FERegisterClass_T : public FECoreFactory { public: FERegisterClass_T(SUPER_CLASS_ID sid, const char* szclass, const char* szalias, int spec = -1) : FECoreFactory(sid, szclass, szalias, spec) { FECoreKernel& fecore = FECoreKernel::GetInstance(); fecore.RegisterFactory(this); } FECoreBase* Create(FEModel* pfem) const { return new T(pfem); } }; //----------------------------------------------------------------------------- // Register a factory class #define REGISTER_FECORE_FACTORY(theFactory) \ static theFactory _##theFactory##_rc; //----------------------------------------------------------------------------- // Register a class using default creation parameters #define REGISTER_FECORE_CLASS(theClass, ...) \ static FERegisterClass_T<theClass> _##theClass##_rc(theClass::classID(), #theClass, __VA_ARGS__); //----------------------------------------------------------------------------- // Register a class using default creation parameters #define REGISTER_FECORE_CLASS_EXPLICIT(theClass, theID, ...) \ static FERegisterClass_T<theClass> _##theClass##_rc(theID, #theClass, __VA_ARGS__); //----------------------------------------------------------------------------- // version for classes that require template arguments #define REGISTER_FECORE_CLASS_T(theClass, theArg, theName) \ static FERegisterClass_T<theClass<theArg> > _##theClass##theArg##_rc(theClass<theArg>::classID(), 0, theName); //----------------------------------------------------------------------------- // version for classes that require template arguments #define REGISTER_FECORE_CLASS_T2(theClass, theArg1, theArg2, theName) \ static FERegisterClass_T<theClass<theArg1, theArg2> > _##theClass##theArg1##theArg2##_rc(theClass<theArg1, theArg2>::classID(), 0, theName); //----------------------------------------------------------------------------- // Create an instance of a class. // This assumes that TBase is derived from FECoreBase and defines a class ID. template <typename TBase> inline TBase* fecore_new(const char* sztype, FEModel* pfem) { FECoreKernel& fecore = FECoreKernel::GetInstance(); return static_cast<TBase*>(fecore.Create(TBase::classID(), sztype, pfem)); } //----------------------------------------------------------------------------- // Create an instance of a class. // This assumes that TBase is derived from FECoreBase and defines a class ID. template <typename TBase> inline TBase* fecore_new(int classIndex, FEModel* pfem) { FECoreKernel& fecore = FECoreKernel::GetInstance(); const FECoreFactory* f = fecore.GetFactoryClass(TBase::classID(), classIndex); if (f) return static_cast<TBase*>(f->Create(pfem)); else return nullptr; } //----------------------------------------------------------------------------- template <typename TClass> inline TClass* fecore_new_class(const char* szclass, FEModel* fem) { FECoreKernel& fecore = FECoreKernel::GetInstance(); return static_cast<TClass*>(fecore.CreateClass(szclass, fem)); } //----------------------------------------------------------------------------- #define fecore_alloc(theClass, fem) fecore_new_class<theClass>(#theClass, fem) //----------------------------------------------------------------------------- // Three-parameter form of the fecore_new function for situations where the base class does not // define the classID value. template <typename TBase> inline TBase* fecore_new(int sid, const char* sztype, FEModel* pfem) { FECoreKernel& fecore = FECoreKernel::GetInstance(); return static_cast<TBase*>(fecore.Create(sid, sztype, pfem)); } //============================================================================= // TODO: Move all this stuff to sdk.h //----------------------------------------------------------------------------- // Template class for factory classes for plugins template <typename T, SUPER_CLASS_ID sid> class FEPluginFactory_T : public FECoreFactory { public: FEPluginFactory_T(const char* sz) : FECoreFactory(sid, nullptr, sz){} FECoreBase* Create(FEModel* pfem) const { return new T(pfem); } }; //------------------------------------------------------------------------------ // This is for functions exported from a plugin #ifdef WIN32 #define FECORE_EXPORT extern "C" __declspec(dllexport) #else #define FECORE_EXPORT extern "C" #endif
<reponame>vaibhavsingh97/serverless-enigma import os import json from random import randint import giphy_client from flask import Flask from giphy_client.rest import ApiException app = Flask(__name__) api_instance = giphy_client.DefaultApi() API_KEY = os.environ.get('GIPHY_TOKEN') q = 'cat' limit = 100 offset = 0 rating = 'g' lang = 'en' fmt = 'json' @app.route("/") def home(): return json.dumps({ 'status code': 200, 'message': "Welcome to cat gif API" }) @app.route("/catgif") def get_cat_gif(): try: api_response = api_instance.gifs_search_get( API_KEY, q, limit=limit, offset=offset, rating=rating, lang=lang, fmt=fmt).to_dict() random_gif = api_response['data'][randint( 0, 100)]['images']['downsized']['url'] return json.dumps({ 'status_code': 200, 'url': random_gif }) except ApiException as e: return json.dumps({ 'status code': 400, 'message': "Exception when calling giphy api: {}".format(e) })
def _register_heartbeat(self, hearbeat_filepath: str): t_now = datetime.utcnow() with open(f"{hearbeat_filepath}", "w") as file_obj: file_obj.write(t_now.strftime("%Y-%m-%d %H:%M:%S"))
<gh_stars>0 // Lisp core functions #include <math.h> #include "types.h" // Datatypes #include "vars.h" // Variable tools #ifndef CFUNC_H #define CFUNC_H #define ASSERTM(x,m) if (!(x)) {printf("\nFatal error: " m "\n\n"); exit(1);} var_t *cons(var_t *var1,var_t *var2) { var_t *c=NEW(var_t); c->type=CELL; c->data.l=NEW(cell_t); c->data.l->car=var1; c->data.l->cdr=var2?var2:&NIL; return c; } var_t *car(var_t *var) { ASSERTM(var->type==CELL||var->type==QUOTE ||var->type==VOID||var->type==FUNCTION ,"car(): Invalid argument datatype"); if (var==&NIL) return &NIL; return var->data.l->car; } var_t *cdr(var_t *var) { ASSERTM(var->type==CELL||var->type==QUOTE ||var->type==VOID||var->type==FUNCTION ,"cdr(): Invalid argument datatype"); if (var==&NIL) return &NIL; return var->data.l->cdr; } var_t *display(var_t *var) { switch (var->type) { case VARIABLE: case SPECIAL: printf("%s",var->data.s); return &NIL; case VOID: printf("NIL"); return &NIL; case INT: printf("%li",var->data.i); return &NIL; case FLOAT: printf("%lf",var->data.f); return &NIL; case CHAR: printf("%c",var->data.c); return &NIL; case SYMBOL: printf("%s",var->data.s); return &NIL; case FUNCTION: printf("#FUNCTION-%x",var); return &NIL; case QUOTE: case CELL: break; default: printf("ERROR"); return NULL; } putchar('('); for (;var->type==CELL||var->type==QUOTE&&cdr(var);var=cdr(var)) { display(car(var)); putchar(' '); } if (var&&var->type!=VOID) { printf(". "); display(var); putchar(' '); } printf("\e[D)"); return &NIL; } var_t *eq(var_t *v1,var_t *v2) { if (v1->type==SYMBOL||v1->type==VARIABLE) return v1==v2||!strcmp(v1->data.s,v2->data.s)?&T:&NIL; if (v1->type!=v2->type) return &NIL; if (v1->type==VOID&&v2->type==VOID) return &T; if (v1->type!=CELL&&v1->type!=QUOTE) return v1->data.i==v2->data.i?&T:&NIL; return &NIL; } var_t *atom(var_t *var) { return var->type==CELL||var->type==QUOTE?&NIL:&T; } var_t *terpri() { putchar('\n'); return &NIL; } // Arithmetic var_t *arith(var_t *v1,var_t *v2,char op) { ASSERTM(v1->type==INT||v1->type==FLOAT,"arith(): First argument not a number"); ASSERTM(v2->type==INT||v2->type==FLOAT,"arith(): Second argument not a number"); var_t *result=NEW(var_t); result->type=INT; if (v1->type==FLOAT||v2->type==FLOAT ||(op=='/'&&v1->data.i%v2->data.i!=0)) goto FLOAT; #define INT_OP_CASE(a,o,b) result->data.i=a->data.i o b->data.i; break switch (op) { case '+': INT_OP_CASE(v1,+,v2); case '-': INT_OP_CASE(v1,-,v2); case '*': INT_OP_CASE(v1,*,v2); case '/': INT_OP_CASE(v1,/,v2); case '%': INT_OP_CASE(v1,%,v2); case '^': result->data.i=pow(v1->data.i,v2->data.i); } goto RETURN; FLOAT: result->type=FLOAT; #define NUMBER_VALUE(x) (x->type==INT?x->data.i:x->data.f) #define FLOAT_OP_CASE(a,o,b) result->data.f=NUMBER_VALUE(a) o NUMBER_VALUE(b); break switch (op) { // Need to cope with the possibility that either variable is a float case '+': FLOAT_OP_CASE(v1,+,v2); case '-': FLOAT_OP_CASE(v1,-,v2); case '*': FLOAT_OP_CASE(v1,*,v2); case '/': FLOAT_OP_CASE(v1,/,v2); case '%': result->data.f=fmod(NUMBER_VALUE(v1),NUMBER_VALUE(v2)); break; case '^': result->data.f=pow(NUMBER_VALUE(v1),NUMBER_VALUE(v2)); } RETURN: return result; } #endif
info = [int(x) for x in input().split()] string = [char for char in input()] nums = [] num = 0 for i in range(len(string)): if string[i] == "#": num += 1 else: if nums == 0: num = 0 else: nums.append(num) num = 0 if sorted(nums, reverse=True)[0] >= info[1]: print('NO') else: print('YES')
package main import ( "strings" ) func parseURL(url string, silent bool) string { if !silent { log(1, "Parsing URL %s...", bolden(url)) } repoURL := url // Trim repoURL = strings.TrimSpace(repoURL) repoURL = strings.TrimSuffix(repoURL, "/") // Change protocol to http:// if split := strings.Split(repoURL, "//"); strings.Contains(repoURL, "://") { repoURL = "http://" + strings.Join(split[1:], "://") } else { repoURL = "http://" + repoURL } debugLog("Parsed URL: %s", repoURL) return repoURL } func readSources() ([]string, string) { log(1, "Reading sources file...") raw := readFile(configPath+"sources.txt", "An error occurred while reading sources file") log(1, "Parsing sources file...") trimmed := strings.TrimSpace(raw) return strings.Split(trimmed, "\n"), trimmed } func stripSources(sourcesFile string, noParse bool) ([]string, string) { log(1, "Stripping sources file of comments...") final := []string{} finalStr := "" // Iterate through each line for _, line := range strings.Split(strings.TrimSpace(sourcesFile), "\n") { if strings.HasPrefix(line, "#") || strings.TrimSpace(line) == "" { // Skip comments and empty lines continue } parsedLine := line if !noParse { // Parse URL if noParse is set to false parsedLine = parseURL(line, true) } finalStr += parsedLine + "\n" final = append(final, parsedLine) } return final, finalStr } func saveChanges(sourcesFile string) { log(1, "Saving changes...") newFile(configPath+"sources.txt", sourcesFile, "An error occurred while saving changes to sources file") } func addRepo(repoLink string) { if !isValidURL(repoLink) { if force { log(3, "Invalid url, but continuing because force is set to true.") } else { errorLogRaw("Invalid url: %s", bolden(repoLink)) } } _, sourcesFile := readSources() _, stripped := stripSources(sourcesFile, true) if strings.Contains(stripped, repoLink) { if force { log(3, "Repo %s already exists in sources file, but continuing because force is set to true.", bolden(repoLink)) } else { errorLogRaw("Repo %s already exists in sources file", bolden(repoLink)) } } log(1, "Appending %s to sources file...", bolden(repoLink)) sourcesFile = strings.TrimSpace(sourcesFile + "\n" + repoLink) saveChanges(sourcesFile) } func rmRepo(repoLink string) { repos, _ := readSources() log(1, "Removing %s from sources file...", bolden(repoLink)) final := "" for i, repo := range repos { if repo == repoLink { debugLog("Match found at index %d.", i) continue } final = final + repo + "\n" } sourcesFile := strings.TrimSpace(final) saveChanges(sourcesFile) } func listRepos() { rawRepos, _ := readSources() repos, _ := stripSources(strings.Join(rawRepos, "\n"), true) log(1, "Repos:") for _, repo := range repos { rawLogf(" %s - %s\n", bolden(repo), repoLabel(repo, false)) } } func repoLabel(repo string, includeLink bool) string { prefixes := [][]string{ {"http://raw.githubusercontent.com/talwat/indiepkg/main/packages/linux-only", textCol.Blue + "(Linux only)" + RESETCOL}, {"http://raw.githubusercontent.com/talwat/indiepkg/main/packages/bin", textCol.Violet + "(Binary package)" + RESETCOL}, {"http://raw.githubusercontent.com/talwat/indiepkg/main", textCol.Cyan + "(Official repo)" + RESETCOL}, {"http://raw.githubusercontent.com/talwat/indiepkg", textCol.Blue + "(Other branch)" + RESETCOL}, } // Iterate through 2D array for prefix := range prefixes { if strings.HasPrefix(parseURL(repo, true), prefixes[prefix][0]) { // Check prefix matches return prefixes[prefix][1] } } if includeLink { return textCol.Yellow + "(Third party repo: " + repo + ")" + RESETCOL } return textCol.Yellow + "(Third party repo)" + RESETCOL }
<filename>test/JsonStruct/deserialize.ts<gh_stars>1-10 import { JsonName, JsonStruct, deserialize } from './../../src'; class InnerClass { @JsonName() fieldToSerialize: string; @JsonName('customName') fieldTwo: number; static fromServer(data: object): InnerClass { return deserialize(data, InnerClass); } } class BaseStructCase { @JsonStruct(InnerClass) inner: InnerClass; @JsonStruct(InnerClass, 'customInner') inner2: InnerClass; } describe('JsonStruct deserialize case', () => { const instance = deserialize({ inner: { fieldToSerialize: 'hello', customName: 2 }, customInner: { fieldToSerialize: 'good buy' }, noMatterInner: { customName: 3 } }, BaseStructCase); test('be equal to reference', () => { expect(instance).toEqual({ inner: { fieldToSerialize: 'hello', fieldTwo: 2 }, inner2: { fieldToSerialize: 'good buy' } }); }); });
def do_change_name_selected(self): cif = self.get_selected_cif() if cif == None: return FileControlEditDialog(self.context, cif)
/** * Example of how to do closed multi-dimensional sequential * pattern mining in source code. * @author Philippe Fournier-Viger */ public class MainTestMultiDimSequentialPatternMiningClosed { public static void main(String [] arg) throws IOException{ // Minimum absolute support = 50 % double minsupp = 0.50; String input = fileToPath("ContextMDSequenceNoTime.txt"); String output = ".//output.txt"; // Load a sequence database MDSequenceDatabase contextMDDatabase = new MDSequenceDatabase(); // contextMDDatabase.loadFile(input); // contextMDDatabase.printContext(); // If the second boolean is true, the algorithm will use // CHARM instead of AprioriClose for mining frequent closed itemsets. // This options is offered because on some database, AprioriClose does not // perform very well. Other algorithms could be added. AlgoDim algoDim = new AlgoDim(false, true); AlgoSeqDim algoSeqDim = new AlgoSeqDim(); // Apply algorithm AlgoBIDEPlus bideplus = new AlgoBIDEPlus(minsupp); algoSeqDim.runAlgorithm(contextMDDatabase, bideplus, algoDim, true, output); // Print results algoSeqDim.printStatistics(contextMDDatabase.size()); } public static String fileToPath(String filename) throws UnsupportedEncodingException{ URL url = MainTestMultiDimSequentialPatternMiningClosed.class.getResource(filename); return java.net.URLDecoder.decode(url.getPath(),"UTF-8"); } }
STUDENT Harry Bainbridge wrote his final year dissertation on rapper Kanye West. The english literature undergraduate penned 10,492 words on reality star Kim Kardashian's singer husband. 5 Harry Bainbridge wrote 10,492 words on Kanye West for his dissertation He titled his work: "I Love Kanye: Identity in the works of Kanye West". It began: "This essay looks to examine the script of the Kanye West identity and the constant battle for control over it. "It charts the construction and evolution of this image through performance, its relationship with religion and capitalism and its manifestation in a digital landscape." Getty Images 5 The student looked at Kanye West's attempts to grapple with his own identity Fan Harry, 24, said: "I spent a few years working in a celebrity marketing job and became really interested in the creation of public identities that we, the audience, consume as images, rather than actual people. "I'm also a big Kanye fan so wanted to dig into his back catalogue." He told how his work involved hours spent "listening over and over to albums and reading lyrics". Getty Images 5 Harry is a big fan of Kanye West and wanted to choose a topic he found exciting for his dissertation The Leeds University student, from Middleton Tyas, North Yorks., added: "I wanted to work on something that I was really excited about and interested in. "I also wanted to write something that I felt hadn’t necessarily been covered before, so I wanted to challenge myself with something slightly off the beaten track." Kanye, 39, who wed Kim in 2014, has endured a turbulent few months recently. MOST READ IN NEWS Exclusive BRUTE FARCE Albanian killer fighting deportation over right to happy family life beats wife Exclusive PIE ROLLER £148m EuroMillions winner scoffs 50 home-delivered Cornish pasties every WEEK TREE OF TERROR Mum horrified to learn what the strange 'pods' were hanging from branches MISSED THE BOAT Clueless couple stranded as cruise leaves WITHOUT them because they're late MOMO NO-NO Momo Challenge in 'Peppa Pig and Fortnite vids' as YouTube and Instagram slammed HEN DO MYSTERY Brit newlywed, 27, 'CLUNG to balcony before fatal Benidorm hotel plunge' Latest tit-for-tat attacks India ‘shoots down Pakistani jet' after 2 of its own planes were downed MOMO SHOCK Creepy 'suicide character' Momo told lad, 8, to 'stab himself in neck' NET NASTY Stacey Solomon fears for kids after Momo Challenge spreads to YouTube & Fortnite SUICIDE WARNING What is Momo and how can parents protect their children? In November he was admitted to hospital with reported temporary psychosis caused by dehydration and lack of sleep. He cancelled the rest of his tour and has since kept a low profile. In December, he posted a series of tweets about meeting Donald Trump before deleting them. Getty Images 5 Kanye West had a turbulent few months which caused him to cancel his tour And in February, he launched the latest fashion show for his Yeezy brand - but stayed backstage. Last year sociology undergraduate Eliza Cummings-Cove, 20, wrote 9,959 words on Kanye's wife, Kim Kardashian, and her family. She admitted it all started as a joke but decided to use Kim, Khloe and Kourtney to explore sexual liberation, consumerism, racial fetishisation. Getty Images 5 Kanye West was admitted to hospital with reported temporary psychosis in November She watched more than 80 hours of their shows as part of the study before concluding that they had a negative influence on women. Chris McGovern, from the Campaign for Real Education, said: "When rapper Dizzee Rascall recently made it on to the A-Level English syllabus along with Russell Brand the floodgates of educational anarchy really opened. "It should come as no surprise at all that Kanye West qualifies for dissertation status. "These days many students regard the likes of Wordsworth, Byron and Dickens as irrelevant dead white males. "They want literature to be relevant to the real and cool narcissistic world they live in."
<gh_stars>0 export { VueRenderService } from './VueRenderService'
/* * Copyright (c) 2006-2017 DMDirc Developers * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.dmdirc.addons.ui_swing.dialogs; import com.dmdirc.ui.CoreUIUtils; import java.awt.Component; import java.awt.Dimension; import java.awt.Window; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JDialog; /** * Provides common methods for dialogs. */ public class StandardDialog extends JDialog { /** Serial version UID. */ private static final long serialVersionUID = 1; /** Parent window. */ private Component owner; /** The OK button for this frame. */ private JButton okButton; /** The cancel button for this frame. */ private JButton cancelButton; /** * Creates a new instance of StandardDialog. * * @param owner The frame that owns this dialog * @param modal Whether to display modally or not */ public StandardDialog(final Window owner, final ModalityType modal) { super(owner, modal); this.owner = owner; if (owner != null) { setIconImages(owner.getIconImages()); } orderButtons(new JButton(), new JButton()); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } @Override public void setTitle(final String title) { super.setTitle("DMDirc: " + title); } /** * Displays the dialog if it is not visible, otherwise requests focus. */ public void displayOrRequestFocus() { displayOrRequestFocus(owner); } /** * Displays the dialog if it is not visible, otherwise requests focus. The parent window will * only be changed if the dialog has not been displayed. * * @param parent Parent window */ public void displayOrRequestFocus(final Component parent) { if (isVisible()) { requestFocus(); } else { display(parent); } } /** * Displays the dialog centering on the specified window. * * @param owner Window to center on */ public void display(final Component owner) { this.owner = owner; display(); } /** * Displays the dialog centering on the parent window. */ public void display() { if (isVisible()) { return; } addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { executeAction(getCancelButton()); } }); centreOnOwner(); pack(); centreOnOwner(); setVisible(false); setVisible(true); } /** * Centres this dialog on its owner, or the screen if no owner is present. */ public void centreOnOwner() { if (owner == null) { CoreUIUtils.centreWindow(this); } else { setLocationRelativeTo(owner); } } /** * Returns the window owner for this dialog. * * @return Parent window or null */ public Component getParentWindow() { return owner; } /** * Sets the specified button up as the OK button. * * @param button The target button */ protected void setOkButton(final JButton button) { okButton = button; button.setText("OK"); button.setDefaultCapable(false); } /** * Sets the specified button up as the Cancel button. * * @param button The target button */ protected void setCancelButton(final JButton button) { cancelButton = button; button.setText("Cancel"); button.setDefaultCapable(false); } /** * Gets the left hand button for a dialog. * * @return left JButton */ protected JButton getLeftButton() { if (System.getProperty("os.name").toLowerCase().startsWith("win")) { return getOkButton(); } else { return getCancelButton(); } } /** * Gets the right hand button for a dialog. * * @return right JButton */ protected JButton getRightButton() { if (System.getProperty("os.name").toLowerCase().startsWith("win")) { return getCancelButton(); } else { return getOkButton(); } } /** * Orders the OK and Cancel buttons in an appropriate order for the current operating system. * * @param leftButton The left-most button * @param rightButton The right-most button */ protected void orderButtons(final JButton leftButton, final JButton rightButton) { if (System.getProperty("os.name").toLowerCase().startsWith("win")) { // Windows - put the OK button on the left setOkButton(leftButton); setCancelButton(rightButton); } else { // Everything else - adhere to usability guidelines and put it on // the right. setOkButton(rightButton); setCancelButton(leftButton); } leftButton.setPreferredSize(new Dimension(100, 25)); rightButton.setPreferredSize(new Dimension(100, 25)); leftButton.setMinimumSize(new Dimension(100, 25)); rightButton.setMinimumSize(new Dimension(100, 25)); } /** * Retrieves the OK button for this form. * * @return The form's OK button */ public JButton getOkButton() { return okButton; } /** * Retrieves the Cancel button for this form. * * @return The form's cancel button */ public JButton getCancelButton() { return cancelButton; } /** * Simulates the user clicking on the specified target button. * * @param target The button to use */ public void executeAction(final JButton target) { if (target != null && target.isEnabled()) { target.doClick(); } } /** * This method is called when enter is pressed anywhere in the dialog except on a button. By * default this method does nothing. * * @return Returns true if the key press has been handled and is not be be forwarded on by * default this is false */ public boolean enterPressed() { return false; } /** * This method is called when ctrl + enter is pressed anywhere in the dialog. By default this * method presses the OK button. * * @return Returns true if the key press has been handled and is not be be forwarded on by * default this is true */ public boolean ctrlEnterPressed() { executeAction(getOkButton()); return true; } /** * This method is called when enter is pressed anywhere in the dialog except on a button. By * default this method presses the cancel button. * * @return Returns true if the key press has been handled and is not be be forwarded on by * default this is true */ public boolean escapePressed() { executeAction(getCancelButton()); return true; } }
The tighter credit policies also extend to the Streamline Refinance program, which allows borrowers with V.A. loans to refinance into another V.A. loan with very little paperwork and, until recently, no appraisal. Mr. Long and V.A. representatives say that lenders are now requiring borrowers to pay for an appraisal, which can cost $300 or more depending on a home’s location. If the new loan amount is more than the value of the home, they will most likely reject the application. Newsletter Sign Up Continue reading the main story Please verify you're not a robot by clicking the box. Invalid email address. Please re-enter. You must select a newsletter to subscribe to. Sign Up You will receive emails containing news content , updates and promotions from The New York Times. You may opt-out at any time. You agree to receive occasional updates and special offers for The New York Times's products and services. Thank you for subscribing. An error has occurred. Please try again later. View all New York Times newsletters. Not surprisingly, V.A. loan volume has fallen so far this year. William White, the acting assistant director for loan policy at Veterans Affairs, said his agency was on pace to insure about 300,000 mortgages this fiscal year, which ends Sept. 30, versus 325,000 in 2009. The nation’s overall loan volume rose about 19 percent during the same period, according to the Mortgage Bankers Association, to $1.92 trillion from $1.62 trillion. (The trade group tracks only total dollar amount.) Mr. White said he understood why lenders might be restricting the loans, as the V.A. insurance only covers 25 percent of the loan amount. But he added that borrowers of V.A. loans generally had a lower default rate than prime borrowers over all — 2.6 percent versus 3.4 percent, according to the Mortgage Bankers Association — despite the fact that their credit scores were typically lower. V.A. mortgage borrowers tend to “show some discipline,” Mr. White said, offering one explanation, “and we think they try real hard to make their payments.” The average credit score for a V.A. borrower last year was just over 700, while the average credit score for all borrowers was 750, according to the Federal Housing Finance Agency, which oversees Fannie Mae and Freddie Mac, the government-sponsored companies that establish underwriting standards. Mr. Long noted that V.A. loans remain competitive with other loan products. Borrowers who qualify — they must prove 24 months of continuous active military duty, and cannot have experienced a dishonorable discharge, among other things — can secure rates of 4.75 percent on 30-year fixed-rate loans, he said. That is the case even for borrowers with 620 credit scores, he added. The average rate nationwide for all 30-year fixed-rate loans is around 4.70 percent. There is a one-time insurance fee that varies according to the size of the loan and the borrower’s credit profile, but the average is about 1.75 percent of the loan amount. On a $200,000 mortgage the cost would be $3,500. About a quarter of applicants — disabled or retired veterans, for instance — qualify for exemptions from that payment.
<reponame>Fiend-Star-666/Java-codes package com.intern.carRental.primary; import java.util.List; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import com.intern.carRental.primary.abstrct.Vehicle; import com.intern.primary.simplePOJO.Location; import lombok.Getter; import lombok.Setter; @Getter @Setter @Entity public class CarRentalLocation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; @Embedded private Location address; @OneToMany(mappedBy = "carRentalLocation") private List<Vehicle> vehicle; @ManyToOne(optional = false) private CarRentalSystem carRentalSystem; @Override public String toString() { return "CarRentalLocation [id=" + id + ", name=" + name + ", address=" + address + ", carRentalSystem=" + carRentalSystem.toString() + "]"; } // public Location getLocation() { // return address; // TODO getLocation // } }
Taste solution consumption by FHH-Chr nBN consomic rats. There has been extensive work to elucidate the behavioral and physiological mechanisms responsible for taste preferences of the rat but little attempt to delineate the underlying genetic architecture. Here, we exploit the FHH-Chr n(BN)/Mcwi consomic rat strain set to identify chromosomes carrying genes responsible for taste preferences. We screened the parental Fawn Hooded Hypertensive (FHH) and Brown Norway (BN) strains and 22 FHH-Chr n(BN) consomic strains, with 96-h 2-bottle tests, involving a choice between water and each of the following 16 solutions: 10 mM NaCl, 237 mM NaCl, 32 mM CaCl(2), 1 mM saccharin, 100 mM NH(4)Cl, 32 mM sucrose, 100 mM KCl, 4% ethanol, 1 mM HCl, 10 mM monosodium glutamate, 1 mM citric acid, 32 microM quinine hydrochloride, 1% corn oil, 32 microM denatonium, 1% Polycose, and 1 microM capsaicin. Depending on the taste solution involved, between 1 and 16 chromosomes were implicated in the response. Few of these chromosomes carried genes believed to mediate taste transduction in the mouse, and many chromosomes with no candidate taste genes were revealed. The genetic architecture of taste preferences is considerably more complex than has heretofore been acknowledged.
<gh_stars>0 /* * (C) Copyright 2020 Radix DLT Ltd * * Radix DLT Ltd licenses this file to you 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 com.radixdlt.ledger; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.inject.Inject; import com.radixdlt.atom.Txn; import com.radixdlt.consensus.LedgerHeader; import com.radixdlt.consensus.LedgerProof; import com.radixdlt.consensus.bft.BFTCommittedUpdate; import com.radixdlt.consensus.bft.BFTNode; import com.radixdlt.consensus.bft.BFTValidatorSet; import com.radixdlt.consensus.Ledger; import com.radixdlt.consensus.bft.PreparedVertex; import com.radixdlt.consensus.bft.VerifiedVertex; import com.radixdlt.consensus.bft.VerifiedVertexStoreState; import com.radixdlt.consensus.bft.View; import com.radixdlt.consensus.liveness.NextTxnsGenerator; import com.radixdlt.counters.SystemCounters; import com.radixdlt.counters.SystemCounters.CounterType; import com.radixdlt.environment.EventDispatcher; import com.radixdlt.environment.EventProcessor; import com.radixdlt.environment.RemoteEventProcessor; import com.radixdlt.mempool.MempoolAdd; import com.radixdlt.network.TimeSupplier; import com.radixdlt.store.LastProof; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; /** * Synchronizes execution */ public final class StateComputerLedger implements Ledger, NextTxnsGenerator { public interface PreparedTxn { Txn txn(); } public static class StateComputerResult { private final List<PreparedTxn> preparedTxns; private final Map<Txn, Exception> failedCommands; private final BFTValidatorSet nextValidatorSet; public StateComputerResult( List<PreparedTxn> preparedTxns, Map<Txn, Exception> failedCommands, BFTValidatorSet nextValidatorSet ) { this.preparedTxns = Objects.requireNonNull(preparedTxns); this.failedCommands = Objects.requireNonNull(failedCommands); this.nextValidatorSet = nextValidatorSet; } public StateComputerResult(List<PreparedTxn> preparedTxns, Map<Txn, Exception> failedCommands) { this(preparedTxns, failedCommands, null); } public Optional<BFTValidatorSet> getNextValidatorSet() { return Optional.ofNullable(nextValidatorSet); } public List<PreparedTxn> getSuccessfulCommands() { return preparedTxns; } public Map<Txn, Exception> getFailedCommands() { return failedCommands; } } public interface StateComputer { void addToMempool(MempoolAdd mempoolAdd, BFTNode origin); List<Txn> getNextTxnsFromMempool(List<PreparedTxn> prepared); StateComputerResult prepare(List<PreparedTxn> previous, List<Txn> next, long epoch, View view, long timestamp); void commit(VerifiedTxnsAndProof verifiedTxnsAndProof, VerifiedVertexStoreState vertexStoreState); } private final Comparator<LedgerProof> headerComparator; private final StateComputer stateComputer; private final EventDispatcher<LedgerUpdate> ledgerUpdateDispatcher; private final SystemCounters counters; private final LedgerAccumulator accumulator; private final LedgerAccumulatorVerifier verifier; private final Object lock = new Object(); private final TimeSupplier timeSupplier; private LedgerProof currentLedgerHeader; @Inject public StateComputerLedger( TimeSupplier timeSupplier, @LastProof LedgerProof initialLedgerState, Comparator<LedgerProof> headerComparator, StateComputer stateComputer, EventDispatcher<LedgerUpdate> ledgerUpdateDispatcher, LedgerAccumulator accumulator, LedgerAccumulatorVerifier verifier, SystemCounters counters ) { this.timeSupplier = Objects.requireNonNull(timeSupplier); this.headerComparator = Objects.requireNonNull(headerComparator); this.stateComputer = Objects.requireNonNull(stateComputer); this.ledgerUpdateDispatcher = Objects.requireNonNull(ledgerUpdateDispatcher); this.counters = Objects.requireNonNull(counters); this.accumulator = Objects.requireNonNull(accumulator); this.verifier = Objects.requireNonNull(verifier); this.currentLedgerHeader = initialLedgerState; } public RemoteEventProcessor<MempoolAdd> mempoolAddRemoteEventProcessor() { return (node, mempoolAdd) -> { synchronized (lock) { stateComputer.addToMempool(mempoolAdd, node); } }; } public EventProcessor<MempoolAdd> mempoolAddEventProcessor() { return mempoolAdd -> { synchronized (lock) { stateComputer.addToMempool(mempoolAdd, null); } }; } @Override public List<Txn> generateNextTxns(View view, List<PreparedVertex> prepared) { final ImmutableList<PreparedTxn> preparedTxns = prepared.stream() .flatMap(PreparedVertex::successfulCommands) .collect(ImmutableList.toImmutableList()); synchronized (lock) { return stateComputer.getNextTxnsFromMempool(preparedTxns); } } @Override public Optional<PreparedVertex> prepare(LinkedList<PreparedVertex> previous, VerifiedVertex vertex) { final LedgerHeader parentHeader = vertex.getParentHeader().getLedgerHeader(); final AccumulatorState parentAccumulatorState = parentHeader.getAccumulatorState(); final ImmutableList<PreparedTxn> prevCommands = previous.stream() .flatMap(PreparedVertex::successfulCommands) .collect(ImmutableList.toImmutableList()); final long quorumTimestamp; // if vertex has genesis parent then QC is mocked so just use previous timestamp // this does have the edge case of never increasing timestamps if configuration is // one view per epoch but good enough for now if (vertex.getParentHeader().getView().isGenesis()) { quorumTimestamp = vertex.getParentHeader().getLedgerHeader().timestamp(); } else { quorumTimestamp = vertex.getQC().getTimestampedSignatures().weightedTimestamp(); } synchronized (lock) { if (this.currentLedgerHeader.getStateVersion() > parentAccumulatorState.getStateVersion()) { return Optional.empty(); } // Don't execute atom if in process of epoch change if (parentHeader.isEndOfEpoch()) { final long localTimestamp = timeSupplier.currentTime(); final PreparedVertex preparedVertex = vertex .withHeader(parentHeader.updateViewAndTimestamp(vertex.getView(), quorumTimestamp), localTimestamp) .andTxns(ImmutableList.of(), ImmutableMap.of()); return Optional.of(preparedVertex); } final var maybeCommands = this.verifier.verifyAndGetExtension( this.currentLedgerHeader.getAccumulatorState(), prevCommands, p -> p.txn().getId().asHashCode(), parentAccumulatorState ); // TODO: Write a test to get here // Can possibly get here without maliciousness if parent vertex isn't locked by everyone else if (maybeCommands.isEmpty()) { return Optional.empty(); } final var concatenatedCommands = maybeCommands.get(); final StateComputerResult result = stateComputer.prepare( concatenatedCommands, vertex.getTxns(), vertex.getParentHeader().getLedgerHeader().getEpoch(), vertex.getView(), quorumTimestamp ); AccumulatorState accumulatorState = parentHeader.getAccumulatorState(); for (PreparedTxn txn : result.getSuccessfulCommands()) { accumulatorState = this.accumulator.accumulate(accumulatorState, txn.txn().getId().asHashCode()); } final LedgerHeader ledgerHeader = LedgerHeader.create( parentHeader.getEpoch(), vertex.getView(), accumulatorState, quorumTimestamp, result.getNextValidatorSet().orElse(null) ); final long localTimestamp = timeSupplier.currentTime(); return Optional.of(vertex .withHeader(ledgerHeader, localTimestamp) .andTxns(result.getSuccessfulCommands(), result.getFailedCommands()) ); } } public EventProcessor<BFTCommittedUpdate> bftCommittedUpdateEventProcessor() { return committedUpdate -> { final ImmutableList<Txn> txns = committedUpdate.getCommitted().stream() .flatMap(PreparedVertex::successfulCommands) .map(PreparedTxn::txn) .collect(ImmutableList.toImmutableList()); var proof = committedUpdate.getVertexStoreState().getRootHeader(); var verifiedTxnsAndProof = VerifiedTxnsAndProof.create(txns, proof); // TODO: Make these two atomic (RPNV1-827) this.commit(verifiedTxnsAndProof, committedUpdate.getVertexStoreState()); }; } public EventProcessor<VerifiedTxnsAndProof> syncEventProcessor() { return p -> this.commit(p, null); } private void commit(VerifiedTxnsAndProof verifiedTxnsAndProof, VerifiedVertexStoreState vertexStoreState) { synchronized (lock) { final LedgerProof nextHeader = verifiedTxnsAndProof.getProof(); if (headerComparator.compare(nextHeader, this.currentLedgerHeader) <= 0) { return; } var verifiedExtension = verifier.verifyAndGetExtension( this.currentLedgerHeader.getAccumulatorState(), verifiedTxnsAndProof.getTxns(), txn -> txn.getId().asHashCode(), verifiedTxnsAndProof.getProof().getAccumulatorState() ); if (verifiedExtension.isEmpty()) { throw new ByzantineQuorumException("Accumulator failure " + currentLedgerHeader + " " + verifiedTxnsAndProof); } var txns = verifiedExtension.get(); if (vertexStoreState == null) { this.counters.add(CounterType.LEDGER_SYNC_COMMANDS_PROCESSED, txns.size()); } else { this.counters.add(CounterType.LEDGER_BFT_COMMANDS_PROCESSED, txns.size()); } var txnsAndProof = VerifiedTxnsAndProof.create(txns, verifiedTxnsAndProof.getProof()); // persist this.stateComputer.commit(txnsAndProof, vertexStoreState); // TODO: move all of the following to post-persist event handling this.currentLedgerHeader = nextHeader; this.counters.set(CounterType.LEDGER_STATE_VERSION, this.currentLedgerHeader.getStateVersion()); LedgerUpdate ledgerUpdate = new LedgerUpdate(txnsAndProof); ledgerUpdateDispatcher.dispatch(ledgerUpdate); } } }
/** * Dig the next available piece of land if not done. As soon as it reaches * bedrock, lava or goes below 0, it's considered done. */ @Override public void updateEntity() { super.updateEntity(); if (worldObj.isRemote) { return; } if (updateTracker.markTimeIfDelay(worldObj)) { sendNetworkUpdate(); } ticksSinceAction++; if (mode == Mode.Off) { if (miner != null) { miner.invalidate(); miner = null; } isDigging = false; return; } if (getBattery().getEnergyStored() == 0) { return; } if (miner == null) { World world = worldObj; int depth = yCoord - 1; while (world.getBlock(xCoord, depth, zCoord) == BuildCraftFactory.plainPipeBlock) { depth = depth - 1; } if (depth < 1 || depth < yCoord - BuildCraftFactory.miningDepth || !BlockUtils.canChangeBlock(world, xCoord, depth, zCoord)) { isDigging = false; getBattery().useEnergy(0, 10, false); return; } if (world.isAirBlock(xCoord, depth, zCoord) || world.getBlock(xCoord, depth, zCoord).isReplaceable(world, xCoord, depth, zCoord)) { ticksSinceAction = 0; world.setBlock(xCoord, depth, zCoord, BuildCraftFactory.plainPipeBlock); } else { miner = new BlockMiner(world, this, xCoord, depth, zCoord); } } if (miner != null) { isDigging = true; ticksSinceAction = 0; int usedEnergy = miner.acceptEnergy(getBattery().getEnergyStored()); getBattery().useEnergy(usedEnergy, usedEnergy, false); if (miner.hasFailed()) { isDigging = false; } if (miner.hasFailed() || miner.hasMined()) { miner = null; } } }
from collections import defaultdict import logging import math logger = logging.getLogger('lobster.algo') class Algo(object): """A task creation algorithm Attempts to be fair when creating tasks by making sure that tasks are created evenly for every category and every workflow in each category based on the remaining work per workflow and cores used. Parameters ---------- config : Configuration The Lobster configuration to use. """ def __init__(self, config): self.__config = config def run(self, total_cores, queued, remaining): """Run the task creation algorithm. If not enough tasks can be created for a workflow, the available tasks are scaled down in size/runtime ("tapered") to ensure that the available resources are used most efficiently. Steps ----- 1. Calculate remaining workload, weighed by cores, per category 2. Determine how many cores need to be filled 3. Go through workflows: 1. Determine the fraction of category workload versus the total workload 2. Do the same for the workflow workload versus the category workload 3. Use the first fraction to calculate how many tasks should be created for the category 4. Adjust for mininum queued and maximum total task requirements 5. Subtract already queued tasks 6. Calculate how many tasks should be created for the current workflow based on the previously calculated fraction 7. Adjust task size taper based on available tasks and needed tasks Parameters ---------- total_cores : int The number of cores that `WorkQueue` currently is in control of. queued : dict A dictionary containing information about the queue on a per category basis. Keys are category names, values are dictionaries with the keys `running` and `queued`, denoting how many category tasks fall into each bin. remaining : dict A dictionary with workflows as keys, and a tuple containing the following as value: * if all units for the workflow are available * how many units are left to process * how many tasks can still be created with the default size Returns ------- data : list A list containing workflow label, how many tasks to create, and the task taper adjustment. """ # Remaining workload workloads = defaultdict(int) for wflow, (complete, units, tasks) in remaining.items(): if not complete and tasks < 1.: logger.debug("workflow {} has not enough units available to form new tasks".format(wflow.label)) continue elif units == 0: continue task_cores = wflow.category.cores or 1 workloads[wflow.category.name] += task_cores * tasks # How many cores we need to occupy: have at least 10% of the # available cores provisioned with waiting work fill_cores = total_cores + max(int(0.1 * total_cores), self.__config.advanced.payload) total_workload = sum(workloads.values()) if total_workload == 0: return [] # contains (workflow label, tasks, taper) data = [] for wflow, (complete, units, tasks) in remaining.items(): if not complete and tasks < 1. or units == 0: continue task_cores = wflow.category.cores or 1 category_fraction = workloads[wflow.category.name] / float(total_workload) workflow_fraction = task_cores * tasks / float(workloads[wflow.category.name]) needed_category_tasks = category_fraction * fill_cores / task_cores if wflow.category.tasks_max: allowed = wflow.category.tasks_max - sum(queued[wflow.category.name].values()) needed_category_tasks = min(allowed, needed_category_tasks) if wflow.category.tasks_min: required = wflow.category.tasks_min - queued[wflow.category.name]['queued'] needed_category_tasks = max(required, needed_category_tasks) needed_category_tasks -= queued[wflow.category.name]['queued'] needed_workflow_tasks = max(0, int(math.ceil(needed_category_tasks * workflow_fraction))) if needed_category_tasks <= 0: continue taper = 1. if tasks < needed_workflow_tasks and complete: taper = min(1., tasks / float(needed_workflow_tasks)) logger.debug(("creating tasks for {w.label} (category: {w.category.name}):\n" + "\tcategory task limit: ({w.category.tasks_min}, {w.category.tasks_max})\n" + "\tcategory tasks needed: {0}\n" + "\tworkflow tasks needed: {1}\n" + "\tworkflow tasks available: {2} (complete: {4})\n" + "\ttask taper: {3}").format(needed_category_tasks, needed_workflow_tasks, tasks, taper, complete, w=wflow)) data.append((wflow.label, needed_workflow_tasks, taper)) # adjust accounting for next workflow queued[wflow.category.name]['queued'] += needed_workflow_tasks return data
Congenital hypothyroidism in Indian preterm babies - screening, prevalence, and aetiology. INTRODUCTION Paucity of data on hypothyroidism in Indian preterms. Aim of the study: To describe the prevalence, aetiology, and experience with screening for primary hypothyroidism in preterm babies. MATERIAL AND METHODS A prospective observational study conducted for 3 years in a tertiary care unit, where all babies born < 37 weeks screened by heel prick for Thyroid Stimulating Hormone (TSH) were included. All screen positive cases (TSH ≥ 6 µIU/ml) underwent venous testing immediately; venous TSH ≥ 20 or Free T4 < 0.9 ng/dl was considered as confirmed positive. All babies underwent venous testing at term. Etiological testing was performed where feasible. Confirmed cases were initiated on thyroxine therapy and followed up. RESULTS 1167 preterm babies presented during the study period. 1147 (98%) underwent TSH screening and 17 (1.4%) were screen positive; 15 babies underwent confirmatory venous test. Of these 15 babies, 2 were confirmed and started on therapy. The remaining 13 babies underwent retest venous sample at term, and 8 of these were confirmed cases. Of the screen-negative babies, 94% underwent repeat venous testing at term/ prior to discharge. Five were confirmed to have congenital hypothyroidism. Thus, the prevalence of congenital hypothyroidism was 1 in 77 preterm babies. No correlation was observed between screening TSH and venous TSH (p > 0.05). Aetiological evaluation in 8 babies revealed secondary to maternal antibody in 4 cases (50%) and permanent thyroid defects in 4 cases (50%). CONCLUSIONS We observed a high prevalence (1 in 77), need for repeat venous testing, irrespective of initial screening, and significant permanent congenital hypothyroidism (50%) in our series.
cityscape The Switch to Presto Could Make Life a Lot Harder for Seniors and Students Until 2017, discounted fares will only be available at Davisville station. Renz Gamboa uses the TTC every day. He’s a student who attends school in Toronto, and he used to purchase a Metropass for his commute. He didn’t know about the discounted fares offered to students like him by the TTC through Presto, and when he heard about the reloadable transit card, he decided to buy one. But then he learned he had to travel to Davisville station to get his discount. Presto is intended to make life easier for commuters in the GTA. But for students and seniors, both of whom are eligible for discounted fares, the new system could be inconvenient at best and inaccessible at worst. The value of having Presto for seniors and students who routinely ride the TTC is that they’re able to add a concession on the self-service fare card. This is a feature that allows customers to apply discounts. By default, the card is set to the adult fare, and in order to have their discount applied, riders only have one option: they have to visit Davisville station. While making the trip to Davisville is a one-time burden to get approved for discounted fares, having only the one option raises concerns for people who rely on transit to travel through the GTA, especially those with mobility issues. The number of TTC rides increased to 70,967,000 in 2015 from 65,596,000 in 2012, according to the Toronto Transit Commission Analysis of Ridership. Only 438,000 fares used Presto, compared to 25,092,000 who used a monthly pass. Seniors or people with disabilities may find it challenging to reach Davisville. While the station is more accessible than others, obstacles can still arise, such as elevators or escalators being out of service. And more practically, those on the outskirts of Toronto’s midtown—whether from Etobicoke or Scarborough—will have to make a long trek just to get a concession they’re entitled to. Gamboa says paying for any kind of transportation—bus, train, or subway—with the quick tap of a card will make things more flexible for passengers. But having discounted fares available only at one location detracts from that convenience. TTC Chair and Councillor Josh Colle (Ward 15, Eglinton-Lawrence) admits the system still isn’t perfect. “The senior [discount situation] is admittedly not as convenient as we like right now, having to go to Davisville,” Colle says. “Eventually you’ll be able get your card, if you’re a senior or student, and the concession that comes with it wherever you get your card, the same way you get your tickets or tokens now.” The TTC announced this summer it intends to eliminate tokens and tickets by mid-2017 to pave the way for widespread Presto use. It will still accept cash payment, but that likely won’t be for long—the TTC is expected to only accept Presto cards by the end of 2017. There likely won’t be an increase in the number of locations offering the concession until well after the transition period ends next year. So far, Presto readers have been installed in more than 1,000 TTC buses and at turnstile entrances of 30 subway stations to complement all streetcars travelling across the city. The system-wide rollout of the card on all buses and subway stations is expected to be completed by the end of this year. TTC communications advisor Kadeem Griffiths says commuters will know ahead of time of any coming changes to fare policies. “It will be communicated well in advance when we stop accepting cash, tickets and tokens, and when everyone should be transitioned over to Presto,” Griffiths says. Colle adds that the TTC and Metrolinx will have to overcome the challenge of educating Torontonians about the new fare system, making sure the distribution network of Presto is wide and available everywhere. Even if the TTC expands the availability of discounts for seniors and students, ensuring that all of its stations are accessible is equally important. Currently, 34 stations (including Davisville) are considered accessible with elevators and escalators. But 35 others remain inaccessible, though they are required to undergo changes by 2025 to comply with the Accessibility for Ontarians with Disabilities Act. The TTC is expected to spend $462.8 million on accessibility projects [PDF] as part of its 2016-2025 capital budget. But a chunk of the funds, $429 million, will be spent on accessibility retrofits at subway stations, including elevators, power-operated sliding doors, fare gates, ramps, and signage. Until things change, commuters like Gamboa will have to head to Davisville—an out-of-the-way trip—all for a discount that’s rightfully theirs. : This article originally cited incorrect ridership numbers. We regret the error.
<filename>UnicornBattle/Assets/AppCenter/Plugins/iOS/Crashes/Utility/NSErrorHelper.h // Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT license. extern "C" const char* app_center_unity_nserror_domain(void* error); extern "C" long app_center_unity_nserror_code(void* error); extern "C" const char* app_center_unity_nserror_description(void* error);
package signaling import ( "fmt" "github.com/ysugimoto/signalingo/connection" "github.com/ysugimoto/signalingo/env" "github.com/ysugimoto/signalingo/hooks" "github.com/ysugimoto/signalingo/logger" "github.com/ysugimoto/signalingo/operation" "golang.org/x/net/websocket" "net/http" ) var manager *Manager func Listen(env env.Env) { url := initHandler(env) if err := http.ListenAndServe(url, nil); err != nil { panic(fmt.Sprintf("%v", err)) } } func ListenTLS(env env.Env) { url := initHandler(env) if err := http.ListenAndServeTLS(url, env.Server.Cert, env.Server.Key, nil); err != nil { panic(fmt.Sprintf("%v", err)) } } func initHandler(env env.Env) (url string) { initLog(env) manager = NewManager(env) http.Handle(env.Server.Endpoint, createWebSocketHandler(env, false)) http.Handle("/manage", createWebSocketHandler(env, true)) url = fmt.Sprintf("%s:%d", env.Server.Host, env.Server.Port) logger.Infof("Signaling server started on \"%s\"\n", url) return } func initLog(env env.Env) { logger.SetLevel(env.Log.Level) if env.Log.Type == "file" { logger.SetLogFile(env.Log.Filepath) } } func GracefulShutdown() { logger.Info("Signal received, graceful shutdown") if msg, err := operation.NewShutdownMessage(); err == nil { manager.Broadcast(msg) } manager.Purge() } func createWebSocketHandler(env env.Env, admin bool) websocket.Handler { return websocket.Handler(func(ws *websocket.Conn) { client := connection.NewConnection(ws, admin) // Handshake message if msg, err := operation.NewHandshakeMessage(client.UUID, manager.GetAllUsers()); err == nil { var resp int // Do we need hook? if env.Hook.Url == "" { resp = 0 } else { hook := hooks.NewWebHook(env.Hook.Url, client.Extra) hook.Run() resp = <-hook.Resp } if resp == 0 { if err := client.Send(msg); err != nil { logger.Fatal("Handshake send failed") } else { logger.Infof("UUID: %s handshake", client.UUID) } } else { client.Close() return } } manager.AddConnection(client) defer func() { manager.CloseConnection(client) }() for { if client.Closed { break } if msg, err := client.Receive(); err != nil { break } else { logger.Infof("WebSocket receive message: %s\n", msg) manager.HandleMessage(msg) } } }) }
The Effect of Taxes on the Performance of the Stock Market-Arab Stock Markets as A Model The research aims to provide a comprehensive and in-depth picture of the theoretical frameworks and empirical studies that framed and explained the mechanism of transmission of direct and indirect influence through which taxes can play an important and prominent role in interpreting the performance of the stock market, as well as building a quantitative model capable of clarifying the size and direction of the impact of taxes. And some other controlling variables (inflation, interest rate, economic growth, money supply, government spending, public debt) as illustrative variables, in the performance indicators of the stock market, which was expressed by the market index, and the turnover rate as response variables, for a sample of Arab countries (Egypt, Jordan, Morocco, Oman, Tunisia, Lebanon, Bahrain) for the period (1997-2019), To achieve this, we relied on the aggregate regression methodology (PRM), the fixed-effect model (FEM), and the random effect model (REM), which are based on the balanced double data (Balanced Panel Data), to obtain results closer to reality and reach an analysis It can be used in investment decisions, and the results revealed the contribution of taxes to the positive impact on the performance indicators of the stock market for the sample countries.
////////////////////////////////////////////////////////////////////////////// // Copyright (C) 1993 - 2000 California Institute of Technology // // // // Read the COPYING and README files, or contact '<EMAIL>', // // before continuing. SOME RESTRICTIONS MAY APPLY TO USE OF THIS FILE. // ////////////////////////////////////////////////////////////////////////////// #ifndef cBarScreen_h #define cBarScreen_h #ifndef cScreen_h #include "cScreen.h" #endif #ifndef cString_h #include "cString.h" #endif class cBarScreen : public cScreen { protected: cWorld* m_world; cString prog_name; int AddMenuOption(const cString option, int max_x, int cur_x); public: cBarScreen(cWorld* world, int y_size, int x_size, int y_start, int x_start, cViewInfo & in_info, const cString & in_name) : cScreen(y_size, x_size, y_start, x_start, in_info), m_world(world), prog_name(in_name) { ; } ~cBarScreen() { ; } // Virtual in base screen... void Draw(cAvidaContext& ctx); void Update(cAvidaContext& ctx); void DoInput(cAvidaContext& ctx, int in_char) { (void) in_char; } }; #endif
/** * Created by liyou on 18/11/7. */ public class ArticleModel implements ArticleDetailContract.Model { @Override public void loadArticleList(int page, RequestListener<PageEntity<ArticleEntity>> listener) { OkGo.<BaseResponse<PageEntity<ArticleEntity>>>get(Urls.ARTICLE + page + "/json") .execute(new JsonCallback<BaseResponse<PageEntity<ArticleEntity>>>() { @Override public void onSuccess(Response<BaseResponse<PageEntity<ArticleEntity>>> response) { listener.requestSuccess(response.body().data); } }); } }
/// Wrap a future with one that will timeout when this timeout expires. pub fn mix<'a, 'b, R, F>( &'a self, f: F, ) -> impl std::future::Future<Output = KitsuneResult<R>> + 'b + Send where R: 'b, F: std::future::Future<Output = KitsuneResult<R>> + 'b + Send, { let time_remaining = self.time_remaining(); async move { match tokio::time::timeout(time_remaining, f).await { Ok(r) => r, Err(_) => Err(KitsuneErrorKind::TimedOut.into()), } } }
Assessment and application of potential food provisioning services of ecosystems in Three-gorge areas The assessment of food provisioning services of ecosystems in Three-gorge areas is helpful for better understanding the function of ecosystems in local human well-beings. In this paper, process-based models are used to assess the potential food provisioning services derived from agriculture ecosystems and grassland ecosystems, a modifying model along with normal woodlands and a set of modifying coefficients is built to assess the potential food from woodland ecosystems. A set of power regression models based on environment factors are built to estimate the potential fish production from water ecosystems. Land cover data stemmed from Landsat TM images, as well as other natural and social-economic data in 1km resolution such as temperature, precipitation, and DEM, are used to support these assessment models. It shows that the four ecosystems in Three-gorge areas can provide 85.98×1012 calories heat, 2.49 billion kilograms protein and 823.4 million kilograms fat. Human carrying capacity model under the balance nutrition pattern is built in this paper, which results in two key findings: ecosystems in Three-gorge areas can feed 45.92 million people under wealthy living standard which is 1.53 times of the current population, and the sustainable population is from 9.69 to 36.23 million under that living standard. Multi-scale population pressure model is built to calculate the population pressure index in Three-gorge areas. The grain for green pressure index, a multivariate linear weighed model, is used to determine the spatial distribution of farmland fit for grain for green and fit for protecting.
/** * Update the the right side of the panel to display the selected node * * @param event the selection event indicating what node was selecteds */ @Override public void nodeSelected(RejTreeNodeSelectionEvent event) { RejTreeNodeView view = event.getNode().getView(); int curDividerLocation = this.splitPane.getDividerLocation(); this.splitPane.setRightComponent(view); this.splitPane.setDividerLocation(curDividerLocation); }
from sys import stdin, stdout def find(A,B): return (B//2)*A+(-(-A//2) if B%2 else 0) def main(): for _ in range(int(stdin.readline())): A,B=sorted(map(int, stdin.readline().split())) print(find(A,B)) main()
‘I did a good deed by killing a Turkish gendarme,’ Niğde assailant says NİĞDE The perpetrator identified as Ç.R., a Swiss national who was first reported as being from Kosovo, was arrested by the court with two others captured after the March 20 attack. One of the perpetrators of an attack against Turkish gendarmes in the Central Anatolian province of Niğde last week reportedly expressed no remorse for his act during his testimony in court after being captured by police.“I did a good deed by killing the Turkish gendarmerie soldier,” the perpetrator identified as Ç.R., a Swiss national who was first reported as being from Kosovo, told police, according to Doğan News Agency.The attack on March 20 left three dead and five injured, including a Turkish gendarmerie soldier and a police officer. All of the assailants, captured within hours, are suspected of being members of the Islamic State of Iraq and the Levant (ISIL), which is linked with al-Qaeda.“I don’t render an account to anyone but Allah. I will not give any testimony. You are all pagans,” he was also quoted as saying. He also reportedly said Turkey was considered an “enemy” for being a NATO member.Meanwhile, the driver of the assailants’ pickup truck, identified as B.X., denied being a part of the shooting and being a member of any organization. He reportedly explained he was accompanying Ç.R., whom he did not know before, on his way back to Kosovo.“When [Ç.R.] saw the checkpoint, he directed his gun behind my back and started to open fire. When I asked him what happened, he shouted at me, telling me to drive the truck. I was under the influence of drugs when the incident happened. I did not see if any police or gendarmerie soldiers were shot or not,” he reportedly said.A third assailant M.Z., a national of Macedonia, was also arrested by the court.Following the attack, Turkish officers said the information they received pointed to Syrian links.“Some people might want to cause unrest before the elections,” Deputy Prime Minister Beşir Atalay had claimed.
Real Madrid sign the best young player in Brazil for €45m: Vinicius Junior Real Madrid sign another young talent As Real Madrid continue to challenge for the double of La Liga and the Champions League this season, they are also making huge waves in the transfer market as well. On Sunday, Brazilian newspaper Globoesporte report that Real Madrid have agreed a deal to sign the best young player in Brazil for 45 million euros: Vinicius Junior. Globoesporte are arguably the best source for football news in Brazil and they confirm that the deal is all but done. Vinicius Junior Vinicius Junior is currently 16, and Real Madrid have agreed to sign the Flamengo attacker when he turns 18, and he will head to Spain after the World Cup. Real Madrid beat Barcelona to the signing of Vinicius Junior with the deal set to cost 61 million euros in total, including wages and a payment to his agents. In comparison, Manchester City paid just over 32 million euros for Gabriel Jesus last summer. The Barcelona offer Barcelona had offered 25 million euros for Vinicius Junior, to Flamengo and slightly less money in wages. Real Madrid will pay the youngster 8 million euros per season. The Catalans even had Neymar ring up Vinicius Junior in a bid to sway him to sign for Barcelona. According to Globoesporte, everything is agreed between Real Madrid, Flamengo and the player himself, all that needs to be done is to sign contracts. The best young player in Brazil At 16, Vinicius Junior has been treated like a jewel at Rio giants Flamengo having joined the club in 2010. Vinicius Junior has been the main standout young player at the club since emerging to prominence in the Under-13 side at Flamengo. In 2017, Vinicius Junior became champion, best player and top scorer at the South American Under-17 Championship. Flamengo own 100% of the rights to Vinicius Junior and the 45 million euro transfer fee will be double what Santos received from selling Neymar to Barcelona. Video evidence of Vinicius Junior
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { environment } from '@cartella/env/environment'; @Injectable({ providedIn: 'root', }) export class ResetPasswordService { resetEndpoint = `${environment.api}/auth/reset`; verifyEndpoint = `${environment.api}/auth/change-password`; constructor(private http: HttpClient) {} generateOTP(email: string) { return this.http.post(this.resetEndpoint, { email }); } changePassword(data: { email: string; otp: string; password: string }) { return this.http.post(this.verifyEndpoint, data); } }
/*//////////////////////////////////////////////////////////////////////// Copyright (c) 1997-2000 <NAME> and ETL,AIST,MITI Copyright (c) 2001-2006 National Institute of Advanced Industrial Science and Technology (AIST) AIST-Product-ID: 2000-ETL-198715-01, H14PRO-049, H15PRO-165, H18PRO-443 Permission to use this material for noncommercial and/or evaluation purpose, copy this material for your own use, and distribute the copies via publicly accessible on-line media, without fee, is hereby granted provided that the above copyright notice and this permission notice appear in all copies. AIST MAKES NO REPRESENTATIONS ABOUT THE ACCURACY OR SUITABILITY OF THIS MATERIAL FOR ANY PURPOSE. IT IS PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. ///////////////////////////////////////////////////////////////////////// Content-Type: program/C; charset=US-ASCII Program: setutimes.c Author: <NAME> <<EMAIL>> Description: History: 970724 created //////////////////////////////////////////////////////////////////////#*/ #include "file.h" #include "vsocket.h" /* <sys/time.h> for timeval of utimes() */ #include <ctype.h> int set_utimes(PCStr(path),int atime,int mtime) { FileStat st; struct timeval tv[2]; /**/ if( stat(path,&st) != 0 ) return -1; if( atime != 0 && atime != -1 ) tv[0].tv_sec = atime; else tv[0].tv_sec = st.st_atime; tv[0].tv_usec = 0; if( mtime != 0 && mtime != -1 ) tv[1].tv_sec = mtime; else tv[1].tv_sec = st.st_mtime; tv[1].tv_usec = 0; return utimes(path,tv); } int Futimes(int fd,int as,int au,int ms,int mu); int INHERENT_futimes(); int set_futimes(int fd,int atime,int mtime){ FileStat st; int as,au,ms,mu; int rcode; if( fstat(fd,&st) != 0 ) return -1; if( atime != 0 && atime != -1 ) as = atime; else as = st.st_atime; au = 0; if( mtime != 0 && mtime != -1 ) ms = mtime; else ms = st.st_mtime; mu = 0; rcode = Futimes(fd,as,au,ms,mu); return rcode; } /* * futimes() is better in the performance and the time is that * of the host machine. * fturncate() sets the time which can be different with that * of the host machine if the file is on a network-file system. */ int file_touch(int fd){ FileSize fsize; if( INHERENT_futimes() ){ if( set_futimes(fd,-1,time(0)) == 0 ){ return 0; } } if( 0 <= (fsize = file_size(fd)) ) if( ftruncate(fd,fsize+1) == 0 ) if( ftruncate(fd,fsize) == 0 ) return 0; return -1; } /* * these casting to (off_t) seems to have been necessary when without * prototype (without including <unistd.h>) * maybe it is unnecssary after 8.10.0. and it will be harmful where * (off_t < 4GB, non-BSD) and (4GB < FileSize, default after 9.2.2) * ftell()/fseek() is NG because it uses int and * should be replaced with ftello()/fseeko() or fgetpos()/fsetpos(). */ FileSize Lseek(int fd,FileSize off,int wh); int Ftruncate(FILE *fp,FileSize offset,int whence) { Fpos_t savoff; FileSize siz; int rcode; /* savoff = ftell(fp); fseek(fp,offset,whence); rcode = ftruncate(fileno(fp),(off_t)ftell(fp)); fseek(fp,savoff,0); */ Fgetpos(fp,&savoff); fseek(fp,offset,whence); siz = Lseek(fileno(fp),offset,whence); if( siz <= 0xFFFFFFFF ){ int fsiz = ftell(fp); if( siz != fsiz ){ syslog_ERROR("## Ftruncate(%d,%lld,%d) %d %lld\n", fileno(fp),offset,whence,fsiz,siz); siz = fsiz; } } rcode = ftruncate(fileno(fp),siz); Fsetpos(fp,&savoff); return rcode; } FileSize Lseek(int fd,FileSize off,int wh) { return lseek(fd,off,wh); /* return lseek(fd,(off_t)off,wh); */ } FileSize Ltell(int fd){ FileSize off; off = lseek(fd,0,1); return off; } void ftouch(FILE *fp,int time) { int off; off = ftell(fp); fseek(fp,0,2); fwrite("",1,1,fp); fflush(fp); fseek(fp,-1,2); Ftruncate(fp,0,1); fseek(fp,off,0); } void File_touch(PCStr(path),int clock) { FILE *fp; if( fp = fopen(path,"a") ){ ftouch(fp,clock); fclose(fp); } } int touch_main(int ac,const char *av[]){ FileSize size = 0; int clock = -1; int fd = fileno(stdout); int orand = 0; int ai; const char *a1; FILE *fp; for( ai = 1; ai < ac; ai++ ){ a1 = av[ai]; if( a1[0] == '+' ){ if( a1[1] == 0 ) clock = time(0); else clock = atoi(a1+1); }else if( a1[0] == '-' ){ if( isdigit(a1[1]) ){ size = kmxatoi(a1+1); }else switch( a1[1] ){ case 'r': orand = 1; break; } }else{ fp = fopen(a1,"r+"); if( fp == NULL ) fp = fopen(a1,"w"); if( fp ){ fd = fileno(fp); } } } if( 0 < size ){ Lseek(fd,size-1,0); IGNRETP write(fd,"",1); } if( 0 < clock ){ set_futimes(fd,-1,clock); } return 0; }